Debian Codegraph @

selector/parser/parse_literal.go

raw symbols SCIP
1 package parser
2
3 import (
4 "fmt"
5 "regexp"
6 "strconv"
7 "strings"
8
9 "github.com/tomwright/dasel/v3/selector/ast"
10 "github.com/tomwright/dasel/v3/selector/lexer"
11 )
12
13 func parseStringLiteral(p *Parser) (ast.Expr, error) {
14 token := p.current()
15 p.advance()
16 return ast.StringExpr{
17 Value: token.Value,
18 }, nil
19 }
20
21 func parseBoolLiteral(p *Parser) (ast.Expr, error) {
22 token := p.current()
23 p.advance()
24 return ast.BoolExpr{
25 Value: strings.EqualFold(token.Value, "true"),
26 }, nil
27 }
28
29 func parseSpread(p *Parser) (ast.Expr, error) {
30 p.advance()
31 return ast.SpreadExpr{}, nil
32 }
33
34 func parseNumberLiteral(p *Parser) (ast.Expr, error) {
35 token := p.current()
36
37 var negative bool
38 if token.IsKind(lexer.Dash) {
39 negative = true
40 token = p.advance()
41 }
42
43 next := p.advance()
44 switch {
45 case next.IsKind(lexer.Symbol) && strings.EqualFold(next.Value, "f"):
46 value, err := strconv.ParseFloat(token.Value, 64)
47 if err != nil {
48 return nil, err
49 }
50 p.advance()
51 if negative {
52 value = -value
53 }
54 return ast.NumberFloatExpr{
55 Value: value,
56 }, nil
57
58 case strings.Contains(token.Value, "."):
59 value, err := strconv.ParseFloat(token.Value, 64)
60 if err != nil {
61 return nil, err
62 }
63 if negative {
64 value = -value
65 }
66 return ast.NumberFloatExpr{
67 Value: value,
68 }, nil
69
70 default:
71 value, err := strconv.ParseInt(token.Value, 10, 64)
72 if err != nil {
73 return nil, err
74 }
75 if negative {
76 value = -value
77 }
78 return ast.NumberIntExpr{
79 Value: value,
80 }, nil
81 }
82 }
83
84 func parseRegexPattern(p *Parser) (ast.Expr, error) {
85 if err := p.expect(lexer.RegexPattern); err != nil {
86 return nil, err
87 }
88
89 pattern := p.current()
90
91 p.advance()
92
93 comp, err := regexp.Compile(pattern.Value)
94 if err != nil {
95 return nil, fmt.Errorf("failed to compile regexp pattern: %w", err)
96 }
97
98 return ast.RegexExpr{
99 Regex: comp,
100 }, nil
101 }