OSDN Git Service

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