S4b: sessione salvata, e in Docker lasciare la pagina del browser copia la sessione (#36) #61
No files matched your search
@@ -328,7 +328,7 @@ export function savedSessionBox(saved, page) {
|
||||
// Neither choice is shown as chosen, and neither can be picked, until the server says which one is stored: the page
|
||||
// never claims a choice the next copy will not follow. Once Alberto picks one, a late answer no longer changes it;
|
||||
// a choice the server did not save goes back to the one before.
|
||||
let saved = null;
|
||||
let stored = null;
|
||||
let chosen = false;
|
||||
const show = (value) => {
|
||||
keep.input.checked = value === 'tieni-completa';
|
||||
@@ -336,10 +336,10 @@ export function savedSessionBox(saved, page) {
|
||||
};
|
||||
const choose = async (value) => {
|
||||
chosen = true;
|
||||
const before = saved;
|
||||
const before = stored;
|
||||
try {
|
||||
const settings = await api('/api/connection/settings', { method: 'PUT', body: { incompleteCopy: value } });
|
||||
saved = settings && settings.incompleteCopy ? settings.incompleteCopy : value;
|
||||
stored = settings && settings.incompleteCopy ? settings.incompleteCopy : value;
|
||||
unknown.hidden = true;
|
||||
toast(k('salvato'));
|
||||
} catch (error) {
|
||||
@@ -353,8 +353,8 @@ export function savedSessionBox(saved, page) {
|
||||
for (const choice of [replace, keep]) choice.input.disabled = true;
|
||||
api('/api/connection/settings', { signal: page && page.signal }).then((settings) => {
|
||||
if (chosen) return;
|
||||
saved = settings.incompleteCopy;
|
||||
show(saved);
|
||||
stored = settings.incompleteCopy;
|
||||
show(stored);
|
||||
}).catch(() => {
|
||||
if (page && page.signal && page.signal.aborted) return; // the page was left
|
||||
if (!chosen) unknown.hidden = false;
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
using Febe.Tests.Desktop.Support;
|
||||
using Febe.Tests.Web.Support;
|
||||
|
||||
namespace Febe.Tests.Web;
|
||||
|
||||
/// <summary>
|
||||
/// The modules of the interface load: a mistake that stops one module from parsing breaks every page importing it, and
|
||||
/// the Chromium tests that would see it run only in the CI. <see cref="ScriptCheck"/> reads them without a browser.
|
||||
/// </summary>
|
||||
[TestClass]
|
||||
public sealed class ScriptSyntaxTests
|
||||
{
|
||||
[TestMethod]
|
||||
public void EveryModuleOfTheInterfaceReadsWithoutTheMistakesThatStopItLoading()
|
||||
{
|
||||
var root = Repository.PathOf("src", "Febe.Web", "wwwroot");
|
||||
var files = Directory.GetFiles(root, "*.js", SearchOption.AllDirectories);
|
||||
Assert.IsGreaterThan(30, files.Length, "the modules of the interface");
|
||||
var problems = new List<string>();
|
||||
foreach (var file in files)
|
||||
{
|
||||
var name = Path.GetRelativePath(root, file);
|
||||
problems.AddRange(ScriptCheck.Problems(File.ReadAllText(file)).Select(p => $"{name}, {p}"));
|
||||
}
|
||||
|
||||
Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void EveryStaticImportNamesSomethingTheOtherModuleExports()
|
||||
{
|
||||
var root = Repository.PathOf("src", "Febe.Web", "wwwroot");
|
||||
var problems = new List<string>();
|
||||
var checkedNames = 0;
|
||||
foreach (var file in Directory.GetFiles(root, "*.js", SearchOption.AllDirectories))
|
||||
{
|
||||
foreach (var (from, names, line) in ScriptCheck.Imports(File.ReadAllText(file)))
|
||||
{
|
||||
if (!from.StartsWith('.'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var target = Path.GetFullPath(Path.Combine(Path.GetDirectoryName(file)!, from));
|
||||
var where = $"{Path.GetRelativePath(root, file)}, riga {line}";
|
||||
if (!File.Exists(target))
|
||||
{
|
||||
problems.Add($"{where}: «{from}» non esiste");
|
||||
continue;
|
||||
}
|
||||
|
||||
var exports = ScriptCheck.Exports(File.ReadAllText(target));
|
||||
foreach (var name in names)
|
||||
{
|
||||
checkedNames++;
|
||||
if (!exports.Contains(name))
|
||||
{
|
||||
problems.Add($"{where}: «{from}» non esporta «{name}»");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Assert.IsGreaterThan(50, checkedNames);
|
||||
Assert.IsEmpty(problems, string.Join(Environment.NewLine, problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("export function box(saved, page) {\n if (!saved) return null;\n let saved = null;\n}", "«saved» dichiarato di nuovo con let (già parametro", DisplayName = "parametro ridichiarato (connection.js, b29b35a)")]
|
||||
[DataRow("const show = (value) => { const value = 1; };", "«value» dichiarato di nuovo", DisplayName = "parametro di una freccia")]
|
||||
[DataRow("items.map(x => { let x = 2; return x; });", "«x» dichiarato di nuovo", DisplayName = "parametro senza parentesi")]
|
||||
[DataRow("function f() { let a = 1; if (a) { let b; } const a = 2; }", "«a» dichiarato di nuovo con const", DisplayName = "due volte nello stesso blocco")]
|
||||
[DataRow("import { h } from './dom.js';\nconst h = 1;", "«h» dichiarato di nuovo con const (già import", DisplayName = "nome già importato")]
|
||||
[DataRow("class A { m(p) { class p {} } }", "«p» dichiarato di nuovo con class", DisplayName = "classe con il nome di un parametro")]
|
||||
[DataRow("function f() { if (x) { return 1; }", "mai chiusa", DisplayName = "parentesi graffa mai chiusa")]
|
||||
[DataRow("const a = [1, 2);", "chiude «[»", DisplayName = "parentesi che non corrispondono")]
|
||||
[DataRow("const s = 'non chiusa;\n", "stringa non chiusa", DisplayName = "stringa non chiusa")]
|
||||
[DataRow("const s = `a ${b} c;\n", "modello fra apici inversi non chiuso", DisplayName = "modello non chiuso")]
|
||||
public void TheCheckFindsTheMistakesThatStopAModuleLoading(string source, string expected)
|
||||
{
|
||||
var problems = ScriptCheck.Problems(source);
|
||||
Assert.IsTrue(problems.Any(p => p.Contains(expected, StringComparison.Ordinal)), string.Join(" | ", problems.DefaultIfEmpty("(nessuno)")));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
[DataRow("export function box(saved, page) {\n let stored = null;\n const show = (value) => { stored = value; };\n}", DisplayName = "la correzione di connection.js")]
|
||||
[DataRow("for (let i = 0; i < 3; i++) { let i2 = i; }\nfor (let i = 0; i < 3; i++) { const j = i; }", DisplayName = "variabili dei cicli")]
|
||||
[DataRow("const re = /a{2}[/}]\\//g; const half = 4 / 2; const t = `x ${ { a: 1 }.a } ${`y ${1}`}`;", DisplayName = "espressioni regolari, divisioni e modelli annidati")]
|
||||
[DataRow("function f(a) { { let a = 1; } if (a) { const a = 2; } }", DisplayName = "lo stesso nome in un blocco interno")]
|
||||
[DataRow("const o = { let: 1, const: 2 }; o.let = o.const;", DisplayName = "proprietà con nomi di parole chiave")]
|
||||
[DataRow("try { x(); } catch (error) { console.log(error); }\nconst error = 1;", DisplayName = "parametro di catch e nome fuori")]
|
||||
[DataRow("// a comment with ' and ` and {\n/* and } */ const a = \"}\";", DisplayName = "commenti e stringhe con parentesi")]
|
||||
public void TheCheckLeavesValidCodeAlone(string source)
|
||||
{
|
||||
var problems = ScriptCheck.Problems(source);
|
||||
Assert.IsEmpty(problems, string.Join(" | ", problems));
|
||||
}
|
||||
|
||||
[TestMethod]
|
||||
public void ImportsAndExportsAreReadByTheirNames()
|
||||
{
|
||||
var exports = ScriptCheck.Exports("export function a() {}\nexport async function b() {}\nexport const c = 1;\nexport class D {}\nconst e = 1, f = 2;\nexport { e, f as g };\nexport default a;");
|
||||
CollectionAssert.AreEquivalent(new[] { "a", "b", "c", "D", "e", "g", "default" }, exports.ToArray());
|
||||
var imports = ScriptCheck.Imports("import { a, b as c } from './x.js';\nimport * as y from './y.js';\nconst z = await import('./z.js');");
|
||||
Assert.HasCount(2, imports);
|
||||
Assert.AreEqual("./x.js", imports[0].From);
|
||||
CollectionAssert.AreEqual(new[] { "a", "b" }, imports[0].Names);
|
||||
Assert.IsEmpty(imports[1].Names);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user