| 1 |
#!/usr/bin/env python3 |
| 2 |
# |
| 3 |
# This Source Code Form is subject to the terms of the Mozilla Public |
| 4 |
# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 |
# file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 6 |
|
| 7 |
import math |
| 8 |
import os |
| 9 |
import re |
| 10 |
import shutil |
| 11 |
import sys |
| 12 |
import traceback |
| 13 |
from datetime import date |
| 14 |
from typing import Any, Optional |
| 15 |
|
| 16 |
import yaml |
| 17 |
|
| 18 |
# Skip all common files used to support tests for jstests |
| 19 |
# These files are listed in the README.txt |
| 20 |
SUPPORT_FILES = set( |
| 21 |
[ |
| 22 |
"browser.js", |
| 23 |
"shell.js", |
| 24 |
"template.js", |
| 25 |
"user.js", |
| 26 |
"js-test-driver-begin.js", |
| 27 |
"js-test-driver-end.js", |
| 28 |
] |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
# Run once per subdirectory |
| 33 |
def findAndCopyIncludes(dirPath: str, baseDir: str, includeDir: str) -> "list[str]": |
| 34 |
relPath = os.path.relpath(dirPath, baseDir) |
| 35 |
includes: list[str] = ["sm/non262.js"] |
| 36 |
os.makedirs(os.path.join(includeDir, "sm"), exist_ok=True) |
| 37 |
|
| 38 |
# Recurse down all folders in the relative path until |
| 39 |
# we reach the base directory of shell.js include files. |
| 40 |
# Each directory will have a shell.js file to copy. |
| 41 |
while relPath: |
| 42 |
# find the shell.js |
| 43 |
shellFile = os.path.join(baseDir, relPath, "shell.js") |
| 44 |
|
| 45 |
# if the file isn't excluded, exists, and is not empty, include in includes |
| 46 |
if ( |
| 47 |
not any(relPath == f"non262/{path}" for path in UNSUPPORTED_PATHS) |
| 48 |
and os.path.exists(shellFile) |
| 49 |
and os.path.getsize(shellFile) > 0 |
| 50 |
): |
| 51 |
with open(shellFile, "rb") as f: |
| 52 |
testSource = f.read() |
| 53 |
|
| 54 |
if b"// SKIP test262 export" not in testSource: |
| 55 |
# create new shell.js file name |
| 56 |
includeFileName = "sm/" + relPath.replace("/", "-") + "-shell.js" |
| 57 |
includes.append(includeFileName) |
| 58 |
|
| 59 |
includesPath = os.path.join(includeDir, includeFileName) |
| 60 |
shutil.copyfile(shellFile, includesPath) |
| 61 |
|
| 62 |
relPath = os.path.split(relPath)[0] |
| 63 |
|
| 64 |
return includes |
| 65 |
|
| 66 |
|
| 67 |
UNSUPPORTED_CODE: "list[bytes]" = [ |
| 68 |
b"// SKIP test262 export", |
| 69 |
b"inTimeZone(", |
| 70 |
b"getTimeZone(", |
| 71 |
b"setTimeZone(", |
| 72 |
b"getAvailableLocalesOf(", |
| 73 |
b"uneval(", |
| 74 |
b"Debugger", |
| 75 |
b"SpecialPowers", |
| 76 |
b"evalcx(", |
| 77 |
b"evaluate(", |
| 78 |
b"drainJobQueue(", |
| 79 |
b"getPromiseResult(", |
| 80 |
b"assertEventuallyEq(", |
| 81 |
b"assertEventuallyThrows(", |
| 82 |
b"settlePromiseNow(", |
| 83 |
b"setPromiseRejectionTrackerCallback", |
| 84 |
b"displayName(", |
| 85 |
b"InternalError", |
| 86 |
b"toSource(", |
| 87 |
b"toSource.call(", |
| 88 |
b"isRope(", |
| 89 |
b"isSameCompartment(", |
| 90 |
b"isCCW", |
| 91 |
b"nukeCCW", |
| 92 |
b"representativeStringArray(", |
| 93 |
b"largeArrayBufferSupported(", |
| 94 |
b"helperThreadCount(", |
| 95 |
b"serialize(", |
| 96 |
b"deserialize(", |
| 97 |
b"clone_object_check", |
| 98 |
b"grayRoot(", |
| 99 |
b"blackRoot(", |
| 100 |
b"gczeal", |
| 101 |
b"getSelfHostedValue(", |
| 102 |
b"oomTest(", |
| 103 |
b"assertLineAndColumn(", |
| 104 |
b"wrapWithProto(", |
| 105 |
b"Reflect.parse(", |
| 106 |
b"relazifyFunctions(", |
| 107 |
b"ignoreUnhandledRejections", |
| 108 |
b".lineNumber", |
| 109 |
b"expectExitCode", |
| 110 |
b"loadRelativeToScript", |
| 111 |
b"XorShiftGenerator", |
| 112 |
] |
| 113 |
|
| 114 |
|
| 115 |
def skipTest(source: bytes) -> Optional[bytes]: |
| 116 |
if b"This Source Code Form is subject to the terms of the Mozilla Public" in source: |
| 117 |
return b"MPL license" |
| 118 |
for c in UNSUPPORTED_CODE: |
| 119 |
if c in source: |
| 120 |
return c |
| 121 |
|
| 122 |
return None |
| 123 |
|
| 124 |
|
| 125 |
MODELINE_PATTERN = re.compile(rb"/(/|\*) -\*- .* -\*-( \*/)?[\r\n]+") |
| 126 |
|
| 127 |
UNSUPPORTED_FEATURES = [ |
| 128 |
"async-iterator-helpers", |
| 129 |
"Iterator.range", |
| 130 |
] |
| 131 |
|
| 132 |
UNSUPPORTED_PATHS = [ |
| 133 |
"Intl", |
| 134 |
"Temporal/Intl", |
| 135 |
"reflect-parse", |
| 136 |
"extensions/empty.txt", |
| 137 |
"extensions/file-mapped-arraybuffers.txt", |
| 138 |
"module/bug1693261-async.mjs", |
| 139 |
"module/bug1693261-c1.mjs", |
| 140 |
"module/bug1693261-c2.mjs", |
| 141 |
"module/bug1693261-x.mjs", |
| 142 |
] |
| 143 |
|
| 144 |
|
| 145 |
def convertTestFile(source: bytes, includes: "list[str]") -> Optional[bytes]: |
| 146 |
""" |
| 147 |
Convert a jstest test to a compatible Test262 test file. |
| 148 |
""" |
| 149 |
|
| 150 |
source = MODELINE_PATTERN.sub(b"", source) |
| 151 |
|
| 152 |
# Extract the reftest data from the source |
| 153 |
source, reftest = parseHeader(source) |
| 154 |
|
| 155 |
# Add copyright, if needed. |
| 156 |
copyright, source = insertCopyrightLines(source) |
| 157 |
|
| 158 |
# Extract the frontmatter data from the source |
| 159 |
frontmatter, source = extractMeta(source) |
| 160 |
|
| 161 |
source, addincludes = translateHelpers(source) |
| 162 |
includes = includes + addincludes |
| 163 |
|
| 164 |
meta = computeMeta(source, reftest, frontmatter, includes) |
| 165 |
|
| 166 |
if "features" in meta and any(f in UNSUPPORTED_FEATURES for f in meta["features"]): |
| 167 |
return None |
| 168 |
|
| 169 |
source = insertMeta(source, meta) |
| 170 |
|
| 171 |
source = convertReportCompare(source) |
| 172 |
|
| 173 |
return copyright + source |
| 174 |
|
| 175 |
|
| 176 |
## parseHeader |
| 177 |
|
| 178 |
|
| 179 |
class ReftestEntry: |
| 180 |
def __init__( |
| 181 |
self, |
| 182 |
features: "list[str]", |
| 183 |
error: Optional[str], |
| 184 |
module: bool, |
| 185 |
info: Optional[str], |
| 186 |
): |
| 187 |
self.features: list[str] = features |
| 188 |
self.error: Optional[str] = error |
| 189 |
self.module: bool = module |
| 190 |
self.info: Optional[str] = info |
| 191 |
|
| 192 |
|
| 193 |
def featureFromReftest(reftest: str) -> Optional[str]: |
| 194 |
if reftest == "Iterator": |
| 195 |
return "iterator-helpers" |
| 196 |
if reftest == "AsyncIterator": |
| 197 |
return "async-iterator-helpers" |
| 198 |
if reftest == "Temporal": |
| 199 |
return "Temporal" |
| 200 |
if reftest in ("Intl", "addIntlExtras"): |
| 201 |
return None |
| 202 |
raise Exception(f"Unexpected feature {reftest}") |
| 203 |
|
| 204 |
|
| 205 |
def fetchReftestEntries(reftest: str) -> ReftestEntry: |
| 206 |
""" |
| 207 |
Collects and stores the entries from the reftest header. |
| 208 |
""" |
| 209 |
|
| 210 |
# TODO: fails, slow, skip, random, random-if |
| 211 |
|
| 212 |
features: list[str] = [] |
| 213 |
error: Optional[str] = None |
| 214 |
comments: Optional[str] = None |
| 215 |
module: bool = False |
| 216 |
|
| 217 |
# should capture conditions to skip |
| 218 |
matchesSkip = re.search(r"skip-if\((.*)\)", reftest) |
| 219 |
if matchesSkip: |
| 220 |
matches = matchesSkip.group(1).split("||") |
| 221 |
for match in matches: |
| 222 |
# captures a features list |
| 223 |
dependsOnProp = re.search( |
| 224 |
r"!this.hasOwnProperty\([\'\"](.*?)[\'\"]\)", match |
| 225 |
) |
| 226 |
if dependsOnProp: |
| 227 |
if feature := featureFromReftest(dependsOnProp.group(1)): |
| 228 |
features.append(feature) |
| 229 |
else: |
| 230 |
print("# Can't parse the following skip-if rule: %s" % match) |
| 231 |
|
| 232 |
# should capture the expected error |
| 233 |
matchesError = re.search(r"error:\s*(\w*)", reftest) |
| 234 |
if matchesError: |
| 235 |
# The metadata from the reftests won't say if it's a runtime or an |
| 236 |
# early error. This specification is required for the frontmatter tags. |
| 237 |
error = matchesError.group(1) |
| 238 |
|
| 239 |
# just tells if it's a module |
| 240 |
matchesModule = re.search(r"\bmodule\b", reftest) |
| 241 |
if matchesModule: |
| 242 |
module = True |
| 243 |
|
| 244 |
# captures any comments |
| 245 |
matchesComments = re.search(r" -- (.*)", reftest) |
| 246 |
if matchesComments: |
| 247 |
comments = matchesComments.group(1) |
| 248 |
|
| 249 |
return ReftestEntry(features=features, error=error, module=module, info=comments) |
| 250 |
|
| 251 |
|
| 252 |
def parseHeader(source: bytes) -> "tuple[bytes, Optional[ReftestEntry]]": |
| 253 |
""" |
| 254 |
Parse the source to return it with the extracted the header |
| 255 |
""" |
| 256 |
from lib.manifest import TEST_HEADER_PATTERN_INLINE |
| 257 |
|
| 258 |
# Bail early if we do not start with a single comment. |
| 259 |
if not source.startswith(b"//"): |
| 260 |
return (source, None) |
| 261 |
|
| 262 |
# Extract the token. |
| 263 |
part, _, rest = source.partition(b"\n") |
| 264 |
part = part.decode("utf-8") |
| 265 |
matches = TEST_HEADER_PATTERN_INLINE.match(part) |
| 266 |
|
| 267 |
if matches and matches.group(0): |
| 268 |
reftest = matches.group(0) |
| 269 |
|
| 270 |
# Remove the found header from the source; |
| 271 |
# Fetch and return the reftest entries |
| 272 |
return (rest, fetchReftestEntries(reftest)) |
| 273 |
|
| 274 |
return (source, None) |
| 275 |
|
| 276 |
|
| 277 |
## insertCopyrightLines |
| 278 |
|
| 279 |
|
| 280 |
LICENSE_PATTERN = re.compile( |
| 281 |
rb"// Copyright( \([C]\))? (\w+) .+\. {1,2}All rights reserved\.[\r\n]{1,2}" |
| 282 |
+ rb"(" |
| 283 |
+ rb"// This code is governed by the( BSD)? license found in the LICENSE file\." |
| 284 |
+ rb"|" |
| 285 |
+ rb"// See LICENSE for details." |
| 286 |
+ rb"|" |
| 287 |
+ rb"// Use of this source code is governed by a BSD-style license that can be[\r\n]{1,2}" |
| 288 |
+ rb"// found in the LICENSE file\." |
| 289 |
+ rb"|" |
| 290 |
+ rb"// See LICENSE or https://github\.com/tc39/test262/blob/HEAD/LICENSE" |
| 291 |
+ rb")[\r\n]{1,2}", |
| 292 |
re.IGNORECASE, |
| 293 |
) |
| 294 |
|
| 295 |
PD_PATTERN1 = re.compile( |
| 296 |
rb"/\*[\r\n]{1,2}" |
| 297 |
+ rb" \* Any copyright is dedicated to the Public Domain\.[\r\n]{1,2}" |
| 298 |
+ rb" \* (http://creativecommons\.org/licenses/publicdomain/|https://creativecommons\.org/publicdomain/zero/1\.0/)[\r\n]{1,2}" |
| 299 |
+ rb"( \* Contributors?:" |
| 300 |
+ rb"(( [^\r\n]*[\r\n]{1,2})|" |
| 301 |
+ rb"([\r\n]{1,2}( \* [^\r\n]*[\r\n]{1,2})+)))?" |
| 302 |
+ rb" \*/[\r\n]{1,2}", |
| 303 |
re.IGNORECASE, |
| 304 |
) |
| 305 |
|
| 306 |
PD_PATTERN2 = re.compile( |
| 307 |
rb"// Any copyright is dedicated to the Public Domain\.[\r\n]{1,2}" |
| 308 |
+ rb"// (http://creativecommons\.org/licenses/publicdomain/|https://creativecommons\.org/publicdomain/zero/1\.0/)[\r\n]{1,2}" |
| 309 |
+ rb"(// Contributors?: [^\r\n]*[\r\n]{1,2})?", |
| 310 |
re.IGNORECASE, |
| 311 |
) |
| 312 |
|
| 313 |
PD_PATTERN3 = re.compile( |
| 314 |
rb"/\* Any copyright is dedicated to the Public Domain\.[\r\n]{1,2}" |
| 315 |
+ rb" \* (http://creativecommons\.org/licenses/publicdomain/|https://creativecommons\.org/publicdomain/zero/1\.0/) \*/[\r\n]{1,2}", |
| 316 |
re.IGNORECASE, |
| 317 |
) |
| 318 |
|
| 319 |
|
| 320 |
BSD_TEMPLATE = ( |
| 321 |
b"""\ |
| 322 |
// Copyright (C) %d Mozilla Corporation. All rights reserved. |
| 323 |
// This code is governed by the BSD license found in the LICENSE file. |
| 324 |
|
| 325 |
""" |
| 326 |
% date.today().year |
| 327 |
) |
| 328 |
|
| 329 |
PD_TEMPLATE = b"""\ |
| 330 |
/* |
| 331 |
* Any copyright is dedicated to the Public Domain. |
| 332 |
* http://creativecommons.org/licenses/publicdomain/ |
| 333 |
*/ |
| 334 |
|
| 335 |
""" |
| 336 |
|
| 337 |
|
| 338 |
def insertCopyrightLines(source: bytes) -> "tuple[bytes, bytes]": |
| 339 |
""" |
| 340 |
Insert the copyright lines into the file. |
| 341 |
""" |
| 342 |
if match := LICENSE_PATTERN.search(source): |
| 343 |
start, end = match.span() |
| 344 |
return source[start:end], source[:start] + source[end:] |
| 345 |
|
| 346 |
if ( |
| 347 |
match := PD_PATTERN1.search(source) |
| 348 |
or PD_PATTERN2.search(source) |
| 349 |
or PD_PATTERN3.search(source) |
| 350 |
): |
| 351 |
start, end = match.span() |
| 352 |
return PD_TEMPLATE, source[:start] + source[end:] |
| 353 |
|
| 354 |
return BSD_TEMPLATE, source |
| 355 |
|
| 356 |
|
| 357 |
## extractMeta |
| 358 |
|
| 359 |
FRONTMATTER_WRAPPER_PATTERN = re.compile( |
| 360 |
rb"/\*\---\n([\s]*)((?:\s|\S)*)[\n\s*]---\*/[\r\n]{1,2}", flags=re.DOTALL |
| 361 |
) |
| 362 |
|
| 363 |
|
| 364 |
def extractMeta(source: bytes) -> "tuple[dict[str, Any], bytes]": |
| 365 |
""" |
| 366 |
Capture the frontmatter metadata as yaml if it exists. |
| 367 |
Returns a new dict if it doesn't. |
| 368 |
""" |
| 369 |
|
| 370 |
match = FRONTMATTER_WRAPPER_PATTERN.search(source) |
| 371 |
if not match: |
| 372 |
return {}, source |
| 373 |
|
| 374 |
indent, frontmatter_lines = match.groups() |
| 375 |
|
| 376 |
unindented = re.sub(b"^%s" % indent, b"", frontmatter_lines) |
| 377 |
|
| 378 |
yamlresult = yaml.safe_load(unindented) |
| 379 |
if isinstance(yamlresult, str): |
| 380 |
result = {"info": yamlresult} |
| 381 |
else: |
| 382 |
result = yamlresult |
| 383 |
start, end = match.span() |
| 384 |
return result, source[:start] + source[end:] |
| 385 |
|
| 386 |
|
| 387 |
## computeMeta |
| 388 |
|
| 389 |
|
| 390 |
def translateHelpers(source: bytes) -> "tuple[bytes, list[str]]": |
| 391 |
""" |
| 392 |
Translate SpiderMonkey helper methods that have standard variants in test262. |
| 393 |
This also returns a list of includes that are needed to use these variants in test262, if any. |
| 394 |
""" |
| 395 |
|
| 396 |
includes: list[str] = [] |
| 397 |
source, n = re.subn(rb"\bassertDeepEq\b", b"assert.deepEqual", source) |
| 398 |
if n: |
| 399 |
includes.append("deepEqual.js") |
| 400 |
|
| 401 |
source, n = re.subn(rb"\bassertEqArray\b", b"assert.compareArray", source) |
| 402 |
if n: |
| 403 |
includes.append("compareArray.js") |
| 404 |
|
| 405 |
source = re.sub(rb"\bdetachArrayBuffer\b", b"$262.detachArrayBuffer", source) |
| 406 |
source = re.sub(rb"\bnewGlobal\b", b"createNewGlobal", source) |
| 407 |
source = re.sub(rb"\bassertEq\b", b"assert.sameValue", source) |
| 408 |
|
| 409 |
return (source, includes) |
| 410 |
|
| 411 |
|
| 412 |
def mergeMeta( |
| 413 |
reftest: "Optional[ReftestEntry]", |
| 414 |
frontmatter: "dict[str, Any]", |
| 415 |
includes: "list[str]", |
| 416 |
) -> "dict[str, Any]": |
| 417 |
""" |
| 418 |
Merge the metadata from reftest and an existing frontmatter and populate |
| 419 |
required frontmatter fields properly. |
| 420 |
""" |
| 421 |
|
| 422 |
# Merge the meta from reftest to the frontmatter |
| 423 |
|
| 424 |
# Add the shell specific includes |
| 425 |
if includes: |
| 426 |
frontmatter["includes"] = frontmatter.get("includes", []) + list(includes) |
| 427 |
|
| 428 |
flags: list[str] = frontmatter.get("flags", []) |
| 429 |
if "noStrict" not in flags and "onlyStrict" not in flags: |
| 430 |
frontmatter.setdefault("flags", []).append("noStrict") |
| 431 |
|
| 432 |
if not reftest: |
| 433 |
return frontmatter |
| 434 |
|
| 435 |
frontmatter.setdefault("features", []).extend(reftest.features) |
| 436 |
|
| 437 |
# Only add the module flag if the value from reftest is truish |
| 438 |
if reftest.module: |
| 439 |
frontmatter.setdefault("flags", []).append("module") |
| 440 |
if "noStrict" in frontmatter["flags"]: |
| 441 |
frontmatter["flags"].remove("noStrict") |
| 442 |
if "onlyStrict" in frontmatter["flags"]: |
| 443 |
frontmatter["flags"].remove("onlyStrict") |
| 444 |
|
| 445 |
# Add any comments to the info tag |
| 446 |
if reftest.info: |
| 447 |
info = reftest.info |
| 448 |
# Open some space in an existing info text |
| 449 |
if "info" in frontmatter and frontmatter["info"]: |
| 450 |
frontmatter["info"] += "\n\n%s" % info |
| 451 |
else: |
| 452 |
frontmatter["info"] = info |
| 453 |
|
| 454 |
# Set the negative flags |
| 455 |
if reftest.error: |
| 456 |
error = reftest.error |
| 457 |
if "negative" not in frontmatter: |
| 458 |
frontmatter["negative"] = { |
| 459 |
# This code is assuming error tags are parse errors, but they |
| 460 |
# might be runtime errors as well. |
| 461 |
# From this point, this code can also print a warning asking to |
| 462 |
# specify the error phase in the generated code or fill the |
| 463 |
# phase with an empty string. |
| 464 |
"phase": "parse", |
| 465 |
"type": error, |
| 466 |
} |
| 467 |
# Print a warning if the errors don't match |
| 468 |
elif frontmatter["negative"].get("type") != error: |
| 469 |
print( |
| 470 |
"Warning: The reftest error doesn't match the existing " |
| 471 |
+ "frontmatter error. %s != %s" |
| 472 |
% (error, frontmatter["negative"]["type"]) |
| 473 |
) |
| 474 |
|
| 475 |
return frontmatter |
| 476 |
|
| 477 |
|
| 478 |
def cleanupMeta(meta: "dict[str, Any]") -> "dict[str, Any]": |
| 479 |
""" |
| 480 |
Clean up all the frontmatter meta tags. This is not a lint tool, just a |
| 481 |
simple cleanup to remove trailing spaces and duplicate entries from lists. |
| 482 |
""" |
| 483 |
|
| 484 |
# Trim values on each string tag |
| 485 |
for tag in ("description", "esid", "es5id", "es6id", "info", "author"): |
| 486 |
if tag in meta: |
| 487 |
if not meta[tag]: |
| 488 |
del meta[tag] |
| 489 |
else: |
| 490 |
meta[tag] = meta[tag].strip() |
| 491 |
if not len(meta[tag]): |
| 492 |
del meta[tag] |
| 493 |
|
| 494 |
# Populate required tags |
| 495 |
for tag in ("description", "esid"): |
| 496 |
meta.setdefault(tag, "pending") |
| 497 |
|
| 498 |
# Remove duplicate entries on each list tag |
| 499 |
for tag in ("features", "flags", "includes"): |
| 500 |
if tag in meta: |
| 501 |
if not meta[tag]: |
| 502 |
del meta[tag] |
| 503 |
else: |
| 504 |
# We need the list back for the yaml dump |
| 505 |
meta[tag] = sorted(set(meta[tag]), reverse=tag == "includes") |
| 506 |
if not len(meta[tag]): |
| 507 |
del meta[tag] |
| 508 |
|
| 509 |
if "negative" in meta: |
| 510 |
# If the negative tag exists, phase needs to be present and set |
| 511 |
if meta["negative"].get("phase") not in ["parse", "resolution", "runtime"]: |
| 512 |
print( |
| 513 |
"Warning: the negative.phase is not properly set.\n" |
| 514 |
+ "Ref https://github.com/tc39/test262/blob/main/INTERPRETING.md#negative" |
| 515 |
) |
| 516 |
# If the negative tag exists, type is required |
| 517 |
if "type" not in meta["negative"]: |
| 518 |
print( |
| 519 |
"Warning: the negative.type is not set.\n" |
| 520 |
+ "Ref https://github.com/tc39/test262/blob/main/INTERPRETING.md#negative" |
| 521 |
) |
| 522 |
|
| 523 |
return meta |
| 524 |
|
| 525 |
|
| 526 |
def insertMeta(source: bytes, frontmatter: "dict[str, Any]") -> bytes: |
| 527 |
""" |
| 528 |
Insert the formatted frontmatter into the file, use the current existing |
| 529 |
space if any |
| 530 |
""" |
| 531 |
lines: list[bytes] = [] |
| 532 |
|
| 533 |
lines.append(b"/*---") |
| 534 |
|
| 535 |
for key, value in frontmatter.items(): |
| 536 |
if key in ("description", "info"): |
| 537 |
lines.append(b"%s: |" % key.encode("ascii")) |
| 538 |
lines.append( |
| 539 |
yaml.dump( |
| 540 |
value, |
| 541 |
encoding="utf8", |
| 542 |
default_style="|", |
| 543 |
default_flow_style=False, |
| 544 |
allow_unicode=True, |
| 545 |
) |
| 546 |
.strip() |
| 547 |
.replace(b"|-\n", b"") |
| 548 |
) |
| 549 |
elif key in ["flags", "includes", "features"]: |
| 550 |
lines.append( |
| 551 |
b"%s: " % key.encode("ascii") |
| 552 |
+ yaml.dump( |
| 553 |
value, encoding="utf8", default_flow_style=True, width=math.inf |
| 554 |
).strip() |
| 555 |
) |
| 556 |
else: |
| 557 |
lines.append( |
| 558 |
yaml.dump( |
| 559 |
{key: value}, encoding="utf8", default_flow_style=False |
| 560 |
).strip() |
| 561 |
) |
| 562 |
|
| 563 |
lines.append(b"---*/\n") |
| 564 |
source = b"\n".join(lines) + source |
| 565 |
|
| 566 |
if frontmatter.get("negative", {}).get("phase", "") == "parse": |
| 567 |
source += b"$DONOTEVALUATE();\n" |
| 568 |
|
| 569 |
return source |
| 570 |
|
| 571 |
|
| 572 |
def computeMeta( |
| 573 |
source: bytes, |
| 574 |
reftest: "Optional[ReftestEntry]", |
| 575 |
frontmatter: "dict[str, Any]", |
| 576 |
includes: "list[str]", |
| 577 |
) -> "dict[str, Any]": |
| 578 |
""" |
| 579 |
Captures the reftest meta and a pre-existing meta if any and merge them |
| 580 |
into a single dict. |
| 581 |
""" |
| 582 |
|
| 583 |
if source.startswith((b'"use strict"', b"'use strict'")): |
| 584 |
frontmatter.setdefault("flags", []).append("onlyStrict") |
| 585 |
|
| 586 |
if b"createIsHTMLDDA" in source: |
| 587 |
frontmatter.setdefault("features", []).append("IsHTMLDDA") |
| 588 |
|
| 589 |
# Merge the reftest and frontmatter |
| 590 |
merged = mergeMeta(reftest, frontmatter, includes) |
| 591 |
|
| 592 |
# Cleanup the metadata |
| 593 |
return cleanupMeta(merged) |
| 594 |
|
| 595 |
|
| 596 |
## convertReportCompare |
| 597 |
|
| 598 |
|
| 599 |
def convertReportCompare(source: bytes) -> bytes: |
| 600 |
""" |
| 601 |
Captures all the reportCompare and convert them accordingly. |
| 602 |
|
| 603 |
Cases with reportCompare calls where the arguments are the same and one of |
| 604 |
0, true, or null, will be discarded as they are not necessary for Test262. |
| 605 |
|
| 606 |
Otherwise, reportCompare will be replaced with assert.sameValue, as the |
| 607 |
equivalent in Test262 |
| 608 |
""" |
| 609 |
|
| 610 |
def replaceFn(matchobj: "re.Match[bytes]") -> bytes: |
| 611 |
actual: bytes = matchobj.group(4) |
| 612 |
expected: bytes = matchobj.group(5) |
| 613 |
|
| 614 |
if actual == expected and actual in [b"0", b"true", b"null"]: |
| 615 |
return b"" |
| 616 |
|
| 617 |
return matchobj.group() |
| 618 |
|
| 619 |
newSource = re.sub( |
| 620 |
rb".*(if \(typeof reportCompare ===? (\"|')function(\"|')\)\s*)?reportCompare\s*\(\s*(\w*)\s*,\s*(\w*)\s*(,\s*\S*)?\s*\)\s*;*\s*", |
| 621 |
replaceFn, |
| 622 |
source, |
| 623 |
) |
| 624 |
|
| 625 |
return re.sub(rb"\breportCompare\b", b"assert.sameValue", newSource) |
| 626 |
|
| 627 |
|
| 628 |
def exportTest262( |
| 629 |
outDir: str, providedSrcs: "list[str]", includeShell: bool, baseDir: str |
| 630 |
): |
| 631 |
# Create the output directory from scratch. |
| 632 |
print(f"Generating output in {os.path.abspath(outDir)}") |
| 633 |
if os.path.isdir(outDir): |
| 634 |
shutil.rmtree(outDir) |
| 635 |
|
| 636 |
# only make the includes directory if requested |
| 637 |
includeDir = os.path.join(outDir, "harness-includes") |
| 638 |
if includeShell: |
| 639 |
os.makedirs(includeDir) |
| 640 |
|
| 641 |
skipped = 0 |
| 642 |
skippedDirs = 0 |
| 643 |
|
| 644 |
# Go through each source path |
| 645 |
for providedSrc in providedSrcs: |
| 646 |
src = os.path.abspath(providedSrc) |
| 647 |
if not os.path.isdir(src): |
| 648 |
print(f"Did not find directory {src}") |
| 649 |
# the basename of the path will be used in case multiple "src" arguments |
| 650 |
# are passed in to create an output directory for each "src". |
| 651 |
basename = os.path.basename(src) |
| 652 |
|
| 653 |
# Process all test directories recursively. |
| 654 |
for dirPath, dirNames, fileNames in os.walk(src): |
| 655 |
# we need to make and get the unique set of includes for this filepath |
| 656 |
includes = [] |
| 657 |
if includeShell: |
| 658 |
includes = findAndCopyIncludes(dirPath, baseDir, includeDir) |
| 659 |
|
| 660 |
relPath = os.path.relpath(dirPath, src) |
| 661 |
fullRelPath = os.path.join(basename, relPath) |
| 662 |
|
| 663 |
if relPath in UNSUPPORTED_PATHS: |
| 664 |
print("SKIPPED unsupported path %s" % relPath) |
| 665 |
# Prevent recursing into subdirectories |
| 666 |
del dirNames[:] |
| 667 |
skippedDirs += 1 |
| 668 |
continue |
| 669 |
|
| 670 |
# Make new test subdirectory to seperate from includes |
| 671 |
currentOutDir = os.path.join(outDir, "tests", fullRelPath) |
| 672 |
|
| 673 |
# This also creates the own outDir folder |
| 674 |
if not os.path.exists(currentOutDir): |
| 675 |
os.makedirs(currentOutDir) |
| 676 |
|
| 677 |
for fileName in fileNames: |
| 678 |
# Skip browser.js files |
| 679 |
if fileName == "browser.js" or fileName == "shell.js": |
| 680 |
continue |
| 681 |
|
| 682 |
if fileName.endswith("~"): |
| 683 |
continue |
| 684 |
|
| 685 |
filePath = os.path.join(dirPath, fileName) |
| 686 |
testName = os.path.join( |
| 687 |
fullRelPath, fileName |
| 688 |
) # captures folder(s)+filename |
| 689 |
|
| 690 |
# This is hacky, but we're unlikely to add anything new |
| 691 |
# that needs to be skipped this way. |
| 692 |
if relPath + "/" + fileName in UNSUPPORTED_PATHS: |
| 693 |
print("SKIPPED %s" % testName) |
| 694 |
skipped += 1 |
| 695 |
continue |
| 696 |
|
| 697 |
# Copy non-test files as is. |
| 698 |
if "_FIXTURE" in fileName or os.path.splitext(fileName)[1] != ".js": |
| 699 |
shutil.copyfile(filePath, os.path.join(currentOutDir, fileName)) |
| 700 |
print("C %s" % testName) |
| 701 |
continue |
| 702 |
|
| 703 |
# Read the original test source and preprocess it for Test262 |
| 704 |
with open(filePath, "rb") as testFile: |
| 705 |
testSource = testFile.read() |
| 706 |
|
| 707 |
if not testSource: |
| 708 |
print("SKIPPED %s" % testName) |
| 709 |
skipped += 1 |
| 710 |
continue |
| 711 |
|
| 712 |
skip = skipTest(testSource) |
| 713 |
if skip is not None: |
| 714 |
print( |
| 715 |
f"SKIPPED {testName} because file contains {skip.decode('ascii')}" |
| 716 |
) |
| 717 |
skipped += 1 |
| 718 |
continue |
| 719 |
|
| 720 |
try: |
| 721 |
newSource = convertTestFile(testSource, includes) |
| 722 |
if newSource is None: |
| 723 |
print(f"SKIPPED {testName} due to disabled features") |
| 724 |
skipped += 1 |
| 725 |
continue |
| 726 |
except Exception as e: |
| 727 |
print(f"SKIPPED {testName} due to error {e}") |
| 728 |
traceback.print_exc(file=sys.stdout) |
| 729 |
skipped += 1 |
| 730 |
continue |
| 731 |
|
| 732 |
with open(os.path.join(currentOutDir, fileName), "wb") as output: |
| 733 |
output.write(newSource) |
| 734 |
|
| 735 |
print("SAVED %s" % testName) |
| 736 |
|
| 737 |
print(f"Skipped {skipped} tests and {skippedDirs} test directories") |
| 738 |
|
| 739 |
|
| 740 |
if __name__ == "__main__": |
| 741 |
import argparse |
| 742 |
|
| 743 |
# This script must be run from js/src/tests to work correctly. |
| 744 |
if "/".join(os.path.normpath(os.getcwd()).split(os.sep)[-3:]) != "js/src/tests": |
| 745 |
raise RuntimeError("%s must be run from js/src/tests" % sys.argv[0]) |
| 746 |
|
| 747 |
parser = argparse.ArgumentParser( |
| 748 |
description="Export tests to match Test262 file compliance." |
| 749 |
) |
| 750 |
parser.add_argument( |
| 751 |
"--out", |
| 752 |
default="test262/export", |
| 753 |
help="Output directory. Any existing directory will be removed! " |
| 754 |
"(default: %(default)s)", |
| 755 |
) |
| 756 |
parser.add_argument( |
| 757 |
"--exportshellincludes", |
| 758 |
action="store_true", |
| 759 |
help="Optionally export shell.js files as includes in exported tests. " |
| 760 |
"Only use for testing, do not use for exporting to test262 (test262 tests " |
| 761 |
"should have as few dependencies as possible).", |
| 762 |
) |
| 763 |
parser.add_argument( |
| 764 |
"src", nargs="+", help="Source folder with test files to export" |
| 765 |
) |
| 766 |
args = parser.parse_args() |
| 767 |
exportTest262( |
| 768 |
os.path.abspath(args.out), args.src, args.exportshellincludes, os.getcwd() |
| 769 |
) |