@skillstech/thunderlang 1.0.4 → 1.1.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 +140 -0
- package/dist/core.cjs +2568 -462
- package/dist/index.cjs +7562 -5084
- package/dist/learn.cjs +1963 -315
- package/intent-graph.schema.json +11 -0
- package/package.json +6 -2
- package/src/cli.mjs +141 -58
- package/src/codegen.mjs +145 -55
- package/src/conformance.mjs +15 -6
- package/src/core/check.mjs +725 -0
- package/src/core/cli.mjs +133 -0
- package/src/core/diagnostics.mjs +81 -0
- package/src/core/format.mjs +20 -0
- package/src/core/from-python.mjs +645 -0
- package/src/core/index.mjs +38 -0
- package/src/core/lexer.mjs +115 -0
- package/src/core/parser.mjs +742 -0
- package/src/core/project.mjs +167 -0
- package/src/core/round-trip.mjs +150 -0
- package/src/core/runtime-python.mjs +801 -0
- package/src/core/target-python.mjs +486 -0
- package/src/core.d.ts +5 -2
- package/src/core.mjs +5 -2
- package/src/data-schema.mjs +8 -1
- package/src/emit.mjs +1 -1
- package/src/evidence.mjs +1 -1
- package/src/expr.mjs +81 -4
- package/src/form-words.mjs +2 -0
- package/src/index.d.ts +8 -1
- package/src/index.mjs +5 -1
- package/src/intent-schema.mjs +1 -0
- package/src/mcp.mjs +23 -0
- package/src/meaning.mjs +45 -6
- package/src/model.d.mts +7 -3
- package/src/model.mjs +19 -6
- package/src/money.d.mts +18 -0
- package/src/money.mjs +124 -0
- package/src/plain-contract.mjs +18 -2
- package/src/read.d.mts +11 -0
- package/src/read.mjs +40 -6
- package/src/review-comment.d.mts +16 -0
- package/src/review-comment.mjs +145 -0
- package/src/say-less.mjs +1432 -0
- package/src/system.mjs +153 -44
- package/src/target-cs.mjs +39 -34
- package/src/target-elixir.mjs +40 -30
- package/src/target-go.mjs +41 -36
- package/src/target-java.mjs +34 -27
- package/src/target-kotlin.mjs +43 -35
- package/src/target-py.mjs +57 -55
- package/src/target-result.d.mts +48 -0
- package/src/target-result.mjs +112 -0
- package/src/target-rust.mjs +42 -38
- package/src/target-scala.mjs +45 -35
- package/src/target-ts.mjs +37 -45
- package/src/target-types.mjs +41 -5
- package/src/target-util.mjs +55 -2
- package/src/trace-cli.mjs +58 -0
- package/src/trace-fs.mjs +76 -0
- package/src/trace.mjs +261 -0
- package/src/translate.d.mts +3 -0
- package/src/translate.mjs +62 -32
- package/src/why-cli.mjs +31 -0
- package/src/why.d.mts +28 -0
- package/src/why.mjs +532 -0
- package/src/write-steps.mjs +22 -5
package/src/expr.mjs
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
// unary := '-' unary | primary
|
|
14
14
|
// primary := number | string | bool | ident(.ident)* | '(' or ')' | '[' list ']'
|
|
15
15
|
|
|
16
|
+
import { moneyLiteral, moneyCompare, numberToDecimalText, MONEY_TYPES } from './money.mjs';
|
|
17
|
+
|
|
16
18
|
export class ExprError extends Error {}
|
|
17
19
|
|
|
18
20
|
const OPS = ['>=', '<=', '==', '!=', '&&', '||', '>', '<', '=', '+', '-', '*', '/', '%', '!', '(', ')', '[', ']', ','];
|
|
@@ -155,6 +157,10 @@ function evalNode(n, inputs) {
|
|
|
155
157
|
case 'neg': { const r = -Number(evalNode(n.a, inputs)); return Number.isFinite(r) ? r : null; }
|
|
156
158
|
case 'arith': {
|
|
157
159
|
const a = Number(evalNode(n.a, inputs)); const b = Number(evalNode(n.b, inputs));
|
|
160
|
+
// Thunder numbers are decimals: + - * are exact on decimal operands (0.1 + 0.2 == 0.3), so a
|
|
161
|
+
// money or percentage rule never decides on a binary floating point artefact.
|
|
162
|
+
const exact = decimalArith(n.op, a, b);
|
|
163
|
+
if (exact !== null) return exact;
|
|
158
164
|
const r = n.op === '+' ? a + b : n.op === '-' ? a - b : n.op === '*' ? a * b : n.op === '/' ? a / b : a % b;
|
|
159
165
|
// Non-finite results (divide/modulo by zero, NaN from non-numeric operands) are
|
|
160
166
|
// neutralized to null so they can never leak a surprising truthy comparison (e.g.
|
|
@@ -184,6 +190,36 @@ function evalNode(n, inputs) {
|
|
|
184
190
|
}
|
|
185
191
|
}
|
|
186
192
|
|
|
193
|
+
// Exact decimal + - * for finite numbers whose shortest decimal text has no exponent: scale both to
|
|
194
|
+
// integers (BigInt), operate, and scale back. Returns null when the operands are not plain decimals
|
|
195
|
+
// (the caller then uses ordinary number arithmetic) or the operator is / or %.
|
|
196
|
+
const PLAIN_DECIMAL = /^(-)?(\d+)(?:\.(\d+))?$/;
|
|
197
|
+
function decimalParts(x) {
|
|
198
|
+
if (!Number.isFinite(x)) return null;
|
|
199
|
+
const m = String(x).match(PLAIN_DECIMAL);
|
|
200
|
+
if (!m) return null;
|
|
201
|
+
const frac = m[3] || '';
|
|
202
|
+
const int = BigInt(m[2] + frac);
|
|
203
|
+
return { int: m[1] ? -int : int, scale: frac.length };
|
|
204
|
+
}
|
|
205
|
+
function decimalArith(op, a, b) {
|
|
206
|
+
if (op !== '+' && op !== '-' && op !== '*') return null;
|
|
207
|
+
const x = decimalParts(a); const y = decimalParts(b);
|
|
208
|
+
if (!x || !y) return null;
|
|
209
|
+
let int; let scale;
|
|
210
|
+
if (op === '*') { int = x.int * y.int; scale = x.scale + y.scale; }
|
|
211
|
+
else {
|
|
212
|
+
scale = Math.max(x.scale, y.scale);
|
|
213
|
+
const xi = x.int * 10n ** BigInt(scale - x.scale); const yi = y.int * 10n ** BigInt(scale - y.scale);
|
|
214
|
+
int = op === '+' ? xi + yi : xi - yi;
|
|
215
|
+
}
|
|
216
|
+
const neg = int < 0n;
|
|
217
|
+
const digits = (neg ? -int : int).toString().padStart(scale + 1, '0');
|
|
218
|
+
const text = scale ? `${digits.slice(0, -scale)}.${digits.slice(-scale)}` : digits;
|
|
219
|
+
const r = Number(`${neg ? '-' : ''}${text}`);
|
|
220
|
+
return Number.isFinite(r) ? r : null;
|
|
221
|
+
}
|
|
222
|
+
|
|
187
223
|
function eq(a, b) {
|
|
188
224
|
const na = asNum(a); const nb = asNum(b);
|
|
189
225
|
if (na != null && nb != null) return na === nb;
|
|
@@ -219,9 +255,47 @@ const DIALECTS = {
|
|
|
219
255
|
elixir: { and: (a, b) => `(${a} and ${b})`, or: (a, b) => `(${a} or ${b})`, not: (a) => `(not ${a})`, bool: (v) => String(v), eq: (a, b) => `${a} == ${b}`, neq: (a, b) => `${a} != ${b}`, inList: (list, x) => `${x} in [${list.join(', ')}]`, nil: 'nil' },
|
|
220
256
|
};
|
|
221
257
|
|
|
222
|
-
|
|
258
|
+
// The literal decimal text of a numeric literal node (or a negated one), or null.
|
|
259
|
+
function literalDecimal(n) {
|
|
260
|
+
if (n.k === 'lit' && typeof n.v === 'number') return numberToDecimalText(n.v);
|
|
261
|
+
if (n.k === 'neg' && n.a.k === 'lit' && typeof n.a.v === 'number') return `-${numberToDecimalText(n.a.v)}`;
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function renderExpr(src, inputs, D, money = {}, dialect = 'js') {
|
|
223
266
|
const known = new Set(inputs);
|
|
267
|
+
const isMoney = (n) => n.k === 'ref' && Object.prototype.hasOwnProperty.call(money, n.path);
|
|
268
|
+
const moneyRefs = (n, out = []) => {
|
|
269
|
+
if (isMoney(n)) out.push(n.path);
|
|
270
|
+
else if (n.k === 'arith' || n.k === 'cmp') { moneyRefs(n.a, out); moneyRefs(n.b, out); }
|
|
271
|
+
else if (n.k === 'neg') moneyRefs(n.a, out);
|
|
272
|
+
return out;
|
|
273
|
+
};
|
|
274
|
+
// A comparison that involves a Money input renders with the target's exact Money type. Each side
|
|
275
|
+
// may be a Money input, an amount such as 12.30, or a sum/difference of those (exact in every Money
|
|
276
|
+
// representation). Anything else (multiplication, division, mixing currencies) is refused.
|
|
277
|
+
const moneyCmp = (n) => {
|
|
278
|
+
if (!MONEY_TYPES[dialect]) throw new ExprError(`Money inputs have no exact representation in this target yet, and Thunder will not compare money as binary floating point`);
|
|
279
|
+
const refs = moneyRefs(n);
|
|
280
|
+
const units = money[refs[0]];
|
|
281
|
+
const other = refs.find((p) => money[p] !== units);
|
|
282
|
+
if (other) throw new ExprError(`"${refs[0]}" and "${other}" are Money with different minor units (different currencies)`);
|
|
283
|
+
const side = (x) => {
|
|
284
|
+
if (isMoney(x)) return x.path;
|
|
285
|
+
const dec = literalDecimal(x);
|
|
286
|
+
if (dec != null) { try { return moneyLiteral(dialect, dec, units); } catch (e) { throw new ExprError(e.message); } }
|
|
287
|
+
if (x.k === 'arith' && (x.op === '+' || x.op === '-')) {
|
|
288
|
+
const a = side(x.a); const b = side(x.b);
|
|
289
|
+
if (dialect === 'java') return `${a}.${x.op === '+' ? 'add' : 'subtract'}(${b})`;
|
|
290
|
+
return `(${a} ${x.op} ${b})`;
|
|
291
|
+
}
|
|
292
|
+
throw new ExprError(`Money can only be compared with Money inputs, amounts such as 12.30, or their sums and differences; multiplication, division, and other computed values are not translated exactly`);
|
|
293
|
+
};
|
|
294
|
+
return moneyCompare(dialect, n.op, side(n.a), side(n.b));
|
|
295
|
+
};
|
|
224
296
|
const r = (n) => {
|
|
297
|
+
if (n.k === 'cmp' && moneyRefs(n).length) return moneyCmp(n);
|
|
298
|
+
if (isMoney(n)) throw new ExprError(`Money input "${n.path}" is used outside a comparison (arithmetic, lists, or yes/no use are not translated exactly)`);
|
|
225
299
|
switch (n.k) {
|
|
226
300
|
case 'or': return D.or(r(n.a), r(n.b));
|
|
227
301
|
case 'and': return D.and(r(n.a), r(n.b));
|
|
@@ -274,10 +348,13 @@ export function simplifyExpr(src) {
|
|
|
274
348
|
/**
|
|
275
349
|
* Render a `when` condition as an equivalent expression in a target language, for code generation.
|
|
276
350
|
* Input names render as identifiers; any other bare token is an enum literal (a string). Reuses
|
|
277
|
-
* the parser, so precedence is exact. `dialect` is js (default) | csharp | java
|
|
351
|
+
* the parser, so precedence is exact. `dialect` is js (default) | csharp | java | python | go | rust |
|
|
352
|
+
* kotlin | scala | elixir. `money` maps Money input names to their minor units; comparisons on them
|
|
353
|
+
* render with the target's exact Money type (money.mjs), and any other use throws ExprError.
|
|
278
354
|
*/
|
|
279
|
-
export function exprToCode(src, { inputs = [], dialect = 'js' } = {}) {
|
|
280
|
-
|
|
355
|
+
export function exprToCode(src, { inputs = [], dialect = 'js', money = {} } = {}) {
|
|
356
|
+
const d = DIALECTS[dialect] ? dialect : 'js';
|
|
357
|
+
return renderExpr(src, inputs, DIALECTS[d], money || {}, d);
|
|
281
358
|
}
|
|
282
359
|
export const exprToJs = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'js' });
|
|
283
360
|
export const exprToCSharp = (src, opts = {}) => exprToCode(src, { ...opts, dialect: 'csharp' });
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// Generated by scripts/form-words.mjs from the step readers' fixed wording. Do not edit by hand.
|
|
2
|
+
export const FORM_WORDS = new Set("abort about above acc accepted access account accountsfor across act action actions active actives actor ad add added adding address adds admin administrator after afterall aftereach again against agrees ahead aks alias alignas alignof all allowed allows allsteps alone along alongside also alter always amazon amount an analytics and andor andorsteps annotateroutes annotation annotations announces another ansible answer answers any anything anywhere api app appending applies apply approves appservice are arg args argsat argsof argument arguments argv arith arithsays arithwords arm armexpr arms armsays armssubject around arr array arraylist arrives arrow arrowparam arrowre as ascall ascodewords asg aside asking asks asm assert assign assigned assignedto assignment assigns assignsteps assignwords associatedtype async asyncsession at atom attachclause attaches attr attribute attributes auth author auto available average await away aws az azure ba back background backs backticks backup bad badgateway badge badrequest balance balanced balancedreturnhead balancedtext balancer band bang bar bare base based baseline basync bb bbetween bc bdo be become becomes before beforeall beforebare beforeeach begin being belong below belse belseif bench berrors besides best between bfor bhandler bif big bigint bin binds bis bits blank blankcalls blanked blankpreprocessor blankstrings blet blk blob block blockat blocked blockend blocks bmethod bnot bo bodies bodiless body bodyrange bodystart book books bool boolean bor both bottom brace braces bracetextwithvalues bracewords bracket brackets bracketsclosed branch branches break brings bthen bucket build building builds built builtin bulk bus buse but bwhere by byname byte cache calculation call callable callargs callback called callee caller calling callnoun callof calls callverb can cancellationtoken cancelled cancels cannot cannotfail cap capital captures card carries carry case casebreaks caselabel cases cast cat catch catchall catches categories caught caused ccontainer cd cdecl cdeclaration cerr cfg ch chain chained change changed changes changing channel char character characters charat chars chart charts chead check checked checknotnull checkpoint checkpoints checks children choice choices choose chooser chooses choosing chr claim class classes classifystatement classifywords classname clause clausehead clausekids clauses clean cleancheader cleandoc cleans cleansteps clears cli click client clip clog close closed closein closeof closes closing closure closurehead closures cloud cloudformation cloudfront cloudwatch cls cluster cmd cmdlets cmds cmp cnormalize co code codeexpr codeof col collapsed collect collection colon column columns come comes command commandcalledas commands comment comments commit commits committed common compare compares comparison comparisons compile compiled completely completenessof compose compound computed cond condition conditions condjs condsaid condt condwords config configureawait confirm confirms conflict conn connected connection connects const consteval constexpr constinit constructor cont contain container containers content contents context continuation continuations continue continues control controller convenience conversion convert copies copy cosmos could count countable counted counting counts cout cpp crate create created createdataction createdatroute creates creturntype csays cstyle csuffixok csv ct ctor ctrl ctx ctype cur curl current cursor da daemon dashed data database date datetime db dbcc dbcontext dbl deallocate debounce debugging debugprint debugs decimal decision decisionof declaration declarations declare declared declares declspec decltype decodes decorator decorators def default defer defined definefunction defineproperty defines definething definition definitions deinit delete deletes delim delivery deliveryfee deny depends deploying deployment deploys deprecate deprecated deps depth desc descending describe detached detaches detail detailed details dev dfr di dialect dialects dict dictionary did didset dies differ different diouxxeeffggaacspn dir directory disconnects display displaylabel diusc divided divides dividing do doas doc docabove docker dockerfile docline docstring docstrings does dollar done double doubled down downloads dprintf dq drawn draws drop drops due dur dw dyn dynamic dynamodb ea each early easy eb ec echo ecr ecs ed edits ee eennbbxx effect eks elif eligible elixir else elseat elseif elsif elvis email empties empty enabled encodes end endline ends endswith enforces english ensure enters entries entry enum enumerable enumerated enums env environment eo err error errorf errors esc escapes eval even event eventhubs every everyday everything ex exact exactly example examples excel except excepted exchange exec execute executed exist existing exists exit exitcode expands expect explained explains explicit export exported exports expr express expression exprsteps extension extern extof extra exts fa fact fail failcode failed failnow fails failure faithfulness fakes fallback fallbackwords fallsthrough fallthrough false family far fastify fastifyreply fastifyrequest fatal fatalf fb fd fdescribe fee fetch ffddmmll field fields file fileprivate files fills filter final finally find findcfunctions findindex finds findswiftfunctions finish finished finishes first firstargs firstblock firststring firsttext fits fix fixed fixedof fixes flags flat flatmap float fmt fmtat fn fname fnidx fnline fnre fns fnsteps fnvalue folder folders follows foo fooled for forbidden force forceinline foreach forgets form format formats forms formula forward forwardref found fprintf fputs frame framework frees friend from front full fully fun func function functions fv gate gated gateway gc generic get getopts gets getter gg gi gim git give given gives givevalue giving glob global globals globby gm go goes going gone google got goto gradle grant grants graph grep group groupcases grouped grouping groupop groups grows gt guard had halt handle handler handlers handles handling hands happens has hash hashset hashtable hasown hastext have having head header headerdoc headers headline headof hello helm helper helptext here hh hides highest history hit hold holds home hour how hs htmlresponse http httpcontext httperrorof httpfail httprequest httpresponse httpservletrequest hubs iam id identity idioms idx if ifchain ifsteps ignores ignoring ilnow ilogger im image images impl implemented implicitreturn import imports in iname inat include included includes inclusive indentedjson index indexedwords indexof inferred init initialize initializer inl inline inlineelse inlinekid inner innere innernote inners input inputs inputsof insert insertcode inserted insertgetid insertname inside inspects installed installing installs instanceof int integer interesting interface internal internalservererror interrupt intest into intoalways invisible ioexception ip is isarray iscode iscodewords isdef isdevnull isglob isid isinstance islast isop isp isplumbing isset isspace istest isvar isw it item items iter iterable its itself iw java javascript jmp job jobs join joincontinued joined joinedtext joins joinword jscontext jsmorefunctions json jsonify jsonresponse jump jumps just kb keep keepat keeping keeps kept key keyboard keys keyvault keyword kid kids kill kind kinds kindwords know known knows knowsfrom koa kotlin kotlinexprend kotlinpattern kotlinterminate kotlinwhenarms kt kubectl kubernetes kv kw label labels lambda lang language languages lapply large larger largest last lastcmd lastexitcode lastindex lastindexof lastn lastop lastseg laststeps lastval lastwords late later latest lead leadingdoc least leave leaves left len length less let lets letter letters letting level lex lexsql lgl lhs lib library librarystep licence like limits line lineat linedoc linefinder lines link linked links list listargs listed lists listwords lit literal literalpath literals live ll load loads local location lock locks lodash log logger logging logic logical login logs long longer looking looks lookup loop loopofapply lower lowest ls lv machine macro macros made make makereader makes makestepper makestype managed management manager many map mapcode mapping mapply mark marked marks maskcode masked match matchall matchclose matched matches matching matchingclose matchparen math matters maven max may meaning measures media member memberranges memo memoize memory memset mentions merge merges merging message messageof messages method methodnotallowed methods methodsfrom microsoft mid middle middleware millisecond min minute missing mistake mistakes mjs mls model modify module modulemember modules monitor more most mounts move moved moves msg multiplies must mut mutable mutating my mysql na name nameat named names namespace namespaces nametok native nc nee needed needs neg negate negation negations nest nested nestedstep net network never new newer next nextfunction nextkind nextrequest nexttok nil nk nl nm no nocontent node nodecond nodes nodesteps noexcept noglob nohup none nonisolated nonnull noreturn norm normalizephp not note noteerrors notes notfound nothing notimplemented notnull noun nsg nslog null nullptr num number numbers numeric nx obj objclose object objectkeys objects objopen of off offsets og ok old older on once one oneline onevalue online only onshelf op open opened openers opens openssl operator operators ops opt optimizes option options opts or order ordered original orjsonresponse other others otherwise otherwiseline out outer outes output outputs outputwords outside over overdue override own owner pa package packages packs page paid pair paired panic para paragraph param parameter parameters params paramsclose paramsof paramsopen paramtext paren parent parentheses parentof parse parseexpr parseparams parsestatement part partly parts partsof pass passedto passes password past pat patch path pats pattern patterns pauses payload payloadtoolarge payloadwords payment paymentrequired pclose pending per perror person pester pg pgsql php phphashcomments pick picks pieces pings pipe pipeline pipelines pipelinesteps pl place placeholder plain plainenums plainname plaintextresponse plan playbook plumber plumbing plural pode pointer points pop popd popen port pos position positional positions possessivewords post postgresql power powershell powershellreading pre pred prefix prefixof prepared prepares preprocessor prev previous principal print printed printf printftext println prints prisma private procedures process processes prog program programs progress project prompt prop properties props protected protects protocol prototype ps pscommandpath psitem psscriptroot psthings ptr public publishes punc punct purges purrr push pushd put puts pv pw pwd py pybalanced pydocstring pyheader python qualifier query question questions queue quick quietly quote quoted quotedbody quotes raise raiserror raises random range ranges rangewords rare rasg rather raw rawt rawv rds re react read readable readableshare reader reading readinglanguage readkotlinif readonly reads ready real rearranges reason reasons receives recognize recognizes reconfigure record records redirect redirectof redirecttarget redirs redirwords redis redo redoes reduce references regexp register registers registration registry release releases reloads relying remainder remembering remembers remote remove removed removes renames renews repairs repeat repeated repeating repeats repl replace replaced replaces replays replof reply reports repositories repository representation req request requestidioms requests require required requirement requirenamespace requirenotnull requires res rescue resets reshapes resizes resource resources resp responds response responseentity responseof responsewriter rest restarts restate restated restates restore restores result results resumes ret retention retry return returned returns returnstep reverse revoke revokes rg rhs right ro role rollback rolling rolls rotates round roup route routefor router routeres routes routine row rows rq rr rreading rruu rscript rthings rtype ruby rule rules run running runs rust rv rw rwords safe safely said same sametype sapply save saved saves saving say sayarithmetic sayatom sayatomwords saycall saychain sayclibrary saycodecondition saycommand saycommon sayexactly saylibrarycall saylogic saynativeshape saynode saypython says sayvalue saywhether sayword scala scalar scale scales scaling scheduled scoped scopes scrambled scrambles screen script scriptparams scriptpath search searches second secret secrets sections security see seed seeing sees seg select selectcasesays selector self semi semicolons send sending sends sent sentence sentstep separate seq sequelize server serverrequest service servicebus services serviceunavailable servlet session set setclass setgeneric setmethod setopt setotherwise setpair setrefclass sets setting settings setup setvalidity several sh shape shapes share shares shebang shelf shell shellcheck shellreading shellwordsof shift short shortcut should show showing shown shows side sig sign signal signals signature signed signing signs sigs sil simple simplesays simplesaysinner single size sizeof skip skipbalanced skipparens skipped skips skipstring slash slice slots sm small smallest sn snprintf sns so some something sort sorts source sp space spaces span spanof special specify spelled spells splat splice split splitcomma splitlogic splits splitshift splitstatements splittop splittopargs spread sql sqlcondition sqllogicname sqltextwords sqs src ss ssh st stack stage standard start startat starting startline starts startswith startvalue state stateful statement statementexpr statements static status statusof stay stays std stderr step steps stepsfrom stepsin stepsofbody still stmts stmtstart stop stopf stopifnot stopped stops storage stored stores str strcasecmp strcmp strictmode string stringify strings stringtext strip stripe stripquotedtext striprubystrings striptail strlen strtext struct structs structure style sub subj subject subjectnames submits submodules subscript subscription subshell subtracts success such sudo suffix sui suite summary sums super supports suppress suppressmessages sv swaps swift swiftcondition swifthead swifttextwithvalues switch switches switchstep symbol synchronized syncs syntax system systems table tables tag tags tail taken takes tal target targetwords task teardown tee tells template templates term terminal terms ternary terraform test tests testthat testwords text textof texts than that the their theirs them then thenpart thensays thento thentoks there these they thing things this those thread throttle throw throws thunder tied time timeout timeoutexception times tnr to today together tok token tokens toks tokscode told tolowercase too tool tools toomanyrequests top toplevel toplevelindex topsteps tostderr total tothundercondition tothunderoutcome touppercase tr traces trail trailing transaction trap traps treats tree tried tries triggers trim triple true truncate try trycatch trystep ts tsql tuple turn turned turns tv tx txt ty type typealias typed typedef typeof types typescript typeset ui un unauthorized unavailable unblocks unchanged unchecked undefined under underneath understood undoes undone uninstalls union unique unknowncommand unless unlocks unmarks unmounts unpacks unprocessable unprocessableentity unprotects unq unquote unquoted unread unregisters unsafe unsaved unset unsetopt unshift unsigned unsupported until unused up update updates upgrades uploads upper url usage use usecallback used useeffectevent useevent usememo user users uses using usual uullff val valid vals value valuechoice valued valuelogic valueof valueofblock values valuewords vapor vapply var variable variables vars varwords vault vec vector ver verb verbstep version versions very via view views vim virtual visible visit vnet void volatile volume vt vtoks wait waitfor waiting waits walk walking wantfail warning warns was watches way weak web webrequest well wget wh what when whenever where whereof wherever whether which whichever while whitespace who whole wholecallargs wholevaluecall whose whosefrom widths willset with withcallinghandlers withinwindow without withoutsinglequoted word words wordsplain work worked workflow workloads works workspace would wrapped wraps write writes written wrong ws wur xdescribe xml xs xtest xx yaml yes yesno yet yield yields you za zero zeros zsh".split(' '));
|
package/src/index.d.ts
CHANGED
|
@@ -705,7 +705,13 @@ export function toCSharp(ast: IntentAst): string;
|
|
|
705
705
|
export function toJava(ast: IntentAst): string;
|
|
706
706
|
export function toPython(ast: IntentAst): string;
|
|
707
707
|
export const GENERATORS: Record<string, (ast: IntentAst) => string>;
|
|
708
|
-
|
|
708
|
+
/** Generated code plus one IL-GEN-001 error per rule condition the target could not translate (that rule throws). */
|
|
709
|
+
export function generateWithDiagnostics(ast: IntentAst, target: string): { code: string; diagnostics: import('./target-result.mjs').GenerationDiagnostic[] };
|
|
710
|
+
export { GEN_UNTRANSLATED, ERROR_KINDS, isCaseResult, untranslatedMessage } from './target-result.mjs';
|
|
711
|
+
export type { CaseResult, TargetRun, TargetErrorKind, GenerationDiagnostic } from './target-result.mjs';
|
|
712
|
+
export { parseMoney, formatMoney, roundHalfUp, minorUnitsFor, moneyTypeMinorUnits, MoneyError, MONEY_DEFAULT_MINOR_UNITS } from './money.mjs';
|
|
713
|
+
/** `money` maps Money input names to minor units; their comparisons render exactly, other uses throw. */
|
|
714
|
+
export function exprToJs(src: string, opts?: { inputs?: string[]; money?: Record<string, number> }): string;
|
|
709
715
|
export function subjectName(ast: IntentAst): string | null;
|
|
710
716
|
export function intentRefId(astOrName: IntentAst | string, opts?: { sourceHash?: string }): string;
|
|
711
717
|
|
|
@@ -743,6 +749,7 @@ export { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText }
|
|
|
743
749
|
export { thunderizeFiles, THUNDER_TEXT_EXT } from './thunderize.mjs';
|
|
744
750
|
export { sameMeaning, renderSame } from './same.mjs';
|
|
745
751
|
export { thunderReview, renderReview, REVIEW_SCHEMA } from './review.mjs';
|
|
752
|
+
export { renderReviewComment, reviewCounts } from './review-comment.mjs';
|
|
746
753
|
export { EXPR_SCHEMA, parseStatement, renderStatement, sayFull, detailOf, sameExpr } from './meaning.mjs';
|
|
747
754
|
export type { Expr } from './meaning.mjs';
|
|
748
755
|
export { stepRoundTrip, runBehavior, ROUND_TRIP_LANGUAGES } from './round-trip.mjs';
|
package/src/index.mjs
CHANGED
|
@@ -115,7 +115,10 @@ export { FOCUS_SCHEMA, SCOPE_TYPES, FOCUS_REASONS, makeScope, buildFocusGraph, i
|
|
|
115
115
|
// Comprehension Contract , the C0..C7 understanding level (intent-comprehension-v1)
|
|
116
116
|
export { COMPREHENSION_SCHEMA, LEVELS as COMPREHENSION_LEVELS, comprehensionLevel, comprehensionReport } from './comprehension.mjs';
|
|
117
117
|
// Code generation , deterministic scaffolds from intent (intent-codegen-v1)
|
|
118
|
-
export { CODEGEN_SCHEMA, GENERATORS, toTypeScript, toCSharp, toJava, toPython } from './codegen.mjs';
|
|
118
|
+
export { CODEGEN_SCHEMA, GENERATORS, toTypeScript, toCSharp, toJava, toPython, generateWithDiagnostics } from './codegen.mjs';
|
|
119
|
+
// Honest generation and run results (IL-GEN-001, structured case results) and exact Thunder Money
|
|
120
|
+
export { GEN_UNTRANSLATED, ERROR_KINDS, isCaseResult, untranslatedMessage } from './target-result.mjs';
|
|
121
|
+
export { parseMoney, formatMoney, roundHalfUp, minorUnitsFor, moneyTypeMinorUnits, MoneyError, MONEY_DEFAULT_MINOR_UNITS } from './money.mjs';
|
|
119
122
|
// Change Lens , what a branch/PR changed by meaning (intent-changes-v1)
|
|
120
123
|
export { CHANGES_SCHEMA, changeReport } from './changes.mjs';
|
|
121
124
|
export { exprToJs, exprToCSharp, exprToJava, exprToCode } from './expr.mjs';
|
|
@@ -194,6 +197,7 @@ export { VISUAL_SCHEMA, THUNDER_VISUAL, visualFor, visualForStep, thunderText }
|
|
|
194
197
|
export { thunderizeFiles, THUNDER_TEXT_EXT } from "./thunderize.mjs";
|
|
195
198
|
export { sameMeaning, renderSame } from "./same.mjs";
|
|
196
199
|
export { thunderReview, renderReview, REVIEW_SCHEMA } from "./review.mjs";
|
|
200
|
+
export { renderReviewComment, reviewCounts } from "./review-comment.mjs";
|
|
197
201
|
// Every step's meaning tree, and code → Thunder → code for steps.
|
|
198
202
|
export { EXPR_SCHEMA, parseStatement, renderStatement, sayFull, detailOf, sameExpr } from "./meaning.mjs";
|
|
199
203
|
export { stepRoundTrip, runBehavior, ROUND_TRIP_LANGUAGES } from "./round-trip.mjs";
|
package/src/intent-schema.mjs
CHANGED
|
@@ -133,6 +133,7 @@ const IL_AUTHOR_RULE_ROWS = [
|
|
|
133
133
|
{ ruleId: 'IL-SEC-001', area: 'security', severity: 'blocker', blocks: ['release'], summary: 'Secret-typed field travels over the event bus.' },
|
|
134
134
|
{ ruleId: 'IL-SEC-002', area: 'security', severity: 'blocker', blocks: ['release'], summary: 'API returns a secret with no auth requirement.' },
|
|
135
135
|
{ ruleId: 'IL-TYPE-001', area: 'type', severity: 'info', blocks: [], summary: 'Field uses an unrecognized (likely mistyped) type.' },
|
|
136
|
+
{ ruleId: 'IL-GEN-001', area: 'generation', severity: 'error', blocks: ['implementation'], summary: 'A rule condition could not be translated for a target: generation reports it, the generated rule throws, and live runs report it not translated (never a stand-in false).' },
|
|
136
137
|
// 12-Factor Agents conformance (twelve-factor-v1). Advisory: an intent's alignment with the
|
|
137
138
|
// humanlayer/12-factor-agents principles. `thunder twelve-factor` scores these.
|
|
138
139
|
{ ruleId: 'IL-12F-01', area: 'twelve-factor', severity: 'info', blocks: [], summary: 'F1 Natural language to tool calls: model dispatch as a decision/command.' },
|
package/src/mcp.mjs
CHANGED
|
@@ -18,6 +18,8 @@ import { runTests } from './testing.mjs';
|
|
|
18
18
|
import { resolveObligations } from './obligations.mjs';
|
|
19
19
|
import { buildReviewAtlas, renderReviewBrief, reviewAtlasExitCode } from './review-atlas.mjs';
|
|
20
20
|
import { evaluateDecision } from './runtime.mjs';
|
|
21
|
+
import { buildTrace, traceImpact, traceImpactOf, renderImpact } from './trace.mjs';
|
|
22
|
+
import { readRepoDir, gitChanges } from './trace-fs.mjs';
|
|
21
23
|
import { buildIntentGraph } from './intent-graph.mjs';
|
|
22
24
|
import { buildConformance } from './conformance.mjs';
|
|
23
25
|
import { checkDrift } from './drift.mjs';
|
|
@@ -261,6 +263,27 @@ const TOOLS = [
|
|
|
261
263
|
return { ...rest, files: files.length, matched: items.length, items: items.slice(0, Math.max(1, Math.min(500, Number(limit) || 50))) };
|
|
262
264
|
},
|
|
263
265
|
},
|
|
266
|
+
{
|
|
267
|
+
name: 'intent_trace',
|
|
268
|
+
description: 'ASK THUNDER TRACE BEFORE CHANGING CODE THAT OTHER REPOSITORIES USE (local only). Give the repository folders. With "thing" (a route like "POST /api/orders", an event name, or "repo:file[:line]") or "diff": true (the branch and uncommitted changes), it answers what the change can affect in the OTHER repositories: callers of a changed or removed route, listeners of a published event, ranked high/medium/low, one hop out, every item cited repo@sha:file:line. With neither, it gives the links between the repositories. Read from code; nothing is run; a call whose address is worked out when it runs is listed as not linked, never guessed.',
|
|
269
|
+
inputSchema: {
|
|
270
|
+
type: 'object', required: ['paths'],
|
|
271
|
+
properties: {
|
|
272
|
+
paths: { type: 'array', minItems: 1, maxItems: 50, items: { ...str, description: 'a repository folder' } },
|
|
273
|
+
thing: { ...str, description: 'what changes: "POST /api/orders", "order.placed", or "repo:src/file.ts:12"' },
|
|
274
|
+
diff: { type: 'boolean', description: 'use the current changes (since the branch left main, plus uncommitted)' },
|
|
275
|
+
base: { ...str, description: 'with diff: the commit or branch to compare against' },
|
|
276
|
+
},
|
|
277
|
+
},
|
|
278
|
+
run: ({ paths, thing, diff = false, base }) => {
|
|
279
|
+
if (!Array.isArray(paths) || !paths.length || paths.length > 50) throw new Error('Give 1 to 50 repository folders in "paths".');
|
|
280
|
+
const repos = paths.map((p) => readRepoDir(resolve(String(p))));
|
|
281
|
+
const trace = buildTrace(repos);
|
|
282
|
+
if (!thing && !diff) return { trace };
|
|
283
|
+
const r = thing ? traceImpactOf(trace, String(thing)) : traceImpact(trace, repos.flatMap((repo) => gitChanges(repo, base).changes));
|
|
284
|
+
return { ...r, text: renderImpact(r) };
|
|
285
|
+
},
|
|
286
|
+
},
|
|
264
287
|
{
|
|
265
288
|
name: 'intent_promote',
|
|
266
289
|
description: 'Turn a decision recovered from code into a readable ThunderLang contract with starter examples chosen at every rule and threshold. The examples record what the code does TODAY (computed from the recovered rule), so a person must confirm each answer; after that, intent_verify_diff can hold every change to it. Give the source code and the decision (function) name.',
|
package/src/meaning.mjs
CHANGED
|
@@ -521,6 +521,7 @@ class Parser {
|
|
|
521
521
|
if (t.v === '...' && (fam === 'c')) { this.next(); return { kind: 'spread', value: this.expr(1), form: '...' }; }
|
|
522
522
|
if ((t.v === '*' || t.v === '**') && (fam === 'py' || fam === 'rb' || this.lang === 'kotlin')) { this.next(); return { kind: 'spread', value: this.expr(fam === 'py' ? 13 : 15), form: t.v }; }
|
|
523
523
|
if (t.v === '&' && fam === 'rb') { this.next(); return { kind: 'spread', value: this.expr(15), form: '&' }; }
|
|
524
|
+
if ((t.v === '*' || t.v === '&') && (this.lang === 'c' || this.lang === 'cpp')) { this.next(); return { kind: 'unary', op: t.v, value: this.expr(17) }; }
|
|
524
525
|
if ((t.v === '*' || t.v === '&' || t.v === '<-') && (fam === 'go' || fam === 'rs')) {
|
|
525
526
|
this.next();
|
|
526
527
|
if (t.v === '&' && fam === 'rs' && this.isId('mut')) { this.next(); return { kind: 'unary', op: '&mut', value: this.expr(16) }; }
|
|
@@ -754,6 +755,13 @@ class Parser {
|
|
|
754
755
|
node = { kind: 'member', object: node, property: p.v };
|
|
755
756
|
continue;
|
|
756
757
|
}
|
|
758
|
+
if (t.v === '->' && (lang === 'c' || lang === 'cpp')) {
|
|
759
|
+
this.next();
|
|
760
|
+
const p = this.next();
|
|
761
|
+
if (p.t !== 'id') fail('expected a name after ->');
|
|
762
|
+
node = { kind: 'member', object: node, property: p.v, arrow: true };
|
|
763
|
+
continue;
|
|
764
|
+
}
|
|
757
765
|
if (t.v === '&.' && fam === 'rb') { this.next(); const pn = this.next(); if (pn.t !== 'id') fail('a name after &.'); node = { kind: 'member', object: node, property: pn.v, optional: true }; continue; }
|
|
758
766
|
if (t.v === '?.' && fam === 'c') {
|
|
759
767
|
this.next();
|
|
@@ -776,7 +784,7 @@ class Parser {
|
|
|
776
784
|
if (t.v === '!!' && lang === 'kotlin') { this.next(); node = { kind: 'unary', op: '!!', value: node, postfix: true }; continue; }
|
|
777
785
|
if (t.v === '?' && fam === 'rs' && !t.sp) { this.next(); node = { kind: 'unary', op: '?', value: node, postfix: true }; continue; }
|
|
778
786
|
if ((t.v === '++' || t.v === '--') && !t.nl && fam !== 'py') { this.next(); node = { kind: 'unary', op: t.v, value: node, postfix: true }; continue; }
|
|
779
|
-
if (t.v === '<' && (lang === 'typescript' || lang === 'csharp' || lang === 'java' || lang === 'kotlin') && !t.sp && this.looksLikeTypeArgs()) { node = { ...node, typeArgs: this.typeArgs() }; continue; }
|
|
787
|
+
if (t.v === '<' && (lang === 'typescript' || lang === 'csharp' || lang === 'java' || lang === 'kotlin' || lang === 'cpp') && !t.sp && this.looksLikeTypeArgs()) { node = { ...node, typeArgs: this.typeArgs() }; continue; }
|
|
780
788
|
if (t.v === '{' && !this.noBrace && (fam === 'go' || fam === 'rs') && this.isTypeName(node)) { node = this.compositeLit(node); continue; }
|
|
781
789
|
if (t.v === '{' && lang === 'kotlin' && !this.noBrace && (node.kind === 'call' || node.kind === 'name' || node.kind === 'member')) { node = this.withTrailing(node, this.kotlinLambda()); continue; }
|
|
782
790
|
// Ruby: braces after a call are its block (`items.each { |x| … }`, `loop { … }`); a hash is only ever an argument.
|
|
@@ -810,7 +818,7 @@ class Parser {
|
|
|
810
818
|
if (t.t === 'op') {
|
|
811
819
|
if (t.v === '<') depth++;
|
|
812
820
|
else if (t.v === '>' || t.v === '>>') { depth -= t.v.length; if (depth <= 0) { const nx = this.peek(o + 1); return nx.t === 'op' && (nx.v === '(' || (nx.v === '{' && this.lang === 'csharp')); } }
|
|
813
|
-
else if (!/^(?:,|\.|\[|\]|\||&|\?|=>|\(|\)|:)$/.test(t.v)) return false;
|
|
821
|
+
else if (!/^(?:,|\.|\[|\]|\||&|\?|=>|\(|\)|:)$/.test(t.v) && !(this.lang === 'cpp' && /^(?:::|\*|&&)$/.test(t.v))) return false;
|
|
814
822
|
} else if (t.t !== 'id' && t.t !== 'str' && t.t !== 'num') return false;
|
|
815
823
|
}
|
|
816
824
|
return false;
|
|
@@ -881,6 +889,8 @@ class Parser {
|
|
|
881
889
|
}
|
|
882
890
|
|
|
883
891
|
paren() {
|
|
892
|
+
// C / C++: a cast `(redisPollEvents *)data`, `(int)n`, `(const char *)p`.
|
|
893
|
+
if (this.lang === 'c' || this.lang === 'cpp') { const c = this.cCast(); if (c) return c; }
|
|
884
894
|
// An arrow function `(a, b) => …` / `(a: T): R => …`?
|
|
885
895
|
if (this.fam === 'c' && (isJs(this.lang) || this.lang === 'csharp' || this.lang === 'java')) {
|
|
886
896
|
// JSX inside brackets (`return (\n <div>…`) is read as JSX, not scanned as code.
|
|
@@ -890,6 +900,22 @@ class Parser {
|
|
|
890
900
|
}
|
|
891
901
|
return this.plainParen();
|
|
892
902
|
}
|
|
903
|
+
cCast() {
|
|
904
|
+
const src = this.L.src, open = this.peek().s;
|
|
905
|
+
const close = src.indexOf(')', open);
|
|
906
|
+
if (close < 0) return null;
|
|
907
|
+
const inner = src.slice(open + 1, close);
|
|
908
|
+
const m = /^\s*((?:(?:const|volatile|struct|enum|union|unsigned|signed|long|short)\s+)*)([A-Za-z_][\w:]*)(\s*<[^()]*>)?((?:\s*(?:const\s*)?[*&])*)\s*$/.exec(inner);
|
|
909
|
+
if (!m) return null;
|
|
910
|
+
const clearlyType = /\*|&/.test(m[4]) || !!m[1] || /^(?:int|char|long|short|float|double|void|bool|size_t|ssize_t|unsigned|signed|u?int\d+_t|uintptr_t|intptr_t|ptrdiff_t|time_t|off_t|wchar_t|char\d+_t|uint|uchar|BOOL|DWORD|HANDLE)$/.test(m[2]) || /_t$/.test(m[2]);
|
|
911
|
+
if (!clearlyType) return null;
|
|
912
|
+
const after = src.slice(close + 1).trimStart();
|
|
913
|
+
if (!/^[A-Za-z_\d("'*&!~-]/.test(after)) return null;
|
|
914
|
+
while (this.peek().t !== 'eof' && this.peek().s < close) this.next();
|
|
915
|
+
if (!this.isOp(')')) return null;
|
|
916
|
+
this.next();
|
|
917
|
+
return { kind: 'cast', type: inner.trim(), value: this.expr(16), form: 'c' };
|
|
918
|
+
}
|
|
893
919
|
arrowOrParen() {
|
|
894
920
|
// Find the matching ) and look for => (or ->, Java) after it, past an optional return type.
|
|
895
921
|
let depth = 0, o = 0;
|
|
@@ -1563,6 +1589,8 @@ function statement(p) {
|
|
|
1563
1589
|
return node;
|
|
1564
1590
|
}
|
|
1565
1591
|
if (v === 'default' && fam !== 'py' && (p.isOp(':', 1) || p.isOp('->', 1))) { p.next(); p.next(); return p.peek().t === 'eof' ? { kind: 'case', default: true } : { kind: 'case', default: true, inline: true }; }
|
|
1592
|
+
// Swift `try f()` / `try? f()` / Rust-like `try await f()`: an expression that may throw, not a try block.
|
|
1593
|
+
if (v === 'try' && lang === 'swift' && !p.isOp('{', 1)) { p.next(); if (p.isOp('?') || p.isOp('!')) p.next(); if (p.isId('await')) p.next(); return statement(p); }
|
|
1566
1594
|
if (v === 'try' || v === 'begin') { p.next(); return { kind: 'try' }; }
|
|
1567
1595
|
if (v === 'return' && !(p.isOp('=', 1))) {
|
|
1568
1596
|
p.next();
|
|
@@ -1613,6 +1641,7 @@ function statement(p) {
|
|
|
1613
1641
|
if (v === 'async' && fam === 'py' && (p.isId('with', 1) || p.isId('for', 1) || p.isId('def', 1))) { p.next(); const s = statement(p); return { ...s, async: true }; }
|
|
1614
1642
|
if (v === 'pass' && fam === 'py') { p.next(); return endStatement(p, { kind: 'pass' }); }
|
|
1615
1643
|
if (v === 'def' || (v === 'function' && p.peek(1).t === 'id') || (v === 'func' && p.peek(1).t === 'id') || (v === 'fn' && fam === 'rs') || (v === 'fun' && lang === 'kotlin') || (v === 'async' && isJs(lang) && p.isId('function', 1) && p.peek(2).t === 'id')) return functionHeader(p);
|
|
1644
|
+
if ((lang === 'c' || lang === 'cpp') && /^(?:const|static|struct|enum|union|constexpr|unsigned|signed|long|short|register|extern|volatile|inline|mutable)$/.test(v) && typedDeclAhead(p)) return typedDeclaration(p);
|
|
1616
1645
|
if (/^(?:class|struct|interface|enum|impl|trait|object|record|module|type|namespace|import|export|from|package|use|using|lock|synchronized|unsafe|goto|static|public|private|protected|internal|abstract|override|virtual|final|readonly|global|nonlocal|extern|template|typedef|label)$/.test(v) && !(p.isOp('(', 1) && !/^(?:using|lock|synchronized)$/.test(v)) && !(p.isOp('.', 1)) && !(p.peek(1).t === 'op' && (ASSIGN_OPS.has(p.peek(1).v) || p.peek(1).v === ',' || p.peek(1).v === '['))) {
|
|
1617
1646
|
if (v === 'export' && (p.isId('const', 1) || p.isId('let', 1) || p.isId('function', 1))) { p.next(); return statement(p); }
|
|
1618
1647
|
if ((v === 'global' || v === 'nonlocal') && fam === 'py') { p.next(); const names = []; while (p.peek().t === 'id') { names.push(p.next().v); if (p.isOp(',')) p.next(); } return endStatement(p, { kind: 'declare', names, scope: v }); }
|
|
@@ -1820,14 +1849,15 @@ function methodHeader(p) {
|
|
|
1820
1849
|
function typedDeclAhead(p, method = false) {
|
|
1821
1850
|
// Type name = …; Type<A, B>[] name; final Type name = …
|
|
1822
1851
|
let o = 0;
|
|
1823
|
-
|
|
1852
|
+
const cLike = p.lang === 'c' || p.lang === 'cpp';
|
|
1853
|
+
while (p.peek(o).t === 'id' && (/^(?:final|static|readonly|const|volatile|var|unsigned|signed)$/.test(p.peek(o).v) || (cLike && /^(?:struct|enum|union|constexpr|long|short|register|extern|inline|mutable|thread_local)$/.test(p.peek(o).v))) && p.peek(o + 1).t === 'id') o++;
|
|
1824
1854
|
if (p.peek(o).t !== 'id') return false;
|
|
1825
1855
|
if (/^(?:return|throw|new|await|yield|case|goto|else|in|is|as|out|ref|params|this|base|super)$/.test(p.peek(o).v)) return false;
|
|
1826
1856
|
o++;
|
|
1827
1857
|
let depth = 0;
|
|
1828
1858
|
for (let guard = 0; guard < 40; guard++) {
|
|
1829
1859
|
const t = p.peek(o);
|
|
1830
|
-
if (t.t === 'op' && (t.v === '.' || t.v === '?' || t.v === '*' || t.v === '&') && depth === 0) { o++; if (p.peek(o).t === 'id' && t.v === '.') o++; continue; }
|
|
1860
|
+
if (t.t === 'op' && (t.v === '.' || t.v === '?' || t.v === '*' || t.v === '&' || (cLike && (t.v === '::' || t.v === '&&'))) && depth === 0) { o++; if (p.peek(o).t === 'id' && (t.v === '.' || t.v === '::')) o++; continue; }
|
|
1831
1861
|
if (t.t === 'op' && t.v === '<') { depth++; o++; continue; }
|
|
1832
1862
|
if (t.t === 'op' && (t.v === '>' || t.v === '>>')) { depth -= t.v.length; o++; continue; }
|
|
1833
1863
|
if (t.t === 'op' && t.v === '[' && p.isOp(']', o + 1)) { o += 2; continue; }
|
|
@@ -1837,7 +1867,7 @@ function typedDeclAhead(p, method = false) {
|
|
|
1837
1867
|
if (depth !== 0 || p.peek(o).t !== 'id') return false;
|
|
1838
1868
|
const after = p.peek(o + 1);
|
|
1839
1869
|
if (method) return after.t === 'op' && after.v === '(' ? o : false;
|
|
1840
|
-
return after.t === 'eof' || (after.t === 'op' && (after.v === '=' || after.v === ';' || after.v === ',')) ? o : false;
|
|
1870
|
+
return after.t === 'eof' || (after.t === 'op' && (after.v === '=' || after.v === ';' || after.v === ',' || (cLike && after.v === '['))) ? o : false;
|
|
1841
1871
|
}
|
|
1842
1872
|
function typedDeclaration(p, inner = false) {
|
|
1843
1873
|
const a = p.k;
|
|
@@ -1848,6 +1878,10 @@ function typedDeclaration(p, inner = false) {
|
|
|
1848
1878
|
const items = [];
|
|
1849
1879
|
for (;;) {
|
|
1850
1880
|
const name = p.next().v;
|
|
1881
|
+
// C / C++ arrays: `char port[6];`
|
|
1882
|
+
let dims = '';
|
|
1883
|
+
while ((p.lang === 'c' || p.lang === 'cpp') && p.isOp('[')) { const d0 = p.k; let depth = 0; do { const x = p.next(); if (x.t === 'eof') fail('array size'); if (x.v === '[') depth++; else if (x.v === ']') depth--; } while (depth > 0); dims += p.text(d0, p.k); }
|
|
1884
|
+
if (dims) { if (p.isOp('=')) fail('array initializer'); items.push({ kind: 'declare', declare: 'typed', type: `${type}${dims}`, names: [name] }); if (p.isOp(',')) { p.next(); continue; } break; }
|
|
1851
1885
|
if (p.isOp('=')) { p.next(); items.push({ kind: 'assign', op: '=', declare: 'typed', type, target: { kind: 'name', name }, value: p.isOp('{') ? p.objectLit() : p.expr(0.6) }); }
|
|
1852
1886
|
else items.push({ kind: 'declare', declare: 'typed', type, names: [name] });
|
|
1853
1887
|
if (p.isOp(',')) { p.next(); continue; }
|
|
@@ -1938,12 +1972,17 @@ function forHeader(p) {
|
|
|
1938
1972
|
}
|
|
1939
1973
|
let declare = null;
|
|
1940
1974
|
if (p.peek().t === 'id' && /^(?:const|let|var|val|final|auto)$/.test(p.peek().v) && (p.peek(1).t === 'id' || p.isOp('[', 1) || p.isOp('{', 1) || p.isOp('(', 1))) declare = p.next().v;
|
|
1975
|
+
// C++: `auto &t : threads` / `auto* p : ps`.
|
|
1976
|
+
if (declare === 'auto' && (lang === 'cpp' || lang === 'c')) while (p.isOp('&') || p.isOp('*') || p.isOp('&&')) p.next();
|
|
1977
|
+
if (declare === 'const' && (lang === 'cpp' || lang === 'c')) declare = null;
|
|
1941
1978
|
// Java/C#: the element's type before its name.
|
|
1942
1979
|
let type = null;
|
|
1943
1980
|
if (p.peek().t === 'id' && !declare) {
|
|
1944
1981
|
const k0 = p.k;
|
|
1945
1982
|
let o = 0;
|
|
1946
|
-
|
|
1983
|
+
// (C++: `const auto& item`, `std::string *s`.)
|
|
1984
|
+
const cLike = lang === 'c' || lang === 'cpp';
|
|
1985
|
+
while (p.peek(o).t === 'id' || (p.peek(o).t === 'op' && (/^(?:\.|<|>|\[|\]|,|\?)$/.test(p.peek(o).v) || (cLike && /^(?:&|\*|&&|::)$/.test(p.peek(o).v))))) { if (p.peek(o).t === 'id' && (/^(?:of|in)$/.test(p.peek(o).v))) break; if (p.isOp(':', o)) break; o++; }
|
|
1947
1986
|
if (o >= 2 && p.peek(o - 1).t === 'id') { type = p.text(k0, k0 + o - 1); p.k = k0 + o - 1; }
|
|
1948
1987
|
}
|
|
1949
1988
|
const targets = [];
|
package/src/model.d.mts
CHANGED
|
@@ -7,7 +7,9 @@ export interface FlowNode { id: string; kind: 'start' | 'decision' | 'step' | 'l
|
|
|
7
7
|
/** A yes/no question as a statement on each side, when it splits cleanly: { yes: "the x header is the KEY setting", no: "… is not …" }. */
|
|
8
8
|
holds?: { yes: string; no: string };
|
|
9
9
|
/** The step's full meaning (thunder-expr-v1). */ expr?: Expr;
|
|
10
|
-
/** What the short words leave out, one level down: "with: order, { validate: false }". Shown in Details and the full Thunder Text. */ detail?: string
|
|
10
|
+
/** What the short words leave out, one level down: "with: order, { validate: false }". Shown in Details and the full Thunder Text. */ detail?: string;
|
|
11
|
+
/** False for a node shown as code ("code, not explained"); true for every node in Thunder's own words. Always set. */ explained: boolean;
|
|
12
|
+
/** When `explained` is false: why, in a few plain words. */ notExplainedWhy?: string }
|
|
11
13
|
export interface FlowEdge { from: string; to: string; label?: 'yes' | 'no' | 'each' | 'next' | 'done' | 'error' | 'case' | 'nested'; /** On a 'case' edge: the case it takes ("When it is from 90 to 100", "Otherwise", "None of these"). */ text?: string }
|
|
12
14
|
export interface FlowBlock { id: string; yes?: FlowBlock[]; no?: FlowBlock[]; each?: FlowBlock[]; body?: FlowBlock[];
|
|
13
15
|
/** A choice among several cases (switch, when, match, select): one side per case, in order. The decision node has `cases: true`. */
|
|
@@ -42,8 +44,10 @@ export interface Link { from: string; to: string; kind: LinkKind; node?: string;
|
|
|
42
44
|
export type ModelLink = Link;
|
|
43
45
|
export interface Member { id: string; kind: 'action' | 'rule' | 'steps' | 'setup' | 'not-read' | 'pipeline' | 'image-build'; /** Pipelines: when it runs, in words. */ when?: string; name: string; label: string; owner?: string; file: string; language: string; lines: [number, number]; doc?: string; route?: string;
|
|
44
46
|
/** JS/TS: what the function is assigned to (`exports.normalizeType`, `View.prototype.lookup`, `res.json`). */ assignedTo?: string;
|
|
45
|
-
/** JS/TS: an anonymous function passed to a call (named `<parent> › callback at line N`); `passedTo` is the call. */ callback?: true; passedTo?: string; youGive: string[]; /** Each input's kind in words, by its label, when the code says it. */ inputKinds?: Record<string, string>; youGetBack?: string; rule?: unknown; question?: string; yesNo?: boolean; flow: Flow;
|
|
46
|
-
|
|
47
|
+
/** JS/TS: an anonymous function passed to a call (named `<parent> › callback at line N`); `passedTo` is the call. */ callback?: true; passedTo?: string; youGive: string[]; /** Each input's kind in words, by its label, when the code says it. */ inputKinds?: Record<string, string>; youGetBack?: string; rule?: unknown; question?: string; yesNo?: boolean; flow: Flow;
|
|
48
|
+
/** How sure: steps put into words, of every step Thunder read in this member (absent for rules). */ explainedSteps?: number; totalSteps?: number; /** Set by proof by running (executed.mjs markExecuted) only where a run proved the reading. */ completeness?: { level: 'executed'; reasons: string[] } }
|
|
49
|
+
export interface ThunderModel { schema: 'thunder-model-v1'; name: string; files: { path: string; language: string; purpose?: string; category: 'application' | 'infrastructure' | 'delivery'; /** Why this file could not be read. */ skipped?: string }[]; things: Thing[]; members: Member[]; links: Link[]; unknowns: { id?: string; file: string; line: number; why: string }[]; permissions: Permission[]; settings: Setting[]; facts: Fact[]; notLinked?: NotLinked[];
|
|
50
|
+
/** How sure, for the whole app: steps put into words, of every step read. */ explainedSteps: number; totalSteps: number }
|
|
47
51
|
/** A call, request, event, or import worth linking that was not linked, and why (dynamic import, computed URL, external package, two routes match, an interface). */
|
|
48
52
|
export interface NotLinked { from?: string; node?: string; file: string | null; line: number | null; call?: string; import?: string; why: string; /** For an external package: how many imports of it. */ files?: number }
|
|
49
53
|
/** Which areas (folders, two levels deep) call which, from cross-file and service links. */
|
package/src/model.mjs
CHANGED
|
@@ -270,7 +270,8 @@ const possessiveWords = (text) => String(text)
|
|
|
270
270
|
.replace(/\b([a-z]+(?:_[a-z0-9]+)+|[a-z]+(?:[A-Z][a-z0-9]*)+)\b/g, (m) => words(m)); // days_late, daysLate -> days late
|
|
271
271
|
/** An answer as words: NoFee -> "No fee", true -> "Yes". */
|
|
272
272
|
// (Quoted text is an answer as written: its case, signs, and spaces are kept.)
|
|
273
|
-
|
|
273
|
+
// (A short name that would split into one-letter pieces, such as NaN, is kept as written: "Na n" is not a word.)
|
|
274
|
+
const answerWords = (r) => (/^true$/i.test(r) ? 'Yes' : /^false$/i.test(r) ? 'No' : /^(["'`]).*\1$/s.test(String(r).trim()) ? String(r).trim() : /^[A-Za-z]{2,4}$/.test(String(r).trim()) && /[a-z][A-Z]|[A-Z][a-z]+[A-Z]/.test(String(r)) ? String(r).trim() : cap(words(r)));
|
|
274
275
|
|
|
275
276
|
/**
|
|
276
277
|
* A branch as a question a kid can answer with yes or no, asked the positive way round. "If book.status is not on
|
|
@@ -286,7 +287,9 @@ export function askAsQuestion(step, ruleLabel) {
|
|
|
286
287
|
const held = [];
|
|
287
288
|
const says = String(step.says).replace(/"(?:\\.|[^"\\])*"|`[^`]*`|«[^»]*»/g, (m) => (isCodeWords(String(step.says).replace(/^If (?:not: )?/, '')) ? m : `\u0001${held.push(m) - 1}\u0002`));
|
|
288
289
|
const r = askWords({ ...step, says }, ruleLabel);
|
|
289
|
-
|
|
290
|
+
// (Every text made from the held words gets them back: the question and both sides of `holds`, which a review quotes.)
|
|
291
|
+
const back = (t) => String(t).replace(/\u0001(\d+)\u0002/g, (m, k) => held[Number(k)]);
|
|
292
|
+
return { ...r, text: back(r.text), ...(r.holds ? { holds: { yes: back(r.holds.yes), no: back(r.holds.no) } } : {}) };
|
|
290
293
|
}
|
|
291
294
|
function askWords(step, ruleLabel) {
|
|
292
295
|
let c = String(step.says).replace(/^If /, '').replace(/ \(\d+ steps? inside\)$/, '').trim();
|
|
@@ -334,7 +337,7 @@ function compoundWords(c) {
|
|
|
334
337
|
export function ruleFlow(item, start) {
|
|
335
338
|
const nodes = [], edges = [];
|
|
336
339
|
let n = 0;
|
|
337
|
-
const node = (kind, text, extra = {}) => { const id = `n${n++}`; nodes.push({ id, kind, text, row: nodes.length, ...extra }); return id; };
|
|
340
|
+
const node = (kind, text, extra = {}) => { const id = `n${n++}`; nodes.push({ id, kind, text, row: nodes.length, explained: true, ...extra }); return id; };
|
|
338
341
|
let prev = node('start', start, { lane: 0, does: 'start' });
|
|
339
342
|
let label;
|
|
340
343
|
for (const r of item.rules || []) {
|
|
@@ -379,6 +382,10 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
379
382
|
const id = `n${n++}`;
|
|
380
383
|
const { [DETAIL_OF]: of, ...rest } = extra;
|
|
381
384
|
const nd = { id, kind, text, ...rest };
|
|
385
|
+
// `explained`: false for every node shown as code ("code, not explained"), with `notExplainedWhy` when known.
|
|
386
|
+
nd.explained = !(kind === 'code' || nd.code || rest.explained === false);
|
|
387
|
+
if (nd.explained) delete nd.notExplainedWhy;
|
|
388
|
+
else if (!nd.notExplainedWhy) nd.notExplainedWhy = 'the reader did not recognize this form';
|
|
382
389
|
if (of) lazyDetail(nd, of);
|
|
383
390
|
nodes.push(nd);
|
|
384
391
|
return id;
|
|
@@ -411,7 +418,7 @@ export function flowOf(steps, { start = 'Start', memberIndex = new Map(), member
|
|
|
411
418
|
const does = stepDoes(st);
|
|
412
419
|
// Every node keeps its step's meaning tree (`expr`) and, when the short words leave something out, `detail`:
|
|
413
420
|
// the rest, one level down ("with: order, { validate: false }"). Details and the full Thunder Text show it.
|
|
414
|
-
const base = { line: st.line, lane, does, ...(usesOf(st) ? { uses: usesOf(st) } : {}), ...(st.expr ? { expr: st.expr, [DETAIL_OF]: { says: st.says, kind: st.kind, code: st.code, restates: st.restates, expr: st.expr } } : {}) };
|
|
421
|
+
const base = { line: st.line, lane, does, ...(st.explained === false ? { explained: false, ...(st.notExplainedWhy ? { notExplainedWhy: st.notExplainedWhy } : {}) } : {}), ...(st.codeWords ? { code: true } : {}), ...(usesOf(st) ? { uses: usesOf(st) } : {}), ...(st.expr ? { expr: st.expr, [DETAIL_OF]: { says: st.says, kind: st.kind, code: st.code, restates: st.restates, expr: st.expr } } : {}) };
|
|
415
422
|
// A choice among several cases (switch, when, match, select): one question with one side per case.
|
|
416
423
|
const arms = st.kind === 'branch' && st.children?.length && st.children.every((c) => c.kind === 'check' && c.caseLabel) ? st.children : null;
|
|
417
424
|
if (arms) {
|
|
@@ -718,6 +725,8 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
718
725
|
...(rule ? { rule, question: rule.question } : {}),
|
|
719
726
|
// A yes/no rule is named as a question ("Can borrow?"); a rule with named answers is not ("Late fee").
|
|
720
727
|
...(kind === 'rule' ? { yesNo: [...(item.rules || []).map((r) => r.result), item.otherwise?.result].every((r) => r == null || /^(true|false)$/i.test(r)) } : {}),
|
|
728
|
+
// How sure: of the steps Thunder read, how many it put into words (the rest are shown as code, not explained).
|
|
729
|
+
...(item.totalSteps != null ? { explainedSteps: item.explainedSteps, totalSteps: item.totalSteps } : {}),
|
|
721
730
|
_steps: item.steps || [], _item: item, ...(item.qualifier && !owner ? { _qualifier: item.qualifier } : {}),
|
|
722
731
|
};
|
|
723
732
|
if (owner) owner.can.push(m.id);
|
|
@@ -793,7 +802,10 @@ export function thunderModel(files, { name = 'app' } = {}) {
|
|
|
793
802
|
if (t.kind !== 'thing' || t.knows.length || owners.has(t.id)) continue;
|
|
794
803
|
if (/(Exception|Error)$/.test(t.name)) things.splice(i, 1); else t.kind = 'record';
|
|
795
804
|
}
|
|
796
|
-
|
|
805
|
+
// How sure, for the whole app: steps put into words, of all steps read.
|
|
806
|
+
const totalSteps = members.reduce((n, m) => n + (m.totalSteps ?? 0), 0);
|
|
807
|
+
const explainedSteps = members.reduce((n, m) => n + (m.explainedSteps ?? 0), 0);
|
|
808
|
+
const model = { schema: MODEL_SCHEMA, name, files: fileInfo, things, members, links, unknowns, permissions, settings, facts, explainedSteps, totalSteps };
|
|
797
809
|
// The whole system: calls that go to another file, HTTP requests to this repo's routes, events to listeners.
|
|
798
810
|
try { linkSystem(model, files); } catch (e) { model.notLinked = [{ file: fileInfo[0]?.path ?? null, line: 1, why: `Calls across files could not be linked: ${e.message}` }]; }
|
|
799
811
|
return model;
|
|
@@ -809,7 +821,8 @@ function flowLines(flow, depth = 1, note = null, full = false) {
|
|
|
809
821
|
// `note` (optional) adds words after a node: the running system's counts (running.mjs).
|
|
810
822
|
const at = (n) => `${n.line ? ` (line ${n.line})` : ''}${(note && note(n)) || ''}`;
|
|
811
823
|
// (A value given back that could not be put into words still says it is given back: the ending is never hidden.)
|
|
812
|
-
|
|
824
|
+
// (A restated ending that is not a value — `exit 0`, `exec prog`, `die` — is shown as its code, never as "Gives back".)
|
|
825
|
+
const say = (n) => (n.kind === 'end' && n.code && !/^(?:return|yield|exit|exec|die|abort|quit|halt|throw|raise|panic|break|continue|Exit|Throw|Write-Error)\b/.test(String(n.text).trim()) ? `Gives back \`${n.text}\` (code, not explained)` : n.kind === 'code' || (n.kind === 'end' && n.code) ? `\`${n.text}\` (code, not explained)` : (n.kind === 'loop' || n.kind === 'stop' || n.kind === 'step') && n.code ? `${n.text} (code, not explained)` : n.kind === 'decision' && n.cases ? `${n.text}${n.code ? ' (code, not explained)' : ''}` : n.kind === 'decision' ? `Ask: ${n.text}${n.code ? ' (code, not explained)' : ''}` : n.kind === 'end' && n.answer ? `Answer: ${n.text}` : n.text);
|
|
813
826
|
const go = (blocks, d) => {
|
|
814
827
|
for (const b of blocks || []) {
|
|
815
828
|
const n = byId.get(b.id);
|
package/src/money.d.mts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/** Thunder Money: an exact decimal amount in minor units, never binary floating point. */
|
|
2
|
+
export class MoneyError extends Error {}
|
|
3
|
+
export const MONEY_DEFAULT_MINOR_UNITS: 2;
|
|
4
|
+
/** Minor units for an ISO 4217 code (2 when unknown or absent): JPY 0, USD 2, KWD 3. */
|
|
5
|
+
export function minorUnitsFor(currency?: string | null): number;
|
|
6
|
+
/** Minor units when `type` is `Money` or `Money(XXX)`, else null. */
|
|
7
|
+
export function moneyTypeMinorUnits(type: string): number | null;
|
|
8
|
+
/** Parse "12.30" (or "$12.30" with allowDollar) to exact minor units. Extra precision throws; nothing is rounded. */
|
|
9
|
+
export function parseMoney(text: string | number, opts?: { minorUnits?: number; allowDollar?: boolean }): bigint;
|
|
10
|
+
/** Render minor units as a decimal string with exactly `minorUnits` places. */
|
|
11
|
+
export function formatMoney(minor: bigint | number, opts?: { minorUnits?: number }): string;
|
|
12
|
+
/** Round half up (a half goes away from zero, as in Thunder Core) to `minorUnits` places. Use only where a spec asks for rounding. */
|
|
13
|
+
export function roundHalfUp(text: string | number, opts?: { minorUnits?: number }): bigint;
|
|
14
|
+
export function numberToDecimalText(n: number): string;
|
|
15
|
+
/** The exact Money literal for a target dialect, or null when the target has none wired up. */
|
|
16
|
+
export function moneyLiteral(dialect: string, text: string | number, minorUnits?: number): string | null;
|
|
17
|
+
export const MONEY_TYPES: Record<string, string>;
|
|
18
|
+
export function moneyCompare(dialect: string, op: string, a: string, b: string): string;
|