MCPcopy
hub / github.com/hashicorp/hcl / ParseStringLiteralToken

Function ParseStringLiteralToken

hclsyntax/parser.go:1908–2067  ·  view source on GitHub ↗

ParseStringLiteralToken processes the given token, which must be either a TokenQuotedLit or a TokenStringLit, returning the string resulting from resolving any escape sequences. If any error diagnostics are returned, the returned string may be incomplete or otherwise invalid.

(tok Token)

Source from the content-addressed store, hash-verified

1906// If any error diagnostics are returned, the returned string may be incomplete
1907// or otherwise invalid.
1908func ParseStringLiteralToken(tok Token) (string, hcl.Diagnostics) {
1909 var quoted bool
1910 switch tok.Type {
1911 case TokenQuotedLit:
1912 quoted = true
1913 case TokenStringLit:
1914 quoted = false
1915 default:
1916 panic("ParseStringLiteralToken can only be used with TokenStringLit and TokenQuotedLit tokens")
1917 }
1918 var diags hcl.Diagnostics
1919
1920 ret := make([]byte, 0, len(tok.Bytes))
1921 slices := scanStringLit(tok.Bytes, quoted)
1922
1923 // We will mutate rng constantly as we walk through our token slices below.
1924 // Any diagnostics must take a copy of this rng rather than simply pointing
1925 // to it, e.g. by using rng.Ptr() rather than &rng.
1926 rng := tok.Range
1927 rng.End = rng.Start
1928
1929Slices:
1930 for _, slice := range slices {
1931 if len(slice) == 0 {
1932 continue
1933 }
1934
1935 // Advance the start of our range to where the previous token ended
1936 rng.Start = rng.End
1937
1938 // Advance the end of our range to after our token.
1939 b := slice
1940 for len(b) > 0 {
1941 adv, ch, _ := textseg.ScanGraphemeClusters(b, true)
1942 rng.End.Byte += adv
1943 switch ch[0] {
1944 case '\r', '\n':
1945 rng.End.Line++
1946 rng.End.Column = 1
1947 default:
1948 rng.End.Column++
1949 }
1950 b = b[adv:]
1951 }
1952
1953 TokenType:
1954 switch slice[0] {
1955 case '\\':
1956 if !quoted {
1957 // If we're not in quoted mode then just treat this token as
1958 // normal. (Slices can still start with backslash even if we're
1959 // not specifically looking for backslash sequences.)
1960 break TokenType
1961 }
1962 if len(slice) < 2 {
1963 diags = append(diags, &hcl.Diagnostic{
1964 Severity: hcl.DiagError,
1965 Summary: "Invalid escape sequence",

Callers 3

CurrentMethod · 0.92
parseTemplatePartsMethod · 0.85

Calls 2

scanStringLitFunction · 0.85
PtrMethod · 0.80

Tested by

no test coverage detected