Files
Febe/tests/Febe.Tests/Web/Support/ScriptCheck.cs
Alby96andClaude Opus 5.5 2068dd28f3 Correzioni della revisione della catena 0.3.0, ognuna con la sua prova
- Collegamento: corretta la SyntaxError di connection.js (una «let saved» dichiarata due
  volte nello stesso blocco fermava tutta la pagina). Nuova prova ScriptSyntaxTests con un
  controllo scritto in casa che legge ogni modulo di wwwroot: parentesi, dichiarazioni
  doppie nello stesso blocco, importazioni che il modulo di arrivo non esporta.
- HEIF: il riconoscimento dei formati prende ogni marchio che HeifDecoder accetta (mif2,
  MiHE, marchi solo compatibili), così rilevazione, decodifica, misure, miniatura e
  impronta concordano.
- Docker, lasciare la pagina del browser: un nuovo contratto del browser cancella l'uscita
  annotata (_leftAt) anche prima che la vista si riapra, e la copia della sessione aspetta
  un altro comando del collegamento al più LetGoWait invece che senza limite.
- JPEG e PNG: senza EOI o IEND la decodifica fallisce («File danneggiato o incompleto»),
  la sola lettura delle misure resta tollerante.
- Visualizzatore: IsDamaged legge prima l'intestazione e il file intero solo quando può
  servire, in modo asincrono e con una piccola memoria per file, così una scheda con
  molti file non blocca il server.
- Importazione (§9.3): le immagini danneggiate si importano come le altre ma si segnano
  nella revisione, nel resoconto e nel CSV.
- Pulizia: le prove con il limite di 5 minuti non corrono più in parallelo fra loro.
- Pila dei caratteri come l'appendice B, senza Liberation; testo di Informazioni sulle
  immagini fatte in casa; guida (Problemi comuni, Sicurezza) allineata all'uscita in
  Docker dalla pagina del browser.
- docs/decisioni.md: le righe del 25 novembre 2026 con i motivi, compresa l'unione 537517b
  tenuta così com'è.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 14:21:36 +01:00

611 lines
20 KiB
C#

using System.Text;
namespace Febe.Tests.Web.Support;
/// <summary>
/// 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
/// <c>let</c>, <c>const</c> or <c>class</c> 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, <c>var</c>) it leaves alone rather than guess.
/// </summary>
internal static class ScriptCheck
{
private static readonly HashSet<string> RegexAfterWords = new(StringComparer.Ordinal)
{
"return", "typeof", "case", "do", "else", "in", "of", "new", "delete", "void", "throw", "instanceof", "yield", "await",
};
private static readonly HashSet<string> NotFunctionBefore = new(StringComparer.Ordinal)
{
"if", "for", "while", "switch", "with", "return", "typeof", "await", "void", "delete", "in", "of", "new", "yield",
};
private static readonly HashSet<string> 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);
/// <summary>The problems found in the source of one module, each with its line; empty when it reads cleanly.</summary>
public static List<string> Problems(string source)
{
var problems = new List<string>();
List<Token> tokens;
try
{
tokens = Tokens(source);
}
catch (FormatException ex)
{
problems.Add(ex.Message);
return problems;
}
CheckScopes(tokens, problems);
return problems;
}
/// <summary>The names a module exports (<c>export function</c>, <c>const</c>, <c>let</c>, <c>class</c>, <c>{ a as b }</c>, default).</summary>
public static HashSet<string> Exports(string source)
{
var names = new HashSet<string>(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;
}
/// <summary>The static imports of a module: the module named and the names taken from it (not «* as» nor default).</summary>
public static List<(string From, List<string> Names, int Line)> Imports(string source)
{
var imports = new List<(string, List<string>, 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<string>();
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;
/// <summary>The tokens of the source; throws <see cref="FormatException"/> for an unfinished string, comment or regex.</summary>
internal static List<Token> Tokens(string s)
{
var tokens = new List<Token>();
// Braces opened in code: '{' an ordinary one, 'E' the «${» of a template literal.
var braces = new Stack<char>();
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;
/// <summary>Index of the opening token.</summary>
public int Start { get; } = start;
/// <summary>Names declared in this block with let, const or class, or as parameters (for a function body).</summary>
public Dictionary<string, string> Names { get; } = new(StringComparer.Ordinal);
}
private static void CheckScopes(List<Token> tokens, List<string> problems)
{
var frames = new Stack<Frame>();
frames.Push(new Frame('m', 1, -1));
List<string>? 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");
}
}
/// <summary>A «)» just closed: when a function body follows, the simple names of its parameters are kept for it.</summary>
private static void OnParenClosed(List<Token> tokens, int open, int close, ref List<string>? 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<string>();
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;
}
/// <summary>True when the word at <paramref name="i"/> starts a statement (a declaration, not an expression).</summary>
private static bool StatementStart(List<Token> 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");
}
}