@tylix/compiler 1.1.0 → 1.2.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tylix/compiler",
3
- "version": "1.1.0",
3
+ "version": "1.2.0",
4
4
  "description": "Compiler for Tylix .tyx pages and components: parses, type-checks and compiles them to server-rendered HTML and client JavaScript.",
5
5
  "license": "MIT",
6
6
  "author": "Mbiyrukzz",
@@ -0,0 +1,360 @@
1
+ // One entry point for tools that need to know what is wrong with a
2
+ // .tyx file and where: `tylix check`, the dev error overlay and the
3
+ // editor language server all call diagnoseTyx().
4
+ //
5
+ // const { kind, name, diagnostics, symbols } = diagnoseTyx(source, {
6
+ // language: { not: 'loose' }, // same switches as the real build
7
+ // typecheck: true, // run the TypeScript checker (pages
8
+ // // and components)
9
+ // apiHelpersSource: '', // app/useApi/*.ts, module syntax stripped
10
+ // })
11
+ //
12
+ // Positions are 1-based lines and columns in `source` itself (not in a
13
+ // section), so they can be shown or underlined as they are.
14
+ //
15
+ // Only files that start with `page`, `component` or `capability` are
16
+ // Tylix. Anything else that happens to end in .tyx (generator
17
+ // templates, legacy <script>/<template> components) comes back as
18
+ // kind 'other' with no diagnostics.
19
+ import { Lexer } from '../lexer/Lexer.js'
20
+ import { Parser } from '../parser/Parser.js'
21
+ import { parsePageFile } from '../parser/parsePageFile.js'
22
+ import { parseComponentFile } from '../parser/parseComponentFile.js'
23
+ import { parseTemplate } from '../parser/parseTemplate.js'
24
+ import { normalizeLanguageOptions } from '../parser/languageOptions.js'
25
+ import { extractImports } from '../imports/extractImports.js'
26
+ import { typecheckPage } from '../typecheckPage.js'
27
+ import { generateParams } from '../codegen/generateExpression.js'
28
+
29
+ const HEADER_RE = /^\s*(page|component|capability)\s+([A-Za-z_$][A-Za-z0-9_$]*)/
30
+
31
+ // { kind: 'page' | 'component' | 'capability', name } or
32
+ // { kind: 'other', name: null }.
33
+ export function detectTyxKind(source) {
34
+ const m = HEADER_RE.exec(source)
35
+ return m ? { kind: m[1], name: m[2] } : { kind: 'other', name: null }
36
+ }
37
+
38
+ // 1-based { line, column } of a character offset.
39
+ export function offsetToPosition(source, offset) {
40
+ const clamped = Math.max(0, Math.min(offset, source.length))
41
+ let line = 1
42
+ let lineStart = 0
43
+ for (let i = 0; i < clamped; i++) {
44
+ if (source.charCodeAt(i) === 10) {
45
+ line++
46
+ lineStart = i + 1
47
+ }
48
+ }
49
+ return { line, column: clamped - lineStart + 1 }
50
+ }
51
+
52
+ // Character offset of a 1-based line's first character.
53
+ function lineStartOffset(source, line) {
54
+ let offset = 0
55
+ for (let l = 1; l < line; l++) {
56
+ const next = source.indexOf('\n', offset)
57
+ if (next === -1) return source.length
58
+ offset = next + 1
59
+ }
60
+ return offset
61
+ }
62
+
63
+ // Token types as people write them, for messages like
64
+ // "Unexpected token EQUALS" -> 'Unexpected "="'.
65
+ const TOKEN_TEXT = {
66
+ EOF: 'end of input', IDENTIFIER: 'a name', NUMBER: 'a number',
67
+ STRING: 'a string', TEMPLATE_LITERAL: 'a template literal',
68
+ LBRACE: '{', RBRACE: '}', LPAREN: '(', RPAREN: ')', LBRACKET: '[',
69
+ RBRACKET: ']', COLON: ':', COMMA: ',', EQUALS: '=', SEMICOLON: ';',
70
+ DOT: '.', SPREAD: '...', ARROW: '=>', QUESTION: '?', QUESTION_DOT: '?.',
71
+ NULLISH: '??', PLUS: '+', MINUS: '-', STAR: '*', SLASH: '/', PERCENT: '%',
72
+ GT: '>', LT: '<', GTE: '>=', LTE: '<=', PIPE: '|', AMP: '&',
73
+ PLUS_EQUALS: '+=', MINUS_EQUALS: '-=', PLUS_PLUS: '++', MINUS_MINUS: '--',
74
+ }
75
+
76
+ function tokenText(type) {
77
+ if (TOKEN_TEXT[type]) {
78
+ const t = TOKEN_TEXT[type]
79
+ return /^[a-z]/.test(t) ? t : `"${t}"`
80
+ }
81
+ return `"${type.toLowerCase()}"` // keywords: ACTION -> "action"
82
+ }
83
+
84
+ // Messages carry "at line N" for the terminal; the position is now a
85
+ // field of its own, and N was often relative to a section anyway.
86
+ function cleanMessage(message) {
87
+ return String(message ?? 'Unknown error')
88
+ .replace(/\s+\(line \d+\)/g, '')
89
+ .replace(/\s+(?:starting )?at line \d+(?=[\s,:;.)]|$)/g, '')
90
+ .replace(/\b(Unexpected token|got) ([A-Z][A-Z_]+)\b/g, (_, lead, type) =>
91
+ `${lead === 'got' ? 'got' : 'Unexpected'} ${tokenText(type)}`,
92
+ )
93
+ .trim()
94
+ }
95
+
96
+ function rangeDiagnostic(source, offset, length, message, origin) {
97
+ const start = offsetToPosition(source, offset)
98
+ const width = Math.max(1, length ?? 1)
99
+ const end = offsetToPosition(source, offset + width)
100
+ return {
101
+ severity: 'error',
102
+ origin,
103
+ message: cleanMessage(message),
104
+ line: start.line,
105
+ column: start.column,
106
+ endLine: end.line,
107
+ endColumn: end.column,
108
+ offset,
109
+ length: width,
110
+ }
111
+ }
112
+
113
+ // A whole-line diagnostic (typecheck results only know the line).
114
+ function lineDiagnostic(source, line, message, origin) {
115
+ const lines = source.split('\n')
116
+ const safeLine = Math.max(1, Math.min(line, lines.length))
117
+ const text = lines[safeLine - 1] ?? ''
118
+ const indent = text.length - text.trimStart().length
119
+ const offset = lineStartOffset(source, safeLine) + indent
120
+ return {
121
+ ...rangeDiagnostic(
122
+ source,
123
+ offset,
124
+ Math.max(1, text.trimEnd().length - indent),
125
+ message,
126
+ origin,
127
+ ),
128
+ message: String(message).trim(),
129
+ }
130
+ }
131
+
132
+ // Turns an error thrown while parsing one section into a diagnostic in
133
+ // the file. `base` is where that section's text starts in `source`.
134
+ function sectionError(source, err, base, origin) {
135
+ if (typeof err?.offset === 'number') {
136
+ return rangeDiagnostic(
137
+ source,
138
+ base + err.offset,
139
+ err.length,
140
+ err.message,
141
+ origin,
142
+ )
143
+ }
144
+ const m = /at line (\d+)/.exec(err?.message ?? '')
145
+ const baseLine = offsetToPosition(source, base).line
146
+ const line = m ? baseLine + Number(m[1]) - 1 : baseLine
147
+ return lineDiagnostic(source, line, cleanMessage(err?.message), origin)
148
+ }
149
+
150
+ function describeParams(params) {
151
+ try {
152
+ return `(${generateParams(params ?? [], true)})`
153
+ } catch {
154
+ return '()'
155
+ }
156
+ }
157
+
158
+ // Outline entries for the editor (document symbols, completion, hover).
159
+ // `line` is absolute; script AST lines count from the script start.
160
+ function collectSymbols(node, scriptLineBase) {
161
+ const at = (l) => (typeof l === 'number' ? scriptLineBase + l - 1 : scriptLineBase)
162
+ const out = []
163
+ for (const p of node.props ?? []) {
164
+ out.push({
165
+ kind: 'prop',
166
+ name: p.name,
167
+ detail: `${p.name}${p.optional ? '?' : ''}: ${p.propType ?? 'any'}`,
168
+ line: at(p.line),
169
+ })
170
+ }
171
+ for (const s of node.state ?? []) {
172
+ out.push({
173
+ kind: 'state',
174
+ name: s.name,
175
+ detail: `${s.name}: ${s.typeAnnotation ?? 'any'}`,
176
+ line: at(s.line),
177
+ })
178
+ }
179
+ for (const c of node.computed ?? []) {
180
+ out.push({
181
+ kind: 'computed',
182
+ name: c.name,
183
+ detail: `${c.name}${c.returnType ? `: ${c.returnType}` : ''}`,
184
+ line: at(c.line),
185
+ })
186
+ }
187
+ for (const a of node.actions ?? []) {
188
+ out.push({
189
+ kind: 'action',
190
+ name: a.name,
191
+ detail: `${a.isAsync ? 'async ' : ''}${a.name}${describeParams(a.params)}${a.returnType ? `: ${a.returnType}` : ''}`,
192
+ line: at(a.line),
193
+ })
194
+ }
195
+ for (const u of [...(node.uses ?? []), ...(node.needs ?? [])]) {
196
+ out.push({ kind: 'uses', name: u.name, detail: `uses ${u.name}`, line: at(u.line) })
197
+ }
198
+ if (node.onMount) {
199
+ out.push({ kind: 'lifecycle', name: 'onMount', detail: 'onMount', line: at(node.onMount.line) })
200
+ }
201
+ if (node.init) {
202
+ out.push({ kind: 'lifecycle', name: 'init', detail: 'init', line: at(node.init.line) })
203
+ }
204
+ return out
205
+ }
206
+
207
+ // "missing template section" while a line does start with `template`
208
+ // means an unclosed ( { or [ above it swallowed the keyword. Parsing
209
+ // the script up to that line finds the real mistake.
210
+ function hiddenTemplateError(source, clean, language) {
211
+ const header = HEADER_RE.exec(clean)
212
+ const templateLine = /^[ \t]*template[ \t]*\r?$/m.exec(clean)
213
+ if (!header || !templateLine) return null
214
+ const base = header.index + header[0].length
215
+ const script = clean.slice(base, templateLine.index)
216
+ let tokens
217
+ try {
218
+ tokens = new Lexer(script).tokenize()
219
+ } catch (err) {
220
+ return sectionError(source, err, base, 'syntax')
221
+ }
222
+ const pairs = { RPAREN: 'LPAREN', RBRACE: 'LBRACE', RBRACKET: 'LBRACKET' }
223
+ const open = []
224
+ for (const t of tokens) {
225
+ if (t.type === 'LPAREN' || t.type === 'LBRACE' || t.type === 'LBRACKET') {
226
+ open.push(t)
227
+ } else if (pairs[t.type] && open.at(-1)?.type === pairs[t.type]) {
228
+ open.pop()
229
+ }
230
+ }
231
+ const culprit = open.at(-1)
232
+ if (culprit) {
233
+ return rangeDiagnostic(
234
+ source,
235
+ base + culprit.start,
236
+ 1,
237
+ `"${culprit.value}" is never closed, so the template section below it is hidden`,
238
+ 'syntax',
239
+ )
240
+ }
241
+ try {
242
+ new Parser(tokens, language).parse()
243
+ } catch (err) {
244
+ return sectionError(source, err, base, 'syntax')
245
+ }
246
+ return null
247
+ }
248
+
249
+ export function diagnoseTyx(source, options = {}) {
250
+ const { kind, name } = detectTyxKind(source)
251
+ const result = { kind, name, diagnostics: [], symbols: [], imports: [] }
252
+ if (kind === 'other') return result
253
+
254
+ let language
255
+ try {
256
+ language = normalizeLanguageOptions(options.language ?? {})
257
+ } catch (err) {
258
+ result.diagnostics.push(lineDiagnostic(source, 1, err.message, 'config'))
259
+ return result
260
+ }
261
+
262
+ // Import lines are blanked line-for-line, so lines (and columns below
263
+ // the imports) are unchanged in `clean`.
264
+ let clean = source
265
+ if (kind !== 'capability') {
266
+ try {
267
+ const extracted = extractImports(source)
268
+ clean = extracted.source
269
+ result.imports = extracted.imports
270
+ } catch (err) {
271
+ const m = /line (\d+)/.exec(err.message)
272
+ result.diagnostics.push(
273
+ lineDiagnostic(source, m ? Number(m[1]) : 1, cleanMessage(err.message), 'imports'),
274
+ )
275
+ return result
276
+ }
277
+ }
278
+
279
+ if (kind === 'capability') {
280
+ try {
281
+ const node = new Parser(new Lexer(clean).tokenize(), language).parseCapability()
282
+ result.symbols = collectSymbols(node, 1)
283
+ } catch (err) {
284
+ result.diagnostics.push(sectionError(clean, err, 0, 'syntax'))
285
+ }
286
+ return result
287
+ }
288
+
289
+ let parts
290
+ try {
291
+ parts = kind === 'page' ? parsePageFile(clean) : parseComponentFile(clean)
292
+ } catch (err) {
293
+ result.diagnostics.push(hiddenTemplateError(clean, clean, language) ??
294
+ lineDiagnostic(clean, 1, err.message, 'syntax'))
295
+ return result
296
+ }
297
+
298
+ const scriptLineBase = offsetToPosition(clean, parts.scriptOffset).line
299
+ if (parts.script.trim().length > 0) {
300
+ try {
301
+ const node = new Parser(new Lexer(parts.script).tokenize(), language).parse()
302
+ result.symbols = collectSymbols(node, scriptLineBase)
303
+ } catch (err) {
304
+ result.diagnostics.push(sectionError(clean, err, parts.scriptOffset, 'syntax'))
305
+ }
306
+ }
307
+
308
+ if (parts.template.trim().length > 0) {
309
+ try {
310
+ parseTemplate(parts.template, language)
311
+ } catch (err) {
312
+ result.diagnostics.push(
313
+ sectionError(clean, err, parts.templateOffset, 'syntax'),
314
+ )
315
+ }
316
+ }
317
+
318
+ // Types only mean something once the file parses.
319
+ if (options.typecheck && result.diagnostics.length === 0) {
320
+ // typecheckPage wants a `page` header; a component has the same
321
+ // sections. Same-length swap, so every line stays where it is.
322
+ const asPage =
323
+ kind === 'component'
324
+ ? clean.replace(/^(\s*)component(\s)/, '$1page $2')
325
+ : clean
326
+ try {
327
+ for (const d of typecheckPage(asPage, options.apiHelpersSource ?? '', language)) {
328
+ result.diagnostics.push(lineDiagnostic(clean, d.line, d.message, 'typecheck'))
329
+ }
330
+ } catch (err) {
331
+ result.diagnostics.push(lineDiagnostic(clean, 1, err.message, 'typecheck'))
332
+ }
333
+ }
334
+
335
+ // Offsets were measured in `clean`; give them in `source`.
336
+ for (const d of result.diagnostics) {
337
+ d.offset = lineStartOffset(source, d.line) + d.column - 1
338
+ }
339
+ return result
340
+ }
341
+
342
+ // "file:line:col message" with a two-line code frame and a caret, for
343
+ // terminals and the dev overlay's plain-text copy.
344
+ export function formatDiagnostic(source, d, file = '') {
345
+ const lines = source.split('\n')
346
+ const out = [`${file ? `${file}:` : ''}${d.line}:${d.column} ${d.message}`]
347
+ const from = Math.max(1, d.line - 2)
348
+ const to = Math.min(lines.length, d.line + 1)
349
+ const width = String(to).length
350
+ for (let l = from; l <= to; l++) {
351
+ const marker = l === d.line ? '>' : ' '
352
+ out.push(`${marker} ${String(l).padStart(width)} | ${lines[l - 1]}`)
353
+ if (l === d.line) {
354
+ const span =
355
+ d.endLine === d.line ? Math.max(1, d.endColumn - d.column) : 1
356
+ out.push(` ${' '.repeat(width)} | ${' '.repeat(d.column - 1)}${'^'.repeat(span)}`)
357
+ }
358
+ }
359
+ return out.join('\n')
360
+ }
package/src/index.js CHANGED
@@ -21,4 +21,5 @@ export * from './typecheck/transpileHelperSource.js'
21
21
  export * from './imports/extractImports.js'
22
22
  export * from './imports/resolveImports.js'
23
23
  export * from './runtime/capability.js'
24
- export * from './codegen/generateCapability.js'
24
+ export * from './codegen/generateCapability.js'
25
+ export * from './diagnostics/diagnose.js'
@@ -163,7 +163,20 @@ export class Lexer {
163
163
  this.tokenStart = 0
164
164
  }
165
165
 
166
+ // Errors leave with `offset` (a character index into this source)
167
+ // so tools can point at the exact spot, not just the line.
166
168
  tokenize() {
169
+ try {
170
+ return this.tokenizeAll()
171
+ } catch (err) {
172
+ if (err && typeof err === 'object' && err.offset === undefined) {
173
+ err.offset = this.tokenStart
174
+ }
175
+ throw err
176
+ }
177
+ }
178
+
179
+ tokenizeAll() {
167
180
  const src = this.source
168
181
 
169
182
  while (this.pos < src.length) {
@@ -252,6 +252,14 @@ function hasExpr(collection, value) {
252
252
  * `yield`, `class`, `extends`, `debugger`) are ordinary identifier
253
253
  * tokens; the parser recognises them by position.
254
254
  */
255
+ // Best-effort width of a token for error underlines.
256
+ function tokenLength(token) {
257
+ if (token.type === TokenType.EOF) return 0
258
+ if (token.type === TokenType.STRING) return String(token.value).length + 2
259
+ if (typeof token.value === 'string') return Math.max(1, token.value.length)
260
+ return 1
261
+ }
262
+
255
263
  export class Parser {
256
264
  constructor(tokens, options = {}) {
257
265
  this.tokens = tokens
@@ -273,7 +281,28 @@ export class Parser {
273
281
  }
274
282
  }
275
283
 
284
+ // Errors leave with `offset` (start of the token the parser stopped
285
+ // at, as an index into the lexed source) and `length`.
276
286
  parse() {
287
+ return this.withErrorOffset(() => this.parsePage())
288
+ }
289
+
290
+ withErrorOffset(fn) {
291
+ try {
292
+ return fn()
293
+ } catch (err) {
294
+ if (err && typeof err === 'object' && err.offset === undefined) {
295
+ const token = this.tokens[Math.min(this.pos, this.tokens.length - 1)]
296
+ if (token && typeof token.start === 'number') {
297
+ err.offset = token.start
298
+ err.length = tokenLength(token)
299
+ }
300
+ }
301
+ throw err
302
+ }
303
+ }
304
+
305
+ parsePage() {
277
306
  const page = {
278
307
  props: [],
279
308
  state: [],
@@ -709,6 +738,10 @@ export class Parser {
709
738
  // lifecycle hook, so sharing parse()'s isSectionKeyword/loop would
710
739
  // mean threading capability-only exceptions through page-only logic.
711
740
  parseCapability() {
741
+ return this.withErrorOffset(() => this.parseCapabilityFile())
742
+ }
743
+
744
+ parseCapabilityFile() {
712
745
  this.expect(TokenType.CAPABILITY, "Expected 'capability'")
713
746
  const name = this.expect(
714
747
  TokenType.IDENTIFIER,
@@ -24,7 +24,12 @@ export function parseComponentFile(source) {
24
24
  const scriptEnd =
25
25
  boundaries.find((b) => b.keyword === 'template')?.start ??
26
26
  afterDeclaration.length
27
- const scriptSource = afterDeclaration.slice(0, scriptEnd).trim()
27
+ const rawScript = afterDeclaration.slice(0, scriptEnd)
28
+ const scriptSource = rawScript.trim()
29
+ const declarationEnd = componentMatch.index + componentMatch[0].length
30
+ const leading = (text) => text.length - text.trimStart().length
31
+ const scriptOffset = declarationEnd + leading(rawScript)
32
+ let templateOffset = declarationEnd
28
33
 
29
34
  const templateBoundary = boundaries.find((b) => b.keyword === 'template')
30
35
  const styleBoundary = boundaries.find((b) => b.keyword === 'style')
@@ -35,9 +40,13 @@ export function parseComponentFile(source) {
35
40
  styleBoundary && styleBoundary.start > templateBoundary.start
36
41
  ? styleBoundary.start
37
42
  : afterDeclaration.length
38
- template = afterDeclaration
39
- .slice(templateBoundary.contentStart, templateEnd)
40
- .trim()
43
+ const rawTemplate = afterDeclaration.slice(
44
+ templateBoundary.contentStart,
45
+ templateEnd,
46
+ )
47
+ template = rawTemplate.trim()
48
+ templateOffset =
49
+ declarationEnd + templateBoundary.contentStart + leading(rawTemplate)
41
50
  }
42
51
 
43
52
  let style = ''
@@ -51,5 +60,12 @@ export function parseComponentFile(source) {
51
60
  )
52
61
  }
53
62
 
54
- return { componentName, script: scriptSource, template, style }
63
+ return {
64
+ componentName,
65
+ script: scriptSource,
66
+ template,
67
+ style,
68
+ scriptOffset,
69
+ templateOffset,
70
+ }
55
71
  }
@@ -13,6 +13,10 @@ import { TokenType } from '../lexer/tokenTypes.js'
13
13
  export function parseExpressionString(source, options = {}) {
14
14
  const tokens = new Lexer(source).tokenize()
15
15
  const parser = new Parser(tokens, options)
16
+ return parser.withErrorOffset(() => parseWhole(parser, source))
17
+ }
18
+
19
+ function parseWhole(parser, source) {
16
20
  const expression = parser.parseExpression()
17
21
  if (!parser.check(TokenType.EOF)) {
18
22
  const next = parser.peek()
@@ -164,6 +164,8 @@ export function parsePageFile(source) {
164
164
  .trim()
165
165
  : ''
166
166
 
167
+ const declarationEnd = pageMatch.index + pageMatch[0].length
168
+
167
169
  return {
168
170
  pageName,
169
171
  script: scriptSource,
@@ -171,5 +173,9 @@ export function parsePageFile(source) {
171
173
  style,
172
174
  scriptStartLine,
173
175
  templateStartLine,
176
+ // Character offsets of `script` and `template` in `source`, so a
177
+ // position inside either maps straight back onto the file.
178
+ scriptOffset: declarationEnd + leadingWhitespaceLength,
179
+ templateOffset: absoluteContentStart + templateLeadingWhitespaceLength,
174
180
  }
175
181
  }