@lokascript/framework 4.8.0 → 5.0.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 +42 -1
- package/dist/api/create-dsl.d.ts +9 -10
- package/dist/api/create-dsl.d.ts.map +1 -1
- package/dist/api/index.js +835 -1670
- package/dist/api/index.js.map +1 -1
- package/dist/core/index.d.ts +0 -1
- package/dist/core/index.d.ts.map +1 -1
- package/dist/core/index.js +549 -1132
- package/dist/core/index.js.map +1 -1
- package/dist/core/matching/index.d.ts +2 -0
- package/dist/core/matching/index.d.ts.map +1 -1
- package/dist/core/matching/possessive-keywords.d.ts.map +1 -0
- package/dist/core/matching/stock-confidence.d.ts +3 -4
- package/dist/core/matching/stock-confidence.d.ts.map +1 -1
- package/dist/core/matching/stock-reading.d.ts +4 -4
- package/dist/core/{pattern-matching/utils → matching}/type-validation.d.ts +1 -1
- package/dist/core/matching/type-validation.d.ts.map +1 -0
- package/dist/generation/index.d.ts +1 -1
- package/dist/generation/index.d.ts.map +1 -1
- package/dist/generation/index.js +20 -169
- package/dist/generation/index.js.map +1 -1
- package/dist/generation/profile.d.ts +30 -0
- package/dist/generation/profile.d.ts.map +1 -0
- package/dist/generation/renderer.d.ts +1 -1
- package/dist/generation/renderer.d.ts.map +1 -1
- package/dist/generation/schema-patterns.d.ts +3 -3
- package/dist/index.cjs +929 -1674
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +929 -1668
- package/dist/index.js.map +1 -1
- package/dist/multilingual/builders.d.ts +3 -3
- package/dist/multilingual/builders.d.ts.map +1 -1
- package/dist/multilingual/index.js.map +1 -1
- package/dist/parsing/index.d.ts +0 -1
- package/dist/parsing/index.d.ts.map +1 -1
- package/dist/parsing/index.js +0 -1145
- package/dist/parsing/index.js.map +1 -1
- package/dist/testing/gate/lint/types.d.ts +1 -1
- package/dist/testing/gate/lint/types.d.ts.map +1 -1
- package/package.json +2 -7
- package/src/__test__/test-utils.ts +1 -1
- package/src/api/create-dsl-engine.test.ts +60 -35
- package/src/api/create-dsl.ts +24 -35
- package/src/core/index.ts +0 -1
- package/src/core/matching/index.ts +2 -0
- package/src/core/matching/stock-confidence.ts +3 -4
- package/src/core/matching/stock-reading.ts +6 -6
- package/src/core/{pattern-matching/utils → matching}/type-validation.test.ts +2 -2
- package/src/core/{pattern-matching/utils → matching}/type-validation.ts +1 -1
- package/src/generation/domain-renderer.test.ts +1 -1
- package/src/generation/index.ts +1 -1
- package/src/generation/profile.ts +41 -0
- package/src/generation/renderer.test.ts +1 -1
- package/src/generation/renderer.ts +1 -1
- package/src/generation/schema-patterns.ts +3 -3
- package/src/multilingual/bridge.test.ts +31 -23
- package/src/multilingual/builders.ts +3 -3
- package/src/parsing/index.ts +0 -1
- package/src/testing/gate/lint/types.ts +1 -1
- package/dist/core/pattern-matching/index.d.ts +0 -6
- package/dist/core/pattern-matching/index.d.ts.map +0 -1
- package/dist/core/pattern-matching/index.js +0 -1211
- package/dist/core/pattern-matching/index.js.map +0 -1
- package/dist/core/pattern-matching/pattern-matcher.d.ts +0 -122
- package/dist/core/pattern-matching/pattern-matcher.d.ts.map +0 -1
- package/dist/core/pattern-matching/utils/index.d.ts +0 -6
- package/dist/core/pattern-matching/utils/index.d.ts.map +0 -1
- package/dist/core/pattern-matching/utils/possessive-keywords.d.ts.map +0 -1
- package/dist/core/pattern-matching/utils/type-validation.d.ts.map +0 -1
- package/dist/generation/pattern-generator.d.ts +0 -55
- package/dist/generation/pattern-generator.d.ts.map +0 -1
- package/src/core/pattern-matching/index.ts +0 -6
- package/src/core/pattern-matching/pattern-matcher.test.ts +0 -1031
- package/src/core/pattern-matching/pattern-matcher.ts +0 -765
- package/src/core/pattern-matching/utils/index.ts +0 -6
- package/src/generation/pattern-generator.test.ts +0 -532
- package/src/generation/pattern-generator.ts +0 -327
- /package/dist/core/{pattern-matching/utils → matching}/possessive-keywords.d.ts +0 -0
- /package/src/core/{pattern-matching/utils → matching}/possessive-keywords.ts +0 -0
|
@@ -1,765 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pattern Matcher
|
|
3
|
-
*
|
|
4
|
-
* Matches tokenized input against language patterns to extract semantic roles.
|
|
5
|
-
* This is the core algorithm for multilingual parsing.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import type {
|
|
9
|
-
LanguagePattern,
|
|
10
|
-
PatternToken,
|
|
11
|
-
PatternMatchResult,
|
|
12
|
-
SemanticRole,
|
|
13
|
-
SemanticValue,
|
|
14
|
-
TokenStream,
|
|
15
|
-
LanguageToken,
|
|
16
|
-
} from '../types';
|
|
17
|
-
import { createLogger } from '../logger';
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
* Helper to check if a value is a built-in reference.
|
|
21
|
-
* In the generic framework, we don't assume any built-in references.
|
|
22
|
-
* DSLs that need references (like hyperscript's 'me', 'it', 'you') should
|
|
23
|
-
* handle them in their tokenizer or provide a custom reference validator.
|
|
24
|
-
*
|
|
25
|
-
* For generic DSLs, identifiers are treated as expressions by default.
|
|
26
|
-
*/
|
|
27
|
-
// A role's value is read by the code the stock reader runs too (core/matching/stock-reading.ts).
|
|
28
|
-
import { readRoleValue, safeToLowerCase } from '../matching/stock-reading';
|
|
29
|
-
import { stockConfidenceModel } from '../matching/stock-confidence';
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Minimal profile interface needed by PatternMatcher.
|
|
33
|
-
* DSLs can provide this to enable possessive handling and language-specific features.
|
|
34
|
-
*/
|
|
35
|
-
export interface PatternMatcherProfile {
|
|
36
|
-
readonly code: string;
|
|
37
|
-
readonly possessive?: {
|
|
38
|
-
readonly keywords?: Record<string, string>;
|
|
39
|
-
};
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// =============================================================================
|
|
43
|
-
// Pattern Matcher
|
|
44
|
-
// =============================================================================
|
|
45
|
-
|
|
46
|
-
export class PatternMatcher {
|
|
47
|
-
/** Maximum tokens to scan ahead when looking for a group's leading marker */
|
|
48
|
-
private static readonly MAX_MARKER_SCAN = 3;
|
|
49
|
-
|
|
50
|
-
/** Debug logger */
|
|
51
|
-
private logger = createLogger('pattern-matcher');
|
|
52
|
-
|
|
53
|
-
/** Current language profile for the pattern being matched */
|
|
54
|
-
private currentProfile: PatternMatcherProfile | undefined;
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
* Try to match a single pattern against the token stream.
|
|
58
|
-
* Returns the match result or null if no match.
|
|
59
|
-
*
|
|
60
|
-
* @param tokens - Token stream to match against
|
|
61
|
-
* @param pattern - Pattern to match
|
|
62
|
-
* @param profile - Optional language profile for possessive handling
|
|
63
|
-
*/
|
|
64
|
-
matchPattern(
|
|
65
|
-
tokens: TokenStream,
|
|
66
|
-
pattern: LanguagePattern,
|
|
67
|
-
profile?: PatternMatcherProfile
|
|
68
|
-
): PatternMatchResult | null {
|
|
69
|
-
const mark = tokens.mark();
|
|
70
|
-
const captured = new Map<SemanticRole, SemanticValue>();
|
|
71
|
-
|
|
72
|
-
// Debug logging
|
|
73
|
-
this.logger.debug('========================================');
|
|
74
|
-
this.logger.debug('matchPattern ENTRY');
|
|
75
|
-
this.logger.debug('Pattern ID:', pattern.id);
|
|
76
|
-
this.logger.debug('Pattern command:', pattern.command);
|
|
77
|
-
this.logger.debug('Pattern language:', pattern.language);
|
|
78
|
-
this.logger.debug('Pattern template:', JSON.stringify(pattern.template, null, 2));
|
|
79
|
-
|
|
80
|
-
if (this.logger.isEnabled()) {
|
|
81
|
-
const firstTokens = [];
|
|
82
|
-
for (let i = 0; i < 10; i++) {
|
|
83
|
-
const t = tokens.peek(i);
|
|
84
|
-
if (t)
|
|
85
|
-
firstTokens.push({
|
|
86
|
-
type: (t as any).type,
|
|
87
|
-
value: (t as any).value,
|
|
88
|
-
kind: (t as any).kind,
|
|
89
|
-
});
|
|
90
|
-
else break;
|
|
91
|
-
}
|
|
92
|
-
this.logger.debug('Input tokens (first 10):', firstTokens);
|
|
93
|
-
this.logger.debug('Profile code:', profile?.code);
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
// Use provided profile for possessive keyword lookup
|
|
97
|
-
this.currentProfile = profile;
|
|
98
|
-
|
|
99
|
-
// Reset match counters for this pattern
|
|
100
|
-
this.stemMatchCount = 0;
|
|
101
|
-
this.totalKeywordMatches = 0;
|
|
102
|
-
|
|
103
|
-
this.logger.debug('--- Calling matchTokenSequence ---');
|
|
104
|
-
this.logger.debug('Pattern tokens to match:', JSON.stringify(pattern.template.tokens, null, 2));
|
|
105
|
-
const success = this.matchTokenSequence(tokens, pattern.template.tokens, captured);
|
|
106
|
-
this.logger.debug('matchTokenSequence returned:', success);
|
|
107
|
-
this.logger.debug(
|
|
108
|
-
'Captured roles:',
|
|
109
|
-
Array.from(captured.entries()).map(([k, v]) => [k, JSON.stringify(v)])
|
|
110
|
-
);
|
|
111
|
-
|
|
112
|
-
if (!success) {
|
|
113
|
-
this.logger.debug('>>> MATCH FAILED - resetting token position');
|
|
114
|
-
tokens.reset(mark);
|
|
115
|
-
return null;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
// Calculate confidence BEFORE applying defaults
|
|
119
|
-
// This ensures defaulted roles don't artificially inflate confidence
|
|
120
|
-
const confidence = stockConfidenceModel.calculate({
|
|
121
|
-
pattern,
|
|
122
|
-
captured,
|
|
123
|
-
stemMatchCount: this.stemMatchCount,
|
|
124
|
-
totalKeywordMatches: this.totalKeywordMatches,
|
|
125
|
-
});
|
|
126
|
-
|
|
127
|
-
// Apply extraction rules to fill in any missing roles with defaults
|
|
128
|
-
this.applyExtractionRules(pattern, captured);
|
|
129
|
-
|
|
130
|
-
return {
|
|
131
|
-
pattern,
|
|
132
|
-
captured,
|
|
133
|
-
consumedTokens: tokens.position() - mark.position,
|
|
134
|
-
confidence,
|
|
135
|
-
};
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
/**
|
|
139
|
-
* Try to match multiple patterns, return the best match.
|
|
140
|
-
*
|
|
141
|
-
* @param tokens - Token stream to match against
|
|
142
|
-
* @param patterns - Candidate patterns to try
|
|
143
|
-
* @param profile - Optional language profile for possessive handling
|
|
144
|
-
*/
|
|
145
|
-
matchBest(
|
|
146
|
-
tokens: TokenStream,
|
|
147
|
-
patterns: LanguagePattern[],
|
|
148
|
-
profile?: PatternMatcherProfile
|
|
149
|
-
): PatternMatchResult | null {
|
|
150
|
-
const matches: PatternMatchResult[] = [];
|
|
151
|
-
|
|
152
|
-
for (const pattern of patterns) {
|
|
153
|
-
const mark = tokens.mark();
|
|
154
|
-
const result = this.matchPattern(tokens, pattern, profile);
|
|
155
|
-
|
|
156
|
-
if (result) {
|
|
157
|
-
matches.push(result);
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
tokens.reset(mark);
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
if (matches.length === 0) {
|
|
164
|
-
return null;
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
// Sort by confidence and priority
|
|
168
|
-
matches.sort((a, b) => {
|
|
169
|
-
// First by priority
|
|
170
|
-
const priorityDiff = b.pattern.priority - a.pattern.priority;
|
|
171
|
-
if (priorityDiff !== 0) return priorityDiff;
|
|
172
|
-
|
|
173
|
-
// Then by confidence
|
|
174
|
-
const confidenceDiff = b.confidence - a.confidence;
|
|
175
|
-
if (Math.abs(confidenceDiff) > 0.001) return confidenceDiff;
|
|
176
|
-
|
|
177
|
-
// Then by tokens consumed (prefer more complete matches)
|
|
178
|
-
return b.consumedTokens - a.consumedTokens;
|
|
179
|
-
});
|
|
180
|
-
|
|
181
|
-
// Re-consume tokens for the best match
|
|
182
|
-
const best = matches[0];
|
|
183
|
-
this.matchPattern(tokens, best.pattern);
|
|
184
|
-
|
|
185
|
-
return best;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
/**
|
|
189
|
-
* Match a sequence of pattern tokens against the token stream.
|
|
190
|
-
*
|
|
191
|
-
* Supports bounded single-step backtracking: if an optional role consumes
|
|
192
|
-
* a token and the immediately following pattern token fails, the matcher
|
|
193
|
-
* resets to before the optional role and retries the failed token.
|
|
194
|
-
*/
|
|
195
|
-
private matchTokenSequence(
|
|
196
|
-
tokens: TokenStream,
|
|
197
|
-
patternTokens: PatternToken[],
|
|
198
|
-
captured: Map<SemanticRole, SemanticValue>,
|
|
199
|
-
parentStopMarkers?: Set<string>
|
|
200
|
-
): boolean {
|
|
201
|
-
// Skip leading conjunctions for Arabic (proclitics: و, ف, ول, وب, etc.)
|
|
202
|
-
// BUT NOT if the pattern explicitly expects a conjunction (proclitic patterns)
|
|
203
|
-
const firstPatternToken = patternTokens[0];
|
|
204
|
-
const patternExpectsConjunction =
|
|
205
|
-
firstPatternToken?.type === 'literal' &&
|
|
206
|
-
(firstPatternToken.value === 'and' ||
|
|
207
|
-
firstPatternToken.value === 'then' ||
|
|
208
|
-
firstPatternToken.alternatives?.includes('and') ||
|
|
209
|
-
firstPatternToken.alternatives?.includes('then'));
|
|
210
|
-
|
|
211
|
-
if (this.currentProfile?.code === 'ar' && !patternExpectsConjunction) {
|
|
212
|
-
while (tokens.peek()?.kind === 'conjunction') {
|
|
213
|
-
tokens.advance();
|
|
214
|
-
}
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
// Backtracking state: track the most recent optional role that consumed a token
|
|
218
|
-
let prevOptionalMark: ReturnType<TokenStream['mark']> | null = null;
|
|
219
|
-
let prevOptionalRole: SemanticRole | null = null;
|
|
220
|
-
|
|
221
|
-
for (let i = 0; i < patternTokens.length; i++) {
|
|
222
|
-
const patternToken = patternTokens[i];
|
|
223
|
-
this.logger.debug(' >> Matching pattern token:', JSON.stringify(patternToken, null, 2));
|
|
224
|
-
const currTok = tokens.peek();
|
|
225
|
-
this.logger.debug(
|
|
226
|
-
' >> Current input token:',
|
|
227
|
-
currTok
|
|
228
|
-
? JSON.stringify({
|
|
229
|
-
type: (currTok as any).type,
|
|
230
|
-
value: (currTok as any).value,
|
|
231
|
-
kind: (currTok as any).kind,
|
|
232
|
-
})
|
|
233
|
-
: 'EOF'
|
|
234
|
-
);
|
|
235
|
-
|
|
236
|
-
// Greedy role capture: consume all remaining tokens until the next
|
|
237
|
-
// recognized marker keyword or end of input
|
|
238
|
-
if (patternToken.type === 'role' && patternToken.greedy) {
|
|
239
|
-
const stopMarkers = this.collectStopMarkers(patternTokens, i + 1);
|
|
240
|
-
// Merge parent-level stop markers so greedy roles inside groups
|
|
241
|
-
// know when to stop for tokens outside the group (e.g., SOV verb keywords)
|
|
242
|
-
if (parentStopMarkers) {
|
|
243
|
-
for (const m of parentStopMarkers) stopMarkers.add(m);
|
|
244
|
-
}
|
|
245
|
-
const values: string[] = [];
|
|
246
|
-
while (!tokens.isAtEnd()) {
|
|
247
|
-
const nextToken = tokens.peek();
|
|
248
|
-
if (!nextToken) break;
|
|
249
|
-
if (this.isStopMarker(nextToken, stopMarkers)) break;
|
|
250
|
-
values.push(nextToken.value);
|
|
251
|
-
tokens.advance();
|
|
252
|
-
}
|
|
253
|
-
if (values.length > 0) {
|
|
254
|
-
captured.set(patternToken.role, { type: 'expression', raw: values.join(' ') });
|
|
255
|
-
prevOptionalMark = null;
|
|
256
|
-
prevOptionalRole = null;
|
|
257
|
-
continue;
|
|
258
|
-
} else if (patternToken.optional) {
|
|
259
|
-
continue;
|
|
260
|
-
} else {
|
|
261
|
-
return false;
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// Group tokens: compute sibling stop markers and forward to inner matching
|
|
266
|
-
if (patternToken.type === 'group') {
|
|
267
|
-
const siblingStopMarkers = this.collectStopMarkers(patternTokens, i + 1);
|
|
268
|
-
if (parentStopMarkers) {
|
|
269
|
-
for (const m of parentStopMarkers) siblingStopMarkers.add(m);
|
|
270
|
-
}
|
|
271
|
-
const groupMatched = this.matchGroupToken(
|
|
272
|
-
tokens,
|
|
273
|
-
patternToken as PatternToken & { type: 'group' },
|
|
274
|
-
captured,
|
|
275
|
-
siblingStopMarkers
|
|
276
|
-
);
|
|
277
|
-
if (groupMatched) {
|
|
278
|
-
prevOptionalMark = null;
|
|
279
|
-
prevOptionalRole = null;
|
|
280
|
-
continue;
|
|
281
|
-
}
|
|
282
|
-
if (this.isOptional(patternToken)) {
|
|
283
|
-
continue;
|
|
284
|
-
}
|
|
285
|
-
return false;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
// Save stream position before attempting optional roles
|
|
289
|
-
const isOptionalRole = patternToken.type === 'role' && patternToken.optional === true;
|
|
290
|
-
const markBefore = isOptionalRole ? tokens.mark() : null;
|
|
291
|
-
|
|
292
|
-
// SOV marker-stealing guard: before matching a required role, check if
|
|
293
|
-
// the current input token would match the immediately-following pattern
|
|
294
|
-
// literal (the role's own postpositional marker). If so, skip consuming
|
|
295
|
-
// this token as a role value — it should be matched as the literal instead.
|
|
296
|
-
const isRoleToken = patternToken.type === 'role';
|
|
297
|
-
if (isRoleToken && !isOptionalRole) {
|
|
298
|
-
const nextPT = i + 1 < patternTokens.length ? patternTokens[i + 1] : null;
|
|
299
|
-
if (nextPT?.type === 'literal') {
|
|
300
|
-
const currentToken = tokens.peek();
|
|
301
|
-
if (currentToken && this.getMatchType(currentToken, nextPT.value) !== 'none') {
|
|
302
|
-
// Current token is the marker literal, not a role value — treat role as failed
|
|
303
|
-
this.logger.debug(
|
|
304
|
-
' >> MARKER-STEAL GUARD: current token matches next literal, skipping role'
|
|
305
|
-
);
|
|
306
|
-
// Fall through to failure handling below
|
|
307
|
-
// (which will trigger backtracking of previous optional role)
|
|
308
|
-
|
|
309
|
-
// Match failed
|
|
310
|
-
this.logger.debug(' >> Token match FAILED');
|
|
311
|
-
|
|
312
|
-
if (this.isOptional(patternToken)) {
|
|
313
|
-
continue;
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// Required token failed — try backtracking over the previous optional role
|
|
317
|
-
if (prevOptionalMark && prevOptionalRole) {
|
|
318
|
-
this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);
|
|
319
|
-
tokens.reset(prevOptionalMark);
|
|
320
|
-
captured.delete(prevOptionalRole);
|
|
321
|
-
prevOptionalMark = null;
|
|
322
|
-
prevOptionalRole = null;
|
|
323
|
-
|
|
324
|
-
// Retry the current (failed) pattern token from the restored position
|
|
325
|
-
const retryMatched = this.matchPatternToken(tokens, patternToken, captured);
|
|
326
|
-
this.logger.debug(' >> Backtrack retry result:', retryMatched);
|
|
327
|
-
if (retryMatched) {
|
|
328
|
-
continue;
|
|
329
|
-
}
|
|
330
|
-
}
|
|
331
|
-
|
|
332
|
-
return false;
|
|
333
|
-
}
|
|
334
|
-
}
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
const matched = this.matchPatternToken(tokens, patternToken, captured);
|
|
338
|
-
this.logger.debug(' >> Match result:', matched);
|
|
339
|
-
|
|
340
|
-
if (matched) {
|
|
341
|
-
if (isOptionalRole) {
|
|
342
|
-
// Track this consumption so we can undo it if the next token fails
|
|
343
|
-
prevOptionalMark = markBefore;
|
|
344
|
-
prevOptionalRole = patternToken.role;
|
|
345
|
-
} else {
|
|
346
|
-
// Non-optional succeeded — clear backtrack state
|
|
347
|
-
prevOptionalMark = null;
|
|
348
|
-
prevOptionalRole = null;
|
|
349
|
-
}
|
|
350
|
-
continue;
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
// Match failed
|
|
354
|
-
this.logger.debug(' >> Token match FAILED');
|
|
355
|
-
|
|
356
|
-
if (this.isOptional(patternToken)) {
|
|
357
|
-
continue;
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
// Required token failed — try backtracking over the previous optional role
|
|
361
|
-
if (prevOptionalMark && prevOptionalRole) {
|
|
362
|
-
this.logger.debug(' >> BACKTRACKING: undoing optional role', prevOptionalRole);
|
|
363
|
-
tokens.reset(prevOptionalMark);
|
|
364
|
-
captured.delete(prevOptionalRole);
|
|
365
|
-
prevOptionalMark = null;
|
|
366
|
-
prevOptionalRole = null;
|
|
367
|
-
|
|
368
|
-
// Retry the current (failed) pattern token from the restored position
|
|
369
|
-
const retryMatched = this.matchPatternToken(tokens, patternToken, captured);
|
|
370
|
-
this.logger.debug(' >> Backtrack retry result:', retryMatched);
|
|
371
|
-
if (retryMatched) {
|
|
372
|
-
continue;
|
|
373
|
-
}
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
return false;
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
return true;
|
|
380
|
-
}
|
|
381
|
-
|
|
382
|
-
/**
|
|
383
|
-
* Match a single pattern token against the current position in the stream.
|
|
384
|
-
*/
|
|
385
|
-
private matchPatternToken(
|
|
386
|
-
tokens: TokenStream,
|
|
387
|
-
patternToken: PatternToken,
|
|
388
|
-
captured: Map<SemanticRole, SemanticValue>
|
|
389
|
-
): boolean {
|
|
390
|
-
switch (patternToken.type) {
|
|
391
|
-
case 'literal':
|
|
392
|
-
return this.matchLiteralToken(tokens, patternToken);
|
|
393
|
-
|
|
394
|
-
case 'role':
|
|
395
|
-
return readRoleValue(tokens, patternToken, captured, this.currentProfile);
|
|
396
|
-
|
|
397
|
-
case 'group':
|
|
398
|
-
return this.matchGroupToken(tokens, patternToken, captured);
|
|
399
|
-
|
|
400
|
-
default:
|
|
401
|
-
return false;
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
|
|
405
|
-
/**
|
|
406
|
-
* Match a literal pattern token (keyword or particle).
|
|
407
|
-
*/
|
|
408
|
-
private matchLiteralToken(
|
|
409
|
-
tokens: TokenStream,
|
|
410
|
-
patternToken: PatternToken & { type: 'literal' }
|
|
411
|
-
): boolean {
|
|
412
|
-
const token = tokens.peek();
|
|
413
|
-
this.logger.debug(' >>> matchLiteralToken: expecting', patternToken.value);
|
|
414
|
-
this.logger.debug(
|
|
415
|
-
' >>> matchLiteralToken: got token',
|
|
416
|
-
token
|
|
417
|
-
? JSON.stringify({
|
|
418
|
-
type: (token as any).type,
|
|
419
|
-
value: (token as any).value,
|
|
420
|
-
kind: (token as any).kind,
|
|
421
|
-
})
|
|
422
|
-
: 'null'
|
|
423
|
-
);
|
|
424
|
-
if (!token) {
|
|
425
|
-
this.logger.debug(' >>> matchLiteralToken: FAIL - no token');
|
|
426
|
-
return false;
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
// Check main value
|
|
430
|
-
const matchType = this.getMatchType(token, patternToken.value);
|
|
431
|
-
this.logger.debug(
|
|
432
|
-
' >>> matchType for',
|
|
433
|
-
token.value,
|
|
434
|
-
'vs',
|
|
435
|
-
patternToken.value,
|
|
436
|
-
':',
|
|
437
|
-
matchType
|
|
438
|
-
);
|
|
439
|
-
if (matchType !== 'none') {
|
|
440
|
-
this.totalKeywordMatches++;
|
|
441
|
-
if (matchType === 'stem') {
|
|
442
|
-
this.stemMatchCount++;
|
|
443
|
-
}
|
|
444
|
-
tokens.advance();
|
|
445
|
-
return true;
|
|
446
|
-
}
|
|
447
|
-
|
|
448
|
-
// Check alternatives
|
|
449
|
-
if (patternToken.alternatives) {
|
|
450
|
-
for (const alt of patternToken.alternatives) {
|
|
451
|
-
const altMatchType = this.getMatchType(token, alt);
|
|
452
|
-
if (altMatchType !== 'none') {
|
|
453
|
-
this.totalKeywordMatches++;
|
|
454
|
-
if (altMatchType === 'stem') {
|
|
455
|
-
this.stemMatchCount++;
|
|
456
|
-
}
|
|
457
|
-
tokens.advance();
|
|
458
|
-
return true;
|
|
459
|
-
}
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
|
|
463
|
-
return false;
|
|
464
|
-
}
|
|
465
|
-
|
|
466
|
-
/**
|
|
467
|
-
* Match a group pattern token (optional sequence).
|
|
468
|
-
* When the group's leading marker isn't at the current position, scans ahead
|
|
469
|
-
* up to MAX_MARKER_SCAN tokens to find it. This allows unmarked tokens
|
|
470
|
-
* (e.g., a value like 'hello') to sit between groups without blocking later
|
|
471
|
-
* marker matches.
|
|
472
|
-
*/
|
|
473
|
-
private matchGroupToken(
|
|
474
|
-
tokens: TokenStream,
|
|
475
|
-
patternToken: PatternToken & { type: 'group' },
|
|
476
|
-
captured: Map<SemanticRole, SemanticValue>,
|
|
477
|
-
parentStopMarkers?: Set<string>
|
|
478
|
-
): boolean {
|
|
479
|
-
const mark = tokens.mark();
|
|
480
|
-
const capturedBefore = new Set(captured.keys());
|
|
481
|
-
|
|
482
|
-
const success = this.matchTokenSequence(
|
|
483
|
-
tokens,
|
|
484
|
-
patternToken.tokens,
|
|
485
|
-
captured,
|
|
486
|
-
parentStopMarkers
|
|
487
|
-
);
|
|
488
|
-
if (success) return true;
|
|
489
|
-
|
|
490
|
-
// Reset from failed attempt
|
|
491
|
-
tokens.reset(mark);
|
|
492
|
-
for (const role of captured.keys()) {
|
|
493
|
-
if (!capturedBefore.has(role)) captured.delete(role);
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
if (!patternToken.optional) return false;
|
|
497
|
-
|
|
498
|
-
// Marker scan: look ahead for the group's leading marker past intervening tokens.
|
|
499
|
-
// This handles cases like "types 'hello' into #search" where 'hello' blocks the
|
|
500
|
-
// 'into' marker from being found at the current position.
|
|
501
|
-
const leadingMarker = this.getGroupLeadingMarker(patternToken);
|
|
502
|
-
if (leadingMarker) {
|
|
503
|
-
for (let offset = 1; offset <= PatternMatcher.MAX_MARKER_SCAN; offset++) {
|
|
504
|
-
const ahead = tokens.peek(offset);
|
|
505
|
-
if (!ahead) break;
|
|
506
|
-
const aheadValue = (ahead.normalized || ahead.value).toLowerCase();
|
|
507
|
-
if (aheadValue === leadingMarker) {
|
|
508
|
-
this.logger.debug(
|
|
509
|
-
' >> MARKER SCAN: found',
|
|
510
|
-
leadingMarker,
|
|
511
|
-
'at offset',
|
|
512
|
-
offset,
|
|
513
|
-
'- skipping intervening tokens'
|
|
514
|
-
);
|
|
515
|
-
// Advance past intervening tokens to reach the marker
|
|
516
|
-
for (let s = 0; s < offset; s++) tokens.advance();
|
|
517
|
-
|
|
518
|
-
// Retry group match from marker position
|
|
519
|
-
const retrySuccess = this.matchTokenSequence(
|
|
520
|
-
tokens,
|
|
521
|
-
patternToken.tokens,
|
|
522
|
-
captured,
|
|
523
|
-
parentStopMarkers
|
|
524
|
-
);
|
|
525
|
-
if (retrySuccess) return true;
|
|
526
|
-
|
|
527
|
-
// Retry failed — full reset
|
|
528
|
-
tokens.reset(mark);
|
|
529
|
-
for (const role of captured.keys()) {
|
|
530
|
-
if (!capturedBefore.has(role)) captured.delete(role);
|
|
531
|
-
}
|
|
532
|
-
break;
|
|
533
|
-
}
|
|
534
|
-
}
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
return true; // Optional group, just skip
|
|
538
|
-
}
|
|
539
|
-
|
|
540
|
-
/**
|
|
541
|
-
* Get the leading marker literal from an optional group.
|
|
542
|
-
* Returns the lowercase marker value, or null if the group
|
|
543
|
-
* doesn't start with a literal token (e.g., SOV groups where
|
|
544
|
-
* the role comes before the marker).
|
|
545
|
-
*/
|
|
546
|
-
private getGroupLeadingMarker(group: PatternToken & { type: 'group' }): string | null {
|
|
547
|
-
const first = group.tokens[0];
|
|
548
|
-
if (first?.type === 'literal') return first.value.toLowerCase();
|
|
549
|
-
return null;
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
/**
|
|
553
|
-
* Get the type of match for a token against a value.
|
|
554
|
-
* Used for confidence calculation.
|
|
555
|
-
*/
|
|
556
|
-
private getMatchType(
|
|
557
|
-
token: LanguageToken,
|
|
558
|
-
value: string
|
|
559
|
-
): 'exact' | 'normalized' | 'stem' | 'case-insensitive' | 'none' {
|
|
560
|
-
// Exact match (highest confidence)
|
|
561
|
-
if (token.value === value) return 'exact';
|
|
562
|
-
|
|
563
|
-
// Explicit keyword map normalized match (high confidence)
|
|
564
|
-
if (token.normalized === value) return 'normalized';
|
|
565
|
-
|
|
566
|
-
// Morphologically normalized stem match (medium-high confidence)
|
|
567
|
-
// Only accept if stem confidence is reasonable
|
|
568
|
-
if (token.stem === value && token.stemConfidence !== undefined && token.stemConfidence >= 0.7) {
|
|
569
|
-
return 'stem';
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
// Case-insensitive match for keywords (medium confidence)
|
|
573
|
-
if (token.kind === 'keyword' && safeToLowerCase(token.value) === value.toLowerCase()) {
|
|
574
|
-
return 'case-insensitive';
|
|
575
|
-
}
|
|
576
|
-
|
|
577
|
-
return 'none';
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
/**
|
|
581
|
-
* Collect literal values from upcoming pattern tokens that act as stop markers
|
|
582
|
-
* for greedy role capture. Returns the set of lowercase values.
|
|
583
|
-
*/
|
|
584
|
-
private collectStopMarkers(patternTokens: PatternToken[], startIndex: number): Set<string> {
|
|
585
|
-
const markers = new Set<string>();
|
|
586
|
-
for (let j = startIndex; j < patternTokens.length; j++) {
|
|
587
|
-
const pt = patternTokens[j];
|
|
588
|
-
if (pt.type === 'literal') {
|
|
589
|
-
markers.add(pt.value.toLowerCase());
|
|
590
|
-
if (pt.alternatives) {
|
|
591
|
-
for (const alt of pt.alternatives) {
|
|
592
|
-
markers.add(alt.toLowerCase());
|
|
593
|
-
}
|
|
594
|
-
}
|
|
595
|
-
break;
|
|
596
|
-
}
|
|
597
|
-
if (pt.type === 'group') {
|
|
598
|
-
for (const gt of pt.tokens) {
|
|
599
|
-
if (gt.type === 'literal') {
|
|
600
|
-
markers.add(gt.value.toLowerCase());
|
|
601
|
-
if (gt.alternatives) {
|
|
602
|
-
for (const alt of gt.alternatives) {
|
|
603
|
-
markers.add(alt.toLowerCase());
|
|
604
|
-
}
|
|
605
|
-
}
|
|
606
|
-
break;
|
|
607
|
-
}
|
|
608
|
-
}
|
|
609
|
-
// For optional groups, continue scanning past them so the greedy
|
|
610
|
-
// capture also sees subsequent required literals (e.g., the SOV verb
|
|
611
|
-
// keyword after an optional WHERE group).
|
|
612
|
-
if (!pt.optional) break;
|
|
613
|
-
}
|
|
614
|
-
}
|
|
615
|
-
return markers;
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
/**
|
|
619
|
-
* Check if a token matches any stop marker for greedy capture.
|
|
620
|
-
*/
|
|
621
|
-
private isStopMarker(token: LanguageToken, stopMarkers: Set<string>): boolean {
|
|
622
|
-
if (stopMarkers.size === 0) return false;
|
|
623
|
-
// Check both raw value and normalized form against stop markers.
|
|
624
|
-
// Pattern literals use native keywords (e.g., '選択') while tokenizers may
|
|
625
|
-
// set normalized to the English equivalent (e.g., 'select'). Both must match.
|
|
626
|
-
if (stopMarkers.has(token.value.toLowerCase())) return true;
|
|
627
|
-
if (token.normalized && stopMarkers.has(token.normalized.toLowerCase())) return true;
|
|
628
|
-
return false;
|
|
629
|
-
}
|
|
630
|
-
|
|
631
|
-
/**
|
|
632
|
-
* Track stem matches for confidence calculation.
|
|
633
|
-
* This is set during matching and read during confidence calculation.
|
|
634
|
-
*/
|
|
635
|
-
private stemMatchCount: number = 0;
|
|
636
|
-
private totalKeywordMatches: number = 0;
|
|
637
|
-
|
|
638
|
-
// ==========================================================================
|
|
639
|
-
// Depth Limits for Expression Parsing (security hardening)
|
|
640
|
-
// ==========================================================================
|
|
641
|
-
|
|
642
|
-
/**
|
|
643
|
-
* Apply extraction rules to fill in static values and defaults for missing roles.
|
|
644
|
-
*/
|
|
645
|
-
private applyExtractionRules(
|
|
646
|
-
pattern: LanguagePattern,
|
|
647
|
-
captured: Map<SemanticRole, SemanticValue>
|
|
648
|
-
): void {
|
|
649
|
-
for (const [role, rule] of Object.entries(pattern.extraction)) {
|
|
650
|
-
if (!captured.has(role as SemanticRole)) {
|
|
651
|
-
if (rule.value !== undefined) {
|
|
652
|
-
// Static value extraction (e.g., action: { value: "toggle" })
|
|
653
|
-
captured.set(role as SemanticRole, { type: 'literal', value: rule.value });
|
|
654
|
-
} else if (rule.default) {
|
|
655
|
-
captured.set(role as SemanticRole, rule.default);
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
}
|
|
660
|
-
|
|
661
|
-
/**
|
|
662
|
-
* Check if a pattern token is optional.
|
|
663
|
-
*/
|
|
664
|
-
private isOptional(patternToken: PatternToken): boolean {
|
|
665
|
-
return patternToken.type !== 'literal' && patternToken.optional === true;
|
|
666
|
-
}
|
|
667
|
-
|
|
668
|
-
// ===========================================================================
|
|
669
|
-
// English Idiom Support - Noise Word Handling
|
|
670
|
-
// ===========================================================================
|
|
671
|
-
|
|
672
|
-
/**
|
|
673
|
-
* Extract event modifiers from the token stream.
|
|
674
|
-
* Event modifiers are .once, .debounce(N), .throttle(N), .queue(strategy)
|
|
675
|
-
* that can appear after event names.
|
|
676
|
-
*
|
|
677
|
-
* Returns EventModifiers object or undefined if no modifiers found.
|
|
678
|
-
*/
|
|
679
|
-
extractEventModifiers(tokens: TokenStream): import('../types').EventModifiers | undefined {
|
|
680
|
-
const modifiers: {
|
|
681
|
-
once?: boolean;
|
|
682
|
-
debounce?: number;
|
|
683
|
-
throttle?: number;
|
|
684
|
-
queue?: 'first' | 'last' | 'all' | 'none';
|
|
685
|
-
from?: SemanticValue;
|
|
686
|
-
} = {};
|
|
687
|
-
|
|
688
|
-
let foundModifier = false;
|
|
689
|
-
|
|
690
|
-
// Consume all consecutive event modifier tokens
|
|
691
|
-
while (!tokens.isAtEnd()) {
|
|
692
|
-
const token = tokens.peek();
|
|
693
|
-
if (!token || token.kind !== 'event-modifier') {
|
|
694
|
-
break;
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
const metadata = token.metadata as
|
|
698
|
-
{ modifierName: string; value?: number | string } | undefined;
|
|
699
|
-
if (!metadata) {
|
|
700
|
-
break;
|
|
701
|
-
}
|
|
702
|
-
|
|
703
|
-
foundModifier = true;
|
|
704
|
-
|
|
705
|
-
switch (metadata.modifierName) {
|
|
706
|
-
case 'once':
|
|
707
|
-
modifiers.once = true;
|
|
708
|
-
break;
|
|
709
|
-
case 'debounce':
|
|
710
|
-
if (typeof metadata.value === 'number') {
|
|
711
|
-
modifiers.debounce = metadata.value;
|
|
712
|
-
}
|
|
713
|
-
break;
|
|
714
|
-
case 'throttle':
|
|
715
|
-
if (typeof metadata.value === 'number') {
|
|
716
|
-
modifiers.throttle = metadata.value;
|
|
717
|
-
}
|
|
718
|
-
break;
|
|
719
|
-
case 'queue':
|
|
720
|
-
if (
|
|
721
|
-
metadata.value === 'first' ||
|
|
722
|
-
metadata.value === 'last' ||
|
|
723
|
-
metadata.value === 'all' ||
|
|
724
|
-
metadata.value === 'none'
|
|
725
|
-
) {
|
|
726
|
-
modifiers.queue = metadata.value;
|
|
727
|
-
}
|
|
728
|
-
break;
|
|
729
|
-
}
|
|
730
|
-
|
|
731
|
-
tokens.advance();
|
|
732
|
-
}
|
|
733
|
-
|
|
734
|
-
return foundModifier ? modifiers : undefined;
|
|
735
|
-
}
|
|
736
|
-
}
|
|
737
|
-
|
|
738
|
-
// =============================================================================
|
|
739
|
-
// Convenience Functions
|
|
740
|
-
// =============================================================================
|
|
741
|
-
|
|
742
|
-
/**
|
|
743
|
-
* Singleton pattern matcher instance.
|
|
744
|
-
*/
|
|
745
|
-
export const patternMatcher = new PatternMatcher();
|
|
746
|
-
|
|
747
|
-
/**
|
|
748
|
-
* Match tokens against a pattern.
|
|
749
|
-
*/
|
|
750
|
-
export function matchPattern(
|
|
751
|
-
tokens: TokenStream,
|
|
752
|
-
pattern: LanguagePattern
|
|
753
|
-
): PatternMatchResult | null {
|
|
754
|
-
return patternMatcher.matchPattern(tokens, pattern);
|
|
755
|
-
}
|
|
756
|
-
|
|
757
|
-
/**
|
|
758
|
-
* Match tokens against multiple patterns, return best match.
|
|
759
|
-
*/
|
|
760
|
-
export function matchBest(
|
|
761
|
-
tokens: TokenStream,
|
|
762
|
-
patterns: LanguagePattern[]
|
|
763
|
-
): PatternMatchResult | null {
|
|
764
|
-
return patternMatcher.matchBest(tokens, patterns);
|
|
765
|
-
}
|