all repos

clerk @ ea009344028fe0607fba0840944d0050e80ec981

missing tooling for ledger/hledger

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

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