From b115d851bd173c6f7c320b0e07e8297ead464301 Mon Sep 17 00:00:00 2001 From: Liam Harwood Date: Mon, 29 Apr 2019 15:41:21 -0400 Subject: [PATCH] Add a warning when there is no matching start tag for an end tag --- .../java/com/hubspot/jinjava/tree/TreeParser.java | 14 ++++++++++++++ .../com/hubspot/jinjava/tree/TreeParserTest.java | 11 +++++++++++ 2 files changed, 25 insertions(+) diff --git a/src/main/java/com/hubspot/jinjava/tree/TreeParser.java b/src/main/java/com/hubspot/jinjava/tree/TreeParser.java index d77abe1b5..466213a74 100644 --- a/src/main/java/com/hubspot/jinjava/tree/TreeParser.java +++ b/src/main/java/com/hubspot/jinjava/tree/TreeParser.java @@ -199,11 +199,13 @@ private void endTag(Tag tag, TagToken tagToken) { parent.getMaster().setRightTrimAfterEnd(tagToken.isRightTrim()); } + boolean hasMatchingStartTag = false; while (!(parent instanceof RootNode)) { TagNode parentTag = (TagNode) parent; parent = parent.getParent(); if (parentTag.getEndName().equals(tag.getEndTagName())) { + hasMatchingStartTag = true; break; } else { interpreter.addError(TemplateError.fromException( @@ -212,5 +214,17 @@ private void endTag(Tag tag, TagToken tagToken) { tagToken.getLineNumber(), tagToken.getStartPosition()))); } } + if (!hasMatchingStartTag) { + interpreter.addError(new TemplateError( + ErrorType.WARNING, + ErrorReason.SYNTAX_ERROR, + ErrorItem.TAG, + "Missing start tag", + tag.getName(), + tagToken.getLineNumber(), + tagToken.getStartPosition(), + null + )); + } } } diff --git a/src/test/java/com/hubspot/jinjava/tree/TreeParserTest.java b/src/test/java/com/hubspot/jinjava/tree/TreeParserTest.java index ec1f8e887..0c56944bd 100644 --- a/src/test/java/com/hubspot/jinjava/tree/TreeParserTest.java +++ b/src/test/java/com/hubspot/jinjava/tree/TreeParserTest.java @@ -11,6 +11,7 @@ import com.hubspot.jinjava.Jinjava; import com.hubspot.jinjava.JinjavaConfig; import com.hubspot.jinjava.interpret.JinjavaInterpreter; +import com.hubspot.jinjava.interpret.TemplateError.ErrorType; public class TreeParserTest { @@ -86,6 +87,16 @@ public void trimAndLstripBlocks() { + "\n"); } + @Test + public void itWarnsAgainstMissingStartTags() { + String expression = "{% if true %} foo {% endif %} {% endif %}"; + final Node tree = new TreeParser(interpreter, expression).buildTree(); + assertThat(interpreter.getErrors()).hasSize(1); + assertThat(interpreter.getErrors().get(0).getSeverity()).isEqualTo(ErrorType.WARNING); + assertThat(interpreter.getErrors().get(0).getMessage()).isEqualTo("Missing start tag"); + assertThat(interpreter.getErrors().get(0).getFieldName()).isEqualTo("endif"); + } + Node parse(String fixture) { try { return new TreeParser(interpreter, Resources.toString(