OSDN Git Service

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