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