1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
|
# Copyright 2019 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import web_idl
_CODE_GEN_EXPR_PASS_KEY = object()
class CodeGenExpr(object):
"""
Represents an expression which is composable to produce another expression.
This is designed primarily to represent conditional expressions and basic
logical operators (expr_not, expr_and, expr_or) come along with.
"""
def __init__(self, expr, is_compound=False, pass_key=None):
assert isinstance(expr, (bool, str))
assert isinstance(is_compound, bool)
assert pass_key is _CODE_GEN_EXPR_PASS_KEY
if isinstance(expr, bool):
self._text = "true" if expr else "false"
else:
self._text = expr
self._is_compound = is_compound
self._is_always_false = expr is False
self._is_always_true = expr is True
def __eq__(self, other):
if not isinstance(self, other.__class__):
return NotImplemented
# Assume that, as long as the two texts are the same, the two
# expressions must be the same, i.e. |_is_compound|, etc. must be the
# same or do not matter.
return self.to_text() == other.to_text()
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return hash(self.to_text())
def __str__(self):
"""
__str__ is designed to be used when composing another expression. If
you'd only like to have a string representation, |to_text| works better.
"""
if self._is_compound:
return "({})".format(self.to_text())
return self.to_text()
def to_text(self):
return self._text
@property
def is_always_false(self):
"""
The expression is always False, and code generators have chances of
optimizations.
"""
return self._is_always_false
@property
def is_always_true(self):
"""
The expression is always True, and code generators have chances of
optimizations.
"""
return self._is_always_true
def _Expr(*args, **kwargs):
return CodeGenExpr(*args, pass_key=_CODE_GEN_EXPR_PASS_KEY, **kwargs)
def _unary_op(op, term):
assert isinstance(op, str)
assert isinstance(term, CodeGenExpr)
return _Expr("{}{}".format(op, term), is_compound=True)
def _binary_op(op, terms):
assert isinstance(op, str)
assert isinstance(terms, (list, tuple))
assert all(isinstance(term, CodeGenExpr) for term in terms)
assert all(
not (term.is_always_false or term.is_always_true) for term in terms)
return _Expr(op.join(map(str, terms)), is_compound=True)
def expr_not(term):
assert isinstance(term, CodeGenExpr)
if term.is_always_false:
return _Expr(True)
if term.is_always_true:
return _Expr(False)
return _unary_op("!", term)
def expr_and(terms):
assert isinstance(terms, (list, tuple))
assert all(isinstance(term, CodeGenExpr) for term in terms)
assert terms
if any(term.is_always_false for term in terms):
return _Expr(False)
terms = list(filter(lambda x: not x.is_always_true, terms))
if not terms:
return _Expr(True)
terms = expr_uniq(terms)
if len(terms) == 1:
return terms[0]
return _binary_op(" && ", terms)
def expr_or(terms):
assert isinstance(terms, (list, tuple))
assert all(isinstance(term, CodeGenExpr) for term in terms)
assert terms
if any(term.is_always_true for term in terms):
return _Expr(True)
terms = list(filter(lambda x: not x.is_always_false, terms))
if not terms:
return _Expr(False)
terms = expr_uniq(terms)
if len(terms) == 1:
return terms[0]
return _binary_op(" || ", terms)
def expr_uniq(terms):
assert isinstance(terms, (list, tuple))
assert all(isinstance(term, CodeGenExpr) for term in terms)
uniq_terms = []
for term in terms:
if term not in uniq_terms:
uniq_terms.append(term)
return uniq_terms
def expr_from_exposure(exposure,
global_names=None,
may_use_feature_selector=False):
"""
Returns an expression to determine whether this property should be exposed
or not.
Args:
exposure: web_idl.Exposure of the target construct.
global_names: When specified, it's taken into account that the global
object implements |global_names|.
may_use_feature_selector: True enables use of ${feature_selector} iff
the exposure is context dependent.
"""
assert isinstance(exposure, web_idl.Exposure)
assert (global_names is None
or (isinstance(global_names, (list, tuple))
and all(isinstance(name, str) for name in global_names)))
assert isinstance(may_use_feature_selector, bool)
# The property exposures are categorized into three.
# - Unconditional: Always exposed.
# - Context-independent: Enabled per v8::Isolate.
# - Context-dependent: Enabled per v8::Context, e.g. origin trials, browser
# controlled features.
#
# Context-dependent properties can be installed in two phases.
# - The first phase installs all the properties that are associated with the
# features enabled at the moment. This phase is represented by
# FeatureSelector as FeatureSelector.IsAll().
# - The second phase installs the properties associated with the specified
# feature. This phase is represented as FeatureSelector.IsAny(feature).
#
# The exposure condition is represented as;
# (and feature_selector-independent-term
# (or
# feature_selector-1st-phase-term
# feature_selector-2nd-phase-term))
# which can be represented in more details as:
# (and cross_origin_isolated_term
# injection_mitigated_term
# isolated_context_term
# secure_context_term
# uncond_exposed_term
# (or
# (and feature_selector.IsAll() # 1st phase; all enabled
# cond_exposed_term
# (or feature_enabled_term
# context_enabled_term))
# (or exposed_selector_term # 2nd phase; any selected
# feature_selector_term)))
# where
# cross_origin_isolated_term represents [CrossOriginIsolated]
# injection_mitigated_term represents [InjectionMitigated]
# isolated_context_term represents [IsolatedContext]
# secure_context_term represents [SecureContext=F1]
# uncond_exposed_term represents [Exposed=(G1, G2)]
# cond_exposed_term represents [Exposed(G1 F1, G2 F2)]
# feature_enabled_term represents [RuntimeEnabled=(F1, F2)]
# context_enabled_term represents [ContextEnabled=F1]
# exposed_selector_term represents [Exposed(G1 F1, G2 F2)]
# feature_selector_term represents [RuntimeEnabled=(F1, F2)]
uncond_exposed_terms = []
cond_exposed_terms = []
feature_enabled_terms = []
context_enabled_terms = []
exposed_selector_terms = []
feature_selector_names = [] # Will turn into feature_selector.IsAnyOf(...)
def ref_enabled(feature):
arg = "${execution_context}" if feature.is_context_dependent else ""
return _Expr("RuntimeEnabledFeatures::{}Enabled({})".format(
feature, arg))
def ref_selected(features):
feature_tokens = map(
lambda feature: "mojom::blink::OriginTrialFeature::k{}".format(
feature), features)
return _Expr("${{feature_selector}}.IsAnyOf({})".format(
", ".join(feature_tokens)))
# [CrossOriginIsolated], [CrossOriginIsolatedOrRuntimeEnabled]
if exposure.only_in_coi_contexts:
cross_origin_isolated_term = _Expr("${is_cross_origin_isolated}")
elif exposure.only_in_coi_contexts_or_runtime_enabled_features:
cross_origin_isolated_term = expr_or([
_Expr("${is_cross_origin_isolated}"),
expr_or(
list(
map(
ref_enabled, exposure.
only_in_coi_contexts_or_runtime_enabled_features)))
])
else:
cross_origin_isolated_term = _Expr(True)
# [InjectionMitigated]
if exposure.only_in_injection_mitigated_contexts:
injection_mitigated_context_term = _Expr(
"${is_in_injection_mitigated_context}")
else:
injection_mitigated_context_term = _Expr(True)
# [IsolatedContext]
if exposure.only_in_isolated_contexts:
isolated_context_term = _Expr("${is_in_isolated_context}")
else:
isolated_context_term = _Expr(True)
# [SecureContext]
if exposure.only_in_secure_contexts is True:
secure_context_term = _Expr("${is_in_secure_context}")
elif exposure.only_in_secure_contexts is False:
secure_context_term = _Expr(True)
else:
terms = list(map(ref_enabled, exposure.only_in_secure_contexts))
secure_context_term = expr_or(
[_Expr("${is_in_secure_context}"),
expr_not(expr_and(terms))])
# [Exposed]
GLOBAL_NAME_TO_EXECUTION_CONTEXT_TEST = {
"AnimationWorklet": "IsAnimationWorkletGlobalScope",
"AudioWorklet": "IsAudioWorkletGlobalScope",
"DedicatedWorker": "IsDedicatedWorkerGlobalScope",
"LayoutWorklet": "IsLayoutWorkletGlobalScope",
"PaintWorklet": "IsPaintWorkletGlobalScope",
"ServiceWorker": "IsServiceWorkerGlobalScope",
"ShadowRealm": "IsShadowRealmGlobalScope",
"SharedWorker": "IsSharedWorkerGlobalScope",
"SharedStorageWorklet": "IsSharedStorageWorkletGlobalScope",
"Window": "IsWindow",
"Worker": "IsWorkerGlobalScope",
"Worklet": "IsWorkletGlobalScope",
}
if global_names:
matched_global_count = 0
for entry in exposure.global_names_and_features:
if entry.global_name == "*":
# [Exposed(GLOBAL_NAME FEATURE_NAME)] is not supported.
assert entry.feature is None
# Constructs with the wildcard exposure ([Exposed=*]) are
# unconditionally exposed.
pass
elif entry.global_name not in global_names:
continue
matched_global_count += 1
if entry.feature:
cond_exposed_terms.append(ref_enabled(entry.feature))
if entry.feature.is_origin_trial:
feature_selector_names.append(entry.feature)
assert (not exposure.global_names_and_features
or matched_global_count > 0)
else:
for entry in exposure.global_names_and_features:
if entry.global_name == "*":
# [Exposed(GLOBAL_NAME FEATURE_NAME)] is not supported.
assert entry.feature is None
# Constructs with the wildcard exposure ([Exposed=*]) are
# unconditionally exposed.
continue
try:
execution_context_check = GLOBAL_NAME_TO_EXECUTION_CONTEXT_TEST[
entry.global_name]
except KeyError:
# We don't currently have a general way of checking the exposure
# of [TargetOfExposed] exposure. If this is actually a global,
# add it to GLOBAL_NAME_TO_EXECUTION_CONTEXT_CHECK.
# TODO(pbos): Migrate this to use NOTREACHED() directly, or even
# better don't generate code that shouldn't be reachable at all.
return _Expr(
"(::logging::NotReachedError::NotReached("
"base::NotFatalUntil::NoSpecifiedMilestoneInternal) << "
"\"{} exposure test is not supported at runtime\", false)".
format(entry.global_name))
pred_term = _Expr(
"${{execution_context}}->{}()".format(execution_context_check))
if not entry.feature:
uncond_exposed_terms.append(pred_term)
else:
cond_exposed_terms.append(
expr_and([pred_term, ref_enabled(entry.feature)]))
if entry.feature.is_origin_trial:
exposed_selector_terms.append(
expr_and([pred_term,
ref_selected([entry.feature])]))
# [RuntimeEnabled]
if exposure.runtime_enabled_features:
feature_enabled_terms.extend(
map(ref_enabled, exposure.runtime_enabled_features))
if exposure.origin_trial_features:
feature_selector_names.extend(exposure.origin_trial_features)
# [ContextEnabled]
if exposure.context_enabled_features:
terms = list(
map(
lambda feature: _Expr(
"${{context_feature_settings}}->is{}Enabled()".format(
feature)), exposure.context_enabled_features))
context_enabled_terms.append(
expr_and([_Expr("${context_feature_settings}"),
expr_or(terms)]))
# Build an expression.
top_level_terms = []
top_level_terms.append(cross_origin_isolated_term)
top_level_terms.append(injection_mitigated_context_term)
top_level_terms.append(isolated_context_term)
top_level_terms.append(secure_context_term)
if uncond_exposed_terms:
top_level_terms.append(expr_or(uncond_exposed_terms))
if not (may_use_feature_selector
and exposure.is_context_dependent(global_names)):
if cond_exposed_terms:
top_level_terms.append(expr_or(cond_exposed_terms))
if feature_enabled_terms:
top_level_terms.append(expr_and(feature_enabled_terms))
if context_enabled_terms:
top_level_terms.append(expr_or(context_enabled_terms))
return expr_and(top_level_terms)
all_enabled_terms = [_Expr("${feature_selector}.IsAll()")]
if cond_exposed_terms:
all_enabled_terms.append(expr_or(cond_exposed_terms))
if feature_enabled_terms or context_enabled_terms:
terms = []
if feature_enabled_terms:
terms.append(expr_and(feature_enabled_terms))
if context_enabled_terms:
terms.append(expr_or(context_enabled_terms))
all_enabled_terms.append(expr_or(terms))
selector_terms = []
if exposed_selector_terms:
selector_terms.append(expr_or(exposed_selector_terms))
if feature_selector_names:
# Remove duplicates
selector_terms.append(ref_selected(sorted(
set(feature_selector_names))))
terms = []
terms.append(expr_and(all_enabled_terms))
if selector_terms:
terms.append(expr_or(selector_terms))
top_level_terms.append(expr_or(terms))
return expr_and(top_level_terms)
|