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 id_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 							 id_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, id_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 	      id_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, id_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 							     id_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, false));
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,
2364 	  true },
2365 	{ GOPRAGMA_YESWRITEBARRIERREC, "yeswritebarrierrec", false, true,
2366 	  true },
2367 	{ GOPRAGMA_CGOUNSAFEARGS, "cgo_unsafe_args", false, true, true },
2368 	{ GOPRAGMA_UINTPTRESCAPES, "uintptrescapes", true, true, true },
2369       };
2370 
2371   bool is_decl = !this->peek_token()->is_op(OPERATOR_LCURLY);
2372   if (pragmas != 0)
2373     {
2374       for (size_t i = 0;
2375 	   i < sizeof(pragma_check) / sizeof(pragma_check[0]);
2376 	   ++i)
2377 	{
2378 	  if ((pragmas & pragma_check[i].bit) == 0)
2379 	    continue;
2380 
2381 	  if (is_decl)
2382 	    {
2383 	      if (pragma_check[i].decl_ok)
2384 		continue;
2385 	      go_warning_at(location, 0,
2386 			    ("ignoring magic %<//go:%s%> comment "
2387 			     "before declaration"),
2388 			    pragma_check[i].name);
2389 	    }
2390 	  else if (rec == NULL)
2391 	    {
2392 	      if (pragma_check[i].func_ok)
2393 		continue;
2394 	      go_warning_at(location, 0,
2395 			    ("ignoring magic %<//go:%s%> comment "
2396 			     "before function definition"),
2397 			    pragma_check[i].name);
2398 	    }
2399 	  else
2400 	    {
2401 	      if (pragma_check[i].method_ok)
2402 		continue;
2403 	      go_warning_at(location, 0,
2404 			    ("ignoring magic %<//go:%s%> comment "
2405 			     "before method definition"),
2406 			    pragma_check[i].name);
2407 	    }
2408 
2409 	  pragmas &= ~ pragma_check[i].bit;
2410 	}
2411     }
2412 
2413   if (is_decl)
2414     {
2415       if (named_object == NULL)
2416 	{
2417           // Function declarations with the blank identifier as a name are
2418           // mostly ignored since they cannot be called.  We make an object
2419           // for this declaration for type-checking purposes.
2420           if (Gogo::is_sink_name(name))
2421             {
2422               static int count;
2423               char buf[30];
2424               snprintf(buf, sizeof buf, ".$sinkfndecl%d", count);
2425               ++count;
2426               name = std::string(buf);
2427             }
2428 
2429 	  if (fntype == NULL
2430               || (expected_receiver && rec == NULL))
2431 	    this->gogo_->add_erroneous_name(name);
2432 	  else
2433 	    {
2434 	      named_object = this->gogo_->declare_function(name, fntype,
2435 							   location);
2436 	      if (!extern_name.empty()
2437 		  && named_object->is_function_declaration())
2438 		{
2439 		  Function_declaration* fd =
2440 		    named_object->func_declaration_value();
2441 		  fd->set_asm_name(extern_name);
2442 		}
2443 	    }
2444 	}
2445 
2446       if (pragmas != 0 && named_object->is_function_declaration())
2447 	named_object->func_declaration_value()->set_pragmas(pragmas);
2448     }
2449   else
2450     {
2451       bool hold_is_erroneous_function = this->is_erroneous_function_;
2452       if (fntype == NULL)
2453 	{
2454 	  fntype = Type::make_function_type(NULL, NULL, NULL, location);
2455 	  this->is_erroneous_function_ = true;
2456 	  if (!Gogo::is_sink_name(name))
2457 	    this->gogo_->add_erroneous_name(name);
2458 	  name = this->gogo_->pack_hidden_name("_", false);
2459 	}
2460       named_object = this->gogo_->start_function(name, fntype, true, location);
2461       Location end_loc = this->block();
2462       this->gogo_->finish_function(end_loc);
2463 
2464       if (pragmas != 0
2465 	  && !this->is_erroneous_function_
2466 	  && named_object->is_function())
2467 	named_object->func_value()->set_pragmas(pragmas);
2468       this->is_erroneous_function_ = hold_is_erroneous_function;
2469     }
2470 }
2471 
2472 // Receiver = Parameters .
2473 
2474 Typed_identifier*
receiver()2475 Parse::receiver()
2476 {
2477   Location location = this->location();
2478   Typed_identifier_list* til;
2479   if (!this->parameters(&til, NULL))
2480     return NULL;
2481   else if (til == NULL || til->empty())
2482     {
2483       go_error_at(location, "method has no receiver");
2484       return NULL;
2485     }
2486   else if (til->size() > 1)
2487     {
2488       go_error_at(location, "method has multiple receivers");
2489       return NULL;
2490     }
2491   else
2492     return &til->front();
2493 }
2494 
2495 // Operand    = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2496 // Literal    = BasicLit | CompositeLit | FunctionLit .
2497 // BasicLit   = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2498 
2499 // If MAY_BE_SINK is true, this operand may be "_".
2500 
2501 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
2502 // if the entire expression is in parentheses.
2503 
2504 Expression*
operand(bool may_be_sink,bool * is_parenthesized)2505 Parse::operand(bool may_be_sink, bool* is_parenthesized)
2506 {
2507   const Token* token = this->peek_token();
2508   Expression* ret;
2509   switch (token->classification())
2510     {
2511     case Token::TOKEN_IDENTIFIER:
2512       {
2513 	Location location = token->location();
2514 	std::string id = token->identifier();
2515 	bool is_exported = token->is_identifier_exported();
2516 	std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2517 
2518 	Named_object* in_function;
2519 	Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2520 
2521 	Package* package = NULL;
2522 	if (named_object != NULL && named_object->is_package())
2523 	  {
2524 	    if (!this->advance_token()->is_op(OPERATOR_DOT)
2525 		|| !this->advance_token()->is_identifier())
2526 	      {
2527 		go_error_at(location, "unexpected reference to package");
2528 		return Expression::make_error(location);
2529 	      }
2530 	    package = named_object->package_value();
2531 	    package->note_usage(id);
2532 	    id = this->peek_token()->identifier();
2533 	    is_exported = this->peek_token()->is_identifier_exported();
2534 	    packed = this->gogo_->pack_hidden_name(id, is_exported);
2535 	    named_object = package->lookup(packed);
2536 	    location = this->location();
2537 	    go_assert(in_function == NULL);
2538 	  }
2539 
2540 	this->advance_token();
2541 
2542 	if (named_object != NULL
2543 	    && named_object->is_type()
2544 	    && !named_object->type_value()->is_visible())
2545 	  {
2546 	    go_assert(package != NULL);
2547 	    go_error_at(location, "invalid reference to hidden type %<%s.%s%>",
2548 			Gogo::message_name(package->package_name()).c_str(),
2549 			Gogo::message_name(id).c_str());
2550 	    return Expression::make_error(location);
2551 	  }
2552 
2553 
2554 	if (named_object == NULL)
2555 	  {
2556 	    if (package != NULL)
2557 	      {
2558 		std::string n1 = Gogo::message_name(package->package_name());
2559 		std::string n2 = Gogo::message_name(id);
2560 		if (!is_exported)
2561 		  go_error_at(location,
2562 			      ("invalid reference to unexported identifier "
2563 			       "%<%s.%s%>"),
2564 			      n1.c_str(), n2.c_str());
2565 		else
2566 		  go_error_at(location,
2567 			      "reference to undefined identifier %<%s.%s%>",
2568 			      n1.c_str(), n2.c_str());
2569 		return Expression::make_error(location);
2570 	      }
2571 
2572 	    named_object = this->gogo_->add_unknown_name(packed, location);
2573 	  }
2574 
2575 	if (in_function != NULL
2576 	    && in_function != this->gogo_->current_function()
2577 	    && (named_object->is_variable()
2578 		|| named_object->is_result_variable()))
2579 	  return this->enclosing_var_reference(in_function, named_object,
2580 					       may_be_sink, location);
2581 
2582 	switch (named_object->classification())
2583 	  {
2584 	  case Named_object::NAMED_OBJECT_CONST:
2585 	    return Expression::make_const_reference(named_object, location);
2586 	  case Named_object::NAMED_OBJECT_TYPE:
2587 	    return Expression::make_type(named_object->type_value(), location);
2588 	  case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2589 	    {
2590 	      Type* t = Type::make_forward_declaration(named_object);
2591 	      return Expression::make_type(t, location);
2592 	    }
2593 	  case Named_object::NAMED_OBJECT_VAR:
2594 	  case Named_object::NAMED_OBJECT_RESULT_VAR:
2595 	    // Any left-hand-side can be a sink, so if this can not be
2596 	    // a sink, then it must be a use of the variable.
2597 	    if (!may_be_sink)
2598 	      this->mark_var_used(named_object);
2599 	    return Expression::make_var_reference(named_object, location);
2600 	  case Named_object::NAMED_OBJECT_SINK:
2601 	    if (may_be_sink)
2602 	      return Expression::make_sink(location);
2603 	    else
2604 	      {
2605 		go_error_at(location, "cannot use %<_%> as value");
2606 		return Expression::make_error(location);
2607 	      }
2608 	  case Named_object::NAMED_OBJECT_FUNC:
2609 	  case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2610 	    return Expression::make_func_reference(named_object, NULL,
2611 						   location);
2612 	  case Named_object::NAMED_OBJECT_UNKNOWN:
2613 	    {
2614 	      Unknown_expression* ue =
2615 		Expression::make_unknown_reference(named_object, location);
2616 	      if (this->is_erroneous_function_)
2617 		ue->set_no_error_message();
2618 	      return ue;
2619 	    }
2620 	  case Named_object::NAMED_OBJECT_ERRONEOUS:
2621 	    return Expression::make_error(location);
2622 	  default:
2623 	    go_unreachable();
2624 	  }
2625       }
2626       go_unreachable();
2627 
2628     case Token::TOKEN_STRING:
2629       ret = Expression::make_string(token->string_value(), token->location());
2630       this->advance_token();
2631       return ret;
2632 
2633     case Token::TOKEN_CHARACTER:
2634       ret = Expression::make_character(token->character_value(), NULL,
2635 				       token->location());
2636       this->advance_token();
2637       return ret;
2638 
2639     case Token::TOKEN_INTEGER:
2640       ret = Expression::make_integer_z(token->integer_value(), NULL,
2641 				       token->location());
2642       this->advance_token();
2643       return ret;
2644 
2645     case Token::TOKEN_FLOAT:
2646       ret = Expression::make_float(token->float_value(), NULL,
2647 				   token->location());
2648       this->advance_token();
2649       return ret;
2650 
2651     case Token::TOKEN_IMAGINARY:
2652       {
2653 	mpfr_t zero;
2654 	mpfr_init_set_ui(zero, 0, MPFR_RNDN);
2655 	mpc_t val;
2656 	mpc_init2(val, mpc_precision);
2657 	mpc_set_fr_fr(val, zero, *token->imaginary_value(), MPC_RNDNN);
2658 	mpfr_clear(zero);
2659 	ret = Expression::make_complex(&val, NULL, token->location());
2660 	mpc_clear(val);
2661 	this->advance_token();
2662 	return ret;
2663       }
2664 
2665     case Token::TOKEN_KEYWORD:
2666       switch (token->keyword())
2667 	{
2668 	case KEYWORD_FUNC:
2669 	  return this->function_lit();
2670 	case KEYWORD_CHAN:
2671 	case KEYWORD_INTERFACE:
2672 	case KEYWORD_MAP:
2673 	case KEYWORD_STRUCT:
2674 	  {
2675 	    Location location = token->location();
2676 	    return Expression::make_type(this->type(), location);
2677 	  }
2678 	default:
2679 	  break;
2680 	}
2681       break;
2682 
2683     case Token::TOKEN_OPERATOR:
2684       if (token->is_op(OPERATOR_LPAREN))
2685 	{
2686 	  this->advance_token();
2687 	  ret = this->expression(PRECEDENCE_NORMAL, may_be_sink, true, NULL,
2688 				 NULL);
2689 	  if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2690 	    go_error_at(this->location(), "missing %<)%>");
2691 	  else
2692 	    this->advance_token();
2693 	  if (is_parenthesized != NULL)
2694 	    *is_parenthesized = true;
2695 	  return ret;
2696 	}
2697       else if (token->is_op(OPERATOR_LSQUARE))
2698 	{
2699 	  // Here we call array_type directly, as this is the only
2700 	  // case where an ellipsis is permitted for an array type.
2701 	  Location location = token->location();
2702 	  return Expression::make_type(this->array_type(true), location);
2703 	}
2704       break;
2705 
2706     default:
2707       break;
2708     }
2709 
2710   go_error_at(this->location(), "expected operand");
2711   return Expression::make_error(this->location());
2712 }
2713 
2714 // Handle a reference to a variable in an enclosing function.  We add
2715 // it to a list of such variables.  We return a reference to a field
2716 // in a struct which will be passed on the static chain when calling
2717 // the current function.
2718 
2719 Expression*
enclosing_var_reference(Named_object * in_function,Named_object * var,bool may_be_sink,Location location)2720 Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2721 			       bool may_be_sink, Location location)
2722 {
2723   go_assert(var->is_variable() || var->is_result_variable());
2724 
2725   // Any left-hand-side can be a sink, so if this can not be
2726   // a sink, then it must be a use of the variable.
2727   if (!may_be_sink)
2728     this->mark_var_used(var);
2729 
2730   Named_object* this_function = this->gogo_->current_function();
2731   Named_object* closure = this_function->func_value()->closure_var();
2732 
2733   // The last argument to the Enclosing_var constructor is the index
2734   // of this variable in the closure.  We add 1 to the current number
2735   // of enclosed variables, because the first field in the closure
2736   // points to the function code.
2737   Enclosing_var ev(var, in_function, this->enclosing_vars_.size() + 1);
2738   std::pair<Enclosing_vars::iterator, bool> ins =
2739     this->enclosing_vars_.insert(ev);
2740   if (ins.second)
2741     {
2742       // This is a variable we have not seen before.  Add a new field
2743       // to the closure type.
2744       this_function->func_value()->add_closure_field(var, location);
2745     }
2746 
2747   Expression* closure_ref = Expression::make_var_reference(closure,
2748 							   location);
2749   closure_ref =
2750       Expression::make_dereference(closure_ref,
2751                                    Expression::NIL_CHECK_NOT_NEEDED,
2752                                    location);
2753 
2754   // The closure structure holds pointers to the variables, so we need
2755   // to introduce an indirection.
2756   Expression* e = Expression::make_field_reference(closure_ref,
2757 						   ins.first->index(),
2758 						   location);
2759   e = Expression::make_dereference(e, Expression::NIL_CHECK_NOT_NEEDED,
2760                                    location);
2761   return Expression::make_enclosing_var_reference(e, var, location);
2762 }
2763 
2764 // CompositeLit  = LiteralType LiteralValue .
2765 // LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
2766 //                 SliceType | MapType | TypeName .
2767 // LiteralValue  = "{" [ ElementList [ "," ] ] "}" .
2768 // ElementList   = Element { "," Element } .
2769 // Element       = [ Key ":" ] Value .
2770 // Key           = FieldName | ElementIndex .
2771 // FieldName     = identifier .
2772 // ElementIndex  = Expression .
2773 // Value         = Expression | LiteralValue .
2774 
2775 // We have already seen the type if there is one, and we are now
2776 // looking at the LiteralValue.  The case "[" "..."  "]" ElementType
2777 // will be seen here as an array type whose length is "nil".  The
2778 // DEPTH parameter is non-zero if this is an embedded composite
2779 // literal and the type was omitted.  It gives the number of steps up
2780 // to the type which was provided.  E.g., in [][]int{{1}} it will be
2781 // 1.  In [][][]int{{{1}}} it will be 2.
2782 
2783 Expression*
composite_lit(Type * type,int depth,Location location)2784 Parse::composite_lit(Type* type, int depth, Location location)
2785 {
2786   go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2787   this->advance_token();
2788 
2789   if (this->peek_token()->is_op(OPERATOR_RCURLY))
2790     {
2791       this->advance_token();
2792       return Expression::make_composite_literal(type, depth, false, NULL,
2793 						false, location);
2794     }
2795 
2796   bool has_keys = false;
2797   bool all_are_names = true;
2798   Expression_list* vals = new Expression_list;
2799   while (true)
2800     {
2801       Expression* val;
2802       bool is_type_omitted = false;
2803       bool is_name = false;
2804 
2805       const Token* token = this->peek_token();
2806 
2807       if (token->is_identifier())
2808 	{
2809 	  std::string identifier = token->identifier();
2810 	  bool is_exported = token->is_identifier_exported();
2811 	  Location id_location = token->location();
2812 
2813 	  if (this->advance_token()->is_op(OPERATOR_COLON))
2814 	    {
2815 	      // This may be a field name.  We don't know for sure--it
2816 	      // could also be an expression for an array index.  We
2817 	      // don't want to parse it as an expression because may
2818 	      // trigger various errors, e.g., if this identifier
2819 	      // happens to be the name of a package.
2820 	      Gogo* gogo = this->gogo_;
2821 	      val = this->id_to_expression(gogo->pack_hidden_name(identifier,
2822 								  is_exported),
2823 					   id_location, false, true);
2824 	      is_name = true;
2825 	    }
2826 	  else
2827 	    {
2828 	      this->unget_token(Token::make_identifier_token(identifier,
2829 							     is_exported,
2830 							     id_location));
2831 	      val = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
2832 				     NULL);
2833 	    }
2834 	}
2835       else if (!token->is_op(OPERATOR_LCURLY))
2836 	val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
2837       else
2838 	{
2839 	  // This must be a composite literal inside another composite
2840 	  // literal, with the type omitted for the inner one.
2841 	  val = this->composite_lit(type, depth + 1, token->location());
2842           is_type_omitted = true;
2843 	}
2844 
2845       token = this->peek_token();
2846       if (!token->is_op(OPERATOR_COLON))
2847 	{
2848 	  if (has_keys)
2849 	    vals->push_back(NULL);
2850 	  is_name = false;
2851 	}
2852       else
2853 	{
2854           if (is_type_omitted)
2855             {
2856               // VAL is a nested composite literal with an omitted type being
2857               // used a key.  Record this information in VAL so that the correct
2858               // type is associated with the literal value if VAL is a
2859               // map literal.
2860               val->complit()->update_key_path(depth);
2861             }
2862 
2863 	  this->advance_token();
2864 
2865 	  if (!has_keys && !vals->empty())
2866 	    {
2867 	      Expression_list* newvals = new Expression_list;
2868 	      for (Expression_list::const_iterator p = vals->begin();
2869 		   p != vals->end();
2870 		   ++p)
2871 		{
2872 		  newvals->push_back(NULL);
2873 		  newvals->push_back(*p);
2874 		}
2875 	      delete vals;
2876 	      vals = newvals;
2877 	    }
2878 	  has_keys = true;
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 edepth = 0;
2924 	  while (!token->is_eof()
2925 		 && (edepth > 0 || !token->is_op(OPERATOR_RCURLY)))
2926 	    {
2927 	      if (token->is_op(OPERATOR_LCURLY))
2928 		++edepth;
2929 	      else if (token->is_op(OPERATOR_RCURLY))
2930 		--edepth;
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,bool is_composite_literal_key)3344 Parse::id_to_expression(const std::string& name, Location location,
3345 			bool is_lhs, bool is_composite_literal_key)
3346 {
3347   Named_object* in_function;
3348   Named_object* named_object = this->gogo_->lookup(name, &in_function);
3349   if (named_object == NULL)
3350     {
3351       if (is_composite_literal_key)
3352 	{
3353 	  // This is a composite literal key, which means that it
3354 	  // could just be a struct field name, so avoid confusiong by
3355 	  // not adding it to the bindings.  We'll look up the name
3356 	  // later during the lowering phase if necessary.
3357 	  return Expression::make_composite_literal_key(name, location);
3358 	}
3359       named_object = this->gogo_->add_unknown_name(name, location);
3360     }
3361 
3362   if (in_function != NULL
3363       && in_function != this->gogo_->current_function()
3364       && (named_object->is_variable() || named_object->is_result_variable()))
3365     return this->enclosing_var_reference(in_function, named_object, is_lhs,
3366 					 location);
3367 
3368   switch (named_object->classification())
3369     {
3370     case Named_object::NAMED_OBJECT_CONST:
3371       return Expression::make_const_reference(named_object, location);
3372     case Named_object::NAMED_OBJECT_VAR:
3373     case Named_object::NAMED_OBJECT_RESULT_VAR:
3374       if (!is_lhs)
3375 	this->mark_var_used(named_object);
3376       return Expression::make_var_reference(named_object, location);
3377     case Named_object::NAMED_OBJECT_SINK:
3378       return Expression::make_sink(location);
3379     case Named_object::NAMED_OBJECT_FUNC:
3380     case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3381       return Expression::make_func_reference(named_object, NULL, location);
3382     case Named_object::NAMED_OBJECT_UNKNOWN:
3383       {
3384 	Unknown_expression* ue =
3385 	  Expression::make_unknown_reference(named_object, location);
3386 	if (this->is_erroneous_function_)
3387 	  ue->set_no_error_message();
3388 	return ue;
3389       }
3390     case Named_object::NAMED_OBJECT_PACKAGE:
3391     case Named_object::NAMED_OBJECT_TYPE:
3392     case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3393       {
3394 	// These cases can arise for a field name in a composite
3395 	// literal.  Keep track of these as they might be fake uses of
3396 	// the related package.
3397 	Unknown_expression* ue =
3398 	  Expression::make_unknown_reference(named_object, location);
3399 	if (named_object->package() != NULL)
3400 	  named_object->package()->note_fake_usage(ue);
3401 	if (this->is_erroneous_function_)
3402 	  ue->set_no_error_message();
3403 	return ue;
3404       }
3405     case Named_object::NAMED_OBJECT_ERRONEOUS:
3406       return Expression::make_error(location);
3407     default:
3408       go_error_at(this->location(), "unexpected type of identifier");
3409       return Expression::make_error(location);
3410     }
3411 }
3412 
3413 // Expression = UnaryExpr { binary_op Expression } .
3414 
3415 // PRECEDENCE is the precedence of the current operator.
3416 
3417 // If MAY_BE_SINK is true, this expression may be "_".
3418 
3419 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3420 // literal.
3421 
3422 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3423 // guard (var := expr.("type") using the literal keyword "type").
3424 
3425 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3426 // if the entire expression is in parentheses.
3427 
3428 Expression*
expression(Precedence precedence,bool may_be_sink,bool may_be_composite_lit,bool * is_type_switch,bool * is_parenthesized)3429 Parse::expression(Precedence precedence, bool may_be_sink,
3430 		  bool may_be_composite_lit, bool* is_type_switch,
3431 		  bool *is_parenthesized)
3432 {
3433   Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
3434 				      is_type_switch, is_parenthesized);
3435 
3436   while (true)
3437     {
3438       if (is_type_switch != NULL && *is_type_switch)
3439 	return left;
3440 
3441       const Token* token = this->peek_token();
3442       if (token->classification() != Token::TOKEN_OPERATOR)
3443 	{
3444 	  // Not a binary_op.
3445 	  return left;
3446 	}
3447 
3448       Precedence right_precedence;
3449       switch (token->op())
3450 	{
3451 	case OPERATOR_OROR:
3452 	  right_precedence = PRECEDENCE_OROR;
3453 	  break;
3454 	case OPERATOR_ANDAND:
3455 	  right_precedence = PRECEDENCE_ANDAND;
3456 	  break;
3457 	case OPERATOR_EQEQ:
3458 	case OPERATOR_NOTEQ:
3459 	case OPERATOR_LT:
3460 	case OPERATOR_LE:
3461 	case OPERATOR_GT:
3462 	case OPERATOR_GE:
3463 	  right_precedence = PRECEDENCE_RELOP;
3464 	  break;
3465 	case OPERATOR_PLUS:
3466 	case OPERATOR_MINUS:
3467 	case OPERATOR_OR:
3468 	case OPERATOR_XOR:
3469 	  right_precedence = PRECEDENCE_ADDOP;
3470 	  break;
3471 	case OPERATOR_MULT:
3472 	case OPERATOR_DIV:
3473 	case OPERATOR_MOD:
3474 	case OPERATOR_LSHIFT:
3475 	case OPERATOR_RSHIFT:
3476 	case OPERATOR_AND:
3477 	case OPERATOR_BITCLEAR:
3478 	  right_precedence = PRECEDENCE_MULOP;
3479 	  break;
3480 	default:
3481 	  right_precedence = PRECEDENCE_INVALID;
3482 	  break;
3483 	}
3484 
3485       if (right_precedence == PRECEDENCE_INVALID)
3486 	{
3487 	  // Not a binary_op.
3488 	  return left;
3489 	}
3490 
3491       if (is_parenthesized != NULL)
3492 	*is_parenthesized = false;
3493 
3494       Operator op = token->op();
3495       Location binop_location = token->location();
3496 
3497       if (precedence >= right_precedence)
3498 	{
3499 	  // We've already seen A * B, and we see + C.  We want to
3500 	  // return so that A * B becomes a group.
3501 	  return left;
3502 	}
3503 
3504       this->advance_token();
3505 
3506       left = this->verify_not_sink(left);
3507       Expression* right = this->expression(right_precedence, false,
3508 					   may_be_composite_lit,
3509 					   NULL, NULL);
3510       left = Expression::make_binary(op, left, right, binop_location);
3511     }
3512 }
3513 
3514 bool
expression_may_start_here()3515 Parse::expression_may_start_here()
3516 {
3517   const Token* token = this->peek_token();
3518   switch (token->classification())
3519     {
3520     case Token::TOKEN_INVALID:
3521     case Token::TOKEN_EOF:
3522       return false;
3523     case Token::TOKEN_KEYWORD:
3524       switch (token->keyword())
3525 	{
3526 	case KEYWORD_CHAN:
3527 	case KEYWORD_FUNC:
3528 	case KEYWORD_MAP:
3529 	case KEYWORD_STRUCT:
3530 	case KEYWORD_INTERFACE:
3531 	  return true;
3532 	default:
3533 	  return false;
3534 	}
3535     case Token::TOKEN_IDENTIFIER:
3536       return true;
3537     case Token::TOKEN_STRING:
3538       return true;
3539     case Token::TOKEN_OPERATOR:
3540       switch (token->op())
3541 	{
3542 	case OPERATOR_PLUS:
3543 	case OPERATOR_MINUS:
3544 	case OPERATOR_NOT:
3545 	case OPERATOR_XOR:
3546 	case OPERATOR_MULT:
3547 	case OPERATOR_CHANOP:
3548 	case OPERATOR_AND:
3549 	case OPERATOR_LPAREN:
3550 	case OPERATOR_LSQUARE:
3551 	  return true;
3552 	default:
3553 	  return false;
3554 	}
3555     case Token::TOKEN_CHARACTER:
3556     case Token::TOKEN_INTEGER:
3557     case Token::TOKEN_FLOAT:
3558     case Token::TOKEN_IMAGINARY:
3559       return true;
3560     default:
3561       go_unreachable();
3562     }
3563 }
3564 
3565 // UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3566 
3567 // If MAY_BE_SINK is true, this expression may be "_".
3568 
3569 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3570 // literal.
3571 
3572 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3573 // guard (var := expr.("type") using the literal keyword "type").
3574 
3575 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3576 // if the entire expression is in parentheses.
3577 
3578 Expression*
unary_expr(bool may_be_sink,bool may_be_composite_lit,bool * is_type_switch,bool * is_parenthesized)3579 Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3580 		  bool* is_type_switch, bool* is_parenthesized)
3581 {
3582   const Token* token = this->peek_token();
3583 
3584   // There is a complex parse for <- chan.  The choices are
3585   // Convert x to type <- chan int:
3586   //   (<- chan int)(x)
3587   // Receive from (x converted to type chan <- chan int):
3588   //   (<- chan <- chan int (x))
3589   // Convert x to type <- chan (<- chan int).
3590   //   (<- chan <- chan int)(x)
3591   if (token->is_op(OPERATOR_CHANOP))
3592     {
3593       Location location = token->location();
3594       if (this->advance_token()->is_keyword(KEYWORD_CHAN))
3595 	{
3596 	  Expression* expr = this->primary_expr(false, may_be_composite_lit,
3597 						NULL, NULL);
3598 	  if (expr->is_error_expression())
3599 	    return expr;
3600 	  else if (!expr->is_type_expression())
3601 	    return Expression::make_receive(expr, location);
3602 	  else
3603 	    {
3604 	      if (expr->type()->is_error_type())
3605 		return expr;
3606 
3607 	      // We picked up "chan TYPE", but it is not a type
3608 	      // conversion.
3609 	      Channel_type* ct = expr->type()->channel_type();
3610 	      if (ct == NULL)
3611 		{
3612 		  // This is probably impossible.
3613 		  go_error_at(location, "expected channel type");
3614 		  return Expression::make_error(location);
3615 		}
3616 	      else if (ct->may_receive())
3617 		{
3618 		  // <- chan TYPE.
3619 		  Type* t = Type::make_channel_type(false, true,
3620 						    ct->element_type());
3621 		  return Expression::make_type(t, location);
3622 		}
3623 	      else
3624 		{
3625 		  // <- chan <- TYPE.  Because we skipped the leading
3626 		  // <-, we parsed this as chan <- TYPE.  With the
3627 		  // leading <-, we parse it as <- chan (<- TYPE).
3628 		  Type *t = this->reassociate_chan_direction(ct, location);
3629 		  return Expression::make_type(t, location);
3630 		}
3631 	    }
3632 	}
3633 
3634       this->unget_token(Token::make_operator_token(OPERATOR_CHANOP, location));
3635       token = this->peek_token();
3636     }
3637 
3638   if (token->is_op(OPERATOR_PLUS)
3639       || token->is_op(OPERATOR_MINUS)
3640       || token->is_op(OPERATOR_NOT)
3641       || token->is_op(OPERATOR_XOR)
3642       || token->is_op(OPERATOR_CHANOP)
3643       || token->is_op(OPERATOR_MULT)
3644       || token->is_op(OPERATOR_AND))
3645     {
3646       Location location = token->location();
3647       Operator op = token->op();
3648       this->advance_token();
3649 
3650       Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL,
3651 					  NULL);
3652       if (expr->is_error_expression())
3653 	;
3654       else if (op == OPERATOR_MULT && expr->is_type_expression())
3655 	expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3656 				     location);
3657       else if (op == OPERATOR_AND && expr->is_composite_literal())
3658 	expr = Expression::make_heap_expression(expr, location);
3659       else if (op != OPERATOR_CHANOP)
3660 	expr = Expression::make_unary(op, expr, location);
3661       else
3662 	expr = Expression::make_receive(expr, location);
3663       return expr;
3664     }
3665   else
3666     return this->primary_expr(may_be_sink, may_be_composite_lit,
3667 			      is_type_switch, is_parenthesized);
3668 }
3669 
3670 // This is called for the obscure case of
3671 //   (<- chan <- chan int)(x)
3672 // In unary_expr we remove the leading <- and parse the remainder,
3673 // which gives us
3674 //   chan <- (chan int)
3675 // When we add the leading <- back in, we really want
3676 //   <- chan (<- chan int)
3677 // This means that we need to reassociate.
3678 
3679 Type*
reassociate_chan_direction(Channel_type * ct,Location location)3680 Parse::reassociate_chan_direction(Channel_type *ct, Location location)
3681 {
3682   Channel_type* ele = ct->element_type()->channel_type();
3683   if (ele == NULL)
3684     {
3685       go_error_at(location, "parse error");
3686       return Type::make_error_type();
3687     }
3688   Type* sub = ele;
3689   if (ele->may_send())
3690     sub = Type::make_channel_type(false, true, ele->element_type());
3691   else
3692     sub = this->reassociate_chan_direction(ele, location);
3693   return Type::make_channel_type(false, true, sub);
3694 }
3695 
3696 // Statement =
3697 //	Declaration | LabeledStmt | SimpleStmt |
3698 //	GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3699 //	FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3700 //	DeferStmt .
3701 
3702 // LABEL is the label of this statement if it has one.
3703 
3704 void
statement(Label * label)3705 Parse::statement(Label* label)
3706 {
3707   const Token* token = this->peek_token();
3708   switch (token->classification())
3709     {
3710     case Token::TOKEN_KEYWORD:
3711       {
3712 	switch (token->keyword())
3713 	  {
3714 	  case KEYWORD_CONST:
3715 	  case KEYWORD_TYPE:
3716 	  case KEYWORD_VAR:
3717 	    this->declaration();
3718 	    break;
3719 	  case KEYWORD_FUNC:
3720 	  case KEYWORD_MAP:
3721 	  case KEYWORD_STRUCT:
3722 	  case KEYWORD_INTERFACE:
3723 	    this->simple_stat(true, NULL, NULL, NULL);
3724 	    break;
3725 	  case KEYWORD_GO:
3726 	  case KEYWORD_DEFER:
3727 	    this->go_or_defer_stat();
3728 	    break;
3729 	  case KEYWORD_RETURN:
3730 	    this->return_stat();
3731 	    break;
3732 	  case KEYWORD_BREAK:
3733 	    this->break_stat();
3734 	    break;
3735 	  case KEYWORD_CONTINUE:
3736 	    this->continue_stat();
3737 	    break;
3738 	  case KEYWORD_GOTO:
3739 	    this->goto_stat();
3740 	    break;
3741 	  case KEYWORD_IF:
3742 	    this->if_stat();
3743 	    break;
3744 	  case KEYWORD_SWITCH:
3745 	    this->switch_stat(label);
3746 	    break;
3747 	  case KEYWORD_SELECT:
3748 	    this->select_stat(label);
3749 	    break;
3750 	  case KEYWORD_FOR:
3751 	    this->for_stat(label);
3752 	    break;
3753 	  default:
3754 	    go_error_at(this->location(), "expected statement");
3755 	    this->advance_token();
3756 	    break;
3757 	  }
3758       }
3759       break;
3760 
3761     case Token::TOKEN_IDENTIFIER:
3762       {
3763 	std::string identifier = token->identifier();
3764 	bool is_exported = token->is_identifier_exported();
3765 	Location location = token->location();
3766 	if (this->advance_token()->is_op(OPERATOR_COLON))
3767 	  {
3768 	    this->advance_token();
3769 	    this->labeled_stmt(identifier, location);
3770 	  }
3771 	else
3772 	  {
3773 	    this->unget_token(Token::make_identifier_token(identifier,
3774 							   is_exported,
3775 							   location));
3776 	    this->simple_stat(true, NULL, NULL, NULL);
3777 	  }
3778       }
3779       break;
3780 
3781     case Token::TOKEN_OPERATOR:
3782       if (token->is_op(OPERATOR_LCURLY))
3783 	{
3784 	  Location location = token->location();
3785 	  this->gogo_->start_block(location);
3786 	  Location end_loc = this->block();
3787 	  this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3788 				 location);
3789 	}
3790       else if (!token->is_op(OPERATOR_SEMICOLON))
3791 	this->simple_stat(true, NULL, NULL, NULL);
3792       break;
3793 
3794     case Token::TOKEN_STRING:
3795     case Token::TOKEN_CHARACTER:
3796     case Token::TOKEN_INTEGER:
3797     case Token::TOKEN_FLOAT:
3798     case Token::TOKEN_IMAGINARY:
3799       this->simple_stat(true, NULL, NULL, NULL);
3800       break;
3801 
3802     default:
3803       go_error_at(this->location(), "expected statement");
3804       this->advance_token();
3805       break;
3806     }
3807 }
3808 
3809 bool
statement_may_start_here()3810 Parse::statement_may_start_here()
3811 {
3812   const Token* token = this->peek_token();
3813   switch (token->classification())
3814     {
3815     case Token::TOKEN_KEYWORD:
3816       {
3817 	switch (token->keyword())
3818 	  {
3819 	  case KEYWORD_CONST:
3820 	  case KEYWORD_TYPE:
3821 	  case KEYWORD_VAR:
3822 	  case KEYWORD_FUNC:
3823 	  case KEYWORD_MAP:
3824 	  case KEYWORD_STRUCT:
3825 	  case KEYWORD_INTERFACE:
3826 	  case KEYWORD_GO:
3827 	  case KEYWORD_DEFER:
3828 	  case KEYWORD_RETURN:
3829 	  case KEYWORD_BREAK:
3830 	  case KEYWORD_CONTINUE:
3831 	  case KEYWORD_GOTO:
3832 	  case KEYWORD_IF:
3833 	  case KEYWORD_SWITCH:
3834 	  case KEYWORD_SELECT:
3835 	  case KEYWORD_FOR:
3836 	    return true;
3837 
3838 	  default:
3839 	    return false;
3840 	  }
3841       }
3842       break;
3843 
3844     case Token::TOKEN_IDENTIFIER:
3845       return true;
3846 
3847     case Token::TOKEN_OPERATOR:
3848       if (token->is_op(OPERATOR_LCURLY)
3849 	  || token->is_op(OPERATOR_SEMICOLON))
3850 	return true;
3851       else
3852 	return this->expression_may_start_here();
3853 
3854     case Token::TOKEN_STRING:
3855     case Token::TOKEN_CHARACTER:
3856     case Token::TOKEN_INTEGER:
3857     case Token::TOKEN_FLOAT:
3858     case Token::TOKEN_IMAGINARY:
3859       return true;
3860 
3861     default:
3862       return false;
3863     }
3864 }
3865 
3866 // LabeledStmt = Label ":" Statement .
3867 // Label       = identifier .
3868 
3869 void
labeled_stmt(const std::string & label_name,Location location)3870 Parse::labeled_stmt(const std::string& label_name, Location location)
3871 {
3872   Label* label = this->gogo_->add_label_definition(label_name, location);
3873 
3874   if (this->peek_token()->is_op(OPERATOR_RCURLY))
3875     {
3876       // This is a label at the end of a block.  A program is
3877       // permitted to omit a semicolon here.
3878       return;
3879     }
3880 
3881   if (!this->statement_may_start_here())
3882     {
3883       if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
3884 	{
3885 	  // We don't treat the fallthrough keyword as a statement,
3886 	  // because it can't appear most places where a statement is
3887 	  // permitted, but it may have a label.  We introduce a
3888 	  // semicolon because the caller expects to see a statement.
3889 	  this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3890 						       location));
3891 	  return;
3892 	}
3893 
3894       // Mark the label as used to avoid a useless error about an
3895       // unused label.
3896       if (label != NULL)
3897         label->set_is_used();
3898 
3899       go_error_at(location, "missing statement after label");
3900       this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3901 						   location));
3902       return;
3903     }
3904 
3905   this->statement(label);
3906 }
3907 
3908 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
3909 //	Assignment | ShortVarDecl .
3910 
3911 // EmptyStmt was handled in Parse::statement.
3912 
3913 // In order to make this work for if and switch statements, if
3914 // RETURN_EXP is not NULL, and we see an ExpressionStat, we return the
3915 // expression rather than adding an expression statement to the
3916 // current block.  If we see something other than an ExpressionStat,
3917 // we add the statement, set *RETURN_EXP to true if we saw a send
3918 // statement, and return NULL.  The handling of send statements is for
3919 // better error messages.
3920 
3921 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
3922 // RangeClause.
3923 
3924 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
3925 // guard (var := expr.("type") using the literal keyword "type").
3926 
3927 Expression*
simple_stat(bool may_be_composite_lit,bool * return_exp,Range_clause * p_range_clause,Type_switch * p_type_switch)3928 Parse::simple_stat(bool may_be_composite_lit, bool* return_exp,
3929 		   Range_clause* p_range_clause, Type_switch* p_type_switch)
3930 {
3931   const Token* token = this->peek_token();
3932 
3933   // An identifier follow by := is a SimpleVarDecl.
3934   if (token->is_identifier())
3935     {
3936       std::string identifier = token->identifier();
3937       bool is_exported = token->is_identifier_exported();
3938       Location location = token->location();
3939 
3940       token = this->advance_token();
3941       if (token->is_op(OPERATOR_COLONEQ)
3942 	  || token->is_op(OPERATOR_COMMA))
3943 	{
3944 	  identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
3945 	  this->simple_var_decl_or_assignment(identifier, location,
3946 					      may_be_composite_lit,
3947 					      p_range_clause,
3948 					      (token->is_op(OPERATOR_COLONEQ)
3949 					       ? p_type_switch
3950 					       : NULL));
3951 	  return NULL;
3952 	}
3953 
3954       this->unget_token(Token::make_identifier_token(identifier, is_exported,
3955 						     location));
3956     }
3957   else if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
3958     {
3959       Typed_identifier_list til;
3960       this->range_clause_decl(&til, p_range_clause);
3961       return NULL;
3962     }
3963 
3964   Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
3965 				     may_be_composite_lit,
3966 				     (p_type_switch == NULL
3967 				      ? NULL
3968 				      : &p_type_switch->found),
3969 				     NULL);
3970   if (p_type_switch != NULL && p_type_switch->found)
3971     {
3972       p_type_switch->name.clear();
3973       p_type_switch->location = exp->location();
3974       p_type_switch->expr = this->verify_not_sink(exp);
3975       return NULL;
3976     }
3977   token = this->peek_token();
3978   if (token->is_op(OPERATOR_CHANOP))
3979     {
3980       this->send_stmt(this->verify_not_sink(exp), may_be_composite_lit);
3981       if (return_exp != NULL)
3982 	*return_exp = true;
3983     }
3984   else if (token->is_op(OPERATOR_PLUSPLUS)
3985 	   || token->is_op(OPERATOR_MINUSMINUS))
3986     this->inc_dec_stat(this->verify_not_sink(exp));
3987   else if (token->is_op(OPERATOR_COMMA)
3988 	   || token->is_op(OPERATOR_EQ))
3989     this->assignment(exp, may_be_composite_lit, p_range_clause);
3990   else if (token->is_op(OPERATOR_PLUSEQ)
3991 	   || token->is_op(OPERATOR_MINUSEQ)
3992 	   || token->is_op(OPERATOR_OREQ)
3993 	   || token->is_op(OPERATOR_XOREQ)
3994 	   || token->is_op(OPERATOR_MULTEQ)
3995 	   || token->is_op(OPERATOR_DIVEQ)
3996 	   || token->is_op(OPERATOR_MODEQ)
3997 	   || token->is_op(OPERATOR_LSHIFTEQ)
3998 	   || token->is_op(OPERATOR_RSHIFTEQ)
3999 	   || token->is_op(OPERATOR_ANDEQ)
4000 	   || token->is_op(OPERATOR_BITCLEAREQ))
4001     this->assignment(this->verify_not_sink(exp), may_be_composite_lit,
4002 		     p_range_clause);
4003   else if (return_exp != NULL)
4004     return this->verify_not_sink(exp);
4005   else
4006     {
4007       exp = this->verify_not_sink(exp);
4008 
4009       if (token->is_op(OPERATOR_COLONEQ))
4010 	{
4011 	  if (!exp->is_error_expression())
4012 	    go_error_at(token->location(), "non-name on left side of %<:=%>");
4013 	  this->gogo_->mark_locals_used();
4014 	  while (!token->is_op(OPERATOR_SEMICOLON)
4015 		 && !token->is_eof())
4016 	    token = this->advance_token();
4017 	  return NULL;
4018 	}
4019 
4020       this->expression_stat(exp);
4021     }
4022 
4023   return NULL;
4024 }
4025 
4026 bool
simple_stat_may_start_here()4027 Parse::simple_stat_may_start_here()
4028 {
4029   return this->expression_may_start_here();
4030 }
4031 
4032 // Parse { Statement ";" } which is used in a few places.  The list of
4033 // statements may end with a right curly brace, in which case the
4034 // semicolon may be omitted.
4035 
4036 void
statement_list()4037 Parse::statement_list()
4038 {
4039   while (this->statement_may_start_here())
4040     {
4041       this->statement(NULL);
4042       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4043 	this->advance_token();
4044       else if (this->peek_token()->is_op(OPERATOR_RCURLY))
4045 	break;
4046       else
4047 	{
4048 	  if (!this->peek_token()->is_eof() || !saw_errors())
4049 	    go_error_at(this->location(), "expected %<;%> or %<}%> or newline");
4050 	  if (!this->skip_past_error(OPERATOR_RCURLY))
4051 	    return;
4052 	}
4053     }
4054 }
4055 
4056 bool
statement_list_may_start_here()4057 Parse::statement_list_may_start_here()
4058 {
4059   return this->statement_may_start_here();
4060 }
4061 
4062 // ExpressionStat = Expression .
4063 
4064 void
expression_stat(Expression * exp)4065 Parse::expression_stat(Expression* exp)
4066 {
4067   this->gogo_->add_statement(Statement::make_statement(exp, false));
4068 }
4069 
4070 // SendStmt = Channel "&lt;-" Expression .
4071 // Channel  = Expression .
4072 
4073 void
send_stmt(Expression * channel,bool may_be_composite_lit)4074 Parse::send_stmt(Expression* channel, bool may_be_composite_lit)
4075 {
4076   go_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
4077   Location loc = this->location();
4078   this->advance_token();
4079   Expression* val = this->expression(PRECEDENCE_NORMAL, false,
4080 				     may_be_composite_lit, NULL, NULL);
4081   Statement* s = Statement::make_send_statement(channel, val, loc);
4082   this->gogo_->add_statement(s);
4083 }
4084 
4085 // IncDecStat = Expression ( "++" | "--" ) .
4086 
4087 void
inc_dec_stat(Expression * exp)4088 Parse::inc_dec_stat(Expression* exp)
4089 {
4090   const Token* token = this->peek_token();
4091   if (token->is_op(OPERATOR_PLUSPLUS))
4092     this->gogo_->add_statement(Statement::make_inc_statement(exp));
4093   else if (token->is_op(OPERATOR_MINUSMINUS))
4094     this->gogo_->add_statement(Statement::make_dec_statement(exp));
4095   else
4096     go_unreachable();
4097   this->advance_token();
4098 }
4099 
4100 // Assignment = ExpressionList assign_op ExpressionList .
4101 
4102 // EXP is an expression that we have already parsed.
4103 
4104 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
4105 // side may be a composite literal.
4106 
4107 // If RANGE_CLAUSE is not NULL, then this will recognize a
4108 // RangeClause.
4109 
4110 void
assignment(Expression * expr,bool may_be_composite_lit,Range_clause * p_range_clause)4111 Parse::assignment(Expression* expr, bool may_be_composite_lit,
4112 		  Range_clause* p_range_clause)
4113 {
4114   Expression_list* vars;
4115   if (!this->peek_token()->is_op(OPERATOR_COMMA))
4116     {
4117       vars = new Expression_list();
4118       vars->push_back(expr);
4119     }
4120   else
4121     {
4122       this->advance_token();
4123       vars = this->expression_list(expr, true, may_be_composite_lit);
4124     }
4125 
4126   this->tuple_assignment(vars, may_be_composite_lit, p_range_clause);
4127 }
4128 
4129 // An assignment statement.  LHS is the list of expressions which
4130 // appear on the left hand side.
4131 
4132 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
4133 // side may be a composite literal.
4134 
4135 // If RANGE_CLAUSE is not NULL, then this will recognize a
4136 // RangeClause.
4137 
4138 void
tuple_assignment(Expression_list * lhs,bool may_be_composite_lit,Range_clause * p_range_clause)4139 Parse::tuple_assignment(Expression_list* lhs, bool may_be_composite_lit,
4140 			Range_clause* p_range_clause)
4141 {
4142   const Token* token = this->peek_token();
4143   if (!token->is_op(OPERATOR_EQ)
4144       && !token->is_op(OPERATOR_PLUSEQ)
4145       && !token->is_op(OPERATOR_MINUSEQ)
4146       && !token->is_op(OPERATOR_OREQ)
4147       && !token->is_op(OPERATOR_XOREQ)
4148       && !token->is_op(OPERATOR_MULTEQ)
4149       && !token->is_op(OPERATOR_DIVEQ)
4150       && !token->is_op(OPERATOR_MODEQ)
4151       && !token->is_op(OPERATOR_LSHIFTEQ)
4152       && !token->is_op(OPERATOR_RSHIFTEQ)
4153       && !token->is_op(OPERATOR_ANDEQ)
4154       && !token->is_op(OPERATOR_BITCLEAREQ))
4155     {
4156       go_error_at(this->location(), "expected assignment operator");
4157       return;
4158     }
4159   Operator op = token->op();
4160   Location location = token->location();
4161 
4162   token = this->advance_token();
4163 
4164   if (lhs == NULL)
4165     return;
4166 
4167   if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
4168     {
4169       if (op != OPERATOR_EQ)
4170 	go_error_at(this->location(), "range clause requires %<=%>");
4171       this->range_clause_expr(lhs, p_range_clause);
4172       return;
4173     }
4174 
4175   Expression_list* vals = this->expression_list(NULL, false,
4176 						may_be_composite_lit);
4177 
4178   // We've parsed everything; check for errors.
4179   if (vals == NULL)
4180     return;
4181   for (Expression_list::const_iterator pe = lhs->begin();
4182        pe != lhs->end();
4183        ++pe)
4184     {
4185       if ((*pe)->is_error_expression())
4186 	return;
4187       if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
4188 	go_error_at((*pe)->location(), "cannot use %<_%> as value");
4189     }
4190   for (Expression_list::const_iterator pe = vals->begin();
4191        pe != vals->end();
4192        ++pe)
4193     {
4194       if ((*pe)->is_error_expression())
4195 	return;
4196     }
4197 
4198   Call_expression* call;
4199   Index_expression* map_index;
4200   Receive_expression* receive;
4201   Type_guard_expression* type_guard;
4202   if (lhs->size() == vals->size())
4203     {
4204       Statement* s;
4205       if (lhs->size() > 1)
4206 	{
4207 	  if (op != OPERATOR_EQ)
4208 	    go_error_at(location, "multiple values only permitted with %<=%>");
4209 	  s = Statement::make_tuple_assignment(lhs, vals, location);
4210 	}
4211       else
4212 	{
4213 	  if (op == OPERATOR_EQ)
4214 	    s = Statement::make_assignment(lhs->front(), vals->front(),
4215 					   location);
4216 	  else
4217 	    s = Statement::make_assignment_operation(op, lhs->front(),
4218 						     vals->front(), location);
4219 	  delete lhs;
4220 	  delete vals;
4221 	}
4222       this->gogo_->add_statement(s);
4223     }
4224   else if (vals->size() == 1
4225 	   && (call = (*vals->begin())->call_expression()) != NULL)
4226     {
4227       if (op != OPERATOR_EQ)
4228 	go_error_at(location, "multiple results only permitted with %<=%>");
4229       call->set_expected_result_count(lhs->size());
4230       delete vals;
4231       vals = new Expression_list;
4232       for (unsigned int i = 0; i < lhs->size(); ++i)
4233 	vals->push_back(Expression::make_call_result(call, i));
4234       Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
4235       this->gogo_->add_statement(s);
4236     }
4237   else if (lhs->size() == 2
4238 	   && vals->size() == 1
4239 	   && (map_index = (*vals->begin())->index_expression()) != NULL)
4240     {
4241       if (op != OPERATOR_EQ)
4242 	go_error_at(location, "two values from map requires %<=%>");
4243       Expression* val = lhs->front();
4244       Expression* present = lhs->back();
4245       Statement* s = Statement::make_tuple_map_assignment(val, present,
4246 							  map_index, location);
4247       this->gogo_->add_statement(s);
4248     }
4249   else if (lhs->size() == 2
4250 	   && vals->size() == 1
4251 	   && (receive = (*vals->begin())->receive_expression()) != NULL)
4252     {
4253       if (op != OPERATOR_EQ)
4254 	go_error_at(location, "two values from receive requires %<=%>");
4255       Expression* val = lhs->front();
4256       Expression* success = lhs->back();
4257       Expression* channel = receive->channel();
4258       Statement* s = Statement::make_tuple_receive_assignment(val, success,
4259 							      channel,
4260 							      location);
4261       this->gogo_->add_statement(s);
4262     }
4263   else if (lhs->size() == 2
4264 	   && vals->size() == 1
4265 	   && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
4266     {
4267       if (op != OPERATOR_EQ)
4268 	go_error_at(location, "two values from type guard requires %<=%>");
4269       Expression* val = lhs->front();
4270       Expression* ok = lhs->back();
4271       Expression* expr = type_guard->expr();
4272       Type* type = type_guard->type();
4273       Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
4274 								 expr, type,
4275 								 location);
4276       this->gogo_->add_statement(s);
4277     }
4278   else
4279     {
4280       go_error_at(location, ("number of variables does not "
4281                              "match number of values"));
4282     }
4283 }
4284 
4285 // GoStat = "go" Expression .
4286 // DeferStat = "defer" Expression .
4287 
4288 void
go_or_defer_stat()4289 Parse::go_or_defer_stat()
4290 {
4291   go_assert(this->peek_token()->is_keyword(KEYWORD_GO)
4292 	     || this->peek_token()->is_keyword(KEYWORD_DEFER));
4293   bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
4294   Location stat_location = this->location();
4295 
4296   this->advance_token();
4297   Location expr_location = this->location();
4298 
4299   bool is_parenthesized = false;
4300   Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
4301 				      &is_parenthesized);
4302   Call_expression* call_expr = expr->call_expression();
4303   if (is_parenthesized || call_expr == NULL)
4304     {
4305       go_error_at(expr_location, "argument to go/defer must be function call");
4306       return;
4307     }
4308 
4309   // Make it easier to simplify go/defer statements by putting every
4310   // statement in its own block.
4311   this->gogo_->start_block(stat_location);
4312   Statement* stat;
4313   if (is_go)
4314     {
4315       stat = Statement::make_go_statement(call_expr, stat_location);
4316       call_expr->set_is_concurrent();
4317     }
4318   else
4319     {
4320       stat = Statement::make_defer_statement(call_expr, stat_location);
4321       call_expr->set_is_deferred();
4322     }
4323   this->gogo_->add_statement(stat);
4324   this->gogo_->add_block(this->gogo_->finish_block(stat_location),
4325 			 stat_location);
4326 }
4327 
4328 // ReturnStat = "return" [ ExpressionList ] .
4329 
4330 void
return_stat()4331 Parse::return_stat()
4332 {
4333   go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
4334   Location location = this->location();
4335   this->advance_token();
4336   Expression_list* vals = NULL;
4337   if (this->expression_may_start_here())
4338     vals = this->expression_list(NULL, false, true);
4339   this->gogo_->add_statement(Statement::make_return_statement(vals, location));
4340 
4341   if (vals == NULL
4342       && this->gogo_->current_function()->func_value()->results_are_named())
4343     {
4344       Named_object* function = this->gogo_->current_function();
4345       Function::Results* results = function->func_value()->result_variables();
4346       for (Function::Results::const_iterator p = results->begin();
4347 	   p != results->end();
4348 	   ++p)
4349 	{
4350 	  Named_object* no = this->gogo_->lookup((*p)->name(), NULL);
4351 	  if (no == NULL)
4352 	    go_assert(saw_errors());
4353 	  else if (!no->is_result_variable())
4354 	    go_error_at(location, "%qs is shadowed during return",
4355 			(*p)->message_name().c_str());
4356 	}
4357     }
4358 }
4359 
4360 // IfStmt = "if" [ SimpleStmt ";" ] Expression Block
4361 //          [ "else" ( IfStmt | Block ) ] .
4362 
4363 void
if_stat()4364 Parse::if_stat()
4365 {
4366   go_assert(this->peek_token()->is_keyword(KEYWORD_IF));
4367   Location location = this->location();
4368   this->advance_token();
4369 
4370   this->gogo_->start_block(location);
4371 
4372   bool saw_simple_stat = false;
4373   Expression* cond = NULL;
4374   bool saw_send_stmt = false;
4375   if (this->simple_stat_may_start_here())
4376     {
4377       cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL);
4378       saw_simple_stat = true;
4379     }
4380   if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4381     {
4382       // The SimpleStat is an expression statement.
4383       this->expression_stat(cond);
4384       cond = NULL;
4385     }
4386   if (cond == NULL)
4387     {
4388       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4389 	this->advance_token();
4390       else if (saw_simple_stat)
4391 	{
4392 	  if (saw_send_stmt)
4393 	    go_error_at(this->location(),
4394 			("send statement used as value; "
4395 			 "use select for non-blocking send"));
4396 	  else
4397 	    go_error_at(this->location(),
4398 			"expected %<;%> after statement in if expression");
4399 	  if (!this->expression_may_start_here())
4400 	    cond = Expression::make_error(this->location());
4401 	}
4402       if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY))
4403 	{
4404 	  go_error_at(this->location(),
4405 		      "missing condition in if statement");
4406 	  cond = Expression::make_error(this->location());
4407 	}
4408       if (cond == NULL)
4409 	cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL, NULL);
4410     }
4411 
4412   // Check for the easy error of a newline before starting the block.
4413   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4414     {
4415       Location semi_loc = this->location();
4416       if (this->advance_token()->is_op(OPERATOR_LCURLY))
4417 	go_error_at(semi_loc, "missing %<{%> after if clause");
4418       // Otherwise we will get an error when we call this->block
4419       // below.
4420     }
4421 
4422   this->gogo_->start_block(this->location());
4423   Location end_loc = this->block();
4424   Block* then_block = this->gogo_->finish_block(end_loc);
4425 
4426   // Check for the easy error of a newline before "else".
4427   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4428     {
4429       Location semi_loc = this->location();
4430       if (this->advance_token()->is_keyword(KEYWORD_ELSE))
4431 	go_error_at(this->location(),
4432 		 "unexpected semicolon or newline before %<else%>");
4433       else
4434 	this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4435 						     semi_loc));
4436     }
4437 
4438   Block* else_block = NULL;
4439   if (this->peek_token()->is_keyword(KEYWORD_ELSE))
4440     {
4441       this->gogo_->start_block(this->location());
4442       const Token* token = this->advance_token();
4443       if (token->is_keyword(KEYWORD_IF))
4444 	this->if_stat();
4445       else if (token->is_op(OPERATOR_LCURLY))
4446 	this->block();
4447       else
4448 	{
4449 	  go_error_at(this->location(), "expected %<if%> or %<{%>");
4450 	  this->statement(NULL);
4451 	}
4452       else_block = this->gogo_->finish_block(this->location());
4453     }
4454 
4455   this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
4456 							  else_block,
4457 							  location));
4458 
4459   this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4460 			 location);
4461 }
4462 
4463 // SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4464 // ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
4465 //			"{" { ExprCaseClause } "}" .
4466 // TypeSwitchStmt  = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
4467 //			"{" { TypeCaseClause } "}" .
4468 // TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
4469 
4470 void
switch_stat(Label * label)4471 Parse::switch_stat(Label* label)
4472 {
4473   go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
4474   Location location = this->location();
4475   this->advance_token();
4476 
4477   this->gogo_->start_block(location);
4478 
4479   bool saw_simple_stat = false;
4480   Expression* switch_val = NULL;
4481   bool saw_send_stmt;
4482   Type_switch type_switch;
4483   bool have_type_switch_block = false;
4484   if (this->simple_stat_may_start_here())
4485     {
4486       switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4487 				     &type_switch);
4488       saw_simple_stat = true;
4489     }
4490   if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4491     {
4492       // The SimpleStat is an expression statement.
4493       this->expression_stat(switch_val);
4494       switch_val = NULL;
4495     }
4496   if (switch_val == NULL && !type_switch.found)
4497     {
4498       if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4499 	this->advance_token();
4500       else if (saw_simple_stat)
4501 	{
4502 	  if (saw_send_stmt)
4503 	    go_error_at(this->location(),
4504 			("send statement used as value; "
4505 			 "use select for non-blocking send"));
4506 	  else
4507 	    go_error_at(this->location(),
4508 			"expected %<;%> after statement in switch expression");
4509 	}
4510       if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4511 	{
4512 	  if (this->peek_token()->is_identifier())
4513 	    {
4514 	      const Token* token = this->peek_token();
4515 	      std::string identifier = token->identifier();
4516 	      bool is_exported = token->is_identifier_exported();
4517 	      Location id_loc = token->location();
4518 
4519 	      token = this->advance_token();
4520 	      bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
4521 	      this->unget_token(Token::make_identifier_token(identifier,
4522 							     is_exported,
4523 							     id_loc));
4524 	      if (is_coloneq)
4525 		{
4526 		  // This must be a TypeSwitchGuard.  It is in a
4527 		  // different block from any initial SimpleStat.
4528 		  if (saw_simple_stat)
4529 		    {
4530 		      this->gogo_->start_block(id_loc);
4531 		      have_type_switch_block = true;
4532 		    }
4533 
4534 		  switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4535 						 &type_switch);
4536 		  if (!type_switch.found)
4537 		    {
4538 		      if (switch_val == NULL
4539 			  || !switch_val->is_error_expression())
4540 			{
4541 			  go_error_at(id_loc,
4542 				      "expected type switch assignment");
4543 			  switch_val = Expression::make_error(id_loc);
4544 			}
4545 		    }
4546 		}
4547 	    }
4548 	  if (switch_val == NULL && !type_switch.found)
4549 	    {
4550 	      switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
4551 					    &type_switch.found, NULL);
4552 	      if (type_switch.found)
4553 		{
4554 		  type_switch.name.clear();
4555 		  type_switch.expr = switch_val;
4556 		  type_switch.location = switch_val->location();
4557 		}
4558 	    }
4559 	}
4560     }
4561 
4562   if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4563     {
4564       Location token_loc = this->location();
4565       if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
4566 	  && this->advance_token()->is_op(OPERATOR_LCURLY))
4567 	go_error_at(token_loc, "missing %<{%> after switch clause");
4568       else if (this->peek_token()->is_op(OPERATOR_COLONEQ))
4569 	{
4570 	  go_error_at(token_loc, "invalid variable name");
4571 	  this->advance_token();
4572 	  this->expression(PRECEDENCE_NORMAL, false, false,
4573 			   &type_switch.found, NULL);
4574 	  if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4575 	    this->advance_token();
4576 	  if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4577 	    {
4578 	      if (have_type_switch_block)
4579 		this->gogo_->add_block(this->gogo_->finish_block(location),
4580 				       location);
4581 	      this->gogo_->add_block(this->gogo_->finish_block(location),
4582 				     location);
4583 	      return;
4584 	    }
4585 	  if (type_switch.found)
4586 	    type_switch.expr = Expression::make_error(location);
4587 	}
4588       else
4589 	{
4590 	  go_error_at(this->location(), "expected %<{%>");
4591 	  if (have_type_switch_block)
4592 	    this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4593 				   location);
4594 	  this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4595 				 location);
4596 	  return;
4597 	}
4598     }
4599   this->advance_token();
4600 
4601   Statement* statement;
4602   if (type_switch.found)
4603     statement = this->type_switch_body(label, type_switch, location);
4604   else
4605     statement = this->expr_switch_body(label, switch_val, location);
4606 
4607   if (statement != NULL)
4608     this->gogo_->add_statement(statement);
4609 
4610   if (have_type_switch_block)
4611     this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4612 			   location);
4613 
4614   this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4615 			 location);
4616 }
4617 
4618 // The body of an expression switch.
4619 //   "{" { ExprCaseClause } "}"
4620 
4621 Statement*
expr_switch_body(Label * label,Expression * switch_val,Location location)4622 Parse::expr_switch_body(Label* label, Expression* switch_val,
4623 			Location location)
4624 {
4625   Switch_statement* statement = Statement::make_switch_statement(switch_val,
4626 								 location);
4627 
4628   this->push_break_statement(statement, label);
4629 
4630   Case_clauses* case_clauses = new Case_clauses();
4631   bool saw_default = false;
4632   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4633     {
4634       if (this->peek_token()->is_eof())
4635 	{
4636 	  if (!saw_errors())
4637 	    go_error_at(this->location(), "missing %<}%>");
4638 	  return NULL;
4639 	}
4640       this->expr_case_clause(case_clauses, &saw_default);
4641     }
4642   this->advance_token();
4643 
4644   statement->add_clauses(case_clauses);
4645 
4646   this->pop_break_statement();
4647 
4648   return statement;
4649 }
4650 
4651 // ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
4652 // FallthroughStat = "fallthrough" .
4653 
4654 void
expr_case_clause(Case_clauses * clauses,bool * saw_default)4655 Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
4656 {
4657   Location location = this->location();
4658 
4659   bool is_default = false;
4660   Expression_list* vals = this->expr_switch_case(&is_default);
4661 
4662   if (!this->peek_token()->is_op(OPERATOR_COLON))
4663     {
4664       if (!saw_errors())
4665 	go_error_at(this->location(), "expected %<:%>");
4666       return;
4667     }
4668   else
4669     this->advance_token();
4670 
4671   Block* statements = NULL;
4672   if (this->statement_list_may_start_here())
4673     {
4674       this->gogo_->start_block(this->location());
4675       this->statement_list();
4676       statements = this->gogo_->finish_block(this->location());
4677     }
4678 
4679   bool is_fallthrough = false;
4680   if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4681     {
4682       Location fallthrough_loc = this->location();
4683       is_fallthrough = true;
4684       while (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4685 	;
4686       if (this->peek_token()->is_op(OPERATOR_RCURLY))
4687 	go_error_at(fallthrough_loc,
4688 		    _("cannot fallthrough final case in switch"));
4689       else if (!this->peek_token()->is_keyword(KEYWORD_CASE)
4690 	       && !this->peek_token()->is_keyword(KEYWORD_DEFAULT))
4691 	{
4692 	  go_error_at(fallthrough_loc, "fallthrough statement out of place");
4693 	  while (!this->peek_token()->is_keyword(KEYWORD_CASE)
4694 		 && !this->peek_token()->is_keyword(KEYWORD_DEFAULT)
4695 		 && !this->peek_token()->is_op(OPERATOR_RCURLY)
4696 		 && !this->peek_token()->is_eof())
4697 	    {
4698 	      if (this->statement_may_start_here())
4699 		this->statement_list();
4700 	      else
4701 		this->advance_token();
4702 	    }
4703 	}
4704     }
4705 
4706   if (is_default)
4707     {
4708       if (*saw_default)
4709 	{
4710 	  go_error_at(location, "multiple defaults in switch");
4711 	  return;
4712 	}
4713       *saw_default = true;
4714     }
4715 
4716   if (is_default || vals != NULL)
4717     clauses->add(vals, is_default, statements, is_fallthrough, location);
4718 }
4719 
4720 // ExprSwitchCase = "case" ExpressionList | "default" .
4721 
4722 Expression_list*
expr_switch_case(bool * is_default)4723 Parse::expr_switch_case(bool* is_default)
4724 {
4725   const Token* token = this->peek_token();
4726   if (token->is_keyword(KEYWORD_CASE))
4727     {
4728       this->advance_token();
4729       return this->expression_list(NULL, false, true);
4730     }
4731   else if (token->is_keyword(KEYWORD_DEFAULT))
4732     {
4733       this->advance_token();
4734       *is_default = true;
4735       return NULL;
4736     }
4737   else
4738     {
4739       if (!saw_errors())
4740 	go_error_at(this->location(), "expected %<case%> or %<default%>");
4741       if (!token->is_op(OPERATOR_RCURLY))
4742 	this->advance_token();
4743       return NULL;
4744     }
4745 }
4746 
4747 // The body of a type switch.
4748 //   "{" { TypeCaseClause } "}" .
4749 
4750 Statement*
type_switch_body(Label * label,const Type_switch & type_switch,Location location)4751 Parse::type_switch_body(Label* label, const Type_switch& type_switch,
4752 			Location location)
4753 {
4754   Expression* init = type_switch.expr;
4755   std::string var_name = type_switch.name;
4756   if (!var_name.empty())
4757     {
4758       if (Gogo::is_sink_name(var_name))
4759         {
4760 	  go_error_at(type_switch.location,
4761 		      "no new variables on left side of %<:=%>");
4762           var_name.clear();
4763         }
4764       else
4765 	{
4766           Location loc = type_switch.location;
4767 	  Temporary_statement* switch_temp =
4768               Statement::make_temporary(NULL, init, loc);
4769 	  this->gogo_->add_statement(switch_temp);
4770           init = Expression::make_temporary_reference(switch_temp, loc);
4771 	}
4772     }
4773 
4774   Type_switch_statement* statement =
4775       Statement::make_type_switch_statement(var_name, init, location);
4776   this->push_break_statement(statement, label);
4777 
4778   Type_case_clauses* case_clauses = new Type_case_clauses();
4779   bool saw_default = false;
4780   std::vector<Named_object*> implicit_vars;
4781   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4782     {
4783       if (this->peek_token()->is_eof())
4784 	{
4785 	  go_error_at(this->location(), "missing %<}%>");
4786 	  return NULL;
4787 	}
4788       this->type_case_clause(var_name, init, case_clauses, &saw_default,
4789                              &implicit_vars);
4790     }
4791   this->advance_token();
4792 
4793   statement->add_clauses(case_clauses);
4794 
4795   this->pop_break_statement();
4796 
4797   // If there is a type switch variable implicitly declared in each case clause,
4798   // check that it is used in at least one of the cases.
4799   if (!var_name.empty())
4800     {
4801       bool used = false;
4802       for (std::vector<Named_object*>::iterator p = implicit_vars.begin();
4803 	   p != implicit_vars.end();
4804 	   ++p)
4805 	{
4806 	  if ((*p)->var_value()->is_used())
4807 	    {
4808 	      used = true;
4809 	      break;
4810 	    }
4811 	}
4812       if (!used)
4813 	go_error_at(type_switch.location, "%qs declared and not used",
4814 		    Gogo::message_name(var_name).c_str());
4815     }
4816   return statement;
4817 }
4818 
4819 // TypeCaseClause  = TypeSwitchCase ":" [ StatementList ] .
4820 // IMPLICIT_VARS is the list of variables implicitly declared for each type
4821 // case if there is a type switch variable declared.
4822 
4823 void
type_case_clause(const std::string & var_name,Expression * init,Type_case_clauses * clauses,bool * saw_default,std::vector<Named_object * > * implicit_vars)4824 Parse::type_case_clause(const std::string& var_name, Expression* init,
4825                         Type_case_clauses* clauses, bool* saw_default,
4826 			std::vector<Named_object*>* implicit_vars)
4827 {
4828   Location location = this->location();
4829 
4830   std::vector<Type*> types;
4831   bool is_default = false;
4832   this->type_switch_case(&types, &is_default);
4833 
4834   if (!this->peek_token()->is_op(OPERATOR_COLON))
4835     go_error_at(this->location(), "expected %<:%>");
4836   else
4837     this->advance_token();
4838 
4839   Block* statements = NULL;
4840   if (this->statement_list_may_start_here())
4841     {
4842       this->gogo_->start_block(this->location());
4843       if (!var_name.empty())
4844 	{
4845 	  Type* type = NULL;
4846           Location var_loc = init->location();
4847 	  if (types.size() == 1)
4848 	    {
4849 	      type = types.front();
4850 	      init = Expression::make_type_guard(init, type, location);
4851 	    }
4852 
4853 	  Variable* v = new Variable(type, init, false, false, false,
4854 				     var_loc);
4855 	  v->set_is_used();
4856 	  v->set_is_type_switch_var();
4857 	  implicit_vars->push_back(this->gogo_->add_variable(var_name, v));
4858 	}
4859       this->statement_list();
4860       statements = this->gogo_->finish_block(this->location());
4861     }
4862 
4863   if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4864     {
4865       go_error_at(this->location(),
4866 		  "fallthrough is not permitted in a type switch");
4867       if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4868 	this->advance_token();
4869     }
4870 
4871   if (is_default)
4872     {
4873       go_assert(types.empty());
4874       if (*saw_default)
4875 	{
4876 	  go_error_at(location, "multiple defaults in type switch");
4877 	  return;
4878 	}
4879       *saw_default = true;
4880       clauses->add(NULL, false, true, statements, location);
4881     }
4882   else if (!types.empty())
4883     {
4884       for (std::vector<Type*>::const_iterator p = types.begin();
4885 	   p + 1 != types.end();
4886 	   ++p)
4887 	clauses->add(*p, true, false, NULL, location);
4888       clauses->add(types.back(), false, false, statements, location);
4889     }
4890   else
4891     clauses->add(Type::make_error_type(), false, false, statements, location);
4892 }
4893 
4894 // TypeSwitchCase  = "case" type | "default"
4895 
4896 // We accept a comma separated list of types.
4897 
4898 void
type_switch_case(std::vector<Type * > * types,bool * is_default)4899 Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
4900 {
4901   const Token* token = this->peek_token();
4902   if (token->is_keyword(KEYWORD_CASE))
4903     {
4904       this->advance_token();
4905       while (true)
4906 	{
4907 	  Type* t = this->type();
4908 
4909 	  if (!t->is_error_type())
4910 	    types->push_back(t);
4911 	  else
4912 	    {
4913 	      this->gogo_->mark_locals_used();
4914 	      token = this->peek_token();
4915 	      while (!token->is_op(OPERATOR_COLON)
4916 		     && !token->is_op(OPERATOR_COMMA)
4917 		     && !token->is_op(OPERATOR_RCURLY)
4918 		     && !token->is_eof())
4919 		token = this->advance_token();
4920 	    }
4921 
4922 	  if (!this->peek_token()->is_op(OPERATOR_COMMA))
4923 	    break;
4924 	  this->advance_token();
4925 	}
4926     }
4927   else if (token->is_keyword(KEYWORD_DEFAULT))
4928     {
4929       this->advance_token();
4930       *is_default = true;
4931     }
4932   else
4933     {
4934       go_error_at(this->location(), "expected %<case%> or %<default%>");
4935       if (!token->is_op(OPERATOR_RCURLY))
4936 	this->advance_token();
4937     }
4938 }
4939 
4940 // SelectStat = "select" "{" { CommClause } "}" .
4941 
4942 void
select_stat(Label * label)4943 Parse::select_stat(Label* label)
4944 {
4945   go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
4946   Location location = this->location();
4947   const Token* token = this->advance_token();
4948 
4949   if (!token->is_op(OPERATOR_LCURLY))
4950     {
4951       Location token_loc = token->location();
4952       if (token->is_op(OPERATOR_SEMICOLON)
4953 	  && this->advance_token()->is_op(OPERATOR_LCURLY))
4954 	go_error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4955       else
4956 	{
4957 	  go_error_at(this->location(), "expected %<{%>");
4958 	  return;
4959 	}
4960     }
4961   this->advance_token();
4962 
4963   Select_statement* statement = Statement::make_select_statement(location);
4964 
4965   this->push_break_statement(statement, label);
4966 
4967   Select_clauses* select_clauses = new Select_clauses();
4968   bool saw_default = false;
4969   while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4970     {
4971       if (this->peek_token()->is_eof())
4972 	{
4973 	  go_error_at(this->location(), "expected %<}%>");
4974 	  return;
4975 	}
4976       this->comm_clause(select_clauses, &saw_default);
4977     }
4978 
4979   this->advance_token();
4980 
4981   statement->add_clauses(select_clauses);
4982 
4983   this->pop_break_statement();
4984 
4985   this->gogo_->add_statement(statement);
4986 }
4987 
4988 // CommClause = CommCase ":" { Statement ";" } .
4989 
4990 void
comm_clause(Select_clauses * clauses,bool * saw_default)4991 Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
4992 {
4993   Location location = this->location();
4994   bool is_send = false;
4995   Expression* channel = NULL;
4996   Expression* val = NULL;
4997   Expression* closed = NULL;
4998   std::string varname;
4999   std::string closedname;
5000   bool is_default = false;
5001   bool got_case = this->comm_case(&is_send, &channel, &val, &closed,
5002 				  &varname, &closedname, &is_default);
5003 
5004   if (this->peek_token()->is_op(OPERATOR_COLON))
5005     this->advance_token();
5006   else
5007     go_error_at(this->location(), "expected colon");
5008 
5009   this->gogo_->start_block(this->location());
5010 
5011   Named_object* var = NULL;
5012   if (!varname.empty())
5013     {
5014       // FIXME: LOCATION is slightly wrong here.
5015       Variable* v = new Variable(NULL, channel, false, false, false,
5016 				 location);
5017       v->set_type_from_chan_element();
5018       var = this->gogo_->add_variable(varname, v);
5019     }
5020 
5021   Named_object* closedvar = NULL;
5022   if (!closedname.empty())
5023     {
5024       // FIXME: LOCATION is slightly wrong here.
5025       Variable* v = new Variable(Type::lookup_bool_type(), NULL,
5026 				 false, false, false, location);
5027       closedvar = this->gogo_->add_variable(closedname, v);
5028     }
5029 
5030   this->statement_list();
5031 
5032   Block* statements = this->gogo_->finish_block(this->location());
5033 
5034   if (is_default)
5035     {
5036       if (*saw_default)
5037 	{
5038 	  go_error_at(location, "multiple defaults in select");
5039 	  return;
5040 	}
5041       *saw_default = true;
5042     }
5043 
5044   if (got_case)
5045     clauses->add(is_send, channel, val, closed, var, closedvar, is_default,
5046 		 statements, location);
5047   else if (statements != NULL)
5048     {
5049       // Add the statements to make sure that any names they define
5050       // are traversed.
5051       this->gogo_->add_block(statements, location);
5052     }
5053 }
5054 
5055 // CommCase   = "case" ( SendStmt | RecvStmt ) | "default" .
5056 
5057 bool
comm_case(bool * is_send,Expression ** channel,Expression ** val,Expression ** closed,std::string * varname,std::string * closedname,bool * is_default)5058 Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
5059 		 Expression** closed, std::string* varname,
5060 		 std::string* closedname, bool* is_default)
5061 {
5062   const Token* token = this->peek_token();
5063   if (token->is_keyword(KEYWORD_DEFAULT))
5064     {
5065       this->advance_token();
5066       *is_default = true;
5067     }
5068   else if (token->is_keyword(KEYWORD_CASE))
5069     {
5070       this->advance_token();
5071       if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname,
5072 				   closedname))
5073 	return false;
5074     }
5075   else
5076     {
5077       go_error_at(this->location(), "expected %<case%> or %<default%>");
5078       if (!token->is_op(OPERATOR_RCURLY))
5079 	this->advance_token();
5080       return false;
5081     }
5082 
5083   return true;
5084 }
5085 
5086 // RecvStmt   = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
5087 // RecvExpr   = Expression .
5088 
5089 bool
send_or_recv_stmt(bool * is_send,Expression ** channel,Expression ** val,Expression ** closed,std::string * varname,std::string * closedname)5090 Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val,
5091 			 Expression** closed, std::string* varname,
5092 			 std::string* closedname)
5093 {
5094   const Token* token = this->peek_token();
5095   bool saw_comma = false;
5096   bool closed_is_id = false;
5097   if (token->is_identifier())
5098     {
5099       Gogo* gogo = this->gogo_;
5100       std::string recv_var = token->identifier();
5101       bool is_rv_exported = token->is_identifier_exported();
5102       Location recv_var_loc = token->location();
5103       token = this->advance_token();
5104       if (token->is_op(OPERATOR_COLONEQ))
5105 	{
5106 	  // case rv := <-c:
5107 	  this->advance_token();
5108 	  Expression* e = this->expression(PRECEDENCE_NORMAL, false, false,
5109 					   NULL, NULL);
5110 	  Receive_expression* re = e->receive_expression();
5111 	  if (re == NULL)
5112 	    {
5113 	      if (!e->is_error_expression())
5114 		go_error_at(this->location(), "expected receive expression");
5115 	      return false;
5116 	    }
5117 	  if (recv_var == "_")
5118 	    {
5119 	      go_error_at(recv_var_loc,
5120 			  "no new variables on left side of %<:=%>");
5121 	      recv_var = Gogo::erroneous_name();
5122 	    }
5123 	  *is_send = false;
5124 	  *varname = gogo->pack_hidden_name(recv_var, is_rv_exported);
5125 	  *channel = re->channel();
5126 	  return true;
5127 	}
5128       else if (token->is_op(OPERATOR_COMMA))
5129 	{
5130 	  token = this->advance_token();
5131 	  if (token->is_identifier())
5132 	    {
5133 	      std::string recv_closed = token->identifier();
5134 	      bool is_rc_exported = token->is_identifier_exported();
5135 	      Location recv_closed_loc = token->location();
5136 	      closed_is_id = true;
5137 
5138 	      token = this->advance_token();
5139 	      if (token->is_op(OPERATOR_COLONEQ))
5140 		{
5141 		  // case rv, rc := <-c:
5142 		  this->advance_token();
5143 		  Expression* e = this->expression(PRECEDENCE_NORMAL, false,
5144 						   false, NULL, NULL);
5145 		  Receive_expression* re = e->receive_expression();
5146 		  if (re == NULL)
5147 		    {
5148 		      if (!e->is_error_expression())
5149 			go_error_at(this->location(),
5150 				 "expected receive expression");
5151 		      return false;
5152 		    }
5153 		  if (recv_var == "_" && recv_closed == "_")
5154 		    {
5155 		      go_error_at(recv_var_loc,
5156 				  "no new variables on left side of %<:=%>");
5157 		      recv_var = Gogo::erroneous_name();
5158 		    }
5159 		  *is_send = false;
5160 		  if (recv_var != "_")
5161 		    *varname = gogo->pack_hidden_name(recv_var,
5162 						      is_rv_exported);
5163 		  if (recv_closed != "_")
5164 		    *closedname = gogo->pack_hidden_name(recv_closed,
5165 							 is_rc_exported);
5166 		  *channel = re->channel();
5167 		  return true;
5168 		}
5169 
5170 	      this->unget_token(Token::make_identifier_token(recv_closed,
5171 							     is_rc_exported,
5172 							     recv_closed_loc));
5173 	    }
5174 
5175 	  *val = this->id_to_expression(gogo->pack_hidden_name(recv_var,
5176 							       is_rv_exported),
5177 					recv_var_loc, true, false);
5178 	  saw_comma = true;
5179 	}
5180       else
5181 	this->unget_token(Token::make_identifier_token(recv_var,
5182 						       is_rv_exported,
5183 						       recv_var_loc));
5184     }
5185 
5186   // If SAW_COMMA is false, then we are looking at the start of the
5187   // send or receive expression.  If SAW_COMMA is true, then *VAL is
5188   // set and we just read a comma.
5189 
5190   Expression* e;
5191   if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP))
5192     {
5193       e = this->expression(PRECEDENCE_NORMAL, true, true, NULL, NULL);
5194       if (e->receive_expression() != NULL)
5195 	{
5196 	  *is_send = false;
5197 	  *channel = e->receive_expression()->channel();
5198 	  // This is 'case (<-c):'.  We now expect ':'.  If we see
5199 	  // '<-', then we have case (<-c)<-v:
5200 	  if (!this->peek_token()->is_op(OPERATOR_CHANOP))
5201 	    return true;
5202 	}
5203     }
5204   else
5205     {
5206       // case <-c:
5207       *is_send = false;
5208       this->advance_token();
5209       *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5210 
5211       // The next token should be ':'.  If it is '<-', then we have
5212       // case <-c <- v:
5213       // which is to say, send on a channel received from a channel.
5214       if (!this->peek_token()->is_op(OPERATOR_CHANOP))
5215 	return true;
5216 
5217       e = Expression::make_receive(*channel, (*channel)->location());
5218     }
5219 
5220   if (!saw_comma && this->peek_token()->is_op(OPERATOR_COMMA))
5221     {
5222       this->advance_token();
5223       // case v, e = <-c:
5224       if (!e->is_sink_expression())
5225 	*val = e;
5226       e = this->expression(PRECEDENCE_NORMAL, true, true, NULL, NULL);
5227       saw_comma = true;
5228     }
5229 
5230   if (this->peek_token()->is_op(OPERATOR_EQ))
5231     {
5232       *is_send = false;
5233       this->advance_token();
5234       Location recvloc = this->location();
5235       Expression* recvexpr = this->expression(PRECEDENCE_NORMAL, false,
5236 					      true, NULL, NULL);
5237       if (recvexpr->receive_expression() == NULL)
5238 	{
5239 	  go_error_at(recvloc, "missing %<<-%>");
5240 	  return false;
5241 	}
5242       *channel = recvexpr->receive_expression()->channel();
5243       if (saw_comma)
5244 	{
5245 	  // case v, e = <-c:
5246 	  // *VAL is already set.
5247 	  if (!e->is_sink_expression())
5248 	    *closed = e;
5249 	}
5250       else
5251 	{
5252 	  // case v = <-c:
5253 	  if (!e->is_sink_expression())
5254 	    *val = e;
5255 	}
5256       return true;
5257     }
5258 
5259   if (saw_comma)
5260     {
5261       if (closed_is_id)
5262 	go_error_at(this->location(), "expected %<=%> or %<:=%>");
5263       else
5264 	go_error_at(this->location(), "expected %<=%>");
5265       return false;
5266     }
5267 
5268   if (this->peek_token()->is_op(OPERATOR_CHANOP))
5269     {
5270       // case c <- v:
5271       *is_send = true;
5272       *channel = this->verify_not_sink(e);
5273       this->advance_token();
5274       *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5275       return true;
5276     }
5277 
5278   go_error_at(this->location(), "expected %<<-%> or %<=%>");
5279   return false;
5280 }
5281 
5282 // ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
5283 // Condition = Expression .
5284 
5285 void
for_stat(Label * label)5286 Parse::for_stat(Label* label)
5287 {
5288   go_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
5289   Location location = this->location();
5290   const Token* token = this->advance_token();
5291 
5292   // Open a block to hold any variables defined in the init statement
5293   // of the for statement.
5294   this->gogo_->start_block(location);
5295 
5296   Block* init = NULL;
5297   Expression* cond = NULL;
5298   Block* post = NULL;
5299   Range_clause range_clause;
5300 
5301   if (!token->is_op(OPERATOR_LCURLY))
5302     {
5303       if (token->is_keyword(KEYWORD_VAR))
5304 	{
5305 	  go_error_at(this->location(),
5306                       "var declaration not allowed in for initializer");
5307 	  this->var_decl();
5308 	}
5309 
5310       if (token->is_op(OPERATOR_SEMICOLON))
5311 	this->for_clause(&cond, &post);
5312       else
5313 	{
5314 	  // We might be looking at a Condition, an InitStat, or a
5315 	  // RangeClause.
5316 	  bool saw_send_stmt;
5317 	  cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL);
5318 	  if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5319 	    {
5320 	      if (cond == NULL && !range_clause.found)
5321 		{
5322 		  if (saw_send_stmt)
5323 		    go_error_at(this->location(),
5324                                 ("send statement used as value; "
5325                                  "use select for non-blocking send"));
5326 		  else
5327 		    go_error_at(this->location(),
5328                                 "parse error in for statement");
5329 		}
5330 	    }
5331 	  else
5332 	    {
5333 	      if (range_clause.found)
5334 		go_error_at(this->location(), "parse error after range clause");
5335 
5336 	      if (cond != NULL)
5337 		{
5338 		  // COND is actually an expression statement for
5339 		  // InitStat at the start of a ForClause.
5340 		  this->expression_stat(cond);
5341 		  cond = NULL;
5342 		}
5343 
5344 	      this->for_clause(&cond, &post);
5345 	    }
5346 	}
5347     }
5348 
5349   // Check for the easy error of a newline before starting the block.
5350   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5351     {
5352       Location semi_loc = this->location();
5353       if (this->advance_token()->is_op(OPERATOR_LCURLY))
5354 	go_error_at(semi_loc, "missing %<{%> after for clause");
5355       // Otherwise we will get an error when we call this->block
5356       // below.
5357     }
5358 
5359   // Build the For_statement and note that it is the current target
5360   // for break and continue statements.
5361 
5362   For_statement* sfor;
5363   For_range_statement* srange;
5364   Statement* s;
5365   if (!range_clause.found)
5366     {
5367       sfor = Statement::make_for_statement(init, cond, post, location);
5368       s = sfor;
5369       srange = NULL;
5370     }
5371   else
5372     {
5373       srange = Statement::make_for_range_statement(range_clause.index,
5374 						   range_clause.value,
5375 						   range_clause.range,
5376 						   location);
5377       s = srange;
5378       sfor = NULL;
5379     }
5380 
5381   this->push_break_statement(s, label);
5382   this->push_continue_statement(s, label);
5383 
5384   // Gather the block of statements in the loop and add them to the
5385   // For_statement.
5386 
5387   this->gogo_->start_block(this->location());
5388   Location end_loc = this->block();
5389   Block* statements = this->gogo_->finish_block(end_loc);
5390 
5391   if (sfor != NULL)
5392     sfor->add_statements(statements);
5393   else
5394     srange->add_statements(statements);
5395 
5396   // This is no longer the break/continue target.
5397   this->pop_break_statement();
5398   this->pop_continue_statement();
5399 
5400   // Add the For_statement to the list of statements, and close out
5401   // the block we started to hold any variables defined in the for
5402   // statement.
5403 
5404   this->gogo_->add_statement(s);
5405 
5406   this->gogo_->add_block(this->gogo_->finish_block(this->location()),
5407 			 location);
5408 }
5409 
5410 // ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
5411 // InitStat = SimpleStat .
5412 // PostStat = SimpleStat .
5413 
5414 // We have already read InitStat at this point.
5415 
5416 void
for_clause(Expression ** cond,Block ** post)5417 Parse::for_clause(Expression** cond, Block** post)
5418 {
5419   go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
5420   this->advance_token();
5421   if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5422     *cond = NULL;
5423   else if (this->peek_token()->is_op(OPERATOR_LCURLY))
5424     {
5425       go_error_at(this->location(), "missing %<{%> after for clause");
5426       *cond = NULL;
5427       *post = NULL;
5428       return;
5429     }
5430   else
5431     *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5432   if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5433     go_error_at(this->location(), "expected semicolon");
5434   else
5435     this->advance_token();
5436 
5437   if (this->peek_token()->is_op(OPERATOR_LCURLY))
5438     *post = NULL;
5439   else
5440     {
5441       this->gogo_->start_block(this->location());
5442       this->simple_stat(false, NULL, NULL, NULL);
5443       *post = this->gogo_->finish_block(this->location());
5444     }
5445 }
5446 
5447 // RangeClause = [ IdentifierList ( "=" | ":=" ) ] "range" Expression .
5448 
5449 // This is the := version.  It is called with a list of identifiers.
5450 
5451 void
range_clause_decl(const Typed_identifier_list * til,Range_clause * p_range_clause)5452 Parse::range_clause_decl(const Typed_identifier_list* til,
5453 			 Range_clause* p_range_clause)
5454 {
5455   go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5456   Location location = this->location();
5457 
5458   p_range_clause->found = true;
5459 
5460   if (til->size() > 2)
5461     go_error_at(this->location(), "too many variables for range clause");
5462 
5463   this->advance_token();
5464   Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL,
5465 				      NULL);
5466   p_range_clause->range = expr;
5467 
5468   if (til->empty())
5469     return;
5470 
5471   bool any_new = false;
5472 
5473   const Typed_identifier* pti = &til->front();
5474   Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new,
5475 				    NULL, NULL);
5476   if (any_new && no->is_variable())
5477     no->var_value()->set_type_from_range_index();
5478   p_range_clause->index = Expression::make_var_reference(no, location);
5479 
5480   if (til->size() == 1)
5481     p_range_clause->value = NULL;
5482   else
5483     {
5484       pti = &til->back();
5485       bool is_new = false;
5486       no = this->init_var(*pti, NULL, expr, true, true, &is_new, NULL, NULL);
5487       if (is_new && no->is_variable())
5488 	no->var_value()->set_type_from_range_value();
5489       if (is_new)
5490 	any_new = true;
5491       p_range_clause->value = Expression::make_var_reference(no, location);
5492     }
5493 
5494   if (!any_new)
5495     go_error_at(location, "variables redeclared but no variable is new");
5496 }
5497 
5498 // The = version of RangeClause.  This is called with a list of
5499 // expressions.
5500 
5501 void
range_clause_expr(const Expression_list * vals,Range_clause * p_range_clause)5502 Parse::range_clause_expr(const Expression_list* vals,
5503 			 Range_clause* p_range_clause)
5504 {
5505   go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5506 
5507   p_range_clause->found = true;
5508 
5509   go_assert(vals->size() >= 1);
5510   if (vals->size() > 2)
5511     go_error_at(this->location(), "too many variables for range clause");
5512 
5513   this->advance_token();
5514   p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
5515 					   NULL, NULL);
5516 
5517   if (vals->empty())
5518     return;
5519 
5520   p_range_clause->index = vals->front();
5521   if (vals->size() == 1)
5522     p_range_clause->value = NULL;
5523   else
5524     p_range_clause->value = vals->back();
5525 }
5526 
5527 // Push a statement on the break stack.
5528 
5529 void
push_break_statement(Statement * enclosing,Label * label)5530 Parse::push_break_statement(Statement* enclosing, Label* label)
5531 {
5532   if (this->break_stack_ == NULL)
5533     this->break_stack_ = new Bc_stack();
5534   this->break_stack_->push_back(std::make_pair(enclosing, label));
5535 }
5536 
5537 // Push a statement on the continue stack.
5538 
5539 void
push_continue_statement(Statement * enclosing,Label * label)5540 Parse::push_continue_statement(Statement* enclosing, Label* label)
5541 {
5542   if (this->continue_stack_ == NULL)
5543     this->continue_stack_ = new Bc_stack();
5544   this->continue_stack_->push_back(std::make_pair(enclosing, label));
5545 }
5546 
5547 // Pop the break stack.
5548 
5549 void
pop_break_statement()5550 Parse::pop_break_statement()
5551 {
5552   this->break_stack_->pop_back();
5553 }
5554 
5555 // Pop the continue stack.
5556 
5557 void
pop_continue_statement()5558 Parse::pop_continue_statement()
5559 {
5560   this->continue_stack_->pop_back();
5561 }
5562 
5563 // Find a break or continue statement given a label name.
5564 
5565 Statement*
find_bc_statement(const Bc_stack * bc_stack,const std::string & label)5566 Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
5567 {
5568   if (bc_stack == NULL)
5569     return NULL;
5570   for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
5571        p != bc_stack->rend();
5572        ++p)
5573     {
5574       if (p->second != NULL && p->second->name() == label)
5575 	{
5576 	  p->second->set_is_used();
5577 	  return p->first;
5578 	}
5579     }
5580   return NULL;
5581 }
5582 
5583 // BreakStat = "break" [ identifier ] .
5584 
5585 void
break_stat()5586 Parse::break_stat()
5587 {
5588   go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
5589   Location location = this->location();
5590 
5591   const Token* token = this->advance_token();
5592   Statement* enclosing;
5593   if (!token->is_identifier())
5594     {
5595       if (this->break_stack_ == NULL || this->break_stack_->empty())
5596 	{
5597 	  go_error_at(this->location(),
5598                       "break statement not within for or switch or select");
5599 	  return;
5600 	}
5601       enclosing = this->break_stack_->back().first;
5602     }
5603   else
5604     {
5605       enclosing = this->find_bc_statement(this->break_stack_,
5606 					  token->identifier());
5607       if (enclosing == NULL)
5608 	{
5609 	  // If there is a label with this name, mark it as used to
5610 	  // avoid a useless error about an unused label.
5611 	  this->gogo_->add_label_reference(token->identifier(),
5612                                            Linemap::unknown_location(), false);
5613 
5614 	  go_error_at(token->location(), "invalid break label %qs",
5615                       Gogo::message_name(token->identifier()).c_str());
5616 	  this->advance_token();
5617 	  return;
5618 	}
5619       this->advance_token();
5620     }
5621 
5622   Unnamed_label* label;
5623   if (enclosing->classification() == Statement::STATEMENT_FOR)
5624     label = enclosing->for_statement()->break_label();
5625   else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5626     label = enclosing->for_range_statement()->break_label();
5627   else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
5628     label = enclosing->switch_statement()->break_label();
5629   else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
5630     label = enclosing->type_switch_statement()->break_label();
5631   else if (enclosing->classification() == Statement::STATEMENT_SELECT)
5632     label = enclosing->select_statement()->break_label();
5633   else
5634     go_unreachable();
5635 
5636   this->gogo_->add_statement(Statement::make_break_statement(label,
5637 							     location));
5638 }
5639 
5640 // ContinueStat = "continue" [ identifier ] .
5641 
5642 void
continue_stat()5643 Parse::continue_stat()
5644 {
5645   go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
5646   Location location = this->location();
5647 
5648   const Token* token = this->advance_token();
5649   Statement* enclosing;
5650   if (!token->is_identifier())
5651     {
5652       if (this->continue_stack_ == NULL || this->continue_stack_->empty())
5653 	{
5654 	  go_error_at(this->location(), "continue statement not within for");
5655 	  return;
5656 	}
5657       enclosing = this->continue_stack_->back().first;
5658     }
5659   else
5660     {
5661       enclosing = this->find_bc_statement(this->continue_stack_,
5662 					  token->identifier());
5663       if (enclosing == NULL)
5664 	{
5665 	  // If there is a label with this name, mark it as used to
5666 	  // avoid a useless error about an unused label.
5667 	  this->gogo_->add_label_reference(token->identifier(),
5668                                            Linemap::unknown_location(), false);
5669 
5670 	  go_error_at(token->location(), "invalid continue label %qs",
5671                       Gogo::message_name(token->identifier()).c_str());
5672 	  this->advance_token();
5673 	  return;
5674 	}
5675       this->advance_token();
5676     }
5677 
5678   Unnamed_label* label;
5679   if (enclosing->classification() == Statement::STATEMENT_FOR)
5680     label = enclosing->for_statement()->continue_label();
5681   else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5682     label = enclosing->for_range_statement()->continue_label();
5683   else
5684     go_unreachable();
5685 
5686   this->gogo_->add_statement(Statement::make_continue_statement(label,
5687 								location));
5688 }
5689 
5690 // GotoStat = "goto" identifier .
5691 
5692 void
goto_stat()5693 Parse::goto_stat()
5694 {
5695   go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
5696   Location location = this->location();
5697   const Token* token = this->advance_token();
5698   if (!token->is_identifier())
5699     go_error_at(this->location(), "expected label for goto");
5700   else
5701     {
5702       Label* label = this->gogo_->add_label_reference(token->identifier(),
5703 						      location, true);
5704       Statement* s = Statement::make_goto_statement(label, location);
5705       this->gogo_->add_statement(s);
5706       this->advance_token();
5707     }
5708 }
5709 
5710 // PackageClause = "package" PackageName .
5711 
5712 void
package_clause()5713 Parse::package_clause()
5714 {
5715   const Token* token = this->peek_token();
5716   Location location = token->location();
5717   std::string name;
5718   if (!token->is_keyword(KEYWORD_PACKAGE))
5719     {
5720       go_error_at(this->location(), "program must start with package clause");
5721       name = "ERROR";
5722     }
5723   else
5724     {
5725       token = this->advance_token();
5726       if (token->is_identifier())
5727 	{
5728 	  name = token->identifier();
5729 	  if (name == "_")
5730 	    {
5731 	      go_error_at(this->location(), "invalid package name %<_%>");
5732 	      name = Gogo::erroneous_name();
5733 	    }
5734 	  this->advance_token();
5735 	}
5736       else
5737 	{
5738 	  go_error_at(this->location(), "package name must be an identifier");
5739 	  name = "ERROR";
5740 	}
5741     }
5742   this->gogo_->set_package_name(name, location);
5743 }
5744 
5745 // ImportDecl = "import" Decl<ImportSpec> .
5746 
5747 void
import_decl()5748 Parse::import_decl()
5749 {
5750   go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
5751   this->advance_token();
5752   this->decl(&Parse::import_spec, NULL, 0);
5753 }
5754 
5755 // ImportSpec = [ "." | PackageName ] PackageFileName .
5756 
5757 void
import_spec(void *,unsigned int pragmas)5758 Parse::import_spec(void*, unsigned int pragmas)
5759 {
5760   if (pragmas != 0)
5761     go_warning_at(this->location(), 0,
5762 		  "ignoring magic %<//go:...%> comment before import");
5763 
5764   const Token* token = this->peek_token();
5765   Location location = token->location();
5766 
5767   std::string local_name;
5768   bool is_local_name_exported = false;
5769   if (token->is_op(OPERATOR_DOT))
5770     {
5771       local_name = ".";
5772       token = this->advance_token();
5773     }
5774   else if (token->is_identifier())
5775     {
5776       local_name = token->identifier();
5777       is_local_name_exported = token->is_identifier_exported();
5778       token = this->advance_token();
5779     }
5780 
5781   if (!token->is_string())
5782     {
5783       go_error_at(this->location(), "import statement not a string");
5784       this->advance_token();
5785       return;
5786     }
5787 
5788   this->gogo_->import_package(token->string_value(), local_name,
5789 			      is_local_name_exported, true, location);
5790 
5791   this->advance_token();
5792 }
5793 
5794 // SourceFile       = PackageClause ";" { ImportDecl ";" }
5795 //			{ TopLevelDecl ";" } .
5796 
5797 void
program()5798 Parse::program()
5799 {
5800   this->package_clause();
5801 
5802   const Token* token = this->peek_token();
5803   if (token->is_op(OPERATOR_SEMICOLON))
5804     token = this->advance_token();
5805   else
5806     go_error_at(this->location(),
5807                 "expected %<;%> or newline after package clause");
5808 
5809   while (token->is_keyword(KEYWORD_IMPORT))
5810     {
5811       this->import_decl();
5812       token = this->peek_token();
5813       if (token->is_op(OPERATOR_SEMICOLON))
5814 	token = this->advance_token();
5815       else
5816 	go_error_at(this->location(),
5817                     "expected %<;%> or newline after import declaration");
5818     }
5819 
5820   while (!token->is_eof())
5821     {
5822       if (this->declaration_may_start_here())
5823 	this->declaration();
5824       else
5825 	{
5826 	  go_error_at(this->location(), "expected declaration");
5827 	  this->gogo_->mark_locals_used();
5828 	  do
5829 	    this->advance_token();
5830 	  while (!this->peek_token()->is_eof()
5831 		 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
5832 		 && !this->peek_token()->is_op(OPERATOR_RCURLY));
5833 	  if (!this->peek_token()->is_eof()
5834 	      && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
5835 	    this->advance_token();
5836 	}
5837       token = this->peek_token();
5838       if (token->is_op(OPERATOR_SEMICOLON))
5839 	token = this->advance_token();
5840       else if (!token->is_eof() || !saw_errors())
5841 	{
5842 	  if (token->is_op(OPERATOR_CHANOP))
5843 	    go_error_at(this->location(),
5844                         ("send statement used as value; "
5845                          "use select for non-blocking send"));
5846 	  else
5847 	    go_error_at(this->location(),
5848                         ("expected %<;%> or newline after top "
5849                          "level declaration"));
5850 	  this->skip_past_error(OPERATOR_INVALID);
5851 	}
5852     }
5853 }
5854 
5855 // Skip forward to a semicolon or OP.  OP will normally be
5856 // OPERATOR_RPAREN or OPERATOR_RCURLY.  If we find a semicolon, move
5857 // past it and return.  If we find OP, it will be the next token to
5858 // read.  Return true if we are OK, false if we found EOF.
5859 
5860 bool
skip_past_error(Operator op)5861 Parse::skip_past_error(Operator op)
5862 {
5863   this->gogo_->mark_locals_used();
5864   const Token* token = this->peek_token();
5865   while (!token->is_op(op))
5866     {
5867       if (token->is_eof())
5868 	return false;
5869       if (token->is_op(OPERATOR_SEMICOLON))
5870 	{
5871 	  this->advance_token();
5872 	  return true;
5873 	}
5874       token = this->advance_token();
5875     }
5876   return true;
5877 }
5878 
5879 // Check that an expression is not a sink.
5880 
5881 Expression*
verify_not_sink(Expression * expr)5882 Parse::verify_not_sink(Expression* expr)
5883 {
5884   if (expr->is_sink_expression())
5885     {
5886       go_error_at(expr->location(), "cannot use %<_%> as value");
5887       expr = Expression::make_error(expr->location());
5888     }
5889 
5890   // If this can not be a sink, and it is a variable, then we are
5891   // using the variable, not just assigning to it.
5892   if (expr->var_expression() != NULL)
5893     this->mark_var_used(expr->var_expression()->named_object());
5894   else if (expr->enclosed_var_expression() != NULL)
5895     this->mark_var_used(expr->enclosed_var_expression()->variable());
5896   return expr;
5897 }
5898 
5899 // Mark a variable as used.
5900 
5901 void
mark_var_used(Named_object * no)5902 Parse::mark_var_used(Named_object* no)
5903 {
5904   if (no->is_variable())
5905     no->var_value()->set_is_used();
5906 }
5907