OSDN Git Service

Fix using package name as composite literal struct key.
[pf3gnuchains/gcc-fork.git] / gcc / go / gofrontend / parse.cc
1 // parse.cc -- Go frontend parser.
2
3 // Copyright 2009 The Go Authors. All rights reserved.
4 // Use of this source code is governed by a BSD-style
5 // license that can be found in the LICENSE file.
6
7 #include "go-system.h"
8
9 #include "lex.h"
10 #include "gogo.h"
11 #include "types.h"
12 #include "statements.h"
13 #include "expressions.h"
14 #include "parse.h"
15
16 // Struct Parse::Enclosing_var_comparison.
17
18 // Return true if v1 should be considered to be less than v2.
19
20 bool
21 Parse::Enclosing_var_comparison::operator()(const Enclosing_var& v1,
22                                             const Enclosing_var& v2)
23 {
24   if (v1.var() == v2.var())
25     return false;
26
27   const std::string& n1(v1.var()->name());
28   const std::string& n2(v2.var()->name());
29   int i = n1.compare(n2);
30   if (i < 0)
31     return true;
32   else if (i > 0)
33     return false;
34
35   // If we get here it means that a single nested function refers to
36   // two different variables defined in enclosing functions, and both
37   // variables have the same name.  I think this is impossible.
38   go_unreachable();
39 }
40
41 // Class Parse.
42
43 Parse::Parse(Lex* lex, Gogo* gogo)
44   : lex_(lex),
45     token_(Token::make_invalid_token(0)),
46     unget_token_(Token::make_invalid_token(0)),
47     unget_token_valid_(false),
48     gogo_(gogo),
49     break_stack_(NULL),
50     continue_stack_(NULL),
51     iota_(0),
52     enclosing_vars_()
53 {
54 }
55
56 // Return the current token.
57
58 const Token*
59 Parse::peek_token()
60 {
61   if (this->unget_token_valid_)
62     return &this->unget_token_;
63   if (this->token_.is_invalid())
64     this->token_ = this->lex_->next_token();
65   return &this->token_;
66 }
67
68 // Advance to the next token and return it.
69
70 const Token*
71 Parse::advance_token()
72 {
73   if (this->unget_token_valid_)
74     {
75       this->unget_token_valid_ = false;
76       if (!this->token_.is_invalid())
77         return &this->token_;
78     }
79   this->token_ = this->lex_->next_token();
80   return &this->token_;
81 }
82
83 // Push a token back on the input stream.
84
85 void
86 Parse::unget_token(const Token& token)
87 {
88   go_assert(!this->unget_token_valid_);
89   this->unget_token_ = token;
90   this->unget_token_valid_ = true;
91 }
92
93 // The location of the current token.
94
95 source_location
96 Parse::location()
97 {
98   return this->peek_token()->location();
99 }
100
101 // IdentifierList = identifier { "," identifier } .
102
103 void
104 Parse::identifier_list(Typed_identifier_list* til)
105 {
106   const Token* token = this->peek_token();
107   while (true)
108     {
109       if (!token->is_identifier())
110         {
111           error_at(this->location(), "expected identifier");
112           return;
113         }
114       std::string name =
115         this->gogo_->pack_hidden_name(token->identifier(),
116                                       token->is_identifier_exported());
117       til->push_back(Typed_identifier(name, NULL, token->location()));
118       token = this->advance_token();
119       if (!token->is_op(OPERATOR_COMMA))
120         return;
121       token = this->advance_token();
122     }
123 }
124
125 // ExpressionList = Expression { "," Expression } .
126
127 // If MAY_BE_SINK is true, the expressions in the list may be "_".
128
129 Expression_list*
130 Parse::expression_list(Expression* first, bool may_be_sink)
131 {
132   Expression_list* ret = new Expression_list();
133   if (first != NULL)
134     ret->push_back(first);
135   while (true)
136     {
137       ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink, true,
138                                       NULL));
139
140       const Token* token = this->peek_token();
141       if (!token->is_op(OPERATOR_COMMA))
142         return ret;
143
144       // Most expression lists permit a trailing comma.
145       source_location location = token->location();
146       this->advance_token();
147       if (!this->expression_may_start_here())
148         {
149           this->unget_token(Token::make_operator_token(OPERATOR_COMMA,
150                                                        location));
151           return ret;
152         }
153     }
154 }
155
156 // QualifiedIdent = [ PackageName "." ] identifier .
157 // PackageName = identifier .
158
159 // This sets *PNAME to the identifier and sets *PPACKAGE to the
160 // package or NULL if there isn't one.  This returns true on success,
161 // false on failure in which case it will have emitted an error
162 // message.
163
164 bool
165 Parse::qualified_ident(std::string* pname, Named_object** ppackage)
166 {
167   const Token* token = this->peek_token();
168   if (!token->is_identifier())
169     {
170       error_at(this->location(), "expected identifier");
171       return false;
172     }
173
174   std::string name = token->identifier();
175   bool is_exported = token->is_identifier_exported();
176   name = this->gogo_->pack_hidden_name(name, is_exported);
177
178   token = this->advance_token();
179   if (!token->is_op(OPERATOR_DOT))
180     {
181       *pname = name;
182       *ppackage = NULL;
183       return true;
184     }
185
186   Named_object* package = this->gogo_->lookup(name, NULL);
187   if (package == NULL || !package->is_package())
188     {
189       error_at(this->location(), "expected package");
190       // We expect . IDENTIFIER; skip both.
191       if (this->advance_token()->is_identifier())
192         this->advance_token();
193       return false;
194     }
195
196   package->package_value()->set_used();
197
198   token = this->advance_token();
199   if (!token->is_identifier())
200     {
201       error_at(this->location(), "expected identifier");
202       return false;
203     }
204
205   name = token->identifier();
206
207   if (name == "_")
208     {
209       error_at(this->location(), "invalid use of %<_%>");
210       name = "blank";
211     }
212
213   if (package->name() == this->gogo_->package_name())
214     name = this->gogo_->pack_hidden_name(name,
215                                          token->is_identifier_exported());
216
217   *pname = name;
218   *ppackage = package;
219
220   this->advance_token();
221
222   return true;
223 }
224
225 // Type = TypeName | TypeLit | "(" Type ")" .
226 // TypeLit =
227 //      ArrayType | StructType | PointerType | FunctionType | InterfaceType |
228 //      SliceType | MapType | ChannelType .
229
230 Type*
231 Parse::type()
232 {
233   const Token* token = this->peek_token();
234   if (token->is_identifier())
235     return this->type_name(true);
236   else if (token->is_op(OPERATOR_LSQUARE))
237     return this->array_type(false);
238   else if (token->is_keyword(KEYWORD_CHAN)
239            || token->is_op(OPERATOR_CHANOP))
240     return this->channel_type();
241   else if (token->is_keyword(KEYWORD_INTERFACE))
242     return this->interface_type();
243   else if (token->is_keyword(KEYWORD_FUNC))
244     {
245       source_location location = token->location();
246       this->advance_token();
247       Type* type = this->signature(NULL, location);
248       if (type == NULL)
249         return Type::make_error_type();
250       return type;
251     }
252   else if (token->is_keyword(KEYWORD_MAP))
253     return this->map_type();
254   else if (token->is_keyword(KEYWORD_STRUCT))
255     return this->struct_type();
256   else if (token->is_op(OPERATOR_MULT))
257     return this->pointer_type();
258   else if (token->is_op(OPERATOR_LPAREN))
259     {
260       this->advance_token();
261       Type* ret = this->type();
262       if (this->peek_token()->is_op(OPERATOR_RPAREN))
263         this->advance_token();
264       else
265         {
266           if (!ret->is_error_type())
267             error_at(this->location(), "expected %<)%>");
268         }
269       return ret;
270     }
271   else
272     {
273       error_at(token->location(), "expected type");
274       return Type::make_error_type();
275     }
276 }
277
278 bool
279 Parse::type_may_start_here()
280 {
281   const Token* token = this->peek_token();
282   return (token->is_identifier()
283           || token->is_op(OPERATOR_LSQUARE)
284           || token->is_op(OPERATOR_CHANOP)
285           || token->is_keyword(KEYWORD_CHAN)
286           || token->is_keyword(KEYWORD_INTERFACE)
287           || token->is_keyword(KEYWORD_FUNC)
288           || token->is_keyword(KEYWORD_MAP)
289           || token->is_keyword(KEYWORD_STRUCT)
290           || token->is_op(OPERATOR_MULT)
291           || token->is_op(OPERATOR_LPAREN));
292 }
293
294 // TypeName = QualifiedIdent .
295
296 // If MAY_BE_NIL is true, then an identifier with the value of the
297 // predefined constant nil is accepted, returning the nil type.
298
299 Type*
300 Parse::type_name(bool issue_error)
301 {
302   source_location location = this->location();
303
304   std::string name;
305   Named_object* package;
306   if (!this->qualified_ident(&name, &package))
307     return Type::make_error_type();
308
309   Named_object* named_object;
310   if (package == NULL)
311     named_object = this->gogo_->lookup(name, NULL);
312   else
313     {
314       named_object = package->package_value()->lookup(name);
315       if (named_object == NULL
316           && issue_error
317           && package->name() != this->gogo_->package_name())
318         {
319           // Check whether the name is there but hidden.
320           std::string s = ('.' + package->package_value()->unique_prefix()
321                            + '.' + package->package_value()->name()
322                            + '.' + name);
323           named_object = package->package_value()->lookup(s);
324           if (named_object != NULL)
325             {
326               const std::string& packname(package->package_value()->name());
327               error_at(location, "invalid reference to hidden type %<%s.%s%>",
328                        Gogo::message_name(packname).c_str(),
329                        Gogo::message_name(name).c_str());
330               issue_error = false;
331             }
332         }
333     }
334
335   bool ok = true;
336   if (named_object == NULL)
337     {
338       if (package != NULL)
339         ok = false;
340       else
341         named_object = this->gogo_->add_unknown_name(name, location);
342     }
343   else if (named_object->is_type())
344     {
345       if (!named_object->type_value()->is_visible())
346         ok = false;
347     }
348   else if (named_object->is_unknown() || named_object->is_type_declaration())
349     ;
350   else
351     ok = false;
352
353   if (!ok)
354     {
355       if (issue_error)
356         error_at(location, "expected type");
357       return Type::make_error_type();
358     }
359
360   if (named_object->is_type())
361     return named_object->type_value();
362   else if (named_object->is_unknown() || named_object->is_type_declaration())
363     return Type::make_forward_declaration(named_object);
364   else
365     go_unreachable();
366 }
367
368 // ArrayType = "[" [ ArrayLength ] "]" ElementType .
369 // ArrayLength = Expression .
370 // ElementType = CompleteType .
371
372 Type*
373 Parse::array_type(bool may_use_ellipsis)
374 {
375   go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
376   const Token* token = this->advance_token();
377
378   Expression* length = NULL;
379   if (token->is_op(OPERATOR_RSQUARE))
380     this->advance_token();
381   else
382     {
383       if (!token->is_op(OPERATOR_ELLIPSIS))
384         length = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
385       else if (may_use_ellipsis)
386         {
387           // An ellipsis is used in composite literals to represent a
388           // fixed array of the size of the number of elements.  We
389           // use a length of nil to represent this, and change the
390           // length when parsing the composite literal.
391           length = Expression::make_nil(this->location());
392           this->advance_token();
393         }
394       else
395         {
396           error_at(this->location(),
397                    "use of %<[...]%> outside of array literal");
398           length = Expression::make_error(this->location());
399           this->advance_token();
400         }
401       if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
402         {
403           error_at(this->location(), "expected %<]%>");
404           return Type::make_error_type();
405         }
406       this->advance_token();
407     }
408
409   Type* element_type = this->type();
410
411   return Type::make_array_type(element_type, length);
412 }
413
414 // MapType = "map" "[" KeyType "]" ValueType .
415 // KeyType = CompleteType .
416 // ValueType = CompleteType .
417
418 Type*
419 Parse::map_type()
420 {
421   source_location location = this->location();
422   go_assert(this->peek_token()->is_keyword(KEYWORD_MAP));
423   if (!this->advance_token()->is_op(OPERATOR_LSQUARE))
424     {
425       error_at(this->location(), "expected %<[%>");
426       return Type::make_error_type();
427     }
428   this->advance_token();
429
430   Type* key_type = this->type();
431
432   if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
433     {
434       error_at(this->location(), "expected %<]%>");
435       return Type::make_error_type();
436     }
437   this->advance_token();
438
439   Type* value_type = this->type();
440
441   if (key_type->is_error_type() || value_type->is_error_type())
442     return Type::make_error_type();
443
444   return Type::make_map_type(key_type, value_type, location);
445 }
446
447 // StructType     = "struct" "{" { FieldDecl ";" } "}" .
448
449 Type*
450 Parse::struct_type()
451 {
452   go_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT));
453   source_location location = this->location();
454   if (!this->advance_token()->is_op(OPERATOR_LCURLY))
455     {
456       source_location token_loc = this->location();
457       if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
458           && this->advance_token()->is_op(OPERATOR_LCURLY))
459         error_at(token_loc, "unexpected semicolon or newline before %<{%>");
460       else
461         {
462           error_at(this->location(), "expected %<{%>");
463           return Type::make_error_type();
464         }
465     }
466   this->advance_token();
467
468   Struct_field_list* sfl = new Struct_field_list;
469   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
470     {
471       this->field_decl(sfl);
472       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
473         this->advance_token();
474       else if (!this->peek_token()->is_op(OPERATOR_RCURLY))
475         {
476           error_at(this->location(), "expected %<;%> or %<}%> or newline");
477           if (!this->skip_past_error(OPERATOR_RCURLY))
478             return Type::make_error_type();
479         }
480     }
481   this->advance_token();
482
483   for (Struct_field_list::const_iterator pi = sfl->begin();
484        pi != sfl->end();
485        ++pi)
486     {
487       if (pi->type()->is_error_type())
488         return pi->type();
489       for (Struct_field_list::const_iterator pj = pi + 1;
490            pj != sfl->end();
491            ++pj)
492         {
493           if (pi->field_name() == pj->field_name()
494               && !Gogo::is_sink_name(pi->field_name()))
495             error_at(pi->location(), "duplicate field name %<%s%>",
496                      Gogo::message_name(pi->field_name()).c_str());
497         }
498     }
499
500   return Type::make_struct_type(sfl, location);
501 }
502
503 // FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] .
504 // Tag = string_lit .
505
506 void
507 Parse::field_decl(Struct_field_list* sfl)
508 {
509   const Token* token = this->peek_token();
510   source_location location = token->location();
511   bool is_anonymous;
512   bool is_anonymous_pointer;
513   if (token->is_op(OPERATOR_MULT))
514     {
515       is_anonymous = true;
516       is_anonymous_pointer = true;
517     }
518   else if (token->is_identifier())
519     {
520       std::string id = token->identifier();
521       bool is_id_exported = token->is_identifier_exported();
522       source_location id_location = token->location();
523       token = this->advance_token();
524       is_anonymous = (token->is_op(OPERATOR_SEMICOLON)
525                       || token->is_op(OPERATOR_RCURLY)
526                       || token->is_op(OPERATOR_DOT)
527                       || token->is_string());
528       is_anonymous_pointer = false;
529       this->unget_token(Token::make_identifier_token(id, is_id_exported,
530                                                      id_location));
531     }
532   else
533     {
534       error_at(this->location(), "expected field name");
535       while (!token->is_op(OPERATOR_SEMICOLON)
536              && !token->is_op(OPERATOR_RCURLY)
537              && !token->is_eof())
538         token = this->advance_token();
539       return;
540     }
541
542   if (is_anonymous)
543     {
544       if (is_anonymous_pointer)
545         {
546           this->advance_token();
547           if (!this->peek_token()->is_identifier())
548             {
549               error_at(this->location(), "expected field name");
550               while (!token->is_op(OPERATOR_SEMICOLON)
551                      && !token->is_op(OPERATOR_RCURLY)
552                      && !token->is_eof())
553                 token = this->advance_token();
554               return;
555             }
556         }
557       Type* type = this->type_name(true);
558
559       std::string tag;
560       if (this->peek_token()->is_string())
561         {
562           tag = this->peek_token()->string_value();
563           this->advance_token();
564         }
565
566       if (!type->is_error_type())
567         {
568           if (is_anonymous_pointer)
569             type = Type::make_pointer_type(type);
570           sfl->push_back(Struct_field(Typed_identifier("", type, location)));
571           if (!tag.empty())
572             sfl->back().set_tag(tag);
573         }
574     }
575   else
576     {
577       Typed_identifier_list til;
578       while (true)
579         {
580           token = this->peek_token();
581           if (!token->is_identifier())
582             {
583               error_at(this->location(), "expected identifier");
584               return;
585             }
586           std::string name =
587             this->gogo_->pack_hidden_name(token->identifier(),
588                                           token->is_identifier_exported());
589           til.push_back(Typed_identifier(name, NULL, token->location()));
590           if (!this->advance_token()->is_op(OPERATOR_COMMA))
591             break;
592           this->advance_token();
593         }
594
595       Type* type = this->type();
596
597       std::string tag;
598       if (this->peek_token()->is_string())
599         {
600           tag = this->peek_token()->string_value();
601           this->advance_token();
602         }
603
604       for (Typed_identifier_list::iterator p = til.begin();
605            p != til.end();
606            ++p)
607         {
608           p->set_type(type);
609           sfl->push_back(Struct_field(*p));
610           if (!tag.empty())
611             sfl->back().set_tag(tag);
612         }
613     }
614 }
615
616 // PointerType = "*" Type .
617
618 Type*
619 Parse::pointer_type()
620 {
621   go_assert(this->peek_token()->is_op(OPERATOR_MULT));
622   this->advance_token();
623   Type* type = this->type();
624   if (type->is_error_type())
625     return type;
626   return Type::make_pointer_type(type);
627 }
628
629 // ChannelType   = Channel | SendChannel | RecvChannel .
630 // Channel       = "chan" ElementType .
631 // SendChannel   = "chan" "<-" ElementType .
632 // RecvChannel   = "<-" "chan" ElementType .
633
634 Type*
635 Parse::channel_type()
636 {
637   const Token* token = this->peek_token();
638   bool send = true;
639   bool receive = true;
640   if (token->is_op(OPERATOR_CHANOP))
641     {
642       if (!this->advance_token()->is_keyword(KEYWORD_CHAN))
643         {
644           error_at(this->location(), "expected %<chan%>");
645           return Type::make_error_type();
646         }
647       send = false;
648       this->advance_token();
649     }
650   else
651     {
652       go_assert(token->is_keyword(KEYWORD_CHAN));
653       if (this->advance_token()->is_op(OPERATOR_CHANOP))
654         {
655           receive = false;
656           this->advance_token();
657         }
658     }
659
660   // Better error messages for the common error of omitting the
661   // channel element type.
662   if (!this->type_may_start_here())
663     {
664       token = this->peek_token();
665       if (token->is_op(OPERATOR_RCURLY))
666         error_at(this->location(), "unexpected %<}%> in channel type");
667       else if (token->is_op(OPERATOR_RPAREN))
668         error_at(this->location(), "unexpected %<)%> in channel type");
669       else if (token->is_op(OPERATOR_COMMA))
670         error_at(this->location(), "unexpected comma in channel type");
671       else
672         error_at(this->location(), "expected channel element type");
673       return Type::make_error_type();
674     }
675
676   Type* element_type = this->type();
677   return Type::make_channel_type(send, receive, element_type);
678 }
679
680 // Signature      = Parameters [ Result ] .
681
682 // RECEIVER is the receiver if there is one, or NULL.  LOCATION is the
683 // location of the start of the type.
684
685 // This returns NULL on a parse error.
686
687 Function_type*
688 Parse::signature(Typed_identifier* receiver, source_location location)
689 {
690   bool is_varargs = false;
691   Typed_identifier_list* params;
692   bool params_ok = this->parameters(&params, &is_varargs);
693
694   Typed_identifier_list* result = NULL;
695   if (this->peek_token()->is_op(OPERATOR_LPAREN)
696       || this->type_may_start_here())
697     {
698       if (!this->result(&result))
699         return NULL;
700     }
701
702   if (!params_ok)
703     return NULL;
704
705   Function_type* ret = Type::make_function_type(receiver, params, result,
706                                                 location);
707   if (is_varargs)
708     ret->set_is_varargs();
709   return ret;
710 }
711
712 // Parameters     = "(" [ ParameterList [ "," ] ] ")" .
713
714 // This returns false on a parse error.
715
716 bool
717 Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs)
718 {
719   *pparams = NULL;
720
721   if (!this->peek_token()->is_op(OPERATOR_LPAREN))
722     {
723       error_at(this->location(), "expected %<(%>");
724       return false;
725     }
726
727   Typed_identifier_list* params = NULL;
728   bool saw_error = false;
729
730   const Token* token = this->advance_token();
731   if (!token->is_op(OPERATOR_RPAREN))
732     {
733       params = this->parameter_list(is_varargs);
734       if (params == NULL)
735         saw_error = true;
736       token = this->peek_token();
737     }
738
739   // The optional trailing comma is picked up in parameter_list.
740
741   if (!token->is_op(OPERATOR_RPAREN))
742     error_at(this->location(), "expected %<)%>");
743   else
744     this->advance_token();
745
746   if (saw_error)
747     return false;
748
749   *pparams = params;
750   return true;
751 }
752
753 // ParameterList  = ParameterDecl { "," ParameterDecl } .
754
755 // This sets *IS_VARARGS if the list ends with an ellipsis.
756 // IS_VARARGS will be NULL if varargs are not permitted.
757
758 // We pick up an optional trailing comma.
759
760 // This returns NULL if some error is seen.
761
762 Typed_identifier_list*
763 Parse::parameter_list(bool* is_varargs)
764 {
765   source_location location = this->location();
766   Typed_identifier_list* ret = new Typed_identifier_list();
767
768   bool saw_error = false;
769
770   // If we see an identifier and then a comma, then we don't know
771   // whether we are looking at a list of identifiers followed by a
772   // type, or a list of types given by name.  We have to do an
773   // arbitrary lookahead to figure it out.
774
775   bool parameters_have_names;
776   const Token* token = this->peek_token();
777   if (!token->is_identifier())
778     {
779       // This must be a type which starts with something like '*'.
780       parameters_have_names = false;
781     }
782   else
783     {
784       std::string name = token->identifier();
785       bool is_exported = token->is_identifier_exported();
786       source_location location = token->location();
787       token = this->advance_token();
788       if (!token->is_op(OPERATOR_COMMA))
789         {
790           if (token->is_op(OPERATOR_DOT))
791             {
792               // This is a qualified identifier, which must turn out
793               // to be a type.
794               parameters_have_names = false;
795             }
796           else if (token->is_op(OPERATOR_RPAREN))
797             {
798               // A single identifier followed by a parenthesis must be
799               // a type name.
800               parameters_have_names = false;
801             }
802           else
803             {
804               // An identifier followed by something other than a
805               // comma or a dot or a right parenthesis must be a
806               // parameter name followed by a type.
807               parameters_have_names = true;
808             }
809
810           this->unget_token(Token::make_identifier_token(name, is_exported,
811                                                          location));
812         }
813       else
814         {
815           // An identifier followed by a comma may be the first in a
816           // list of parameter names followed by a type, or it may be
817           // the first in a list of types without parameter names.  To
818           // find out we gather as many identifiers separated by
819           // commas as we can.
820           std::string id_name = this->gogo_->pack_hidden_name(name,
821                                                               is_exported);
822           ret->push_back(Typed_identifier(id_name, NULL, location));
823           bool just_saw_comma = true;
824           while (this->advance_token()->is_identifier())
825             {
826               name = this->peek_token()->identifier();
827               is_exported = this->peek_token()->is_identifier_exported();
828               location = this->peek_token()->location();
829               id_name = this->gogo_->pack_hidden_name(name, is_exported);
830               ret->push_back(Typed_identifier(id_name, NULL, location));
831               if (!this->advance_token()->is_op(OPERATOR_COMMA))
832                 {
833                   just_saw_comma = false;
834                   break;
835                 }
836             }
837
838           if (just_saw_comma)
839             {
840               // We saw ID1 "," ID2 "," followed by something which
841               // was not an identifier.  We must be seeing the start
842               // of a type, and ID1 and ID2 must be types, and the
843               // parameters don't have names.
844               parameters_have_names = false;
845             }
846           else if (this->peek_token()->is_op(OPERATOR_RPAREN))
847             {
848               // We saw ID1 "," ID2 ")".  ID1 and ID2 must be types,
849               // and the parameters don't have names.
850               parameters_have_names = false;
851             }
852           else if (this->peek_token()->is_op(OPERATOR_DOT))
853             {
854               // We saw ID1 "," ID2 ".".  ID2 must be a package name,
855               // ID1 must be a type, and the parameters don't have
856               // names.
857               parameters_have_names = false;
858               this->unget_token(Token::make_identifier_token(name, is_exported,
859                                                              location));
860               ret->pop_back();
861               just_saw_comma = true;
862             }
863           else
864             {
865               // We saw ID1 "," ID2 followed by something other than
866               // ",", ".", or ")".  We must be looking at the start of
867               // a type, and ID1 and ID2 must be parameter names.
868               parameters_have_names = true;
869             }
870
871           if (parameters_have_names)
872             {
873               go_assert(!just_saw_comma);
874               // We have just seen ID1, ID2 xxx.
875               Type* type;
876               if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
877                 type = this->type();
878               else
879                 {
880                   error_at(this->location(), "%<...%> only permits one name");
881                   saw_error = true;
882                   this->advance_token();
883                   type = this->type();
884                 }
885               for (size_t i = 0; i < ret->size(); ++i)
886                 ret->set_type(i, type);
887               if (!this->peek_token()->is_op(OPERATOR_COMMA))
888                 return saw_error ? NULL : ret;
889               if (this->advance_token()->is_op(OPERATOR_RPAREN))
890                 return saw_error ? NULL : ret;
891             }
892           else
893             {
894               Typed_identifier_list* tret = new Typed_identifier_list();
895               for (Typed_identifier_list::const_iterator p = ret->begin();
896                    p != ret->end();
897                    ++p)
898                 {
899                   Named_object* no = this->gogo_->lookup(p->name(), NULL);
900                   Type* type;
901                   if (no == NULL)
902                     no = this->gogo_->add_unknown_name(p->name(),
903                                                        p->location());
904
905                   if (no->is_type())
906                     type = no->type_value();
907                   else if (no->is_unknown() || no->is_type_declaration())
908                     type = Type::make_forward_declaration(no);
909                   else
910                     {
911                       error_at(p->location(), "expected %<%s%> to be a type",
912                                Gogo::message_name(p->name()).c_str());
913                       saw_error = true;
914                       type = Type::make_error_type();
915                     }
916                   tret->push_back(Typed_identifier("", type, p->location()));
917                 }
918               delete ret;
919               ret = tret;
920               if (!just_saw_comma
921                   || this->peek_token()->is_op(OPERATOR_RPAREN))
922                 return saw_error ? NULL : ret;
923             }
924         }
925     }
926
927   bool mix_error = false;
928   this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
929   while (this->peek_token()->is_op(OPERATOR_COMMA))
930     {
931       if (is_varargs != NULL && *is_varargs)
932         {
933           error_at(this->location(), "%<...%> must be last parameter");
934           saw_error = true;
935         }
936       if (this->advance_token()->is_op(OPERATOR_RPAREN))
937         break;
938       this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
939     }
940   if (mix_error)
941     {
942       error_at(location, "invalid named/anonymous mix");
943       saw_error = true;
944     }
945   if (saw_error)
946     {
947       delete ret;
948       return NULL;
949     }
950   return ret;
951 }
952
953 // ParameterDecl  = [ IdentifierList ] [ "..." ] Type .
954
955 void
956 Parse::parameter_decl(bool parameters_have_names,
957                       Typed_identifier_list* til,
958                       bool* is_varargs,
959                       bool* mix_error)
960 {
961   if (!parameters_have_names)
962     {
963       Type* type;
964       source_location location = this->location();
965       if (!this->peek_token()->is_identifier())
966         {
967           if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
968             type = this->type();
969           else
970             {
971               if (is_varargs == NULL)
972                 error_at(this->location(), "invalid use of %<...%>");
973               else
974                 *is_varargs = true;
975               this->advance_token();
976               if (is_varargs == NULL
977                   && this->peek_token()->is_op(OPERATOR_RPAREN))
978                 type = Type::make_error_type();
979               else
980                 {
981                   Type* element_type = this->type();
982                   type = Type::make_array_type(element_type, NULL);
983                 }
984             }
985         }
986       else
987         {
988           type = this->type_name(false);
989           if (type->is_error_type()
990               || (!this->peek_token()->is_op(OPERATOR_COMMA)
991                   && !this->peek_token()->is_op(OPERATOR_RPAREN)))
992             {
993               *mix_error = true;
994               while (!this->peek_token()->is_op(OPERATOR_COMMA)
995                      && !this->peek_token()->is_op(OPERATOR_RPAREN))
996                 this->advance_token();
997             }
998         }
999       if (!type->is_error_type())
1000         til->push_back(Typed_identifier("", type, location));
1001     }
1002   else
1003     {
1004       size_t orig_count = til->size();
1005       if (this->peek_token()->is_identifier())
1006         this->identifier_list(til);
1007       else
1008         *mix_error = true;
1009       size_t new_count = til->size();
1010
1011       Type* type;
1012       if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1013         type = this->type();
1014       else
1015         {
1016           if (is_varargs == NULL)
1017             error_at(this->location(), "invalid use of %<...%>");
1018           else if (new_count > orig_count + 1)
1019             error_at(this->location(), "%<...%> only permits one name");
1020           else
1021             *is_varargs = true;
1022           this->advance_token();
1023           Type* element_type = this->type();
1024           type = Type::make_array_type(element_type, NULL);
1025         }
1026       for (size_t i = orig_count; i < new_count; ++i)
1027         til->set_type(i, type);
1028     }
1029 }
1030
1031 // Result         = Parameters | Type .
1032
1033 // This returns false on a parse error.
1034
1035 bool
1036 Parse::result(Typed_identifier_list** presults)
1037 {
1038   if (this->peek_token()->is_op(OPERATOR_LPAREN))
1039     return this->parameters(presults, NULL);
1040   else
1041     {
1042       source_location location = this->location();
1043       Type* type = this->type();
1044       if (type->is_error_type())
1045         {
1046           *presults = NULL;
1047           return false;
1048         }
1049       Typed_identifier_list* til = new Typed_identifier_list();
1050       til->push_back(Typed_identifier("", type, location));
1051       *presults = til;
1052       return true;
1053     }
1054 }
1055
1056 // Block = "{" [ StatementList ] "}" .
1057
1058 // Returns the location of the closing brace.
1059
1060 source_location
1061 Parse::block()
1062 {
1063   if (!this->peek_token()->is_op(OPERATOR_LCURLY))
1064     {
1065       source_location loc = this->location();
1066       if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1067           && this->advance_token()->is_op(OPERATOR_LCURLY))
1068         error_at(loc, "unexpected semicolon or newline before %<{%>");
1069       else
1070         {
1071           error_at(this->location(), "expected %<{%>");
1072           return UNKNOWN_LOCATION;
1073         }
1074     }
1075
1076   const Token* token = this->advance_token();
1077
1078   if (!token->is_op(OPERATOR_RCURLY))
1079     {
1080       this->statement_list();
1081       token = this->peek_token();
1082       if (!token->is_op(OPERATOR_RCURLY))
1083         {
1084           if (!token->is_eof() || !saw_errors())
1085             error_at(this->location(), "expected %<}%>");
1086
1087           // Skip ahead to the end of the block, in hopes of avoiding
1088           // lots of meaningless errors.
1089           source_location ret = token->location();
1090           int nest = 0;
1091           while (!token->is_eof())
1092             {
1093               if (token->is_op(OPERATOR_LCURLY))
1094                 ++nest;
1095               else if (token->is_op(OPERATOR_RCURLY))
1096                 {
1097                   --nest;
1098                   if (nest < 0)
1099                     {
1100                       this->advance_token();
1101                       break;
1102                     }
1103                 }
1104               token = this->advance_token();
1105               ret = token->location();
1106             }
1107           return ret;
1108         }
1109     }
1110
1111   source_location ret = token->location();
1112   this->advance_token();
1113   return ret;
1114 }
1115
1116 // InterfaceType      = "interface" "{" [ MethodSpecList ] "}" .
1117 // MethodSpecList     = MethodSpec { ";" MethodSpec } [ ";" ] .
1118
1119 Type*
1120 Parse::interface_type()
1121 {
1122   go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE));
1123   source_location location = this->location();
1124
1125   if (!this->advance_token()->is_op(OPERATOR_LCURLY))
1126     {
1127       source_location token_loc = this->location();
1128       if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1129           && this->advance_token()->is_op(OPERATOR_LCURLY))
1130         error_at(token_loc, "unexpected semicolon or newline before %<{%>");
1131       else
1132         {
1133           error_at(this->location(), "expected %<{%>");
1134           return Type::make_error_type();
1135         }
1136     }
1137   this->advance_token();
1138
1139   Typed_identifier_list* methods = new Typed_identifier_list();
1140   if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1141     {
1142       this->method_spec(methods);
1143       while (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1144         {
1145           if (this->advance_token()->is_op(OPERATOR_RCURLY))
1146             break;
1147           this->method_spec(methods);
1148         }
1149       if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1150         {
1151           error_at(this->location(), "expected %<}%>");
1152           while (!this->advance_token()->is_op(OPERATOR_RCURLY))
1153             {
1154               if (this->peek_token()->is_eof())
1155                 return Type::make_error_type();
1156             }
1157         }
1158     }
1159   this->advance_token();
1160
1161   if (methods->empty())
1162     {
1163       delete methods;
1164       methods = NULL;
1165     }
1166
1167   Interface_type* ret = Type::make_interface_type(methods, location);
1168   this->gogo_->record_interface_type(ret);
1169   return ret;
1170 }
1171
1172 // MethodSpec         = MethodName Signature | InterfaceTypeName .
1173 // MethodName         = identifier .
1174 // InterfaceTypeName  = TypeName .
1175
1176 void
1177 Parse::method_spec(Typed_identifier_list* methods)
1178 {
1179   const Token* token = this->peek_token();
1180   if (!token->is_identifier())
1181     {
1182       error_at(this->location(), "expected identifier");
1183       return;
1184     }
1185
1186   std::string name = token->identifier();
1187   bool is_exported = token->is_identifier_exported();
1188   source_location location = token->location();
1189
1190   if (this->advance_token()->is_op(OPERATOR_LPAREN))
1191     {
1192       // This is a MethodName.
1193       name = this->gogo_->pack_hidden_name(name, is_exported);
1194       Type* type = this->signature(NULL, location);
1195       if (type == NULL)
1196         return;
1197       methods->push_back(Typed_identifier(name, type, location));
1198     }
1199   else
1200     {
1201       this->unget_token(Token::make_identifier_token(name, is_exported,
1202                                                      location));
1203       Type* type = this->type_name(false);
1204       if (type->is_error_type()
1205           || (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1206               && !this->peek_token()->is_op(OPERATOR_RCURLY)))
1207         {
1208           if (this->peek_token()->is_op(OPERATOR_COMMA))
1209             error_at(this->location(),
1210                      "name list not allowed in interface type");
1211           else
1212             error_at(location, "expected signature or type name");
1213           token = this->peek_token();
1214           while (!token->is_eof()
1215                  && !token->is_op(OPERATOR_SEMICOLON)
1216                  && !token->is_op(OPERATOR_RCURLY))
1217             token = this->advance_token();
1218           return;
1219         }
1220       // This must be an interface type, but we can't check that now.
1221       // We check it and pull out the methods in
1222       // Interface_type::do_verify.
1223       methods->push_back(Typed_identifier("", type, location));
1224     }
1225 }
1226
1227 // Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1228
1229 void
1230 Parse::declaration()
1231 {
1232   const Token* token = this->peek_token();
1233   if (token->is_keyword(KEYWORD_CONST))
1234     this->const_decl();
1235   else if (token->is_keyword(KEYWORD_TYPE))
1236     this->type_decl();
1237   else if (token->is_keyword(KEYWORD_VAR))
1238     this->var_decl();
1239   else if (token->is_keyword(KEYWORD_FUNC))
1240     this->function_decl();
1241   else
1242     {
1243       error_at(this->location(), "expected declaration");
1244       this->advance_token();
1245     }
1246 }
1247
1248 bool
1249 Parse::declaration_may_start_here()
1250 {
1251   const Token* token = this->peek_token();
1252   return (token->is_keyword(KEYWORD_CONST)
1253           || token->is_keyword(KEYWORD_TYPE)
1254           || token->is_keyword(KEYWORD_VAR)
1255           || token->is_keyword(KEYWORD_FUNC));
1256 }
1257
1258 // Decl<P> = P | "(" [ List<P> ] ")" .
1259
1260 void
1261 Parse::decl(void (Parse::*pfn)(void*), void* varg)
1262 {
1263   if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1264     (this->*pfn)(varg);
1265   else
1266     {
1267       if (!this->advance_token()->is_op(OPERATOR_RPAREN))
1268         {
1269           this->list(pfn, varg, true);
1270           if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1271             {
1272               error_at(this->location(), "missing %<)%>");
1273               while (!this->advance_token()->is_op(OPERATOR_RPAREN))
1274                 {
1275                   if (this->peek_token()->is_eof())
1276                     return;
1277                 }
1278             }
1279         }
1280       this->advance_token();
1281     }
1282 }
1283
1284 // List<P> = P { ";" P } [ ";" ] .
1285
1286 // In order to pick up the trailing semicolon we need to know what
1287 // might follow.  This is either a '}' or a ')'.
1288
1289 void
1290 Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren)
1291 {
1292   (this->*pfn)(varg);
1293   Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY;
1294   while (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1295          || this->peek_token()->is_op(OPERATOR_COMMA))
1296     {
1297       if (this->peek_token()->is_op(OPERATOR_COMMA))
1298         error_at(this->location(), "unexpected comma");
1299       if (this->advance_token()->is_op(follow))
1300         break;
1301       (this->*pfn)(varg);
1302     }
1303 }
1304
1305 // ConstDecl      = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1306
1307 void
1308 Parse::const_decl()
1309 {
1310   go_assert(this->peek_token()->is_keyword(KEYWORD_CONST));
1311   this->advance_token();
1312   this->reset_iota();
1313
1314   Type* last_type = NULL;
1315   Expression_list* last_expr_list = NULL;
1316
1317   if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1318     this->const_spec(&last_type, &last_expr_list);
1319   else
1320     {
1321       this->advance_token();
1322       while (!this->peek_token()->is_op(OPERATOR_RPAREN))
1323         {
1324           this->const_spec(&last_type, &last_expr_list);
1325           if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1326             this->advance_token();
1327           else if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1328             {
1329               error_at(this->location(), "expected %<;%> or %<)%> or newline");
1330               if (!this->skip_past_error(OPERATOR_RPAREN))
1331                 return;
1332             }
1333         }
1334       this->advance_token();
1335     }
1336
1337   if (last_expr_list != NULL)
1338     delete last_expr_list;
1339 }
1340
1341 // ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
1342
1343 void
1344 Parse::const_spec(Type** last_type, Expression_list** last_expr_list)
1345 {
1346   Typed_identifier_list til;
1347   this->identifier_list(&til);
1348
1349   Type* type = NULL;
1350   if (this->type_may_start_here())
1351     {
1352       type = this->type();
1353       *last_type = NULL;
1354       *last_expr_list = NULL;
1355     }
1356
1357   Expression_list *expr_list;
1358   if (!this->peek_token()->is_op(OPERATOR_EQ))
1359     {
1360       if (*last_expr_list == NULL)
1361         {
1362           error_at(this->location(), "expected %<=%>");
1363           return;
1364         }
1365       type = *last_type;
1366       expr_list = new Expression_list;
1367       for (Expression_list::const_iterator p = (*last_expr_list)->begin();
1368            p != (*last_expr_list)->end();
1369            ++p)
1370         expr_list->push_back((*p)->copy());
1371     }
1372   else
1373     {
1374       this->advance_token();
1375       expr_list = this->expression_list(NULL, false);
1376       *last_type = type;
1377       if (*last_expr_list != NULL)
1378         delete *last_expr_list;
1379       *last_expr_list = expr_list;
1380     }
1381
1382   Expression_list::const_iterator pe = expr_list->begin();
1383   for (Typed_identifier_list::iterator pi = til.begin();
1384        pi != til.end();
1385        ++pi, ++pe)
1386     {
1387       if (pe == expr_list->end())
1388         {
1389           error_at(this->location(), "not enough initializers");
1390           return;
1391         }
1392       if (type != NULL)
1393         pi->set_type(type);
1394
1395       if (!Gogo::is_sink_name(pi->name()))
1396         this->gogo_->add_constant(*pi, *pe, this->iota_value());
1397     }
1398   if (pe != expr_list->end())
1399     error_at(this->location(), "too many initializers");
1400
1401   this->increment_iota();
1402
1403   return;
1404 }
1405
1406 // TypeDecl = "type" Decl<TypeSpec> .
1407
1408 void
1409 Parse::type_decl()
1410 {
1411   go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE));
1412   this->advance_token();
1413   this->decl(&Parse::type_spec, NULL);
1414 }
1415
1416 // TypeSpec = identifier Type .
1417
1418 void
1419 Parse::type_spec(void*)
1420 {
1421   const Token* token = this->peek_token();
1422   if (!token->is_identifier())
1423     {
1424       error_at(this->location(), "expected identifier");
1425       return;
1426     }
1427   std::string name = token->identifier();
1428   bool is_exported = token->is_identifier_exported();
1429   source_location location = token->location();
1430   token = this->advance_token();
1431
1432   // The scope of the type name starts at the point where the
1433   // identifier appears in the source code.  We implement this by
1434   // declaring the type before we read the type definition.
1435   Named_object* named_type = NULL;
1436   if (name != "_")
1437     {
1438       name = this->gogo_->pack_hidden_name(name, is_exported);
1439       named_type = this->gogo_->declare_type(name, location);
1440     }
1441
1442   Type* type;
1443   if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
1444     type = this->type();
1445   else
1446     {
1447       error_at(this->location(),
1448                "unexpected semicolon or newline in type declaration");
1449       type = Type::make_error_type();
1450       this->advance_token();
1451     }
1452
1453   if (type->is_error_type())
1454     {
1455       while (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1456              && !this->peek_token()->is_eof())
1457         this->advance_token();
1458     }
1459
1460   if (name != "_")
1461     {
1462       if (named_type->is_type_declaration())
1463         {
1464           Type* ftype = type->forwarded();
1465           if (ftype->forward_declaration_type() != NULL
1466               && (ftype->forward_declaration_type()->named_object()
1467                   == named_type))
1468             {
1469               error_at(location, "invalid recursive type");
1470               type = Type::make_error_type();
1471             }
1472
1473           this->gogo_->define_type(named_type,
1474                                    Type::make_named_type(named_type, type,
1475                                                          location));
1476           go_assert(named_type->package() == NULL);
1477         }
1478       else
1479         {
1480           // This will probably give a redefinition error.
1481           this->gogo_->add_type(name, type, location);
1482         }
1483     }
1484 }
1485
1486 // VarDecl = "var" Decl<VarSpec> .
1487
1488 void
1489 Parse::var_decl()
1490 {
1491   go_assert(this->peek_token()->is_keyword(KEYWORD_VAR));
1492   this->advance_token();
1493   this->decl(&Parse::var_spec, NULL);
1494 }
1495
1496 // VarSpec = IdentifierList
1497 //             ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
1498
1499 void
1500 Parse::var_spec(void*)
1501 {
1502   // Get the variable names.
1503   Typed_identifier_list til;
1504   this->identifier_list(&til);
1505
1506   source_location location = this->location();
1507
1508   Type* type = NULL;
1509   Expression_list* init = NULL;
1510   if (!this->peek_token()->is_op(OPERATOR_EQ))
1511     {
1512       type = this->type();
1513       if (type->is_error_type())
1514         {
1515           while (!this->peek_token()->is_op(OPERATOR_EQ)
1516                  && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
1517                  && !this->peek_token()->is_eof())
1518             this->advance_token();
1519         }
1520       if (this->peek_token()->is_op(OPERATOR_EQ))
1521         {
1522           this->advance_token();
1523           init = this->expression_list(NULL, false);
1524         }
1525     }
1526   else
1527     {
1528       this->advance_token();
1529       init = this->expression_list(NULL, false);
1530     }
1531
1532   this->init_vars(&til, type, init, false, location);
1533
1534   if (init != NULL)
1535     delete init;
1536 }
1537
1538 // Create variables.  TIL is a list of variable names.  If TYPE is not
1539 // NULL, it is the type of all the variables.  If INIT is not NULL, it
1540 // is an initializer list for the variables.
1541
1542 void
1543 Parse::init_vars(const Typed_identifier_list* til, Type* type,
1544                  Expression_list* init, bool is_coloneq,
1545                  source_location location)
1546 {
1547   // Check for an initialization which can yield multiple values.
1548   if (init != NULL && init->size() == 1 && til->size() > 1)
1549     {
1550       if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq,
1551                                     location))
1552         return;
1553       if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq,
1554                                    location))
1555         return;
1556       if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq,
1557                                        location))
1558         return;
1559       if (this->init_vars_from_type_guard(til, type, *init->begin(),
1560                                           is_coloneq, location))
1561         return;
1562     }
1563
1564   if (init != NULL && init->size() != til->size())
1565     {
1566       if (init->empty() || !init->front()->is_error_expression())
1567         error_at(location, "wrong number of initializations");
1568       init = NULL;
1569       if (type == NULL)
1570         type = Type::make_error_type();
1571     }
1572
1573   // Note that INIT was already parsed with the old name bindings, so
1574   // we don't have to worry that it will accidentally refer to the
1575   // newly declared variables.
1576
1577   Expression_list::const_iterator pexpr;
1578   if (init != NULL)
1579     pexpr = init->begin();
1580   bool any_new = false;
1581   for (Typed_identifier_list::const_iterator p = til->begin();
1582        p != til->end();
1583        ++p)
1584     {
1585       if (init != NULL)
1586         go_assert(pexpr != init->end());
1587       this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq,
1588                      false, &any_new);
1589       if (init != NULL)
1590         ++pexpr;
1591     }
1592   if (init != NULL)
1593     go_assert(pexpr == init->end());
1594   if (is_coloneq && !any_new)
1595     error_at(location, "variables redeclared but no variable is new");
1596 }
1597
1598 // See if we need to initialize a list of variables from a function
1599 // call.  This returns true if we have set up the variables and the
1600 // initialization.
1601
1602 bool
1603 Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type,
1604                            Expression* expr, bool is_coloneq,
1605                            source_location location)
1606 {
1607   Call_expression* call = expr->call_expression();
1608   if (call == NULL)
1609     return false;
1610
1611   // This is a function call.  We can't check here whether it returns
1612   // the right number of values, but it might.  Declare the variables,
1613   // and then assign the results of the call to them.
1614
1615   unsigned int index = 0;
1616   bool any_new = false;
1617   for (Typed_identifier_list::const_iterator pv = vars->begin();
1618        pv != vars->end();
1619        ++pv, ++index)
1620     {
1621       Expression* init = Expression::make_call_result(call, index);
1622       this->init_var(*pv, type, init, is_coloneq, false, &any_new);
1623     }
1624
1625   if (is_coloneq && !any_new)
1626     error_at(location, "variables redeclared but no variable is new");
1627
1628   return true;
1629 }
1630
1631 // See if we need to initialize a pair of values from a map index
1632 // expression.  This returns true if we have set up the variables and
1633 // the initialization.
1634
1635 bool
1636 Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type,
1637                           Expression* expr, bool is_coloneq,
1638                           source_location location)
1639 {
1640   Index_expression* index = expr->index_expression();
1641   if (index == NULL)
1642     return false;
1643   if (vars->size() != 2)
1644     return false;
1645
1646   // This is an index which is being assigned to two variables.  It
1647   // must be a map index.  Declare the variables, and then assign the
1648   // results of the map index.
1649   bool any_new = false;
1650   Typed_identifier_list::const_iterator p = vars->begin();
1651   Expression* init = type == NULL ? index : NULL;
1652   Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1653                                         type == NULL, &any_new);
1654   if (type == NULL && any_new && val_no->is_variable())
1655     val_no->var_value()->set_type_from_init_tuple();
1656   Expression* val_var = Expression::make_var_reference(val_no, location);
1657
1658   ++p;
1659   Type* var_type = type;
1660   if (var_type == NULL)
1661     var_type = Type::lookup_bool_type();
1662   Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1663                                     &any_new);
1664   Expression* present_var = Expression::make_var_reference(no, location);
1665
1666   if (is_coloneq && !any_new)
1667     error_at(location, "variables redeclared but no variable is new");
1668
1669   Statement* s = Statement::make_tuple_map_assignment(val_var, present_var,
1670                                                       index, location);
1671
1672   if (!this->gogo_->in_global_scope())
1673     this->gogo_->add_statement(s);
1674   else if (!val_no->is_sink())
1675     {
1676       if (val_no->is_variable())
1677         val_no->var_value()->add_preinit_statement(this->gogo_, s);
1678     }
1679   else if (!no->is_sink())
1680     {
1681       if (no->is_variable())
1682         no->var_value()->add_preinit_statement(this->gogo_, s);
1683     }
1684   else
1685     {
1686       // Execute the map index expression just so that we can fail if
1687       // the map is nil.
1688       Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1689                                                       NULL, location);
1690       dummy->var_value()->add_preinit_statement(this->gogo_, s);
1691     }
1692
1693   return true;
1694 }
1695
1696 // See if we need to initialize a pair of values from a receive
1697 // expression.  This returns true if we have set up the variables and
1698 // the initialization.
1699
1700 bool
1701 Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type,
1702                               Expression* expr, bool is_coloneq,
1703                               source_location location)
1704 {
1705   Receive_expression* receive = expr->receive_expression();
1706   if (receive == NULL)
1707     return false;
1708   if (vars->size() != 2)
1709     return false;
1710
1711   // This is a receive expression which is being assigned to two
1712   // variables.  Declare the variables, and then assign the results of
1713   // the receive.
1714   bool any_new = false;
1715   Typed_identifier_list::const_iterator p = vars->begin();
1716   Expression* init = type == NULL ? receive : NULL;
1717   Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1718                                         type == NULL, &any_new);
1719   if (type == NULL && any_new && val_no->is_variable())
1720     val_no->var_value()->set_type_from_init_tuple();
1721   Expression* val_var = Expression::make_var_reference(val_no, location);
1722
1723   ++p;
1724   Type* var_type = type;
1725   if (var_type == NULL)
1726     var_type = Type::lookup_bool_type();
1727   Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1728                                     &any_new);
1729   Expression* received_var = Expression::make_var_reference(no, location);
1730
1731   if (is_coloneq && !any_new)
1732     error_at(location, "variables redeclared but no variable is new");
1733
1734   Statement* s = Statement::make_tuple_receive_assignment(val_var,
1735                                                           received_var,
1736                                                           receive->channel(),
1737                                                           false,
1738                                                           location);
1739
1740   if (!this->gogo_->in_global_scope())
1741     this->gogo_->add_statement(s);
1742   else if (!val_no->is_sink())
1743     {
1744       if (val_no->is_variable())
1745         val_no->var_value()->add_preinit_statement(this->gogo_, s);
1746     }
1747   else if (!no->is_sink())
1748     {
1749       if (no->is_variable())
1750         no->var_value()->add_preinit_statement(this->gogo_, s);
1751     }
1752   else
1753     {
1754       Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1755                                                       NULL, location);
1756       dummy->var_value()->add_preinit_statement(this->gogo_, s);
1757     }
1758
1759   return true;
1760 }
1761
1762 // See if we need to initialize a pair of values from a type guard
1763 // expression.  This returns true if we have set up the variables and
1764 // the initialization.
1765
1766 bool
1767 Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
1768                                  Type* type, Expression* expr,
1769                                  bool is_coloneq, source_location location)
1770 {
1771   Type_guard_expression* type_guard = expr->type_guard_expression();
1772   if (type_guard == NULL)
1773     return false;
1774   if (vars->size() != 2)
1775     return false;
1776
1777   // This is a type guard expression which is being assigned to two
1778   // variables.  Declare the variables, and then assign the results of
1779   // the type guard.
1780   bool any_new = false;
1781   Typed_identifier_list::const_iterator p = vars->begin();
1782   Type* var_type = type;
1783   if (var_type == NULL)
1784     var_type = type_guard->type();
1785   Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1786                                         &any_new);
1787   Expression* val_var = Expression::make_var_reference(val_no, location);
1788
1789   ++p;
1790   var_type = type;
1791   if (var_type == NULL)
1792     var_type = Type::lookup_bool_type();
1793   Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1794                                     &any_new);
1795   Expression* ok_var = Expression::make_var_reference(no, location);
1796
1797   Expression* texpr = type_guard->expr();
1798   Type* t = type_guard->type();
1799   Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
1800                                                              texpr, t,
1801                                                              location);
1802
1803   if (is_coloneq && !any_new)
1804     error_at(location, "variables redeclared but no variable is new");
1805
1806   if (!this->gogo_->in_global_scope())
1807     this->gogo_->add_statement(s);
1808   else if (!val_no->is_sink())
1809     {
1810       if (val_no->is_variable())
1811         val_no->var_value()->add_preinit_statement(this->gogo_, s);
1812     }
1813   else if (!no->is_sink())
1814     {
1815       if (no->is_variable())
1816         no->var_value()->add_preinit_statement(this->gogo_, s);
1817     }
1818   else
1819     {
1820       Named_object* dummy = this->create_dummy_global(type, NULL, location);
1821       dummy->var_value()->add_preinit_statement(this->gogo_, s);
1822     }
1823
1824   return true;
1825 }
1826
1827 // Create a single variable.  If IS_COLONEQ is true, we permit
1828 // redeclarations in the same block, and we set *IS_NEW when we find a
1829 // new variable which is not a redeclaration.
1830
1831 Named_object*
1832 Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
1833                 bool is_coloneq, bool type_from_init, bool* is_new)
1834 {
1835   source_location location = tid.location();
1836
1837   if (Gogo::is_sink_name(tid.name()))
1838     {
1839       if (!type_from_init && init != NULL)
1840         {
1841           if (!this->gogo_->in_global_scope())
1842             this->gogo_->add_statement(Statement::make_statement(init));
1843           else
1844             return this->create_dummy_global(type, init, location);
1845         }
1846       return this->gogo_->add_sink();
1847     }
1848
1849   if (is_coloneq)
1850     {
1851       Named_object* no = this->gogo_->lookup_in_block(tid.name());
1852       if (no != NULL
1853           && (no->is_variable() || no->is_result_variable()))
1854         {
1855           // INIT may be NULL even when IS_COLONEQ is true for cases
1856           // like v, ok := x.(int).
1857           if (!type_from_init && init != NULL)
1858             {
1859               Expression *v = Expression::make_var_reference(no, location);
1860               Statement *s = Statement::make_assignment(v, init, location);
1861               this->gogo_->add_statement(s);
1862             }
1863           return no;
1864         }
1865     }
1866   *is_new = true;
1867   Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
1868                                false, false, location);
1869   Named_object* no = this->gogo_->add_variable(tid.name(), var);
1870   if (!no->is_variable())
1871     {
1872       // The name is already defined, so we just gave an error.
1873       return this->gogo_->add_sink();
1874     }
1875   return no;
1876 }
1877
1878 // Create a dummy global variable to force an initializer to be run in
1879 // the right place.  This is used when a sink variable is initialized
1880 // at global scope.
1881
1882 Named_object*
1883 Parse::create_dummy_global(Type* type, Expression* init,
1884                            source_location location)
1885 {
1886   if (type == NULL && init == NULL)
1887     type = Type::lookup_bool_type();
1888   Variable* var = new Variable(type, init, true, false, false, location);
1889   static int count;
1890   char buf[30];
1891   snprintf(buf, sizeof buf, "_.%d", count);
1892   ++count;
1893   return this->gogo_->add_variable(buf, var);
1894 }
1895
1896 // SimpleVarDecl = identifier ":=" Expression .
1897
1898 // We've already seen the identifier.
1899
1900 // FIXME: We also have to implement
1901 //  IdentifierList ":=" ExpressionList
1902 // In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
1903 // tuple assignments here as well.
1904
1905 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
1906 // RangeClause.
1907
1908 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
1909 // guard (var := expr.("type") using the literal keyword "type").
1910
1911 void
1912 Parse::simple_var_decl_or_assignment(const std::string& name,
1913                                      source_location location,
1914                                      Range_clause* p_range_clause,
1915                                      Type_switch* p_type_switch)
1916 {
1917   Typed_identifier_list til;
1918   til.push_back(Typed_identifier(name, NULL, location));
1919
1920   // We've seen one identifier.  If we see a comma now, this could be
1921   // "a, *p = 1, 2".
1922   if (this->peek_token()->is_op(OPERATOR_COMMA))
1923     {
1924       go_assert(p_type_switch == NULL);
1925       while (true)
1926         {
1927           const Token* token = this->advance_token();
1928           if (!token->is_identifier())
1929             break;
1930
1931           std::string id = token->identifier();
1932           bool is_id_exported = token->is_identifier_exported();
1933           source_location id_location = token->location();
1934
1935           token = this->advance_token();
1936           if (!token->is_op(OPERATOR_COMMA))
1937             {
1938               if (token->is_op(OPERATOR_COLONEQ))
1939                 {
1940                   id = this->gogo_->pack_hidden_name(id, is_id_exported);
1941                   til.push_back(Typed_identifier(id, NULL, location));
1942                 }
1943               else
1944                 this->unget_token(Token::make_identifier_token(id,
1945                                                                is_id_exported,
1946                                                                id_location));
1947               break;
1948             }
1949
1950           id = this->gogo_->pack_hidden_name(id, is_id_exported);
1951           til.push_back(Typed_identifier(id, NULL, location));
1952         }
1953
1954       // We have a comma separated list of identifiers in TIL.  If the
1955       // next token is COLONEQ, then this is a simple var decl, and we
1956       // have the complete list of identifiers.  If the next token is
1957       // not COLONEQ, then the only valid parse is a tuple assignment.
1958       // The list of identifiers we have so far is really a list of
1959       // expressions.  There are more expressions following.
1960
1961       if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
1962         {
1963           Expression_list* exprs = new Expression_list;
1964           for (Typed_identifier_list::const_iterator p = til.begin();
1965                p != til.end();
1966                ++p)
1967             exprs->push_back(this->id_to_expression(p->name(),
1968                                                     p->location()));
1969
1970           Expression_list* more_exprs = this->expression_list(NULL, true);
1971           for (Expression_list::const_iterator p = more_exprs->begin();
1972                p != more_exprs->end();
1973                ++p)
1974             exprs->push_back(*p);
1975           delete more_exprs;
1976
1977           this->tuple_assignment(exprs, p_range_clause);
1978           return;
1979         }
1980     }
1981
1982   go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
1983   const Token* token = this->advance_token();
1984
1985   if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
1986     {
1987       this->range_clause_decl(&til, p_range_clause);
1988       return;
1989     }
1990
1991   Expression_list* init;
1992   if (p_type_switch == NULL)
1993     init = this->expression_list(NULL, false);
1994   else
1995     {
1996       bool is_type_switch = false;
1997       Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
1998                                           &is_type_switch);
1999       if (is_type_switch)
2000         {
2001           p_type_switch->found = true;
2002           p_type_switch->name = name;
2003           p_type_switch->location = location;
2004           p_type_switch->expr = expr;
2005           return;
2006         }
2007
2008       if (!this->peek_token()->is_op(OPERATOR_COMMA))
2009         {
2010           init = new Expression_list();
2011           init->push_back(expr);
2012         }
2013       else
2014         {
2015           this->advance_token();
2016           init = this->expression_list(expr, false);
2017         }
2018     }
2019
2020   this->init_vars(&til, NULL, init, true, location);
2021 }
2022
2023 // FunctionDecl = "func" identifier Signature [ Block ] .
2024 // MethodDecl = "func" Receiver identifier Signature [ Block ] .
2025
2026 // gcc extension:
2027 //   FunctionDecl = "func" identifier Signature
2028 //                    __asm__ "(" string_lit ")" .
2029 // This extension means a function whose real name is the identifier
2030 // inside the asm.
2031
2032 void
2033 Parse::function_decl()
2034 {
2035   go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2036   source_location location = this->location();
2037   const Token* token = this->advance_token();
2038
2039   Typed_identifier* rec = NULL;
2040   if (token->is_op(OPERATOR_LPAREN))
2041     {
2042       rec = this->receiver();
2043       token = this->peek_token();
2044     }
2045
2046   if (!token->is_identifier())
2047     {
2048       error_at(this->location(), "expected function name");
2049       return;
2050     }
2051
2052   std::string name =
2053     this->gogo_->pack_hidden_name(token->identifier(),
2054                                   token->is_identifier_exported());
2055
2056   this->advance_token();
2057
2058   Function_type* fntype = this->signature(rec, this->location());
2059   if (fntype == NULL)
2060     return;
2061
2062   Named_object* named_object = NULL;
2063
2064   if (this->peek_token()->is_keyword(KEYWORD_ASM))
2065     {
2066       if (!this->advance_token()->is_op(OPERATOR_LPAREN))
2067         {
2068           error_at(this->location(), "expected %<(%>");
2069           return;
2070         }
2071       token = this->advance_token();
2072       if (!token->is_string())
2073         {
2074           error_at(this->location(), "expected string");
2075           return;
2076         }
2077       std::string asm_name = token->string_value();
2078       if (!this->advance_token()->is_op(OPERATOR_RPAREN))
2079         {
2080           error_at(this->location(), "expected %<)%>");
2081           return;
2082         }
2083       this->advance_token();
2084       if (!Gogo::is_sink_name(name))
2085         {
2086           named_object = this->gogo_->declare_function(name, fntype, location);
2087           if (named_object->is_function_declaration())
2088             named_object->func_declaration_value()->set_asm_name(asm_name);
2089         }
2090     }
2091
2092   // Check for the easy error of a newline before the opening brace.
2093   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
2094     {
2095       source_location semi_loc = this->location();
2096       if (this->advance_token()->is_op(OPERATOR_LCURLY))
2097         error_at(this->location(),
2098                  "unexpected semicolon or newline before %<{%>");
2099       else
2100         this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
2101                                                      semi_loc));
2102     }
2103
2104   if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2105     {
2106       if (named_object == NULL && !Gogo::is_sink_name(name))
2107         this->gogo_->declare_function(name, fntype, location);
2108     }
2109   else
2110     {
2111       this->gogo_->start_function(name, fntype, true, location);
2112       source_location end_loc = this->block();
2113       this->gogo_->finish_function(end_loc);
2114     }
2115 }
2116
2117 // Receiver     = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
2118 // BaseTypeName = identifier .
2119
2120 Typed_identifier*
2121 Parse::receiver()
2122 {
2123   go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
2124
2125   std::string name;
2126   const Token* token = this->advance_token();
2127   source_location location = token->location();
2128   if (!token->is_op(OPERATOR_MULT))
2129     {
2130       if (!token->is_identifier())
2131         {
2132           error_at(this->location(), "method has no receiver");
2133           while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2134             token = this->advance_token();
2135           if (!token->is_eof())
2136             this->advance_token();
2137           return NULL;
2138         }
2139       name = token->identifier();
2140       bool is_exported = token->is_identifier_exported();
2141       token = this->advance_token();
2142       if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN))
2143         {
2144           // An identifier followed by something other than a dot or a
2145           // right parenthesis must be a receiver name followed by a
2146           // type.
2147           name = this->gogo_->pack_hidden_name(name, is_exported);
2148         }
2149       else
2150         {
2151           // This must be a type name.
2152           this->unget_token(Token::make_identifier_token(name, is_exported,
2153                                                          location));
2154           token = this->peek_token();
2155           name.clear();
2156         }
2157     }
2158
2159   // Here the receiver name is in NAME (it is empty if the receiver is
2160   // unnamed) and TOKEN is the first token in the type.
2161
2162   bool is_pointer = false;
2163   if (token->is_op(OPERATOR_MULT))
2164     {
2165       is_pointer = true;
2166       token = this->advance_token();
2167     }
2168
2169   if (!token->is_identifier())
2170     {
2171       error_at(this->location(), "expected receiver name or type");
2172       int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0;
2173       while (!token->is_eof())
2174         {
2175           token = this->advance_token();
2176           if (token->is_op(OPERATOR_LPAREN))
2177             ++c;
2178           else if (token->is_op(OPERATOR_RPAREN))
2179             {
2180               if (c == 0)
2181                 break;
2182               --c;
2183             }
2184         }
2185       if (!token->is_eof())
2186         this->advance_token();
2187       return NULL;
2188     }
2189
2190   Type* type = this->type_name(true);
2191
2192   if (is_pointer && !type->is_error_type())
2193     type = Type::make_pointer_type(type);
2194
2195   if (this->peek_token()->is_op(OPERATOR_RPAREN))
2196     this->advance_token();
2197   else
2198     {
2199       if (this->peek_token()->is_op(OPERATOR_COMMA))
2200         error_at(this->location(), "method has multiple receivers");
2201       else
2202         error_at(this->location(), "expected %<)%>");
2203       while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2204         token = this->advance_token();
2205       if (!token->is_eof())
2206         this->advance_token();
2207       return NULL;
2208     }
2209
2210   return new Typed_identifier(name, type, location);
2211 }
2212
2213 // Operand    = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2214 // Literal    = BasicLit | CompositeLit | FunctionLit .
2215 // BasicLit   = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2216
2217 // If MAY_BE_SINK is true, this operand may be "_".
2218
2219 Expression*
2220 Parse::operand(bool may_be_sink)
2221 {
2222   const Token* token = this->peek_token();
2223   Expression* ret;
2224   switch (token->classification())
2225     {
2226     case Token::TOKEN_IDENTIFIER:
2227       {
2228         source_location location = token->location();
2229         std::string id = token->identifier();
2230         bool is_exported = token->is_identifier_exported();
2231         std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2232
2233         Named_object* in_function;
2234         Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2235
2236         Package* package = NULL;
2237         if (named_object != NULL && named_object->is_package())
2238           {
2239             if (!this->advance_token()->is_op(OPERATOR_DOT)
2240                 || !this->advance_token()->is_identifier())
2241               {
2242                 error_at(location, "unexpected reference to package");
2243                 return Expression::make_error(location);
2244               }
2245             package = named_object->package_value();
2246             package->set_used();
2247             id = this->peek_token()->identifier();
2248             is_exported = this->peek_token()->is_identifier_exported();
2249             packed = this->gogo_->pack_hidden_name(id, is_exported);
2250             named_object = package->lookup(packed);
2251             location = this->location();
2252             go_assert(in_function == NULL);
2253           }
2254
2255         this->advance_token();
2256
2257         if (named_object != NULL
2258             && named_object->is_type()
2259             && !named_object->type_value()->is_visible())
2260           {
2261             go_assert(package != NULL);
2262             error_at(location, "invalid reference to hidden type %<%s.%s%>",
2263                      Gogo::message_name(package->name()).c_str(),
2264                      Gogo::message_name(id).c_str());
2265             return Expression::make_error(location);
2266           }
2267
2268
2269         if (named_object == NULL)
2270           {
2271             if (package != NULL)
2272               {
2273                 std::string n1 = Gogo::message_name(package->name());
2274                 std::string n2 = Gogo::message_name(id);
2275                 if (!is_exported)
2276                   error_at(location,
2277                            ("invalid reference to unexported identifier "
2278                             "%<%s.%s%>"),
2279                            n1.c_str(), n2.c_str());
2280                 else
2281                   error_at(location,
2282                            "reference to undefined identifier %<%s.%s%>",
2283                            n1.c_str(), n2.c_str());
2284                 return Expression::make_error(location);
2285               }
2286
2287             named_object = this->gogo_->add_unknown_name(packed, location);
2288           }
2289
2290         if (in_function != NULL
2291             && in_function != this->gogo_->current_function()
2292             && (named_object->is_variable()
2293                 || named_object->is_result_variable()))
2294           return this->enclosing_var_reference(in_function, named_object,
2295                                                location);
2296
2297         switch (named_object->classification())
2298           {
2299           case Named_object::NAMED_OBJECT_CONST:
2300             return Expression::make_const_reference(named_object, location);
2301           case Named_object::NAMED_OBJECT_TYPE:
2302             return Expression::make_type(named_object->type_value(), location);
2303           case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2304             {
2305               Type* t = Type::make_forward_declaration(named_object);
2306               return Expression::make_type(t, location);
2307             }
2308           case Named_object::NAMED_OBJECT_VAR:
2309           case Named_object::NAMED_OBJECT_RESULT_VAR:
2310             return Expression::make_var_reference(named_object, location);
2311           case Named_object::NAMED_OBJECT_SINK:
2312             if (may_be_sink)
2313               return Expression::make_sink(location);
2314             else
2315               {
2316                 error_at(location, "cannot use _ as value");
2317                 return Expression::make_error(location);
2318               }
2319           case Named_object::NAMED_OBJECT_FUNC:
2320           case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2321             return Expression::make_func_reference(named_object, NULL,
2322                                                    location);
2323           case Named_object::NAMED_OBJECT_UNKNOWN:
2324             return Expression::make_unknown_reference(named_object, location);
2325           default:
2326             go_unreachable();
2327           }
2328       }
2329       go_unreachable();
2330
2331     case Token::TOKEN_STRING:
2332       ret = Expression::make_string(token->string_value(), token->location());
2333       this->advance_token();
2334       return ret;
2335
2336     case Token::TOKEN_INTEGER:
2337       ret = Expression::make_integer(token->integer_value(), NULL,
2338                                      token->location());
2339       this->advance_token();
2340       return ret;
2341
2342     case Token::TOKEN_FLOAT:
2343       ret = Expression::make_float(token->float_value(), NULL,
2344                                    token->location());
2345       this->advance_token();
2346       return ret;
2347
2348     case Token::TOKEN_IMAGINARY:
2349       {
2350         mpfr_t zero;
2351         mpfr_init_set_ui(zero, 0, GMP_RNDN);
2352         ret = Expression::make_complex(&zero, token->imaginary_value(),
2353                                        NULL, token->location());
2354         mpfr_clear(zero);
2355         this->advance_token();
2356         return ret;
2357       }
2358
2359     case Token::TOKEN_KEYWORD:
2360       switch (token->keyword())
2361         {
2362         case KEYWORD_FUNC:
2363           return this->function_lit();
2364         case KEYWORD_CHAN:
2365         case KEYWORD_INTERFACE:
2366         case KEYWORD_MAP:
2367         case KEYWORD_STRUCT:
2368           {
2369             source_location location = token->location();
2370             return Expression::make_type(this->type(), location);
2371           }
2372         default:
2373           break;
2374         }
2375       break;
2376
2377     case Token::TOKEN_OPERATOR:
2378       if (token->is_op(OPERATOR_LPAREN))
2379         {
2380           this->advance_token();
2381           ret = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2382           if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2383             error_at(this->location(), "missing %<)%>");
2384           else
2385             this->advance_token();
2386           return ret;
2387         }
2388       else if (token->is_op(OPERATOR_LSQUARE))
2389         {
2390           // Here we call array_type directly, as this is the only
2391           // case where an ellipsis is permitted for an array type.
2392           source_location location = token->location();
2393           return Expression::make_type(this->array_type(true), location);
2394         }
2395       break;
2396
2397     default:
2398       break;
2399     }
2400
2401   error_at(this->location(), "expected operand");
2402   return Expression::make_error(this->location());
2403 }
2404
2405 // Handle a reference to a variable in an enclosing function.  We add
2406 // it to a list of such variables.  We return a reference to a field
2407 // in a struct which will be passed on the static chain when calling
2408 // the current function.
2409
2410 Expression*
2411 Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2412                                source_location location)
2413 {
2414   go_assert(var->is_variable() || var->is_result_variable());
2415
2416   Named_object* this_function = this->gogo_->current_function();
2417   Named_object* closure = this_function->func_value()->closure_var();
2418
2419   Enclosing_var ev(var, in_function, this->enclosing_vars_.size());
2420   std::pair<Enclosing_vars::iterator, bool> ins =
2421     this->enclosing_vars_.insert(ev);
2422   if (ins.second)
2423     {
2424       // This is a variable we have not seen before.  Add a new field
2425       // to the closure type.
2426       this_function->func_value()->add_closure_field(var, location);
2427     }
2428
2429   Expression* closure_ref = Expression::make_var_reference(closure,
2430                                                            location);
2431   closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location);
2432
2433   // The closure structure holds pointers to the variables, so we need
2434   // to introduce an indirection.
2435   Expression* e = Expression::make_field_reference(closure_ref,
2436                                                    ins.first->index(),
2437                                                    location);
2438   e = Expression::make_unary(OPERATOR_MULT, e, location);
2439   return e;
2440 }
2441
2442 // CompositeLit  = LiteralType LiteralValue .
2443 // LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
2444 //                 SliceType | MapType | TypeName .
2445 // LiteralValue  = "{" [ ElementList [ "," ] ] "}" .
2446 // ElementList   = Element { "," Element } .
2447 // Element       = [ Key ":" ] Value .
2448 // Key           = FieldName | ElementIndex .
2449 // FieldName     = identifier .
2450 // ElementIndex  = Expression .
2451 // Value         = Expression | LiteralValue .
2452
2453 // We have already seen the type if there is one, and we are now
2454 // looking at the LiteralValue.  The case "[" "..."  "]" ElementType
2455 // will be seen here as an array type whose length is "nil".  The
2456 // DEPTH parameter is non-zero if this is an embedded composite
2457 // literal and the type was omitted.  It gives the number of steps up
2458 // to the type which was provided.  E.g., in [][]int{{1}} it will be
2459 // 1.  In [][][]int{{{1}}} it will be 2.
2460
2461 Expression*
2462 Parse::composite_lit(Type* type, int depth, source_location location)
2463 {
2464   go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2465   this->advance_token();
2466
2467   if (this->peek_token()->is_op(OPERATOR_RCURLY))
2468     {
2469       this->advance_token();
2470       return Expression::make_composite_literal(type, depth, false, NULL,
2471                                                 location);
2472     }
2473
2474   bool has_keys = false;
2475   Expression_list* vals = new Expression_list;
2476   while (true)
2477     {
2478       Expression* val;
2479       bool is_type_omitted = false;
2480
2481       const Token* token = this->peek_token();
2482
2483       if (token->is_identifier())
2484         {
2485           std::string identifier = token->identifier();
2486           bool is_exported = token->is_identifier_exported();
2487           source_location location = token->location();
2488
2489           if (this->advance_token()->is_op(OPERATOR_COLON))
2490             {
2491               // This may be a field name.  We don't know for sure--it
2492               // could also be an expression for an array index.  We
2493               // don't want to parse it as an expression because may
2494               // trigger various errors, e.g., if this identifier
2495               // happens to be the name of a package.
2496               Gogo* gogo = this->gogo_;
2497               val = this->id_to_expression(gogo->pack_hidden_name(identifier,
2498                                                                   is_exported),
2499                                            location);
2500             }
2501           else
2502             {
2503               this->unget_token(Token::make_identifier_token(identifier,
2504                                                              is_exported,
2505                                                              location));
2506               val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2507             }
2508         }
2509       else if (!token->is_op(OPERATOR_LCURLY))
2510         val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2511       else
2512         {
2513           // This must be a composite literal inside another composite
2514           // literal, with the type omitted for the inner one.
2515           val = this->composite_lit(type, depth + 1, token->location());
2516           is_type_omitted = true;
2517         }
2518
2519       token = this->peek_token();
2520       if (!token->is_op(OPERATOR_COLON))
2521         {
2522           if (has_keys)
2523             vals->push_back(NULL);
2524         }
2525       else
2526         {
2527           if (is_type_omitted && !val->is_error_expression())
2528             {
2529               error_at(this->location(), "unexpected %<:%>");
2530               val = Expression::make_error(this->location());
2531             }
2532
2533           this->advance_token();
2534
2535           if (!has_keys && !vals->empty())
2536             {
2537               Expression_list* newvals = new Expression_list;
2538               for (Expression_list::const_iterator p = vals->begin();
2539                    p != vals->end();
2540                    ++p)
2541                 {
2542                   newvals->push_back(NULL);
2543                   newvals->push_back(*p);
2544                 }
2545               delete vals;
2546               vals = newvals;
2547             }
2548           has_keys = true;
2549
2550           if (val->unknown_expression() != NULL)
2551             val->unknown_expression()->set_is_composite_literal_key();
2552
2553           vals->push_back(val);
2554
2555           if (!token->is_op(OPERATOR_LCURLY))
2556             val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2557           else
2558             {
2559               // This must be a composite literal inside another
2560               // composite literal, with the type omitted for the
2561               // inner one.
2562               val = this->composite_lit(type, depth + 1, token->location());
2563             }
2564
2565           token = this->peek_token();
2566         }
2567
2568       vals->push_back(val);
2569
2570       if (token->is_op(OPERATOR_COMMA))
2571         {
2572           if (this->advance_token()->is_op(OPERATOR_RCURLY))
2573             {
2574               this->advance_token();
2575               break;
2576             }
2577         }
2578       else if (token->is_op(OPERATOR_RCURLY))
2579         {
2580           this->advance_token();
2581           break;
2582         }
2583       else
2584         {
2585           error_at(this->location(), "expected %<,%> or %<}%>");
2586
2587           int depth = 0;
2588           while (!token->is_eof()
2589                  && (depth > 0 || !token->is_op(OPERATOR_RCURLY)))
2590             {
2591               if (token->is_op(OPERATOR_LCURLY))
2592                 ++depth;
2593               else if (token->is_op(OPERATOR_RCURLY))
2594                 --depth;
2595               token = this->advance_token();
2596             }
2597           if (token->is_op(OPERATOR_RCURLY))
2598             this->advance_token();
2599
2600           return Expression::make_error(location);
2601         }
2602     }
2603
2604   return Expression::make_composite_literal(type, depth, has_keys, vals,
2605                                             location);
2606 }
2607
2608 // FunctionLit = "func" Signature Block .
2609
2610 Expression*
2611 Parse::function_lit()
2612 {
2613   source_location location = this->location();
2614   go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2615   this->advance_token();
2616
2617   Enclosing_vars hold_enclosing_vars;
2618   hold_enclosing_vars.swap(this->enclosing_vars_);
2619
2620   Function_type* type = this->signature(NULL, location);
2621   if (type == NULL)
2622     type = Type::make_function_type(NULL, NULL, NULL, location);
2623
2624   // For a function literal, the next token must be a '{'.  If we
2625   // don't see that, then we may have a type expression.
2626   if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2627     return Expression::make_type(type, location);
2628
2629   Bc_stack* hold_break_stack = this->break_stack_;
2630   Bc_stack* hold_continue_stack = this->continue_stack_;
2631   this->break_stack_ = NULL;
2632   this->continue_stack_ = NULL;
2633
2634   Named_object* no = this->gogo_->start_function("", type, true, location);
2635
2636   source_location end_loc = this->block();
2637
2638   this->gogo_->finish_function(end_loc);
2639
2640   if (this->break_stack_ != NULL)
2641     delete this->break_stack_;
2642   if (this->continue_stack_ != NULL)
2643     delete this->continue_stack_;
2644   this->break_stack_ = hold_break_stack;
2645   this->continue_stack_ = hold_continue_stack;
2646
2647   hold_enclosing_vars.swap(this->enclosing_vars_);
2648
2649   Expression* closure = this->create_closure(no, &hold_enclosing_vars,
2650                                              location);
2651
2652   return Expression::make_func_reference(no, closure, location);
2653 }
2654
2655 // Create a closure for the nested function FUNCTION.  This is based
2656 // on ENCLOSING_VARS, which is a list of all variables defined in
2657 // enclosing functions and referenced from FUNCTION.  A closure is the
2658 // address of a struct which contains the addresses of all the
2659 // referenced variables.  This returns NULL if no closure is required.
2660
2661 Expression*
2662 Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
2663                       source_location location)
2664 {
2665   if (enclosing_vars->empty())
2666     return NULL;
2667
2668   // Get the variables in order by their field index.
2669
2670   size_t enclosing_var_count = enclosing_vars->size();
2671   std::vector<Enclosing_var> ev(enclosing_var_count);
2672   for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
2673        p != enclosing_vars->end();
2674        ++p)
2675     ev[p->index()] = *p;
2676
2677   // Build an initializer for a composite literal of the closure's
2678   // type.
2679
2680   Named_object* enclosing_function = this->gogo_->current_function();
2681   Expression_list* initializer = new Expression_list;
2682   for (size_t i = 0; i < enclosing_var_count; ++i)
2683     {
2684       go_assert(ev[i].index() == i);
2685       Named_object* var = ev[i].var();
2686       Expression* ref;
2687       if (ev[i].in_function() == enclosing_function)
2688         ref = Expression::make_var_reference(var, location);
2689       else
2690         ref = this->enclosing_var_reference(ev[i].in_function(), var,
2691                                             location);
2692       Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
2693                                                    location);
2694       initializer->push_back(refaddr);
2695     }
2696
2697   Named_object* closure_var = function->func_value()->closure_var();
2698   Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
2699   Expression* cv = Expression::make_struct_composite_literal(st, initializer,
2700                                                              location);
2701   return Expression::make_heap_composite(cv, location);
2702 }
2703
2704 // PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
2705
2706 // If MAY_BE_SINK is true, this expression may be "_".
2707
2708 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
2709 // literal.
2710
2711 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2712 // guard (var := expr.("type") using the literal keyword "type").
2713
2714 Expression*
2715 Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
2716                     bool* is_type_switch)
2717 {
2718   source_location start_loc = this->location();
2719   bool is_parenthesized = this->peek_token()->is_op(OPERATOR_LPAREN);
2720
2721   Expression* ret = this->operand(may_be_sink);
2722
2723   // An unknown name followed by a curly brace must be a composite
2724   // literal, and the unknown name must be a type.
2725   if (may_be_composite_lit
2726       && !is_parenthesized
2727       && ret->unknown_expression() != NULL
2728       && this->peek_token()->is_op(OPERATOR_LCURLY))
2729     {
2730       Named_object* no = ret->unknown_expression()->named_object();
2731       Type* type = Type::make_forward_declaration(no);
2732       ret = Expression::make_type(type, ret->location());
2733     }
2734
2735   // We handle composite literals and type casts here, as it is the
2736   // easiest way to handle types which are in parentheses, as in
2737   // "((uint))(1)".
2738   if (ret->is_type_expression())
2739     {
2740       if (this->peek_token()->is_op(OPERATOR_LCURLY))
2741         {
2742           if (is_parenthesized)
2743             error_at(start_loc,
2744                      "cannot parenthesize type in composite literal");
2745           ret = this->composite_lit(ret->type(), 0, ret->location());
2746         }
2747       else if (this->peek_token()->is_op(OPERATOR_LPAREN))
2748         {
2749           source_location loc = this->location();
2750           this->advance_token();
2751           Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
2752                                               NULL);
2753           if (this->peek_token()->is_op(OPERATOR_ELLIPSIS))
2754             {
2755               error_at(this->location(),
2756                        "invalid use of %<...%> in type conversion");
2757               this->advance_token();
2758             }
2759           if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2760             error_at(this->location(), "expected %<)%>");
2761           else
2762             this->advance_token();
2763           if (expr->is_error_expression())
2764             return expr;
2765           ret = Expression::make_cast(ret->type(), expr, loc);
2766         }
2767     }
2768
2769   while (true)
2770     {
2771       const Token* token = this->peek_token();
2772       if (token->is_op(OPERATOR_LPAREN))
2773         ret = this->call(this->verify_not_sink(ret));
2774       else if (token->is_op(OPERATOR_DOT))
2775         {
2776           ret = this->selector(this->verify_not_sink(ret), is_type_switch);
2777           if (is_type_switch != NULL && *is_type_switch)
2778             break;
2779         }
2780       else if (token->is_op(OPERATOR_LSQUARE))
2781         ret = this->index(this->verify_not_sink(ret));
2782       else
2783         break;
2784     }
2785
2786   return ret;
2787 }
2788
2789 // Selector = "." identifier .
2790 // TypeGuard = "." "(" QualifiedIdent ")" .
2791
2792 // Note that Operand can expand to QualifiedIdent, which contains a
2793 // ".".  That is handled directly in operand when it sees a package
2794 // name.
2795
2796 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2797 // guard (var := expr.("type") using the literal keyword "type").
2798
2799 Expression*
2800 Parse::selector(Expression* left, bool* is_type_switch)
2801 {
2802   go_assert(this->peek_token()->is_op(OPERATOR_DOT));
2803   source_location location = this->location();
2804
2805   const Token* token = this->advance_token();
2806   if (token->is_identifier())
2807     {
2808       // This could be a field in a struct, or a method in an
2809       // interface, or a method associated with a type.  We can't know
2810       // which until we have seen all the types.
2811       std::string name =
2812         this->gogo_->pack_hidden_name(token->identifier(),
2813                                       token->is_identifier_exported());
2814       if (token->identifier() == "_")
2815         {
2816           error_at(this->location(), "invalid use of %<_%>");
2817           name = this->gogo_->pack_hidden_name("blank", false);
2818         }
2819       this->advance_token();
2820       return Expression::make_selector(left, name, location);
2821     }
2822   else if (token->is_op(OPERATOR_LPAREN))
2823     {
2824       this->advance_token();
2825       Type* type = NULL;
2826       if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
2827         type = this->type();
2828       else
2829         {
2830           if (is_type_switch != NULL)
2831             *is_type_switch = true;
2832           else
2833             {
2834               error_at(this->location(),
2835                        "use of %<.(type)%> outside type switch");
2836               type = Type::make_error_type();
2837             }
2838           this->advance_token();
2839         }
2840       if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2841         error_at(this->location(), "missing %<)%>");
2842       else
2843         this->advance_token();
2844       if (is_type_switch != NULL && *is_type_switch)
2845         return left;
2846       return Expression::make_type_guard(left, type, location);
2847     }
2848   else
2849     {
2850       error_at(this->location(), "expected identifier or %<(%>");
2851       return left;
2852     }
2853 }
2854
2855 // Index          = "[" Expression "]" .
2856 // Slice          = "[" Expression ":" [ Expression ] "]" .
2857
2858 Expression*
2859 Parse::index(Expression* expr)
2860 {
2861   source_location location = this->location();
2862   go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
2863   this->advance_token();
2864
2865   Expression* start;
2866   if (!this->peek_token()->is_op(OPERATOR_COLON))
2867     start = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2868   else
2869     {
2870       mpz_t zero;
2871       mpz_init_set_ui(zero, 0);
2872       start = Expression::make_integer(&zero, NULL, location);
2873       mpz_clear(zero);
2874     }
2875
2876   Expression* end = NULL;
2877   if (this->peek_token()->is_op(OPERATOR_COLON))
2878     {
2879       // We use nil to indicate a missing high expression.
2880       if (this->advance_token()->is_op(OPERATOR_RSQUARE))
2881         end = Expression::make_nil(this->location());
2882       else
2883         end = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2884     }
2885   if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
2886     error_at(this->location(), "missing %<]%>");
2887   else
2888     this->advance_token();
2889   return Expression::make_index(expr, start, end, location);
2890 }
2891
2892 // Call           = "(" [ ArgumentList [ "," ] ] ")" .
2893 // ArgumentList   = ExpressionList [ "..." ] .
2894
2895 Expression*
2896 Parse::call(Expression* func)
2897 {
2898   go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
2899   Expression_list* args = NULL;
2900   bool is_varargs = false;
2901   const Token* token = this->advance_token();
2902   if (!token->is_op(OPERATOR_RPAREN))
2903     {
2904       args = this->expression_list(NULL, false);
2905       token = this->peek_token();
2906       if (token->is_op(OPERATOR_ELLIPSIS))
2907         {
2908           is_varargs = true;
2909           token = this->advance_token();
2910         }
2911     }
2912   if (token->is_op(OPERATOR_COMMA))
2913     token = this->advance_token();
2914   if (!token->is_op(OPERATOR_RPAREN))
2915     error_at(this->location(), "missing %<)%>");
2916   else
2917     this->advance_token();
2918   if (func->is_error_expression())
2919     return func;
2920   return Expression::make_call(func, args, is_varargs, func->location());
2921 }
2922
2923 // Return an expression for a single unqualified identifier.
2924
2925 Expression*
2926 Parse::id_to_expression(const std::string& name, source_location location)
2927 {
2928   Named_object* in_function;
2929   Named_object* named_object = this->gogo_->lookup(name, &in_function);
2930   if (named_object == NULL)
2931     named_object = this->gogo_->add_unknown_name(name, location);
2932
2933   if (in_function != NULL
2934       && in_function != this->gogo_->current_function()
2935       && (named_object->is_variable() || named_object->is_result_variable()))
2936     return this->enclosing_var_reference(in_function, named_object,
2937                                          location);
2938
2939   switch (named_object->classification())
2940     {
2941     case Named_object::NAMED_OBJECT_CONST:
2942       return Expression::make_const_reference(named_object, location);
2943     case Named_object::NAMED_OBJECT_VAR:
2944     case Named_object::NAMED_OBJECT_RESULT_VAR:
2945       return Expression::make_var_reference(named_object, location);
2946     case Named_object::NAMED_OBJECT_SINK:
2947       return Expression::make_sink(location);
2948     case Named_object::NAMED_OBJECT_FUNC:
2949     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2950       return Expression::make_func_reference(named_object, NULL, location);
2951     case Named_object::NAMED_OBJECT_UNKNOWN:
2952       return Expression::make_unknown_reference(named_object, location);
2953     case Named_object::NAMED_OBJECT_PACKAGE:
2954     case Named_object::NAMED_OBJECT_TYPE:
2955     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2956       // These cases can arise for a field name in a composite
2957       // literal.
2958       return Expression::make_unknown_reference(named_object, location);
2959     default:
2960       error_at(this->location(), "unexpected type of identifier");
2961       return Expression::make_error(location);
2962     }
2963 }
2964
2965 // Expression = UnaryExpr { binary_op Expression } .
2966
2967 // PRECEDENCE is the precedence of the current operator.
2968
2969 // If MAY_BE_SINK is true, this expression may be "_".
2970
2971 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
2972 // literal.
2973
2974 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2975 // guard (var := expr.("type") using the literal keyword "type").
2976
2977 Expression*
2978 Parse::expression(Precedence precedence, bool may_be_sink,
2979                   bool may_be_composite_lit, bool* is_type_switch)
2980 {
2981   Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
2982                                       is_type_switch);
2983
2984   while (true)
2985     {
2986       if (is_type_switch != NULL && *is_type_switch)
2987         return left;
2988
2989       const Token* token = this->peek_token();
2990       if (token->classification() != Token::TOKEN_OPERATOR)
2991         {
2992           // Not a binary_op.
2993           return left;
2994         }
2995
2996       Precedence right_precedence;
2997       switch (token->op())
2998         {
2999         case OPERATOR_OROR:
3000           right_precedence = PRECEDENCE_OROR;
3001           break;
3002         case OPERATOR_ANDAND:
3003           right_precedence = PRECEDENCE_ANDAND;
3004           break;
3005         case OPERATOR_EQEQ:
3006         case OPERATOR_NOTEQ:
3007         case OPERATOR_LT:
3008         case OPERATOR_LE:
3009         case OPERATOR_GT:
3010         case OPERATOR_GE:
3011           right_precedence = PRECEDENCE_RELOP;
3012           break;
3013         case OPERATOR_PLUS:
3014         case OPERATOR_MINUS:
3015         case OPERATOR_OR:
3016         case OPERATOR_XOR:
3017           right_precedence = PRECEDENCE_ADDOP;
3018           break;
3019         case OPERATOR_MULT:
3020         case OPERATOR_DIV:
3021         case OPERATOR_MOD:
3022         case OPERATOR_LSHIFT:
3023         case OPERATOR_RSHIFT:
3024         case OPERATOR_AND:
3025         case OPERATOR_BITCLEAR:
3026           right_precedence = PRECEDENCE_MULOP;
3027           break;
3028         default:
3029           right_precedence = PRECEDENCE_INVALID;
3030           break;
3031         }
3032
3033       if (right_precedence == PRECEDENCE_INVALID)
3034         {
3035           // Not a binary_op.
3036           return left;
3037         }
3038
3039       Operator op = token->op();
3040       source_location binop_location = token->location();
3041
3042       if (precedence >= right_precedence)
3043         {
3044           // We've already seen A * B, and we see + C.  We want to
3045           // return so that A * B becomes a group.
3046           return left;
3047         }
3048
3049       this->advance_token();
3050
3051       left = this->verify_not_sink(left);
3052       Expression* right = this->expression(right_precedence, false,
3053                                            may_be_composite_lit,
3054                                            NULL);
3055       left = Expression::make_binary(op, left, right, binop_location);
3056     }
3057 }
3058
3059 bool
3060 Parse::expression_may_start_here()
3061 {
3062   const Token* token = this->peek_token();
3063   switch (token->classification())
3064     {
3065     case Token::TOKEN_INVALID:
3066     case Token::TOKEN_EOF:
3067       return false;
3068     case Token::TOKEN_KEYWORD:
3069       switch (token->keyword())
3070         {
3071         case KEYWORD_CHAN:
3072         case KEYWORD_FUNC:
3073         case KEYWORD_MAP:
3074         case KEYWORD_STRUCT:
3075         case KEYWORD_INTERFACE:
3076           return true;
3077         default:
3078           return false;
3079         }
3080     case Token::TOKEN_IDENTIFIER:
3081       return true;
3082     case Token::TOKEN_STRING:
3083       return true;
3084     case Token::TOKEN_OPERATOR:
3085       switch (token->op())
3086         {
3087         case OPERATOR_PLUS:
3088         case OPERATOR_MINUS:
3089         case OPERATOR_NOT:
3090         case OPERATOR_XOR:
3091         case OPERATOR_MULT:
3092         case OPERATOR_CHANOP:
3093         case OPERATOR_AND:
3094         case OPERATOR_LPAREN:
3095         case OPERATOR_LSQUARE:
3096           return true;
3097         default:
3098           return false;
3099         }
3100     case Token::TOKEN_INTEGER:
3101     case Token::TOKEN_FLOAT:
3102     case Token::TOKEN_IMAGINARY:
3103       return true;
3104     default:
3105       go_unreachable();
3106     }
3107 }
3108
3109 // UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3110
3111 // If MAY_BE_SINK is true, this expression may be "_".
3112
3113 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3114 // literal.
3115
3116 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3117 // guard (var := expr.("type") using the literal keyword "type").
3118
3119 Expression*
3120 Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3121                   bool* is_type_switch)
3122 {
3123   const Token* token = this->peek_token();
3124   if (token->is_op(OPERATOR_PLUS)
3125       || token->is_op(OPERATOR_MINUS)
3126       || token->is_op(OPERATOR_NOT)
3127       || token->is_op(OPERATOR_XOR)
3128       || token->is_op(OPERATOR_CHANOP)
3129       || token->is_op(OPERATOR_MULT)
3130       || token->is_op(OPERATOR_AND))
3131     {
3132       source_location location = token->location();
3133       Operator op = token->op();
3134       this->advance_token();
3135
3136       if (op == OPERATOR_CHANOP
3137           && this->peek_token()->is_keyword(KEYWORD_CHAN))
3138         {
3139           // This is "<- chan" which must be the start of a type.
3140           this->unget_token(Token::make_operator_token(op, location));
3141           return Expression::make_type(this->type(), location);
3142         }
3143
3144       Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL);
3145       if (expr->is_error_expression())
3146         ;
3147       else if (op == OPERATOR_MULT && expr->is_type_expression())
3148         expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3149                                      location);
3150       else if (op == OPERATOR_AND && expr->is_composite_literal())
3151         expr = Expression::make_heap_composite(expr, location);
3152       else if (op != OPERATOR_CHANOP)
3153         expr = Expression::make_unary(op, expr, location);
3154       else
3155         expr = Expression::make_receive(expr, location);
3156       return expr;
3157     }
3158   else
3159     return this->primary_expr(may_be_sink, may_be_composite_lit,
3160                               is_type_switch);
3161 }
3162
3163 // Statement =
3164 //      Declaration | LabeledStmt | SimpleStmt |
3165 //      GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3166 //      FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3167 //      DeferStmt .
3168
3169 // LABEL is the label of this statement if it has one.
3170
3171 void
3172 Parse::statement(Label* label)
3173 {
3174   const Token* token = this->peek_token();
3175   switch (token->classification())
3176     {
3177     case Token::TOKEN_KEYWORD:
3178       {
3179         switch (token->keyword())
3180           {
3181           case KEYWORD_CONST:
3182           case KEYWORD_TYPE:
3183           case KEYWORD_VAR:
3184             this->declaration();
3185             break;
3186           case KEYWORD_FUNC:
3187           case KEYWORD_MAP:
3188           case KEYWORD_STRUCT:
3189           case KEYWORD_INTERFACE:
3190             this->simple_stat(true, NULL, NULL, NULL);
3191             break;
3192           case KEYWORD_GO:
3193           case KEYWORD_DEFER:
3194             this->go_or_defer_stat();
3195             break;
3196           case KEYWORD_RETURN:
3197             this->return_stat();
3198             break;
3199           case KEYWORD_BREAK:
3200             this->break_stat();
3201             break;
3202           case KEYWORD_CONTINUE:
3203             this->continue_stat();
3204             break;
3205           case KEYWORD_GOTO:
3206             this->goto_stat();
3207             break;
3208           case KEYWORD_IF:
3209             this->if_stat();
3210             break;
3211           case KEYWORD_SWITCH:
3212             this->switch_stat(label);
3213             break;
3214           case KEYWORD_SELECT:
3215             this->select_stat(label);
3216             break;
3217           case KEYWORD_FOR:
3218             this->for_stat(label);
3219             break;
3220           default:
3221             error_at(this->location(), "expected statement");
3222             this->advance_token();
3223             break;
3224           }
3225       }
3226       break;
3227
3228     case Token::TOKEN_IDENTIFIER:
3229       {
3230         std::string identifier = token->identifier();
3231         bool is_exported = token->is_identifier_exported();
3232         source_location location = token->location();
3233         if (this->advance_token()->is_op(OPERATOR_COLON))
3234           {
3235             this->advance_token();
3236             this->labeled_stmt(identifier, location);
3237           }
3238         else
3239           {
3240             this->unget_token(Token::make_identifier_token(identifier,
3241                                                            is_exported,
3242                                                            location));
3243             this->simple_stat(true, NULL, NULL, NULL);
3244           }
3245       }
3246       break;
3247
3248     case Token::TOKEN_OPERATOR:
3249       if (token->is_op(OPERATOR_LCURLY))
3250         {
3251           source_location location = token->location();
3252           this->gogo_->start_block(location);
3253           source_location end_loc = this->block();
3254           this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3255                                  location);
3256         }
3257       else if (!token->is_op(OPERATOR_SEMICOLON))
3258         this->simple_stat(true, NULL, NULL, NULL);
3259       break;
3260
3261     case Token::TOKEN_STRING:
3262     case Token::TOKEN_INTEGER:
3263     case Token::TOKEN_FLOAT:
3264     case Token::TOKEN_IMAGINARY:
3265       this->simple_stat(true, NULL, NULL, NULL);
3266       break;
3267
3268     default:
3269       error_at(this->location(), "expected statement");
3270       this->advance_token();
3271       break;
3272     }
3273 }
3274
3275 bool
3276 Parse::statement_may_start_here()
3277 {
3278   const Token* token = this->peek_token();
3279   switch (token->classification())
3280     {
3281     case Token::TOKEN_KEYWORD:
3282       {
3283         switch (token->keyword())
3284           {
3285           case KEYWORD_CONST:
3286           case KEYWORD_TYPE:
3287           case KEYWORD_VAR:
3288           case KEYWORD_FUNC:
3289           case KEYWORD_MAP:
3290           case KEYWORD_STRUCT:
3291           case KEYWORD_INTERFACE:
3292           case KEYWORD_GO:
3293           case KEYWORD_DEFER:
3294           case KEYWORD_RETURN:
3295           case KEYWORD_BREAK:
3296           case KEYWORD_CONTINUE:
3297           case KEYWORD_GOTO:
3298           case KEYWORD_IF:
3299           case KEYWORD_SWITCH:
3300           case KEYWORD_SELECT:
3301           case KEYWORD_FOR:
3302             return true;
3303
3304           default:
3305             return false;
3306           }
3307       }
3308       break;
3309
3310     case Token::TOKEN_IDENTIFIER:
3311       return true;
3312
3313     case Token::TOKEN_OPERATOR:
3314       if (token->is_op(OPERATOR_LCURLY)
3315           || token->is_op(OPERATOR_SEMICOLON))
3316         return true;
3317       else
3318         return this->expression_may_start_here();
3319
3320     case Token::TOKEN_STRING:
3321     case Token::TOKEN_INTEGER:
3322     case Token::TOKEN_FLOAT:
3323     case Token::TOKEN_IMAGINARY:
3324       return true;
3325
3326     default:
3327       return false;
3328     }
3329 }
3330
3331 // LabeledStmt = Label ":" Statement .
3332 // Label       = identifier .
3333
3334 void
3335 Parse::labeled_stmt(const std::string& label_name, source_location location)
3336 {
3337   Label* label = this->gogo_->add_label_definition(label_name, location);
3338
3339   if (this->peek_token()->is_op(OPERATOR_RCURLY))
3340     {
3341       // This is a label at the end of a block.  A program is
3342       // permitted to omit a semicolon here.
3343       return;
3344     }
3345
3346   if (!this->statement_may_start_here())
3347     {
3348       // Mark the label as used to avoid a useless error about an
3349       // unused label.
3350       label->set_is_used();
3351
3352       error_at(location, "missing statement after label");
3353       this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3354                                                    location));
3355       return;
3356     }
3357
3358   this->statement(label);
3359 }
3360
3361 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
3362 //      Assignment | ShortVarDecl .
3363
3364 // EmptyStmt was handled in Parse::statement.
3365
3366 // In order to make this work for if and switch statements, if
3367 // RETURN_EXP is not NULL, and we see an ExpressionStat, we return the
3368 // expression rather than adding an expression statement to the
3369 // current block.  If we see something other than an ExpressionStat,
3370 // we add the statement, set *RETURN_EXP to true if we saw a send
3371 // statement, and return NULL.  The handling of send statements is for
3372 // better error messages.
3373
3374 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
3375 // RangeClause.
3376
3377 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
3378 // guard (var := expr.("type") using the literal keyword "type").
3379
3380 Expression*
3381 Parse::simple_stat(bool may_be_composite_lit, bool* return_exp,
3382                    Range_clause* p_range_clause, Type_switch* p_type_switch)
3383 {
3384   const Token* token = this->peek_token();
3385
3386   // An identifier follow by := is a SimpleVarDecl.
3387   if (token->is_identifier())
3388     {
3389       std::string identifier = token->identifier();
3390       bool is_exported = token->is_identifier_exported();
3391       source_location location = token->location();
3392
3393       token = this->advance_token();
3394       if (token->is_op(OPERATOR_COLONEQ)
3395           || token->is_op(OPERATOR_COMMA))
3396         {
3397           identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
3398           this->simple_var_decl_or_assignment(identifier, location,
3399                                               p_range_clause,
3400                                               (token->is_op(OPERATOR_COLONEQ)
3401                                                ? p_type_switch
3402                                                : NULL));
3403           return NULL;
3404         }
3405
3406       this->unget_token(Token::make_identifier_token(identifier, is_exported,
3407                                                      location));
3408     }
3409
3410   Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
3411                                      may_be_composite_lit,
3412                                      (p_type_switch == NULL
3413                                       ? NULL
3414                                       : &p_type_switch->found));
3415   if (p_type_switch != NULL && p_type_switch->found)
3416     {
3417       p_type_switch->name.clear();
3418       p_type_switch->location = exp->location();
3419       p_type_switch->expr = this->verify_not_sink(exp);
3420       return NULL;
3421     }
3422   token = this->peek_token();
3423   if (token->is_op(OPERATOR_CHANOP))
3424     {
3425       this->send_stmt(this->verify_not_sink(exp));
3426       if (return_exp != NULL)
3427         *return_exp = true;
3428     }
3429   else if (token->is_op(OPERATOR_PLUSPLUS)
3430            || token->is_op(OPERATOR_MINUSMINUS))
3431     this->inc_dec_stat(this->verify_not_sink(exp));
3432   else if (token->is_op(OPERATOR_COMMA)
3433            || token->is_op(OPERATOR_EQ))
3434     this->assignment(exp, p_range_clause);
3435   else if (token->is_op(OPERATOR_PLUSEQ)
3436            || token->is_op(OPERATOR_MINUSEQ)
3437            || token->is_op(OPERATOR_OREQ)
3438            || token->is_op(OPERATOR_XOREQ)
3439            || token->is_op(OPERATOR_MULTEQ)
3440            || token->is_op(OPERATOR_DIVEQ)
3441            || token->is_op(OPERATOR_MODEQ)
3442            || token->is_op(OPERATOR_LSHIFTEQ)
3443            || token->is_op(OPERATOR_RSHIFTEQ)
3444            || token->is_op(OPERATOR_ANDEQ)
3445            || token->is_op(OPERATOR_BITCLEAREQ))
3446     this->assignment(this->verify_not_sink(exp), p_range_clause);
3447   else if (return_exp != NULL)
3448     return this->verify_not_sink(exp);
3449   else
3450     this->expression_stat(this->verify_not_sink(exp));
3451
3452   return NULL;
3453 }
3454
3455 bool
3456 Parse::simple_stat_may_start_here()
3457 {
3458   return this->expression_may_start_here();
3459 }
3460
3461 // Parse { Statement ";" } which is used in a few places.  The list of
3462 // statements may end with a right curly brace, in which case the
3463 // semicolon may be omitted.
3464
3465 void
3466 Parse::statement_list()
3467 {
3468   while (this->statement_may_start_here())
3469     {
3470       this->statement(NULL);
3471       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3472         this->advance_token();
3473       else if (this->peek_token()->is_op(OPERATOR_RCURLY))
3474         break;
3475       else
3476         {
3477           if (!this->peek_token()->is_eof() || !saw_errors())
3478             error_at(this->location(), "expected %<;%> or %<}%> or newline");
3479           if (!this->skip_past_error(OPERATOR_RCURLY))
3480             return;
3481         }
3482     }
3483 }
3484
3485 bool
3486 Parse::statement_list_may_start_here()
3487 {
3488   return this->statement_may_start_here();
3489 }
3490
3491 // ExpressionStat = Expression .
3492
3493 void
3494 Parse::expression_stat(Expression* exp)
3495 {
3496   exp->discarding_value();
3497   this->gogo_->add_statement(Statement::make_statement(exp));
3498 }
3499
3500 // SendStmt = Channel "&lt;-" Expression .
3501 // Channel  = Expression .
3502
3503 void
3504 Parse::send_stmt(Expression* channel)
3505 {
3506   go_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
3507   source_location loc = this->location();
3508   this->advance_token();
3509   Expression* val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3510   Statement* s = Statement::make_send_statement(channel, val, loc);
3511   this->gogo_->add_statement(s);
3512 }
3513
3514 // IncDecStat = Expression ( "++" | "--" ) .
3515
3516 void
3517 Parse::inc_dec_stat(Expression* exp)
3518 {
3519   const Token* token = this->peek_token();
3520
3521   // Lvalue maps require special handling.
3522   if (exp->index_expression() != NULL)
3523     exp->index_expression()->set_is_lvalue();
3524
3525   if (token->is_op(OPERATOR_PLUSPLUS))
3526     this->gogo_->add_statement(Statement::make_inc_statement(exp));
3527   else if (token->is_op(OPERATOR_MINUSMINUS))
3528     this->gogo_->add_statement(Statement::make_dec_statement(exp));
3529   else
3530     go_unreachable();
3531   this->advance_token();
3532 }
3533
3534 // Assignment = ExpressionList assign_op ExpressionList .
3535
3536 // EXP is an expression that we have already parsed.
3537
3538 // If RANGE_CLAUSE is not NULL, then this will recognize a
3539 // RangeClause.
3540
3541 void
3542 Parse::assignment(Expression* expr, Range_clause* p_range_clause)
3543 {
3544   Expression_list* vars;
3545   if (!this->peek_token()->is_op(OPERATOR_COMMA))
3546     {
3547       vars = new Expression_list();
3548       vars->push_back(expr);
3549     }
3550   else
3551     {
3552       this->advance_token();
3553       vars = this->expression_list(expr, true);
3554     }
3555
3556   this->tuple_assignment(vars, p_range_clause);
3557 }
3558
3559 // An assignment statement.  LHS is the list of expressions which
3560 // appear on the left hand side.
3561
3562 // If RANGE_CLAUSE is not NULL, then this will recognize a
3563 // RangeClause.
3564
3565 void
3566 Parse::tuple_assignment(Expression_list* lhs, Range_clause* p_range_clause)
3567 {
3568   const Token* token = this->peek_token();
3569   if (!token->is_op(OPERATOR_EQ)
3570       && !token->is_op(OPERATOR_PLUSEQ)
3571       && !token->is_op(OPERATOR_MINUSEQ)
3572       && !token->is_op(OPERATOR_OREQ)
3573       && !token->is_op(OPERATOR_XOREQ)
3574       && !token->is_op(OPERATOR_MULTEQ)
3575       && !token->is_op(OPERATOR_DIVEQ)
3576       && !token->is_op(OPERATOR_MODEQ)
3577       && !token->is_op(OPERATOR_LSHIFTEQ)
3578       && !token->is_op(OPERATOR_RSHIFTEQ)
3579       && !token->is_op(OPERATOR_ANDEQ)
3580       && !token->is_op(OPERATOR_BITCLEAREQ))
3581     {
3582       error_at(this->location(), "expected assignment operator");
3583       return;
3584     }
3585   Operator op = token->op();
3586   source_location location = token->location();
3587
3588   token = this->advance_token();
3589
3590   if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
3591     {
3592       if (op != OPERATOR_EQ)
3593         error_at(this->location(), "range clause requires %<=%>");
3594       this->range_clause_expr(lhs, p_range_clause);
3595       return;
3596     }
3597
3598   Expression_list* vals = this->expression_list(NULL, false);
3599
3600   // We've parsed everything; check for errors.
3601   if (lhs == NULL || vals == NULL)
3602     return;
3603   for (Expression_list::const_iterator pe = lhs->begin();
3604        pe != lhs->end();
3605        ++pe)
3606     {
3607       if ((*pe)->is_error_expression())
3608         return;
3609       if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
3610         error_at((*pe)->location(), "cannot use _ as value");
3611     }
3612   for (Expression_list::const_iterator pe = vals->begin();
3613        pe != vals->end();
3614        ++pe)
3615     {
3616       if ((*pe)->is_error_expression())
3617         return;
3618     }
3619
3620   // Map expressions act differently when they are lvalues.
3621   for (Expression_list::iterator plv = lhs->begin();
3622        plv != lhs->end();
3623        ++plv)
3624     if ((*plv)->index_expression() != NULL)
3625       (*plv)->index_expression()->set_is_lvalue();
3626
3627   Call_expression* call;
3628   Index_expression* map_index;
3629   Receive_expression* receive;
3630   Type_guard_expression* type_guard;
3631   if (lhs->size() == vals->size())
3632     {
3633       Statement* s;
3634       if (lhs->size() > 1)
3635         {
3636           if (op != OPERATOR_EQ)
3637             error_at(location, "multiple values only permitted with %<=%>");
3638           s = Statement::make_tuple_assignment(lhs, vals, location);
3639         }
3640       else
3641         {
3642           if (op == OPERATOR_EQ)
3643             s = Statement::make_assignment(lhs->front(), vals->front(),
3644                                            location);
3645           else
3646             s = Statement::make_assignment_operation(op, lhs->front(),
3647                                                      vals->front(), location);
3648           delete lhs;
3649           delete vals;
3650         }
3651       this->gogo_->add_statement(s);
3652     }
3653   else if (vals->size() == 1
3654            && (call = (*vals->begin())->call_expression()) != NULL)
3655     {
3656       if (op != OPERATOR_EQ)
3657         error_at(location, "multiple results only permitted with %<=%>");
3658       delete vals;
3659       vals = new Expression_list;
3660       for (unsigned int i = 0; i < lhs->size(); ++i)
3661         vals->push_back(Expression::make_call_result(call, i));
3662       Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
3663       this->gogo_->add_statement(s);
3664     }
3665   else if (lhs->size() == 2
3666            && vals->size() == 1
3667            && (map_index = (*vals->begin())->index_expression()) != NULL)
3668     {
3669       if (op != OPERATOR_EQ)
3670         error_at(location, "two values from map requires %<=%>");
3671       Expression* val = lhs->front();
3672       Expression* present = lhs->back();
3673       Statement* s = Statement::make_tuple_map_assignment(val, present,
3674                                                           map_index, location);
3675       this->gogo_->add_statement(s);
3676     }
3677   else if (lhs->size() == 1
3678            && vals->size() == 2
3679            && (map_index = lhs->front()->index_expression()) != NULL)
3680     {
3681       if (op != OPERATOR_EQ)
3682         error_at(location, "assigning tuple to map index requires %<=%>");
3683       Expression* val = vals->front();
3684       Expression* should_set = vals->back();
3685       Statement* s = Statement::make_map_assignment(map_index, val, should_set,
3686                                                     location);
3687       this->gogo_->add_statement(s);
3688     }
3689   else if (lhs->size() == 2
3690            && vals->size() == 1
3691            && (receive = (*vals->begin())->receive_expression()) != NULL)
3692     {
3693       if (op != OPERATOR_EQ)
3694         error_at(location, "two values from receive requires %<=%>");
3695       Expression* val = lhs->front();
3696       Expression* success = lhs->back();
3697       Expression* channel = receive->channel();
3698       Statement* s = Statement::make_tuple_receive_assignment(val, success,
3699                                                               channel,
3700                                                               false,
3701                                                               location);
3702       this->gogo_->add_statement(s);
3703     }
3704   else if (lhs->size() == 2
3705            && vals->size() == 1
3706            && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
3707     {
3708       if (op != OPERATOR_EQ)
3709         error_at(location, "two values from type guard requires %<=%>");
3710       Expression* val = lhs->front();
3711       Expression* ok = lhs->back();
3712       Expression* expr = type_guard->expr();
3713       Type* type = type_guard->type();
3714       Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
3715                                                                  expr, type,
3716                                                                  location);
3717       this->gogo_->add_statement(s);
3718     }
3719   else
3720     {
3721       error_at(location, "number of variables does not match number of values");
3722     }
3723 }
3724
3725 // GoStat = "go" Expression .
3726 // DeferStat = "defer" Expression .
3727
3728 void
3729 Parse::go_or_defer_stat()
3730 {
3731   go_assert(this->peek_token()->is_keyword(KEYWORD_GO)
3732              || this->peek_token()->is_keyword(KEYWORD_DEFER));
3733   bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
3734   source_location stat_location = this->location();
3735   this->advance_token();
3736   source_location expr_location = this->location();
3737   Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3738   Call_expression* call_expr = expr->call_expression();
3739   if (call_expr == NULL)
3740     {
3741       error_at(expr_location, "expected call expression");
3742       return;
3743     }
3744
3745   // Make it easier to simplify go/defer statements by putting every
3746   // statement in its own block.
3747   this->gogo_->start_block(stat_location);
3748   Statement* stat;
3749   if (is_go)
3750     stat = Statement::make_go_statement(call_expr, stat_location);
3751   else
3752     stat = Statement::make_defer_statement(call_expr, stat_location);
3753   this->gogo_->add_statement(stat);
3754   this->gogo_->add_block(this->gogo_->finish_block(stat_location),
3755                          stat_location);
3756 }
3757
3758 // ReturnStat = "return" [ ExpressionList ] .
3759
3760 void
3761 Parse::return_stat()
3762 {
3763   go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
3764   source_location location = this->location();
3765   this->advance_token();
3766   Expression_list* vals = NULL;
3767   if (this->expression_may_start_here())
3768     vals = this->expression_list(NULL, false);
3769   this->gogo_->add_statement(Statement::make_return_statement(vals, location));
3770 }
3771
3772 // IfStmt    = "if" [ SimpleStmt ";" ] Expression Block [ "else" Statement ] .
3773
3774 void
3775 Parse::if_stat()
3776 {
3777   go_assert(this->peek_token()->is_keyword(KEYWORD_IF));
3778   source_location location = this->location();
3779   this->advance_token();
3780
3781   this->gogo_->start_block(location);
3782
3783   bool saw_simple_stat = false;
3784   Expression* cond = NULL;
3785   bool saw_send_stmt;
3786   if (this->simple_stat_may_start_here())
3787     {
3788       cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL);
3789       saw_simple_stat = true;
3790     }
3791   if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
3792     {
3793       // The SimpleStat is an expression statement.
3794       this->expression_stat(cond);
3795       cond = NULL;
3796     }
3797   if (cond == NULL)
3798     {
3799       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3800         this->advance_token();
3801       else if (saw_simple_stat)
3802         {
3803           if (saw_send_stmt)
3804             error_at(this->location(),
3805                      ("send statement used as value; "
3806                       "use select for non-blocking send"));
3807           else
3808             error_at(this->location(),
3809                      "expected %<;%> after statement in if expression");
3810           if (!this->expression_may_start_here())
3811             cond = Expression::make_error(this->location());
3812         }
3813       if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY))
3814         {
3815           error_at(this->location(),
3816                    "missing condition in if statement");
3817           cond = Expression::make_error(this->location());
3818         }
3819       if (cond == NULL)
3820         cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL);
3821     }
3822
3823   this->gogo_->start_block(this->location());
3824   source_location end_loc = this->block();
3825   Block* then_block = this->gogo_->finish_block(end_loc);
3826
3827   // Check for the easy error of a newline before "else".
3828   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3829     {
3830       source_location semi_loc = this->location();
3831       if (this->advance_token()->is_keyword(KEYWORD_ELSE))
3832         error_at(this->location(),
3833                  "unexpected semicolon or newline before %<else%>");
3834       else
3835         this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3836                                                      semi_loc));
3837     }
3838
3839   Block* else_block = NULL;
3840   if (this->peek_token()->is_keyword(KEYWORD_ELSE))
3841     {
3842       this->advance_token();
3843       // We create a block to gather the statement.
3844       this->gogo_->start_block(this->location());
3845       this->statement(NULL);
3846       else_block = this->gogo_->finish_block(this->location());
3847     }
3848
3849   this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
3850                                                           else_block,
3851                                                           location));
3852
3853   this->gogo_->add_block(this->gogo_->finish_block(this->location()),
3854                          location);
3855 }
3856
3857 // SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
3858 // ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
3859 //                      "{" { ExprCaseClause } "}" .
3860 // TypeSwitchStmt  = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
3861 //                      "{" { TypeCaseClause } "}" .
3862 // TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
3863
3864 void
3865 Parse::switch_stat(Label* label)
3866 {
3867   go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
3868   source_location location = this->location();
3869   this->advance_token();
3870
3871   this->gogo_->start_block(location);
3872
3873   bool saw_simple_stat = false;
3874   Expression* switch_val = NULL;
3875   bool saw_send_stmt;
3876   Type_switch type_switch;
3877   if (this->simple_stat_may_start_here())
3878     {
3879       switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
3880                                      &type_switch);
3881       saw_simple_stat = true;
3882     }
3883   if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
3884     {
3885       // The SimpleStat is an expression statement.
3886       this->expression_stat(switch_val);
3887       switch_val = NULL;
3888     }
3889   if (switch_val == NULL && !type_switch.found)
3890     {
3891       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3892         this->advance_token();
3893       else if (saw_simple_stat)
3894         {
3895           if (saw_send_stmt)
3896             error_at(this->location(),
3897                      ("send statement used as value; "
3898                       "use select for non-blocking send"));
3899           else
3900             error_at(this->location(),
3901                      "expected %<;%> after statement in switch expression");
3902         }
3903       if (!this->peek_token()->is_op(OPERATOR_LCURLY))
3904         {
3905           if (this->peek_token()->is_identifier())
3906             {
3907               const Token* token = this->peek_token();
3908               std::string identifier = token->identifier();
3909               bool is_exported = token->is_identifier_exported();
3910               source_location id_loc = token->location();
3911
3912               token = this->advance_token();
3913               bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
3914               this->unget_token(Token::make_identifier_token(identifier,
3915                                                              is_exported,
3916                                                              id_loc));
3917               if (is_coloneq)
3918                 {
3919                   // This must be a TypeSwitchGuard.
3920                   switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
3921                                                  &type_switch);
3922                   if (!type_switch.found)
3923                     {
3924                       if (switch_val == NULL
3925                           || !switch_val->is_error_expression())
3926                         {
3927                           error_at(id_loc, "expected type switch assignment");
3928                           switch_val = Expression::make_error(id_loc);
3929                         }
3930                     }
3931                 }
3932             }
3933           if (switch_val == NULL && !type_switch.found)
3934             {
3935               switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
3936                                             &type_switch.found);
3937               if (type_switch.found)
3938                 {
3939                   type_switch.name.clear();
3940                   type_switch.expr = switch_val;
3941                   type_switch.location = switch_val->location();
3942                 }
3943             }
3944         }
3945     }
3946
3947   if (!this->peek_token()->is_op(OPERATOR_LCURLY))
3948     {
3949       source_location token_loc = this->location();
3950       if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
3951           && this->advance_token()->is_op(OPERATOR_LCURLY))
3952         error_at(token_loc, "unexpected semicolon or newline before %<{%>");
3953       else if (this->peek_token()->is_op(OPERATOR_COLONEQ))
3954         {
3955           error_at(token_loc, "invalid variable name");
3956           this->advance_token();
3957           this->expression(PRECEDENCE_NORMAL, false, false,
3958                            &type_switch.found);
3959           if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3960             this->advance_token();
3961           if (!this->peek_token()->is_op(OPERATOR_LCURLY))
3962             return;
3963           if (type_switch.found)
3964             type_switch.expr = Expression::make_error(location);
3965         }
3966       else
3967         {
3968           error_at(this->location(), "expected %<{%>");
3969           this->gogo_->add_block(this->gogo_->finish_block(this->location()),
3970                                  location);
3971           return;
3972         }
3973     }
3974   this->advance_token();
3975
3976   Statement* statement;
3977   if (type_switch.found)
3978     statement = this->type_switch_body(label, type_switch, location);
3979   else
3980     statement = this->expr_switch_body(label, switch_val, location);
3981
3982   if (statement != NULL)
3983     this->gogo_->add_statement(statement);
3984
3985   this->gogo_->add_block(this->gogo_->finish_block(this->location()),
3986                          location);
3987 }
3988
3989 // The body of an expression switch.
3990 //   "{" { ExprCaseClause } "}"
3991
3992 Statement*
3993 Parse::expr_switch_body(Label* label, Expression* switch_val,
3994                         source_location location)
3995 {
3996   Switch_statement* statement = Statement::make_switch_statement(switch_val,
3997                                                                  location);
3998
3999   this->push_break_statement(statement, label);
4000
4001   Case_clauses* case_clauses = new Case_clauses();
4002   bool saw_default = false;
4003   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4004     {
4005       if (this->peek_token()->is_eof())
4006         {
4007           if (!saw_errors())
4008             error_at(this->location(), "missing %<}%>");
4009           return NULL;
4010         }
4011       this->expr_case_clause(case_clauses, &saw_default);
4012     }
4013   this->advance_token();
4014
4015   statement->add_clauses(case_clauses);
4016
4017   this->pop_break_statement();
4018
4019   return statement;
4020 }
4021
4022 // ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
4023 // FallthroughStat = "fallthrough" .
4024
4025 void
4026 Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
4027 {
4028   source_location location = this->location();
4029
4030   bool is_default = false;
4031   Expression_list* vals = this->expr_switch_case(&is_default);
4032
4033   if (!this->peek_token()->is_op(OPERATOR_COLON))
4034     {
4035       if (!saw_errors())
4036         error_at(this->location(), "expected %<:%>");
4037       return;
4038     }
4039   else
4040     this->advance_token();
4041
4042   Block* statements = NULL;
4043   if (this->statement_list_may_start_here())
4044     {
4045       this->gogo_->start_block(this->location());
4046       this->statement_list();
4047       statements = this->gogo_->finish_block(this->location());
4048     }
4049
4050   bool is_fallthrough = false;
4051   if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4052     {
4053       is_fallthrough = true;
4054       if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4055         this->advance_token();
4056     }
4057
4058   if (is_default)
4059     {
4060       if (*saw_default)
4061         {
4062           error_at(location, "multiple defaults in switch");
4063           return;
4064         }
4065       *saw_default = true;
4066     }
4067
4068   if (is_default || vals != NULL)
4069     clauses->add(vals, is_default, statements, is_fallthrough, location);
4070 }
4071
4072 // ExprSwitchCase = "case" ExpressionList | "default" .
4073
4074 Expression_list*
4075 Parse::expr_switch_case(bool* is_default)
4076 {
4077   const Token* token = this->peek_token();
4078   if (token->is_keyword(KEYWORD_CASE))
4079     {
4080       this->advance_token();
4081       return this->expression_list(NULL, false);
4082     }
4083   else if (token->is_keyword(KEYWORD_DEFAULT))
4084     {
4085       this->advance_token();
4086       *is_default = true;
4087       return NULL;
4088     }
4089   else
4090     {
4091       if (!saw_errors())
4092         error_at(this->location(), "expected %<case%> or %<default%>");
4093       if (!token->is_op(OPERATOR_RCURLY))
4094         this->advance_token();
4095       return NULL;
4096     }
4097 }
4098
4099 // The body of a type switch.
4100 //   "{" { TypeCaseClause } "}" .
4101
4102 Statement*
4103 Parse::type_switch_body(Label* label, const Type_switch& type_switch,
4104                         source_location location)
4105 {
4106   Named_object* switch_no = NULL;
4107   if (!type_switch.name.empty())
4108     {
4109       Variable* switch_var = new Variable(NULL, type_switch.expr, false, false,
4110                                           false, type_switch.location);
4111       switch_no = this->gogo_->add_variable(type_switch.name, switch_var);
4112     }
4113
4114   Type_switch_statement* statement =
4115     Statement::make_type_switch_statement(switch_no,
4116                                           (switch_no == NULL
4117                                            ? type_switch.expr
4118                                            : NULL),
4119                                           location);
4120
4121   this->push_break_statement(statement, label);
4122
4123   Type_case_clauses* case_clauses = new Type_case_clauses();
4124   bool saw_default = false;
4125   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4126     {
4127       if (this->peek_token()->is_eof())
4128         {
4129           error_at(this->location(), "missing %<}%>");
4130           return NULL;
4131         }
4132       this->type_case_clause(switch_no, case_clauses, &saw_default);
4133     }
4134   this->advance_token();
4135
4136   statement->add_clauses(case_clauses);
4137
4138   this->pop_break_statement();
4139
4140   return statement;
4141 }
4142
4143 // TypeCaseClause  = TypeSwitchCase ":" [ StatementList ] .
4144
4145 void
4146 Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses,
4147                         bool* saw_default)
4148 {
4149   source_location location = this->location();
4150
4151   std::vector<Type*> types;
4152   bool is_default = false;
4153   this->type_switch_case(&types, &is_default);
4154
4155   if (!this->peek_token()->is_op(OPERATOR_COLON))
4156     error_at(this->location(), "expected %<:%>");
4157   else
4158     this->advance_token();
4159
4160   Block* statements = NULL;
4161   if (this->statement_list_may_start_here())
4162     {
4163       this->gogo_->start_block(this->location());
4164       if (switch_no != NULL && types.size() == 1)
4165         {
4166           Type* type = types.front();
4167           Expression* init = Expression::make_var_reference(switch_no,
4168                                                             location);
4169           init = Expression::make_type_guard(init, type, location);
4170           Variable* v = new Variable(type, init, false, false, false,
4171                                      location);
4172           v->set_is_type_switch_var();
4173           this->gogo_->add_variable(switch_no->name(), v);
4174         }
4175       this->statement_list();
4176       statements = this->gogo_->finish_block(this->location());
4177     }
4178
4179   if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4180     {
4181       error_at(this->location(),
4182                "fallthrough is not permitted in a type switch");
4183       if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4184         this->advance_token();
4185     }
4186
4187   if (is_default)
4188     {
4189       go_assert(types.empty());
4190       if (*saw_default)
4191         {
4192           error_at(location, "multiple defaults in type switch");
4193           return;
4194         }
4195       *saw_default = true;
4196       clauses->add(NULL, false, true, statements, location);
4197     }
4198   else if (!types.empty())
4199     {
4200       for (std::vector<Type*>::const_iterator p = types.begin();
4201            p + 1 != types.end();
4202            ++p)
4203         clauses->add(*p, true, false, NULL, location);
4204       clauses->add(types.back(), false, false, statements, location);
4205     }
4206   else
4207     clauses->add(Type::make_error_type(), false, false, statements, location);
4208 }
4209
4210 // TypeSwitchCase  = "case" type | "default"
4211
4212 // We accept a comma separated list of types.
4213
4214 void
4215 Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
4216 {
4217   const Token* token = this->peek_token();
4218   if (token->is_keyword(KEYWORD_CASE))
4219     {
4220       this->advance_token();
4221       while (true)
4222         {
4223           Type* t = this->type();
4224           if (!t->is_error_type())
4225             types->push_back(t);
4226           if (!this->peek_token()->is_op(OPERATOR_COMMA))
4227             break;
4228           this->advance_token();
4229         }
4230     }
4231   else if (token->is_keyword(KEYWORD_DEFAULT))
4232     {
4233       this->advance_token();
4234       *is_default = true;
4235     }
4236   else
4237     {
4238       error_at(this->location(), "expected %<case%> or %<default%>");
4239       if (!token->is_op(OPERATOR_RCURLY))
4240         this->advance_token();
4241     }
4242 }
4243
4244 // SelectStat = "select" "{" { CommClause } "}" .
4245
4246 void
4247 Parse::select_stat(Label* label)
4248 {
4249   go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
4250   source_location location = this->location();
4251   const Token* token = this->advance_token();
4252
4253   if (!token->is_op(OPERATOR_LCURLY))
4254     {
4255       source_location token_loc = token->location();
4256       if (token->is_op(OPERATOR_SEMICOLON)
4257           && this->advance_token()->is_op(OPERATOR_LCURLY))
4258         error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4259       else
4260         {
4261           error_at(this->location(), "expected %<{%>");
4262           return;
4263         }
4264     }
4265   this->advance_token();
4266
4267   Select_statement* statement = Statement::make_select_statement(location);
4268
4269   this->push_break_statement(statement, label);
4270
4271   Select_clauses* select_clauses = new Select_clauses();
4272   bool saw_default = false;
4273   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4274     {
4275       if (this->peek_token()->is_eof())
4276         {
4277           error_at(this->location(), "expected %<}%>");
4278           return;
4279         }
4280       this->comm_clause(select_clauses, &saw_default);
4281     }
4282
4283   this->advance_token();
4284
4285   statement->add_clauses(select_clauses);
4286
4287   this->pop_break_statement();
4288
4289   this->gogo_->add_statement(statement);
4290 }
4291
4292 // CommClause = CommCase ":" { Statement ";" } .
4293
4294 void
4295 Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
4296 {
4297   source_location location = this->location();
4298   bool is_send = false;
4299   Expression* channel = NULL;
4300   Expression* val = NULL;
4301   Expression* closed = NULL;
4302   std::string varname;
4303   std::string closedname;
4304   bool is_default = false;
4305   bool got_case = this->comm_case(&is_send, &channel, &val, &closed,
4306                                   &varname, &closedname, &is_default);
4307
4308   if (!is_send
4309       && varname.empty()
4310       && closedname.empty()
4311       && val != NULL
4312       && val->index_expression() != NULL)
4313     val->index_expression()->set_is_lvalue();
4314
4315   if (this->peek_token()->is_op(OPERATOR_COLON))
4316     this->advance_token();
4317   else
4318     error_at(this->location(), "expected colon");
4319
4320   this->gogo_->start_block(this->location());
4321
4322   Named_object* var = NULL;
4323   if (!varname.empty())
4324     {
4325       // FIXME: LOCATION is slightly wrong here.
4326       Variable* v = new Variable(NULL, channel, false, false, false,
4327                                  location);
4328       v->set_type_from_chan_element();
4329       var = this->gogo_->add_variable(varname, v);
4330     }
4331
4332   Named_object* closedvar = NULL;
4333   if (!closedname.empty())
4334     {
4335       // FIXME: LOCATION is slightly wrong here.
4336       Variable* v = new Variable(Type::lookup_bool_type(), NULL,
4337                                  false, false, false, location);
4338       closedvar = this->gogo_->add_variable(closedname, v);
4339     }
4340
4341   this->statement_list();
4342
4343   Block* statements = this->gogo_->finish_block(this->location());
4344
4345   if (is_default)
4346     {
4347       if (*saw_default)
4348         {
4349           error_at(location, "multiple defaults in select");
4350           return;
4351         }
4352       *saw_default = true;
4353     }
4354
4355   if (got_case)
4356     clauses->add(is_send, channel, val, closed, var, closedvar, is_default,
4357                  statements, location);
4358   else if (statements != NULL)
4359     {
4360       // Add the statements to make sure that any names they define
4361       // are traversed.
4362       this->gogo_->add_block(statements, location);
4363     }
4364 }
4365
4366 // CommCase   = "case" ( SendStmt | RecvStmt ) | "default" .
4367
4368 bool
4369 Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
4370                  Expression** closed, std::string* varname,
4371                  std::string* closedname, bool* is_default)
4372 {
4373   const Token* token = this->peek_token();
4374   if (token->is_keyword(KEYWORD_DEFAULT))
4375     {
4376       this->advance_token();
4377       *is_default = true;
4378     }
4379   else if (token->is_keyword(KEYWORD_CASE))
4380     {
4381       this->advance_token();
4382       if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname,
4383                                    closedname))
4384         return false;
4385     }
4386   else
4387     {
4388       error_at(this->location(), "expected %<case%> or %<default%>");
4389       if (!token->is_op(OPERATOR_RCURLY))
4390         this->advance_token();
4391       return false;
4392     }
4393
4394   return true;
4395 }
4396
4397 // RecvStmt   = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
4398 // RecvExpr   = Expression .
4399
4400 bool
4401 Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val,
4402                          Expression** closed, std::string* varname,
4403                          std::string* closedname)
4404 {
4405   const Token* token = this->peek_token();
4406   bool saw_comma = false;
4407   bool closed_is_id = false;
4408   if (token->is_identifier())
4409     {
4410       Gogo* gogo = this->gogo_;
4411       std::string recv_var = token->identifier();
4412       bool is_rv_exported = token->is_identifier_exported();
4413       source_location recv_var_loc = token->location();
4414       token = this->advance_token();
4415       if (token->is_op(OPERATOR_COLONEQ))
4416         {
4417           // case rv := <-c:
4418           if (!this->advance_token()->is_op(OPERATOR_CHANOP))
4419             {
4420               error_at(this->location(), "expected %<<-%>");
4421               return false;
4422             }
4423           if (recv_var == "_")
4424             {
4425               error_at(recv_var_loc,
4426                        "no new variables on left side of %<:=%>");
4427               recv_var = "blank";
4428             }
4429           *is_send = false;
4430           *varname = gogo->pack_hidden_name(recv_var, is_rv_exported);
4431           this->advance_token();
4432           *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4433           return true;
4434         }
4435       else if (token->is_op(OPERATOR_COMMA))
4436         {
4437           token = this->advance_token();
4438           if (token->is_identifier())
4439             {
4440               std::string recv_closed = token->identifier();
4441               bool is_rc_exported = token->is_identifier_exported();
4442               source_location recv_closed_loc = token->location();
4443               closed_is_id = true;
4444
4445               token = this->advance_token();
4446               if (token->is_op(OPERATOR_COLONEQ))
4447                 {
4448                   // case rv, rc := <-c:
4449                   if (!this->advance_token()->is_op(OPERATOR_CHANOP))
4450                     {
4451                       error_at(this->location(), "expected %<<-%>");
4452                       return false;
4453                     }
4454                   if (recv_var == "_" && recv_closed == "_")
4455                     {
4456                       error_at(recv_var_loc,
4457                                "no new variables on left side of %<:=%>");
4458                       recv_var = "blank";
4459                     }
4460                   *is_send = false;
4461                   if (recv_var != "_")
4462                     *varname = gogo->pack_hidden_name(recv_var,
4463                                                       is_rv_exported);
4464                   if (recv_closed != "_")
4465                     *closedname = gogo->pack_hidden_name(recv_closed,
4466                                                          is_rc_exported);
4467                   this->advance_token();
4468                   *channel = this->expression(PRECEDENCE_NORMAL, false, true,
4469                                               NULL);
4470                   return true;
4471                 }
4472
4473               this->unget_token(Token::make_identifier_token(recv_closed,
4474                                                              is_rc_exported,
4475                                                              recv_closed_loc));
4476             }
4477
4478           *val = this->id_to_expression(gogo->pack_hidden_name(recv_var,
4479                                                                is_rv_exported),
4480                                         recv_var_loc);
4481           saw_comma = true;
4482         }
4483       else
4484         this->unget_token(Token::make_identifier_token(recv_var,
4485                                                        is_rv_exported,
4486                                                        recv_var_loc));
4487     }
4488
4489   // If SAW_COMMA is false, then we are looking at the start of the
4490   // send or receive expression.  If SAW_COMMA is true, then *VAL is
4491   // set and we just read a comma.
4492
4493   Expression* e;
4494   if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP))
4495     e = this->expression(PRECEDENCE_NORMAL, true, true, NULL);
4496   else
4497     {
4498       // case <-c:
4499       *is_send = false;
4500       this->advance_token();
4501       *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4502
4503       // The next token should be ':'.  If it is '<-', then we have
4504       // case <-c <- v:
4505       // which is to say, send on a channel received from a channel.
4506       if (!this->peek_token()->is_op(OPERATOR_CHANOP))
4507         return true;
4508
4509       e = Expression::make_receive(*channel, (*channel)->location());
4510     }
4511
4512   if (this->peek_token()->is_op(OPERATOR_EQ))
4513     {
4514       if (!this->advance_token()->is_op(OPERATOR_CHANOP))
4515         {
4516           error_at(this->location(), "missing %<<-%>");
4517           return false;
4518         }
4519       *is_send = false;
4520       this->advance_token();
4521       *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4522       if (saw_comma)
4523         {
4524           // case v, e = <-c:
4525           // *VAL is already set.
4526           if (!e->is_sink_expression())
4527             *closed = e;
4528         }
4529       else
4530         {
4531           // case v = <-c:
4532           if (!e->is_sink_expression())
4533             *val = e;
4534         }
4535       return true;
4536     }
4537
4538   if (saw_comma)
4539     {
4540       if (closed_is_id)
4541         error_at(this->location(), "expected %<=%> or %<:=%>");
4542       else
4543         error_at(this->location(), "expected %<=%>");
4544       return false;
4545     }
4546
4547   if (this->peek_token()->is_op(OPERATOR_CHANOP))
4548     {
4549       // case c <- v:
4550       *is_send = true;
4551       *channel = this->verify_not_sink(e);
4552       this->advance_token();
4553       *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4554       return true;
4555     }
4556
4557   error_at(this->location(), "expected %<<-%> or %<=%>");
4558   return false;
4559 }
4560
4561 // ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
4562 // Condition = Expression .
4563
4564 void
4565 Parse::for_stat(Label* label)
4566 {
4567   go_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
4568   source_location location = this->location();
4569   const Token* token = this->advance_token();
4570
4571   // Open a block to hold any variables defined in the init statement
4572   // of the for statement.
4573   this->gogo_->start_block(location);
4574
4575   Block* init = NULL;
4576   Expression* cond = NULL;
4577   Block* post = NULL;
4578   Range_clause range_clause;
4579
4580   if (!token->is_op(OPERATOR_LCURLY))
4581     {
4582       if (token->is_keyword(KEYWORD_VAR))
4583         {
4584           error_at(this->location(),
4585                    "var declaration not allowed in for initializer");
4586           this->var_decl();
4587         }
4588
4589       if (token->is_op(OPERATOR_SEMICOLON))
4590         this->for_clause(&cond, &post);
4591       else
4592         {
4593           // We might be looking at a Condition, an InitStat, or a
4594           // RangeClause.
4595           bool saw_send_stmt;
4596           cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL);
4597           if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
4598             {
4599               if (cond == NULL && !range_clause.found)
4600                 {
4601                   if (saw_send_stmt)
4602                     error_at(this->location(),
4603                              ("send statement used as value; "
4604                               "use select for non-blocking send"));
4605                   else
4606                     error_at(this->location(), "parse error in for statement");
4607                 }
4608             }
4609           else
4610             {
4611               if (range_clause.found)
4612                 error_at(this->location(), "parse error after range clause");
4613
4614               if (cond != NULL)
4615                 {
4616                   // COND is actually an expression statement for
4617                   // InitStat at the start of a ForClause.
4618                   this->expression_stat(cond);
4619                   cond = NULL;
4620                 }
4621
4622               this->for_clause(&cond, &post);
4623             }
4624         }
4625     }
4626
4627   // Build the For_statement and note that it is the current target
4628   // for break and continue statements.
4629
4630   For_statement* sfor;
4631   For_range_statement* srange;
4632   Statement* s;
4633   if (!range_clause.found)
4634     {
4635       sfor = Statement::make_for_statement(init, cond, post, location);
4636       s = sfor;
4637       srange = NULL;
4638     }
4639   else
4640     {
4641       srange = Statement::make_for_range_statement(range_clause.index,
4642                                                    range_clause.value,
4643                                                    range_clause.range,
4644                                                    location);
4645       s = srange;
4646       sfor = NULL;
4647     }
4648
4649   this->push_break_statement(s, label);
4650   this->push_continue_statement(s, label);
4651
4652   // Gather the block of statements in the loop and add them to the
4653   // For_statement.
4654
4655   this->gogo_->start_block(this->location());
4656   source_location end_loc = this->block();
4657   Block* statements = this->gogo_->finish_block(end_loc);
4658
4659   if (sfor != NULL)
4660     sfor->add_statements(statements);
4661   else
4662     srange->add_statements(statements);
4663
4664   // This is no longer the break/continue target.
4665   this->pop_break_statement();
4666   this->pop_continue_statement();
4667
4668   // Add the For_statement to the list of statements, and close out
4669   // the block we started to hold any variables defined in the for
4670   // statement.
4671
4672   this->gogo_->add_statement(s);
4673
4674   this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4675                          location);
4676 }
4677
4678 // ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
4679 // InitStat = SimpleStat .
4680 // PostStat = SimpleStat .
4681
4682 // We have already read InitStat at this point.
4683
4684 void
4685 Parse::for_clause(Expression** cond, Block** post)
4686 {
4687   go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
4688   this->advance_token();
4689   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4690     *cond = NULL;
4691   else if (this->peek_token()->is_op(OPERATOR_LCURLY))
4692     {
4693       error_at(this->location(),
4694                "unexpected semicolon or newline before %<{%>");
4695       *cond = NULL;
4696       *post = NULL;
4697       return;
4698     }
4699   else
4700     *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4701   if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
4702     error_at(this->location(), "expected semicolon");
4703   else
4704     this->advance_token();
4705
4706   if (this->peek_token()->is_op(OPERATOR_LCURLY))
4707     *post = NULL;
4708   else
4709     {
4710       this->gogo_->start_block(this->location());
4711       this->simple_stat(false, NULL, NULL, NULL);
4712       *post = this->gogo_->finish_block(this->location());
4713     }
4714 }
4715
4716 // RangeClause = IdentifierList ( "=" | ":=" ) "range" Expression .
4717
4718 // This is the := version.  It is called with a list of identifiers.
4719
4720 void
4721 Parse::range_clause_decl(const Typed_identifier_list* til,
4722                          Range_clause* p_range_clause)
4723 {
4724   go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
4725   source_location location = this->location();
4726
4727   p_range_clause->found = true;
4728
4729   go_assert(til->size() >= 1);
4730   if (til->size() > 2)
4731     error_at(this->location(), "too many variables for range clause");
4732
4733   this->advance_token();
4734   Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL);
4735   p_range_clause->range = expr;
4736
4737   bool any_new = false;
4738
4739   const Typed_identifier* pti = &til->front();
4740   Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new);
4741   if (any_new && no->is_variable())
4742     no->var_value()->set_type_from_range_index();
4743   p_range_clause->index = Expression::make_var_reference(no, location);
4744
4745   if (til->size() == 1)
4746     p_range_clause->value = NULL;
4747   else
4748     {
4749       pti = &til->back();
4750       bool is_new = false;
4751       no = this->init_var(*pti, NULL, expr, true, true, &is_new);
4752       if (is_new && no->is_variable())
4753         no->var_value()->set_type_from_range_value();
4754       if (is_new)
4755         any_new = true;
4756       p_range_clause->value = Expression::make_var_reference(no, location);
4757     }
4758
4759   if (!any_new)
4760     error_at(location, "variables redeclared but no variable is new");
4761 }
4762
4763 // The = version of RangeClause.  This is called with a list of
4764 // expressions.
4765
4766 void
4767 Parse::range_clause_expr(const Expression_list* vals,
4768                          Range_clause* p_range_clause)
4769 {
4770   go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
4771
4772   p_range_clause->found = true;
4773
4774   go_assert(vals->size() >= 1);
4775   if (vals->size() > 2)
4776     error_at(this->location(), "too many variables for range clause");
4777
4778   this->advance_token();
4779   p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
4780                                            NULL);
4781
4782   p_range_clause->index = vals->front();
4783   if (vals->size() == 1)
4784     p_range_clause->value = NULL;
4785   else
4786     p_range_clause->value = vals->back();
4787 }
4788
4789 // Push a statement on the break stack.
4790
4791 void
4792 Parse::push_break_statement(Statement* enclosing, Label* label)
4793 {
4794   if (this->break_stack_ == NULL)
4795     this->break_stack_ = new Bc_stack();
4796   this->break_stack_->push_back(std::make_pair(enclosing, label));
4797 }
4798
4799 // Push a statement on the continue stack.
4800
4801 void
4802 Parse::push_continue_statement(Statement* enclosing, Label* label)
4803 {
4804   if (this->continue_stack_ == NULL)
4805     this->continue_stack_ = new Bc_stack();
4806   this->continue_stack_->push_back(std::make_pair(enclosing, label));
4807 }
4808
4809 // Pop the break stack.
4810
4811 void
4812 Parse::pop_break_statement()
4813 {
4814   this->break_stack_->pop_back();
4815 }
4816
4817 // Pop the continue stack.
4818
4819 void
4820 Parse::pop_continue_statement()
4821 {
4822   this->continue_stack_->pop_back();
4823 }
4824
4825 // Find a break or continue statement given a label name.
4826
4827 Statement*
4828 Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
4829 {
4830   if (bc_stack == NULL)
4831     return NULL;
4832   for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
4833        p != bc_stack->rend();
4834        ++p)
4835     {
4836       if (p->second != NULL && p->second->name() == label)
4837         {
4838           p->second->set_is_used();
4839           return p->first;
4840         }
4841     }
4842   return NULL;
4843 }
4844
4845 // BreakStat = "break" [ identifier ] .
4846
4847 void
4848 Parse::break_stat()
4849 {
4850   go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
4851   source_location location = this->location();
4852
4853   const Token* token = this->advance_token();
4854   Statement* enclosing;
4855   if (!token->is_identifier())
4856     {
4857       if (this->break_stack_ == NULL || this->break_stack_->empty())
4858         {
4859           error_at(this->location(),
4860                    "break statement not within for or switch or select");
4861           return;
4862         }
4863       enclosing = this->break_stack_->back().first;
4864     }
4865   else
4866     {
4867       enclosing = this->find_bc_statement(this->break_stack_,
4868                                           token->identifier());
4869       if (enclosing == NULL)
4870         {
4871           // If there is a label with this name, mark it as used to
4872           // avoid a useless error about an unused label.
4873           this->gogo_->add_label_reference(token->identifier());
4874
4875           error_at(token->location(), "invalid break label %qs",
4876                    Gogo::message_name(token->identifier()).c_str());
4877           this->advance_token();
4878           return;
4879         }
4880       this->advance_token();
4881     }
4882
4883   Unnamed_label* label;
4884   if (enclosing->classification() == Statement::STATEMENT_FOR)
4885     label = enclosing->for_statement()->break_label();
4886   else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
4887     label = enclosing->for_range_statement()->break_label();
4888   else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
4889     label = enclosing->switch_statement()->break_label();
4890   else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
4891     label = enclosing->type_switch_statement()->break_label();
4892   else if (enclosing->classification() == Statement::STATEMENT_SELECT)
4893     label = enclosing->select_statement()->break_label();
4894   else
4895     go_unreachable();
4896
4897   this->gogo_->add_statement(Statement::make_break_statement(label,
4898                                                              location));
4899 }
4900
4901 // ContinueStat = "continue" [ identifier ] .
4902
4903 void
4904 Parse::continue_stat()
4905 {
4906   go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
4907   source_location location = this->location();
4908
4909   const Token* token = this->advance_token();
4910   Statement* enclosing;
4911   if (!token->is_identifier())
4912     {
4913       if (this->continue_stack_ == NULL || this->continue_stack_->empty())
4914         {
4915           error_at(this->location(), "continue statement not within for");
4916           return;
4917         }
4918       enclosing = this->continue_stack_->back().first;
4919     }
4920   else
4921     {
4922       enclosing = this->find_bc_statement(this->continue_stack_,
4923                                           token->identifier());
4924       if (enclosing == NULL)
4925         {
4926           // If there is a label with this name, mark it as used to
4927           // avoid a useless error about an unused label.
4928           this->gogo_->add_label_reference(token->identifier());
4929
4930           error_at(token->location(), "invalid continue label %qs",
4931                    Gogo::message_name(token->identifier()).c_str());
4932           this->advance_token();
4933           return;
4934         }
4935       this->advance_token();
4936     }
4937
4938   Unnamed_label* label;
4939   if (enclosing->classification() == Statement::STATEMENT_FOR)
4940     label = enclosing->for_statement()->continue_label();
4941   else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
4942     label = enclosing->for_range_statement()->continue_label();
4943   else
4944     go_unreachable();
4945
4946   this->gogo_->add_statement(Statement::make_continue_statement(label,
4947                                                                 location));
4948 }
4949
4950 // GotoStat = "goto" identifier .
4951
4952 void
4953 Parse::goto_stat()
4954 {
4955   go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
4956   source_location location = this->location();
4957   const Token* token = this->advance_token();
4958   if (!token->is_identifier())
4959     error_at(this->location(), "expected label for goto");
4960   else
4961     {
4962       Label* label = this->gogo_->add_label_reference(token->identifier());
4963       Statement* s = Statement::make_goto_statement(label, location);
4964       this->gogo_->add_statement(s);
4965       this->advance_token();
4966     }
4967 }
4968
4969 // PackageClause = "package" PackageName .
4970
4971 void
4972 Parse::package_clause()
4973 {
4974   const Token* token = this->peek_token();
4975   source_location location = token->location();
4976   std::string name;
4977   if (!token->is_keyword(KEYWORD_PACKAGE))
4978     {
4979       error_at(this->location(), "program must start with package clause");
4980       name = "ERROR";
4981     }
4982   else
4983     {
4984       token = this->advance_token();
4985       if (token->is_identifier())
4986         {
4987           name = token->identifier();
4988           if (name == "_")
4989             {
4990               error_at(this->location(), "invalid package name _");
4991               name = "blank";
4992             }
4993           this->advance_token();
4994         }
4995       else
4996         {
4997           error_at(this->location(), "package name must be an identifier");
4998           name = "ERROR";
4999         }
5000     }
5001   this->gogo_->set_package_name(name, location);
5002 }
5003
5004 // ImportDecl = "import" Decl<ImportSpec> .
5005
5006 void
5007 Parse::import_decl()
5008 {
5009   go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
5010   this->advance_token();
5011   this->decl(&Parse::import_spec, NULL);
5012 }
5013
5014 // ImportSpec = [ "." | PackageName ] PackageFileName .
5015
5016 void
5017 Parse::import_spec(void*)
5018 {
5019   const Token* token = this->peek_token();
5020   source_location location = token->location();
5021
5022   std::string local_name;
5023   bool is_local_name_exported = false;
5024   if (token->is_op(OPERATOR_DOT))
5025     {
5026       local_name = ".";
5027       token = this->advance_token();
5028     }
5029   else if (token->is_identifier())
5030     {
5031       local_name = token->identifier();
5032       is_local_name_exported = token->is_identifier_exported();
5033       token = this->advance_token();
5034     }
5035
5036   if (!token->is_string())
5037     {
5038       error_at(this->location(), "missing import package name");
5039       return;
5040     }
5041
5042   this->gogo_->import_package(token->string_value(), local_name,
5043                               is_local_name_exported, location);
5044
5045   this->advance_token();
5046 }
5047
5048 // SourceFile       = PackageClause ";" { ImportDecl ";" }
5049 //                      { TopLevelDecl ";" } .
5050
5051 void
5052 Parse::program()
5053 {
5054   this->package_clause();
5055
5056   const Token* token = this->peek_token();
5057   if (token->is_op(OPERATOR_SEMICOLON))
5058     token = this->advance_token();
5059   else
5060     error_at(this->location(),
5061              "expected %<;%> or newline after package clause");
5062
5063   while (token->is_keyword(KEYWORD_IMPORT))
5064     {
5065       this->import_decl();
5066       token = this->peek_token();
5067       if (token->is_op(OPERATOR_SEMICOLON))
5068         token = this->advance_token();
5069       else
5070         error_at(this->location(),
5071                  "expected %<;%> or newline after import declaration");
5072     }
5073
5074   while (!token->is_eof())
5075     {
5076       if (this->declaration_may_start_here())
5077         this->declaration();
5078       else
5079         {
5080           error_at(this->location(), "expected declaration");
5081           do
5082             this->advance_token();
5083           while (!this->peek_token()->is_eof()
5084                  && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
5085                  && !this->peek_token()->is_op(OPERATOR_RCURLY));
5086           if (!this->peek_token()->is_eof()
5087               && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
5088             this->advance_token();
5089         }
5090       token = this->peek_token();
5091       if (token->is_op(OPERATOR_SEMICOLON))
5092         token = this->advance_token();
5093       else if (!token->is_eof() || !saw_errors())
5094         {
5095           if (token->is_op(OPERATOR_CHANOP))
5096             error_at(this->location(),
5097                      ("send statement used as value; "
5098                       "use select for non-blocking send"));
5099           else
5100             error_at(this->location(),
5101                      "expected %<;%> or newline after top level declaration");
5102           this->skip_past_error(OPERATOR_INVALID);
5103         }
5104     }
5105 }
5106
5107 // Reset the current iota value.
5108
5109 void
5110 Parse::reset_iota()
5111 {
5112   this->iota_ = 0;
5113 }
5114
5115 // Return the current iota value.
5116
5117 int
5118 Parse::iota_value()
5119 {
5120   return this->iota_;
5121 }
5122
5123 // Increment the current iota value.
5124
5125 void
5126 Parse::increment_iota()
5127 {
5128   ++this->iota_;
5129 }
5130
5131 // Skip forward to a semicolon or OP.  OP will normally be
5132 // OPERATOR_RPAREN or OPERATOR_RCURLY.  If we find a semicolon, move
5133 // past it and return.  If we find OP, it will be the next token to
5134 // read.  Return true if we are OK, false if we found EOF.
5135
5136 bool
5137 Parse::skip_past_error(Operator op)
5138 {
5139   const Token* token = this->peek_token();
5140   while (!token->is_op(op))
5141     {
5142       if (token->is_eof())
5143         return false;
5144       if (token->is_op(OPERATOR_SEMICOLON))
5145         {
5146           this->advance_token();
5147           return true;
5148         }
5149       token = this->advance_token();
5150     }
5151   return true;
5152 }
5153
5154 // Check that an expression is not a sink.
5155
5156 Expression*
5157 Parse::verify_not_sink(Expression* expr)
5158 {
5159   if (expr->is_sink_expression())
5160     {
5161       error_at(expr->location(), "cannot use _ as value");
5162       expr = Expression::make_error(expr->location());
5163     }
5164   return expr;
5165 }