Skip to content

Commit

Permalink
holders: Introduce HoldableObject
Browse files Browse the repository at this point in the history
  • Loading branch information
mensinda committed Jun 18, 2021
1 parent d601227 commit 66b32a4
Show file tree
Hide file tree
Showing 12 changed files with 78 additions and 42 deletions.
30 changes: 15 additions & 15 deletions mesonbuild/build.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from . import mlog
from . import programs
from .mesonlib import (
HoldableObject,
File, MesonException, MachineChoice, PerMachine, OrderedSet, listify,
extract_as_list, typeslistify, stringlistify, classify_unity_sources,
get_filenames_templates_dict, substitute_values, has_path_sep, unholder,
Expand Down Expand Up @@ -125,13 +126,13 @@ def get_target_macos_dylib_install_name(ld) -> str:
class InvalidArguments(MesonException):
pass

class DependencyOverride:
class DependencyOverride(HoldableObject):
def __init__(self, dep, node, explicit=True):
self.dep = dep
self.node = node
self.explicit = explicit

class Headers:
class Headers(HoldableObject):

def __init__(self, sources: T.List[File], install_subdir: T.Optional[str],
install_dir: T.Optional[str], install_mode: T.Optional['FileMode'],
Expand Down Expand Up @@ -161,7 +162,7 @@ def get_custom_install_mode(self) -> T.Optional['FileMode']:
return self.custom_install_mode


class Man:
class Man(HoldableObject):

def __init__(self, sources: T.List[File], install_dir: T.Optional[str],
install_mode: T.Optional['FileMode'], subproject: str,
Expand All @@ -182,7 +183,7 @@ def get_sources(self) -> T.List['File']:
return self.sources


class InstallDir:
class InstallDir(HoldableObject):

def __init__(self, src_subdir: str, inst_subdir: str, install_dir: str,
install_mode: T.Optional['FileMode'],
Expand Down Expand Up @@ -327,12 +328,11 @@ def get_project_link_args(self, compiler, project, for_machine):

return link_args.get(compiler.get_language(), [])

class IncludeDirs:
class IncludeDirs(HoldableObject):

"""Internal representation of an include_directories call."""

def __init__(self, curdir: str, dirs: T.List[str], is_system: bool,
extra_build_dirs: T.Optional[T.List[str]] = None):
def __init__(self, curdir: str, dirs: T.List[str], is_system: bool, extra_build_dirs: T.Optional[T.List[str]] = None):
self.curdir = curdir
self.incdirs = dirs
self.is_system = is_system
Expand Down Expand Up @@ -361,7 +361,7 @@ def to_string_list(self, sourcedir: str) -> T.List[str]:
strlist.append(os.path.join(sourcedir, self.curdir, idir))
return strlist

class ExtractedObjects:
class ExtractedObjects(HoldableObject):
'''
Holds a list of sources for which the objects must be extracted
'''
Expand Down Expand Up @@ -416,7 +416,7 @@ def get_outputs(self, backend):
for source in self.srclist
]

class EnvironmentVariables:
class EnvironmentVariables(HoldableObject):
def __init__(self) -> None:
self.envvars = []
# The set of all env vars we have operations for. Only used for self.has_name()
Expand Down Expand Up @@ -458,7 +458,7 @@ def get_env(self, full_env: T.Dict[str, str]) -> T.Dict[str, str]:
env[name] = method(env, name, values, separator)
return env

class Target:
class Target(HoldableObject):

# TODO: should Target be an abc.ABCMeta?

Expand Down Expand Up @@ -1508,7 +1508,7 @@ def check_module_linking(self):
'platforms')
return

class Generator:
class Generator(HoldableObject):
def __init__(self, exe: T.Union['Executable', programs.ExternalProgram],
arguments: T.List[str],
output: T.List[str],
Expand Down Expand Up @@ -1584,7 +1584,7 @@ def process_files(self, files: T.Iterable[T.Union[str, File, 'CustomTarget', 'Cu
return output


class GeneratedList:
class GeneratedList(HoldableObject):

"""The output of generator.process."""

Expand Down Expand Up @@ -2527,7 +2527,7 @@ def get_classpath_args(self):
return ['-cp', os.pathsep.join(cp_paths)]
return []

class CustomTargetIndex:
class CustomTargetIndex(HoldableObject):

"""A special opaque object returned by indexing a CustomTarget. This object
exists in Meson, but acts as a proxy in the backends, making targets depend
Expand Down Expand Up @@ -2583,7 +2583,7 @@ def extract_all_objects_recurse(self):
def get_custom_install_dir(self):
return self.target.get_custom_install_dir()

class ConfigurationData:
class ConfigurationData(HoldableObject):
def __init__(self) -> None:
super().__init__()
self.values = {} # T.Dict[str, T.Union[str, int, bool]]
Expand All @@ -2602,7 +2602,7 @@ def keys(self) -> T.Iterator[str]:

# A bit poorly named, but this represents plain data files to copy
# during install.
class Data:
class Data(HoldableObject):
def __init__(self, sources: T.List[File], install_dir: str,
install_mode: T.Optional['FileMode'], subproject: str,
rename: T.List[str] = None):
Expand Down
7 changes: 4 additions & 3 deletions mesonbuild/compilers/compilers.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from .. import mlog
from .. import mesonlib
from ..mesonlib import (
HoldableObject,
EnvironmentException, MachineChoice, MesonException,
Popen_safe, LibType, TemporaryDirectoryWinProof, OptionKey,
)
Expand Down Expand Up @@ -435,7 +436,7 @@ def get_base_link_args(options: 'KeyedOptionDictType', linker: 'Compiler',
class CrossNoRunException(MesonException):
pass

class RunResult:
class RunResult(HoldableObject):
def __init__(self, compiled: bool, returncode: int = 999,
stdout: str = 'UNDEFINED', stderr: str = 'UNDEFINED'):
self.compiled = compiled
Expand All @@ -444,7 +445,7 @@ def __init__(self, compiled: bool, returncode: int = 999,
self.stderr = stderr


class CompileResult:
class CompileResult(HoldableObject):

"""The result of Compiler.compiles (and friends)."""

Expand All @@ -467,7 +468,7 @@ def __init__(self, stdo: T.Optional[str] = None, stde: T.Optional[str] = None,
self.text_mode = text_mode


class Compiler(metaclass=abc.ABCMeta):
class Compiler(HoldableObject, metaclass=abc.ABCMeta):
# Libraries to ignore in find_library() since they are provided by the
# compiler or the C library. Currently only used for MSVC.
ignore_libs = [] # type: T.List[str]
Expand Down
4 changes: 3 additions & 1 deletion mesonbuild/coredata.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from pathlib import PurePath
from collections import OrderedDict
from .mesonlib import (
HoldableObject,
MesonException, EnvironmentException, MachineChoice, PerMachine,
PerMachineDefaultable, default_libdir, default_libexecdir,
default_prefix, split_args, OptionKey, OptionType, stringlistify,
Expand Down Expand Up @@ -61,7 +62,7 @@ def __init__(self, old_version: str, current_version: str) -> None:
self.current_version = current_version


class UserOption(T.Generic[_T]):
class UserOption(T.Generic[_T], HoldableObject):
def __init__(self, description: str, choices: T.Optional[T.Union[str, T.List[_T]]], yielding: T.Optional[bool]):
super().__init__()
self.choices = choices
Expand Down Expand Up @@ -255,6 +256,7 @@ class UserFeatureOption(UserComboOption):

def __init__(self, description: str, value: T.Any, yielding: T.Optional[bool] = None):
super().__init__(description, self.static_choices, value, yielding)
self.name: T.Optional[str] = None # TODO: Refactor options to all store their name

def is_enabled(self) -> bool:
return self.value == 'enabled'
Expand Down
4 changes: 2 additions & 2 deletions mesonbuild/dependencies/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

from .. import mlog
from ..compilers import clib_langs
from ..mesonlib import MachineChoice, MesonException
from ..mesonlib import MachineChoice, MesonException, HoldableObject
from ..mesonlib import version_compare_many
from ..interpreterbase import FeatureDeprecated

Expand Down Expand Up @@ -65,7 +65,7 @@ class DependencyMethods(Enum):
DependencyTypeName = T.NewType('DependencyTypeName', str)


class Dependency:
class Dependency(HoldableObject):

@classmethod
def _process_include_type_kw(cls, kwargs: T.Dict[str, T.Any]) -> str:
Expand Down
4 changes: 2 additions & 2 deletions mesonbuild/envconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from enum import Enum

from . import mesonlib
from .mesonlib import EnvironmentException
from .mesonlib import EnvironmentException, HoldableObject
from . import mlog
from pathlib import Path

Expand Down Expand Up @@ -232,7 +232,7 @@ def __contains__(self, item: T.Union[str, bool, int, T.List[str]]) -> bool:
def get(self, key: str, default: T.Optional[T.Union[str, bool, int, T.List[str]]] = None) -> T.Optional[T.Union[str, bool, int, T.List[str]]]:
return self.properties.get(key, default)

class MachineInfo:
class MachineInfo(HoldableObject):
def __init__(self, system: str, cpu_family: str, cpu: str, endian: str):
self.system = system
self.cpu_family = cpu_family
Expand Down
2 changes: 1 addition & 1 deletion mesonbuild/interpreter/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@
from .compiler import CompilerHolder
from .interpreterobjects import (ExecutableHolder, BuildTargetHolder, CustomTargetHolder,
CustomTargetIndexHolder, MachineHolder, Test,
ConfigurationDataHolder, SubprojectHolder, DependencyHolder,
ConfigurationDataObject, SubprojectHolder, DependencyHolder,
GeneratedListHolder, ExternalProgramHolder,
extract_required_kwarg)
2 changes: 1 addition & 1 deletion mesonbuild/interpreter/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def dump_value(self, arr, list_sep, indent):
'version',
}

class Interpreter(InterpreterBase):
class Interpreter(InterpreterBase, HoldableObject):

def __init__(
self,
Expand Down
2 changes: 1 addition & 1 deletion mesonbuild/interpreter/interpreterobjects.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from ..interpreterbase.decorators import FeatureCheckBase
from ..dependencies import Dependency, ExternalLibrary, InternalDependency
from ..programs import ExternalProgram
from ..mesonlib import FileMode, OptionKey, listify, Popen_safe
from ..mesonlib import HoldableObject, MesonException, OptionKey, listify, Popen_safe

import typing as T

Expand Down
34 changes: 23 additions & 11 deletions mesonbuild/interpreterbase/baseobjects.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,33 @@
from .. import mparser
from .exceptions import InvalidCode
from .helpers import flatten
from ..mesonlib import HoldableObject

import typing as T

if T.TYPE_CHECKING:
# Object holders need the actual interpreter
from ..interpreter import Interpreter

TV_fw_var = T.Union[str, int, bool, list, dict, 'InterpreterObject']
TV_fw_args = T.List[T.Union[mparser.BaseNode, TV_fw_var]]
TV_fw_kwargs = T.Dict[str, T.Union[mparser.BaseNode, TV_fw_var]]

TV_func = T.TypeVar('TV_func', bound=T.Callable[..., T.Any])

TYPE_elementary = T.Union[str, int, bool]
TYPE_var = T.Union[TYPE_elementary, T.List[T.Any], T.Dict[str, T.Any], 'InterpreterObject']
TYPE_elementary = T.Union[str, int, bool, T.List[T.Any], T.Dict[str, T.Any]]
TYPE_var = T.Union[TYPE_elementary, HoldableObject, 'MesonInterpreterObject']
TYPE_nvar = T.Union[TYPE_var, mparser.BaseNode]
TYPE_kwargs = T.Dict[str, TYPE_var]
TYPE_nkwargs = T.Dict[str, TYPE_nvar]
TYPE_key_resolver = T.Callable[[mparser.BaseNode], str]

class InterpreterObject:
def __init__(self, *, subproject: T.Optional[str] = None) -> None:
self.methods = {} # type: T.Dict[str, T.Callable[[T.List[TYPE_nvar], TYPE_nkwargs], TYPE_var]]
self.methods: T.Dict[
str,
T.Callable[[T.List[TYPE_var], TYPE_kwargs], TYPE_var]
] = {}
# Current node set during a method call. This can be used as location
# when printing a warning message during a method call.
self.current_node: mparser.BaseNode = None
Expand All @@ -41,8 +50,8 @@ def __init__(self, *, subproject: T.Optional[str] = None) -> None:
def method_call(
self,
method_name: str,
args: TV_fw_args,
kwargs: TV_fw_kwargs
args: T.List[TYPE_var],
kwargs: TYPE_kwargs
) -> TYPE_var:
if method_name in self.methods:
method = self.methods[method_name]
Expand All @@ -52,20 +61,23 @@ def method_call(
raise InvalidCode('Unknown method "%s" in object.' % method_name)

class MesonInterpreterObject(InterpreterObject):
''' All non-elementary objects should be derived from this '''
''' All non-elementary objects and non-object-holders should be derived from this '''

class MutableInterpreterObject:
''' Dummy class to mark the object type as mutable '''

TV_InterpreterObject = T.TypeVar('TV_InterpreterObject')
InterpreterObjectTypeVar = T.TypeVar('InterpreterObjectTypeVar', bound=HoldableObject)

class ObjectHolder(MesonInterpreterObject, T.Generic[TV_InterpreterObject]):
def __init__(self, obj: TV_InterpreterObject, *, subproject: T.Optional[str] = None) -> None:
super().__init__(subproject=subproject)
class ObjectHolder(InterpreterObject, T.Generic[InterpreterObjectTypeVar]):
def __init__(self, obj: InterpreterObjectTypeVar, interpreter: 'Interpreter') -> None:
super().__init__(subproject=interpreter.subproject)
assert isinstance(obj, HoldableObject), f'This is a bug: Trying to hold object of type `{type(obj).__name__}` that is not an `HoldableObject`'
self.held_object = obj
self.interpreter = interpreter
self.env = self.interpreter.environment

def __repr__(self) -> str:
return f'<Holder: {self.held_object!r}>'
return f'<[{type(self).__name__}] holds [{type(self.held_object).__name__}]: {self.held_object!r}>'

class RangeHolder(MesonInterpreterObject):
def __init__(self, start: int, stop: int, step: int, *, subproject: T.Optional[str] = None) -> None:
Expand Down
8 changes: 7 additions & 1 deletion mesonbuild/mesonlib/universal.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import sys
import stat
import time
import abc
import platform, subprocess, operator, os, shlex, shutil, re
import collections
from functools import lru_cache, wraps, total_ordering
Expand Down Expand Up @@ -46,6 +47,7 @@
'an_unpicklable_object',
'python_command',
'project_meson_versions',
'HoldableObject',
'File',
'FileMode',
'GitException',
Expand Down Expand Up @@ -267,6 +269,10 @@ def check_direntry_issues(direntry_array: T.Union[T.List[T.Union[str, bytes]], s
import threading
an_unpicklable_object = threading.Lock()

class HoldableObject(metaclass=abc.ABCMeta):
''' Dummy base class for all objects that can be
held by an interpreter.baseobjects.ObjectHolder '''

class FileMode:
# The first triad is for owner permissions, the second for group permissions,
# and the third for others (everyone else).
Expand Down Expand Up @@ -366,7 +372,7 @@ def perms_s_to_bits(cls, perms_s: T.Optional[str]) -> int:
Visual Studio compiler, as it treats .C files as C code, unless you add
the /TP compiler flag, but this is unreliable.
See https://github.com/mesonbuild/meson/pull/8747 for the discussions."""
class File:
class File(HoldableObject):
def __init__(self, is_built: bool, subdir: str, fname: str):
if fname.endswith(".C") or fname.endswith(".H"):
mlog.warning(dot_C_dot_H_warning, once=True)
Expand Down
2 changes: 1 addition & 1 deletion mesonbuild/programs.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from .environment import Environment


class ExternalProgram:
class ExternalProgram(mesonlib.HoldableObject):

"""A program that is found on the system."""

Expand Down
Loading

0 comments on commit 66b32a4

Please sign in to comment.