Test262Test.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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(',');
  126. foreach (var file in files)
  127. {
  128. engine.Execute(Sources[file.Trim()]);
  129. }
  130. }
  131. if (code.IndexOf("propertyHelper.js", StringComparison.OrdinalIgnoreCase) != -1)
  132. {
  133. engine.Execute(Sources["propertyHelper.js"]);
  134. }
  135. string lastError = null;
  136. bool negative = code.IndexOf("negative:", StringComparison.Ordinal) > -1;
  137. try
  138. {
  139. engine.Execute(new JavaScriptParser(code, new ParserOptions(fileName)).ParseScript());
  140. }
  141. catch (JavaScriptException j)
  142. {
  143. lastError = j.ToString();
  144. }
  145. catch (Exception e)
  146. {
  147. lastError = e.ToString();
  148. }
  149. if (!negative && !string.IsNullOrWhiteSpace(lastError))
  150. {
  151. throw new XunitException(lastError);
  152. }
  153. }
  154. protected void RunTestInternal(SourceFile sourceFile)
  155. {
  156. if (sourceFile.Skip)
  157. {
  158. return;
  159. }
  160. if (sourceFile.Code.IndexOf("onlyStrict", StringComparison.Ordinal) < 0)
  161. {
  162. RunTestCode(sourceFile.Source, sourceFile.Code, strict: false);
  163. }
  164. if (!_strictSkips.Contains(sourceFile.Source)
  165. && sourceFile.Code.IndexOf("noStrict", StringComparison.Ordinal) < 0)
  166. {
  167. RunTestCode(sourceFile.Source, sourceFile.Code, strict: true);
  168. }
  169. }
  170. public static IEnumerable<object[]> SourceFiles(string pathPrefix, bool skipped)
  171. {
  172. var results = new ConcurrentBag<object[]>();
  173. var fixturesPath = Path.Combine(BasePath, "test");
  174. var segments = pathPrefix.Split('\\');
  175. var searchPath = Path.Combine(fixturesPath, Path.Combine(segments));
  176. var files = Directory.GetFiles(searchPath, "*", SearchOption.AllDirectories);
  177. foreach (var file in files)
  178. {
  179. var name = file.Substring(fixturesPath.Length + 1).Replace("\\", "/");
  180. bool skip = _skipReasons.TryGetValue(name, out var reason);
  181. var code = skip ? "" : File.ReadAllText(file);
  182. var flags = Regex.Match(code, "flags: \\[(.+?)\\]");
  183. if (flags.Success)
  184. {
  185. var items = flags.Groups[1].Captures[0].Value.Split(',');
  186. foreach (var item in items.Select(x => x.Trim()))
  187. {
  188. switch (item)
  189. {
  190. // TODO implement
  191. case "async":
  192. skip = true;
  193. reason = "async not implemented";
  194. break;
  195. }
  196. }
  197. }
  198. var features = Regex.Match(code, "features: \\[(.+?)\\]");
  199. if (features.Success)
  200. {
  201. var items = features.Groups[1].Captures[0].Value.Split(',');
  202. foreach (var item in items.Select(x => x.Trim()))
  203. {
  204. switch (item)
  205. {
  206. // TODO implement
  207. case "tail-call-optimization":
  208. skip = true;
  209. reason = "tail-calls not implemented";
  210. break;
  211. case "BigInt":
  212. skip = true;
  213. reason = "BigInt not implemented";
  214. break;
  215. case "generators":
  216. skip = true;
  217. reason = "generators not implemented";
  218. break;
  219. case "async-functions":
  220. skip = true;
  221. reason = "async-functions not implemented";
  222. break;
  223. case "async-iteration":
  224. skip = true;
  225. reason = "async not implemented";
  226. break;
  227. case "class-fields-private":
  228. case "class-fields-public":
  229. skip = true;
  230. reason = "private/public class fields not implemented in esprima";
  231. break;
  232. case "String.prototype.replaceAll":
  233. skip = true;
  234. reason = "not in spec yet";
  235. break;
  236. case "u180e":
  237. skip = true;
  238. reason = "unicode/regexp not implemented";
  239. break;
  240. case "regexp-match-indices":
  241. skip = true;
  242. reason = "regexp-match-indices not implemented";
  243. break;
  244. case "regexp-named-groups":
  245. skip = true;
  246. reason = "regexp-named-groups not implemented";
  247. break;
  248. case "regexp-lookbehind":
  249. skip = true;
  250. reason = "regexp-lookbehind not implemented";
  251. break;
  252. case "SharedArrayBuffer":
  253. skip = true;
  254. reason = "SharedArrayBuffer not implemented";
  255. break;
  256. case "resizable-arraybuffer":
  257. skip = true;
  258. reason = "resizable-arraybuffer not implemented";
  259. break;
  260. case "TypedArray.prototype.at":
  261. skip = true;
  262. reason = "TypedArray.prototype.at not implemented";
  263. break;
  264. }
  265. }
  266. }
  267. if (code.IndexOf("SpecialCasing.txt") > -1)
  268. {
  269. skip = true;
  270. reason = "SpecialCasing.txt not implemented";
  271. }
  272. if (name.StartsWith("language/expressions/object/dstr-async-gen-meth-"))
  273. {
  274. skip = true;
  275. reason = "Esprima problem, Unexpected token *";
  276. }
  277. if (name.StartsWith("built-ins/RegExp/property-escapes/generated/"))
  278. {
  279. skip = true;
  280. reason = "Esprima problem, Invalid regular expression";
  281. }
  282. if (name.StartsWith("built-ins/RegExp/unicode_"))
  283. {
  284. skip = true;
  285. reason = "Unicode support and its special cases need more work";
  286. }
  287. // Promises
  288. if (name.StartsWith("built-ins/Promise/allSettled") ||
  289. name.StartsWith("built-ins/Promise/any"))
  290. {
  291. skip = true;
  292. reason = "Promise.any and Promise.allSettled are not implemented yet";
  293. }
  294. if (file.EndsWith("tv-line-continuation.js")
  295. || file.EndsWith("tv-line-terminator-sequence.js")
  296. || file.EndsWith("special-characters.js"))
  297. {
  298. // LF endings required
  299. code = code.Replace("\r\n", "\n");
  300. }
  301. var sourceFile = new SourceFile(
  302. name,
  303. file,
  304. skip,
  305. reason,
  306. code);
  307. if (skipped == sourceFile.Skip)
  308. {
  309. results.Add(new object[]
  310. {
  311. sourceFile
  312. });
  313. }
  314. }
  315. return results;
  316. }
  317. private static ParserOptions CreateParserOptions(string fileName) =>
  318. new ParserOptions(fileName)
  319. {
  320. AdaptRegexp = true,
  321. Tolerant = true
  322. };
  323. }
  324. public class SourceFile : IXunitSerializable
  325. {
  326. public SourceFile()
  327. {
  328. }
  329. public SourceFile(
  330. string source,
  331. string fullPath,
  332. bool skip,
  333. string reason,
  334. string code)
  335. {
  336. Skip = skip;
  337. Source = source;
  338. Reason = reason;
  339. FullPath = fullPath;
  340. Code = code;
  341. }
  342. public string Source { get; set; }
  343. public bool Skip { get; set; }
  344. public string Reason { get; set; }
  345. public string FullPath { get; set; }
  346. public string Code { get; set; }
  347. public void Deserialize(IXunitSerializationInfo info)
  348. {
  349. Skip = info.GetValue<bool>(nameof(Skip));
  350. Source = info.GetValue<string>(nameof(Source));
  351. Reason = info.GetValue<string>(nameof(Reason));
  352. FullPath = info.GetValue<string>(nameof(FullPath));
  353. Code = info.GetValue<string>(nameof(Code));
  354. }
  355. public void Serialize(IXunitSerializationInfo info)
  356. {
  357. info.AddValue(nameof(Skip), Skip);
  358. info.AddValue(nameof(Source), Source);
  359. info.AddValue(nameof(Reason), Reason);
  360. info.AddValue(nameof(FullPath), FullPath);
  361. info.AddValue(nameof(Code), Code);
  362. }
  363. public override string ToString()
  364. {
  365. return Source;
  366. }
  367. }
  368. }