all repos

clerk @ 232cfab

missing tooling for ledger/hledger

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

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