all repos

clerk @ 3d2b11f

missing tooling for ledger/hledger

clerk/journal/parser/parser.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
add support of subdirectives and it's highlights, 1 month ago
1
package parser
2
3
import (
4
	"fmt"
5
	"strconv"
6
	"strings"
7
	"unicode"
8
	"unicode/utf8"
9
10
	"olexsmir.xyz/clerk/internal/decimal"
11
	"olexsmir.xyz/clerk/journal/ast"
12
	"olexsmir.xyz/clerk/journal/lexer"
13
	"olexsmir.xyz/clerk/journal/token"
14
)
15
16
type Parser struct {
17
	lexer  *lexer.Lexer
18
	errors []*ast.ParseError
19
	cur    token.Token
20
	peek   token.Token
21
22
	defaultYear int // set by year directive, used for short date inference
23
}
24
25
func New(lex *lexer.Lexer) *Parser {
26
	p := &Parser{lexer: lex}
27
	p.advance() // populate .peek
28
	p.advance() // populate .cur
29
	return p
30
}
31
32
func NewWithYear(lex *lexer.Lexer, year int) *Parser {
33
	p := &Parser{lexer: lex, defaultYear: year}
34
	p.advance() // populate .peek
35
	p.advance() // populate .cur
36
	return p
37
}
38
39
func (p *Parser) ParseJournal() *ast.Journal {
40
	f := &ast.Journal{}
41
	for p.cur.Type != token.EOF {
42
		if e := p.parseEntry(); e != nil {
43
			f.Entries = append(f.Entries, e)
44
		}
45
	}
46
	f.Errors = p.errors
47
	return f
48
}
49
50
func (p *Parser) parseEntry() ast.Entry {
51
	if p.got(token.BANG) || p.got(token.AT) {
52
		if isDirectiveKeyword(p.peek.Type) {
53
			p.advance() // consume prefix
54
		}
55
	}
56
57
	switch p.cur.Type {
58
	case token.ILLEGAL:
59
		p.errorf("illegal character %q", p.cur.Literal)
60
		p.advance()
61
		return nil
62
	case token.INDENT:
63
		p.errorf("unexpected indent")
64
		p.syncToNextline()
65
		return nil
66
	case token.DATE:
67
		return p.parseTransaction()
68
	case token.TILDE:
69
		return p.parsePeriodicTransaction()
70
	case token.EQ:
71
		return p.parseAutomatedTransaction()
72
	case token.NEWLINE:
73
		return p.parseBlankLine()
74
	case token.SEMICOLON, token.HASH, token.PERCENT, token.STAR:
75
		return p.parseComment()
76
	case token.ACCOUNT:
77
		return p.parseAccountDirective()
78
	case token.COMMODITY:
79
		return p.parseCommodityDirective()
80
	case token.INCLUDE:
81
		return p.parseIncludeDirective()
82
	case token.ALIAS:
83
		return p.parseAliasDirective()
84
	case token.PAYEE:
85
		return p.parsePayeeDirective()
86
	case token.TAG:
87
		return p.parseTagDirective()
88
	case token.YEAR:
89
		return p.parseYearDirective()
90
	case token.DECIMALMARK:
91
		return p.parseDecimalMarkDirective()
92
	case token.D:
93
		return p.parseDefaultCommodityDirective()
94
	case token.P:
95
		return p.parseMarketPriceDirective()
96
	case token.N:
97
		return p.parseIgnoredDirective()
98
	case token.C:
99
		return p.parseConversionDirective()
100
	case token.APPLY:
101
		return p.parseApplyDirective()
102
	case token.END:
103
		return p.parseEndDirective()
104
	case token.COMMENTKW:
105
		return p.parseCommentBlockDirective()
106
	default:
107
		p.errorf("unexpected token %s", p.cur.Type)
108
		p.sync()
109
		return nil
110
	}
111
}
112
113
func (p *Parser) parseTransaction() *ast.Transaction {
114
	s := p.cur.Span
115
	tx := &ast.Transaction{}
116
117
	tx.Date = p.parseDate()
118
119
	p.skipWhitespace()
120
121
	// optional secondary date
122
	if p.got(token.EQ) {
123
		p.advance()
124
		p.skipWhitespace()
125
		d := p.parseDate()
126
		tx.SecondDate = &d
127
	}
128
129
	p.skipWhitespace()
130
131
	// optional status
132
	tx.Status = p.parseStatus()
133
134
	// optional code - the lexer emits "(CODE)" as a single TEXT token; split it here
135
	if p.got(token.TEXT) {
136
		if lit := p.cur.Literal; len(lit) >= 2 && lit[0] == '(' && lit[len(lit)-1] == ')' {
137
			tx.Code = &ast.Code{Value: lit[1 : len(lit)-1], Span: p.cur.Span}
138
			p.advance()
139
			p.skipWhitespace()
140
		}
141
	}
142
143
	// optional payee | note
144
	if p.got(token.TEXT) || p.got(token.STRING) {
145
		tx.Payee = p.parsePayee()
146
147
		// check for | separator
148
		p.skipWhitespace()
149
150
		if p.got(token.PIPE) {
151
			p.advance()
152
			if p.got(token.TEXT) {
153
				sn := p.cur.Span
154
				n := p.cur.Literal
155
				p.advance()
156
				tx.Note = &ast.Note{Value: n, Span: p.span(sn)}
157
			}
158
		}
159
	}
160
161
	tx.Comment = p.parseOptInlineComment()
162
	p.expectNewline()
163
164
	tx.HeaderComments, tx.Postings = p.parseHeaderCommentsAndPostings()
165
166
	tx.Span = p.span(s)
167
	return tx
168
}
169
170
func unquote(s string) string {
171
	if len(s) >= 2 && ((s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'')) {
172
		return s[1 : len(s)-1]
173
	}
174
	return s
175
}
176
177
func (p *Parser) parsePayee() *ast.Payee {
178
	s := p.cur.Span
179
180
	if p.got(token.STRING) {
181
		name := unquote(p.cur.Literal)
182
		p.advance()
183
		return &ast.Payee{Name: name, Span: p.span(s)}
184
	}
185
186
	// keep spaces/tags between text tokens; stop before trailing whitespace
187
	var name strings.Builder
188
	for payeeWord(p.cur.Type) || (payeeWord(p.peek.Type) && p.got(token.WHITESPACE)) {
189
		_, _ = name.WriteString(p.cur.Literal)
190
		p.advance()
191
	}
192
	return &ast.Payee{Name: unquote(name.String()), Span: p.span(s)}
193
}
194
195
func payeeWord(t token.Type) bool {
196
	switch t {
197
	case token.TEXT, token.INT, token.DECIMAL, token.COMMODITYMARK:
198
		return true
199
	}
200
	return false
201
}
202
203
func (p *Parser) parsePeriodicTransaction() *ast.PeriodicTransaction {
204
	s := p.cur.Span
205
	p.expect(token.TILDE)
206
	p.skipWhitespace()
207
208
	pt := &ast.PeriodicTransaction{}
209
210
	pt.Period = p.parsePeriod()
211
212
	if desc, dspan := p.parseOptPeriodicDescription(); desc != "" {
213
		pt.Description = &ast.Description{Value: desc, Span: dspan}
214
	}
215
216
	comment := p.parseOptInlineComment()
217
	p.expectNewline()
218
219
	pt.HeaderComments, pt.Postings = p.parseHeaderCommentsAndPostings()
220
221
	pt.Span = p.span(s)
222
	pt.Comment = comment
223
	return pt
224
}
225
226
func (p *Parser) parseAutomatedTransaction() *ast.AutomatedTransaction {
227
	s := p.cur.Span
228
	p.expect(token.EQ)
229
	p.skipWhitespace()
230
231
	at := &ast.AutomatedTransaction{}
232
233
	// expression
234
	sd := p.cur.Span
235
	expr := p.parseDirectiveExpr()
236
	at.Expr = ast.Expr{Value: expr, Span: p.span(sd)}
237
	at.Comment = p.parseOptInlineComment()
238
	p.expectNewline()
239
240
	at.HeaderComments, at.Postings = p.parseHeaderCommentsAndPostings()
241
242
	at.Span = p.span(s)
243
	return at
244
}
245
246
func (p *Parser) parseHeaderCommentsAndPostings() (comments []*ast.Comment, postings []*ast.Posting) {
247
	for p.got(token.INDENT) && p.willGet(token.SEMICOLON) {
248
		p.advance() // consume indent
249
		comments = append(comments, p.parseComment())
250
	}
251
252
	for p.got(token.INDENT) {
253
		if posting := p.parsePosting(); posting != nil {
254
			postings = append(postings, posting)
255
		}
256
	}
257
258
	return comments, postings
259
}
260
261
func (p *Parser) parsePeriod() ast.Period {
262
	s := p.cur.Span
263
264
	var periodBuf strings.Builder
265
266
	for !p.got(token.NEWLINE) && !p.got(token.EOF) &&
267
		!p.got(token.SEMICOLON) && !p.got(token.HASH) && !p.got(token.PERCENT) && !p.got(token.STAR) {
268
269
		if p.got(token.WHITESPACE) {
270
			if len(p.cur.Literal) >= 2 {
271
				break
272
			}
273
			if p.willGet(token.NEWLINE) || p.willGet(token.EOF) ||
274
				p.willGet(token.SEMICOLON) || p.willGet(token.HASH) ||
275
				p.willGet(token.PERCENT) || p.willGet(token.STAR) {
276
				p.advance()
277
				continue
278
			}
279
		}
280
281
		periodBuf.WriteString(p.cur.Literal)
282
		p.advance()
283
	}
284
285
	str := periodBuf.String()
286
	period := ast.Period{Raw: str, Span: p.span(s)}
287
288
	if _, after, ok := strings.Cut(str, " from "); ok {
289
		end := strings.Index(after, " ")
290
		dateStr := after
291
		if end >= 0 {
292
			dateStr = after[:end]
293
		}
294
		if d := parseSimpleDate(dateStr); d.Year > 0 {
295
			fromOff := strings.Index(str, dateStr)
296
			d.Span = periodDateSpan(period, str, dateStr, fromOff)
297
			period.From = &d
298
			rest := after
299
			if end >= 0 {
300
				rest = after[end:]
301
			}
302
			if _, toAfter, ok := strings.Cut(rest, " to "); ok {
303
				if toEnd := strings.Index(toAfter, " "); toEnd >= 0 {
304
					toAfter = toAfter[:toEnd]
305
				}
306
				if d := parseSimpleDate(toAfter); d.Year > 0 {
307
					d.Span = periodDateSpan(period, str, toAfter, fromOff+len(dateStr))
308
					period.To = &d
309
				}
310
			}
311
		}
312
	}
313
	return period
314
}
315
316
// periodDateSpan returns the source span of dateStr, which occurs in the
317
// period text at or after searchFrom. The period span and text cover the same
318
// bytes, so offsets line up 1:1.
319
func periodDateSpan(period ast.Period, text, dateStr string, searchFrom int) token.Span {
320
	off := strings.Index(text[searchFrom:], dateStr)
321
	abs := period.Span.Start.Offset + searchFrom + off
322
	return token.Span{
323
		Start: token.Pos{File: period.Span.Start.File, Offset: abs},
324
		End:   token.Pos{File: period.Span.Start.File, Offset: abs + len(dateStr)},
325
	}
326
}
327
328
func (p *Parser) parseComment() *ast.Comment {
329
	s := p.cur.Span
330
	c := p.parseCommentRest(s)
331
	p.expectNewline()
332
	c.Span = p.span(s) // comment spans its line through the newline
333
	return c
334
}
335
336
func (p *Parser) parseAccountDirective() *ast.AccountDirective {
337
	s := p.cur.Span
338
	p.expect(token.ACCOUNT)
339
	p.skipWhitespace()
340
341
	account := p.parseAccount()
342
	comment := p.parseOptInlineComment()
343
	p.expectNewline()
344
345
	var subs []ast.AccountSubdirective
346
	for p.got(token.INDENT) {
347
		p.advance()
348
		p.skipWhitespace()
349
		if p.got(token.NEWLINE) || p.got(token.EOF) {
350
			// whitespace-only line: block continues
351
			p.expectNewline()
352
			continue
353
		}
354
		switch {
355
		case p.got(token.SEMICOLON):
356
			// comment line: directive mode lexes only ';' as a comment marker
357
			s := p.cur.Span
358
			c := p.parseCommentRest(s)
359
			p.expectNewline()
360
			subs = append(subs, ast.AccountSubdirective{NameSpan: s, Comment: c})
361
		case p.got(token.TEXT) && isCommentMarker(p.cur.Literal):
362
			// '#', '%' and '*' lex as TEXT in directive mode; treat them as comment lines
363
			c := p.parseTextComment()
364
			subs = append(subs, ast.AccountSubdirective{NameSpan: c.Span, Comment: c})
365
		case p.got(token.TEXT):
366
			name := p.cur.Literal
367
			if !isAccountSubdirective(name) {
368
				p.errorf("unknown subdirective %q", name)
369
				p.skipToNewline()
370
				continue
371
			}
372
			kw := p.cur.Span
373
			p.advance()
374
			value, vspan := p.parseSubdirectiveValue()
375
			if value == "" {
376
				p.errorf("expected value for subdirective %q", name)
377
			}
378
			c := p.parseOptInlineComment()
379
			p.expectNewline()
380
			subs = append(subs, ast.AccountSubdirective{
381
				Name:      name,
382
				NameSpan:  kw,
383
				Value:     value,
384
				ValueSpan: vspan,
385
				Comment:   c,
386
			})
387
		default:
388
			p.errorf("expected subdirective name, got %s", p.cur.Type)
389
			p.skipToNewline()
390
		}
391
	}
392
393
	return &ast.AccountDirective{
394
		Account:       account,
395
		Subdirectives: subs,
396
		Comment:       comment,
397
		Span:          p.span(s),
398
	}
399
}
400
401
func (p *Parser) parseCommodityDirective() *ast.CommodityDirective {
402
	s := p.cur.Span
403
	p.expect(token.COMMODITY)
404
	p.skipWhitespace()
405
406
	var commodity string
407
	var commoditySpan token.Span
408
	var format *ast.FormatSubDirective
409
410
	switch p.cur.Type {
411
	case token.COMMODITYMARK, token.TEXT, token.STRING:
412
		cs := p.cur.Span
413
		commodity = unquote(p.cur.Literal)
414
		p.advance()
415
		commoditySpan = token.Span{Start: cs.Start, End: p.cur.Span.Start}
416
		hadSpace := p.got(token.WHITESPACE)
417
		p.skipWhitespace()
418
		if p.got(token.INT) || p.got(token.DECIMAL) || p.got(token.TEXT) {
419
			amt := p.parseAmount()
420
			amt.Commodity = commodity
421
			amt.CommoditySpan = commoditySpan
422
			amt.CommodityPos = ast.CommodityBefore
423
			amt.HasSpace = hadSpace
424
			format = &ast.FormatSubDirective{Amount: *amt}
425
		}
426
	case token.INT, token.DECIMAL:
427
		amt := p.parseAmount()
428
		commodity = amt.Commodity
429
		commoditySpan = amt.CommoditySpan
430
		format = &ast.FormatSubDirective{Amount: *amt}
431
	default:
432
		p.errorf("expected commodity name or amount, got %s", p.cur.Type)
433
	}
434
435
	if commodity == "" {
436
		p.errorf("expected commodity name, got %s", p.cur.Type)
437
	}
438
439
	// hledger parity: an inline format amount must include a decimal mark
440
	if format != nil && format.Amount.QuantityFmt.Decimal == 0 {
441
		p.errorfAt(format.Amount.Span.Start, "Please include a decimal point or decimal comma in commodity directives, to help us parse correctly. It may be followed by zero or more decimal digits.")
442
	}
443
444
	comment := p.parseOptInlineComment()
445
	p.expectNewline()
446
447
	var blockComments []*ast.Comment
448
	for p.got(token.INDENT) {
449
		p.advance()
450
		p.skipWhitespace()
451
		if p.got(token.NEWLINE) || p.got(token.EOF) {
452
			// whitespace-only line: block continues
453
			p.expectNewline()
454
			continue
455
		}
456
		switch {
457
		case p.got(token.TEXT) && p.cur.Literal == "format":
458
			kw := p.cur.Span
459
			p.advance()
460
			p.skipWhitespace()
461
			amt := p.parseAmount()
462
			// hledger parity: the format symbol must match the declared commodity,
463
			// and the amount must include a decimal mark; the node is kept either
464
			// way so the printer can round-trip the input.
465
			if amt.Commodity != commodity {
466
				p.errorfAt(amt.Span.Start, "commodity directive symbol %q and format directive symbol %q should be the same", commodity, amt.Commodity)
467
			} else if amt.QuantityFmt.Decimal == 0 {
468
				p.errorfAt(amt.Span.Start, "Please include a decimal point or decimal comma in commodity directives, to help us parse correctly. It may be followed by zero or more decimal digits.")
469
			}
470
			c := p.parseOptInlineComment()
471
			p.expectNewline()
472
			format = &ast.FormatSubDirective{KeywordSpan: kw, Amount: *amt, Comment: c}
473
		case p.got(token.SEMICOLON): // comment line
474
			c := p.parseCommentRest(p.cur.Span)
475
			p.expectNewline()
476
			blockComments = append(blockComments, c)
477
		case p.got(token.TEXT) && isCommentMarker(p.cur.Literal):
478
			// '#', '%' and '*' lex as TEXT in directive mode; treat them as comment lines
479
			blockComments = append(blockComments, p.parseTextComment())
480
		case p.got(token.TEXT):
481
			p.errorf("unknown subdirective %q", p.cur.Literal)
482
			p.skipToNewline()
483
		default:
484
			p.errorf("expected subdirective name, got %s", p.cur.Type)
485
			p.skipToNewline()
486
		}
487
	}
488
489
	cd := &ast.CommodityDirective{
490
		Commodity:     commodity,
491
		CommoditySpan: commoditySpan,
492
		FormatSub:     format,
493
		BlockComments: blockComments,
494
		Comment:       comment,
495
		Span:          p.span(s),
496
	}
497
	return cd
498
}
499
500
func (p *Parser) parseIncludeDirective() *ast.IncludeDirective {
501
	s := p.cur.Span
502
	p.expect(token.INCLUDE)
503
	p.skipWhitespace()
504
505
	id := &ast.IncludeDirective{}
506
507
	if p.got(token.TEXT) {
508
		id.Path = p.cur.Literal
509
		p.advance()
510
	} else {
511
		p.errorf("expected file path, got %s", p.cur.Type)
512
	}
513
514
	id.Comment = p.parseOptInlineComment()
515
	p.expectNewline()
516
	id.Span = p.span(s)
517
	return id
518
}
519
520
func (p *Parser) parseAliasDirective() *ast.AliasDirective {
521
	s := p.cur.Span
522
	alias := &ast.AliasDirective{}
523
	p.expect(token.ALIAS)
524
	p.skipWhitespace()
525
	alias.From = p.parseAccount()
526
	p.skipWhitespace()
527
	p.expect(token.EQ)
528
	p.skipWhitespace()
529
	alias.To = p.parseAccount()
530
	alias.Comment = p.parseOptInlineComment()
531
	p.expectNewline()
532
	alias.Span = p.span(s)
533
	return alias
534
}
535
536
func (p *Parser) parsePayeeDirective() *ast.PayeeDirective {
537
	s := p.cur.Span
538
	p.expect(token.PAYEE)
539
	p.skipWhitespace()
540
541
	var name *ast.Payee
542
	if p.got(token.TEXT) || p.got(token.STRING) || p.got(token.COMMODITYMARK) {
543
		name = p.parsePayee()
544
	}
545
546
	comment := p.parseOptInlineComment()
547
	p.expectNewline()
548
549
	return &ast.PayeeDirective{
550
		Name:    name,
551
		Comment: comment,
552
		Span:    p.span(s),
553
	}
554
}
555
556
func (p *Parser) parseTagDirective() *ast.TagDirective {
557
	s := p.cur.Span
558
	p.expect(token.TAG)
559
	p.skipWhitespace()
560
561
	name := ""
562
	if p.got(token.TEXT) || p.got(token.COMMODITYMARK) || p.got(token.STRING) {
563
		name = unquote(p.cur.Literal)
564
		p.advance()
565
	}
566
567
	comment := p.parseOptInlineComment()
568
	p.expectNewline()
569
570
	return &ast.TagDirective{
571
		Name:    name,
572
		Comment: comment,
573
		Span:    p.span(s),
574
	}
575
}
576
577
func (p *Parser) parseYearDirective() *ast.YearDirective {
578
	s := p.cur.Span
579
	year := &ast.YearDirective{}
580
	p.expect(token.YEAR)
581
	p.skipWhitespace()
582
583
	if p.got(token.INT) {
584
		year.Year, _ = strconv.Atoi(p.cur.Literal)
585
		p.defaultYear = year.Year
586
		p.advance()
587
	} else {
588
		p.errorf("expected year, got %s", p.cur.Type)
589
	}
590
591
	year.Comment = p.parseOptInlineComment()
592
	p.expectNewline()
593
	year.Span = p.span(s)
594
595
	return year
596
}
597
598
func (p *Parser) parseDecimalMarkDirective() *ast.DecimalMarkDirective {
599
	s := p.cur.Span
600
	mark := &ast.DecimalMarkDirective{}
601
	p.expect(token.DECIMALMARK)
602
	p.skipWhitespace()
603
604
	mark.Mark = byte('.')
605
	if p.got(token.TEXT) {
606
		if len(p.cur.Literal) > 0 {
607
			mark.Mark = p.cur.Literal[0]
608
		}
609
		p.advance()
610
	}
611
612
	mark.Comment = p.parseOptInlineComment()
613
	p.expectNewline()
614
	mark.Span = p.span(s)
615
	return mark
616
}
617
618
func (p *Parser) parseDefaultCommodityDirective() *ast.DefaultCommodityDirective {
619
	s := p.cur.Span
620
	com := &ast.DefaultCommodityDirective{}
621
	p.expect(token.D)
622
	p.skipWhitespace()
623
	com.Amount = *p.parseAmount()
624
	com.Comment = p.parseOptInlineComment()
625
	p.expectNewline()
626
	com.Span = p.span(s)
627
	return com
628
}
629
630
func (p *Parser) parseConversionDirective() *ast.ConversionDirective {
631
	s := p.cur.Span
632
	cd := &ast.ConversionDirective{}
633
	p.expect(token.C)
634
	p.skipWhitespace()
635
636
	if p.isAmountStart() {
637
		cd.From = *p.parseAmount()
638
	} else {
639
		p.errorf("expected amount, got %s", p.cur.Type)
640
	}
641
642
	p.skipWhitespace()
643
	if p.got(token.EQ) {
644
		p.advance()
645
		p.skipWhitespace()
646
		if p.isAmountStart() {
647
			cd.To = *p.parseAmount()
648
		} else {
649
			p.errorf("expected amount, got %s", p.cur.Type)
650
		}
651
	}
652
653
	cd.Comment = p.parseOptInlineComment()
654
	p.expectNewline()
655
	cd.Span = p.span(s)
656
	return cd
657
}
658
659
func (p *Parser) parseIgnoredDirective() *ast.IgnoredDirective {
660
	s := p.cur.Span
661
	p.expect(token.N)
662
	p.skipWhitespace()
663
664
	id := &ast.IgnoredDirective{}
665
	if p.got(token.TEXT) || p.got(token.COMMODITYMARK) {
666
		id.Text = p.cur.Literal
667
		p.advance()
668
	}
669
	id.Comment = p.parseOptInlineComment()
670
671
	p.expectNewline()
672
	id.Span = p.span(s)
673
	return id
674
}
675
676
func (p *Parser) parseMarketPriceDirective() *ast.MarketPriceDirective {
677
	s := p.cur.Span
678
	p.expect(token.P)
679
	p.skipWhitespace()
680
681
	mp := &ast.MarketPriceDirective{}
682
	mp.DateTime.Date = p.parseDate()
683
	p.skipWhitespace()
684
685
	if p.got(token.TIME) {
686
		mp.DateTime.Time = new(p.parseTime())
687
		p.skipWhitespace()
688
	}
689
690
	tok, _ := p.expect(token.COMMODITYMARK)
691
	mp.Commodity = tok.Literal
692
	p.skipWhitespace()
693
694
	mp.Amount = *p.parseAmount()
695
696
	mp.Comment = p.parseOptInlineComment()
697
698
	p.expectNewline()
699
	mp.Span = p.span(s)
700
	return mp
701
}
702
703
func (p *Parser) parseTime() ast.Time {
704
	s := p.cur.Span
705
	tok, _ := p.expect(token.TIME)
706
	lit := tok.Literal
707
708
	parts := strings.Split(lit, ":")
709
	if len(parts) < 2 {
710
		p.errorf("invalid time format: %q", lit)
711
		return ast.Time{Span: p.span(s)}
712
	}
713
714
	hour, _ := strconv.Atoi(parts[0])
715
	minute, _ := strconv.Atoi(parts[1])
716
	second := 0
717
	if len(parts) > 2 {
718
		second, _ = strconv.Atoi(parts[2])
719
	}
720
721
	if hour < 0 || hour > 23 {
722
		p.errorf("invalid hour %d in time %q", hour, lit)
723
	}
724
	if minute < 0 || minute > 59 {
725
		p.errorf("invalid minute %d in time %q", minute, lit)
726
	}
727
	if second < 0 || second > 59 {
728
		p.errorf("invalid second %d in time %q", second, lit)
729
	}
730
731
	return ast.Time{
732
		Hour:   hour,
733
		Minute: minute,
734
		Second: second,
735
		Span:   p.span(s),
736
	}
737
}
738
739
func (p *Parser) parseApplyDirective() *ast.ApplyDirective {
740
	s := p.cur.Span
741
	p.expect(token.APPLY)
742
	p.skipWhitespace()
743
744
	expr := p.parseDirectiveExpr()
745
	comment := p.parseOptInlineComment()
746
	p.expectNewline()
747
748
	return &ast.ApplyDirective{
749
		Expr:    expr,
750
		Comment: comment,
751
		Span:    p.span(s),
752
	}
753
}
754
755
func (p *Parser) parseEndDirective() *ast.EndDirective {
756
	s := p.cur.Span
757
	p.expect(token.END)
758
	p.skipWhitespace()
759
760
	expr := p.parseDirectiveExpr()
761
	comment := p.parseOptInlineComment()
762
	p.expectNewline()
763
764
	return &ast.EndDirective{
765
		Expr:    expr,
766
		Comment: comment,
767
		Span:    p.span(s),
768
	}
769
}
770
771
func (p *Parser) parseCommentBlockDirective() *ast.CommentBlockDirective {
772
	start := p.cur.Span
773
	p.expect(token.COMMENTKW)
774
	p.skipWhitespace()
775
776
	header := p.parseDirectiveExpr()
777
	comment := p.parseOptInlineComment()
778
	p.expectNewline()
779
780
	var content strings.Builder
781
	for p.cur.Type != token.EOF {
782
		if p.got(token.END) {
783
			if p.willGet(token.NEWLINE) || p.willGet(token.EOF) {
784
				p.advance()
785
				p.expectNewline()
786
				break
787
			}
788
			if p.willGet(token.WHITESPACE) {
789
				endTok := p.cur
790
				p.advance()
791
				wsTok := p.cur
792
				p.advance()
793
				if p.got(token.TEXT) && p.cur.Literal == "comment" { // todo: this should check if it's an actual COMMENTKW token
794
					p.advance()
795
					p.parseDirectiveExpr()
796
					p.parseOptInlineComment()
797
					p.expectNewline()
798
					break
799
				}
800
				content.WriteString(endTok.Literal)
801
				content.WriteString(wsTok.Literal)
802
				continue
803
			}
804
		}
805
		content.WriteString(p.cur.Literal)
806
		p.advance()
807
	}
808
809
	return &ast.CommentBlockDirective{
810
		Header:  header,
811
		Content: content.String(),
812
		Comment: comment,
813
		Span:    p.span(start),
814
	}
815
}
816
817
func (p *Parser) parseStatus() ast.Status {
818
	s := p.cur.Span
819
	st := ast.Status{}
820
	switch p.cur.Type {
821
	case token.STAR:
822
		st.Value = ast.StatusCleared
823
	case token.BANG:
824
		st.Value = ast.StatusPending
825
	}
826
	if st.Value != ast.StatusNone {
827
		p.advance()
828
		p.skipWhitespace()
829
	}
830
	st.Span = p.span(s)
831
	return st
832
}
833
834
func (p *Parser) isAmountStart() bool {
835
	switch p.cur.Type {
836
	default:
837
		return false
838
	case token.COMMODITYMARK, token.STRING, token.INT, token.DECIMAL, token.MINUS, token.PLUS, token.PARENEXPR, token.STAR:
839
		return true
840
	}
841
}
842
843
func (p *Parser) parseAmount() *ast.Amount {
844
	s := p.cur.Span
845
	amt := &ast.Amount{
846
		QuantityFmt: ast.QuantityFormat{},
847
	}
848
	defer func() {
849
		// The span covers from the first token to the start of the next unconsumed token.
850
		// Since parseQuantityInto (and possible commodity consumption) advanced past the last
851
		// amount token, p.cur points to the next token after the amount — which is the correct end.
852
		amt.Span = p.span(s)
853
	}()
854
855
	p.parseAmountSign(amt)
856
	p.skipWhitespace()
857
858
	// commodity before quantity: $10.00, eur 10.00
859
	if p.got(token.COMMODITYMARK) || p.got(token.TEXT) || p.got(token.STRING) {
860
		cs := p.cur.Span
861
		amt.Commodity = unquote(p.cur.Literal)
862
		amt.CommodityPos = ast.CommodityBefore
863
		p.advance()
864
		amt.CommoditySpan = token.Span{Start: cs.Start, End: p.cur.Span.Start}
865
		if p.got(token.WHITESPACE) {
866
			amt.HasSpace = true
867
			p.skipWhitespace()
868
		}
869
	}
870
871
	// optional sign after commodity: $ -10
872
	p.parseAmountSign(amt)
873
	p.skipWhitespace()
874
875
	p.parseQuantityInto(amt)
876
877
	// commodity after quantity: 10.00 UAH, 10.00 "EUR" (only if not set)
878
	if amt.Commodity == "" {
879
		switch p.cur.Type {
880
		case token.WHITESPACE:
881
			p.skipWhitespace()
882
			if p.got(token.COMMODITYMARK) || p.got(token.TEXT) || p.got(token.STRING) {
883
				cs := p.cur.Span
884
				amt.HasSpace = true
885
				amt.Commodity = unquote(p.cur.Literal)
886
				amt.CommodityPos = ast.CommodityAfter
887
				p.advance()
888
				amt.CommoditySpan = token.Span{Start: cs.Start, End: p.cur.Span.Start}
889
			}
890
		case token.COMMODITYMARK, token.TEXT, token.STRING:
891
			cs := p.cur.Span
892
			amt.Commodity = unquote(p.cur.Literal)
893
			amt.CommodityPos = ast.CommodityAfter
894
			p.advance()
895
			amt.CommoditySpan = token.Span{Start: cs.Start, End: p.cur.Span.Start}
896
		}
897
	}
898
899
	return amt
900
}
901
902
// parseAmountSign consumes an optional leading +/- into IsNegative.
903
func (p *Parser) parseAmountSign(amt *ast.Amount) {
904
	switch p.cur.Type {
905
	case token.MINUS:
906
		amt.IsNegative = true
907
		p.advance()
908
	case token.PLUS:
909
		p.advance()
910
	}
911
}
912
913
func (p *Parser) parseAmountWithOptExpr() *ast.Amount {
914
	if p.got(token.STAR) {
915
		p.advance()
916
		p.skipWhitespace()
917
		amt := p.parseAmount()
918
		if amt != nil {
919
			amt.IsExpr = true
920
		}
921
		return amt
922
	}
923
	if p.got(token.PARENEXPR) {
924
		lit := p.cur.Literal
925
		amt := &ast.Amount{
926
			IsExpr:      true,
927
			QuantityFmt: ast.QuantityFormat{},
928
		}
929
		if len(lit) >= 2 && lit[0] == '(' && lit[len(lit)-1] == ')' {
930
			amt.Expr = strings.Trim(lit[1:len(lit)-1], " \t")
931
		}
932
		amt.Span = p.cur.Span
933
		p.advance()
934
		return amt
935
	}
936
	return p.parseAmount()
937
}
938
939
func (p *Parser) parsePosting() *ast.Posting {
940
	s := p.cur.Span
941
	posting := &ast.Posting{}
942
	p.expect(token.INDENT)
943
944
	// exit if it's empty line
945
	if p.got(token.NEWLINE) || p.got(token.EOF) {
946
		p.syncToNextline()
947
		return nil
948
	}
949
950
	// optional status, outside of brackets, '! (account)'
951
	posting.Status = p.parseStatus()
952
953
	// detect virtual posting brackets
954
	switch p.cur.Type {
955
	case token.LPAREN:
956
		posting.Type = ast.PostingVirtualUnbalanced
957
		p.advance()
958
	case token.LBRACKET:
959
		posting.Type = ast.PostingVirtualBalanced
960
		p.advance()
961
	}
962
963
	// optional status, inside of brackets, '(* account)'
964
	if p.got(token.STAR) || p.got(token.BANG) {
965
		posting.Status = p.parseStatus()
966
	}
967
968
	// validate, must be account text
969
	if p.cur.Type != token.TEXT {
970
		p.errorf("expected account name, got %s", p.cur.Type)
971
		p.syncToNextline()
972
		return nil
973
	}
974
975
	posting.Account = p.parseAccount()
976
977
	// consume closing bracket
978
	switch p.cur.Type {
979
	case token.RPAREN:
980
		p.advance()
981
	case token.RBRACKET:
982
		p.advance()
983
	}
984
985
	// optional amount - after two spaces
986
	if p.got(token.WHITESPACE) {
987
		p.skipWhitespace()
988
		if p.isAmountStart() {
989
			posting.Amount = p.parseAmountWithOptExpr()
990
		}
991
	}
992
993
	// optional cost '@' or '@@'
994
	p.skipWhitespace()
995
	if p.got(token.AT) || p.got(token.ATAT) {
996
		posting.Cost = p.parseCost()
997
	}
998
999
	// optional balance assertion or assignment
1000
	p.skipWhitespace()
1001
	if p.got(token.COLON) && p.willGet(token.EQ) {
1002
		p.advance() // consume ':' of ':='
1003
		posting.Balance = p.parseBalanceAssertion()
1004
		posting.Balance.IsAssignment = true
1005
	} else if p.got(token.EQ) || p.got(token.EQEQ) || p.got(token.EQEQEQ) || p.got(token.EQSTAR) {
1006
		posting.Balance = p.parseBalanceAssertion()
1007
	}
1008
1009
	posting.Comment = p.parseOptInlineComment()
1010
	p.expectNewline()
1011
1012
	// continuation comments
1013
	for p.got(token.INDENT) && p.willGet(token.SEMICOLON) {
1014
		p.advance()
1015
		c := p.parseComment()
1016
		posting.Comments = append(posting.Comments, *c)
1017
	}
1018
1019
	posting.Span = p.span(s)
1020
	return posting
1021
}
1022
1023
func (p *Parser) parseCost() *ast.Cost {
1024
	s := p.cur.Span
1025
	isTotal := p.got(token.ATAT)
1026
	p.advance() // consume '@' '@@'
1027
	p.skipWhitespace()
1028
	return &ast.Cost{
1029
		IsTotal: isTotal,
1030
		Amount:  *p.parseAmount(),
1031
		Span:    p.span(s),
1032
	}
1033
}
1034
1035
func (p *Parser) parseBalanceAssertion() *ast.BalanceAssertion {
1036
	s := p.cur.Span
1037
1038
	ba := &ast.BalanceAssertion{}
1039
	switch p.cur.Type {
1040
	case token.EQ: // basic assertion
1041
	case token.EQSTAR: // inclusive assertion
1042
		ba.IsInclusive = true
1043
	case token.EQEQ: // strict assertion
1044
		ba.IsStrict = true
1045
	case token.EQEQEQ: // strict inclusive assertion
1046
		ba.IsStrict = true
1047
		ba.IsInclusive = true
1048
	}
1049
	p.advance()
1050
	p.skipWhitespace()
1051
1052
	ba.Amount = *p.parseAmount()
1053
	p.skipWhitespace()
1054
	if p.got(token.AT) || p.got(token.ATAT) {
1055
		c := p.parseCost()
1056
		ba.Cost = c
1057
	}
1058
	ba.Span = p.span(s)
1059
	return ba
1060
}
1061
1062
func (p *Parser) readAccountSegment() (ast.SubAccount, bool) {
1063
	switch p.cur.Type {
1064
	case token.TEXT:
1065
		sub := ast.SubAccount{Name: p.cur.Literal, Span: p.cur.Span}
1066
		p.advance()
1067
1068
		// handle multi work segment, e.g: "credit card"
1069
		if p.got(token.WHITESPACE) && p.willGet(token.TEXT) && len(p.peek.Literal) > 0 && p.peek.Literal[0] != '(' {
1070
			sub.Name += " "
1071
			p.advance()
1072
			sub.Name += p.cur.Literal
1073
			p.advance()
1074
		}
1075
		return sub, true
1076
1077
	case token.COMMODITYMARK:
1078
		sub := ast.SubAccount{Name: p.cur.Literal, Span: p.cur.Span}
1079
		p.advance()
1080
		// merge "EUR" + "-HRK" to "EUR-HRK"
1081
		for p.got(token.TEXT) {
1082
			sub.Name += p.cur.Literal
1083
			p.advance()
1084
		}
1085
		return sub, true
1086
1087
	default:
1088
		return ast.SubAccount{}, false
1089
	}
1090
}
1091
1092
func (p *Parser) parseAccount() ast.Account {
1093
	s := p.cur.Span
1094
	acc := ast.Account{}
1095
1096
	sub, ok := p.readAccountSegment()
1097
	if !ok {
1098
		p.errorf("expected account, got %s", p.cur.Type)
1099
		return ast.Account{}
1100
	}
1101
	acc.Name = append(acc.Name, sub)
1102
1103
	for p.got(token.COLON) {
1104
		p.advance()
1105
		sub, ok := p.readAccountSegment()
1106
		if !ok {
1107
			break
1108
		}
1109
		acc.Name = append(acc.Name, sub)
1110
	}
1111
1112
	acc.Span = p.span(s)
1113
	return acc
1114
}
1115
1116
func (p *Parser) parseDate() ast.Date {
1117
	s := p.cur.Span
1118
	tok, ok := p.expect(token.DATE)
1119
	if !ok {
1120
		return ast.Date{Span: p.span(s)}
1121
	}
1122
1123
	year, month, day, sep, err := ParseDateLiteral(tok.Literal)
1124
	if err != nil {
1125
		p.errorf("%v", err)
1126
		return ast.Date{Span: p.span(s)}
1127
	}
1128
	if year == 0 {
1129
		year = p.defaultYear
1130
	}
1131
1132
	return ast.Date{Year: year, Month: month, Day: day, Sep: sep, Span: p.span(s)}
1133
}
1134
1135
func (p *Parser) parseOptInlineComment() *ast.Comment {
1136
	p.skipWhitespace()
1137
	if !p.got(token.SEMICOLON) {
1138
		return nil
1139
	}
1140
	return p.parseCommentRest(p.cur.Span)
1141
}
1142
1143
// parseCommentRest consumes a comment marker at p.cur, then optional text;
1144
// s anchors the span at the marker's start.
1145
func (p *Parser) parseCommentRest(s token.Span) *ast.Comment {
1146
	marker := p.cur.Literal[0]
1147
	p.advance()
1148
	p.skipWhitespace()
1149
1150
	var tags []ast.Tag
1151
	text := ""
1152
	if p.got(token.TEXT) {
1153
		text = p.cur.Literal
1154
		tags = parseCommentTags(text, p.cur.Span.Start)
1155
		p.advance()
1156
	}
1157
1158
	return &ast.Comment{
1159
		Marker: marker,
1160
		Tags:   tags,
1161
		Text:   text,
1162
		Span:   p.span(s),
1163
	}
1164
}
1165
1166
func (p *Parser) parseOptPeriodicDescription() (string, token.Span) {
1167
	if p.cur.Type != token.WHITESPACE || len(p.cur.Literal) < 2 {
1168
		return "", token.Span{}
1169
	}
1170
1171
	p.skipWhitespace()
1172
1173
	if p.cur.Type != token.TEXT {
1174
		return "", token.Span{}
1175
	}
1176
1177
	s := p.cur.Span
1178
	desc := p.parseDescription()
1179
	return desc, p.span(s)
1180
}
1181
1182
func (p *Parser) parseDescription() string {
1183
	var desc strings.Builder
1184
	for p.got(token.TEXT) || (p.got(token.WHITESPACE) && p.willGet(token.TEXT)) {
1185
		_, _ = desc.WriteString(p.cur.Literal)
1186
		p.advance()
1187
	}
1188
	return desc.String()
1189
}
1190
1191
func (p *Parser) parseDirectiveExpr() string {
1192
	var b strings.Builder
1193
	for p.cur.Type != token.NEWLINE && p.cur.Type != token.EOF && p.cur.Type != token.SEMICOLON {
1194
		_, _ = b.WriteString(p.cur.Literal)
1195
		p.advance()
1196
	}
1197
	return b.String()
1198
}
1199
1200
func (p *Parser) parseQuantityInto(amt *ast.Amount) {
1201
	if p.cur.Type != token.INT && p.cur.Type != token.DECIMAL && p.cur.Type != token.TEXT {
1202
		p.errorf("expected quantity, got %s", p.cur.Type)
1203
		return
1204
	}
1205
1206
	lit := p.cur.Literal
1207
	p.advance()
1208
1209
	// detect format metadata before normalizing
1210
	amt.QuantityFmt = detectFormat(lit)
1211
1212
	// normalize for decimal.NewFromString
1213
	// remove thousands separators, replace decimal mark with '.'
1214
	normalized := normalizeLiteral(lit, amt.QuantityFmt.Thousands, amt.QuantityFmt.Decimal)
1215
1216
	q, err := decimal.FromString(normalized)
1217
	if err != nil {
1218
		p.errorf("invalid quantity %q: %v", lit, err)
1219
		return
1220
	}
1221
1222
	if amt.IsNegative {
1223
		q = q.Neg()
1224
	}
1225
	amt.Quantity = q
1226
}
1227
1228
func (p *Parser) parseBlankLine() *ast.BlankLine {
1229
	s := p.cur.Span
1230
	p.expectNewline()
1231
	return &ast.BlankLine{Span: s}
1232
}
1233
1234
func (p *Parser) expectNewline() {
1235
	if p.got(token.NEWLINE) || p.got(token.EOF) {
1236
		if p.got(token.NEWLINE) {
1237
			p.advance()
1238
		}
1239
		return
1240
	}
1241
	p.errorf("expected %s, got %s", token.NEWLINE, p.cur.Type)
1242
}
1243
1244
func (p *Parser) advance() token.Token {
1245
	prev := p.cur
1246
	p.cur = p.peek
1247
	p.peek = p.lexer.Next()
1248
	return prev
1249
}
1250
1251
func (p *Parser) got(kind token.Type) bool     { return p.cur.Type == kind }
1252
func (p *Parser) willGet(kind token.Type) bool { return p.peek.Type == kind }
1253
1254
func (p *Parser) expect(kind token.Type) (token.Token, bool) {
1255
	if p.got(kind) {
1256
		return p.advance(), true
1257
	}
1258
	p.errorf("expected %s, got %s", kind, p.cur.Type)
1259
	return p.cur, false
1260
}
1261
1262
func (p *Parser) errorf(format string, args ...any) {
1263
	p.errors = append(p.errors, &ast.ParseError{
1264
		Span:    p.cur.Span,
1265
		Message: fmt.Sprintf(format, args...),
1266
	})
1267
}
1268
1269
// errorfAt records a parse error pointing at a single position.
1270
func (p *Parser) errorfAt(pos token.Pos, format string, args ...any) {
1271
	p.errors = append(p.errors, &ast.ParseError{
1272
		Span:    token.Span{Start: pos, End: pos},
1273
		Message: fmt.Sprintf(format, args...),
1274
	})
1275
}
1276
1277
func isAccountSubdirective(name string) bool {
1278
	switch name {
1279
	case "alias", "type", "note":
1280
		return true
1281
	}
1282
	return false
1283
}
1284
1285
func isCommentMarker(s string) bool {
1286
	return len(s) > 0 && (s[0] == '#' || s[0] == '%' || s[0] == '*')
1287
}
1288
1289
// skipToNewline consumes the rest of the current line.
1290
func (p *Parser) skipToNewline() {
1291
	for !p.got(token.NEWLINE) && !p.got(token.EOF) {
1292
		p.advance()
1293
	}
1294
	p.expectNewline()
1295
}
1296
1297
// parseSubdirectiveValue consumes the tokens after a subdirective keyword up
1298
// to an inline comment or the end of the line, returning the raw text and its
1299
// span (trimmed of surrounding whitespace). Single-token values return the
1300
// lexer's literal, sharing the source backing without a copy.
1301
func (p *Parser) parseSubdirectiveValue() (string, token.Span) {
1302
	var b strings.Builder
1303
	var first, last token.Span
1304
	var single, pendingWS string
1305
	for !p.got(token.SEMICOLON) && !p.got(token.NEWLINE) && !p.got(token.EOF) {
1306
		t := p.cur
1307
		if t.Type == token.WHITESPACE || t.Type == token.INDENT {
1308
			if first.Start.Offset > 0 {
1309
				pendingWS = t.Literal // only the last whitespace run matters
1310
			}
1311
			p.advance()
1312
			continue
1313
		}
1314
		if first.Start.Offset == 0 {
1315
			first, last = t.Span, t.Span
1316
			single = t.Literal
1317
		} else {
1318
			if single != "" {
1319
				b.WriteString(single)
1320
				single = ""
1321
			}
1322
			if pendingWS != "" {
1323
				b.WriteString(pendingWS)
1324
				pendingWS = ""
1325
			}
1326
			b.WriteString(t.Literal)
1327
			last = t.Span
1328
		}
1329
		p.advance()
1330
	}
1331
	if first.Start.Offset == 0 {
1332
		return "", token.Span{}
1333
	}
1334
	if single != "" {
1335
		return single, token.Span{Start: first.Start, End: last.End}
1336
	}
1337
	return strings.TrimSpace(b.String()), token.Span{Start: first.Start, End: last.End}
1338
}
1339
1340
// parseTextComment consumes a comment line whose marker ('#', '%' or '*')
1341
// lexed as TEXT inside a directive block, building the comment from token
1342
// literals. Tags are not extracted; the comment is one line.
1343
func (p *Parser) parseTextComment() *ast.Comment {
1344
	s := p.cur.Span
1345
	marker := p.cur.Literal[0]
1346
	var b strings.Builder
1347
	b.WriteString(p.cur.Literal)
1348
	p.advance()
1349
	for !p.got(token.NEWLINE) && !p.got(token.EOF) {
1350
		b.WriteString(p.cur.Literal)
1351
		p.advance()
1352
	}
1353
	text := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(b.String()), string(marker)))
1354
	span := p.span(s) // marker to line end, without the newline
1355
	p.expectNewline()
1356
	return &ast.Comment{Marker: marker, Text: text, Span: span}
1357
}
1358
1359
func isDirectiveKeyword(t token.Type) bool {
1360
	switch t {
1361
	case token.COMMENTKW, token.ACCOUNT, token.COMMODITY, token.INCLUDE,
1362
		token.ALIAS, token.PAYEE, token.TAG, token.APPLY, token.END,
1363
		token.YEAR, token.DECIMALMARK, token.D, token.P, token.N, token.C:
1364
		return true
1365
	}
1366
	return false
1367
}
1368
1369
func (p *Parser) sync() {
1370
	for {
1371
		switch p.cur.Type {
1372
		case token.EOF:
1373
			return
1374
		case token.NEWLINE:
1375
			p.advance()
1376
			t := p.cur.Type
1377
			if isDirectiveKeyword(t) || t == token.DATE || t == token.TILDE || t == token.EQ {
1378
				return
1379
			}
1380
		default:
1381
			p.advance()
1382
		}
1383
	}
1384
}
1385
1386
func (p *Parser) syncToNextline() {
1387
	for p.cur.Type != token.NEWLINE && p.cur.Type != token.EOF {
1388
		p.advance()
1389
	}
1390
	if p.got(token.NEWLINE) {
1391
		p.advance()
1392
	}
1393
}
1394
1395
func (p *Parser) skipWhitespace() {
1396
	for p.got(token.WHITESPACE) {
1397
		p.advance()
1398
	}
1399
}
1400
1401
func (p *Parser) span(s token.Span) token.Span {
1402
	return token.Span{Start: s.Start, End: p.cur.Span.Start}
1403
}
1404
1405
func normalizeLiteral(lit string, thousands, decimal byte) string {
1406
	var b strings.Builder
1407
	for _, ch := range []byte(lit) {
1408
		if thousands != 0 && ch == thousands {
1409
			continue // skip thousands separator
1410
		}
1411
		if ch == decimal {
1412
			b.WriteByte('.')
1413
		} else {
1414
			b.WriteByte(ch)
1415
		}
1416
	}
1417
	return b.String()
1418
}
1419
1420
func detectFormat(lit string) ast.QuantityFormat {
1421
	var seps []int
1422
	for i, ch := range []byte(lit) {
1423
		if ch == '.' || ch == ',' || ch == ' ' || ch == '_' || ch == '\'' {
1424
			seps = append(seps, i)
1425
		}
1426
	}
1427
1428
	if len(seps) == 0 {
1429
		return ast.QuantityFormat{}
1430
	}
1431
1432
	last := seps[len(seps)-1]
1433
	dec := lit[last]
1434
	if dec != '.' && dec != ',' {
1435
		// the last separator is a thousands mark; the literal has no decimal mark
1436
		dec = 0
1437
	}
1438
	var thou byte
1439
	if len(seps) > 1 {
1440
		thou = lit[seps[0]]
1441
	} else if dec == 0 {
1442
		// single space/underscore/apostrophe is always thousands
1443
		thou = lit[last]
1444
	}
1445
1446
	// calculate precision when the last separator is a real decimal
1447
	prec := 0
1448
	if thou == 0 || len(seps) > 1 {
1449
		prec = len(lit) - last - 1
1450
	}
1451
1452
	return ast.QuantityFormat{Decimal: dec, Thousands: thou, Precision: prec}
1453
}
1454
1455
// parseSimpleDate  parses full YYYY/MM/DD date literal embedded in free text.
1456
func parseSimpleDate(s string) ast.Date {
1457
	year, month, day, sep, err := ParseDateLiteral(s)
1458
	if err != nil {
1459
		return ast.Date{}
1460
	}
1461
	return ast.Date{Year: year, Month: month, Day: day, Sep: sep}
1462
}
1463
1464
// ParseDateLiteral parses and validates a date literal.
1465
// It accepts full YYYY/MM/DD and partial MM/DD forms, with '-', '/' or '.' as separators.
1466
func ParseDateLiteral(lit string) (year, month, day int, sep byte, err error) {
1467
	sep = dateSeparator(lit)
1468
	if sep == 0 {
1469
		return 0, 0, 0, 0, fmt.Errorf("invalid date format: %q", lit)
1470
	}
1471
1472
	parts := strings.Split(lit, string(sep))
1473
	if len(parts) != 2 && len(parts) != 3 {
1474
		return 0, 0, 0, 0, fmt.Errorf("invalid date format: %q", lit)
1475
	}
1476
1477
	nums := make([]int, len(parts))
1478
	for i, part := range parts {
1479
		if nums[i], err = strconv.Atoi(part); err != nil {
1480
			return 0, 0, 0, 0, fmt.Errorf("invalid date literal: %q", lit)
1481
		}
1482
	}
1483
1484
	month = nums[len(parts)-2]
1485
	if month < 1 || month > 12 {
1486
		return 0, 0, 0, 0, fmt.Errorf("invalid month %d in %q", month, lit)
1487
	}
1488
1489
	day = nums[len(parts)-1]
1490
	if day < 1 || day > 31 {
1491
		return 0, 0, 0, 0, fmt.Errorf("invalid day %d in %q", day, lit)
1492
	}
1493
1494
	if len(parts) == 2 {
1495
		return 0, month, day, sep, nil
1496
	}
1497
	return nums[0], month, day, sep, nil
1498
}
1499
1500
func dateSeparator(lit string) byte {
1501
	for i := 0; i < len(lit); i++ {
1502
		if lit[i] == '/' || lit[i] == '-' || lit[i] == '.' {
1503
			return lit[i]
1504
		}
1505
	}
1506
	return 0
1507
}
1508
1509
// parseCommentTags extacts tags from comment text.
1510
// A tag is a word immediately followed by a ':', with an optional value that ends at a comma or the end of a line.
1511
// https://hledger.org/1.52/hledger.html?highlight=tags#tags
1512
func parseCommentTags(text string, base token.Pos) []ast.Tag {
1513
	var tags []ast.Tag
1514
	for i := 0; i < len(text); {
1515
		colon := strings.IndexByte(text[i:], ':')
1516
		if colon < 0 {
1517
			break
1518
		}
1519
		colon += i
1520
1521
		keyStart := colon
1522
		for keyStart > i {
1523
			r, size := utf8.DecodeLastRuneInString(text[:keyStart])
1524
			if unicode.IsSpace(r) {
1525
				break
1526
			}
1527
			keyStart -= size
1528
		}
1529
		if keyStart == colon { // nothing before the colon = not a tag
1530
			i = colon + 1
1531
			continue
1532
		}
1533
		key := text[keyStart:colon]
1534
1535
		valueEnd := colon + 1
1536
		for valueEnd < len(text) && text[valueEnd] != ',' {
1537
			valueEnd++
1538
		}
1539
		value := strings.TrimSpace(text[colon+1 : valueEnd])
1540
1541
		tags = append(tags, ast.Tag{
1542
			Key:   key,
1543
			Value: value,
1544
			Span: token.Span{
1545
				Start: tagPos(base, text, keyStart),
1546
				End:   tagPos(base, text, valueEnd),
1547
			},
1548
		})
1549
		i = valueEnd
1550
		if i < len(text) && text[i] == ',' {
1551
			i++
1552
		}
1553
	}
1554
1555
	return tags
1556
}
1557
1558
func tagPos(base token.Pos, text string, off int) token.Pos {
1559
	return token.Pos{
1560
		File:   base.File,
1561
		Offset: base.Offset + off,
1562
		Line:   base.Line,
1563
		Col:    base.Col + utf8.RuneCountInString(text[:off]),
1564
	}
1565
}