@skillstech/thunderlang 1.6.1 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/dist/core.cjs +31 -28
- package/dist/index.cjs +292 -59
- package/dist/learn.cjs +81 -22
- package/package.json +1 -1
- package/src/ai.mjs +2 -1
- package/src/atlas.mjs +2 -1
- package/src/behaviour.mjs +246 -0
- package/src/cli-main.mjs +2818 -0
- package/src/cli.mjs +9 -2799
- package/src/conflict.mjs +0 -0
- package/src/core/ThunderDotnet.cs +195 -0
- package/src/core/check.mjs +4 -4
- package/src/core/cli.mjs +7 -2
- package/src/core/csharp-run.mjs +29 -8
- package/src/core/diagnostics.mjs +3 -1
- package/src/core/engine-core.mjs +20 -1
- package/src/core/go-run.mjs +3 -2
- package/src/core/java-run.mjs +3 -3
- package/src/core/kind.mjs +42 -0
- package/src/core/parser.mjs +54 -7
- package/src/core/project.mjs +3 -0
- package/src/core/react-run.mjs +3 -3
- package/src/core/runtime-npm.mjs +79 -0
- package/src/core/runtime-react.mjs +2 -1
- package/src/core/runtime-typescript.mjs +7 -3
- package/src/core/rust-run.mjs +3 -2
- package/src/core/target-csharp.mjs +5 -1
- package/src/core/target-go.mjs +1 -1
- package/src/core/target-python.mjs +1 -1
- package/src/core/target-rust.mjs +1 -1
- package/src/core/target-typescript.mjs +33 -1
- package/src/core/typescript-run.mjs +9 -4
- package/src/decision.mjs +2 -1
- package/src/distributed.mjs +2 -1
- package/src/emit.mjs +2 -2
- package/src/focus.mjs +2 -1
- package/src/intent-atlas.mjs +4 -3
- package/src/mcp.mjs +10 -3
- package/src/passport-fs.mjs +2 -1
- package/src/passport.mjs +2 -1
- package/src/privacy.mjs +2 -1
- package/src/read-repo.mjs +3 -2
- package/src/report.mjs +3 -2
- package/src/review.mjs +2 -1
- package/src/select.mjs +2 -1
- package/src/semantic-diff.mjs +7 -6
- package/src/system.mjs +2 -1
- package/src/text-order.mjs +6 -0
- package/src/thunderize.mjs +2 -1
- package/src/trace-data.mjs +3 -2
- package/src/trace.mjs +4 -3
- package/src/write-across-cli.mjs +22 -4
- package/src/write-across.mjs +2 -1
- package/syntaxes/thunder.tmLanguage.json +196 -0
package/src/conflict.mjs
CHANGED
|
Binary file
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
// ThunderDotnet.cs: written by the Thunder compiler next to compiled C# when a program uses .NET libraries
|
|
2
|
+
// (Use "<Type>" from .NET as <name>, or from NuGet). The boundary between Thunder values and .NET values.
|
|
3
|
+
//
|
|
4
|
+
// Thunder -> .NET, to fit the method's parameter: a whole number becomes int, long, double, or decimal (whichever the
|
|
5
|
+
// parameter is, when it fits); a decimal number becomes decimal or double; money becomes its amount; text stays a
|
|
6
|
+
// string; yes/no a bool; nothing null; a list an array or a List of the parameter's element type; a date a DateTime
|
|
7
|
+
// at midnight. A value that came from .NET goes back unchanged.
|
|
8
|
+
// .NET -> Thunder: int, long, short, byte (and unsigned) become whole numbers; decimal becomes the exact decimal;
|
|
9
|
+
// double and float become the decimal they print as ("R"), so 0.1 stays 0.1; string, bool, and null as they are;
|
|
10
|
+
// arrays and lists become lists; anything else stays a library value that can be handed back to .NET.
|
|
11
|
+
// The method is chosen by name and by which overload every value fits, in the order .NET lists them, preferring one
|
|
12
|
+
// whose parameters need no widening. No fit: TC508 in words.
|
|
13
|
+
#nullable disable
|
|
14
|
+
namespace Thunder
|
|
15
|
+
{
|
|
16
|
+
using System;
|
|
17
|
+
using System.Collections;
|
|
18
|
+
using System.Collections.Generic;
|
|
19
|
+
using System.Globalization;
|
|
20
|
+
using System.Linq;
|
|
21
|
+
using System.Numerics;
|
|
22
|
+
using System.Reflection;
|
|
23
|
+
|
|
24
|
+
public sealed class DotnetLibrary
|
|
25
|
+
{
|
|
26
|
+
public readonly Type type; public readonly string name;
|
|
27
|
+
public DotnetLibrary(Type type, string name) { this.type = type; this.name = name; }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public static class Dotnet
|
|
31
|
+
{
|
|
32
|
+
// Libraries may format by culture (words, dates). A program that uses .NET libraries runs with real culture
|
|
33
|
+
// data, pinned to en-US, so it says the same thing on every machine.
|
|
34
|
+
static Dotnet()
|
|
35
|
+
{
|
|
36
|
+
var c = CultureInfo.GetCultureInfo("en-US");
|
|
37
|
+
CultureInfo.DefaultThreadCurrentCulture = c; CultureInfo.DefaultThreadCurrentUICulture = c;
|
|
38
|
+
CultureInfo.CurrentCulture = c; CultureInfo.CurrentUICulture = c;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The type named `typeName`: in .NET itself, or in a package's assembly next to the program (NuGet). */
|
|
42
|
+
public static DotnetLibrary library(string typeName)
|
|
43
|
+
{
|
|
44
|
+
var t = Type.GetType(typeName, false);
|
|
45
|
+
if (t == null) foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) { t = a.GetType(typeName, false); if (t != null) break; }
|
|
46
|
+
if (t == null)
|
|
47
|
+
foreach (var dll in System.IO.Directory.GetFiles(AppContext.BaseDirectory, "*.dll"))
|
|
48
|
+
{
|
|
49
|
+
try { t = Assembly.LoadFrom(dll).GetType(typeName, false); } catch { }
|
|
50
|
+
if (t != null) break;
|
|
51
|
+
}
|
|
52
|
+
if (t == null) throw new ThunderErr("TC508", "There is no .NET type called \"" + typeName + "\". Write it with its namespace, as in \"System.IO.Path\"; a type from a package needs its NuGet line.", "LibraryError");
|
|
53
|
+
return new DotnetLibrary(t, typeName);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
sealed class NoFit { public static readonly NoFit It = new NoFit(); }
|
|
57
|
+
|
|
58
|
+
static object to(object v, Type p, ref int cost)
|
|
59
|
+
{
|
|
60
|
+
var u = Nullable.GetUnderlyingType(p) ?? p;
|
|
61
|
+
if (v == null || v is NotGiven) return (!p.IsValueType || Nullable.GetUnderlyingType(p) != null) ? null : NoFit.It;
|
|
62
|
+
if (v is Money m) v = m.amount;
|
|
63
|
+
if (u == typeof(object)) { cost += 3; return toPlain(v); }
|
|
64
|
+
if (u.IsInstanceOfType(v) && !(v is Dec) && !(v is BigInteger)) return v;
|
|
65
|
+
if (v is bool b) return u == typeof(bool) ? b : NoFit.It;
|
|
66
|
+
if (v is string s) { if (u == typeof(string)) return s; if (u == typeof(char) && s.Length == 1) { cost += 1; return s[0]; } return NoFit.It; }
|
|
67
|
+
if (v is BigInteger n)
|
|
68
|
+
{
|
|
69
|
+
try
|
|
70
|
+
{
|
|
71
|
+
if (u == typeof(int) && n >= int.MinValue && n <= int.MaxValue) return (int)n;
|
|
72
|
+
if (u == typeof(long) && n >= long.MinValue && n <= long.MaxValue) { cost += 1; return (long)n; }
|
|
73
|
+
if (u == typeof(short) && n >= short.MinValue && n <= short.MaxValue) { cost += 2; return (short)n; }
|
|
74
|
+
if (u == typeof(byte) && n >= byte.MinValue && n <= byte.MaxValue) { cost += 2; return (byte)n; }
|
|
75
|
+
if (u == typeof(decimal)) { cost += 2; return (decimal)n; }
|
|
76
|
+
if (u == typeof(double)) { cost += 3; return (double)n; }
|
|
77
|
+
if (u == typeof(float)) { cost += 4; return (float)n; }
|
|
78
|
+
if (u == typeof(BigInteger)) return n;
|
|
79
|
+
}
|
|
80
|
+
catch (OverflowException) { }
|
|
81
|
+
return NoFit.It;
|
|
82
|
+
}
|
|
83
|
+
if (v is Dec d)
|
|
84
|
+
{
|
|
85
|
+
var text = d.ToString();
|
|
86
|
+
if (u == typeof(decimal) && decimal.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var dm)) return dm;
|
|
87
|
+
if (u == typeof(double)) { cost += 1; return double.Parse(text, CultureInfo.InvariantCulture); }
|
|
88
|
+
if (u == typeof(float)) { cost += 2; return float.Parse(text, CultureInfo.InvariantCulture); }
|
|
89
|
+
return NoFit.It;
|
|
90
|
+
}
|
|
91
|
+
if (v is PyDate dt) return u == typeof(DateTime) ? new DateTime(dt.y, dt.m, dt.d) : u == typeof(DateOnly) ? new DateOnly(dt.y, dt.m, dt.d) : (object)NoFit.It;
|
|
92
|
+
if (v is List<object> list)
|
|
93
|
+
{
|
|
94
|
+
Type el = u.IsArray ? u.GetElementType() : u.IsGenericType && u.GetGenericArguments().Length == 1 && (typeof(IEnumerable).IsAssignableFrom(u)) ? u.GetGenericArguments()[0] : null;
|
|
95
|
+
if (el == null) return NoFit.It;
|
|
96
|
+
var items = new List<object>();
|
|
97
|
+
foreach (var x in list) { var c = to(x, el, ref cost); if (c is NoFit) return NoFit.It; items.Add(c); }
|
|
98
|
+
if (u.IsArray) { var arr = Array.CreateInstance(el, items.Count); for (int i = 0; i < items.Count; i++) arr.SetValue(items[i], i); return arr; }
|
|
99
|
+
var lt = typeof(List<>).MakeGenericType(el);
|
|
100
|
+
if (!u.IsAssignableFrom(lt)) return NoFit.It;
|
|
101
|
+
var l = (IList)Activator.CreateInstance(lt);
|
|
102
|
+
foreach (var x in items) l.Add(x);
|
|
103
|
+
return l;
|
|
104
|
+
}
|
|
105
|
+
return NoFit.It;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** A Thunder value as the plainest .NET value, for an object parameter. */
|
|
109
|
+
static object toPlain(object v)
|
|
110
|
+
{
|
|
111
|
+
if (v is BigInteger n) return n >= long.MinValue && n <= long.MaxValue ? (object)(long)n : n;
|
|
112
|
+
if (v is Dec d) return decimal.TryParse(d.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out var dm) ? dm : (object)double.Parse(d.ToString(), CultureInfo.InvariantCulture);
|
|
113
|
+
if (v is Money m) return toPlain(m.amount);
|
|
114
|
+
if (v is PyDate dt) return new DateTime(dt.y, dt.m, dt.d);
|
|
115
|
+
if (v is List<object> l) return l.Select(toPlain).ToList();
|
|
116
|
+
return v;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** A .NET value as a Thunder value. */
|
|
120
|
+
public static object from(object v)
|
|
121
|
+
{
|
|
122
|
+
switch (v)
|
|
123
|
+
{
|
|
124
|
+
case null: return null;
|
|
125
|
+
case string s: return s;
|
|
126
|
+
case bool b: return b;
|
|
127
|
+
case char c: return c.ToString();
|
|
128
|
+
case int i: return new BigInteger(i);
|
|
129
|
+
case long l: return new BigInteger(l);
|
|
130
|
+
case short sh: return new BigInteger(sh);
|
|
131
|
+
case byte by: return new BigInteger(by);
|
|
132
|
+
case uint ui: return new BigInteger(ui);
|
|
133
|
+
case ulong ul: return new BigInteger(ul);
|
|
134
|
+
case BigInteger n: return n;
|
|
135
|
+
case decimal dm: return Dec.Parse(dm.ToString(CultureInfo.InvariantCulture));
|
|
136
|
+
case double db: if (double.IsNaN(db) || double.IsInfinity(db)) throw new ThunderErr("TC509", "The library gave back " + db.ToString(CultureInfo.InvariantCulture) + ", which is not a number Thunder can use.", "ValueError"); return Dec.Parse(db.ToString("R", CultureInfo.InvariantCulture));
|
|
137
|
+
case float f: return Dec.Parse(((double)f).ToString("R", CultureInfo.InvariantCulture));
|
|
138
|
+
case DateTime dt: return dt.TimeOfDay == TimeSpan.Zero ? new PyDate(dt.Year, dt.Month, dt.Day) : (object)dt;
|
|
139
|
+
case DateOnly d: return new PyDate(d.Year, d.Month, d.Day);
|
|
140
|
+
case IEnumerable e when !(v is IDictionary): { var list = new List<object>(); foreach (var x in e) list.Add(from(x)); return list; }
|
|
141
|
+
default: return v;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** <library>.<method>(<args>): the static method of that name whose parameters every value fits. */
|
|
146
|
+
public static object call(object lib, string method, object[] args)
|
|
147
|
+
{
|
|
148
|
+
var L = lib as DotnetLibrary;
|
|
149
|
+
if (L == null) throw new ThunderErr("TC508", "\"" + method + "\" with a dot reaches into a library brought in with Use.", "LibraryError");
|
|
150
|
+
var methods = L.type.GetMethods(BindingFlags.Public | BindingFlags.Static).Where((m) => m.Name == method).ToArray();
|
|
151
|
+
if (methods.Length == 0) throw new ThunderErr("TC508", "The .NET type \"" + L.name + "\" has no method named \"" + method + "\".", "LibraryError");
|
|
152
|
+
MethodInfo best = null; object[] bestArgs = null; int bestCost = int.MaxValue;
|
|
153
|
+
foreach (var m in methods)
|
|
154
|
+
{
|
|
155
|
+
if (m.ContainsGenericParameters) continue;
|
|
156
|
+
var ps = m.GetParameters();
|
|
157
|
+
if (ps.Length < args.Length) continue;
|
|
158
|
+
if (ps.Skip(args.Length).Any((p) => !p.HasDefaultValue)) continue;
|
|
159
|
+
var conv = new object[ps.Length]; int cost = 0; bool ok = true;
|
|
160
|
+
for (int i = 0; i < ps.Length && ok; i++)
|
|
161
|
+
{
|
|
162
|
+
if (i >= args.Length) { conv[i] = ps[i].DefaultValue; cost += 1; continue; }
|
|
163
|
+
var c = to(args[i], ps[i].ParameterType, ref cost);
|
|
164
|
+
if (c is NoFit) ok = false; else conv[i] = c;
|
|
165
|
+
}
|
|
166
|
+
if (ok && cost < bestCost) { best = m; bestArgs = conv; bestCost = cost; }
|
|
167
|
+
}
|
|
168
|
+
if (best == null)
|
|
169
|
+
{
|
|
170
|
+
var kinds = string.Join(", ", args.Select((a) => T.typeName(a)));
|
|
171
|
+
throw new ThunderErr("TC508", "No \"" + L.name + "." + method + "\" takes " + (args.Length == 0 ? "no values" : "these values (" + kinds + ")") + ". It takes: " + string.Join("; ", methods.Select((m) => "(" + string.Join(", ", m.GetParameters().Select((p) => p.ParameterType.Name + " " + p.Name)) + ")")) + ".", "LibraryError");
|
|
172
|
+
}
|
|
173
|
+
try { return from(best.Invoke(null, bestArgs)); }
|
|
174
|
+
catch (TargetInvocationException e) when (e.InnerException != null)
|
|
175
|
+
{
|
|
176
|
+
if (e.InnerException is TErr te) throw te;
|
|
177
|
+
// The innermost cause says why (a type that failed to start up wraps the real reason).
|
|
178
|
+
var cause = e.InnerException;
|
|
179
|
+
while ((cause is TypeInitializationException || cause is TargetInvocationException) && cause.InnerException != null) cause = cause.InnerException;
|
|
180
|
+
throw new ThunderErr("TC508", ".NET code used by this line failed: " + cause.GetType().Name + ": " + cause.Message, "LibraryError");
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** <library>.<name> without a call: a static property or field. */
|
|
185
|
+
public static object get(object lib, string name)
|
|
186
|
+
{
|
|
187
|
+
var L = lib as DotnetLibrary;
|
|
188
|
+
var p = L?.type.GetProperty(name, BindingFlags.Public | BindingFlags.Static);
|
|
189
|
+
if (p != null) return from(p.GetValue(null));
|
|
190
|
+
var f = L?.type.GetField(name, BindingFlags.Public | BindingFlags.Static);
|
|
191
|
+
if (f != null) return from(f.GetValue(null));
|
|
192
|
+
throw new ThunderErr("TC508", "The .NET type \"" + L?.name + "\" has nothing named \"" + name + "\".", "LibraryError");
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
package/src/core/check.mjs
CHANGED
|
@@ -27,7 +27,7 @@ export const typeWords = (t) => {
|
|
|
27
27
|
case 'map': return 'a map';
|
|
28
28
|
case 'record': return `a ${t.text ?? t.name}`;
|
|
29
29
|
case 'optional': return `${typeWords(t.of)} or nothing`;
|
|
30
|
-
case 'module': return 'a
|
|
30
|
+
case 'module': return 'a library';
|
|
31
31
|
default: return 'a value';
|
|
32
32
|
}
|
|
33
33
|
};
|
|
@@ -87,13 +87,13 @@ class Checker {
|
|
|
87
87
|
for (const r of inf.records) { this.records.set(r.name, r); this.info.imported.add(r); }
|
|
88
88
|
for (const f of inf.funcs) { this.global.vars.set(f.name, { kind: 'func', line: f.line, name: f.name, text: f.text, py: f.py, stmt: f, ret: f.ret ?? UNKNOWN }); this.funcs.set(f.name, f); this.info.imported.add(f); }
|
|
89
89
|
for (const k of inf.consts) { this.global.vars.set(k.name, { kind: 'const', line: k.line, name: k.name, text: k.text, py: k.py, type: k.e.type ?? UNKNOWN }); this.info.imported.add(k); }
|
|
90
|
-
for (const m of inf.modules) { this.global.vars.set(m.name, { kind: 'module', line: m.line, name: m.name, text: m.text, py: m.py, type: T('module') }); this.info.imported.add(m); }
|
|
90
|
+
for (const m of inf.modules) { this.global.vars.set(m.name, { kind: 'module', line: m.line, name: m.name, text: m.text, py: m.py, ecosystem: m.ecosystem, type: T('module') }); this.info.imported.add(m); }
|
|
91
91
|
}
|
|
92
92
|
// 1. Global declarations, hoisted: records, functions, modules, kept values.
|
|
93
93
|
for (const s of top) {
|
|
94
94
|
if (s.k === 'record') this.declare(s, 'record', s.line, { py: pyName(s.name, 'pascal'), stmt: s });
|
|
95
95
|
else if (s.k === 'func') this.declare(s, 'func', s.line, { py: pyName(s.name), stmt: s, ret: UNKNOWN });
|
|
96
|
-
else if (s.k === 'use') this.declare(s, 'module', s.line, { py: pyName(s.name), module: s.module, type: T('module') });
|
|
96
|
+
else if (s.k === 'use') this.declare(s, 'module', s.line, { py: pyName(s.name), module: s.module, ecosystem: s.ecosystem, type: T('module') });
|
|
97
97
|
else if (s.k === 'screen') {
|
|
98
98
|
const prev = this.screens.get(s.name);
|
|
99
99
|
if (prev) this.err('TC203', s.line, `There is already a screen called "${s.text}" (line ${prev.line}).`, 'Give one of them a different name.');
|
|
@@ -621,7 +621,7 @@ class Checker {
|
|
|
621
621
|
}
|
|
622
622
|
case 'dot': {
|
|
623
623
|
const ot = this.ex(e.obj, sc, o);
|
|
624
|
-
if (ot.k !== 'module') this.err('TC402', line, `"${e.attr}" with a dot reaches into a
|
|
624
|
+
if (ot.k !== 'module') this.err('TC402', line, `"${e.attr}" with a dot reaches into a library brought in with "Use". ${e.obj.k === 'name' ? `"${e.obj.text}"` : 'This'} is not one.`, 'Write "Use <module> as <name>" (Python) or Use "<package>" from npm as <name> at the top of the file first.');
|
|
625
625
|
for (const a of e.args ?? []) this.ex(a, sc, o);
|
|
626
626
|
return UNKNOWN;
|
|
627
627
|
}
|
package/src/core/cli.mjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
// The Thunder Core commands: thunder new | run | build | test | check | format.
|
|
2
2
|
//
|
|
3
|
-
// When does a command mean Thunder Core (and not a mission .thunder file)? Deterministically, never by guessing
|
|
4
|
-
// from the file's contents:
|
|
3
|
+
// When does a command mean Thunder Core (and not a mission .thunder file)? Deterministically, never by guessing:
|
|
5
4
|
// - thunder new <dir> always creates a Thunder Core project (missions: thunder init <Name>)
|
|
6
5
|
// - no file given, and a thunder.toml is in this folder or above it
|
|
7
6
|
// - the file is a folder that holds a thunder.toml, or a .thunder file under one
|
|
8
7
|
// - --core is given (a single file with no project)
|
|
8
|
+
// - --mission is given: never Core
|
|
9
|
+
// - otherwise, a .thunder file whose first line cannot start a mission (fileKind in kind.mjs)
|
|
9
10
|
// Everything else falls through to the mission commands, unchanged.
|
|
10
11
|
|
|
11
12
|
import { readFileSync, writeFileSync, existsSync, statSync, readdirSync } from 'node:fs';
|
|
@@ -24,6 +25,7 @@ import { runWithEngine, testWithEngine, ENGINES } from './engine.mjs';
|
|
|
24
25
|
import { recordedRun, screenApp, screenOutline, runInProcess } from './engine-core.mjs';
|
|
25
26
|
import { hasScreens } from './target-react.mjs';
|
|
26
27
|
import { COMPILER_VERSION } from '../emit.mjs';
|
|
28
|
+
import { fileKind } from './kind.mjs';
|
|
27
29
|
|
|
28
30
|
/** The format of a Time Machine recording (thunder run --record, thunder replay). */
|
|
29
31
|
export const TIME_MACHINE_SCHEMA = 'thunder-time-machine-v1';
|
|
@@ -70,6 +72,9 @@ export function coreTarget(cmd, argv, cwd = process.cwd()) {
|
|
|
70
72
|
if (!file.endsWith('.thunder')) return null;
|
|
71
73
|
const root = findProjectRoot(p);
|
|
72
74
|
if (root || a.core) return { root, file: p };
|
|
75
|
+
if (a.mission) return null;
|
|
76
|
+
// No project and no flag: the file itself says. A mission always starts with a mission keyword.
|
|
77
|
+
try { if (fileKind(readFileSync(p, 'utf8')).kind === 'program') return { root: null, file: p }; } catch { /* unreadable: the mission commands say so */ }
|
|
73
78
|
return null;
|
|
74
79
|
}
|
|
75
80
|
|
package/src/core/csharp-run.mjs
CHANGED
|
@@ -4,10 +4,11 @@
|
|
|
4
4
|
// Program.cs that runs the program (`dotnet ThunderProgram.dll`) or its tests (`dotnet ThunderProgram.dll test`).
|
|
5
5
|
// Several programs can share one build (one namespace each, picked by number), which is how the conformance tests
|
|
6
6
|
// keep .NET's build time down.
|
|
7
|
-
import { writeFileSync, mkdirSync, readFileSync, existsSync } from 'node:fs';
|
|
7
|
+
import { writeFileSync, mkdirSync, readFileSync, existsSync, rmSync } from 'node:fs';
|
|
8
8
|
import { join } from 'node:path';
|
|
9
9
|
import { spawnSync } from 'node:child_process';
|
|
10
10
|
import { toCSharp, pythonOnlyUses, classOf, cs } from './target-csharp.mjs';
|
|
11
|
+
import { npmRefusals } from './target-typescript.mjs';
|
|
11
12
|
import { diag } from './diagnostics.mjs';
|
|
12
13
|
|
|
13
14
|
export const CS_RUNTIME = readFileSync(new URL('./ThunderRuntime.cs', import.meta.url), 'utf8');
|
|
@@ -15,9 +16,9 @@ export const ASSEMBLY = 'ThunderProgram';
|
|
|
15
16
|
|
|
16
17
|
/** TC405 for every Use in a file: Python modules exist only for the Python target. */
|
|
17
18
|
export function csharpDiagnostics(result) {
|
|
18
|
-
return pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
19
|
+
return [...npmRefusals(result.info, 'C#', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
19
20
|
`"${u.module}" is a Python module, and this program is compiled to C#, which cannot use it.`,
|
|
20
|
-
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'));
|
|
21
|
+
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
|
|
21
22
|
}
|
|
22
23
|
|
|
23
24
|
/** The .NET SDK here: { cmd, version, major } or { error }. */
|
|
@@ -31,7 +32,23 @@ export function findDotnet() {
|
|
|
31
32
|
return { cmd, version, major };
|
|
32
33
|
}
|
|
33
34
|
|
|
34
|
-
|
|
35
|
+
/** The .NET boundary (Use "<type>" from .NET or NuGet), written next to the program only when it uses one. */
|
|
36
|
+
export const CS_DOTNET = readFileSync(new URL('./ThunderDotnet.cs', import.meta.url), 'utf8');
|
|
37
|
+
|
|
38
|
+
/** The NuGet packages a program's files name: [{ package, version, line, file }]. */
|
|
39
|
+
export function nugetPackages(results) {
|
|
40
|
+
return results.flatMap((r) => (r.info.modules ?? []).filter((m) => !r.info.imported?.has(m) && m.ecosystem === 'nuget').map((m) => ({ package: m.package, version: m.version, line: m.line, file: r.file })));
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const usesDotnet = (results) => results.some((r) => (r.info.modules ?? []).some((m) => !r.info.imported?.has(m) && (m.ecosystem === 'dotnet' || m.ecosystem === 'nuget')));
|
|
44
|
+
|
|
45
|
+
const packageRefs = (packages) => {
|
|
46
|
+
const seen = new Map();
|
|
47
|
+
for (const p of packages) if (!seen.has(p.package)) seen.set(p.package, p.version);
|
|
48
|
+
return seen.size ? ` <ItemGroup>\n${[...seen].map(([n, v]) => ` <PackageReference Include="${n}" Version="${v}" />`).join('\n')}\n </ItemGroup>\n` : '';
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
const csproj = (major, packages = [], invariant = true) => `<Project Sdk="Microsoft.NET.Sdk">
|
|
35
52
|
<!-- Generated by the Thunder compiler. Build: dotnet build; run: dotnet bin/${ASSEMBLY}.dll (add "test" to run the tests). -->
|
|
36
53
|
<PropertyGroup>
|
|
37
54
|
<OutputType>Exe</OutputType>
|
|
@@ -40,7 +57,7 @@ const csproj = (major) => `<Project Sdk="Microsoft.NET.Sdk">
|
|
|
40
57
|
<RootNamespace>${ASSEMBLY}</RootNamespace>
|
|
41
58
|
<Nullable>disable</Nullable>
|
|
42
59
|
<ImplicitUsings>disable</ImplicitUsings>
|
|
43
|
-
<InvariantGlobalization
|
|
60
|
+
<InvariantGlobalization>${invariant}</InvariantGlobalization>
|
|
44
61
|
<SatelliteResourceLanguages>en</SatelliteResourceLanguages>
|
|
45
62
|
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
|
|
46
63
|
<NoWarn>CS0162;CS0168;CS0219;CS0472;CS1717;CS8321;CS0414</NoWarn>
|
|
@@ -49,7 +66,7 @@ const csproj = (major) => `<Project Sdk="Microsoft.NET.Sdk">
|
|
|
49
66
|
<ItemGroup>
|
|
50
67
|
<Compile Remove="bin/**;obj/**" />
|
|
51
68
|
</ItemGroup>
|
|
52
|
-
</Project>
|
|
69
|
+
${packageRefs(packages)}</Project>
|
|
53
70
|
`;
|
|
54
71
|
|
|
55
72
|
/** The C# for one program's results (src files, then test files) in `namespace`: { [module]: text }. */
|
|
@@ -84,6 +101,8 @@ export function writeCSharp(results, outDir, { entry = results.find((r) => r.kin
|
|
|
84
101
|
const files = compileCSharp(results);
|
|
85
102
|
for (const [m, text] of Object.entries(files)) writeFileSync(join(outDir, `${m}.cs`), text);
|
|
86
103
|
writeFileSync(join(outDir, 'ThunderRuntime.cs'), CS_RUNTIME);
|
|
104
|
+
if (usesDotnet(results)) writeFileSync(join(outDir, 'ThunderDotnet.cs'), CS_DOTNET);
|
|
105
|
+
else rmSync(join(outDir, 'ThunderDotnet.cs'), { force: true });
|
|
87
106
|
const code = runCode(results, entry, ASSEMBLY, 16);
|
|
88
107
|
writeFileSync(join(outDir, 'Program.cs'), `// Generated by the Thunder compiler: runs the program, or every Test block with "test".
|
|
89
108
|
using Thunder;
|
|
@@ -110,7 +129,7 @@ ${code.run}
|
|
|
110
129
|
}
|
|
111
130
|
}
|
|
112
131
|
`);
|
|
113
|
-
writeFileSync(join(outDir, `${ASSEMBLY}.csproj`), csproj(major));
|
|
132
|
+
writeFileSync(join(outDir, `${ASSEMBLY}.csproj`), csproj(major, nugetPackages(results), !usesDotnet(results)));
|
|
114
133
|
return Object.keys(files);
|
|
115
134
|
}
|
|
116
135
|
|
|
@@ -128,6 +147,8 @@ export function writeCSharpBatch(programs, outDir, { major = findDotnet().major
|
|
|
128
147
|
cases.push(` case ${i}:\n if (tests)\n {\n${code.tests}\n }\n else\n {\n${code.run}\n }\n break;`);
|
|
129
148
|
});
|
|
130
149
|
writeFileSync(join(outDir, 'ThunderRuntime.cs'), CS_RUNTIME);
|
|
150
|
+
const all = programs.flatMap((p) => p.results);
|
|
151
|
+
if (usesDotnet(all)) writeFileSync(join(outDir, 'ThunderDotnet.cs'), CS_DOTNET);
|
|
131
152
|
writeFileSync(join(outDir, 'Program.cs'), `// Generated by the Thunder compiler: many programs in one build, chosen by number.
|
|
132
153
|
using Thunder;
|
|
133
154
|
|
|
@@ -150,7 +171,7 @@ ${cases.join('\n')}
|
|
|
150
171
|
}
|
|
151
172
|
}
|
|
152
173
|
`);
|
|
153
|
-
writeFileSync(join(outDir, `${ASSEMBLY}.csproj`), csproj(major));
|
|
174
|
+
writeFileSync(join(outDir, `${ASSEMBLY}.csproj`), csproj(major, nugetPackages(all), !usesDotnet(all)));
|
|
154
175
|
}
|
|
155
176
|
|
|
156
177
|
/** dotnet build the project in `outDir` into outDir/bin. { ok, output } or { error } when there is no .NET SDK. */
|
package/src/core/diagnostics.mjs
CHANGED
|
@@ -51,6 +51,8 @@ export const CODES = {
|
|
|
51
51
|
TC405: 'A Python module ("Use") can be used only when compiling to Python',
|
|
52
52
|
TC406: 'A Screen is built only for React (--target react)',
|
|
53
53
|
TC407: 'A step that cannot run when a button is pressed',
|
|
54
|
+
TC408: 'An npm package ("Use … from npm") can be used only when compiling to TypeScript',
|
|
55
|
+
TC409: 'A .NET library ("Use … from .NET" or "from NuGet") can be used only when compiling to C#',
|
|
54
56
|
TC501: 'Divided by zero (runtime)',
|
|
55
57
|
TC502: 'Nothing used where a value was needed (runtime)',
|
|
56
58
|
TC503: 'A field or entry is missing (runtime)',
|
|
@@ -58,7 +60,7 @@ export const CODES = {
|
|
|
58
60
|
TC505: 'An Expect check failed (runtime)',
|
|
59
61
|
TC506: 'Values of different kinds were mixed (runtime)',
|
|
60
62
|
TC507: 'The program stopped with a message (runtime)',
|
|
61
|
-
TC508: '
|
|
63
|
+
TC508: 'Library code used through "Use" failed (runtime)',
|
|
62
64
|
TC509: 'A value could not be converted (runtime)',
|
|
63
65
|
};
|
|
64
66
|
|
package/src/core/engine-core.mjs
CHANGED
|
@@ -40,7 +40,7 @@ const MAX_RECORDED = 20000; // a recording stops growing here (and says so); the
|
|
|
40
40
|
/** The Python modules a program uses (Use), which this engine does not run. */
|
|
41
41
|
export function pythonModulesUsed(results) {
|
|
42
42
|
const out = [];
|
|
43
|
-
for (const r of results) for (const m of r.info.modules) if (!r.info.imported?.has(m)) out.push({ file: r.file, module: m.module, name: m.text ?? m.name, line: m.line });
|
|
43
|
+
for (const r of results) for (const m of r.info.modules) if (!r.info.imported?.has(m)) out.push({ file: r.file, module: m.module, name: m.text ?? m.name, line: m.line, ecosystem: m.ecosystem ?? 'python' });
|
|
44
44
|
return out;
|
|
45
45
|
}
|
|
46
46
|
|
|
@@ -48,6 +48,8 @@ export function pythonModulesUsed(results) {
|
|
|
48
48
|
export function refusalText(uses) {
|
|
49
49
|
const u = uses[0];
|
|
50
50
|
const more = uses.length > 1 ? ` (and ${uses.length - 1} more)` : '';
|
|
51
|
+
if (u.ecosystem === 'dotnet' || u.ecosystem === 'nuget') return `This program uses the .NET type "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it as C#: --target csharp.`;
|
|
52
|
+
if (u.ecosystem === 'npm') return `This program uses the npm package "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it as TypeScript: --target typescript.`;
|
|
51
53
|
return `This program uses the Python module "${u.module}" (${u.file}, line ${u.line})${more}. The Thunder engine runs Thunder only and never imitates a library, so run it with Python: leave out --engine thunder.`;
|
|
52
54
|
}
|
|
53
55
|
|
|
@@ -560,8 +562,21 @@ class Engine {
|
|
|
560
562
|
|
|
561
563
|
// ── public API ─────────────────────────────────────────────────────────────────────────────────────────────────
|
|
562
564
|
|
|
565
|
+
/**
|
|
566
|
+
* A program with problems is never run: running what did not compile could print a wrong answer, or pass a test
|
|
567
|
+
* that should fail. The CLI stops before this; this keeps every other caller (the site, OpenThunder) just as safe.
|
|
568
|
+
*/
|
|
569
|
+
function notCompiled(results) {
|
|
570
|
+
const bad = results.filter((r) => r && r.ok === false);
|
|
571
|
+
if (!bad.length) return null;
|
|
572
|
+
const lines = bad.flatMap((r) => (r.diagnostics ?? []).filter((d) => d.severity !== 'warning').map((d) => `${r.file ?? 'main.thunder'}, line ${d.line ?? '?'}: ${d.message} [${d.code}]`));
|
|
573
|
+
return { status: 2, stdout: '', stderr: `${lines.join('\n') || 'The program has problems'}\nNothing was run: fix the problems first.\n`, notCompiled: true, steps: [] };
|
|
574
|
+
}
|
|
575
|
+
|
|
563
576
|
/** The same, on the calling thread (its stack allows only a few hundred nested calls). */
|
|
564
577
|
export function runInProcess({ entry, cwd, deeper = false, readText = null } = {}) {
|
|
578
|
+
const broken = notCompiled([entry]);
|
|
579
|
+
if (broken) return broken;
|
|
565
580
|
const uses = pythonModulesUsed([entry]);
|
|
566
581
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
567
582
|
const eng = new Engine({ cwd, deeper, readText });
|
|
@@ -582,6 +597,8 @@ export function runInProcess({ entry, cwd, deeper = false, readText = null } = {
|
|
|
582
597
|
* Gives back { status, stdout, stderr, steps, truncated }. Like runInProcess, on the calling thread.
|
|
583
598
|
*/
|
|
584
599
|
export function recordedRun({ entry, cwd, readText = null } = {}) {
|
|
600
|
+
const broken = notCompiled([entry]);
|
|
601
|
+
if (broken) return broken;
|
|
585
602
|
const uses = pythonModulesUsed([entry]);
|
|
586
603
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses, steps: [] };
|
|
587
604
|
const eng = new Engine({ cwd, readText, record: true });
|
|
@@ -597,6 +614,8 @@ export function recordedRun({ entry, cwd, readText = null } = {}) {
|
|
|
597
614
|
|
|
598
615
|
/** The same, on the calling thread. */
|
|
599
616
|
export function testInProcess({ results, cwd, deeper = false, readText = null } = {}) {
|
|
617
|
+
const broken = notCompiled(results);
|
|
618
|
+
if (broken) return broken;
|
|
600
619
|
const uses = pythonModulesUsed(results);
|
|
601
620
|
if (uses.length) return { status: 2, stdout: '', stderr: `${refusalText(uses)}\n`, refused: uses };
|
|
602
621
|
const eng = new Engine({ cwd, deeper, readText });
|
package/src/core/go-run.mjs
CHANGED
|
@@ -10,15 +10,16 @@ import { spawnSync } from 'node:child_process';
|
|
|
10
10
|
import { fileURLToPath } from 'node:url';
|
|
11
11
|
import { tmpdir } from 'node:os';
|
|
12
12
|
import { toGo, pythonOnlyUses, id, goStr, goNamespaces as namespaces } from './target-go.mjs';
|
|
13
|
+
import { npmRefusals, dotnetRefusals } from './target-typescript.mjs';
|
|
13
14
|
import { diag } from './diagnostics.mjs';
|
|
14
15
|
|
|
15
16
|
export const GO_RUNTIME = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'runtime-go', 'thunder_runtime.go'), 'utf8');
|
|
16
17
|
|
|
17
18
|
/** TC405 for every Use in a file: Python modules exist only for the Python target. */
|
|
18
19
|
export function goDiagnostics(result) {
|
|
19
|
-
return pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
20
|
+
return [...npmRefusals(result.info, 'Go', diag), ...dotnetRefusals(result.info, 'Go', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
20
21
|
`"${u.module}" is a Python module, and this program is compiled to Go, which cannot use it.`,
|
|
21
|
-
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'));
|
|
22
|
+
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
|
|
22
23
|
}
|
|
23
24
|
|
|
24
25
|
|
package/src/core/java-run.mjs
CHANGED
|
@@ -7,7 +7,7 @@ import { writeFileSync, mkdirSync, readFileSync, rmSync, existsSync } from 'node
|
|
|
7
7
|
import { join, delimiter } from 'node:path';
|
|
8
8
|
import { spawnSync } from 'node:child_process';
|
|
9
9
|
import { toJava, javaTestRunner, javaClassName } from './target-java.mjs';
|
|
10
|
-
import { pythonOnlyUses } from './target-typescript.mjs';
|
|
10
|
+
import { pythonOnlyUses, npmRefusals, dotnetRefusals } from './target-typescript.mjs';
|
|
11
11
|
import { diag } from './diagnostics.mjs';
|
|
12
12
|
|
|
13
13
|
const RUNTIME_DIR = new URL('./java/thunder/', import.meta.url);
|
|
@@ -19,9 +19,9 @@ const exportedNames = (r) => [...r.info.records, ...r.info.funcs, ...r.info.cons
|
|
|
19
19
|
|
|
20
20
|
/** TC405 for every Use in a file: Python modules exist only for the Python target. */
|
|
21
21
|
export function javaDiagnostics(result) {
|
|
22
|
-
return pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
22
|
+
return [...npmRefusals(result.info, 'Java', diag), ...dotnetRefusals(result.info, 'Java', diag), ...pythonOnlyUses(result.info).map((u) => diag('TC405', u.line,
|
|
23
23
|
`"${u.module}" is a Python module, and this program is compiled to Java, which cannot use it.`,
|
|
24
|
-
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'));
|
|
24
|
+
'Build for Python (target = "python") to use Python modules. Thunder never swaps in a different library.'))];
|
|
25
25
|
}
|
|
26
26
|
|
|
27
27
|
/** Compile checked results to Java: { 'app/<Class>.java': text, 'app/RunTests.java': text }. */
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// What kind of .thunder file is this: a mission (a specification the compiler checks) or a Thunder Core program
|
|
2
|
+
// (code that runs)? Decided by a fixed rule, never by guessing, in this order:
|
|
3
|
+
// 1. thunder new, a thunder.toml in the file's folder or above it, or --core: a program (src/core/cli.mjs).
|
|
4
|
+
// 2. Otherwise the file's first line that is not blank or a comment decides. A mission always starts with one of
|
|
5
|
+
// the mission keywords, in lowercase, with at most a name after it ("mission Checkout", "service Billing",
|
|
6
|
+
// "use product"). A line that cannot start a mission ("say "Hello"", "Set total to 0", "To greet:",
|
|
7
|
+
// "A Trade has:", "Screen Today:", "Use csv as csv") means a program.
|
|
8
|
+
// 3. Anything that could be either (an empty file, or "use csv" alone) stays a mission, as before 1.7.
|
|
9
|
+
// Every mission written before this rule existed starts with a mission keyword, so none changes meaning.
|
|
10
|
+
|
|
11
|
+
/** The keywords a mission file's top-level blocks start with (the mission parser's own list, src/parse.mjs). */
|
|
12
|
+
export const MISSION_KEYWORDS = new Set([
|
|
13
|
+
'mission', 'note', 'goal', 'why', 'requires', 'requires_skill', 'demonstrates', 'input', 'output', 'guarantees',
|
|
14
|
+
'guarantee', 'never', 'constraints', 'invariant', 'assumptions', 'risks', 'target', 'style', 'verify', 'errors',
|
|
15
|
+
'examples', 'service', 'api', 'event', 'database', 'architecture', 'selection', 'use', 'title', 'for', 'persona',
|
|
16
|
+
'customer', 'problem', 'evidence', 'outcome', 'metric', 'scope', 'non_goal', 'owner', 'unknown', 'question',
|
|
17
|
+
'assumption', 'experience', 'pattern', 'style_intent', 'decision', 'property', 'scenario', 'evaluation',
|
|
18
|
+
'capability', 'interface', 'component', 'artifact', 'outcome_contract', 'release', 'result', 'learning', 'test',
|
|
19
|
+
'data', 'waiver', 'command', 'on', 'lifecycle', 'always', 'eventually', 'until', 'conflict', 'implement',
|
|
20
|
+
'requires_skills', 'approval', 'inferred', 'maps_to', 'needs_review', 'source', 'confidence',
|
|
21
|
+
]);
|
|
22
|
+
|
|
23
|
+
/** The first line of `source` that is not blank or a comment, or null. */
|
|
24
|
+
export function firstCodeLine(source) {
|
|
25
|
+
for (const raw of String(source).split(/\r?\n/)) {
|
|
26
|
+
const line = raw.trim();
|
|
27
|
+
if (line && !line.startsWith('#')) return { text: line, indented: raw.length > 0 && /^\s/.test(raw) };
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 'mission' or 'program', from the file's text alone (rule 2 and 3 above), with the reason in words so a person
|
|
34
|
+
* can see why: { kind, reason }.
|
|
35
|
+
*/
|
|
36
|
+
export function fileKind(source) {
|
|
37
|
+
const first = firstCodeLine(source);
|
|
38
|
+
if (!first) return { kind: 'mission', reason: 'the file has no lines yet' };
|
|
39
|
+
const m = /^([a-z_]+)(?:\s+([A-Za-z_][\w.-]*))?\s*$/.exec(first.text);
|
|
40
|
+
if (!first.indented && m && MISSION_KEYWORDS.has(m[1])) return { kind: 'mission', reason: `its first line starts with the mission keyword "${m[1]}"` };
|
|
41
|
+
return { kind: 'program', reason: `its first line ("${first.text.length > 40 ? `${first.text.slice(0, 40)}…` : first.text}") cannot start a mission` };
|
|
42
|
+
}
|
package/src/core/parser.mjs
CHANGED
|
@@ -201,7 +201,8 @@ function paramGroups(ts) {
|
|
|
201
201
|
if (n > 3 && isWord(inner[n - 3], 'if') && isWord(inner[n - 2], 'not') && isWord(inner[n - 1], 'given')) { defaultTokens = inner.slice(0, -3); g = g.slice(0, open); }
|
|
202
202
|
}
|
|
203
203
|
const k = g.findIndex((t) => isWord(t, 'as'));
|
|
204
|
-
|
|
204
|
+
const raw = k < 0 ? g : g.slice(0, k);
|
|
205
|
+
return { words: stripArticle(raw), raw, typeTokens: k < 0 ? null : g.slice(k + 1), defaultTokens };
|
|
205
206
|
});
|
|
206
207
|
}
|
|
207
208
|
|
|
@@ -638,7 +639,12 @@ function fillBlock(open, lines, n, ep, names) {
|
|
|
638
639
|
|
|
639
640
|
function nameWords(ts, line, what) {
|
|
640
641
|
const words = stripArticle(ts);
|
|
641
|
-
if (!words.length)
|
|
642
|
+
if (!words.length) {
|
|
643
|
+
// The name was only "a", "an", or "the": Thunder skips those words in a name ("the total" is "total").
|
|
644
|
+
const only = ts.length === 1 && ts[0].t === 'word' ? ts[0].text : null;
|
|
645
|
+
if (only) throw new CoreError(diag('TC108', line, `"${only}" can't be a name on its own: Thunder skips "a", "an", and "the" in names ("the total" is "total").`, `Use a word that says what it holds, like "first number" or "amount".`));
|
|
646
|
+
throw new CoreError(diag('TC108', line, `${what} is missing a name.`));
|
|
647
|
+
}
|
|
642
648
|
for (const t of words) {
|
|
643
649
|
if (t.t !== 'word') throw new CoreError(diag('TC105', line, `A name can only use words, but "${show(t)}" is not a word.`));
|
|
644
650
|
if (RESERVED.has(t.lower)) throw new CoreError(diag('TC202', line, `A name can't contain the word "${t.text}", because it belongs to Thunder.`, `Try a name without "${t.text}".`));
|
|
@@ -735,7 +741,7 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
735
741
|
let r = 0;
|
|
736
742
|
while (kids[r] && isWord(kids[r].tokens[0], 'receive')) {
|
|
737
743
|
const kid = kids[r];
|
|
738
|
-
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.
|
|
744
|
+
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.raw, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
|
|
739
745
|
r++;
|
|
740
746
|
}
|
|
741
747
|
bodyNodes = kids.slice(r);
|
|
@@ -770,12 +776,53 @@ function parseStatement(n, ep, names, diagnostics, ctx, siblings) {
|
|
|
770
776
|
if (w0 === 'never') return parseNever(ts, line, ep);
|
|
771
777
|
if (w0 === 'use') {
|
|
772
778
|
if (!ctx.top) fail('TC402', '"Use" must be written at the left edge of the file.');
|
|
779
|
+
// Use <python module> [from Python] [as <name>] or Use "<npm package>" from npm as <name>
|
|
780
|
+
// or Use "<.NET type>" from .NET as <name> or Use "<.NET type>" from NuGet "<package>" version "<v>" as <name>
|
|
773
781
|
const asAt = rest.findIndex((t) => isWord(t, 'as'));
|
|
774
|
-
|
|
782
|
+
let modTs = asAt < 0 ? rest : rest.slice(0, asAt);
|
|
783
|
+
const fromAt = modTs.findIndex((t) => isWord(t, 'from'));
|
|
784
|
+
let ecosystem = 'python';
|
|
785
|
+
if (fromAt >= 0) {
|
|
786
|
+
const eco = modTs.slice(fromAt + 1);
|
|
787
|
+
const plain = (t) => t && typeof t.parts === 'undefined' ? null : t && t.parts.every((x) => typeof x === 'string') ? t.parts.join('') : null;
|
|
788
|
+
const word0 = eco[0]?.t === 'word' ? eco[0].text.toLowerCase() : '';
|
|
789
|
+
let said = eco.length === 1 && eco[0].t === 'word' ? word0 : '';
|
|
790
|
+
// ".NET" is read as a dot and the word NET.
|
|
791
|
+
if (eco.length === 2 && eco[0].t === 'sym' && eco[0].text === '.' && eco[1].t === 'word' && eco[1].text.toLowerCase() === 'net') said = 'dotnet';
|
|
792
|
+
if (word0 === 'nuget') {
|
|
793
|
+
// NuGet "<package>" version "<version>": the package and its exact version, so every build gets the same code.
|
|
794
|
+
const pkg = eco[1]?.t === 'str' ? plain(eco[1]) : null;
|
|
795
|
+
const ver = isWord(eco[2], 'version') && eco[3]?.t === 'str' ? plain(eco[3]) : null;
|
|
796
|
+
if (!pkg || !ver || eco.length !== 4 || !/^[A-Za-z0-9_.-]+$/.test(pkg) || !/^\d+(\.\d+){1,3}([-+][\w.-]+)?$/.test(ver)) fail('TC108', 'Name the NuGet package and its version: Use "Humanizer.NumberToWordsExtension" from NuGet "Humanizer.Core" version "2.14.1" as words.');
|
|
797
|
+
said = 'nuget';
|
|
798
|
+
modTs = modTs.slice(0, fromAt);
|
|
799
|
+
ecosystem = said;
|
|
800
|
+
var nuget = { package: pkg, version: ver };
|
|
801
|
+
} else {
|
|
802
|
+
if (!['python', 'npm', 'dotnet'].includes(said)) fail('TC108', `A library comes from Python, npm, .NET, or NuGet, for example: Use csv from Python as csv, Use "date-fns" from npm as dates, or Use "System.IO.Path" from .NET as paths.`);
|
|
803
|
+
ecosystem = said;
|
|
804
|
+
modTs = modTs.slice(0, fromAt);
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
if (ecosystem === 'dotnet' || ecosystem === 'nuget') {
|
|
808
|
+
const t = modTs[0];
|
|
809
|
+
const type = modTs.length === 1 && t.t === 'str' && t.parts.every((x) => typeof x === 'string') ? t.parts.join('') : null;
|
|
810
|
+
if (type == null || !/^[A-Za-z_]\w*(\.[A-Za-z_]\w*)+$/.test(type)) fail('TC108', 'Write a .NET type with its namespace, in quotes, for example: Use "System.IO.Path" from .NET as paths.');
|
|
811
|
+
if (asAt < 0) fail('TC108', `Give the type a name to use in Thunder: Use "${type}" from ${ecosystem === 'nuget' ? 'NuGet' : '.NET'} … as <name>.`);
|
|
812
|
+
return { k: 'use', module: type, ecosystem, ...(ecosystem === 'nuget' ? nuget : {}), ...nameWords(rest.slice(asAt + 1), line, '"Use"'), line };
|
|
813
|
+
}
|
|
814
|
+
if (ecosystem === 'npm' || modTs[0]?.t === 'str') {
|
|
815
|
+
const t = modTs[0];
|
|
816
|
+
const pkg = modTs.length === 1 && t.t === 'str' && t.parts.every((x) => typeof x === 'string') ? t.parts.join('') : null;
|
|
817
|
+
if (pkg == null || !/^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(\/[\w.-]+)*$|^node:[a-z_/]+$/i.test(pkg)) fail('TC108', 'Write an npm package in quotes, for example: Use "date-fns" from npm as dates.');
|
|
818
|
+
if (ecosystem !== 'npm') fail('TC108', `Say where "${pkg}" comes from: Use "${pkg}" from npm as <name>.`);
|
|
819
|
+
if (asAt < 0) fail('TC108', `Give the package a name to use in Thunder: Use "${pkg}" from npm as <name>.`);
|
|
820
|
+
return { k: 'use', module: pkg, ecosystem, ...nameWords(rest.slice(asAt + 1), line, '"Use"'), line };
|
|
821
|
+
}
|
|
775
822
|
const module = modTs.map((t) => (t.t === 'word' ? t.text : t.t === 'sym' && t.text === '.' ? '.' : '\u0000')).join('');
|
|
776
|
-
if (!module || module.includes('\u0000') || !/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/.test(module)) fail('TC108', 'Write "Use <python module> as <name>", for example: Use csv as csv.');
|
|
823
|
+
if (!module || module.includes('\u0000') || !/^[A-Za-z_][\w]*(\.[A-Za-z_][\w]*)*$/.test(module)) fail('TC108', 'Write "Use <python module> as <name>", for example: Use csv as csv. For npm: Use "date-fns" from npm as dates.');
|
|
777
824
|
const alias = asAt < 0 ? { name: module.split('.')[0].toLowerCase(), text: module.split('.')[0] } : nameWords(rest.slice(asAt + 1), line, '"Use"');
|
|
778
|
-
return { k: 'use', module, ...alias, line };
|
|
825
|
+
return { k: 'use', module, ecosystem, ...alias, line };
|
|
779
826
|
}
|
|
780
827
|
if (w0 === 'test') {
|
|
781
828
|
if (!ctx.top) fail('TC402', 'A "Test" block must be written at the left edge of the file.');
|
|
@@ -901,7 +948,7 @@ function parseScreen(n, ep, names, diagnostics) {
|
|
|
901
948
|
while (kids[k] && isWord(kids[k].tokens[0], 'receive')) {
|
|
902
949
|
const kid = kids[k];
|
|
903
950
|
try {
|
|
904
|
-
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.
|
|
951
|
+
params.push(...paramGroups(kid.tokens.slice(1)).map((p) => ({ ...nameWords(p.raw, kid.line, '"Receive"'), type: p.typeTokens ? typeOf(ep, p.typeTokens, kid.line) : null, dflt: p.defaultTokens ? ep.parse(p.defaultTokens, kid.line) : null, line: kid.line })));
|
|
905
952
|
} catch (e) { if (e instanceof CoreError) diagnostics.push(e.diagnostic); else throw e; }
|
|
906
953
|
k++;
|
|
907
954
|
}
|