Compare commits

...

758 Commits

Author SHA1 Message Date
Andrew Gerrand
394b383a1e [release-branch.r60] doc: document release.r60.3
««« CL 5267049 / eeca0d4a91a3
doc: document release.r60.3

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/5267049
»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/5296041
2011-10-18 10:55:12 +11:00
Russ Cox
b9e10a3217 [release-branch.r60] reflect: disallow Interface method on Value obtained via unexported name
exp/datafmt is incompatible with this change, so delete it.
It was scheduled for deletion soon anyway.

««« CL 5266054 / f798c2579fbd
reflect: disallow Interface method on Value obtained via unexported name

Had been allowing it for use by fmt, but it is too hard to lock down.
Fix other packages not to depend on it.

R=r, r
CC=golang-dev
https://golang.org/cl/5266054
»»»

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/5286051
2011-10-17 19:01:28 -04:00
Andrew Gerrand
6c4e7f4b68 [release-branch.r60] doc: document r60.2
««« CL 5204041 / 1fb56f387a76
doc: document r60.2

R=rsc, dsymonds
CC=golang-dev
https://golang.org/cl/5204041
»»»

R=bradfitz
CC=golang-dev
https://golang.org/cl/5204043
2011-10-05 14:23:39 -07:00
Andrew Gerrand
609de85973 [release-branch.r60] doc: link to A Tour of Go
««« CL 5181045 / bc48691295c8
doc: link to A Tour of Go

R=golang-dev, rsc, r
CC=golang-dev
https://golang.org/cl/5181045
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/5203041
2011-10-05 13:33:48 -07:00
Andrew Gerrand
60000444b8 [release-branch.r60] doc: update tutorial.
««« CL 5175052 / e144a6dec55e
doc: update tutorial.
Fix for new regexp library ($ isn't end of line any more).
Don't assume . is in PATH.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/5175052
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/5199042
2011-10-05 13:29:59 -07:00
Andrew Gerrand
31c829af98 [release-branch.r60] documentation: Debugging Go code with GDB tutorial.
««« CL 5168046 / 320d83ed794a
documentation: Debugging Go code with GDB tutorial.

R=adg, cw, lvd
CC=golang-dev
https://golang.org/cl/5168046

»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/5172053
2011-10-05 13:28:08 -07:00
Andrew Gerrand
efcce1bedd [release-branch.r60] doc: link to image/draw blog post.
««« CL 5154046 / 087a4bd61f20
doc: link to image/draw blog post.

R=adg
TBR=adg
CC=golang-dev
https://golang.org/cl/5154046
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/5202041
2011-10-05 13:25:52 -07:00
Andrew Gerrand
246c2fb736 [release-branch.r60] doc: link to image blog post
««« CL 5086048 / 09032e16d47c
doc: link to image blog post

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/5086048
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/5201041
2011-10-05 13:18:41 -07:00
Russ Cox
af68419ab2 [release-branch.r60] runtime: fix map memory leak
««« CL 5158045 / aaf8ddb0c780
runtime: fix map memory leak

The map implementation was using the C idiom of using
a pointer just past the end of its table as a limit pointer.
Unfortunately, the garbage collector sees that pointer as
pointing at the block adjacent to the map table, pinning
in memory a block that would otherwise be freed.

Fix by making limit pointer point at last valid entry, not
just past it.

Reviewed by Mike Burrows.

R=golang-dev, bradfitz, lvd, r
CC=golang-dev
https://golang.org/cl/5158045
»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/5169047
2011-10-03 13:34:24 -04:00
Andrew Gerrand
4af7136fcf [release-branch.r60] doc: update release.r60.1 notes
««« CL 5045045 / d101b482f64e
doc: update release.r60.1 notes

R=dsymonds
CC=golang-dev
https://golang.org/cl/5045045
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/5063041
2011-09-19 12:32:07 +10:00
Andrew Gerrand
88102c4d10 [release-branch.r60] json: add struct tag option to wrap literals in strings
««« CL 4918051 / ba6daf799367
json: add struct tag option to wrap literals in strings

Since JavaScript doesn't have [u]int64 types, some JSON APIs
encode such types as strings to avoid losing precision.

This adds a new struct tag option ",string" to cause
fields to be wrapped in JSON strings on encoding
and unwrapped from strings when decoding.

R=rsc, gustavo
CC=golang-dev
https://golang.org/cl/4918051
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/5049043
2011-09-19 11:59:19 +10:00
Andrew Gerrand
ab046b2afa [release-branch.r60] json: fix decode bug with struct tag names with ,opts being ignored
««« CL 4965049 / f8e4df3c4048
json: fix decode bug with struct tag names with ,opts being ignored

When the encoder was updated to respect the ",omitempty"
struct tag options, the decoder half was never updated to know
about the new struct tag format. (the format is now an optional
name, followed by zero or more ",option" strings)

This only affected people who used ",omitempty" along with
a field name. In that case, the serialized JSON wouldn't
decode to the original value.

R=golang-dev, dvyukov
CC=golang-dev
https://golang.org/cl/4965049
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/5029043
2011-09-19 11:54:29 +10:00
Andrew Gerrand
37a9064879 [release-branch.r60] doc: release.r60.1
««« CL 5002041 / d21944c38c39
doc: release.r60.1

R=r
CC=golang-dev
https://golang.org/cl/5002041
»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/5019044
2011-09-15 21:32:34 +10:00
Andrew Gerrand
070fc85831 [release-branch.r60] doc: link to notable blog posts
««« CL 4996041 / f6fdb6a54203
doc: link to notable blog posts

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4996041
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/4969081
2011-09-13 14:52:58 +10:00
Andrew Gerrand
8b8e079462 [release-branch.r60] misc/goplay: another template fix
««« CL 4950063 / 775543b0795c
misc/goplay: another template fix

Fixes #2219.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4950063
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/5000041
2011-09-13 14:45:37 +10:00
Andrew Gerrand
728eb92503 [release-branch.r60] misc/goplay: Fix template output
««« CL 4960052 / da491846e511
misc/goplay: Fix template output

Fixes #2219.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4960052
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/4960067
2011-09-13 14:43:18 +10:00
Andrew Gerrand
50026d415b [release-branch.r60] ld: grow dwarf includestack on demand.
««« CL 4988048 / c0abe3f34cec
ld: grow dwarf includestack on demand.

Fixes #2241
while not breaking issue 1878 again.

R=rsc
CC=golang-dev
https://golang.org/cl/4988048
»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4973075
2011-09-12 10:20:04 +10:00
Andrew Gerrand
5464bfebe7 [release-branch.r60] doc: release.r60
««« CL 4981047 / c0fea223bc90
doc: release.r60

R=dsymonds, r, rsc
CC=golang-dev
https://golang.org/cl/4981047
»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4961072
2011-09-08 12:16:42 +10:00
Andrew Gerrand
8b228654d0 [release-branch.r60] template: indirect or dereference function arguments if necessary to match the type of the formal.
««« CL 4967056 / a163a464ef59
template: indirect or dereference function arguments if necessary to match the type of the formal.
Fixes #2235

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4967056
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/4992043
2011-09-08 11:15:38 +10:00
Andrew Gerrand
2800956682 [release-branch.r60] template: fix deadlock.
««« CL 4963054 / c581abafc917
template: fix deadlock.
No need for lexInsideAction to loop.
Fixes #2217.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4963054
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/4974068
2011-09-08 11:12:11 +10:00
Andrew Gerrand
1adba86fdd [release-branch.r60] template: range over channel
««« CL 4951046 / 379452c085ab
template: range over channel

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4951046
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/4983052
2011-09-08 11:06:22 +10:00
Andrew Gerrand
dda8180c96 [release-branch.r60] template: Grammar fix for template documentation.
««« CL 4944043 / 6577cd4b870f
template: Grammar fix for template documentation.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4944043

»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/4978058
2011-09-08 11:02:39 +10:00
Andrew Gerrand
1fc3d23ca0 [release-branch.r60] exp/template: remove else and end nodes from public view.
««« CL 4905052 / 508513bbf607
exp/template: remove else and end nodes from public view.
They are used internally and do not appear in the final parse tree.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4905052
»»»

R=dsymonds
CC=golang-dev
https://golang.org/cl/4951069
2011-09-08 10:59:11 +10:00
Andrew Gerrand
b8f72d6110 [release-branch.r60] gc: fix pc/line table
««« CL 4938042 / 5671737303a0
gc: fix pc/line table

When a line directive was encountered we would push a new 'z' entry into
the history to indicate the start of new file attributation, and a 'Z'
entry to change line numbering.  However we didn't pop the 'z' entry, so
we were actually corrupting the history stack.  The most obvious
occurance of this was in the code that build the symbol tables for the
DWARF information - where an internal stack in the linker would overflow
when more than a few line directives were encountered in a single stack
(Issue 1878).  So now we pop the 'z' entry when we encounter the end of
the file that the directive was in, which maintains the history stack
integrity.

Also, although new 'z' entries for new files had relative paths
expanded, the same was not done for line directives.  Now we do it for
line directives also - so that the now correct DWARF information has the
full path available.

Fixes #1878.

R=rsc
CC=golang-dev
https://golang.org/cl/4938042

»»»

R=golang-dev
CC=golang-dev
https://golang.org/cl/4973069
2011-09-08 10:55:54 +10:00
Andrew Gerrand
616801951b [release-branch.r60] gofix: do not convert url in field names
««« CL 4972052 / 0f7a647510f9
gofix: do not convert url in field names

There's some ambiguity in the U{url: url} case as it could be
both a map or a struct literal, but given context it's more
likely a struct, so U{url: url_} rather than U{url_: url_}.
At least that was the case for me.

R=golang-dev, rsc, adg
CC=golang-dev
https://golang.org/cl/4972052
»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4962058
2011-09-08 10:52:28 +10:00
Andrew Gerrand
e84d4effa1 [release-branch.r60] gofix: forgot to rename the URL type
««« CL 4952041 / c51a2f3f897a
gofix: forgot to rename the URL type
Fixes #2182

R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4952041
»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4951068
2011-09-08 10:51:09 +10:00
Andrew Gerrand
d28f559503 [release-branch.r60] gofix: osopen: fixed=true when changing O_CREAT
««« CL 4921047 / 15cefddbe963
gofix: osopen: fixed=true when changing O_CREAT

R=rsc, r
CC=golang-dev
https://golang.org/cl/4921047

»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4961071
2011-09-08 10:49:40 +10:00
Andrew Gerrand
f7e76c75f1 [release-branch.r60] goinstall: select the tag that is closest to runtime.Version
««« CL 4873057 / db63f3a1f992
goinstall: select the tag that is closest to runtime.Version

release.r50 looks for newest tag <= go.r50
weekly.2010-10-10 looks for newest tag <= go.2010-10-10

Implements behavior for hg, git, and bzr.

R=dsymonds, rsc, n13m3y3r
CC=golang-dev
https://golang.org/cl/4873057
»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4974067
2011-09-08 10:48:19 +10:00
Andrew Gerrand
adc856a211 [release-branch.r60] goinstall: report lack of $GOPATH on errors
««« CL 4929047 / 7bfbbfb1ad42
goinstall: report lack of $GOPATH on errors

Fixes #2175.

R=alex.brainman, rsc, gustavo, adg
CC=golang-dev
https://golang.org/cl/4929047
»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4964068
2011-09-08 10:45:04 +10:00
Andrew Gerrand
6a571c5191 [release-branch.r60] goinstall: error out with paths that end with '/'
««« CL 4807048 / ae3b2b092cf7
goinstall: error out with paths that end with '/'

R=adg, rsc, tarmigan+golang
CC=golang-dev
https://golang.org/cl/4807048

»»»

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4968077
2011-09-08 10:43:40 +10:00
Andrew Gerrand
808bb141a6 create release-branch.r60 2011-09-08 10:39:39 +10:00
Andrew Gerrand
1491a20540 weekly.2011-08-17
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4914042
2011-08-18 14:27:08 +10:00
Rob Pike
10622421b5 gofix: walk names in ValueSpecs
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4887048
2011-08-18 13:48:44 +10:00
Rob Pike
3f5edd2461 test/chan/select5.go: change "with" to "if" in templatea
I converted this program yesterday and the output is the
same as it used to be, ignoring space, but the result is
not the best expression of the algorithm.  The old {.section
Maybe} pieces are now {{with .Maybe}}, as a direct translation,
but I they should be {{if .Maybe}} as the output is just a
bool and there is no cascading.

I have verified that the output of the program is unaffected.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4889053
2011-08-18 13:27:18 +10:00
Yasuhiro Matsumoto
d2a45dbf08 misc/vim: command complete using autoload helper function.
R=golang-dev, dsymonds, jnwhiteh, n13m3y3r, gustavo
CC=golang-dev
https://golang.org/cl/4837051
2011-08-18 11:50:55 +10:00
Rob Pike
8380ff34ed http: remove a TODO due to new behavior of nil maps
R=golang-dev, dsymonds, adg
CC=golang-dev
https://golang.org/cl/4907049
2011-08-18 11:01:43 +10:00
Mike Samuel
e4a89d7cca exp/template/html: defines a parse context for a subset of HTML.
This defines just enough context to distinguish HTML URI attributes
from parsed character data.

It does not affect any public module API as I thought I would get
early comment on style for defining enumerations and tables.

R=rsc, r, nigeltao, r
CC=golang-dev
https://golang.org/cl/4906043
2011-08-18 10:40:29 +10:00
Andrew Gerrand
b67b72da43 doc/codelab: use new template package
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4897048
2011-08-18 10:38:08 +10:00
Robert Griesemer
0f801ff81e godoc: template cleanup
Use naming convention for template variables
to indicate "escaped-ness" for easier reviewing.
(per suggestion from bradfitz)

R=bradfitz
CC=golang-dev
https://golang.org/cl/4914041
2011-08-17 16:38:58 -07:00
Russ Cox
75cb084283 test: new nil semantics
R=gri
CC=golang-dev
https://golang.org/cl/4644052
2011-08-17 15:55:06 -04:00
Russ Cox
3770b0e60c gc: implement nil chan support
The spec has defined nil chans this way for months.
I'm behind.

R=ken2
CC=golang-dev
https://golang.org/cl/4897050
2011-08-17 15:54:17 -04:00
Russ Cox
65bde087ae gc: implement nil map support
The spec has defined nil maps this way for months.
I'm behind.

R=ken2
CC=golang-dev
https://golang.org/cl/4901052
2011-08-17 14:56:27 -04:00
Russ Cox
cf79411b1d gc: fix mkbuiltin
Broken by Plan 9 changes.

R=ken2
CC=golang-dev
https://golang.org/cl/4896050
2011-08-17 14:54:51 -04:00
Robert Griesemer
42e6c03fc5 go/parser: disallow for statements w/ illegal range clauses
R=rsc
CC=golang-dev
https://golang.org/cl/4908047
2011-08-17 10:45:30 -07:00
Fazlul Shahriar
0f7bc92bdb net: Plan 9 support
All tests enabled by default passes except those in timeout_test.go.

For TestLookupPort, add an entry for "bootps" in /lib/ndb/common
(Plan 9 calls it "bootp"). I've sent out a patch to fix this.

R=paulzhol, rsc, mikioh.mikioh
CC=ality, golang-dev
https://golang.org/cl/4779041
2011-08-17 13:28:29 -04:00
Robert Griesemer
b77c40a2b3 go/parser: do not accept type literals where not permitted in general
- Resolves a long-standing TODO.
- Replacement for CL 4908042 by befelemepeseveze@gmail.com

Fixes #2155.

R=rsc
CC=golang-dev
https://golang.org/cl/4904048
2011-08-17 10:27:32 -07:00
Kyle Lemons
ca6e1dbc22 xml: escape string chardata in xml.Marshal
Fixes #2150.

R=golang-dev, nigeltao, rsc
CC=golang-dev
https://golang.org/cl/4890042
2011-08-17 12:12:08 -04:00
Dave Cheney
9f06ccb48d asn1: add support for unmarshalling structs with int32 members
Also improve error message for unsupported integer types

R=agl, rsc
CC=golang-dev
https://golang.org/cl/4873049
2011-08-17 12:12:01 -04:00
Marcel van Lohuizen
b40bd5efb7 exp/norm: implementation of decomposition and composing functionality.
forminfo.go:
- Wrappers for table data.
- Per Form dispatch table.
composition.go:
- reorderBuffer type.  Implements decomposition, reordering, and composition.
- Note: decompose and decomposeString fields in formInfo could be replaced by
  a pointer to the trie for the respective form.  The proposed design makes
  testing easier, though.
normalization.go:
- Temporarily added panic("not implemented") methods to make the tests run.
  These will be removed again with the next CL, which will introduce the
  implementation.

R=r, rogpeppe, mpvl, rsc
CC=golang-dev
https://golang.org/cl/4875043
2011-08-17 18:12:39 +10:00
Rob Pike
6b5962c274 test/chan/select5.go: update to new templates
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4911041
2011-08-17 16:51:04 +10:00
Mike Samuel
7dce257ac8 exp/template/html: rework Reverse(*Template) to do naive autoescaping
Replaces the toy func Reverse(*Template) with one that implements
naive autoescaping.

Now Escape(*Template) walks a template parse tree to find all
template actions and adds the |html command to them if it is not
already present.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4867049
2011-08-17 16:00:02 +10:00
Andrew Gerrand
2a189845b6 doc/codewalk: new Markov chain codewalk
R=gri, r, rsc
CC=golang-dev
https://golang.org/cl/4891041
2011-08-17 15:53:17 +10:00
Rob Pike
a22e77e6ae template: move exp/template into template.
(Leave exp/template/html where it is for now.)

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4899048
2011-08-17 14:55:57 +10:00
Rob Pike
73b7afbebd template: delete old template code.
It's already in old/template; make that build.
Update a couple of references to point to the old template.
They can be updated later.
Update goplay to use exp/template.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4902046
2011-08-17 14:34:48 +10:00
Rob Pike
ff0240da6d misc: fix a couple of template uses preparatory to the big switch.
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4876057
2011-08-17 13:57:06 +10:00
Rob Pike
1d8f822c17 url: new package
This is just moving the URL code from package http into its own package,
which has been planned for a while.
Besides clarity, this also breaks a nascent dependency cycle the new template
package was about to introduce.

Add a gofix module, url, and use it to generate changes outside http and url.

Sadness about the churn, gladness about some of the naming improvements.

R=dsymonds, bradfitz, rsc, gustavo, r
CC=golang-dev
https://golang.org/cl/4893043
2011-08-17 13:36:02 +10:00
Aleksandar Dezelin
d72c96df2a net: Added function SetTimeout() to interface Listener.
Fixes #2148.

R=golang-dev, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4905042
2011-08-16 18:36:51 -04:00
Robert Griesemer
182cf988e9 go/parser: use correct precedence when parsing range clauses
Fixes #2156.

R=rsc
CC=golang-dev
https://golang.org/cl/4899046
2011-08-16 15:19:23 -07:00
Russ Cox
9801c8e886 A+C: Aleksandar Dezelin (individual CLA)
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4901047
2011-08-16 18:15:36 -04:00
Joel Sing
5af6ce541f net: add multicast stubs for openbsd
Add multicast stubs and sync with recent changes.

R=golang-dev, mikioh.mikioh
CC=golang-dev
https://golang.org/cl/4838058
2011-08-16 17:28:16 -04:00
Joel Sing
1bc245181e net, syscall: move multicast address handling
Multicast address handling is not consistent across all BSDs. Move
the multicast address handling code into OS dependent files. This
will be needed for OpenBSD support.

R=mikioh.mikioh, golang-dev
CC=golang-dev
https://golang.org/cl/4809074
2011-08-16 17:26:51 -04:00
Mikio Hara
c20ced956e net: return correct local address for an accepted TCP connection
Fixes #2127.

R=rsc
CC=golang-dev
https://golang.org/cl/4873043
2011-08-16 16:53:09 -04:00
Dmitriy Vyukov
a2677cf363 runtime: fix GC bitmap corruption
The corruption can occur when GOMAXPROCS
is changed from >1 to 1, since GOMAXPROCS=1
does not imply there is only 1 goroutine running,
other goroutines can still be not parked after
the change.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4873050
2011-08-16 16:53:02 -04:00
Julian Phillips
01dd57b312 cgo: omit duplicate symbols in writeDefs
When the C API being used includes multiple names for the same
underlying symbol (e.g. multiple #define's for the same variable), then
cgo will generate the same placeholder variables for each name.  This
then prevents the code from compiling due to multiple declarations of
the same variable - so change cgo to only create one instance of the
variable for the underlying symbol.

R=rsc
CC=golang-dev
https://golang.org/cl/4826055
2011-08-16 14:56:23 -04:00
Lucio De Re
f12e543255 5l, 6l, 8l: add varargck for %Z
R=golang-dev
CC=golang-dev, rsc
https://golang.org/cl/4837044
2011-08-16 14:22:12 -04:00
Lucio De Re
c8c6e1961d 5c, 6c, 6l: fix Plan 9 build warnings
src/cmd/5c/reg.c:
. Added USED() attribute.

src/cmd/6c/cgen.c:
. Revised code around "REGARG" to resemble use in "8c" and
  consequently remove a warning.

src/cmd/6l/asm.c:
. Added USED() attributes.
. Removed an unnecessary assignment.

R=golang-dev
CC=golang-dev, rsc
https://golang.org/cl/4836045
2011-08-16 14:22:08 -04:00
Lucio De Re
93ecb5bb1b ld: make addaddrplus4 static
R=golang-dev
CC=golang-dev, rsc
https://golang.org/cl/4835043
2011-08-16 14:22:02 -04:00
Russ Cox
a5d7c1f45e errchk: allow multiple patterns
// ERROR "pattern1" "pattern2"

means that there has to be one or more
lines matching pattern1 and then excluding
those, there have to be one or more lines
matching pattern2.  So if you expect two
different error messages from a particular
line, writing two separate patterns checks
that both errors are produced.

Also, errchk now flags lines that produce
more errors than expected.  Before, as long as
at least one error matched the pattern, all the
others were ignored.

Revise tests to expect or silence these
additional errors.

R=lvd, r, iant
CC=golang-dev
https://golang.org/cl/4869044
2011-08-16 11:14:26 -04:00
Dmitriy Vyukov
53573c02b8 rpc: make Server.Mutex unexported
Currently it's possible to write:
var s rpc.Server
...
// reuse for my own purposes
s.Lock()
...
s.Unlock()
which is seemingly not intended.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4888049
2011-08-16 18:34:56 +10:00
Dmitriy Vyukov
381f6a2eeb syscall: make LazyDLL/LazyProc.Mutex unexported
They are seemingly not intended to be a part
of the public interface.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4873052
2011-08-16 18:33:48 +10:00
Rob Pike
00dd2b4ab9 builtin: correct description of a closed channel.
R=golang-dev, dvyukov
CC=golang-dev
https://golang.org/cl/4896046
2011-08-16 16:03:30 +10:00
Rob Pike
43d6389397 builtin: tweak a couple of descriptions.
R=golang-dev, adg, dsymonds
CC=golang-dev
https://golang.org/cl/4875050
2011-08-16 15:24:00 +10:00
Robert Griesemer
0310935058 godoc: show all top-level decls for (fake) package builtin
R=r, adg
CC=golang-dev
https://golang.org/cl/4904045
2011-08-15 19:05:52 -07:00
Robert Griesemer
e6ae13d35d godoc: fix lib/godoc/package.txt template
- show documentation in text mode; e.g.:
http://localhost:7777/cmd/godoc/?f=text

- simplify template by using $ variable

R=r, adg
CC=golang-dev
https://golang.org/cl/4873045
2011-08-15 15:42:27 -07:00
Robert Griesemer
91fadbca17 godoc: fix escaping in templates
- HTML-escape URL paths
- URL-escape URL parameters

R=bradfitz
CC=golang-dev
https://golang.org/cl/4890041
2011-08-15 15:15:54 -07:00
Sugu Sougoumarane
9f677f91d1 rpc: implement ServeRequest to synchronously serve a single request.
This is useful for applications that want to micromanage the rpc service.
Moved part of ServeCodec into a new readRequest function.
Renamed existing readRequest to readRequestHeader, and reordered
its parameters to align with the new readRequest and service.call.

R=golang-dev, r, rsc, sougou
CC=golang-dev, msolomon
https://golang.org/cl/4889043
2011-08-16 08:06:22 +10:00
Rob Pike
de1f856d66 builtin: add documentation for builtins
Do this by adding a fake package called builtin. At the moment, godoc will
not present this documentation because the function names are all lower case,
but there are plans to address this.
The print and println functions are undocumented here. I could be talked
into doing them but I'd rather not promote their use.

R=dsymonds, n13m3y3r, r, gri, rsc
CC=golang-dev
https://golang.org/cl/4907041
2011-08-16 07:51:44 +10:00
Gustavo Niemeyer
b0fc8a9d57 build: don't print anything on version.bash -save
R=rsc
CC=golang-dev
https://golang.org/cl/4904044
2011-08-15 14:25:54 -03:00
Gustavo Niemeyer
220c74984a build: support versioning without hg
CL 4873048 introduced the ability to build without hg and
getting an "unknown" version.  While this approach works
to avoid the hg dependency, it also means that every
exported tree that is built without hg or .hg will have not
only missing information, but will also be compatible to
one another.  Considering that it is a common practice to
remove the VCS data in distributions, I suggest we don't
take this approach to avoid its consequences.

This CL fixes the same problem in a different way: if a
VERSION file at the top of the tree exists, use it at
all times.  If it doesn't, fall back to using information
from hg necessarily, and fail if that's not possible.  The
error message when VERSION and hg are not available
instructs users to handle it properly.

The VERSION file can be generated with
"src/version.bash -save" while hg is still around.

R=golang-dev, rsc, gustavo
CC=golang-dev
https://golang.org/cl/4897043
2011-08-15 14:19:30 -03:00
Gustavo Niemeyer
a2bb0159d6 reflect: panic on Invalid Interface call
This was initially pushed as part of CL 4876046, found
when logic in exp/template was using the method on
an Invalid value.

R=rsc
CC=golang-dev
https://golang.org/cl/4890043
2011-08-15 14:14:15 -03:00
Andrew Gerrand
241a262fe5 build: don't require hg for build
R=golang-dev, dsymonds, n13m3y3r
CC=golang-dev
https://golang.org/cl/4873048
2011-08-15 21:19:07 +10:00
Gustavo Niemeyer
175849295c runtime: fix pseudo-randomness on some selects
Fixes #2152.

R=golang-dev, dvyukov
CC=golang-dev
https://golang.org/cl/4888044
2011-08-15 03:51:51 -03:00
Rob Pike
d7440ce21a old/template: copy code from template
First step of moving exp/template into template: save the old code.
Code is unedited except for target name in Makefile.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4893042
2011-08-15 15:16:57 +10:00
Gustavo Niemeyer
e3df71f50b exp/template: support field syntax on maps
While using exp/template in practice, the syntax for
indexing values using the "index" action was found to be
very inconvenient for frequent use when handling dynamic
data from maps such as the ones used with json and yaml,
that use a type like map[string]interface{}.

For these kinds of maps, the default handling of fields as
{{.Field}} makes the task of handling the several references
significantly more pleasant and elegant, and is equivalent
to what's currently done in the "template" package and in
other external packages (e.g. mustache).

Even with this change, the index action is still relevant
as it allows indexing maps in other scenarios where keys
wouldn't be valid field names.

R=golang-dev, r, gustavo
CC=golang-dev
https://golang.org/cl/4898043
2011-08-15 00:56:01 -03:00
Gustavo Niemeyer
e3f3a5411a exp/template: don't panic on range of nil interface
This avoids a non-obvious panic when range is used on a
nil interface, and fixes it by behaving as if the range
was empty.

The new behavior is equivalent to the outcome of iterating
on a nil map or slice, and is useful because it allows
generic structures such as used in json (map[string]interface{})
to behave correctly if a key generally set to a list or map
isn't present.

R=golang-dev, r, gustavo
CC=golang-dev
https://golang.org/cl/4876046
2011-08-15 00:22:28 -03:00
Robert Hencke
8a439334ad exp/norm: fix incorrect prints found by govet.
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4895042
2011-08-14 14:02:48 +10:00
Andrew Gerrand
6e66b16abe goinstall: report all newly-installed public packages
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4875048
2011-08-14 10:52:20 +10:00
Rob Pike
9bcec3bbce C: add Sugu Sougoumarane, Googler.
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4901041
2011-08-14 09:35:01 +10:00
Andrew Gerrand
df3df7b70a godoc: fix godoc.html template bug: correctly display package roots
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4898042
2011-08-14 08:56:47 +10:00
David Symonds
5e48e648f1 exp/template: rename filter: url -> urlquery.
R=r, rsc
CC=golang-dev
https://golang.org/cl/4873046
2011-08-13 14:00:16 +10:00
Robert Griesemer
c71b676724 godoc: position URLs (containing file names) must be quoted and URL escaped
Since the posLink_url also adds a non-URL attribute, the quoting and  URL-escaping
must happen inside posLink_url (otherwise the non-URL attribute becomes part or the
URL portion of the tag.

R=r
CC=golang-dev
https://golang.org/cl/4888041
2011-08-12 16:28:55 -07:00
Robert Griesemer
5c45e56898 godoc: remove last vestiges of old template system
- rename template funcs for better consistency and
  sort them into groups of related functionality
- try to be more consistent with html vs url escaping

R=r
CC=golang-dev
https://golang.org/cl/4887041
2011-08-12 15:43:10 -07:00
Robert Griesemer
5233c50321 godoc: first round of template cleanups
- simplified pipelines
- simplified templates by using template variables
- converted most old-style formatters into new-style funcs
- fixed some escaping bugs (use of url escaping where it was missing)

R=r, dsymonds
CC=golang-dev
https://golang.org/cl/4868044
2011-08-12 10:06:32 -07:00
Marcel van Lohuizen
4abbdc0399 exp/norm: generate trie struct in triegen.go for better encapsulation.
R=r, r
CC=golang-dev
https://golang.org/cl/4837071
2011-08-12 18:00:31 +02:00
Marcel van Lohuizen
58a92bd1ef exp/norm: generate trie struct in triegen.go for better encapsulation.
R=r, r
CC=golang-dev
https://golang.org/cl/4837071
2011-08-12 17:44:14 +02:00
Mikio Hara
8d19d6bb39 lib/godoc: fix typo
R=gri, dsymonds
CC=golang-dev
https://golang.org/cl/4881042
2011-08-12 22:42:42 +10:00
Joel Sing
8c46e47b61 crypto, exec, path, time: add support for OpenBSD
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4837048
2011-08-12 14:44:16 +10:00
Mike Samuel
595e9d5034 exp/template/html: New package with a toy template transformation.
func Reverse(*Template) *Template
returns a template that produces the reverse of the original
for any input.

Changes outside exp/template/html include:
- Adding a getter for a template's FuncMap so that derived templates
  can inherit function definitions.
- Exported one node factory function, newIdentifier.
  Deriving tempaltes requires constructing new nodes, but I didn't
  export all of them because I think shallow copy functions might
  be more useful for this kind of work.
- Bugfix: Template's Name() method ignores the name field so
  template.New("foo") is a nil dereference instead of "foo".

Caveats: Reverse is a toy.  It is not UTF-8 safe, and does not
preserve order of calls to funcs in FuncMap.

For context, see http://groups.google.com/group/golang-nuts/browse_thread/thread/e8bc7c771aae3f20/b1ac41dc6f609b6e?lnk=gst

R=rsc, r, nigeltao, r
CC=golang-dev
https://golang.org/cl/4808089
2011-08-12 14:34:29 +10:00
Rob Pike
1b13131c6b CLA: Add Mike Samuel, Googler.
R=golang-dev, dsymonds
CC=golang-dev, mikesamuel
https://golang.org/cl/4875042
2011-08-12 14:31:12 +10:00
David Symonds
fe59d86dd6 exp/template: fix implementation of printValue.
R=r
CC=golang-dev
https://golang.org/cl/4878042
2011-08-12 13:29:56 +10:00
Rob Pike
3cca9e0b00 utf8: rename some internal constants to remove leading underscores.
How quaint.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4874045
2011-08-12 11:50:46 +10:00
Rob Pike
b1d1da405a exp/template: add builtin len function
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4868045
2011-08-12 11:47:44 +10:00
Robert Griesemer
2e394c51d9 godoc: moving to new template package
- first step; rough conversion of all template files
- there is plenty of opportunity for cleanups/simplifications (next CLs)
- html and text output as before

R=r, dsymonds
CC=golang-dev
https://golang.org/cl/4852048
2011-08-11 13:24:13 -07:00
Nigel Tao
bca65e395e html: parse more malformed tags.
This continues the work in revision 914a659b44ff, now passing more test
cases. As before, the new tokenization tests match html5lib's behavior.

Fixes #2124.

R=dsymonds, r
CC=golang-dev
https://golang.org/cl/4867042
2011-08-11 18:49:09 +10:00
Rob Pike
6ca968c791 exp/template: find the String method by taking the address if we need to.
Also simplify nil handling in printing.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4869042
2011-08-11 14:36:51 +10:00
Gustavo Niemeyer
f3625e7087 exp/template: rename Parse*File and Parse*Files for clarity
IMPORTANT: Previous usage of *Files will continue to compile
fine but misbehave since the interface is compatible.

The following functions have been renamed:

    ParseFiles => ParseGlob
    ParseFile => ParseFiles
    ParseSetFiles => ParseSetGlob
    ParseSetFile => ParseSetFiles
    ParseTemplateFiles => ParseTemplateGlob
    ParseTemplateFile => ParseTemplateFiles

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4867041
2011-08-10 23:28:48 -05:00
Alex Brainman
c8ee9c60d2 runtime: better checks for syscall.NewCallback parameter
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4859042
2011-08-11 12:23:55 +10:00
Russ Cox
d118905c2c codereview: set status while committing CL
Not sure how to detect read-only but at least
this pins the blame on the hg server.

R=r, bradfitz
CC=golang-dev
https://golang.org/cl/4847053
2011-08-10 21:36:59 -04:00
Russ Cox
c02423902d build: allow builds without cgo
R=bradfitz, dsymonds, fshahriar
CC=golang-dev
https://golang.org/cl/4859043
2011-08-10 21:36:48 -04:00
Rob Pike
39fa2a5bf2 exp/template: truth for interface values.
Also protect against invalid (zero Value) reflect.Values.

R=rsc, gri
CC=golang-dev
https://golang.org/cl/4810094
2011-08-11 08:27:16 +10:00
Dave Grijalva
8f3c7497ac http: corrects undocumented side effects in http.DefaultTransport's RoundTrip method
Fixes #2140.

The http.DefaultTransport's RoundTrip method leaves the http.Request object
in an altered state after performing the round trip.  This patch removes
the header from the Request before returning to the client.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4857041
2011-08-10 14:16:13 -07:00
Brad Fitzpatrick
ebb2f4af35 A+C: Dave Grijalva (ngmoco CLA)
R=rsc
CC=golang-dev
https://golang.org/cl/4855051
2011-08-10 14:05:52 -07:00
Brad Fitzpatrick
31fa584906 http: fix ParseMultipartForm after MultipartReader error
Addresses part of issue 2093
Thanks to espians....@

R=golang-dev, nigeltao
CC=golang-dev
https://golang.org/cl/4808087
2011-08-10 08:08:53 -07:00
Marcel van Lohuizen
849b54a2f9 exp/norm: added trie lookup code and associated tests.
- triegen.go: Factored out trie generation code from maketables.go
  (only renamed printTrieTables to printTables and made it a method).
- maketesttables.go: new tool to generate data for the trie unit test.
- Makefile: changed accordingly.
- trie.go: trie lookup code.
- trietest_data.go: generated by maketesttables.go.
- trie_test.go: unit test for trie.go.

R=r
CC=golang-dev
https://golang.org/cl/4844053
2011-08-10 15:36:27 +02:00
Marcel van Lohuizen
00cb627b87 exp/norm: added trie lookup code and associated tests.
- triegen.go: Factored out trie generation code from maketables.go
  (only renamed printTrieTables to printTables and made it a method).
- maketesttables.go: new tool to generate data for the trie unit test.
- Makefile: changed accordingly.
- trie.go: trie lookup code.
- trietest_data.go: generated by maketesttables.go.
- trie_test.go: unit test for trie.go.

R=r
CC=golang-dev
https://golang.org/cl/4844053
2011-08-10 15:34:12 +02:00
Russ Cox
83c734601c json: fix []unmarshaler case
Now that reflect has v.Addr(), we can use it.

R=golang-dev, dsymonds, r
CC=golang-dev
https://golang.org/cl/4860041
2011-08-10 09:26:51 -04:00
Rob Pike
c9cf04a9f6 time: allow the input to have fractional seconds even if
the format string does not specify its presence.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4839059
2011-08-10 23:24:45 +10:00
Alex Brainman
9c774c3f26 runtime: correct seh installation during callbacks
Every time we enter callback from Windows, it is
possible that go exception handler is not at the top
of per-thread exception handlers chain. So it needs
to be installed again. At this moment this is done
by replacing top SEH frame with SEH frame as at time
of syscall for the time of callback. This is incorrect,
because, if exception strike, we won't be able to call
any exception handlers installed inside syscall,
because they are not in the chain. This changes
procedure to add new SEH frame on top of existing
chain instead.

I also removed m sehframe field, because I don't
think it is needed. We use single global exception
handler everywhere.

R=golang-dev, r
CC=golang-dev, hectorchu
https://golang.org/cl/4832060
2011-08-10 17:17:28 +10:00
Nigel Tao
8fced60a72 tag weekly.2011-08-10
R=r
CC=golang-dev
https://golang.org/cl/4808088
2011-08-10 16:05:31 +10:00
Nigel Tao
da7e1ba00b weekly.2011-08-10
R=r
CC=golang-dev
https://golang.org/cl/4830069
2011-08-10 16:00:22 +10:00
Rob Pike
ae03a192e0 timing.log: significant improvements after custom algorithms
See https://golang.org/cl/4815087

R=golang-dev, nigeltao
CC=golang-dev
https://golang.org/cl/4849050
2011-08-10 15:45:37 +10:00
Nigel Tao
37afff2978 html: parse malformed tags missing a '>', such as <p id=0</p>.
The additional token_test.go cases matches html5lib behavior.

Fixes #2124.

R=gri
CC=golang-dev
https://golang.org/cl/4844055
2011-08-10 13:39:07 +10:00
Wei Guangjing
1ac7a69701 ld: add one empty symbol into pe to make dumpbin works.
Fixes #2139.

R=golang-dev, alex.brainman
CC=golang-dev
https://golang.org/cl/4838056
2011-08-10 11:09:06 +10:00
Brad Fitzpatrick
d24a9785eb http: configurable and default request header size limit
This addresses the biggest DoS in issue 2093

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4841050
2011-08-09 10:55:14 -07:00
Yasuhiro Matsumoto
29df7bb7ec http: add test to serve content in index.html
R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4798071
2011-08-09 10:25:53 -07:00
Rob Pike
1adda4601a exp/template: do not take address of interface variable to find methods.
Also allow struct values as "with" targets.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4809086
2011-08-09 17:07:29 +10:00
Rob Pike
7506ee7584 exp/template: remove reflect from the API
It means keeping two sets of maps, but things look cleaner from
the outside.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4839056
2011-08-09 16:49:36 +10:00
Rob Pike
c66917d2b6 exp/template: split the parse tree into a separate package exp/template/parse
Mostly a mechanical change, with a few cleanups to make the split easier.
The external interface to exp/template is unaffected.

In another round I will play with the function map setup to see if I can
avoid exposing reflect across the boundary, but that will require some
structural changes I did not want to mix into this CL.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4849049
2011-08-09 15:42:53 +10:00
Kyle Consalus
476150f4bf crypto/x509, go/scanner, index/suffixarray: Removed []interface{}/vector uses.
Changed some []interface{} uses to slices of the concrete types; removed use of IntVector.

R=gri, rsc
CC=golang-dev
https://golang.org/cl/4810085
2011-08-08 14:32:37 -07:00
Robert Griesemer
5987a4ad29 scanner: correct error position for illegal UTF-8 encodings
- added corresponding test cases
- re-grouped tests for better readability

Fixes #2138.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4815091
2011-08-08 13:54:32 -07:00
John Asmuth
ffc0830c75 container/vector: removed last instances of vector outside of container/vector itself from the core libs
R=gri
CC=golang-dev
https://golang.org/cl/4810078
2011-08-08 11:27:09 -07:00
Joel Sing
68fea34be3 syscall: move bsd mmap syscall
The mmap system call varies across BSDs. Move mmap and munmap into
the operating system dependent files. This will be needed to add
syscall support for OpenBSD.

R=rsc
CC=golang-dev
https://golang.org/cl/4822056
2011-08-08 09:56:45 -04:00
Joel Sing
f6fab25582 net: add support for openbsd
R=rsc
CC=golang-dev
https://golang.org/cl/4816060
2011-08-08 09:56:42 -04:00
Joel Sing
21ac258e07 runtime: openbsd amd64 runtime support
Add support for the go runtime on openbsd/amd64. This is based on
the existing freebsd runtime.

Threads are implemented using OpenBSD's rthreads, which are currently
disabled by default, however can be enabled via the kern.rthreads
sysctl.

For now, cgo is disabled.

R=rsc
CC=golang-dev
https://golang.org/cl/4815067
2011-08-08 09:56:38 -04:00
Joel Sing
604b91a43e os: add support for openbsd
R=rsc
CC=golang-dev
https://golang.org/cl/4798061
2011-08-08 09:56:36 -04:00
Rob Pike
9c2ebab826 exp/template: document that comments may span newlines.
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4855045
2011-08-08 23:42:49 +10:00
Dmitriy Vyukov
54e9406ffb runtime: add more specialized type algorithms
The change adds specialized type algorithms
for slices and types of size 8/16/32/64/128.
It significantly accelerates chan and map operations
for most builtin types as well as user structs.

benchmark                   old,ns/op   new,ns/op
BenchmarkChanUncontended          226          94
(on Intel Xeon E5620, 2.4GHz, Linux 64 bit)

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4815087
2011-08-08 09:35:32 -04:00
David Symonds
a09ba8b638 exp/template: url filter.
R=r
CC=golang-dev
https://golang.org/cl/4837063
2011-08-08 16:29:57 +10:00
David Symonds
ec010fddb5 exp/template: fix Must example.
R=r
CC=golang-dev
https://golang.org/cl/4839052
2011-08-08 15:38:37 +10:00
Rob Pike
3c10403784 time: parse and format fractional seconds
R=golang-dev, rogpeppe, r, dsymonds, bradfitz, fvbommel
CC=golang-dev
https://golang.org/cl/4830065
2011-08-08 07:50:17 +10:00
Robert Griesemer
4c268b335f gofmt: update test script so 'make test' succeeds
R=r, rsc
CC=golang-dev
https://golang.org/cl/4832055
2011-08-06 12:30:54 -07:00
Rob Pike
7d87f3d233 FAQ: variant types, unions
Fixes #1935.

R=rsc, bradfitz
CC=golang-dev
https://golang.org/cl/4850044
2011-08-06 11:21:59 +10:00
Rob Pike
93c4a246a4 FAQ: lots of small tweaks plus a couple of new discussions.
Expand the conversations about pointers, memory, and
garbage collection.
Describe the lack of co/contravariant typing.

Fixes #1929.
Fixes #1930.

R=dsymonds, r, mirtchovski, edsrzf, hanwen, rsc
CC=golang-dev
https://golang.org/cl/4852041
2011-08-06 07:41:55 +10:00
Alex Brainman
be269b2f6d time: fix windows build
R=golang-dev, mattn.jp, dsymonds
CC=golang-dev
https://golang.org/cl/4849042
2011-08-05 17:19:17 +10:00
Rob Pike
88233e89db asn1: fix build
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4830061
2011-08-05 15:10:06 +10:00
Rob Pike
bfaa175e09 time: add nanoseconds to the Time structure.
R=golang-dev, dsymonds, bradfitz, kevlar, rsc, r
CC=golang-dev
https://golang.org/cl/4851041
2011-08-05 13:44:02 +10:00
Alex Brainman
5da14d1697 net: implement windows LookupMX and LookupAddr
Also sort SRV records before returning from LookupSRV.

R=rsc
CC=golang-dev
https://golang.org/cl/4817049
2011-08-05 10:27:51 +10:00
Mikio Hara
ba9833269d net: fix /proc/net/igmp,igmp6 reading bug on linux
Fixes #2130.

R=rsc, dave
CC=golang-dev
https://golang.org/cl/4846044
2011-08-05 09:20:13 +10:00
Rob Pike
5b1f159fb5 exp/norm: fix build by adding a test placeholder
R=golang-dev, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4838050
2011-08-05 08:25:49 +10:00
Marcel van Lohuizen
b35d49fca1 exp/norm: maketables tool for generating tables for normalization.
R=r, bsiegert, r, alex.brainman
CC=golang-dev
https://golang.org/cl/4662080
2011-08-04 23:15:19 +02:00
Dmitriy Vyukov
d770aadee5 runtime: faster chan creation on Linux/FreeBSD/Plan9
The change removes chan finalizer (Lock destructor)
if it is not required on the platform.

benchmark                    old ns/op    new ns/op    delta
BenchmarkChanCreation          1132.00       381.00  -66.34%
BenchmarkChanCreation-2        1215.00       243.00  -80.00%
BenchmarkChanCreation-4        1084.00       186.00  -82.84%
BenchmarkChanCreation-8        1415.00       154.00  -89.12%
BenchmarkChanCreation-16       1386.00       144.00  -89.61%
(on 2 x Intel Xeon E5620, 8 HT cores, 2.4 GHz, Linux)

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4841041
2011-08-04 08:31:03 -04:00
Yasuhiro Matsumoto
62d4b8ebd2 http: correct path to serve index.html.
calling filepath.FromSlash(x) make invalid character to serve file.
Fixes #2128

R=golang-dev, alex.brainman, rsc
CC=golang-dev
https://golang.org/cl/4810064
2011-08-04 08:20:53 -04:00
David Symonds
4143491c4a http: add more MPEG-4 MIME types to sniffer, and disable MP4 sniffing.
R=rsc
CC=golang-dev
https://golang.org/cl/4808056
2011-08-04 22:10:17 +10:00
Rob Pike
583f72434f fmt: call UpdateMemStats in malloc counter
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4830059
2011-08-04 16:32:14 +10:00
David Symonds
bb8e36b4a1 gob: avoid a couple of init-time allocations.
R=r
CC=golang-dev
https://golang.org/cl/4806049
2011-08-04 16:22:22 +10:00
Rob Pike
19e80b0818 gob: add UpdateMemStats calls to malloc counter
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4808071
2011-08-04 15:56:25 +10:00
Rob Pike
ee9168d507 gob: don't invoke GobEncoder on zero values.
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4801076
2011-08-04 14:39:44 +10:00
Mikio Hara
946cb0ece1 net: joined group addresses for a specific interface for darwin, freebsd, linux
This CL enables to list the multicast, joined group addresses
for a specific interface by using Interface.MulticastAddrs
method.

R=rsc
CC=golang-dev
https://golang.org/cl/4808062
2011-08-04 00:22:52 -04:00
Mikio Hara
dc7f82559d syscall: update routing message support for BSD variants
R=rsc
CC=golang-dev
https://golang.org/cl/4826056
2011-08-04 00:22:48 -04:00
Hector Chu
6500065543 runtime: remove unnecessary locking
R=rsc, dvyukov
CC=golang-dev
https://golang.org/cl/4819051
2011-08-04 00:22:39 -04:00
Rob Pike
6fe82e6b96 test/bench: note changes after recent improvements to locking and runtime
Some tests are significantly faster (50%), a few are slower (up to 30%).
Fannkuch is confusing: parallel code is a little slower for gc, non-parallel and all gccgo runs are faster.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4830058
2011-08-04 11:29:20 +10:00
Dmitriy Vyukov
a496c9eaa6 runtime: correct Note documentation
Reflect the fact that notesleep() can be called
by exactly one thread.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4816064
2011-08-03 15:51:55 -04:00
Yasuhiro Matsumoto
b32e210586 misc/vim: Godoc command.
vim command 'Godoc' to see godoc.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4815071
2011-08-03 16:46:35 +10:00
Russ Cox
16cdba8572 errchk: add -0 flag
R=lvd
CC=golang-dev
https://golang.org/cl/4837049
2011-08-02 15:19:44 -04:00
David Symonds
11e254e62c ld: fail linking if the top-level package is not main.
This makes {5,6,8}l conform to the spec more tightly.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4826063
2011-08-02 07:45:04 -04:00
Rob Pike
3dbe10c453 exp/template: return nil value from helpers on error, even methods.
R=rsc
CC=golang-dev
https://golang.org/cl/4835046
2011-08-01 20:02:52 -07:00
Andrew Gerrand
b0ef0294d2 go/build: use GOBIN as binary path for GOROOT
Fixes #2106.

R=golang-dev, dsymonds, rsc
CC=golang-dev
https://golang.org/cl/4836047
2011-08-01 19:17:23 -07:00
Andrew Gerrand
034711ed76 tag release.r59
R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4841044
2011-08-01 14:20:02 -07:00
Roger Peppe
6ed27d4770 exp/template: make index function on maps return zero value when key not present.
R=r
CC=golang-dev
https://golang.org/cl/4808065
2011-08-01 09:03:35 -07:00
Roger Peppe
5c5ce6d24d exp/template: ensure that a valid Set is returned even on error.
R=r
CC=golang-dev
https://golang.org/cl/4838044
2011-08-01 09:02:06 -07:00
Dave Cheney
317911c9ff 5g: fix set but not used error
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4816061
2011-07-31 19:54:47 -07:00
Alex Brainman
8800f7cb55 http: correct format flags when printing errors during tests
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4809065
2011-08-01 11:50:50 +10:00
Lucio De Re
05f734c8b4 cmd/ld/pe.c: Corrected mismatched print formats and variables.
R=golang-dev, alex.brainman
CC=golang-dev, rsc
https://golang.org/cl/4839041
2011-08-01 11:12:50 +10:00
Nigel Tao
1d0c141d7d html: parse doctype tokens; merge adjacent text nodes.
The test case input is "<!DOCTYPE html><span><button>foo</span>bar".
The correct parse is:
| <!DOCTYPE html>
| <html>
|   <head>
|   <body>
|     <span>
|       <button>
|         "foobar"

R=gri
CC=golang-dev
https://golang.org/cl/4794063
2011-08-01 10:26:46 +10:00
Andrew Gerrand
4d2766e994 doc: document release.r59
R=golang-dev, dsymonds, r, r
CC=golang-dev
https://golang.org/cl/4835044
2011-07-31 15:29:10 -07:00
Andrew Gerrand
70f6133b84 doc: fix typo in Effective Go
Fixes #2120.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4810061
2011-07-31 15:25:26 -07:00
Alex Brainman
9d7e39340d syscall: delay load of dll functions until they are called
Before this change, syscall package would load
all dlls used anywhere in the go tree on startup.
For example, this program:

package main

import "fmt"

func main() {
       fmt.Printf("Hello world\n")
}

would load these dlls

kernel32.dll
advapi32.dll
shell32.dll
wsock32.dll
ws2_32.dll
dnsapi.dll
iphlpapi.dll

Most of these dlls are network related and are not used
in this program. Now the same program loads only

kernel32.dll
shell32.dll

This decreases start times somewhat.

This also relaxes the rules of which dlls can be included
in the standard library. We could now include system calls
that are not available on all versions of Windows, because
we could decide if we should call them during runtime.

R=rsc, vcc.163
CC=golang-dev
https://golang.org/cl/4815046
2011-07-31 20:07:04 +10:00
David Symonds
be96fa5a2e go_faq: drop a dramatic comma.
R=r
CC=golang-dev
https://golang.org/cl/4809064
2011-07-31 12:59:58 +10:00
Andrew Gerrand
ffccc026cb exp/norm: correct package doc comment
Fixes #2118.

R=golang-dev, r, iant
CC=golang-dev
https://golang.org/cl/4815073
2011-07-30 18:02:09 -07:00
Robert Griesemer
7162f39fc3 exp/template: fix endless loop
No progress was made in indirect() if the reflect.Value
was an non-nil and non-empty interface.

R=r, r
CC=golang-dev
https://golang.org/cl/4810060
2011-07-30 17:11:52 -07:00
Andrew Gerrand
bf184398f6 tag weekly.2011-07-29
R=rsc
CC=golang-dev
https://golang.org/cl/4833047
2011-07-29 15:21:24 -07:00
Andrew Gerrand
b583108436 weekly.2011-07-29
R=rsc
CC=golang-dev
https://golang.org/cl/4801062
2011-07-29 15:11:48 -07:00
Hector Chu
9bc58accce runtime: fix scheduling race
Affects programs using cgo or runtime.LockOSThread.

Fixes #2100.

R=rsc, dvyukov
CC=golang-dev
https://golang.org/cl/4810059
2011-07-29 17:39:02 -04:00
Kyle Lemons
31442a6737 xml: Header: fix close tag and newline
R=rsc
CC=golang-dev
https://golang.org/cl/4830043
2011-07-29 14:09:07 -04:00
Joel Sing
2d7ddfa64d libmach: stubs for openbsd
Add libmach stubs for openbsd.

R=rsc
CC=golang-dev
https://golang.org/cl/4815065
2011-07-29 13:48:00 -04:00
Russ Cox
124172e2cf godoc: allow form feed in text files
Now recognizes misc/emacs/go-mode-load.el as text.

Fixes #2115.

R=gri
CC=golang-dev
https://golang.org/cl/4801061
2011-07-29 13:47:54 -04:00
Joel Sing
ffa14e849c 6l: OpenBSD support
Add linker support for OpenBSD ELF-64.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4815066
2011-07-29 13:47:41 -04:00
Dmitriy Vyukov
91f0f18100 runtime: fix data race in findfunc()
The data race can lead to reads of partially
initialized concurrently mutated symbol data.
The change also adds a simple sanity test
for Caller() and FuncForPC().

R=rsc
CC=golang-dev
https://golang.org/cl/4817058
2011-07-29 13:47:24 -04:00
Joel Sing
eb2b3f5dc7 syscall: move bsd pipe syscall
Not all BSDs have the same pipe() syscall implementation - move the Darwin/FreeBSD specific implementation into their respective OS syscall files. This will be needed to add OpenBSD syscall support.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4823057
2011-07-29 13:47:20 -04:00
Andrew Gerrand
e0b6f4721f archive/zip: more efficient reader and bug fix
Fixes #2090.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4815068
2011-07-29 10:47:00 -07:00
Russ Cox
60dac9b3db CONTRIBUTORS: add Joel Sing (Google CLA)
R=golang-dev, r
CC=golang-dev, jsing
https://golang.org/cl/4830044
2011-07-29 13:31:42 -04:00
Dmitriy Vyukov
4e5086b993 runtime: improve Linux mutex
The implementation is hybrid active/passive spin/blocking mutex.
The design minimizes amount of context switches and futex calls.
The idea is that all critical sections in runtime are intentially
small, so pure blocking mutex behaves badly causing
a lot of context switches, thread parking/unparking and kernel calls.
Note that some synthetic benchmarks become somewhat slower,
that's due to increased contention on other data structures,
it should not affect programs that do any real work.

On 2 x Intel E5620, 8 HT cores, 2.4GHz
benchmark                     old ns/op    new ns/op    delta
BenchmarkSelectContended         521.00       503.00   -3.45%
BenchmarkSelectContended-2       661.00       320.00  -51.59%
BenchmarkSelectContended-4      1139.00       629.00  -44.78%
BenchmarkSelectContended-8      2870.00       878.00  -69.41%
BenchmarkSelectContended-16     5276.00       818.00  -84.50%
BenchmarkChanContended           112.00       103.00   -8.04%
BenchmarkChanContended-2         631.00       174.00  -72.42%
BenchmarkChanContended-4         682.00       272.00  -60.12%
BenchmarkChanContended-8        1601.00       520.00  -67.52%
BenchmarkChanContended-16       3100.00       372.00  -88.00%
BenchmarkChanSync                253.00       239.00   -5.53%
BenchmarkChanSync-2             5030.00      4648.00   -7.59%
BenchmarkChanSync-4             4826.00      4694.00   -2.74%
BenchmarkChanSync-8             4778.00      4713.00   -1.36%
BenchmarkChanSync-16            5289.00      4710.00  -10.95%
BenchmarkChanProdCons0           273.00       254.00   -6.96%
BenchmarkChanProdCons0-2         599.00       400.00  -33.22%
BenchmarkChanProdCons0-4        1168.00       659.00  -43.58%
BenchmarkChanProdCons0-8        2831.00      1057.00  -62.66%
BenchmarkChanProdCons0-16       4197.00      1037.00  -75.29%
BenchmarkChanProdCons10          150.00       140.00   -6.67%
BenchmarkChanProdCons10-2        607.00       268.00  -55.85%
BenchmarkChanProdCons10-4       1137.00       404.00  -64.47%
BenchmarkChanProdCons10-8       2115.00       828.00  -60.85%
BenchmarkChanProdCons10-16      4283.00       855.00  -80.04%
BenchmarkChanProdCons100         117.00       110.00   -5.98%
BenchmarkChanProdCons100-2       558.00       218.00  -60.93%
BenchmarkChanProdCons100-4       722.00       287.00  -60.25%
BenchmarkChanProdCons100-8      1840.00       431.00  -76.58%
BenchmarkChanProdCons100-16     3394.00       448.00  -86.80%
BenchmarkChanProdConsWork0      2014.00      1996.00   -0.89%
BenchmarkChanProdConsWork0-2    1207.00      1127.00   -6.63%
BenchmarkChanProdConsWork0-4    1913.00       611.00  -68.06%
BenchmarkChanProdConsWork0-8    3016.00       949.00  -68.53%
BenchmarkChanProdConsWork0-16   4320.00      1154.00  -73.29%
BenchmarkChanProdConsWork10     1906.00      1897.00   -0.47%
BenchmarkChanProdConsWork10-2   1123.00      1033.00   -8.01%
BenchmarkChanProdConsWork10-4   1076.00       571.00  -46.93%
BenchmarkChanProdConsWork10-8   2748.00      1096.00  -60.12%
BenchmarkChanProdConsWork10-16  4600.00      1105.00  -75.98%
BenchmarkChanProdConsWork100    1884.00      1852.00   -1.70%
BenchmarkChanProdConsWork100-2  1235.00      1146.00   -7.21%
BenchmarkChanProdConsWork100-4  1217.00       619.00  -49.14%
BenchmarkChanProdConsWork100-8  1534.00       509.00  -66.82%
BenchmarkChanProdConsWork100-16 4126.00       918.00  -77.75%
BenchmarkSyscall                  34.40        33.30   -3.20%
BenchmarkSyscall-2               160.00       121.00  -24.38%
BenchmarkSyscall-4               131.00       136.00   +3.82%
BenchmarkSyscall-8               139.00       131.00   -5.76%
BenchmarkSyscall-16              161.00       168.00   +4.35%
BenchmarkSyscallWork             950.00       950.00   +0.00%
BenchmarkSyscallWork-2           481.00       480.00   -0.21%
BenchmarkSyscallWork-4           268.00       270.00   +0.75%
BenchmarkSyscallWork-8           156.00       169.00   +8.33%
BenchmarkSyscallWork-16          188.00       184.00   -2.13%
BenchmarkSemaSyntNonblock         36.40        35.60   -2.20%
BenchmarkSemaSyntNonblock-2       81.40        45.10  -44.59%
BenchmarkSemaSyntNonblock-4      126.00       108.00  -14.29%
BenchmarkSemaSyntNonblock-8      112.00       112.00   +0.00%
BenchmarkSemaSyntNonblock-16     110.00       112.00   +1.82%
BenchmarkSemaSyntBlock            35.30        35.30   +0.00%
BenchmarkSemaSyntBlock-2         118.00       124.00   +5.08%
BenchmarkSemaSyntBlock-4         105.00       108.00   +2.86%
BenchmarkSemaSyntBlock-8         101.00       111.00   +9.90%
BenchmarkSemaSyntBlock-16        112.00       118.00   +5.36%
BenchmarkSemaWorkNonblock        810.00       811.00   +0.12%
BenchmarkSemaWorkNonblock-2      476.00       414.00  -13.03%
BenchmarkSemaWorkNonblock-4      238.00       228.00   -4.20%
BenchmarkSemaWorkNonblock-8      140.00       126.00  -10.00%
BenchmarkSemaWorkNonblock-16     117.00       116.00   -0.85%
BenchmarkSemaWorkBlock           810.00       811.00   +0.12%
BenchmarkSemaWorkBlock-2         454.00       466.00   +2.64%
BenchmarkSemaWorkBlock-4         243.00       241.00   -0.82%
BenchmarkSemaWorkBlock-8         145.00       137.00   -5.52%
BenchmarkSemaWorkBlock-16        132.00       123.00   -6.82%
BenchmarkContendedSemaphore      123.00       102.00  -17.07%
BenchmarkContendedSemaphore-2     34.80        34.90   +0.29%
BenchmarkContendedSemaphore-4     34.70        34.80   +0.29%
BenchmarkContendedSemaphore-8     34.70        34.70   +0.00%
BenchmarkContendedSemaphore-16    34.80        34.70   -0.29%
BenchmarkMutex                    26.80        26.00   -2.99%
BenchmarkMutex-2                 108.00        45.20  -58.15%
BenchmarkMutex-4                 103.00       127.00  +23.30%
BenchmarkMutex-8                 109.00       147.00  +34.86%
BenchmarkMutex-16                102.00       152.00  +49.02%
BenchmarkMutexSlack               27.00        26.90   -0.37%
BenchmarkMutexSlack-2            149.00       165.00  +10.74%
BenchmarkMutexSlack-4            121.00       209.00  +72.73%
BenchmarkMutexSlack-8            101.00       158.00  +56.44%
BenchmarkMutexSlack-16            97.00       129.00  +32.99%
BenchmarkMutexWork               792.00       794.00   +0.25%
BenchmarkMutexWork-2             407.00       409.00   +0.49%
BenchmarkMutexWork-4             220.00       209.00   -5.00%
BenchmarkMutexWork-8             267.00       160.00  -40.07%
BenchmarkMutexWork-16            315.00       300.00   -4.76%
BenchmarkMutexWorkSlack          792.00       793.00   +0.13%
BenchmarkMutexWorkSlack-2        406.00       404.00   -0.49%
BenchmarkMutexWorkSlack-4        225.00       212.00   -5.78%
BenchmarkMutexWorkSlack-8        268.00       136.00  -49.25%
BenchmarkMutexWorkSlack-16       300.00       300.00   +0.00%
BenchmarkRWMutexWrite100          27.10        27.00   -0.37%
BenchmarkRWMutexWrite100-2        33.10        40.80  +23.26%
BenchmarkRWMutexWrite100-4       113.00        88.10  -22.04%
BenchmarkRWMutexWrite100-8       119.00        95.30  -19.92%
BenchmarkRWMutexWrite100-16      148.00       109.00  -26.35%
BenchmarkRWMutexWrite10           29.60        29.40   -0.68%
BenchmarkRWMutexWrite10-2        111.00        61.40  -44.68%
BenchmarkRWMutexWrite10-4        270.00       208.00  -22.96%
BenchmarkRWMutexWrite10-8        204.00       185.00   -9.31%
BenchmarkRWMutexWrite10-16       261.00       190.00  -27.20%
BenchmarkRWMutexWorkWrite100    1040.00      1036.00   -0.38%
BenchmarkRWMutexWorkWrite100-2   593.00       580.00   -2.19%
BenchmarkRWMutexWorkWrite100-4   470.00       365.00  -22.34%
BenchmarkRWMutexWorkWrite100-8   468.00       289.00  -38.25%
BenchmarkRWMutexWorkWrite100-16  604.00       374.00  -38.08%
BenchmarkRWMutexWorkWrite10      951.00       951.00   +0.00%
BenchmarkRWMutexWorkWrite10-2   1001.00       928.00   -7.29%
BenchmarkRWMutexWorkWrite10-4   1555.00      1006.00  -35.31%
BenchmarkRWMutexWorkWrite10-8   2085.00      1171.00  -43.84%
BenchmarkRWMutexWorkWrite10-16  2082.00      1614.00  -22.48%

R=rsc, iant, msolo, fw, iant
CC=golang-dev
https://golang.org/cl/4711045
2011-07-29 12:44:06 -04:00
Russ Cox
bed7e3ed78 gc: fix pprof deadlock
Fixes #2051.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4834041
2011-07-28 21:03:40 -04:00
Russ Cox
032ffb2e90 gc: more graceful errors during struct definition
Fixes #2110.

R=ken2
CC=golang-dev
https://golang.org/cl/4823060
2011-07-28 20:41:18 -04:00
Rob Pike
33a4da89d3 exp/template: fix build
TBR=gri

R=gri
CC=golang-dev
https://golang.org/cl/4815070
2011-07-28 16:46:32 -07:00
Russ Cox
71ba47ac9e build: fix noclobber
I got it backwards last time, and somehow
that was leaking into the parent shell?

R=golang-dev, iant
CC=golang-dev
https://golang.org/cl/4826054
2011-07-28 19:38:14 -04:00
Rob Pike
1b4dff0f69 exp/template: simplify the helper functions
- create a pair of "Must" functions, one for templates, one for sets
- regularize the return values of the parsers so they can be wrapped by Must
- delete all the old Must functions and methods.

R=golang-dev, gri, r
CC=golang-dev
https://golang.org/cl/4826052
2011-07-28 16:19:16 -07:00
Russ Cox
28a23675cd 5g, 6g, 8g: shift, opt fixes
Fixes #1808.

R=ken2
CC=golang-dev
https://golang.org/cl/4813052
2011-07-28 18:22:12 -04:00
Russ Cox
8c23c1ab87 5g: defer vs optimizer bug
Fixes #1924.

R=ken2
CC=golang-dev
https://golang.org/cl/4802063
2011-07-28 16:28:23 -04:00
Andrew Balholm
3de6228aea http: make serveFile redirects relative to work with StripPrefix
serveFile was using absolute redirects, which didn't work under StripPrefix.
Now it uses relative redirects.

R=golang-dev, rsc, bradfitz
CC=golang-dev, kevlar
https://golang.org/cl/4789042
2011-07-28 11:43:16 -07:00
Russ Cox
08bfb39515 6g, 8g: divide corner case
Fixes #1772.

R=ken2
CC=golang-dev
https://golang.org/cl/4798062
2011-07-28 14:18:22 -04:00
Russ Cox
fe206e63ca build: handle spaces in $USER
Fixes #2107.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4830042
2011-07-28 13:04:52 -04:00
Russ Cox
e0d6f95069 build: update all-qemu.bash
nothing but GOARCH=arm makes sense.
http/cgi uses network too.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4800053
2011-07-28 13:04:30 -04:00
Russ Cox
4389192669 gc: shift type bug
Fixes #1664.

R=ken2
CC=golang-dev
https://golang.org/cl/4798056
2011-07-28 13:03:30 -04:00
Roger Peppe
ca68b2810d exp/template: make Set.ParseFile etc resolve functions in the Set
Fixes #2114

R=r
CC=golang-dev
https://golang.org/cl/4823056
2011-07-28 09:59:20 -07:00
Russ Cox
db9229def8 cgo: add GoBytes, fix gmp example
Fixes #1640.
Fixes #2007.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4815063
2011-07-28 12:39:50 -04:00
Russ Cox
acb02ebc30 gc: another width test
R=ken2
CC=golang-dev
https://golang.org/cl/4808057
2011-07-28 12:32:43 -04:00
Russ Cox
2f8190a8f8 gc: line number + type checking nits
Fixes #1910.
Fixes #1979.
Fixes #1990.
Fixes #1993.
Fixes #2089.

R=ken2
CC=golang-dev
https://golang.org/cl/4828046
2011-07-28 12:31:16 -04:00
Roger Peppe
3041f2a37c exp/template: make Set.MustParse* methods return the set.
This brings them into line with the Template.MustParse* methods
and makes it possible to use them in global variable initializations.

R=r
CC=golang-dev
https://golang.org/cl/4798059
2011-07-28 08:41:06 -07:00
Alex Brainman
fa249cae38 ld: remove cseekend and redo pe writing
Simplify code and add more checks.

Fixes #2105.

R=rsc
CC=golang-dev
https://golang.org/cl/4794060
2011-07-28 14:30:52 +10:00
Rob Pike
5a52c6ad29 rpc and exp/template: simplify tests for exported items
Fix code to count mallocs - needed to call UpdateMemStats.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4823055
2011-07-27 21:26:16 -07:00
Benny Siegert
a65f4ccb89 image/tiff: Do not panic when RowsPerStrip is missing.
The RowsPerStrip tag is mandatory according to the spec. However,
Mac OS sometimes (?) omits it. I managed to create such an image
by applying "tiffutil -none" on a compressed image.

If RowsPerStrip is 0, there was a division by zero in the decoder.
Assume that the image is a single strip in this case.

R=nigeltao, bradfitz
CC=golang-dev
https://golang.org/cl/4815061
2011-07-28 11:15:59 +10:00
Russ Cox
890bdc5339 gc: top-level closure bug
Fixes #2055.

R=ken2
CC=golang-dev
https://golang.org/cl/4816059
2011-07-27 19:31:11 -04:00
Russ Cox
f91eb3c2f9 gc: composite literal double eval bug
Fixes #2086.

R=ken2
CC=golang-dev
https://golang.org/cl/4803055
2011-07-27 18:55:30 -04:00
Rob Pike
5ea413e2a0 unicode: fix case-mapping for roman numerals!!
Hurray!
Also fix the mystical U+0345 COMBINING GREEK YPOGEGRAMMENI,
so everyone is satisfied.
Also add a -local flag to use local files for faster turnaround
when debugging.

R=rsc
CC=golang-dev
https://golang.org/cl/4825054
2011-07-27 15:54:23 -07:00
John Asmuth
2f4632febc container/vector: removed some uses of container/vector in other pkgs
R=gri
CC=golang-dev
https://golang.org/cl/4823054
2011-07-27 15:23:42 -07:00
Andrew Gerrand
22f71cde6a A+C: John Asmuth
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4827045
2011-07-27 15:23:14 -07:00
Robert Griesemer
d7a0e0e6a2 godoc: app engine configuration and updated documentation
Also: Fixed an error message in zip.go.

R=r, dsymonds
CC=golang-dev
https://golang.org/cl/4816053
2011-07-27 15:14:12 -07:00
Russ Cox
1bd4b6371a gc: use more Go-like names for methods
Fixes #991.

R=ken2
CC=golang-dev
https://golang.org/cl/4819049
2011-07-27 17:56:13 -04:00
Russ Cox
112267d55e gc: diagnose (x) := 0
Fixes #1756.

R=ken2
CC=golang-dev
https://golang.org/cl/4810057
2011-07-27 17:39:30 -04:00
Russ Cox
db3088a37c build: fix for noclobber users
Fixes #2020.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4814056
2011-07-27 17:38:39 -04:00
Russ Cox
a84abbe508 gc: zero-width struct, zero-length array fixes
Fixes #1774.
Fixes #2095.
Fixes #2097.

R=ken2
CC=golang-dev
https://golang.org/cl/4826046
2011-07-27 16:47:45 -04:00
Russ Cox
dec8009fe8 gc: iota outside const
Fixes #1662.

R=ken2
CC=golang-dev
https://golang.org/cl/4828045
2011-07-27 14:45:27 -04:00
Russ Cox
49b70d01c0 gc: echo literal in error message
Fixes #1192.

R=ken2
CC=golang-dev
https://golang.org/cl/4794062
2011-07-27 14:36:21 -04:00
Russ Cox
100a034120 runtime: higher goroutine arg limit, clearer error
Fixes #591.

R=ken2
CC=golang-dev
https://golang.org/cl/4803054
2011-07-27 12:41:46 -04:00
David Symonds
c913cb8ba5 reflect: rename new TestVariadic to TestVariadicType.
R=nigeltao
CC=golang-dev
https://golang.org/cl/4825050
2011-07-27 13:44:57 +10:00
David Symonds
fc1cf58809 reflect: doc fixes for obsolete types.
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4802061
2011-07-27 13:29:44 +10:00
Rob Pike
2fc962697a goinstall: generate makefiles using exp/template
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4809052
2011-07-26 14:45:36 -07:00
Rob Pike
7e1101d470 rpc: convert /debug/rpc handler to exp/template
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4819048
2011-07-26 14:44:51 -07:00
Robert Griesemer
e21f69338b http: set content type for fileserver directory listings
R=bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4815062
2011-07-26 11:30:11 -07:00
Russ Cox
12a5774cde gc, runtime: fix range+panic line number bugs
Fixes #1856.

R=ken2
CC=golang-dev
https://golang.org/cl/4810054
2011-07-26 00:52:46 -04:00
Russ Cox
cce10dacc6 gc: fix select line number
Fixes #1393.

R=ken2
CC=golang-dev
https://golang.org/cl/4811054
2011-07-26 00:52:17 -04:00
Russ Cox
bf899befdb gc: disallow [...][...]int{{1,2,3}}
Fixes #1600.

R=ken2
CC=golang-dev
https://golang.org/cl/4819045
2011-07-26 00:52:02 -04:00
Mikio Hara
e5437ab065 runtime: fix freebsd build
Fixes #2078.

R=rsc
CC=golang-dev
https://golang.org/cl/4800052
2011-07-26 00:49:32 -04:00
Russ Cox
55dfdb64ab build: remove rm dreg
Undo CL 4254056 now that enough time has elapsed
that people with old trees have all built and removed
those files (which are no longer generated in that location).

Fixes #1581.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4802059
2011-07-26 00:30:39 -04:00
David Symonds
e527d49e55 http: implement MP4 sniffing.
R=rsc
CC=golang-dev
https://golang.org/cl/4809044
2011-07-26 13:28:20 +10:00
Alex Brainman
003d5411ae net: fix memory corruption in windows *netFD.ReadFrom
We must keep memory used by syscall.WSARecvFrom away from
garbage collector until after overlapped call is completed.

Fixes #2094.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4817050
2011-07-26 11:55:52 +10:00
Andrew Gerrand
83305fecfe goinstall: abort and warn when using any url scheme, not just 'http://'
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4801053
2011-07-26 04:16:34 +10:00
Lucio De Re
75c918c1ae ld: fix build on Plan 9
ld/data.c:
. Format specifier with corresponding cast to cater for all
  architectures (llux and vlong).

ld/ldelf.c:
ld/ldmacho.c:
. Missing "pn" argument in diag() calls.

ld/ldpe.c:
. Dropped "sym->sectnum" in diag() call.
. Typo in a comment.

ld/lib.h:
. Added varargck pragma for "O".

R=rsc
CC=golang-dev
https://golang.org/cl/4749042
2011-07-25 13:45:50 -04:00
Lucio De Re
eb3f2083f9 build: define getcallerpc in u.h (fix for Plan 9 build)
. By defining getcallerpc(x) as __builtin_return_address(0)
  here, it becomes possible to use the Plan 9 compatible form
  when compiling using GCC.  The alternative is to add conditional
  compilation based on the compiler identity in "cmd/8g/gsubr.c"
  to distinguish between the two cases.

R=golang-dev
CC=golang-dev, rsc
https://golang.org/cl/4800048
2011-07-25 13:45:44 -04:00
Lucio De Re
12995e2d35 gc: fix mkbuiltin for Plan 9 build
. Replaced Posix #includes with u.h and libc.h.
. Replaced fprintf(stderr,...); exit(1); with sysfatal() calls.

R=golang-dev
CC=golang-dev, rsc
https://golang.org/cl/4823047
2011-07-25 13:45:37 -04:00
Wei Guangjing
ee14fbdf34 build: fixes for mingw-w64
R=rsc
CC=golang-dev
https://golang.org/cl/4742042
2011-07-25 13:39:01 -04:00
Wei Guangjing
0871af25aa ld: don't skip first 2 symbols in ldpe.
some object files don't has file name symbol.

R=golang-dev, lucio.dere, rsc
CC=golang-dev
https://golang.org/cl/4814051
2011-07-25 12:25:44 -04:00
Yuval Pavel Zholkover
2aa2ceb873 runtime: Plan 9, skip calling runtime·ldt0setup.
R=golang-dev
CC=alex.brainman, golang-dev
https://golang.org/cl/4816049
2011-07-25 12:25:41 -04:00
Dmitriy Vyukov
33ff947cac runtime: fix compilation of send select cases
Fixes #2102.

R=fullung, rsc
CC=golang-dev
https://golang.org/cl/4825043
2011-07-25 12:25:37 -04:00
Alex Brainman
770543107d syscall: remove unused windows code and comments
R=golang-dev, vcc.163, rsc
CC=golang-dev
https://golang.org/cl/4826042
2011-07-25 12:25:23 -04:00
Ian Lance Taylor
3a07d516b4 runtime: remove rnd calls that pass a second argument of 1
When rnd is called with a second argument of 1, it simply
returns the first argument anyway.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4820045
2011-07-24 22:03:17 -07:00
Russ Cox
a1e7cd97d5 exp/regexp: implement regexp API using exp/regexp/syntax
Still need to write tests for new syntax
and fix bugs that the tests find, but this
is a good check point.

All tests pass.

Compared against existing regexp:

benchmark                                old ns/op    new ns/op    delta
regexp.BenchmarkLiteral                       1869          620  -66.83%
regexp.BenchmarkNotLiteral                    9489         7823  -17.56%
regexp.BenchmarkMatchClass                   10372         8386  -19.15%
regexp.BenchmarkMatchClass_InRange           10800         7750  -28.24%
regexp.BenchmarkReplaceAll                   13492         8519  -36.86%
regexp.BenchmarkAnchoredLiteralShortNonMatch   747          339  -54.62%
regexp.BenchmarkAnchoredLiteralLongNonMatch    599          335  -44.07%
regexp.BenchmarkAnchoredShortMatch            2137          917  -57.09%
regexp.BenchmarkAnchoredLongMatch             2029          917  -54.81%

R=r, r
CC=golang-dev, sam.thorogood
https://golang.org/cl/4820046
2011-07-24 17:00:28 -04:00
Andrew Gerrand
fc2480da3c goinstall: write to goinstall.log in respective GOPATH
goinstall: report every newly installed package to the dashboard

This makes "goinstall -a" work on systems with GOROOTs that are
not user-writable, as is the case with Debian's Go packages.

This also makes goinstall.log the canonical list of installed
packages, in that only packages new to goinstall.log are reported to
the dashboard.

A side-effect is that writing to goinstall.log is now mandatory.
(A bug in the original implementation meant this was the case, anyway.)

The principal benefit of this change is that multiple packages from the
same repository can now be reported to the dashboard.  It is also less
likely for a user to report multiple installations of the same package
to the dashboard (they would need to remove the package from
goinstall.log first).

R=rsc, n13m3y3r
CC=golang-dev
https://golang.org/cl/4786041
2011-07-24 13:43:08 +10:00
Andrew Balholm
d56c8132e8 unicode: fix doc comment for Range32
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4811050
2011-07-24 10:51:19 +10:00
Florian Uekermann
480ef72c23 sort: fixed bug in (Float64Slice) Less; NaN less than anything else
Previously comparisons with NaN led to contradictory results if it was
compared to anything not NaN, since Less always returned false, thus
breaking monotonicity of ordering.
This fix makes NaN less than anything else and adds NaN and (+-)Inf to
testcases.

Fixes #2092.

R=golang-dev, r, rsc, r
CC=golang-dev
https://golang.org/cl/4805051
2011-07-23 15:47:06 -04:00
Quan Yong Zhai
47410a2490 runtime: replace byte-at-a-time zeroing loop with memclr
R=golang-dev, r, r, dsymonds, rsc
CC=golang-dev
https://golang.org/cl/4813043
2011-07-23 15:46:58 -04:00
Russ Cox
ba134539c5 runtime: faster entersyscall/exitsyscall
Replace cas with xadd in scheduler.
Suggested by Dmitriy in last code review.
Verified with Promela model.

When there's actual contention for the atomic word,
this avoids the looping that compare-and-swap requires.

benchmark                            old ns/op    new ns/op    delta
runtime_test.BenchmarkSyscall               32           26  -17.08%
runtime_test.BenchmarkSyscall-2            155           59  -61.81%
runtime_test.BenchmarkSyscall-3            112           52  -52.95%
runtime_test.BenchmarkSyscall-4             94           48  -48.57%
runtime_test.BenchmarkSyscallWork          871          872   +0.11%
runtime_test.BenchmarkSyscallWork-2        481          477   -0.83%
runtime_test.BenchmarkSyscallWork-3        338          335   -0.89%
runtime_test.BenchmarkSyscallWork-4        263          256   -2.66%

R=golang-dev, iant
CC=golang-dev
https://golang.org/cl/4800047
2011-07-23 12:22:55 -04:00
Wei Guangjing
7ce1a4bdc0 ld: fixes .bss for ldpe
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4794056
2011-07-23 12:21:13 -04:00
Rob Pike
2d972ad493 exp/template: construct sets from plain template files
This is the last piece (I hope) of the set creation code.
These helpers create sets from files containing individual
template definitions, free of {{define}} clauses. This
design is helpful if the templates live one per file,
undecorated.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4801052
2011-07-23 18:10:30 +10:00
Robert Griesemer
3ddaa95d71 fix build: clean up file end in an attempt to fix build
R=r, iant
CC=golang-dev
https://golang.org/cl/4809050
2011-07-22 22:45:14 -07:00
Robert Griesemer
dcef981217 godoc/httpzip.go: use correct path in Readdir
Fixes a problem where Readdir would always return
empty directories (Readdir is only called by godoc
if the usual directory handler is commented out
in godoc.go, and if a zip file system is provided;
thus, this bug never manifested itself in godoc).

Also:
- better choice of variable/field names
- simplified error handling a bit
- better comments

R=bradfitz
CC=golang-dev
https://golang.org/cl/4813047
2011-07-22 22:24:04 -07:00
Brad Fitzpatrick
8fdc2851e4 zip: add a test for the previous >65k files fix
This surprisingly takes 30 seconds on my fast machine
so disabling by default. Need to optimize the Writer
at some point.

R=golang-dev, r, r
CC=golang-dev
https://golang.org/cl/4815048
2011-07-22 18:30:07 -07:00
Russ Cox
a667e44e75 lib9: use $PWD in getwd
This makes the full file paths recorded by 6g
prefer $PWD over the actual directory name
(relevant when $PWD gets to the current directory
via symlinks).  It's what everyone else does, and
what people expect.

R=iant, r, mattn.jp
CC=golang-dev
https://golang.org/cl/4824041
2011-07-22 21:21:17 -04:00
Wei Guangjing
4e5e12e305 ld: fixes ldpe link with SXREF global values.
R=golang-dev, mattn.jp, rsc
CC=golang-dev
https://golang.org/cl/4794052
2011-07-22 21:21:08 -04:00
Russ Cox
b9b204d55d ld: detect all import cycles
Fixes #2052.

R=r
CC=golang-dev
https://golang.org/cl/4812053
2011-07-22 21:18:03 -04:00
Russ Cox
07c103f6e6 sort: remove testing cycle
import cycle:
        "testing"
        imports "flag"
        imports "sort"
        imports "testing"

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4811048
2011-07-22 21:17:46 -04:00
Robert Griesemer
e62e595e7a godoc/zip.go: fix another zip file system bug
Don't report that a directory was found just because we found
the list index where the directory would be if it were there...

R=iant
CC=golang-dev
https://golang.org/cl/4812051
2011-07-22 15:21:50 -07:00
Robert Griesemer
fa497796f5 go/parser: report illegal label declarations at ':' rather than guessing the start
Also:
- Add parser.SpuriousError flag. If set, the parser reports all (including
  spurious) errors rather then at most one error per line.
- Add -e flag to gofmt and gotype: If set, gofmt and gotype report all
  (including spurious) errors rather than at most one error per line.
- Updated the respective documentation.

Fixes #2088.

R=rsc
CC=golang-dev
https://golang.org/cl/4803047
2011-07-22 09:55:37 -07:00
Rob Pike
3d552700ce goyacc: cleanups
- remove calls to print
- make units compile again
- make units.y closer to gofmt style

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4802052
2011-07-22 17:58:38 +10:00
Rob Pike
f0d8af200c exp/template: trivial cleanup in test
Clean up glitch created by flurry of editing.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4808052
2011-07-22 17:52:46 +10:00
Rob Pike
54045e6bcd pkg/http: fix a couple of error messages
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4805048
2011-07-22 17:11:44 +10:00
Andrew Gerrand
38e5128243 archive/zip: handle zip files with more than 65535 files
R=r
CC=golang-dev
https://golang.org/cl/4812048
2011-07-22 14:57:17 +10:00
Russ Cox
226fb099d9 runtime: add UpdateMemStats, use in tests
Drops mallocrep1.go back to a reasonable
amount of time.  (154 -> 0.8 seconds on my Mac)

Fixes #2085.

R=golang-dev, dvyukov, r
CC=golang-dev
https://golang.org/cl/4811045
2011-07-22 00:55:01 -04:00
Rob Pike
222450addb exp/template: add globbing helpers to load groups of files into sets.
Also make the Set.Parse methods variadic so you can parse static lists of files without loops.

R=rsc, dsymonds, r
CC=golang-dev
https://golang.org/cl/4802051
2011-07-22 13:55:45 +10:00
David Symonds
99e5d48e59 http: clarify use of w.conn.body in Write when sniffing.
R=gri, r, r, rsc
CC=golang-dev
https://golang.org/cl/4794047
2011-07-22 13:52:21 +10:00
Rob Pike
3e79c958c4 exp/template: plain actions with declarations should produce no output.
This is already the behavior for pipelines producing values for if, with, and range.

R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4808050
2011-07-22 10:51:40 +10:00
Roger Peppe
47647b9865 exp/template: fix action variable declarations inside range
R=r
CC=golang-dev
https://golang.org/cl/4807043
2011-07-22 09:53:25 +10:00
Robert Griesemer
e109a2bb8c big: minor comment adjustments
R=mtj, r
CC=golang-dev
https://golang.org/cl/4814044
2011-07-21 15:01:58 -07:00
Michael T. Jones
12c736158a big: refine printf formatting and optimize string conversion
Now handles standard precision specifications, standard interactions of
redundant specifications (such as precision and zero-fill), handles the
special case of precision specified but equal to zero, and generates the
output without recursive calls to format/printf to be clearer and faster.

R=gri, mtj, gri
CC=golang-dev
https://golang.org/cl/4703050
2011-07-21 14:29:08 -07:00
Russ Cox
301d8a6d4a http: fix chunking bug during content sniffing
R=golang-dev, bradfitz, gri
CC=golang-dev
https://golang.org/cl/4807044
2011-07-21 14:29:14 -04:00
Russ Cox
22853098a9 gc: select functions are no longer special
R=ken2
CC=golang-dev
https://golang.org/cl/4794049
2011-07-21 14:10:39 -04:00
Dmitriy Vyukov
6b2ec06587 runtime: faster select
Make selectsend() accept pointer to the element,
it makes it possible to make Scase fixed-size
and allocate/free Select, all Scase's and all SudoG at once.
As a consequence SudoG freelist die out.

benchmark                       old,ns/op  new,ns/op
BenchmarkSelectUncontended	     1080        558
BenchmarkSelectUncontended-2	      675        264
BenchmarkSelectUncontended-4	      459        205
BenchmarkSelectContended	     1086        560
BenchmarkSelectContended-2	     1775       1672
BenchmarkSelectContended-4	     2668       2149
(on Intel Q6600, 4 cores, 2.4GHz)

benchmark                       old ns/op    new ns/op    delta
BenchmarkSelectUncontended         517.00       326.00  -36.94%
BenchmarkSelectUncontended-2       281.00       166.00  -40.93%
BenchmarkSelectUncontended-4       250.00        83.10  -66.76%
BenchmarkSelectUncontended-8       107.00        47.40  -55.70%
BenchmarkSelectUncontended-16       67.80        41.30  -39.09%
BenchmarkSelectContended           513.00       325.00  -36.65%
BenchmarkSelectContended-2         699.00       628.00  -10.16%
BenchmarkSelectContended-4        1085.00      1092.00   +0.65%
BenchmarkSelectContended-8        3253.00      2477.00  -23.85%
BenchmarkSelectContended-16       5313.00      5116.00   -3.71%
(on Intel E5620, 8 HT cores, 2.4 GHz)

R=rsc, ken
CC=golang-dev
https://golang.org/cl/4811041
2011-07-21 13:57:13 -04:00
Russ Cox
17d9093bf2 undo CL 4808044 / 1bd754e69ce7
ServeMux depends on having a URL
in order to mux.  It might be that the right
fix is to have CONNECT handlers just not
look at URL.

««« original CL description
http: do not parse req.URL for CONNECT

CONNECT's argument is not a URL.

R=golang-dev, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4808044

»»»

TBR=bradfitz
CC=golang-dev
https://golang.org/cl/4798046
2011-07-21 13:25:55 -04:00
Yasuhiro Matsumoto
bf5ec12dd5 http: do not parse req.URL for CONNECT
CONNECT's argument is not a URL.

R=golang-dev, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4808044
2011-07-21 11:33:59 -04:00
Dmitriy Vyukov
c3a86dab36 testing: output benchmark name before executing it
It makes it clear what benchmark is currently running.
Especially useful in case of hangup or crash.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4816043
2011-07-21 11:31:07 -04:00
Dmitriy Vyukov
d2ab2b9f42 sync: improve Once fast path
Use atomic.LoadUint32(&done) instead of
atomic.AddInt32(&done, 0) on fast path.

benchmark            old ns/op    new ns/op    delta
BenchmarkOnce            13.40         7.26  -45.82%
BenchmarkOnce-2          22.90         4.04  -82.36%
BenchmarkOnce-4          25.60         2.16  -91.56%
BenchmarkOnce-8          25.80         1.38  -94.65%
BenchmarkOnce-16         24.40         1.33  -94.55%

(on HP Z600, 2 x Intel Xeon E5620, 8 HT cores, 2.4 GHz)

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4787041
2011-07-21 11:30:14 -04:00
Dmitriy Vyukov
d6ed1b70ad runtime: replace centralized ncgocall counter with a distributed one
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4809042
2011-07-21 11:29:08 -04:00
David Symonds
6c46afdf41 http: disable sniffer for now.
Something is broken, and investigation is underway.
In the meantime, godoc is broken, so disable sniffing for now
by reverting to the pre-sniffer state.

R=r
CC=golang-dev
https://golang.org/cl/4809046
2011-07-21 22:20:09 +10:00
Gustavo Niemeyer
14eba969d8 ld: fix freebsd build reverting .interp move
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4794046
2011-07-21 03:48:56 -03:00
Michael T. Jones
8cdee891d7 fmt: handle precision 0 format stings in standard way
The C-stdlib heritage of printf/fprintf/sprintf has two odd
aspects for precisions of zero with integers. First, the zero
can be specified in any of these ways, "%4.0d", "%.0d" and
"%.d" which was not previously supported here. Secondly, the
seemingly universal interpretation of precision for integers
is that precision==0 and value==0 means print nothing at all.
The code here now handles this for integers just as the code
in big/int.c does the same for the Int type. New tests are
added to fmt_test.go to verify these changes.

R=r, r
CC=golang-dev
https://golang.org/cl/4717045
2011-07-21 16:46:51 +10:00
Rob Pike
0f7a1951b8 exp/template: A template can be in one set only.
This simplifies the API and makes it easier to make the template
invocation statically secure, at the cost of some minor flexibility.

R=golang-dev, dsymonds, r
CC=golang-dev
https://golang.org/cl/4794045
2011-07-21 14:22:01 +10:00
Nigel Tao
5f134f9b5b html: sync html/testdata/webkit with upstream WebKit.
As $GOROOT/src/pkg/html/testdata/webkit/README says, we're pulling from
$WEBKITROOT/LayoutTests/html5lib/resources.

R=r
CC=golang-dev
https://golang.org/cl/4810043
2011-07-21 12:50:45 +10:00
Nigel Tao
5a141064ed html: parse misnested formatting tags according to the HTML5 spec.
This is the "adoption agency" algorithm.

The test case input is "<a><p>X<a>Y</a>Z</p></a>". The correct parse is:
| <html>
|   <head>
|   <body>
|     <a>
|     <p>
|       <a>
|         "X"
|       <a>
|         "Y"
|       "Z"

R=gri
CC=golang-dev
https://golang.org/cl/4771042
2011-07-21 11:20:54 +10:00
Rob Pike
d11c0f1dbb gob: send empty but non-nil maps.
Fixes #2082.

R=golang-dev, dsymonds, r
CC=golang-dev
https://golang.org/cl/4798042
2011-07-21 10:27:11 +10:00
Robert Griesemer
4c03bf9c59 godoc: fix zip file directory lookup
Also: remove left-over println calls.

R=bradfitz
CC=golang-dev
https://golang.org/cl/4807042
2011-07-20 16:22:13 -07:00
Andrew Balholm
816c972ff0 html: handle character entities without semicolons
Fix the TODO: unescape("&notit;") should be "¬it;"

Also accept digits in entity names.

R=nigeltao
CC=golang-dev, rsc
https://golang.org/cl/4781042
2011-07-21 09:10:49 +10:00
David Symonds
78c89d21bc http: sniffing algorithm.
This follows draft-ietf-websec-mime-sniff-03 in its intent,
though not its algorithmic specification.

R=rsc
CC=golang-dev
https://golang.org/cl/4746042
2011-07-21 08:38:35 +10:00
Mike Solomon
7911965fe9 io/ioutil: improve performance of ioutil.Discard
Fixes #2084.

R=bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4817041
2011-07-20 14:34:49 -07:00
Brad Fitzpatrick
125419a250 CONTRIBUTORS: add Mike Solomon (Google CLA)
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4818041
2011-07-20 13:30:46 -07:00
Brad Fitzpatrick
bf768294ed os: point readers at the exec package
R=golang-dev, evan, rsc
CC=golang-dev
https://golang.org/cl/4802046
2011-07-20 11:38:18 -07:00
Dmitriy Vyukov
102b5b34a7 runtime: apply minor tweaks to channels
Remove complicated PRNG algorithm
(argument is limited by uint16 and can't be <= 1).
Do not require chansend/chanrecv selgen to be bumped with CAS.

R=rsc, ken
CC=golang-dev
https://golang.org/cl/4816041
2011-07-20 14:28:55 -04:00
Dmitriy Vyukov
90f3cb13fb runtime: improve performance of sync channels
1. SudoG always contains a pointer to the element
(thus no variable size, and less copying).
2. chansend/chanrecv allocate SudoG on the stack.
3. Copying of elements and gorotuine notifications
are moved out of critical sections.

benchmark                        old ns/op    new ns/op    delta
BenchmarkSelectUncontended          515.00       514.00   -0.19%
BenchmarkSelectUncontended-2        291.00       281.00   -3.44%
BenchmarkSelectUncontended-4        213.00       189.00  -11.27%
BenchmarkSelectUncontended-8         78.30        79.00   +0.89%
BenchmarkSelectContended            518.00       514.00   -0.77%
BenchmarkSelectContended-2          655.00       631.00   -3.66%
BenchmarkSelectContended-4         1026.00      1051.00   +2.44%
BenchmarkSelectContended-8         2026.00      2128.00   +5.03%
BenchmarkSelectNonblock             175.00       173.00   -1.14%
BenchmarkSelectNonblock-2            85.10        87.70   +3.06%
BenchmarkSelectNonblock-4            60.10        43.30  -27.95%
BenchmarkSelectNonblock-8            37.60        25.50  -32.18%
BenchmarkChanUncontended            109.00       114.00   +4.59%
BenchmarkChanUncontended-2           54.60        57.20   +4.76%
BenchmarkChanUncontended-4           27.40        28.70   +4.74%
BenchmarkChanUncontended-8           14.60        15.10   +3.42%
BenchmarkChanContended              108.00       114.00   +5.56%
BenchmarkChanContended-2            621.00       617.00   -0.64%
BenchmarkChanContended-4            759.00       677.00  -10.80%
BenchmarkChanContended-8           1635.00      1517.00   -7.22%
BenchmarkChanSync                   299.00       256.00  -14.38%
BenchmarkChanSync-2                5055.00      4624.00   -8.53%
BenchmarkChanSync-4                4998.00      4680.00   -6.36%
BenchmarkChanSync-8                5019.00      4760.00   -5.16%
BenchmarkChanProdCons0              316.00       274.00  -13.29%
BenchmarkChanProdCons0-2           1280.00       617.00  -51.80%
BenchmarkChanProdCons0-4           2433.00      1332.00  -45.25%
BenchmarkChanProdCons0-8           3651.00      1934.00  -47.03%
BenchmarkChanProdCons10             153.00       152.00   -0.65%
BenchmarkChanProdCons10-2           626.00       581.00   -7.19%
BenchmarkChanProdCons10-4          1440.00      1323.00   -8.12%
BenchmarkChanProdCons10-8          2036.00      2017.00   -0.93%

R=rsc, ken
CC=golang-dev
https://golang.org/cl/4790042
2011-07-20 11:51:25 -04:00
Gustavo Niemeyer
ba2e3af177 ld: remove overlap of ELF sections on dynamic binaries
The dynamic ELF sections were pointing to the proper data,
but that data was already owned by the rodata and text sections.
Some ELF references explicitly prohibit multiple sections from
owning the same data, and strip behaves accordingly.

The data for these sections was moved out and their ranges are
now owned by their respective sections.  This change makes strip
happy both with and without -s being provided at link time.

A test was added in debug/elf to ensure there are no regressions
on this area in the future.

Fixes #1242.
Fixes #2022.

NOTE: Tested on Linux amd64/386/arm only.

R=rsc
CC=golang-dev
https://golang.org/cl/4808043
2011-07-20 12:47:02 -03:00
Russ Cox
971459e826 net/textproto: fix build
R=bradfitz
CC=golang-dev
https://golang.org/cl/4815041
2011-07-20 11:41:41 -04:00
Russ Cox
27a3dcd0d2 net/textproto: avoid 1 copy in ReadLine, ReadContinuedLine
Fixes #2083.

R=msolo, bradfitz
CC=golang-dev
https://golang.org/cl/4812042
2011-07-20 11:11:57 -04:00
Marcel van Lohuizen
df07b6d14a exp/norm: API for normalization library.
R=r, r, mpvl, rsc
CC=golang-dev
https://golang.org/cl/4678041
2011-07-20 19:46:05 +10:00
Andrew Gerrand
dbba5ccfab gobuilder: goinstall with -dashboard=false instead of -log=false
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4801043
2011-07-20 16:07:40 +10:00
Andrew Gerrand
40462453c6 tag weekly.2011-07-19
R=r
CC=golang-dev
https://golang.org/cl/4802043
2011-07-20 15:48:36 +10:00
Andrew Gerrand
50ddb98b24 weekly.2011-07-19
R=golang-dev, nigeltao, dsymonds, r
CC=golang-dev
https://golang.org/cl/4801042
2011-07-20 15:45:55 +10:00
Andrew Gerrand
48d1240e51 misc/dashboard: center align build results
R=rsc, dsymonds
CC=golang-dev
https://golang.org/cl/4806041
2011-07-20 11:22:56 +10:00
Rob Pike
62f618a22c sync/atomic: delete workaround
Load seems to work on arm now.

R=dsymonds
CC=golang-dev
https://golang.org/cl/4795042
2011-07-20 08:39:24 +10:00
Robert Griesemer
8930ce2dc1 godoc: implement http.FileSystem for zip files
R=rsc, adg, bradfitz
CC=golang-dev
https://golang.org/cl/4750047
2011-07-19 08:22:20 -07:00
Lucio De Re
b546f50716 runtime: make goc2c build on Plan 9
pkg/runtime/Makefile:
. Adjusted so "goc2c.c" is built using the Plan 9 libraries.

pkg/runtime/goc2c.c:
. Added/subtracted #include headers to correspond to Plan 9
  toolkit.
. Changed fprintf(stderr,...)/exit() combinations to
  sysfatal() calls, adjusted the "%u" format to "%ud".
. Added exits(0) at the end of main().
. Made main() a void-returning function and removed the
  "return 0" at the end of it.

Tested on UBUNTU and Plan 9 only.

R=r, rsc
CC=golang-dev
https://golang.org/cl/4626093
2011-07-19 11:04:33 -04:00
Russ Cox
025abd530e runtime: faster entersyscall, exitsyscall
Uses atomic memory accesses to avoid the need to acquire
and release schedlock on fast paths.

benchmark                            old ns/op    new ns/op    delta
runtime_test.BenchmarkSyscall               73           31  -56.63%
runtime_test.BenchmarkSyscall-2            538           74  -86.23%
runtime_test.BenchmarkSyscall-3            508          103  -79.72%
runtime_test.BenchmarkSyscall-4            721           97  -86.52%
runtime_test.BenchmarkSyscallWork          920          873   -5.11%
runtime_test.BenchmarkSyscallWork-2        516          481   -6.78%
runtime_test.BenchmarkSyscallWork-3        550          343  -37.64%
runtime_test.BenchmarkSyscallWork-4        632          263  -58.39%

(Intel Core i7 L640 2.13 GHz-based Lenovo X201s)

Reduced a less artificial server benchmark
from 11.5r 12.0u 8.0s to 8.3r 9.1u 1.0s.

R=dvyukov, r, bradfitz, r, iant, iant
CC=golang-dev
https://golang.org/cl/4723042
2011-07-19 11:01:17 -04:00
Wei Guangjing
9f636598ba cgo: windows amd64 port
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4725041
2011-07-19 10:47:33 -04:00
Dmitriy Vyukov
0b200b4d09 sync/atomic: fix LoadInt32 on ARM
R0 is clobbered after cas,
while R1 preserves its value.

R=golang-dev
CC=golang-dev
https://golang.org/cl/4782042
2011-07-19 22:10:07 +10:00
Rob Pike
3bbeef5201 sync/atomic: attempt to get the arm build green.
Disable the LoadInt32 and LoadUint32 tests, since they fail.
These should be fixed but we want to get through the rest of the build
to see if something else unrelated is broken.  The arm build has been
bad for a long time.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4780041
2011-07-19 17:06:13 +10:00
Tarmigan Casebolt
a0d3be1689 goinstall, dashboard: Google Code now supports git
R=golang-dev, adg, rsc, tarmigan+golang
CC=golang-dev
https://golang.org/cl/4760055
2011-07-19 16:58:18 +10:00
Rob Pike
423ab2333a 5l: fix arm linker bug introduced by 4742041
Should fix the arm build.

R=golang-dev, dsymonds, adg
CC=golang-dev
https://golang.org/cl/4777041
2011-07-19 15:44:25 +10:00
Andrew Gerrand
894222f9de doc/talks/io2010: handle the errors
R=golang-dev, dsymonds, dsymonds, r
CC=golang-dev
https://golang.org/cl/4771041
2011-07-19 14:10:12 +10:00
Alex Brainman
42effdf096 go/build: fixes for windows paths
R=golang-dev, mattn.jp, adg
CC=golang-dev
https://golang.org/cl/4746047
2011-07-19 14:02:23 +10:00
Robert Griesemer
98f5fc5e86 archive/zip: support functions to get modified time in ns from MS-DOS time
R=rsc, r, bradfitz, r, adg
CC=golang-dev
https://golang.org/cl/4748056
2011-07-18 20:30:44 -07:00
Alex Brainman
208e6e6dfc exp/wingui: make sure it builds again
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4770041
2011-07-19 13:18:21 +10:00
Rob Pike
a5a94f5d57 gif: fix local color map and coordinates
R=nigeltao
CC=golang-dev
https://golang.org/cl/4759051
2011-07-19 11:47:15 +10:00
Andrew Gerrand
7a18fc3bcb dashboard: list "most installed this week" with rolling count
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4631085
2011-07-19 11:12:10 +10:00
Robert Griesemer
95117d30a2 time: typo in documentation
R=r
CC=golang-dev
https://golang.org/cl/4763048
2011-07-18 17:54:32 -07:00
Hector Chu
47e6042f73 runtime: fix select pass 3
Fixes #2075

R=rsc, ken, r
CC=golang-dev
https://golang.org/cl/4748045
2011-07-18 16:15:01 -04:00
Russ Cox
bd77619142 runtime: track running goroutine count
Used to use mcpu+msyscall but that's
problematic for packing into a single
atomic word.  The running goroutine count
(where running == Go code or syscall)
can be maintained separately, always
manipulated under lock.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4767041
2011-07-18 15:50:55 -04:00
Dmitriy Vyukov
27753ff108 runtime: add per-M caches for MemStats
Avoid touching centralized state during
memory manager operations.

R=mirtchovski
CC=golang-dev, rsc
https://golang.org/cl/4766042
2011-07-18 14:56:22 -04:00
Dmitriy Vyukov
66d5c9b1e9 runtime: add per-M caches for MemStats
Avoid touching centralized state during
memory manager opreations.

R=rsc
CC=golang-dev
https://golang.org/cl/4766042
2011-07-18 14:52:57 -04:00
Ian Lance Taylor
257df1719d debug/proc: Remove.
The package was always GNU/Linux specific, and is no longer
used by anything now that exp/ogle has been removed.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4757049
2011-07-18 09:55:09 -07:00
Dmitriy Vyukov
ee6e1a3ff7 sync: add fast paths to WaitGroup
benchmark                                        old ns/op    new ns/op    delta
BenchmarkWaitGroupUncontended                        93.50        33.60  -64.06%
BenchmarkWaitGroupUncontended-2                      44.30        16.90  -61.85%
BenchmarkWaitGroupUncontended-4                      21.80         8.47  -61.15%
BenchmarkWaitGroupUncontended-8                      12.10         4.86  -59.83%
BenchmarkWaitGroupUncontended-16                      7.38         3.35  -54.61%
BenchmarkWaitGroupAddDone                            58.40        33.70  -42.29%
BenchmarkWaitGroupAddDone-2                         293.00        85.80  -70.72%
BenchmarkWaitGroupAddDone-4                         243.00        51.10  -78.97%
BenchmarkWaitGroupAddDone-8                         236.00        52.20  -77.88%
BenchmarkWaitGroupAddDone-16                        215.00        43.30  -79.86%
BenchmarkWaitGroupAddDoneWork                       826.00       794.00   -3.87%
BenchmarkWaitGroupAddDoneWork-2                     450.00       424.00   -5.78%
BenchmarkWaitGroupAddDoneWork-4                     277.00       220.00  -20.58%
BenchmarkWaitGroupAddDoneWork-8                     440.00       116.00  -73.64%
BenchmarkWaitGroupAddDoneWork-16                    569.00        66.50  -88.31%
BenchmarkWaitGroupWait                               29.00         8.04  -72.28%
BenchmarkWaitGroupWait-2                             74.10         4.15  -94.40%
BenchmarkWaitGroupWait-4                            117.00         2.30  -98.03%
BenchmarkWaitGroupWait-8                            111.00         1.31  -98.82%
BenchmarkWaitGroupWait-16                           104.00         1.27  -98.78%
BenchmarkWaitGroupWaitWork                          802.00       792.00   -1.25%
BenchmarkWaitGroupWaitWork-2                        411.00       401.00   -2.43%
BenchmarkWaitGroupWaitWork-4                        210.00       199.00   -5.24%
BenchmarkWaitGroupWaitWork-8                        206.00       105.00  -49.03%
BenchmarkWaitGroupWaitWork-16                       334.00        54.40  -83.71%

R=rsc
CC=golang-dev
https://golang.org/cl/4672050
2011-07-18 12:35:55 -04:00
Russ Cox
92c6061b5c 5l: assume Linux binary, not Plan 9
R=bradfitz
CC=golang-dev
https://golang.org/cl/4767042
2011-07-18 12:30:10 -04:00
Brad Fitzpatrick
3745716bc3 http: let FileServer work when path doesn't begin with a slash
... as when it's over-stripped with StripPrefix.

R=golang-dev, andybalholm, rsc
CC=golang-dev
https://golang.org/cl/4759052
2011-07-18 09:04:48 -07:00
Russ Cox
caa5647408 ld: allow seek within write buffer
Reduces number of write+seek's from 88516 to 2080
when linking godoc with 6l.

Thanks to Alex Brainman for pointing out the
many small writes.

R=golang-dev, r, alex.brainman, robert.hencke
CC=golang-dev
https://golang.org/cl/4743043
2011-07-18 12:04:09 -04:00
Albert Strasheim
870fdd760a syscall: Parse and encode SCM_RIGHTS and SCM_CREDENTIALS.
R=rsc, agl, mikioh.mikioh
CC=golang-dev
https://golang.org/cl/4667066
2011-07-18 11:21:59 -04:00
Dmitriy Vyukov
c1f035ba4c runtime: fix data race in Plan9 sysalloc
Add mutex to protect brk limit.
Add mstats.sys update.

R=rsc
CC=golang-dev
https://golang.org/cl/4762045
2011-07-18 10:50:04 -04:00
Brad Fitzpatrick
e8689404a7 cgo: add missing semicolon in generated struct
This affected certain signatures needing padding
like:

//export Foo
func Foo() (int, C.long) { ... }

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4745047
2011-07-18 07:23:52 -07:00
Dave Cheney
c945d9c8a1 gc: fix silent sign truncation in pgen.c
Fixes #2076.

R=golang-dev, r, r, dsymonds, lucio.dere
CC=golang-dev
https://golang.org/cl/4744047
2011-07-18 21:09:28 +10:00
Rob Pike
9a5bb287e8 exp/template: dig into empty interfaces so a struct (say) stored in an empty
interface field can be unpacked. We don't have type assertions here so we
must be forthright.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4757047
2011-07-18 17:34:42 +10:00
Andrew Gerrand
ab55133ca9 doc: fix padding on h1 tags
See /doc/codewalk/sharemem/ for an example of how it's broken.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4742044
2011-07-18 17:30:00 +10:00
Alex Brainman
3c4ca95da9 path/filepath: fixes for windows paths
- Clean and IsAbs to handle paths with drive letter properly.
- Clean to replace / with \.

R=golang-dev, adg
CC=golang-dev, mattn.jp
https://golang.org/cl/4758051
2011-07-18 17:08:12 +10:00
Nigel Tao
95323c59ea runtime: fix panic for make(chan [0]byte).
I suspect that this was introduced by
http://code.google.com/p/go/source/detail?r=6e4ee32fffd1

R=r
CC=golang-dev
https://golang.org/cl/4764045
2011-07-18 15:54:11 +10:00
David Symonds
a8e0035bd3 http: drain the pipe output in TestHandlerPanic to avoid logging deadlock.
R=r
CC=golang-dev
https://golang.org/cl/4756047
2011-07-18 12:59:16 +10:00
Rob Pike
08e47ebb7d fmt: fix a couple of documentation glitches.
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4758050
2011-07-18 11:44:27 +10:00
Rob Pike
50d90451ff reflect: panic if Method index is out of range for a type.
Makes the code agree with the documentation.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4759050
2011-07-18 11:34:13 +10:00
Rob Pike
9d55c282e3 5c: attempt to fix build by silencing warnings about unused variables.
The story is more complicated; this is just a bandaid.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4755047
2011-07-18 11:08:55 +10:00
Quan Yong Zhai
cb051a3a1d gob: minor cleanup
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4754050
2011-07-18 10:48:31 +10:00
Rob Pike
f189308fb4 fmt: Scan(&int) was mishandling a lone zero.
It took it as an octal base prefix but assumed more digits were coming.
Fixes #2077.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4764044
2011-07-18 10:05:35 +10:00
Lucio De Re
8c5c3c504c cmd/5l/Makefile: directory prefix nit, "../5l/" is not needed.
R=golang-dev, r
CC=golang-dev, rsc
https://golang.org/cl/4755046
2011-07-18 08:46:47 +10:00
Brad Fitzpatrick
8b33c7b5be http: make tests quiet, fixing a test race
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4754044
2011-07-17 15:46:10 -07:00
Brad Fitzpatrick
6075206904 log: more locking
This didn't actually cause a bug, but looks wrong.

There was a lock but there was more shared mutable state not
guarded by it.

R=golang-dev, dsymonds, r
CC=golang-dev
https://golang.org/cl/4760047
2011-07-17 15:46:00 -07:00
Rob Pike
c705701c69 exp/templates: variable scope persists until "end".
The previous CL doicumented and diagnosed the old situation.
This one changes it to something more traditional: any action
may declare a variable, and the block structure of scopes
applies only to control seequences.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4748047
2011-07-17 13:31:59 +10:00
Rob Pike
331840f509 exp/template: allow declaration of variables only inside control structures.
In simple pipelines the declaration has no scope.
Also document the scope.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4761044
2011-07-17 12:32:00 +10:00
Russ Cox
e07c6e6ee7 http: fixes for sniffing
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4753044
2011-07-15 12:07:37 -04:00
Lucio De Re
4c6280b0f1 6a, 6c, 6l: fix for Plan 9 build
6a/a.h:
. Dropped <u.h> and <libc.h>.
. Made definition of EOF conditional.

6a/a.y:
. Added <u.h> and <libc.h>.

6a/lex.c:
. Added <u.h> and <libc.h>.
. Dropped <ctype.h> (now in <u.h>).

6c/gc.h:
. Added varargck pragma for "lD".

6c/swt.c:
. Dropped unused "thestring" argument in Bprint() calls.

6l/Makefile:
. Dropped unneeded directory prefix.

6l/l.h:
. Dropped unneeded directory prefix.
. Added varargck pragma for "I" and "i".

6l/obj.c:
. Dropped unneeded assignment.
. Dropped unreachable goto statement.

6l/pass.c:
. Dropped assignments flagged as unused.

6l/prof.c:
. Replaced "#if 0" with "#ifdef NOTDEF".

6l/span.c:
. Dropped unused incrementation.
. Added USED() as required.
. Dropped unreachable "return" statement.

R=golang-dev
CC=golang-dev, rsc
https://golang.org/cl/4747044
2011-07-15 11:58:39 -04:00
Lucio De Re
5ea4d73b17 5a, 5c, 5l: fix for Plan 9 build
5a/a.h:
. Removed <u.h> and <lib.h>.
. Made definition of EOF conditional.

5a/a.y:
. Added <u.h> and <lib.h>.

5a/lex.c:
. Added <u.h> and <lib.h>.
. Dropped <ctype.h> (now in <u.h>).

5c/peep.c:
. Removed unnecessary "return 0" statement.

5c/reg.c:
. Added compilation condition around unused code.

5c/swt.c:
. Removed unused "thestring" argument from Bprint() calls.

5l/asm.c:
. Added USED() statements as required.
. Adjusted a few format specifications.
. Added compilation condition around unused code.

5l/l.h:
. Dropped directory prefix from <../5l/5.out.h>.
. Added varargck pragma for "I" and "i".

5l/obj.c:
. Cascaded consecutive "if" statements.
. Dropped unnecessary incrementation and assignments.

5l/pass.c:
. Dropped unnecessary assignment.

5l/prof.c:
. #if 0 converted to #ifdef NOTDEF.

5l/span.c:
. Dropped unnecessary incrementation and assignments.

R=golang-dev
CC=golang-dev, rsc
https://golang.org/cl/4752041
2011-07-15 11:58:28 -04:00
Lucio De Re
0490eb60bb 8l: nits
8l/Makefile:
. Dropped unnecessary prefix from "../8l/8.out.h"

8l/l.h:
. Dropped unnecessary prefix from "../8l/8.out.h"
. Dropped unused and inconsistent "I" vararg pragma.

R=golang-dev
CC=golang-dev, rsc
https://golang.org/cl/4754041
2011-07-15 11:51:59 -04:00
Dmitriy Vyukov
491aa1579d runtime: native xadd for 386/amd64
benchmark                          old ns/op    new ns/op    delta
BenchmarkSemaUncontended               37.40        34.10   -8.82%
BenchmarkSemaUncontended-2             18.90        17.70   -6.35%
BenchmarkSemaUncontended-4             11.90        10.90   -8.40%
BenchmarkSemaUncontended-8              6.26         5.19  -17.09%
BenchmarkSemaUncontended-16             4.39         3.91  -10.93%
BenchmarkSemaSyntNonblock              38.00        35.30   -7.11%
BenchmarkSemaSyntNonblock-2            83.00        46.70  -43.73%
BenchmarkSemaSyntNonblock-4           124.00       101.00  -18.55%
BenchmarkSemaSyntNonblock-8           124.00       116.00   -6.45%
BenchmarkSemaSyntNonblock-16          148.00       114.00  -22.97%

(on HP Z600 2 x Xeon E5620, 8 HT cores, 2.40GHz)

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4755041
2011-07-15 11:27:16 -04:00
Luuk van Dijk
8cf8806d31 gc: some enhancements to printing debug info.
R=rsc
CC=golang-dev
https://golang.org/cl/4710046
2011-07-15 16:00:05 +02:00
Russ Cox
e1b2e20217 http: sniffing placeholder
R=dsymonds
CC=golang-dev
https://golang.org/cl/4746041
2011-07-15 01:01:49 -04:00
Andrew Gerrand
5d929a9c92 go/build: less aggressive failure when GOROOT not found
R=golang-dev, rsc, dsymonds
CC=golang-dev
https://golang.org/cl/4743041
2011-07-15 13:45:22 +10:00
Russ Cox
29125be5c7 runtime: make TestSideEffectOrder work twice
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4714045
2011-07-14 23:43:03 -04:00
Brad Fitzpatrick
fc7b42325a cgi: make test less flaky
Previously, during the anti-zombie test, a
CGI process had to finish within ~625ms.
Now it gets ~5.6 seconds.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4741041
2011-07-14 17:00:14 -07:00
Robert Griesemer
48f598a393 go/printer: simplify internal state
No formatting changes.

R=rsc
CC=golang-dev
https://golang.org/cl/4735042
2011-07-14 16:09:15 -07:00
Robert Griesemer
38a53c7ecb go spec: (up-)date
R=rsc, bradfitz, r
CC=golang-dev
https://golang.org/cl/4738042
2011-07-14 15:58:37 -07:00
Robert Griesemer
90564a9256 go/printer: changed max. number of newlines from 3 to 2
manual changes in src/pkg/go/printer, src/cmd/gofix/signal_test.go
(cd src/cmd/gofix/testdata; gofmt -w *.in *.out)
(cd src/pkg/go/printer; gotest -update)
gofmt -w misc src

runs all tests

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4715041
2011-07-14 14:39:40 -07:00
Russ Cox
58e19aa4cb go: require { } around else block
R=gri, ken, r
CC=golang-dev
https://golang.org/cl/4721044
2011-07-14 17:15:52 -04:00
Brad Fitzpatrick
3f53475c97 json: add omitempty struct tag option
Fixes #2032

R=rsc, dsymonds, r, r
CC=golang-dev
https://golang.org/cl/4709044
2011-07-14 11:54:55 -07:00
Robert Griesemer
8d73781f8b godoc: fix build (add Makefile change)
R=bradfitz
CC=golang-dev
https://golang.org/cl/4733041
2011-07-14 11:48:23 -07:00
Robert Griesemer
df68a61c9e godoc: support for file systems stored in .zip files
Instead of serving files of the underlying OS file system,
a .zip file may be provided to godoc containing the files
to serve; for instance:

   godoc -http=:6060 -zip=go.zip

using a .zip file created from a clean tree as follows:

   zip -r go.zip $GOROOT

R=rsc
CC=golang-dev
https://golang.org/cl/4670053
2011-07-14 11:34:53 -07:00
Luuk van Dijk
e8ff9a624f gc: fix closure bug
Fixes #2056.

R=rsc
CC=golang-dev
https://golang.org/cl/4709042
2011-07-14 18:13:39 +02:00
David Symonds
cbad580e9c json: escape < and > in any JSON string.
Angle brackets can trigger some browser sniffers, causing
some forms of JSON output to be interpreted as HTML.
Escaping angle brackets closes that security hole.

R=rsc
CC=golang-dev
https://golang.org/cl/4701047
2011-07-14 13:30:08 +10:00
Rob Pike
fc1f0bd5e9 exp/template: allow range actions to declare a key and element variable.
{{range $key, $element := pipeline}}
This CL is smaller than it looks due to some rearrangement and renaming.

R=rsc, r
CC=golang-dev
https://golang.org/cl/4709047
2011-07-14 13:15:55 +10:00
Russ Cox
aec89c4c40 mime: fix build
R=bradfitz
CC=golang-dev
https://golang.org/cl/4695060
2011-07-13 20:04:12 -07:00
David Symonds
a16ad6fe0f exp/template: escape < and > in JS escaper.
Angle brackets can trigger some browser sniffers,
causing some output to be interpreted as HTML.
Escaping angle brackets closes that security hole.

R=r
CC=golang-dev
https://golang.org/cl/4714044
2011-07-14 12:02:58 +10:00
Rob Pike
dfffc7a5d5 exp/template: include function name in error returned by function or method call.
R=golang-dev, rsc, r
CC=golang-dev
https://golang.org/cl/4711049
2011-07-14 11:32:06 +10:00
Rob Pike
19e207d24d exp/template: simplify method and function calls by using the value's Method
rather than the type's, so a method's invocation works the same as a function's.

R=golang-dev, rsc, r
CC=golang-dev
https://golang.org/cl/4704049
2011-07-14 11:00:23 +10:00
Mikio Hara
689a2ec8c3 json: allow using '$' and '-' as the struct field's tag
R=adg, rsc, bradfitz, mattn.jp, gustavo
CC=golang-dev
https://golang.org/cl/4625081
2011-07-13 17:41:33 -07:00
Rob Pike
125e8277d5 reflect: trivial addition: Value.NumMethod.
Just an oversight it was missing.

R=rsc, dsymonds, bradfitz, r
CC=golang-dev
https://golang.org/cl/4695059
2011-07-14 10:38:15 +10:00
Yuval Pavel Zholkover
0bf36ce8fb os: Plan 9: add Process.Signal as a way to send notes.
Move the Signal interface from exec_posix.go to exec.go.
Remove some unsused code from file_plan9.go.

R=fshahriar, rsc
CC=golang-dev
https://golang.org/cl/4683044
2011-07-13 16:29:37 -07:00
Alex Brainman
dde435587d runtime: correct FixedStack value (fixes windows build)
Fixes #2068.

R=rsc
CC=golang-dev
https://golang.org/cl/4705046
2011-07-14 09:13:39 +10:00
Lucio De Re
3f2cc8ba7e cc: fixes for Plan 9 build
<ctype.h> has been moved into <u.h>, specifically to be able to
drop it from these modules.

Will someone check platforms other than UBUNTU/386, please?

R=bsiegert, rsc
CC=golang-dev
https://golang.org/cl/4648078
2011-07-13 16:01:29 -07:00
Brad Fitzpatrick
8ba48fb5ca fix build from e904b6784768 breakage
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4696047
2011-07-13 15:48:57 -07:00
Russ Cox
aebfd63cd9 syscall: add Flock on Linux
Fixes #2069.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4703048
2011-07-13 15:34:36 -07:00
Russ Cox
a16baf0777 syscall: change missing from windows net fixes
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4701045
2011-07-13 15:34:21 -07:00
Robert Griesemer
f4acaa8ecd filepath/path: fix a comment
R=bradfitz
CC=golang-dev
https://golang.org/cl/4704047
2011-07-13 15:10:50 -07:00
Rob Pike
469e333106 exp/template: tweak behavior of booleans.
Russ suggested this technique, making the "and" and "or" functions handier.
But it's hacky, and I can be talked out of it.

R=dsymonds, rsc
CC=golang-dev
https://golang.org/cl/4698044
2011-07-14 07:59:04 +10:00
Rob Pike
c3344d61bd exp/template: allow niladic methods inside chained field references.
Also really fix the bug about dot vs. receivers.

R=rsc, r
CC=golang-dev
https://golang.org/cl/4705047
2011-07-14 07:52:07 +10:00
Yasuhiro Matsumoto
2012290c7e http: fix Content-Type of file extension.
ServeFile() pass empty string to serveFile(). serveFile() should get
file extension via joining root and filename.

R=bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4654089
2011-07-13 14:39:33 -07:00
Wei Guangjing
350504559e net: windows/amd64 port
R=rsc, alex.brainman
CC=golang-dev
https://golang.org/cl/3790044
2011-07-13 12:44:21 -07:00
Matthew Horsnell
932db13e93 debug/elf: Read ELF Program headers.
NewFile has been fixed to read ELF Program headers into the structs.
Added test coverage.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4628062
2011-07-13 12:34:29 -07:00
Russ Cox
ceb4377556 A+C: Matthew Horsnell (individual CLA)
R=golang-dev, iant
CC=golang-dev
https://golang.org/cl/4700044
2011-07-13 12:33:03 -07:00
Wei Guangjing
a6e60916c1 runtime: stdcall_raw stack 16byte align for Win64
R=alex.brainman, rsc
CC=golang-dev
https://golang.org/cl/4681049
2011-07-13 11:44:44 -07:00
Dmitriy Vyukov
86a659cad0 runtime: fix data race during Itab hash update/lookup
The data race is on newly published Itab nodes, which are
both unsafely published and unsafely acquired. It can
break on IA-32/Intel64 due to compiler optimizations
(most likely not an issue as of now) and on ARM due to
hardware memory access reorderings.

R=rsc
CC=golang-dev
https://golang.org/cl/4673055
2011-07-13 11:22:41 -07:00
Brad Fitzpatrick
dcdaeebdfb docs: fix wrong it's -> its
R=golang-dev, iant
CC=golang-dev
https://golang.org/cl/4702046
2011-07-13 10:54:51 -07:00
Sam Thorogood
e3a773479d exp/regexp/syntax: add Prog.NumCap
R=rsc, r
CC=golang-dev
https://golang.org/cl/4662083
2011-07-13 10:15:00 -07:00
Robert Griesemer
4c986d86b1 exp/eval, exp/ogle: remove packages eval and ogle
An externally maintained version of exp/eval can
be found at: https://bitbucket.org/binet/go-eval/ .

R=golang-dev, r, rsc
CC=golang-dev
https://golang.org/cl/4695047
2011-07-13 09:40:53 -07:00
Bobby Powers
050d839df0 gob: register more slice types
Without explicitly registering slice types, gob fails to encode
map[string]interface{} instances where the value is a slice,
failing with a message such as:

  gob: type not registered for interface: []string

Fixes #2065.

R=golang-dev, gri, r
CC=golang-dev
https://golang.org/cl/4672056
2011-07-13 17:12:17 +10:00
Nigel Tao
d360e0213d html: update section references in comments to the latest HTML5 spec.
R=r
CC=golang-dev
https://golang.org/cl/4699048
2011-07-13 16:53:02 +10:00
Rob Pike
9415cd1d79 C+A: Bobby Powers <bobbypowers@gmail.com>
R=golang-dev, dsymonds
CC=bobbypowers, golang-dev
https://golang.org/cl/4695050
2011-07-13 16:10:12 +10:00
Rob Pike
7aa1a1a64d exp/template: doc and API changes suggested by rsc.
- template invocation is by string constant only.
- NewSet is gone.
- no global Funcs
- writer is now first arg to Execute

R=rsc, r
CC=golang-dev
https://golang.org/cl/4700043
2011-07-13 15:58:31 +10:00
Rob Pike
2e9388e321 exp/template: add Set.AddSet and Set.Union.
Document and test that Set.Parse can be called multiple times.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4703044
2011-07-13 13:50:05 +10:00
Rob Pike
41efecf51c exp/template: allow variables as template names.
Just an oversight it wasn't already there.
Thanks to islandberry@live.com for pointing out the omission.

R=golang-dev, dsymonds
CC=golang-dev, islandberry
https://golang.org/cl/4703043
2011-07-13 13:21:18 +10:00
Rob Pike
c1c8d46d20 go_tutorial: change the way it's generated.
No longer do we generate HTML from it; instead the input
file is already in HTML but has template invocations to
extract programs from other files.
Delete htmlgen, which is no longer needed.
Add tmpltohtml, which runs the templating code.

R=golang-dev, dsymonds, adg
CC=golang-dev
https://golang.org/cl/4699041
2011-07-13 13:20:05 +10:00
David Anderson
f1df07bf6a 5l, 6l, 8l: Add a PT_LOAD PHDR entry for the PHDR.
Per the TIS ELF spec, if a PHDR entry is present in the
program header table, it must be part of the memory image of
the program. Failure to do this makes elflint complain, and
causes some tools that manipulate ELF to crash.

R=iant, rsc
CC=dave, golang-dev
https://golang.org/cl/4650067
2011-07-12 17:49:55 -07:00
Robert Griesemer
75780f99f4 csv: fix spelling errors in comments
Fixes #2066.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4699045
2011-07-12 17:45:29 -07:00
Russ Cox
7318664c22 tag release.r58.1: adds OS X Lion support
R=adg, dsymonds
CC=golang-dev
https://golang.org/cl/4702043
2011-07-12 17:44:59 -07:00
Quan Yong Zhai
fe9991e8b2 runtime: replace runtime.mcpy with runtime.memmove
faster string operations, and more

tested on linux/386

runtime_test.BenchmarkSliceToString                    642          532  -17.13%
runtime_test.BenchmarkStringToSlice                    636          528  -16.98%
runtime_test.BenchmarkConcatString                    1109          897  -19.12%

R=r, iant, rsc
CC=golang-dev
https://golang.org/cl/4674042
2011-07-12 17:30:40 -07:00
Andrew Gerrand
ba91dac3a9 doc: gofix io2010 demo programs
R=golang-dev, gri, r, agl
CC=golang-dev
https://golang.org/cl/4696046
2011-07-13 09:40:49 +10:00
Wei Guangjing
f340b3de5a debug/pe: fixes ImportedSymbols for Win64.
R=golang-dev, alex.brainman
CC=golang-dev
https://golang.org/cl/4639086
2011-07-12 11:29:38 -07:00
Robert Hencke
67edf9cb87 gc: make size of struct{} and [0]byte 0 bytes
Fixes #1949.

R=iant, rsc
CC=golang-dev
https://golang.org/cl/4634124
2011-07-12 11:12:06 -07:00
Dmitriy Vyukov
86e7323bdf runtime: eliminate false sharing during stack growth
Remove static variable from runtime·oldstack().
Benchmark results on HP Z600 (2 x Xeon E5620, 8 HT cores, 2.40GHz)
are as follows (with CL 4657091 applied):
benchmark                                        old ns/op    new ns/op    delta
BenchmarkStackGrowth                               1183.00      1180.00   -0.25%
BenchmarkStackGrowth-2                             1249.00      1211.00   -3.04%
BenchmarkStackGrowth-4                              954.00       805.00  -15.62%
BenchmarkStackGrowth-8                              701.00       683.00   -2.57%
BenchmarkStackGrowth-16                             465.00       415.00  -10.75%

R=rsc
CC=golang-dev
https://golang.org/cl/4693042
2011-07-12 10:56:21 -07:00
Russ Cox
88e0c0517a runtime: fix comment (lost in shuffle)
TBR=dvyukov
CC=golang-dev
https://golang.org/cl/4710041
2011-07-12 09:26:05 -07:00
Dmitriy Vyukov
c9152a8568 runtime: eliminate contention during stack allocation
Standard-sized stack frames use plain malloc/free
instead of centralized lock-protected FixAlloc.
Benchmark results on HP Z600 (2 x Xeon E5620, 8 HT cores, 2.40GHz)
are as follows:
benchmark                                        old ns/op    new ns/op    delta
BenchmarkStackGrowth                               1045.00       949.00   -9.19%
BenchmarkStackGrowth-2                             3450.00       800.00  -76.81%
BenchmarkStackGrowth-4                             5076.00       513.00  -89.89%
BenchmarkStackGrowth-8                             7805.00       471.00  -93.97%
BenchmarkStackGrowth-16                           11751.00       321.00  -97.27%

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4657091
2011-07-12 09:24:32 -07:00
Dmitriy Vyukov
daaf29cf93 sync: improve RWMutex performance
The new implementation features wait-free
fast path for readers which significantly improves
performance/scalability on read-mostly workloads.
Benchmark results on HP Z600 (2 x Xeon E5620, 8 HT cores, 2.40GHz)
are as follows:
benchmark                              old ns/op    new ns/op    delta
BenchmarkRWMutexUncontended               179.00        96.60  -46.03%
BenchmarkRWMutexUncontended-2              89.10        49.10  -44.89%
BenchmarkRWMutexUncontended-4              44.70        24.70  -44.74%
BenchmarkRWMutexUncontended-8              23.30        12.90  -44.64%
BenchmarkRWMutexUncontended-16             16.80         8.75  -47.92%
BenchmarkRWMutexWrite100                   79.60        26.80  -66.33%
BenchmarkRWMutexWrite100-2                305.00        33.00  -89.18%
BenchmarkRWMutexWrite100-4                245.00       113.00  -53.88%
BenchmarkRWMutexWrite100-8                330.00       147.00  -55.45%
BenchmarkRWMutexWrite100-16               371.00       152.00  -59.03%
BenchmarkRWMutexWrite10                    78.30        29.80  -61.94%
BenchmarkRWMutexWrite10-2                 348.00       165.00  -52.59%
BenchmarkRWMutexWrite10-4                 447.00       199.00  -55.48%
BenchmarkRWMutexWrite10-8                 564.00       180.00  -68.09%
BenchmarkRWMutexWrite10-16                492.00       192.00  -60.98%
BenchmarkRWMutexWorkWrite100             1077.00      1037.00   -3.71%
BenchmarkRWMutexWorkWrite100-2            659.00       596.00   -9.56%
BenchmarkRWMutexWorkWrite100-4            509.00       361.00  -29.08%
BenchmarkRWMutexWorkWrite100-8            603.00       351.00  -41.79%
BenchmarkRWMutexWorkWrite100-16           750.00       607.00  -19.07%
BenchmarkRWMutexWorkWrite10               990.00       951.00   -3.94%
BenchmarkRWMutexWorkWrite10-2            1119.00      1070.00   -4.38%
BenchmarkRWMutexWorkWrite10-4            1300.00      1199.00   -7.77%
BenchmarkRWMutexWorkWrite10-8            1424.00      1291.00   -9.34%
BenchmarkRWMutexWorkWrite10-16           1981.00      1786.00   -9.84%

R=rsc
CC=golang-dev
https://golang.org/cl/4671051
2011-07-12 09:24:21 -07:00
Rob Pike
4c63129545 effective go: tweak the words about semicolons, parens in control structures,
and make and new.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4699043
2011-07-12 23:45:10 +10:00
Adam Langley
9f4c288c16 hash/crc32: add SSE4.2 support
Using the CRC32 instruction speeds up the Castagnoli computation by
about 20x on a modern Intel CPU.

R=rsc
CC=golang-dev
https://golang.org/cl/4650072
2011-07-12 09:29:24 -04:00
Alex Brainman
0f8678a747 go/build: include processing of .c files for cgo packages
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4696041
2011-07-12 17:27:07 +10:00
Nigel Tao
851ded9660 image: remove superfluous if condition.
DrawMask already returns early if r.Empty().

R=r
CC=golang-dev
https://golang.org/cl/4703041
2011-07-12 17:02:55 +10:00
Nigel Tao
caaa6764fa image: re-organize draw.go.
There are no behavioral changes, only some copy-and-pastes.

Before, drawFillOver was next to drawCopyOver.

After, drawFillOver is next to drawFillSrc, which is more similar to
drawFillOver than drawCopyOver is.

Similarly, drawCopyOver is now next to drawCopySrc, etc.

R=r
CC=golang-dev
https://golang.org/cl/4695045
2011-07-12 16:56:29 +10:00
Nigel Tao
8bd5089513 image: change Pix from []FooColor to []uint8.
Some benchmark numbers below. The image/draw fast-paths show dramatic
improvement, the generic slow-paths show a smaller slow-down.

BEFORE
png.BenchmarkEncodePaletted      200       8203800 ns/op      37.45 MB/s
png.BenchmarkEncodeRGBOpaque         100      26940440 ns/op      45.61 MB/s
png.BenchmarkEncodeRGBA       20      73821000 ns/op      16.65 MB/s
jpeg.BenchmarkEncodeRGBOpaque         50      35598640 ns/op      34.52 MB/s
draw.BenchmarkFillOver	     500	   4024226 ns/op
draw.BenchmarkFillSrc	   10000	    152736 ns/op
draw.BenchmarkCopyOver	     500	   3452824 ns/op
draw.BenchmarkCopySrc	   50000	     73218 ns/op
draw.BenchmarkNRGBAOver	     500	   3941234 ns/op
draw.BenchmarkNRGBASrc	    1000	   2484400 ns/op
draw.BenchmarkYCbCr	    1000	   2609005 ns/op
draw.BenchmarkGlyphOver	    2000	   1169575 ns/op
draw.BenchmarkRGBA	     200	   9031390 ns/op
draw.BenchmarkGenericOver	      50	  34636620 ns/op
draw.BenchmarkGenericMaskOver	     100	  16561150 ns/op
draw.BenchmarkGenericSrc	     100	  13873760 ns/op
draw.BenchmarkGenericMaskSrc	     100	  25198860 ns/op

AFTER
png.BenchmarkEncodePaletted      200       8206600 ns/op      37.43 MB/s
png.BenchmarkEncodeRGBOpaque         100      26129530 ns/op      47.03 MB/s
png.BenchmarkEncodeRGBA       20      75776750 ns/op      16.22 MB/s
jpeg.BenchmarkEncodeRGBOpaque         50      37192940 ns/op      33.04 MB/s
draw.BenchmarkFillOver	     500	   3008134 ns/op
draw.BenchmarkFillSrc	   10000	    154214 ns/op
draw.BenchmarkCopyOver	    1000	   2169988 ns/op
draw.BenchmarkCopySrc	   50000	     73095 ns/op
draw.BenchmarkNRGBAOver	    1000	   2491079 ns/op
draw.BenchmarkNRGBASrc	    2000	   1361244 ns/op
draw.BenchmarkYCbCr	    1000	   2554269 ns/op
draw.BenchmarkGlyphOver	    2000	   1042225 ns/op
draw.BenchmarkRGBA	     100	  10233340 ns/op
draw.BenchmarkGenericOver	      50	  38421560 ns/op
draw.BenchmarkGenericMaskOver	     100	  17521190 ns/op
draw.BenchmarkGenericSrc	     100	  16351200 ns/op
draw.BenchmarkGenericMaskSrc	     100	  26538190 ns/op

R=r
CC=golang-dev
https://golang.org/cl/4675076
2011-07-12 16:39:38 +10:00
Nigel Tao
6ec6f1ef62 image/draw: add benchmarks.
R=r
CC=golang-dev
https://golang.org/cl/4695043
2011-07-12 16:17:02 +10:00
Russ Cox
1002e82fff doc: document r58.1
R=adg, dsymonds
CC=golang-dev
https://golang.org/cl/4700041
2011-07-12 01:39:09 -04:00
Dmitriy Vyukov
013ad89c9b runtime: eliminate false sharing on runtime.goidgen
runtime.goidgen can be quite frequently modified and
shares cache line with the following variables,
it leads to false sharing.
50c6b0 b nfname
50c6b4 b nfunc
50c6b8 b nfunc$17
50c6bc b nhist$17
50c6c0 B runtime.checking
50c6c4 B runtime.gcwaiting
50c6c8 B runtime.goidgen
50c6cc B runtime.gomaxprocs
50c6d0 B runtime.panicking
50c6d4 B strconv.IntSize
50c6d8 B src/pkg/runtime/_xtest_.ss
50c6e0 B src/pkg/runtime/_xtest_.stop
50c6e8 b addrfree
50c6f0 b addrmem
50c6f8 b argv

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4673054
2011-07-12 01:25:14 -04:00
Dmitriy Vyukov
909f31872a runtime: eliminate false sharing on random number generators
Use machine-local random number generator instead of
racy global ones.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4674049
2011-07-12 01:23:58 -04:00
Dmitriy Vyukov
f9f21aa1fb runtime: fix data race on runtime·maxstring
The data race can lead to erroneous output of
"[invalid string]" instead of a string.

R=golang-dev
CC=golang-dev
https://golang.org/cl/4678049
2011-07-12 01:21:06 -04:00
Alex Brainman
8ed9fc600c 6l: change default output name to 6.out.exe on windows
R=golang-dev, vcc.163
CC=golang-dev
https://golang.org/cl/4670049
2011-07-12 14:22:48 +10:00
Brad Fitzpatrick
ce3c3953be http: support for periodic flushing in ReverseProxy
Fixes #2012

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4662091
2011-07-11 20:56:21 -07:00
Rob Pike
7c47741811 exp/template: make numbers adhere to Go's rules for ideal constants.
Without further type informatnion, 1.0 is a float and an integer
must fit in an int.

R=rsc
CC=golang-dev
https://golang.org/cl/4696042
2011-07-12 13:15:26 +10:00
Alex Brainman
05c89edcd3 go/build: make Nuke comment say what it does
R=rsc
CC=golang-dev
https://golang.org/cl/4697041
2011-07-12 13:08:22 +10:00
Andrew Gerrand
87d71a3815 codereview: fix for Mercurial 1.9
R=golang-dev, mirtchovski, mikioh.mikioh
CC=golang-dev
https://golang.org/cl/4686049
2011-07-11 22:58:40 -04:00
Yasuhiro Matsumoto
34bac8bcd4 doc: don't specify make target for working on windwos.
makehtml does not work on windows.

R=golang-dev, adg, rsc
CC=golang-dev
https://golang.org/cl/4675041
2011-07-11 20:02:32 -04:00
Andrew Gerrand
b4f0e8ffd3 undo CL 4675045 / 0e11e08951f7
Breaks Mercurial 1.8.3.

««« original CL description
codereview: fix for Mercurial 1.9

Fixes #2038.

R=rsc, bobbypowers
CC=golang-dev
https://golang.org/cl/4675045
»»»

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4685055
2011-07-12 09:57:39 +10:00
Andrew Gerrand
762ea79057 codereview: fix for Mercurial 1.9
Fixes #2038.

R=rsc, bobbypowers
CC=golang-dev
https://golang.org/cl/4675045
2011-07-12 09:36:46 +10:00
Brad Fitzpatrick
1722ec22cd cgi: close stdout reader pipe when finished
This causes the child, if still writing, to get an error or
SIGPIPE and most likely exit so our subsequent wait can
finish.

A more guaranteed fix would be putting a time limit on the
child's overall execution, but this fixes the problem
I was having.

Fixes #2059

R=rsc
CC=golang-dev
https://golang.org/cl/4675081
2011-07-11 15:59:27 -07:00
Brad Fitzpatrick
d53385fd0c os: don't permit Process.Signal after a successful Wait
R=dsymonds, rsc
CC=golang-dev
https://golang.org/cl/4689043
2011-07-11 15:47:42 -07:00
Brad Fitzpatrick
d1f4e0d14e exec: closeAfterWait append bug
Wasn't actually eager closing the fds as a result of the
copy/paste bug. (GC was doing it instead)

R=rsc
CC=golang-dev
https://golang.org/cl/4671057
2011-07-11 14:46:46 -07:00
Evan Martin
2f69a73591 json: encode \r and \n in strings as e.g. "\n", not "\u000A"
This is allowed by the JSON spec and is shorter/easier to read.

R=golang-dev, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4678046
2011-07-11 07:31:08 -07:00
Brad Fitzpatrick
f19b24a182 strconv: handle [-+]Infinity in atof
This is the form as returned by Postgres, as well
as JavaScript.

I've tried and failed to find authorative docs online
about the proper string serialization, if any.

R=golang-dev, gri, r, r, rsc
CC=golang-dev
https://golang.org/cl/4650077
2011-07-11 07:25:45 -07:00
Rob Pike
d366c36945 exp/template: fix bug in argument evaluation.
Must keep dot and the receiver separate - variables broke that symmetry.
Also clean up function invocation and rename "data" to "dot" for clarity.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4678048
2011-07-11 18:06:24 +10:00
Alex Brainman
3c6a7b3fc5 go/build: use os.MkdirAll to create directories
Replaces "mkdir -p ..." command, as Windows mkdir command
does not support -p flag. Also, is simpler and faster then
launching new process.

R=golang-dev, mattn.jp, adg, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4626087
2011-07-11 15:40:41 +10:00
Rob Pike
7b79b3b244 exp/template: fields and methods on variables.
Not strictly necessary (you could achieve the same, clumsily,
via with blocks) but great to have: $x.Field, $y.Method.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4678047
2011-07-11 15:23:38 +10:00
Rob Pike
96bbcc4256 exp/template: documentation glitches and typos.
Also explain that len(v)==0 makes v a 'zero value'
in template execution.

R=golang-dev, dsymonds, adg, r
CC=golang-dev
https://golang.org/cl/4691041
2011-07-11 14:43:21 +10:00
Rob Pike
0027dc91b0 exp/template: simpler parse of char constants.
We can avoid the check against empty constants (''),
which UnquoteChar doesn't handle well, by leaving on
the trailing quote and seeing that's all we have left at the end.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4657090
2011-07-11 12:36:10 +10:00
Rob Pike
bf9531f80b exp/template: character constants.
Easier to implement than to justify leaving them out.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4662089
2011-07-11 11:46:22 +10:00
Rob Pike
e7030e7fef exp/template: static check for defined variables.
Worth catching at parse time rather than execution. Plus it's really easy.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4641100
2011-07-11 10:01:15 +10:00
Rob Pike
1fe9c9a78f exp/eval: delete binary
Mistakenly checked in.
Fixes #2058.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4670057
2011-07-11 09:36:17 +10:00
Rob Pike
e44853c969 flag: make -help nicer.
- suppress the print that -help is not defined.
- return a special error code if -help is set
- do not change behavior if an explict "help" flag is defined.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4641099
2011-07-11 09:35:50 +10:00
Rob Pike
abae847134 exp/template: add functions print and println.
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4687041
2011-07-11 09:19:18 +10:00
Rob Pike
4acddca41b exp/template: package documentation
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4675072
2011-07-10 20:56:26 +10:00
Nigel Tao
87d9e7e166 image: change Pix[0] to mean top-left corner of an image's Rect instead
of the origin.

image/png and image/jpeg benchmarks show no significant changes.

The image/draw changes suggest to me that making a gofix for this is not
feasible. People are just going to have to make manual fixes.

R=r
CC=golang-dev
https://golang.org/cl/4681044
2011-07-10 14:29:47 +10:00
Andrew Gerrand
4d47600f46 archive/zip: add Writer
R=bradfitz, dchest, r, rsc
CC=golang-dev
https://golang.org/cl/4523077
2011-07-10 11:30:16 +10:00
Evan Martin
e45b3213cd multipart: use textproto to handle multiline header
R=bradfitz
CC=golang-dev
https://golang.org/cl/4686044
2011-07-09 15:18:31 -07:00
Brad Fitzpatrick
658a02a50c CONTRIBUTORS: add Evan Martin (Google CLA)
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4657089
2011-07-09 15:18:18 -07:00
Andrew Balholm
b053400e37 http: update triv.go with gofix
Sample code in triv.go wouldn't compile because it didn't use the new
FileSystem interface.
This was discussed on golang-nuts on July 7.
https://groups.google.com/forum/#!topic/golang-nuts/NMhZk3Ft_Vc

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4684044
2011-07-09 15:10:39 -07:00
Rob Pike
3987b91213 exp/template: better template invocation
1) Make the value optional ({{template "foo"}})
2) Allow the template identifier to be a thing of type *Template.
The second makes it easy to drop templates in to a set dynamically
during invocation.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4671056
2011-07-10 07:32:01 +10:00
Rob Pike
c17347eea9 tutorial: remove all line numbers and references to them.
R=golang-dev, mikioh.mikioh, dsymonds
CC=golang-dev
https://golang.org/cl/4675070
2011-07-09 23:17:38 +10:00
Mikio Hara
ab3365d34e doc/progs: gofmt -w
R=r, gri, r
CC=golang-dev
https://golang.org/cl/4662085
2011-07-09 20:16:45 +10:00
Rob Pike
e86d727e60 exp/template: vars as arguments to functions and methods.
That should be it, bugs aside.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4671055
2011-07-09 17:11:35 +10:00
Rob Pike
58baf64827 exp/template: variable evaluation.
Still need to do static checking of declarations during parse.

R=golang-dev, dsymonds, r
CC=golang-dev
https://golang.org/cl/4667070
2011-07-09 12:05:39 +10:00
Rob Pike
bbf5eb5ba2 exp/template: delete upward evaluation.
It was an ill-advised carryover from the previous template package.
Also clean up function evaluation.
Also add a Name method to Template.

R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4657088
2011-07-09 08:59:56 +10:00
Rob Pike
d3d08e1e3a exp/template: forgot to allow . as a function argument
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4671053
2011-07-08 18:25:46 +10:00
Rob Pike
b8c664297b exp/template: parse variables and declarations
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4631099
2011-07-08 17:54:16 +10:00
Rob Pike
ee14989e43 exp/template: lex variables
Variables start with'$' and are declared with ':='.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4662084
2011-07-08 17:53:55 +10:00
Rob Pike
02039b6345 exp/template: add a tree-walking example to the test.
Also fix a comment formatting glitch.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4672054
2011-07-08 16:49:06 +10:00
Andrew Gerrand
ad58dc9d26 exp/template: the must-have MustParse functions
R=r
CC=golang-dev
https://golang.org/cl/4641096
2011-07-08 16:01:32 +10:00
Rob Pike
a852981d17 exp/template: allow fields and methods to be found in parent structs.
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4657085
2011-07-08 15:22:05 +10:00
Andrew Gerrand
6f4cf3999b tag weekly.2011-07-07
R=r
CC=golang-dev
https://golang.org/cl/4664066
2011-07-08 13:30:49 +10:00
Andrew Gerrand
4f03ef7993 weekly.2011-07-07
R=golang-dev, dsymonds, r
CC=golang-dev
https://golang.org/cl/4668061
2011-07-08 13:13:38 +10:00
Andrew Gerrand
5bcbcab311 sort: rename helpers: s/Sort// in sort.Sort[Float64s|Ints|Strings]
Includes 'sorthelpers' gofix and updates to tree.

R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4631098
2011-07-08 10:52:50 +10:00
David Symonds
e67a2504a1 gob: export fields in structs in the package documentation.
R=r
CC=golang-dev
https://golang.org/cl/4648075
2011-07-08 10:51:56 +10:00
Brad Fitzpatrick
3236097ab0 cgi: don't depend on CGI.pm for tests
CGI.pm used to be part of the Perl core,
but some distros now bundle perl-core
and perl-modules separately.

It's not worth depending on.

R=golang-dev, mattn.jp
CC=golang-dev
https://golang.org/cl/4675063
2011-07-07 17:45:28 -07:00
Nigel Tao
b39afde805 image/draw: add draw tests where the destination image doesn't start
at (0, 0).

Also refactor the test to use the SubImage method rather than monkeying
with an image's Pix and Rect fields.

R=r
CC=golang-dev
https://golang.org/cl/4678045
2011-07-08 09:54:21 +10:00
Adam Langley
d1d466f620 crypto/x509: prevent chain cycles in Verify
It's possible to include a self-signed root certificate as an
intermediate and push Verify into a loop.

I already had a test for this so I thought that it was ok, but it
turns out that the test was void because the Verisign root certificate
doesn't contain the "IsCA" flag and so it wasn't an acceptable
intermediate certificate for that reason.

R=bradfitz
CC=golang-dev
https://golang.org/cl/4657080
2011-07-07 18:06:50 -04:00
Brad Fitzpatrick
141f676bab doc: remove ed from apt-get package list
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4672052
2011-07-07 13:45:13 -07:00
Nigel Tao
03f987c8ea image: tighten Paletted.Opaque to check only those palette entries
in the image, not all palette entries.

R=r
CC=golang-dev
https://golang.org/cl/4672049
2011-07-07 16:32:19 +10:00
Rob Pike
07c9a92564 os: fix documentation for FileInfo.Name.
It's the base name, not the full name.
Fixes #2047.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4680041
2011-07-07 16:05:38 +10:00
Rob Pike
238274ede0 exp/template: handle pointers and values in empty interfaces.
R=golang-dev, r, mattn.jp
CC=golang-dev
https://golang.org/cl/4664064
2011-07-07 14:51:35 +10:00
Rob Pike
8d538c6d3d exp/template: change the name from 'metacharacter' to 'delimiter',
because that's what they are.
No semantic change.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4675060
2011-07-07 10:56:33 +10:00
Gideon Jan-Wessel Redelinghuys
582d6e5848 crypto/openpgp: fixed dangerous use of for loop variable
In function readSignedMessage a pointer to for loop variable 'key' was incorrectly being assigned
to md.SignedBy. Changed so that md.SignedBy is pointing to the 'more correct' memory position.

R=golang-dev, r, agl
CC=golang-dev
https://golang.org/cl/4631088
2011-07-07 10:49:03 +10:00
Rob Pike
7875ecb462 C+A: Gideon Jan-Wessel Redelinghuys
R=golang-dev, dsymonds
CC=gjredelinghuys, golang-dev
https://golang.org/cl/4675059
2011-07-07 10:46:54 +10:00
Alex Brainman
e71fc0c1fe syscall: rearrange windows code so 386 and amd64 can share files
R=golang-dev, r
CC=golang-dev, vcc.163
https://golang.org/cl/4641093
2011-07-07 10:40:45 +10:00
Rob Pike
ae19943e2b CONTRIBUTORS: add Google contributor mpvl@golang.org
R=golang-dev, dsymonds
CC=golang-dev, mpvl
https://golang.org/cl/4643075
2011-07-07 10:35:37 +10:00
Rob Pike
46ecd6f141 exp/template: index: forgot the always last-to-arrive uintptr.
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4636087
2011-07-07 07:00:48 +10:00
Adam Langley
1aa571d38b asn1: support T61 and UTF8 string.
There is no end to the kitchen sink of string types in ASN.1.

Fixes #1953.

R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4672045
2011-07-06 16:25:44 -04:00
Adam Langley
502589e030 crypto/tls: fix generate_cert.go
Fixes #2030.

R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4635092
2011-07-06 16:22:21 -04:00
Ian Lance Taylor
7b0bb48056 json: fix test if rand returns 0.
Fixes test when run with gccgo using optimization, which
changes the order of the calls to rand.

R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4639101
2011-07-06 13:00:54 -07:00
Rob Pike
6732bd3526 exp/template: index function for arrays, slices, and maps.
R=golang-dev, adg, r
CC=golang-dev
https://golang.org/cl/4643072
2011-07-06 22:27:06 +10:00
Rob Pike
64228e36a4 exp/template: silence test noise (but add a flag to put it back)
Also delete a TODO and clean up a little evaluation code.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4643071
2011-07-06 17:46:36 +10:00
David Symonds
33705ddea1 exp/template: add a JavaScript escaper.
R=r
CC=golang-dev
https://golang.org/cl/4671048
2011-07-06 16:51:49 +10:00
Rob Pike
a33cc423b4 exp/template: allow an empty interface value to be the target of range, etc.
We extract the concrete value inside.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4677041
2011-07-06 16:40:46 +10:00
Rob Pike
381a555f40 exp/template: improve error message for non-exported field.
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4636086
2011-07-06 15:56:39 +10:00
Rob Pike
a8e5db9449 maketables: update debugging data.
This is unused in the generation of the tables, but was incorrect if we ever needed it.
Also update the reference to the document.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4626097
2011-07-06 15:35:23 +10:00
David Symonds
9d5ed1744a exp/template: add missing dotNode case.
R=r
CC=golang-dev
https://golang.org/cl/4672044
2011-07-06 15:14:10 +10:00
Rob Pike
9495dd31d2 exp/template: fixes and updates.
- fix line numbers - forgot to update state.line during execution
- add a comment convention {{/* comment */}}
- set.Template returns the named template in the set
- set.Execute executes the named template in the set
- use a local methodByName so this package can be used with earlier release of reflect.
- use initial cap to detect exported names

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4668054
2011-07-06 14:46:41 +10:00
David Symonds
d45ba2c146 exp/template: remove debugging dreg.
R=r, gri
TBR=r
CC=golang-dev
https://golang.org/cl/4671047
2011-07-06 14:18:46 +10:00
Yasuhiro Matsumoto
1e6d946594 html: parse start tags that aren't explicitly otherwise dealt with.
R=golang-dev, nigeltao
CC=golang-dev
https://golang.org/cl/4626080
2011-07-06 13:08:52 +10:00
Rob Pike
329990d525 exp/template: remove the need for a goroutine.
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4626095
2011-07-06 11:02:53 +10:00
Rob Pike
4657d7d7db exp/template: remove the visibility of the token channel from the parser.
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4675053
2011-07-06 10:13:53 +10:00
Luuk van Dijk
13d048a221 gc: fix %N for OGOTO nodes.
6g -W crashed on any source with a goto. this fixes that.

R=rsc, r
CC=golang-dev
https://golang.org/cl/4675052
2011-07-06 00:02:03 +02:00
Rob Pike
eea5443572 exp/template: add templates to sets; boolean logic.
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4670045
2011-07-05 17:05:15 +10:00
Andrew Gerrand
b7db4fef22 godoc: ignore directories that begin with '.'
Fixes #2017.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4675047
2011-07-05 17:00:18 +10:00
Rob Pike
5b1658232e exp/template: statically check that functions names have been defined.
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4675046
2011-07-05 16:02:34 +10:00
Fazlul Shahriar
bedee318d5 os: fix build for Plan 9
R=golang-dev, alex.brainman
CC=golang-dev
https://golang.org/cl/4657074
2011-07-05 16:01:29 +10:00
Rob Pike
cc9fed7c1a exp/template: add an html escaping function.
R=golang-dev, dsymonds, adg
CC=golang-dev
https://golang.org/cl/4626092
2011-07-05 15:58:54 +10:00
Nigel Tao
104f57ad39 image: add a test for filling sub-images.
R=r
CC=golang-dev
https://golang.org/cl/4626091
2011-07-05 14:42:31 +10:00
Rob Pike
b177c97803 exp/template: functions
Add the ability to attach functions to template and template sets.
Make variadic functions and methods work.
Still to come: static checking of function names during parse.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4643068
2011-07-05 14:23:51 +10:00
Rob Pike
9cf37c3723 docs: fold the prog.sh scripting from makehtml into htmlgen itself.
This allows us to drop some crufty scripting and provides a firmer
footing for building better tools for preparing documents with source
code inside.

Also eliminate line numbers from the examples and text.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4650069
2011-07-04 16:15:14 +10:00
Andrew Gerrand
a342006207 goinstall: only report successfully-installed packages to the dashboard
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4657071
2011-07-04 16:05:11 +10:00
Rob Pike
13f889778e exp/template: add template sets, allowing templates to reference one another
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4673042
2011-07-04 15:15:47 +10:00
Rob Pike
72efdea20e exp/template: allow complex numbers, add 'with', 'define', and 'template' keywords.
Also simplify the handling of keywords.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4639096
2011-07-04 11:50:35 +10:00
Rob Pike
db0e358022 reflect: allow Len on String values.
It's probably just an oversight that it doesn't work,
perhaps caused by analogy with Cap.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4634125
2011-07-04 11:45:31 +10:00
Andrew Gerrand
8c7a73bbbb go/build: evaluate symlinks before comparing path to GOPATH
R=golang-dev, r, dsymonds
CC=golang-dev
https://golang.org/cl/4645078
2011-07-04 10:26:03 +10:00
Andrew Gerrand
3cd8f27d79 godoc: search GOPATH for documentation
R=rsc, mattn.jp
CC=golang-dev
https://golang.org/cl/4627065
2011-07-02 14:07:06 +10:00
Andrew Gerrand
72a73198df goinstall: documentation for new remote repository behavior and tweaks
R=rsc, julian
CC=golang-dev
https://golang.org/cl/4642049
2011-07-02 14:05:43 +10:00
Andrew Gerrand
6a2e2432c9 dashboard: show build state and package comments on dashboard
This permits full URLs to be shown on the dashboard,
not just the repository roots.

This has been tested.

R=rsc, mattn.jp
CC=golang-dev
https://golang.org/cl/4627081
2011-07-02 14:02:42 +10:00
Adam Langley
acc284d847 crypto/openpgp: add ability to reserialize keys.
This changes Signature so that parsed signatures can be reserialized
exactly. With this ability we can add Serialize to Entity and also the
ability to sign other public keys.

R=bradfitz
CC=golang-dev
https://golang.org/cl/4627084
2011-07-01 13:53:12 -04:00
Paul Borman
00f7cd4b36 csv: new package
csv reader/writer based on RFC 4180

R=rsc, mattn.jp, r, dchest
CC=golang-dev
https://golang.org/cl/4629085
2011-07-01 12:16:56 -04:00
Russ Cox
21752bc130 CONTRIBUTORS: add Paul Borman (Google CLA)
R=borman, bradfitz
CC=golang-dev
https://golang.org/cl/4654079
2011-07-01 12:09:53 -04:00
Russ Cox
1eb656784c 5c, 6c: fix build
R=ken2
CC=golang-dev
https://golang.org/cl/4668049
2011-07-01 11:13:38 -04:00
Alex Brainman
810a2dc077 lib9: stop build if ../version.bash fails
R=golang-dev, m, rsc
CC=golang-dev
https://golang.org/cl/4639091
2011-07-01 10:42:25 -04:00
Wei Guangjing
63b8b948d9 windows: define and use syscall.Handle
Fixes #1487.

R=rsc, alex.brainman, go.peter.90, mikioh.mikioh, mattn.jp
CC=golang-dev
https://golang.org/cl/4600042
2011-07-01 10:18:07 -04:00
Yasuhiro Matsumoto
21efa147ba cmd/goinstall: try to access via https.
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4667051
2011-07-01 10:11:33 -04:00
Lucio De Re
b0449c50f7 8c: fixes for Plan 9 build
8c/gc.h:
. Added <u.h> header.
. Added "lD" pragma for "*Adr" to supplement "D".

8c/swt.c:
. Removed unreferenced "thestring" arguments in Bprint() calls.

cc/acid.c:
cc/com.c:
cc/com64.c:
cc/dcl.c:
cc/scon.c:
. Added <u.h>, required by "cc.h".

cc/bits.c:
. Added <u.h>, required by "cc.h".

cc/cc.h:
. Removed <u.h> and <ctype.h>.
. Added "O" pragma to accept "uint" as well as "int".
. Added new "U" pragma (char *).

cc/cc.y:
. Added <u.h> before <stdio.h> (and "cc.h").

cc/dpchk.c:
cc/mac.c:
. Added <u.h> and <ctype.h>.

cc/funct.c:
. Added <u.h>, required by "cc.h".

cc/godefs.c
. Added <u.h>, required by "cc.h".
. Dropped unused "t" argument in Bprint().

cc/lex.c:
. Added <u.h> and <ctype.h>.
. Removed unnecessary incrementation.
. Changed exit() invocations with exits().

cc/omachcap.c:
. Added <u.h>, required by "cc.h".
. USED(n) for unused argument to machcap().

cc/sub.c:
. Added <u.h> and <ctype.h>.

R=rsc
CC=golang-dev
https://golang.org/cl/4629070
2011-07-01 09:50:24 -04:00
Brad Fitzpatrick
3aa8272e44 fix build; add simplify.go to regexp Makefile
R=rsc
CC=golang-dev
https://golang.org/cl/4643062
2011-06-30 10:45:36 -07:00
Yasuhiro Matsumoto
2f9fbad043 http/cgi: add Handler.Dir to specify working directory
R=golang-dev, bradfitz, alex.brainman
CC=golang-dev
https://golang.org/cl/4635042
2011-06-30 09:44:23 -07:00
Dmitriy Vyukov
dd2074c82a sync: improve Mutex to allow successive acquisitions
This implementation allows a goroutine to do successive acquisitions
of a mutex even if there are blocked goroutines.
Moreover, it allows a newcomer goroutine to acquire a mutex ahead of
blocked goroutines (that is, it does not enforce FIFO).
On implementation level it's achieved by separating waiter count and
locked flag.
Benchmark results on HP Z600 (2 x Xeon E5620, 8 HT cores, 2.40GHz)
are as follows (with 4631059 "replace Semacquire/Semrelease implementation"
patch applied):
benchmark                                        old ns/op    new ns/op    delta
sync_test.BenchmarkMutexUncontended                  24.10        25.40   +5.39%
sync_test.BenchmarkMutexUncontended-2                12.00        13.00   +8.33%
sync_test.BenchmarkMutexUncontended-4                 6.06         6.83  +12.71%
sync_test.BenchmarkMutexUncontended-8                 3.63         3.60   -0.83%
sync_test.BenchmarkMutexUncontended-16                2.38         2.49   +4.62%

sync_test.BenchmarkMutex                             25.00        26.40   +5.60%
sync_test.BenchmarkMutex-2                          231.00        49.00  -78.79%
sync_test.BenchmarkMutex-4                          259.00       114.00  -55.98%
sync_test.BenchmarkMutex-8                          641.00       110.00  -82.84%
sync_test.BenchmarkMutex-16                        1380.00        96.30  -93.02%

sync_test.BenchmarkMutexSlack                        24.80        26.20   +5.65%
sync_test.BenchmarkMutexSlack-2                     210.00       106.00  -49.52%
sync_test.BenchmarkMutexSlack-4                     453.00       119.00  -73.73%
sync_test.BenchmarkMutexSlack-8                    1024.00       105.00  -89.75%
sync_test.BenchmarkMutexSlack-16                   1291.00        91.90  -92.88%

sync_test.BenchmarkMutexWork                        796.00       796.00   +0.00%
sync_test.BenchmarkMutexWork-2                      399.00       401.00   +0.50%
sync_test.BenchmarkMutexWork-4                      216.00       212.00   -1.85%
sync_test.BenchmarkMutexWork-8                     1547.00       196.00  -87.33%
sync_test.BenchmarkMutexWork-16                    2754.00       287.00  -89.58%

sync_test.BenchmarkMutexWorkSlack                   792.00       800.00   +1.01%
sync_test.BenchmarkMutexWorkSlack-2                 430.00       420.00   -2.33%
sync_test.BenchmarkMutexWorkSlack-4                 467.00       230.00  -50.75%
sync_test.BenchmarkMutexWorkSlack-8                1860.00       273.00  -85.32%
sync_test.BenchmarkMutexWorkSlack-16               3029.00       294.00  -90.29%

R=rsc
CC=golang-dev
https://golang.org/cl/4631075
2011-06-30 11:13:29 -04:00
Russ Cox
b4cae4aee2 exp/regexp/syntax: finish Regexp manipulation
Except for the inevitable bug fixes, the Regexp code is done.

R=sam.thorogood, r
CC=golang-dev
https://golang.org/cl/4635082
2011-06-30 10:26:22 -04:00
Russ Cox
a809abafa5 govet: automate test
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4629084
2011-06-30 10:26:11 -04:00
Yasuhiro Matsumoto
054cf72b56 html: fix nesting when parsing a close tag.
R=nigeltao
CC=golang-dev
https://golang.org/cl/4636067
2011-06-30 23:16:33 +10:00
Julian Phillips
8ffbc4016a goinstall: Add support for generic hosts using special import form
This change extends goinstall to support "magic" package names of the
form:
        <host>/<repo>.<vcs>/<path>

Where <host> is the hostname, <repo> the path to the repository, <vcs>
the type of vcs (git, hg, bzr or svn), and <path> is the path inside the
repository that contains the source code for the package.

For example: "example.com/pub/foo.hg/src" means download the Mercurial
repository at either pub/foo.hg or pub/foo from example.com and then
build and install the source files from src inside the repository
checkout.

Repositories on the built-in hostings sites (github, bitbucket,
launchpad and googlecode) must still use the old form (i.e.
github.com/xxx/yyy.git/src will be rejected).

R=adg, rsc
CC=golang-dev
https://golang.org/cl/4626064
2011-06-30 18:54:53 +10:00
Yasuhiro Matsumoto
369418d29c misc/vim: allow only utf-8 for fileencoding (fix CL4625078).
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4650062
2011-06-30 17:07:44 +10:00
Yasuhiro Matsumoto
51a79d0306 misc/vim: allow only utf-8 for fileencoding.
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4625078
2011-06-30 16:19:53 +10:00
Andrew Gerrand
4dfdacd2bd build: make version.bash aware of branches
Fixes #2026.

R=bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4645074
2011-06-30 15:39:00 +10:00
Brad Fitzpatrick
73896bdc85 net: break up and simplify Dial a bit
No API or functional change.

R=jacek.masiulaniec, mikioh.mikioh, rsc
CC=golang-dev
https://golang.org/cl/4630081
2011-06-29 21:56:13 -07:00
Rob Pike
de36d19dfb time: zero-pad two-digit years.
Fixes #2024

R=adg, dsymonds
CC=golang-dev
https://golang.org/cl/4635083
2011-06-30 14:05:29 +10:00
David Symonds
ba8e61d833 os: use a different symbol from syscall in mkunixsignals.sh.
Open is more likely to be present than Syscall.

R=rsc
CC=golang-dev
https://golang.org/cl/4645073
2011-06-30 13:35:40 +10:00
Brad Fitzpatrick
d980f538d7 http: document that ServerConn and ClientConn are low-level
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4635081
2011-06-29 18:23:38 -07:00
Andrew Gerrand
121775f2c8 tag release.r58
R=rsc
CC=golang-dev
https://golang.org/cl/4634113
2011-06-30 09:59:44 +10:00
Andrew Gerrand
f81d81ca3f document release.r58
R=rsc, r, bsiegert
CC=golang-dev
https://golang.org/cl/4643058
2011-06-30 09:45:10 +10:00
Alex Brainman
7cc5d5db9d run.bash: small fix
Fixes #2025.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4636075
2011-06-30 09:44:16 +10:00
Andrew Balholm
7983ab9d1a http: make NewChunkedReader public
R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4634112
2011-06-29 12:27:53 -07:00
Brad Fitzpatrick
45f956ab82 C+A: add Andy Balholm
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4630080
2011-06-29 11:46:06 -07:00
Russ Cox
b2127a6c99 testing: make ResetTimer not start/stop the timer
R=r
CC=golang-dev
https://golang.org/cl/4626085
2011-06-29 10:26:16 -04:00
Russ Cox
25733a94fd reflect: support for struct tag use by multiple packages
Each package using struct field tags assumes that
it is the only package storing data in the tag.
This CL adds support in package reflect for sharing
tags between multiple packages.  In this scheme, the
tags must be of the form

        key:"value" key2:"value2"

(raw strings help when writing that tag in Go source).

reflect.StructField's Tag field now has type StructTag
(a string type), which has method Get(key string) string
that returns the associated value.

Clients of json and xml will need to be updated.
Code that says

        type T struct {
                X int "name"
        }

should become

        type T struct {
                X int `json:"name"`  // or `xml:"name"`
        }

Use govet to identify struct tags that need to be changed
to use the new syntax.

R=r, r, dsymonds, bradfitz, kevlar, fvbommel, n13m3y3r
CC=golang-dev
https://golang.org/cl/4645069
2011-06-29 09:52:34 -04:00
Wei Guangjing
f83609f642 runtime: windows/amd64 port
R=rsc, alex.brainman, hectorchu, r
CC=golang-dev
https://golang.org/cl/3759042
2011-06-29 17:37:56 +10:00
Robert Hencke
83550f0728 gofix: fixes for os/signal changes
Fixes #1971.

R=adg, rsc
CC=golang-dev
https://golang.org/cl/4630056
2011-06-29 16:44:47 +10:00
Rob Pike
d6f80e1a4c regexp: document that Regexp is thread-safe.
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4667047
2011-06-29 15:41:09 +10:00
Rob Pike
c756a1954c exp/template: boolean constants
R=rsc
CC=golang-dev
https://golang.org/cl/4628073
2011-06-29 15:02:04 +10:00
Russ Cox
7e1a3e9f20 exp/regexp/syntax: incremental concat, alternate
Also reuse of *Regexp nodes.

I believe this is the end of the parser.
The only non-execution code that remains is
the code to expand x{3,5} into simpler operations.

R=sam.thorogood, r
CC=golang-dev
https://golang.org/cl/4629078
2011-06-29 00:55:37 -04:00
Russ Cox
3379414b21 codereview: restrict sync to default branch
'default' is the name of the main branch,
the one that isn't a release branch.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4636072
2011-06-29 00:45:29 -04:00
Russ Cox
ff4518da17 gc: fix package quoting logic
The decision for when to say "hash/crc32".New instead of
crc32.New in an error was double-counting imports
from different packages or indirect imports, so it was
quoting even when there was no ambiguity.

R=ken2
CC=golang-dev
https://golang.org/cl/4645070
2011-06-28 23:58:35 -04:00
Rob Pike
3a52cf56f8 gob: delete some unused bits from the GobEncoder/GobDecoder code.
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4631076
2011-06-29 13:57:59 +10:00
Rob Pike
c2e0d604ee exp/template: fix build
wrong path in Makefile. why didn't my all.bash fail?
TBR=dsymonds

R=dsymonds
CC=golang-dev
https://golang.org/cl/4630075
2011-06-29 13:55:49 +10:00
Rob Pike
a733f0bcd1 exp/template: use MethodByName, add to build.
R=rsc, adg, r
CC=golang-dev
https://golang.org/cl/4641081
2011-06-29 13:44:13 +10:00
Rob Pike
22484e2262 reflect: MethodByName
It's more common to ask for methods by name than by index, so might
as well make it easy to do so.

R=rsc
CC=golang-dev
https://golang.org/cl/4639083
2011-06-29 13:11:49 +10:00
Mikio Hara
161deaa85c runtime/cgo: fix build
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4629082
2011-06-28 22:26:31 -04:00
Gustavo Niemeyer
cf143e9dbf ld: fix ELF strip by removing overlap of sections
The gosymtab and gopclntab sections were pointing to the proper
data, but that data was already owned by the rodata section.
Some ELF references explicitly prohibit multiple sections from
owning the same data, and strip behaves accordingly.

The data for these sections was moved to after rodata, and the
gosymtab and gopclntab sections now own their respective ranges.

This change makes strip happy both with and without -s being
provided at link time.  Note that it won't remove these sections
because they are still allocated, and that's by design since
they are necessary at runtime for generating proper backtraces
and similar introspection operations.

Unlike the previous behavior, -s will now maintain zero-sized
gosymtab and gopclntab sections.  This makes the implementation
slightly cleaner.

Fixes #1242.

NOTE: Tested on Linux amd64/386/arm only.

R=ality, rsc
CC=golang-dev
https://golang.org/cl/4639077
2011-06-28 22:28:30 +01:00
Russ Cox
d0ac84fe40 cc: broken return is an error, not a warning
R=ken2
CC=golang-dev
https://golang.org/cl/4626081
2011-06-28 16:00:55 -04:00
Dmitriy Vyukov
997c00f991 runtime: replace Semacquire/Semrelease implementation
1. The implementation uses distributed hash table of waitlists instead of a centralized one.
  It significantly improves scalability for uncontended semaphores.
2. The implementation provides wait-free fast-path for signalers.
3. The implementation uses less locks (1 lock/unlock instead of 5 for Semacquire).
4. runtime·ready() call is moved out of critical section.
5. Semacquire() does not call semwake().
Benchmark results on HP Z600 (2 x Xeon E5620, 8 HT cores, 2.40GHz)
are as follows:
benchmark                                        old ns/op    new ns/op    delta
runtime_test.BenchmarkSemaUncontended                58.20        36.30  -37.63%
runtime_test.BenchmarkSemaUncontended-2             199.00        18.30  -90.80%
runtime_test.BenchmarkSemaUncontended-4             327.00         9.20  -97.19%
runtime_test.BenchmarkSemaUncontended-8             491.00         5.32  -98.92%
runtime_test.BenchmarkSemaUncontended-16            946.00         4.18  -99.56%

runtime_test.BenchmarkSemaSyntNonblock               59.00        36.80  -37.63%
runtime_test.BenchmarkSemaSyntNonblock-2            167.00       138.00  -17.37%
runtime_test.BenchmarkSemaSyntNonblock-4            333.00       129.00  -61.26%
runtime_test.BenchmarkSemaSyntNonblock-8            464.00       130.00  -71.98%
runtime_test.BenchmarkSemaSyntNonblock-16          1015.00       136.00  -86.60%

runtime_test.BenchmarkSemaSyntBlock                  58.80        36.70  -37.59%
runtime_test.BenchmarkSemaSyntBlock-2               294.00       149.00  -49.32%
runtime_test.BenchmarkSemaSyntBlock-4               333.00       177.00  -46.85%
runtime_test.BenchmarkSemaSyntBlock-8               471.00       221.00  -53.08%
runtime_test.BenchmarkSemaSyntBlock-16              990.00       227.00  -77.07%

runtime_test.BenchmarkSemaWorkNonblock              829.00       832.00   +0.36%
runtime_test.BenchmarkSemaWorkNonblock-2            425.00       419.00   -1.41%
runtime_test.BenchmarkSemaWorkNonblock-4            308.00       220.00  -28.57%
runtime_test.BenchmarkSemaWorkNonblock-8            394.00       147.00  -62.69%
runtime_test.BenchmarkSemaWorkNonblock-16          1510.00       149.00  -90.13%

runtime_test.BenchmarkSemaWorkBlock                 828.00       813.00   -1.81%
runtime_test.BenchmarkSemaWorkBlock-2               428.00       436.00   +1.87%
runtime_test.BenchmarkSemaWorkBlock-4               232.00       219.00   -5.60%
runtime_test.BenchmarkSemaWorkBlock-8               392.00       251.00  -35.97%
runtime_test.BenchmarkSemaWorkBlock-16             1524.00       298.00  -80.45%

sync_test.BenchmarkMutexUncontended                  24.10        24.00   -0.41%
sync_test.BenchmarkMutexUncontended-2                12.00        12.00   +0.00%
sync_test.BenchmarkMutexUncontended-4                 6.25         6.17   -1.28%
sync_test.BenchmarkMutexUncontended-8                 3.43         3.34   -2.62%
sync_test.BenchmarkMutexUncontended-16                2.34         2.32   -0.85%

sync_test.BenchmarkMutex                             24.70        24.70   +0.00%
sync_test.BenchmarkMutex-2                          208.00        99.50  -52.16%
sync_test.BenchmarkMutex-4                         2744.00       256.00  -90.67%
sync_test.BenchmarkMutex-8                         5137.00       556.00  -89.18%
sync_test.BenchmarkMutex-16                        5368.00      1284.00  -76.08%

sync_test.BenchmarkMutexSlack                        24.70        25.00   +1.21%
sync_test.BenchmarkMutexSlack-2                    1094.00       186.00  -83.00%
sync_test.BenchmarkMutexSlack-4                    3430.00       402.00  -88.28%
sync_test.BenchmarkMutexSlack-8                    5051.00      1066.00  -78.90%
sync_test.BenchmarkMutexSlack-16                   6806.00      1363.00  -79.97%

sync_test.BenchmarkMutexWork                        793.00       792.00   -0.13%
sync_test.BenchmarkMutexWork-2                      398.00       398.00   +0.00%
sync_test.BenchmarkMutexWork-4                     1441.00       308.00  -78.63%
sync_test.BenchmarkMutexWork-8                     8532.00       847.00  -90.07%
sync_test.BenchmarkMutexWork-16                    8225.00      2760.00  -66.44%

sync_test.BenchmarkMutexWorkSlack                   793.00       793.00   +0.00%
sync_test.BenchmarkMutexWorkSlack-2                 418.00       414.00   -0.96%
sync_test.BenchmarkMutexWorkSlack-4                4481.00       480.00  -89.29%
sync_test.BenchmarkMutexWorkSlack-8                6317.00      1598.00  -74.70%
sync_test.BenchmarkMutexWorkSlack-16               9111.00      3038.00  -66.66%

R=rsc
CC=golang-dev
https://golang.org/cl/4631059
2011-06-28 15:09:53 -04:00
Brad Fitzpatrick
39acba55ee fmt: rename errno and error to err for doc consistency
The public godoc looked confused. I imagine these were
written before current conventions were established.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4662060
2011-06-28 11:00:31 -07:00
Albert Strasheim
a026d0fc76 runtime/cgo: check for errors from pthread_create
R=rsc, iant, dvyukov
CC=golang-dev
https://golang.org/cl/4643057
2011-06-28 12:04:50 -04:00
Dmitriy Vyukov
660b22988b runtime: add Semacquire/Semrelease benchmarks
R=rsc
CC=golang-dev
https://golang.org/cl/4625065
2011-06-28 11:15:24 -04:00
Dmitriy Vyukov
93dde6b0e6 sync: add fast path to Once
The implementation does not grab the lock,
if Once is already initalized.
Benchmark results on HP Z600 (2 x Xeon E5620, 8 HT cores, 2.40GHz)
are as follows:
benchmark                                        old ns/op    new ns/op    delta
sync_test.BenchmarkOnce                             187.00        14.00  -92.51%
sync_test.BenchmarkOnce-2                           909.00        21.40  -97.65%
sync_test.BenchmarkOnce-4                          3684.00        20.90  -99.43%
sync_test.BenchmarkOnce-8                          5987.00        23.00  -99.62%
sync_test.BenchmarkOnce-16                         5051.00        21.60  -99.57%

R=bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4641066
2011-06-28 09:43:01 -04:00
Rob Pike
81592c298b Add the beginnings of the template execution code. Lots still to do,
including evaluation up the data tree (in this code all fields must be
in dot itself), plus more control structure, but the basics are in place.

R=rsc, r
CC=golang-dev
https://golang.org/cl/4665041
2011-06-28 23:04:08 +10:00
Dmitriy Vyukov
5c15f8710c sync: replace Mutex benchmarks
For both contended and uncontended case:
 - support arbitrary number of cpus (not just 2)
 - dynamic load balancing (improves stability)
 - periodic execution of Gosched() to work around non-preemptiviness
For uncontended case eliminates possible false-sharing.
For contended case includes additional variation with some
amount of local work between mutex operations.

R=r, rsc
CC=golang-dev
https://golang.org/cl/4634093
2011-06-28 08:14:54 -04:00
Evan Shaw
cf3eeb2984 io.WriteString: if the object has a WriteString method, use it
This avoids allocation when writing to bytes.Buffers and bufio.Writers, for
example.

R=golang-dev, rsc, r, consalus, r
CC=golang-dev
https://golang.org/cl/4625068
2011-06-28 16:10:39 +10:00
Andrew Gerrand
546c78b744 builder: minor fixes
R=golang-dev, gri, bradfitz
CC=golang-dev
https://golang.org/cl/4634050
2011-06-28 16:01:52 +10:00
Brad Fitzpatrick
6282292f8d mime/multipart: parse LF-delimited messages, not just CRLF
Against the spec, but appear in the wild.

Fixes #1966

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4662059
2011-06-27 21:59:51 -07:00
Russ Cox
52cd055f91 exp/regexp/syntax: case-folding in character classes
Also fix \x{123} parsing.

R=r
CC=golang-dev
https://golang.org/cl/4632052
2011-06-27 23:23:51 -04:00
Alex Brainman
6b648cafde runtime: another attempt to allow stdcall to be used from both 386 and amd64 arch
R=rsc
CC=golang-dev, vcc.163
https://golang.org/cl/4627071
2011-06-28 12:46:16 +10:00
Russ Cox
fe2ccb53c0 cc: add two new #pragma varargck
#pragma varargck countpos f 1
says that the first argument to f is
the count of variadic arguments that follow.

#pragma varargck type f t
says that t is one of the allowed types for
a variadic argument to f.
(can be repeated)

combined, these can be used to check the
runtime.stdcall functions in the windows port
or in any other port that needs a vararg list of
uintptrs even on a 64-bit platform (where it is
very easy to pass a less-than-uintptr in the ...).

demo:

typedef unsigned int uintptr;

#pragma varargck countpos f 1
#pragma varargck type f uintptr
#pragma varargck type f void*

int f(int count, ...);

void *v;
char *p;

void
main(void)
{
        f(1, v);  // ok
        f(1, main);  // ok
        f(1, p);  // ok
        f(2, v, v);  // ok

        f(2, v);  // found 1 argument after count 2
        f(1, 'a');  // invalid type INT in call to f
        f(1, 0);  // invalid type INT in call to f
}

R=ken, r, alex.brainman
CC=golang-dev
https://golang.org/cl/4634103
2011-06-27 22:42:34 -04:00
Rob Pike
f71153278a os: simplify WriteString
It was working too hard.

R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4639081
2011-06-28 11:09:21 +10:00
Russ Cox
46e7466080 exp/regexp/syntax: compiled form
R=r, sam.thorogood, kevlar
CC=golang-dev, rsc
https://golang.org/cl/4636046
2011-06-27 19:52:59 -04:00
Rob Pike
ebb1566a46 strings.Split: make the default to split all.
Change the signature of Split to have no count,
assuming a full split, and rename the existing
Split with a count to SplitN.
Do the same to package bytes.
Add a gofix module.

R=adg, dsymonds, alex.brainman, rsc
CC=golang-dev
https://golang.org/cl/4661051
2011-06-28 09:43:14 +10:00
Ken Rockot
82a8afdf14 syscall: support for tty options in StartProcess
These are the relevant changes to exec_unix.go now that
mkerrors.sh outputs have been updated.

R=rsc
CC=golang-dev
https://golang.org/cl/4648064
2011-06-27 19:07:49 -04:00
Kyle Lemons
abd50de296 xml: add Marshal and MarshalIndent
I have written up a Marshal and MarshalIndent pair that should
closely reflect the way that Unmarshal works.  I would love feedback
on making this code more accessible and efficient... I haven't used
reflecton on this scale before, so there is probably a lot of work
that can be done on that.

Some potentially controversial things:
- All tag names are lower-cased by default.
- Zero-valued struct values are skipped.
- No namespace prefix (o:tag, etc) mechanism is supplied.
- You are allowed to marshal non-struct values (even though unmarshal
  cannot handle them).
- A tag for a non-XMLName struct field that isn't "attr", "chardata",
  or "innerxml" is used as the name of the tag.  This could wreak
  havoc if you try to marshal a protobuf struct.
- The "innerxml" and "chardata" are inserted verbatim.  If you try to
  marshal something straight from unmarshal, the results could be
  unexpected (remove "innerxml" support from Marshal would be one
  possible solution).

R=rsc
CC=golang-dev
https://golang.org/cl/4539082
2011-06-27 19:07:28 -04:00
Russ Cox
9ded2b3451 CONTRIBUTORS: update Rietveld address for Kyle Lemons
R=golang-dev, bradfitz, r
CC=golang-dev
https://golang.org/cl/4634101
2011-06-27 19:07:22 -04:00
Brad Fitzpatrick
ac213ab834 http: respect Handlers setting Connection: close in their response
Fixes #2011

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4667043
2011-06-27 15:53:48 -07:00
Russ Cox
8475832f0d testing: scale benchmark precision to 0.01ns if needed
R=dvyukov, r
CC=golang-dev
https://golang.org/cl/4657053
2011-06-27 18:50:27 -04:00
Russ Cox
6aaa86ff66 gc: avoid package name ambiguity in error messages
Fixes #2006.

R=ken2
CC=golang-dev
https://golang.org/cl/4643056
2011-06-27 18:44:30 -04:00
Brad Fitzpatrick
19f795042a http: add FileSystem interface, make FileServer use it
Permits serving from virtual filesystems, such as files linked
into a binary, or from a zip file.

Also adds a gofix for:

http.FileServer(root, prefix) -> http.StripPrefix(prefix, http.FileServer(http.Dir(root)))

R=r, rsc, gri, adg, dsymonds, r, gri
CC=golang-dev
https://golang.org/cl/4629047
2011-06-27 15:26:36 -07:00
Graham Miller
f795bdb979 bufio: do not cache Read errors
Reader previously had cached an error from the underlying reader
and would return it on every subsequent call to Read.  The Reader
will now return the error only once, and subsequent calls will result
in a new Read call to the underlying Reader.

Fixes #1934.

R=bradfitz, rogpeppe, rsc
CC=golang-dev
https://golang.org/cl/4528133
2011-06-27 16:12:04 -04:00
Dmitriy Vyukov
3a4a581c49 sync: add benchmark for Once.
R=r, rsc
CC=golang-dev
https://golang.org/cl/4650054
2011-06-27 16:02:13 -04:00
Lucio De Re
6bcfb95168 8a: fixes for Plan 9 build
8a/a.h:
. Removed <u.h> and <libc.h> includes as they work better in "a.y".
. Made definition of EOF conditional as it's defined in the Plan 9
  header files, but not elsewhere.

8a/a.y:
. Added <u.h> and <libc.h> because <stdio.h> in Plan 9 needs them.
  Sequence <u.h>, <stdio.h>, <libc.h> recommended by RSC.

8a/lex.c:
. Added <u.h> and <libc.h> as now needed by "a.h".
. Dropped <ctype.h>.

cc/lexbody:
. exit() -> exits().
. Dropped unwanted incrementation.

cc/macbody:
. Adjusted a few format specifications.

R=rsc
CC=golang-dev
https://golang.org/cl/4644047
2011-06-27 14:42:18 -04:00
Anthony Martin
10d0dffd76 ld: elide the Go symbol table when using -s
R=rsc, n13m3y3r, gustavo
CC=golang-dev
https://golang.org/cl/4661050
2011-06-27 14:39:38 -04:00
Russ Cox
5f84559e3a build: use correct list of required programs
R=golang-dev, bradfitz, go.peter.90
CC=golang-dev
https://golang.org/cl/4627068
2011-06-27 14:30:02 -04:00
Brad Fitzpatrick
6c6c232072 http: add StripPrefix handler wrapper
R=rsc
CC=golang-dev
https://golang.org/cl/4626067
2011-06-27 11:03:43 -07:00
Russ Cox
f79bcb4b86 codereview: make --ignore_hgpatch_failure work again
R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4627067
2011-06-27 13:45:17 -04:00
Brad Fitzpatrick
7e29f1add8 http: do TLS handshake explicitly before copying TLS state
Previously we were snapshotting the TLS state into *Request
before we did the HTTP ReadRequest, the first Read of which
triggered the TLS handshake implicitly.

Fixes #1956

R=golang-dev, rsc
CC=agl, golang-dev
https://golang.org/cl/4630072
2011-06-27 10:37:33 -07:00
Dmitriy Vyukov
9843ca5e2b gotest: add -test.benchtime and -test.cpu flags.
-test.benchtime allows to specify benchmark execution time.
-test.cpu allows to execute tests/benchmarks for several
values of GOMAXPROCS.

R=r, r, rsc
CC=golang-dev
https://golang.org/cl/4662046
2011-06-27 13:31:40 -04:00
Russ Cox
9dd354c63f 5l, 6l, 8l: drop use of ed during build
build runs with chmod 0 /bin/ed now

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4635071
2011-06-27 12:03:19 -04:00
Russ Cox
dfacfd6431 syscall: regenerate zerrors for darwin/linux/freebsd
did darwin on mac with older, not broken xcode.
did linux arm by copying diffs from linux 386.
did freebsd amd64 by copying diffs from freebsd 386.

R=golang-dev, r, mikioh.mikioh
CC=golang-dev
https://golang.org/cl/4629067
2011-06-27 11:02:32 -04:00
Dmitry Chestnykh
d1dbfe5827 crypto: replace "crypto/block" with "crypto/cipher" in comments
Documentation mentioned the obsolete package "crypto/block",
which has been replaced with "crypto/cipher".

R=golang-dev, agl
CC=golang-dev
https://golang.org/cl/4654064
2011-06-27 09:16:42 -04:00
Robert Hencke
da19831c17 gofix: fixes for path/filepath changes
Fixes #1970.

R=rsc, r
CC=golang-dev
https://golang.org/cl/4650050
2011-06-26 11:24:28 +10:00
Robert Hencke
69905c6213 gofix: fixes for sort changes
Fixes #1969.

R=gri, rsc, r
CC=golang-dev
https://golang.org/cl/4634076
2011-06-26 08:48:53 +10:00
Robert Griesemer
f70e8ed0f3 ebnflint: better handling of stdin
- don't rely on /dev/stdin as the name for standard input
- employ EBNF extraction if the source contains tags

"cat source.html | ebnflint" works now

R=r
CC=golang-dev
https://golang.org/cl/4641075
2011-06-24 17:29:19 -07:00
Michael T. Jones
d94e350f48 fmt: Added SkipSpace() function to fmt's ScanState interface.
Users of the Scan() infrastructure that employ ReadRune() rather than
Token() need a way to skip leading spaces and newlines as set by the
the parent, Fscan(), Fscanln, or Fscanf(). As the internal methods and
boolean flags are not exported, this new function was added here and
in the Int and Nat Scan() functions of the big package. (fmt.Rat did
not need change since it uses Token()) Also added Printf style format
code support to int types and tests for same to int_test.go

R=r, r, gri, mtj
CC=golang-dev
https://golang.org/cl/4634074
2011-06-24 17:26:45 -07:00
Brad Fitzpatrick
5d4eea6a2f http: better handling of 0-length Request.Body
As rsc suggested after change 58a6bdac3d12 was committed, we
now read the first byte of Request.Body when the
Request.ContentLength is 0 to disambiguate between a truly
zero-length body and a body of unknown length where the user
didn't set the ContentLength field.

This was also causing the reverse proxy problem where incoming
requests (which always have a body, of private type http.body,
even for 0-lengthed requests) were being relayed to the http
Transport for fetching, which was serializing the request as a
chunked request (since ContentLength was 0 and Body was
non-nil)

Fixes #1999

R=golang-dev, kevlar
CC=golang-dev
https://golang.org/cl/4628063
2011-06-24 16:46:14 -07:00
Brad Fitzpatrick
e16b74075f http: assume ContentLength 0 on GET requests
Incremental step in fix for issue 1999

R=golang-dev, kevlar
CC=golang-dev
https://golang.org/cl/4667041
2011-06-24 13:48:12 -07:00
Pascal S. de Kloe
e0e28d2b93 mime: lower-case media type parameters
RFC 1521 section 4 states "The type, subtype, and parameter names are not case sensitive.".

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4648047
2011-06-24 11:32:06 -07:00
Robert Hencke
7a471eadcc os: remove duplicate package description
file.go contains a more complete package description.

R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4645058
2011-06-24 11:23:49 -07:00
Quan Yong Zhai
fc57c4b7a9 misc/emacs: update list of builtins.
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4630065
2011-06-24 11:19:48 -07:00
Alex Brainman
a39ead7ed2 path/filepath: enable TestWalk to run on windows
R=golang-dev
CC=golang-dev
https://golang.org/cl/4630066
2011-06-24 19:18:59 +10:00
Andrew Gerrand
163f70ffdc tag weekly.2011-06-23
R=r
CC=golang-dev
https://golang.org/cl/4635067
2011-06-24 16:18:39 +10:00
Andrew Gerrand
30d08b404c weekly.2011-06-23
R=golang-dev, robert.hencke, r
CC=golang-dev
https://golang.org/cl/4625062
2011-06-24 16:04:17 +10:00
Yasuhiro Matsumoto
8ab2c98972 os: fixed PathListSeparator to ';' for windows.
Fixed issue 1992

R=golang-dev, alex.brainman
CC=golang-dev
https://golang.org/cl/4661047
2011-06-24 15:00:59 +10:00
Brad Fitzpatrick
89873e60e2 http: buffer Request.Write
Fixes #1996

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4639068
2011-06-23 21:10:51 -07:00
Gustavo Niemeyer
65b036c381 runtime: don't use twice the memory with grsec-like kernels
grsec needs the FIXED flag to be provided to mmap, which
works now.  That said, when the allocation fails to be made
in the specific address, we're still given back a writable
page.  This change will unmap that page to avoid using
twice the amount of memory needed.

It'd also be pretty easy to avoid the extra system calls
once we detected that the flag is needed, but I'm not sure
if that edge case is worth the effort.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4634086
2011-06-24 00:29:59 -03:00
Andrew Gerrand
b4bab6f8b3 goinstall: build with make by default, add -make flag
This is a temporary measure until go/build can build cgo packages.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4627056
2011-06-24 13:01:17 +10:00
Yasuhiro Matsumoto
73d741fd5b mime/multipart: remove newline at top of the multipart.
R=golang-dev, bradfitz, arctanofyourface
CC=golang-dev
https://golang.org/cl/4635063
2011-06-23 10:11:33 -07:00
Anthony Martin
d847467041 libmach: fix disassembly of FCMOVcc and FCOMI
The optable for 0xDB is handled specially.

This was the cause of a really weird bug
when using cov (386!) on the math package.

A real head-scratcher.

R=rsc
CC=golang-dev
https://golang.org/cl/4639066
2011-06-23 09:32:29 -04:00
Anthony Martin
8f72a87b4c libmach: fix tracing on linux (for cov)
R=rsc, dave
CC=golang-dev
https://golang.org/cl/4629064
2011-06-22 23:24:14 -04:00
Russ Cox
c475c3071a 5c: do not use R9 and R10
This program used to use R9 and R10.
Now it fails to compile (out of registers).
I used to know a simpler test but can't remember it.

Learned something new: Rietveld refuses change
list descriptions bigger than 10 kB.

int sum(int x, int y, int z, int w) {
        return
        (((((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))/
        ((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))))%
        (((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))/
        ((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))))*
        ((((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))/
        ((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))))%
        (((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))/
        ((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))))))*
        (((((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))/
        ((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))))%
        (((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))/
        ((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))))*
        ((((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))/
        ((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))))%
        (((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))))/
        ((((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))|
        (((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w))&
        ((x*y+z*w|x*y+z*w)^
        (x*y+z*w|x*y+z*w)))))))
        ;
}

R=ken2
CC=golang-dev
https://golang.org/cl/4650053
2011-06-22 23:22:36 -04:00
Alex Brainman
5d53aab4a2 exec: LookPath should not search %PATH% for files like c:cmd.exe
R=golang-dev
CC=golang-dev
https://golang.org/cl/4632055
2011-06-23 10:56:53 +10:00
Rob Pike
96731619ce exp/template: make -0 be an unsigned int.
Fix (inconsequential) type error in list initializer.

R=rsc
CC=golang-dev
https://golang.org/cl/4638058
2011-06-23 10:19:29 +10:00
Andrew Gerrand
d7df79a7e5 go/build: include Import objects in Script Inputs
This has the effect of making goinstall rebuild a package's
dependencies when they are newer than the current package object.

R=rsc
CC=golang-dev
https://golang.org/cl/4627051
2011-06-23 10:15:46 +10:00
Yasuhiro Matsumoto
88442358a9 net, syscall: interface for windows
R=mikioh.mikioh, alex.brainman, rsc, vincent.vanackere
CC=golang-dev
https://golang.org/cl/4590050
2011-06-23 09:54:57 +10:00
Russ Cox
36b5e1d698 io: clarify Read, ReadAt, Copy, Copyn EOF behavior
R=golang-dev, bradfitz, iant, dsymonds, nigeltao, r
CC=golang-dev
https://golang.org/cl/4629062
2011-06-22 19:33:07 -04:00
Rob Pike
cd7826e5f6 First cut at the parser for the new template package.
This is not a full grammar, but the pieces are there to implement whatever we converge on.

R=rsc
CC=golang-dev
https://golang.org/cl/4629053
2011-06-23 09:27:28 +10:00
Alex Brainman
123549acb1 exec: better error message for windows LookPath
Fixes #1991.

R=golang-dev, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4648049
2011-06-23 09:16:20 +10:00
Nigel Tao
6b4fb9f85a image: basic test for the 16-bits-per-color-channel types.
R=r
CC=golang-dev
https://golang.org/cl/4635059
2011-06-23 08:39:00 +10:00
Ken Rockot
c8443d7242 syscall: add tty support to StartProcess
These changes add a Ctty int field to the Unix syscall.ProcAttr which,
if set >= 0 in conjuction with Setsid=true, will be used by
forkAndExecInChild as the file descriptor for the new child's
controlling terminal.

Necessary changes have been made to mkerrors.sh to generate defs for
TIOC*, though changes to its output files are not included here.
The changes made should support Linux, FreeBSD and Darwin, at least.

R=iant, bradfitz, r, rsc, borman
CC=golang-dev
https://golang.org/cl/4532075
2011-06-22 18:07:20 -04:00
Russ Cox
8a4acd53f1 A+C: Ken Rockot (individual CLA)
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4648053
2011-06-22 18:07:08 -04:00
Russ Cox
2e41120a82 build: explain $PWD use
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4639064
2011-06-22 17:00:46 -04:00
Dmitriy Vyukov
8cab7f5703 sync: restore GOMAXPROCS during benchmarks
R=golang-dev
CC=dvyukov, golang-dev
https://golang.org/cl/4631060
2011-06-22 16:20:37 -04:00
Gustavo Niemeyer
89d334ffe1 ld: don't attempt to build dynamic sections unnecessarily
This prevents ld from generating zeroed symtab entries for
sections that aren't going to be generated because dynamic
linkage has been disabled (-d was used or no dynamic libs
were seen).  Even though they were not explicitly added by
doelf, the section creation process was making them
reachable again.

The windows head is being disconsidered for this because
apparently it's not taking into account debug['d'].

This makes elflint 0.1% happier.

R=golang-dev, rsc, gustavo
CC=golang-dev
https://golang.org/cl/4638050
2011-06-22 15:12:22 -04:00
Brad Fitzpatrick
5dfdccf2b0 Fix Windows build; ErrorString->NewError
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4634080
2011-06-22 11:33:30 -07:00
Robert Griesemer
712fb6dcd3 os.Error API: don't export os.ErrorString, use os.NewError consistently
This is a core API change.

1) gofix misc src
2) Manual adjustments to the following files under src/pkg:
   gob/decode.go
   rpc/client.go
   os/error.go
   io/io.go
   bufio/bufio.go
   http/request.go
   websocket/client.go
as well as:
   src/cmd/gofix/testdata/*.go.in (reverted)
   test/fixedbugs/bug243.go
3) Implemented gofix patch (oserrorstring.go) and test case (oserrorstring_test.go)

Compiles and runs all tests.

R=r, rsc, gri
CC=golang-dev
https://golang.org/cl/4607052
2011-06-22 10:52:47 -07:00
Russ Cox
55b0662465 godefs: remove test from build
The test is only defined on darwin/amd64, and it fails
with recent versions of Xcode, which do not support
-gstabs+ debugging output.  At some point godefs will
have to be replaced, perhaps merged with cgo.
Godefs is not needed during builds anyway (its output files
are checked into the repository in src/pkg/runtime),
so its failure on the newer Xcode is a distraction from an
otherwise usable build.  Disable the test.

Fixes #1985.

R=golang-dev, gri, robert.hencke, r
CC=golang-dev
https://golang.org/cl/4638053
2011-06-21 21:45:13 -04:00
Adam Langley
f2e94de6d6 crypto/openpgp: add ElGamal support.
R=bradfitz, r
CC=golang-dev
https://golang.org/cl/4639049
2011-06-21 21:00:49 -04:00
Lucio De Re
10b5519d3a 8l: more fixes for Plan 9
Once these changes are effected, it is possible to construct
"8l" native on a (386?) Plan 9 system, albeit with assistance
from modules such as mkfiles that are not (yet) included in any
public patches.

8l/asm.c:
. Corrected some format qualifiers.

8l/list.c:
. Cast a print() argument to (int) to match the given format.
  It may be possible to change the format (%R), but I have not
  looked into it.

8l/obj.c:
. Removed some unused code.

8l/span.c:
. Removed unnecessary incrementation on "bp".
. Corrected some format qualifiers.

ld/data.c:
. Corrected some format qualifiers.
. Cast print argument to (int): used as field size.
. Use braces to suppress warning about empty if() statements.

ld/dwarf.c:
. Trivial spelling mistake in comment.

ld/ldelf.c:
. Added USED() statements to silence warnings.
. Dropped redundant address (&) operators.
. corrected some format qualifiers.
. Cast to (int) for switch selection variable.

ld/macho.c:
. Added USED() statements to silence warnings.

ld/ldpe.c:
. Added USED() statements to silence warnings.
. More careful use of "sect" variable.
. Corrected some format qualifiers.
. Removed redundant assignments.
. Minor fix dropped as it was submitted separately.

ld/pe.c:
. Dropped <time.h> which is now in <u.h>.
. Dropped redundant address (&) operators.
. Added a missing variable initialisation.

ld/symtab.c:
. Added USED() statements to silence warnings.
. Removed redundant incrementation.
. Corrected some format qualifiers.

All the above have been tested against a (very) recent release
and do not seem to trigger any regressions.

All review suggestions have been incorporated.

R=rsc
CC=golang-dev
https://golang.org/cl/4633043
2011-06-21 12:14:32 -04:00
Robert Hencke
b88e669a8f nacl, tiny: remove vestiges
R=golang-dev, r, rsc
CC=golang-dev
https://golang.org/cl/4635053
2011-06-21 12:02:40 -04:00
Russ Cox
d6be71c788 gopprof: update list of memory allocators
Also import new weblist command from Google version.

R=r, bradfitz
CC=golang-dev
https://golang.org/cl/4650048
2011-06-21 11:27:08 -04:00
Andrew Gerrand
f338d9f73b goinstall: undo 1ad616fb313d (always rebuild...)
CL 4627051 is a better way of doing the same thing.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4654045
2011-06-21 17:13:16 +10:00
Alex Brainman
524d02cbca builder: run make single-threaded on windows
Will still honor MAKEFLAGS environment variable if set.

R=golang-dev
CC=bradfitz, golang-dev
https://golang.org/cl/4644049
2011-06-21 12:26:38 +10:00
Andrew Gerrand
ceae2c9301 goinstall: undo repo peeking code
Keeping the Julian's good refactoring work.

R=rsc
CC=golang-dev
https://golang.org/cl/4638049
2011-06-21 11:28:15 +10:00
Ben Lynn
6be0bdf7bc Effective Go: supplied missing type in variadic function example.
R=golang-dev, nigeltao
CC=golang-dev
https://golang.org/cl/4595055
2011-06-21 10:55:07 +10:00
Mikio Hara
5d6f118f23 syscall: add socket control message support for darwin, freebsd, linux
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4528113
2011-06-20 18:40:20 -04:00
Rob Pike
97a929aac9 fmt: catch panics from calls to String etc.
This change causes Print et al. to catch panics generated by
calls to String, GoString, and Format.  The panic is formatted
into the output stream as an error, but the program continues.
As a special case, if the argument was a nil pointer, the
result is just "<nil>", because that's almost certainly enough
information and handles the very common case of String
methods that don't guard against nil.

Scan does not want this change. Input must work; output can
be for debugging and it's nice to get output even when you
make a mistake.

R=dsymonds, r, adg, gri, rsc, gri
CC=golang-dev
https://golang.org/cl/4640043
2011-06-21 08:31:02 +10:00
Russ Cox
4bbe9d87d7 all-qemu.bash: cannot test go/build
R=adg, r
CC=golang-dev
https://golang.org/cl/4633054
2011-06-20 17:44:36 -04:00
Brad Fitzpatrick
9ee83f546f http: write Header keys with empty values
R=golang-dev, rsc, r
CC=golang-dev
https://golang.org/cl/4630052
2011-06-20 14:36:03 -07:00
Brad Fitzpatrick
922ceaddd2 http: permit handlers to explicitly remove the Date header
We'll do the right thing by default, but people wanting minimal
response sizes can explicitly remove the Date header.
(empty fields aren't written out)

R=rsc
CC=golang-dev
https://golang.org/cl/4634048
2011-06-20 13:39:03 -07:00
Graham Miller
cf201ed6a0 os: change Waitmsg String method to use pointer receiver
Fixes #1851.

R=rsc
CC=golang-dev
https://golang.org/cl/4628045
2011-06-20 15:42:17 -04:00
Brad Fitzpatrick
c2784340a7 http: add Server.ListenAndServeTLS
Fixes #1964

R=rsc
CC=golang-dev
https://golang.org/cl/4630045
2011-06-20 12:19:26 -07:00
Mikio Hara
10f1436bad syscall: add LSF support for linux
R=rsc
CC=golang-dev
https://golang.org/cl/4626041
2011-06-20 14:51:34 -04:00
Robert Hencke
58ff8c1dfd codereview.py: note that hg change -d abandons a change list
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4644043
2011-06-20 14:50:00 -04:00
Anthony Martin
028f74f827 5g, 6g, 8g: fix comments in method call generation
R=golang-dev
CC=golang-dev
https://golang.org/cl/4652042
2011-06-20 14:49:29 -04:00
Anthony Martin
12b2269860 5g, 5l: fix more set but not used warnings
These are present when building with gcc 4.6.

R=golang-dev, dave
CC=golang-dev, lvd
https://golang.org/cl/4636047
2011-06-20 14:18:04 -04:00
Russ Cox
e0a617496e test: test of goto restrictions
R=gri, iant, bradfitz, fvbommel, r
CC=golang-dev
https://golang.org/cl/4652041
2011-06-20 14:06:00 -04:00
Brad Fitzpatrick
da7b96f714 http: fix req.Cookie(name) with cookies in one header
Fixes #1974

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4654042
2011-06-20 10:33:07 -07:00
Pascal S. de Kloe
67ec47d1c0 mime: fix RFC references
R=golang-dev, bradfitz
CC=brad fitzpatrick <bradfitz, golang-dev
https://golang.org/cl/4634063
2011-06-20 07:41:18 -07:00
Anthony Martin
f7d754fcce build: exclude packages that fail on Plan 9 (for now)
All but two packages depend on net:
        debug/proc
        os/signal

With this change, we can produce
a working build with GOOS=plan9.

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4639053
2011-06-20 22:23:43 +10:00
Andrew Gerrand
f22e5cfc6d goinstall: update doc.go
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4645048
2011-06-20 16:39:16 +10:00
Yasuhiro Matsumoto
b7b8f2b086 misc/godashboard: Accept sub-directories for goinstall's report.
Fixed issue 1155.

R=golang-dev, adg, rsc
CC=golang-dev
https://golang.org/cl/4592059
2011-06-20 14:46:32 +10:00
Andrew Gerrand
f3a7dad654 goinstall: s/vlogf/printf/
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4628050
2011-06-20 14:44:14 +10:00
Andrew Gerrand
e068b85bea goinstall: wait for all commands to finish instead of timeout
goinstall: make ".git" repo suffix optional

R=golang-dev, r, r
CC=golang-dev
https://golang.org/cl/4643048
2011-06-20 14:12:23 +10:00
Anthony Martin
20943baed3 exec: add support for Plan 9
R=paulzhol, mirtchovski, fshahriar, alex.brainman, r
CC=golang-dev
https://golang.org/cl/4386041
2011-06-20 13:34:10 +10:00
Julian Phillips
c319fb07bc goinstall: Add support for arbitary code repositories
Extend goinstall to support downloading from any hg/git/svn/bzr hosting
site, not just the standard ones.  The type of hosting is automatically
checked by trying all the tools, so the import statement looks like:

  import "example.com/mything"

Which will work for Mercurial (http), Subversion (http, svn), Git (http,
git) and Bazaar (http, bzr) hosting.

All the existing package imports will work through this new mechanism,
but the existing hard-coded host support is left in place to ensure
there is no change in behaviour.

R=golang-dev, bradfitz, fvbommel, go.peter.90, n13m3y3r, adg, duperray.olivier
CC=golang-dev
https://golang.org/cl/4650043
2011-06-20 13:00:43 +10:00
Rob Pike
5e77b9d334 doc/GoCourseDay1: shrink the PDF by rewriting it using ps2pdf.
No difference in content or appearance.
Forgot to do this when I updated this file a few days ago.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4626056
2011-06-20 12:36:14 +10:00
Robert Hencke
a5b5e2b79e godefs: rudimentary tests
currently only defined for darwin

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4528123
2011-06-20 11:54:07 +10:00
Rob Pike
783c46b197 8a: delete dreg l.s
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4631053
2011-06-20 11:53:41 +10:00
Anthony Martin
d119e3bc0f time: add support for Plan 9
R=paulzhol, mirtchovski, r, r, rsc
CC=golang-dev
https://golang.org/cl/4362041
2011-06-19 16:36:33 +10:00
Andrew Gerrand
bbddcc14c6 A+C: add Julian Phillips
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4628048
2011-06-19 16:09:28 +10:00
Rob Pike
f22f40532e Make.ccmd: another build fix.
It's sad to think there are environments where compiling against a library
isn't enough information for the the linker to decide that you need that
library.
TBR=jdpoirier

R=jdpoirier
CC=golang-dev
https://golang.org/cl/4646047
2011-06-19 15:30:54 +10:00
Rob Pike
3890ce0ed5 Make.ccmd: fix build - libraries in wrong order.
TBR=jdpoirier

R=jdpoirier
CC=golang-dev
https://golang.org/cl/4648045
2011-06-19 14:56:25 +10:00
Dave Cheney
cbb2d8e20e cc: nit: silence comment warnings
R=golang-dev, r, r
CC=golang-dev
https://golang.org/cl/4648043
2011-06-19 13:58:08 +10:00
Joe Poirier
26b6a97c15 Make.ccmd: link with mach lib,
remove explicit linking in make files

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4629051
2011-06-19 13:57:22 +10:00
Andrew Gerrand
df02e65d54 doc/faq: remove misleading FAQ entry
R=golang-dev, dsymonds, r
CC=golang-dev
https://golang.org/cl/4638046
2011-06-19 13:53:07 +10:00
Andrew Gerrand
c967ba0210 goinstall: always rebuild a package after its dependencies are built
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4627047
2011-06-19 09:36:45 +10:00
Scott Lawrence
3c06518405 http: fix documentation typo
(Variable is referred to alternately as 'r' and 'req')

R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4648042
2011-06-18 21:53:18 +10:00
Andrew Gerrand
17805ddb6f doc/faq: add question about converting from []T to []interface{}
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4639046
2011-06-18 20:31:38 +10:00
Russ Cox
61f4ec132b syscall: fix build for Sizeof change
R=ken2
CC=golang-dev
https://golang.org/cl/4635051
2011-06-17 17:07:21 -04:00
Russ Cox
cf9f380499 gc: unsafe.Alignof, unsafe.Offsetof, unsafe.Sizeof now return uintptr
R=ken2
CC=golang-dev
https://golang.org/cl/4640045
2011-06-17 16:12:14 -04:00
Russ Cox
b96ff8458c 5g, 8g: fix build
R=ken2
CC=golang-dev
https://golang.org/cl/4627045
2011-06-17 16:05:00 -04:00
Russ Cox
7f4c5ea7d8 gc: implement goto restriction
Remove now-unnecessary zeroing of stack frames.

R=ken2
CC=golang-dev
https://golang.org/cl/4641044
2011-06-17 15:25:05 -04:00
Russ Cox
e852202f37 gc: descriptive panic for nil pointer -> value method call
R=ken2
CC=golang-dev
https://golang.org/cl/4646042
2011-06-17 15:23:27 -04:00
Russ Cox
f4c7db0ed9 spec: disallow goto into blocks
R=gri, r, r
CC=golang-dev
https://golang.org/cl/4631045
2011-06-17 12:49:04 -04:00
Russ Cox
21e75da486 respect goto restrictions
R=gri
CC=golang-dev
https://golang.org/cl/4625044
2011-06-17 06:07:13 -04:00
Alex Brainman
8155ff5452 go/build: use back quotes for regular expression
R=adg
CC=golang-dev
https://golang.org/cl/4643045
2011-06-17 16:41:59 +10:00
Alex Brainman
eaa082f691 8l: minor fix discovered by lucio
R=lucio.dere, vcc.163, bradfitz
CC=golang-dev
https://golang.org/cl/4645044
2011-06-17 15:55:54 +10:00
Andrew Gerrand
e5105f55dc tag weekly.2011-06-16
R=dsymonds
CC=golang-dev
https://golang.org/cl/4648041
2011-06-17 11:35:57 +10:00
Andrew Gerrand
d6b9dd8b81 weekly.2011-06-16
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4643044
2011-06-17 11:31:40 +10:00
Andrew Gerrand
4340b57d88 goinstall, go/build: support building cgo packages
Fixes #1962.

R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4636044
2011-06-17 11:15:54 +10:00
Nigel Tao
ca91ce2d85 doc/effective_go: add a note about prefixing error strings with their
package name.

R=r, rsc
CC=golang-dev
https://golang.org/cl/4630042
2011-06-17 10:51:10 +10:00
Nigel Tao
278952c393 regexp: add a package prefix to error strings.
R=r, r
CC=golang-dev
https://golang.org/cl/4630041
2011-06-17 10:50:38 +10:00
Alex Brainman
c562fbc44e cgo: make file path work for windows
R=golang-dev, mattn.jp, adg
CC=golang-dev
https://golang.org/cl/4634043
2011-06-17 10:17:33 +10:00
Brad Fitzpatrick
380e5a3709 http: document http client/transport thread safety
Fixes #1961

R=golang-dev, rsc, r
CC=golang-dev
https://golang.org/cl/4633045
2011-06-16 15:02:47 -07:00
Russ Cox
fc77e82617 unicode: add case folding tables
R=r, r
CC=golang-dev
https://golang.org/cl/4571074
2011-06-16 17:56:25 -04:00
Brad Fitzpatrick
6e9b1a78ff http: make Headers be source of truth
Previously Request and Response had redundant fields for
Referer, UserAgent, and cookies which caused confusion and
bugs.  It also didn't allow us to expand the package over
time, since the way to access fields would be in the Headers
one day and promoted to a field the next day.  That would be
hard to gofix, especially with code ranging over Headers.

After a discussion on the mail package's design with a similar
problem, we've designed to make the Headers be the source of
truth and add accessors instead.

Request:
change: Referer -> Referer()
change: UserAgent -> UserAgent()
change: Cookie -> Cookies()
new: Cookie(name) *Cookie
new: AddCookie(*Cookie)

Response:
change: Cookie -> Cookies()

Cookie:
new: String() string

R=rsc
CC=golang-dev
https://golang.org/cl/4620049
2011-06-16 13:02:28 -07:00
Volker Dobler
7f3e109d2f xml: allow attributes without value in non-strict mode.
Attributes without value are commen in html and the xml
parser will accept them in non-strict mode and use the
attribute name as value. Thus parsing <p nowrap> as
<p norwar="nowrap">.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4601053
2011-06-16 12:56:49 -04:00
Russ Cox
d81147b617 A+C: Volker Dobler (individual CLA)
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4589055
2011-06-16 12:56:39 -04:00
Brad Fitzpatrick
98f95b8048 mime/multipart: convert Reader from interface to struct
It was always a weird interface but I didn't know what I
was doing at the time.  rsc questioned me about it then
but didn't press on it during review.  Then adg bugged me
about it too recently.

So clean it up. It parallels the Writer struct too.

R=golang-dev, r, rsc
CC=golang-dev
https://golang.org/cl/4602063
2011-06-16 08:55:53 -07:00
Russ Cox
95963e6294 runtime/cgo: fix for OS X 10.7
Correct a few error messages (libcgo -> runtime/cgo)
and delete old nacl_386.c file too.

Fixes #1657.

R=iant
CC=golang-dev
https://golang.org/cl/4603057
2011-06-16 11:10:31 -04:00
Rob Pike
2b08e952bb sort: change the name of Float64Array to Float64Slice.
I missed this before because I used the wrong regexp. What a moron.

R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4639041
2011-06-16 17:48:02 +10:00
Russ Cox
b955448d59 tag release = release.r57.2
R=adg
CC=golang-dev
https://golang.org/cl/4638041
2011-06-16 02:09:48 -04:00
Russ Cox
e56a1e0299 tag release.r57.2
R=adg
CC=golang-dev
https://golang.org/cl/4637042
2011-06-16 02:06:27 -04:00
Rob Pike
8db6802cec docs/GoCourseDay1.pdf: fix error in operator table.
Communications op was listed as a binary; it isn't any more.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4637041
2011-06-16 16:03:24 +10:00
Russ Cox
aaae15ef0f doc: document r57.2
R=adg, r
CC=golang-dev
https://golang.org/cl/4627042
2011-06-16 01:46:14 -04:00
Russ Cox
5a5a7b5163 6g, 8g: fix goto fix
R=ken2
CC=golang-dev
https://golang.org/cl/4632041
2011-06-16 01:25:49 -04:00
Robert Griesemer
333167ff35 go/printer, gofmt: print "select {}" on one line
No impact on existing sources under src, misc.

Fixes #1959.

R=r, rsc, r
CC=golang-dev
https://golang.org/cl/4589056
2011-06-15 21:47:29 -07:00
Russ Cox
5d9dbe19a7 gc: work around goto bug
R=ken2
CC=golang-dev
https://golang.org/cl/4629042
2011-06-16 00:18:43 -04:00
Russ Cox
f011bd378f build: use awk instead of giant egrep regexp
Avoids buggy version of egrep on some Macs.

R=r, dsymonds
CC=golang-dev
https://golang.org/cl/4603056
2011-06-16 00:04:24 -04:00
Dave Cheney
832e87500e go/build: support building cgo packages on non intel platforms
See https://golang.org/cl/4572045/

R=adg, rsc
CC=golang-dev
https://golang.org/cl/4627041
2011-06-16 13:35:27 +10:00
Nigel Tao
9555ea7a5b image/draw: add an Op argument to Draw.
R=r
CC=golang-dev
https://golang.org/cl/4622041
2011-06-16 11:45:16 +10:00
Yasuhiro Matsumoto
7fd51f2fb4 syscall: use strict in perl scripts
R=golang-dev, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4609047
2011-06-15 17:41:07 -07:00
Russ Cox
0193139bec undo CL 4557047 / 8818ac606e92
I don't think we've discussed this API enough.

««« original CL description
bike/shed: new package.

It comes up often enough that it's time to provide
the utility of a standard package.

R=r, mirtchovski, adg, rsc, n13m3y3r, ality, go.peter.90, lstoakes, iant, jan.mercl, bsiegert, robert.hencke, rogpeppe, befelemepeseveze, kevlar
CC=golang-dev
https://golang.org/cl/4557047
»»»

R=dsymonds, bradfitz, gri
CC=golang-dev
https://golang.org/cl/4576065
2011-06-15 19:47:52 -04:00
Robert Griesemer
fb9ea79916 godoc: replace direct OS file system accesses in favor
of accesses via a FileSystem interface.

Preparation for appengine version which gets its files
via a snapshot or zip file and uses a corresponding
FileSystem implementation.

R=rsc, r
CC=golang-dev
https://golang.org/cl/4572065
2011-06-15 14:06:35 -07:00
Rob Pike
e3d2a29e99 doc/effective_go.html: replace tab with spaces.
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4609042
2011-06-16 00:13:18 +10:00
Rob Pike
d6653fed98 http: use runtime/debug.Stack() to dump stack trace on panic.
Test output now looks like this:

2011/06/15 21:10:41 http: panic serving 127.0.0.1:59729: intentional death for testing
$GOROOT/src/pkg/http/server.go:495 (0x3f9f8)
        _func_004: buf.Write(debug.Stack())
$GOROOT/src/pkg/runtime/proc.c:1041 (0x12367)
        panic: reflect·call(d->fn, d->args, d->siz);
$GOROOT/src/pkg/http/serve_test.go:775 (0x5831b)
        _func_029: panic("intentional death for testing")
$GOROOT/src/pkg/http/server.go:575 (0x26366)
        HandlerFunc.ServeHTTP: f(w, r)
$GOROOT/src/pkg/http/server.go:541 (0x261a9)
        *conn.serve: c.handler.ServeHTTP(w, w.req)
$GOROOT/src/pkg/runtime/proc.c:178 (0x10a83)
        goexit: runtime·goexit(void)

with $GOROOT expanded, of course.

R=bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4607051
2011-06-16 00:12:50 +10:00
Andrew Gerrand
39208939c6 go/build: better, self-contained tests
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4576063
2011-06-15 21:35:34 +10:00
Scott Lawrence
bee3b0358c gofix: Fix inconsistent indentation in help output
R=golang-dev, r
CC=golang-dev
https://golang.org/cl/4572066
2011-06-15 21:07:21 +10:00
Dave Cheney
c357ca663f go/build: remove crud in cgotest/_obj
R=adg
CC=golang-dev
https://golang.org/cl/4584060
2011-06-15 16:39:17 +10:00
Andrew Gerrand
7c248ae077 go/build: fix build and clean ups
R=rsc
CC=golang-dev
https://golang.org/cl/4620045
2011-06-15 14:56:12 +10:00
Andrew Gerrand
4a8de67058 go/build: record all cgo intermediate files (fix build)
R=rsc
CC=golang-dev
https://golang.org/cl/4613045
2011-06-15 14:29:26 +10:00
Andrew Gerrand
db5a4ffc2a goinstall: use go/make package to scan and build packages
R=rsc, n13m3y3r, kevlar
CC=golang-dev
https://golang.org/cl/4515180
2011-06-15 13:28:35 +10:00
Yasuhiro Matsumoto
414da2e4a3 syscall: mksyscall_windows.pl should output unix newline.
R=golang-dev, bradfitz, alex.brainman
CC=golang-dev
https://golang.org/cl/4601058
2011-06-15 11:50:21 +10:00
David Symonds
812b2b6405 mail: cosmetic fixes.
R=rsc, gri
CC=golang-dev
https://golang.org/cl/4602062
2011-06-15 09:10:59 +10:00
Russ Cox
1a4681ed74 exp/regexp/syntax: more escapes, character classes
Still TODO: parsing optimizations

make_perl_groups.pl is copied with minimal modifications
(just to generate Go syntax instead of C++) from RE2.
Google Inc is "The RE2 Author" of that file and is one of
the Go Authors, so copyright changed to the Go Authors instead.

R=sam.thorogood, r, fvbommel, robert.hencke
CC=golang-dev
https://golang.org/cl/4612041
2011-06-14 14:30:10 -04:00
Lucio De Re
340251e43d build: fix header files for Plan 9
The "elf.h" header changes involve only comments, the released
Plan 9 C preprocessing function does not cope with multiline
comments following the #define keyword.  All multiline comments
have been moved to the line above the associated definition.
Sigh!  Fixing the Plan 9 compiler is not an option.

<time.h> does not exist in the Plan 9 Native library.  I have
moved it from src/cmd/ld/pe.h to include/u.h. RSC correctly points
out that this copy of <u.h> is not the one used to compile the
Go release on Plan 9 platforms.

R=golang-dev
CC=golang-dev, rsc
https://golang.org/cl/4574042
2011-06-14 14:14:11 -04:00
Gustavo Niemeyer
a84e9d01f0 ld: make .rodata section read-only
Fixes the respective warning from elflint.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4607048
2011-06-14 15:13:54 -03:00
Gustavo Niemeyer
a5c1fa7f02 debug/elf: rename test .o files to .obj
.o files are commonly found in default ignore lists by
source management tools, including dpkg-source, bzr, etc.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4568078
2011-06-14 15:06:39 -03:00
Mikio Hara
c4dfc55be9 net: export all fields in Interface
Fixes #1942.

R=fullung, rsc
CC=golang-dev
https://golang.org/cl/4602044
2011-06-14 13:32:52 -04:00
Jeff Hodges
0ce57a73c5 syscall: add ptrace on darwin
The ptrace syscall remains gutted on darwin, but usable.  This
also makes the syscall addition process reproducible on darwin
instead of relying on a file path in rsc's home directory.
I've also removed an override of $PATH in env.bash that made
tooling harder.

R=rsc, dave, r
CC=golang-dev
https://golang.org/cl/4517147
2011-06-14 12:56:46 -04:00
Maxim Ushakov
5f77bf8b20 xml: handle non-string attribute fields
R=kevlar, rsc
CC=golang-dev
https://golang.org/cl/4528114
2011-06-14 11:51:03 -04:00
Alex Brainman
c195cc8d82 exec: make LookPath work even when PATHEXT env variable is not set on Windows
R=golang-dev, mattn.jp
CC=golang-dev
https://golang.org/cl/4559062
2011-06-14 11:46:05 -04:00
William Chan
5af8e53a14 http/spdy: improve error handling.
Create a new spdy.Error type that includes the enumerated error type and
the associated stream id (0 if not associated with a specific stream).
This will let users handle errors differently (RST_STREAM vs GOAWAY).

R=bradfitz, rsc, rogpeppe
CC=golang-dev
https://golang.org/cl/4532131
2011-06-14 11:31:18 -04:00
Yuval Pavel Zholkover
400d825ea0 syscall: fix Plan 9 build.
Move mmapper from syscall.go to syscall_unix.go.
Remove Sendfile from syscall_plan9.go.

R=rsc, alex.brainman
CC=golang-dev
https://golang.org/cl/4368060
2011-06-14 11:29:51 -04:00
Mikio Hara
b100a29bc4 syscall: update BPF support for BSD variants
R=dave, rsc
CC=golang-dev
https://golang.org/cl/4589044
2011-06-14 11:28:36 -04:00
Yuval Pavel Zholkover
18112437d9 os: Plan 9, fix OpenFile & Chmod. Update tests.
Add Process.Kill.

R=rsc
CC=golang-dev
https://golang.org/cl/4571049
2011-06-14 11:20:34 -04:00
Wei Guangjing
9e2ffc315f ld: fix link Windows PE __declspec(dllimport) symbol
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4568077
2011-06-14 11:05:59 -04:00
Luuk van Dijk
2ad42a8249 gc: frame compaction for arm.
Required moving some parts of gc/pgen.c to ?g/ggen.c

on linux tests pass for all 3 architectures, and
frames are actually compacted (diagnostic code for
that has been removed from the CL).

R=rsc
CC=golang-dev
https://golang.org/cl/4571071
2011-06-14 17:03:37 +02:00
Russ Cox
4d0f2e9195 syscall, os, exec: introduce *syscall.SysProcAttr field in os.ProcAttr and exec.Cmd
R=r, bradfitz, alex.brainman, borman, vincent.vanackere
CC=golang-dev
https://golang.org/cl/4607046
2011-06-14 10:49:34 -04:00
David Symonds
371aa14e06 mail: decode RFC 2047 "B" encoding.
R=rsc, r
CC=golang-dev
https://golang.org/cl/4584056
2011-06-14 17:32:47 +10:00
Rob Pike
c6c8dbd646 doc/gopher: add a small gif to use as an app engine logo on GAE pages.
R=golang-dev, dsymonds
CC=golang-dev
https://golang.org/cl/4591078
2011-06-14 17:25:57 +10:00
Rob Pike
6d42af7197 doc/gopher: add jpgs of the goggled gopher logo for App Engine.
R=golang-dev, r, adg
CC=golang-dev
https://golang.org/cl/4591077
2011-06-14 16:42:52 +10:00
Rob Pike
34e0725dec os: be explicit in the package comment that this package is for portable features only.
R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4602058
2011-06-14 11:49:33 +10:00
Robert Griesemer
2769356dda go spec: specify constant conversions
This is not a language change.

Added paragraphs specifying which conversions
yield results that are constants.

R=r, rsc, iant, ken
CC=golang-dev
https://golang.org/cl/4515176
2011-06-13 16:47:33 -07:00
Robert Griesemer
eee70b07c1 go spec: unsafe.Alignof/Offsetof/Sizeof return uintptr
This is (indirectly) a language change. Per e-mail discussion
on golang-dev.

Fixes #1943.

R=rsc, iant, r, ken
CC=golang-dev
https://golang.org/cl/4581058
2011-06-13 16:46:42 -07:00
Russ Cox
8d8ac637ee build: stop early if commands are missing
If we fail due to a missing command (always bison)
during the build, it is running many things in parallel
and the error message gets lost in the noise.
Also diagnose bison++.

$ ./make.bash
Your system's bison is bison++, a buggy copy of the original bison.
Go needs the original bison instead.
See http://golang.org/doc/install.html#ctools
$ sudo apt-get remove bison++
... ridiculous amount of output ...
$ ./make.bash
Cannot find 'bison' on search path.
See http://golang.org/doc/install.html#ctools
$ sudo apt-get install bison
... ridiculous amount of output ...
$ ./make.bash
... works

Fixes #1938.
Fixes #1946.

R=bradfitz
CC=golang-dev
https://golang.org/cl/4528137
2011-06-13 15:28:54 -04:00
Russ Cox
9968090ddd cgo: handle new Apple LLVM-based gcc from Xcode 4.2
That gcc does not include enumerator names and values
in its DWARF debug output.  Create a data block from which
we can read the values instead.

Fixes #1881.

R=iant
CC=golang-dev
https://golang.org/cl/4607045
2011-06-13 14:43:54 -04:00
Adam Langley
8834bb0bfa crypto/openpgp: flesh out Encrypt by adding support for signing.
R=bradfitz
CC=golang-dev
https://golang.org/cl/4572059
2011-06-13 13:04:59 -04:00
Luuk van Dijk
d164b6081d ld: dwarf emit filenames in debug_line header instead of as extended opcodes.
Makes it possible for older tools like objdump to find the filenames,
fixes  objdump -d -l --start-address=0x400c00 --stop-address=0x400c36 6.out
fixes #1950

R=rsc
CC=golang-dev
https://golang.org/cl/4609043
2011-06-13 16:56:43 +02:00
Russ Cox
b96c3477f8 exp/regexp/syntax: syntax data structures, parser
Parser is a work in progress but can populate most of the
interesting parts of the data structure, so a good checkpoint.
All the complicated Perl syntax is missing, as are various
important optimizations made during parsing to the
syntax tree.

The plan is that exp/regexp's API will mimic regexp,
and exp/regexp/syntax provides the parser directly
for programs that need it (and for implementing exp/regexp).

Once finished, exp/regexp will replace regexp.

R=r, sam.thorogood, kevlar, edsrzf
CC=golang-dev
https://golang.org/cl/4538123
2011-06-13 09:20:23 -04:00
Stephen Ma
b4bb970e18 gc: handle go print() and go println()
Fixes #1952.

R=golang-dev, rsc
CC=golang-dev
https://golang.org/cl/4611041
2011-06-13 22:50:51 +10:00
Rob Pike
7bc8e90e36 exp/template: lexical scanner for new template package.
An unusual design using slice and a goroutine makes for a
compact scanner with very little allocation.

R=rsc, r
CC=golang-dev, kevlar
https://golang.org/cl/4610041
2011-06-13 16:08:35 +10:00
Alex Brainman
9ded954a3b net: rearrange source files so we could run more tests on windows
R=rsc
CC=golang-dev
https://golang.org/cl/4603043
2011-06-13 10:22:31 +10:00
Robert Griesemer
95b8137a16 go spec: clarify rules for append, scope rules for :=
Fixes #1936.
Fixes #1940.

R=rsc, r, iant, ken, iant
CC=golang-dev
https://golang.org/cl/4585049
2011-06-12 12:09:50 -07:00
Alex Brainman
27cbf06d50 mime/multipart: allow for temp files to be removed after tests are finished on Windows
R=golang-dev, bradfitz
CC=golang-dev
https://golang.org/cl/4605044
2011-06-11 16:23:44 +10:00
Yasuhiro Matsumoto
1374097381 net: Sendfile for win32.
implement using TransmitFile().

R=bsiegert, bradfitz, alex.brainman, rsc, go.peter.90
CC=golang-dev
https://golang.org/cl/4536076
2011-06-11 13:24:48 +10:00
Robert Griesemer
968afa0e8c go/scanner: partially revert CL4538096 now that we have %#U for runes
R=r, bradfitz, rsc
CC=golang-dev
https://golang.org/cl/4572049
2011-06-10 17:19:01 -07:00
Robert Griesemer
c8ee1b8ebc io/ioutil: fix typo in comment
R=r, r
CC=golang-dev
https://golang.org/cl/4592052
2011-06-10 17:07:22 -07:00
Rob Pike
d152fe74e1 fmt: debugging formats for characters: %+q %#U
%+q uses strconv.Quote[Rune]ToASCII, guaranteeing ASCII-only output.
%#U a quoted character if the rune is printable: 'x'=U+0078; otherwise
it's as before: U+000A.

R=golang-dev, gri, rsc
CC=golang-dev
https://golang.org/cl/4589047
2011-06-11 00:03:02 +00:00
Rob Pike
4b1170d2b1 sort: change IntArray etc. to IntSlice for better name hygiene.
R=golang-dev, gri
CC=golang-dev
https://golang.org/cl/4602054
2011-06-11 09:25:18 +10:00
Robert Griesemer
18333f2de5 Go memory model: minor clarification
Fixes #1941.

R=rsc
CC=golang-dev
https://golang.org/cl/4576053
2011-06-10 12:31:10 -07:00
Adam Langley
531c01d990 crypto/openpgp: build fix (unreviewed)
R=agl
CC=golang-dev
https://golang.org/cl/4572057
2011-06-10 13:32:20 -04:00
Adam Langley
f0d21a773f crypto/openpgp: add ability to encrypt messages.
R=bradfitz, r
CC=golang-dev
https://golang.org/cl/4581051
2011-06-10 12:58:14 -04:00
David Symonds
b5071e92b4 bike/shed: new package.
It comes up often enough that it's time to provide
the utility of a standard package.

R=r, mirtchovski, adg, rsc, n13m3y3r, ality, go.peter.90, lstoakes, iant, jan.mercl, bsiegert, robert.hencke, rogpeppe, befelemepeseveze, kevlar
CC=golang-dev
https://golang.org/cl/4557047
2011-06-10 22:32:45 +10:00
Yuval Pavel Zholkover
0924185840 runtime: fix Plan 9 "lingering goroutines bug".
R=rsc, r
CC=golang-dev
https://golang.org/cl/4589042
2011-06-10 17:23:54 +10:00
Rob Pike
9b409ac7ee docs: Update notes for 3-day Go course.
R=golang-dev, adg
CC=golang-dev
https://golang.org/cl/4605041
2011-06-10 15:05:51 +10:00
Andrew Gerrand
944076c8e9 tag weekly.2011-06-09
R=r
CC=golang-dev
https://golang.org/cl/4591064
2011-06-10 14:52:11 +10:00
1238 changed files with 67141 additions and 35079 deletions

View File

@@ -41,6 +41,8 @@ src/cmd/gc/y1.tab.c
src/cmd/gc/yerr.h
src/cmd/goinstall/syslist.go
src/pkg/Make.deps
src/pkg/exp/norm/maketables
src/pkg/exp/norm/maketesttables
src/pkg/exp/ogle/ogle
src/pkg/go/build/syslist.go
src/pkg/os/signal/unix.go

13
.hgtags
View File

@@ -62,6 +62,17 @@ d6903b7fbff40c13ee7ea3177c0ae54c7f89d2e6 weekly.2011-04-13
2f0fa51fa2da6ab50fcebba526326153da8ed999 weekly.2011-04-27
8493bb64e5592bd20c0e60e78e7f8052c1276fcf release.r57
95d2ce135523c96c4cea049af94ce76dd8c7d981 release.r57.1
95d2ce135523c96c4cea049af94ce76dd8c7d981 release
c98449d685d2b6aa1df9bfd2e1cce9307efb6e00 weekly.2011-05-22
3418f22c39eb8299053ae681199ee90f8cd29c6d weekly.2011-06-02
c81944152e973a917797679055b8fcdc70fbc802 weekly.2011-06-09
9d7967223815ef6415ff01aa0fe6ad38cdbc7810 release.r57.2
dac76f0b1a18a5de5b54a1dc0b231aceaf1c8583 weekly.2011-06-16
541c445d6c1353fbfa39df7dc4b0eb27558d1fc1 weekly.2011-06-23
1b38d90eebcddefabb3901c5bb63c7e2b04a6ec5 release.r58
16bfa562ba767aefd82e598da8b15ee4729e23b0 weekly.2011-07-07
d292bc7886682d35bb391bf572be28656baee12d release.r58.1
3c21f37b25a3f7a1726265c5339c8a7b0b329336 weekly.2011-07-19
bb28251f6da4aca85658582c370c7df89d34efd4 weekly.2011-07-29
d5785050f61d973fc36775f7bd2e26689529cb3e release.r59
d5785050f61d973fc36775f7bd2e26689529cb3e release
c17ce5ec06b4bd5cf6e7ff2ceb0a60c2e40e0b17 weekly.2011-08-10

10
AUTHORS
View File

@@ -11,11 +11,13 @@
Abhinav Gupta <abhinav.g90@gmail.com>
Adrian O'Grady <elpollouk@gmail.com>
Albert Strasheim <fullung@gmail.com>
Aleksandar Dezelin <dezelin@gmail.com>
Alex Brainman <alex.brainman@gmail.com>
Alexander Orlov <alexander.orlov@loxal.net>
Alexey Borzenkov <snaury@gmail.com>
Amrut Joshi <amrut.joshi@gmail.com>
Andrei Vieru <euvieru@gmail.com>
Andrew Balholm <andybalholm@gmail.com>
Andrew Skiba <skibaa@gmail.com>
Andrey Mirtchovski <mirtchovski@gmail.com>
Andy Davis <andy@bigandian.com>
@@ -27,6 +29,7 @@ Aron Nopanen <aron.nopanen@gmail.com>
Arvindh Rajesh Tamilmani <art@a-30.net>
Ben Olive <sionide21@gmail.com>
Benny Siegert <bsiegert@gmail.com>
Bobby Powers <bobbypowers@gmail.com>
Caine Tighe <arctanofyourface@gmail.com>
Charles L. Dorian <cldorian@gmail.com>
Chris Dollin <ehog.hedge@gmail.com>
@@ -60,6 +63,7 @@ Fazlul Shahriar <fshahriar@gmail.com>
Firmansyah Adiputra <frm.adiputra@gmail.com>
Florian Uekermann <florian@uekermann-online.de>
Gary Burd <gary@beagledreams.com>
Gideon Jan-Wessel Redelinghuys <gjredelinghuys@gmail.com>
Giles Lean <giles.lean@pobox.com>
Google Inc.
Graham Miller <graham.miller@gmail.com>
@@ -78,15 +82,18 @@ Jeff Hodges <jeff@somethingsimilar.com>
Jeff R. Allen <jra@nella.org>
Jim McGrath <jimmc2@gmail.com>
Joe Poirier <jdpoirier@gmail.com>
John Asmuth <jasmuth@gmail.com>
Jonathan Mark <jhmark@xenops.com>
Jonathan Wills <runningwild@gmail.com>
Jose Luis Vázquez González <josvazg@gmail.com>
Josh Goebel <dreamer3@gmail.com>
Jukka-Pekka Kekkonen <karatepekka@gmail.com>
Julian Phillips <julian@quantumfyre.co.uk>
Kai Backman <kaib@golang.org>
Kei Son <hey.calmdown@gmail.com>
Keith Rarick <kr@xph.us>
Ken Friedenbach <kenliz@cruzio.com>
Ken Rockot <ken@oz.gs>
Kevin Ballard <kevin@sb.org>
Kyle Consalus <consalus@gmail.com>
Kyle Lemons <kyle@kylelemons.net>
@@ -96,6 +103,7 @@ Luit van Drongelen <luitvd@gmail.com>
Markus Duft <markus.duft@salomon.at>
Martin Neubauer <m.ne@gmx.net>
Mathieu Lonjaret <mathieu.lonjaret@gmail.com>
Matthew Horsnell <matthew.horsnell@gmail.com>
Micah Stetson <micah.stetson@gmail.com>
Michael Elkins <michael.elkins@gmail.com>
Michael Hoisie <hoisie@gmail.com>
@@ -105,6 +113,7 @@ Mikio Hara <mikioh.mikioh@gmail.com>
Mikkel Krautz <mikkel@krautz.dk>
Moriyoshi Koizumi <mozo@mozo.jp>
Môshe van der Sterre <moshevds@gmail.com>
ngmoco, LLC
Nicholas Waples <nwaples@gmail.com>
Nigel Kerr <nigel.kerr@gmail.com>
Olivier Antoine <olivier.antoine@gmail.com>
@@ -140,6 +149,7 @@ Tor Andersson <tor.andersson@gmail.com>
Vincent Ambo <tazjin@googlemail.com>
Vincent Vanackere <vincent.vanackere@gmail.com>
Vinu Rajashekhar <vinutheraj@gmail.com>
Volker Dobler <dr.volker.dobler@gmail.com>
Wei Guangjing <vcc.163@gmail.com>
William Josephson <wjosephson@gmail.com>
Yasuhiro Matsumoto <mattn.jp@gmail.com>

View File

@@ -35,11 +35,13 @@ Abhinav Gupta <abhinav.g90@gmail.com>
Adam Langley <agl@golang.org>
Adrian O'Grady <elpollouk@gmail.com>
Albert Strasheim <fullung@gmail.com>
Aleksandar Dezelin <dezelin@gmail.com>
Alex Brainman <alex.brainman@gmail.com>
Alexander Orlov <alexander.orlov@loxal.net>
Alexey Borzenkov <snaury@gmail.com>
Amrut Joshi <amrut.joshi@gmail.com>
Andrei Vieru <euvieru@gmail.com>
Andrew Balholm <andybalholm@gmail.com>
Andrew Gerrand <adg@golang.org>
Andrew Skiba <skibaa@gmail.com>
Andrey Mirtchovski <mirtchovski@gmail.com>
@@ -58,6 +60,7 @@ Ben Olive <sionide21@gmail.com>
Benny Siegert <bsiegert@gmail.com>
Berengar Lehr <Berengar.Lehr@gmx.de>
Bill Neubauer <wcn@golang.org> <wcn@google.com>
Bobby Powers <bobbypowers@gmail.com>
Brad Fitzpatrick <bradfitz@golang.org> <bradfitz@gmail.com>
Brendan O'Dea <bod@golang.org>
Caine Tighe <arctanofyourface@gmail.com>
@@ -77,6 +80,7 @@ Daniel Fleischman <danielfleischman@gmail.com>
Daniel Nadasi <dnadasi@google.com>
Daniel Theophanes <kardianos@gmail.com>
Dave Cheney <dave@cheney.net>
Dave Grijalva <dgrijalva@ngmoco.com>
David Anderson <danderson@google.com>
David Crawshaw <david.crawshaw@zentus.com>
David Forsythe <dforsythe@gmail.com>
@@ -93,6 +97,7 @@ Eivind Uggedal <eivind@uggedal.com>
Eoghan Sherry <ejsherry@gmail.com>
Eric Clark <zerohp@gmail.com>
Eric Eisner <eric.d.eisner@gmail.com>
Evan Martin <evan.martin@gmail.com>
Evan Shaw <chickencha@gmail.com>
Fan Hongjian <fan.howard@gmail.com>
Fazlul Shahriar <fshahriar@gmail.com>
@@ -100,6 +105,7 @@ Firmansyah Adiputra <frm.adiputra@gmail.com>
Florian Uekermann <florian@uekermann-online.de> <f1@uekermann-online.de>
Fumitoshi Ukai <ukai@google.com>
Gary Burd <gary@beagledreams.com> <gary.burd@gmail.com>
Gideon Jan-Wessel Redelinghuys <gjredelinghuys@gmail.com>
Giles Lean <giles.lean@pobox.com>
Graham Miller <graham.miller@gmail.com>
Gustavo Niemeyer <gustavo@niemeyer.net> <n13m3y3r@gmail.com>
@@ -122,7 +128,9 @@ Jeff Hodges <jeff@somethingsimilar.com>
Jeff R. Allen <jra@nella.org> <jeff.allen@gmail.com>
Jim McGrath <jimmc2@gmail.com>
Joe Poirier <jdpoirier@gmail.com>
Joel Sing <jsing@google.com>
Johan Euphrosine <proppy@google.com>
John Asmuth <jasmuth@gmail.com>
John DeNero <denero@google.com>
Jonathan Allie <jonallie@google.com>
Jonathan Mark <jhmark@xenops.com> <jhmark000@gmail.com>
@@ -131,25 +139,29 @@ Jos Visser <josv@google.com>
Jose Luis Vázquez González <josvazg@gmail.com>
Josh Goebel <dreamer3@gmail.com>
Jukka-Pekka Kekkonen <karatepekka@gmail.com>
Julian Phillips <julian@quantumfyre.co.uk>
Kai Backman <kaib@golang.org>
Kei Son <hey.calmdown@gmail.com>
Keith Rarick <kr@xph.us>
Ken Friedenbach <kenliz@cruzio.com>
Ken Rockot <ken@oz.gs> <ken.rockot@gmail.com>
Ken Thompson <ken@golang.org>
Kevin Ballard <kevin@sb.org>
Kirklin McDonald <kirklin.mcdonald@gmail.com>
Kyle Consalus <consalus@gmail.com>
Kyle Lemons <kyle@kylelemons.net> <etherealflaim@gmail.com>
Kyle Lemons <kyle@kylelemons.net> <kevlar@google.com>
Larry Hosken <lahosken@golang.org>
Lorenzo Stoakes <lstoakes@gmail.com>
Lucio De Re <lucio.dere@gmail.com>
Luit van Drongelen <luitvd@gmail.com>
Luuk van Dijk <lvd@golang.org> <lvd@google.com>
Marcel van Lohuizen <mpvl@golang.org>
Mark Zavislak <zavislak@google.com>
Markus Duft <markus.duft@salomon.at>
Martin Neubauer <m.ne@gmx.net>
Mathieu Lonjaret <mathieu.lonjaret@gmail.com>
Matt Jones <mrjones@google.com>
Matthew Horsnell <matthew.horsnell@gmail.com>
Maxim Ushakov <ushakov@google.com>
Micah Stetson <micah.stetson@gmail.com>
Michael Elkins <michael.elkins@gmail.com>
@@ -157,6 +169,8 @@ Michael Hoisie <hoisie@gmail.com>
Michael T. Jones <mtj@google.com> <michael.jones@gmail.com>
Miek Gieben <miek@miek.nl> <remigius.gieben@gmail.com>
Mikael Tillenius <mikti42@gmail.com>
Mike Samuel <mikesamuel@gmail.com>
Mike Solomon <msolo@gmail.com>
Mikio Hara <mikioh.mikioh@gmail.com>
Mikkel Krautz <mikkel@krautz.dk> <krautz@gmail.com>
Moriyoshi Koizumi <mozo@mozo.jp>
@@ -169,6 +183,7 @@ Padraig Kitterick <padraigkitterick@gmail.com>
Paolo Giarrusso <p.giarrusso@gmail.com>
Pascal S. de Kloe <pascal@quies.net>
Patrick Gavlin <pgavlin@gmail.com>
Paul Borman <borman@google.com>
Petar Maymounkov <petarm@gmail.com>
Peter Froehlich <peter.hans.froehlich@gmail.com>
Peter McKenzie <petermck@google.com>
@@ -201,6 +216,7 @@ Spring Mc <heresy.mc@gmail.com>
Stefan Nilsson <snilsson@nada.kth.se>
Stephen Ma <stephenm@golang.org>
Stephen Weinberg <stephen@q5comm.com>
Sugu Sougoumarane <ssougou@gmail.com>
Sven Almgren <sven@tras.se>
Tarmigan Casebolt <tarmigan@gmail.com>
Timo Savola <timo.savola@gmail.com>
@@ -211,6 +227,7 @@ Vincent Ambo <tazjin@googlemail.com>
Vincent Vanackere <vincent.vanackere@gmail.com>
Vinu Rajashekhar <vinutheraj@gmail.com>
Vish Subramanian <vish@google.com>
Volker Dobler <dr.volker.dobler@gmail.com>
Wei Guangjing <vcc.163@gmail.com>
William Chan <willchan@chromium.org>
William Josephson <wjosephson@gmail.com>

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -4,8 +4,8 @@
include ../src/Make.inc
TARG=htmlgen
TARG=tmpltohtml
GOFILES=\
htmlgen.go\
tmpltohtml.go\
include ../src/Make.cmd

View File

@@ -135,7 +135,6 @@ h1#title {
clear: both;
}
#content h1 {
margin-bottom: -0em;
padding: 0;
}
#content h2 {

View File

@@ -1,6 +1,6 @@
<h1>Editing {Title}</h1>
<h1>Editing {{.Title |html}}</h1>
<form action="/save/{Title}" method="POST">
<div><textarea name="body" rows="20" cols="80">{Body|html}</textarea></div>
<form action="/save/{{.Title |html}}" method="POST">
<div><textarea name="body" rows="20" cols="80">{{printf "%s" .Body |html}}</textarea></div>
<div><input type="submit" value="Save"></div>
</form>

View File

@@ -68,7 +68,7 @@ func saveHandler(w http.ResponseWriter, r *http.Request) {
}
func renderTemplate(w http.ResponseWriter, tmpl string, p *Page) {
t, err := template.ParseFile(tmpl+".html", nil)
t, err := template.ParseFile(tmpl+".html")
if err != nil {
http.Error(w, err.String(), http.StatusInternalServerError)
return

View File

@@ -34,14 +34,14 @@ func editHandler(w http.ResponseWriter, r *http.Request) {
if err != nil {
p = &Page{Title: title}
}
t, _ := template.ParseFile("edit.html", nil)
t, _ := template.ParseFile("edit.html")
t.Execute(w, p)
}
func viewHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[lenPath:]
p, _ := loadPage(title)
t, _ := template.ParseFile("view.html", nil)
t, _ := template.ParseFile("view.html")
t.Execute(w, p)
}

View File

@@ -59,7 +59,8 @@ var templates = make(map[string]*template.Template)
func init() {
for _, tmpl := range []string{"edit", "view"} {
templates[tmpl] = template.MustParseFile(tmpl+".html", nil)
t := template.Must(template.ParseFile(tmpl+".html"))
templates[tmpl] = t
}
}

View File

@@ -1,12 +1,12 @@
package main
import (
"os"
"template"
"os"
"io/ioutil"
)
func main() {
b, _ := ioutil.ReadAll(os.Stdin)
template.HTMLFormatter(os.Stdout, "", b)
template.HTMLEscape(os.Stdout, b)
}

View File

@@ -429,7 +429,9 @@ Of course, there is a better way.
<h2>The <code>template</code> package</h2>
<p>
The <code>template</code> package is part of the Go standard library. We can
The <code>template</code> package is part of the Go standard library.
(A new template package is coming; this code lab will be updated soon.)
We can
use <code>template</code> to keep the HTML in a separate file, allowing
us to change the layout of our edit page without modifying the underlying Go
code.
@@ -454,10 +456,10 @@ Open a new file named <code>edit.html</code>, and add the following lines:
</p>
<pre>
&lt;h1&gt;Editing {Title}&lt;/h1&gt;
&lt;h1&gt;Editing {{.Title |html}}&lt;/h1&gt;
&lt;form action=&#34;/save/{Title}&#34; method=&#34;POST&#34;&gt;
&lt;div&gt;&lt;textarea name=&#34;body&#34; rows=&#34;20&#34; cols=&#34;80&#34;&gt;{Body|html}&lt;/textarea&gt;&lt;/div&gt;
&lt;form action=&#34;/save/{{.Title |html}}&#34; method=&#34;POST&#34;&gt;
&lt;div&gt;&lt;textarea name=&#34;body&#34; rows=&#34;20&#34; cols=&#34;80&#34;&gt;{{printf &#34;%s&#34; .Body |html}}&lt;/textarea&gt;&lt;/div&gt;
&lt;div&gt;&lt;input type=&#34;submit&#34; value=&#34;Save&#34;&gt;&lt;/div&gt;
&lt;/form&gt;
</pre>
@@ -474,7 +476,7 @@ func editHandler(w http.ResponseWriter, r *http.Request) {
if err != nil {
p = &amp;Page{Title: title}
}
t, _ := template.ParseFile(&#34;edit.html&#34;, nil)
t, _ := template.ParseFile(&#34;edit.html&#34;)
t.Execute(w, p)
}
</pre>
@@ -485,19 +487,21 @@ The function <code>template.ParseFile</code> will read the contents of
</p>
<p>
The method <code>t.Execute</code> replaces all occurrences of
<code>{Title}</code> and <code>{Body}</code> with the values of
<code>p.Title</code> and <code>p.Body</code>, and writes the resultant
HTML to the <code>http.ResponseWriter</code>.
The method <code>t.Execute</code> executes the template, writing the
generated HTML to the <code>http.ResponseWriter</code>.
The <code>.Title</code> and <code>.Body</code> dotted identifiers refer to
<code>p.Title</code> and <code>p.Body</code>.
</p>
<p>
Note that we've used <code>{Body|html}</code> in the above template.
The <code>|html</code> part asks the template engine to pass the value
<code>Body</code> through the <code>html</code> formatter before outputting it,
which escapes HTML characters (such as replacing <code>&gt;</code> with
<code>&amp;gt;</code>).
This will prevent user data from corrupting the form HTML.
Template directives are enclosed in double curly braces.
The <code>printf "%s" .Body</code> instruction is a function call
that outputs <code>.Body</code> as a string instead of a stream of bytes,
the same as a call to <code>fmt.Printf</code>.
The <code>|html</code> part of each directive pipes the value through the
<code>html</code> formatter before outputting it, which escapes HTML
characters (such as replacing <code>&gt;</code> with <code>&amp;gt;</code>),
preventing user data from corrupting the form HTML.
</p>
<p>
@@ -511,11 +515,11 @@ While we're working with templates, let's create a template for our
</p>
<pre>
&lt;h1&gt;{Title}&lt;/h1&gt;
&lt;h1&gt;{{.Title |html}}&lt;/h1&gt;
&lt;p&gt;[&lt;a href=&#34;/edit/{Title}&#34;&gt;edit&lt;/a&gt;]&lt;/p&gt;
&lt;p&gt;[&lt;a href=&#34;/edit/{{.Title |html}}&#34;&gt;edit&lt;/a&gt;]&lt;/p&gt;
&lt;div&gt;{Body}&lt;/div&gt;
&lt;div&gt;{{printf &#34;%s&#34; .Body |html}}&lt;/div&gt;
</pre>
<p>
@@ -526,7 +530,7 @@ Modify <code>viewHandler</code> accordingly:
func viewHandler(w http.ResponseWriter, r *http.Request) {
title := r.URL.Path[lenPath:]
p, _ := loadPage(title)
t, _ := template.ParseFile(&#34;view.html&#34;, nil)
t, _ := template.ParseFile(&#34;view.html&#34;)
t.Execute(w, p)
}
</pre>
@@ -706,16 +710,17 @@ var templates = make(map[string]*template.Template)
<p>
Then we create an <code>init</code> function, which will be called before
<code>main</code> at program initialization. The function
<code>template.MustParseFile</code> is a convenience wrapper around
<code>ParseFile</code> that does not return an error code; instead, it panics
if an error is encountered. A panic is appropriate here; if the templates can't
be loaded the only sensible thing to do is exit the program.
<code>template.Must</code> is a convenience wrapper that panics when passed a
non-nil <code>os.Error</code> value, and otherwise returns the
<code>*Template</code> unaltered. A panic is appropriate here; if the templates
can't be loaded the only sensible thing to do is exit the program.
</p>
<pre>
func init() {
for _, tmpl := range []string{&#34;edit&#34;, &#34;view&#34;} {
templates[tmpl] = template.MustParseFile(tmpl+&#34;.html&#34;, nil)
t := template.Must(template.ParseFile(tmpl + &#34;.html&#34;))
templates[tmpl] = t
}
}
</pre>
@@ -761,10 +766,9 @@ var titleValidator = regexp.MustCompile(&#34;^[a-zA-Z0-9]+$&#34;)
<p>
The function <code>regexp.MustCompile</code> will parse and compile the
regular expression, and return a <code>regexp.Regexp</code>.
<code>MustCompile</code>, like <code>template.MustParseFile</code>,
is distinct from <code>Compile</code> in that it will panic if
the expression compilation fails, while <code>Compile</code> returns an
<code>os.Error</code> as a second parameter.
<code>MustCompile</code> is distinct from <code>Compile</code> in that it will
panic if the expression compilation fails, while <code>Compile</code> returns
an <code>os.Error</code> as a second parameter.
</p>
<p>

View File

@@ -8,8 +8,8 @@ import (
"go/ast"
"go/token"
"log"
"os"
"template"
"os"
)
var (

View File

@@ -1,5 +1,5 @@
<h1>{Title}</h1>
<h1>{{.Title |html}}</h1>
<p>[<a href="/edit/{Title}">edit</a>]</p>
<p>[<a href="/edit/{{.Title |html}}">edit</a>]</p>
<div>{Body}</div>
<div>{{printf "%s" .Body |html}}</div>

View File

@@ -369,7 +369,9 @@ Of course, there is a better way.
<h2>The <code>template</code> package</h2>
<p>
The <code>template</code> package is part of the Go standard library. We can
The <code>template</code> package is part of the Go standard library.
(A new template package is coming; this code lab will be updated soon.)
We can
use <code>template</code> to keep the HTML in a separate file, allowing
us to change the layout of our edit page without modifying the underlying Go
code.
@@ -412,19 +414,21 @@ The function <code>template.ParseFile</code> will read the contents of
</p>
<p>
The method <code>t.Execute</code> replaces all occurrences of
<code>{Title}</code> and <code>{Body}</code> with the values of
<code>p.Title</code> and <code>p.Body</code>, and writes the resultant
HTML to the <code>http.ResponseWriter</code>.
The method <code>t.Execute</code> executes the template, writing the
generated HTML to the <code>http.ResponseWriter</code>.
The <code>.Title</code> and <code>.Body</code> dotted identifiers refer to
<code>p.Title</code> and <code>p.Body</code>.
</p>
<p>
Note that we've used <code>{Body|html}</code> in the above template.
The <code>|html</code> part asks the template engine to pass the value
<code>Body</code> through the <code>html</code> formatter before outputting it,
which escapes HTML characters (such as replacing <code>&gt;</code> with
<code>&amp;gt;</code>).
This will prevent user data from corrupting the form HTML.
Template directives are enclosed in double curly braces.
The <code>printf "%s" .Body</code> instruction is a function call
that outputs <code>.Body</code> as a string instead of a stream of bytes,
the same as a call to <code>fmt.Printf</code>.
The <code>|html</code> part of each directive pipes the value through the
<code>html</code> formatter before outputting it, which escapes HTML
characters (such as replacing <code>&gt;</code> with <code>&amp;gt;</code>),
preventing user data from corrupting the form HTML.
</p>
<p>
@@ -570,10 +574,10 @@ our <code>*Template</code> values, keyed by <code>string</code>
<p>
Then we create an <code>init</code> function, which will be called before
<code>main</code> at program initialization. The function
<code>template.MustParseFile</code> is a convenience wrapper around
<code>ParseFile</code> that does not return an error code; instead, it panics
if an error is encountered. A panic is appropriate here; if the templates can't
be loaded the only sensible thing to do is exit the program.
<code>template.Must</code> is a convenience wrapper that panics when passed a
non-nil <code>os.Error</code> value, and otherwise returns the
<code>*Template</code> unaltered. A panic is appropriate here; if the templates
can't be loaded the only sensible thing to do is exit the program.
</p>
<pre>
@@ -616,10 +620,9 @@ Then we can create a global variable to store our validation regexp:
<p>
The function <code>regexp.MustCompile</code> will parse and compile the
regular expression, and return a <code>regexp.Regexp</code>.
<code>MustCompile</code>, like <code>template.MustParseFile</code>,
is distinct from <code>Compile</code> in that it will panic if
the expression compilation fails, while <code>Compile</code> returns an
<code>os.Error</code> as a second parameter.
<code>MustCompile</code> is distinct from <code>Compile</code> in that it will
panic if the expression compilation fails, while <code>Compile</code> returns
an <code>os.Error</code> as a second parameter.
</p>
<p>

130
doc/codewalk/markov.go Normal file
View File

@@ -0,0 +1,130 @@
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/*
Generating random text: a Markov chain algorithm
Based on the program presented in the "Design and Implementation" chapter
of The Practice of Programming (Kernighan and Pike, Addison-Wesley 1999).
See also Computer Recreations, Scientific American 260, 122 - 125 (1989).
A Markov chain algorithm generates text by creating a statistical model of
potential textual suffixes for a given prefix. Consider this text:
I am not a number! I am a free man!
Our Markov chain algorithm would arrange this text into this set of prefixes
and suffixes, or "chain": (This table assumes a prefix length of two words.)
Prefix Suffix
"" "" I
"" I am
I am a
I am not
a free man!
am a free
am not a
a number! I
number! I am
not a number!
To generate text using this table we select an initial prefix ("I am", for
example), choose one of the suffixes associated with that prefix at random
with probability determined by the input statistics ("a"),
and then create a new prefix by removing the first word from the prefix
and appending the suffix (making the new prefix is "am a"). Repeat this process
until we can't find any suffixes for the current prefix or we exceed the word
limit. (The word limit is necessary as the chain table may contain cycles.)
Our version of this program reads text from standard input, parsing it into a
Markov chain, and writes generated text to standard output.
The prefix and output lengths can be specified using the -prefix and -words
flags on the command-line.
*/
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"rand"
"strings"
"time"
)
// Prefix is a Markov chain prefix of one or more words.
type Prefix []string
// String returns the Prefix as a string (for use as a map key).
func (p Prefix) String() string {
return strings.Join(p, " ")
}
// Shift removes the first word from the Prefix and appends the given word.
func (p Prefix) Shift(word string) {
copy(p, p[1:])
p[len(p)-1] = word
}
// Chain contains a map ("chain") of prefixes to a list of suffixes.
// A prefix is a string of prefixLen words joined with spaces.
// A suffix is a single word. A prefix can have multiple suffixes.
type Chain struct {
chain map[string][]string
prefixLen int
}
// NewChain returns a new Chain with prefixes of prefixLen words.
func NewChain(prefixLen int) *Chain {
return &Chain{make(map[string][]string), prefixLen}
}
// Build reads text from the provided Reader and
// parses it into prefixes and suffixes that are stored in Chain.
func (c *Chain) Build(r io.Reader) {
br := bufio.NewReader(r)
p := make(Prefix, c.prefixLen)
for {
var s string
if _, err := fmt.Fscan(br, &s); err != nil {
break
}
key := p.String()
c.chain[key] = append(c.chain[key], s)
p.Shift(s)
}
}
// Generate returns a string of at most n words generated from Chain.
func (c *Chain) Generate(n int) string {
p := make(Prefix, c.prefixLen)
var words []string
for i := 0; i < n; i++ {
choices := c.chain[p.String()]
if len(choices) == 0 {
break
}
next := choices[rand.Intn(len(choices))]
words = append(words, next)
p.Shift(next)
}
return strings.Join(words, " ")
}
func main() {
// Register command-line flags.
numWords := flag.Int("words", 100, "maximum number of words to print")
prefixLen := flag.Int("prefix", 2, "prefix length in words")
flag.Parse() // Parse command-line flags.
rand.Seed(time.Nanoseconds()) // Seed the random number generator.
c := NewChain(*prefixLen) // Initialize a new Chain.
c.Build(os.Stdin) // Build chains from standard input.
text := c.Generate(*numWords) // Generate text.
fmt.Println(text) // Write text to standard output.
}

308
doc/codewalk/markov.xml Normal file
View File

@@ -0,0 +1,308 @@
<!--
Copyright 2011 The Go Authors. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
<codewalk title="Generating arbitrary text: a Markov chain algorithm">
<step title="Introduction" src="doc/codewalk/markov.go:/Generating/,/line\./">
This codewalk describes a program that generates random text using
a Markov chain algorithm. The package comment describes the algorithm
and the operation of the program. Please read it before continuing.
</step>
<step title="Modeling Markov chains" src="doc/codewalk/markov.go:/ chain/">
A chain consists of a prefix and a suffix. Each prefix is a set
number of words, while a suffix is a single word.
A prefix can have an arbitrary number of suffixes.
To model this data, we use a <code>map[string][]string</code>.
Each map key is a prefix (a <code>string</code>) and its values are
lists of suffixes (a slice of strings, <code>[]string</code>).
<br/><br/>
Here is the example table from the package comment
as modeled by this data structure:
<pre>
map[string][]string{
" ": {"I"},
" I": {"am"},
"I am": {"a", "not"},
"a free": {"man!"},
"am a": {"free"},
"am not": {"a"},
"a number!": {"I"},
"number! I": {"am"},
"not a": {"number!"},
}</pre>
While each prefix consists of multiple words, we
store prefixes in the map as a single <code>string</code>.
It would seem more natural to store the prefix as a
<code>[]string</code>, but we can't do this with a map because the
key type of a map must implement equality (and slices do not).
<br/><br/>
Therefore, in most of our code we will model prefixes as a
<code>[]string</code> and join the strings together with a space
to generate the map key:
<pre>
Prefix Map key
[]string{"", ""} " "
[]string{"", "I"} " I"
[]string{"I", "am"} "I am"
</pre>
</step>
<step title="The Chain struct" src="doc/codewalk/markov.go:/type Chain/,/}/">
The complete state of the chain table consists of the table itself and
the word length of the prefixes. The <code>Chain</code> struct stores
this data.
</step>
<step title="The NewChain constructor function" src="doc/codewalk/markov.go:/func New/,/}/">
The <code>Chain</code> struct has two unexported fields (those that
do not begin with an upper case character), and so we write a
<code>NewChain</code> constructor function that initializes the
<code>chain</code> map with <code>make</code> and sets the
<code>prefixLen</code> field.
<br/><br/>
This is constructor function is not strictly necessary as this entire
program is within a single package (<code>main</code>) and therefore
there is little practical difference between exported and unexported
fields. We could just as easily write out the contents of this function
when we want to construct a new Chain.
But using these unexported fields is good practice; it clearly denotes
that only methods of Chain and its constructor function should access
those fields. Also, structuring <code>Chain</code> like this means we
could easily move it into its own package at some later date.
</step>
<step title="The Prefix type" src="doc/codewalk/markov.go:/type Prefix/">
Since we'll be working with prefixes often, we define a
<code>Prefix</code> type with the concrete type <code>[]string</code>.
Defining a named type clearly allows us to be explicit when we are
working with a prefix instead of just a <code>[]string</code>.
Also, in Go we can define methods on any named type (not just structs),
so we can add methods that operate on <code>Prefix</code> if we need to.
</step>
<step title="The String method" src="doc/codewalk/markov.go:/func[^\n]+String/,/}/">
The first method we define on <code>Prefix</code> is
<code>String</code>. It returns a <code>string</code> representation
of a <code>Prefix</code> by joining the slice elements together with
spaces. We will use this method to generate keys when working with
the chain map.
</step>
<step title="Building the chain" src="doc/codewalk/markov.go:/func[^\n]+Build/,/\n}/">
The <code>Build</code> method reads text from an <code>io.Reader</code>
and parses it into prefixes and suffixes that are stored in the
<code>Chain</code>.
<br/><br/>
The <code><a href="/pkg/io/#Reader">io.Reader</a></code> is an
interface type that is widely used by the standard library and
other Go code. Our code uses the
<code><a href="/pkg/fmt/#Fscan">fmt.Fscan</a></code> function, which
reads space-separated values from an <code>io.Reader</code>.
<br/><br/>
The <code>Build</code> method returns once the <code>Reader</code>'s
<code>Read</code> method returns <code>os.EOF</code> (end of file)
or some other read error occurs.
</step>
<step title="Buffering the input" src="doc/codewalk/markov.go:/bufio\.NewReader/">
This function does many small reads, which can be inefficient for some
<code>Readers</code>. For efficiency we wrap the provided
<code>io.Reader</code> with
<code><a href="/pkg/bufio/">bufio.NewReader</a></code> to create a
new <code>io.Reader</code> that provides buffering.
</step>
<step title="The Prefix variable" src="doc/codewalk/markov.go:/make\(Prefix/">
At the top of the function we make a <code>Prefix</code> slice
<code>p</code> using the <code>Chain</code>'s <code>prefixLen</code>
field as its length.
We'll use this variable to hold the current prefix and mutate it with
each new word we encounter.
</step>
<step title="Scanning words" src="doc/codewalk/markov.go:/var s string/,/\n }/">
In our loop we read words from the <code>Reader</code> into a
<code>string</code> variable <code>s</code> using
<code>fmt.Fscan</code>. Since <code>Fscan</code> uses space to
separate each input value, each call will yield just one word
(including punctuation), which is exactly what we need.
<br/><br/>
<code>Fscan</code> returns an error if it encounters a read error
(<code>os.EOF</code>, for example) or if it can't scan the requested
value (in our case, a single string). In either case we just want to
stop scanning, so we <code>break</code> out of the loop.
</step>
<step title="Adding a prefix and suffix to the chain" src="doc/codewalk/markov.go:/ key/,/key\], s\)">
The word stored in <code>s</code> is a new suffix. We add the new
prefix/suffix combination to the <code>chain</code> map by computing
the map key with <code>p.String</code> and appending the suffix
to the slice stored under that key.
<br/><br/>
The built-in <code>append</code> function appends elements to a slice
and allocates new storage when necessary. When the provided slice is
<code>nil</code>, <code>append</code> allocates a new slice.
This behavior conveniently ties in with the semantics of our map:
retrieving an unset key returns the zero value of the value type and
the zero value of <code>[]string</code> is <code>nil</code>.
When our program encounters a new prefix (yielding a <code>nil</code>
value in the map) <code>append</code> will allocate a new slice.
<br/><br/>
For more information about the <code>append</code> function and slices
in general see the
<a href="http://blog.golang.org/2011/01/go-slices-usage-and-internals.html">Slices: usage and internals</a> article.
</step>
<step title="Pushing the suffix onto the prefix" src="doc/codewalk/markov.go:/p\.Shift/">
Before reading the next word our algorithm requires us to drop the
first word from the prefix and push the current suffix onto the prefix.
<br/><br/>
When in this state
<pre>
p == Prefix{"I", "am"}
s == "not" </pre>
the new value for <code>p</code> would be
<pre>
p == Prefix{"am", "not"}</pre>
This operation is also required during text generation so we put
the code to perform this mutation of the slice inside a method on
<code>Prefix</code> named <code>Shift</code>.
</step>
<step title="The Shift method" src="doc/codewalk/markov.go:/func[^\n]+Shift/,/\n}/">
The <code>Shift</code> method uses the built-in <code>copy</code>
function to copy the last len(p)-1 elements of <code>p</code> to
the start of the slice, effectively moving the elements
one index to the left (if you consider zero as the leftmost index).
<pre>
p := Prefix{"I", "am"}
copy(p, p[:1])
// p == Prefix{"am", "am"}</pre>
We then assign the provided <code>word</code> to the last index
of the slice:
<pre>
// suffix == "not"
p[len(p)-1] = suffix
// p == Prefix{"am", "not"}</pre>
</step>
<step title="Generating text" src="doc/codewalk/markov.go:/func[^\n]+Generate/,/\n}/">
The <code>Generate</code> method is similar to <code>Build</code>
except that instead of reading words from a <code>Reader</code>
and storing them in a map, it reads words from the map and
appends them to a slice (<code>words</code>).
<br/><br/>
<code>Generate</code> uses a conditional for loop to generate
up to <code>n</code> words.
</step>
<step title="Getting potential suffixes" src="doc/codewalk/markov.go:/choices/,/}\n/">
At each iteration of the loop we retrieve a list of potential suffixes
for the current prefix. We access the <code>chain</code> map at key
<code>p.String()</code> and assign its contents to <code>choices</code>.
<br/><br/>
If <code>len(choices)</code> is zero we break out of the loop as there
are no potential suffixes for that prefix.
This test also works if the key isn't present in the map at all:
in that case, <code>choices</code> will be <code>nil</code> and the
length of a <code>nil</code> slice is zero.
</step>
<step title="Choosing a suffix at random" src="doc/codewalk/markov.go:/next := choices/,/Shift/">
To choose a suffix we use the
<code><a href="/pkg/rand/#Intn">rand.Intn</a></code> function.
It returns a random integer up to (but not including) the provided
value. Passing in <code>len(choices)</code> gives us a random index
into the full length of the list.
<br/><br/>
We use that index to pick our new suffix, assign it to
<code>next</code> and append it to the <code>words</code> slice.
<br/><br/>
Next, we <code>Shift</code> the new suffix onto the prefix just as
we did in the <code>Build</code> method.
</step>
<step title="Returning the generated text" src="doc/codewalk/markov.go:/Join\(words/">
Before returning the generated text as a string, we use the
<code>strings.Join</code> function to join the elements of
the <code>words</code> slice together, separated by spaces.
</step>
<step title="Command-line flags" src="doc/codewalk/markov.go:/Register command-line flags/,/prefixLen/">
To make it easy to tweak the prefix and generated text lengths we
use the <code><a href="/pkg/flag/">flag</a></code> package to parse
command-line flags.
<br/><br/>
These calls to <code>flag.Int</code> register new flags with the
<code>flag</code> package. The arguments to <code>Int</code> are the
flag name, its default value, and a description. The <code>Int</code>
function returns a pointer to an integer that will contain the
user-supplied value (or the default value if the flag was omitted on
the command-line).
</step>
<step title="Program set up" src="doc/codewalk/markov.go:/flag.Parse/,/rand.Seed/">
The <code>main</code> function begins by parsing the command-line
flags with <code>flag.Parse</code> and seeding the <code>rand</code>
package's random number generator with the current time.
<br/><br/>
If the command-line flags provided by the user are invalid the
<code>flag.Parse</code> function will print an informative usage
message and terminate the program.
</step>
<step title="Creating and building a new Chain" src="doc/codewalk/markov.go:/c := NewChain/,/c\.Build/">
To create the new <code>Chain</code> we call <code>NewChain</code>
with the value of the <code>prefix</code> flag.
<br/><br/>
To build the chain we call <code>Build</code> with
<code>os.Stdin</code> (which implements <code>io.Reader</code>) so
that it will read its input from standard input.
</step>
<step title="Generating and printing text" src="doc/codewalk/markov.go:/c\.Generate/,/fmt.Println/">
Finally, to generate text we call <code>Generate</code> with
the value of the <code>words</code> flag and assigning the result
to the variable <code>text</code>.
<br/><br/>
Then we call <code>fmt.Println</code> to write the text to standard
output, followed by a carriage return.
</step>
<step title="Using this program" src="doc/codewalk/markov.go">
To use this program, first compile and link it.
If you are using <code>6g</code> as your compiler, the command
would look something like this:
<pre>
$ 6g markov.go &amp;&amp; 6l -o markov markov.6</pre>
And then execute it while piping in some input text:
<pre>
$ echo "a man a plan a canal panama" | ./markov -prefix=1
a plan a man a plan a canal panama
</pre>
Here's a transcript of generating some text using the Go distribution's
README file as source material:
<pre>
$ ./markov -words=10 &lt $GOROOT/go/README
This is the source code repository for the Go source
$ ./markov -prefix=1 -words=10 &lt $GOROOT/go/README
This is the go directory (the one containing this README).
$ ./markov -prefix=1 -words=10 &lt $GOROOT/go/README
This is the variable if you have just untarred a</pre>
</step>
<step title="An exercise for the reader" src="doc/codewalk/markov.go">
The <code>Generate</code> function does a lot of allocations when it
builds the <code>words</code> slice. As an exercise, modify it to
take an <code>io.Writer</code> to which it incrementally writes the
generated text with <code>Fprint</code>.
Aside from being more efficient this makes <code>Generate</code>
more symmetrical to <code>Build</code>.
</step>
</codewalk>

479
doc/debugging_with_gdb.html Normal file
View File

@@ -0,0 +1,479 @@
<!-- title Debugging Go Code with GDB -->
<p><i>
This applies to the 6g toolchain. Gccgo has native gdb support. Besides this
overview you might want to consult the
<a href="http://sourceware.org/gdb/current/onlinedocs/gdb/">GDB manual</a>.
</i></p>
<h2 id="Introduction">Introduction</h2>
<p>
When you compile and link your Go programs with the 6g/6l or 8g/8l toolchains
on Linux, Mac OSX or FreeBSD, the resulting binaries contain DWARFv3
debugging information that recent versions (>7.1) of the GDB debugger can
use to inspect a live process or a core dump.
</p>
<p>
Pass the <code>'-s'</code> flag to the linker to omit the debug information.
</p>
<h3 id="Common_Operations">Common Operations</h3>
<ul>
<li>
Show file and line number for code
and set breakpoints:
<pre>(gdb) <b>list</b>
(gdb) <b>list <i>line</i></b>
(gdb) <b>list <i>file.go</i>:<i>line</i></b>
(gdb) <b>break <i>line</i></b>
(gdb) <b>break <i>file.go</i>:<i>line</i></b>
(gdb) <b>disas</b></pre>
</li>
<li>
Unwind stack frames:
<pre>(gdb) <b>bt</b>
(gdb) <b>frame <i>n</i></b></pre>
</li>
<li>
Show the name, type and location on the stack frame of local variables,
arguments and return values:
<pre>(gdb) <b>info locals</b>
(gdb) <b>info args</b>
(gdb) <b>p variable</b>
(gdb) <b>whatis variable</b></pre>
</li>
<li>
Show the name, type and location of global variables:
<pre>(gdb) <b>info variables <i>regexp</i></b></pre>
</li>
</ul>
<h3 id="Go_Extensions">Go Extensions</h3>
<p>
A recent extension mechanism to GDB allows it to load extension scripts for a
given binary. The tool chain uses this to extend GDB with a handful of
commands to inspect internals of the runtime code (such as goroutines) and to
pretty print the built-in map, slice and channel types.
</p>
<ul>
<li>
Pretty printing a string, slice, map, channel or interface:
<pre>(gdb) <b>p <i>var</i></b></pre>
</li>
<li>
A $len() and $cap() function for strings, slices and maps:
<pre>(gdb) <b>p $len(<i>var</i>)</b></pre>
</li>
<li>
A function to cast interfaces to their dynamic types:
<pre>(gdb) <b>p $dtype(<i>var</i>)</b>
(gdb) <b>iface <i>var</i></b></pre>
<p class="detail"><b>Known issue:</b> GDB cant automatically find the dynamic
type of an interface value if its long name differs from its short name
(annoying when printing stacktraces, the pretty printer falls back to printing
the short type name and a pointer).</p>
</li>
<li>
Inspecting goroutines:
<pre>(gdb) <b>info goroutines</b>
(gdb) <b>goroutine <i>n</i> <i>cmd</i></b>
(gdb) <b>help goroutine</b></pre>
For example:
<pre>(gdb) <b>goroutine 12 bt</b></pre>
</li>
</ul>
<p>
If you'd like to see how this works, or want to extend it, take a look at <a
href="/src/pkg/runtime/runtime-gdb.py">src/pkg/runtime/runtime-gdb.py</a> in
the Go source distribution. It depends on some special magic types
(<code>hash&lt;T,U&gt;</code>) and variables (<code>runtime.m</code> and
<code>runtime.g</code>) that the linker
(<a href="/src/cmd/ld/dwarf.c">src/cmd/ld/dwarf.c</a>) ensures are described in
the DWARF code.
</ines
<p>
If you're interested in what the debugging information looks like, run
'<code>objdump -W 6.out</code>' and browse through the <code>.debug_*</code>
sections.
</p>
<h3 id="Known_Issues">Known Issues</h3>
<ol>
<li>String pretty printing only triggers for type string, not for types derived
from it.</li>
<li>Type information is missing for the C parts of the runtime library.</li>
<li>GDB does not understand Gos name qualifications and treats
<code>"fmt.Print"</code> as an unstructured literal with a <code>"."</code>
that needs to be quoted. It objects even more strongly to method names of
the form <code>pkg.(*MyType).Meth</code>.
<li>All global variables are lumped into package <code>"main"</code>.</li>
</ol>
<h2 id="Tutorial">Tutorial</h2>
<p>
In this tutorial we will inspect the binary of the
<a href="/pkg/regexp/">regexp</a> package's unit tests. To build the binary,
change to <code>$GOROOT/src/pkg/regexp</code> and run <code>gotest</code>.
This should produce an executable file named <code>6.out</code>.
</p>
<h3 id="Getting_Started">Getting Started</h3>
<p>
Launch GDB, debugging <code>6.out</code>:
</p>
<pre>
$ <b>gdb 6.out</b>
GNU gdb (GDB) 7.2-gg8
Copyright (C) 2010 Free Software Foundation, Inc.
License GPLv 3+: GNU GPL version 3 or later &lt;http://gnu.org/licenses/gpl.html&gt;
Type "show copying" and "show warranty" for licensing/warranty details.
This GDB was configured as "x86_64-linux".
Reading symbols from /home/user/go/src/pkg/regexp/6.out...
done.
Loading Go Runtime support.
(gdb)
</pre>
<p>
The message <code>"Loading Go Runtime support"</code> means that GDB loaded the
extension from <code>$GOROOT/src/pkg/runtime/runtime-gdb.py</code>.
</p>
<p>
To help GDB find the Go runtime sources and the accompanying support script,
pass your <code>$GOROOT</code> with the <code>'-d'</code> flag:
</p>
<pre>
$ <b>gdb 6.out -d $GOROOT</b>
</pre>
<p>
If for some reason GDB still can't find that directory or that script, you can load
it by hand by telling gdb (assuming you have the go sources in
<code>~/go/</code>):
<p>
<pre>
(gdb) <b>source ~/go/src/pkg/runtime/runtime-gdb.py</b>
Loading Go Runtime support.
</pre>
<h3 id="Inspecting_the_source">Inspecting the source</h3>
<p>
Use the <code>"l"</code> or <code>"list"</code> command to inspect source code.
</p>
<pre>
(gdb) <b>l</b>
</pre>
<p>
List a specific part of the source parametrizing <code>"list"</code> with a
function name (it must be qualified with its package name).
</p>
<pre>
(gdb) <b>l main.main</b>
</pre>
<p>
List a specific file and line number:
</p>
<pre>
(gdb) <b>l regexp.go:1</b>
(gdb) <i># Hit enter to repeat last command. Here, this lists next 10 lines.</i>
</pre>
<h3 id="Naming">Naming</h3>
<p>
Variable and function names must be qualified with the name of the packages
they belong to. The <code>Compile</code> function from the <code>regexp</code>
package is known to GDB as <code>'regexp.Compile'</code>.
</p>
<p>
Methods must be qualified with the name of their receiver types. For example,
the <code>*Regexp</code> types <code>doParse</code> method is known as
<code>'regexp.*Regexp.doParse'</code>. (Note that the second dot is a "middot,"
an artifact of Gos internal representation of methods.)
</p>
<p>
Variables that shadow other variables are magically suffixed with a number in the debug info.
Variables referenced by closures will appear as pointers magically prefixed with '&amp'.
</p>
<h3 id="Setting_breakpoints">Setting breakpoints</h3>
<p>
Set a breakpoint at the <code>TestFind</code> function:
</p>
<pre>
(gdb) <b>b 'regexp.TestFind'</b>
Breakpoint 1 at 0x424908: file /home/user/go/src/pkg/regexp/find_test.go, line 148.
</pre>
<p>
Run the program:
</p>
<pre>
(gdb) <b>run</b>
Starting program: /home/lvd/g/src/pkg/regexp/6.out
Breakpoint 1, regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/pkg/regexp/find_test.go:148
148 func TestFind(t *testing.T) {
</pre>
<p>
Execution has paused at the breakpoint.
See which goroutines are running, and what they're doing:
</p>
<pre>
(gdb) <b>info goroutines</b>
1 waiting runtime.gosched
* 13 running runtime.goexit
</pre>
<p>
the one marked with the <code>*</code> is the current goroutine.
</p>
<h3 id="Inspecting_the_stack">Inspecting the stack</h3>
<p>
Look at the stack trace for where weve paused the program:
</p>
<pre>
(gdb) <b>bt</b> <i># backtrace</i>
#0 regexp.TestFind (t=0xf8404a89c0) at /home/user/go/src/pkg/regexp/find_test.go:148
#1 0x000000000042f60b in testing.tRunner (t=0xf8404a89c0, test=0x573720) at /home/user/go/src/pkg/testing/testing.go:156
#2 0x000000000040df64 in runtime.initdone () at /home/user/go/src/pkg/runtime/proc.c:242
#3 0x000000f8404a89c0 in ?? ()
#4 0x0000000000573720 in ?? ()
#5 0x0000000000000000 in ?? ()
</pre>
<p>
The other goroutine, number 1, is stuck in <code>runtime.gosched</code>, blocked on a channel receive:
</p>
<pre>
(gdb) <b>goroutine 1 bt</b>
#0 0x000000000040facb in runtime.gosched () at /home/lvd/g/src/pkg/runtime/proc.c:873
#1 0x00000000004031c9 in runtime.chanrecv (c=void, ep=void, selected=void, received=void)
at /home/lvd/g/src/pkg/runtime/chan.c:342
#2 0x0000000000403299 in runtime.chanrecv1 (t=void, c=void) at/home/lvd/g/src/pkg/runtime/chan.c:423
#3 0x000000000043075b in testing.RunTests (matchString={void (struct string, struct string, bool *, os.Error *)} 0x7ffff7f9ef60, tests= []testing.InternalTest = {...}) at /home/lvd/g/src/pkg/testing/testing.go:201
#4 0x00000000004302b1 in testing.Main (matchString={void (struct string, struct string, bool *, os.Error *)} 0x7ffff7f9ef80, tests= []testing.InternalTest = {...}, benchmarks= []testing.InternalBenchmark = {...})
at /home/lvd/g/src/pkg/testing/testing.go:168
#5 0x0000000000400dc1 in main.main () at /home/lvd/g/src/pkg/regexp/_testmain.go:98
#6 0x00000000004022e7 in runtime.mainstart () at /home/lvd/g/src/pkg/runtime/amd64/asm.s:78
#7 0x000000000040ea6f in runtime.initdone () at /home/lvd/g/src/pkg/runtime/proc.c:243
#8 0x0000000000000000 in ?? ()
</pre>
<p>
The stack frame shows were currently executing the <code>regexp.TestFind</code> function, as expected.
</p>
<pre>
(gdb) <b>info frame</b>
Stack level 0, frame at 0x7ffff7f9ff88:
rip = 0x425530 in regexp.TestFind (/home/lvd/g/src/pkg/regexp/find_test.go:148);
saved rip 0x430233
called by frame at 0x7ffff7f9ffa8
source language minimal.
Arglist at 0x7ffff7f9ff78, args: t=0xf840688b60
Locals at 0x7ffff7f9ff78, Previous frame's sp is 0x7ffff7f9ff88
Saved registers:
rip at 0x7ffff7f9ff80
</pre>
<p>
The command <code>info locals</code> lists all variables local to the function and their values, but is a bit
dangerous to use, since it will also try to print uninitialized variables. Uninitialized slices may cause gdb to try
to print arbitrary large arrays.
</p>
<p>
The functions arguments:
</p>
<pre>
(gdb) <b>info args</b>
t = 0xf840688b60
</pre>
<p>
When printing the argument, notice that its a pointer to a
<code>Regexp</code> value. Note that GDB has incorrectly put the <code>*</code>
on the right-hand side of the type name and made up a 'struct' keyword, in traditional C style.
</p>
<pre>
(gdb) <b>p re</b>
(gdb) p t
$1 = (struct testing.T *) 0xf840688b60
(gdb) p t
$1 = (struct testing.T *) 0xf840688b60
(gdb) p *t
$2 = {errors = "", failed = false, ch = 0xf8406f5690}
(gdb) p *t->ch
$3 = struct hchan<*testing.T>
</pre>
<p>
That <code>struct hchan<*testing.T></code> is the runtime-internal represntation of a channel. It is currently empty, or gdb would have pretty-printed it's contents.
</p>
<p>
Stepping forward:
</p>
<pre>
(gdb) <b>n</b> <i># execute next line</i>
149 for _, test := range findTests {
(gdb) <i># enter is repeat</i>
150 re := MustCompile(test.pat)
(gdb) <b>p test.pat</b>
$4 = ""
(gdb) <b>p re</b>
$5 = (struct regexp.Regexp *) 0xf84068d070
(gdb) <b>p *re</b>
$6 = {expr = "", prog = 0xf840688b80, prefix = "", prefixBytes = []uint8, prefixComplete = true,
prefixRune = 0, cond = 0 '\000', numSubexp = 0, longest = false, mu = {state = 0, sema = 0},
machine = []*regexp.machine}
(gdb) <b>p *re->prog</b>
$7 = {Inst = []regexp/syntax.Inst = {{Op = 5 '\005', Out = 0, Arg = 0, Rune = []int}, {Op =
6 '\006', Out = 2, Arg = 0, Rune = []int}, {Op = 4 '\004', Out = 0, Arg = 0, Rune = []int}},
Start = 1, NumCap = 2}
</pre>
<p>
We can step into the <code>String</code>function call with <code>"s"</code>:
</p>
<pre>
(gdb) <b>s</b>
regexp.(*Regexp).String (re=0xf84068d070, noname=void) at /home/lvd/g/src/pkg/regexp/regexp.go:97
97 func (re *Regexp) String() string {
</pre>
<p>
Get a stack trace to see where we are:
</p>
<pre>
(gdb) <b>bt</b>
(gdb) bt
#0 regexp.(*Regexp).String (re=0xf84068d070, noname=void)
at /home/lvd/g/src/pkg/regexp/regexp.go:97
#1 0x0000000000425615 in regexp.TestFind (t=0xf840688b60)
at /home/lvd/g/src/pkg/regexp/find_test.go:151
#2 0x0000000000430233 in testing.tRunner (t=0xf840688b60, test=0x5747b8)
at /home/lvd/g/src/pkg/testing/testing.go:156
#3 0x000000000040ea6f in runtime.initdone () at /home/lvd/g/src/pkg/runtime/proc.c:243
....
</pre>
<p>
Look at the source code:
</p>
<pre>
(gdb) <b>l</b>
92 mu sync.Mutex
93 machine []*machine
94 }
95
96 // String returns the source text used to compile the regular expression.
97 func (re *Regexp) String() string {
98 return re.expr
99 }
100
101 // Compile parses a regular expression and returns, if successful,
</pre>
<h3 id="Pretty_Printing">Pretty Printing</h3>
<p>
GDB's pretty printing mechanism is triggered by regexp matches on type names. An example for slices:
</p>
<pre>
(gdb) <b>p utf</b>
$22 = []uint8 = {0 '\000', 0 '\000', 0 '\000', 0 '\000'}
</pre>
<p>
Since slices, arrays and strings are not C pointers, GDB can't interpret the subscripting operation for you, but
you can look inside the runtime representation to do that (tab completion helps here):
</p>
<pre>
(gdb) <b>p slc</b>
$11 = []int = {0, 0}
(gdb) <b>p slc-&gt</b><i>&ltTAB&gt</i>
array slc len
(gdb) <b>p slc->array</b>
$12 = (int *) 0xf84057af00
(gdb) <b>p slc->array[1]</b>
$13 = 0</pre>
<p>
The extension functions $len and $cap work on strings, arrays and slices:
</p>
<pre>
(gdb) <b>p $len(utf)</b>
$23 = 4
(gdb) <b>p $cap(utf)</b>
$24 = 4
</pre>
<p>
Channels and maps are 'reference' types, which gdb shows as pointers to C++-like types <code>hash&ltint,string&gt*</code>. Dereferencing will trigger prettyprinting
</p>
<p>
Interfaces are represented in the runtime as a pointer to a type descriptor and a pointer to a value. The Go GDB runtime extension decodes this and automatically triggers pretty printing for the runtime type. The extension function <code>$dtype</code> decodes the dynamic type for you (examples are taken from a breakpoint at <code>regexp.go</code> line 293.)
</p>
<pre>
(gdb) <b>p i</b>
$4 = {str = "cbb"}
(gdb) <b>whatis i</b>
type = regexp.input
(gdb) <b>p $dtype(i)</b>
$26 = (struct regexp.inputBytes *) 0xf8400b4930
(gdb) <b>iface i</b>
regexp.input: struct regexp.inputBytes *
</pre>

View File

@@ -14,6 +14,294 @@ hg pull
hg update release.r<i>NN</i>
</pre>
<h2 id="r60">r60 (released 2011/09/07)</h2>
<p>
The r60 release corresponds to
<code><a href="weekly.html#2011-08-17">weekly.2011-08-17</a></code>.
This section highlights the most significant changes in this release.
For a more detailed summary, see the
<a href="weekly.html#2011-08-17">weekly release notes</a>.
For complete information, see the
<a href="http://code.google.com/p/go/source/list?r=release-branch.r60">Mercurial change list</a>.
</p>
<h3 id="r60.lang">Language</h3>
<p>
An "else" block is now required to have braces except if the body of the "else"
is another "if". Since gofmt always puts those braces in anyway,
gofmt-formatted programs will not be affected.
To fix other programs, run gofmt.
</p>
<h3 id="r60.pkg">Packages</h3>
<p>
<a href="/pkg/http/">Package http</a>'s URL parsing and query escaping code
(such as <code>ParseURL</code> and <code>URLEscape</code>) has been moved to
the new <a href="/pkg/url/">url package</a>, with several simplifications to
the names. Client code can be updated automatically with gofix.
</p>
<p>
<a href="/pkg/image/">Package image</a> has had significant changes made to the
<code>Pix</code> field of struct types such as
<a href="/pkg/image/#RGBA">image.RGBA</a> and
<a href="/pkg/image/#NRGBA">image.NRGBA</a>.
The <a href="/pkg/image/#Image">image.Image</a> interface type has not changed,
though, and you should not need to change your code if you don't explicitly
refer to <code>Pix</code> fields. For example, if you decode a number of images
using the <a href="/pkg/image/jpeg/">image/jpeg</a> package, compose them using
<a href="/pkg/image/draw/">image/draw</a>, and then encode the result using
<a href="/pkg/img/png">image/png</a>, then your code should still work as
before.
If your code <i>does</i> refer to <code>Pix</code> fields see the
<a href="/doc/devel/weekly.html#2011-07-19">weekly.2011-07-19</a>
snapshot notes for how to update your code.
</p>
<p>
<a href="/pkg/template/">Package template</a> has been replaced with a new
templating package (formerly <code>exp/template</code>). The original template
package is still available as <a href="/pkg/old/template/">old/template</a>.
The <code>old/template</code> package is deprecated and will be removed.
The Go tree has been updated to use the new template package. We encourage
users of the old template package to switch to the new one. Code that uses
<code>template</code> or <code>exp/template</code> will need to change its
import lines to <code>"old/template"</code> or <code>"template"</code>,
respectively.
</p>
<h3 id="r60.cmd">Tools</h3>
<p>
<a href="/cmd/goinstall/">Goinstall</a> now uses a new tag selection scheme.
When downloading or updating, goinstall looks for a tag or branch with the
<code>"go."</code> prefix that corresponds to the local Go version. For Go
<code>release.r58</code> it looks for <code>go.r58</code>. For
<code>weekly.2011-06-03</code> it looks for <code>go.weekly.2011-06-03</code>.
If the specific <code>go.X</code> tag or branch is not found, it chooses the
closest earlier version. If an appropriate tag or branch is found, goinstall
uses that version of the code. Otherwise it uses the default version selected
by the version control system. Library authors are encouraged to use the
appropriate tag or branch names in their repositories to make their libraries
more accessible.
</p>
<h3 id="r60.minor">Minor revisions</h3>
<p>
r60.1 includes a
<a href="http://code.google.com/p/go/source/detail?r=1824581bf62d">linker
fix</a>, a pair of
<a href="http://code.google.com/p/go/source/detail?r=9ef4429c2c64">goplay</a>
<a href="http://code.google.com/p/go/source/detail?r=d42ed8c3098e">fixes</a>,
and a <code>json</code> package
<a href="http://code.google.com/p/go/source/detail?r=d5e97874fe84">fix</a> and
a new
<a href="http://code.google.com/p/go/source/detail?r=4f0e6269213f">struct tag
option</a>.
</p>
<p>
r60.2
<a href="http://code.google.com/p/go/source/detail?r=ff19536042ac">fixes</a>
a memory leak involving maps.
</p>
<p>
r60.3 fixes a
<a href="http://code.google.com/p/go/source/detail?r=01fa62f5e4e5">reflect bug</a>.
</p>
<h2 id="r59">r59 (released 2011/08/01)</h2>
<p>
The r59 release corresponds to
<code><a href="weekly.html#2011-07-07">weekly.2011-07-07</a></code>.
This section highlights the most significant changes in this release.
For a more detailed summary, see the
<a href="weekly.html#2011-07-07">weekly release notes</a>.
For complete information, see the
<a href="http://code.google.com/p/go/source/list?r=release-branch.r59">Mercurial change list</a>.
</p>
<h3 id="r59.lang">Language</h3>
<p>
This release includes a language change that restricts the use of
<code>goto</code>. In essence, a <code>goto</code> statement outside a block
cannot jump to a label inside that block. Your code may require changes if it
uses <code>goto</code>.
See <a href="http://code.google.com/p/go/source/detail?r=dc6d3cf9279d">this
changeset</a> for how the new rule affected the Go tree.
</p>
<h3 id="r59.pkg">Packages</h3>
<p>
As usual, <a href="/cmd/gofix/">gofix</a> will handle the bulk of the rewrites
necessary for these changes to package APIs.
</p>
<p>
<a href="/pkg/http">Package http</a> has a new
<a href="/pkg/http/#FileSystem">FileSystem</a> interface that provides access
to files. The <a href="/pkg/http/#FileServer">FileServer</a> helper now takes a
<code>FileSystem</code> argument instead of an explicit file system root. By
implementing your own <code>FileSystem</code> you can use the
<code>FileServer</code> to serve arbitrary data.
</p>
<p>
<a href="/pkg/os/">Package os</a>'s <code>ErrorString</code> type has been
hidden. Most uses of <code>os.ErrorString</code> can be replaced with
<a href="/pkg/os/#NewError">os.NewError</a>.
</p>
<p>
<a href="/pkg/reflect/">Package reflect</a> supports a new struct tag scheme
that enables sharing of struct tags between multiple packages.
In this scheme, the tags must be of the form:
</p>
<pre>
`key:"value" key2:"value2"`
</pre>
<p>
The <a href="/pkg/reflect/#StructField">StructField</a> type's Tag field now
has type <a href="/pkg/reflect/#StructTag">StructTag</a>, which has a
<code>Get</code> method. Clients of <a href="/pkg/json">json</a> and
<a href="/pkg/xml">xml</a> will need to be updated. Code that says
</p>
<pre>
type T struct {
X int "name"
}
</pre>
<p>
should become
</p>
<pre>
type T struct {
X int `json:"name"` // or `xml:"name"`
}
</pre>
<p>
Use <a href="/cmd/govet/">govet</a> to identify struct tags that need to be
changed to use the new syntax.
</p>
<p>
<a href="/pkg/sort/">Package sort</a>'s <code>IntArray</code> type has been
renamed to <a href="/pkg/sort/#IntSlice">IntSlice</a>, and similarly for
<a href="/pkg/sort/#Float64Slice">Float64Slice</a> and
<a href="/pkg/sort/#StringSlice">StringSlice</a>.
</p>
<p>
<a href="/pkg/strings/">Package strings</a>'s <code>Split</code> function has
itself been split into <a href="/pkg/strings/#Split">Split</a> and
<a href="/pkg/strings/#SplitN">SplitN</a>.
<code>SplitN</code> is the same as the old <code>Split</code>.
The new <code>Split</code> is equivalent to <code>SplitN</code> with a final
argument of -1.
</p>
<a href="/pkg/image/draw/">Package image/draw</a>'s
<a href="/pkg/image/draw/#Draw">Draw</a> function now takes an additional
argument, a compositing operator.
If in doubt, use <a href="/pkg/image/draw/#Op">draw.Over</a>.
</p>
<h3 id="r59.cmd">Tools</h3>
<p>
<a href="/cmd/goinstall/">Goinstall</a> now installs packages and commands from
arbitrary remote repositories (not just Google Code, Github, and so on).
See the <a href="/cmd/goinstall/">goinstall documentation</a> for details.
</p>
<h2 id="r58">r58 (released 2011/06/29)</h2>
<p>
The r58 release corresponds to
<code><a href="weekly.html#2011-06-09">weekly.2011-06-09</a></code>
with additional bug fixes.
This section highlights the most significant changes in this release.
For a more detailed summary, see the
<a href="weekly.html#2011-06-09">weekly release notes</a>.
For complete information, see the
<a href="http://code.google.com/p/go/source/list?r=release-branch.r58">Mercurial change list</a>.
</p>
<h3 id="r58.lang">Language</h3>
<p>
This release fixes a <a href="http://code.google.com/p/go/source/detail?r=b720749486e1">use of uninitialized memory in programs that misuse <code>goto</code></a>.
</p>
<h3 id="r58.pkg">Packages</h3>
<p>
As usual, <a href="/cmd/gofix/">gofix</a> will handle the bulk of the rewrites
necessary for these changes to package APIs.
</p>
<p>
<a href="/pkg/http/">Package http</a> drops the <code>finalURL</code> return
value from the <a href="/pkg/http/#Client.Get">Client.Get</a> method. The value
is now available via the new <code>Request</code> field on <a
href="/pkg/http/#Response">http.Response</a>.
Most instances of the type map[string][]string in have been
replaced with the new <a href="/pkg/http/#Values">Values</a> type.
</p>
<p>
<a href="/pkg/exec/">Package exec</a> has been redesigned with a more
convenient and succinct API.
</p>
<p>
<a href="/pkg/strconv/">Package strconv</a>'s <a href="/pkg/strconv/#Quote">Quote</a>
function now escapes only those Unicode code points not classified as printable
by <a href="/pkg/unicode/#IsPrint">unicode.IsPrint</a>.
Previously Quote would escape all non-ASCII characters.
This also affects the <a href="/pkg/fmt/">fmt</a> package's <code>"%q"</code>
formatting directive. The previous quoting behavior is still available via
strconv's new <a href="/pkg/strconv/#QuoteToASCII">QuoteToASCII</a> function.
</p>
<p>
<a href="/pkg/os/signal/">Package os/signal</a>'s
<a href="/pkg/os/#Signal">Signal</a> and
<a href="/pkg/os/#UnixSignal">UnixSignal</a> types have been moved to the
<a href="/pkg/os/">os</a> package.
</p>
<p>
<a href="/pkg/image/draw/">Package image/draw</a> is the new name for
<code>exp/draw</code>. The GUI-related code from <code>exp/draw</code> is now
located in the <a href="/pkg/exp/gui/">exp/gui</a> package.
</p>
<h3 id="r58.cmd">Tools</h3>
<p>
<a href="/cmd/goinstall/">Goinstall</a> now observes the GOPATH environment
variable to build and install your own code and external libraries outside of
the Go tree (and avoid writing Makefiles).
</p>
<h3 id="r58.minor">Minor revisions</h3>
<p>r58.1 adds
<a href="http://code.google.com/p/go/source/detail?r=293c25943586">build</a> and
<a href="http://code.google.com/p/go/source/detail?r=bf17e96b6582">runtime</a>
changes to make Go run on OS X 10.7 Lion.
</p>
<h2 id="r57">r57 (released 2011/05/03)</h2>
<p>
@@ -136,7 +424,7 @@ Remember that gofix will handle the bulk of the rewrites
necessary for these changes to package APIs.
</p>
<h3 id="r57.tool">Tools</h3>
<h3 id="r57.cmd">Tools</h3>
<p><a href="/cmd/gofix/">Gofix</a>, a new command, is described above.</p>
@@ -162,6 +450,7 @@ For other uses, see the <a href="/pkg/runtime/pprof/">runtime/pprof</a> document
<h3 id="r57.minor">Minor revisions</h3>
<p>r57.1 fixes a <a href="http://code.google.com/p/go/source/detail?r=ff2bc62726e7145eb2ecc1e0f076998e4a8f86f0">nil pointer dereference in http.FormFile</a>.</p>
<p>r57.2 fixes a <a href="http://code.google.com/p/go/source/detail?r=063b0ff67d8277df03c956208abc068076818dae">use of uninitialized memory in programs that misuse <code>goto</code></a>.</p>
<h2 id="r56">r56 (released 2011/03/16)</h2>

View File

@@ -14,7 +14,700 @@ hg pull
hg update weekly.<i>YYYY-MM-DD</i>
</pre>
<h2 id="2011-06-09">2011-06-09</h2>
<h2 id="2011-09-07">2011-09-07</h2>
<pre>
This weekly snapshot consists of improvements and bug fixes, including fixes
for issues introduced by escape analysis changes in the gc compiler.
* build: clear execute bit from Go files (thanks Mike Rosset),
error out if problem with sudo.bash /usr/local/bin (thanks Mike Rosset).
* exp/norm: add Reader and Writer,
performance improvements of quickSpan.
* exp/regexp: bug fixes and RE2 tests.
* exp/template/html: string replacement refactoring,
tweaks to js{,_test}.go.
* gc: add -p flag to catch import cycles earlier,
fix label recursion bugs,
fix zero-length struct eval,
zero stack-allocated slice backing arrays,
* gc, ld: fix Windows file paths (thanks Hector Chu).
* go/parser: accept corner cases of signature syntax.
* gobuilder: ignore _test.go files when looking for docs, more logging.
* godoc: minor tweaks for App Engine use.
* gofix: do not convert url in field names (thanks Gustavo Niemeyer).
* gofmt: indent multi-line signatures.
* gopprof: regexp fixes (thanks Hector Chu).
* image/png: check zlib checksum during Decode.
* libmach: fix incorrect use of memset (thanks Dave Cheney).
* misc/goplay: fix template output.
* net: ParseCIDR returns IPNet instead of IPMask (thanks Mikio Hara),
sync CIDRMask code, doc.
* os: use GetFileAttributesEx to implement Stat on windows (thanks Alex Brainman).
* runtime: fix openbsd 386 raisesigpipe,
implement exception handling on windows/amd64 (thanks Hector Chu),
test for concurrent channel consumers (thanks Christopher Wedgwood).
* sort: use heapsort to bail out quicksort (thanks Ziad Hatahet).
* sync/atomic: add LoadUintptr, add Store functions.
* syscall: update routing message attributes handling (thanks Mikio Hara).
* template: fix deadlock,
indirect or dereference function arguments if necessary,
slightly simplify the test for assignability of arguments.
* url: handle ; in ParseQuery.
* websocket: fix incorrect prints found by govet (thanks Robert Hencke).
</pre>
<h2 id="2011-09-01">2011-09-01</h2>
<pre>
This weekly contains performance improvements and bug fixes.
The gc compiler now does escape analysis, which improves program performance
by placing variables on the call stack instead of the heap when it is safe to
do so.
The container/vector package is deprecated and will be removed at some point
in the future.
Other changes:
* archive/tar: support symlinks. (thanks Mike Rosset)
* big: fix nat.scan bug. (thanks Evan Shaw)
* bufio: handle a "\r\n" that straddles the buffer.
add openbsd.
avoid redundant bss declarations.
fix unused parameters.
fix windows/amd64 build with newest mingw-w64. (thanks Hector Chu)
* bytes: clarify that NewBuffer is not for beginners.
* cgo: explain how to free something.
fix GoBytes. (thanks Gustavo Niemeyer)
fixes callback for windows amd64. (thanks Wei Guangjing)
note that CString result must be freed. (thanks Gustavo Niemeyer)
* cov: remove tautological #defines. (thanks Lucio De Re)
* dashboard: yet another utf-8 fix.
* doc/codelab/wiki: fix Makefile.
* doc/progs: fix windows/amd64. (thanks Jaroslavas Počepko)
* doc/tmpltohtml: update to new template package.
* doc: emphasize that environment variables are optional.
* effective_go: convert to use tmpltohtml.
* exp/norm: reduced the size of the byte buffer used by reorderBuffer by half by reusing space when combining.
a few minor fixes to support the implementation of norm.
added implementation for []byte versions of methods.
* exp/template/html: add some tests for ">" attributes.
added handling for URL attributes.
differentiate URL-valued attributes (such as href).
reworked escapeText to recognize attr boundaries.
* exp/wingui: made compatible with windows/amd64. (thanks Jaroslavas Počepko)
* flag: add Parsed, restore Usage.
* gc: add openbsd.
escape analysis.
fix build on Plan 9. (thanks Lucio De Re)
fix div bug.
fix pc/line table. (thanks Julian Phillips)
fix some spurious leaks.
make static initialization more static.
remove JCXZ; add JCXZW, JCXZL, and JCXZQ instructions. (thanks Jaroslavas Počepko)
shuffle #includes.
simplify escape analysis recursion.
tweak and enable escape analysis.
* go/ast cleanup: base File/PackageExports on FilterFile/FilterPackage code.
adjustments to filter function.
fix ast.MergePackageFiles to collect infos about imports. (thanks Sebastien Binet)
generalize ast.FilterFile.
* go/build: add test support & use in gotest.
separate test imports out when scanning. (thanks Gustavo Niemeyer)
* go/parser: fix type switch scoping.
fix type switch scoping.
* gob: explain that Debug isn't useful unless it's compiled in.
* gobuilder: increase log limit.
* godashboard: fix utf-8 in user names.
* godoc: first step towards reducing index size.
add dummy playground.js to silence godoc warning at start-up.
added systematic throttling to indexing goroutine.
fix bug in zip.go.
support for reading/writing (splitted) index files.
use virtual file system when generating package synopses.
* gofix: forgot to rename the URL type.
osopen: fixed=true when changing O_CREAT. (thanks Tarmigan Casebolt)
* goinstall: error out with paths that end with '/'. (thanks Tarmigan Casebolt)
report lack of $GOPATH on errors. (thanks Gustavo Niemeyer)
select the tag that is closest to runtime.Version.
* gotry: add missing $. (thanks Tarmigan Casebolt)
* http: add MaxBytesReader to limit request body size.
add file protocol transport.
adjust test threshold for larger suse buffers.
delete error kludge.
on invalid request, send 400 response.
return 413 instead of 400 when the request body is too large. (thanks Dave Cheney)
support setting Transport's TLS client config.
* image/tiff: add a decode benchmark. (thanks Benny Siegert)
decoder optimization. (thanks Benny Siegert)
* image: add PalettedImage interface, and make image/png recognize it. (thanks Jaroslavas Počepko)
* io: add TeeReader. (thanks Hector Chu)
* json: add struct tag option to wrap literals in strings.
calculate Offset for Indent correctly. (thanks Jeff Hodges)
fix decode bug with struct tag names with ,opts being ignored.
* ld: handle Plan 9 ar format. (thanks Lucio De Re)
remove duplicate bss definitions.
* libmach: support reading symbols from Windows .exe for nm. (thanks Mateusz Czapliński)
* math: fix Pow10 loop. (thanks Volker Dobler)
* mime: ParseMediaType returns os.Error now, not a nil map.
media type formatter. (thanks Pascal S. de Kloe)
text charset defaults. (thanks Pascal S. de Kloe)
* misc/dashboard: remove limit for json package list.
* misc/emacs: refine label detection.
* net: add ParseMAC function. (thanks Paul Borman)
change the internal form of IPMask for IPv4. (thanks Mikio Hara)
disable "tcp" test on openbsd.
fix windows build. (thanks Alex Brainman)
join and leave a IPv6 group address, on a specific interface. (thanks Mikio Hara)
make use of IPv4len, IPv6len. (thanks Mikio Hara)
move internal string manipulation routines to parse.go. (thanks Mikio Hara)
* os: disable Hostname test on OpenBSD.
fix WNOHANG Waitmsg. (thanks Gustavo Niemeyer)
* reflect: add Value.Bytes, Value.SetBytes methods.
* rpc: add benchmark for async rpc calls.
* runtime: add openbsd 386 defs.h.
add runtime support for openbsd 386.
add runtime· prefix to showframe.
ctrlhandler for windows amd64. (thanks Wei Guangjing)
fix stack cleanup on windows/amd64. (thanks Hector Chu)
fix void warnings.
go interface to cdecl calbacks. (thanks Jaroslavas Počepko)
handle string + char literals in goc2c.
make arm work on Ubuntu Natty qemu.
openbsd thread tweaks.
simplify stack traces.
speed up cgo calls. (thanks Alex Brainman)
use cgo runtime functions to call windows syscalls. (thanks Alex Brainman)
windows/amd64 callbacks fixed and syscall fixed to allow using it in callbacks. (thanks Jaroslavas Počepko)
* strconv: put decimal on stack.
* spec: update section on Implementation Differences.
* syscall: SOMAXCONN should be 0x7fffffff at winsock2. (thanks Yasuhiro Matsumoto)
add openbsd 386.
handle RTM_NEWROUTE in ParseNetlinkRouteAttr on Linux. (thanks Albert Strasheim)
handle routing entry in ParseRoutingSockaddr on BSD variants. (thanks Mikio Hara)
openbsd amd64 syscall support.
use the vdso page on linux x86 for faster syscalls instead of int $0x80. (thanks Yuval Pavel Zholkover)
* template/parse: give if, range, and with a common representation.
* template: grammar fix for template documentation. (thanks Bill Neubauer)
range over channel.
remove else and end nodes from public view.
* test: put GOROOT/bin before all others in run.
* time: fix Plan 9 build. (thanks Fazlul Shahriar)
fix zone during windows test.
* type switches: test for pathological case.
* version.bash: update VERSION on -save if already present. (thanks Gustavo Niemeyer)
* websocket: implements new version of WebSocket protocol. (thanks Fumitoshi Ukai)
* windows/386: clean stack after syscall. (thanks Jaroslavas Počepko)
* xml: marshal "parent>child" tags correctly. (thanks Ross Light)
</pre>
<h2 id="2011-08-17">2011-08-17 (<a href="release.html#r60">base for r60</a>)</h2>
<pre>
This weekly contains some package re-shuffling. Users of the http and
template packages may be affected.
This weekly replaces the template package with exp/template.
The original template package is still available as old/template.
The old/template package is deprecated and will be removed at some point
in the future. The Go tree has been updated to use the new template package.
We encourage users of the old template package to switch to the new one.
Code that uses template or exp/template will need to change
its import lines to "old/template" or "template", respectively.
The http package's URL parsing and query escaping code (such as ParseURL and
URLEscape) has been moved to the new url package, with several simplifications
to the names. Client code can be updated automatically with gofix.
* asn1: support unmarshalling structs with int32 members (thanks Dave Cheney).
* build: allow builds without cgo or hg,
support versioning without hg (thanks Gustavo Niemeyer).
* builtin: add documentation for builtins.
* cgo: omit duplicate symbols in writeDefs (thanks Julian Phillips).
* misc: add support for OpenBSD.
* doc/codewalk: new Markov chain codewalk.
* exp/norm: added trie lookup code and associated tests,
generate trie struct in triegen.go for better encapsulation,
implementation of decomposition and composing functionality.
* exp/template/html: new experimental package for auto-escaping HTML templates.
* exp/template: don't panic on range of nil interface,
rename Parse*File and Parse*Files for clarity,
support field syntax on maps (thanks Gustavo Niemeyer), and
many other fixes and changes.
* gc: implement nil chan and nil map support.
* go/parser: range clause and type literal fixes.
* godoc: show all top-level decls for (fake) package builtin.
* goinstall: really report all newly-installed public packages.
* html: parse more malformed tags.
* http: fix ParseMultipartForm after MultipartReader error,
fix side effects in DefaultTransport's RoundTrip method (thanks Dave Grijalva).
* json: fix []unmarshaler case.
* ld: make addaddrplus4 static (thanks Lucio De Re).
* syscall: move multicast address handling to the net package.
* net: Plan 9 support (thanks Fazlul Shahriar),
add SetTimeout to Listener interface (thanks Aleksandar Dezelin),
add multicast stubs for OpenBSD,
return correct local address for an accepted TCP connection (thanks Mikio Hara).
* reflect: panic on Invalid Interface call (thanks Gustavo Niemeyer).
* rpc: implement ServeRequest to synchronously serve a single request,
make Server.Mutex unexported.
* runtime: better checks for syscall.NewCallback parameter (thanks Alex Brainman),
correct SEH installation during callbacks (thanks Alex Brainman),
fix GC bitmap corruption,
fix pseudo-randomness on some selects (thanks Gustavo Niemeyer).
* syscall: make LazyDLL/LazyProc.Mutex unexported.
* test: allow multiple patterns in errchk,
new nil semantics.
* time: take fractional seconds even if not in the format string.
* url: new package.
* utf8: rename some internal constants to remove leading underscores.
* xml: escape string chardata in xml.Marshal.
</pre>
<h2 id="2011-08-10">2011-08-10</h2>
<pre>
This weekly contains performance improvements and bug fixes.
There are no outward-facing changes, but imports of the old-style
container/vector package have also been removed from the core library (thanks
John Asmuth, Kyle Consalus).
Other changes:
* 5g: fix set but not used error (thanks Dave Cheney).
* cmd/ld: Corrected mismatched print formats and variables (thanks Lucio De Re).
* errchk: add -0 flag.
* exp/norm: fix build by adding a test placeholder,
maketables tool for generating tables for normalization.
* exp/template: bug fixes,
ensure that a valid Set is returned even on error (thanks Roger Peppe),
make index on maps return zero when key not present (thanks Roger Peppe),
split the parse tree into a separate package exp/template/parse,
add url query formatting filter.
* faq: lots of small tweaks plus a couple of new discussions,
variant types, unions.
* fmt: call UpdateMemStats in malloc counter.
* go/build: use GOBIN as binary path for GOROOT.
* gob: add UpdateMemStats calls to malloc counter,
avoid a couple of init-time allocations,
don't invoke GobEncoder on zero values.
* gofmt: update test script so 'make test' succeeds.
* html: parse doctype tokens; merge adjacent text nodes.
* http: add more MPEG-4 MIME types to sniffer, and disable MP4 sniffing,
add test to serve content in index.html (thanks Yasuhiro Matsumoto),
configurable and default request header size limit,
correct format flags when printing errors in tests (thanks Alex Brainman),
correct path to serve index.html (thanks Yasuhiro Matsumoto),
* ld: add one empty symbol into pe to make dumpbin works (thanks Wei Guangjing),
fail linking if the top-level package is not main.
* misc/vim: godoc command (thanks Yasuhiro Matsumoto).
* net: add support for openbsd (thanks Joel Sing),
fix /proc/net/igmp,igmp6 reading bug on linux (thanks Mikio Hara),
implement windows LookupMX and LookupAddr (thanks Mikio Hara),
sort SRV records before returning from LookupSRV (thanks Alex Brainman),
* os: add support for openbsd (thanks Joel Sing).
* runtime: add more specialized type algorithms,
correct Note documentation,
faster chan creation on Linux/FreeBSD/Plan9,
openbsd amd64 runtime support (thanks Joel Sing),
remove unnecessary locking (thanks Hector Chu).
* scanner: correct error position for illegal UTF-8 encodings.
* syscall: delay load of dll functions on Windows (thanks Alex Brainman),
move BSD mmap syscall (thanks Joel Sing),
update routing message support for BSD variants (thanks Mikio Hara).
* test/bench: note changes after recent improvements to locking and runtime.
* time: add nanoseconds to the Time structure,
parse and format fractional seconds.
</pre>
<h2 id="2011-07-29">2011-07-29</h2>
<pre>
This weekly contains performance improvements and many bug fixes.
* 6l: OpenBSD support.
* archive/zip: handle zip files with more than 65535 files,
more efficient reader and bug fix.
* big: refine printf formatting and optimize string conversion.
* build: fixes for mingw-w64 (thanks Wei Guangjing),
miscellaneous fixes.
* cgo: add GoBytes, fix gmp example.
* exp/norm: API for normalization library.
* exp/regexp: implement regexp API using exp/regexp/syntax.
* exp/template: more tweaks and fixes, convert the tree to use exp/template.
* fmt: handle precision 0 format strings in standard way.
* gc: a raft of bug fixes.
* go/parser: report illegal label declarations at ':'.
* gob: send empty but non-nil maps.
* godoc: allow form feed in text files,
app engine configuration and updated documentation.
* goinstall: abort and warn when using any url scheme, not just 'http://',
write to goinstall.log in respective GOPATH.
* html: handle character entities without semicolons (thanks Andrew Balholm),
parse misnested formatting tags according to the HTML5 spec,
sync html/testdata/webkit with upstream WebKit.
* http: content-type sniffing,
make serveFile redirects relative (thanks Andrew Balholm),
other fixes.
* image/tiff: Do not panic when RowsPerStrip is missing (thanks Benny Siegert).
* io/ioutil: improve performance of ioutil.Discard (thanks Mike Solomon).
* ld: detect all import cycles,
ldpe fixes (thanks Wei Guangjing),
remove cseekend and redo pe writing (thanks Alex Brainman),
remove overlap of ELF sections on dynamic binaries (thanks Gustavo Niemeyer).
* net/textproto: avoid 1 copy in ReadLine, ReadContinuedLine.
* net: fix memory corruption in windows *netFD.ReadFrom (thanks Alex Brainman).
* runtime: faster entersyscall/exitsyscall,
fix scheduler races (thanks Hector Chu),
higher goroutine arg limit, clearer error,
parallelism-related performance optimizations and fixes,
replace byte-at-a-time zeroing loop with memclr (thanks Quan Yong Zhai).
* sort: fix Float64Slice sort; NaN smallest value (thanks Florian Uekermann).
* src: removed some uses of container/vector (thanks John Asmuth).
* sync: improve Once fast path.
* unicode: fix case-mapping for roman numerals.
</pre>
<h2 id="2011-07-19">2011-07-19</h2>
<pre>
This weekly snapshot includes a language change and a change to the image
package that may require changes to client code.
The language change is that an "else" block is now required to have braces
except if the body of the "else" is another "if". Since gofmt always puts those
braces in anyway, programs will not be affected unless they contain "else for",
"else switch", or "else select". Run gofmt to fix any such programs.
The image package has had significant changes made to the Pix field of struct
types such as image.RGBA and image.NRGBA. The image.Image interface type has
not changed, though, and you should not need to change your code if you don't
explicitly refer to Pix fields. For example, if you decode a number of images
using the image/jpeg package, compose them using image/draw, and then encode
the result using image/png, then your code should still work as before.
If you do explicitly refer to Pix fields, there are two changes. First, Pix[0]
now refers to the pixel at Bounds().Min instead of the pixel at (0, 0). Second,
the element type of the Pix slice is now uint8 instead of image.FooColor. For
example, for an image.RGBA, the channel values will be packed R, G, B, A, R, G,
B, A, etc. For 16-bits-per-channel color types, the pixel data will be stored
as big-endian uint8s.
Most Pix field types have changed, and so if your code still compiles after
this change, then you probably don't need to make any further changes (unless
you use an image.Paletted's Pix field). If you do get compiler errors, code
that used to look like this:
// Get the R, G, B, A values for the pixel at (x, y).
var m *image.RGBA = loadAnImage()
c := m.Pix[y*m.Stride + x]
r, g, b, a := c.R, c.G, c.B, c.A
should now look like this:
// Get the R, G, B, A values for the pixel at (x, y).
var m *image.RGBA = loadAnImage()
i := (y-m.Rect.Min.Y)*m.Stride + (x-m.Rect.Min.X)*4
r := m.Pix[i+0]
g := m.Pix[i+1]
b := m.Pix[i+2]
a := m.Pix[i+3]
This image package change will not be fixed by gofix: how best to translate
code into something efficient and idiomatic depends on the surrounding context,
and is not easily automatable. Examples of what to do can be found in the
changes to image/draw/draw.go in http://codereview.appspot.com/4675076/
Other changes:
* 6l: change default output name to 6.out.exe on windows (thanks Alex Brainman).
* archive/zip: add Writer,
add Mtime_ns function to get modified time in sensible format.
* cc, ld, gc: fixes for Plan 9 build (thanks Lucio De Re).
* cgi: close stdout reader pipe when finished.
* cgo: add missing semicolon in generated struct,
windows amd64 port (thanks Wei Guangjing).
* codereview: fix for Mercurial 1.9.
* dashboard: list "most installed this week" with rolling count.
* debug/elf: read ELF Program headers (thanks Matthew Horsnell).
* debug/pe: fixes ImportedSymbols for Win64 (thanks Wei Guangjing).
* debug/proc: remove unused package.
* doc/talks/io2010: update with gofix and handle the errors.
* exp/eval, exp/ogle: remove packages eval and ogle.
* exp/regexp/syntax: add Prog.NumCap.
* exp/template: API changes, bug fixes, and tweaks.
* flag: make -help nicer.
* fmt: Scan(&int) was mishandling a lone digit.
* gc: fix closure bug,
fix to build with clang (thanks Dave Cheney),
make size of struct{} and [0]byte 0 bytes (thanks Robert Hencke),
some enhancements to printing debug info.
* gif: fix local color map and coordinates.
* go/build: fixes for windows (thanks Alex Brainman),
include processing of .c files for cgo packages (thanks Alex Brainman),
less aggressive failure when GOROOT not found.
* go/printer: changed max. number of newlines from 3 to 2.
* gob: register more slice types (thanks Bobby Powers).
* godoc: support for file systems stored in .zip files.
* goinstall, dashboard: Google Code now supports git (thanks Tarmigan Casebolt).
* hash/crc32: add SSE4.2 support.
* html: update section references in comments to the latest HTML5 spec.
* http: drain the pipe output in TestHandlerPanic to avoid logging deadlock,
fix Content-Type of file extension (thanks Yasuhiro Matsumoto),
implement http.FileSystem for zip files,
let FileServer work when path doesn't begin with a slash,
support for periodic flushing in ReverseProxy.
* image/draw: add benchmarks.
* json: add omitempty struct tag option,
allow using '$' and '-' as the struct field's tag (thanks Mikio Hara),
encode \r and \n in strings as e.g. "\n", not "\u000A" (thanks Evan Martin),
escape < and > in any JSON string for XSS prevention.
* ld: allow seek within write buffer<
add a PT_LOAD PHDR entry for the PHDR (thanks David Anderson).
* net: windows/amd64 port (thanks Wei Guangjing).
* os: plan9: add Process.Signal as a way to send notes (thanks Yuval Pavel Zholkover).
* os: don't permit Process.Signal after a successful Wait.
* path/filepath: fixes for windows paths (thanks Alex Brainman).
* reflect: add Value.NumMethod,
panic if Method index is out of range for a type.
* runtime: faster entersyscall, exitsyscall,
fix panic for make(chan [0]byte),
fix subtle select bug (thanks Hector Chu),
make goc2c build on Plan 9 (thanks Lucio De Re),
make TestSideEffectOrder work twice,
several parallelism-related optimizations and fixes,
stdcall_raw stack 16byte align for Win64 (thanks Wei Guangjing),
string-related optimizations (thanks Quan Yong Zhai),
track running goroutine count.
* strconv: handle [-+]Infinity in atof.
* sync: add fast paths to WaitGroup,
improve RWMutex performance.
* syscall: add Flock on Linux,
parse and encode SCM_RIGHTS and SCM_CREDENTIALS (thanks Albert Strasheim).
</pre>
<h2 id="2011-07-07">2011-07-07 (<a href="release.html#r59">base for r59</a>)</h2>
<pre>
This weekly snapshot includes changes to the strings, http, reflect, json, and
xml packages. Code that uses these packages will need changes. Most of these
changes can be made automatically with gofix.
The strings package's Split function has itself been split into Split and
SplitN. SplitN is the same as the old Split. The new Split is equivalent to
SplitN with a final argument of -1.
The http package has a new FileSystem interface that provides access to files.
The FileServer helper now takes a FileSystem argument instead of an explicit
file system root. By implementing your own FileSystem you can use the
FileServer to serve arbitrary data.
The reflect package supports a new struct tag scheme that enables sharing of
struct tags between multiple packages.
In this scheme, the tags must be of the form:
key:"value" key2:"value2"
reflect.StructField's Tag field now has type StructTag (a string type), which
has method Get(key string) string that returns the associated value.
Clients of json and xml will need to be updated. Code that says
type T struct {
X int "name"
}
should become
type T struct {
X int `json:"name"` // or `xml:"name"`
}
Use govet to identify struct tags that need to be changed to use the new syntax.
Other changes:
* 5l, 6l, 8l: drop use of ed during build.
* asn1: support T61 and UTF8 string.
* bufio: do not cache Read errors (thanks Graham Miller).
* build: make version.bash aware of branches.
* cgi: don't depend on CGI.pm for tests.
* codereview: make --ignore_hgpatch_failure work again,
restrict sync to default branch.
* crypto/openpgp: add ability to reserialize keys,
bug fix (thanks Gideon Jan-Wessel Redelinghuys).
* crypto/tls: fix generate_cert.go.
* crypto/x509: prevent chain cycles in Verify.
* csv: new package.
* doc: remove ed from apt-get package list.
* docs: fold the prog.sh scripting from makehtml into htmlgen itself.
* ebnflint: better handling of stdin.
* exp/regexp/syntax: new experimental RE2-based regexp implementation.
* exp/template: a new experimental templating package.
* fmt: add SkipSpace to fmt's ScanState interface.
* fmt: rename errno and error to err for doc consistency.
* gc: avoid package name ambiguity in error messages,
fix package quoting logic,
fixes for Plan 9 (thanks Lucio De Re).
* go/build: evaluate symlinks before comparing path to GOPATH.
* gob: use exported fields in structs in the package documentation.
* godoc: ignore directories that begin with '.',
search GOPATH for documentation.
* gofix: os/signal, path/filepath, and sort fixes (thanks Robert Hencke),
* goinstall: add support for generic hosts (thanks Julian Phillips),
only report successfully-installed packages to the dashboard,
try to access via https (thanks Yasuhiro Matsumoto).
* gotest: add -test.benchtime and -test.cpu flags.
* html: fixes and improvements (thanks Yasuhiro Matsumoto).
* http/cgi: add Handler.Dir to specify working directory (thanks Yasuhiro Matsumoto).
* http: add StripPrefix handler wrapper,
assume ContentLength 0 on GET requests,
better handling of 0-length Request.Body,
do TLS handshake explicitly before copying TLS state,
document that ServerConn and ClientConn are low-level,
make NewChunkedReader public (thanks Andrew Balholm),
respect Handlers setting Connection: close in their response.
* image: more tests, Paletted.Opaque optimization.
* io.WriteString: if the object has a WriteString method, use it (thanks Evan Shaw).
* ld: elide the Go symbol table when using -s (thanks Anthony Martin).
* ld: fix ELF strip by removing overlap of sections (thanks Gustavo Niemeyer).
* mime/multipart: parse LF-delimited messages, not just CRLF.
* mime: permit lower-case media type parameters (thanks Pascal S. de Kloe).
* misc/dashboard: new features and improvements (not yet deployed).
* misc/emacs: update list of builtins (thanks Quan Yong Zhai).
* misc/vim: allow only utf-8 for file encoding (thanks Yasuhiro Matsumoto).
* os: fix documentation for FileInfo.Name,
simplify WriteString,
use a different symbol from syscall in mkunixsignals.sh.
* path/filepath: enable TestWalk to run on windows (thanks Alex Brainman).
* reflect: add MethodByName,
allow Len on String values.
* regexp: document that Regexp is thread-safe.
* runtime/cgo: check for errors from pthread_create (thanks Albert Strasheim).
* runtime: add Semacquire/Semrelease benchmarks,
improved Semacquire/Semrelease implementation,
windows/amd64 port (thanks Wei Guangjing).
* sync: add fast path to Once,
improve Mutex to allow successive acquisitions,
new and improved benchmarks.
* syscall: regenerate zerrors for darwin/linux/freebsd,
support for tty options in StartProcess (thanks Ken Rockot).
* testing: make ResetTimer not start/stop the timer,
scale benchmark precision to 0.01ns if needed.
* time: zero-pad two-digit years.
* unicode/maketables: update debugging data.
* windows: define and use syscall.Handle (thanks Wei Guangjing).
* xml: add Marshal and MarshalIndent.
</pre>
<h2 id="2011-06-23">2011-06-23</h2>
<pre>
This release includes a language change that restricts the use of goto.
In essence, a "goto" statement outside a block cannot jump to a label inside
that block. Your code may require changes if it uses goto.
This changeset shows how the new rule affected the Go tree:
http://code.google.com/p/go/source/detail?r=dc6d3cf9279d
The os.ErrorString type has been hidden. If your code uses os.ErrorString it
must be changed. Most uses of os.ErrorString can be replaced with os.NewError.
Other changes:
* 5c: do not use R9 and R10.
* 8l: more fixes for Plan 9 (thanks Lucio De Re).
* build: Make.ccmd: link with mach lib (thanks Joe Poirier).
* build: exclude packages that fail on Plan 9 (thanks Anthony Martin).
* cc: nit: silence comment warnings (thanks Dave Cheney).
* codereview.py: note that hg change -d abandons a change list (thanks Robert Hencke).
* crypto/openpgp: add ElGamal support.
* doc/faq: add question about converting from []T to []interface{}.
* doc: Effective Go: fix variadic function example (thanks Ben Lynn).
* exec: LookPath should not search %PATH% for files like c:cmd.exe (thanks Alex Brainman),
add support for Plan 9 (thanks Anthony Martin),
better error message for windows LookPath (thanks Alex Brainman).
* fmt: catch panics from calls to String etc.
* gc: descriptive panic for nil pointer -> value method call,
implement goto restriction,
unsafe.Alignof, unsafe.Offsetof, unsafe.Sizeof now return uintptr.
* go/build: include Import objects in Script Inputs.
* godefs: rudimentary tests (thanks Robert Hencke).
* goinstall: refactor and generalize repo handling code (thanks Julian Phillips),
temporarily use Makefiles by default (override with -make=false).
* gopprof: update list of memory allocators.
* http: add Server.ListenAndServeTLS,
buffer request.Write,
fix req.Cookie(name) with cookies in one header,
permit handlers to explicitly remove the Date header,
write Header keys with empty values.
* image: basic test for the 16-bits-per-color-channel types.
* io: clarify Read, ReadAt, Copy, Copyn EOF behavior.
* ld: don't attempt to build dynamic sections unnecessarily (thanks Gustavo Niemeyer).
* libmach: fix disassembly of FCMOVcc and FCOMI (thanks Anthony Martin),
fix tracing on linux (for cov) (thanks Anthony Martin).
* mime: fix RFC references (thanks Pascal S. de Kloe).
* misc/gobuilder: run make single-threaded on windows (thanks Alex Brainman).
* misc/godashboard: Accept sub-directories for goinstall's report (thanks Yasuhiro Matsumoto).
* nacl, tiny: remove vestiges (thanks Robert Hencke).
* net, syscall: interface for windows (thanks Yasuhiro Matsumoto).
* os: change Waitmsg String method to use pointer receiver (thanks Graham Miller).
* runtime: don't use twice the memory with grsec-like kernels (thanks Gustavo Niemeyer),
* spec: disallow goto into blocks.
* sync: restore GOMAXPROCS during benchmarks.
* syscall: add LSF support for linux (thanks Mikio Hara),
add socket control message support for darwin, freebsd, linux (thanks Mikio Hara),
add tty support to StartProcess (thanks Ken Rockot),
fix build for Sizeof change.
* test: test of goto restrictions.
* time: add support for Plan 9 (thanks Anthony Martin).
</pre>
<h2 id="2011-06-16">2011-06-16</h2>
<pre>
This release includes changes to the sort and image/draw packages that will
require changes to client code.
The sort.IntArray type has been renamed to IntSlice, and similarly for
StringArray and Float64Array.
The image/draw package's Draw function now takes an additional argument,
a compositing operator. If in doubt, use draw.Over.
Other changes:
* build: fix header files for Plan 9 (thanks Lucio De Re).
* cgo: handle new Apple LLVM-based gcc from Xcode 4.2.
* crypto/openpgp: add ability to encrypt and sign messages.
* doc/gopher: add goggled gopher logo for App Engine.
* doc: Update notes for 3-day Go course.
* exec: make LookPath work when PATHEXT var not set on Windows (thanks Alex Brainman).
* exp/regexp/syntax: syntax data structures, parser, escapes, character classes.
* exp/template: lexical scanner for new template package.
* fmt: debugging formats for characters: %+q %#U.
* gc: frame compaction for arm,
handle go print() and go println(),
work around goto bug.
* go/build: fixes, self-contained tests.
* go/printer, gofmt: print "select {}" on one line.
* godoc: replace OS file system accesses in favor of a FileSystem interface.
* gofix: fix inconsistent indentation in help output (thanks Scott Lawrence).
* goinstall: use go/build package to scan and build packages.
* http/spdy: improve error handling (thanks William Chan).
* http: use runtime/debug.Stack() to dump stack trace on panic.
* ld: dwarf emit filenames in debug_line header instead of as extended opcodes,
fix link Windows PE __declspec(dllimport) symbol (thanks Wei Guangjing),
make .rodata section read-only (thanks Gustavo Niemeyer).
* mail: decode RFC 2047 "B" encoding.
* mime/multipart: remove temp files after tests on Windows (thanks Alex Brainman).
* net: export all fields in Interface (thanks Mikio Hara),
rearrange source to run more tests on Windows (thanks Alex Brainman),
sendfile for win32 (thanks Yasuhiro Matsumoto).
* os: Plan 9, fix OpenFile & Chmod, add Process.Kill (thanks Yuval Pavel Zholkover).
* runtime: fix Plan 9 "lingering goroutines bug" (thanks Yuval Pavel Zholkover).
* spec: clarify rules for append, scope rules for :=,
specify constant conversions,
unsafe.Alignof/Offsetof/Sizeof return uintptr.
* syscall, os, exec: add *syscall.SysProcAttr field to os.ProcAttr and exec.Cmd.
* syscall: add ptrace on darwin (thanks Jeff Hodges),
mksyscall_windows.pl should output unix newline (thanks Yasuhiro Matsumoto).
update BPF support for BSD variants (thanks Mikio Hara),
use strict in perl scripts (thanks Yasuhiro Matsumoto).
* xml: handle non-string attribute fields (thanks Maxim Ushakov).
</pre>
<h2 id="2011-06-09">2011-06-09 (<a href="release.html#r58">base for r58</a>)</h2>
<pre>
This release includes changes to the strconv, http, and exp/draw packages.

View File

@@ -16,6 +16,16 @@ Once you've learned a little about the language,
idioms of programming in Go.
</p>
<h3 id="go_tour"><a href="http://go-tour.appspot.com/">A Tour of Go</a></h3>
<p>
An interactive introduction to Go in three sections.
The first section covers basic syntax and data structures; the second discusses
methods and interfaces; and the third introduces Go's concurrency primitives.
Each section concludes with a few exercises so you can practice what you've
learned. You can <a href="http://go-tour.appspot.com/">take the tour online</a> or
<a href="http://code.google.com/p/go-tour/">install it locally</a>.
</p>
<h3 id="orig_tutorial"><a href="go_tutorial.html">A Tutorial for the Go Programming Language</a></h3>
<p>
The first tutorial. An introductory text that touches upon several core
@@ -23,6 +33,17 @@ concepts: syntax, types, allocation, constants, I/O, sorting, printing,
goroutines, and channels.
</p>
<h3 id="course_notes">Course Notes</h3>
<p>
Slides from a 3-day course about the Go programming language.
A more thorough introduction than the tutorial.
</p>
<ul>
<li><a href="GoCourseDay1.pdf">Day 1: Basics</a> <small>[270KB PDF]</small></li>
<li><a href="GoCourseDay2.pdf">Day 2: Types, Methods, Interfaces</a> <small>[270KB PDF]</small></li>
<li><a href="GoCourseDay3.pdf">Day 3: Concurrency and Communication</a> <small>[180KB PDF]</small></li>
</ul>
<h3 id="effective_go"><a href="effective_go.html">Effective Go</a></h3>
<p>
A document that gives tips for writing clear, idiomatic Go code.
@@ -51,12 +72,53 @@ and closures.
<p>
Guided tours of Go programs.
</p>
<ul>
<li><a href="/doc/codewalk/functions">First-Class Functions in Go</a></li>
<li><a href="/doc/codewalk/markov">Generating arbitrary text: a Markov chain algorithm</a></li>
<li><a href="/doc/codewalk/sharemem">Share Memory by Communicating</a></li>
</ul>
<h3 id="go_for_cpp_programmers"><a href="go_for_cpp_programmers.html">Go for C++ Programmers</a></h3>
<p>
An introduction to Go for C++ programmers.
</p>
<h2 id="articles">Go Articles</h2>
<p>
Notable articles from the <a href="http://blog.golang.org/">Go Blog</a>.
</p>
<h3>Language</h3>
<ul>
<li><a href="http://blog.golang.org/2010/04/json-rpc-tale-of-interfaces.html">JSON-RPC: a tale of interfaces</a></li>
<li><a href="http://blog.golang.org/2010/07/gos-declaration-syntax.html">Go's Declaration Syntax</a></li>
<li><a href="http://blog.golang.org/2010/08/defer-panic-and-recover.html">Defer, Panic, and Recover</a></li>
<li><a href="http://blog.golang.org/2010/09/go-concurrency-patterns-timing-out-and.html">Go Concurrency Patterns: Timing out, moving on</a></li>
<li><a href="http://blog.golang.org/2011/01/go-slices-usage-and-internals.html">Go Slices: usage and internals</a></li>
<li><a href="http://blog.golang.org/2011/05/gif-decoder-exercise-in-go-interfaces.html">A GIF decoder: an exercise in Go interfaces</a></li>
<li><a href="http://blog.golang.org/2011/07/error-handling-and-go.html">Error Handling and Go</a></li>
</ul>
<h3>Packages</h3>
<ul>
<li><a href="http://blog.golang.org/2011/01/json-and-go.html">JSON and Go</a> - using the <a href="/pkg/json/">json</a> package.</li>
<li><a href="http://blog.golang.org/2011/03/gobs-of-data.html">Gobs of data</a> - the design and use of the <a href="/pkg/gob/">gob</a> package.</li>
<li><a href="http://blog.golang.org/2011/09/laws-of-reflection.html">The Laws of Reflection</a> - the fundamentals of the <a href="/pkg/reflect/">reflect</a> package.</li>
<li><a href="http://blog.golang.org/2011/09/go-image-package.html">The Go image package</a> - the fundamentals of the <a href="/pkg/image/">image</a> package.</li>
<li><a href="http://blog.golang.org/2011/09/go-imagedraw-package.html">The Go image/draw package</a> - the fundamentals of the <a href="/pkg/image/draw/">image/draw</a> package.</li>
</ul>
<h3>Tools</h3>
<ul>
<li><a href="http://blog.golang.org/2011/03/c-go-cgo.html">C? Go? Cgo!</a> - linking against C code with <a href="/cmd/cgo/">cgo</a>.</li>
<li><a href="http://blog.golang.org/2011/03/godoc-documenting-go-code.html">Godoc: documenting Go code</a> - writing good documentation for <a href="/cmd/godoc/">godoc</a>.</li>
<li><a href="http://blog.golang.org/2011/06/profiling-go-programs.html">Profiling Go Programs</a></li>
</ul>
<h2 id="tutorials_nonenglish">Non-English Documentation</h2>
<h3 id="docs_be">Belarusian &mdash; Беларуская</h3>
@@ -129,6 +191,11 @@ one goroutine can be guaranteed to observe values produced by writes to the
same variable in a different goroutine.
</p>
<h3 id="debugging_with_gdb"><a href="debugging_with_gdb.html">Debugging Go Code with GDB</a></h3>
<p>
Using GDB to debug Go programs.
</p>
<h2 id="videos_talks">Videos and Talks</h2>
<h3 id="writing_web_apps"><a href="http://www.youtube.com/watch?v=-i0hat7pdpk">Writing Web Apps in Go</a></h3>
@@ -209,7 +276,7 @@ from Hoares 1978 paper to Go provides insight into how and why Go works as it
does.
</i></p>
<h3 id="emerging_go"><a href="talks/gofrontend-gcc-summit-2010.pdf">The Go frontend for GCC</a></h3>
<h3 id="go_frontend_gcc"><a href="talks/gofrontend-gcc-summit-2010.pdf">The Go frontend for GCC</a></h3>
<p>
A description of the Go language frontend for gcc.
Ian Lance Taylor's paper delivered at the GCC Summit 2010.

View File

@@ -116,7 +116,7 @@ Some formatting details remain. Very briefly,
<dt>Parentheses</dt>
<dd>
Go needs fewer parentheses: control structures (<code>if</code>,
<code>for</code>, <code>switch</code>) do not require parentheses in
<code>for</code>, <code>switch</code>) do not have parentheses in
their syntax.
Also, the operator precedence hierarchy is shorter and clearer, so
<pre>
@@ -233,9 +233,9 @@ Since the whole declaration is presented, such a comment can often be perfunctor
<pre>
// Error codes returned by failures to parse an expression.
var (
ErrInternal = os.NewError("internal error")
ErrUnmatchedLpar = os.NewError("unmatched '('")
ErrUnmatchedRpar = os.NewError("unmatched ')'")
ErrInternal = os.NewError("regexp: internal error")
ErrUnmatchedLpar = os.NewError("regexp: unmatched '('")
ErrUnmatchedRpar = os.NewError("regexp: unmatched ')'")
...
)
</pre>
@@ -350,7 +350,7 @@ Both names read well in practice:
<pre>
owner := obj.Owner()
if owner != user {
obj.SetOwner(user)
obj.SetOwner(user)
}
</pre>
@@ -405,7 +405,7 @@ break continue fallthrough return ++ -- ) }
<p>
the lexer always inserts a semicolon after the token.
This could be summarized as, &ldquo;if the newline comes
after a token that could end a statement, add a semicolon&rdquo;.
after a token that could end a statement, insert a semicolon&rdquo;.
</p>
<p>
@@ -461,7 +461,7 @@ initialization statement like that of <code>for</code>;
and there are new control structures including a type switch and a
multiway communications multiplexer, <code>select</code>.
The syntax is also slightly different:
parentheses are not required
there are no parentheses
and the bodies must always be brace-delimited.
</p>
@@ -564,7 +564,7 @@ for i := 0; i &lt; 10; i++ {
<p>
If you're looping over an array, slice, string, or map,
or reading from a channel, a <code>range</code> clause can
manage the loop for you.
manage the loop.
</p>
<pre>
var m map[string]int
@@ -943,8 +943,11 @@ Go has two allocation primitives, the built-in functions
They do different things and apply to different types, which can be confusing,
but the rules are simple.
Let's talk about <code>new</code> first.
It's a built-in function essentially the same as its namesakes
in other languages: <code>new(T)</code> allocates zeroed storage for a new item of type
It's a built-in function that allocates memory, but unlike its namesakes
in some other languages it does not <em>initialize</em> the memory,
it only <em>zeroes</em> it.
That is,
<code>new(T)</code> allocates zeroed storage for a new item of type
<code>T</code> and returns its address, a value of type <code>*T</code>.
In Go terminology, it returns a pointer to a newly allocated zero value of type
<code>T</code>.
@@ -2245,7 +2248,7 @@ we would write <code>job.Logger</code>.
This would be useful if we wanted to refine the methods of <code>Logger</code>.
</p>
<pre>
func (job *Job) Logf(format string, args ...) {
func (job *Job) Logf(format string, args ...interface{}) {
job.Logger.Logf("%q: %s", job.Command, fmt.Sprintf(format, args))
}
</pre>
@@ -2673,6 +2676,13 @@ it is much more informative than the plain
"no such file or directory".
</p>
<p>
When feasible, error strings should identify their origin, such as by having
a prefix naming the package that generated the error. For example, in package
image, the string representation for a decoding error due to an unknown format
is "image: unknown format".
</p>
<p>
Callers that care about the precise error details can
use a type switch or a type assertion to look for specific
@@ -2720,7 +2730,7 @@ suppresses the usual check for a <code>return</code> statement.
<pre>
// A toy implementation of cube root using Newton's method.
func CubeRoot(x float64) float64 {
z := x/3 // Arbitrary intitial value
z := x/3 // Arbitrary initial value
for i := 0; i &lt; 1e6; i++ {
prevz := z
z -= (z*z*z-x) / (3*z*z)
@@ -2916,7 +2926,7 @@ import (
"http"
"io"
"log"
"template"
"old/template" // New template package coming soon...
)
var addr = flag.String("addr", ":1718", "http service address") // Q=17, R=18

View File

@@ -8,6 +8,7 @@ What is the purpose of the project?</h3>
<p>
No major systems language has emerged in over a decade, but over that time
the computing landscape has changed tremendously. There are several trends:
</p>
<ul>
<li>
@@ -26,11 +27,11 @@ are not well supported by popular systems languages.
<li>
The emergence of multicore computers has generated worry and confusion.
</ul>
</p>
<p>
We believe it's worth trying again with a new language, a concurrent,
garbage-collected language with fast compilation. Regarding the points above:
</p>
<ul>
<li>
@@ -50,7 +51,6 @@ concurrent execution and communication.
By its design, Go proposes an approach for the construction of system
software on multicore machines.
</ul>
</p>
<h3 id="What_is_the_origin_of_the_name">
What is the origin of the name?</h3>
@@ -105,7 +105,8 @@ and libraries from prototype to reality.
</p>
<p>
Many others have contributed ideas, discussions, and code.
Go became a public open source project on November 10, 2009.
Many people from the community have contributed ideas, discussions, and code.
</p>
<h3 id="creating_a_new_language">
@@ -183,16 +184,6 @@ easier to understand what happens when things combine.
<h2 id="Usage">Usage</h2>
<h3 id="Who_should_use_the_language">
Who should use the language?</h3>
<p>
Go is an experiment. We hope adventurous users will give it a try and see
if they enjoy it. Not every programmer
will, but we hope enough will find satisfaction in the approach it
offers to justify further development.
</p>
<h3 id="Is_Google_using_go_internally"> Is Google using Go internally?</h3>
<p>
@@ -324,7 +315,16 @@ exceptional.
</p>
<p>
Go takes a different approach. Instead of exceptions, it has a couple
Go takes a different approach. For plain error handling, Go's multi-value
returns make it easy to report an error without overloading the return value.
<a href="http://blog.golang.org/2011/07/error-handling-and-go.html">A
canonical error type, coupled
with Go's other features</a>, makes error
handling pleasant but quite different from that in other languages.
</p>
<p>
Go also has a couple
of built-in functions to signal and recover from truly exceptional
conditions. The recovery mechanism is executed only as part of a
function's state being torn down after an error, which is sufficient
@@ -382,7 +382,7 @@ Why build concurrency on the ideas of CSP?</h3>
Concurrency and multi-threaded programming have a reputation
for difficulty. We believe the problem is due partly to complex
designs such as pthreads and partly to overemphasis on low-level details
such as mutexes, condition variables, and even memory barriers.
such as mutexes, condition variables, and memory barriers.
Higher-level interfaces enable much simpler code, even if there are still
mutexes and such under the covers.
</p>
@@ -400,14 +400,14 @@ Why goroutines instead of threads?</h3>
<p>
Goroutines are part of making concurrency easy to use. The idea, which has
been around for a while, is to multiplex independently executing
functions&mdash;coroutines, really&mdash;onto a set of threads.
functions&mdash;coroutines&mdash;onto a set of threads.
When a coroutine blocks, such as by calling a blocking system call,
the run-time automatically moves other coroutines on the same operating
system thread to a different, runnable thread so they won't be blocked.
The programmer sees none of this, which is the point.
The result, which we call goroutines, can be very cheap: unless they spend a lot of time
in long-running system calls, they cost little more than the memory
for the stack.
for the stack, which is just a few kilobytes.
</p>
<p>
@@ -483,8 +483,8 @@ that specifies a subset of its methods. Besides reducing the
bookkeeping, this approach has real advantages. Types can satisfy
many interfaces at once, without the complexities of traditional
multiple inheritance.
Interfaces can be very lightweight&mdash;having one or even zero methods
in an interface can express useful concepts.
Interfaces can be very lightweight&mdash;an interface with
one or even zero methods can express a useful concept.
Interfaces can be added after the fact if a new idea comes along
or for testing&mdash;without annotating the original types.
Because there are no explicit relationships between types
@@ -504,7 +504,7 @@ stream ciphers. All these ideas stem from a single interface
<p>
It takes some getting used to but this implicit style of type
dependency is one of the most exciting things about Go.
dependency is one of the most productive things about Go.
</p>
<h3 id="methods_on_basics">
@@ -598,6 +598,139 @@ the interface idea. Sometimes, though, they're necessary to resolve ambiguities
among similar interfaces.
</p>
<h3 id="t_and_equal_interface">
Why doesn't type T satisfy the Equal interface?</h3>
<p>
Consider this simple interface to represent an object that can compare
itself with another value:
</p>
<pre>
type Equaler interface {
Equal(Equaler) bool
}
</pre>
<p>
and this type, <code>T</code>:
</p>
<pre>
type T int
func (t T) Equal(u T) bool { return t == u } // does not satisfy Equaler
</pre>
<p>
Unlike the analogous situation in some polymorphic type systems,
<code>T</code> does not implement <code>Equaler</code>.
The argument type of <code>T.Equal</code> is <code>T</code>,
not literally the required type <code>Equaler</code>.
</p>
<p>
In Go, the type system does not promote the argument of
<code>Equal</code>; that is the programmer's responsibility, as
illustrated by the type <code>T2</code>, which does implement
<code>Equaler</code>:
</p>
<pre>
type T2 int
func (t T2) Equal(u Equaler) bool { return t == u.(T2) } // satisfies Equaler
</pre>
<p>
Even this isn't like other type systems, though, because in Go <em>any</em>
type that satisfies <code>Equaler</code> could be passed as the
argument to <code>T2.Equal</code>, and at run time we must
check that the argument is of type <code>T2</code>.
Some languages arrange to make that guarantee at compile time.
</p>
<p>
A related example goes the other way:
</p>
<pre>
type Opener interface {
Open(name) Reader
}
func (t T3) Open() *os.File
</pre>
<p>
In Go, <code>T3</code> does not satisfy <code>Opener</code>,
although it might in another language.
</p>
<p>
While it is true that Go's type system does less for the programmer
in such cases, the lack of subtyping makes the rules about
interface satisfaction very easy to state: are the function's names
and signatures exactly those of the interface?
Go's rule is also easy to implement efficiently.
We feel these benefits offset the lack of
automatic type promotion. Should Go one day adopt some form of generic
typing, we expect there would be a way to express the idea of these
examples and also have them be statically checked.
</p>
<h3 id="convert_slice_of_interface">
Can I convert a []T to an []interface{}?</h3>
<p>
Not directly because they do not have the same representation in memory.
It is necessary to copy the elements individually to the destination
slice. This example converts a slice of <code>int</code> to a slice of
<code>interface{}</code>:
</p>
<pre>
t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}
</pre>
<h3 id="unions">
Why are there no untagged unions, as in C?</h3>
<p>
Untagged unions would violate Go's memory safety
guarantees.
</p>
<h3 id="variant_types">
Why does Go not have variant types?</h3>
<p>
Variant types, also known as algebraic types, provide a way to specify
that a value might take one of a set of other types, but only those
types. A common example in systems programming would specify that an
error is, say, a network error, a security error or an application
error and allow the caller to discriminate the source of the problem
by examining the type of the error. Another example is a syntax tree
in which each node can be a different type: declaration, statement,
assignment and so on.
</p>
<p>
We considered adding variant types to Go, but after discussion
decided to leave them out because they overlap in confusing ways
with interfaces. What would happen if the elements of a variant type
were themselves interfaces?
</p>
<p>
Also, some of what variant types address is already covered by the
language. The error example is easy to express using an interface
value to hold the error and a type switch to discriminate cases. The
syntax tree example is also doable, although not as elegantly.
</p>
<h2 id="values">Values</h2>
<h3 id="conversions">
@@ -728,17 +861,62 @@ makes a copy of the pointer, but again not the data it points to.
Should I define methods on values or pointers?</h3>
<pre>
func (s *MyStruct) someMethod() { } // method on pointer
func (s MyStruct) someMethod() { } // method on value
func (s *MyStruct) pointerMethod() { } // method on pointer
func (s MyStruct) valueMethod() { } // method on value
</pre>
<p>
For programmers unaccustomed to pointers, the distinction between these
two examples can be confusing, but the situation is actually very simple.
When defining a method on a type, the receiver (<code>s</code> in the above
example) behaves exactly is if it were an argument to the method. Define the
method on a pointer type if you need the method to modify the data the receiver
points to. Otherwise, it is often cleaner to define the method on a value type.
example) behaves exactly as if it were an argument to the method.
Whether to define the receiver as a value or as a pointer is the same
question, then, as whether a function argument should be a value or
a pointer.
There are several considerations.
</p>
<p>
First, and most important, does the method need to modify the
receiver?
If it does, the receiver <em>must</em> be a pointer.
(Slices and maps are reference types, so their story is a little
more subtle, but for instance to change the length of a slice
in a method the receiver must still be a pointer.)
In the examples above, if <code>pointerMethod</code> modifies
the fields of <code>s</code>,
the caller will see those changes, but <code>valueMethod</code>
is called with a copy of the caller's argument (that's the definition
of passing a value), so changes it makes will be invisible to the caller.
</p>
<p>
By the way, pointer receivers are identical to the situation in Java,
although in Java the pointers are hidden under the covers; it's Go's
value receivers that are unusual.
</p>
<p>
Second is the consideration of efficiency. If the receiver is large,
a big <code>struct</code> for instance, it will be much cheaper to
use a pointer receiver.
</p>
<p>
Next is consistency. If some of the methods of the type must have
pointer receivers, the rest should too, so the method set is
consistent regardless of how the type is used.
See the section on <a href="#different_method_sets">method sets</a>
for details.
</p>
<p>
For types such as basic types, slices, and small <code>structs</code>,
a value receiver is very cheap so unless the semantics of the method
requires a pointer, a value receiver is efficient and clear.
</p>
<h3 id="new_and_make">
What's the difference between new and make?</h3>
@@ -1045,7 +1223,7 @@ How is the run-time support implemented?</h3>
Again due to bootstrapping issues, the run-time code is mostly in C (with a
tiny bit of assembler) although Go is capable of implementing most of
it now. <code>Gccgo</code>'s run-time support uses <code>glibc</code>.
<code>Gc</code> uses a custom library, to keep the footprint under
<code>Gc</code> uses a custom library to keep the footprint under
control; it is
compiled with a version of the Plan 9 C compiler that supports
segmented stacks for goroutines.
@@ -1070,6 +1248,60 @@ that includes more powerful run-time support. We believe that with some effort
the size of Go binaries can be reduced.
</p>
<h3 id="unused_variables_and_imports">
Can I stop these complaints about my unused variable/import?</h3>
<p>
The presence of an unused variable may indicate a bug, while
unused imports just slow down compilation.
Accumulate enough unused imports in your code tree and
things can get very slow.
For these reasons, Go allows neither.
</p>
<p>
When developing code, it's common to create these situations
temporarily and it can be annoying to have to edit them out before the
program will compile.
</p>
<p>
Some have asked for a compiler option to turn those checks off
or at least reduce them to warnings.
Such an option has not been added, though,
because compiler options should not affect the semantics of the
language and because the Go compiler does not report warnings, only
errors that prevent compilation.
</p>
<p>
There are two reasons for having no warnings. First, if it's worth
complaining about, it's worth fixing in the code. (And if it's not
worth fixing, it's not worth mentioning.) Second, having the compiler
generate warnings encourages the implementation to warn about weak
cases that can make compilation noisy, masking real errors that
<em>should</em> be fixed.
</p>
<p>
It's easy to address the situation, though. Use the blank identifier
to let unused things persist while you're developing.
</p>
<pre>
import "unused"
// This declaration marks the import as used by referencing an
// item from the package.
var _ = unused.Item // TODO: Delete before committing!
func main() {
debugData := debug.Profile()
_ = debugData // Used only during debugging.
....
}
</pre>
<h2 id="Performance">Performance</h2>
<h3 id="Why_does_Go_perform_badly_on_benchmark_x">
@@ -1103,6 +1335,11 @@ isn't fast enough yet (even if it were, taking care not to generate unnecessary
garbage can have a huge effect).
</p>
<p>
In any case, Go can often be very competitive. See the blog post about
<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
Go programs</a> for an informative example.
<h2 id="change_from_c">Changes from C</h2>
<h3 id="different_syntax">
@@ -1157,7 +1394,9 @@ and <code>chan</code> keep things clear.
</p>
<p>
See the <a href="http://blog.golang.org/2010/07/gos-declaration-syntax.html">Go's Declaration Syntax</a> article for more details.
See the article about
<a href="http://blog.golang.org/2010/07/gos-declaration-syntax.html">Go's Declaration Syntax</a>
for more details.
</p>
<h3 id="no_pointer_arithmetic">
@@ -1244,3 +1483,14 @@ program helps everyone.
Finally, concurrency aside, garbage collection makes interfaces
simpler because they don't need to specify how memory is managed across them.
</p>
<p>
On the topic of performance, keep in mind that Go gives the programmer
considerable control over memory layout and allocation, much more than
is typical in garbage-collected languages. A careful programmer can reduce
the garbage collection overhead dramatically by using the language well;
see the article about
<a href="http://blog.golang.org/2011/06/profiling-go-programs.html">profiling
Go programs</a> for a worked example, including a demonstration of Go's
profiling tools.
</p>

View File

@@ -1,4 +1,5 @@
<!-- The Go Memory Model -->
<!-- subtitle Version of June 10, 2011 -->
<style>
p.rule {
@@ -42,8 +43,8 @@ Also, if <span class="event">e<sub>1</sub></span> does not happen before <span c
after <span class="event">e<sub>2</sub></span>, then we say that <span class="event">e<sub>1</sub></span> and <span class="event">e<sub>2</sub></span> happen concurrently.
</p>
<p>
Within a single goroutine, the happens before order is the
<p class="rule">
Within a single goroutine, the happens-before order is the
order expressed by the program.
</p>

View File

@@ -1,5 +1,5 @@
<!-- title The Go Programming Language Specification -->
<!-- subtitle Version of June 7, 2011 -->
<!-- subtitle Version of July 14, 2011 -->
<!--
TODO
@@ -10,7 +10,6 @@ TODO
[ ] clarify what a field name is in struct declarations
(struct{T} vs struct {T T} vs struct {t T})
[ ] need explicit language about the result type of operations
[ ] should string(1<<s) and float32(1<<s) be valid?
[ ] should probably write something about evaluation order of statements even
though obvious
[ ] review language on implicit dereferencing
@@ -529,7 +528,8 @@ A constant value is represented by an
<a href="#Character_literals">character</a>, or
<a href="#String_literals">string</a> literal,
an identifier denoting a constant,
a <a href="#Constant_expressions">constant expression</a>, or
a <a href="#Constant_expressions">constant expression</a>,
a <a href="#Conversions">conversion</a> with a result that is a constant, or
the result value of some built-in functions such as
<code>unsafe.Sizeof</code> applied to any value,
<code>cap</code> or <code>len</code> applied to
@@ -1452,6 +1452,7 @@ Go is lexically scoped using blocks:
<li>The scope of a constant or variable identifier declared
inside a function begins at the end of the ConstSpec or VarSpec
(ShortVarDecl for short variable declarations)
and ends at the end of the innermost containing block.</li>
<li>The scope of a type identifier declared inside a function
@@ -3227,8 +3228,42 @@ If the type starts with an operator it must be parenthesized:
</pre>
<p>
A value <code>x</code> can be converted to type <code>T</code> in any
of these cases:
A <a href="#Constants">constant</a> value <code>x</code> can be converted to
type <code>T</code> in any of these cases:
</p>
<ul>
<li>
<code>x</code> is representable by a value of type <code>T</code>.
</li>
<li>
<code>x</code> is an integer constant and <code>T</code> is a
<a href="#String_types">string type</a>.
The same rule as for non-constant <code>x</code> applies in this case
<a href="#Conversions_to_and_from_a_string_type">Conversions to and from a string type</a>).
</li>
</ul>
<p>
Converting a constant yields a typed constant as result.
</p>
<pre>
uint(iota) // iota value of type uint
float32(2.718281828) // 2.718281828 of type float32
complex128(1) // 1.0 + 0.0i of type complex128
string('x') // "x" of type string
string(0x266c) // "♬" of type string
MyString("foo" + "bar") // "foobar" of type MyString
string([]byte{'a'}) // not a constant: []byte{'a'} is not a constant
(*int)(nil) // not a constant: nil is not a constant, *int is not a boolean, numeric, or string type
int(1.2) // illegal: 1.2 cannot be represented as an int
string(65.0) // illegal: 65.0 is not an integer constant
</pre>
<p>
A non-constant value <code>x</code> can be converted to type <code>T</code>
in any of these cases:
</p>
<ul>
@@ -3262,15 +3297,27 @@ of these cases:
</ul>
<p>
Specific rules apply to conversions between numeric types or to and from
a string type.
Specific rules apply to (non-constant) conversions between numeric types or
to and from a string type.
These conversions may change the representation of <code>x</code>
and incur a run-time cost.
All other conversions only change the type but not the representation
of <code>x</code>.
</p>
<p>
There is no linguistic mechanism to convert between pointers and integers.
The package <a href="#Package_unsafe"><code>unsafe</code></a>
implements this functionality under
restricted circumstances.
</p>
<h4>Conversions between numeric types</h4>
<p>
For the conversion of non-constant numeric values, the following rules apply:
</p>
<ol>
<li>
When converting between integer types, if the value is a signed integer, it is
@@ -3296,13 +3343,12 @@ of precision, but <code>float32(x + 0.1)</code> does not.
</ol>
<p>
In all conversions involving floating-point or complex values,
In all non-constant conversions involving floating-point or complex values,
if the result type cannot represent the value the conversion
succeeds but the result value is
implementation-dependent.
succeeds but the result value is implementation-dependent.
</p>
<h4>Conversions to and from a string type</h4>
<h4 id="Conversions_to_and_from_a_string_type">Conversions to and from a string type</h4>
<ol>
<li>
@@ -3360,12 +3406,6 @@ If the string is empty, the result is <code>[]int(nil)</code>.
</li>
</ol>
<p>
There is no linguistic mechanism to convert between pointers and integers.
The package <a href="#Package_unsafe"><code>unsafe</code></a>
implements this functionality under
restricted circumstances.
</p>
<h3 id="Constant_expressions">Constant expressions</h3>
@@ -3722,7 +3762,7 @@ present, the "else" branch is executed.
</p>
<pre class="ebnf">
IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" Statement ] .
IfStmt = "if" [ SimpleStmt ";" ] Expression Block [ "else" ( IfStmt | Block ) ] .
</pre>
<pre>
@@ -4353,8 +4393,8 @@ goto Error
<p>
Executing the "goto" statement must not cause any variables to come into
scope that were not already in scope at the point of the goto. For
instance, this example:
<a href="#Declarations_and_scope">scope</a> that were not already in scope at the point of the goto.
For instance, this example:
</p>
<pre>
@@ -4366,9 +4406,29 @@ L:
<p>
is erroneous because the jump to label <code>L</code> skips
the creation of <code>v</code>.
<!--
(<span class="alert">TODO: Eliminate in favor of used and not set errors?</span>)
-->
</p>
<p>
A "goto" statement outside a <a href="#Blocks">block</a> cannot jump to a label inside that block.
For instance, this example:
</p>
<pre>
if n%2 == 1 {
goto L1
}
for n &gt; 0 {
f()
n--
L1:
f()
n--
}
</pre>
<p>
is erroneous because the label <code>L1</code> is inside
the "for" statement's block but the <code>goto</code> is not.
</p>
<h3 id="Fallthrough_statements">Fallthrough statements</h3>
@@ -4590,11 +4650,14 @@ Two built-in functions assist in common slice operations.
</p>
<p>
The function <code>append</code> appends zero or more values <code>x</code>
The <a href="#Function_types">variadic</a> function <code>append</code>
appends zero or more values <code>x</code>
to <code>s</code> of type <code>S</code>, which must be a slice type, and
returns the resulting slice, also of type <code>S</code>.
Each value <code>x</code> must be <a href="#Assignability">assignable</a> to
the <a href="#Slice_types">element type</a> of <code>S</code>.
The values <code>x</code> are passed to a parameter of type <code>...T</code>
where <code>T</code> is the <a href="#Slice_types">element type</a> of
<code>S</code> and the respective
<a href="#Passing_arguments_to_..._parameters">parameter passing rules</a> apply.
</p>
<pre class="grammar">
@@ -5102,9 +5165,9 @@ package unsafe
type ArbitraryType int // shorthand for an arbitrary Go type; it is not a real type
type Pointer *ArbitraryType
func Alignof(variable ArbitraryType) int
func Offsetof(selector ArbitraryType) int
func Sizeof(variable ArbitraryType) int
func Alignof(variable ArbitraryType) uintptr
func Offsetof(selector ArbitraryType) uinptr
func Sizeof(variable ArbitraryType) uintptr
func Reflect(val interface{}) (typ runtime.Type, addr uintptr)
func Typeof(val interface{}) (typ interface{})
@@ -5127,7 +5190,7 @@ For a struct <code>s</code> with field <code>f</code>:
</p>
<pre>
uintptr(unsafe.Pointer(&amp;s)) + uintptr(unsafe.Offsetof(s.f)) == uintptr(unsafe.Pointer(&amp;s.f))
uintptr(unsafe.Pointer(&amp;s)) + unsafe.Offsetof(s.f) == uintptr(unsafe.Pointer(&amp;s.f))
</pre>
<p>
@@ -5140,12 +5203,12 @@ alignment of the (type of the) variable in bytes. For a variable
</p>
<pre>
uintptr(unsafe.Pointer(&amp;x)) % uintptr(unsafe.Alignof(x)) == 0
uintptr(unsafe.Pointer(&amp;x)) % unsafe.Alignof(x) == 0
</pre>
<p>
Calls to <code>Alignof</code>, <code>Offsetof</code>, and
<code>Sizeof</code> are compile-time constant expressions of type <code>int</code>.
<code>Sizeof</code> are compile-time constant expressions of type <code>uintptr</code>.
</p>
<p>
The functions <code>unsafe.Typeof</code>,
@@ -5198,10 +5261,12 @@ The following minimal alignment properties are guaranteed:
</li>
</ol>
<h2 id="Implementation_differences"><span class="alert">Implementation differences - TODO</span></h2>
<span class="alert">
<h2 id="Implementation_differences">Implementation differences - TODO</h2>
<ul>
<li><span class="alert">The restriction on <code>goto</code> statements and targets (no intervening declarations) is not honored.</span></li>
<li><span class="alert"><code>len(a)</code> is only a constant if <code>a</code> is a (qualified) identifier denoting an array or pointer to an array.</span></li>
<li><span class="alert"><code>nil</code> maps are not treated like empty maps.</span></li>
<li><span class="alert">Trying to send/receive from a <code>nil</code> channel causes a run-time panic.</span></li>
<li><code>len(a)</code> is only a constant if <code>a</code> is a (qualified) identifier denoting an array or pointer to an array.</li>
<li><code>nil</code> maps are not treated like empty maps.</li>
<li>Trying to send/receive from a <code>nil</code> channel causes a run-time panic.</li>
<li><code>unsafe.Alignof</code>, <code>unsafe.Offsetof</code>, and <code>unsafe.Sizeof</code> return an <code>int</code>.</li>
</ul>
</span>

File diff suppressed because it is too large Load Diff

990
doc/go_tutorial.tmpl Normal file
View File

@@ -0,0 +1,990 @@
<!-- A Tutorial for the Go Programming Language -->
<h2>Introduction</h2>
<p>
This document is a tutorial introduction to the basics of the Go programming
language, intended for programmers familiar with C or C++. It is not a comprehensive
guide to the language; at the moment the document closest to that is the
<a href='/doc/go_spec.html'>language specification</a>.
After you've read this tutorial, you should look at
<a href='/doc/effective_go.html'>Effective Go</a>,
which digs deeper into how the language is used and
talks about the style and idioms of programming in Go.
Also, slides from a 3-day course about Go are available.
They provide some background and a lot of examples:
<a href='/doc/GoCourseDay1.pdf'>Day 1</a>,
<a href='/doc/GoCourseDay2.pdf'>Day 2</a>,
<a href='/doc/GoCourseDay3.pdf'>Day 3</a>.
<p>
The presentation here proceeds through a series of modest programs to illustrate
key features of the language. All the programs work (at time of writing) and are
checked into the repository in the directory <a href='/doc/progs'><code>/doc/progs/</code></a>.
<p>
<h2>Hello, World</h2>
<p>
Let's start in the usual way:
<p>
{{code "progs/helloworld.go" `/package/` "$"}}
<p>
Every Go source file declares, using a <code>package</code> statement, which package it's part of.
It may also import other packages to use their facilities.
This program imports the package <code>fmt</code> to gain access to
our old, now capitalized and package-qualified, friend, <code>fmt.Printf</code>.
<p>
Functions are introduced with the <code>func</code> keyword.
The <code>main</code> package's <code>main</code> function is where the program starts running (after
any initialization).
<p>
String constants can contain Unicode characters, encoded in UTF-8.
(In fact, Go source files are defined to be encoded in UTF-8.)
<p>
The comment convention is the same as in C++:
<p>
<pre>
/* ... */
// ...
</pre>
<p>
Later we'll have much more to say about printing.
<p>
<h2>Semicolons</h2>
<p>
You might have noticed that our program has no semicolons. In Go
code, the only place you typically see semicolons is separating the
clauses of <code>for</code> loops and the like; they are not necessary after
every statement.
<p>
In fact, what happens is that the formal language uses semicolons,
much as in C or Java, but they are inserted automatically
at the end of every line that looks like the end of a statement. You
don't need to type them yourself.
<p>
For details about how this is done you can see the language
specification, but in practice all you need to know is that you
never need to put a semicolon at the end of a line. (You can put
them in if you want to write multiple statements per line.) As an
extra help, you can also leave out a semicolon immediately before
a closing brace.
<p>
This approach makes for clean-looking, semicolon-free code. The
one surprise is that it's important to put the opening
brace of a construct such as an <code>if</code> statement on the same line as
the <code>if</code>; if you don't, there are situations that may not compile
or may give the wrong result. The language forces the brace style
to some extent.
<p>
<h2>Compiling</h2>
<p>
Go is a compiled language. At the moment there are two compilers.
<code>Gccgo</code> is a Go compiler that uses the GCC back end. There is also a
suite of compilers with different (and odd) names for each architecture:
<code>6g</code> for the 64-bit x86, <code>8g</code> for the 32-bit x86, and more. These
compilers run significantly faster but generate less efficient code
than <code>gccgo</code>. At the time of writing (late 2009), they also have
a more robust run-time system although <code>gccgo</code> is catching up.
<p>
Here's how to compile and run our program. With <code>6g</code>, say,
<p>
<pre>
$ 6g helloworld.go # compile; object goes into helloworld.6
$ 6l helloworld.6 # link; output goes into 6.out
$ ./6.out
Hello, world; or Καλημέρα κόσμε; or こんにちは 世界
$
</pre>
<p>
With <code>gccgo</code> it looks a little more traditional.
<p>
<pre>
$ gccgo helloworld.go
$ a.out
Hello, world; or Καλημέρα κόσμε; or こんにちは 世界
$
</pre>
<p>
<h2>Echo</h2>
<p>
Next up, here's a version of the Unix utility <code>echo(1)</code>:
<p>
{{code "progs/echo.go" `/package/` "$"}}
<p>
This program is small but it's doing a number of new things. In the last example,
we saw <code>func</code> introduce a function. The keywords <code>var</code>, <code>const</code>, and <code>type</code>
(not used yet) also introduce declarations, as does <code>import</code>.
Notice that we can group declarations of the same sort into
parenthesized lists, one item per line, as in the <code>import</code> and <code>const</code> clauses here.
But it's not necessary to do so; we could have said
<p>
<pre>
const Space = " "
const Newline = "\n"
</pre>
<p>
This program imports the <code>&quot;os&quot;</code> package to access its <code>Stdout</code> variable, of type
<code>*os.File</code>. The <code>import</code> statement is actually a declaration: in its general form,
as used in our ``hello world'' program,
it names the identifier (<code>fmt</code>)
that will be used to access members of the package imported from the file (<code>&quot;fmt&quot;</code>),
found in the current directory or in a standard location.
In this program, though, we've dropped the explicit name from the imports; by default,
packages are imported using the name defined by the imported package,
which by convention is of course the file name itself. Our ``hello world'' program
could have said just <code>import &quot;fmt&quot;</code>.
<p>
You can specify your
own import names if you want but it's only necessary if you need to resolve
a naming conflict.
<p>
Given <code>os.Stdout</code> we can use its <code>WriteString</code> method to print the string.
<p>
After importing the <code>flag</code> package, we use a <code>var</code> declaration
to create and initialize a global variable, called <code>omitNewline</code>,
to hold the value of echo's <code>-n</code> flag.
The variable has type <code>*bool</code>, pointer to <code>bool</code>.
<p>
In <code>main.main</code>, we parse the arguments (the call to <code>flag.Parse</code>) and then create a local
string variable with which to build the output.
<p>
The declaration statement has the form
<p>
<pre>
var s string = ""
</pre>
<p>
This is the <code>var</code> keyword, followed by the name of the variable, followed by
its type, followed by an equals sign and an initial value for the variable.
<p>
Go tries to be terse, and this declaration could be shortened. Since the
string constant is of type string, we don't have to tell the compiler that.
We could write
<p>
<pre>
var s = ""
</pre>
<p>
or we could go even shorter and write the idiom
<p>
<pre>
s := ""
</pre>
<p>
The <code>:=</code> operator is used a lot in Go to represent an initializing declaration.
There's one in the <code>for</code> clause on the next line:
<p>
{{code "progs/echo.go" `/for/`}}
<p>
The <code>flag</code> package has parsed the arguments and left the non-flag arguments
in a list that can be iterated over in the obvious way.
<p>
The Go <code>for</code> statement differs from that of C in a number of ways. First,
it's the only looping construct; there is no <code>while</code> or <code>do</code>. Second,
there are no parentheses on the clause, but the braces on the body
are mandatory. The same applies to the <code>if</code> and <code>switch</code> statements.
Later examples will show some other ways <code>for</code> can be written.
<p>
The body of the loop builds up the string <code>s</code> by appending (using <code>+=</code>)
the arguments and separating spaces. After the loop, if the <code>-n</code> flag is not
set, the program appends a newline. Finally, it writes the result.
<p>
Notice that <code>main.main</code> is a niladic function with no return type.
It's defined that way. Falling off the end of <code>main.main</code> means
''success''; if you want to signal an erroneous return, call
<p>
<pre>
os.Exit(1)
</pre>
<p>
The <code>os</code> package contains other essentials for getting
started; for instance, <code>os.Args</code> is a slice used by the
<code>flag</code> package to access the command-line arguments.
<p>
<h2>An Interlude about Types</h2>
<p>
Go has some familiar types such as <code>int</code> and <code>uint</code> (unsigned <code>int</code>), which represent
values of the ''appropriate'' size for the machine. It also defines
explicitly-sized types such as <code>int8</code>, <code>float64</code>, and so on, plus
unsigned integer types such as <code>uint</code>, <code>uint32</code>, etc.
These are distinct types; even if <code>int</code> and <code>int32</code> are both 32 bits in size,
they are not the same type. There is also a <code>byte</code> synonym for
<code>uint8</code>, which is the element type for strings.
<p>
Floating-point types are always sized: <code>float32</code> and <code>float64</code>,
plus <code>complex64</code> (two <code>float32s</code>) and <code>complex128</code>
(two <code>float64s</code>). Complex numbers are outside the
scope of this tutorial.
<p>
Speaking of <code>string</code>, that's a built-in type as well. Strings are
<i>immutable values</i>&mdash;they are not just arrays of <code>byte</code> values.
Once you've built a string <i>value</i>, you can't change it, although
of course you can change a string <i>variable</i> simply by
reassigning it. This snippet from <code>strings.go</code> is legal code:
<p>
{{code "progs/strings.go" `/hello/` `/ciao/`}}
<p>
However the following statements are illegal because they would modify
a <code>string</code> value:
<p>
<pre>
s[0] = 'x'
(*p)[1] = 'y'
</pre>
<p>
In C++ terms, Go strings are a bit like <code>const strings</code>, while pointers
to strings are analogous to <code>const string</code> references.
<p>
Yes, there are pointers. However, Go simplifies their use a little;
read on.
<p>
Arrays are declared like this:
<p>
<pre>
var arrayOfInt [10]int
</pre>
<p>
Arrays, like strings, are values, but they are mutable. This differs
from C, in which <code>arrayOfInt</code> would be usable as a pointer to <code>int</code>.
In Go, since arrays are values, it's meaningful (and useful) to talk
about pointers to arrays.
<p>
The size of the array is part of its type; however, one can declare
a <i>slice</i> variable to hold a reference to any array, of any size,
with the same element type.
A <i>slice
expression</i> has the form <code>a[low : high]</code>, representing
the internal array indexed from <code>low</code> through <code>high-1</code>; the resulting
slice is indexed from <code>0</code> through <code>high-low-1</code>.
In short, slices look a lot like arrays but with
no explicit size (<code>[]</code> vs. <code>[10]</code>) and they reference a segment of
an underlying, usually anonymous, regular array. Multiple slices
can share data if they represent pieces of the same array;
multiple arrays can never share data.
<p>
Slices are much more common in Go programs than
regular arrays; they're more flexible, have reference semantics,
and are efficient. What they lack is the precise control of storage
layout of a regular array; if you want to have a hundred elements
of an array stored within your structure, you should use a regular
array. To create one, use a compound value <i>constructor</i>&mdash;an
expression formed
from a type followed by a brace-bounded expression like this:
<p>
<pre>
[3]int{1,2,3}
</pre>
<p>
In this case the constructor builds an array of 3 <code>ints</code>.
<p>
When passing an array to a function, you almost always want
to declare the formal parameter to be a slice. When you call
the function, slice the array to create
(efficiently) a slice reference and pass that.
By default, the lower and upper bounds of a slice match the
ends of the existing object, so the concise notation <code>[:]</code>
will slice the whole array.
<p>
Using slices one can write this function (from <code>sum.go</code>):
<p>
{{code "progs/sum.go" `/sum/` `/^}/`}}
<p>
Note how the return type (<code>int</code>) is defined for <code>sum</code> by stating it
after the parameter list.
<p>
To call the function, we slice the array. This intricate call (we'll show
a simpler way in a moment) constructs
an array and slices it:
<p>
<pre>
s := sum([3]int{1,2,3}[:])
</pre>
<p>
If you are creating a regular array but want the compiler to count the
elements for you, use <code>...</code> as the array size:
<p>
<pre>
s := sum([...]int{1,2,3}[:])
</pre>
<p>
That's fussier than necessary, though.
In practice, unless you're meticulous about storage layout within a
data structure, a slice itself&mdash;using empty brackets with no size&mdash;is all you need:
<p>
<pre>
s := sum([]int{1,2,3})
</pre>
<p>
There are also maps, which you can initialize like this:
<p>
<pre>
m := map[string]int{"one":1 , "two":2}
</pre>
<p>
The built-in function <code>len</code>, which returns number of elements,
makes its first appearance in <code>sum</code>. It works on strings, arrays,
slices, maps, and channels.
<p>
By the way, another thing that works on strings, arrays, slices, maps
and channels is the <code>range</code> clause on <code>for</code> loops. Instead of writing
<p>
<pre>
for i := 0; i &lt; len(a); i++ { ... }
</pre>
<p>
to loop over the elements of a slice (or map or ...) , we could write
<p>
<pre>
for i, v := range a { ... }
</pre>
<p>
This assigns <code>i</code> to the index and <code>v</code> to the value of the successive
elements of the target of the range. See
<a href='/doc/effective_go.html'>Effective Go</a>
for more examples of its use.
<p>
<p>
<h2>An Interlude about Allocation</h2>
<p>
Most types in Go are values. If you have an <code>int</code> or a <code>struct</code>
or an array, assignment
copies the contents of the object.
To allocate a new variable, use the built-in function <code>new</code>, which
returns a pointer to the allocated storage.
<p>
<pre>
type T struct { a, b int }
var t *T = new(T)
</pre>
<p>
or the more idiomatic
<p>
<pre>
t := new(T)
</pre>
<p>
Some types&mdash;maps, slices, and channels (see below)&mdash;have reference semantics.
If you're holding a slice or a map and you modify its contents, other variables
referencing the same underlying data will see the modification. For these three
types you want to use the built-in function <code>make</code>:
<p>
<pre>
m := make(map[string]int)
</pre>
<p>
This statement initializes a new map ready to store entries.
If you just declare the map, as in
<p>
<pre>
var m map[string]int
</pre>
<p>
it creates a <code>nil</code> reference that cannot hold anything. To use the map,
you must first initialize the reference using <code>make</code> or by assignment from an
existing map.
<p>
Note that <code>new(T)</code> returns type <code>*T</code> while <code>make(T)</code> returns type
<code>T</code>. If you (mistakenly) allocate a reference object with <code>new</code> rather than <code>make</code>,
you receive a pointer to a nil reference, equivalent to
declaring an uninitialized variable and taking its address.
<p>
<h2>An Interlude about Constants</h2>
<p>
Although integers come in lots of sizes in Go, integer constants do not.
There are no constants like <code>0LL</code> or <code>0x0UL</code>. Instead, integer
constants are evaluated as large-precision values that
can overflow only when they are assigned to an integer variable with
too little precision to represent the value.
<p>
<pre>
const hardEight = (1 &lt;&lt; 100) &gt;&gt; 97 // legal
</pre>
<p>
There are nuances that deserve redirection to the legalese of the
language specification but here are some illustrative examples:
<p>
<pre>
var a uint64 = 0 // a has type uint64, value 0
a := uint64(0) // equivalent; uses a "conversion"
i := 0x1234 // i gets default type: int
var j int = 1e6 // legal - 1000000 is representable in an int
x := 1.5 // a float64, the default type for floating constants
i3div2 := 3/2 // integer division - result is 1
f3div2 := 3./2. // floating-point division - result is 1.5
</pre>
<p>
Conversions only work for simple cases such as converting <code>ints</code> of one
sign or size to another and between integers and floating-point numbers,
plus a couple of other instances outside the scope of a tutorial.
There are no automatic numeric conversions of any kind in Go,
other than that of making constants have concrete size and type when
assigned to a variable.
<p>
<h2>An I/O Package</h2>
<p>
Next we'll look at a simple package for doing file I/O with an
open/close/read/write interface. Here's the start of <code>file.go</code>:
<p>
{{code "progs/file.go" `/package/` `/^}/`}}
<p>
The first few lines declare the name of the
package&mdash;<code>file</code>&mdash;and then import two packages. The <code>os</code>
package hides the differences
between various operating systems to give a consistent view of files and
so on; here we're going to use its error handling utilities
and reproduce the rudiments of its file I/O.
<p>
The other item is the low-level, external <code>syscall</code> package, which provides
a primitive interface to the underlying operating system's calls.
<p>
Next is a type definition: the <code>type</code> keyword introduces a type declaration,
in this case a data structure called <code>File</code>.
To make things a little more interesting, our <code>File</code> includes the name of the file
that the file descriptor refers to.
<p>
Because <code>File</code> starts with a capital letter, the type is available outside the package,
that is, by users of the package. In Go the rule about visibility of information is
simple: if a name (of a top-level type, function, method, constant or variable, or of
a structure field or method) is capitalized, users of the package may see it. Otherwise, the
name and hence the thing being named is visible only inside the package in which
it is declared. This is more than a convention; the rule is enforced by the compiler.
In Go, the term for publicly visible names is ''exported''.
<p>
In the case of <code>File</code>, all its fields are lower case and so invisible to users, but we
will soon give it some exported, upper-case methods.
<p>
First, though, here is a factory to create a <code>File</code>:
<p>
{{code "progs/file.go" `/newFile/` `/^}/`}}
<p>
This returns a pointer to a new <code>File</code> structure with the file descriptor and name
filled in. This code uses Go's notion of a ''composite literal'', analogous to
the ones used to build maps and arrays, to construct a new heap-allocated
object. We could write
<p>
<pre>
n := new(File)
n.fd = fd
n.name = name
return n
</pre>
<p>
but for simple structures like <code>File</code> it's easier to return the address of a
composite literal, as is done here in the <code>return</code> statement from <code>newFile</code>.
<p>
We can use the factory to construct some familiar, exported variables of type <code>*File</code>:
<p>
{{code "progs/file.go" `/var/` `/^\)/`}}
<p>
The <code>newFile</code> function was not exported because it's internal. The proper,
exported factory to use is <code>OpenFile</code> (we'll explain that name in a moment):
<p>
{{code "progs/file.go" `/func.OpenFile/` `/^}/`}}
<p>
There are a number of new things in these few lines. First, <code>OpenFile</code> returns
multiple values, a <code>File</code> and an error (more about errors in a moment).
We declare the
multi-value return as a parenthesized list of declarations; syntactically
they look just like a second parameter list. The function
<code>syscall.Open</code>
also has a multi-value return, which we can grab with the multi-variable
declaration on the first line; it declares <code>r</code> and <code>e</code> to hold the two values,
both of type <code>int</code> (although you'd have to look at the <code>syscall</code> package
to see that). Finally, <code>OpenFile</code> returns two values: a pointer to the new <code>File</code>
and the error. If <code>syscall.Open</code> fails, the file descriptor <code>r</code> will
be negative and <code>newFile</code> will return <code>nil</code>.
<p>
About those errors: The <code>os</code> library includes a general notion of an error.
It's a good idea to use its facility in your own interfaces, as we do here, for
consistent error handling throughout Go code. In <code>Open</code> we use a
conversion to translate Unix's integer <code>errno</code> value into the integer type
<code>os.Errno</code>, which implements <code>os.Error</code>.
<p>
Why <code>OpenFile</code> and not <code>Open</code>? To mimic Go's <code>os</code> package, which
our exercise is emulating. The <code>os</code> package takes the opportunity
to make the two commonest cases - open for read and create for
write - the simplest, just <code>Open</code> and <code>Create</code>. <code>OpenFile</code> is the
general case, analogous to the Unix system call <code>Open</code>. Here is
the implementation of our <code>Open</code> and <code>Create</code>; they're trivial
wrappers that eliminate common errors by capturing
the tricky standard arguments to open and, especially, to create a file:
<p>
{{code "progs/file.go" `/^const/` `/^}/`}}
<p>
{{code "progs/file.go" `/func.Create/` `/^}/`}}
<p>
Back to our main story.
Now that we can build <code>Files</code>, we can write methods for them. To declare
a method of a type, we define a function to have an explicit receiver
of that type, placed
in parentheses before the function name. Here are some methods for <code>*File</code>,
each of which declares a receiver variable <code>file</code>.
<p>
{{code "progs/file.go" `/Close/` "$"}}
<p>
There is no implicit <code>this</code> and the receiver variable must be used to access
members of the structure. Methods are not declared within
the <code>struct</code> declaration itself. The <code>struct</code> declaration defines only data members.
In fact, methods can be created for almost any type you name, such as an integer or
array, not just for <code>structs</code>. We'll see an example with arrays later.
<p>
The <code>String</code> method is so called because of a printing convention we'll
describe later.
<p>
The methods use the public variable <code>os.EINVAL</code> to return the (<code>os.Error</code>
version of the) Unix error code <code>EINVAL</code>. The <code>os</code> library defines a standard
set of such error values.
<p>
We can now use our new package:
<p>
{{code "progs/helloworld3.go" `/package/` "$"}}
<p>
The ''<code>./</code>'' in the import of ''<code>./file</code>'' tells the compiler
to use our own package rather than
something from the directory of installed packages.
(Also, ''<code>file.go</code>'' must be compiled before we can import the
package.)
<p>
Now we can compile and run the program. On Unix, this would be the result:
<p>
<pre>
$ 6g file.go # compile file package
$ 6g helloworld3.go # compile main package
$ 6l -o helloworld3 helloworld3.6 # link - no need to mention "file"
$ helloworld3
hello, world
can't open file; err=No such file or directory
$
</pre>
<p>
<h2>Rotting cats</h2>
<p>
Building on the <code>file</code> package, here's a simple version of the Unix utility <code>cat(1)</code>,
<code>progs/cat.go</code>:
<p>
{{code "progs/cat.go" `/package/` "$"}}
<p>
By now this should be easy to follow, but the <code>switch</code> statement introduces some
new features. Like a <code>for</code> loop, an <code>if</code> or <code>switch</code> can include an
initialization statement. The <code>switch</code> statement in <code>cat</code> uses one to create variables
<code>nr</code> and <code>er</code> to hold the return values from the call to <code>f.Read</code>. (The <code>if</code> a few lines later
has the same idea.) The <code>switch</code> statement is general: it evaluates the cases
from top to bottom looking for the first case that matches the value; the
case expressions don't need to be constants or even integers, as long as
they all have the same type.
<p>
Since the <code>switch</code> value is just <code>true</code>, we could leave it off&mdash;as is also
the situation
in a <code>for</code> statement, a missing value means <code>true</code>. In fact, such a <code>switch</code>
is a form of <code>if-else</code> chain. While we're here, it should be mentioned that in
<code>switch</code> statements each <code>case</code> has an implicit <code>break</code>.
<p>
The argument to <code>file.Stdout.Write</code> is created by slicing the array <code>buf</code>.
Slices provide the standard Go way to handle I/O buffers.
<p>
Now let's make a variant of <code>cat</code> that optionally does <code>rot13</code> on its input.
It's easy to do by just processing the bytes, but instead we will exploit
Go's notion of an <i>interface</i>.
<p>
The <code>cat</code> subroutine uses only two methods of <code>f</code>: <code>Read</code> and <code>String</code>,
so let's start by defining an interface that has exactly those two methods.
Here is code from <code>progs/cat_rot13.go</code>:
<p>
{{code "progs/cat_rot13.go" `/type.reader/` `/^}/`}}
<p>
Any type that has the two methods of <code>reader</code>&mdash;regardless of whatever
other methods the type may also have&mdash;is said to <i>implement</i> the
interface. Since <code>file.File</code> implements these methods, it implements the
<code>reader</code> interface. We could tweak the <code>cat</code> subroutine to accept a <code>reader</code>
instead of a <code>*file.File</code> and it would work just fine, but let's embellish a little
first by writing a second type that implements <code>reader</code>, one that wraps an
existing <code>reader</code> and does <code>rot13</code> on the data. To do this, we just define
the type and implement the methods and with no other bookkeeping,
we have a second implementation of the <code>reader</code> interface.
<p>
{{code "progs/cat_rot13.go" `/type.rotate13/` `/end.of.rotate13/`}}
<p>
(The <code>rot13</code> function called in <code>Read</code> is trivial and not worth reproducing here.)
<p>
To use the new feature, we define a flag:
<p>
{{code "progs/cat_rot13.go" `/rot13Flag/`}}
<p>
and use it from within a mostly unchanged <code>cat</code> function:
<p>
{{code "progs/cat_rot13.go" `/func.cat/` `/^}/`}}
<p>
(We could also do the wrapping in <code>main</code> and leave <code>cat</code> mostly alone, except
for changing the type of the argument; consider that an exercise.)
The <code>if</code> at the top of <code>cat</code> sets it all up: If the <code>rot13</code> flag is true, wrap the <code>reader</code>
we received into a <code>rotate13</code> and proceed. Note that the interface variables
are values, not pointers: the argument is of type <code>reader</code>, not <code>*reader</code>,
even though under the covers it holds a pointer to a <code>struct</code>.
<p>
Here it is in action:
<p>
<pre>
$ echo abcdefghijklmnopqrstuvwxyz | ./cat
abcdefghijklmnopqrstuvwxyz
$ echo abcdefghijklmnopqrstuvwxyz | ./cat --rot13
nopqrstuvwxyzabcdefghijklm
$
</pre>
<p>
Fans of dependency injection may take cheer from how easily interfaces
allow us to substitute the implementation of a file descriptor.
<p>
Interfaces are a distinctive feature of Go. An interface is implemented by a
type if the type implements all the methods declared in the interface.
This means
that a type may implement an arbitrary number of different interfaces.
There is no type hierarchy; things can be much more <i>ad hoc</i>,
as we saw with <code>rot13</code>. The type <code>file.File</code> implements <code>reader</code>; it could also
implement a <code>writer</code>, or any other interface built from its methods that
fits the current situation. Consider the <i>empty interface</i>
<p>
<pre>
type Empty interface {}
</pre>
<p>
<i>Every</i> type implements the empty interface, which makes it
useful for things like containers.
<p>
<h2>Sorting</h2>
<p>
Interfaces provide a simple form of polymorphism. They completely
separate the definition of what an object does from how it does it, allowing
distinct implementations to be represented at different times by the
same interface variable.
<p>
As an example, consider this simple sort algorithm taken from <code>progs/sort.go</code>:
<p>
{{code "progs/sort.go" `/func.Sort/` `/^}/`}}
<p>
The code needs only three methods, which we wrap into sort's <code>Interface</code>:
<p>
{{code "progs/sort.go" `/interface/` `/^}/`}}
<p>
We can apply <code>Sort</code> to any type that implements <code>Len</code>, <code>Less</code>, and <code>Swap</code>.
The <code>sort</code> package includes the necessary methods to allow sorting of
arrays of integers, strings, etc.; here's the code for arrays of <code>int</code>
<p>
{{code "progs/sort.go" `/type.*IntSlice/` `/Swap/`}}
<p>
Here we see methods defined for non-<code>struct</code> types. You can define methods
for any type you define and name in your package.
<p>
And now a routine to test it out, from <code>progs/sortmain.go</code>. This
uses a function in the <code>sort</code> package, omitted here for brevity,
to test that the result is sorted.
<p>
{{code "progs/sortmain.go" `/func.ints/` `/^}/`}}
<p>
If we have a new type we want to be able to sort, all we need to do is
to implement the three methods for that type, like this:
<p>
{{code "progs/sortmain.go" `/type.day/` `/Swap/`}}
<p>
<p>
<h2>Printing</h2>
<p>
The examples of formatted printing so far have been modest. In this section
we'll talk about how formatted I/O can be done well in Go.
<p>
We've seen simple uses of the package <code>fmt</code>, which
implements <code>Printf</code>, <code>Fprintf</code>, and so on.
Within the <code>fmt</code> package, <code>Printf</code> is declared with this signature:
<p>
<pre>
Printf(format string, v ...interface{}) (n int, errno os.Error)
</pre>
<p>
The token <code>...</code> introduces a variable-length argument list that in C would
be handled using the <code>stdarg.h</code> macros.
In Go, variadic functions are passed a slice of the arguments of the
specified type. In <code>Printf</code>'s case, the declaration says <code>...interface{}</code>
so the actual type is a slice of empty interface values, <code>[]interface{}</code>.
<code>Printf</code> can examine the arguments by iterating over the slice
and, for each element, using a type switch or the reflection library
to interpret the value.
It's off topic here but such run-time type analysis
helps explain some of the nice properties of Go's <code>Printf</code>,
due to the ability of <code>Printf</code> to discover the type of its arguments
dynamically.
<p>
For example, in C each format must correspond to the type of its
argument. It's easier in many cases in Go. Instead of <code>%llud</code> you
can just say <code>%d</code>; <code>Printf</code> knows the size and signedness of the
integer and can do the right thing for you. The snippet
<p>
{{code "progs/print.go" 10 11}}
<p>
prints
<p>
<pre>
18446744073709551615 -1
</pre>
<p>
In fact, if you're lazy the format <code>%v</code> will print, in a simple
appropriate style, any value, even an array or structure. The output of
<p>
{{code "progs/print.go" 14 20}}
<p>
is
<p>
<pre>
18446744073709551615 {77 Sunset Strip} [1 2 3 4]
</pre>
<p>
You can drop the formatting altogether if you use <code>Print</code> or <code>Println</code>
instead of <code>Printf</code>. Those routines do fully automatic formatting.
The <code>Print</code> function just prints its elements out using the equivalent
of <code>%v</code> while <code>Println</code> inserts spaces between arguments
and adds a newline. The output of each of these two lines is identical
to that of the <code>Printf</code> call above.
<p>
{{code "progs/print.go" 21 22}}
<p>
If you have your own type you'd like <code>Printf</code> or <code>Print</code> to format,
just give it a <code>String</code> method that returns a string. The print
routines will examine the value to inquire whether it implements
the method and if so, use it rather than some other formatting.
Here's a simple example.
<p>
{{code "progs/print_string.go" 9 "$"}}
<p>
Since <code>*testType</code> has a <code>String</code> method, the
default formatter for that type will use it and produce the output
<p>
<pre>
77 Sunset Strip
</pre>
<p>
Observe that the <code>String</code> method calls <code>Sprint</code> (the obvious Go
variant that returns a string) to do its formatting; special formatters
can use the <code>fmt</code> library recursively.
<p>
Another feature of <code>Printf</code> is that the format <code>%T</code> will print a string
representation of the type of a value, which can be handy when debugging
polymorphic code.
<p>
It's possible to write full custom print formats with flags and precisions
and such, but that's getting a little off the main thread so we'll leave it
as an exploration exercise.
<p>
You might ask, though, how <code>Printf</code> can tell whether a type implements
the <code>String</code> method. Actually what it does is ask if the value can
be converted to an interface variable that implements the method.
Schematically, given a value <code>v</code>, it does this:
<p>
<p>
<pre>
type Stringer interface {
String() string
}
</pre>
<p>
<pre>
s, ok := v.(Stringer) // Test whether v implements "String()"
if ok {
result = s.String()
} else {
result = defaultOutput(v)
}
</pre>
<p>
The code uses a ``type assertion'' (<code>v.(Stringer)</code>) to test if the value stored in
<code>v</code> satisfies the <code>Stringer</code> interface; if it does, <code>s</code>
will become an interface variable implementing the method and <code>ok</code> will
be <code>true</code>. We then use the interface variable to call the method.
(The ''comma, ok'' pattern is a Go idiom used to test the success of
operations such as type conversion, map update, communications, and so on,
although this is the only appearance in this tutorial.)
If the value does not satisfy the interface, <code>ok</code> will be false.
<p>
In this snippet the name <code>Stringer</code> follows the convention that we add ''[e]r''
to interfaces describing simple method sets like this.
<p>
One last wrinkle. To complete the suite, besides <code>Printf</code> etc. and <code>Sprintf</code>
etc., there are also <code>Fprintf</code> etc. Unlike in C, <code>Fprintf</code>'s first argument is
not a file. Instead, it is a variable of type <code>io.Writer</code>, which is an
interface type defined in the <code>io</code> library:
<p>
<pre>
type Writer interface {
Write(p []byte) (n int, err os.Error)
}
</pre>
<p>
(This interface is another conventional name, this time for <code>Write</code>; there are also
<code>io.Reader</code>, <code>io.ReadWriter</code>, and so on.)
Thus you can call <code>Fprintf</code> on any type that implements a standard <code>Write</code>
method, not just files but also network channels, buffers, whatever
you want.
<p>
<h2>Prime numbers</h2>
<p>
Now we come to processes and communication&mdash;concurrent programming.
It's a big subject so to be brief we assume some familiarity with the topic.
<p>
A classic program in the style is a prime sieve.
(The sieve of Eratosthenes is computationally more efficient than
the algorithm presented here, but we are more interested in concurrency than
algorithmics at the moment.)
It works by taking a stream of all the natural numbers and introducing
a sequence of filters, one for each prime, to winnow the multiples of
that prime. At each step we have a sequence of filters of the primes
so far, and the next number to pop out is the next prime, which triggers
the creation of the next filter in the chain.
<p>
Here's a flow diagram; each box represents a filter element whose
creation is triggered by the first number that flowed from the
elements before it.
<p>
<br>
<p>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src='sieve.gif'>
<p>
<br>
<p>
To create a stream of integers, we use a Go <i>channel</i>, which,
borrowing from CSP's descendants, represents a communications
channel that can connect two concurrent computations.
In Go, channel variables are references to a run-time object that
coordinates the communication; as with maps and slices, use
<code>make</code> to create a new channel.
<p>
Here is the first function in <code>progs/sieve.go</code>:
<p>
{{code "progs/sieve.go" `/Send/` `/^}/`}}
<p>
The <code>generate</code> function sends the sequence 2, 3, 4, 5, ... to its
argument channel, <code>ch</code>, using the binary communications operator <code>&lt;-</code>.
Channel operations block, so if there's no recipient for the value on <code>ch</code>,
the send operation will wait until one becomes available.
<p>
The <code>filter</code> function has three arguments: an input channel, an output
channel, and a prime number. It copies values from the input to the
output, discarding anything divisible by the prime. The unary communications
operator <code>&lt;-</code> (receive) retrieves the next value on the channel.
<p>
{{code "progs/sieve.go" `/Copy.the/` `/^}/`}}
<p>
The generator and filters execute concurrently. Go has
its own model of process/threads/light-weight processes/coroutines,
so to avoid notational confusion we call concurrently executing
computations in Go <i>goroutines</i>. To start a goroutine,
invoke the function, prefixing the call with the keyword <code>go</code>;
this starts the function running in parallel with the current
computation but in the same address space:
<p>
<pre>
go sum(hugeArray) // calculate sum in the background
</pre>
<p>
If you want to know when the calculation is done, pass a channel
on which it can report back:
<p>
<pre>
ch := make(chan int)
go sum(hugeArray, ch)
// ... do something else for a while
result := &lt;-ch // wait for, and retrieve, result
</pre>
<p>
Back to our prime sieve. Here's how the sieve pipeline is stitched
together:
<p>
{{code "progs/sieve.go" `/func.main/` `/^}/`}}
<p>
The first line of <code>main</code> creates the initial channel to pass to <code>generate</code>, which it
then starts up. As each prime pops out of the channel, a new <code>filter</code>
is added to the pipeline and <i>its</i> output becomes the new value
of <code>ch</code>.
<p>
The sieve program can be tweaked to use a pattern common
in this style of programming. Here is a variant version
of <code>generate</code>, from <code>progs/sieve1.go</code>:
<p>
{{code "progs/sieve1.go" `/func.generate/` `/^}/`}}
<p>
This version does all the setup internally. It creates the output
channel, launches a goroutine running a function literal, and
returns the channel to the caller. It is a factory for concurrent
execution, starting the goroutine and returning its connection.
<p>
The function literal notation used in the <code>go</code> statement allows us to construct an
anonymous function and invoke it on the spot. Notice that the local
variable <code>ch</code> is available to the function literal and lives on even
after <code>generate</code> returns.
<p>
The same change can be made to <code>filter</code>:
<p>
{{code "progs/sieve1.go" `/func.filter/` `/^}/`}}
<p>
The <code>sieve</code> function's main loop becomes simpler and clearer as a
result, and while we're at it let's turn it into a factory too:
<p>
{{code "progs/sieve1.go" `/func.sieve/` `/^}/`}}
<p>
Now <code>main</code>'s interface to the prime sieve is a channel of primes:
<p>
{{code "progs/sieve1.go" `/func.main/` `/^}/`}}
<p>
<h2>Multiplexing</h2>
<p>
With channels, it's possible to serve multiple independent client goroutines without
writing an explicit multiplexer. The trick is to send the server a channel in the message,
which it will then use to reply to the original sender.
A realistic client-server program is a lot of code, so here is a very simple substitute
to illustrate the idea. It starts by defining a <code>request</code> type, which embeds a channel
that will be used for the reply.
<p>
{{code "progs/server.go" `/type.request/` `/^}/`}}
<p>
The server will be trivial: it will do simple binary operations on integers. Here's the
code that invokes the operation and responds to the request:
<p>
{{code "progs/server.go" `/type.binOp/` `/^}/`}}
<p>
The type declaration makes <code>binOp</code> represent a function taking two integers and
returning a third.
<p>
The <code>server</code> routine loops forever, receiving requests and, to avoid blocking due to
a long-running operation, starting a goroutine to do the actual work.
<p>
{{code "progs/server.go" `/func.server/` `/^}/`}}
<p>
We construct a server in a familiar way, starting it and returning a channel
connected to it:
<p>
{{code "progs/server.go" `/func.startServer/` `/^}/`}}
<p>
Here's a simple test. It starts a server with an addition operator and sends out
<code>N</code> requests without waiting for the replies. Only after all the requests are sent
does it check the results.
<p>
{{code "progs/server.go" `/func.main/` `/^}/`}}
<p>
One annoyance with this program is that it doesn't shut down the server cleanly; when <code>main</code> returns
there are a number of lingering goroutines blocked on communication. To solve this,
we can provide a second, <code>quit</code> channel to the server:
<p>
{{code "progs/server1.go" `/func.startServer/` `/^}/`}}
<p>
It passes the quit channel to the <code>server</code> function, which uses it like this:
<p>
{{code "progs/server1.go" `/func.server/` `/^}/`}}
<p>
Inside <code>server</code>, the <code>select</code> statement chooses which of the multiple communications
listed by its cases can proceed. If all are blocked, it waits until one can proceed; if
multiple can proceed, it chooses one at random. In this instance, the <code>select</code> allows
the server to honor requests until it receives a quit message, at which point it
returns, terminating its execution.
<p>
<p>
All that's left is to strobe the <code>quit</code> channel
at the end of main:
<p>
{{code "progs/server1.go" `/adder,.quit/`}}
...
{{code "progs/server1.go" `/quit....true/`}}
<p>
There's a lot more to Go programming and concurrent programming in general but this
quick tour should give you some of the basics.

View File

@@ -1,939 +0,0 @@
<!-- A Tutorial for the Go Programming Language -->
Introduction
----
This document is a tutorial introduction to the basics of the Go programming
language, intended for programmers familiar with C or C++. It is not a comprehensive
guide to the language; at the moment the document closest to that is the
<a href='/doc/go_spec.html'>language specification</a>.
After you've read this tutorial, you should look at
<a href='/doc/effective_go.html'>Effective Go</a>,
which digs deeper into how the language is used and
talks about the style and idioms of programming in Go.
Also, slides from a 3-day course about Go are available.
Although they're badly out of date, they provide some
background and a lot of examples:
<a href='/doc/GoCourseDay1.pdf'>Day 1</a>,
<a href='/doc/GoCourseDay2.pdf'>Day 2</a>,
<a href='/doc/GoCourseDay3.pdf'>Day 3</a>.
The presentation here proceeds through a series of modest programs to illustrate
key features of the language. All the programs work (at time of writing) and are
checked into the repository in the directory <a href='/doc/progs'>"/doc/progs/"</a>.
Program snippets are annotated with the line number in the original file; for
cleanliness, blank lines remain blank.
Hello, World
----
Let's start in the usual way:
--PROG progs/helloworld.go /package/ END
Every Go source file declares, using a "package" statement, which package it's part of.
It may also import other packages to use their facilities.
This program imports the package "fmt" to gain access to
our old, now capitalized and package-qualified, friend, "fmt.Printf".
Functions are introduced with the "func" keyword.
The "main" package's "main" function is where the program starts running (after
any initialization).
String constants can contain Unicode characters, encoded in UTF-8.
(In fact, Go source files are defined to be encoded in UTF-8.)
The comment convention is the same as in C++:
/* ... */
// ...
Later we'll have much more to say about printing.
Semicolons
----
You might have noticed that our program has no semicolons. In Go
code, the only place you typically see semicolons is separating the
clauses of "for" loops and the like; they are not necessary after
every statement.
In fact, what happens is that the formal language uses semicolons,
much as in C or Java, but they are inserted automatically
at the end of every line that looks like the end of a statement. You
don't need to type them yourself.
For details about how this is done you can see the language
specification, but in practice all you need to know is that you
never need to put a semicolon at the end of a line. (You can put
them in if you want to write multiple statements per line.) As an
extra help, you can also leave out a semicolon immediately before
a closing brace.
This approach makes for clean-looking, semicolon-free code. The
one surprise is that it's important to put the opening
brace of a construct such as an "if" statement on the same line as
the "if"; if you don't, there are situations that may not compile
or may give the wrong result. The language forces the brace style
to some extent.
Compiling
----
Go is a compiled language. At the moment there are two compilers.
"Gccgo" is a Go compiler that uses the GCC back end. There is also a
suite of compilers with different (and odd) names for each architecture:
"6g" for the 64-bit x86, "8g" for the 32-bit x86, and more. These
compilers run significantly faster but generate less efficient code
than "gccgo". At the time of writing (late 2009), they also have
a more robust run-time system although "gccgo" is catching up.
Here's how to compile and run our program. With "6g", say,
$ 6g helloworld.go # compile; object goes into helloworld.6
$ 6l helloworld.6 # link; output goes into 6.out
$ 6.out
Hello, world; or Καλημέρα κόσμε; or こんにちは 世界
$
With "gccgo" it looks a little more traditional.
$ gccgo helloworld.go
$ a.out
Hello, world; or Καλημέρα κόσμε; or こんにちは 世界
$
Echo
----
Next up, here's a version of the Unix utility "echo(1)":
--PROG progs/echo.go /package/ END
This program is small but it's doing a number of new things. In the last example,
we saw "func" introduce a function. The keywords "var", "const", and "type"
(not used yet) also introduce declarations, as does "import".
Notice that we can group declarations of the same sort into
parenthesized lists, one item per line, as on lines 7-10 and 14-17.
But it's not necessary to do so; we could have said
const Space = " "
const Newline = "\n"
This program imports the "&quot;os&quot;" package to access its "Stdout" variable, of type
"*os.File". The "import" statement is actually a declaration: in its general form,
as used in our ``hello world'' program,
it names the identifier ("fmt")
that will be used to access members of the package imported from the file ("&quot;fmt&quot;"),
found in the current directory or in a standard location.
In this program, though, we've dropped the explicit name from the imports; by default,
packages are imported using the name defined by the imported package,
which by convention is of course the file name itself. Our ``hello world'' program
could have said just "import &quot;fmt&quot;".
You can specify your
own import names if you want but it's only necessary if you need to resolve
a naming conflict.
Given "os.Stdout" we can use its "WriteString" method to print the string.
Having imported the "flag" package, line 12 creates a global variable to hold
the value of echo's "-n" flag. The variable "omitNewline" has type "*bool", pointer
to "bool".
In "main.main", we parse the arguments (line 20) and then create a local
string variable we will use to build the output.
The declaration statement has the form
var s string = ""
This is the "var" keyword, followed by the name of the variable, followed by
its type, followed by an equals sign and an initial value for the variable.
Go tries to be terse, and this declaration could be shortened. Since the
string constant is of type string, we don't have to tell the compiler that.
We could write
var s = ""
or we could go even shorter and write the idiom
s := ""
The ":=" operator is used a lot in Go to represent an initializing declaration.
There's one in the "for" clause on the next line:
--PROG progs/echo.go /for/
The "flag" package has parsed the arguments and left the non-flag arguments
in a list that can be iterated over in the obvious way.
The Go "for" statement differs from that of C in a number of ways. First,
it's the only looping construct; there is no "while" or "do". Second,
there are no parentheses on the clause, but the braces on the body
are mandatory. The same applies to the "if" and "switch" statements.
Later examples will show some other ways "for" can be written.
The body of the loop builds up the string "s" by appending (using "+=")
the arguments and separating spaces. After the loop, if the "-n" flag is not
set, the program appends a newline. Finally, it writes the result.
Notice that "main.main" is a niladic function with no return type.
It's defined that way. Falling off the end of "main.main" means
''success''; if you want to signal an erroneous return, call
os.Exit(1)
The "os" package contains other essentials for getting
started; for instance, "os.Args" is a slice used by the
"flag" package to access the command-line arguments.
An Interlude about Types
----
Go has some familiar types such as "int" and "uint" (unsigned "int"), which represent
values of the ''appropriate'' size for the machine. It also defines
explicitly-sized types such as "int8", "float64", and so on, plus
unsigned integer types such as "uint", "uint32", etc.
These are distinct types; even if "int" and "int32" are both 32 bits in size,
they are not the same type. There is also a "byte" synonym for
"uint8", which is the element type for strings.
Floating-point types are always sized: "float32" and "float64",
plus "complex64" (two "float32s") and "complex128"
(two "float64s"). Complex numbers are outside the
scope of this tutorial.
Speaking of "string", that's a built-in type as well. Strings are
<i>immutable values</i>&mdash;they are not just arrays of "byte" values.
Once you've built a string <i>value</i>, you can't change it, although
of course you can change a string <i>variable</i> simply by
reassigning it. This snippet from "strings.go" is legal code:
--PROG progs/strings.go /hello/ /ciao/
However the following statements are illegal because they would modify
a "string" value:
s[0] = 'x'
(*p)[1] = 'y'
In C++ terms, Go strings are a bit like "const strings", while pointers
to strings are analogous to "const string" references.
Yes, there are pointers. However, Go simplifies their use a little;
read on.
Arrays are declared like this:
var arrayOfInt [10]int
Arrays, like strings, are values, but they are mutable. This differs
from C, in which "arrayOfInt" would be usable as a pointer to "int".
In Go, since arrays are values, it's meaningful (and useful) to talk
about pointers to arrays.
The size of the array is part of its type; however, one can declare
a <i>slice</i> variable to hold a reference to any array, of any size,
with the same element type.
A <i>slice
expression</i> has the form "a[low : high]", representing
the internal array indexed from "low" through "high-1"; the resulting
slice is indexed from "0" through "high-low-1".
In short, slices look a lot like arrays but with
no explicit size ("[]" vs. "[10]") and they reference a segment of
an underlying, usually anonymous, regular array. Multiple slices
can share data if they represent pieces of the same array;
multiple arrays can never share data.
Slices are much more common in Go programs than
regular arrays; they're more flexible, have reference semantics,
and are efficient. What they lack is the precise control of storage
layout of a regular array; if you want to have a hundred elements
of an array stored within your structure, you should use a regular
array. To create one, use a compound value <i>constructor</i>&mdash;an
expression formed
from a type followed by a brace-bounded expression like this:
[3]int{1,2,3}
In this case the constructor builds an array of 3 "ints".
When passing an array to a function, you almost always want
to declare the formal parameter to be a slice. When you call
the function, slice the array to create
(efficiently) a slice reference and pass that.
By default, the lower and upper bounds of a slice match the
ends of the existing object, so the concise notation "[:]"
will slice the whole array.
Using slices one can write this function (from "sum.go"):
--PROG progs/sum.go /sum/ /^}/
Note how the return type ("int") is defined for "sum" by stating it
after the parameter list.
To call the function, we slice the array. This intricate call (we'll show
a simpler way in a moment) constructs
an array and slices it:
s := sum([3]int{1,2,3}[:])
If you are creating a regular array but want the compiler to count the
elements for you, use "..." as the array size:
s := sum([...]int{1,2,3}[:])
That's fussier than necessary, though.
In practice, unless you're meticulous about storage layout within a
data structure, a slice itself&mdash;using empty brackets with no size&mdash;is all you need:
s := sum([]int{1,2,3})
There are also maps, which you can initialize like this:
m := map[string]int{"one":1 , "two":2}
The built-in function "len", which returns number of elements,
makes its first appearance in "sum". It works on strings, arrays,
slices, maps, and channels.
By the way, another thing that works on strings, arrays, slices, maps
and channels is the "range" clause on "for" loops. Instead of writing
for i := 0; i &lt; len(a); i++ { ... }
to loop over the elements of a slice (or map or ...) , we could write
for i, v := range a { ... }
This assigns "i" to the index and "v" to the value of the successive
elements of the target of the range. See
<a href='/doc/effective_go.html'>Effective Go</a>
for more examples of its use.
An Interlude about Allocation
----
Most types in Go are values. If you have an "int" or a "struct"
or an array, assignment
copies the contents of the object.
To allocate a new variable, use the built-in function "new", which
returns a pointer to the allocated storage.
type T struct { a, b int }
var t *T = new(T)
or the more idiomatic
t := new(T)
Some types&mdash;maps, slices, and channels (see below)&mdash;have reference semantics.
If you're holding a slice or a map and you modify its contents, other variables
referencing the same underlying data will see the modification. For these three
types you want to use the built-in function "make":
m := make(map[string]int)
This statement initializes a new map ready to store entries.
If you just declare the map, as in
var m map[string]int
it creates a "nil" reference that cannot hold anything. To use the map,
you must first initialize the reference using "make" or by assignment from an
existing map.
Note that "new(T)" returns type "*T" while "make(T)" returns type
"T". If you (mistakenly) allocate a reference object with "new" rather than "make",
you receive a pointer to a nil reference, equivalent to
declaring an uninitialized variable and taking its address.
An Interlude about Constants
----
Although integers come in lots of sizes in Go, integer constants do not.
There are no constants like "0LL" or "0x0UL". Instead, integer
constants are evaluated as large-precision values that
can overflow only when they are assigned to an integer variable with
too little precision to represent the value.
const hardEight = (1 &lt;&lt; 100) &gt;&gt; 97 // legal
There are nuances that deserve redirection to the legalese of the
language specification but here are some illustrative examples:
var a uint64 = 0 // a has type uint64, value 0
a := uint64(0) // equivalent; uses a "conversion"
i := 0x1234 // i gets default type: int
var j int = 1e6 // legal - 1000000 is representable in an int
x := 1.5 // a float64, the default type for floating constants
i3div2 := 3/2 // integer division - result is 1
f3div2 := 3./2. // floating-point division - result is 1.5
Conversions only work for simple cases such as converting "ints" of one
sign or size to another and between integers and floating-point numbers,
plus a couple of other instances outside the scope of a tutorial.
There are no automatic numeric conversions of any kind in Go,
other than that of making constants have concrete size and type when
assigned to a variable.
An I/O Package
----
Next we'll look at a simple package for doing file I/O with an
open/close/read/write interface. Here's the start of "file.go":
--PROG progs/file.go /package/ /^}/
The first few lines declare the name of the
package&mdash;"file"&mdash;and then import two packages. The "os"
package hides the differences
between various operating systems to give a consistent view of files and
so on; here we're going to use its error handling utilities
and reproduce the rudiments of its file I/O.
The other item is the low-level, external "syscall" package, which provides
a primitive interface to the underlying operating system's calls.
Next is a type definition: the "type" keyword introduces a type declaration,
in this case a data structure called "File".
To make things a little more interesting, our "File" includes the name of the file
that the file descriptor refers to.
Because "File" starts with a capital letter, the type is available outside the package,
that is, by users of the package. In Go the rule about visibility of information is
simple: if a name (of a top-level type, function, method, constant or variable, or of
a structure field or method) is capitalized, users of the package may see it. Otherwise, the
name and hence the thing being named is visible only inside the package in which
it is declared. This is more than a convention; the rule is enforced by the compiler.
In Go, the term for publicly visible names is ''exported''.
In the case of "File", all its fields are lower case and so invisible to users, but we
will soon give it some exported, upper-case methods.
First, though, here is a factory to create a "File":
--PROG progs/file.go /newFile/ /^}/
This returns a pointer to a new "File" structure with the file descriptor and name
filled in. This code uses Go's notion of a ''composite literal'', analogous to
the ones used to build maps and arrays, to construct a new heap-allocated
object. We could write
n := new(File)
n.fd = fd
n.name = name
return n
but for simple structures like "File" it's easier to return the address of a
composite literal, as is done here on line 21.
We can use the factory to construct some familiar, exported variables of type "*File":
--PROG progs/file.go /var/ /^.$/
The "newFile" function was not exported because it's internal. The proper,
exported factory to use is "OpenFile" (we'll explain that name in a moment):
--PROG progs/file.go /func.OpenFile/ /^}/
There are a number of new things in these few lines. First, "OpenFile" returns
multiple values, a "File" and an error (more about errors in a moment).
We declare the
multi-value return as a parenthesized list of declarations; syntactically
they look just like a second parameter list. The function
"syscall.Open"
also has a multi-value return, which we can grab with the multi-variable
declaration on line 31; it declares "r" and "e" to hold the two values,
both of type "int" (although you'd have to look at the "syscall" package
to see that). Finally, line 35 returns two values: a pointer to the new "File"
and the error. If "syscall.Open" fails, the file descriptor "r" will
be negative and "newFile" will return "nil".
About those errors: The "os" library includes a general notion of an error.
It's a good idea to use its facility in your own interfaces, as we do here, for
consistent error handling throughout Go code. In "Open" we use a
conversion to translate Unix's integer "errno" value into the integer type
"os.Errno", which implements "os.Error".
Why "OpenFile" and not "Open"? To mimic Go's "os" package, which
our exercise is emulating. The "os" package takes the opportunity
to make the two commonest cases - open for read and create for
write - the simplest, just "Open" and "Create". "OpenFile" is the
general case, analogous to the Unix system call "Open". Here is
the implementation of our "Open" and "Create"; they're trivial
wrappers that eliminate common errors by capturing
the tricky standard arguments to open and, especially, to create a file:
--PROG progs/file.go /^const/ /^}/
--PROG progs/file.go /func.Create/ /^}/
Back to our main story.
Now that we can build "Files", we can write methods for them. To declare
a method of a type, we define a function to have an explicit receiver
of that type, placed
in parentheses before the function name. Here are some methods for "*File",
each of which declares a receiver variable "file".
--PROG progs/file.go /Close/ END
There is no implicit "this" and the receiver variable must be used to access
members of the structure. Methods are not declared within
the "struct" declaration itself. The "struct" declaration defines only data members.
In fact, methods can be created for almost any type you name, such as an integer or
array, not just for "structs". We'll see an example with arrays later.
The "String" method is so called because of a printing convention we'll
describe later.
The methods use the public variable "os.EINVAL" to return the ("os.Error"
version of the) Unix error code "EINVAL". The "os" library defines a standard
set of such error values.
We can now use our new package:
--PROG progs/helloworld3.go /package/ END
The ''"./"'' in the import of ''"./file"'' tells the compiler
to use our own package rather than
something from the directory of installed packages.
(Also, ''"file.go"'' must be compiled before we can import the
package.)
Now we can compile and run the program. On Unix, this would be the result:
$ 6g file.go # compile file package
$ 6g helloworld3.go # compile main package
$ 6l -o helloworld3 helloworld3.6 # link - no need to mention "file"
$ helloworld3
hello, world
can't open file; err=No such file or directory
$
Rotting cats
----
Building on the "file" package, here's a simple version of the Unix utility "cat(1)",
"progs/cat.go":
--PROG progs/cat.go /package/ END
By now this should be easy to follow, but the "switch" statement introduces some
new features. Like a "for" loop, an "if" or "switch" can include an
initialization statement. The "switch" on line 18 uses one to create variables
"nr" and "er" to hold the return values from the call to "f.Read". (The "if" on line 25
has the same idea.) The "switch" statement is general: it evaluates the cases
from top to bottom looking for the first case that matches the value; the
case expressions don't need to be constants or even integers, as long as
they all have the same type.
Since the "switch" value is just "true", we could leave it off&mdash;as is also
the situation
in a "for" statement, a missing value means "true". In fact, such a "switch"
is a form of "if-else" chain. While we're here, it should be mentioned that in
"switch" statements each "case" has an implicit "break".
Line 25 calls "Write" by slicing the incoming buffer, which is itself a slice.
Slices provide the standard Go way to handle I/O buffers.
Now let's make a variant of "cat" that optionally does "rot13" on its input.
It's easy to do by just processing the bytes, but instead we will exploit
Go's notion of an <i>interface</i>.
The "cat" subroutine uses only two methods of "f": "Read" and "String",
so let's start by defining an interface that has exactly those two methods.
Here is code from "progs/cat_rot13.go":
--PROG progs/cat_rot13.go /type.reader/ /^}/
Any type that has the two methods of "reader"&mdash;regardless of whatever
other methods the type may also have&mdash;is said to <i>implement</i> the
interface. Since "file.File" implements these methods, it implements the
"reader" interface. We could tweak the "cat" subroutine to accept a "reader"
instead of a "*file.File" and it would work just fine, but let's embellish a little
first by writing a second type that implements "reader", one that wraps an
existing "reader" and does "rot13" on the data. To do this, we just define
the type and implement the methods and with no other bookkeeping,
we have a second implementation of the "reader" interface.
--PROG progs/cat_rot13.go /type.rotate13/ /end.of.rotate13/
(The "rot13" function called on line 42 is trivial and not worth reproducing here.)
To use the new feature, we define a flag:
--PROG progs/cat_rot13.go /rot13Flag/
and use it from within a mostly unchanged "cat" function:
--PROG progs/cat_rot13.go /func.cat/ /^}/
(We could also do the wrapping in "main" and leave "cat" mostly alone, except
for changing the type of the argument; consider that an exercise.)
Lines 56 through 58 set it all up: If the "rot13" flag is true, wrap the "reader"
we received into a "rotate13" and proceed. Note that the interface variables
are values, not pointers: the argument is of type "reader", not "*reader",
even though under the covers it holds a pointer to a "struct".
Here it is in action:
<pre>
$ echo abcdefghijklmnopqrstuvwxyz | ./cat
abcdefghijklmnopqrstuvwxyz
$ echo abcdefghijklmnopqrstuvwxyz | ./cat --rot13
nopqrstuvwxyzabcdefghijklm
$
</pre>
Fans of dependency injection may take cheer from how easily interfaces
allow us to substitute the implementation of a file descriptor.
Interfaces are a distinctive feature of Go. An interface is implemented by a
type if the type implements all the methods declared in the interface.
This means
that a type may implement an arbitrary number of different interfaces.
There is no type hierarchy; things can be much more <i>ad hoc</i>,
as we saw with "rot13". The type "file.File" implements "reader"; it could also
implement a "writer", or any other interface built from its methods that
fits the current situation. Consider the <i>empty interface</i>
<pre>
type Empty interface {}
</pre>
<i>Every</i> type implements the empty interface, which makes it
useful for things like containers.
Sorting
----
Interfaces provide a simple form of polymorphism. They completely
separate the definition of what an object does from how it does it, allowing
distinct implementations to be represented at different times by the
same interface variable.
As an example, consider this simple sort algorithm taken from "progs/sort.go":
--PROG progs/sort.go /func.Sort/ /^}/
The code needs only three methods, which we wrap into sort's "Interface":
--PROG progs/sort.go /interface/ /^}/
We can apply "Sort" to any type that implements "Len", "Less", and "Swap".
The "sort" package includes the necessary methods to allow sorting of
arrays of integers, strings, etc.; here's the code for arrays of "int"
--PROG progs/sort.go /type.*IntArray/ /Swap/
Here we see methods defined for non-"struct" types. You can define methods
for any type you define and name in your package.
And now a routine to test it out, from "progs/sortmain.go". This
uses a function in the "sort" package, omitted here for brevity,
to test that the result is sorted.
--PROG progs/sortmain.go /func.ints/ /^}/
If we have a new type we want to be able to sort, all we need to do is
to implement the three methods for that type, like this:
--PROG progs/sortmain.go /type.day/ /Swap/
Printing
----
The examples of formatted printing so far have been modest. In this section
we'll talk about how formatted I/O can be done well in Go.
We've seen simple uses of the package "fmt", which
implements "Printf", "Fprintf", and so on.
Within the "fmt" package, "Printf" is declared with this signature:
Printf(format string, v ...interface{}) (n int, errno os.Error)
The token "..." introduces a variable-length argument list that in C would
be handled using the "stdarg.h" macros.
In Go, variadic functions are passed a slice of the arguments of the
specified type. In "Printf"'s case, the declaration says "...interface{}"
so the actual type is a slice of empty interface values, "[]interface{}".
"Printf" can examine the arguments by iterating over the slice
and, for each element, using a type switch or the reflection library
to interpret the value.
It's off topic here but such run-time type analysis
helps explain some of the nice properties of Go's "Printf",
due to the ability of "Printf" to discover the type of its arguments
dynamically.
For example, in C each format must correspond to the type of its
argument. It's easier in many cases in Go. Instead of "%llud" you
can just say "%d"; "Printf" knows the size and signedness of the
integer and can do the right thing for you. The snippet
--PROG progs/print.go 'NR==10' 'NR==11'
prints
18446744073709551615 -1
In fact, if you're lazy the format "%v" will print, in a simple
appropriate style, any value, even an array or structure. The output of
--PROG progs/print.go 'NR==14' 'NR==20'
is
18446744073709551615 {77 Sunset Strip} [1 2 3 4]
You can drop the formatting altogether if you use "Print" or "Println"
instead of "Printf". Those routines do fully automatic formatting.
The "Print" function just prints its elements out using the equivalent
of "%v" while "Println" inserts spaces between arguments
and adds a newline. The output of each of these two lines is identical
to that of the "Printf" call above.
--PROG progs/print.go 'NR==21' 'NR==22'
If you have your own type you'd like "Printf" or "Print" to format,
just give it a "String" method that returns a string. The print
routines will examine the value to inquire whether it implements
the method and if so, use it rather than some other formatting.
Here's a simple example.
--PROG progs/print_string.go 'NR==9' END
Since "*testType" has a "String" method, the
default formatter for that type will use it and produce the output
77 Sunset Strip
Observe that the "String" method calls "Sprint" (the obvious Go
variant that returns a string) to do its formatting; special formatters
can use the "fmt" library recursively.
Another feature of "Printf" is that the format "%T" will print a string
representation of the type of a value, which can be handy when debugging
polymorphic code.
It's possible to write full custom print formats with flags and precisions
and such, but that's getting a little off the main thread so we'll leave it
as an exploration exercise.
You might ask, though, how "Printf" can tell whether a type implements
the "String" method. Actually what it does is ask if the value can
be converted to an interface variable that implements the method.
Schematically, given a value "v", it does this:
type Stringer interface {
String() string
}
s, ok := v.(Stringer) // Test whether v implements "String()"
if ok {
result = s.String()
} else {
result = defaultOutput(v)
}
The code uses a ``type assertion'' ("v.(Stringer)") to test if the value stored in
"v" satisfies the "Stringer" interface; if it does, "s"
will become an interface variable implementing the method and "ok" will
be "true". We then use the interface variable to call the method.
(The ''comma, ok'' pattern is a Go idiom used to test the success of
operations such as type conversion, map update, communications, and so on,
although this is the only appearance in this tutorial.)
If the value does not satisfy the interface, "ok" will be false.
In this snippet the name "Stringer" follows the convention that we add ''[e]r''
to interfaces describing simple method sets like this.
One last wrinkle. To complete the suite, besides "Printf" etc. and "Sprintf"
etc., there are also "Fprintf" etc. Unlike in C, "Fprintf"'s first argument is
not a file. Instead, it is a variable of type "io.Writer", which is an
interface type defined in the "io" library:
type Writer interface {
Write(p []byte) (n int, err os.Error)
}
(This interface is another conventional name, this time for "Write"; there are also
"io.Reader", "io.ReadWriter", and so on.)
Thus you can call "Fprintf" on any type that implements a standard "Write"
method, not just files but also network channels, buffers, whatever
you want.
Prime numbers
----
Now we come to processes and communication&mdash;concurrent programming.
It's a big subject so to be brief we assume some familiarity with the topic.
A classic program in the style is a prime sieve.
(The sieve of Eratosthenes is computationally more efficient than
the algorithm presented here, but we are more interested in concurrency than
algorithmics at the moment.)
It works by taking a stream of all the natural numbers and introducing
a sequence of filters, one for each prime, to winnow the multiples of
that prime. At each step we have a sequence of filters of the primes
so far, and the next number to pop out is the next prime, which triggers
the creation of the next filter in the chain.
Here's a flow diagram; each box represents a filter element whose
creation is triggered by the first number that flowed from the
elements before it.
<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src='sieve.gif'>
<br>
To create a stream of integers, we use a Go <i>channel</i>, which,
borrowing from CSP's descendants, represents a communications
channel that can connect two concurrent computations.
In Go, channel variables are references to a run-time object that
coordinates the communication; as with maps and slices, use
"make" to create a new channel.
Here is the first function in "progs/sieve.go":
--PROG progs/sieve.go /Send/ /^}/
The "generate" function sends the sequence 2, 3, 4, 5, ... to its
argument channel, "ch", using the binary communications operator "&lt;-".
Channel operations block, so if there's no recipient for the value on "ch",
the send operation will wait until one becomes available.
The "filter" function has three arguments: an input channel, an output
channel, and a prime number. It copies values from the input to the
output, discarding anything divisible by the prime. The unary communications
operator "&lt;-" (receive) retrieves the next value on the channel.
--PROG progs/sieve.go /Copy.the/ /^}/
The generator and filters execute concurrently. Go has
its own model of process/threads/light-weight processes/coroutines,
so to avoid notational confusion we call concurrently executing
computations in Go <i>goroutines</i>. To start a goroutine,
invoke the function, prefixing the call with the keyword "go";
this starts the function running in parallel with the current
computation but in the same address space:
go sum(hugeArray) // calculate sum in the background
If you want to know when the calculation is done, pass a channel
on which it can report back:
ch := make(chan int)
go sum(hugeArray, ch)
// ... do something else for a while
result := &lt;-ch // wait for, and retrieve, result
Back to our prime sieve. Here's how the sieve pipeline is stitched
together:
--PROG progs/sieve.go /func.main/ /^}/
Line 29 creates the initial channel to pass to "generate", which it
then starts up. As each prime pops out of the channel, a new "filter"
is added to the pipeline and <i>its</i> output becomes the new value
of "ch".
The sieve program can be tweaked to use a pattern common
in this style of programming. Here is a variant version
of "generate", from "progs/sieve1.go":
--PROG progs/sieve1.go /func.generate/ /^}/
This version does all the setup internally. It creates the output
channel, launches a goroutine running a function literal, and
returns the channel to the caller. It is a factory for concurrent
execution, starting the goroutine and returning its connection.
The function literal notation (lines 12-16) allows us to construct an
anonymous function and invoke it on the spot. Notice that the local
variable "ch" is available to the function literal and lives on even
after "generate" returns.
The same change can be made to "filter":
--PROG progs/sieve1.go /func.filter/ /^}/
The "sieve" function's main loop becomes simpler and clearer as a
result, and while we're at it let's turn it into a factory too:
--PROG progs/sieve1.go /func.sieve/ /^}/
Now "main"'s interface to the prime sieve is a channel of primes:
--PROG progs/sieve1.go /func.main/ /^}/
Multiplexing
----
With channels, it's possible to serve multiple independent client goroutines without
writing an explicit multiplexer. The trick is to send the server a channel in the message,
which it will then use to reply to the original sender.
A realistic client-server program is a lot of code, so here is a very simple substitute
to illustrate the idea. It starts by defining a "request" type, which embeds a channel
that will be used for the reply.
--PROG progs/server.go /type.request/ /^}/
The server will be trivial: it will do simple binary operations on integers. Here's the
code that invokes the operation and responds to the request:
--PROG progs/server.go /type.binOp/ /^}/
Line 14 defines the name "binOp" to be a function taking two integers and
returning a third.
The "server" routine loops forever, receiving requests and, to avoid blocking due to
a long-running operation, starting a goroutine to do the actual work.
--PROG progs/server.go /func.server/ /^}/
We construct a server in a familiar way, starting it and returning a channel
connected to it:
--PROG progs/server.go /func.startServer/ /^}/
Here's a simple test. It starts a server with an addition operator and sends out
"N" requests without waiting for the replies. Only after all the requests are sent
does it check the results.
--PROG progs/server.go /func.main/ /^}/
One annoyance with this program is that it doesn't shut down the server cleanly; when "main" returns
there are a number of lingering goroutines blocked on communication. To solve this,
we can provide a second, "quit" channel to the server:
--PROG progs/server1.go /func.startServer/ /^}/
It passes the quit channel to the "server" function, which uses it like this:
--PROG progs/server1.go /func.server/ /^}/
Inside "server", the "select" statement chooses which of the multiple communications
listed by its cases can proceed. If all are blocked, it waits until one can proceed; if
multiple can proceed, it chooses one at random. In this instance, the "select" allows
the server to honor requests until it receives a quit message, at which point it
returns, terminating its execution.
All that's left is to strobe the "quit" channel
at the end of main:
--PROG progs/server1.go /adder,.quit/
...
--PROG progs/server1.go /quit....true/
There's a lot more to Go programming and concurrent programming in general but this
quick tour should give you some of the basics.

Binary file not shown.

After

Width:  |  Height:  |  Size: 133 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 158 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@@ -1,177 +0,0 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Process plain text into HTML.
// - h2's are made from lines followed by a line "----\n"
// - tab-indented blocks become <pre> blocks
// - blank lines become <p> marks (except inside <pre> tags)
// - "quoted strings" become <code>quoted strings</code>
package main
import (
"bufio"
"bytes"
"log"
"os"
)
var (
lines = make([][]byte, 0, 2000) // probably big enough; grows if not
empty = []byte("")
newline = []byte("\n")
tab = []byte("\t")
quote = []byte(`"`)
indent = []byte{' ', ' ', ' ', ' '}
sectionMarker = []byte("----\n")
preStart = []byte("<pre>")
preEnd = []byte("</pre>\n")
pp = []byte("<p>\n")
)
func main() {
read()
headings()
coalesce(preStart, foldPre)
coalesce(tab, foldTabs)
paragraphs()
quotes()
write()
}
func read() {
b := bufio.NewReader(os.Stdin)
for {
line, err := b.ReadBytes('\n')
if err == os.EOF {
break
}
if err != nil {
log.Fatal(err)
}
lines = append(lines, line)
}
}
func write() {
b := bufio.NewWriter(os.Stdout)
for _, line := range lines {
b.Write(expandTabs(line))
}
b.Flush()
}
// each time prefix is found on a line, call fold and replace
// line with return value from fold.
func coalesce(prefix []byte, fold func(i int) (n int, line []byte)) {
j := 0 // output line number goes up by one each loop
for i := 0; i < len(lines); {
if bytes.HasPrefix(lines[i], prefix) {
nlines, block := fold(i)
lines[j] = block
i += nlines
} else {
lines[j] = lines[i]
i++
}
j++
}
lines = lines[0:j]
}
// return the <pre> block as a single slice
func foldPre(i int) (n int, line []byte) {
buf := new(bytes.Buffer)
for i < len(lines) {
buf.Write(lines[i])
n++
if bytes.Equal(lines[i], preEnd) {
break
}
i++
}
return n, buf.Bytes()
}
// return the tab-indented block as a single <pre>-bounded slice
func foldTabs(i int) (n int, line []byte) {
buf := new(bytes.Buffer)
buf.WriteString("<pre>\n")
for i < len(lines) {
if !bytes.HasPrefix(lines[i], tab) {
break
}
buf.Write(lines[i])
n++
i++
}
buf.WriteString("</pre>\n")
return n, buf.Bytes()
}
func headings() {
b := bufio.NewWriter(os.Stdout)
for i, l := range lines {
if i > 0 && bytes.Equal(l, sectionMarker) {
lines[i-1] = []byte("<h2>" + string(trim(lines[i-1])) + "</h2>\n")
lines[i] = empty
}
}
b.Flush()
}
func paragraphs() {
for i, l := range lines {
if bytes.Equal(l, newline) {
lines[i] = pp
}
}
}
func quotes() {
for i, l := range lines {
lines[i] = codeQuotes(l)
}
}
func codeQuotes(l []byte) []byte {
if bytes.HasPrefix(l, preStart) {
return l
}
n := bytes.Index(l, quote)
if n < 0 {
return l
}
buf := new(bytes.Buffer)
inQuote := false
for _, c := range l {
if c == '"' {
if inQuote {
buf.WriteString("</code>")
} else {
buf.WriteString("<code>")
}
inQuote = !inQuote
} else {
buf.WriteByte(c)
}
}
return buf.Bytes()
}
// drop trailing newline
func trim(l []byte) []byte {
n := len(l)
if n > 0 && l[n-1] == '\n' {
return l[0 : n-1]
}
return l
}
// expand tabs to spaces. don't worry about columns.
func expandTabs(l []byte) []byte {
return bytes.Replace(l, tab, indent, -1)
}

View File

@@ -81,8 +81,8 @@ To build it, you need these programs installed:
<li>the standard C libraries,
<li>the parser generator Bison,
<li>GNU <tt>make</tt> (version 3.81 or later),
<li><tt>awk</tt>, and
<li>the text editor <tt>ed</tt>.
and
<li><tt>awk</tt>.
</ul>
</p>
@@ -91,7 +91,7 @@ installed as part of
<a href="http://developer.apple.com/TOOLS/Xcode/">Xcode</a>.
</p>
<p>On Ubuntu/Debian, use <code>sudo apt-get install bison ed gawk gcc libc6-dev
<p>On Ubuntu/Debian, use <code>sudo apt-get install bison gawk gcc libc6-dev
make</code>. If you want to build 32-bit binaries on a 64-bit system you'll
also need the <code>libc6-dev-i386</code> package.
</p>
@@ -257,7 +257,8 @@ the process of building and testing Go programs.
<h2 id="next">What's next</h2>
<p>
Start by reading the <a href="go_tutorial.html">Go Tutorial</a>.
Start by taking <a href="http://code.google.com/p/go-tour/">A Tour of Go</a>
or reading the <a href="go_tutorial.html">Go Tutorial</a>.
</p>
<p>

View File

@@ -5,9 +5,8 @@
set -e
TXT=${1:-go_tutorial.txt} # input file
HTML=$(basename $TXT .txt).html # output file (basename)
TMP=TEMP.txt # input to htmlgen
TMPL=${1:-go_tutorial.tmpl} # input file
HTML=$(basename $TMPL .tmpl).html # output file (basename)
if ! test -w $HTML
then
@@ -15,17 +14,4 @@ then
exit 1
fi
if grep -q '^--PROG' $TXT
then
echo >&2 makehtml: processing PROG sections
<$TXT >$TMP awk '
/^--PROG/ { system("sh ./prog.sh "$2" "$3" "$4" "); getline }
/^/ {print}
'
else
cp $TXT $TMP
fi
make htmlgen && ./htmlgen < $TMP > $HTML
rm -f $TMP
make && ./tmpltohtml $TMPL > $HTML

View File

@@ -1,72 +0,0 @@
#!/bin/sh
# Copyright 2009 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# generate HTML for a program excerpt.
# first arg is file name
# second arg is awk pattern to match start line
# third arg is awk pattern to stop processing
#
# missing third arg means print one line
# third arg "END" means proces rest of file
# missing second arg means process whole file
#
# examples:
#
# prog.sh foo.go # whole file
# prog.sh foo.go "/^func.main/" # signature of main
# prog.sh foo.go "/^func.main/" "/^}/ # body of main
#
# non-blank lines are annotated with line number in file
# line numbers are printed %.2d to make them equal-width for nice formatting.
# the format gives a leading 0. the format %2d gives a leading space but
# that appears to confuse sanjay's makehtml formatter into bungling quotes
# because it makes some lines look indented.
echo "<pre> <!-- $* -->"
case $# in
3)
if test "$3" = "END" # $2 to end of file
then
awk '
function LINE() { printf("%.2d\t%s\n", NR, $0) }
BEGIN { printing = 0 }
'$2' { printing = 1; LINE(); getline }
printing { if($0 ~ /./) { LINE() } else { print "" } }
'
else # $2 through $3
awk '
function LINE() { printf("%.2d\t%s\n", NR, $0) }
BEGIN { printing = 0 }
'$2' { printing = 1; LINE(); getline }
'$3' && printing { if(printing) {printing = 0; LINE(); exit} }
printing { if($0 ~ /./) { LINE() } else { print "" } }
'
fi
;;
2) # one line
awk '
function LINE() { printf("%.2d\t%s\n", NR, $0) }
'$2' { LINE(); getline; exit }
'
;;
1) # whole file
awk '
function LINE() { printf("%.2d\t%s\n", NR, $0) }
{ if($0 ~ /./) { LINE() } else { print "" } }
'
;;
*)
echo >&2 usage: prog.sh file.go /func.main/ /^}/
esac <$1 |
sed '
s/&/\&amp;/g
s/"/\&quot;/g
s/</\&lt;/g
s/>/\&gt;/g
'
echo '</pre>'

View File

@@ -6,18 +6,18 @@ package main
import (
"os"
"flag" // command line option parser
"flag" // command line option parser
)
var omitNewline = flag.Bool("n", false, "don't print final newline")
const (
Space = " "
Space = " "
Newline = "\n"
)
func main() {
flag.Parse() // Scans the arg list and sets up flags
flag.Parse() // Scans the arg list and sets up flags
var s string = ""
for i := 0; i < flag.NArg(); i++ {
if i > 0 {

89
doc/progs/file_windows.go Normal file
View File

@@ -0,0 +1,89 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package file
import (
"os"
"syscall"
)
type File struct {
fd syscall.Handle // file descriptor number
name string // file name at Open time
}
func newFile(fd syscall.Handle, name string) *File {
if fd < 0 {
return nil
}
return &File{fd, name}
}
var (
Stdin = newFile(syscall.Stdin, "/dev/stdin")
Stdout = newFile(syscall.Stdout, "/dev/stdout")
Stderr = newFile(syscall.Stderr, "/dev/stderr")
)
func OpenFile(name string, mode int, perm uint32) (file *File, err os.Error) {
r, e := syscall.Open(name, mode, perm)
if e != 0 {
err = os.Errno(e)
}
return newFile(r, name), err
}
const (
O_RDONLY = syscall.O_RDONLY
O_RDWR = syscall.O_RDWR
O_CREATE = syscall.O_CREAT
O_TRUNC = syscall.O_TRUNC
)
func Open(name string) (file *File, err os.Error) {
return OpenFile(name, O_RDONLY, 0)
}
func Create(name string) (file *File, err os.Error) {
return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}
func (file *File) Close() os.Error {
if file == nil {
return os.EINVAL
}
e := syscall.Close(file.fd)
file.fd = syscall.InvalidHandle // so it can't be closed again
if e != 0 {
return os.Errno(e)
}
return nil
}
func (file *File) Read(b []byte) (ret int, err os.Error) {
if file == nil {
return -1, os.EINVAL
}
r, e := syscall.Read(file.fd, b)
if e != 0 {
err = os.Errno(e)
}
return int(r), err
}
func (file *File) Write(b []byte) (ret int, err os.Error) {
if file == nil {
return -1, os.EINVAL
}
r, e := syscall.Write(file.fd, b)
if e != 0 {
err = os.Errno(e)
}
return int(r), err
}
func (file *File) String() string {
return file.name
}

View File

@@ -4,7 +4,7 @@
package main
import fmt "fmt" // Package implementing formatted I/O.
import fmt "fmt" // Package implementing formatted I/O.
func main() {
fmt.Printf("Hello, world; or Καλημέρα κόσμε; or こんにちは 世界\n")

View File

@@ -15,7 +15,7 @@ func main() {
file.Stdout.Write(hello)
f, err := file.Open("/does/not/exist")
if f == nil {
fmt.Printf("can't open file; err=%s\n", err.String())
fmt.Printf("can't open file; err=%s\n", err.String())
os.Exit(1)
}
}

View File

@@ -7,7 +7,7 @@ package main
import "fmt"
func main() {
var u64 uint64 = 1<<64-1
var u64 uint64 = 1<<64 - 1
fmt.Printf("%d %d\n", u64, int64(u64))
// harder stuff

View File

@@ -14,8 +14,13 @@ fi
rm -f *.$O
if [ "$GOOS" = "windows" ];then
$GC -o file.8 file_windows.go
else
$GC file.go
fi
for i in \
file.go \
helloworld.go \
helloworld3.go \
echo.go \

View File

@@ -7,8 +7,8 @@ package main
import "fmt"
type request struct {
a, b int
replyc chan int
a, b int
replyc chan int
}
type binOp func(a, b int) int
@@ -21,7 +21,7 @@ func run(op binOp, req *request) {
func server(op binOp, service chan *request) {
for {
req := <-service
go run(op, req) // don't wait for it
go run(op, req) // don't wait for it
}
}
@@ -42,8 +42,8 @@ func main() {
req.replyc = make(chan int)
adder <- req
}
for i := N-1; i >= 0; i-- { // doesn't matter what order
if <-reqs[i].replyc != N + 2*i {
for i := N - 1; i >= 0; i-- { // doesn't matter what order
if <-reqs[i].replyc != N+2*i {
fmt.Println("fail at", i)
}
}

View File

@@ -7,8 +7,8 @@ package main
import "fmt"
type request struct {
a, b int
replyc chan int
a, b int
replyc chan int
}
type binOp func(a, b int) int
@@ -22,7 +22,7 @@ func server(op binOp, service chan *request, quit chan bool) {
for {
select {
case req := <-service:
go run(op, req) // don't wait for it
go run(op, req) // don't wait for it
case <-quit:
return
}
@@ -47,8 +47,8 @@ func main() {
req.replyc = make(chan int)
adder <- req
}
for i := N-1; i >= 0; i-- { // doesn't matter what order
if <-reqs[i].replyc != N + 2*i {
for i := N - 1; i >= 0; i-- { // doesn't matter what order
if <-reqs[i].replyc != N+2*i {
fmt.Println("fail at", i)
}
}

View File

@@ -9,7 +9,7 @@ import "fmt"
// Send the sequence 2, 3, 4, ... to channel 'ch'.
func generate(ch chan int) {
for i := 2; ; i++ {
ch <- i // Send 'i' to channel 'ch'.
ch <- i // Send 'i' to channel 'ch'.
}
}
@@ -17,17 +17,17 @@ func generate(ch chan int) {
// removing those divisible by 'prime'.
func filter(in, out chan int, prime int) {
for {
i := <-in // Receive value of new variable 'i' from 'in'.
if i % prime != 0 {
out <- i // Send 'i' to channel 'out'.
i := <-in // Receive value of new variable 'i' from 'in'.
if i%prime != 0 {
out <- i // Send 'i' to channel 'out'.
}
}
}
// The prime sieve: Daisy-chain filter processes together.
func main() {
ch := make(chan int) // Create a new channel.
go generate(ch) // Start generate() as a goroutine.
ch := make(chan int) // Create a new channel.
go generate(ch) // Start generate() as a goroutine.
for i := 0; i < 100; i++ { // Print the first hundred primes.
prime := <-ch
fmt.Println(prime)

View File

@@ -9,7 +9,7 @@ import "fmt"
// Send the sequence 2, 3, 4, ... to returned channel
func generate() chan int {
ch := make(chan int)
go func(){
go func() {
for i := 2; ; i++ {
ch <- i
}
@@ -22,7 +22,7 @@ func filter(in chan int, prime int) chan int {
out := make(chan int)
go func() {
for {
if i := <-in; i % prime != 0 {
if i := <-in; i%prime != 0 {
out <- i
}
}

View File

@@ -21,7 +21,7 @@ func Sort(data Interface) {
func IsSorted(data Interface) bool {
n := data.Len()
for i := n - 1; i > 0; i-- {
if data.Less(i, i - 1) {
if data.Less(i, i-1) {
return false
}
}
@@ -30,34 +30,30 @@ func IsSorted(data Interface) bool {
// Convenience types for common cases
type IntArray []int
type IntSlice []int
func (p IntArray) Len() int { return len(p) }
func (p IntArray) Less(i, j int) bool { return p[i] < p[j] }
func (p IntArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p IntSlice) Len() int { return len(p) }
func (p IntSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p IntSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
type Float64Slice []float64
type Float64Array []float64
func (p Float64Slice) Len() int { return len(p) }
func (p Float64Slice) Less(i, j int) bool { return p[i] < p[j] }
func (p Float64Slice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func (p Float64Array) Len() int { return len(p) }
func (p Float64Array) Less(i, j int) bool { return p[i] < p[j] }
func (p Float64Array) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
type StringArray []string
func (p StringArray) Len() int { return len(p) }
func (p StringArray) Less(i, j int) bool { return p[i] < p[j] }
func (p StringArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
type StringSlice []string
func (p StringSlice) Len() int { return len(p) }
func (p StringSlice) Less(i, j int) bool { return p[i] < p[j] }
func (p StringSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
// Convenience wrappers for common cases
func SortInts(a []int) { Sort(IntArray(a)) }
func SortFloat64s(a []float64) { Sort(Float64Array(a)) }
func SortStrings(a []string) { Sort(StringArray(a)) }
func SortInts(a []int) { Sort(IntSlice(a)) }
func SortFloat64s(a []float64) { Sort(Float64Slice(a)) }
func SortStrings(a []string) { Sort(StringSlice(a)) }
func IntsAreSorted(a []int) bool { return IsSorted(IntArray(a)) }
func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Array(a)) }
func StringsAreSorted(a []string) bool { return IsSorted(StringArray(a)) }
func IntsAreSorted(a []int) bool { return IsSorted(IntSlice(a)) }
func Float64sAreSorted(a []float64) bool { return IsSorted(Float64Slice(a)) }
func StringsAreSorted(a []string) bool { return IsSorted(StringSlice(a)) }

View File

@@ -11,7 +11,7 @@ import (
func ints() {
data := []int{74, 59, 238, -784, 9845, 959, 905, 0, 0, 42, 7586, -5467984, 7586}
a := sort.IntArray(data)
a := sort.IntSlice(data)
sort.Sort(a)
if !sort.IsSorted(a) {
panic("fail")
@@ -20,7 +20,7 @@ func ints() {
func strings() {
data := []string{"monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"}
a := sort.StringArray(data)
a := sort.StringSlice(data)
sort.Sort(a)
if !sort.IsSorted(a) {
panic("fail")
@@ -28,27 +28,27 @@ func strings() {
}
type day struct {
num int
shortName string
longName string
num int
shortName string
longName string
}
type dayArray struct {
data []*day
}
func (p *dayArray) Len() int { return len(p.data) }
func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num }
func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] }
func (p *dayArray) Len() int { return len(p.data) }
func (p *dayArray) Less(i, j int) bool { return p.data[i].num < p.data[j].num }
func (p *dayArray) Swap(i, j int) { p.data[i], p.data[j] = p.data[j], p.data[i] }
func days() {
Sunday := day{0, "SUN", "Sunday"}
Monday := day{1, "MON", "Monday"}
Tuesday := day{2, "TUE", "Tuesday"}
Sunday := day{0, "SUN", "Sunday"}
Monday := day{1, "MON", "Monday"}
Tuesday := day{2, "TUE", "Tuesday"}
Wednesday := day{3, "WED", "Wednesday"}
Thursday := day{4, "THU", "Thursday"}
Friday := day{5, "FRI", "Friday"}
Saturday := day{6, "SAT", "Saturday"}
Thursday := day{4, "THU", "Thursday"}
Friday := day{5, "FRI", "Friday"}
Saturday := day{6, "SAT", "Saturday"}
data := []*day{&Tuesday, &Thursday, &Wednesday, &Sunday, &Monday, &Friday, &Saturday}
a := dayArray{data}
sort.Sort(&a)

View File

@@ -8,7 +8,9 @@ import "os"
func main() {
s := "hello"
if s[1] != 'e' { os.Exit(1) }
if s[1] != 'e' {
os.Exit(1)
}
s = "good bye"
var p *string = &s
*p = "ciao"

View File

@@ -14,7 +14,6 @@ func sum(a []int) int { // returns an int
return s
}
func main() {
s := sum([3]int{1, 2, 3}[:]) // a slice of the array is passed to sum
fmt.Print(s, "\n")

View File

@@ -49,10 +49,13 @@ google.setOnLoadCallback(loadFeed);
It's a fast, statically typed, compiled language that feels like a
dynamically typed, interpreted language.
</p>
<h2>Check it out!</h2>
<h2>
Get started now with
<a target="_blank" href="http://go-tour.appspot.com/">A Tour of Go</a>.
</h2>
<p>
<div class="how">[<a href="/doc/playground.html">How does this work?</a>]</div>
<a href="/doc/install.html">Install Go now</a>, or try it right here in your browser:</p>
Or try it right here in your browser:</p>
<div id="playground" class="small"></div>
<script src="/doc/play/playground.js"></script>
</div>

View File

@@ -2,39 +2,84 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This code differs from the slides in that it handles errors.
package main
import (
"crypto/aes"
"crypto/block"
"crypto/cipher"
"compress/gzip"
"io"
"log"
"os"
)
func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) {
r, _ := os.Open(srcfile, os.O_RDONLY, 0)
func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) os.Error {
r, err := os.Open(srcfile)
if err != nil {
return err
}
var w io.Writer
w, _ = os.Open(dstfile, os.O_WRONLY|os.O_CREATE, 0666)
c, _ := aes.NewCipher(key)
w = block.NewOFBWriter(c, iv, w)
w2, _ := gzip.NewDeflater(w)
io.Copy(w2, r)
w2.Close()
w, err = os.Create(dstfile)
if err != nil {
return err
}
c, err := aes.NewCipher(key)
if err != nil {
return err
}
w = cipher.StreamWriter{S: cipher.NewOFB(c, iv), W: w}
w2, err := gzip.NewWriter(w)
if err != nil {
return err
}
defer w2.Close()
_, err = io.Copy(w2, r)
return err
}
func DecryptAndGunzip(dstfile, srcfile string, key, iv []byte) {
f, _ := os.Open(srcfile, os.O_RDONLY, 0)
func DecryptAndGunzip(dstfile, srcfile string, key, iv []byte) os.Error {
f, err := os.Open(srcfile)
if err != nil {
return err
}
defer f.Close()
c, _ := aes.NewCipher(key)
r := block.NewOFBReader(c, iv, f)
r, _ = gzip.NewInflater(r)
w, _ := os.Open(dstfile, os.O_WRONLY|os.O_CREATE, 0666)
c, err := aes.NewCipher(key)
if err != nil {
return err
}
r := cipher.StreamReader{S: cipher.NewOFB(c, iv), R: f}
r2, err := gzip.NewReader(r)
if err != nil {
return err
}
w, err := os.Create(dstfile)
if err != nil {
return err
}
defer w.Close()
io.Copy(w, r)
_, err = io.Copy(w, r2)
return err
}
func main() {
EncryptAndGzip("/tmp/passwd.gz", "/etc/passwd", make([]byte, 16), make([]byte, 16))
DecryptAndGunzip("/dev/stdout", "/tmp/passwd.gz", make([]byte, 16), make([]byte, 16))
err := EncryptAndGzip(
"/tmp/passwd.gz",
"/etc/passwd",
make([]byte, 16),
make([]byte, 16),
)
if err != nil {
log.Fatal(err)
}
err = DecryptAndGunzip(
"/dev/stdout",
"/tmp/passwd.gz",
make([]byte, 16),
make([]byte, 16),
)
if err != nil {
log.Fatal(err)
}
}

View File

@@ -2,27 +2,51 @@
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This code differs from the slides in that it handles errors.
package main
import (
"crypto/aes"
"crypto/block"
"crypto/cipher"
"compress/gzip"
"io"
"log"
"os"
)
func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) {
r, _ := os.Open(srcfile, os.O_RDONLY, 0)
func EncryptAndGzip(dstfile, srcfile string, key, iv []byte) os.Error {
r, err := os.Open(srcfile)
if err != nil {
return err
}
var w io.WriteCloser
w, _ = os.Open(dstfile, os.O_WRONLY|os.O_CREATE, 0666)
w, err = os.Create(dstfile)
if err != nil {
return err
}
defer w.Close()
w, _ = gzip.NewDeflater(w)
w, err = gzip.NewWriter(w)
if err != nil {
return err
}
defer w.Close()
c, _ := aes.NewCipher(key)
io.Copy(block.NewCBCEncrypter(c, iv, w), r)
c, err := aes.NewCipher(key)
if err != nil {
return err
}
_, err = io.Copy(cipher.StreamWriter{S: cipher.NewOFB(c, iv), W: w}, r)
return err
}
func main() {
EncryptAndGzip("/tmp/passwd.gz", "/etc/passwd", make([]byte, 16), make([]byte, 16))
err := EncryptAndGzip(
"/tmp/passwd.gz",
"/etc/passwd",
make([]byte, 16),
make([]byte, 16),
)
if err != nil {
log.Fatal(err)
}
}

176
doc/tmpltohtml.go Normal file
View File

@@ -0,0 +1,176 @@
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// The template uses the function "code" to inject program
// source into the output by extracting code from files and
// injecting them as HTML-escaped <pre> blocks.
//
// The syntax is simple: 1, 2, or 3 space-separated arguments:
//
// Whole file:
// {{code "foo.go"}}
// One line (here the signature of main):
// {{code "foo.go" `/^func.main/`}}
// Block of text, determined by start and end (here the body of main):
// {{code "foo.go" `/^func.main/` `/^}/`
//
// Patterns can be `/regular expression/`, a decimal number, or "$"
// to signify the end of the file.
package main
import (
"exp/template"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
"regexp"
"strings"
)
func Usage() {
fmt.Fprintf(os.Stderr, "usage: tmpltohtml file\n")
os.Exit(2)
}
func main() {
flag.Usage = Usage
flag.Parse()
if len(flag.Args()) != 1 {
Usage()
}
// Read and parse the input.
name := flag.Args()[0]
tmpl := template.New(name).Funcs(template.FuncMap{"code": code})
if _, err := tmpl.ParseFile(name); err != nil {
log.Fatal(err)
}
// Execute the template.
if err := tmpl.Execute(os.Stdout, 0); err != nil {
log.Fatal(err)
}
}
// contents reads a file by name and returns its contents as a string.
func contents(name string) string {
file, err := ioutil.ReadFile(name)
if err != nil {
log.Fatal(err)
}
return string(file)
}
// format returns a textual representation of the arg, formatted according to its nature.
func format(arg interface{}) string {
switch arg := arg.(type) {
case int:
return fmt.Sprintf("%d", arg)
case string:
if len(arg) > 2 && arg[0] == '/' && arg[len(arg)-1] == '/' {
return fmt.Sprintf("%#q", arg)
}
return fmt.Sprintf("%q", arg)
default:
log.Fatalf("unrecognized argument: %v type %T", arg, arg)
}
return ""
}
func code(file string, arg ...interface{}) (string, os.Error) {
text := contents(file)
var command string
switch len(arg) {
case 0:
// text is already whole file.
command = fmt.Sprintf("code %q", file)
case 1:
command = fmt.Sprintf("code %q %s", file, format(arg[0]))
text = oneLine(file, text, arg[0])
case 2:
command = fmt.Sprintf("code %q %s %s", file, format(arg[0]), format(arg[1]))
text = multipleLines(file, text, arg[0], arg[1])
default:
return "", fmt.Errorf("incorrect code invocation: code %q %q", file, arg)
}
// Replace tabs by spaces, which work better in HTML.
text = strings.Replace(text, "\t", " ", -1)
// Escape the program text for HTML.
text = template.HTMLEscapeString(text)
// Include the command as a comment.
text = fmt.Sprintf("<pre><!--{{%s}}\n-->%s</pre>", command, text)
return text, nil
}
// parseArg returns the integer or string value of the argument and tells which it is.
func parseArg(arg interface{}, file string, max int) (ival int, sval string, isInt bool) {
switch n := arg.(type) {
case int:
if n <= 0 || n > max {
log.Fatalf("%q:%d is out of range", file, n)
}
return n, "", true
case string:
return 0, n, false
}
log.Fatalf("unrecognized argument %v type %T", arg, arg)
return
}
// oneLine returns the single line generated by a two-argument code invocation.
func oneLine(file, text string, arg interface{}) string {
lines := strings.SplitAfter(contents(file), "\n")
line, pattern, isInt := parseArg(arg, file, len(lines))
if isInt {
return lines[line-1]
}
return lines[match(file, 0, lines, pattern)-1]
}
// multipleLines returns the text generated by a three-argument code invocation.
func multipleLines(file, text string, arg1, arg2 interface{}) string {
lines := strings.SplitAfter(contents(file), "\n")
line1, pattern1, isInt1 := parseArg(arg1, file, len(lines))
line2, pattern2, isInt2 := parseArg(arg2, file, len(lines))
if !isInt1 {
line1 = match(file, 0, lines, pattern1)
}
if !isInt2 {
line2 = match(file, line1, lines, pattern2)
} else if line2 < line1 {
log.Fatal("lines out of order for %q: %d %d", line1, line2)
}
return strings.Join(lines[line1-1:line2], "")
}
// match identifies the input line that matches the pattern in a code invocation.
// If start>0, match lines starting there rather than at the beginning.
// The return value is 1-indexed.
func match(file string, start int, lines []string, pattern string) int {
// $ matches the end of the file.
if pattern == "$" {
if len(lines) == 0 {
log.Fatal("%q: empty file", file)
}
return len(lines)
}
// /regexp/ matches the line that matches the regexp.
if len(pattern) > 2 && pattern[0] == '/' && pattern[len(pattern)-1] == '/' {
re, err := regexp.Compile(pattern[1 : len(pattern)-1])
if err != nil {
log.Fatal(err)
}
for i := start; i < len(lines); i++ {
if re.MatchString(lines[i]) {
return i + 1
}
}
log.Fatalf("%s: no match for %#q", file, pattern)
}
log.Fatalf("unrecognized pattern: %q", pattern)
return 0
}

View File

@@ -292,16 +292,20 @@ extern char* getgoroot(void);
extern char* getgoversion(void);
#ifdef _WIN32
#ifndef _WIN64
struct timespec {
int tv_sec;
long tv_nsec;
};
#define execv(prog, argv) execv(prog, (const char* const*)(argv))
#define execvp(prog, argv) execvp(prog, (const char**)(argv))
#endif
extern int nanosleep(const struct timespec *rqtp, struct timespec *rmtp);
extern int fork(void);
extern int pread(int fd, void *buf, int n, int off);
extern int pwrite(int fd, void *buf, int n, int off);
#define execv(prog, argv) execv(prog, (const char* const*)(argv))
#define execvp(prog, argv) execvp(prog, (const char**)(argv))
#define lseek(fd, n, base) _lseeki64(fd, n, base)
#define mkdir(path, perm) mkdir(path)
#define pipe(fd) _pipe(fd, 512, O_BINARY)

View File

@@ -69,6 +69,7 @@ extern "C" {
#include <math.h>
#include <ctype.h> /* for tolower */
#include <signal.h>
#include <time.h>
/*
* OS-specific crap
@@ -193,6 +194,8 @@ typedef u64int uint64;
#undef _NEEDUINT
#undef _NEEDULONG
#define getcallerpc(x) __builtin_return_address(0)
#ifndef SIGBUS
#define SIGBUS SIGSEGV /* close enough */
#endif

View File

@@ -75,6 +75,12 @@ except:
def findcommonincoming(repo, remote):
return repo.findcommonincoming(remote)
# in Mercurial 1.9 the cmdutil.match and cmdutil.revpair moved to scmutil
if hgversion >= '1.9':
from mercurial import scmutil
else:
scmutil = cmdutil
oldMessage = """
The code review extension requires Mercurial 1.3 or newer.
@@ -713,14 +719,14 @@ _change_prolog = """# Change list.
# Get effective change nodes taking into account applied MQ patches
def effective_revpair(repo):
try:
return cmdutil.revpair(repo, ['qparent'])
return scmutil.revpair(repo, ['qparent'])
except:
return cmdutil.revpair(repo, None)
return scmutil.revpair(repo, None)
# Return list of changed files in repository that match pats.
# Warn about patterns that did not match.
def matchpats(ui, repo, pats, opts):
matcher = cmdutil.match(repo, pats, opts)
matcher = scmutil.match(repo, pats, opts)
node1, node2 = effective_revpair(repo)
modified, added, removed, deleted, unknown, ignored, clean = repo.status(node1, node2, matcher, ignored=True, clean=True, unknown=True)
return (modified, added, removed, deleted, unknown, ignored, clean)
@@ -827,7 +833,6 @@ Examples:
'''
def promptremove(ui, repo, f):
if promptyesno(ui, "hg remove %s (y/n)?" % (f,)):
@@ -959,6 +964,11 @@ def ReplacementForCmdutilMatch(repo, pats=None, opts=None, globbed=False, defaul
raise util.Abort("no files in CL " + clname)
files = Add(files, cl.files)
pats = Sub(pats, taken) + ['path:'+f for f in files]
# work-around for http://selenic.com/hg/rev/785bbc8634f8
if hgversion >= '1.9' and not hasattr(repo, 'match'):
repo = repo[None]
return original_match(repo, pats=pats, opts=opts, globbed=globbed, default=default)
def RelativePath(path, cwd):
@@ -1292,7 +1302,7 @@ def clpatch_or_undo(ui, repo, clname, opts, mode):
# sequence numbers get to be 7 digits long.
if re.match('^[0-9]{7,}$', clname):
found = False
matchfn = cmdutil.match(repo, [], {'rev': None})
matchfn = scmutil.match(repo, [], {'rev': None})
def prep(ctx, fns):
pass
for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep):
@@ -1316,7 +1326,7 @@ def clpatch_or_undo(ui, repo, clname, opts, mode):
# Create fresh CL and start with patch that would reverse the change.
vers = short(rev.node())
cl = CL("new")
desc = rev.description()
desc = str(rev.description())
if mode == "undo":
cl.desc = (undoHeader % (clname, vers)) + desc + undoFooter
else:
@@ -1352,10 +1362,12 @@ def clpatch_or_undo(ui, repo, clname, opts, mode):
repo[vers].description()
except:
return "local repository is out of date; sync to get %s" % (vers)
patch, err = portPatch(repo, patch, vers, id)
patch1, err = portPatch(repo, patch, vers, id)
if err != "":
return "codereview issue %s is out of date: %s (%s->%s)" % (clname, err, vers, id)
if not opts["ignore_hgpatch_failure"]:
return "codereview issue %s is out of date: %s (%s->%s)" % (clname, err, vers, id)
else:
patch = patch1
argv = ["hgpatch"]
if opts["no_incoming"] or mode == "backport":
argv += ["--checksync=false"]
@@ -1369,7 +1381,7 @@ def clpatch_or_undo(ui, repo, clname, opts, mode):
return "hgpatch failed"
cl.local = True
cl.files = out.strip().split()
if not cl.files:
if not cl.files and not opts["ignore_hgpatch_failure"]:
return "codereview issue %s has no changed files" % clname
files = ChangedFiles(ui, repo, [], opts)
extra = Sub(cl.files, files)
@@ -1605,8 +1617,8 @@ def reposetup(ui, repo):
global original_match
if original_match is None:
start_status_thread()
original_match = cmdutil.match
cmdutil.match = ReplacementForCmdutilMatch
original_match = scmutil.match
scmutil.match = ReplacementForCmdutilMatch
RietveldSetup(ui, repo)
def CheckContributor(ui, repo, user=None):
@@ -1710,6 +1722,7 @@ def submit(ui, repo, *pats, **opts):
print Indent('\n'.join(cl.files), "\t")
return "dry run; not submitted"
set_status("pushing " + cl.name + " to remote server")
m = match.exact(repo.root, repo.getcwd(), cl.files)
node = repo.commit(ustr(opts['message']), ustr(userline), opts.get('date'), m)
if not node:
@@ -1781,7 +1794,7 @@ def sync(ui, repo, **opts):
err = commands.postincoming(ui, repo, modheads, True, "tip")
if err:
return err
commands.update(ui, repo)
commands.update(ui, repo, rev="default")
sync_changes(ui, repo)
def sync_note(msg):
@@ -1826,7 +1839,7 @@ def sync_changes(ui, repo):
break
Rev(rev)
else:
matchfn = cmdutil.match(repo, [], {'rev': None})
matchfn = scmutil.match(repo, [], {'rev': None})
def prep(ctx, fns):
pass
for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep):
@@ -1845,7 +1858,7 @@ def sync_changes(ui, repo):
cl.Flush(ui, repo)
if not cl.files:
if not cl.copied_from:
ui.warn("CL %s has no files; delete with hg change -d %s\n" % (cl.name, cl.name))
ui.warn("CL %s has no files; delete (abandon) with hg change -d %s\n" % (cl.name, cl.name))
else:
ui.warn("CL %s has no files; delete locally with hg change -D %s\n" % (cl.name, cl.name))
return

View File

@@ -18,9 +18,9 @@
<img title="View code in new window" alt="Pop Out Code" src="/doc/codewalk/popout.png" style="display: block; float: right;"/>
</a>
<select id="code-selector">
{.repeated section File}
<option value="/doc/codewalk/?fileprint=/{@|html-esc}">{@|html-esc}</option>
{.end}
{{range .File}}
<option value="/doc/codewalk/?fileprint=/{{urlquery .}}">{{html .}}</option>
{{end}}
</select>
</div>
<div id="code">
@@ -35,19 +35,19 @@
</div>
<div class="right" id="comment-column">
<div id="comment-area">
{.repeated section Step}
{{range .Step}}
<div class="comment first last">
<a class="comment-link" href="/doc/codewalk/?fileprint=/{File|html-esc}&lo={Lo|html-esc}&hi={Hi|html-esc}#mark" target="code-display"></a>
<div class="comment-title">{Title|html-esc}</div>
<a class="comment-link" href="/doc/codewalk/?fileprint=/{{urlquery .File}}&lo={{urlquery .Lo}}&hi={{urlquery .Hi}}#mark" target="code-display"></a>
<div class="comment-title">{{html .Title}}</div>
<div class="comment-text">
{.section Err}
ERROR LOADING FILE: {Err|html-esc}<br/><br/>
{.end}
{XML}
{{with .Err}}
ERROR LOADING FILE: {{html .}}<br/><br/>
{{end}}
{{.XML}}
</div>
<div class="comment-text file-name"><span class="path-file">{@|html-esc}</span></div>
<div class="comment-text file-name"><span class="path-file">{{html .}}</span></div>
</div>
{.end}
{{end}}
</div>
<div id="comment-options" class="setting">
<a id="prev-comment" href="#"><span class="hotkey">p</span>revious step</a>

View File

@@ -5,11 +5,12 @@
-->
<table class="layout">
{.repeated section @}
{{range .}}
<tr>
<td><a href="{Name|html-esc}">{Name|html-esc}</a></td>
<td width="25">&nbsp;</td>
<td>{Title|html-esc}</td>
{{$name_html := html .Name}}
<td><a href="{{$name_html}}">{{$name_html}}</a></td>
<td width="25">&nbsp;</td>
<td>{{html .Title}}</td>
</tr>
{.end}
{{end}}
</table>

View File

@@ -16,14 +16,16 @@
<tr>
<td><a href="..">..</a></td>
</tr>
{.repeated section @}
{{range .}}
<tr>
<td align="left"><a href="{Name|html-esc}{@|dir/}">{Name|html-esc}{@|dir/}</a></td>
{{$name_html := fileInfoName . | html}}
<td align="left"><a href="{{$name_html}}">{{$name_html}}</a></td>
<td></td>
<td align="right">{Size|html-esc}</td>
<td align="right">{{html .Size}}</td>
<td></td>
<td align="left">{Mtime_ns|time}</td>
<td align="left">{{fileInfoTime . | html}}</td>
</tr>
{.end}
{{end}}
</table>
</p>

View File

@@ -5,5 +5,5 @@
-->
<p>
<span class="alert" style="font-size:120%">{@|html-esc}</span>
<span class="alert" style="font-size:120%">{{html .}}</span>
</p>

View File

@@ -2,11 +2,11 @@
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
{.section Title}
<title>{@|html-esc} - The Go Programming Language</title>
{.or}
{{with .Title}}
<title>{{html .}} - The Go Programming Language</title>
{{else}}
<title>The Go Programming Language</title>
{.end}
{{end}}
<link rel="stylesheet" href="/doc/all.css" type="text/css" media="all" charset="utf-8">
<!--[if lt IE 8]>
<link rel="stylesheet" href="/doc/ie.css" type="text/css">
@@ -23,19 +23,17 @@
</ul>
<div class="quickref">
<form method="GET" action="/search">
{.section PkgRoots}
{.repeated section PkgRoots}
<a href="/pkg/{@|html-esc}">{@|html-esc}</a> <span class="sep">|</span>
{.end}
{.or}
{{range .PkgRoots}}
<a href="/pkg/{{html .}}">{{html .}}</a> <span class="sep">|</span>
{{else}}
References:
{.end}
{{end}}
<a href="/pkg/">Packages</a> <span class="sep">|</span>
<a href="/cmd/">Commands</a> <span class="sep">|</span>
<a href="/doc/go_spec.html">Specification</a>
{.section SearchBox}
<input id="search" type="search" name="q" value="{.section Query}{Query|html-esc}{.end}" class="{.section Query}{.or}inactive{.end}" placeholder="code search" results="0" />
{.end}
{{if .SearchBox}}
<input id="search" type="search" name="q" value="{{with .Query}}{{html .}}{{end}}" class="{{if not .Query}}inactive{{end}}" placeholder="code search" results="0" />
{{end}}
</form>
</div>
</div>
@@ -43,28 +41,28 @@
</div>
<div id="content">
<!-- Menu is HTML-escaped elsewhere -->
{.section Menu}
{{with .Menu}}
<div id="menu">
{@}
{{printf "%s" .}}
</div>
{.end}
{{end}}
{.section Title}
<h1 id="generatedHeader">{@|html-esc}</h1>
{.end}
{.section Subtitle}
<span class="subtitle">{@|html-esc}</span>
{.end}
{{with .Title}}
<h1 id="generatedHeader">{{html .}}</h1>
{{end}}
{{with .Subtitle}}
<span class="subtitle">{{html .}}</span>
{{end}}
<!-- The Table of Contents is automatically inserted in this <div>.
Do not delete this <div>. -->
<div id="nav"></div>
<!-- Content is HTML-escaped elsewhere -->
{Content}
{{printf "%s" .Content}}
</div>
<div id="site-info">
<p>Build version {Version|html-esc}. Except as noted, this content is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License</a>.</p>
<p>Build version {{html .Version}}. Except as noted, this content is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 License</a>.</p>
</div>
</div>
</body>

View File

@@ -3,119 +3,120 @@
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
{.section PAst}
<pre>{@ FSet|html-esc}</pre>
{.end}
{.section PDoc}
{{with .PAst}}
<pre>{{node_html . $.FSet}}</pre>
{{end}}
{{with .PDoc}}
<!-- PackageName is printed as title by the top-level template -->
{.section IsPkg}
{# ImportPath is a string - no need for FSet}
<p><code>import "{ImportPath|html-esc}"</code></p>
{.end}
{Doc|html-comment}
{.section IsPkg}
{.section Filenames}
{# Filenames are strings - no need for FSet}
{{if $.IsPkg}}
<p><code>import "{{html .ImportPath}}"</code></p>
{{end}}
{{comment_html .Doc}}
{{if $.IsPkg}}
{{with .Filenames}}
<p>
<h4>Package files</h4>
<span style="font-size:90%">
{.repeated section @}
<a href="/{@|url-src}">{@|localname}</a>
{.end}
{{range .}}
<a href="/{{.|srcLink}}">{{.|filename|html}}</a>
{{end}}
</span>
</p>
{.end}
{.end}
{.section Consts}
{{end}}
{{end}}
{{with .Consts}}
<h2 id="Constants">Constants</h2>
{.repeated section @}
{Doc|html-comment}
<pre>{Decl FSet|html-esc}</pre>
{.end}
{.end}
{.section Vars}
{{range .}}
{{comment_html .Doc}}
<pre>{{node_html .Decl $.FSet}}</pre>
{{end}}
{{end}}
{{with .Vars}}
<h2 id="Variables">Variables</h2>
{.repeated section @}
{Doc|html-comment}
<pre>{Decl FSet|html-esc}</pre>
{.end}
{.end}
{.section Funcs}
{.repeated section @}
{# Name is a string - no need for FSet}
<h2 id="{Name|html-esc}">func <a href="/{Decl FSet|url-pos}">{Name|html-esc}</a></h2>
<p><code>{Decl FSet|html-esc}</code></p>
{Doc|html-comment}
{.end}
{.end}
{.section Types}
{.repeated section @}
<h2 id="{Type.Name FSet|html-esc}">type <a href="/{Decl FSet|url-pos}">{Type.Name FSet|html-esc}</a></h2>
{Doc|html-comment}
<p><pre>{Decl FSet|html-esc}</pre></p>
{.repeated section Consts}
{Doc|html-comment}
<pre>{Decl FSet|html-esc}</pre>
{.end}
{.repeated section Vars}
{Doc|html-comment}
<pre>{Decl FSet|html-esc}</pre>
{.end}
{.repeated section Factories}
<h3 id="{Type.Name FSet|html-esc}.{Name|html-esc}">func <a href="/{Decl FSet|url-pos}">{Name|html-esc}</a></h3>
<p><code>{Decl FSet|html-esc}</code></p>
{Doc|html-comment}
{.end}
{.repeated section Methods}
<h3 id="{Type.Name FSet|html-esc}.{Name|html-esc}">func ({Recv FSet|html-esc}) <a href="/{Decl FSet|url-pos}">{Name|html-esc}</a></h3>
<p><code>{Decl FSet|html-esc}</code></p>
{Doc|html-comment}
{.end}
{.end}
{.end}
{.section Bugs}
{{range .}}
{{comment_html .Doc}}
<pre>{{node_html .Decl $.FSet}}</pre>
{{end}}
{{end}}
{{with .Funcs}}
{{range .}}
{{/* Name is a string - no need for FSet */}}
{{$name_html := html .Name}}
<h2 id="{{$name_html}}">func <a href="/{{posLink_url .Decl $.FSet}}">{{$name_html}}</a></h2>
<p><code>{{node_html .Decl $.FSet}}</code></p>
{{comment_html .Doc}}
{{end}}
{{end}}
{{with .Types}}
{{range .}}
{{$tname_html := node_html .Type.Name $.FSet}}
<h2 id="{{$tname_html}}">type <a href="/{{posLink_url .Decl $.FSet}}">{{$tname_html}}</a></h2>
{{comment_html .Doc}}
<p><pre>{{node_html .Decl $.FSet}}</pre></p>
{{range .Consts}}
{{comment_html .Doc}}
<pre>{{node_html .Decl $.FSet}}</pre>
{{end}}
{{range .Vars}}
{{comment_html .Doc}}
<pre>{{node_html .Decl $.FSet}}</pre>
{{end}}
{{range .Factories}}
{{$name_html := html .Name}}
<h3 id="{{$tname_html}}.{{$name_html}}">func <a href="/{{posLink_url .Decl $.FSet}}">{{$name_html}}</a></h3>
<p><code>{{node_html .Decl $.FSet}}</code></p>
{{comment_html .Doc}}
{{end}}
{{range .Methods}}
{{$name_html := html .Name}}
<h3 id="{{$tname_html}}.{{$name_html}}">func ({{node_html .Recv $.FSet}}) <a href="/{{posLink_url .Decl $.FSet}}">{{$name_html}}</a></h3>
<p><code>{{node_html .Decl $.FSet}}</code></p>
{{comment_html .Doc}}
{{end}}
{{end}}
{{end}}
{{with .Bugs}}
<h2 id="Bugs">Bugs</h2>
{.repeated section @}
{@|html-comment}
{.end}
{.end}
{.end}
{.section PList}
{{range .}}
{{comment_html .}}
{{end}}
{{end}}
{{end}}
{{with .PList}}
<h2>Other packages</h2>
<p>
{# PLIst entries are strings - no need for FSet}
{.repeated section @}
<a href="?p={@|html-esc}">{@|html-esc}</a><br />
{.end}
{{/* PList entries are strings - no need for FSet */}}
{{range .}}
<a href="?p={{urlquery .}}">{{html .}}</a><br />
{{end}}
</p>
{.end}
{.section Dirs}
{{end}}
{{with .Dirs}}
<p class="detail">
Need more packages? The
<a href="http://godashboard.appspot.com/package">Package Dashboard</a>
provides a list of <a href="/cmd/goinstall/">goinstallable</a> packages.
</p>
{# DirList entries are numbers and strings - no need for FSet}
{{/* DirList entries are numbers and strings - no need for FSet */}}
<h2 id="Subdirectories">Subdirectories</h2>
<p>
<table class="layout">
<tr>
<th align="left" colspan="{MaxHeight|html-esc}">Name</th>
<th align="left" colspan="{{html .MaxHeight}}">Name</th>
<td width="25">&nbsp;</td>
<th align="left">Synopsis</th>
</tr>
<tr>
<th align="left"><a href="..">..</a></th>
</tr>
{.repeated section List}
{{range .List}}
<tr>
{Depth|padding}
<td align="left" colspan="{Height|html-esc}"><a href="{Path|html-esc}">{Name|html-esc}</a></td>
{{repeat `<td width="25"></td>` .Depth}}
<td align="left" colspan="{{html .Height}}"><a href="{{html .Path}}">{{html .Name}}</a></td>
<td></td>
<td align="left">{Synopsis|html-esc}</td>
<td align="left">{{html .Synopsis}}</td>
</tr>
{.end}
{{end}}
</table>
</p>
{.end}
{{end}}

View File

@@ -1,95 +1,82 @@
{.section PAst}
{@ FSet}
{.end}
{.section PDoc}
{.section IsPkg}
PACKAGE
{{with .PAst}}{{node . $.FSet}}{{end}}{{/*
package {PackageName}
import "{ImportPath}"
{.or}
COMMAND DOCUMENTATION
{.end}
{.section Doc}
---------------------------------------
{@ FSet}
{.end}
{.section Consts}
*/}}{{with .PDoc}}{{if $.IsPkg}}PACKAGE
package {{.PackageName}}
import "{{.ImportPath}}"
{{else}}COMMAND DOCUMENTATION
{{end}}{{.Doc}}{{/*
---------------------------------------
*/}}{{with .Consts}}
CONSTANTS
{.repeated section @}
{Decl FSet}
{Doc}
{.end}
{.end}
{.section Vars}
{{range .}}{{node .Decl $.FSet}}
{{.Doc}}{{end}}
{{end}}{{/*
---------------------------------------
*/}}{{with .Vars}}
VARIABLES
{.repeated section @}
{Decl FSet}
{Doc}
{.end}
{.end}
{.section Funcs}
{{range .}}{{node .Decl $.FSet}}
{{.Doc}}{{end}}
{{end}}{{/*
---------------------------------------
*/}}{{with .Funcs}}
FUNCTIONS
{.repeated section @}
{Decl FSet}
{Doc}
{.end}
{.end}
{.section Types}
{{range .}}{{node .Decl $.FSet}}
{{.Doc}}
{{end}}{{end}}{{/*
---------------------------------------
*/}}{{with .Types}}
TYPES
{.repeated section @}
{Decl FSet}
{Doc}
{.repeated section Consts}
{Decl FSet}
{Doc}
{.end}
{.repeated section Vars}
{Decl FSet}
{Doc}
{.end}
{.repeated section Factories}
{Decl FSet}
{Doc}
{.end}
{.repeated section Methods}
{Decl FSet}
{Doc}
{.end}
{.end}
{.end}
{.section Bugs}
{{range .}}{{node .Decl $.FSet}}
{{.Doc}}
{{range .Consts}}{{node .Decl $.FSet}}
{{.Doc}}
{{end}}{{range .Vars}}{{node .Decl $.FSet}}
{{.Doc}}
{{end}}{{range .Factories}}{{node .Decl $.FSet}}
{{.Doc}}
{{end}}{{range .Methods}}{{node .Decl $.FSet}}
{{.Doc}}
{{end}}{{end}}{{end}}{{/*
---------------------------------------
*/}}{{with .Bugs}}
BUGS
{.repeated section @}
{@}
{.end}
{.end}
{.end}
{.section PList}
{{range .}}{{.}}
{{end}}{{end}}{{end}}{{/*
---------------------------------------
*/}}{{with .PList}}
OTHER PACKAGES
{.repeated section @}
{@}
{.end}
{.end}
{.section Dirs}
{.section Dirs}
{{range .}}
{{.}}{{end}}
{{end}}{{/*
---------------------------------------
*/}}{{with .Dirs}}
SUBDIRECTORIES
{.repeated section List}
{Name}
{.end}
{.end}
{.end}
{{range .List}}
{{.Name}}{{end}}
{{end}}

View File

@@ -3,93 +3,96 @@
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
-->
{.section Alert}
{{$query_url := urlquery .Query}}
{{with .Alert}}
<p>
<span class="alert" style="font-size:120%">{@}</span>
<span class="alert" style="font-size:120%">{{html .}}</span>
</p>
{.end}
{.section Alt}
{{end}}
{{with .Alt}}
<p>
<span class="alert" style="font-size:120%">Did you mean: </span>
{.repeated section Alts}
<a href="search?q={@|html-esc}" style="font-size:120%">{@|html-esc}</a>
{.end}
{{range .Alts}}
<a href="search?q={{urlquery .}}" style="font-size:120%">{{html .}}</a>
{{end}}
</p>
{.end}
{.section Hit}
{.section Decls}
{{end}}
{{with .Hit}}
{{with .Decls}}
<h2 id="Global">Package-level declarations</h2>
{.repeated section @}
<h3 id="Global_{Pak.Path|url-pkg}">package <a href="/{Pak.Path|url-pkg}">{Pak.Name|html-esc}</a></h3>
{.repeated section Files}
{.repeated section Groups}
{.repeated section Infos}
<a href="/{File.Path|url-src}?h={Query|urlquery-esc}#L{@|infoLine}">{File.Path|url-src}:{@|infoLine}</a>
{@|infoSnippet}
{.end}
{.end}
{.end}
{.end}
{.end}
{.section Others}
{{range .}}
{{$pkg_html := pkgLink .Pak.Path | html}}
<h3 id="Global_{{$pkg_html}}">package <a href="/{{$pkg_html}}">{{html .Pak.Name}}</a></h3>
{{range .Files}}
{{$src_html := srcLink .File.Path | html}}
{{range .Groups}}
{{range .Infos}}
<a href="/{{$src_html}}?h={{$query_url}}#L{{infoLine .}}">{{$src_html}}:{{infoLine .}}</a>
{{infoSnippet_html .}}
{{end}}
{{end}}
{{end}}
{{end}}
{{end}}
{{with .Others}}
<h2 id="Local">Local declarations and uses</h2>
{.repeated section @}
<h3 id="Local_{Pak.Path|url-pkg}">package <a href="/{Pak.Path|url-pkg}">{Pak.Name|html-esc}</a></h3>
{.repeated section Files}
<a href="/{File.Path|url-src}?h={Query|urlquery-esc}">{File.Path|url-src}</a>
{{range .}}
{{$pkg_html := pkgLink .Pak.Path | html}}
<h3 id="Local_{{$pkg_html}}">package <a href="/{{$pkg_html}}">{{html .Pak.Name}}</a></h3>
{{range .Files}}
{{$src_html := srcLink .File.Path | html}}
<a href="/{{$src_html}}?h={{$query_url}}">{{$src_html}}</a>
<table class="layout">
{.repeated section Groups}
{{range .Groups}}
<tr>
<td width="25"></td>
<th align="left" valign="top">{Kind|infoKind}</th>
<th align="left" valign="top">{{infoKind_html .Kind}}</th>
<td align="left" width="4"></td>
<td>
{.repeated section Infos}
<a href="/{File.Path|url-src}?h={Query|urlquery-esc}#L{@|infoLine}">{@|infoLine}</a>
{.end}
{{range .Infos}}
<a href="/{{$src_html}}?h={{$query_url}}#L{{infoLine .}}">{{infoLine .}}</a>
{{end}}
</td>
</tr>
{.end}
{{end}}
</table>
{.end}
{.end}
{.end}
{.end}
{.section Textual}
{.section Complete}
<h2 id="Textual">{Found|html-esc} textual occurrences</h2>
{.or}
<h2 id="Textual">More than {Found|html-esc} textual occurrences</h2>
{{end}}
{{end}}
{{end}}
{{end}}
{{with .Textual}}
{{if $.Complete}}
<h2 id="Textual">{{html $.Found}} textual occurrences</h2>
{{else}}
<h2 id="Textual">More than {{html $.Found}} textual occurrences</h2>
<p>
<span class="alert" style="font-size:120%">Not all files or lines containing "{Query|html-esc}" are shown.</span>
<span class="alert" style="font-size:120%">Not all files or lines containing "{{html $.Query}}" are shown.</span>
</p>
{.end}
{{end}}
<p>
<table class="layout">
{.repeated section @}
{{range .}}
{{$src_html := srcLink .Filename | html}}
<tr>
<td align="left" valign="top">
<a href="/{Filename|url-src}?h={Query|urlquery-esc}">{Filename|url-src}</a>:
<a href="/{{$src_html}}?h={{$query_url}}">{{$src_html}}</a>:
</td>
<td align="left" width="4"></td>
<th align="left" valign="top">{Lines|numlines}</th>
<th align="left" valign="top">{{len .Lines}}</th>
<td align="left" width="4"></td>
<td align="left">
{.repeated section Lines}
<a href="/{Filename|url-src}?h={Query|urlquery-esc}#L{@|html-esc}">{@|html-esc}</a>
{.end}
{.section Complete}
{.or}
{{range .Lines}}
<a href="/{{$src_html}}?h={{$query_url}}#L{{html .}}">{{html .}}</a>
{{end}}
{{if not $.Complete}}
...
{.end}
{{end}}
</td>
</tr>
{.end}
{.section Complete}
{.or}
{{end}}
{{if not $.Complete}}
<tr><td align="left">...</td></tr>
{.end}
{{end}}
</table>
</p>
{.end}
{{end}}

View File

@@ -1,61 +1,40 @@
QUERY
{Query}
{{.Query}}
{{with .Alert}}
{{.}}
{{end}}{{/* .Alert */}}{{/*
{.section Alert}
{@}
---------------------------------------
{.end}
{.section Alt}
*/}}{{with .Alt}}
DID YOU MEAN
{.repeated section Alts}
{@}
{.end}
{{range .Alts}} {{.}}
{{end}}{{end}}{{/* .Alts */}}{{/*
{.end}
{.section Hit}
{.section Decls}
---------------------------------------
*/}}{{with .Hit}}{{with .Decls}}
PACKAGE-LEVEL DECLARATIONS
{.repeated section @}
package {Pak.Name}
{.repeated section Files}
{.repeated section Groups}
{.repeated section Infos}
{File.Path|url-src}:{@|infoLine}
{.end}
{.end}
{.end}
{{range .}}package {{.Pak.Name}}
{{range $file := .Files}}{{range .Groups}}{{range .Infos}} {{srcLink $file.File.Path}}:{{infoLine .}}{{end}}
{{end}}{{end}}{{/* .Files */}}
{{end}}{{end}}{{/* .Decls */}}{{/*
{.end}
{.end}
{.section Others}
---------------------------------------
*/}}{{with .Others}}
LOCAL DECLARATIONS AND USES
{.repeated section @}
package {Pak.Name}
{.repeated section Files}
{.repeated section Groups}
{.repeated section Infos}
{File.Path|url-src}:{@|infoLine}
{.end}
{.end}
{.end}
{{range .}}package {{.Pak.Name}}
{{range $file := .Files}}{{range .Groups}}{{range .Infos}} {{srcLink $file.File.Path}}:{{infoLine .}}
{{end}}{{end}}{{end}}{{/* .Files */}}
{{end}}{{end}}{{/* .Others */}}{{end}}{{/* .Hit */}}{{/*
{.end}
{.end}
{.end}
{.section Textual}
{.section Complete}
{Found} TEXTUAL OCCURRENCES
{.or}
MORE THAN {Found} TEXTUAL OCCURRENCES
{.end}
---------------------------------------
{.repeated section @}
{Lines|numlines} {Filename|url-src}
{.end}
{.section Complete}
{.or}
... ...
{.end}
{.end}
*/}}{{if .Textual}}{{if .Complete}}{{.Found}} TEXTUAL OCCURRENCES{{else}}MORE THAN {{.Found}} TEXTUAL OCCURRENCES{{end}}
{{range .Textual}}{{len .Lines}} {{srcLink .Filename}}
{{end}}{{if not .Complete}}... ...
{{end}}{{end}}

View File

@@ -211,7 +211,6 @@ func (z *Int) destroy() {
z.init = false
}
/*
* arithmetic
*/
@@ -266,7 +265,7 @@ func (z *Int) Mod(x, y *Int) *Int {
func (z *Int) Lsh(x *Int, s uint) *Int {
x.doinit()
z.doinit()
C.mpz_mul_2exp(&z.i[0], &x.i[0], C.ulong(s))
C.mpz_mul_2exp(&z.i[0], &x.i[0], C.mp_bitcnt_t(s))
return z
}
@@ -274,7 +273,7 @@ func (z *Int) Lsh(x *Int, s uint) *Int {
func (z *Int) Rsh(x *Int, s uint) *Int {
x.doinit()
z.doinit()
C.mpz_div_2exp(&z.i[0], &x.i[0], C.ulong(s))
C.mpz_div_2exp(&z.i[0], &x.i[0], C.mp_bitcnt_t(s))
return z
}
@@ -300,7 +299,6 @@ func (z *Int) Int64() int64 {
return int64(C.mpz_get_si(&z.i[0]))
}
// Neg sets z = -x and returns z.
func (z *Int) Neg(x *Int) *Int {
x.doinit()
@@ -317,7 +315,6 @@ func (z *Int) Abs(x *Int) *Int {
return z
}
/*
* functions without a clear receiver
*/

View File

@@ -42,3 +42,4 @@ func (f *File) Flush() {
}
var Greeting = C.GoString(C.greeting)
var Gbytes = C.GoBytes(unsafe.Pointer(C.greeting), C.int(len(Greeting)))

View File

@@ -11,9 +11,11 @@ CGOFILES=\
basic.go\
callback.go\
env.go\
exports.go\
issue1222.go\
issue1328.go\
issue1560.go\
duplicate_symbol.go\
CGO_OFILES=\
callback_c.o\

View File

@@ -0,0 +1,21 @@
// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// This file contains test cases for cgo.
package cgotest
/*
int base_symbol = 0;
#define alias_one base_symbol
#define alias_two base_symbol
*/
import "C"
import "fmt"
func duplicateSymbols() {
fmt.Printf("%v %v %v\n", C.base_symbol, C.alias_one, C.alias_two)
}

12
misc/cgo/test/exports.go Normal file
View File

@@ -0,0 +1,12 @@
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package cgotest
import "C"
//export ReturnIntLong
func ReturnIntLong() (int, C.long) {
return 1, 2
}

View File

@@ -12,6 +12,7 @@ import (
"log"
"os"
"strconv"
"url"
)
type param map[string]string
@@ -26,7 +27,7 @@ func dash(meth, cmd string, resp interface{}, args param) os.Error {
log.Println("dash", cmd, args)
}
cmd = "http://" + *dashboard + "/" + cmd
vals := make(http.Values)
vals := make(url.Values)
for k, v := range args {
vals.Add(k, v)
}
@@ -112,16 +113,15 @@ func packages() (pkgs []string, err os.Error) {
return
}
// updatePackage sends package build results and info to the dashboard
func (b *Builder) updatePackage(pkg string, state bool, buildLog, info string, hash string) os.Error {
// updatePackage sends package build results and info dashboard
func (b *Builder) updatePackage(pkg string, ok bool, buildLog, info string) os.Error {
return dash("POST", "package", nil, param{
"builder": b.name,
"key": b.key,
"path": pkg,
"state": strconv.Btoa(state),
"ok": strconv.Btoa(ok),
"log": buildLog,
"info": info,
"go_rev": hash[:12],
})
}

View File

@@ -60,8 +60,9 @@ var (
)
var (
goroot string
releaseRegexp = regexp.MustCompile(`^(release|weekly)\.[0-9\-.]+`)
goroot string
binaryTagRe = regexp.MustCompile(`^(release\.r|weekly\.)[0-9\-.]+`)
releaseRe = regexp.MustCompile(`^release\.r[0-9\-.]+`)
)
func main() {
@@ -161,7 +162,7 @@ func NewBuilder(builder string) (*Builder, os.Error) {
b := &Builder{name: builder}
// get goos/goarch from builder string
s := strings.Split(builder, "-", 3)
s := strings.SplitN(builder, "-", 3)
if len(s) >= 2 {
b.goos, b.goarch = s[0], s[1]
} else {
@@ -177,7 +178,7 @@ func NewBuilder(builder string) (*Builder, os.Error) {
if err != nil {
return nil, fmt.Errorf("readKeys %s (%s): %s", b.name, fn, err)
}
v := strings.Split(string(c), "\n", -1)
v := strings.Split(string(c), "\n")
b.key = v[0]
if len(v) >= 3 {
b.codeUsername, b.codePassword = v[1], v[2]
@@ -200,7 +201,7 @@ func (b *Builder) buildExternal() {
log.Println("hg pull failed:", err)
continue
}
hash, tag, err := firstTag(releaseRegexp)
hash, tag, err := firstTag(releaseRe)
if err != nil {
log.Println(err)
continue
@@ -321,7 +322,7 @@ func (b *Builder) buildHash(hash string) (err os.Error) {
}
// if this is a release, create tgz and upload to google code
releaseHash, release, err := firstTag(releaseRegexp)
releaseHash, release, err := firstTag(binaryTagRe)
if hash == releaseHash {
// clean out build state
err = run(b.envv(), srcDir, "./clean.bash", "--nopkg")
@@ -357,7 +358,10 @@ func (b *Builder) envv() []string {
"GOROOT_FINAL=/usr/local/go",
}
for _, k := range extraEnv {
e = append(e, k+"="+os.Getenv(k))
s, err := os.Getenverror(k)
if err == nil {
e = append(e, k+"="+s)
}
}
return e
}
@@ -368,9 +372,14 @@ func (b *Builder) envvWindows() []string {
"GOOS": b.goos,
"GOARCH": b.goarch,
"GOROOT_FINAL": "/c/go",
// TODO(brainman): remove once we find make that does not hang.
"MAKEFLAGS": "-j1",
}
for _, name := range extraEnv {
start[name] = os.Getenv(name)
s, err := os.Getenverror(name)
if err == nil {
start[name] = s
}
}
skip := map[string]bool{
"GOBIN": true,
@@ -384,7 +393,7 @@ func (b *Builder) envvWindows() []string {
skip[name] = true
}
for _, kv := range os.Environ() {
s := strings.Split(kv, "=", 2)
s := strings.SplitN(kv, "=", 2)
name := strings.ToUpper(s[0])
switch {
case name == "":
@@ -583,7 +592,7 @@ func fullHash(rev string) (hash string, err os.Error) {
if s == "" {
return "", fmt.Errorf("cannot find revision")
}
if len(s) != 20 {
if len(s) != 40 {
return "", fmt.Errorf("hg returned invalid hash " + s)
}
return s, nil
@@ -594,7 +603,7 @@ var revisionRe = regexp.MustCompile(`^([^ ]+) +[0-9]+:([0-9a-f]+)$`)
// firstTag returns the hash and tag of the most recent tag matching re.
func firstTag(re *regexp.Regexp) (hash string, tag string, err os.Error) {
o, _, err := runLog(nil, "", goroot, "hg", "tags")
for _, l := range strings.Split(o, "\n", -1) {
for _, l := range strings.Split(o, "\n") {
if l == "" {
continue
}
@@ -607,7 +616,7 @@ func firstTag(re *regexp.Regexp) (hash string, tag string, err os.Error) {
continue
}
tag = s[1]
hash, err = fullHash(s[3])
hash, err = fullHash(s[2])
return
}
err = os.NewError("no matching tag found")

View File

@@ -10,35 +10,47 @@ import (
"go/token"
"log"
"os"
"path"
"path/filepath"
"strings"
)
const MaxCommentLength = 500 // App Engine won't store more in a StringProperty.
func (b *Builder) buildPackages(workpath string, hash string) os.Error {
pkgs, err := packages()
if err != nil {
return err
}
for _, p := range pkgs {
goroot := path.Join(workpath, "go")
goinstall := path.Join(goroot, "bin", "goinstall")
goroot := filepath.Join(workpath, "go")
gobin := filepath.Join(goroot, "bin")
goinstall := filepath.Join(gobin, "goinstall")
envv := append(b.envv(), "GOROOT="+goroot)
// add GOBIN to path
for i, v := range envv {
if strings.HasPrefix(v, "PATH=") {
p := filepath.SplitList(v[5:])
p = append([]string{gobin}, p...)
s := strings.Join(p, string(filepath.ListSeparator))
envv[i] = "PATH=" + s
}
}
// goinstall
buildLog, code, err := runLog(envv, "", goroot, goinstall, p)
buildLog, code, err := runLog(envv, "", goroot, goinstall, "-dashboard=false", p)
if err != nil {
log.Printf("goinstall %v: %v", p, err)
continue
}
built := code != 0
// get doc comment from package source
info, err := packageComment(p, path.Join(goroot, "pkg", p))
info, err := packageComment(p, filepath.Join(goroot, "src", "pkg", p))
if err != nil {
log.Printf("goinstall %v: %v", p, err)
log.Printf("packageComment %v: %v", p, err)
}
// update dashboard with build state + info
err = b.updatePackage(p, built, buildLog, info, hash)
err = b.updatePackage(p, code == 0, buildLog, info)
if err != nil {
log.Printf("updatePackage %v: %v", p, err)
}
@@ -46,9 +58,15 @@ func (b *Builder) buildPackages(workpath string, hash string) os.Error {
return nil
}
func isGoFile(fi *os.FileInfo) bool {
return fi.IsRegular() && // exclude directories
!strings.HasPrefix(fi.Name, ".") && // ignore .files
filepath.Ext(fi.Name) == ".go"
}
func packageComment(pkg, pkgpath string) (info string, err os.Error) {
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, pkgpath, nil, parser.PackageClauseOnly|parser.ParseComments)
pkgs, err := parser.ParseDir(fset, pkgpath, isGoFile, parser.PackageClauseOnly|parser.ParseComments)
if err != nil {
return
}
@@ -62,5 +80,15 @@ func packageComment(pkg, pkgpath string) (info string, err os.Error) {
pdoc := doc.NewPackageDoc(pkgs[name], pkg)
info = pdoc.Doc
}
// grab only first paragraph
if parts := strings.SplitN(info, "\n\n", 2); len(parts) > 1 {
info = parts[0]
}
// replace newlines with spaces
info = strings.Replace(info, "\n", " ", -1)
// truncate
if len(info) > MaxCommentLength {
info = info[:MaxCommentLength]
}
return
}

View File

@@ -11,9 +11,13 @@ handlers:
- url: /static
static_dir: static
- url: /package.*
- url: /package
script: package.py
- url: /package/daily
script: package.py
login: admin
- url: /project.*
script: package.py

View File

@@ -0,0 +1,13 @@
# Copyright 2011 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import hmac
# local imports
import key
def auth(req):
k = req.get('key')
return k == hmac.new(key.accessKey, req.get('builder')).hexdigest() or k == key.accessKey

View File

@@ -0,0 +1,4 @@
cron:
- description: daily package maintenance
url: /package/daily
schedule: every 24 hours

View File

@@ -14,14 +14,13 @@ from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
import datetime
import hashlib
import hmac
import logging
import os
import re
import bz2
# local imports
import key
from auth import auth
import const
# The majority of our state are commit objects. One of these exists for each of
@@ -142,10 +141,6 @@ class DashboardHandler(webapp.RequestHandler):
simplejson.dump(obj, self.response.out)
return
def auth(req):
k = req.get('key')
return k == hmac.new(key.accessKey, req.get('builder')).hexdigest() or k == key.accessKey
# Todo serves /todo. It tells the builder which commits need to be built.
class Todo(DashboardHandler):
def get(self):

View File

@@ -49,4 +49,3 @@ indexes:
# manually, move them above the marker line. The index.yaml file is
# automatically uploaded to the admin console when you next deploy
# your application using appcfg.py.

View File

@@ -19,37 +19,57 @@
Packages listed on this page are written by third parties and
may or may not build or be safe to use.
</p>
<p>
An "ok" in the <b>build</b> column indicates that the package is
<a href="http://golang.org/cmd/goinstall/">goinstallable</a>
with the latest
<a href="http://golang.org/doc/devel/release.html">release</a> of Go.
</p>
<p>
The <b>info</b> column shows the first paragraph from the
<a href="http://blog.golang.org/2011/03/godoc-documenting-go-code.html">package doc comment</a>.
</p>
<h2>Most Installed Packages (this week)</h2>
<table class="alternate" cellpadding="0" cellspacing="0">
<tr><th>last install</th><th>count</th><th>build</th><th>path</th><th>info</th></tr>
{% for r in by_week_count %}
<tr>
<td class="time">{{r.last_install|date:"Y-M-d H:i"}}</td>
<td class="count">{{r.week_count}}</td>
<td class="ok">{% if r.ok %}<a title="{{r.last_ok|date:"Y-M-d H:i"}}">ok</a>{% else %}&nbsp;{% endif %}</td>
<td class="path"><a href="{{r.web_url}}">{{r.path}}</a></td>
<td class="info">{% if r.info %}{{r.info|escape}}{% endif %}</td>
</tr>
{% endfor %}
</table>
<h2>Recently Installed Packages</h2>
<table class="alternate" cellpadding="0" cellspacing="0">
<tr><th>last install</th><th>count</th><th>path</th><th>project</th></tr>
<tr><th>last install</th><th>count</th><th>build</th><th>path</th><th>info</th></tr>
{% for r in by_time %}
<tr>
<td class="time">{{r.last_install|date:"Y-M-d H:i"}}</td>
<td class="count">{{r.count}}</td>
<td class="ok">{% if r.ok %}<a title="{{r.last_ok|date:"Y-M-d H:i"}}">ok</a>{% else %}&nbsp;{% endif %}</td>
<td class="path"><a href="{{r.web_url}}">{{r.path}}</a></td>
<td class="project">
{% for p in r.project_set %}
<a href="{{p.web_url}}">{{p.name}}</a> - {{p.descr}}
{% endfor %}
</td>
<td class="info">{% if r.info %}{{r.info|escape}}{% endif %}</td>
</tr>
{% endfor %}
</table>
<h2>Most Installed Packages</h2>
<h2>Most Installed Packages (all time)</h2>
<table class="alternate" cellpadding="0" cellspacing="0">
<tr><th>last install</th><th>count</th><th>path</th><th>project</th></tr>
<tr><th>last install</th><th>count</th><th>build</th><th>path</th><th>info</th></tr>
{% for r in by_count %}
<tr>
<td class="time">{{r.last_install|date:"Y-M-d H:i"}}</td>
<td class="count">{{r.count}}</td>
<td class="ok">{% if r.ok %}<a title="{{r.last_ok|date:"Y-M-d H:i"}}">ok</a>{% else %}&nbsp;{% endif %}</td>
<td class="path"><a href="{{r.web_url}}">{{r.path}}</a></td>
<td class="project">
{% for p in r.project_set %}
<a href="{{p.web_url}}">{{p.name}}</a> - {{p.descr}}
{% endfor %}
</td>
<td class="info">{% if r.info %}{{r.info|escape}}{% endif %}</td>
</tr>
{% endfor %}
</table>

View File

@@ -5,35 +5,104 @@
# This is the server part of the package dashboard.
# It must be run by App Engine.
from google.appengine.api import mail
from google.appengine.api import memcache
from google.appengine.api import taskqueue
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.api import urlfetch
import datetime
import logging
import os
import re
import urllib2
import sets
import urllib2
# local imports
from auth import auth
import toutf8
import const
template.register_template_library('toutf8')
# Storage model for package info recorded on server.
# Just path, count, and time of last install.
class Package(db.Model):
path = db.StringProperty()
web_url = db.StringProperty() # derived from path
count = db.IntegerProperty()
web_url = db.StringProperty() # derived from path
count = db.IntegerProperty() # grand total
week_count = db.IntegerProperty() # rolling weekly count
day_count = db.TextProperty(default='') # daily count
last_install = db.DateTimeProperty()
# data contributed by gobuilder
info = db.StringProperty()
ok = db.BooleanProperty()
last_ok = db.DateTimeProperty()
def get_day_count(self):
counts = {}
if not self.day_count:
return counts
for d in str(self.day_count).split('\n'):
date, count = d.split(' ')
counts[date] = int(count)
return counts
def set_day_count(self, count):
days = []
for day, count in count.items():
days.append('%s %d' % (day, count))
days.sort(reverse=True)
days = days[:28]
self.day_count = '\n'.join(days)
def inc(self):
count = self.get_day_count()
today = str(datetime.date.today())
count[today] = count.get(today, 0) + 1
self.set_day_count(count)
self.update_week_count(count)
self.count += 1
def update_week_count(self, count=None):
if count is None:
count = self.get_day_count()
total = 0
today = datetime.date.today()
for i in range(7):
day = str(today - datetime.timedelta(days=i))
if day in count:
total += count[day]
self.week_count = total
# PackageDaily kicks off the daily package maintenance cron job
# and serves the associated task queue.
class PackageDaily(webapp.RequestHandler):
def get(self):
# queue a task to update each package with a week_count > 0
keys = Package.all(keys_only=True).filter('week_count >', 0)
for key in keys:
taskqueue.add(url='/package/daily', params={'key': key.name()})
def post(self):
# update a single package (in a task queue)
def update(key):
p = Package.get_by_key_name(key)
if not p:
return
p.update_week_count()
p.put()
key = self.request.get('key')
if not key:
return
db.run_in_transaction(update, key)
class Project(db.Model):
name = db.StringProperty(indexed=True)
descr = db.StringProperty()
@@ -43,23 +112,26 @@ class Project(db.Model):
tags = db.ListProperty(str)
approved = db.BooleanProperty(indexed=True)
re_bitbucket = re.compile(r'^bitbucket\.org/[a-z0-9A-Z_.\-]+/[a-z0-9A-Z_.\-]+$')
re_googlecode = re.compile(r'^[a-z0-9\-]+\.googlecode\.com/(svn|hg)$')
re_github = re.compile(r'^github\.com/[a-z0-9A-Z_.\-]+/[a-z0-9A-Z_.\-]+$')
re_launchpad = re.compile(r'^launchpad\.net/([a-z0-9A-Z_.\-]+(/[a-z0-9A-Z_.\-]+)?|~[a-z0-9A-Z_.\-]+/(\+junk|[a-z0-9A-Z_.\-]+)/[a-z0-9A-Z_.\-]+)(/[a-z0-9A-Z_.\-/]+)?$')
re_bitbucket = re.compile(r'^(bitbucket\.org/[a-z0-9A-Z_.\-]+/[a-zA-Z0-9_.\-]+)(/[a-z0-9A-Z_.\-/]+)?$')
re_googlecode = re.compile(r'^[a-z0-9\-]+\.googlecode\.com/(svn|hg|git)(/[a-z0-9A-Z_.\-/]+)?$')
re_github = re.compile(r'^github\.com/[a-z0-9A-Z_.\-]+(/[a-z0-9A-Z_.\-]+)+$')
re_launchpad = re.compile(r'^launchpad\.net/([a-z0-9A-Z_.\-]+(/[a-z0-9A-Z_.\-]+)?|~[a-z0-9A-Z_.\-]+/(\+junk|[a-z0-9A-Z_.\-]+)/[a-z0-9A-Z_.\-]+)(/[a-z0-9A-Z_.\-/]+)?$')
def vc_to_web(path):
if re_bitbucket.match(path):
check_url = 'http://' + path + '/?cmd=heads'
web = 'http://' + path + '/'
m = re_bitbucket.match(path)
check_url = 'http://' + m.group(1) + '/?cmd=heads'
web = 'http://' + m.group(1) + '/'
elif re_github.match(path):
# github doesn't let you fetch the .git directory anymore.
# fetch .git/info/refs instead, like git clone would.
check_url = 'http://'+path+'.git/info/refs'
web = 'http://' + path
m = re_github_web.match(path)
check_url = 'https://raw.github.com/' + m.group(1) + '/' + m.group(2) + '/master/'
web = 'http://github.com/' + m.group(1) + '/' + m.group(2) + '/'
elif re_googlecode.match(path):
m = re_googlecode.match(path)
check_url = 'http://'+path
if not m.group(2): # append / after bare '/hg' or '/git'
check_url += '/'
web = 'http://code.google.com/p/' + path[:path.index('.')]
elif re_launchpad.match(path):
check_url = web = 'https://'+path
@@ -73,6 +145,17 @@ re_github_web = re.compile(r'github\.com/([a-z0-9A-Z_.\-]+)/([a-z0-9A-Z_.\-]+)')
re_launchpad_web = re.compile(r'launchpad\.net/([a-z0-9A-Z_.\-]+(/[a-z0-9A-Z_.\-]+)?|~[a-z0-9A-Z_.\-]+/(\+junk|[a-z0-9A-Z_.\-]+)/[a-z0-9A-Z_.\-]+)(/[a-z0-9A-Z_.\-/]+)?')
re_striphttp = re.compile(r'https?://(www\.)?')
def find_googlecode_vcs(path):
# Perform http request to path/hg or path/git to check if they're
# using mercurial or git. Otherwise, assume svn.
for vcs in ['git', 'hg']:
try:
response = urlfetch.fetch('http://'+path+vcs, deadline=1)
if response.status_code == 200:
return vcs
except: pass
return 'svn'
def web_to_vc(url):
url = re_striphttp.sub('', url)
m = re_bitbucket_web.match(url)
@@ -84,13 +167,7 @@ def web_to_vc(url):
m = re_googlecode_web.match(url)
if m:
path = m.group(1)+'.googlecode.com/'
# perform http request to path/hg to check if they're using mercurial
vcs = 'svn'
try:
response = urlfetch.fetch('http://'+path+'hg', deadline=1)
if response.status_code == 200:
vcs = 'hg'
except: pass
vcs = find_googlecode_vcs(path)
return path + vcs
m = re_launchpad_web.match(url)
if m:
@@ -107,29 +184,30 @@ class PackagePage(webapp.RequestHandler):
html = memcache.get('view-package')
if not html:
tdata = {}
q = Package.all().filter('week_count >', 0)
q.order('-week_count')
tdata['by_week_count'] = q.fetch(50)
q = Package.all()
q.order('-last_install')
by_time = q.fetch(100)
tdata['by_time'] = q.fetch(20)
q = Package.all()
q.order('-count')
by_count = q.fetch(100)
tdata['by_count'] = q.fetch(100)
self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
path = os.path.join(os.path.dirname(__file__), 'package.html')
html = template.render(
path,
{"by_time": by_time, "by_count": by_count}
)
html = template.render(path, tdata)
memcache.set('view-package', html, time=CacheTimeout)
self.response.headers['Content-Type'] = 'text/html; charset=utf-8'
self.response.out.write(html)
def json(self):
json = memcache.get('view-package-json')
if not json:
self.response.set_status(200)
self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'
q = Package.all()
s = '{"packages": ['
sep = ''
@@ -139,12 +217,13 @@ class PackagePage(webapp.RequestHandler):
s += '\n]}\n'
json = s
memcache.set('view-package-json', json, time=CacheTimeout)
self.response.set_status(200)
self.response.headers['Content-Type'] = 'text/plain; charset=utf-8'
self.response.out.write(json)
def can_get_url(self, url):
try:
req = urllib2.Request(url)
response = urllib2.urlopen(req)
urllib2.urlopen(urllib2.Request(url))
return True
except:
return False
@@ -174,15 +253,24 @@ class PackagePage(webapp.RequestHandler):
return False
p = Package(key_name = key, path = path, count = 0, web_url = web)
if auth(self.request):
# builder updating package metadata
p.info = self.request.get('info')
p.ok = self.request.get('ok') == "true"
if p.ok:
p.last_ok = datetime.datetime.utcnow()
else:
# goinstall reporting an install
p.inc()
p.last_install = datetime.datetime.utcnow()
# update package object
p.count += 1
p.last_install = datetime.datetime.utcnow()
p.put()
return True
def post(self):
path = self.request.get('path')
ok = self.record_pkg(path)
ok = db.run_in_transaction(self.record_pkg, path)
if ok:
self.response.set_status(200)
self.response.out.write('ok')
@@ -332,6 +420,7 @@ class ProjectPage(webapp.RequestHandler):
def main():
app = webapp.WSGIApplication([
('/package', PackagePage),
('/package/daily', PackageDaily),
('/project.*', ProjectPage),
], debug=True)
run_wsgi_app(app)

View File

@@ -52,7 +52,10 @@ table.alternate tr td:last-child {
padding-right: 0;
}
table.alternate tr:nth-child(2n) {
background-color: #f8f8f8;
background-color: #f0f0f0;
}
td.result {
text-align: center;
}
span.hash {
font-family: monospace;
@@ -62,10 +65,19 @@ span.hash {
td.date {
color: #aaa;
}
td.result {
td.ok {
text-align: center;
color: #060;
font-weight: bold;
}
td.ok a {
cursor: help;
}
th {
text-align: left;
}
th.builder {
text-align: center;
font-weight: bold;
}
a.fail {

View File

@@ -69,8 +69,8 @@
some syntax analysis.")
(defvar go-mode-font-lock-keywords
(let ((builtins '("cap" "close" "closed" "len" "make" "new"
"panic" "panicln" "print" "println"))
(let ((builtins '("append" "cap" "close" "complex" "copy" "imag" "len"
"make" "new" "panic" "print" "println" "real" "recover"))
(constants '("nil" "true" "false" "iota"))
(type-name "\\s *\\(?:[*(]\\s *\\)*\\(?:\\w+\\s *\\.\\s *\\)?\\(\\w+\\)")
)

View File

@@ -142,18 +142,10 @@ func run(cmd ...string) ([]byte, os.Error) {
return exec.Command(cmd[0], cmd[1:]...).CombinedOutput()
}
var frontPage, output *template.Template // HTML templates
var frontPage = template.Must(template.New("frontPage").Parse(frontPageText)) // HTML template
var output = template.Must(template.New("output").Parse(outputText)) // HTML template
func init() {
frontPage = template.New(nil)
frontPage.SetDelims("«", "»")
if err := frontPage.Parse(frontPageText); err != nil {
panic(err)
}
output = template.MustParse(outputText, nil)
}
var outputText = `<pre>{@|html}</pre>`
var outputText = `<pre>{{printf "%s" . |html}}</pre>`
var frontPageText = `<!doctype html>
<html>
@@ -264,7 +256,7 @@ function compileUpdate() {
</head>
<body>
<table width="100%"><tr><td width="60%" valign="top">
<textarea autofocus="true" id="edit" spellcheck="false" onkeydown="keyHandler(event);" onkeyup="autocompile();">«@|html»</textarea>
<textarea autofocus="true" id="edit" spellcheck="false" onkeydown="keyHandler(event);" onkeyup="autocompile();">{{printf "%s" . |html}}</textarea>
<div class="hints">
(Shift-Enter to compile and run.)&nbsp;&nbsp;&nbsp;&nbsp;
<input type="checkbox" id="autocompile" value="checked" /> Compile and run after each keystroke

View File

@@ -1,15 +0,0 @@
#!/bin/sh
# Copyright 2010 The Go Authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Run nacl binary in debug mode (allow file access)
# and then grep away the chatter.
# See ../../src/pkg/exp/nacl/README for more on
# how to configure NaCl.
nacl -d "$@" >/tmp/nacl.out.$$ 2>&1
status=$?
egrep -v 'DEBUG MODE ENABLED|^\[[0-9]+,' /tmp/nacl.out.$$
rm -f /tmp/nacl.out.$$
exit $status

View File

@@ -0,0 +1,49 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" This file provides a utility function that performs auto-completion of
" package names, for use by other commands.
let s:goos = $GOOS
let s:goarch = $GOARCH
if len(s:goos) == 0
if exists('g:golang_goos')
let s:goos = g:golang_goos
elseif has('win32') || has('win64')
let s:goos = 'windows'
elseif has('macunix')
let s:goos = 'darwin'
else
let s:goos = '*'
endif
endif
if len(s:goarch) == 0
if exists('g:golang_goarch')
let s:goarch = g:golang_goarch
else
let s:goarch = '*'
endif
endif
function! go#complete#Package(ArgLead, CmdLine, CursorPos)
let goroot = $GOROOT
if len(goroot) == 0
" should not occur.
return []
endif
let ret = {}
let root = expand(goroot.'/pkg/'.s:goos.'_'.s:goarch)
for i in split(globpath(root, a:ArgLead.'*'), "\n")
if isdirectory(i)
let i .= '/'
elseif i !~ '\.a$'
continue
endif
let i = substitute(substitute(i[len(root)+1:], '[\\]', '/', 'g'), '\.a$', '', 'g')
let ret[i] = i
endfor
return sort(keys(ret))
endfunction

View File

@@ -1 +1 @@
au BufRead,BufNewFile *.go set filetype=go
au BufReadPre,BufNewFile *.go set filetype=go fileencoding=utf-8 fileencodings=utf-8

View File

@@ -0,0 +1,13 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" godoc.vim: Vim command to see godoc.
if exists("b:did_ftplugin")
finish
endif
silent! nmap <buffer> <silent> K <Plug>(godoc-keyword)
" vim:ts=4:sw=4:et

View File

@@ -36,9 +36,9 @@ if exists("b:did_ftplugin")
finish
endif
command! -buffer -nargs=? Drop call s:SwitchImport(0, '', <f-args>)
command! -buffer -nargs=1 Import call s:SwitchImport(1, '', <f-args>)
command! -buffer -nargs=* ImportAs call s:SwitchImport(1, <f-args>)
command! -buffer -nargs=? -complete=customlist,go#complete#Package Drop call s:SwitchImport(0, '', <f-args>)
command! -buffer -nargs=1 -complete=customlist,go#complete#Package Import call s:SwitchImport(1, '', <f-args>)
command! -buffer -nargs=* -complete=customlist,go#complete#Package ImportAs call s:SwitchImport(1, <f-args>)
map <buffer> <LocalLeader>f :Import fmt<CR>
map <buffer> <LocalLeader>F :Drop fmt<CR>

85
misc/vim/plugin/godoc.vim Normal file
View File

@@ -0,0 +1,85 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
"
" godoc.vim: Vim command to see godoc.
if exists("g:loaded_godoc")
finish
endif
let g:loaded_godoc = 1
let s:buf_nr = -1
let s:last_word = ''
function! s:GodocView()
if !bufexists(s:buf_nr)
leftabove new
file `="[Godoc]"`
let s:buf_nr = bufnr('%')
elseif bufwinnr(s:buf_nr) == -1
leftabove split
execute s:buf_nr . 'buffer'
delete _
elseif bufwinnr(s:buf_nr) != bufwinnr('%')
execute bufwinnr(s:buf_nr) . 'wincmd w'
endif
setlocal filetype=godoc
setlocal bufhidden=delete
setlocal buftype=nofile
setlocal noswapfile
setlocal nobuflisted
setlocal modifiable
setlocal nocursorline
setlocal nocursorcolumn
setlocal iskeyword+=:
setlocal iskeyword-=-
nnoremap <buffer> <silent> K :Godoc<cr>
au BufHidden <buffer> call let <SID>buf_nr = -1
endfunction
function! s:GodocWord(word)
let word = a:word
silent! let content = system('godoc ' . word)
if v:shell_error || !len(content)
if len(s:last_word)
silent! let content = system('godoc ' . s:last_word.'/'.word)
if v:shell_error || !len(content)
echo 'No documentation found for "' . word . '".'
return
endif
let word = s:last_word.'/'.word
else
echo 'No documentation found for "' . word . '".'
return
endif
endif
let s:last_word = word
silent! call s:GodocView()
setlocal modifiable
silent! %d _
silent! put! =content
silent! normal gg
setlocal nomodifiable
setfiletype godoc
endfunction
function! s:Godoc(...)
let word = join(a:000, ' ')
if !len(word)
let word = expand('<cword>')
endif
let word = substitute(word, '[^a-zA-Z0-9\/]', '', 'g')
if !len(word)
return
endif
call s:GodocWord(word)
endfunction
command! -nargs=* -range -complete=customlist,go#complete#Package Godoc :call s:Godoc(<q-args>)
nnoremap <silent> <Plug>(godoc-keyword) :<C-u>call <SID>Godoc('')<CR>
" vim:ts=4:sw=4:et

View File

@@ -1,5 +1,17 @@
Vim syntax highlighting for Go (http://golang.org)
==================================================
Vim plugins for Go (http://golang.org)
======================================
To use all the Vim plugins, add these lines to your vimrc.
set rtp+=$GOROOT/misc/vim
filetype plugin indent on
syntax on
If you want to select fewer plugins, use the instructions in the rest of
this file.
Vim syntax highlighting
-----------------------
To install automatic syntax highlighting for GO programs:
@@ -18,15 +30,17 @@ commands:
mkdir -p $HOME/.vim/ftdetect
mkdir -p $HOME/.vim/syntax
mkdir -p $HOME/.vim/autoload/go
ln -s $GOROOT/misc/vim/ftdetect/gofiletype.vim $HOME/.vim/ftdetect/
ln -s $GOROOT/misc/vim/syntax/go.vim $HOME/.vim/syntax
ln -s $GOROOT/misc/vim/autoload/go/complete.vim $HOME/.vim/autoload/go
echo "syntax on" >> $HOME/.vimrc
Vim filetype plugins for Go
===========================
Vim filetype plugins
--------------------
To install one of the available filetype plugins for Go:
To install one of the available filetype plugins:
1. Same as 1 above.
2. Copy or link one or more plugins from ftplugin/go/*.vim to the
@@ -37,10 +51,10 @@ To install one of the available filetype plugins for Go:
filetype plugin on
Vim indentation plugin for Go
=============================
Vim indentation plugin
----------------------
To install automatic indentation for Go:
To install automatic indentation:
1. Same as 1 above.
2. Copy or link indent/go.vim to the indent directory underneath your vim
@@ -48,3 +62,15 @@ To install automatic indentation for Go:
3. Add the following line to your .vimrc file (normally $HOME/.vimrc):
filetype indent on
Godoc plugin
------------
To install godoc plugin:
1. Same as 1 above.
2. Copy or link plugin/godoc.vim to $HOME/.vim/plugin/godoc,
syntax/godoc.vim to $HOME/.vim/syntax/godoc.vim,
ftplugin/go/godoc.vim to $HOME/.vim/ftplugin/go/godoc.vim.
and autoload/go/complete.vim to $HOME/.vim/autoload/go/complete.vim.

20
misc/vim/syntax/godoc.vim Normal file
View File

@@ -0,0 +1,20 @@
" Copyright 2011 The Go Authors. All rights reserved.
" Use of this source code is governed by a BSD-style
" license that can be found in the LICENSE file.
if exists("b:current_syntax")
finish
endif
syn case match
syn match godocTitle "^\([A-Z]*\)$"
command -nargs=+ HiLink hi def link <args>
HiLink godocTitle Title
delcommand HiLink
let b:current_syntax = "godoc"
" vim:ts=4 sts=2 sw=2:

View File

@@ -9,7 +9,7 @@ TARG:=$(TARG).exe
endif
$(TARG): $(OFILES) $(LIB)
$(HOST_LD) -o $(TARG) -L"$(GOROOT)"/lib $(OFILES) $(LIB) -lbio -l9 -lm $(HOST_LDFLAGS)
$(HOST_LD) -o $(TARG) -L"$(GOROOT)"/lib $(OFILES) $(LIB) -lmach -lbio -l9 -lm $(HOST_LDFLAGS)
$(OFILES): $(HFILES)
@@ -36,6 +36,7 @@ y.tab.c: y.tab.h
all: $(TARG)
# Use $(PWD)/$*.c so that gdb shows full path in stack traces.
%.$(HOST_O): %.c
$(HOST_CC) $(HOST_CFLAGS) -c "$(PWD)/$*.c"

View File

@@ -6,6 +6,7 @@
all: $(LIB)
# Use $(PWD)/$*.c so that gdb shows full path in stack traces.
%.$(HOST_O): %.c
$(HOST_CC) $(HOST_CFLAGS) -c "$(PWD)/$*.c"

View File

@@ -121,6 +121,21 @@ HOST_CFLAGS=-I"$(GOROOT)/include" $(HOST_EXTRA_CFLAGS)
HOST_LDFLAGS=$(HOST_EXTRA_LDFLAGS)
PWD=$(shell pwd)
# Decide whether use of cgo is okay.
ifeq ($(CGO_ENABLED),)
# Default on...
CGO_ENABLED:=1
ifeq ($(GOARCH),arm) # ... but not on ARM
CGO_ENABLED:=0
endif
ifeq ($(GOOS),plan9) # ... and not on Plan 9
CGO_ENABLED:=0
endif
ifeq ($(GOOS),openbsd) # ... and not on OpenBSD
CGO_ENABLED:=0
endif
endif
# Make environment more standard.
LANG:=
LC_ALL:=C
@@ -130,11 +145,12 @@ GREP_COLORS:=
export LANG LC_ALL LC_CTYPE GREP_OPTIONS GREP_COLORS
go-env:
@echo export GOARCH=$(GOARCH)
@echo export GOOS=$(GOOS)
@echo export GOHOSTARCH=$(GOHOSTARCH)
@echo export GOHOSTOS=$(GOHOSTOS)
@echo export O=$O
@echo export GOARCH="$(GOARCH)"
@echo export GOOS="$(GOOS)"
@echo export GOHOSTARCH="$(GOHOSTARCH)"
@echo export GOHOSTOS="$(GOHOSTOS)"
@echo export CGO_ENABLED="$(CGO_ENABLED)"
@echo export O="$O"
@echo export AS="$(AS)"
@echo export CC="$(CC)"
@echo export GC="$(GC)"

View File

@@ -59,7 +59,7 @@ coverage:
gotest
6cov -g $(shell pwd) $O.out | grep -v '_test\.go:'
CLEANFILES+=*.so _obj _test _testmain.go *.exe _cgo* *.cgo[12].* test.out build.out
CLEANFILES+=*.so _obj _test _testmain.go *.exe _cgo* test.out build.out
test:
gotest

View File

@@ -6,10 +6,11 @@
# Run all.bash but exclude tests that depend on functionality
# missing in QEMU's system call emulation.
export GOARCH=arm
export NOTEST=""
NOTEST="$NOTEST big" # xxx
NOTEST="$NOTEST http net rpc syslog websocket" # no localhost network
NOTEST="$NOTEST big" # just slow
NOTEST="$NOTEST go/build" # wants to run cgo
NOTEST="$NOTEST http http/cgi net rpc syslog websocket" # no localhost network
NOTEST="$NOTEST os" # 64-bit seek fails
./all.bash

View File

@@ -28,8 +28,6 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#include <u.h>
#include <libc.h>
#include <bio.h>
#include "../5l/5.out.h"
@@ -54,7 +52,9 @@ typedef struct Hist Hist;
#define NSYMB 8192
#define BUFSIZ 8192
#define HISTSZ 20
#ifndef EOF
#define EOF (-1)
#endif
#define IGN (-2)
#define GETC() ((--fi.c < 0)? filbuf(): *fi.p++ & 0xff)
#define NHASH 503

Some files were not shown because too many files have changed in this diff Show More