OSDN Git Service

Change c <- v from an expression to a statement.
[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                                                           location);
1721
1722   if (!this->gogo_->in_global_scope())
1723     this->gogo_->add_statement(s);
1724   else if (!val_no->is_sink())
1725     {
1726       if (val_no->is_variable())
1727         val_no->var_value()->add_preinit_statement(this->gogo_, s);
1728     }
1729   else if (!no->is_sink())
1730     {
1731       if (no->is_variable())
1732         no->var_value()->add_preinit_statement(this->gogo_, s);
1733     }
1734   else
1735     {
1736       Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1737                                                       NULL, location);
1738       dummy->var_value()->add_preinit_statement(this->gogo_, s);
1739     }
1740
1741   return true;
1742 }
1743
1744 // See if we need to initialize a pair of values from a type guard
1745 // expression.  This returns true if we have set up the variables and
1746 // the initialization.
1747
1748 bool
1749 Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
1750                                  Type* type, Expression* expr,
1751                                  bool is_coloneq, source_location location)
1752 {
1753   Type_guard_expression* type_guard = expr->type_guard_expression();
1754   if (type_guard == NULL)
1755     return false;
1756   if (vars->size() != 2)
1757     return false;
1758
1759   // This is a type guard expression which is being assigned to two
1760   // variables.  Declare the variables, and then assign the results of
1761   // the type guard.
1762   bool any_new = false;
1763   Typed_identifier_list::const_iterator p = vars->begin();
1764   Type* var_type = type;
1765   if (var_type == NULL)
1766     var_type = type_guard->type();
1767   Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1768                                         &any_new);
1769   Expression* val_var = Expression::make_var_reference(val_no, location);
1770
1771   ++p;
1772   var_type = type;
1773   if (var_type == NULL)
1774     var_type = Type::lookup_bool_type();
1775   Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1776                                     &any_new);
1777   Expression* ok_var = Expression::make_var_reference(no, location);
1778
1779   Expression* texpr = type_guard->expr();
1780   Type* t = type_guard->type();
1781   Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
1782                                                              texpr, t,
1783                                                              location);
1784
1785   if (is_coloneq && !any_new)
1786     error_at(location, "variables redeclared but no variable is new");
1787
1788   if (!this->gogo_->in_global_scope())
1789     this->gogo_->add_statement(s);
1790   else if (!val_no->is_sink())
1791     {
1792       if (val_no->is_variable())
1793         val_no->var_value()->add_preinit_statement(this->gogo_, s);
1794     }
1795   else if (!no->is_sink())
1796     {
1797       if (no->is_variable())
1798         no->var_value()->add_preinit_statement(this->gogo_, s);
1799     }
1800   else
1801     {
1802       Named_object* dummy = this->create_dummy_global(type, NULL, location);
1803       dummy->var_value()->add_preinit_statement(this->gogo_, s);
1804     }
1805
1806   return true;
1807 }
1808
1809 // Create a single variable.  If IS_COLONEQ is true, we permit
1810 // redeclarations in the same block, and we set *IS_NEW when we find a
1811 // new variable which is not a redeclaration.
1812
1813 Named_object*
1814 Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
1815                 bool is_coloneq, bool type_from_init, bool* is_new)
1816 {
1817   source_location location = tid.location();
1818
1819   if (Gogo::is_sink_name(tid.name()))
1820     {
1821       if (!type_from_init && init != NULL)
1822         {
1823           if (!this->gogo_->in_global_scope())
1824             this->gogo_->add_statement(Statement::make_statement(init));
1825           else
1826             return this->create_dummy_global(type, init, location);
1827         }
1828       return this->gogo_->add_sink();
1829     }
1830
1831   if (is_coloneq)
1832     {
1833       Named_object* no = this->gogo_->lookup_in_block(tid.name());
1834       if (no != NULL
1835           && (no->is_variable() || no->is_result_variable()))
1836         {
1837           // INIT may be NULL even when IS_COLONEQ is true for cases
1838           // like v, ok := x.(int).
1839           if (!type_from_init && init != NULL)
1840             {
1841               Expression *v = Expression::make_var_reference(no, location);
1842               Statement *s = Statement::make_assignment(v, init, location);
1843               this->gogo_->add_statement(s);
1844             }
1845           return no;
1846         }
1847     }
1848   *is_new = true;
1849   Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
1850                                false, false, location);
1851   Named_object* no = this->gogo_->add_variable(tid.name(), var);
1852   if (!no->is_variable())
1853     {
1854       // The name is already defined, so we just gave an error.
1855       return this->gogo_->add_sink();
1856     }
1857   return no;
1858 }
1859
1860 // Create a dummy global variable to force an initializer to be run in
1861 // the right place.  This is used when a sink variable is initialized
1862 // at global scope.
1863
1864 Named_object*
1865 Parse::create_dummy_global(Type* type, Expression* init,
1866                            source_location location)
1867 {
1868   if (type == NULL && init == NULL)
1869     type = Type::lookup_bool_type();
1870   Variable* var = new Variable(type, init, true, false, false, location);
1871   static int count;
1872   char buf[30];
1873   snprintf(buf, sizeof buf, "_.%d", count);
1874   ++count;
1875   return this->gogo_->add_variable(buf, var);
1876 }
1877
1878 // SimpleVarDecl = identifier ":=" Expression .
1879
1880 // We've already seen the identifier.
1881
1882 // FIXME: We also have to implement
1883 //  IdentifierList ":=" ExpressionList
1884 // In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
1885 // tuple assignments here as well.
1886
1887 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
1888 // RangeClause.
1889
1890 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
1891 // guard (var := expr.("type") using the literal keyword "type").
1892
1893 void
1894 Parse::simple_var_decl_or_assignment(const std::string& name,
1895                                      source_location location,
1896                                      Range_clause* p_range_clause,
1897                                      Type_switch* p_type_switch)
1898 {
1899   Typed_identifier_list til;
1900   til.push_back(Typed_identifier(name, NULL, location));
1901
1902   // We've seen one identifier.  If we see a comma now, this could be
1903   // "a, *p = 1, 2".
1904   if (this->peek_token()->is_op(OPERATOR_COMMA))
1905     {
1906       gcc_assert(p_type_switch == NULL);
1907       while (true)
1908         {
1909           const Token* token = this->advance_token();
1910           if (!token->is_identifier())
1911             break;
1912
1913           std::string id = token->identifier();
1914           bool is_id_exported = token->is_identifier_exported();
1915           source_location id_location = token->location();
1916
1917           token = this->advance_token();
1918           if (!token->is_op(OPERATOR_COMMA))
1919             {
1920               if (token->is_op(OPERATOR_COLONEQ))
1921                 {
1922                   id = this->gogo_->pack_hidden_name(id, is_id_exported);
1923                   til.push_back(Typed_identifier(id, NULL, location));
1924                 }
1925               else
1926                 this->unget_token(Token::make_identifier_token(id,
1927                                                                is_id_exported,
1928                                                                id_location));
1929               break;
1930             }
1931
1932           id = this->gogo_->pack_hidden_name(id, is_id_exported);
1933           til.push_back(Typed_identifier(id, NULL, location));
1934         }
1935
1936       // We have a comma separated list of identifiers in TIL.  If the
1937       // next token is COLONEQ, then this is a simple var decl, and we
1938       // have the complete list of identifiers.  If the next token is
1939       // not COLONEQ, then the only valid parse is a tuple assignment.
1940       // The list of identifiers we have so far is really a list of
1941       // expressions.  There are more expressions following.
1942
1943       if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
1944         {
1945           Expression_list* exprs = new Expression_list;
1946           for (Typed_identifier_list::const_iterator p = til.begin();
1947                p != til.end();
1948                ++p)
1949             exprs->push_back(this->id_to_expression(p->name(),
1950                                                     p->location()));
1951
1952           Expression_list* more_exprs = this->expression_list(NULL, true);
1953           for (Expression_list::const_iterator p = more_exprs->begin();
1954                p != more_exprs->end();
1955                ++p)
1956             exprs->push_back(*p);
1957           delete more_exprs;
1958
1959           this->tuple_assignment(exprs, p_range_clause);
1960           return;
1961         }
1962     }
1963
1964   gcc_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
1965   const Token* token = this->advance_token();
1966
1967   if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
1968     {
1969       this->range_clause_decl(&til, p_range_clause);
1970       return;
1971     }
1972
1973   Expression_list* init;
1974   if (p_type_switch == NULL)
1975     init = this->expression_list(NULL, false);
1976   else
1977     {
1978       bool is_type_switch = false;
1979       Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
1980                                           &is_type_switch);
1981       if (is_type_switch)
1982         {
1983           p_type_switch->found = true;
1984           p_type_switch->name = name;
1985           p_type_switch->location = location;
1986           p_type_switch->expr = expr;
1987           return;
1988         }
1989
1990       if (!this->peek_token()->is_op(OPERATOR_COMMA))
1991         {
1992           init = new Expression_list();
1993           init->push_back(expr);
1994         }
1995       else
1996         {
1997           this->advance_token();
1998           init = this->expression_list(expr, false);
1999         }
2000     }
2001
2002   this->init_vars(&til, NULL, init, true, location);
2003 }
2004
2005 // FunctionDecl = "func" identifier Signature [ Block ] .
2006 // MethodDecl = "func" Receiver identifier Signature [ Block ] .
2007
2008 // gcc extension:
2009 //   FunctionDecl = "func" identifier Signature
2010 //                    __asm__ "(" string_lit ")" .
2011 // This extension means a function whose real name is the identifier
2012 // inside the asm.
2013
2014 void
2015 Parse::function_decl()
2016 {
2017   gcc_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2018   source_location location = this->location();
2019   const Token* token = this->advance_token();
2020
2021   Typed_identifier* rec = NULL;
2022   if (token->is_op(OPERATOR_LPAREN))
2023     {
2024       rec = this->receiver();
2025       token = this->peek_token();
2026     }
2027
2028   if (!token->is_identifier())
2029     {
2030       error_at(this->location(), "expected function name");
2031       return;
2032     }
2033
2034   std::string name =
2035     this->gogo_->pack_hidden_name(token->identifier(),
2036                                   token->is_identifier_exported());
2037
2038   this->advance_token();
2039
2040   Function_type* fntype = this->signature(rec, this->location());
2041   if (fntype == NULL)
2042     return;
2043
2044   Named_object* named_object = NULL;
2045
2046   if (this->peek_token()->is_keyword(KEYWORD_ASM))
2047     {
2048       if (!this->advance_token()->is_op(OPERATOR_LPAREN))
2049         {
2050           error_at(this->location(), "expected %<(%>");
2051           return;
2052         }
2053       token = this->advance_token();
2054       if (!token->is_string())
2055         {
2056           error_at(this->location(), "expected string");
2057           return;
2058         }
2059       std::string asm_name = token->string_value();
2060       if (!this->advance_token()->is_op(OPERATOR_RPAREN))
2061         {
2062           error_at(this->location(), "expected %<)%>");
2063           return;
2064         }
2065       this->advance_token();
2066       if (!Gogo::is_sink_name(name))
2067         {
2068           named_object = this->gogo_->declare_function(name, fntype, location);
2069           if (named_object->is_function_declaration())
2070             named_object->func_declaration_value()->set_asm_name(asm_name);
2071         }
2072     }
2073
2074   // Check for the easy error of a newline before the opening brace.
2075   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
2076     {
2077       source_location semi_loc = this->location();
2078       if (this->advance_token()->is_op(OPERATOR_LCURLY))
2079         error_at(this->location(),
2080                  "unexpected semicolon or newline before %<{%>");
2081       else
2082         this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
2083                                                      semi_loc));
2084     }
2085
2086   if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2087     {
2088       if (named_object == NULL && !Gogo::is_sink_name(name))
2089         this->gogo_->declare_function(name, fntype, location);
2090     }
2091   else
2092     {
2093       this->gogo_->start_function(name, fntype, true, location);
2094       source_location end_loc = this->block();
2095       this->gogo_->finish_function(end_loc);
2096     }
2097 }
2098
2099 // Receiver     = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
2100 // BaseTypeName = identifier .
2101
2102 Typed_identifier*
2103 Parse::receiver()
2104 {
2105   gcc_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
2106
2107   std::string name;
2108   const Token* token = this->advance_token();
2109   source_location location = token->location();
2110   if (!token->is_op(OPERATOR_MULT))
2111     {
2112       if (!token->is_identifier())
2113         {
2114           error_at(this->location(), "method has no receiver");
2115           while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2116             token = this->advance_token();
2117           if (!token->is_eof())
2118             this->advance_token();
2119           return NULL;
2120         }
2121       name = token->identifier();
2122       bool is_exported = token->is_identifier_exported();
2123       token = this->advance_token();
2124       if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN))
2125         {
2126           // An identifier followed by something other than a dot or a
2127           // right parenthesis must be a receiver name followed by a
2128           // type.
2129           name = this->gogo_->pack_hidden_name(name, is_exported);
2130         }
2131       else
2132         {
2133           // This must be a type name.
2134           this->unget_token(Token::make_identifier_token(name, is_exported,
2135                                                          location));
2136           token = this->peek_token();
2137           name.clear();
2138         }
2139     }
2140
2141   // Here the receiver name is in NAME (it is empty if the receiver is
2142   // unnamed) and TOKEN is the first token in the type.
2143
2144   bool is_pointer = false;
2145   if (token->is_op(OPERATOR_MULT))
2146     {
2147       is_pointer = true;
2148       token = this->advance_token();
2149     }
2150
2151   if (!token->is_identifier())
2152     {
2153       error_at(this->location(), "expected receiver name or type");
2154       int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0;
2155       while (!token->is_eof())
2156         {
2157           token = this->advance_token();
2158           if (token->is_op(OPERATOR_LPAREN))
2159             ++c;
2160           else if (token->is_op(OPERATOR_RPAREN))
2161             {
2162               if (c == 0)
2163                 break;
2164               --c;
2165             }
2166         }
2167       if (!token->is_eof())
2168         this->advance_token();
2169       return NULL;
2170     }
2171
2172   Type* type = this->type_name(true);
2173
2174   if (is_pointer && !type->is_error_type())
2175     type = Type::make_pointer_type(type);
2176
2177   if (this->peek_token()->is_op(OPERATOR_RPAREN))
2178     this->advance_token();
2179   else
2180     {
2181       if (this->peek_token()->is_op(OPERATOR_COMMA))
2182         error_at(this->location(), "method has multiple receivers");
2183       else
2184         error_at(this->location(), "expected %<)%>");
2185       while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2186         token = this->advance_token();
2187       if (!token->is_eof())
2188         this->advance_token();
2189       return NULL;
2190     }
2191
2192   return new Typed_identifier(name, type, location);
2193 }
2194
2195 // Operand    = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2196 // Literal    = BasicLit | CompositeLit | FunctionLit .
2197 // BasicLit   = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2198
2199 // If MAY_BE_SINK is true, this operand may be "_".
2200
2201 Expression*
2202 Parse::operand(bool may_be_sink)
2203 {
2204   const Token* token = this->peek_token();
2205   Expression* ret;
2206   switch (token->classification())
2207     {
2208     case Token::TOKEN_IDENTIFIER:
2209       {
2210         source_location location = token->location();
2211         std::string id = token->identifier();
2212         bool is_exported = token->is_identifier_exported();
2213         std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2214
2215         Named_object* in_function;
2216         Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2217
2218         Package* package = NULL;
2219         if (named_object != NULL && named_object->is_package())
2220           {
2221             if (!this->advance_token()->is_op(OPERATOR_DOT)
2222                 || !this->advance_token()->is_identifier())
2223               {
2224                 error_at(location, "unexpected reference to package");
2225                 return Expression::make_error(location);
2226               }
2227             package = named_object->package_value();
2228             package->set_used();
2229             id = this->peek_token()->identifier();
2230             is_exported = this->peek_token()->is_identifier_exported();
2231             packed = this->gogo_->pack_hidden_name(id, is_exported);
2232             named_object = package->lookup(packed);
2233             location = this->location();
2234             gcc_assert(in_function == NULL);
2235           }
2236
2237         this->advance_token();
2238
2239         if (named_object != NULL
2240             && named_object->is_type()
2241             && !named_object->type_value()->is_visible())
2242           {
2243             gcc_assert(package != NULL);
2244             error_at(location, "invalid reference to hidden type %<%s.%s%>",
2245                      Gogo::message_name(package->name()).c_str(),
2246                      Gogo::message_name(id).c_str());
2247             return Expression::make_error(location);
2248           }
2249
2250
2251         if (named_object == NULL)
2252           {
2253             if (package != NULL)
2254               {
2255                 std::string n1 = Gogo::message_name(package->name());
2256                 std::string n2 = Gogo::message_name(id);
2257                 if (!is_exported)
2258                   error_at(location,
2259                            ("invalid reference to unexported identifier "
2260                             "%<%s.%s%>"),
2261                            n1.c_str(), n2.c_str());
2262                 else
2263                   error_at(location,
2264                            "reference to undefined identifier %<%s.%s%>",
2265                            n1.c_str(), n2.c_str());
2266                 return Expression::make_error(location);
2267               }
2268
2269             named_object = this->gogo_->add_unknown_name(packed, location);
2270           }
2271
2272         if (in_function != NULL
2273             && in_function != this->gogo_->current_function()
2274             && (named_object->is_variable()
2275                 || named_object->is_result_variable()))
2276           return this->enclosing_var_reference(in_function, named_object,
2277                                                location);
2278
2279         switch (named_object->classification())
2280           {
2281           case Named_object::NAMED_OBJECT_CONST:
2282             return Expression::make_const_reference(named_object, location);
2283           case Named_object::NAMED_OBJECT_TYPE:
2284             return Expression::make_type(named_object->type_value(), location);
2285           case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2286             {
2287               Type* t = Type::make_forward_declaration(named_object);
2288               return Expression::make_type(t, location);
2289             }
2290           case Named_object::NAMED_OBJECT_VAR:
2291           case Named_object::NAMED_OBJECT_RESULT_VAR:
2292             return Expression::make_var_reference(named_object, location);
2293           case Named_object::NAMED_OBJECT_SINK:
2294             if (may_be_sink)
2295               return Expression::make_sink(location);
2296             else
2297               {
2298                 error_at(location, "cannot use _ as value");
2299                 return Expression::make_error(location);
2300               }
2301           case Named_object::NAMED_OBJECT_FUNC:
2302           case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2303             return Expression::make_func_reference(named_object, NULL,
2304                                                    location);
2305           case Named_object::NAMED_OBJECT_UNKNOWN:
2306             return Expression::make_unknown_reference(named_object, location);
2307           default:
2308             gcc_unreachable();
2309           }
2310       }
2311       gcc_unreachable();
2312
2313     case Token::TOKEN_STRING:
2314       ret = Expression::make_string(token->string_value(), token->location());
2315       this->advance_token();
2316       return ret;
2317
2318     case Token::TOKEN_INTEGER:
2319       ret = Expression::make_integer(token->integer_value(), NULL,
2320                                      token->location());
2321       this->advance_token();
2322       return ret;
2323
2324     case Token::TOKEN_FLOAT:
2325       ret = Expression::make_float(token->float_value(), NULL,
2326                                    token->location());
2327       this->advance_token();
2328       return ret;
2329
2330     case Token::TOKEN_IMAGINARY:
2331       {
2332         mpfr_t zero;
2333         mpfr_init_set_ui(zero, 0, GMP_RNDN);
2334         ret = Expression::make_complex(&zero, token->imaginary_value(),
2335                                        NULL, token->location());
2336         mpfr_clear(zero);
2337         this->advance_token();
2338         return ret;
2339       }
2340
2341     case Token::TOKEN_KEYWORD:
2342       switch (token->keyword())
2343         {
2344         case KEYWORD_FUNC:
2345           return this->function_lit();
2346         case KEYWORD_CHAN:
2347         case KEYWORD_INTERFACE:
2348         case KEYWORD_MAP:
2349         case KEYWORD_STRUCT:
2350           {
2351             source_location location = token->location();
2352             return Expression::make_type(this->type(), location);
2353           }
2354         default:
2355           break;
2356         }
2357       break;
2358
2359     case Token::TOKEN_OPERATOR:
2360       if (token->is_op(OPERATOR_LPAREN))
2361         {
2362           this->advance_token();
2363           ret = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2364           if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2365             error_at(this->location(), "missing %<)%>");
2366           else
2367             this->advance_token();
2368           return ret;
2369         }
2370       else if (token->is_op(OPERATOR_LSQUARE))
2371         {
2372           // Here we call array_type directly, as this is the only
2373           // case where an ellipsis is permitted for an array type.
2374           source_location location = token->location();
2375           return Expression::make_type(this->array_type(true), location);
2376         }
2377       break;
2378
2379     default:
2380       break;
2381     }
2382
2383   error_at(this->location(), "expected operand");
2384   return Expression::make_error(this->location());
2385 }
2386
2387 // Handle a reference to a variable in an enclosing function.  We add
2388 // it to a list of such variables.  We return a reference to a field
2389 // in a struct which will be passed on the static chain when calling
2390 // the current function.
2391
2392 Expression*
2393 Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2394                                source_location location)
2395 {
2396   gcc_assert(var->is_variable() || var->is_result_variable());
2397
2398   Named_object* this_function = this->gogo_->current_function();
2399   Named_object* closure = this_function->func_value()->closure_var();
2400
2401   Enclosing_var ev(var, in_function, this->enclosing_vars_.size());
2402   std::pair<Enclosing_vars::iterator, bool> ins =
2403     this->enclosing_vars_.insert(ev);
2404   if (ins.second)
2405     {
2406       // This is a variable we have not seen before.  Add a new field
2407       // to the closure type.
2408       this_function->func_value()->add_closure_field(var, location);
2409     }
2410
2411   Expression* closure_ref = Expression::make_var_reference(closure,
2412                                                            location);
2413   closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location);
2414
2415   // The closure structure holds pointers to the variables, so we need
2416   // to introduce an indirection.
2417   Expression* e = Expression::make_field_reference(closure_ref,
2418                                                    ins.first->index(),
2419                                                    location);
2420   e = Expression::make_unary(OPERATOR_MULT, e, location);
2421   return e;
2422 }
2423
2424 // CompositeLit  = LiteralType LiteralValue .
2425 // LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
2426 //                 SliceType | MapType | TypeName .
2427 // LiteralValue  = "{" [ ElementList [ "," ] ] "}" .
2428 // ElementList   = Element { "," Element } .
2429 // Element       = [ Key ":" ] Value .
2430 // Key           = Expression .
2431 // Value         = Expression | LiteralValue .
2432
2433 // We have already seen the type if there is one, and we are now
2434 // looking at the LiteralValue.  The case "[" "..."  "]" ElementType
2435 // will be seen here as an array type whose length is "nil".  The
2436 // DEPTH parameter is non-zero if this is an embedded composite
2437 // literal and the type was omitted.  It gives the number of steps up
2438 // to the type which was provided.  E.g., in [][]int{{1}} it will be
2439 // 1.  In [][][]int{{{1}}} it will be 2.
2440
2441 Expression*
2442 Parse::composite_lit(Type* type, int depth, source_location location)
2443 {
2444   gcc_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2445   this->advance_token();
2446
2447   if (this->peek_token()->is_op(OPERATOR_RCURLY))
2448     {
2449       this->advance_token();
2450       return Expression::make_composite_literal(type, depth, false, NULL,
2451                                                 location);
2452     }
2453
2454   bool has_keys = false;
2455   Expression_list* vals = new Expression_list;
2456   while (true)
2457     {
2458       Expression* val;
2459       bool is_type_omitted = false;
2460
2461       const Token* token = this->peek_token();
2462
2463       if (!token->is_op(OPERATOR_LCURLY))
2464         val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2465       else
2466         {
2467           // This must be a composite literal inside another composite
2468           // literal, with the type omitted for the inner one.
2469           val = this->composite_lit(type, depth + 1, token->location());
2470           is_type_omitted = true;
2471         }
2472
2473       token = this->peek_token();
2474       if (!token->is_op(OPERATOR_COLON))
2475         {
2476           if (has_keys)
2477             vals->push_back(NULL);
2478         }
2479       else
2480         {
2481           if (is_type_omitted && !val->is_error_expression())
2482             {
2483               error_at(this->location(), "unexpected %<:%>");
2484               val = Expression::make_error(this->location());
2485             }
2486
2487           this->advance_token();
2488
2489           if (!has_keys && !vals->empty())
2490             {
2491               Expression_list* newvals = new Expression_list;
2492               for (Expression_list::const_iterator p = vals->begin();
2493                    p != vals->end();
2494                    ++p)
2495                 {
2496                   newvals->push_back(NULL);
2497                   newvals->push_back(*p);
2498                 }
2499               delete vals;
2500               vals = newvals;
2501             }
2502           has_keys = true;
2503
2504           if (val->unknown_expression() != NULL)
2505             val->unknown_expression()->set_is_composite_literal_key();
2506
2507           vals->push_back(val);
2508
2509           if (!token->is_op(OPERATOR_LCURLY))
2510             val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2511           else
2512             {
2513               // This must be a composite literal inside another
2514               // composite literal, with the type omitted for the
2515               // inner one.
2516               val = this->composite_lit(type, depth + 1, token->location());
2517             }
2518
2519           token = this->peek_token();
2520         }
2521
2522       vals->push_back(val);
2523
2524       if (token->is_op(OPERATOR_COMMA))
2525         {
2526           if (this->advance_token()->is_op(OPERATOR_RCURLY))
2527             {
2528               this->advance_token();
2529               break;
2530             }
2531         }
2532       else if (token->is_op(OPERATOR_RCURLY))
2533         {
2534           this->advance_token();
2535           break;
2536         }
2537       else
2538         {
2539           error_at(this->location(), "expected %<,%> or %<}%>");
2540
2541           int depth = 0;
2542           while (!token->is_eof()
2543                  && (depth > 0 || !token->is_op(OPERATOR_RCURLY)))
2544             {
2545               if (token->is_op(OPERATOR_LCURLY))
2546                 ++depth;
2547               else if (token->is_op(OPERATOR_RCURLY))
2548                 --depth;
2549               token = this->advance_token();
2550             }
2551           if (token->is_op(OPERATOR_RCURLY))
2552             this->advance_token();
2553
2554           return Expression::make_error(location);
2555         }
2556     }
2557
2558   return Expression::make_composite_literal(type, depth, has_keys, vals,
2559                                             location);
2560 }
2561
2562 // FunctionLit = "func" Signature Block .
2563
2564 Expression*
2565 Parse::function_lit()
2566 {
2567   source_location location = this->location();
2568   gcc_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2569   this->advance_token();
2570
2571   Enclosing_vars hold_enclosing_vars;
2572   hold_enclosing_vars.swap(this->enclosing_vars_);
2573
2574   Function_type* type = this->signature(NULL, location);
2575   if (type == NULL)
2576     type = Type::make_function_type(NULL, NULL, NULL, location);
2577
2578   // For a function literal, the next token must be a '{'.  If we
2579   // don't see that, then we may have a type expression.
2580   if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2581     return Expression::make_type(type, location);
2582
2583   Bc_stack* hold_break_stack = this->break_stack_;
2584   Bc_stack* hold_continue_stack = this->continue_stack_;
2585   this->break_stack_ = NULL;
2586   this->continue_stack_ = NULL;
2587
2588   Named_object* no = this->gogo_->start_function("", type, true, location);
2589
2590   source_location end_loc = this->block();
2591
2592   this->gogo_->finish_function(end_loc);
2593
2594   if (this->break_stack_ != NULL)
2595     delete this->break_stack_;
2596   if (this->continue_stack_ != NULL)
2597     delete this->continue_stack_;
2598   this->break_stack_ = hold_break_stack;
2599   this->continue_stack_ = hold_continue_stack;
2600
2601   hold_enclosing_vars.swap(this->enclosing_vars_);
2602
2603   Expression* closure = this->create_closure(no, &hold_enclosing_vars,
2604                                              location);
2605
2606   return Expression::make_func_reference(no, closure, location);
2607 }
2608
2609 // Create a closure for the nested function FUNCTION.  This is based
2610 // on ENCLOSING_VARS, which is a list of all variables defined in
2611 // enclosing functions and referenced from FUNCTION.  A closure is the
2612 // address of a struct which contains the addresses of all the
2613 // referenced variables.  This returns NULL if no closure is required.
2614
2615 Expression*
2616 Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
2617                       source_location location)
2618 {
2619   if (enclosing_vars->empty())
2620     return NULL;
2621
2622   // Get the variables in order by their field index.
2623
2624   size_t enclosing_var_count = enclosing_vars->size();
2625   std::vector<Enclosing_var> ev(enclosing_var_count);
2626   for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
2627        p != enclosing_vars->end();
2628        ++p)
2629     ev[p->index()] = *p;
2630
2631   // Build an initializer for a composite literal of the closure's
2632   // type.
2633
2634   Named_object* enclosing_function = this->gogo_->current_function();
2635   Expression_list* initializer = new Expression_list;
2636   for (size_t i = 0; i < enclosing_var_count; ++i)
2637     {
2638       gcc_assert(ev[i].index() == i);
2639       Named_object* var = ev[i].var();
2640       Expression* ref;
2641       if (ev[i].in_function() == enclosing_function)
2642         ref = Expression::make_var_reference(var, location);
2643       else
2644         ref = this->enclosing_var_reference(ev[i].in_function(), var,
2645                                             location);
2646       Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
2647                                                    location);
2648       initializer->push_back(refaddr);
2649     }
2650
2651   Named_object* closure_var = function->func_value()->closure_var();
2652   Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
2653   Expression* cv = Expression::make_struct_composite_literal(st, initializer,
2654                                                              location);
2655   return Expression::make_heap_composite(cv, location);
2656 }
2657
2658 // PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
2659
2660 // If MAY_BE_SINK is true, this expression may be "_".
2661
2662 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
2663 // literal.
2664
2665 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2666 // guard (var := expr.("type") using the literal keyword "type").
2667
2668 Expression*
2669 Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
2670                     bool* is_type_switch)
2671 {
2672   source_location start_loc = this->location();
2673   bool is_parenthesized = this->peek_token()->is_op(OPERATOR_LPAREN);
2674
2675   Expression* ret = this->operand(may_be_sink);
2676
2677   // An unknown name followed by a curly brace must be a composite
2678   // literal, and the unknown name must be a type.
2679   if (may_be_composite_lit
2680       && !is_parenthesized
2681       && ret->unknown_expression() != NULL
2682       && this->peek_token()->is_op(OPERATOR_LCURLY))
2683     {
2684       Named_object* no = ret->unknown_expression()->named_object();
2685       Type* type = Type::make_forward_declaration(no);
2686       ret = Expression::make_type(type, ret->location());
2687     }
2688
2689   // We handle composite literals and type casts here, as it is the
2690   // easiest way to handle types which are in parentheses, as in
2691   // "((uint))(1)".
2692   if (ret->is_type_expression())
2693     {
2694       if (this->peek_token()->is_op(OPERATOR_LCURLY))
2695         {
2696           if (is_parenthesized)
2697             error_at(start_loc,
2698                      "cannot parenthesize type in composite literal");
2699           ret = this->composite_lit(ret->type(), 0, ret->location());
2700         }
2701       else if (this->peek_token()->is_op(OPERATOR_LPAREN))
2702         {
2703           source_location loc = this->location();
2704           this->advance_token();
2705           Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
2706                                               NULL);
2707           if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2708             error_at(this->location(), "expected %<)%>");
2709           else
2710             this->advance_token();
2711           if (expr->is_error_expression())
2712             return expr;
2713           ret = Expression::make_cast(ret->type(), expr, loc);
2714         }
2715     }
2716
2717   while (true)
2718     {
2719       const Token* token = this->peek_token();
2720       if (token->is_op(OPERATOR_LPAREN))
2721         ret = this->call(this->verify_not_sink(ret));
2722       else if (token->is_op(OPERATOR_DOT))
2723         {
2724           ret = this->selector(this->verify_not_sink(ret), is_type_switch);
2725           if (is_type_switch != NULL && *is_type_switch)
2726             break;
2727         }
2728       else if (token->is_op(OPERATOR_LSQUARE))
2729         ret = this->index(this->verify_not_sink(ret));
2730       else
2731         break;
2732     }
2733
2734   return ret;
2735 }
2736
2737 // Selector = "." identifier .
2738 // TypeGuard = "." "(" QualifiedIdent ")" .
2739
2740 // Note that Operand can expand to QualifiedIdent, which contains a
2741 // ".".  That is handled directly in operand when it sees a package
2742 // name.
2743
2744 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2745 // guard (var := expr.("type") using the literal keyword "type").
2746
2747 Expression*
2748 Parse::selector(Expression* left, bool* is_type_switch)
2749 {
2750   gcc_assert(this->peek_token()->is_op(OPERATOR_DOT));
2751   source_location location = this->location();
2752
2753   const Token* token = this->advance_token();
2754   if (token->is_identifier())
2755     {
2756       // This could be a field in a struct, or a method in an
2757       // interface, or a method associated with a type.  We can't know
2758       // which until we have seen all the types.
2759       std::string name =
2760         this->gogo_->pack_hidden_name(token->identifier(),
2761                                       token->is_identifier_exported());
2762       if (token->identifier() == "_")
2763         {
2764           error_at(this->location(), "invalid use of %<_%>");
2765           name = this->gogo_->pack_hidden_name("blank", false);
2766         }
2767       this->advance_token();
2768       return Expression::make_selector(left, name, location);
2769     }
2770   else if (token->is_op(OPERATOR_LPAREN))
2771     {
2772       this->advance_token();
2773       Type* type = NULL;
2774       if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
2775         type = this->type();
2776       else
2777         {
2778           if (is_type_switch != NULL)
2779             *is_type_switch = true;
2780           else
2781             {
2782               error_at(this->location(),
2783                        "use of %<.(type)%> outside type switch");
2784               type = Type::make_error_type();
2785             }
2786           this->advance_token();
2787         }
2788       if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2789         error_at(this->location(), "missing %<)%>");
2790       else
2791         this->advance_token();
2792       if (is_type_switch != NULL && *is_type_switch)
2793         return left;
2794       return Expression::make_type_guard(left, type, location);
2795     }
2796   else
2797     {
2798       error_at(this->location(), "expected identifier or %<(%>");
2799       return left;
2800     }
2801 }
2802
2803 // Index          = "[" Expression "]" .
2804 // Slice          = "[" Expression ":" [ Expression ] "]" .
2805
2806 Expression*
2807 Parse::index(Expression* expr)
2808 {
2809   source_location location = this->location();
2810   gcc_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
2811   this->advance_token();
2812
2813   Expression* start;
2814   if (!this->peek_token()->is_op(OPERATOR_COLON))
2815     start = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2816   else
2817     {
2818       mpz_t zero;
2819       mpz_init_set_ui(zero, 0);
2820       start = Expression::make_integer(&zero, NULL, location);
2821       mpz_clear(zero);
2822     }
2823
2824   Expression* end = NULL;
2825   if (this->peek_token()->is_op(OPERATOR_COLON))
2826     {
2827       // We use nil to indicate a missing high expression.
2828       if (this->advance_token()->is_op(OPERATOR_RSQUARE))
2829         end = Expression::make_nil(this->location());
2830       else
2831         end = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2832     }
2833   if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
2834     error_at(this->location(), "missing %<]%>");
2835   else
2836     this->advance_token();
2837   return Expression::make_index(expr, start, end, location);
2838 }
2839
2840 // Call           = "(" [ ArgumentList [ "," ] ] ")" .
2841 // ArgumentList   = ExpressionList [ "..." ] .
2842
2843 Expression*
2844 Parse::call(Expression* func)
2845 {
2846   gcc_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
2847   Expression_list* args = NULL;
2848   bool is_varargs = false;
2849   const Token* token = this->advance_token();
2850   if (!token->is_op(OPERATOR_RPAREN))
2851     {
2852       args = this->expression_list(NULL, false);
2853       token = this->peek_token();
2854       if (token->is_op(OPERATOR_ELLIPSIS))
2855         {
2856           is_varargs = true;
2857           token = this->advance_token();
2858         }
2859     }
2860   if (token->is_op(OPERATOR_COMMA))
2861     token = this->advance_token();
2862   if (!token->is_op(OPERATOR_RPAREN))
2863     error_at(this->location(), "missing %<)%>");
2864   else
2865     this->advance_token();
2866   if (func->is_error_expression())
2867     return func;
2868   return Expression::make_call(func, args, is_varargs, func->location());
2869 }
2870
2871 // Return an expression for a single unqualified identifier.
2872
2873 Expression*
2874 Parse::id_to_expression(const std::string& name, source_location location)
2875 {
2876   Named_object* in_function;
2877   Named_object* named_object = this->gogo_->lookup(name, &in_function);
2878   if (named_object == NULL)
2879     named_object = this->gogo_->add_unknown_name(name, location);
2880
2881   if (in_function != NULL
2882       && in_function != this->gogo_->current_function()
2883       && (named_object->is_variable() || named_object->is_result_variable()))
2884     return this->enclosing_var_reference(in_function, named_object,
2885                                          location);
2886
2887   switch (named_object->classification())
2888     {
2889     case Named_object::NAMED_OBJECT_CONST:
2890       return Expression::make_const_reference(named_object, location);
2891     case Named_object::NAMED_OBJECT_VAR:
2892     case Named_object::NAMED_OBJECT_RESULT_VAR:
2893       return Expression::make_var_reference(named_object, location);
2894     case Named_object::NAMED_OBJECT_SINK:
2895       return Expression::make_sink(location);
2896     case Named_object::NAMED_OBJECT_FUNC:
2897     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2898       return Expression::make_func_reference(named_object, NULL, location);
2899     case Named_object::NAMED_OBJECT_UNKNOWN:
2900       return Expression::make_unknown_reference(named_object, location);
2901     default:
2902       error_at(this->location(), "unexpected type of identifier");
2903       return Expression::make_error(location);
2904     }
2905 }
2906
2907 // Expression = UnaryExpr { binary_op Expression } .
2908
2909 // PRECEDENCE is the precedence of the current operator.
2910
2911 // If MAY_BE_SINK is true, this expression may be "_".
2912
2913 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
2914 // literal.
2915
2916 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2917 // guard (var := expr.("type") using the literal keyword "type").
2918
2919 Expression*
2920 Parse::expression(Precedence precedence, bool may_be_sink,
2921                   bool may_be_composite_lit, bool* is_type_switch)
2922 {
2923   Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
2924                                       is_type_switch);
2925
2926   while (true)
2927     {
2928       if (is_type_switch != NULL && *is_type_switch)
2929         return left;
2930
2931       const Token* token = this->peek_token();
2932       if (token->classification() != Token::TOKEN_OPERATOR)
2933         {
2934           // Not a binary_op.
2935           return left;
2936         }
2937
2938       Precedence right_precedence;
2939       switch (token->op())
2940         {
2941         case OPERATOR_OROR:
2942           right_precedence = PRECEDENCE_OROR;
2943           break;
2944         case OPERATOR_ANDAND:
2945           right_precedence = PRECEDENCE_ANDAND;
2946           break;
2947         case OPERATOR_EQEQ:
2948         case OPERATOR_NOTEQ:
2949         case OPERATOR_LT:
2950         case OPERATOR_LE:
2951         case OPERATOR_GT:
2952         case OPERATOR_GE:
2953           right_precedence = PRECEDENCE_RELOP;
2954           break;
2955         case OPERATOR_PLUS:
2956         case OPERATOR_MINUS:
2957         case OPERATOR_OR:
2958         case OPERATOR_XOR:
2959           right_precedence = PRECEDENCE_ADDOP;
2960           break;
2961         case OPERATOR_MULT:
2962         case OPERATOR_DIV:
2963         case OPERATOR_MOD:
2964         case OPERATOR_LSHIFT:
2965         case OPERATOR_RSHIFT:
2966         case OPERATOR_AND:
2967         case OPERATOR_BITCLEAR:
2968           right_precedence = PRECEDENCE_MULOP;
2969           break;
2970         default:
2971           right_precedence = PRECEDENCE_INVALID;
2972           break;
2973         }
2974
2975       if (right_precedence == PRECEDENCE_INVALID)
2976         {
2977           // Not a binary_op.
2978           return left;
2979         }
2980
2981       Operator op = token->op();
2982       source_location binop_location = token->location();
2983
2984       if (precedence >= right_precedence)
2985         {
2986           // We've already seen A * B, and we see + C.  We want to
2987           // return so that A * B becomes a group.
2988           return left;
2989         }
2990
2991       this->advance_token();
2992
2993       left = this->verify_not_sink(left);
2994       Expression* right = this->expression(right_precedence, false,
2995                                            may_be_composite_lit,
2996                                            NULL);
2997       left = Expression::make_binary(op, left, right, binop_location);
2998     }
2999 }
3000
3001 bool
3002 Parse::expression_may_start_here()
3003 {
3004   const Token* token = this->peek_token();
3005   switch (token->classification())
3006     {
3007     case Token::TOKEN_INVALID:
3008     case Token::TOKEN_EOF:
3009       return false;
3010     case Token::TOKEN_KEYWORD:
3011       switch (token->keyword())
3012         {
3013         case KEYWORD_CHAN:
3014         case KEYWORD_FUNC:
3015         case KEYWORD_MAP:
3016         case KEYWORD_STRUCT:
3017         case KEYWORD_INTERFACE:
3018           return true;
3019         default:
3020           return false;
3021         }
3022     case Token::TOKEN_IDENTIFIER:
3023       return true;
3024     case Token::TOKEN_STRING:
3025       return true;
3026     case Token::TOKEN_OPERATOR:
3027       switch (token->op())
3028         {
3029         case OPERATOR_PLUS:
3030         case OPERATOR_MINUS:
3031         case OPERATOR_NOT:
3032         case OPERATOR_XOR:
3033         case OPERATOR_MULT:
3034         case OPERATOR_CHANOP:
3035         case OPERATOR_AND:
3036         case OPERATOR_LPAREN:
3037         case OPERATOR_LSQUARE:
3038           return true;
3039         default:
3040           return false;
3041         }
3042     case Token::TOKEN_INTEGER:
3043     case Token::TOKEN_FLOAT:
3044     case Token::TOKEN_IMAGINARY:
3045       return true;
3046     default:
3047       gcc_unreachable();
3048     }
3049 }
3050
3051 // UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3052
3053 // If MAY_BE_SINK is true, this expression may be "_".
3054
3055 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3056 // literal.
3057
3058 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3059 // guard (var := expr.("type") using the literal keyword "type").
3060
3061 Expression*
3062 Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3063                   bool* is_type_switch)
3064 {
3065   const Token* token = this->peek_token();
3066   if (token->is_op(OPERATOR_PLUS)
3067       || token->is_op(OPERATOR_MINUS)
3068       || token->is_op(OPERATOR_NOT)
3069       || token->is_op(OPERATOR_XOR)
3070       || token->is_op(OPERATOR_CHANOP)
3071       || token->is_op(OPERATOR_MULT)
3072       || token->is_op(OPERATOR_AND))
3073     {
3074       source_location location = token->location();
3075       Operator op = token->op();
3076       this->advance_token();
3077
3078       if (op == OPERATOR_CHANOP
3079           && this->peek_token()->is_keyword(KEYWORD_CHAN))
3080         {
3081           // This is "<- chan" which must be the start of a type.
3082           this->unget_token(Token::make_operator_token(op, location));
3083           return Expression::make_type(this->type(), location);
3084         }
3085
3086       Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL);
3087       if (expr->is_error_expression())
3088         ;
3089       else if (op == OPERATOR_MULT && expr->is_type_expression())
3090         expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3091                                      location);
3092       else if (op == OPERATOR_AND && expr->is_composite_literal())
3093         expr = Expression::make_heap_composite(expr, location);
3094       else if (op != OPERATOR_CHANOP)
3095         expr = Expression::make_unary(op, expr, location);
3096       else
3097         expr = Expression::make_receive(expr, location);
3098       return expr;
3099     }
3100   else
3101     return this->primary_expr(may_be_sink, may_be_composite_lit,
3102                               is_type_switch);
3103 }
3104
3105 // Statement =
3106 //      Declaration | LabeledStmt | SimpleStmt |
3107 //      GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3108 //      FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3109 //      DeferStmt .
3110
3111 // LABEL is the label of this statement if it has one.
3112
3113 void
3114 Parse::statement(const Label* label)
3115 {
3116   const Token* token = this->peek_token();
3117   switch (token->classification())
3118     {
3119     case Token::TOKEN_KEYWORD:
3120       {
3121         switch (token->keyword())
3122           {
3123           case KEYWORD_CONST:
3124           case KEYWORD_TYPE:
3125           case KEYWORD_VAR:
3126             this->declaration();
3127             break;
3128           case KEYWORD_FUNC:
3129           case KEYWORD_MAP:
3130           case KEYWORD_STRUCT:
3131           case KEYWORD_INTERFACE:
3132             this->simple_stat(true, false, NULL, NULL);
3133             break;
3134           case KEYWORD_GO:
3135           case KEYWORD_DEFER:
3136             this->go_or_defer_stat();
3137             break;
3138           case KEYWORD_RETURN:
3139             this->return_stat();
3140             break;
3141           case KEYWORD_BREAK:
3142             this->break_stat();
3143             break;
3144           case KEYWORD_CONTINUE:
3145             this->continue_stat();
3146             break;
3147           case KEYWORD_GOTO:
3148             this->goto_stat();
3149             break;
3150           case KEYWORD_IF:
3151             this->if_stat();
3152             break;
3153           case KEYWORD_SWITCH:
3154             this->switch_stat(label);
3155             break;
3156           case KEYWORD_SELECT:
3157             this->select_stat(label);
3158             break;
3159           case KEYWORD_FOR:
3160             this->for_stat(label);
3161             break;
3162           default:
3163             error_at(this->location(), "expected statement");
3164             this->advance_token();
3165             break;
3166           }
3167       }
3168       break;
3169
3170     case Token::TOKEN_IDENTIFIER:
3171       {
3172         std::string identifier = token->identifier();
3173         bool is_exported = token->is_identifier_exported();
3174         source_location location = token->location();
3175         if (this->advance_token()->is_op(OPERATOR_COLON))
3176           {
3177             this->advance_token();
3178             this->labeled_stmt(identifier, location);
3179           }
3180         else
3181           {
3182             this->unget_token(Token::make_identifier_token(identifier,
3183                                                            is_exported,
3184                                                            location));
3185             this->simple_stat(true, false, NULL, NULL);
3186           }
3187       }
3188       break;
3189
3190     case Token::TOKEN_OPERATOR:
3191       if (token->is_op(OPERATOR_LCURLY))
3192         {
3193           source_location location = token->location();
3194           this->gogo_->start_block(location);
3195           source_location end_loc = this->block();
3196           this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3197                                  location);
3198         }
3199       else if (!token->is_op(OPERATOR_SEMICOLON))
3200         this->simple_stat(true, false, NULL, NULL);
3201       break;
3202
3203     case Token::TOKEN_STRING:
3204     case Token::TOKEN_INTEGER:
3205     case Token::TOKEN_FLOAT:
3206     case Token::TOKEN_IMAGINARY:
3207       this->simple_stat(true, false, NULL, NULL);
3208       break;
3209
3210     default:
3211       error_at(this->location(), "expected statement");
3212       this->advance_token();
3213       break;
3214     }
3215 }
3216
3217 bool
3218 Parse::statement_may_start_here()
3219 {
3220   const Token* token = this->peek_token();
3221   switch (token->classification())
3222     {
3223     case Token::TOKEN_KEYWORD:
3224       {
3225         switch (token->keyword())
3226           {
3227           case KEYWORD_CONST:
3228           case KEYWORD_TYPE:
3229           case KEYWORD_VAR:
3230           case KEYWORD_FUNC:
3231           case KEYWORD_MAP:
3232           case KEYWORD_STRUCT:
3233           case KEYWORD_INTERFACE:
3234           case KEYWORD_GO:
3235           case KEYWORD_DEFER:
3236           case KEYWORD_RETURN:
3237           case KEYWORD_BREAK:
3238           case KEYWORD_CONTINUE:
3239           case KEYWORD_GOTO:
3240           case KEYWORD_IF:
3241           case KEYWORD_SWITCH:
3242           case KEYWORD_SELECT:
3243           case KEYWORD_FOR:
3244             return true;
3245
3246           default:
3247             return false;
3248           }
3249       }
3250       break;
3251
3252     case Token::TOKEN_IDENTIFIER:
3253       return true;
3254
3255     case Token::TOKEN_OPERATOR:
3256       if (token->is_op(OPERATOR_LCURLY)
3257           || token->is_op(OPERATOR_SEMICOLON))
3258         return true;
3259       else
3260         return this->expression_may_start_here();
3261
3262     case Token::TOKEN_STRING:
3263     case Token::TOKEN_INTEGER:
3264     case Token::TOKEN_FLOAT:
3265     case Token::TOKEN_IMAGINARY:
3266       return true;
3267
3268     default:
3269       return false;
3270     }
3271 }
3272
3273 // LabeledStmt = Label ":" Statement .
3274 // Label       = identifier .
3275
3276 void
3277 Parse::labeled_stmt(const std::string& label_name, source_location location)
3278 {
3279   Label* label = this->gogo_->add_label_definition(label_name, location);
3280
3281   if (this->peek_token()->is_op(OPERATOR_RCURLY))
3282     {
3283       // This is a label at the end of a block.  A program is
3284       // permitted to omit a semicolon here.
3285       return;
3286     }
3287
3288   if (!this->statement_may_start_here())
3289     {
3290       error_at(location, "missing statement after label");
3291       this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3292                                                    location));
3293       return;
3294     }
3295
3296   this->statement(label);
3297 }
3298
3299 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
3300 //      Assignment | ShortVarDecl .
3301
3302 // EmptyStmt was handled in Parse::statement.
3303
3304 // In order to make this work for if and switch statements, if
3305 // RETURN_EXP is true, and we see an ExpressionStat, we return the
3306 // expression rather than adding an expression statement to the
3307 // current block.  If we see something other than an ExpressionStat,
3308 // we add the statement and return NULL.
3309
3310 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
3311 // RangeClause.
3312
3313 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
3314 // guard (var := expr.("type") using the literal keyword "type").
3315
3316 Expression*
3317 Parse::simple_stat(bool may_be_composite_lit, bool return_exp,
3318                    Range_clause* p_range_clause, Type_switch* p_type_switch)
3319 {
3320   const Token* token = this->peek_token();
3321
3322   // An identifier follow by := is a SimpleVarDecl.
3323   if (token->is_identifier())
3324     {
3325       std::string identifier = token->identifier();
3326       bool is_exported = token->is_identifier_exported();
3327       source_location location = token->location();
3328
3329       token = this->advance_token();
3330       if (token->is_op(OPERATOR_COLONEQ)
3331           || token->is_op(OPERATOR_COMMA))
3332         {
3333           identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
3334           this->simple_var_decl_or_assignment(identifier, location,
3335                                               p_range_clause,
3336                                               (token->is_op(OPERATOR_COLONEQ)
3337                                                ? p_type_switch
3338                                                : NULL));
3339           return NULL;
3340         }
3341
3342       this->unget_token(Token::make_identifier_token(identifier, is_exported,
3343                                                      location));
3344     }
3345
3346   Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
3347                                      may_be_composite_lit,
3348                                      (p_type_switch == NULL
3349                                       ? NULL
3350                                       : &p_type_switch->found));
3351   if (p_type_switch != NULL && p_type_switch->found)
3352     {
3353       p_type_switch->name.clear();
3354       p_type_switch->location = exp->location();
3355       p_type_switch->expr = this->verify_not_sink(exp);
3356       return NULL;
3357     }
3358   token = this->peek_token();
3359   if (token->is_op(OPERATOR_CHANOP))
3360     this->send_stmt(this->verify_not_sink(exp));
3361   else if (token->is_op(OPERATOR_PLUSPLUS)
3362            || token->is_op(OPERATOR_MINUSMINUS))
3363     this->inc_dec_stat(this->verify_not_sink(exp));
3364   else if (token->is_op(OPERATOR_COMMA)
3365            || token->is_op(OPERATOR_EQ))
3366     this->assignment(exp, p_range_clause);
3367   else if (token->is_op(OPERATOR_PLUSEQ)
3368            || token->is_op(OPERATOR_MINUSEQ)
3369            || token->is_op(OPERATOR_OREQ)
3370            || token->is_op(OPERATOR_XOREQ)
3371            || token->is_op(OPERATOR_MULTEQ)
3372            || token->is_op(OPERATOR_DIVEQ)
3373            || token->is_op(OPERATOR_MODEQ)
3374            || token->is_op(OPERATOR_LSHIFTEQ)
3375            || token->is_op(OPERATOR_RSHIFTEQ)
3376            || token->is_op(OPERATOR_ANDEQ)
3377            || token->is_op(OPERATOR_BITCLEAREQ))
3378     this->assignment(this->verify_not_sink(exp), p_range_clause);
3379   else if (return_exp)
3380     return this->verify_not_sink(exp);
3381   else
3382     this->expression_stat(this->verify_not_sink(exp));
3383
3384   return NULL;
3385 }
3386
3387 bool
3388 Parse::simple_stat_may_start_here()
3389 {
3390   return this->expression_may_start_here();
3391 }
3392
3393 // Parse { Statement ";" } which is used in a few places.  The list of
3394 // statements may end with a right curly brace, in which case the
3395 // semicolon may be omitted.
3396
3397 void
3398 Parse::statement_list()
3399 {
3400   while (this->statement_may_start_here())
3401     {
3402       this->statement(NULL);
3403       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3404         this->advance_token();
3405       else if (this->peek_token()->is_op(OPERATOR_RCURLY))
3406         break;
3407       else
3408         {
3409           if (!this->peek_token()->is_eof() || !saw_errors())
3410             error_at(this->location(), "expected %<;%> or %<}%> or newline");
3411           if (!this->skip_past_error(OPERATOR_RCURLY))
3412             return;
3413         }
3414     }
3415 }
3416
3417 bool
3418 Parse::statement_list_may_start_here()
3419 {
3420   return this->statement_may_start_here();
3421 }
3422
3423 // ExpressionStat = Expression .
3424
3425 void
3426 Parse::expression_stat(Expression* exp)
3427 {
3428   exp->discarding_value();
3429   this->gogo_->add_statement(Statement::make_statement(exp));
3430 }
3431
3432 // SendStmt = Channel "&lt;-" Expression .
3433 // Channel  = Expression .
3434
3435 void
3436 Parse::send_stmt(Expression* channel)
3437 {
3438   gcc_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
3439   source_location loc = this->location();
3440   this->advance_token();
3441   Expression* val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3442   Statement* s = Statement::make_send_statement(channel, val, loc);
3443   this->gogo_->add_statement(s);
3444 }
3445
3446 // IncDecStat = Expression ( "++" | "--" ) .
3447
3448 void
3449 Parse::inc_dec_stat(Expression* exp)
3450 {
3451   const Token* token = this->peek_token();
3452
3453   // Lvalue maps require special handling.
3454   if (exp->index_expression() != NULL)
3455     exp->index_expression()->set_is_lvalue();
3456
3457   if (token->is_op(OPERATOR_PLUSPLUS))
3458     this->gogo_->add_statement(Statement::make_inc_statement(exp));
3459   else if (token->is_op(OPERATOR_MINUSMINUS))
3460     this->gogo_->add_statement(Statement::make_dec_statement(exp));
3461   else
3462     gcc_unreachable();
3463   this->advance_token();
3464 }
3465
3466 // Assignment = ExpressionList assign_op ExpressionList .
3467
3468 // EXP is an expression that we have already parsed.
3469
3470 // If RANGE_CLAUSE is not NULL, then this will recognize a
3471 // RangeClause.
3472
3473 void
3474 Parse::assignment(Expression* expr, Range_clause* p_range_clause)
3475 {
3476   Expression_list* vars;
3477   if (!this->peek_token()->is_op(OPERATOR_COMMA))
3478     {
3479       vars = new Expression_list();
3480       vars->push_back(expr);
3481     }
3482   else
3483     {
3484       this->advance_token();
3485       vars = this->expression_list(expr, true);
3486     }
3487
3488   this->tuple_assignment(vars, p_range_clause);
3489 }
3490
3491 // An assignment statement.  LHS is the list of expressions which
3492 // appear on the left hand side.
3493
3494 // If RANGE_CLAUSE is not NULL, then this will recognize a
3495 // RangeClause.
3496
3497 void
3498 Parse::tuple_assignment(Expression_list* lhs, Range_clause* p_range_clause)
3499 {
3500   const Token* token = this->peek_token();
3501   if (!token->is_op(OPERATOR_EQ)
3502       && !token->is_op(OPERATOR_PLUSEQ)
3503       && !token->is_op(OPERATOR_MINUSEQ)
3504       && !token->is_op(OPERATOR_OREQ)
3505       && !token->is_op(OPERATOR_XOREQ)
3506       && !token->is_op(OPERATOR_MULTEQ)
3507       && !token->is_op(OPERATOR_DIVEQ)
3508       && !token->is_op(OPERATOR_MODEQ)
3509       && !token->is_op(OPERATOR_LSHIFTEQ)
3510       && !token->is_op(OPERATOR_RSHIFTEQ)
3511       && !token->is_op(OPERATOR_ANDEQ)
3512       && !token->is_op(OPERATOR_BITCLEAREQ))
3513     {
3514       error_at(this->location(), "expected assignment operator");
3515       return;
3516     }
3517   Operator op = token->op();
3518   source_location location = token->location();
3519
3520   token = this->advance_token();
3521
3522   if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
3523     {
3524       if (op != OPERATOR_EQ)
3525         error_at(this->location(), "range clause requires %<=%>");
3526       this->range_clause_expr(lhs, p_range_clause);
3527       return;
3528     }
3529
3530   Expression_list* vals = this->expression_list(NULL, false);
3531
3532   // We've parsed everything; check for errors.
3533   if (lhs == NULL || vals == NULL)
3534     return;
3535   for (Expression_list::const_iterator pe = lhs->begin();
3536        pe != lhs->end();
3537        ++pe)
3538     {
3539       if ((*pe)->is_error_expression())
3540         return;
3541       if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
3542         error_at((*pe)->location(), "cannot use _ as value");
3543     }
3544   for (Expression_list::const_iterator pe = vals->begin();
3545        pe != vals->end();
3546        ++pe)
3547     {
3548       if ((*pe)->is_error_expression())
3549         return;
3550     }
3551
3552   // Map expressions act differently when they are lvalues.
3553   for (Expression_list::iterator plv = lhs->begin();
3554        plv != lhs->end();
3555        ++plv)
3556     if ((*plv)->index_expression() != NULL)
3557       (*plv)->index_expression()->set_is_lvalue();
3558
3559   Call_expression* call;
3560   Index_expression* map_index;
3561   Receive_expression* receive;
3562   Type_guard_expression* type_guard;
3563   if (lhs->size() == vals->size())
3564     {
3565       Statement* s;
3566       if (lhs->size() > 1)
3567         {
3568           if (op != OPERATOR_EQ)
3569             error_at(location, "multiple values only permitted with %<=%>");
3570           s = Statement::make_tuple_assignment(lhs, vals, location);
3571         }
3572       else
3573         {
3574           if (op == OPERATOR_EQ)
3575             s = Statement::make_assignment(lhs->front(), vals->front(),
3576                                            location);
3577           else
3578             s = Statement::make_assignment_operation(op, lhs->front(),
3579                                                      vals->front(), location);
3580           delete lhs;
3581           delete vals;
3582         }
3583       this->gogo_->add_statement(s);
3584     }
3585   else if (vals->size() == 1
3586            && (call = (*vals->begin())->call_expression()) != NULL)
3587     {
3588       if (op != OPERATOR_EQ)
3589         error_at(location, "multiple results only permitted with %<=%>");
3590       delete vals;
3591       vals = new Expression_list;
3592       for (unsigned int i = 0; i < lhs->size(); ++i)
3593         vals->push_back(Expression::make_call_result(call, i));
3594       Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
3595       this->gogo_->add_statement(s);
3596     }
3597   else if (lhs->size() == 2
3598            && vals->size() == 1
3599            && (map_index = (*vals->begin())->index_expression()) != NULL)
3600     {
3601       if (op != OPERATOR_EQ)
3602         error_at(location, "two values from map requires %<=%>");
3603       Expression* val = lhs->front();
3604       Expression* present = lhs->back();
3605       Statement* s = Statement::make_tuple_map_assignment(val, present,
3606                                                           map_index, location);
3607       this->gogo_->add_statement(s);
3608     }
3609   else if (lhs->size() == 1
3610            && vals->size() == 2
3611            && (map_index = lhs->front()->index_expression()) != NULL)
3612     {
3613       if (op != OPERATOR_EQ)
3614         error_at(location, "assigning tuple to map index requires %<=%>");
3615       Expression* val = vals->front();
3616       Expression* should_set = vals->back();
3617       Statement* s = Statement::make_map_assignment(map_index, val, should_set,
3618                                                     location);
3619       this->gogo_->add_statement(s);
3620     }
3621   else if (lhs->size() == 2
3622            && vals->size() == 1
3623            && (receive = (*vals->begin())->receive_expression()) != NULL)
3624     {
3625       if (op != OPERATOR_EQ)
3626         error_at(location, "two values from receive requires %<=%>");
3627       Expression* val = lhs->front();
3628       Expression* success = lhs->back();
3629       Expression* channel = receive->channel();
3630       Statement* s = Statement::make_tuple_receive_assignment(val, success,
3631                                                               channel,
3632                                                               location);
3633       this->gogo_->add_statement(s);
3634     }
3635   else if (lhs->size() == 2
3636            && vals->size() == 1
3637            && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
3638     {
3639       if (op != OPERATOR_EQ)
3640         error_at(location, "two values from type guard requires %<=%>");
3641       Expression* val = lhs->front();
3642       Expression* ok = lhs->back();
3643       Expression* expr = type_guard->expr();
3644       Type* type = type_guard->type();
3645       Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
3646                                                                  expr, type,
3647                                                                  location);
3648       this->gogo_->add_statement(s);
3649     }
3650   else
3651     {
3652       error_at(location, "number of variables does not match number of values");
3653     }
3654 }
3655
3656 // GoStat = "go" Expression .
3657 // DeferStat = "defer" Expression .
3658
3659 void
3660 Parse::go_or_defer_stat()
3661 {
3662   gcc_assert(this->peek_token()->is_keyword(KEYWORD_GO)
3663              || this->peek_token()->is_keyword(KEYWORD_DEFER));
3664   bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
3665   source_location stat_location = this->location();
3666   this->advance_token();
3667   source_location expr_location = this->location();
3668   Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3669   Call_expression* call_expr = expr->call_expression();
3670   if (call_expr == NULL)
3671     {
3672       error_at(expr_location, "expected call expression");
3673       return;
3674     }
3675
3676   // Make it easier to simplify go/defer statements by putting every
3677   // statement in its own block.
3678   this->gogo_->start_block(stat_location);
3679   Statement* stat;
3680   if (is_go)
3681     stat = Statement::make_go_statement(call_expr, stat_location);
3682   else
3683     stat = Statement::make_defer_statement(call_expr, stat_location);
3684   this->gogo_->add_statement(stat);
3685   this->gogo_->add_block(this->gogo_->finish_block(stat_location),
3686                          stat_location);
3687 }
3688
3689 // ReturnStat = "return" [ ExpressionList ] .
3690
3691 void
3692 Parse::return_stat()
3693 {
3694   gcc_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
3695   source_location location = this->location();
3696   this->advance_token();
3697   Expression_list* vals = NULL;
3698   if (this->expression_may_start_here())
3699     vals = this->expression_list(NULL, false);
3700   const Function* function = this->gogo_->current_function()->func_value();
3701   const Typed_identifier_list* results = function->type()->results();
3702   this->gogo_->add_statement(Statement::make_return_statement(results, vals,
3703                                                               location));
3704 }
3705
3706 // IfStat = "if" [ [ SimpleStat ] ";" ] [ Condition ]
3707 //             Block [ "else" Statement ] .
3708
3709 void
3710 Parse::if_stat()
3711 {
3712   gcc_assert(this->peek_token()->is_keyword(KEYWORD_IF));
3713   source_location location = this->location();
3714   this->advance_token();
3715
3716   this->gogo_->start_block(location);
3717
3718   Expression* cond = NULL;
3719   if (this->simple_stat_may_start_here())
3720     cond = this->simple_stat(false, true, NULL, NULL);
3721   if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
3722     {
3723       // The SimpleStat is an expression statement.
3724       this->expression_stat(cond);
3725       cond = NULL;
3726     }
3727   if (cond == NULL)
3728     {
3729       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3730         this->advance_token();
3731       if (!this->peek_token()->is_op(OPERATOR_LCURLY))
3732         cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL);
3733     }
3734
3735   this->gogo_->start_block(this->location());
3736   source_location end_loc = this->block();
3737   Block* then_block = this->gogo_->finish_block(end_loc);
3738
3739   // Check for the easy error of a newline before "else".
3740   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3741     {
3742       source_location semi_loc = this->location();
3743       if (this->advance_token()->is_keyword(KEYWORD_ELSE))
3744         error_at(this->location(),
3745                  "unexpected semicolon or newline before %<else%>");
3746       else
3747         this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3748                                                      semi_loc));
3749     }
3750
3751   Block* else_block = NULL;
3752   if (this->peek_token()->is_keyword(KEYWORD_ELSE))
3753     {
3754       this->advance_token();
3755       // We create a block to gather the statement.
3756       this->gogo_->start_block(this->location());
3757       this->statement(NULL);
3758       else_block = this->gogo_->finish_block(this->location());
3759     }
3760
3761   this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
3762                                                           else_block,
3763                                                           location));
3764
3765   this->gogo_->add_block(this->gogo_->finish_block(this->location()),
3766                          location);
3767 }
3768
3769 // SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
3770 // ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
3771 //                      "{" { ExprCaseClause } "}" .
3772 // TypeSwitchStmt  = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
3773 //                      "{" { TypeCaseClause } "}" .
3774 // TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
3775
3776 void
3777 Parse::switch_stat(const Label* label)
3778 {
3779   gcc_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
3780   source_location location = this->location();
3781   this->advance_token();
3782
3783   this->gogo_->start_block(location);
3784
3785   Expression* switch_val = NULL;
3786   Type_switch type_switch;
3787   if (this->simple_stat_may_start_here())
3788     switch_val = this->simple_stat(false, true, NULL, &type_switch);
3789   if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
3790     {
3791       // The SimpleStat is an expression statement.
3792       this->expression_stat(switch_val);
3793       switch_val = NULL;
3794     }
3795   if (switch_val == NULL && !type_switch.found)
3796     {
3797       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3798         this->advance_token();
3799       if (!this->peek_token()->is_op(OPERATOR_LCURLY))
3800         {
3801           if (this->peek_token()->is_identifier())
3802             {
3803               const Token* token = this->peek_token();
3804               std::string identifier = token->identifier();
3805               bool is_exported = token->is_identifier_exported();
3806               source_location id_loc = token->location();
3807
3808               token = this->advance_token();
3809               bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
3810               this->unget_token(Token::make_identifier_token(identifier,
3811                                                              is_exported,
3812                                                              id_loc));
3813               if (is_coloneq)
3814                 {
3815                   // This must be a TypeSwitchGuard.
3816                   switch_val = this->simple_stat(false, true, NULL,
3817                                                  &type_switch);
3818                   if (!type_switch.found)
3819                     {
3820                       if (switch_val == NULL
3821                           || !switch_val->is_error_expression())
3822                         {
3823                           error_at(id_loc, "expected type switch assignment");
3824                           switch_val = Expression::make_error(id_loc);
3825                         }
3826                     }
3827                 }
3828             }
3829           if (switch_val == NULL && !type_switch.found)
3830             {
3831               switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
3832                                             &type_switch.found);
3833               if (type_switch.found)
3834                 {
3835                   type_switch.name.clear();
3836                   type_switch.expr = switch_val;
3837                   type_switch.location = switch_val->location();
3838                 }
3839             }
3840         }
3841     }
3842
3843   if (!this->peek_token()->is_op(OPERATOR_LCURLY))
3844     {
3845       source_location token_loc = this->location();
3846       if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
3847           && this->advance_token()->is_op(OPERATOR_LCURLY))
3848         error_at(token_loc, "unexpected semicolon or newline before %<{%>");
3849       else
3850         {
3851           error_at(this->location(), "expected %<{%>");
3852           this->gogo_->add_block(this->gogo_->finish_block(this->location()),
3853                                  location);
3854           return;
3855         }
3856     }
3857   this->advance_token();
3858
3859   Statement* statement;
3860   if (type_switch.found)
3861     statement = this->type_switch_body(label, type_switch, location);
3862   else
3863     statement = this->expr_switch_body(label, switch_val, location);
3864
3865   if (statement != NULL)
3866     this->gogo_->add_statement(statement);
3867
3868   this->gogo_->add_block(this->gogo_->finish_block(this->location()),
3869                          location);
3870 }
3871
3872 // The body of an expression switch.
3873 //   "{" { ExprCaseClause } "}"
3874
3875 Statement*
3876 Parse::expr_switch_body(const Label* label, Expression* switch_val,
3877                         source_location location)
3878 {
3879   Switch_statement* statement = Statement::make_switch_statement(switch_val,
3880                                                                  location);
3881
3882   this->push_break_statement(statement, label);
3883
3884   Case_clauses* case_clauses = new Case_clauses();
3885   bool saw_default = false;
3886   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
3887     {
3888       if (this->peek_token()->is_eof())
3889         {
3890           if (!saw_errors())
3891             error_at(this->location(), "missing %<}%>");
3892           return NULL;
3893         }
3894       this->expr_case_clause(case_clauses, &saw_default);
3895     }
3896   this->advance_token();
3897
3898   statement->add_clauses(case_clauses);
3899
3900   this->pop_break_statement();
3901
3902   return statement;
3903 }
3904
3905 // ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
3906 // FallthroughStat = "fallthrough" .
3907
3908 void
3909 Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
3910 {
3911   source_location location = this->location();
3912
3913   bool is_default = false;
3914   Expression_list* vals = this->expr_switch_case(&is_default);
3915
3916   if (!this->peek_token()->is_op(OPERATOR_COLON))
3917     {
3918       if (!saw_errors())
3919         error_at(this->location(), "expected %<:%>");
3920       return;
3921     }
3922   else
3923     this->advance_token();
3924
3925   Block* statements = NULL;
3926   if (this->statement_list_may_start_here())
3927     {
3928       this->gogo_->start_block(this->location());
3929       this->statement_list();
3930       statements = this->gogo_->finish_block(this->location());
3931     }
3932
3933   bool is_fallthrough = false;
3934   if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
3935     {
3936       is_fallthrough = true;
3937       if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
3938         this->advance_token();
3939     }
3940
3941   if (is_default)
3942     {
3943       if (*saw_default)
3944         {
3945           error_at(location, "multiple defaults in switch");
3946           return;
3947         }
3948       *saw_default = true;
3949     }
3950
3951   if (is_default || vals != NULL)
3952     clauses->add(vals, is_default, statements, is_fallthrough, location);
3953 }
3954
3955 // ExprSwitchCase = "case" ExpressionList | "default" .
3956
3957 Expression_list*
3958 Parse::expr_switch_case(bool* is_default)
3959 {
3960   const Token* token = this->peek_token();
3961   if (token->is_keyword(KEYWORD_CASE))
3962     {
3963       this->advance_token();
3964       return this->expression_list(NULL, false);
3965     }
3966   else if (token->is_keyword(KEYWORD_DEFAULT))
3967     {
3968       this->advance_token();
3969       *is_default = true;
3970       return NULL;
3971     }
3972   else
3973     {
3974       if (!saw_errors())
3975         error_at(this->location(), "expected %<case%> or %<default%>");
3976       if (!token->is_op(OPERATOR_RCURLY))
3977         this->advance_token();
3978       return NULL;
3979     }
3980 }
3981
3982 // The body of a type switch.
3983 //   "{" { TypeCaseClause } "}" .
3984
3985 Statement*
3986 Parse::type_switch_body(const Label* label, const Type_switch& type_switch,
3987                         source_location location)
3988 {
3989   Named_object* switch_no = NULL;
3990   if (!type_switch.name.empty())
3991     {
3992       Variable* switch_var = new Variable(NULL, type_switch.expr, false, false,
3993                                           false, type_switch.location);
3994       switch_no = this->gogo_->add_variable(type_switch.name, switch_var);
3995     }
3996
3997   Type_switch_statement* statement =
3998     Statement::make_type_switch_statement(switch_no,
3999                                           (switch_no == NULL
4000                                            ? type_switch.expr
4001                                            : NULL),
4002                                           location);
4003
4004   this->push_break_statement(statement, label);
4005
4006   Type_case_clauses* case_clauses = new Type_case_clauses();
4007   bool saw_default = false;
4008   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4009     {
4010       if (this->peek_token()->is_eof())
4011         {
4012           error_at(this->location(), "missing %<}%>");
4013           return NULL;
4014         }
4015       this->type_case_clause(switch_no, case_clauses, &saw_default);
4016     }
4017   this->advance_token();
4018
4019   statement->add_clauses(case_clauses);
4020
4021   this->pop_break_statement();
4022
4023   return statement;
4024 }
4025
4026 // TypeCaseClause  = TypeSwitchCase ":" [ StatementList ] .
4027
4028 void
4029 Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses,
4030                         bool* saw_default)
4031 {
4032   source_location location = this->location();
4033
4034   std::vector<Type*> types;
4035   bool is_default = false;
4036   this->type_switch_case(&types, &is_default);
4037
4038   if (!this->peek_token()->is_op(OPERATOR_COLON))
4039     error_at(this->location(), "expected %<:%>");
4040   else
4041     this->advance_token();
4042
4043   Block* statements = NULL;
4044   if (this->statement_list_may_start_here())
4045     {
4046       this->gogo_->start_block(this->location());
4047       if (switch_no != NULL && types.size() == 1)
4048         {
4049           Type* type = types.front();
4050           Expression* init = Expression::make_var_reference(switch_no,
4051                                                             location);
4052           init = Expression::make_type_guard(init, type, location);
4053           Variable* v = new Variable(type, init, false, false, false,
4054                                      location);
4055           v->set_is_type_switch_var();
4056           this->gogo_->add_variable(switch_no->name(), v);
4057         }
4058       this->statement_list();
4059       statements = this->gogo_->finish_block(this->location());
4060     }
4061
4062   if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4063     {
4064       error_at(this->location(),
4065                "fallthrough is not permitted in a type switch");
4066       if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4067         this->advance_token();
4068     }
4069
4070   if (is_default)
4071     {
4072       gcc_assert(types.empty());
4073       if (*saw_default)
4074         {
4075           error_at(location, "multiple defaults in type switch");
4076           return;
4077         }
4078       *saw_default = true;
4079       clauses->add(NULL, false, true, statements, location);
4080     }
4081   else if (!types.empty())
4082     {
4083       for (std::vector<Type*>::const_iterator p = types.begin();
4084            p + 1 != types.end();
4085            ++p)
4086         clauses->add(*p, true, false, NULL, location);
4087       clauses->add(types.back(), false, false, statements, location);
4088     }
4089   else
4090     clauses->add(Type::make_error_type(), false, false, statements, location);
4091 }
4092
4093 // TypeSwitchCase  = "case" type | "default"
4094
4095 // We accept a comma separated list of types.
4096
4097 void
4098 Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
4099 {
4100   const Token* token = this->peek_token();
4101   if (token->is_keyword(KEYWORD_CASE))
4102     {
4103       this->advance_token();
4104       while (true)
4105         {
4106           Type* t = this->type();
4107           if (!t->is_error_type())
4108             types->push_back(t);
4109           if (!this->peek_token()->is_op(OPERATOR_COMMA))
4110             break;
4111           this->advance_token();
4112         }
4113     }
4114   else if (token->is_keyword(KEYWORD_DEFAULT))
4115     {
4116       this->advance_token();
4117       *is_default = true;
4118     }
4119   else
4120     {
4121       error_at(this->location(), "expected %<case%> or %<default%>");
4122       if (!token->is_op(OPERATOR_RCURLY))
4123         this->advance_token();
4124     }
4125 }
4126
4127 // SelectStat = "select" "{" { CommClause } "}" .
4128
4129 void
4130 Parse::select_stat(const Label* label)
4131 {
4132   gcc_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
4133   source_location location = this->location();
4134   const Token* token = this->advance_token();
4135
4136   if (!token->is_op(OPERATOR_LCURLY))
4137     {
4138       source_location token_loc = token->location();
4139       if (token->is_op(OPERATOR_SEMICOLON)
4140           && this->advance_token()->is_op(OPERATOR_LCURLY))
4141         error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4142       else
4143         {
4144           error_at(this->location(), "expected %<{%>");
4145           return;
4146         }
4147     }
4148   this->advance_token();
4149
4150   Select_statement* statement = Statement::make_select_statement(location);
4151
4152   this->push_break_statement(statement, label);
4153
4154   Select_clauses* select_clauses = new Select_clauses();
4155   bool saw_default = false;
4156   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4157     {
4158       if (this->peek_token()->is_eof())
4159         {
4160           error_at(this->location(), "expected %<}%>");
4161           return;
4162         }
4163       this->comm_clause(select_clauses, &saw_default);
4164     }
4165
4166   this->advance_token();
4167
4168   statement->add_clauses(select_clauses);
4169
4170   this->pop_break_statement();
4171
4172   this->gogo_->add_statement(statement);
4173 }
4174
4175 // CommClause = CommCase ":" { Statement ";" } .
4176
4177 void
4178 Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
4179 {
4180   source_location location = this->location();
4181   bool is_send = false;
4182   Expression* channel = NULL;
4183   Expression* val = NULL;
4184   std::string varname;
4185   bool is_default = false;
4186   bool got_case = this->comm_case(&is_send, &channel, &val, &varname,
4187                                   &is_default);
4188
4189   if (this->peek_token()->is_op(OPERATOR_COLON))
4190     this->advance_token();
4191   else
4192     error_at(this->location(), "expected colon");
4193
4194   Block* statements = NULL;
4195   Named_object* var = NULL;
4196   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4197     this->advance_token();
4198   else if (this->statement_list_may_start_here())
4199     {
4200       this->gogo_->start_block(this->location());
4201
4202       if (!varname.empty())
4203         {
4204           // FIXME: LOCATION is slightly wrong here.
4205           Variable* v = new Variable(NULL, channel, false, false, false,
4206                                      location);
4207           v->set_type_from_chan_element();
4208           var = this->gogo_->add_variable(varname, v);
4209         }
4210
4211       this->statement_list();
4212       statements = this->gogo_->finish_block(this->location());
4213     }
4214
4215   if (is_default)
4216     {
4217       if (*saw_default)
4218         {
4219           error_at(location, "multiple defaults in select");
4220           return;
4221         }
4222       *saw_default = true;
4223     }
4224
4225   if (got_case)
4226     clauses->add(is_send, channel, val, var, is_default, statements, location);
4227   else if (statements != NULL)
4228     {
4229       // Add the statements to make sure that any names they define
4230       // are traversed.
4231       this->gogo_->add_block(statements, location);
4232     }
4233 }
4234
4235 // CommCase   = "case" ( SendStmt | RecvStmt ) | "default" .
4236
4237 bool
4238 Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
4239                  std::string* varname, bool* is_default)
4240 {
4241   const Token* token = this->peek_token();
4242   if (token->is_keyword(KEYWORD_DEFAULT))
4243     {
4244       this->advance_token();
4245       *is_default = true;
4246     }
4247   else if (token->is_keyword(KEYWORD_CASE))
4248     {
4249       this->advance_token();
4250       if (!this->send_or_recv_expr(is_send, channel, val, varname))
4251         return false;
4252     }
4253   else
4254     {
4255       error_at(this->location(), "expected %<case%> or %<default%>");
4256       if (!token->is_op(OPERATOR_RCURLY))
4257         this->advance_token();
4258       return false;
4259     }
4260
4261   return true;
4262 }
4263
4264 // RecvExpr =  [ Expression ( "=" | ":=" ) ] "<-" Expression .
4265
4266 bool
4267 Parse::send_or_recv_expr(bool* is_send, Expression** channel, Expression** val,
4268                          std::string* varname)
4269 {
4270   const Token* token = this->peek_token();
4271   source_location location = token->location();
4272   if (token->is_identifier())
4273     {
4274       std::string recv_var = token->identifier();
4275       bool is_var_exported = token->is_identifier_exported();
4276       if (!this->advance_token()->is_op(OPERATOR_COLONEQ))
4277         this->unget_token(Token::make_identifier_token(recv_var,
4278                                                        is_var_exported,
4279                                                        location));
4280       else
4281         {
4282           if (!this->advance_token()->is_op(OPERATOR_CHANOP))
4283             {
4284               error_at(this->location(), "expected %<<-%>");
4285               return false;
4286             }
4287           *is_send = false;
4288           *varname = this->gogo_->pack_hidden_name(recv_var, is_var_exported);
4289           this->advance_token();
4290           *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4291           return true;
4292         }
4293     }
4294
4295   if (this->peek_token()->is_op(OPERATOR_CHANOP))
4296     {
4297       *is_send = false;
4298       this->advance_token();
4299       *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4300     }
4301   else
4302     {
4303       Expression* left = this->expression(PRECEDENCE_NORMAL, true, true, NULL);
4304
4305       if (this->peek_token()->is_op(OPERATOR_EQ))
4306         {
4307           if (!this->advance_token()->is_op(OPERATOR_CHANOP))
4308             {
4309               error_at(this->location(), "missing %<<-%>");
4310               return false;
4311             }
4312           *is_send = false;
4313           *val = left;
4314           this->advance_token();
4315           *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4316         }
4317       else if (this->peek_token()->is_op(OPERATOR_CHANOP))
4318         {
4319           *is_send = true;
4320           *channel = this->verify_not_sink(left);
4321           this->advance_token();
4322           *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4323         }
4324       else
4325         {
4326           error_at(this->location(), "expected %<<-%> or %<=%>");
4327           return false;
4328         }
4329     }
4330
4331   return true;
4332 }
4333
4334 // ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
4335 // Condition = Expression .
4336
4337 void
4338 Parse::for_stat(const Label* label)
4339 {
4340   gcc_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
4341   source_location location = this->location();
4342   const Token* token = this->advance_token();
4343
4344   // Open a block to hold any variables defined in the init statement
4345   // of the for statement.
4346   this->gogo_->start_block(location);
4347
4348   Block* init = NULL;
4349   Expression* cond = NULL;
4350   Block* post = NULL;
4351   Range_clause range_clause;
4352
4353   if (!token->is_op(OPERATOR_LCURLY))
4354     {
4355       if (token->is_keyword(KEYWORD_VAR))
4356         {
4357           error_at(this->location(),
4358                    "var declaration not allowed in for initializer");
4359           this->var_decl();
4360         }
4361
4362       if (token->is_op(OPERATOR_SEMICOLON))
4363         this->for_clause(&cond, &post);
4364       else
4365         {
4366           // We might be looking at a Condition, an InitStat, or a
4367           // RangeClause.
4368           cond = this->simple_stat(false, true, &range_clause, NULL);
4369           if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
4370             {
4371               if (cond == NULL && !range_clause.found)
4372                 error_at(this->location(), "parse error in for statement");
4373             }
4374           else
4375             {
4376               if (range_clause.found)
4377                 error_at(this->location(), "parse error after range clause");
4378
4379               if (cond != NULL)
4380                 {
4381                   // COND is actually an expression statement for
4382                   // InitStat at the start of a ForClause.
4383                   this->expression_stat(cond);
4384                   cond = NULL;
4385                 }
4386
4387               this->for_clause(&cond, &post);
4388             }
4389         }
4390     }
4391
4392   // Build the For_statement and note that it is the current target
4393   // for break and continue statements.
4394
4395   For_statement* sfor;
4396   For_range_statement* srange;
4397   Statement* s;
4398   if (!range_clause.found)
4399     {
4400       sfor = Statement::make_for_statement(init, cond, post, location);
4401       s = sfor;
4402       srange = NULL;
4403     }
4404   else
4405     {
4406       srange = Statement::make_for_range_statement(range_clause.index,
4407                                                    range_clause.value,
4408                                                    range_clause.range,
4409                                                    location);
4410       s = srange;
4411       sfor = NULL;
4412     }
4413
4414   this->push_break_statement(s, label);
4415   this->push_continue_statement(s, label);
4416
4417   // Gather the block of statements in the loop and add them to the
4418   // For_statement.
4419
4420   this->gogo_->start_block(this->location());
4421   source_location end_loc = this->block();
4422   Block* statements = this->gogo_->finish_block(end_loc);
4423
4424   if (sfor != NULL)
4425     sfor->add_statements(statements);
4426   else
4427     srange->add_statements(statements);
4428
4429   // This is no longer the break/continue target.
4430   this->pop_break_statement();
4431   this->pop_continue_statement();
4432
4433   // Add the For_statement to the list of statements, and close out
4434   // the block we started to hold any variables defined in the for
4435   // statement.
4436
4437   this->gogo_->add_statement(s);
4438
4439   this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4440                          location);
4441 }
4442
4443 // ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
4444 // InitStat = SimpleStat .
4445 // PostStat = SimpleStat .
4446
4447 // We have already read InitStat at this point.
4448
4449 void
4450 Parse::for_clause(Expression** cond, Block** post)
4451 {
4452   gcc_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
4453   this->advance_token();
4454   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4455     *cond = NULL;
4456   else if (this->peek_token()->is_op(OPERATOR_LCURLY))
4457     {
4458       error_at(this->location(),
4459                "unexpected semicolon or newline before %<{%>");
4460       *cond = NULL;
4461       *post = NULL;
4462       return;
4463     }
4464   else
4465     *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4466   if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
4467     error_at(this->location(), "expected semicolon");
4468   else
4469     this->advance_token();
4470
4471   if (this->peek_token()->is_op(OPERATOR_LCURLY))
4472     *post = NULL;
4473   else
4474     {
4475       this->gogo_->start_block(this->location());
4476       this->simple_stat(false, false, NULL, NULL);
4477       *post = this->gogo_->finish_block(this->location());
4478     }
4479 }
4480
4481 // RangeClause = IdentifierList ( "=" | ":=" ) "range" Expression .
4482
4483 // This is the := version.  It is called with a list of identifiers.
4484
4485 void
4486 Parse::range_clause_decl(const Typed_identifier_list* til,
4487                          Range_clause* p_range_clause)
4488 {
4489   gcc_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
4490   source_location location = this->location();
4491
4492   p_range_clause->found = true;
4493
4494   gcc_assert(til->size() >= 1);
4495   if (til->size() > 2)
4496     error_at(this->location(), "too many variables for range clause");
4497
4498   this->advance_token();
4499   Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL);
4500   p_range_clause->range = expr;
4501
4502   bool any_new = false;
4503
4504   const Typed_identifier* pti = &til->front();
4505   Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new);
4506   if (any_new && no->is_variable())
4507     no->var_value()->set_type_from_range_index();
4508   p_range_clause->index = Expression::make_var_reference(no, location);
4509
4510   if (til->size() == 1)
4511     p_range_clause->value = NULL;
4512   else
4513     {
4514       pti = &til->back();
4515       bool is_new = false;
4516       no = this->init_var(*pti, NULL, expr, true, true, &is_new);
4517       if (is_new && no->is_variable())
4518         no->var_value()->set_type_from_range_value();
4519       if (is_new)
4520         any_new = true;
4521       p_range_clause->value = Expression::make_var_reference(no, location);
4522     }
4523
4524   if (!any_new)
4525     error_at(location, "variables redeclared but no variable is new");
4526 }
4527
4528 // The = version of RangeClause.  This is called with a list of
4529 // expressions.
4530
4531 void
4532 Parse::range_clause_expr(const Expression_list* vals,
4533                          Range_clause* p_range_clause)
4534 {
4535   gcc_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
4536
4537   p_range_clause->found = true;
4538
4539   gcc_assert(vals->size() >= 1);
4540   if (vals->size() > 2)
4541     error_at(this->location(), "too many variables for range clause");
4542
4543   this->advance_token();
4544   p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
4545                                            NULL);
4546
4547   p_range_clause->index = vals->front();
4548   if (vals->size() == 1)
4549     p_range_clause->value = NULL;
4550   else
4551     p_range_clause->value = vals->back();
4552 }
4553
4554 // Push a statement on the break stack.
4555
4556 void
4557 Parse::push_break_statement(Statement* enclosing, const Label* label)
4558 {
4559   if (this->break_stack_ == NULL)
4560     this->break_stack_ = new Bc_stack();
4561   this->break_stack_->push_back(std::make_pair(enclosing, label));
4562 }
4563
4564 // Push a statement on the continue stack.
4565
4566 void
4567 Parse::push_continue_statement(Statement* enclosing, const Label* label)
4568 {
4569   if (this->continue_stack_ == NULL)
4570     this->continue_stack_ = new Bc_stack();
4571   this->continue_stack_->push_back(std::make_pair(enclosing, label));
4572 }
4573
4574 // Pop the break stack.
4575
4576 void
4577 Parse::pop_break_statement()
4578 {
4579   this->break_stack_->pop_back();
4580 }
4581
4582 // Pop the continue stack.
4583
4584 void
4585 Parse::pop_continue_statement()
4586 {
4587   this->continue_stack_->pop_back();
4588 }
4589
4590 // Find a break or continue statement given a label name.
4591
4592 Statement*
4593 Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
4594 {
4595   if (bc_stack == NULL)
4596     return NULL;
4597   for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
4598        p != bc_stack->rend();
4599        ++p)
4600     if (p->second != NULL && p->second->name() == label)
4601       return p->first;
4602   return NULL;
4603 }
4604
4605 // BreakStat = "break" [ identifier ] .
4606
4607 void
4608 Parse::break_stat()
4609 {
4610   gcc_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
4611   source_location location = this->location();
4612
4613   const Token* token = this->advance_token();
4614   Statement* enclosing;
4615   if (!token->is_identifier())
4616     {
4617       if (this->break_stack_ == NULL || this->break_stack_->empty())
4618         {
4619           error_at(this->location(),
4620                    "break statement not within for or switch or select");
4621           return;
4622         }
4623       enclosing = this->break_stack_->back().first;
4624     }
4625   else
4626     {
4627       enclosing = this->find_bc_statement(this->break_stack_,
4628                                           token->identifier());
4629       if (enclosing == NULL)
4630         {
4631           error_at(token->location(),
4632                    ("break label %qs not associated with "
4633                     "for or switch or select"),
4634                    Gogo::message_name(token->identifier()).c_str());
4635           this->advance_token();
4636           return;
4637         }
4638       this->advance_token();
4639     }
4640
4641   Unnamed_label* label;
4642   if (enclosing->classification() == Statement::STATEMENT_FOR)
4643     label = enclosing->for_statement()->break_label();
4644   else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
4645     label = enclosing->for_range_statement()->break_label();
4646   else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
4647     label = enclosing->switch_statement()->break_label();
4648   else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
4649     label = enclosing->type_switch_statement()->break_label();
4650   else if (enclosing->classification() == Statement::STATEMENT_SELECT)
4651     label = enclosing->select_statement()->break_label();
4652   else
4653     gcc_unreachable();
4654
4655   this->gogo_->add_statement(Statement::make_break_statement(label,
4656                                                              location));
4657 }
4658
4659 // ContinueStat = "continue" [ identifier ] .
4660
4661 void
4662 Parse::continue_stat()
4663 {
4664   gcc_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
4665   source_location location = this->location();
4666
4667   const Token* token = this->advance_token();
4668   Statement* enclosing;
4669   if (!token->is_identifier())
4670     {
4671       if (this->continue_stack_ == NULL || this->continue_stack_->empty())
4672         {
4673           error_at(this->location(), "continue statement not within for");
4674           return;
4675         }
4676       enclosing = this->continue_stack_->back().first;
4677     }
4678   else
4679     {
4680       enclosing = this->find_bc_statement(this->continue_stack_,
4681                                           token->identifier());
4682       if (enclosing == NULL)
4683         {
4684           error_at(token->location(),
4685                    "continue label %qs not associated with for",
4686                    Gogo::message_name(token->identifier()).c_str());
4687           this->advance_token();
4688           return;
4689         }
4690       this->advance_token();
4691     }
4692
4693   Unnamed_label* label;
4694   if (enclosing->classification() == Statement::STATEMENT_FOR)
4695     label = enclosing->for_statement()->continue_label();
4696   else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
4697     label = enclosing->for_range_statement()->continue_label();
4698   else
4699     gcc_unreachable();
4700
4701   this->gogo_->add_statement(Statement::make_continue_statement(label,
4702                                                                 location));
4703 }
4704
4705 // GotoStat = "goto" identifier .
4706
4707 void
4708 Parse::goto_stat()
4709 {
4710   gcc_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
4711   source_location location = this->location();
4712   const Token* token = this->advance_token();
4713   if (!token->is_identifier())
4714     error_at(this->location(), "expected label for goto");
4715   else
4716     {
4717       Label* label = this->gogo_->add_label_reference(token->identifier());
4718       Statement* s = Statement::make_goto_statement(label, location);
4719       this->gogo_->add_statement(s);
4720       this->advance_token();
4721     }
4722 }
4723
4724 // PackageClause = "package" PackageName .
4725
4726 void
4727 Parse::package_clause()
4728 {
4729   const Token* token = this->peek_token();
4730   source_location location = token->location();
4731   std::string name;
4732   if (!token->is_keyword(KEYWORD_PACKAGE))
4733     {
4734       error_at(this->location(), "program must start with package clause");
4735       name = "ERROR";
4736     }
4737   else
4738     {
4739       token = this->advance_token();
4740       if (token->is_identifier())
4741         {
4742           name = token->identifier();
4743           if (name == "_")
4744             {
4745               error_at(this->location(), "invalid package name _");
4746               name = "blank";
4747             }
4748           this->advance_token();
4749         }
4750       else
4751         {
4752           error_at(this->location(), "package name must be an identifier");
4753           name = "ERROR";
4754         }
4755     }
4756   this->gogo_->set_package_name(name, location);
4757 }
4758
4759 // ImportDecl = "import" Decl<ImportSpec> .
4760
4761 void
4762 Parse::import_decl()
4763 {
4764   gcc_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
4765   this->advance_token();
4766   this->decl(&Parse::import_spec, NULL);
4767 }
4768
4769 // ImportSpec = [ "." | PackageName ] PackageFileName .
4770
4771 void
4772 Parse::import_spec(void*)
4773 {
4774   const Token* token = this->peek_token();
4775   source_location location = token->location();
4776
4777   std::string local_name;
4778   bool is_local_name_exported = false;
4779   if (token->is_op(OPERATOR_DOT))
4780     {
4781       local_name = ".";
4782       token = this->advance_token();
4783     }
4784   else if (token->is_identifier())
4785     {
4786       local_name = token->identifier();
4787       is_local_name_exported = token->is_identifier_exported();
4788       token = this->advance_token();
4789     }
4790
4791   if (!token->is_string())
4792     {
4793       error_at(this->location(), "missing import package name");
4794       return;
4795     }
4796
4797   this->gogo_->import_package(token->string_value(), local_name,
4798                               is_local_name_exported, location);
4799
4800   this->advance_token();
4801 }
4802
4803 // SourceFile       = PackageClause ";" { ImportDecl ";" }
4804 //                      { TopLevelDecl ";" } .
4805
4806 void
4807 Parse::program()
4808 {
4809   this->package_clause();
4810
4811   const Token* token = this->peek_token();
4812   if (token->is_op(OPERATOR_SEMICOLON))
4813     token = this->advance_token();
4814   else
4815     error_at(this->location(),
4816              "expected %<;%> or newline after package clause");
4817
4818   while (token->is_keyword(KEYWORD_IMPORT))
4819     {
4820       this->import_decl();
4821       token = this->peek_token();
4822       if (token->is_op(OPERATOR_SEMICOLON))
4823         token = this->advance_token();
4824       else
4825         error_at(this->location(),
4826                  "expected %<;%> or newline after import declaration");
4827     }
4828
4829   while (!token->is_eof())
4830     {
4831       if (this->declaration_may_start_here())
4832         this->declaration();
4833       else
4834         {
4835           error_at(this->location(), "expected declaration");
4836           do
4837             this->advance_token();
4838           while (!this->peek_token()->is_eof()
4839                  && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
4840                  && !this->peek_token()->is_op(OPERATOR_RCURLY));
4841           if (!this->peek_token()->is_eof()
4842               && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
4843             this->advance_token();
4844         }
4845       token = this->peek_token();
4846       if (token->is_op(OPERATOR_SEMICOLON))
4847         token = this->advance_token();
4848       else if (!token->is_eof() || !saw_errors())
4849         {
4850           error_at(this->location(),
4851                    "expected %<;%> or newline after top level declaration");
4852           this->skip_past_error(OPERATOR_INVALID);
4853         }
4854     }
4855 }
4856
4857 // Reset the current iota value.
4858
4859 void
4860 Parse::reset_iota()
4861 {
4862   this->iota_ = 0;
4863 }
4864
4865 // Return the current iota value.
4866
4867 int
4868 Parse::iota_value()
4869 {
4870   return this->iota_;
4871 }
4872
4873 // Increment the current iota value.
4874
4875 void
4876 Parse::increment_iota()
4877 {
4878   ++this->iota_;
4879 }
4880
4881 // Skip forward to a semicolon or OP.  OP will normally be
4882 // OPERATOR_RPAREN or OPERATOR_RCURLY.  If we find a semicolon, move
4883 // past it and return.  If we find OP, it will be the next token to
4884 // read.  Return true if we are OK, false if we found EOF.
4885
4886 bool
4887 Parse::skip_past_error(Operator op)
4888 {
4889   const Token* token = this->peek_token();
4890   while (!token->is_op(op))
4891     {
4892       if (token->is_eof())
4893         return false;
4894       if (token->is_op(OPERATOR_SEMICOLON))
4895         {
4896           this->advance_token();
4897           return true;
4898         }
4899       token = this->advance_token();
4900     }
4901   return true;
4902 }
4903
4904 // Check that an expression is not a sink.
4905
4906 Expression*
4907 Parse::verify_not_sink(Expression* expr)
4908 {
4909   if (expr->is_sink_expression())
4910     {
4911       error_at(expr->location(), "cannot use _ as value");
4912       expr = Expression::make_error(expr->location());
4913     }
4914   return expr;
4915 }