Test262Test.cs 16 KB

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