OSDN Git Service

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