From b7eb0e5990b45afc10ccc3c91edbd226793843b1 Mon Sep 17 00:00:00 2001 From: Rob Pike Date: Fri, 9 Aug 2013 12:57:21 +1000 Subject: [PATCH] text/template/parse: nicer error when comment ends before final delimiter By separating finding the end of the comment from the end of the action, we can diagnose malformed comments better. Also tweak the documentation to make the comment syntax clearer. Fixes #6022. R=golang-dev, dsymonds CC=golang-dev https://golang.org/cl/12570044 --- src/pkg/text/template/doc.go | 3 ++- src/pkg/text/template/parse/lex.go | 9 +++++++-- src/pkg/text/template/parse/lex_test.go | 4 ++++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/pkg/text/template/doc.go b/src/pkg/text/template/doc.go index 2da339ce83..c9121f74d3 100644 --- a/src/pkg/text/template/doc.go +++ b/src/pkg/text/template/doc.go @@ -44,7 +44,8 @@ data, defined in detail below. */ // {{/* a comment */}} // A comment; discarded. May contain newlines. -// Comments do not nest. +// Comments do not nest and must start and end at the +// delimiters, as shown here. /* {{pipeline}} diff --git a/src/pkg/text/template/parse/lex.go b/src/pkg/text/template/parse/lex.go index 23c0cf0793..1674aaf9cd 100644 --- a/src/pkg/text/template/parse/lex.go +++ b/src/pkg/text/template/parse/lex.go @@ -243,11 +243,16 @@ func lexLeftDelim(l *lexer) stateFn { // lexComment scans a comment. The left comment marker is known to be present. func lexComment(l *lexer) stateFn { l.pos += Pos(len(leftComment)) - i := strings.Index(l.input[l.pos:], rightComment+l.rightDelim) + i := strings.Index(l.input[l.pos:], rightComment) if i < 0 { return l.errorf("unclosed comment") } - l.pos += Pos(i + len(rightComment) + len(l.rightDelim)) + l.pos += Pos(i + len(rightComment)) + if !strings.HasPrefix(l.input[l.pos:], l.rightDelim) { + return l.errorf("comment ends before closing delimiter") + + } + l.pos += Pos(len(l.rightDelim)) l.ignore() return lexText } diff --git a/src/pkg/text/template/parse/lex_test.go b/src/pkg/text/template/parse/lex_test.go index d2264c991c..ae90ae407b 100644 --- a/src/pkg/text/template/parse/lex_test.go +++ b/src/pkg/text/template/parse/lex_test.go @@ -336,6 +336,10 @@ var lexTests = []lexTest{ {itemText, 0, "hello-"}, {itemError, 0, `unclosed comment`}, }}, + {"text with comment close separted from delim", "hello-{{/* */ }}-world", []item{ + {itemText, 0, "hello-"}, + {itemError, 0, `comment ends before closing delimiter`}, + }}, } // collect gathers the emitted items into a slice. -- 2.48.1