Class: Twig::Parser
- Inherits:
-
Object
- Object
- Twig::Parser
- Defined in:
- lib/twig/parser.rb
Constant Summary collapse
- STACKABLE =
%i[ stream parent blocks block_stack macros imported_symbols traits embedded_templates ignore_unknown_twig_callables ].freeze
Instance Attribute Summary collapse
-
#block_stack ⇒ Object
readonly
Returns the value of attribute block_stack.
- #environment ⇒ Environment readonly
- #stream ⇒ TokenStream readonly
Instance Method Summary collapse
- #add_imported_symbol(type, symbol_alias, name = nil, internal_ref = nil) ⇒ Object
- #add_trait(trait) ⇒ Object
- #block?(name) ⇒ Boolean
- #current_token ⇒ Token
- #embed_template(template) ⇒ Object
- #expression_parser ⇒ ExpressionParser
- #filter(name, lineno) ⇒ TwigFilter
- #function(name, args, lineno) ⇒ TwigFunction, Node::Expression::HelperMethod
- #ignore_unknown_twig_callables? ⇒ Boolean
- #imported_symbol(type, symbol_alias) ⇒ Object
- #inheritance? ⇒ Boolean
-
#initialize(environment) ⇒ Parser
constructor
A new instance of Parser.
- #main_scope? ⇒ Boolean
- #parent=(parent) ⇒ Object
- #parse(stream, test = nil, drop_needle: false) ⇒ Node::Module
- #parse_expression(precedence = 0) ⇒ Object
- #peek_block_stack ⇒ Object
- #pop_block_stack ⇒ Object
- #pop_local_scope ⇒ Object
- #push_block_stack(name) ⇒ Object
- #push_local_scope ⇒ Object
- #set_block(name, value) ⇒ Object
- #set_macro(name, node) ⇒ Object
- #subparse(test, drop_needle: false) ⇒ Node::Base
- #subparse_ignore_unknown_twig_callables(test, drop_needle: false) ⇒ Object
- #test(line) ⇒ TwigTest
Constructor Details
#initialize(environment) ⇒ Parser
Returns a new instance of Parser.
25 26 27 28 29 |
# File 'lib/twig/parser.rb', line 25 def initialize(environment) @environment = environment @parsers = environment.expression_parsers @stack = [] end |
Instance Attribute Details
#block_stack ⇒ Object (readonly)
Returns the value of attribute block_stack.
7 8 9 |
# File 'lib/twig/parser.rb', line 7 def block_stack @block_stack end |
#environment ⇒ Environment (readonly)
10 11 12 |
# File 'lib/twig/parser.rb', line 10 def environment @environment end |
#stream ⇒ TokenStream (readonly)
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 |
# File 'lib/twig/parser.rb', line 6 class Parser attr_reader :stream, :block_stack # @return [Environment] attr_reader :environment STACKABLE = %i[ stream parent blocks block_stack macros imported_symbols traits embedded_templates ignore_unknown_twig_callables ].freeze # @param [Environment] environment def initialize(environment) @environment = environment @parsers = environment.expression_parsers @stack = [] end # @param [TokenStream] stream # @return [Node::Module] def parse(stream, test = nil, drop_needle: false) # Save the current value to stack frame = {} STACKABLE.each do |attr| frame[attr] = instance_variable_get("@#{attr}") end @stack << frame @stream = stream @parent = nil @traits = AutoHash.new @macros = {} @blocks = {} @embedded_templates = AutoHash.new @block_stack = [] @imported_symbols = [{}] @ignore_unknown_twig_callables = false begin body = subparse(test, drop_needle:) if !@parent.nil? && (body = filter_body_nodes(body)).nil? body = Node::Empty.new end rescue Error::Syntax => e unless e.source_context e.source_context = stream.source end unless e.lineno e.lineno = stream.current.lineno end raise e end node = Node::Module.new( Node::Body.new({ 0 => body }), @parent, @blocks.empty? ? Node::Empty.new : Node::Nodes.new(@blocks), @macros.empty? ? Node::Empty.new : Node::Nodes.new(@macros), @traits.empty? ? Node::Empty.new : Node::Nodes.new(@traits), @embedded_templates.empty? ? Node::Empty.new : Node::Nodes.new(@embedded_templates), stream.source ) @visitors ||= environment.node_visitors node = NodeTraverser. new(environment, @visitors). traverse(node) # Restore stack frame = @stack.pop STACKABLE.each do |attr| instance_variable_set("@#{attr}", frame[attr]) end node end # @param [Method, nil] test # @return [Node::Base] def subparse(test, drop_needle: false) lineno = current_token.lineno rv = AutoHash.new until stream.eof? case current_token.type when Token::TEXT_TYPE token = stream.next rv.add(Node::Text.new(token.value, token.lineno)) when Token::VAR_START_TYPE token = stream.next expr = parse_expression stream.expect(Token::VAR_END_TYPE) rv.add(Node::Print.new(expr, token.lineno)) when Token::BLOCK_START_TYPE stream.next token = current_token unless token.type == Token::NAME_TYPE raise Error::Syntax.new('A block must start with a tag name.', token.lineno, stream.source) end if test&.call(token) stream.next if drop_needle return rv.values.first if rv.length == 1 return Node::Nodes.new(rv, lineno) end subparser = @environment.token_parser(token.value) unless subparser if test.nil? raise Error::Syntax.new("Unknown \"#{token.value}\" tag.", token.lineno, stream.source) else e = Error::Syntax.new("Unexpected \"#{token.value}\" tag", token.lineno, stream.source) if test.respond_to?(:receiver) && (receiver = test.receiver) && receiver.is_a?(Twig::TokenParser::Base) e.( " (expecting closing tag for the \"#{receiver.tag}\" tag defined near line #{lineno})." ) end raise e end end stream.next subparser.parser = self node = subparser.parse(token) raise 'Cannot return nil from TokenParser' unless node node.tag = subparser.tag rv.add(node) else raise "Unable to parse token of type #{current_token.type}" end end Node::Nodes.new(rv) end def subparse_ignore_unknown_twig_callables(test, drop_needle: false) previous = @ignore_unknown_twig_callables @ignore_unknown_twig_callables = true begin subparse(test, drop_needle:) ensure @ignore_unknown_twig_callables = previous end end # @return [Token] def current_token stream.current end def parse_expression(precedence = 0) token = current_token if token.test(Token::OPERATOR_TYPE) && (parser = parsers.by_name(:prefix, token.value)) stream.next expr = parser.parse(self, token) else expr = parsers.by_class(ExpressionParser::Prefix::Literal.name).parse(self, token) end token = current_token while token.test(Token::OPERATOR_TYPE) && (parser = parsers.by_name(:infix, token.value)) && parser.precedence >= precedence stream.next expr = parser.parse(self, expr, token) token = current_token end expr end # @return [TwigFilter] def filter(name, lineno) unless (filter = environment.filter(name)) unless ignore_unknown_twig_callables? raise Error::Syntax.new("Unknown '#{name}' filter.", lineno, stream.source) end filter = TwigFilter.new(name, -> {}) end filter end # @return [TwigFunction, Node::Expression::HelperMethod] def function(name, args, lineno) unless (function = environment.function(name)) if ignore_unknown_twig_callables? return TwigFunction.new(name, -> {}) elsif environment.allow_helper_methods? return Node::Expression::HelperMethod.new(name, args, lineno) else raise Error::Syntax.new("Unknown \"#{name}\" function.", lineno, stream.source) end end function end # @param [Integer] line # @return [TwigTest] def test(line) name = stream.expect(Token::NAME_TYPE).value if stream.test(Token::NAME_TYPE) # try 2 word tests name = "#{name} #{current_token.value}" if (test = environment.test(name)) stream.next end else test = environment.test(name) end if test.nil? && ignore_unknown_twig_callables? test = TwigTest.new(name, -> {}) end unless test raise Error::Syntax.new("Unknown #{name} test.", line, stream.source) end test end # @return [ExpressionParser] def expression_parser @expression_parser ||= ExpressionParser.new(self, @environment) end # @return [Boolean] def inheritance? @parent || @traits.length.positive? end def main_scope? @imported_symbols.one? end def push_local_scope @imported_symbols.unshift({}) end def pop_local_scope @imported_symbols.shift end def add_imported_symbol(type, symbol_alias, name = nil, internal_ref = nil) @imported_symbols[0][type] ||= {} @imported_symbols[0][type][symbol_alias] = { name:, node: internal_ref } end def imported_symbol(type, symbol_alias) if (symbol = @imported_symbols.dig(0, type, symbol_alias)) symbol else @imported_symbols.dig(-1, type, symbol_alias) end end # @param [Node::Module] template def (template) template.index = rand(2**32) @embedded_templates << template end def peek_block_stack @block_stack[-1] end def pop_block_stack @block_stack.pop end def push_block_stack(name) @block_stack << name end def block?(name) @blocks.key?(name) end def add_trait(trait) @traits << trait end # @param [String] name # @param [Node::Macro] node def set_macro(name, node) @macros[name] = node end # @param [String] name # @param [Node::Body] value def set_block(name, value) if @blocks.key?(name) raise Error::Syntax.new( "The block '#{name}' has already been defined line #{@blocks[name].lineno}.", current_token.lineno, @blocks[name].source_context ) end @blocks[name] = Node::Body.new({ 0 => value }, {}, value.lineno) end # @param [Node::Base] parent def parent=(parent) if @parent raise Error::Syntax.new('Cannot extends twice', parent.lineno, parent.source_context) end @parent = parent end def ignore_unknown_twig_callables? @ignore_unknown_twig_callables end private # @return [ExpressionParser::ExpressionParsers] attr_reader :parsers def filter_body_nodes(node, nested: false) # check that the body does not contain non-empty output nodes if (node.is_a?(Node::Text) && !node.attributes[:data].match?(/\A[[:space:]]*\z/)) || (!node.is_a?(Node::Text) && !node.is_a?(Node::BlockReference) && node.is_a?(Node::Output)) if node.to_s.include?("\xEF\xBB\xBF") t = node.attributes[:data][3..] # bypass empty nodes starting with a BOM if t == '' || t.match?(/\A[[:space:]]*\z/) return nil end end raise Error::Syntax.new( 'A template that extends another one cannot include content outside Twig blocks. Did you forget ' \ 'to put the content inside a {% block %} tag?', node.lineno, stream.source ) end # Bypass nodes that "capture" the output if node.is_a?(Node::Set) return node end # "block" tags that are not captured (see above) are only used for defining # the content of the block. In such a case, nesting it does not work as # expected as the definition is not part of the default template code flow. if nested && node.is_a?(Node::BlockReference) raise Error::Syntax.new( 'A block definition cannot be nested under non-capturing nodes.', node.lineno, stream.source ) end if node.is_a?(Node::Output) return nil end nested ||= !node.is_a?(Node::Nodes) node.nodes.each do |k, n| if filter_body_nodes(n, nested: nested).nil? node.nodes.delete(k) end end node end end |
Instance Method Details
#add_imported_symbol(type, symbol_alias, name = nil, internal_ref = nil) ⇒ Object
276 277 278 279 |
# File 'lib/twig/parser.rb', line 276 def add_imported_symbol(type, symbol_alias, name = nil, internal_ref = nil) @imported_symbols[0][type] ||= {} @imported_symbols[0][type][symbol_alias] = { name:, node: internal_ref } end |
#add_trait(trait) ⇒ Object
312 313 314 |
# File 'lib/twig/parser.rb', line 312 def add_trait(trait) @traits << trait end |
#block?(name) ⇒ Boolean
308 309 310 |
# File 'lib/twig/parser.rb', line 308 def block?(name) @blocks.key?(name) end |
#current_token ⇒ Token
173 174 175 |
# File 'lib/twig/parser.rb', line 173 def current_token stream.current end |
#embed_template(template) ⇒ Object
290 291 292 293 294 |
# File 'lib/twig/parser.rb', line 290 def (template) template.index = rand(2**32) @embedded_templates << template end |
#expression_parser ⇒ ExpressionParser
255 256 257 |
# File 'lib/twig/parser.rb', line 255 def expression_parser @expression_parser ||= ExpressionParser.new(self, @environment) end |
#filter(name, lineno) ⇒ TwigFilter
200 201 202 203 204 205 206 207 208 209 210 |
# File 'lib/twig/parser.rb', line 200 def filter(name, lineno) unless (filter = environment.filter(name)) unless ignore_unknown_twig_callables? raise Error::Syntax.new("Unknown '#{name}' filter.", lineno, stream.source) end filter = TwigFilter.new(name, -> {}) end filter end |
#function(name, args, lineno) ⇒ TwigFunction, Node::Expression::HelperMethod
213 214 215 216 217 218 219 220 221 222 223 224 225 |
# File 'lib/twig/parser.rb', line 213 def function(name, args, lineno) unless (function = environment.function(name)) if ignore_unknown_twig_callables? return TwigFunction.new(name, -> {}) elsif environment.allow_helper_methods? return Node::Expression::HelperMethod.new(name, args, lineno) else raise Error::Syntax.new("Unknown \"#{name}\" function.", lineno, stream.source) end end function end |
#ignore_unknown_twig_callables? ⇒ Boolean
345 346 347 |
# File 'lib/twig/parser.rb', line 345 def ignore_unknown_twig_callables? @ignore_unknown_twig_callables end |
#imported_symbol(type, symbol_alias) ⇒ Object
281 282 283 284 285 286 287 |
# File 'lib/twig/parser.rb', line 281 def imported_symbol(type, symbol_alias) if (symbol = @imported_symbols.dig(0, type, symbol_alias)) symbol else @imported_symbols.dig(-1, type, symbol_alias) end end |
#inheritance? ⇒ Boolean
260 261 262 |
# File 'lib/twig/parser.rb', line 260 def inheritance? @parent || @traits.length.positive? end |
#main_scope? ⇒ Boolean
264 265 266 |
# File 'lib/twig/parser.rb', line 264 def main_scope? @imported_symbols.one? end |
#parent=(parent) ⇒ Object
337 338 339 340 341 342 343 |
# File 'lib/twig/parser.rb', line 337 def parent=(parent) if @parent raise Error::Syntax.new('Cannot extends twice', parent.lineno, parent.source_context) end @parent = parent end |
#parse(stream, test = nil, drop_needle: false) ⇒ Node::Module
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'lib/twig/parser.rb', line 33 def parse(stream, test = nil, drop_needle: false) # Save the current value to stack frame = {} STACKABLE.each do |attr| frame[attr] = instance_variable_get("@#{attr}") end @stack << frame @stream = stream @parent = nil @traits = AutoHash.new @macros = {} @blocks = {} @embedded_templates = AutoHash.new @block_stack = [] @imported_symbols = [{}] @ignore_unknown_twig_callables = false begin body = subparse(test, drop_needle:) if !@parent.nil? && (body = filter_body_nodes(body)).nil? body = Node::Empty.new end rescue Error::Syntax => e unless e.source_context e.source_context = stream.source end unless e.lineno e.lineno = stream.current.lineno end raise e end node = Node::Module.new( Node::Body.new({ 0 => body }), @parent, @blocks.empty? ? Node::Empty.new : Node::Nodes.new(@blocks), @macros.empty? ? Node::Empty.new : Node::Nodes.new(@macros), @traits.empty? ? Node::Empty.new : Node::Nodes.new(@traits), @embedded_templates.empty? ? Node::Empty.new : Node::Nodes.new(@embedded_templates), stream.source ) @visitors ||= environment.node_visitors node = NodeTraverser. new(environment, @visitors). traverse(node) # Restore stack frame = @stack.pop STACKABLE.each do |attr| instance_variable_set("@#{attr}", frame[attr]) end node end |
#parse_expression(precedence = 0) ⇒ Object
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 |
# File 'lib/twig/parser.rb', line 177 def parse_expression(precedence = 0) token = current_token if token.test(Token::OPERATOR_TYPE) && (parser = parsers.by_name(:prefix, token.value)) stream.next expr = parser.parse(self, token) else expr = parsers.by_class(ExpressionParser::Prefix::Literal.name).parse(self, token) end token = current_token while token.test(Token::OPERATOR_TYPE) && (parser = parsers.by_name(:infix, token.value)) && parser.precedence >= precedence stream.next expr = parser.parse(self, expr, token) token = current_token end expr end |
#peek_block_stack ⇒ Object
296 297 298 |
# File 'lib/twig/parser.rb', line 296 def peek_block_stack @block_stack[-1] end |
#pop_block_stack ⇒ Object
300 301 302 |
# File 'lib/twig/parser.rb', line 300 def pop_block_stack @block_stack.pop end |
#pop_local_scope ⇒ Object
272 273 274 |
# File 'lib/twig/parser.rb', line 272 def pop_local_scope @imported_symbols.shift end |
#push_block_stack(name) ⇒ Object
304 305 306 |
# File 'lib/twig/parser.rb', line 304 def push_block_stack(name) @block_stack << name end |
#push_local_scope ⇒ Object
268 269 270 |
# File 'lib/twig/parser.rb', line 268 def push_local_scope @imported_symbols.unshift({}) end |
#set_block(name, value) ⇒ Object
324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/twig/parser.rb', line 324 def set_block(name, value) if @blocks.key?(name) raise Error::Syntax.new( "The block '#{name}' has already been defined line #{@blocks[name].lineno}.", current_token.lineno, @blocks[name].source_context ) end @blocks[name] = Node::Body.new({ 0 => value }, {}, value.lineno) end |
#set_macro(name, node) ⇒ Object
318 319 320 |
# File 'lib/twig/parser.rb', line 318 def set_macro(name, node) @macros[name] = node end |
#subparse(test, drop_needle: false) ⇒ Node::Base
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 |
# File 'lib/twig/parser.rb', line 96 def subparse(test, drop_needle: false) lineno = current_token.lineno rv = AutoHash.new until stream.eof? case current_token.type when Token::TEXT_TYPE token = stream.next rv.add(Node::Text.new(token.value, token.lineno)) when Token::VAR_START_TYPE token = stream.next expr = parse_expression stream.expect(Token::VAR_END_TYPE) rv.add(Node::Print.new(expr, token.lineno)) when Token::BLOCK_START_TYPE stream.next token = current_token unless token.type == Token::NAME_TYPE raise Error::Syntax.new('A block must start with a tag name.', token.lineno, stream.source) end if test&.call(token) stream.next if drop_needle return rv.values.first if rv.length == 1 return Node::Nodes.new(rv, lineno) end subparser = @environment.token_parser(token.value) unless subparser if test.nil? raise Error::Syntax.new("Unknown \"#{token.value}\" tag.", token.lineno, stream.source) else e = Error::Syntax.new("Unexpected \"#{token.value}\" tag", token.lineno, stream.source) if test.respond_to?(:receiver) && (receiver = test.receiver) && receiver.is_a?(Twig::TokenParser::Base) e.( " (expecting closing tag for the \"#{receiver.tag}\" tag defined near line #{lineno})." ) end raise e end end stream.next subparser.parser = self node = subparser.parse(token) raise 'Cannot return nil from TokenParser' unless node node.tag = subparser.tag rv.add(node) else raise "Unable to parse token of type #{current_token.type}" end end Node::Nodes.new(rv) end |
#subparse_ignore_unknown_twig_callables(test, drop_needle: false) ⇒ Object
161 162 163 164 165 166 167 168 169 170 |
# File 'lib/twig/parser.rb', line 161 def subparse_ignore_unknown_twig_callables(test, drop_needle: false) previous = @ignore_unknown_twig_callables @ignore_unknown_twig_callables = true begin subparse(test, drop_needle:) ensure @ignore_unknown_twig_callables = previous end end |
#test(line) ⇒ TwigTest
229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
# File 'lib/twig/parser.rb', line 229 def test(line) name = stream.expect(Token::NAME_TYPE).value if stream.test(Token::NAME_TYPE) # try 2 word tests name = "#{name} #{current_token.value}" if (test = environment.test(name)) stream.next end else test = environment.test(name) end if test.nil? && ignore_unknown_twig_callables? test = TwigTest.new(name, -> {}) end unless test raise Error::Syntax.new("Unknown #{name} test.", line, stream.source) end test end |