OSDN Git Service

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