Test262Test.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. "proxyTrapsHelper.js",
  54. "dateConstants.js",
  55. "assertRelativeDateMs.js",
  56. "regExpUtils.js",
  57. "nans.js",
  58. "compareIterator.js",
  59. "nativeFunctionMatcher.js",
  60. "wellKnownIntrinsicObjects.js",
  61. "fnGlobalObject.js",
  62. "testTypedArray.js",
  63. "detachArrayBuffer.js",
  64. "byteConversionValues.js"
  65. };
  66. Sources = new Dictionary<string, Script>(files.Length);
  67. for (var i = 0; i < files.Length; i++)
  68. {
  69. var source = File.ReadAllText(Path.Combine(BasePath, "harness", files[i]));
  70. Sources[files[i]] = new JavaScriptParser(source, new ParserOptions(files[i])).ParseScript();
  71. }
  72. var content = File.ReadAllText(Path.Combine(BasePath, "test/skipped.json"));
  73. var doc = JArray.Parse(content);
  74. foreach (var entry in doc.Values<JObject>())
  75. {
  76. var source = entry["source"].Value<string>();
  77. _skipReasons[source] = entry["reason"].Value<string>();
  78. if (entry.TryGetValue("mode", out var mode) && mode.Value<string>() == "strict")
  79. {
  80. _strictSkips.Add(source);
  81. }
  82. }
  83. }
  84. protected void RunTestCode(string fileName, string code, bool strict)
  85. {
  86. var engine = new Engine(cfg => cfg
  87. .LocalTimeZone(_pacificTimeZone)
  88. .Strict(strict)
  89. );
  90. engine.Execute(Sources["sta.js"]);
  91. engine.Execute(Sources["assert.js"]);
  92. engine.SetValue("print",
  93. new ClrFunctionInstance(engine, "print", (thisObj, args) => TypeConverter.ToString(args.At(0))));
  94. var o = engine.Realm.Intrinsics.Object.Construct(Arguments.Empty);
  95. o.FastSetProperty("evalScript", new PropertyDescriptor(new ClrFunctionInstance(engine, "evalScript",
  96. (thisObj, args) =>
  97. {
  98. if (args.Length > 1)
  99. {
  100. throw new Exception("only script parsing supported");
  101. }
  102. var options = new ParserOptions {AdaptRegexp = true, Tolerant = false};
  103. var parser = new JavaScriptParser(args.At(0).AsString(), options);
  104. var script = parser.ParseScript(strict);
  105. return engine.Evaluate(script);
  106. }), true, true, true));
  107. o.FastSetProperty("createRealm", new PropertyDescriptor(new ClrFunctionInstance(engine, "createRealm",
  108. (thisObj, args) =>
  109. {
  110. var realm = engine._host.CreateRealm();
  111. realm.GlobalObject.Set("global", realm.GlobalObject);
  112. return realm.GlobalObject;
  113. }), true, true, true));
  114. o.FastSetProperty("detachArrayBuffer", new PropertyDescriptor(new ClrFunctionInstance(engine, "detachArrayBuffer",
  115. (thisObj, args) =>
  116. {
  117. var buffer = (ArrayBufferInstance) args.At(0);
  118. buffer.DetachArrayBuffer();
  119. return JsValue.Undefined;
  120. }), true, true, true));
  121. engine.SetValue("$262", o);
  122. var includes = Regex.Match(code, @"includes: \[(.+?)\]");
  123. if (includes.Success)
  124. {
  125. var files = includes.Groups[1].Captures[0].Value.Split(',', StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);
  126. foreach (var file in files)
  127. {
  128. if (file == "hidden-constructors.js")
  129. {
  130. // suite refers to non-existent file
  131. continue;
  132. }
  133. engine.Execute(Sources[file.Trim()]);
  134. }
  135. }
  136. if (code.IndexOf("propertyHelper.js", StringComparison.OrdinalIgnoreCase) != -1)
  137. {
  138. engine.Execute(Sources["propertyHelper.js"]);
  139. }
  140. string lastError = null;
  141. bool negative = code.IndexOf("negative:", StringComparison.Ordinal) > -1;
  142. try
  143. {
  144. engine.Execute(new JavaScriptParser(code, new ParserOptions(fileName)).ParseScript());
  145. }
  146. catch (JavaScriptException j)
  147. {
  148. lastError = j.ToString();
  149. }
  150. catch (Exception e)
  151. {
  152. lastError = e.ToString();
  153. }
  154. if (!negative && !string.IsNullOrWhiteSpace(lastError))
  155. {
  156. throw new XunitException(lastError);
  157. }
  158. }
  159. protected void RunTestInternal(SourceFile sourceFile)
  160. {
  161. if (sourceFile.Skip)
  162. {
  163. return;
  164. }
  165. if (sourceFile.Code.IndexOf("onlyStrict", StringComparison.Ordinal) < 0)
  166. {
  167. RunTestCode(sourceFile.Source, sourceFile.Code, strict: false);
  168. }
  169. if (!_strictSkips.Contains(sourceFile.Source)
  170. && sourceFile.Code.IndexOf("noStrict", StringComparison.Ordinal) < 0)
  171. {
  172. RunTestCode(sourceFile.Source, sourceFile.Code, strict: true);
  173. }
  174. }
  175. public static IEnumerable<object[]> SourceFiles(string pathPrefix, bool skipped)
  176. {
  177. var results = new ConcurrentBag<object[]>();
  178. var fixturesPath = Path.Combine(BasePath, "test");
  179. var segments = pathPrefix.Split('\\');
  180. var searchPath = Path.Combine(fixturesPath, Path.Combine(segments));
  181. var files = Directory.GetFiles(searchPath, "*", SearchOption.AllDirectories);
  182. foreach (var file in files)
  183. {
  184. var name = file.Substring(fixturesPath.Length + 1).Replace("\\", "/");
  185. bool skip = _skipReasons.TryGetValue(name, out var reason);
  186. var code = skip ? "" : File.ReadAllText(file);
  187. var flags = Regex.Match(code, "flags: \\[(.+?)\\]");
  188. if (flags.Success)
  189. {
  190. var items = flags.Groups[1].Captures[0].Value.Split(',');
  191. foreach (var item in items.Select(x => x.Trim()))
  192. {
  193. switch (item)
  194. {
  195. // TODO implement
  196. case "async":
  197. skip = true;
  198. reason = "async not implemented";
  199. break;
  200. }
  201. }
  202. }
  203. var features = Regex.Match(code, "features: \\[(.+?)\\]");
  204. if (features.Success)
  205. {
  206. var items = features.Groups[1].Captures[0].Value.Split(',');
  207. foreach (var item in items.Select(x => x.Trim()))
  208. {
  209. switch (item)
  210. {
  211. // TODO implement
  212. case "tail-call-optimization":
  213. skip = true;
  214. reason = "tail-calls not implemented";
  215. break;
  216. case "BigInt":
  217. skip = true;
  218. reason = "BigInt 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 "TypedArray.prototype.at":
  266. skip = true;
  267. reason = "TypedArray.prototype.at not implemented";
  268. break;
  269. }
  270. }
  271. }
  272. if (code.IndexOf("SpecialCasing.txt") > -1)
  273. {
  274. skip = true;
  275. reason = "SpecialCasing.txt not implemented";
  276. }
  277. if (name.StartsWith("language/expressions/object/dstr-async-gen-meth-"))
  278. {
  279. skip = true;
  280. reason = "Esprima problem, Unexpected token *";
  281. }
  282. if (name.StartsWith("built-ins/RegExp/property-escapes/generated/"))
  283. {
  284. skip = true;
  285. reason = "Esprima problem, Invalid regular expression";
  286. }
  287. if (name.StartsWith("built-ins/RegExp/unicode_"))
  288. {
  289. skip = true;
  290. reason = "Unicode support and its special cases need more work";
  291. }
  292. // Promises
  293. if (name.StartsWith("built-ins/Promise/allSettled") ||
  294. name.StartsWith("built-ins/Promise/any"))
  295. {
  296. skip = true;
  297. reason = "Promise.any and Promise.allSettled are not implemented yet";
  298. }
  299. if (file.EndsWith("tv-line-continuation.js")
  300. || file.EndsWith("tv-line-terminator-sequence.js")
  301. || file.EndsWith("special-characters.js"))
  302. {
  303. // LF endings required
  304. code = code.Replace("\r\n", "\n");
  305. }
  306. var sourceFile = new SourceFile(
  307. name,
  308. file,
  309. skip,
  310. reason,
  311. code);
  312. if (skipped == sourceFile.Skip)
  313. {
  314. results.Add(new object[]
  315. {
  316. sourceFile
  317. });
  318. }
  319. }
  320. return results;
  321. }
  322. private static ParserOptions CreateParserOptions(string fileName) =>
  323. new ParserOptions(fileName)
  324. {
  325. AdaptRegexp = true,
  326. Tolerant = true
  327. };
  328. }
  329. public class SourceFile : IXunitSerializable
  330. {
  331. public SourceFile()
  332. {
  333. }
  334. public SourceFile(
  335. string source,
  336. string fullPath,
  337. bool skip,
  338. string reason,
  339. string code)
  340. {
  341. Skip = skip;
  342. Source = source;
  343. Reason = reason;
  344. FullPath = fullPath;
  345. Code = code;
  346. }
  347. public string Source { get; set; }
  348. public bool Skip { get; set; }
  349. public string Reason { get; set; }
  350. public string FullPath { get; set; }
  351. public string Code { get; set; }
  352. public void Deserialize(IXunitSerializationInfo info)
  353. {
  354. Skip = info.GetValue<bool>(nameof(Skip));
  355. Source = info.GetValue<string>(nameof(Source));
  356. Reason = info.GetValue<string>(nameof(Reason));
  357. FullPath = info.GetValue<string>(nameof(FullPath));
  358. Code = info.GetValue<string>(nameof(Code));
  359. }
  360. public void Serialize(IXunitSerializationInfo info)
  361. {
  362. info.AddValue(nameof(Skip), Skip);
  363. info.AddValue(nameof(Source), Source);
  364. info.AddValue(nameof(Reason), Reason);
  365. info.AddValue(nameof(FullPath), FullPath);
  366. info.AddValue(nameof(Code), Code);
  367. }
  368. public override string ToString()
  369. {
  370. return Source;
  371. }
  372. }
  373. }