Test262Test.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text.RegularExpressions;
  8. using Esprima;
  9. using Esprima.Ast;
  10. using Jint.Native;
  11. using Jint.Native.ArrayBuffer;
  12. using Jint.Runtime;
  13. using Jint.Runtime.Descriptors;
  14. using Jint.Runtime.Interop;
  15. using Newtonsoft.Json.Linq;
  16. using Xunit.Abstractions;
  17. using Xunit.Sdk;
  18. namespace Jint.Tests.Test262
  19. {
  20. public abstract class Test262Test
  21. {
  22. private static readonly Dictionary<string, Script> Sources;
  23. private static readonly string BasePath;
  24. private static readonly TimeZoneInfo _pacificTimeZone;
  25. private static readonly Dictionary<string, string> _skipReasons = new(StringComparer.OrdinalIgnoreCase);
  26. private static readonly HashSet<string> _strictSkips = new(StringComparer.OrdinalIgnoreCase);
  27. static Test262Test()
  28. {
  29. //NOTE: The Date tests in test262 assume the local timezone is Pacific Standard Time
  30. try
  31. {
  32. _pacificTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
  33. }
  34. catch (TimeZoneNotFoundException)
  35. {
  36. // https://stackoverflow.com/questions/47848111/how-should-i-fetch-timezoneinfo-in-a-platform-agnostic-way
  37. // should be natively supported soon https://github.com/dotnet/runtime/issues/18644
  38. _pacificTimeZone = TimeZoneInfo.FindSystemTimeZoneById("America/Los_Angeles");
  39. }
  40. var assemblyPath = new Uri(typeof(Test262Test).GetTypeInfo().Assembly.Location).LocalPath;
  41. var assemblyDirectory = new FileInfo(assemblyPath).Directory;
  42. BasePath = assemblyDirectory.Parent.Parent.Parent.FullName;
  43. string[] files =
  44. {
  45. "sta.js",
  46. "assert.js",
  47. "arrayContains.js",
  48. "isConstructor.js",
  49. "promiseHelper.js",
  50. "propertyHelper.js",
  51. "compareArray.js",
  52. "decimalToHexString.js",
  53. "deepEqual.js",
  54. "proxyTrapsHelper.js",
  55. "dateConstants.js",
  56. "assertRelativeDateMs.js",
  57. "regExpUtils.js",
  58. "nans.js",
  59. "compareIterator.js",
  60. "nativeFunctionMatcher.js",
  61. "wellKnownIntrinsicObjects.js",
  62. "fnGlobalObject.js",
  63. "testTypedArray.js",
  64. "detachArrayBuffer.js",
  65. "byteConversionValues.js",
  66. "hidden-constructors.js",
  67. "testBigIntTypedArray.js"
  68. };
  69. Sources = new Dictionary<string, Script>(files.Length);
  70. for (var i = 0; i < files.Length; i++)
  71. {
  72. var source = File.ReadAllText(Path.Combine(BasePath, "harness", files[i]));
  73. Sources[files[i]] = new JavaScriptParser(source, new ParserOptions(files[i])).ParseScript();
  74. }
  75. var content = File.ReadAllText(Path.Combine(BasePath, "test/skipped.json"));
  76. var doc = JArray.Parse(content);
  77. foreach (var entry in doc.Values<JObject>())
  78. {
  79. var source = entry["source"].Value<string>();
  80. _skipReasons[source] = entry["reason"].Value<string>();
  81. if (entry.TryGetValue("mode", out var mode) && mode.Value<string>() == "strict")
  82. {
  83. _strictSkips.Add(source);
  84. }
  85. }
  86. }
  87. protected void RunTestCode(string fileName, string code, bool strict)
  88. {
  89. var engine = new Engine(cfg => cfg
  90. .LocalTimeZone(_pacificTimeZone)
  91. .Strict(strict)
  92. );
  93. engine.Execute(Sources["sta.js"]);
  94. engine.Execute(Sources["assert.js"]);
  95. engine.SetValue("print",
  96. new ClrFunctionInstance(engine, "print", (thisObj, args) => TypeConverter.ToString(args.At(0))));
  97. var o = engine.Realm.Intrinsics.Object.Construct(Arguments.Empty);
  98. o.FastSetProperty("evalScript", new PropertyDescriptor(new ClrFunctionInstance(engine, "evalScript",
  99. (thisObj, args) =>
  100. {
  101. if (args.Length > 1)
  102. {
  103. throw new Exception("only script parsing supported");
  104. }
  105. var options = new ParserOptions {AdaptRegexp = true, Tolerant = false};
  106. var parser = new JavaScriptParser(args.At(0).AsString(), options);
  107. var script = parser.ParseScript(strict);
  108. return engine.Evaluate(script);
  109. }), true, true, true));
  110. o.FastSetProperty("createRealm", new PropertyDescriptor(new ClrFunctionInstance(engine, "createRealm",
  111. (thisObj, args) =>
  112. {
  113. var realm = engine._host.CreateRealm();
  114. realm.GlobalObject.Set("global", realm.GlobalObject);
  115. return realm.GlobalObject;
  116. }), true, true, true));
  117. o.FastSetProperty("detachArrayBuffer", new PropertyDescriptor(new ClrFunctionInstance(engine, "detachArrayBuffer",
  118. (thisObj, args) =>
  119. {
  120. var buffer = (ArrayBufferInstance) args.At(0);
  121. buffer.DetachArrayBuffer();
  122. return JsValue.Undefined;
  123. }), true, true, true));
  124. engine.SetValue("$262", o);
  125. var includes = Regex.Match(code, @"includes: \[(.+?)\]");
  126. if (includes.Success)
  127. {
  128. var files = includes.Groups[1].Captures[0].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
  129. foreach (var file in files)
  130. {
  131. engine.Execute(Sources[file.Trim()]);
  132. }
  133. }
  134. if (code.IndexOf("propertyHelper.js", StringComparison.OrdinalIgnoreCase) != -1)
  135. {
  136. engine.Execute(Sources["propertyHelper.js"]);
  137. }
  138. string lastError = null;
  139. bool negative = code.IndexOf("negative:", StringComparison.Ordinal) > -1;
  140. try
  141. {
  142. engine.Execute(new JavaScriptParser(code, new ParserOptions(fileName)).ParseScript());
  143. }
  144. catch (JavaScriptException j)
  145. {
  146. lastError = j.ToString();
  147. }
  148. catch (Exception e)
  149. {
  150. lastError = e.ToString();
  151. }
  152. if (!negative && !string.IsNullOrWhiteSpace(lastError))
  153. {
  154. throw new XunitException($"{Environment.NewLine}{fileName}{Environment.NewLine}{Environment.NewLine}{lastError}");
  155. }
  156. }
  157. protected void RunTestInternal(SourceFile sourceFile)
  158. {
  159. if (sourceFile.Skip)
  160. {
  161. return;
  162. }
  163. if (sourceFile.Code.IndexOf("onlyStrict", StringComparison.Ordinal) < 0)
  164. {
  165. RunTestCode(sourceFile.Source, sourceFile.Code, strict: false);
  166. }
  167. if (!_strictSkips.Contains(sourceFile.Source)
  168. && sourceFile.Code.IndexOf("noStrict", StringComparison.Ordinal) < 0)
  169. {
  170. RunTestCode(sourceFile.Source, sourceFile.Code, strict: true);
  171. }
  172. }
  173. public static IEnumerable<object[]> SourceFiles(string pathPrefix, bool skipped)
  174. {
  175. var results = new ConcurrentBag<object[]>();
  176. var fixturesPath = Path.Combine(BasePath, "test");
  177. var segments = pathPrefix.Split('\\');
  178. var searchPath = Path.Combine(fixturesPath, Path.Combine(segments));
  179. var files = Directory.GetFiles(searchPath, "*", SearchOption.AllDirectories);
  180. foreach (var file in files)
  181. {
  182. if (file.IndexOf("_FIXTURE", StringComparison.OrdinalIgnoreCase) != -1)
  183. {
  184. // Files bearing a name which includes the sequence _FIXTURE MUST NOT be interpreted
  185. // as standalone tests; they are intended to be referenced by test files.
  186. continue;
  187. }
  188. var name = file.Substring(fixturesPath.Length + 1).Replace("\\", "/");
  189. bool skip = _skipReasons.TryGetValue(name, out var reason);
  190. var code = skip ? "" : File.ReadAllText(file);
  191. var flags = Regex.Match(code, "flags: \\[(.+?)\\]");
  192. if (flags.Success)
  193. {
  194. var items = flags.Groups[1].Captures[0].Value.Split(',');
  195. foreach (var item in items.Select(x => x.Trim()))
  196. {
  197. switch (item)
  198. {
  199. // TODO implement
  200. case "async":
  201. skip = true;
  202. reason = "async not implemented";
  203. break;
  204. }
  205. }
  206. }
  207. var features = Regex.Match(code, "features: \\[(.+?)\\]");
  208. if (features.Success)
  209. {
  210. var items = features.Groups[1].Captures[0].Value.Split(',');
  211. foreach (var item in items.Select(x => x.Trim()))
  212. {
  213. switch (item)
  214. {
  215. // TODO implement
  216. case "tail-call-optimization":
  217. skip = true;
  218. reason = "tail-calls not implemented";
  219. break;
  220. case "generators":
  221. skip = true;
  222. reason = "generators not implemented";
  223. break;
  224. case "async-functions":
  225. skip = true;
  226. reason = "async-functions not implemented";
  227. break;
  228. case "async-iteration":
  229. skip = true;
  230. reason = "async not implemented";
  231. break;
  232. case "class-fields-private":
  233. case "class-fields-public":
  234. skip = true;
  235. reason = "private/public class fields not implemented in esprima";
  236. break;
  237. case "String.prototype.replaceAll":
  238. skip = true;
  239. reason = "not in spec yet";
  240. break;
  241. case "u180e":
  242. skip = true;
  243. reason = "unicode/regexp not implemented";
  244. break;
  245. case "regexp-match-indices":
  246. skip = true;
  247. reason = "regexp-match-indices not implemented";
  248. break;
  249. case "regexp-named-groups":
  250. skip = true;
  251. reason = "regexp-named-groups not implemented";
  252. break;
  253. case "regexp-lookbehind":
  254. skip = true;
  255. reason = "regexp-lookbehind not implemented";
  256. break;
  257. case "SharedArrayBuffer":
  258. skip = true;
  259. reason = "SharedArrayBuffer not implemented";
  260. break;
  261. case "resizable-arraybuffer":
  262. skip = true;
  263. reason = "resizable-arraybuffer not implemented";
  264. break;
  265. case "json-modules":
  266. skip = true;
  267. reason = "json-modules not implemented";
  268. break;
  269. case "top-level-await":
  270. skip = true;
  271. reason = "top-level-await not implemented";
  272. break;
  273. case "import-assertions":
  274. skip = true;
  275. reason = "import-assertions not implemented";
  276. break;
  277. }
  278. }
  279. }
  280. if (code.IndexOf("SpecialCasing.txt") > -1)
  281. {
  282. skip = true;
  283. reason = "SpecialCasing.txt not implemented";
  284. }
  285. if (name.StartsWith("language/expressions/object/dstr-async-gen-meth-"))
  286. {
  287. skip = true;
  288. reason = "Esprima problem, Unexpected token *";
  289. }
  290. if (name.StartsWith("built-ins/RegExp/property-escapes/generated/"))
  291. {
  292. skip = true;
  293. reason = "Esprima problem, Invalid regular expression";
  294. }
  295. if (name.StartsWith("built-ins/RegExp/unicode_"))
  296. {
  297. skip = true;
  298. reason = "Unicode support and its special cases need more work";
  299. }
  300. // Promises
  301. if (name.StartsWith("built-ins/Promise/allSettled") ||
  302. name.StartsWith("built-ins/Promise/any"))
  303. {
  304. skip = true;
  305. reason = "Promise.any and Promise.allSettled are not implemented yet";
  306. }
  307. if (file.EndsWith("tv-line-continuation.js")
  308. || file.EndsWith("tv-line-terminator-sequence.js")
  309. || file.EndsWith("special-characters.js"))
  310. {
  311. // LF endings required
  312. code = code.Replace("\r\n", "\n");
  313. }
  314. var sourceFile = new SourceFile(
  315. name,
  316. file,
  317. skip,
  318. reason,
  319. code);
  320. if (skipped == sourceFile.Skip)
  321. {
  322. results.Add(new object[]
  323. {
  324. sourceFile
  325. });
  326. }
  327. }
  328. return results;
  329. }
  330. private static ParserOptions CreateParserOptions(string fileName) =>
  331. new ParserOptions(fileName)
  332. {
  333. AdaptRegexp = true,
  334. Tolerant = true
  335. };
  336. }
  337. public class SourceFile : IXunitSerializable
  338. {
  339. public SourceFile()
  340. {
  341. }
  342. public SourceFile(
  343. string source,
  344. string fullPath,
  345. bool skip,
  346. string reason,
  347. string code)
  348. {
  349. Skip = skip;
  350. Source = source;
  351. Reason = reason;
  352. FullPath = fullPath;
  353. Code = code;
  354. }
  355. public string Source { get; set; }
  356. public bool Skip { get; set; }
  357. public string Reason { get; set; }
  358. public string FullPath { get; set; }
  359. public string Code { get; set; }
  360. public void Deserialize(IXunitSerializationInfo info)
  361. {
  362. Skip = info.GetValue<bool>(nameof(Skip));
  363. Source = info.GetValue<string>(nameof(Source));
  364. Reason = info.GetValue<string>(nameof(Reason));
  365. FullPath = info.GetValue<string>(nameof(FullPath));
  366. Code = info.GetValue<string>(nameof(Code));
  367. }
  368. public void Serialize(IXunitSerializationInfo info)
  369. {
  370. info.AddValue(nameof(Skip), Skip);
  371. info.AddValue(nameof(Source), Source);
  372. info.AddValue(nameof(Reason), Reason);
  373. info.AddValue(nameof(FullPath), FullPath);
  374. info.AddValue(nameof(Code), Code);
  375. }
  376. public override string ToString()
  377. {
  378. return Source;
  379. }
  380. }
  381. }