Debian Codegraph @

mesonbuild/cargo/cfg.py

raw
1 # SPDX-License-Identifier: Apache-2.0
2 # Copyright © 2022-2023 Intel Corporation
3
4 """Rust CFG parser.
5
6 Rust uses its `cfg()` format in cargo.
7 https://doc.rust-lang.org/reference/conditional-compilation.html
8
9 This may have the following functions:
10 - all()
11 - any()
12 - not()
13
14 And additionally is made up of `identifier [ = str]`. Where the str is optional,
15 so you could have examples like:
16 ```
17 [target.`cfg(unix)`.dependencies]
18 [target.'cfg(target_arch = "x86_64")'.dependencies]
19 [target.'cfg(all(target_arch = "x86_64", target_arch = "x86"))'.dependencies]
20 ```
21 """
22
23 from __future__ import annotations
24 import dataclasses
25 import enum
26 import typing as T
27
28
29 from ..mesonlib import MesonBugException, lookahead
30
31 if T.TYPE_CHECKING:
32 _T = T.TypeVar('_T')
33 _LEX_TOKEN = T.Tuple['TokenType', T.Optional[str]]
34 _LEX_STREAM = T.Iterator[_LEX_TOKEN]
35 _LEX_STREAM_AH = T.Iterator[T.Tuple[_LEX_TOKEN, T.Optional[_LEX_TOKEN]]]
36
37
38 class TokenType(enum.Enum):
39
40 LPAREN = enum.auto()
41 RPAREN = enum.auto()
42 STRING = enum.auto()
43 IDENTIFIER = enum.auto()
44 ALL = enum.auto()
45 ANY = enum.auto()
46 NOT = enum.auto()
47 COMMA = enum.auto()
48 EQUAL = enum.auto()
49 CFG = enum.auto()
50
51
52 def lexer(raw: str) -> _LEX_STREAM:
53 """Lex a cfg() expression.
54
55 :param raw: The raw cfg() expression
56 :return: An iterable of tokens
57 """
58 start: int = 0
59 is_string: bool = False
60 for i, s in enumerate(raw):
61 if s.isspace() or s in {')', '(', ',', '=', '"'}:
62 val = raw[start:i]
63 start = i + 1
64 if s == '"' and is_string:
65 yield (TokenType.STRING, val)
66 is_string = False
67 continue
68 elif val == 'any':
69 yield (TokenType.ANY, None)
70 elif val == 'all':
71 yield (TokenType.ALL, None)
72 elif val == 'not':
73 yield (TokenType.NOT, None)
74 elif val == 'cfg':
75 yield (TokenType.CFG, None)
76 elif val:
77 yield (TokenType.IDENTIFIER, val)
78
79 if s == '(':
80 yield (TokenType.LPAREN, None)
81 elif s == ')':
82 yield (TokenType.RPAREN, None)
83 elif s == ',':
84 yield (TokenType.COMMA, None)
85 elif s == '=':
86 yield (TokenType.EQUAL, None)
87 elif s == '"':
88 is_string = True
89 val = raw[start:]
90 if val:
91 # This should always be an identifier
92 yield (TokenType.IDENTIFIER, val)
93
94
95 @dataclasses.dataclass
96 class IR:
97
98 """Base IR node for Cargo CFG."""
99
100
101 @dataclasses.dataclass
102 class String(IR):
103
104 value: str
105
106
107 @dataclasses.dataclass
108 class Identifier(IR):
109
110 value: str
111
112
113 @dataclasses.dataclass
114 class Equal(IR):
115
116 lhs: Identifier
117 rhs: String
118
119
120 @dataclasses.dataclass
121 class Any(IR):
122
123 args: T.List[IR]
124
125
126 @dataclasses.dataclass
127 class All(IR):
128
129 args: T.List[IR]
130
131
132 @dataclasses.dataclass
133 class Not(IR):
134
135 value: IR
136
137
138 def _parse(ast: _LEX_STREAM_AH) -> IR:
139 (token, value), n_stream = next(ast)
140 if n_stream is not None:
141 ntoken, _ = n_stream
142 else:
143 ntoken, _ = (None, None)
144
145 if token is TokenType.IDENTIFIER:
146 assert value
147 id_ = Identifier(value)
148 if ntoken is TokenType.EQUAL:
149 next(ast)
150 (token, value), _ = next(ast)
151 assert token is TokenType.STRING
152 assert value is not None
153 return Equal(id_, String(value))
154 return id_
155 elif token in {TokenType.ANY, TokenType.ALL}:
156 type_ = All if token is TokenType.ALL else Any
157 args: T.List[IR] = []
158 (token, value), n_stream = next(ast)
159 assert token is TokenType.LPAREN
160 if n_stream and n_stream[0] == TokenType.RPAREN:
161 return type_(args)
162 while True:
163 args.append(_parse(ast))
164 (token, value), _ = next(ast)
165 if token is TokenType.RPAREN:
166 break
167 assert token is TokenType.COMMA
168 return type_(args)
169 elif token in {TokenType.NOT, TokenType.CFG}:
170 is_not = token is TokenType.NOT
171 (token, value), _ = next(ast)
172 assert token is TokenType.LPAREN
173 arg = _parse(ast)
174 (token, value), _ = next(ast)
175 assert token is TokenType.RPAREN
176 return Not(arg) if is_not else arg
177 else:
178 raise MesonBugException(f'Unhandled Cargo token:{token} {value}')
179
180
181 def parse(ast: _LEX_STREAM) -> IR:
182 """Parse the tokenized list into Meson AST.
183
184 :param ast: An iterable of Tokens
185 :return: An mparser Node to be used as a conditional
186 """
187 ast_i: _LEX_STREAM_AH = lookahead(ast)
188 return _parse(ast_i)
189
190
191 def _eval_cfg(ir: IR, cfgs: T.Dict[str, str]) -> bool:
192 if isinstance(ir, Identifier):
193 return ir.value in cfgs
194 elif isinstance(ir, Equal):
195 return cfgs.get(ir.lhs.value) == ir.rhs.value
196 elif isinstance(ir, Not):
197 return not _eval_cfg(ir.value, cfgs)
198 elif isinstance(ir, Any):
199 return any(_eval_cfg(i, cfgs) for i in ir.args)
200 elif isinstance(ir, All):
201 return all(_eval_cfg(i, cfgs) for i in ir.args)
202 else:
203 raise MesonBugException(f'Unhandled Cargo cfg IR: {ir}')
204
205
206 def eval_cfg(raw: str, cfgs: T.Dict[str, str]) -> bool:
207 return _eval_cfg(parse(lexer(raw)), cfgs)