Debian Codegraph @

parser/pageparser/pagelexer_shortcode.go

raw
1 // Copyright 2018 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package pageparser
15
16 import "unique"
17
18 type lexerShortcodeState struct {
19 currLeftDelimItem ItemType
20 currRightDelimItem ItemType
21 isInline bool
22 currShortcodeName string // is only set when a shortcode is in opened state
23 closingState int // > 0 = on its way to be closed
24 elementStepNum int // step number in element
25 paramElements int // number of elements (name + value = 2) found first
26 openShortcodes map[unique.Handle[string]]bool // set of shortcodes in open state
27 }
28
29 // Shortcode syntax
30 var (
31 leftDelimSc = []byte("{{")
32 leftDelimScNoMarkup = []byte("{{<")
33 rightDelimScNoMarkup = []byte(">}}")
34 leftDelimScWithMarkup = []byte("{{%")
35 rightDelimScWithMarkup = []byte("%}}")
36 leftComment = []byte("/*") // comments in this context are used to mark shortcodes as "not really a shortcode"
37 rightComment = []byte("*/")
38 )
39
40 func (l *pageLexer) isShortCodeStart() bool {
41 return l.hasPrefix(leftDelimScWithMarkup) || l.hasPrefix(leftDelimScNoMarkup)
42 }
43
44 func lexShortcodeLeftDelim(l *pageLexer) stateFunc {
45 l.pos += len(l.currentLeftShortcodeDelim())
46 if l.hasPrefix(leftComment) {
47 return lexShortcodeComment
48 }
49 l.emit(l.currentLeftShortcodeDelimItem())
50 l.elementStepNum = 0
51 l.paramElements = 0
52 return lexInsideShortcode
53 }
54
55 func lexShortcodeComment(l *pageLexer) stateFunc {
56 posRightComment := l.index(append(rightComment, l.currentRightShortcodeDelim()...))
57 if posRightComment <= 1 {
58 return l.errorf("comment must be closed")
59 }
60 // we emit all as text, except the comment markers
61 l.emit(tText)
62 l.pos += len(leftComment)
63 l.ignore()
64 l.pos += posRightComment - len(leftComment)
65 l.emit(tText)
66 l.pos += len(rightComment)
67 l.ignore()
68 l.pos += len(l.currentRightShortcodeDelim())
69 l.emit(tText)
70 return lexMainSection
71 }
72
73 func lexShortcodeRightDelim(l *pageLexer) stateFunc {
74 l.closingState = 0
75 l.pos += len(l.currentRightShortcodeDelim())
76 l.emit(l.currentRightShortcodeDelimItem())
77 return lexMainSection
78 }
79
80 // either:
81 // 1. param
82 // 2. "param" or "param\"
83 // 3. param="123" or param="123\"
84 // 4. param="Some \"escaped\" text"
85 // 5. `param`
86 // 6. param=`123`
87 func lexShortcodeParam(l *pageLexer, escapedQuoteStart bool) stateFunc {
88 first := true
89 nextEq := false
90
91 var r rune
92
93 for {
94 r = l.next()
95 if first {
96 if r == '"' || (r == '`' && !escapedQuoteStart) {
97 // a positional param with quotes
98 if l.paramElements == 2 {
99 return l.errorf("got quoted positional parameter. Cannot mix named and positional parameters")
100 }
101 l.paramElements = 1
102 l.backup()
103 if r == '"' {
104 return lexShortcodeQuotedParamVal(l, !escapedQuoteStart, tScParam)
105 }
106 return lexShortCodeParamRawStringVal(l, tScParam)
107
108 } else if r == '`' && escapedQuoteStart {
109 return l.errorf("unrecognized escape character")
110 }
111 first = false
112 } else if r == '=' {
113 // a named param
114 l.backup()
115 nextEq = true
116 break
117 }
118
119 if !isAlphaNumericOrHyphen(r) && r != '.' { // Floats have period
120 l.backup()
121 break
122 }
123 }
124
125 if l.paramElements == 0 {
126 l.paramElements++
127
128 if nextEq {
129 l.paramElements++
130 }
131 } else {
132 if nextEq && l.paramElements == 1 {
133 return l.errorf("got named parameter '%s'. Cannot mix named and positional parameters", l.current())
134 } else if !nextEq && l.paramElements == 2 {
135 return l.errorf("got positional parameter '%s'. Cannot mix named and positional parameters", l.current())
136 }
137 }
138
139 l.emit(tScParam)
140 return lexInsideShortcode
141 }
142
143 func lexShortcodeParamVal(l *pageLexer) stateFunc {
144 l.consumeToSpace()
145 l.emit(tScParamVal)
146 return lexInsideShortcode
147 }
148
149 func lexShortCodeParamRawStringVal(l *pageLexer, typ ItemType) stateFunc {
150 openBacktickFound := false
151
152 Loop:
153 for {
154 switch r := l.next(); {
155 case r == '`':
156 if openBacktickFound {
157 l.backup()
158 break Loop
159 } else {
160 openBacktickFound = true
161 l.ignore()
162 }
163 case r == eof:
164 return l.errorf("unterminated raw string in shortcode parameter-argument: '%s'", l.current())
165 }
166 }
167
168 l.emitString(typ)
169 l.next()
170 l.ignore()
171
172 return lexInsideShortcode
173 }
174
175 func lexShortcodeQuotedParamVal(l *pageLexer, escapedQuotedValuesAllowed bool, typ ItemType) stateFunc {
176 openQuoteFound := false
177 escapedInnerQuoteFound := false
178 escapedQuoteState := 0
179
180 Loop:
181 for {
182 switch r := l.next(); {
183 case r == '\\':
184 if l.peek() == '"' {
185 if openQuoteFound && !escapedQuotedValuesAllowed {
186 l.backup()
187 break Loop
188 } else if openQuoteFound {
189 // the coming quote is inside
190 escapedInnerQuoteFound = true
191 escapedQuoteState = 1
192 }
193 } else if l.peek() == '`' {
194 return l.errorf("unrecognized escape character")
195 }
196 case r == eof, r == '\n':
197 return l.errorf("unterminated quoted string in shortcode parameter-argument: '%s'", l.current())
198 case r == '"':
199 if escapedQuoteState == 0 {
200 if openQuoteFound {
201 l.backup()
202 break Loop
203
204 } else {
205 openQuoteFound = true
206 l.ignore()
207 }
208 } else {
209 escapedQuoteState = 0
210 }
211 }
212 }
213
214 if escapedInnerQuoteFound {
215 l.ignoreEscapesAndEmit(typ, true)
216 } else {
217 l.emitString(typ)
218 }
219
220 r := l.next()
221
222 if r == '\\' {
223 if l.peek() == '"' {
224 // ignore the escaped closing quote
225 l.ignore()
226 l.next()
227 l.ignore()
228 }
229 } else if r == '"' {
230 // ignore closing quote
231 l.ignore()
232 } else {
233 // handled by next state
234 l.backup()
235 }
236
237 return lexInsideShortcode
238 }
239
240 // Inline shortcodes has the form {{< myshortcode.inline >}}
241 var inlineIdentifier = []byte("inline ")
242
243 // scans an alphanumeric inside shortcode
244 func lexIdentifierInShortcode(l *pageLexer) stateFunc {
245 lookForEnd := false
246 Loop:
247 for {
248 switch r := l.next(); {
249 case isAlphaNumericOrHyphen(r):
250 // Allow forward slash inside names to make it possible to create namespaces.
251 case r == '/':
252 case r == '.':
253 l.isInline = l.hasPrefix(inlineIdentifier)
254 if !l.isInline {
255 return l.errorf("period in shortcode name only allowed for inline identifiers")
256 }
257 default:
258 l.backup()
259 word := unique.Make(string(l.input[l.start:l.pos]))
260 if l.closingState > 0 {
261 if !l.openShortcodes[word] {
262 return l.errorf("closing tag for shortcode '%s' does not match start tag", word.Value())
263 }
264 l.openShortcodes[word] = false
265 lookForEnd = true
266 }
267
268 l.closingState = 0
269 l.currShortcodeName = word.Value()
270 l.openShortcodes[word] = true
271 l.elementStepNum++
272 if l.isInline {
273 l.emit(tScNameInline)
274 } else {
275 l.emit(tScName)
276 }
277 break Loop
278 }
279 }
280
281 if lookForEnd {
282 return lexEndOfShortcode
283 }
284 return lexInsideShortcode
285 }
286
287 func lexEndOfShortcode(l *pageLexer) stateFunc {
288 l.isInline = false
289 if l.hasPrefix(l.currentRightShortcodeDelim()) {
290 return lexShortcodeRightDelim
291 }
292 switch r := l.next(); {
293 case isASCIISpace(r):
294 l.ignore()
295 default:
296 return l.errorf("unclosed shortcode")
297 }
298 return lexEndOfShortcode
299 }
300
301 // scans the elements inside shortcode tags
302 func lexInsideShortcode(l *pageLexer) stateFunc {
303 if l.hasPrefix(l.currentRightShortcodeDelim()) {
304 return lexShortcodeRightDelim
305 }
306 switch r := l.next(); {
307 case r == eof:
308 // eol is allowed inside shortcodes; this may go to end of document before it fails
309 return l.errorf("unclosed shortcode action")
310 case isASCIISpace(r):
311 l.ignore()
312 case r == '=':
313 l.consumeSpace()
314 l.ignore()
315 peek := l.peek()
316 if peek == '"' || peek == '\\' {
317 return lexShortcodeQuotedParamVal(l, peek != '\\', tScParamVal)
318 } else if peek == '`' {
319 return lexShortCodeParamRawStringVal(l, tScParamVal)
320 }
321 return lexShortcodeParamVal
322 case r == '/':
323 if l.currShortcodeName == "" {
324 return l.errorf("got closing shortcode, but none is open")
325 }
326 l.closingState++
327 l.isInline = false
328 l.elementStepNum = 0
329 l.emit(tScClose)
330 case r == '\\':
331 l.ignore()
332 if l.peek() == '"' || l.peek() == '`' {
333 return lexShortcodeParam(l, true)
334 }
335 case l.elementStepNum > 0 && (isAlphaNumericOrHyphen(r) || r == '"' || r == '`'): // positional params can have quotes
336 l.backup()
337 return lexShortcodeParam(l, false)
338 case isAlphaNumeric(r):
339 l.backup()
340 return lexIdentifierInShortcode
341 default:
342 return l.errorf("unrecognized character in shortcode action: %#U. Note: Parameters with non-alphanumeric args must be quoted", r)
343 }
344 return lexInsideShortcode
345 }
346
347 func (l *pageLexer) currentLeftShortcodeDelimItem() ItemType {
348 return l.currLeftDelimItem
349 }
350
351 func (l *pageLexer) currentRightShortcodeDelimItem() ItemType {
352 return l.currRightDelimItem
353 }
354
355 func (l *pageLexer) currentLeftShortcodeDelim() []byte {
356 if l.currLeftDelimItem == tLeftDelimScWithMarkup {
357 return leftDelimScWithMarkup
358 }
359 return leftDelimScNoMarkup
360 }
361
362 func (l *pageLexer) currentRightShortcodeDelim() []byte {
363 if l.currRightDelimItem == tRightDelimScWithMarkup {
364 return rightDelimScWithMarkup
365 }
366 return rightDelimScNoMarkup
367 }