OSDN Git Service

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