all repos

clerk @ 4047965

missing tooling for ledger/hledger

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

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
parser: support quote commodities in N and P directives, 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 isPayeeWord(p.cur.Type) || (isPayeeWord(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 isPayeeWord(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
			ns := p.cur.Span
358
			c := p.parseCommentRest(ns)
359
			p.expectNewline()
360
			subs = append(subs, ast.AccountSubdirective{Kind: ast.SubdirectiveComment, NameSpan: ns, 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{Kind: ast.SubdirectiveComment, NameSpan: c.Span, Comment: c})
365
		case p.got(token.TEXT):
366
			name := p.cur.Literal
367
			kind, ok := accountSubdirectiveKind(name)
368
			if !ok {
369
				p.errorf("unknown subdirective %q", name)
370
				p.skipToNewline()
371
				continue
372
			}
373
			kw := p.cur.Span
374
			p.advance()
375
			value, vspan := p.parseSubdirectiveValue()
376
			if value == "" {
377
				p.errorf("expected value for subdirective %q", name)
378
			}
379
			c := p.parseOptInlineComment()
380
			p.expectNewline()
381
			subs = append(subs, ast.AccountSubdirective{
382
				Kind:      kind,
383
				NameSpan:  kw,
384
				Value:     value,
385
				ValueSpan: vspan,
386
				Comment:   c,
387
			})
388
		default:
389
			p.errorf("expected subdirective name, got %s", p.cur.Type)
390
			p.skipToNewline()
391
		}
392
	}
393
394
	return &ast.AccountDirective{
395
		Account:       account,
396
		Subdirectives: subs,
397
		Comment:       comment,
398
		Span:          p.span(s),
399
	}
400
}
401
402
func (p *Parser) parseCommodityDirective() *ast.CommodityDirective {
403
	s := p.cur.Span
404
	p.expect(token.COMMODITY)
405
	p.skipWhitespace()
406
407
	var commodity string
408
	var commoditySpan token.Span
409
	var format *ast.FormatSubDirective
410
411
	switch p.cur.Type {
412
	case token.COMMODITYMARK, token.TEXT, token.STRING:
413
		cs := p.cur.Span
414
		commodity = unquote(p.cur.Literal)
415
		p.advance()
416
		commoditySpan = token.Span{Start: cs.Start, End: p.cur.Span.Start}
417
		hadSpace := p.got(token.WHITESPACE)
418
		p.skipWhitespace()
419
		if p.got(token.INT) || p.got(token.DECIMAL) || p.got(token.TEXT) {
420
			amt := p.parseAmount()
421
			amt.Commodity = commodity
422
			amt.CommoditySpan = commoditySpan
423
			amt.CommodityPos = ast.CommodityBefore
424
			amt.HasSpace = hadSpace
425
			format = &ast.FormatSubDirective{Amount: *amt}
426
		}
427
	case token.INT, token.DECIMAL:
428
		amt := p.parseAmount()
429
		commodity = amt.Commodity
430
		commoditySpan = amt.CommoditySpan
431
		format = &ast.FormatSubDirective{Amount: *amt}
432
	default:
433
		p.errorf("expected commodity name or amount, got %s", p.cur.Type)
434
	}
435
436
	if commodity == "" {
437
		p.errorf("expected commodity name, got %s", p.cur.Type)
438
	}
439
440
	// hledger parity: an inline format amount must include a decimal mark
441
	if format != nil && format.Amount.QuantityFmt.Decimal == 0 {
442
		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.")
443
	}
444
445
	comment := p.parseOptInlineComment()
446
	p.expectNewline()
447
448
	var blockComments []*ast.Comment
449
	for p.got(token.INDENT) {
450
		p.advance()
451
		p.skipWhitespace()
452
		if p.got(token.NEWLINE) || p.got(token.EOF) {
453
			// whitespace-only line: block continues
454
			p.expectNewline()
455
			continue
456
		}
457
		switch {
458
		case p.got(token.TEXT) && p.cur.Literal == "format":
459
			kw := p.cur.Span
460
			p.advance()
461
			p.skipWhitespace()
462
			amt := p.parseAmount()
463
			// hledger parity: the format symbol must match the declared commodity,
464
			// and the amount must include a decimal mark; the node is kept either
465
			// way so the printer can round-trip the input.
466
			if amt.Commodity != commodity {
467
				p.errorfAt(amt.Span.Start, "commodity directive symbol %q and format directive symbol %q should be the same", commodity, amt.Commodity)
468
			} else if amt.QuantityFmt.Decimal == 0 {
469
				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.")
470
			}
471
			c := p.parseOptInlineComment()
472
			p.expectNewline()
473
			format = &ast.FormatSubDirective{KeywordSpan: kw, Amount: *amt, Comment: c}
474
		case p.got(token.SEMICOLON): // comment line
475
			c := p.parseCommentRest(p.cur.Span)
476
			p.expectNewline()
477
			blockComments = append(blockComments, c)
478
		case p.got(token.TEXT) && isCommentMarker(p.cur.Literal):
479
			// '#', '%' and '*' lex as TEXT in directive mode; treat them as comment lines
480
			blockComments = append(blockComments, p.parseTextComment())
481
		case p.got(token.TEXT):
482
			p.errorf("unknown subdirective %q", p.cur.Literal)
483
			p.skipToNewline()
484
		default:
485
			p.errorf("expected subdirective name, got %s", p.cur.Type)
486
			p.skipToNewline()
487
		}
488
	}
489
490
	cd := &ast.CommodityDirective{
491
		Commodity:     commodity,
492
		CommoditySpan: commoditySpan,
493
		FormatSub:     format,
494
		BlockComments: blockComments,
495
		Comment:       comment,
496
		Span:          p.span(s),
497
	}
498
	return cd
499
}
500
501
func (p *Parser) parseIncludeDirective() *ast.IncludeDirective {
502
	s := p.cur.Span
503
	p.expect(token.INCLUDE)
504
	p.skipWhitespace()
505
506
	id := &ast.IncludeDirective{}
507
508
	if p.got(token.TEXT) {
509
		id.Path = p.cur.Literal
510
		p.advance()
511
	} else {
512
		p.errorf("expected file path, got %s", p.cur.Type)
513
	}
514
515
	id.Comment = p.parseOptInlineComment()
516
	p.expectNewline()
517
	id.Span = p.span(s)
518
	return id
519
}
520
521
func (p *Parser) parseAliasDirective() *ast.AliasDirective {
522
	s := p.cur.Span
523
	alias := &ast.AliasDirective{}
524
	p.expect(token.ALIAS)
525
	p.skipWhitespace()
526
	alias.From = p.parseAccount()
527
	p.skipWhitespace()
528
	p.expect(token.EQ)
529
	p.skipWhitespace()
530
	alias.To = p.parseAccount()
531
	alias.Comment = p.parseOptInlineComment()
532
	p.expectNewline()
533
	alias.Span = p.span(s)
534
	return alias
535
}
536
537
func (p *Parser) parsePayeeDirective() *ast.PayeeDirective {
538
	s := p.cur.Span
539
	p.expect(token.PAYEE)
540
	p.skipWhitespace()
541
542
	var name *ast.Payee
543
	if p.got(token.TEXT) || p.got(token.STRING) || p.got(token.COMMODITYMARK) {
544
		name = p.parsePayee()
545
	}
546
547
	comment := p.parseOptInlineComment()
548
	p.expectNewline()
549
550
	return &ast.PayeeDirective{
551
		Name:    name,
552
		Comment: comment,
553
		Span:    p.span(s),
554
	}
555
}
556
557
func (p *Parser) parseTagDirective() *ast.TagDirective {
558
	s := p.cur.Span
559
	p.expect(token.TAG)
560
	p.skipWhitespace()
561
562
	name := ""
563
	if p.got(token.TEXT) || p.got(token.COMMODITYMARK) || p.got(token.STRING) {
564
		name = unquote(p.cur.Literal)
565
		p.advance()
566
	}
567
568
	comment := p.parseOptInlineComment()
569
	p.expectNewline()
570
571
	return &ast.TagDirective{
572
		Name:    name,
573
		Comment: comment,
574
		Span:    p.span(s),
575
	}
576
}
577
578
func (p *Parser) parseYearDirective() *ast.YearDirective {
579
	s := p.cur.Span
580
	year := &ast.YearDirective{}
581
	p.expect(token.YEAR)
582
	p.skipWhitespace()
583
584
	if p.got(token.INT) {
585
		year.Year, _ = strconv.Atoi(p.cur.Literal)
586
		p.defaultYear = year.Year
587
		p.advance()
588
	} else {
589
		p.errorf("expected year, got %s", p.cur.Type)
590
	}
591
592
	year.Comment = p.parseOptInlineComment()
593
	p.expectNewline()
594
	year.Span = p.span(s)
595
596
	return year
597
}
598
599
func (p *Parser) parseDecimalMarkDirective() *ast.DecimalMarkDirective {
600
	s := p.cur.Span
601
	mark := &ast.DecimalMarkDirective{}
602
	p.expect(token.DECIMALMARK)
603
	p.skipWhitespace()
604
605
	mark.Mark = byte('.')
606
	if p.got(token.TEXT) {
607
		if len(p.cur.Literal) > 0 {
608
			mark.Mark = p.cur.Literal[0]
609
		}
610
		p.advance()
611
	}
612
613
	mark.Comment = p.parseOptInlineComment()
614
	p.expectNewline()
615
	mark.Span = p.span(s)
616
	return mark
617
}
618
619
func (p *Parser) parseDefaultCommodityDirective() *ast.DefaultCommodityDirective {
620
	s := p.cur.Span
621
	com := &ast.DefaultCommodityDirective{}
622
	p.expect(token.D)
623
	p.skipWhitespace()
624
	com.Amount = *p.parseAmount()
625
	com.Comment = p.parseOptInlineComment()
626
	p.expectNewline()
627
	com.Span = p.span(s)
628
	return com
629
}
630
631
func (p *Parser) parseConversionDirective() *ast.ConversionDirective {
632
	s := p.cur.Span
633
	cd := &ast.ConversionDirective{}
634
	p.expect(token.C)
635
	p.skipWhitespace()
636
637
	if p.isAmountStart() {
638
		cd.From = *p.parseAmount()
639
	} else {
640
		p.errorf("expected amount, got %s", p.cur.Type)
641
	}
642
643
	p.skipWhitespace()
644
	if p.got(token.EQ) {
645
		p.advance()
646
		p.skipWhitespace()
647
		if p.isAmountStart() {
648
			cd.To = *p.parseAmount()
649
		} else {
650
			p.errorf("expected amount, got %s", p.cur.Type)
651
		}
652
	}
653
654
	cd.Comment = p.parseOptInlineComment()
655
	p.expectNewline()
656
	cd.Span = p.span(s)
657
	return cd
658
}
659
660
func (p *Parser) parseIgnoredDirective() *ast.IgnoredDirective {
661
	s := p.cur.Span
662
	p.expect(token.N)
663
	p.skipWhitespace()
664
665
	id := &ast.IgnoredDirective{}
666
	if p.got(token.TEXT) || p.got(token.COMMODITYMARK) || p.got(token.STRING) {
667
		id.Text = unquote(p.cur.Literal)
668
		p.advance()
669
	}
670
	id.Comment = p.parseOptInlineComment()
671
672
	p.expectNewline()
673
	id.Span = p.span(s)
674
	return id
675
}
676
677
func (p *Parser) parseMarketPriceDirective() *ast.MarketPriceDirective {
678
	s := p.cur.Span
679
	p.expect(token.P)
680
	p.skipWhitespace()
681
682
	mp := &ast.MarketPriceDirective{}
683
	mp.DateTime.Date = p.parseDate()
684
	p.skipWhitespace()
685
686
	if p.got(token.TIME) {
687
		mp.DateTime.Time = new(p.parseTime())
688
		p.skipWhitespace()
689
	}
690
691
	if p.got(token.COMMODITYMARK) || p.got(token.STRING) {
692
		mp.Commodity = unquote(p.cur.Literal)
693
		p.advance()
694
	} else {
695
		p.errorf("expected commodity symbol, got %s", p.cur.Type)
696
	}
697
	p.skipWhitespace()
698
699
	mp.Amount = *p.parseAmount()
700
701
	mp.Comment = p.parseOptInlineComment()
702
703
	p.expectNewline()
704
	mp.Span = p.span(s)
705
	return mp
706
}
707
708
func (p *Parser) parseTime() ast.Time {
709
	s := p.cur.Span
710
	tok, _ := p.expect(token.TIME)
711
	lit := tok.Literal
712
713
	parts := strings.Split(lit, ":")
714
	if len(parts) < 2 {
715
		p.errorf("invalid time format: %q", lit)
716
		return ast.Time{Span: p.span(s)}
717
	}
718
719
	hour, _ := strconv.Atoi(parts[0])
720
	minute, _ := strconv.Atoi(parts[1])
721
	second := 0
722
	if len(parts) > 2 {
723
		second, _ = strconv.Atoi(parts[2])
724
	}
725
726
	if hour < 0 || hour > 23 {
727
		p.errorf("invalid hour %d in time %q", hour, lit)
728
	}
729
	if minute < 0 || minute > 59 {
730
		p.errorf("invalid minute %d in time %q", minute, lit)
731
	}
732
	if second < 0 || second > 59 {
733
		p.errorf("invalid second %d in time %q", second, lit)
734
	}
735
736
	return ast.Time{
737
		Hour:   hour,
738
		Minute: minute,
739
		Second: second,
740
		Span:   p.span(s),
741
	}
742
}
743
744
func (p *Parser) parseApplyDirective() *ast.ApplyDirective {
745
	s := p.cur.Span
746
	p.expect(token.APPLY)
747
	p.skipWhitespace()
748
749
	expr := p.parseDirectiveExpr()
750
	comment := p.parseOptInlineComment()
751
	p.expectNewline()
752
753
	return &ast.ApplyDirective{
754
		Expr:    expr,
755
		Comment: comment,
756
		Span:    p.span(s),
757
	}
758
}
759
760
func (p *Parser) parseEndDirective() *ast.EndDirective {
761
	s := p.cur.Span
762
	p.expect(token.END)
763
	p.skipWhitespace()
764
765
	expr := p.parseDirectiveExpr()
766
	comment := p.parseOptInlineComment()
767
	p.expectNewline()
768
769
	return &ast.EndDirective{
770
		Expr:    expr,
771
		Comment: comment,
772
		Span:    p.span(s),
773
	}
774
}
775
776
func (p *Parser) parseCommentBlockDirective() *ast.CommentBlockDirective {
777
	start := p.cur.Span
778
	p.expect(token.COMMENTKW)
779
	p.skipWhitespace()
780
781
	header := p.parseDirectiveExpr()
782
	comment := p.parseOptInlineComment()
783
	p.expectNewline()
784
785
	var content strings.Builder
786
	for p.cur.Type != token.EOF {
787
		if p.got(token.END) {
788
			if p.willGet(token.NEWLINE) || p.willGet(token.EOF) {
789
				p.advance()
790
				p.expectNewline()
791
				break
792
			}
793
			if p.willGet(token.WHITESPACE) {
794
				endTok := p.cur
795
				p.advance()
796
				wsTok := p.cur
797
				p.advance()
798
				if p.got(token.TEXT) && p.cur.Literal == "comment" { // todo: this should check if it's an actual COMMENTKW token
799
					p.advance()
800
					p.parseDirectiveExpr()
801
					p.parseOptInlineComment()
802
					p.expectNewline()
803
					break
804
				}
805
				content.WriteString(endTok.Literal)
806
				content.WriteString(wsTok.Literal)
807
				continue
808
			}
809
		}
810
		content.WriteString(p.cur.Literal)
811
		p.advance()
812
	}
813
814
	return &ast.CommentBlockDirective{
815
		Header:  header,
816
		Content: content.String(),
817
		Comment: comment,
818
		Span:    p.span(start),
819
	}
820
}
821
822
func (p *Parser) parseStatus() ast.Status {
823
	s := p.cur.Span
824
	st := ast.Status{}
825
	switch p.cur.Type {
826
	case token.STAR:
827
		st.Value = ast.StatusCleared
828
	case token.BANG:
829
		st.Value = ast.StatusPending
830
	}
831
	if st.Value != ast.StatusNone {
832
		p.advance()
833
		p.skipWhitespace()
834
	}
835
	st.Span = p.span(s)
836
	return st
837
}
838
839
func (p *Parser) isAmountStart() bool {
840
	switch p.cur.Type {
841
	default:
842
		return false
843
	case token.COMMODITYMARK, token.STRING, token.INT, token.DECIMAL, token.MINUS, token.PLUS, token.PARENEXPR, token.STAR:
844
		return true
845
	}
846
}
847
848
func (p *Parser) parseAmount() *ast.Amount {
849
	s := p.cur.Span
850
	amt := &ast.Amount{
851
		QuantityFmt: ast.QuantityFormat{},
852
	}
853
	defer func() {
854
		// The span covers from the first token to the start of the next unconsumed token.
855
		// Since parseQuantityInto (and possible commodity consumption) advanced past the last
856
		// amount token, p.cur points to the next token after the amount — which is the correct end.
857
		amt.Span = p.span(s)
858
	}()
859
860
	p.parseAmountSign(amt)
861
	p.skipWhitespace()
862
863
	// commodity before quantity: $10.00, eur 10.00
864
	if p.got(token.COMMODITYMARK) || p.got(token.TEXT) || p.got(token.STRING) {
865
		cs := p.cur.Span
866
		amt.Commodity = unquote(p.cur.Literal)
867
		amt.CommodityPos = ast.CommodityBefore
868
		p.advance()
869
		amt.CommoditySpan = token.Span{Start: cs.Start, End: p.cur.Span.Start}
870
		if p.got(token.WHITESPACE) {
871
			amt.HasSpace = true
872
			p.skipWhitespace()
873
		}
874
	}
875
876
	// optional sign after commodity: $ -10
877
	p.parseAmountSign(amt)
878
	p.skipWhitespace()
879
880
	p.parseQuantityInto(amt)
881
882
	// commodity after quantity: 10.00 UAH, 10.00 "EUR" (only if not set)
883
	if amt.Commodity == "" {
884
		switch p.cur.Type {
885
		case token.WHITESPACE:
886
			p.skipWhitespace()
887
			if p.got(token.COMMODITYMARK) || p.got(token.TEXT) || p.got(token.STRING) {
888
				cs := p.cur.Span
889
				amt.HasSpace = true
890
				amt.Commodity = unquote(p.cur.Literal)
891
				amt.CommodityPos = ast.CommodityAfter
892
				p.advance()
893
				amt.CommoditySpan = token.Span{Start: cs.Start, End: p.cur.Span.Start}
894
			}
895
		case token.COMMODITYMARK, token.TEXT, token.STRING:
896
			cs := p.cur.Span
897
			amt.Commodity = unquote(p.cur.Literal)
898
			amt.CommodityPos = ast.CommodityAfter
899
			p.advance()
900
			amt.CommoditySpan = token.Span{Start: cs.Start, End: p.cur.Span.Start}
901
		}
902
	}
903
904
	return amt
905
}
906
907
// parseAmountSign consumes an optional leading +/- into IsNegative.
908
func (p *Parser) parseAmountSign(amt *ast.Amount) {
909
	switch p.cur.Type {
910
	case token.MINUS:
911
		amt.IsNegative = true
912
		p.advance()
913
	case token.PLUS:
914
		p.advance()
915
	}
916
}
917
918
func (p *Parser) parseAmountWithOptExpr() *ast.Amount {
919
	if p.got(token.STAR) {
920
		p.advance()
921
		p.skipWhitespace()
922
		amt := p.parseAmount()
923
		if amt != nil {
924
			amt.IsExpr = true
925
		}
926
		return amt
927
	}
928
	if p.got(token.PARENEXPR) {
929
		lit := p.cur.Literal
930
		amt := &ast.Amount{
931
			IsExpr:      true,
932
			QuantityFmt: ast.QuantityFormat{},
933
		}
934
		if len(lit) >= 2 && lit[0] == '(' && lit[len(lit)-1] == ')' {
935
			amt.Expr = strings.Trim(lit[1:len(lit)-1], " \t")
936
		}
937
		amt.Span = p.cur.Span
938
		p.advance()
939
		return amt
940
	}
941
	return p.parseAmount()
942
}
943
944
func (p *Parser) parsePosting() *ast.Posting {
945
	s := p.cur.Span
946
	posting := &ast.Posting{}
947
	p.expect(token.INDENT)
948
949
	// exit if it's empty line
950
	if p.got(token.NEWLINE) || p.got(token.EOF) {
951
		p.syncToNextline()
952
		return nil
953
	}
954
955
	// optional status, outside of brackets, '! (account)'
956
	posting.Status = p.parseStatus()
957
958
	// detect virtual posting brackets
959
	switch p.cur.Type {
960
	case token.LPAREN:
961
		posting.Type = ast.PostingVirtualUnbalanced
962
		p.advance()
963
	case token.LBRACKET:
964
		posting.Type = ast.PostingVirtualBalanced
965
		p.advance()
966
	}
967
968
	// optional status, inside of brackets, '(* account)'
969
	if p.got(token.STAR) || p.got(token.BANG) {
970
		posting.Status = p.parseStatus()
971
	}
972
973
	// validate, must be account text
974
	if p.cur.Type != token.TEXT {
975
		p.errorf("expected account name, got %s", p.cur.Type)
976
		p.syncToNextline()
977
		return nil
978
	}
979
980
	posting.Account = p.parseAccount()
981
982
	// consume closing bracket
983
	switch p.cur.Type {
984
	case token.RPAREN:
985
		p.advance()
986
	case token.RBRACKET:
987
		p.advance()
988
	}
989
990
	// optional amount - after two spaces
991
	if p.got(token.WHITESPACE) {
992
		p.skipWhitespace()
993
		if p.isAmountStart() {
994
			posting.Amount = p.parseAmountWithOptExpr()
995
		}
996
	}
997
998
	// optional cost '@' or '@@'
999
	p.skipWhitespace()
1000
	if p.got(token.AT) || p.got(token.ATAT) {
1001
		posting.Cost = p.parseCost()
1002
	}
1003
1004
	// optional balance assertion or assignment
1005
	p.skipWhitespace()
1006
	if p.got(token.COLON) && p.willGet(token.EQ) {
1007
		p.advance() // consume ':' of ':='
1008
		posting.Balance = p.parseBalanceAssertion()
1009
		posting.Balance.IsAssignment = true
1010
	} else if p.got(token.EQ) || p.got(token.EQEQ) || p.got(token.EQEQEQ) || p.got(token.EQSTAR) {
1011
		posting.Balance = p.parseBalanceAssertion()
1012
	}
1013
1014
	posting.Comment = p.parseOptInlineComment()
1015
	p.expectNewline()
1016
1017
	// continuation comments
1018
	for p.got(token.INDENT) && p.willGet(token.SEMICOLON) {
1019
		p.advance()
1020
		c := p.parseComment()
1021
		posting.Comments = append(posting.Comments, *c)
1022
	}
1023
1024
	posting.Span = p.span(s)
1025
	return posting
1026
}
1027
1028
func (p *Parser) parseCost() *ast.Cost {
1029
	s := p.cur.Span
1030
	isTotal := p.got(token.ATAT)
1031
	p.advance() // consume '@' '@@'
1032
	p.skipWhitespace()
1033
	return &ast.Cost{
1034
		IsTotal: isTotal,
1035
		Amount:  *p.parseAmount(),
1036
		Span:    p.span(s),
1037
	}
1038
}
1039
1040
func (p *Parser) parseBalanceAssertion() *ast.BalanceAssertion {
1041
	s := p.cur.Span
1042
1043
	ba := &ast.BalanceAssertion{}
1044
	switch p.cur.Type {
1045
	case token.EQ: // basic assertion
1046
	case token.EQSTAR: // inclusive assertion
1047
		ba.IsInclusive = true
1048
	case token.EQEQ: // strict assertion
1049
		ba.IsStrict = true
1050
	case token.EQEQEQ: // strict inclusive assertion
1051
		ba.IsStrict = true
1052
		ba.IsInclusive = true
1053
	}
1054
	p.advance()
1055
	p.skipWhitespace()
1056
1057
	ba.Amount = *p.parseAmount()
1058
	p.skipWhitespace()
1059
	if p.got(token.AT) || p.got(token.ATAT) {
1060
		c := p.parseCost()
1061
		ba.Cost = c
1062
	}
1063
	ba.Span = p.span(s)
1064
	return ba
1065
}
1066
1067
func (p *Parser) readAccountSegment() (ast.SubAccount, bool) {
1068
	switch p.cur.Type {
1069
	case token.TEXT:
1070
		sub := ast.SubAccount{Name: p.cur.Literal, Span: p.cur.Span}
1071
		p.advance()
1072
1073
		// handle multi work segment, e.g: "credit card"
1074
		if p.got(token.WHITESPACE) && p.willGet(token.TEXT) && len(p.peek.Literal) > 0 && p.peek.Literal[0] != '(' {
1075
			sub.Name += " "
1076
			p.advance()
1077
			sub.Name += p.cur.Literal
1078
			p.advance()
1079
		}
1080
		return sub, true
1081
1082
	case token.COMMODITYMARK:
1083
		sub := ast.SubAccount{Name: p.cur.Literal, Span: p.cur.Span}
1084
		p.advance()
1085
		// merge "EUR" + "-HRK" to "EUR-HRK"
1086
		for p.got(token.TEXT) {
1087
			sub.Name += p.cur.Literal
1088
			p.advance()
1089
		}
1090
		return sub, true
1091
1092
	default:
1093
		return ast.SubAccount{}, false
1094
	}
1095
}
1096
1097
func (p *Parser) parseAccount() ast.Account {
1098
	s := p.cur.Span
1099
	acc := ast.Account{}
1100
1101
	sub, ok := p.readAccountSegment()
1102
	if !ok {
1103
		p.errorf("expected account, got %s", p.cur.Type)
1104
		return ast.Account{}
1105
	}
1106
	acc.Name = append(acc.Name, sub)
1107
1108
	for p.got(token.COLON) {
1109
		p.advance()
1110
		sub, ok := p.readAccountSegment()
1111
		if !ok {
1112
			break
1113
		}
1114
		acc.Name = append(acc.Name, sub)
1115
	}
1116
1117
	acc.Span = p.span(s)
1118
	return acc
1119
}
1120
1121
func (p *Parser) parseDate() ast.Date {
1122
	s := p.cur.Span
1123
	tok, ok := p.expect(token.DATE)
1124
	if !ok {
1125
		return ast.Date{Span: p.span(s)}
1126
	}
1127
1128
	year, month, day, sep, err := ParseDateLiteral(tok.Literal)
1129
	if err != nil {
1130
		p.errorf("%v", err)
1131
		return ast.Date{Span: p.span(s)}
1132
	}
1133
	if year == 0 {
1134
		year = p.defaultYear
1135
	}
1136
1137
	return ast.Date{Year: year, Month: month, Day: day, Sep: sep, Span: p.span(s)}
1138
}
1139
1140
func (p *Parser) parseOptInlineComment() *ast.Comment {
1141
	p.skipWhitespace()
1142
	if !p.got(token.SEMICOLON) {
1143
		return nil
1144
	}
1145
	return p.parseCommentRest(p.cur.Span)
1146
}
1147
1148
// parseCommentRest consumes a comment marker at p.cur, then optional text;
1149
// s anchors the span at the marker's start.
1150
func (p *Parser) parseCommentRest(s token.Span) *ast.Comment {
1151
	marker := p.cur.Literal[0]
1152
	p.advance()
1153
	p.skipWhitespace()
1154
1155
	var tags []ast.Tag
1156
	text := ""
1157
	if p.got(token.TEXT) {
1158
		text = p.cur.Literal
1159
		tags = parseCommentTags(text, p.cur.Span.Start)
1160
		p.advance()
1161
	}
1162
1163
	return &ast.Comment{
1164
		Marker: marker,
1165
		Tags:   tags,
1166
		Text:   text,
1167
		Span:   p.span(s),
1168
	}
1169
}
1170
1171
func (p *Parser) parseOptPeriodicDescription() (string, token.Span) {
1172
	if p.cur.Type != token.WHITESPACE || len(p.cur.Literal) < 2 {
1173
		return "", token.Span{}
1174
	}
1175
1176
	p.skipWhitespace()
1177
1178
	if p.cur.Type != token.TEXT {
1179
		return "", token.Span{}
1180
	}
1181
1182
	s := p.cur.Span
1183
	desc := p.parseDescription()
1184
	return desc, p.span(s)
1185
}
1186
1187
func (p *Parser) parseDescription() string {
1188
	var desc strings.Builder
1189
	for p.got(token.TEXT) || (p.got(token.WHITESPACE) && p.willGet(token.TEXT)) {
1190
		_, _ = desc.WriteString(p.cur.Literal)
1191
		p.advance()
1192
	}
1193
	return desc.String()
1194
}
1195
1196
func (p *Parser) parseDirectiveExpr() string {
1197
	var b strings.Builder
1198
	for p.cur.Type != token.NEWLINE && p.cur.Type != token.EOF && p.cur.Type != token.SEMICOLON {
1199
		_, _ = b.WriteString(p.cur.Literal)
1200
		p.advance()
1201
	}
1202
	return b.String()
1203
}
1204
1205
func (p *Parser) parseQuantityInto(amt *ast.Amount) {
1206
	if p.cur.Type != token.INT && p.cur.Type != token.DECIMAL && p.cur.Type != token.TEXT {
1207
		p.errorf("expected quantity, got %s", p.cur.Type)
1208
		return
1209
	}
1210
1211
	lit := p.cur.Literal
1212
	p.advance()
1213
1214
	// detect format metadata before normalizing
1215
	amt.QuantityFmt = detectFormat(lit)
1216
1217
	// normalize for decimal.NewFromString
1218
	// remove thousands separators, replace decimal mark with '.'
1219
	normalized := normalizeLiteral(lit, amt.QuantityFmt.Thousands, amt.QuantityFmt.Decimal)
1220
1221
	q, err := decimal.FromString(normalized)
1222
	if err != nil {
1223
		p.errorf("invalid quantity %q: %v", lit, err)
1224
		return
1225
	}
1226
1227
	if amt.IsNegative {
1228
		q = q.Neg()
1229
	}
1230
	amt.Quantity = q
1231
}
1232
1233
func (p *Parser) parseBlankLine() *ast.BlankLine {
1234
	s := p.cur.Span
1235
	p.expectNewline()
1236
	return &ast.BlankLine{Span: s}
1237
}
1238
1239
func (p *Parser) expectNewline() {
1240
	if p.got(token.NEWLINE) || p.got(token.EOF) {
1241
		if p.got(token.NEWLINE) {
1242
			p.advance()
1243
		}
1244
		return
1245
	}
1246
	p.errorf("expected %s, got %s", token.NEWLINE, p.cur.Type)
1247
}
1248
1249
func (p *Parser) advance() token.Token {
1250
	prev := p.cur
1251
	p.cur = p.peek
1252
	p.peek = p.lexer.Next()
1253
	return prev
1254
}
1255
1256
func (p *Parser) got(kind token.Type) bool     { return p.cur.Type == kind }
1257
func (p *Parser) willGet(kind token.Type) bool { return p.peek.Type == kind }
1258
1259
func (p *Parser) expect(kind token.Type) (token.Token, bool) {
1260
	if p.got(kind) {
1261
		return p.advance(), true
1262
	}
1263
	p.errorf("expected %s, got %s", kind, p.cur.Type)
1264
	return p.cur, false
1265
}
1266
1267
func (p *Parser) errorf(format string, args ...any) {
1268
	p.errors = append(p.errors, &ast.ParseError{
1269
		Span:    p.cur.Span,
1270
		Message: fmt.Sprintf(format, args...),
1271
	})
1272
}
1273
1274
// errorfAt records a parse error pointing at a single position.
1275
func (p *Parser) errorfAt(pos token.Pos, format string, args ...any) {
1276
	p.errors = append(p.errors, &ast.ParseError{
1277
		Span:    token.Span{Start: pos, End: pos},
1278
		Message: fmt.Sprintf(format, args...),
1279
	})
1280
}
1281
1282
func accountSubdirectiveKind(name string) (ast.AccountSubdirectiveKind, bool) {
1283
	switch name {
1284
	case "alias":
1285
		return ast.SubdirectiveAlias, true
1286
	case "type":
1287
		return ast.SubdirectiveType, true
1288
	case "note":
1289
		return ast.SubdirectiveNote, true
1290
	}
1291
	return 0, false
1292
}
1293
1294
func isCommentMarker(s string) bool {
1295
	return len(s) > 0 && (s[0] == '#' || s[0] == '%' || s[0] == '*')
1296
}
1297
1298
// skipToNewline consumes the rest of the current line.
1299
func (p *Parser) skipToNewline() {
1300
	for !p.got(token.NEWLINE) && !p.got(token.EOF) {
1301
		p.advance()
1302
	}
1303
	p.expectNewline()
1304
}
1305
1306
func (p *Parser) parseSubdirectiveValue() (string, token.Span) {
1307
	var b strings.Builder
1308
	var first, last token.Span
1309
	var single, pendingWS string
1310
	for !p.got(token.SEMICOLON) && !p.got(token.NEWLINE) && !p.got(token.EOF) {
1311
		t := p.cur
1312
		if t.Type == token.WHITESPACE || t.Type == token.INDENT {
1313
			if first.Start.Offset > 0 {
1314
				pendingWS = t.Literal // only the last whitespace run matters
1315
			}
1316
			p.advance()
1317
			continue
1318
		}
1319
		if first.Start.Offset == 0 {
1320
			first, last = t.Span, t.Span
1321
			single = t.Literal
1322
		} else {
1323
			if single != "" {
1324
				b.WriteString(single)
1325
				single = ""
1326
			}
1327
			if pendingWS != "" {
1328
				b.WriteString(pendingWS)
1329
				pendingWS = ""
1330
			}
1331
			b.WriteString(t.Literal)
1332
			last = t.Span
1333
		}
1334
		p.advance()
1335
	}
1336
	if first.Start.Offset == 0 {
1337
		return "", token.Span{}
1338
	}
1339
	if single != "" {
1340
		return single, token.Span{Start: first.Start, End: last.End}
1341
	}
1342
	return strings.TrimSpace(b.String()), token.Span{Start: first.Start, End: last.End}
1343
}
1344
1345
func (p *Parser) parseTextComment() *ast.Comment {
1346
	s := p.cur.Span
1347
	marker := p.cur.Literal[0]
1348
	var b strings.Builder
1349
	b.WriteString(p.cur.Literal)
1350
	p.advance()
1351
	for !p.got(token.NEWLINE) && !p.got(token.EOF) {
1352
		b.WriteString(p.cur.Literal)
1353
		p.advance()
1354
	}
1355
	text := strings.TrimSpace(strings.TrimPrefix(strings.TrimSpace(b.String()), string(marker)))
1356
	span := p.span(s) // marker to line end, without the newline
1357
	p.expectNewline()
1358
	return &ast.Comment{Marker: marker, Text: text, Span: span}
1359
}
1360
1361
func isDirectiveKeyword(t token.Type) bool {
1362
	switch t {
1363
	case token.COMMENTKW, token.ACCOUNT, token.COMMODITY, token.INCLUDE,
1364
		token.ALIAS, token.PAYEE, token.TAG, token.APPLY, token.END,
1365
		token.YEAR, token.DECIMALMARK, token.D, token.P, token.N, token.C:
1366
		return true
1367
	}
1368
	return false
1369
}
1370
1371
func (p *Parser) sync() {
1372
	for {
1373
		switch p.cur.Type {
1374
		case token.EOF:
1375
			return
1376
		case token.NEWLINE:
1377
			p.advance()
1378
			t := p.cur.Type
1379
			if isDirectiveKeyword(t) || t == token.DATE || t == token.TILDE || t == token.EQ {
1380
				return
1381
			}
1382
		default:
1383
			p.advance()
1384
		}
1385
	}
1386
}
1387
1388
func (p *Parser) syncToNextline() {
1389
	for p.cur.Type != token.NEWLINE && p.cur.Type != token.EOF {
1390
		p.advance()
1391
	}
1392
	if p.got(token.NEWLINE) {
1393
		p.advance()
1394
	}
1395
}
1396
1397
func (p *Parser) skipWhitespace() {
1398
	for p.got(token.WHITESPACE) {
1399
		p.advance()
1400
	}
1401
}
1402
1403
func (p *Parser) span(s token.Span) token.Span {
1404
	return token.Span{Start: s.Start, End: p.cur.Span.Start}
1405
}
1406
1407
func normalizeLiteral(lit string, thousands, decimal byte) string {
1408
	var b strings.Builder
1409
	for _, ch := range []byte(lit) {
1410
		if thousands != 0 && ch == thousands {
1411
			continue // skip thousands separator
1412
		}
1413
		if ch == decimal {
1414
			b.WriteByte('.')
1415
		} else {
1416
			b.WriteByte(ch)
1417
		}
1418
	}
1419
	return b.String()
1420
}
1421
1422
func detectFormat(lit string) ast.QuantityFormat {
1423
	var seps []int
1424
	for i, ch := range []byte(lit) {
1425
		if ch == '.' || ch == ',' || ch == ' ' || ch == '_' || ch == '\'' {
1426
			seps = append(seps, i)
1427
		}
1428
	}
1429
1430
	if len(seps) == 0 {
1431
		return ast.QuantityFormat{}
1432
	}
1433
1434
	last := seps[len(seps)-1]
1435
	dec := lit[last]
1436
	if dec != '.' && dec != ',' {
1437
		// the last separator is a thousands mark; the literal has no decimal mark
1438
		dec = 0
1439
	}
1440
	var thou byte
1441
	if len(seps) > 1 {
1442
		thou = lit[seps[0]]
1443
	} else if dec == 0 {
1444
		// single space/underscore/apostrophe is always thousands
1445
		thou = lit[last]
1446
	}
1447
1448
	// calculate precision when the last separator is a real decimal
1449
	prec := 0
1450
	if thou == 0 || len(seps) > 1 {
1451
		prec = len(lit) - last - 1
1452
	}
1453
1454
	return ast.QuantityFormat{Decimal: dec, Thousands: thou, Precision: prec}
1455
}
1456
1457
// parseSimpleDate  parses full YYYY/MM/DD date literal embedded in free text.
1458
func parseSimpleDate(s string) ast.Date {
1459
	year, month, day, sep, err := ParseDateLiteral(s)
1460
	if err != nil {
1461
		return ast.Date{}
1462
	}
1463
	return ast.Date{Year: year, Month: month, Day: day, Sep: sep}
1464
}
1465
1466
// ParseDateLiteral parses and validates a date literal.
1467
// It accepts full YYYY/MM/DD and partial MM/DD forms, with '-', '/' or '.' as separators.
1468
func ParseDateLiteral(lit string) (year, month, day int, sep byte, err error) {
1469
	sep = dateSeparator(lit)
1470
	if sep == 0 {
1471
		return 0, 0, 0, 0, fmt.Errorf("invalid date format: %q", lit)
1472
	}
1473
1474
	parts := strings.Split(lit, string(sep))
1475
	if len(parts) != 2 && len(parts) != 3 {
1476
		return 0, 0, 0, 0, fmt.Errorf("invalid date format: %q", lit)
1477
	}
1478
1479
	nums := make([]int, len(parts))
1480
	for i, part := range parts {
1481
		if nums[i], err = strconv.Atoi(part); err != nil {
1482
			return 0, 0, 0, 0, fmt.Errorf("invalid date literal: %q", lit)
1483
		}
1484
	}
1485
1486
	month = nums[len(parts)-2]
1487
	if month < 1 || month > 12 {
1488
		return 0, 0, 0, 0, fmt.Errorf("invalid month %d in %q", month, lit)
1489
	}
1490
1491
	day = nums[len(parts)-1]
1492
	if day < 1 || day > 31 {
1493
		return 0, 0, 0, 0, fmt.Errorf("invalid day %d in %q", day, lit)
1494
	}
1495
1496
	if len(parts) == 2 {
1497
		return 0, month, day, sep, nil
1498
	}
1499
	return nums[0], month, day, sep, nil
1500
}
1501
1502
func dateSeparator(lit string) byte {
1503
	for i := 0; i < len(lit); i++ {
1504
		if lit[i] == '/' || lit[i] == '-' || lit[i] == '.' {
1505
			return lit[i]
1506
		}
1507
	}
1508
	return 0
1509
}
1510
1511
// parseCommentTags extacts tags from comment text.
1512
// A tag is a word immediately followed by a ':', with an optional value that ends at a comma or the end of a line.
1513
// https://hledger.org/1.52/hledger.html?highlight=tags#tags
1514
func parseCommentTags(text string, base token.Pos) []ast.Tag {
1515
	var tags []ast.Tag
1516
	for i := 0; i < len(text); {
1517
		colon := strings.IndexByte(text[i:], ':')
1518
		if colon < 0 {
1519
			break
1520
		}
1521
		colon += i
1522
1523
		keyStart := colon
1524
		for keyStart > i {
1525
			r, size := utf8.DecodeLastRuneInString(text[:keyStart])
1526
			if unicode.IsSpace(r) {
1527
				break
1528
			}
1529
			keyStart -= size
1530
		}
1531
		if keyStart == colon { // nothing before the colon = not a tag
1532
			i = colon + 1
1533
			continue
1534
		}
1535
		key := text[keyStart:colon]
1536
1537
		valueEnd := colon + 1
1538
		for valueEnd < len(text) && text[valueEnd] != ',' {
1539
			valueEnd++
1540
		}
1541
		value := strings.TrimSpace(text[colon+1 : valueEnd])
1542
1543
		tags = append(tags, ast.Tag{
1544
			Key:   key,
1545
			Value: value,
1546
			Span: token.Span{
1547
				Start: tagPos(base, text, keyStart),
1548
				End:   tagPos(base, text, valueEnd),
1549
			},
1550
		})
1551
		i = valueEnd
1552
		if i < len(text) && text[i] == ',' {
1553
			i++
1554
		}
1555
	}
1556
1557
	return tags
1558
}
1559
1560
func tagPos(base token.Pos, text string, off int) token.Pos {
1561
	return token.Pos{
1562
		File:   base.File,
1563
		Offset: base.Offset + off,
1564
		Line:   base.Line,
1565
		Col:    base.Col + utf8.RuneCountInString(text[:off]),
1566
	}
1567
}