| 1 |
# SPDX-License-Identifier: Apache-2.0 |
| 2 |
# Copyright © 2024-2025 Intel Corporation |
| 3 |
|
| 4 |
from __future__ import annotations |
| 5 |
import dataclasses |
| 6 |
import os |
| 7 |
import typing as T |
| 8 |
|
| 9 |
from . import ExtensionModule, ModuleInfo |
| 10 |
from ..build import CustomTarget, CustomTargetIndex, GeneratedList |
| 11 |
from ..compilers.compilers import lang_suffixes |
| 12 |
from ..interpreter.decorators import apply_machine_map |
| 13 |
from ..interpreter.interpreterobjects import extract_required_kwarg |
| 14 |
from ..interpreter.type_checking import NoneType, REQUIRED_KW, DISABLER_KW, NATIVE_KW |
| 15 |
from ..interpreterbase import ( |
| 16 |
ContainerTypeInfo, ObjectHolder, KwargInfo, typed_pos_args, typed_kwargs, |
| 17 |
noPosargs, noKwargs, disablerIfNotFound, InterpreterObject |
| 18 |
) |
| 19 |
from ..mesonlib import File, MesonException, Popen_safe, version_compare |
| 20 |
from ..programs import Program, ExternalProgram, NonExistingExternalProgram |
| 21 |
from ..utils.core import HoldableObject |
| 22 |
from .. import mlog |
| 23 |
|
| 24 |
if T.TYPE_CHECKING: |
| 25 |
from typing_extensions import Literal, TypedDict |
| 26 |
|
| 27 |
from . import ModuleState |
| 28 |
from .._typing import ImmutableListProtocol |
| 29 |
from ..interpreter import Interpreter |
| 30 |
from ..interpreter.kwargs import ExtractRequired |
| 31 |
from ..interpreterbase import TYPE_var, TYPE_kwargs |
| 32 |
from ..mesonlib import MachineChoice |
| 33 |
from ..programs import CommandList |
| 34 |
|
| 35 |
LexImpls = Literal['lex', 'flex', 'reflex', 'win_flex'] |
| 36 |
YaccImpls = Literal['yacc', 'byacc', 'bison', 'win_bison'] |
| 37 |
|
| 38 |
class LexGenerateKwargs(TypedDict): |
| 39 |
|
| 40 |
args: T.List[str] |
| 41 |
source: T.Optional[str] |
| 42 |
header: T.Optional[str] |
| 43 |
table: T.Optional[str] |
| 44 |
plainname: bool |
| 45 |
|
| 46 |
class FindLexKwargs(ExtractRequired): |
| 47 |
|
| 48 |
lex_version: T.List[str] |
| 49 |
flex_version: T.List[str] |
| 50 |
reflex_version: T.List[str] |
| 51 |
win_flex_version: T.List[str] |
| 52 |
implementations: T.List[LexImpls] |
| 53 |
native: MachineChoice |
| 54 |
|
| 55 |
class YaccGenerateKWargs(TypedDict): |
| 56 |
|
| 57 |
args: T.List[str] |
| 58 |
source: T.Optional[str] |
| 59 |
header: T.Optional[str] |
| 60 |
locations: T.Optional[str] |
| 61 |
plainname: bool |
| 62 |
|
| 63 |
class FindYaccKwargs(ExtractRequired): |
| 64 |
|
| 65 |
yacc_version: T.List[str] |
| 66 |
byacc_version: T.List[str] |
| 67 |
bison_version: T.List[str] |
| 68 |
win_bison_version: T.List[str] |
| 69 |
implementations: T.List[YaccImpls] |
| 70 |
native: MachineChoice |
| 71 |
|
| 72 |
|
| 73 |
def is_subset_validator(choices: T.Set[str]) -> T.Callable[[T.List[str]], T.Optional[str]]: |
| 74 |
|
| 75 |
def inner(check: T.List[str]) -> T.Optional[str]: |
| 76 |
if not set(check).issubset(choices): |
| 77 |
invalid = ', '.join(sorted(set(check).difference(choices))) |
| 78 |
valid = ', '.join(sorted(choices)) |
| 79 |
return f"valid members are '{valid}', not '{invalid}'" |
| 80 |
return None |
| 81 |
|
| 82 |
return inner |
| 83 |
|
| 84 |
|
| 85 |
@dataclasses.dataclass |
| 86 |
class _CodeGenerator(HoldableObject): |
| 87 |
|
| 88 |
name: str |
| 89 |
program: Program |
| 90 |
for_machine: MachineChoice |
| 91 |
arguments: ImmutableListProtocol[str] = dataclasses.field(default_factory=list) |
| 92 |
|
| 93 |
def command(self) -> CommandList: |
| 94 |
return T.cast('CommandList', [self.program]) + T.cast('CommandList', self.arguments) |
| 95 |
|
| 96 |
def found(self) -> bool: |
| 97 |
return self.program.found() |
| 98 |
|
| 99 |
|
| 100 |
@dataclasses.dataclass |
| 101 |
class LexGenerator(_CodeGenerator): |
| 102 |
pass |
| 103 |
|
| 104 |
|
| 105 |
class LexHolder(ObjectHolder[LexGenerator]): |
| 106 |
|
| 107 |
@noPosargs |
| 108 |
@noKwargs |
| 109 |
@InterpreterObject.method('implementation') |
| 110 |
def implementation_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str: |
| 111 |
return self.held_object.name |
| 112 |
|
| 113 |
@noPosargs |
| 114 |
@noKwargs |
| 115 |
@InterpreterObject.method('found') |
| 116 |
def found_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool: |
| 117 |
return self.held_object.found() |
| 118 |
|
| 119 |
@typed_pos_args('codegen.lex.generate', (str, File, GeneratedList, CustomTarget, CustomTargetIndex)) |
| 120 |
@typed_kwargs( |
| 121 |
'codegen.lex.generate', |
| 122 |
KwargInfo('args', ContainerTypeInfo(list, str), default=[], listify=True), |
| 123 |
KwargInfo('source', (str, NoneType)), |
| 124 |
KwargInfo('header', (str, NoneType)), |
| 125 |
KwargInfo('table', (str, NoneType)), |
| 126 |
KwargInfo('plainname', bool, default=False), |
| 127 |
) |
| 128 |
@InterpreterObject.method('generate') |
| 129 |
def generate_method(self, args: T.Tuple[T.Union[str, File, GeneratedList, CustomTarget, CustomTargetIndex]], kwargs: LexGenerateKwargs) -> CustomTarget: |
| 130 |
if not self.held_object.found(): |
| 131 |
raise MesonException('Attempted to call generate without finding a lex implementation') |
| 132 |
|
| 133 |
input = self.interpreter.source_strings_to_files([args[0]])[0] |
| 134 |
if isinstance(input, File): |
| 135 |
is_cpp = input.endswith(".ll") |
| 136 |
name = os.path.splitext(input.fname)[0] |
| 137 |
else: |
| 138 |
gen_input = input.get_outputs() |
| 139 |
if len(gen_input) != 1: |
| 140 |
raise MesonException('codegen.lex.generate: generated type inputs must have exactly one output, index into them to select the correct input') |
| 141 |
is_cpp = gen_input[0].endswith('.ll') |
| 142 |
name = os.path.splitext(gen_input[0])[0] |
| 143 |
name = os.path.basename(name) |
| 144 |
|
| 145 |
# If an explicit source was given, use that to determine whether the |
| 146 |
# user expects this to be a C or C++ source. |
| 147 |
if kwargs['source'] is not None: |
| 148 |
ext = kwargs['source'].rsplit('.', 1)[1] |
| 149 |
is_cpp = ext in lang_suffixes['cpp'] |
| 150 |
|
| 151 |
# Flex uses FlexLexer.h for C++ code |
| 152 |
for_machine = self.held_object.for_machine |
| 153 |
if is_cpp and self.held_object.name in {'flex', 'win_flex'}: |
| 154 |
try: |
| 155 |
comp = self.interpreter.environment.coredata.compilers[for_machine]['cpp'] |
| 156 |
except KeyError: |
| 157 |
raise MesonException(f"Could not find a C++ compiler for {for_machine} to search for FlexLexer.h") |
| 158 |
found, _ = comp.has_header('FlexLexer.h', '') |
| 159 |
if not found: |
| 160 |
raise MesonException('Could not find FlexLexer.h, which is required for Flex with C++') |
| 161 |
|
| 162 |
if kwargs['source'] is None: |
| 163 |
outputs = ['@{}@.{}'.format( |
| 164 |
'PLAINNAME' if kwargs['plainname'] else 'BASENAME', |
| 165 |
'cpp' if is_cpp else 'c')] |
| 166 |
else: |
| 167 |
outputs = [kwargs['source']] |
| 168 |
|
| 169 |
command = self.held_object.command() |
| 170 |
if kwargs['header'] is not None: |
| 171 |
outputs.append(kwargs['header']) |
| 172 |
command.append(f'--header-file=@OUTPUT{len(outputs) - 1}@') |
| 173 |
if kwargs['table'] is not None: |
| 174 |
outputs.append(kwargs['table']) |
| 175 |
command.append(f'--tables-file=@OUTPUT{len(outputs) - 1}@') |
| 176 |
command.extend(kwargs['args']) |
| 177 |
# Flex, at least, seems to require that input be the last argument given |
| 178 |
command.append('@INPUT@') |
| 179 |
|
| 180 |
target = CustomTarget( |
| 181 |
f'codegen-lex-{name}-{for_machine.get_lower_case_name()}', |
| 182 |
self.interpreter.subdir, |
| 183 |
self.interpreter.environment, |
| 184 |
command, |
| 185 |
[input], |
| 186 |
outputs, |
| 187 |
self.interpreter.current_build_project(), |
| 188 |
backend=self.interpreter.backend, |
| 189 |
description='Generating lexer {{}} with {}'.format(self.held_object.name), |
| 190 |
) |
| 191 |
self.interpreter.add_target(target.name, target) |
| 192 |
|
| 193 |
return target |
| 194 |
|
| 195 |
|
| 196 |
@dataclasses.dataclass |
| 197 |
class YaccGenerator(_CodeGenerator): |
| 198 |
pass |
| 199 |
|
| 200 |
|
| 201 |
class YaccHolder(ObjectHolder[YaccGenerator]): |
| 202 |
|
| 203 |
@noPosargs |
| 204 |
@noKwargs |
| 205 |
@InterpreterObject.method('implementation') |
| 206 |
def implementation_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> str: |
| 207 |
return self.held_object.name |
| 208 |
|
| 209 |
@noPosargs |
| 210 |
@noKwargs |
| 211 |
@InterpreterObject.method('found') |
| 212 |
def found_method(self, args: T.List[TYPE_var], kwargs: TYPE_kwargs) -> bool: |
| 213 |
return self.held_object.found() |
| 214 |
|
| 215 |
@typed_pos_args('codegen.yacc.generate', (str, File, GeneratedList, CustomTarget, CustomTargetIndex)) |
| 216 |
@typed_kwargs( |
| 217 |
'codegen.yacc.generate', |
| 218 |
KwargInfo('args', ContainerTypeInfo(list, str), default=[], listify=True), |
| 219 |
KwargInfo('source', (str, NoneType)), |
| 220 |
KwargInfo('header', (str, NoneType)), |
| 221 |
KwargInfo('locations', (str, NoneType)), |
| 222 |
KwargInfo('plainname', bool, default=False), |
| 223 |
) |
| 224 |
@InterpreterObject.method('generate') |
| 225 |
def generate_method(self, args: T.Tuple[T.Union[str, File, CustomTarget, CustomTargetIndex, GeneratedList]], kwargs: YaccGenerateKWargs) -> CustomTarget: |
| 226 |
if not self.held_object.found(): |
| 227 |
raise MesonException('Attempted to call generate without finding a yacc implementation') |
| 228 |
|
| 229 |
input = self.interpreter.source_strings_to_files([args[0]])[0] |
| 230 |
if isinstance(input, File): |
| 231 |
is_cpp = input.endswith(".yy") |
| 232 |
name = os.path.splitext(input.fname)[0] |
| 233 |
else: |
| 234 |
gen_input = input.get_outputs() |
| 235 |
if len(gen_input) != 1: |
| 236 |
raise MesonException('codegen.lex.generate: generated type inputs must have exactly one output, index into them to select the correct input') |
| 237 |
is_cpp = gen_input[0].endswith('.yy') |
| 238 |
name = os.path.splitext(gen_input[0])[0] |
| 239 |
name = os.path.basename(name) |
| 240 |
|
| 241 |
command = self.held_object.command() |
| 242 |
command.extend(kwargs['args']) |
| 243 |
|
| 244 |
source_ext = 'cpp' if is_cpp else 'c' |
| 245 |
header_ext = 'hpp' if is_cpp else 'h' |
| 246 |
|
| 247 |
base = '@PLAINNAME@' if kwargs['plainname'] else '@BASENAME@' |
| 248 |
outputs: T.List[str] = [] |
| 249 |
outputs.append(f'{base}.{source_ext}' if kwargs['source'] is None else kwargs['source']) |
| 250 |
outputs.append(f'{base}.{header_ext}' if kwargs['header'] is None else kwargs['header']) |
| 251 |
if kwargs['locations'] is not None: |
| 252 |
outputs.append(kwargs['locations']) |
| 253 |
|
| 254 |
for_machine = self.held_object.for_machine |
| 255 |
target = CustomTarget( |
| 256 |
f'codegen-yacc-{name}-{for_machine.get_lower_case_name()}', |
| 257 |
self.interpreter.subdir, |
| 258 |
self.interpreter.environment, |
| 259 |
command, |
| 260 |
[input], |
| 261 |
outputs, |
| 262 |
self.interpreter.current_build_project(), |
| 263 |
backend=self.interpreter.backend, |
| 264 |
description='Generating parser {{}} with {}'.format(self.held_object.name), |
| 265 |
) |
| 266 |
self.interpreter.add_target(target.name, target) |
| 267 |
return target |
| 268 |
|
| 269 |
|
| 270 |
class CodeGenModule(ExtensionModule): |
| 271 |
|
| 272 |
"""Module with helpers for codegen wrappers.""" |
| 273 |
|
| 274 |
INFO = ModuleInfo('codegen', '1.10.0', unstable=True) |
| 275 |
|
| 276 |
def __init__(self, interpreter: Interpreter) -> None: |
| 277 |
super().__init__(interpreter) |
| 278 |
self.methods.update({ |
| 279 |
'lex': self.lex_method, |
| 280 |
'yacc': self.yacc_method, |
| 281 |
}) |
| 282 |
|
| 283 |
@noPosargs |
| 284 |
@typed_kwargs( |
| 285 |
'codegen.lex', |
| 286 |
KwargInfo('lex_version', ContainerTypeInfo(list, str), default=[], listify=True), |
| 287 |
KwargInfo('flex_version', ContainerTypeInfo(list, str), default=[], listify=True), |
| 288 |
KwargInfo('reflex_version', ContainerTypeInfo(list, str), default=[], listify=True), |
| 289 |
KwargInfo('win_flex_version', ContainerTypeInfo(list, str), default=[], listify=True), |
| 290 |
KwargInfo( |
| 291 |
'implementations', |
| 292 |
ContainerTypeInfo(list, str), |
| 293 |
default=[], |
| 294 |
listify=True, |
| 295 |
validator=is_subset_validator({'lex', 'flex', 'reflex', 'win_flex'}) |
| 296 |
), |
| 297 |
REQUIRED_KW, |
| 298 |
DISABLER_KW, |
| 299 |
NATIVE_KW |
| 300 |
) |
| 301 |
@apply_machine_map |
| 302 |
@disablerIfNotFound |
| 303 |
def lex_method(self, state: ModuleState, args: T.Tuple, kwargs: FindLexKwargs) -> LexGenerator: |
| 304 |
disabled, required, feature = extract_required_kwarg(kwargs, state.subproject) |
| 305 |
if disabled: |
| 306 |
mlog.log('generator lex skipped: feature', mlog.bold(feature), 'disabled') |
| 307 |
return LexGenerator('lex', NonExistingExternalProgram('lex'), kwargs['native']) |
| 308 |
|
| 309 |
names: T.List[LexImpls] = [] |
| 310 |
if kwargs['implementations']: |
| 311 |
names = kwargs['implementations'] |
| 312 |
else: |
| 313 |
if state.environment.machines[kwargs['native']].system == 'windows': |
| 314 |
names.append('win_flex') |
| 315 |
names.extend(['flex', 'reflex', 'lex']) |
| 316 |
|
| 317 |
versions: T.Mapping[str, T.List[str]] = { |
| 318 |
'lex': kwargs['lex_version'], |
| 319 |
'flex': kwargs['flex_version'], |
| 320 |
'reflex': kwargs['reflex_version'], |
| 321 |
'win_flex': kwargs['win_flex_version'] |
| 322 |
} |
| 323 |
|
| 324 |
for name in names: |
| 325 |
bin = state.find_program( |
| 326 |
name, wanted=versions[name], for_machine=kwargs['native'], required=False) |
| 327 |
if bin.found(): |
| 328 |
# If you're building reflex as a subproject, we consider that you |
| 329 |
# know what you're doing. |
| 330 |
if name == 'reflex' and isinstance(bin, ExternalProgram): |
| 331 |
# there are potentially 3 programs called "reflex": |
| 332 |
# 1. https://invisible-island.net/reflex/, an alternate fork |
| 333 |
# of the original flex, this is supported |
| 334 |
# 2. https://www.genivia.com/doc/reflex/html/, an |
| 335 |
# alternative implementation for generating C++ scanners. |
| 336 |
# Not supported |
| 337 |
# 3. https://github.com/cespare/reflex, which is not a lex |
| 338 |
# implementation at all, but a file watcher |
| 339 |
_, out, err = Popen_safe(bin.get_command() + ['--version']) |
| 340 |
if 'unknown flag: --version' in err: |
| 341 |
mlog.debug('Skipping cespare/reflex, which is not a lexer and is not supported') |
| 342 |
continue |
| 343 |
if 'Written by Robert van Engelen' in out: |
| 344 |
mlog.debug('Skipping RE/flex, which is not compatible with POSIX lex.') |
| 345 |
continue |
| 346 |
break |
| 347 |
else: |
| 348 |
if required: |
| 349 |
raise MesonException.from_node( |
| 350 |
'Could not find a lex implementation. Tried: ', ", ".join(names), |
| 351 |
node=state.current_node) |
| 352 |
return LexGenerator(name, bin, kwargs['native']) |
| 353 |
|
| 354 |
lex_args: T.List[str] = [] |
| 355 |
# This option allows compiling with MSVC |
| 356 |
# https://github.com/lexxmark/winflexbison/blob/master/UNISTD_ERROR.readme |
| 357 |
if bin.name == 'win_flex' and state.environment.machines[kwargs['native']].is_windows(): |
| 358 |
lex_args.append('--wincompat') |
| 359 |
lex_args.extend(['-o', '@OUTPUT0@']) |
| 360 |
return LexGenerator(name, bin, kwargs['native'], T.cast('ImmutableListProtocol[str]', lex_args)) |
| 361 |
|
| 362 |
@noPosargs |
| 363 |
@typed_kwargs( |
| 364 |
'codegen.yacc', |
| 365 |
KwargInfo('yacc_version', ContainerTypeInfo(list, str), default=[], listify=True), |
| 366 |
KwargInfo('byacc_version', ContainerTypeInfo(list, str), default=[], listify=True), |
| 367 |
KwargInfo('bison_version', ContainerTypeInfo(list, str), default=[], listify=True), |
| 368 |
KwargInfo('win_bison_version', ContainerTypeInfo(list, str), default=[], listify=True), |
| 369 |
KwargInfo( |
| 370 |
'implementations', |
| 371 |
ContainerTypeInfo(list, str), |
| 372 |
default=[], |
| 373 |
listify=True, |
| 374 |
validator=is_subset_validator({'yacc', 'byacc', 'bison', 'win_bison'}) |
| 375 |
), |
| 376 |
REQUIRED_KW, |
| 377 |
DISABLER_KW, |
| 378 |
NATIVE_KW, |
| 379 |
) |
| 380 |
@apply_machine_map |
| 381 |
@disablerIfNotFound |
| 382 |
def yacc_method(self, state: ModuleState, args: T.Tuple, kwargs: FindYaccKwargs) -> YaccGenerator: |
| 383 |
disabled, required, feature = extract_required_kwarg(kwargs, state.subproject) |
| 384 |
if disabled: |
| 385 |
mlog.log('generator yacc skipped: feature', mlog.bold(feature), 'disabled') |
| 386 |
return YaccGenerator('yacc', NonExistingExternalProgram('yacc'), kwargs['native']) |
| 387 |
names: T.List[YaccImpls] |
| 388 |
if kwargs['implementations']: |
| 389 |
names = kwargs['implementations'] |
| 390 |
else: |
| 391 |
if state.environment.machines[kwargs['native']].system == 'windows': |
| 392 |
names = ['win_bison', 'bison', 'yacc'] |
| 393 |
else: |
| 394 |
names = ['bison', 'byacc', 'yacc'] |
| 395 |
|
| 396 |
versions: T.Mapping[YaccImpls, T.List[str]] = { |
| 397 |
'yacc': kwargs['yacc_version'], |
| 398 |
'byacc': kwargs['byacc_version'], |
| 399 |
'bison': kwargs['bison_version'], |
| 400 |
'win_bison': kwargs['win_bison_version'], |
| 401 |
} |
| 402 |
|
| 403 |
for name in names: |
| 404 |
bin = state.find_program( |
| 405 |
name, wanted=versions[name], for_machine=kwargs['native'], required=False) |
| 406 |
if bin.found(): |
| 407 |
break |
| 408 |
else: |
| 409 |
if required: |
| 410 |
raise MesonException.from_node( |
| 411 |
'Could not find a yacc implementation. Tried: ', ", ".join(names), |
| 412 |
node=state.current_node) |
| 413 |
return YaccGenerator(name, bin, kwargs['native']) |
| 414 |
|
| 415 |
yacc_args: T.List[str] = [] |
| 416 |
|
| 417 |
impl = T.cast('YaccImpls', bin.name) |
| 418 |
if impl == 'yacc' and isinstance(bin, ExternalProgram): |
| 419 |
_, out, _ = Popen_safe(bin.get_command() + ['--version']) |
| 420 |
if 'GNU Bison' in out: |
| 421 |
impl = 'bison' |
| 422 |
elif out.startswith('yacc - 2'): |
| 423 |
impl = 'byacc' |
| 424 |
|
| 425 |
if impl in {'bison', 'win_bison'}: |
| 426 |
yacc_args.append('--defines=@OUTPUT1@') |
| 427 |
if isinstance(bin, ExternalProgram) and version_compare(bin.get_version(), '>= 3.4'): |
| 428 |
yacc_args.append('--color=always') |
| 429 |
elif impl == 'byacc': |
| 430 |
yacc_args.extend(['-H', '@OUTPUT1@']) |
| 431 |
else: |
| 432 |
mlog.warning('This yacc does not appear to be bison or byacc, the ' |
| 433 |
'POSIX specification does not require that header ' |
| 434 |
'output location be configurable, and may not work.', |
| 435 |
fatal=False) |
| 436 |
yacc_args.append('-H') |
| 437 |
yacc_args.extend(['-o', '@OUTPUT0@', '@INPUT@']) |
| 438 |
return YaccGenerator(name, bin, kwargs['native'], T.cast('ImmutableListProtocol[str]', yacc_args)) |
| 439 |
|
| 440 |
|
| 441 |
def initialize(interpreter: Interpreter) -> CodeGenModule: |
| 442 |
interpreter.append_holder_map(LexGenerator, LexHolder) |
| 443 |
interpreter.append_holder_map(YaccGenerator, YaccHolder) |
| 444 |
return CodeGenModule(interpreter) |