using System.Text; namespace Febe.Tests.Web.Support; /// /// A small check of the interface's ES modules that runs without a browser (the Chromium tests run only in the CI): it /// reads the tokens of a module — comments, strings, template literals, regular expressions — and finds the mistakes /// that stop a whole module from loading, so that every page importing it breaks: brackets that do not match, a /// let, const or class declared twice in one block or with the name of a parameter of its function, /// or of an import, and a static import of a name the other module does not export. Not a JavaScript parser: what it /// does not understand (destructured bindings, var) it leaves alone rather than guess. /// internal static class ScriptCheck { private static readonly HashSet RegexAfterWords = new(StringComparer.Ordinal) { "return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw", "instanceof", "yield", "await", }; private static readonly HashSet NotFunctionBefore = new(StringComparer.Ordinal) { "if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield", }; private static readonly HashSet Reserved = new(StringComparer.Ordinal) { "if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield", "function", "class", "const", "let", "var", "this", "super", "null", "true", "false", "else", "do", "try", "catch", "finally", "throw", "case", "default", "break", "continue", "import", "export", "async", "instanceof", }; internal enum Kind { Word, Punct, Text, Number, Regex, } internal readonly record struct Token(Kind Kind, string Value, int Line); /// The problems found in the source of one module, each with its line; empty when it reads cleanly. public static List Problems(string source) { var problems = new List(); List tokens; try { tokens = Tokens(source); } catch (FormatException ex) { problems.Add(ex.Message); return problems; } CheckScopes(tokens, problems); return problems; } /// The names a module exports (export function, const, let, class, { a as b }, default). public static HashSet Exports(string source) { var names = new HashSet(StringComparer.Ordinal); var tokens = Tokens(source); for (var i = 0; i < tokens.Count - 1; i++) { if (!IsWord(tokens[i], "export")) { continue; } var j = i + 1; if (IsWord(tokens[j], "default")) { names.Add("default"); continue; } if (IsWord(tokens[j], "async")) { j++; } if (j < tokens.Count && tokens[j].Kind == Kind.Word && tokens[j].Value is "function" or "const" or "let" or "var" or "class") { j++; if (j < tokens.Count && IsPunct(tokens[j], "*")) { j++; } if (j < tokens.Count && tokens[j].Kind == Kind.Word) { names.Add(tokens[j].Value); } } else if (j < tokens.Count && IsPunct(tokens[j], "{")) { for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++) { if (tokens[j].Kind == Kind.Word && (j + 1 >= tokens.Count || IsPunct(tokens[j + 1], ",") || IsPunct(tokens[j + 1], "}"))) { names.Add(tokens[j].Value); } } } } return names; } /// The static imports of a module: the module named and the names taken from it (not «* as» nor default). public static List<(string From, List Names, int Line)> Imports(string source) { var imports = new List<(string, List, int)>(); var tokens = Tokens(source); for (var i = 0; i < tokens.Count - 1; i++) { if (!IsWord(tokens[i], "import") || IsPunct(tokens[i + 1], "(") || IsPunct(tokens[i + 1], ".")) { continue; } var names = new List(); var j = i + 1; for (; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++) { if (IsPunct(tokens[j], "{")) { for (j++; j < tokens.Count && !IsPunct(tokens[j], "}"); j++) { if (tokens[j].Kind == Kind.Word && !IsWord(tokens[j], "as") && (j == 0 || !IsWord(tokens[j - 1], "as"))) { names.Add(tokens[j].Value); } } } } if (j < tokens.Count && IsWord(tokens[j], "from")) { j++; } if (j < tokens.Count && tokens[j].Kind == Kind.Text) { imports.Add((tokens[j].Value, names, tokens[i].Line)); } } return imports; } private static bool IsWord(Token token, string value) => token.Kind == Kind.Word && token.Value == value; private static bool IsPunct(Token token, string value) => token.Kind == Kind.Punct && token.Value == value; /// The tokens of the source; throws for an unfinished string, comment or regex. internal static List Tokens(string s) { var tokens = new List(); // Braces opened in code: '{' an ordinary one, 'E' the «${» of a template literal. var braces = new Stack(); var line = 1; var i = 0; var inTemplate = false; bool RegexMayStart() { if (tokens.Count == 0) { return true; } var last = tokens[^1]; return last.Kind switch { Kind.Punct => last.Value is not (")" or "]" or "}"), Kind.Word => RegexAfterWords.Contains(last.Value), _ => false, }; } void ScanTemplate() { // From just after a backtick or the «}» of an expression, up to the closing backtick or the next «${». var start = line; var text = new StringBuilder(); while (true) { if (i >= s.Length) { throw new FormatException($"riga {start}: modello fra apici inversi non chiuso"); } var c = s[i]; if (c == '\\') { i += 2; continue; } if (c == '\n') { line++; } if (c == '`') { i++; inTemplate = false; tokens.Add(new Token(Kind.Text, text.ToString(), start)); return; } if (c == '$' && i + 1 < s.Length && s[i + 1] == '{') { i += 2; braces.Push('E'); inTemplate = false; tokens.Add(new Token(Kind.Text, text.ToString(), start)); tokens.Add(new Token(Kind.Punct, "${", line)); return; } text.Append(c); i++; } } while (i < s.Length || inTemplate) { if (inTemplate) { ScanTemplate(); continue; } var c = s[i]; if (c == '\n') { line++; i++; continue; } if (char.IsWhiteSpace(c)) { i++; continue; } if (c == '/' && i + 1 < s.Length && s[i + 1] == '/') { while (i < s.Length && s[i] != '\n') { i++; } continue; } if (c == '/' && i + 1 < s.Length && s[i + 1] == '*') { var end = s.IndexOf("*/", i + 2, StringComparison.Ordinal); if (end < 0) { throw new FormatException($"riga {line}: commento non chiuso"); } line += s.AsSpan(i, end - i).Count('\n'); i = end + 2; continue; } if (c is '\'' or '"') { i++; var text = new StringBuilder(); while (true) { if (i >= s.Length || s[i] == '\n') { throw new FormatException($"riga {line}: stringa non chiusa"); } if (s[i] == '\\') { text.Append(s[i + 1]); i += 2; continue; } if (s[i] == c) { i++; break; } text.Append(s[i++]); } tokens.Add(new Token(Kind.Text, text.ToString(), line)); continue; } if (c == '`') { i++; inTemplate = true; continue; } if (c == '/' && RegexMayStart()) { var start = i++; var inClass = false; while (true) { if (i >= s.Length || s[i] == '\n') { throw new FormatException($"riga {line}: espressione regolare non chiusa"); } if (s[i] == '\\') { i += 2; continue; } if (s[i] == '[') { inClass = true; } else if (s[i] == ']') { inClass = false; } else if (s[i] == '/' && !inClass) { i++; break; } i++; } while (i < s.Length && char.IsAsciiLetter(s[i])) { i++; } tokens.Add(new Token(Kind.Regex, s[start..i], line)); continue; } if (char.IsLetter(c) || c is '_' or '$' or '#') { var start = i++; while (i < s.Length && (char.IsLetterOrDigit(s[i]) || s[i] is '_' or '$')) { i++; } tokens.Add(new Token(Kind.Word, s[start..i], line)); continue; } if (char.IsAsciiDigit(c) || (c == '.' && i + 1 < s.Length && char.IsAsciiDigit(s[i + 1]))) { var start = i++; while (i < s.Length && (char.IsAsciiLetterOrDigit(s[i]) || s[i] is '.' or '_')) { i++; } tokens.Add(new Token(Kind.Number, s[start..i], line)); continue; } if (c == '{') { braces.Push('{'); } else if (c == '}') { if (braces.Count > 0 && braces.Peek() == 'E') { braces.Pop(); i++; tokens.Add(new Token(Kind.Punct, "}$", line)); inTemplate = true; continue; } if (braces.Count > 0) { braces.Pop(); } } // The punctuators that matter here; any other is one character. string[] longest = ["...", "=>", "?.", "??", "===", "!==", "==", "!=", "&&", "||", "**", "<=", ">=", "++", "--"]; var punct = longest.FirstOrDefault(p => string.CompareOrdinal(s, i, p, 0, p.Length) == 0) ?? c.ToString(); tokens.Add(new Token(Kind.Punct, punct, line)); i += punct.Length; } return tokens; } private sealed class Frame(char open, int line, int start) { public char Open { get; } = open; public int Line { get; } = line; /// Index of the opening token. public int Start { get; } = start; /// Names declared in this block with let, const or class, or as parameters (for a function body). public Dictionary Names { get; } = new(StringComparer.Ordinal); } private static void CheckScopes(List tokens, List problems) { var frames = new Stack(); frames.Push(new Frame('m', 1, -1)); List? pendingParams = null; var pendingAt = -1; void Declare(string name, string how, int line) { var scope = frames.Peek(); if (scope.Names.TryGetValue(name, out var before)) { problems.Add($"riga {line}: «{name}» dichiarato di nuovo con {how} (già {before} nello stesso blocco)"); return; } scope.Names[name] = how; } for (var i = 0; i < tokens.Count; i++) { var token = tokens[i]; var prev = i > 0 ? tokens[i - 1] : default; if (token.Kind == Kind.Punct) { switch (token.Value) { case "{": { var frame = new Frame('{', token.Line, i); if (pendingParams is not null && pendingAt == i) { foreach (var name in pendingParams) { frame.Names.TryAdd(name, "parametro"); } } frames.Push(frame); pendingParams = null; continue; } case "(" or "[" or "${": frames.Push(new Frame(token.Value[0], token.Line, i)); continue; case "}" or ")" or "]" or "}$": { var open = token.Value switch { "}" => '{', ")" => '(', "]" => '[', _ => '$' }; if (frames.Count <= 1 || frames.Peek().Open != open) { var top = frames.Peek(); problems.Add(top.Open == 'm' ? $"riga {token.Line}: «{token.Value[0]}» senza apertura" : $"riga {token.Line}: «{token.Value[0]}» chiude «{top.Open}» aperta alla riga {top.Line}"); return; } var closed = frames.Pop(); if (open == '(') { OnParenClosed(tokens, closed.Start, i, ref pendingParams, ref pendingAt); } continue; } case "=>": if (prev.Kind == Kind.Word && !Reserved.Contains(prev.Value)) { pendingParams = [prev.Value]; pendingAt = i + 1; } else if (pendingParams is not null && pendingAt == i) { pendingAt = i + 1; // «(a, b) => {» } continue; } continue; } if (token.Kind != Kind.Word || i + 1 >= tokens.Count || (prev.Kind == Kind.Punct && prev.Value is "." or "?.")) { continue; } var next = tokens[i + 1]; if (token.Value is "let" or "const" && next.Kind == Kind.Word && !Reserved.Contains(next.Value)) { Declare(next.Value, token.Value, next.Line); } else if (token.Value == "class" && next.Kind == Kind.Word && !Reserved.Contains(next.Value) && StatementStart(tokens, i)) { Declare(next.Value, "class", next.Line); } else if (token.Value == "import" && frames.Count == 1 && !IsPunct(next, "(") && !IsPunct(next, ".")) { for (var j = i + 1; j < tokens.Count && !IsWord(tokens[j], "from") && tokens[j].Kind != Kind.Text; j++) { var t = tokens[j]; var after = j + 1 < tokens.Count ? tokens[j + 1] : default; if (t.Kind == Kind.Word && !IsWord(t, "as") && !IsWord(after, "as") && !Reserved.Contains(t.Value)) { Declare(t.Value, "import", t.Line); } } } } if (frames.Count > 1) { var open = frames.Peek(); problems.Add($"riga {open.Line}: «{open.Open}» mai chiusa"); } } /// A «)» just closed: when a function body follows, the simple names of its parameters are kept for it. private static void OnParenClosed(List tokens, int open, int close, ref List? pending, ref int pendingAt) { var next = close + 1 < tokens.Count ? tokens[close + 1] : default; var before = open > 0 ? tokens[open - 1] : default; var arrow = IsPunct(next, "=>"); var body = IsPunct(next, "{") && before.Kind == Kind.Word && (!NotFunctionBefore.Contains(before.Value) || before.Value == "function"); if (!arrow && !body) { return; } var names = new List(); var depth = 0; var pieceStart = true; for (var j = open + 1; j < close; j++) { var t = tokens[j]; if (t.Kind == Kind.Punct && t.Value is "(" or "[" or "{" or "${") { depth++; } else if (t.Kind == Kind.Punct && t.Value is ")" or "]" or "}" or "}$") { depth--; } if (depth == 0 && IsPunct(t, ",")) { pieceStart = true; continue; } if (pieceStart && depth == 0) { pieceStart = false; var name = IsPunct(t, "...") && j + 1 < close ? tokens[j + 1] : t; if (name.Kind == Kind.Word && !Reserved.Contains(name.Value)) { names.Add(name.Value); } } else if (pieceStart) { pieceStart = false; // a destructured parameter: left alone } } pending = names; pendingAt = close + 1; } /// True when the word at starts a statement (a declaration, not an expression). private static bool StatementStart(List tokens, int i) { if (i == 0) { return true; } var prev = tokens[i - 1]; return (prev.Kind == Kind.Punct && prev.Value is ";" or "{" or "}") || IsWord(prev, "export") || IsWord(prev, "default"); } }