Debian Codegraph @

tpl/internal/go_templates/htmltemplate/context.go

raw
1 // Copyright 2011 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 package template
6
7 import (
8 "fmt"
9 "slices"
10
11 "github.com/gohugoio/hugo/tpl/internal/go_templates/texttemplate/parse"
12 )
13
14 // context describes the state an HTML parser must be in when it reaches the
15 // portion of HTML produced by evaluating a particular template node.
16 //
17 // The zero value of type context is the start context for a template that
18 // produces an HTML fragment as defined at
19 // https://www.w3.org/TR/html5/syntax.html#the-end
20 // where the context element is null.
21 type context struct {
22 state state
23 delim delim
24 urlPart urlPart
25 jsCtx jsCtx
26 // jsBraceDepth contains the current depth, for each JS template literal
27 // string interpolation expression, of braces we've seen. This is used to
28 // determine if the next } will close a JS template literal string
29 // interpolation expression or not.
30 jsBraceDepth []int
31 attr attr
32 element element
33 n parse.Node // for range break/continue
34 err *Error
35 }
36
37 func (c context) String() string {
38 var err error
39 if c.err != nil {
40 err = c.err
41 }
42 return fmt.Sprintf("{%v %v %v %v %v %v %v %v}", c.state, c.delim, c.urlPart, c.jsCtx, c.jsBraceDepth, c.attr, c.element, err)
43 }
44
45 // eq reports whether two contexts are equal.
46 func (c context) eq(d context) bool {
47 return c.state == d.state &&
48 c.delim == d.delim &&
49 c.urlPart == d.urlPart &&
50 c.jsCtx == d.jsCtx &&
51 slices.Equal(c.jsBraceDepth, d.jsBraceDepth) &&
52 c.attr == d.attr &&
53 c.element == d.element &&
54 c.err == d.err
55 }
56
57 // mangle produces an identifier that includes a suffix that distinguishes it
58 // from template names mangled with different contexts.
59 func (c context) mangle(templateName string) string {
60 // The mangled name for the default context is the input templateName.
61 if c.state == stateText {
62 return templateName
63 }
64 s := templateName + "$htmltemplate_" + c.state.String()
65 if c.delim != delimNone {
66 s += "_" + c.delim.String()
67 }
68 if c.urlPart != urlPartNone {
69 s += "_" + c.urlPart.String()
70 }
71 if c.jsCtx != jsCtxRegexp {
72 s += "_" + c.jsCtx.String()
73 }
74 if c.jsBraceDepth != nil {
75 s += fmt.Sprintf("_jsBraceDepth(%v)", c.jsBraceDepth)
76 }
77 if c.attr != attrNone {
78 s += "_" + c.attr.String()
79 }
80 if c.element != elementNone {
81 s += "_" + c.element.String()
82 }
83 return s
84 }
85
86 // clone returns a copy of c with the same field values.
87 func (c context) clone() context {
88 clone := c
89 clone.jsBraceDepth = slices.Clone(c.jsBraceDepth)
90 return clone
91 }
92
93 // state describes a high-level HTML parser state.
94 //
95 // It bounds the top of the element stack, and by extension the HTML insertion
96 // mode, but also contains state that does not correspond to anything in the
97 // HTML5 parsing algorithm because a single token production in the HTML
98 // grammar may contain embedded actions in a template. For instance, the quoted
99 // HTML attribute produced by
100 //
101 // <div title="Hello {{.World}}">
102 //
103 // is a single token in HTML's grammar but in a template spans several nodes.
104 type state uint8
105
106 //go:generate stringer -type state
107
108 const (
109 // stateText is parsed character data. An HTML parser is in
110 // this state when its parse position is outside an HTML tag,
111 // directive, comment, and special element body.
112 stateText state = iota
113 // stateTag occurs before an HTML attribute or the end of a tag.
114 stateTag
115 // stateAttrName occurs inside an attribute name.
116 // It occurs between the ^'s in ` ^name^ = value`.
117 stateAttrName
118 // stateAfterName occurs after an attr name has ended but before any
119 // equals sign. It occurs between the ^'s in ` name^ ^= value`.
120 stateAfterName
121 // stateBeforeValue occurs after the equals sign but before the value.
122 // It occurs between the ^'s in ` name =^ ^value`.
123 stateBeforeValue
124 // stateHTMLCmt occurs inside an <!-- HTML comment -->.
125 stateHTMLCmt
126 // stateRCDATA occurs inside an RCDATA element (<textarea> or <title>)
127 // as described at https://www.w3.org/TR/html5/syntax.html#elements-0
128 stateRCDATA
129 // stateAttr occurs inside an HTML attribute whose content is text.
130 stateAttr
131 // stateURL occurs inside an HTML attribute whose content is a URL.
132 stateURL
133 // stateSrcset occurs inside an HTML srcset attribute.
134 stateSrcset
135 // stateJS occurs inside an event handler or script element.
136 stateJS
137 // stateJSDqStr occurs inside a JavaScript double quoted string.
138 stateJSDqStr
139 // stateJSSqStr occurs inside a JavaScript single quoted string.
140 stateJSSqStr
141 // stateJSTmplLit occurs inside a JavaScript back quoted string.
142 stateJSTmplLit
143 // stateJSRegexp occurs inside a JavaScript regexp literal.
144 stateJSRegexp
145 // stateJSBlockCmt occurs inside a JavaScript /* block comment */.
146 stateJSBlockCmt
147 // stateJSLineCmt occurs inside a JavaScript // line comment.
148 stateJSLineCmt
149 // stateJSHTMLOpenCmt occurs inside a JavaScript <!-- HTML-like comment.
150 stateJSHTMLOpenCmt
151 // stateJSHTMLCloseCmt occurs inside a JavaScript --> HTML-like comment.
152 stateJSHTMLCloseCmt
153 // stateCSS occurs inside a <style> element or style attribute.
154 stateCSS
155 // stateCSSDqStr occurs inside a CSS double quoted string.
156 stateCSSDqStr
157 // stateCSSSqStr occurs inside a CSS single quoted string.
158 stateCSSSqStr
159 // stateCSSDqURL occurs inside a CSS double quoted url("...").
160 stateCSSDqURL
161 // stateCSSSqURL occurs inside a CSS single quoted url('...').
162 stateCSSSqURL
163 // stateCSSURL occurs inside a CSS unquoted url(...).
164 stateCSSURL
165 // stateCSSBlockCmt occurs inside a CSS /* block comment */.
166 stateCSSBlockCmt
167 // stateCSSLineCmt occurs inside a CSS // line comment.
168 stateCSSLineCmt
169 // stateError is an infectious error state outside any valid
170 // HTML/CSS/JS construct.
171 stateError
172 // stateMetaContent occurs inside a HTML meta element content attribute.
173 stateMetaContent
174 // stateMetaContentURL occurs inside a "url=" tag in a HTML meta element content attribute.
175 stateMetaContentURL
176 // stateDead marks unreachable code after a {{break}} or {{continue}}.
177 stateDead
178 )
179
180 // isComment is true for any state that contains content meant for template
181 // authors & maintainers, not for end-users or machines.
182 func isComment(s state) bool {
183 switch s {
184 case stateHTMLCmt, stateJSBlockCmt, stateJSLineCmt, stateJSHTMLOpenCmt, stateJSHTMLCloseCmt, stateCSSBlockCmt, stateCSSLineCmt:
185 return true
186 }
187 return false
188 }
189
190 // isInTag return whether s occurs solely inside an HTML tag.
191 func isInTag(s state) bool {
192 switch s {
193 case stateTag, stateAttrName, stateAfterName, stateBeforeValue, stateAttr:
194 return true
195 }
196 return false
197 }
198
199 // isInScriptLiteral returns true if s is one of the literal states within a
200 // <script> tag, and as such occurrences of "<!--", "<script", and "</script"
201 // need to be treated specially.
202 func isInScriptLiteral(s state) bool {
203 // Ignore the comment states (stateJSBlockCmt, stateJSLineCmt,
204 // stateJSHTMLOpenCmt, stateJSHTMLCloseCmt) because their content is already
205 // omitted from the output.
206 switch s {
207 case stateJSDqStr, stateJSSqStr, stateJSTmplLit, stateJSRegexp:
208 return true
209 }
210 return false
211 }
212
213 // delim is the delimiter that will end the current HTML attribute.
214 type delim uint8
215
216 //go:generate stringer -type delim
217
218 const (
219 // delimNone occurs outside any attribute.
220 delimNone delim = iota
221 // delimDoubleQuote occurs when a double quote (") closes the attribute.
222 delimDoubleQuote
223 // delimSingleQuote occurs when a single quote (') closes the attribute.
224 delimSingleQuote
225 // delimSpaceOrTagEnd occurs when a space or right angle bracket (>)
226 // closes the attribute.
227 delimSpaceOrTagEnd
228 )
229
230 // urlPart identifies a part in an RFC 3986 hierarchical URL to allow different
231 // encoding strategies.
232 type urlPart uint8
233
234 //go:generate stringer -type urlPart
235
236 const (
237 // urlPartNone occurs when not in a URL, or possibly at the start:
238 // ^ in "^http://auth/path?k=v#frag".
239 urlPartNone urlPart = iota
240 // urlPartPreQuery occurs in the scheme, authority, or path; between the
241 // ^s in "h^ttp://auth/path^?k=v#frag".
242 urlPartPreQuery
243 // urlPartQueryOrFrag occurs in the query portion between the ^s in
244 // "http://auth/path?^k=v#frag^".
245 urlPartQueryOrFrag
246 // urlPartUnknown occurs due to joining of contexts both before and
247 // after the query separator.
248 urlPartUnknown
249 )
250
251 // jsCtx determines whether a '/' starts a regular expression literal or a
252 // division operator.
253 type jsCtx uint8
254
255 //go:generate stringer -type jsCtx
256
257 const (
258 // jsCtxRegexp occurs where a '/' would start a regexp literal.
259 jsCtxRegexp jsCtx = iota
260 // jsCtxDivOp occurs where a '/' would start a division operator.
261 jsCtxDivOp
262 // jsCtxUnknown occurs where a '/' is ambiguous due to context joining.
263 jsCtxUnknown
264 )
265
266 // element identifies the HTML element when inside a start tag or special body.
267 // Certain HTML element (for example <script> and <style>) have bodies that are
268 // treated differently from stateText so the element type is necessary to
269 // transition into the correct context at the end of a tag and to identify the
270 // end delimiter for the body.
271 type element uint8
272
273 //go:generate stringer -type element
274
275 const (
276 // elementNone occurs outside a special tag or special element body.
277 elementNone element = iota
278 // elementScript corresponds to the raw text <script> element
279 // with JS MIME type or no type attribute.
280 elementScript
281 // elementStyle corresponds to the raw text <style> element.
282 elementStyle
283 // elementTextarea corresponds to the RCDATA <textarea> element.
284 elementTextarea
285 // elementTitle corresponds to the RCDATA <title> element.
286 elementTitle
287 // elementMeta corresponds to the HTML <meta> element.
288 elementMeta
289 )
290
291 //go:generate stringer -type attr
292
293 // attr identifies the current HTML attribute when inside the attribute,
294 // that is, starting from stateAttrName until stateTag/stateText (exclusive).
295 type attr uint8
296
297 const (
298 // attrNone corresponds to a normal attribute or no attribute.
299 attrNone attr = iota
300 // attrScript corresponds to an event handler attribute.
301 attrScript
302 // attrScriptType corresponds to the type attribute in script HTML element
303 attrScriptType
304 // attrStyle corresponds to the style attribute whose value is CSS.
305 attrStyle
306 // attrURL corresponds to an attribute whose value is a URL.
307 attrURL
308 // attrSrcset corresponds to a srcset attribute.
309 attrSrcset
310 // attrMetaContent corresponds to the content attribute in meta HTML element.
311 attrMetaContent
312 )