1
0
mirror of https://github.com/golang/go synced 2024-11-08 01:46:14 -07:00
Commit Graph

173 Commits

Author SHA1 Message Date
Adrien Delorme
d4247f5167 text/template: wrap errors returned by template functions instead of stringifying them
Fixes #34201

Change-Id: Ic2e2967e4b01167345cf38bd006cabb206a64377
GitHub-Last-Rev: 5d0c485655
GitHub-Pull-Request: golang/go#42398
Reviewed-on: https://go-review.googlesource.com/c/go/+/267838
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
Trust: Daniel Martí <mvdan@mvdan.cc>
Trust: Pontus Leitzler <leitzler@gmail.com>
Trust: Cuong Manh Le <cuong.manhle.vn@gmail.com>
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Go Bot <gobot@golang.org>
2021-03-05 18:00:44 +00:00
Joe Tsai
b83d073e9e reflect: add Method.IsExported and StructField.IsExported methods
The IsExported method is a more intuitive helper for checking whether
the method or field is exported than checking whether PkgPath is empty.

In the same CL, modify the standard library to make use of this helper.

Fixes #41563

Change-Id: Iaacfb3b74449501f98e2707aa32095a32bd3c3c1
Reviewed-on: https://go-review.googlesource.com/c/go/+/266197
Trust: Joe Tsai <joetsai@digital-static.net>
Run-TryBot: Joe Tsai <thebrokentoaster@gmail.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2021-02-25 21:21:51 +00:00
Meng Zhuo
3298300ddf text/template: error on range over send channel
template range require channel contains RecvDir
if recv on send only channel will raise an panic.

Fixes #43065

Change-Id: Ie0ea70ce60e074bf8c9f2378e07ef1d4c41dc38f
Reviewed-on: https://go-review.googlesource.com/c/go/+/276532
Trust: Meng Zhuo <mzh@golangcn.org>
Run-TryBot: Meng Zhuo <mzh@golangcn.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
2020-12-15 13:59:00 +00:00
Russ Cox
4f1b0a44cb all: update to use os.ReadFile, os.WriteFile, os.CreateTemp, os.MkdirTemp
As part of #42026, these helpers from io/ioutil were moved to os.
(ioutil.TempFile and TempDir became os.CreateTemp and MkdirTemp.)

Update the Go tree to use the preferred names.

As usual, code compiled with the Go 1.4 bootstrap toolchain
and code vendored from other sources is excluded.

ReadDir changes are in a separate CL, because they are not a
simple search and replace.

For #42026.

Change-Id: If318df0216d57e95ea0c4093b89f65e5b0ababb3
Reviewed-on: https://go-review.googlesource.com/c/go/+/266365
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2020-12-09 19:12:23 +00:00
Russ Cox
1b09d43067 all: update references to symbols moved from io/ioutil to io
The old ioutil references are still valid, but update our code
to reflect best practices and get used to the new locations.

Code compiled with the bootstrap toolchain
(cmd/asm, cmd/dist, cmd/compile, debug/elf)
must remain Go 1.4-compatible and is excluded.
Also excluded vendored code.

For #41190.

Change-Id: I6d86f2bf7bc37a9d904b6cee3fe0c7af6d94d5b1
Reviewed-on: https://go-review.googlesource.com/c/go/+/263142
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Emmanuel Odeke <emm.odeke@gmail.com>
2020-10-20 18:41:18 +00:00
Russ Cox
2a9aa4dcac html/template, text/template: add ParseFS
Now templates can be parsed not just from operating system files
but from arbitrary file systems, including zip files.

For #41190.

Change-Id: I2172001388ddb1f13defa6c5e644e8ec8703ee80
Reviewed-on: https://go-review.googlesource.com/c/go/+/243938
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
2020-10-20 18:41:14 +00:00
Russ Cox
9384d34c58 text/template: allow newlines inside action delimiters
This allows multiline constructs like:

	{{"hello" |
	  printf}}

Now that unclosed actions can span multiple lines,
track and report the start of the action when reporting errors.

Also clean up a few "unexpected <error message>" to be just "<error message>".

Fixes #29770.

Change-Id: I54c6c016029a8328b7902a4b6d85eab713ec3285
Reviewed-on: https://go-review.googlesource.com/c/go/+/254257
Trust: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
2020-10-12 16:30:36 +00:00
Ariel Mashraki
c8ea03828b text/template: add CommentNode to template parse tree
Fixes #34652

Change-Id: Icf6e3eda593fed826736f34f95a9d66f5450cc98
Reviewed-on: https://go-review.googlesource.com/c/go/+/229398
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
2020-08-28 21:45:12 +00:00
Russ Cox
efbe47b162 html/template: add tests from text/template
Copy and adapt tests from text/template, to exercise more of html/template's copy.

Various differences in behavior are flagged with NOTE comments or t.Skip
and documented in #40075. Many of them are probably bugs.
One clarifying test case added to both text/template and html/template.

No changes to the package itself.

Change-Id: Ifefad83d647db846040d24c2741a0244b00ade82
Reviewed-on: https://go-review.googlesource.com/c/go/+/241084
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
2020-07-14 16:54:25 +00:00
Macks
968e18eebd text/template: fix lint typo in VariableNode doc
Change-Id: I68b8c782478aa3e7adbd36a2de1c20b04e8c395b
GitHub-Last-Rev: 50f2719783
GitHub-Pull-Request: golang/go#39622
Reviewed-on: https://go-review.googlesource.com/c/go/+/239383
Reviewed-by: Rob Pike <r@golang.org>
2020-06-23 00:10:24 +00:00
Bryan C. Mills
9f4aeb36e2 all: use a hermetic "go" tool in standard-library tests
The go/build package uses the "go" tool from the user's environment,
but its tests should not assume that that tool is in any particular
state, let alone appropriate for running the test.

Instead, explicitly use testenv.GoTool, adding it to $PATH in a
TestMain when necessary.

Fixes #39199
Fixes #39198

Change-Id: I56618a55ced473e75dd96eeb3a8f7084e2e64d02
Reviewed-on: https://go-review.googlesource.com/c/go/+/234880
Run-TryBot: Bryan C. Mills <bcmills@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Alexander Rakoczy <alex@golang.org>
2020-05-21 21:17:48 +00:00
empijei
d4d298040d html/template,text/template: switch to Unicode escapes for JSON compatibility
The existing implementation is not compatible with JSON
escape as it uses hex escaping.
Unicode escape, instead, is valid for both JSON and JS.
This fix avoids creating a separate escaping context for
scripts of type "application/ld+json" and it is more
future-proof in case more JSON+JS contexts get added
to the platform (e.g. import maps).

Fixes #33671
Fixes #37634

Change-Id: Id6f6524b4abc52e81d9d744d46bbe5bf2e081543
Reviewed-on: https://go-review.googlesource.com/c/go/+/226097
Reviewed-by: Carl Johnson <me@carlmjohnson.net>
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
2020-04-16 17:13:33 +00:00
Brad Fitzpatrick
435b9dd1a1 text/template: avoid a global map to help the linker's deadcode elimination
Fixes #36021
Updates #2559
Updates #26775

Change-Id: I2e6708691311035b63866f25d5b4b3977a118290
Reviewed-on: https://go-review.googlesource.com/c/go/+/210284
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
2020-04-15 15:30:46 +00:00
Daniel Martí
218f4572f5 text/template: make reflect.Value indirections more robust
Always shadow or modify the original parameter name. With code like:

	func index(item reflect.Value, ... {
		v := indirectInterface(item)

It was possible to incorrectly use 'item' and 'v' later in the function,
which could result in subtle bugs. This is precisely the kind of mistake
that led to #36199.

Instead, don't keep both the old and new reflect.Value variables in
scope. Always shadow or modify the original variable.

While at it, simplify the signature of 'length', to receive a
reflect.Value directly and save a few redundant lines.

Change-Id: I01416636a9d49f81246d28b91aca6413b1ba1aa5
Reviewed-on: https://go-review.googlesource.com/c/go/+/212117
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Roberto Clapis <robclap8@gmail.com>
Reviewed-by: Rob Pike <r@golang.org>
2020-02-24 09:16:18 +00:00
Ariel Mashraki
8d7be1e3c9 text/template/parse: remove redundant return
Change the `itemChar` clause to be like all other clauses
that don't return a different state function than the default.

Change-Id: I56c863a7d699c1264b24b42ef23138ec47eaacd8
Reviewed-on: https://go-review.googlesource.com/c/go/+/216117
Reviewed-by: Rob Pike <r@golang.org>
Run-TryBot: Rob Pike <r@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
2020-01-23 23:07:10 +00:00
Daniel Martí
5481a97ab0 text/template: indirect interfaces before slicing
The recently added slice function used indirectInterface, but then
forgot to actually call reflect.Value.Slice on its result. Calling the
Slice method on the original Value without indirectInterface would
result in a panic, if our slice was indeed behind an interface.

Fix that, and add test cases for all three built-in functions that work
with slices.

Fixes #36199.

Change-Id: I9a18f4f604a3b29967eefeb573f8960000936b88
Reviewed-on: https://go-review.googlesource.com/c/go/+/211877
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
2019-12-19 13:52:09 +00:00
Oliver Powell
ba4593ac47 text/template: remove an incorrect comment and clarify docs for AddParseTree
The comment "If the name is the name of this template, overwrite this template."
is incorrect and should be "is not" instead. This comment is no longer
required once the docs are updated to mention this behaviour instead.

Fixes #34695

Change-Id: I773495b2194d7bb7619b13c1a28cbc76e8f69aac
Reviewed-on: https://go-review.googlesource.com/c/go/+/199139
Reviewed-by: Rob Pike <r@golang.org>
2019-12-17 11:10:58 +00:00
Roberto Clapis
94e9a5e19b text/template: harden JSEscape to also escape ampersand and equal
Ampersand and equal are not dangerous in a JS/JSString context
but they might cause issues if interpolated in HTML attributes.

This change makes it harder to introduce XSS by misusing
escaping.

Thanks to t1ddl3r <t1ddl3r@gmail.com> for reporting this common
misuse scenario.

Fixes #35665

Change-Id: Ice6416477bba4cb2ba2fe2cfdc20e027957255c0
Reviewed-on: https://go-review.googlesource.com/c/go/+/207637
Reviewed-by: Filippo Valsorda <filippo@golang.org>
Reviewed-by: Mike Samuel <mikesamuel@gmail.com>
Reviewed-by: Andrew Bonventre <andybons@golang.org>
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
2019-11-21 22:20:17 +00:00
Rob Pike
b8cb75fb17 text/template: add error check for parenthesized first argument in pipeline
An error check was missing: If the first argument of a pipeline is
parenthesized, and the pipeline has further arguments, then
syntactically the pipeline is a function invocation and there must
be a "call". Tricky rare corner case, but easily caught.

Add the error check and some tests to verify behavior.

Fixes #31810.

Change-Id: Ica80b7c11284e4ea9e8cc94a01dbbc9a67e42079
Reviewed-on: https://go-review.googlesource.com/c/go/+/206124
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2019-11-12 05:06:42 +00:00
Ariel Mashraki
debbb1e78d text/template/parse: speed up nodes printing
This CL is a follow up for 198080.
Added a private writeTo method to the Node interface,
in order to use the same builder for printing all nodes
in the tree. Benchmark output against master:

benchmark                     old ns/op     new ns/op     delta
BenchmarkParseLarge-8         24594994      25292054      +2.83%
BenchmarkVariableString-8     117           118           +0.85%
BenchmarkListString-8         10475         3353          -67.99%

benchmark                     old allocs     new allocs     delta
BenchmarkVariableString-8     3              3              +0.00%
BenchmarkListString-8         149            31             -79.19%

benchmark                     old bytes     new bytes     delta
BenchmarkVariableString-8     72            72            +0.00%
BenchmarkListString-8         5698          1608          -71.78%

Change-Id: I2b1cf07cda65c1b80083fb99671289423700feba
Reviewed-on: https://go-review.googlesource.com/c/go/+/198278
Reviewed-by: Rob Pike <r@golang.org>
Run-TryBot: Rob Pike <r@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
2019-10-03 00:16:28 +00:00
Ariel Mashraki
93a79bbcc0 text/template/parse: remove duplication in peekNonSpace
nextNonSpace has an identical code except the call to
backup at the end.

Change-Id: Iefa5b13950007da38323a800fb6b0ce3d436254b
Reviewed-on: https://go-review.googlesource.com/c/go/+/198277
Run-TryBot: Rob Pike <r@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
2019-10-01 20:30:37 +00:00
Ariel Mashraki
86cd6c2ee5 text/template/parse: use strings.Builder in Chain and List nodes
This CL is a continuation of 198078. Benchmark output:

benchmark                     old ns/op     new ns/op     delta
BenchmarkParseLarge-8         24759165      24516563      -0.98%
BenchmarkVariableString-8     115           115           +0.00%
BenchmarkListString-8         924           680           -26.41%

benchmark                     old allocs     new allocs     delta
BenchmarkVariableString-8     3              3              +0.00%
BenchmarkListString-8         14             13             -7.14%

benchmark                     old bytes     new bytes     delta
BenchmarkVariableString-8     72            72            +0.00%
BenchmarkListString-8         512           424           -17.19%

Change-Id: I9ec48fe4832437c556a5fa94d4cbf6e29e28d944
Reviewed-on: https://go-review.googlesource.com/c/go/+/198080
Reviewed-by: Emmanuel Odeke <emm.odeke@gmail.com>
Run-TryBot: Emmanuel Odeke <emm.odeke@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
2019-10-01 19:03:51 +00:00
Ariel Mashraki
4f13a9c5b1 text/template/parse: use strings.Builder in String methods
As mentioned in godoc, strings.Builder is more efficient for
concatenating and building strings.
Running a simple bench test on VariableNode.String() gives:

benchmark                     old ns/op     new ns/op     delta
BenchmarkParseLarge-8         25676831      24453285      -4.77%
BenchmarkVariableString-8     296           115           -61.15%

benchmark                     old allocs     new allocs     delta
BenchmarkVariableString-8     8              3              -62.50%

benchmark                     old bytes     new bytes     delta
BenchmarkVariableString-8     112           72            -35.71%

Change-Id: I13c9340080738fcad1edeed859d33ba608e4b05a
Reviewed-on: https://go-review.googlesource.com/c/go/+/198078
Reviewed-by: Emmanuel Odeke <emm.odeke@gmail.com>
Run-TryBot: Emmanuel Odeke <emm.odeke@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
2019-10-01 07:16:47 +00:00
Rob Pike
27cf81e1b4 text/template: further simplify building the vars list
Followup to https://golang.org/cl/197997

If you know the number of elements, you don't need append at all.
Either use append to grow, or allocate and index. Here we choose
number 2.

Change-Id: Ic58637231789640ff7b293ece04a95a8de7ccf8f
Reviewed-on: https://go-review.googlesource.com/c/go/+/198097
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2019-10-01 00:00:02 +00:00
Pantelis Sampaziotis
f91c850be6 text/template/parse: specify slice capacity in Pipenode.CopyPipe()
The required vars slice capacity is known so it can be specified before appending.

Change-Id: Ifa2fe97602e84198c4d01e5a1b0529f3f65f2df1
GitHub-Last-Rev: a0580df208
GitHub-Pull-Request: golang/go#34613
Reviewed-on: https://go-review.googlesource.com/c/go/+/197997
Reviewed-by: Andrew Bonventre <andybons@golang.org>
2019-09-30 21:48:20 +00:00
Daniel Martí
0f7b4e72a0 text/template: don't evaluate '.' as a float64
When using a '.' constant literal as a reflect.Value variadic argument,
idealConstant would incorrectly result in a float64. This is because
rune literals can be represented as a float64, and contain a period,
which tricked the logic into thinking the literal must have been a
floating point number.

This also happened with other characters that can be part of a floating
point number, such as 'e' or 'P'.

To fix these edge cases, exit the case sooner if the literal was a rune,
since that should always go to the int case instead.

Finally, add test cases that verify that they behave properly. These
would error before, since eq would receive a mix of int and float64,
which aren't comparable.

Fixes #34483.

Change-Id: Icfcb7803bfa0cf317a1d1adacacad3d69a57eb42
Reviewed-on: https://go-review.googlesource.com/c/go/+/196808
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Tom Payne <tom@airmap.com>
Reviewed-by: Rob Pike <r@golang.org>
2019-09-25 09:22:38 +00:00
Ariel Mashraki
95cbcc5c1c text/template: support all comparable types in eq
Extends the built-in eq function to support all Go
comparable types.

Fixes #33740

Change-Id: I522310e313e251c4dc6a013d33d7c2034fe2ec8e
Reviewed-on: https://go-review.googlesource.com/c/go/+/193837
Run-TryBot: Rob Pike <r@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
2019-09-25 09:13:11 +00:00
Mihai Borobocea
8a8cf5bf6d text/template: refer to sorted map keys as "ordered" not "comparable" in docs
Consistent with the spec's definition of "ordered" and "comparable".

Fixes #34147

Change-Id: Id13186df5343588d80eaebfeb23092596a846d51
Reviewed-on: https://go-review.googlesource.com/c/go/+/193840
Reviewed-by: Ian Lance Taylor <iant@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
2019-09-06 21:22:26 +00:00
tnclong
4a4f752c38 text/template: avoid allocating a new common in copy
Template.New calls t.init, which allocates several items that
are immediately rewritten by copy, so avoid the call to New

Change-Id: I16c7cb001bbcd14cf547c1a2db2734a2f8214e7e
Reviewed-on: https://go-review.googlesource.com/c/go/+/182757
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
2019-08-27 16:56:26 +00:00
Dong-hee Na
997086b7e6 text/template: replace bytes.Buffer with strings.Builder
After Go.1.10+ strings.Builder is known as more efficient in
concatenating and building strings than bytes.Buffer.

In this CL,
there is a minor logic fix for getting advantage of strings.builder.

name               old time/op    new time/op    delta
DefinedTemplate-8     543ns ± 3%     512ns ± 2%   -5.73%  (p=0.000 n=8+8)

name               old alloc/op   new alloc/op   delta
DefinedTemplate-8      192B ± 0%      160B ± 0%  -16.67%  (p=0.000 n=8+8)

name               old allocs/op  new allocs/op  delta
DefinedTemplate-8      5.00 ± 0%      5.00 ± 0%     ~     (all equal)

Change-Id: Icda0054d146e6c5e32ed8a4d13221bb6850d31b4
Reviewed-on: https://go-review.googlesource.com/c/go/+/175261
Run-TryBot: Emmanuel Odeke <emm.odeke@gmail.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Emmanuel Odeke <emm.odeke@gmail.com>
Reviewed-by: Brad Fitzpatrick <bradfitz@golang.org>
2019-08-27 16:54:06 +00:00
Robert Griesemer
b97ec8e57f text/scanner: remove AllowDigitSeparator flag again
The scanner was changed to accept the new Go number literal syntax
of which separators are a part. Making them opt-in is inconsistent
with the rest of the changes. For comparison, the strconv package
also accepts the new number literals including separators with the
various conversion routines, if no explicit number base is given.

Updates #28493.

Change-Id: Ifaae2225a9565364610813658bfe692901dd3ccd
Reviewed-on: https://go-review.googlesource.com/c/go/+/184080
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Russ Cox <rsc@golang.org>
2019-06-27 21:13:53 +00:00
Robert Griesemer
bc81f52e93 text/scanner: rename AllowNumberbars to AllowDigitSeparators
Fixes #32661.

Change-Id: I32dc4e7b276b95ac2e87a384caa6c48702368d05
Reviewed-on: https://go-review.googlesource.com/c/go/+/183077
Reviewed-by: Andrew Bonventre <andybons@golang.org>
2019-06-20 18:06:38 +00:00
Andrew Gerrand
263db9b680 html/template, text/template: document glob semantics
This change updates the doc comments of the various ParseGlob functions
and methods to state that they use the semantics of filepath.Match when
matching the file name pattern.

Fixes #30608

Change-Id: Iee4bdc0a2a2f8647d1f9a910e4d72a5de9204d11
Reviewed-on: https://go-review.googlesource.com/c/go/+/179739
Reviewed-by: Dmitri Shuralyov <dmitshur@golang.org>
2019-06-17 21:53:49 +00:00
Daniel Martí
eb2fabf2fa text/template: clarify the safety of Template.New
In particular, the returned template isn't independent from the parent.
For example, it can't be parsed concurrently with other children
templates. Only methods which are explicitly safe for concurrent use,
like Execute, may be used concurrently.

Fixes #30281.

Change-Id: Idc84bf4199c035316cdb83b950fd4a8f2a71cd0c
Reviewed-on: https://go-review.googlesource.com/c/go/+/172297
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Andrew Gerrand <adg@golang.org>
2019-06-07 13:56:20 +00:00
Ariel Mashraki
e2970a4591 text/template: add a slice function to the predefined global functions
The new slice function returns the result of slicing its first argument by
the following arguments. Thus {{slice x 1 3}} is, in Go syntax, x[1:3].
Each sliced item must be a string, slice, or array.

Closed #30153

RELNOTE=yes

Change-Id: I63188c422848cee3d383a64dc4d046e3a1767c63
Reviewed-on: https://go-review.googlesource.com/c/go/+/161762
Reviewed-by: Rob Pike <r@golang.org>
2019-05-23 08:01:24 +00:00
Russ Cox
06b0babf31 all: shorten some tests
Shorten some of the longest tests that run during all.bash.
Removes 7r 50u 21s from all.bash.

After this change, all.bash is under 5 minutes again on my laptop.

For #26473.

Change-Id: Ie0460aa935808d65460408feaed210fbaa1d5d79
Reviewed-on: https://go-review.googlesource.com/c/go/+/177559
Run-TryBot: Russ Cox <rsc@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2019-05-22 12:54:00 +00:00
Bjørn Erik Pedersen
45d74aad53 text/template: fix truth handling of typed interface nils in if and with
Before this commit, the two logically equivalent conditionals below would
produce different output:

    {{ if not .NonEmptyInterfaceTypedNil }}OK{{ else }}{{ end }}
    {{ if .NonEmptyInterfaceTypedNil }}{{ else }}OK{{ end }}

The functions `not`, `or`, and `and` all use the same `truth` function, which
unwraps any concrete interface value before passing it to `isTrue`.

`if` and `with` also use `isTrue` to establish truth, but was missing the
interface indirect call.

Fixes #30501

Change-Id: I9c49eed41e737d8f162e39bef1c3b82fd5518fed
GitHub-Last-Rev: 95fc2c82f2
GitHub-Pull-Request: golang/go#30534
Reviewed-on: https://go-review.googlesource.com/c/go/+/164958
Reviewed-by: Russ Cox <rsc@golang.org>
Run-TryBot: Russ Cox <rsc@golang.org>
2019-05-14 00:50:42 +00:00
Damien Neil
170b8b4b12 all: add Unwrap and Is methods to various error types
Add Unwrap methods to types which wrap an underlying error:

  "encodinc/csv".ParseError
  "encoding/json".MarshalerError
  "net/http".transportReadFromServerError
  "net".OpError
  "net".DNSConfigError
  "net/url".Error
  "os/exec".Error
  "signal/internal/pty".PtyError
  "text/template".ExecError

Add os.ErrTemporary. A case could be made for putting this error
value in package net, since no exported error types in package os
include a Temporary method. However, syscall errors returned from
the os package do include this method.

Add Is methods to error types with a Timeout or Temporary method,
making errors.Is(err, os.Err{Timeout,Temporary}) equivalent to
testing the corresponding method:

  "context".DeadlineExceeded
  "internal/poll".TimeoutError
  "net".adrinfoErrno
  "net".OpError
  "net".DNSError
  "net/http".httpError
  "net/http".tlsHandshakeTimeoutError
  "net/pipe".timeoutError
  "net/url".Error

Updates #30322
Updates #29934

Change-Id: I409fb20c072ea39116ebfb8c7534d493483870dc
Reviewed-on: https://go-review.googlesource.com/c/go/+/170037
Run-TryBot: Damien Neil <dneil@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Marcel van Lohuizen <mpvl@golang.org>
2019-05-04 16:14:12 +00:00
Daniel Martí
a27ede0ba9 all: remove a few unused parameters
I recently modified tabwriter to reduce the number of defers due to
flush calls. However, I forgot to notice that the new function
flushNoDefers can no longer return an error, due to the lack of the
defer.

In crypto/tls, hashForServerKeyExchange never returned a non-nil error,
so simplify the code.

Finally, in go/types and net we can find a few trivially unused
parameters, so remove them.

Change-Id: I54c8de83fbc944df432453b55c93008d7e810e61
Reviewed-on: https://go-review.googlesource.com/c/go/+/174131
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Benny Siegert <bsiegert@gmail.com>
2019-04-29 13:31:54 +00:00
Daniel Martí
e770b5b3aa text/template: allow using -}} with many spaces
lexSpace consumed all spaces, even if the last one was part of a right
delimiter like " -}}". Thus, "3  -}}" wouldn't lex as "3" and a right
delimiter, but as "3", "-", and "}}".

To fix that, make lexSpace stop if it encounters a right delimiter.

Fixes #30948.

Change-Id: I80a5546e5809e54f6823e2bf3a57a7e8808329be
Reviewed-on: https://go-review.googlesource.com/c/go/+/168457
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
2019-03-24 09:06:14 +00:00
Daniel Martí
c4078a1998 text/tabwriter: use a single defer per Write call
Lines with single cells prompt a flush. Unfortunately, a call to
Writer.Flush also means two defers, which is an expensive operation to
do if many lines consist of single cells.

This is common when formatting code with aligned comments. Most lines
aren't going to have any comments at all, so the performance hit is
going to be noticeable.

The Write method already has a "defer handlePanic" of its own, so we
don't need to worry about panics leaking out. The error will now mention
"Write" instead of "Flush" if a panic is encountered during that nested
flush, but arguably that's a good thing; the user called Write, not
Flush.

For the reset call, add a non-deferred call as part of flushNoDefers, as
that's still necessary. Otherwise, the exported Flush method still does
a "defer b.reset".

The current tabwriter benchmarks are unaffected, since they don't
contain many single-cell lines, and because lines are written one at a
time. For that reason, we add a benchmark which has both of these
characteristics.

name    old time/op    new time/op    delta
Code-8    2.72µs ± 0%    1.77µs ± 0%  -34.88%  (p=0.000 n=6+5)

name    old alloc/op   new alloc/op   delta
Code-8      648B ± 0%      648B ± 0%     ~     (all equal)

name    old allocs/op  new allocs/op  delta
Code-8      13.0 ± 0%      13.0 ± 0%     ~     (all equal)

Perhaps unsurprisingly, go/printer also gets a bit faster, as it too
buffers its output before writing it to tabwriter.

name     old time/op  new time/op  delta
Print-8  6.53ms ± 0%  6.39ms ± 0%  -2.22%  (p=0.008 n=5+5)

Change-Id: Ie01fea5ced43886a9eb796cb1e6c810f7a810853
Reviewed-on: https://go-review.googlesource.com/c/go/+/166797
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Robert Griesemer <gri@golang.org>
2019-03-12 22:34:30 +00:00
Daniel Martí
49662bc6b0 all: simplify multiple for loops
If a for loop has a simple condition and begins with a simple
"if x { break; }"; we can simply add "!x" to the loop's condition.

While at it, simplify a few assignments to use the common pattern
"x := staticDefault; if cond { x = otherValue(); }".

Finally, simplify a couple of var declarations.

Change-Id: I413982c6abd32905adc85a9a666cb3819139c19f
Reviewed-on: https://go-review.googlesource.com/c/go/+/165342
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2019-03-08 14:29:19 +00:00
Daniel Martí
15b4c71a91 text/template: error on method calls on nil interfaces
Trying to call a method on a nil interface is a panic in Go. For
example:

	var stringer fmt.Stringer
	println(stringer.String()) // nil pointer dereference

In https://golang.org/cl/143097 we started recovering panics encountered
during function and method calls. However, we didn't handle this case,
as text/template panics before evalCall is ever run.

In particular, reflect's MethodByName will panic if the receiver is of
interface kind and nil:

	panic: reflect: Method on nil interface value

Simply add a check for that edge case, and have Template.Execute return
a helpful error. Note that Execute shouldn't just error if the interface
contains a typed nil, since we're able to find a method to call in that
case.

Finally, add regression tests for both the nil and typed nil interface
cases.

Fixes #30143.

Change-Id: Iffb21b40e14ba5fea0fcdd179cd80d1f23cabbab
Reviewed-on: https://go-review.googlesource.com/c/161761
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Emmanuel Odeke <emm.odeke@gmail.com>
2019-02-26 18:05:09 +00:00
Daniel Martí
856525ce5c text/template: improve nil errors in evalField
If we're accessing a field on a nil struct pointer, and that field is
present in the type, we should print a "nil pointer evaluating X.Y" error
instead of the broader "can't evaluate field Y in X". The latter error
should still be used for the cases where the field is simply missing.

While at it, remove the isNil checks in the struct and map cases. The
indirect func will only return a true isNil when returning a pointer or
interface reflect.Value, so it's impossible for either of these checks
to be useful.

Finally, extend the test suite to test a handful of these edge cases,
including the one shown in the original issue.

Fixes #29137.

Change-Id: I53408ced8a7b53807a0a8461b6baef1cd01d25ae
Reviewed-on: https://go-review.googlesource.com/c/153341
Run-TryBot: Ian Lance Taylor <iant@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Rob Pike <r@golang.org>
2019-02-26 17:50:11 +00:00
Russ Cox
3cf56e78d8 text/template: accept new number syntax
This CL updates text/template's scanner to accept the
new number syntaxes:

 - Hexadecimal floating-point values.
 - Digit-separating underscores.
 - Leading 0b and 0o prefixes.

See golang.org/design/19308-number-literals for background.

For #12711.
For #19308.
For #28493.
For #29008.

Change-Id: I68c16ea35c3f506701063781388de72bafee6b8d
Reviewed-on: https://go-review.googlesource.com/c/160248
Reviewed-by: Rob Pike <r@golang.org>
Reviewed-by: Robert Griesemer <gri@golang.org>
2019-02-26 05:18:38 +00:00
Robert Griesemer
34fb5855eb text/scanner: don't liberally consume (invalid) floats or underbars
This is a follow-up on https://golang.org/cl/161199 which introduced
the new Go 2 number literals to text/scanner.

That change introduced a bug by allowing decimal and hexadecimal floats
to be consumed even if the scanner was not configured to accept floats.

This CL changes the code to not consume a radix dot '.' or exponent
unless the scanner is configured to accept floats.

This CL also introduces a new mode "AllowNumberbars" which controls
whether underbars '_' are permitted as digit separators in numbers
or not.

There is a possibility that we may need to refine text/scanner
further (e.g., the Float mode now includes hexadecimal floats
which it didn't recognize before). We're very early in the cycle,
so let's see how it goes.

RELNOTE=yes

Updates #12711.
Updates #19308.
Updates #28493.
Updates #29008.

Fixes #30320.

Change-Id: I6481d314f0384e09ef6803ffad38dc529b1e89a3
Reviewed-on: https://go-review.googlesource.com/c/163079
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2019-02-20 20:23:28 +00:00
Robert Griesemer
710417bc92 text/scanner: accept new Go2 number literals
This CL introduces text/scanner support for the new binary and octal integer
literals, hexadecimal floats, and digit separators for all number literals.
The new code is closely mirroring the respective code for number literals in
cmd/compile/internal/syntax/scanner.go.

Uniformly use the term "invalid" rather than "illegal" in error messages
to match the respective error messages in the other scanners directly.

R=Go1.13

Updates #12711.
Updates #19308.
Updates #28493.
Updates #29008.

Change-Id: I2f291de13ba5afc0e530cd8326e6bf4c3858ebac
Reviewed-on: https://go-review.googlesource.com/c/161199
Run-TryBot: Robert Griesemer <gri@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
2019-02-11 23:26:17 +00:00
Robert Griesemer
85c1798ac6 text/scanner: don't crash when calling TokenText in error handler
Make sure Scanner.tokEnd is set before we call Scanner.Error
and update documentation accordingly.
(Until now tokEnd was only set before returning from Scan,
so a call to TokenText during error handling may have crashed.)

While at it, tighten a check in Scanner.TokenText to ensure
Scanner.tokEnd >= Scanner.tokPos if we have a token.

Also, silence error messages to Stderr in unrelated TestIllegalExponent.

Fixes #29723.

Change-Id: Ia97beeae91eaf9e0ed3dada0a806f1f7122461cc
Reviewed-on: https://go-review.googlesource.com/c/157819
Reviewed-by: Josh Bleecher Snyder <josharian@gmail.com>
2019-02-11 23:25:32 +00:00
Daniel Martí
37afd3e311 text/template/parse: simplify Tree.pipeline
The pipeline parsing code was unnecessarily complex. It used a for loop
with a trailing break, a complex switch, and up to seven levels of
indentation.

Instead, drop the loop in favor of a single named goto with a comment,
and flatten out the complex switch to be easier to follow. Two lines of
code are now duplicated, but they're simple and only three lines apart.

While at it, move the pipe initialization further up to remove the need
for three variables.

Change-Id: I07b29de195f4000336219aadeadeacaaa4285c58
Reviewed-on: https://go-review.googlesource.com/c/145285
Reviewed-by: Rob Pike <r@golang.org>
Run-TryBot: Rob Pike <r@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
2018-10-29 12:20:11 +00:00
Daniel Martí
1399b52dc4 text/template/parse: error on bad range variables
The package used to accept invalid range pipelines, such as:

	{{range $k, .}}
	{{range $k, 123 := .}}

This is because the logic that allowed a range pipeline to declare
multiple variables was broken. When encountering a single comma inside a
range pipeline, it would happily continue parsing a second variable,
even if we didn't have a variable token at all.

Then, the loop would immediately break, and we'd parse the pipeline we'd
be ranging over. That is, we'd parse {{range $k, .}} as if it were
{{range $k = .}}.

To fix this, only allow the loop to continue if we know we're going to
parse another variable or a token that would end the pipeline. Also add
a few test cases for these error edge cases.

While at it, make use of T.Run, which was useful in debugging
Tree.pipeline via print statements.

Fixes #28437.

Change-Id: Idc9966bf643f0f3bc1b052620357e5b0aa2022ea
Reviewed-on: https://go-review.googlesource.com/c/145282
Run-TryBot: Daniel Martí <mvdan@mvdan.cc>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Reviewed-by: Rob Pike <r@golang.org>
2018-10-28 20:20:00 +00:00