* gcc.dg/guality/guality.exp: Skip on AIX.
[official-gcc.git] / gcc / go / gofrontend / parse.cc
blob429d91bafe2bdc986421b3896e94bddb0394d688
1 // parse.cc -- Go frontend parser.
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.
7 #include "go-system.h"
9 #include "lex.h"
10 #include "gogo.h"
11 #include "types.h"
12 #include "statements.h"
13 #include "expressions.h"
14 #include "parse.h"
16 // Struct Parse::Enclosing_var_comparison.
18 // Return true if v1 should be considered to be less than v2.
20 bool
21 Parse::Enclosing_var_comparison::operator()(const Enclosing_var& v1,
22 const Enclosing_var& v2)
24 if (v1.var() == v2.var())
25 return false;
27 const std::string& n1(v1.var()->name());
28 const std::string& n2(v2.var()->name());
29 int i = n1.compare(n2);
30 if (i < 0)
31 return true;
32 else if (i > 0)
33 return false;
35 // If we get here it means that a single nested function refers to
36 // two different variables defined in enclosing functions, and both
37 // variables have the same name. I think this is impossible.
38 go_unreachable();
41 // Class Parse.
43 Parse::Parse(Lex* lex, Gogo* gogo)
44 : lex_(lex),
45 token_(Token::make_invalid_token(Linemap::unknown_location())),
46 unget_token_(Token::make_invalid_token(Linemap::unknown_location())),
47 unget_token_valid_(false),
48 is_erroneous_function_(false),
49 gogo_(gogo),
50 break_stack_(NULL),
51 continue_stack_(NULL),
52 iota_(0),
53 enclosing_vars_(),
54 type_switch_vars_()
58 // Return the current token.
60 const Token*
61 Parse::peek_token()
63 if (this->unget_token_valid_)
64 return &this->unget_token_;
65 if (this->token_.is_invalid())
66 this->token_ = this->lex_->next_token();
67 return &this->token_;
70 // Advance to the next token and return it.
72 const Token*
73 Parse::advance_token()
75 if (this->unget_token_valid_)
77 this->unget_token_valid_ = false;
78 if (!this->token_.is_invalid())
79 return &this->token_;
81 this->token_ = this->lex_->next_token();
82 return &this->token_;
85 // Push a token back on the input stream.
87 void
88 Parse::unget_token(const Token& token)
90 go_assert(!this->unget_token_valid_);
91 this->unget_token_ = token;
92 this->unget_token_valid_ = true;
95 // The location of the current token.
97 Location
98 Parse::location()
100 return this->peek_token()->location();
103 // IdentifierList = identifier { "," identifier } .
105 void
106 Parse::identifier_list(Typed_identifier_list* til)
108 const Token* token = this->peek_token();
109 while (true)
111 if (!token->is_identifier())
113 error_at(this->location(), "expected identifier");
114 return;
116 std::string name =
117 this->gogo_->pack_hidden_name(token->identifier(),
118 token->is_identifier_exported());
119 til->push_back(Typed_identifier(name, NULL, token->location()));
120 token = this->advance_token();
121 if (!token->is_op(OPERATOR_COMMA))
122 return;
123 token = this->advance_token();
127 // ExpressionList = Expression { "," Expression } .
129 // If MAY_BE_COMPOSITE_LIT is true, an expression may be a composite
130 // literal.
132 // If MAY_BE_SINK is true, the expressions in the list may be "_".
134 Expression_list*
135 Parse::expression_list(Expression* first, bool may_be_sink,
136 bool may_be_composite_lit)
138 Expression_list* ret = new Expression_list();
139 if (first != NULL)
140 ret->push_back(first);
141 while (true)
143 ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink,
144 may_be_composite_lit, NULL, NULL));
146 const Token* token = this->peek_token();
147 if (!token->is_op(OPERATOR_COMMA))
148 return ret;
150 // Most expression lists permit a trailing comma.
151 Location location = token->location();
152 this->advance_token();
153 if (!this->expression_may_start_here())
155 this->unget_token(Token::make_operator_token(OPERATOR_COMMA,
156 location));
157 return ret;
162 // QualifiedIdent = [ PackageName "." ] identifier .
163 // PackageName = identifier .
165 // This sets *PNAME to the identifier and sets *PPACKAGE to the
166 // package or NULL if there isn't one. This returns true on success,
167 // false on failure in which case it will have emitted an error
168 // message.
170 bool
171 Parse::qualified_ident(std::string* pname, Named_object** ppackage)
173 const Token* token = this->peek_token();
174 if (!token->is_identifier())
176 error_at(this->location(), "expected identifier");
177 return false;
180 std::string name = token->identifier();
181 bool is_exported = token->is_identifier_exported();
182 name = this->gogo_->pack_hidden_name(name, is_exported);
184 token = this->advance_token();
185 if (!token->is_op(OPERATOR_DOT))
187 *pname = name;
188 *ppackage = NULL;
189 return true;
192 Named_object* package = this->gogo_->lookup(name, NULL);
193 if (package == NULL || !package->is_package())
195 error_at(this->location(), "expected package");
196 // We expect . IDENTIFIER; skip both.
197 if (this->advance_token()->is_identifier())
198 this->advance_token();
199 return false;
202 package->package_value()->set_used();
204 token = this->advance_token();
205 if (!token->is_identifier())
207 error_at(this->location(), "expected identifier");
208 return false;
211 name = token->identifier();
213 if (name == "_")
215 error_at(this->location(), "invalid use of %<_%>");
216 name = "blank";
219 if (package->name() == this->gogo_->package_name())
220 name = this->gogo_->pack_hidden_name(name,
221 token->is_identifier_exported());
223 *pname = name;
224 *ppackage = package;
226 this->advance_token();
228 return true;
231 // Type = TypeName | TypeLit | "(" Type ")" .
232 // TypeLit =
233 // ArrayType | StructType | PointerType | FunctionType | InterfaceType |
234 // SliceType | MapType | ChannelType .
236 Type*
237 Parse::type()
239 const Token* token = this->peek_token();
240 if (token->is_identifier())
241 return this->type_name(true);
242 else if (token->is_op(OPERATOR_LSQUARE))
243 return this->array_type(false);
244 else if (token->is_keyword(KEYWORD_CHAN)
245 || token->is_op(OPERATOR_CHANOP))
246 return this->channel_type();
247 else if (token->is_keyword(KEYWORD_INTERFACE))
248 return this->interface_type();
249 else if (token->is_keyword(KEYWORD_FUNC))
251 Location location = token->location();
252 this->advance_token();
253 Type* type = this->signature(NULL, location);
254 if (type == NULL)
255 return Type::make_error_type();
256 return type;
258 else if (token->is_keyword(KEYWORD_MAP))
259 return this->map_type();
260 else if (token->is_keyword(KEYWORD_STRUCT))
261 return this->struct_type();
262 else if (token->is_op(OPERATOR_MULT))
263 return this->pointer_type();
264 else if (token->is_op(OPERATOR_LPAREN))
266 this->advance_token();
267 Type* ret = this->type();
268 if (this->peek_token()->is_op(OPERATOR_RPAREN))
269 this->advance_token();
270 else
272 if (!ret->is_error_type())
273 error_at(this->location(), "expected %<)%>");
275 return ret;
277 else
279 error_at(token->location(), "expected type");
280 return Type::make_error_type();
284 bool
285 Parse::type_may_start_here()
287 const Token* token = this->peek_token();
288 return (token->is_identifier()
289 || token->is_op(OPERATOR_LSQUARE)
290 || token->is_op(OPERATOR_CHANOP)
291 || token->is_keyword(KEYWORD_CHAN)
292 || token->is_keyword(KEYWORD_INTERFACE)
293 || token->is_keyword(KEYWORD_FUNC)
294 || token->is_keyword(KEYWORD_MAP)
295 || token->is_keyword(KEYWORD_STRUCT)
296 || token->is_op(OPERATOR_MULT)
297 || token->is_op(OPERATOR_LPAREN));
300 // TypeName = QualifiedIdent .
302 // If MAY_BE_NIL is true, then an identifier with the value of the
303 // predefined constant nil is accepted, returning the nil type.
305 Type*
306 Parse::type_name(bool issue_error)
308 Location location = this->location();
310 std::string name;
311 Named_object* package;
312 if (!this->qualified_ident(&name, &package))
313 return Type::make_error_type();
315 Named_object* named_object;
316 if (package == NULL)
317 named_object = this->gogo_->lookup(name, NULL);
318 else
320 named_object = package->package_value()->lookup(name);
321 if (named_object == NULL
322 && issue_error
323 && package->name() != this->gogo_->package_name())
325 // Check whether the name is there but hidden.
326 std::string s = ('.' + package->package_value()->pkgpath()
327 + '.' + name);
328 named_object = package->package_value()->lookup(s);
329 if (named_object != NULL)
331 Package* p = package->package_value();
332 const std::string& packname(p->package_name());
333 error_at(location, "invalid reference to hidden type %<%s.%s%>",
334 Gogo::message_name(packname).c_str(),
335 Gogo::message_name(name).c_str());
336 issue_error = false;
341 bool ok = true;
342 if (named_object == NULL)
344 if (package == NULL)
345 named_object = this->gogo_->add_unknown_name(name, location);
346 else
348 const std::string& packname(package->package_value()->package_name());
349 error_at(location, "reference to undefined identifier %<%s.%s%>",
350 Gogo::message_name(packname).c_str(),
351 Gogo::message_name(name).c_str());
352 issue_error = false;
353 ok = false;
356 else if (named_object->is_type())
358 if (!named_object->type_value()->is_visible())
359 ok = false;
361 else if (named_object->is_unknown() || named_object->is_type_declaration())
363 else
364 ok = false;
366 if (!ok)
368 if (issue_error)
369 error_at(location, "expected type");
370 return Type::make_error_type();
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();
381 // ArrayType = "[" [ ArrayLength ] "]" ElementType .
382 // ArrayLength = Expression .
383 // ElementType = CompleteType .
385 Type*
386 Parse::array_type(bool may_use_ellipsis)
388 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
389 const Token* token = this->advance_token();
391 Expression* length = NULL;
392 if (token->is_op(OPERATOR_RSQUARE))
393 this->advance_token();
394 else
396 if (!token->is_op(OPERATOR_ELLIPSIS))
397 length = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
398 else if (may_use_ellipsis)
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();
407 else
409 error_at(this->location(),
410 "use of %<[...]%> outside of array literal");
411 length = Expression::make_error(this->location());
412 this->advance_token();
414 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
416 error_at(this->location(), "expected %<]%>");
417 return Type::make_error_type();
419 this->advance_token();
422 Type* element_type = this->type();
424 return Type::make_array_type(element_type, length);
427 // MapType = "map" "[" KeyType "]" ValueType .
428 // KeyType = CompleteType .
429 // ValueType = CompleteType .
431 Type*
432 Parse::map_type()
434 Location location = this->location();
435 go_assert(this->peek_token()->is_keyword(KEYWORD_MAP));
436 if (!this->advance_token()->is_op(OPERATOR_LSQUARE))
438 error_at(this->location(), "expected %<[%>");
439 return Type::make_error_type();
441 this->advance_token();
443 Type* key_type = this->type();
445 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
447 error_at(this->location(), "expected %<]%>");
448 return Type::make_error_type();
450 this->advance_token();
452 Type* value_type = this->type();
454 if (key_type->is_error_type() || value_type->is_error_type())
455 return Type::make_error_type();
457 return Type::make_map_type(key_type, value_type, location);
460 // StructType = "struct" "{" { FieldDecl ";" } "}" .
462 Type*
463 Parse::struct_type()
465 go_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT));
466 Location location = this->location();
467 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
469 Location token_loc = this->location();
470 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
471 && this->advance_token()->is_op(OPERATOR_LCURLY))
472 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
473 else
475 error_at(this->location(), "expected %<{%>");
476 return Type::make_error_type();
479 this->advance_token();
481 Struct_field_list* sfl = new Struct_field_list;
482 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
484 this->field_decl(sfl);
485 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
486 this->advance_token();
487 else if (!this->peek_token()->is_op(OPERATOR_RCURLY))
489 error_at(this->location(), "expected %<;%> or %<}%> or newline");
490 if (!this->skip_past_error(OPERATOR_RCURLY))
491 return Type::make_error_type();
494 this->advance_token();
496 for (Struct_field_list::const_iterator pi = sfl->begin();
497 pi != sfl->end();
498 ++pi)
500 if (pi->type()->is_error_type())
501 return pi->type();
502 for (Struct_field_list::const_iterator pj = pi + 1;
503 pj != sfl->end();
504 ++pj)
506 if (pi->field_name() == pj->field_name()
507 && !Gogo::is_sink_name(pi->field_name()))
508 error_at(pi->location(), "duplicate field name %<%s%>",
509 Gogo::message_name(pi->field_name()).c_str());
513 return Type::make_struct_type(sfl, location);
516 // FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] .
517 // Tag = string_lit .
519 void
520 Parse::field_decl(Struct_field_list* sfl)
522 const Token* token = this->peek_token();
523 Location location = token->location();
524 bool is_anonymous;
525 bool is_anonymous_pointer;
526 if (token->is_op(OPERATOR_MULT))
528 is_anonymous = true;
529 is_anonymous_pointer = true;
531 else if (token->is_identifier())
533 std::string id = token->identifier();
534 bool is_id_exported = token->is_identifier_exported();
535 Location id_location = token->location();
536 token = this->advance_token();
537 is_anonymous = (token->is_op(OPERATOR_SEMICOLON)
538 || token->is_op(OPERATOR_RCURLY)
539 || token->is_op(OPERATOR_DOT)
540 || token->is_string());
541 is_anonymous_pointer = false;
542 this->unget_token(Token::make_identifier_token(id, is_id_exported,
543 id_location));
545 else
547 error_at(this->location(), "expected field name");
548 this->gogo_->mark_locals_used();
549 while (!token->is_op(OPERATOR_SEMICOLON)
550 && !token->is_op(OPERATOR_RCURLY)
551 && !token->is_eof())
552 token = this->advance_token();
553 return;
556 if (is_anonymous)
558 if (is_anonymous_pointer)
560 this->advance_token();
561 if (!this->peek_token()->is_identifier())
563 error_at(this->location(), "expected field name");
564 this->gogo_->mark_locals_used();
565 while (!token->is_op(OPERATOR_SEMICOLON)
566 && !token->is_op(OPERATOR_RCURLY)
567 && !token->is_eof())
568 token = this->advance_token();
569 return;
572 Type* type = this->type_name(true);
574 std::string tag;
575 if (this->peek_token()->is_string())
577 tag = this->peek_token()->string_value();
578 this->advance_token();
581 if (!type->is_error_type())
583 if (is_anonymous_pointer)
584 type = Type::make_pointer_type(type);
585 sfl->push_back(Struct_field(Typed_identifier("", type, location)));
586 if (!tag.empty())
587 sfl->back().set_tag(tag);
590 else
592 Typed_identifier_list til;
593 while (true)
595 token = this->peek_token();
596 if (!token->is_identifier())
598 error_at(this->location(), "expected identifier");
599 return;
601 std::string name =
602 this->gogo_->pack_hidden_name(token->identifier(),
603 token->is_identifier_exported());
604 til.push_back(Typed_identifier(name, NULL, token->location()));
605 if (!this->advance_token()->is_op(OPERATOR_COMMA))
606 break;
607 this->advance_token();
610 Type* type = this->type();
612 std::string tag;
613 if (this->peek_token()->is_string())
615 tag = this->peek_token()->string_value();
616 this->advance_token();
619 for (Typed_identifier_list::iterator p = til.begin();
620 p != til.end();
621 ++p)
623 p->set_type(type);
624 sfl->push_back(Struct_field(*p));
625 if (!tag.empty())
626 sfl->back().set_tag(tag);
631 // PointerType = "*" Type .
633 Type*
634 Parse::pointer_type()
636 go_assert(this->peek_token()->is_op(OPERATOR_MULT));
637 this->advance_token();
638 Type* type = this->type();
639 if (type->is_error_type())
640 return type;
641 return Type::make_pointer_type(type);
644 // ChannelType = Channel | SendChannel | RecvChannel .
645 // Channel = "chan" ElementType .
646 // SendChannel = "chan" "<-" ElementType .
647 // RecvChannel = "<-" "chan" ElementType .
649 Type*
650 Parse::channel_type()
652 const Token* token = this->peek_token();
653 bool send = true;
654 bool receive = true;
655 if (token->is_op(OPERATOR_CHANOP))
657 if (!this->advance_token()->is_keyword(KEYWORD_CHAN))
659 error_at(this->location(), "expected %<chan%>");
660 return Type::make_error_type();
662 send = false;
663 this->advance_token();
665 else
667 go_assert(token->is_keyword(KEYWORD_CHAN));
668 if (this->advance_token()->is_op(OPERATOR_CHANOP))
670 receive = false;
671 this->advance_token();
675 // Better error messages for the common error of omitting the
676 // channel element type.
677 if (!this->type_may_start_here())
679 token = this->peek_token();
680 if (token->is_op(OPERATOR_RCURLY))
681 error_at(this->location(), "unexpected %<}%> in channel type");
682 else if (token->is_op(OPERATOR_RPAREN))
683 error_at(this->location(), "unexpected %<)%> in channel type");
684 else if (token->is_op(OPERATOR_COMMA))
685 error_at(this->location(), "unexpected comma in channel type");
686 else
687 error_at(this->location(), "expected channel element type");
688 return Type::make_error_type();
691 Type* element_type = this->type();
692 return Type::make_channel_type(send, receive, element_type);
695 // Give an error for a duplicate parameter or receiver name.
697 void
698 Parse::check_signature_names(const Typed_identifier_list* params,
699 Parse::Names* names)
701 for (Typed_identifier_list::const_iterator p = params->begin();
702 p != params->end();
703 ++p)
705 if (p->name().empty() || Gogo::is_sink_name(p->name()))
706 continue;
707 std::pair<std::string, const Typed_identifier*> val =
708 std::make_pair(p->name(), &*p);
709 std::pair<Parse::Names::iterator, bool> ins = names->insert(val);
710 if (!ins.second)
712 error_at(p->location(), "redefinition of %qs",
713 Gogo::message_name(p->name()).c_str());
714 inform(ins.first->second->location(),
715 "previous definition of %qs was here",
716 Gogo::message_name(p->name()).c_str());
721 // Signature = Parameters [ Result ] .
723 // RECEIVER is the receiver if there is one, or NULL. LOCATION is the
724 // location of the start of the type.
726 // This returns NULL on a parse error.
728 Function_type*
729 Parse::signature(Typed_identifier* receiver, Location location)
731 bool is_varargs = false;
732 Typed_identifier_list* params;
733 bool params_ok = this->parameters(&params, &is_varargs);
735 Typed_identifier_list* results = NULL;
736 if (this->peek_token()->is_op(OPERATOR_LPAREN)
737 || this->type_may_start_here())
739 if (!this->result(&results))
740 return NULL;
743 if (!params_ok)
744 return NULL;
746 Parse::Names names;
747 if (params != NULL)
748 this->check_signature_names(params, &names);
749 if (results != NULL)
750 this->check_signature_names(results, &names);
752 Function_type* ret = Type::make_function_type(receiver, params, results,
753 location);
754 if (is_varargs)
755 ret->set_is_varargs();
756 return ret;
759 // Parameters = "(" [ ParameterList [ "," ] ] ")" .
761 // This returns false on a parse error.
763 bool
764 Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs)
766 *pparams = NULL;
768 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
770 error_at(this->location(), "expected %<(%>");
771 return false;
774 Typed_identifier_list* params = NULL;
775 bool saw_error = false;
777 const Token* token = this->advance_token();
778 if (!token->is_op(OPERATOR_RPAREN))
780 params = this->parameter_list(is_varargs);
781 if (params == NULL)
782 saw_error = true;
783 token = this->peek_token();
786 // The optional trailing comma is picked up in parameter_list.
788 if (!token->is_op(OPERATOR_RPAREN))
789 error_at(this->location(), "expected %<)%>");
790 else
791 this->advance_token();
793 if (saw_error)
794 return false;
796 *pparams = params;
797 return true;
800 // ParameterList = ParameterDecl { "," ParameterDecl } .
802 // This sets *IS_VARARGS if the list ends with an ellipsis.
803 // IS_VARARGS will be NULL if varargs are not permitted.
805 // We pick up an optional trailing comma.
807 // This returns NULL if some error is seen.
809 Typed_identifier_list*
810 Parse::parameter_list(bool* is_varargs)
812 Location location = this->location();
813 Typed_identifier_list* ret = new Typed_identifier_list();
815 bool saw_error = false;
817 // If we see an identifier and then a comma, then we don't know
818 // whether we are looking at a list of identifiers followed by a
819 // type, or a list of types given by name. We have to do an
820 // arbitrary lookahead to figure it out.
822 bool parameters_have_names;
823 const Token* token = this->peek_token();
824 if (!token->is_identifier())
826 // This must be a type which starts with something like '*'.
827 parameters_have_names = false;
829 else
831 std::string name = token->identifier();
832 bool is_exported = token->is_identifier_exported();
833 Location location = token->location();
834 token = this->advance_token();
835 if (!token->is_op(OPERATOR_COMMA))
837 if (token->is_op(OPERATOR_DOT))
839 // This is a qualified identifier, which must turn out
840 // to be a type.
841 parameters_have_names = false;
843 else if (token->is_op(OPERATOR_RPAREN))
845 // A single identifier followed by a parenthesis must be
846 // a type name.
847 parameters_have_names = false;
849 else
851 // An identifier followed by something other than a
852 // comma or a dot or a right parenthesis must be a
853 // parameter name followed by a type.
854 parameters_have_names = true;
857 this->unget_token(Token::make_identifier_token(name, is_exported,
858 location));
860 else
862 // An identifier followed by a comma may be the first in a
863 // list of parameter names followed by a type, or it may be
864 // the first in a list of types without parameter names. To
865 // find out we gather as many identifiers separated by
866 // commas as we can.
867 std::string id_name = this->gogo_->pack_hidden_name(name,
868 is_exported);
869 ret->push_back(Typed_identifier(id_name, NULL, location));
870 bool just_saw_comma = true;
871 while (this->advance_token()->is_identifier())
873 name = this->peek_token()->identifier();
874 is_exported = this->peek_token()->is_identifier_exported();
875 location = this->peek_token()->location();
876 id_name = this->gogo_->pack_hidden_name(name, is_exported);
877 ret->push_back(Typed_identifier(id_name, NULL, location));
878 if (!this->advance_token()->is_op(OPERATOR_COMMA))
880 just_saw_comma = false;
881 break;
885 if (just_saw_comma)
887 // We saw ID1 "," ID2 "," followed by something which
888 // was not an identifier. We must be seeing the start
889 // of a type, and ID1 and ID2 must be types, and the
890 // parameters don't have names.
891 parameters_have_names = false;
893 else if (this->peek_token()->is_op(OPERATOR_RPAREN))
895 // We saw ID1 "," ID2 ")". ID1 and ID2 must be types,
896 // and the parameters don't have names.
897 parameters_have_names = false;
899 else if (this->peek_token()->is_op(OPERATOR_DOT))
901 // We saw ID1 "," ID2 ".". ID2 must be a package name,
902 // ID1 must be a type, and the parameters don't have
903 // names.
904 parameters_have_names = false;
905 this->unget_token(Token::make_identifier_token(name, is_exported,
906 location));
907 ret->pop_back();
908 just_saw_comma = true;
910 else
912 // We saw ID1 "," ID2 followed by something other than
913 // ",", ".", or ")". We must be looking at the start of
914 // a type, and ID1 and ID2 must be parameter names.
915 parameters_have_names = true;
918 if (parameters_have_names)
920 go_assert(!just_saw_comma);
921 // We have just seen ID1, ID2 xxx.
922 Type* type;
923 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
924 type = this->type();
925 else
927 error_at(this->location(), "%<...%> only permits one name");
928 saw_error = true;
929 this->advance_token();
930 type = this->type();
932 for (size_t i = 0; i < ret->size(); ++i)
933 ret->set_type(i, type);
934 if (!this->peek_token()->is_op(OPERATOR_COMMA))
935 return saw_error ? NULL : ret;
936 if (this->advance_token()->is_op(OPERATOR_RPAREN))
937 return saw_error ? NULL : ret;
939 else
941 Typed_identifier_list* tret = new Typed_identifier_list();
942 for (Typed_identifier_list::const_iterator p = ret->begin();
943 p != ret->end();
944 ++p)
946 Named_object* no = this->gogo_->lookup(p->name(), NULL);
947 Type* type;
948 if (no == NULL)
949 no = this->gogo_->add_unknown_name(p->name(),
950 p->location());
952 if (no->is_type())
953 type = no->type_value();
954 else if (no->is_unknown() || no->is_type_declaration())
955 type = Type::make_forward_declaration(no);
956 else
958 error_at(p->location(), "expected %<%s%> to be a type",
959 Gogo::message_name(p->name()).c_str());
960 saw_error = true;
961 type = Type::make_error_type();
963 tret->push_back(Typed_identifier("", type, p->location()));
965 delete ret;
966 ret = tret;
967 if (!just_saw_comma
968 || this->peek_token()->is_op(OPERATOR_RPAREN))
969 return saw_error ? NULL : ret;
974 bool mix_error = false;
975 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
976 while (this->peek_token()->is_op(OPERATOR_COMMA))
978 if (this->advance_token()->is_op(OPERATOR_RPAREN))
979 break;
980 if (is_varargs != NULL && *is_varargs)
982 error_at(this->location(), "%<...%> must be last parameter");
983 saw_error = true;
985 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
987 if (mix_error)
989 error_at(location, "invalid named/anonymous mix");
990 saw_error = true;
992 if (saw_error)
994 delete ret;
995 return NULL;
997 return ret;
1000 // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
1002 void
1003 Parse::parameter_decl(bool parameters_have_names,
1004 Typed_identifier_list* til,
1005 bool* is_varargs,
1006 bool* mix_error)
1008 if (!parameters_have_names)
1010 Type* type;
1011 Location location = this->location();
1012 if (!this->peek_token()->is_identifier())
1014 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1015 type = this->type();
1016 else
1018 if (is_varargs == NULL)
1019 error_at(this->location(), "invalid use of %<...%>");
1020 else
1021 *is_varargs = true;
1022 this->advance_token();
1023 if (is_varargs == NULL
1024 && this->peek_token()->is_op(OPERATOR_RPAREN))
1025 type = Type::make_error_type();
1026 else
1028 Type* element_type = this->type();
1029 type = Type::make_array_type(element_type, NULL);
1033 else
1035 type = this->type_name(false);
1036 if (type->is_error_type()
1037 || (!this->peek_token()->is_op(OPERATOR_COMMA)
1038 && !this->peek_token()->is_op(OPERATOR_RPAREN)))
1040 *mix_error = true;
1041 while (!this->peek_token()->is_op(OPERATOR_COMMA)
1042 && !this->peek_token()->is_op(OPERATOR_RPAREN))
1043 this->advance_token();
1046 if (!type->is_error_type())
1047 til->push_back(Typed_identifier("", type, location));
1049 else
1051 size_t orig_count = til->size();
1052 if (this->peek_token()->is_identifier())
1053 this->identifier_list(til);
1054 else
1055 *mix_error = true;
1056 size_t new_count = til->size();
1058 Type* type;
1059 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1060 type = this->type();
1061 else
1063 if (is_varargs == NULL)
1064 error_at(this->location(), "invalid use of %<...%>");
1065 else if (new_count > orig_count + 1)
1066 error_at(this->location(), "%<...%> only permits one name");
1067 else
1068 *is_varargs = true;
1069 this->advance_token();
1070 Type* element_type = this->type();
1071 type = Type::make_array_type(element_type, NULL);
1073 for (size_t i = orig_count; i < new_count; ++i)
1074 til->set_type(i, type);
1078 // Result = Parameters | Type .
1080 // This returns false on a parse error.
1082 bool
1083 Parse::result(Typed_identifier_list** presults)
1085 if (this->peek_token()->is_op(OPERATOR_LPAREN))
1086 return this->parameters(presults, NULL);
1087 else
1089 Location location = this->location();
1090 Type* type = this->type();
1091 if (type->is_error_type())
1093 *presults = NULL;
1094 return false;
1096 Typed_identifier_list* til = new Typed_identifier_list();
1097 til->push_back(Typed_identifier("", type, location));
1098 *presults = til;
1099 return true;
1103 // Block = "{" [ StatementList ] "}" .
1105 // Returns the location of the closing brace.
1107 Location
1108 Parse::block()
1110 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
1112 Location loc = this->location();
1113 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1114 && this->advance_token()->is_op(OPERATOR_LCURLY))
1115 error_at(loc, "unexpected semicolon or newline before %<{%>");
1116 else
1118 error_at(this->location(), "expected %<{%>");
1119 return Linemap::unknown_location();
1123 const Token* token = this->advance_token();
1125 if (!token->is_op(OPERATOR_RCURLY))
1127 this->statement_list();
1128 token = this->peek_token();
1129 if (!token->is_op(OPERATOR_RCURLY))
1131 if (!token->is_eof() || !saw_errors())
1132 error_at(this->location(), "expected %<}%>");
1134 this->gogo_->mark_locals_used();
1136 // Skip ahead to the end of the block, in hopes of avoiding
1137 // lots of meaningless errors.
1138 Location ret = token->location();
1139 int nest = 0;
1140 while (!token->is_eof())
1142 if (token->is_op(OPERATOR_LCURLY))
1143 ++nest;
1144 else if (token->is_op(OPERATOR_RCURLY))
1146 --nest;
1147 if (nest < 0)
1149 this->advance_token();
1150 break;
1153 token = this->advance_token();
1154 ret = token->location();
1156 return ret;
1160 Location ret = token->location();
1161 this->advance_token();
1162 return ret;
1165 // InterfaceType = "interface" "{" [ MethodSpecList ] "}" .
1166 // MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] .
1168 Type*
1169 Parse::interface_type()
1171 go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE));
1172 Location location = this->location();
1174 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
1176 Location token_loc = this->location();
1177 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1178 && this->advance_token()->is_op(OPERATOR_LCURLY))
1179 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
1180 else
1182 error_at(this->location(), "expected %<{%>");
1183 return Type::make_error_type();
1186 this->advance_token();
1188 Typed_identifier_list* methods = new Typed_identifier_list();
1189 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1191 this->method_spec(methods);
1192 while (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1194 if (this->advance_token()->is_op(OPERATOR_RCURLY))
1195 break;
1196 this->method_spec(methods);
1198 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1200 error_at(this->location(), "expected %<}%>");
1201 while (!this->advance_token()->is_op(OPERATOR_RCURLY))
1203 if (this->peek_token()->is_eof())
1204 return Type::make_error_type();
1208 this->advance_token();
1210 if (methods->empty())
1212 delete methods;
1213 methods = NULL;
1216 Interface_type* ret = Type::make_interface_type(methods, location);
1217 this->gogo_->record_interface_type(ret);
1218 return ret;
1221 // MethodSpec = MethodName Signature | InterfaceTypeName .
1222 // MethodName = identifier .
1223 // InterfaceTypeName = TypeName .
1225 void
1226 Parse::method_spec(Typed_identifier_list* methods)
1228 const Token* token = this->peek_token();
1229 if (!token->is_identifier())
1231 error_at(this->location(), "expected identifier");
1232 return;
1235 std::string name = token->identifier();
1236 bool is_exported = token->is_identifier_exported();
1237 Location location = token->location();
1239 if (this->advance_token()->is_op(OPERATOR_LPAREN))
1241 // This is a MethodName.
1242 name = this->gogo_->pack_hidden_name(name, is_exported);
1243 Type* type = this->signature(NULL, location);
1244 if (type == NULL)
1245 return;
1246 methods->push_back(Typed_identifier(name, type, location));
1248 else
1250 this->unget_token(Token::make_identifier_token(name, is_exported,
1251 location));
1252 Type* type = this->type_name(false);
1253 if (type->is_error_type()
1254 || (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1255 && !this->peek_token()->is_op(OPERATOR_RCURLY)))
1257 if (this->peek_token()->is_op(OPERATOR_COMMA))
1258 error_at(this->location(),
1259 "name list not allowed in interface type");
1260 else
1261 error_at(location, "expected signature or type name");
1262 this->gogo_->mark_locals_used();
1263 token = this->peek_token();
1264 while (!token->is_eof()
1265 && !token->is_op(OPERATOR_SEMICOLON)
1266 && !token->is_op(OPERATOR_RCURLY))
1267 token = this->advance_token();
1268 return;
1270 // This must be an interface type, but we can't check that now.
1271 // We check it and pull out the methods in
1272 // Interface_type::do_verify.
1273 methods->push_back(Typed_identifier("", type, location));
1277 // Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1279 void
1280 Parse::declaration()
1282 const Token* token = this->peek_token();
1284 bool saw_nointerface = this->lex_->get_and_clear_nointerface();
1285 if (saw_nointerface && !token->is_keyword(KEYWORD_FUNC))
1286 warning_at(token->location(), 0,
1287 "ignoring magic //go:nointerface comment before non-method");
1289 if (token->is_keyword(KEYWORD_CONST))
1290 this->const_decl();
1291 else if (token->is_keyword(KEYWORD_TYPE))
1292 this->type_decl();
1293 else if (token->is_keyword(KEYWORD_VAR))
1294 this->var_decl();
1295 else if (token->is_keyword(KEYWORD_FUNC))
1296 this->function_decl(saw_nointerface);
1297 else
1299 error_at(this->location(), "expected declaration");
1300 this->advance_token();
1304 bool
1305 Parse::declaration_may_start_here()
1307 const Token* token = this->peek_token();
1308 return (token->is_keyword(KEYWORD_CONST)
1309 || token->is_keyword(KEYWORD_TYPE)
1310 || token->is_keyword(KEYWORD_VAR)
1311 || token->is_keyword(KEYWORD_FUNC));
1314 // Decl<P> = P | "(" [ List<P> ] ")" .
1316 void
1317 Parse::decl(void (Parse::*pfn)(void*), void* varg)
1319 if (this->peek_token()->is_eof())
1321 if (!saw_errors())
1322 error_at(this->location(), "unexpected end of file");
1323 return;
1326 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1327 (this->*pfn)(varg);
1328 else
1330 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
1332 this->list(pfn, varg, true);
1333 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1335 error_at(this->location(), "missing %<)%>");
1336 while (!this->advance_token()->is_op(OPERATOR_RPAREN))
1338 if (this->peek_token()->is_eof())
1339 return;
1343 this->advance_token();
1347 // List<P> = P { ";" P } [ ";" ] .
1349 // In order to pick up the trailing semicolon we need to know what
1350 // might follow. This is either a '}' or a ')'.
1352 void
1353 Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren)
1355 (this->*pfn)(varg);
1356 Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY;
1357 while (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1358 || this->peek_token()->is_op(OPERATOR_COMMA))
1360 if (this->peek_token()->is_op(OPERATOR_COMMA))
1361 error_at(this->location(), "unexpected comma");
1362 if (this->advance_token()->is_op(follow))
1363 break;
1364 (this->*pfn)(varg);
1368 // ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1370 void
1371 Parse::const_decl()
1373 go_assert(this->peek_token()->is_keyword(KEYWORD_CONST));
1374 this->advance_token();
1375 this->reset_iota();
1377 Type* last_type = NULL;
1378 Expression_list* last_expr_list = NULL;
1380 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1381 this->const_spec(&last_type, &last_expr_list);
1382 else
1384 this->advance_token();
1385 while (!this->peek_token()->is_op(OPERATOR_RPAREN))
1387 this->const_spec(&last_type, &last_expr_list);
1388 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1389 this->advance_token();
1390 else if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1392 error_at(this->location(), "expected %<;%> or %<)%> or newline");
1393 if (!this->skip_past_error(OPERATOR_RPAREN))
1394 return;
1397 this->advance_token();
1400 if (last_expr_list != NULL)
1401 delete last_expr_list;
1404 // ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
1406 void
1407 Parse::const_spec(Type** last_type, Expression_list** last_expr_list)
1409 Typed_identifier_list til;
1410 this->identifier_list(&til);
1412 Type* type = NULL;
1413 if (this->type_may_start_here())
1415 type = this->type();
1416 *last_type = NULL;
1417 *last_expr_list = NULL;
1420 Expression_list *expr_list;
1421 if (!this->peek_token()->is_op(OPERATOR_EQ))
1423 if (*last_expr_list == NULL)
1425 error_at(this->location(), "expected %<=%>");
1426 return;
1428 type = *last_type;
1429 expr_list = new Expression_list;
1430 for (Expression_list::const_iterator p = (*last_expr_list)->begin();
1431 p != (*last_expr_list)->end();
1432 ++p)
1433 expr_list->push_back((*p)->copy());
1435 else
1437 this->advance_token();
1438 expr_list = this->expression_list(NULL, false, true);
1439 *last_type = type;
1440 if (*last_expr_list != NULL)
1441 delete *last_expr_list;
1442 *last_expr_list = expr_list;
1445 Expression_list::const_iterator pe = expr_list->begin();
1446 for (Typed_identifier_list::iterator pi = til.begin();
1447 pi != til.end();
1448 ++pi, ++pe)
1450 if (pe == expr_list->end())
1452 error_at(this->location(), "not enough initializers");
1453 return;
1455 if (type != NULL)
1456 pi->set_type(type);
1458 if (!Gogo::is_sink_name(pi->name()))
1459 this->gogo_->add_constant(*pi, *pe, this->iota_value());
1460 else
1462 static int count;
1463 char buf[30];
1464 snprintf(buf, sizeof buf, ".$sinkconst%d", count);
1465 ++count;
1466 Typed_identifier ti(std::string(buf), type, pi->location());
1467 Named_object* no = this->gogo_->add_constant(ti, *pe, this->iota_value());
1468 no->const_value()->set_is_sink();
1471 if (pe != expr_list->end())
1472 error_at(this->location(), "too many initializers");
1474 this->increment_iota();
1476 return;
1479 // TypeDecl = "type" Decl<TypeSpec> .
1481 void
1482 Parse::type_decl()
1484 go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE));
1485 this->advance_token();
1486 this->decl(&Parse::type_spec, NULL);
1489 // TypeSpec = identifier Type .
1491 void
1492 Parse::type_spec(void*)
1494 const Token* token = this->peek_token();
1495 if (!token->is_identifier())
1497 error_at(this->location(), "expected identifier");
1498 return;
1500 std::string name = token->identifier();
1501 bool is_exported = token->is_identifier_exported();
1502 Location location = token->location();
1503 token = this->advance_token();
1505 // The scope of the type name starts at the point where the
1506 // identifier appears in the source code. We implement this by
1507 // declaring the type before we read the type definition.
1508 Named_object* named_type = NULL;
1509 if (name != "_")
1511 name = this->gogo_->pack_hidden_name(name, is_exported);
1512 named_type = this->gogo_->declare_type(name, location);
1515 Type* type;
1516 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
1517 type = this->type();
1518 else
1520 error_at(this->location(),
1521 "unexpected semicolon or newline in type declaration");
1522 type = Type::make_error_type();
1523 this->advance_token();
1526 if (type->is_error_type())
1528 this->gogo_->mark_locals_used();
1529 while (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1530 && !this->peek_token()->is_eof())
1531 this->advance_token();
1534 if (name != "_")
1536 if (named_type->is_type_declaration())
1538 Type* ftype = type->forwarded();
1539 if (ftype->forward_declaration_type() != NULL
1540 && (ftype->forward_declaration_type()->named_object()
1541 == named_type))
1543 error_at(location, "invalid recursive type");
1544 type = Type::make_error_type();
1547 this->gogo_->define_type(named_type,
1548 Type::make_named_type(named_type, type,
1549 location));
1550 go_assert(named_type->package() == NULL);
1552 else
1554 // This will probably give a redefinition error.
1555 this->gogo_->add_type(name, type, location);
1560 // VarDecl = "var" Decl<VarSpec> .
1562 void
1563 Parse::var_decl()
1565 go_assert(this->peek_token()->is_keyword(KEYWORD_VAR));
1566 this->advance_token();
1567 this->decl(&Parse::var_spec, NULL);
1570 // VarSpec = IdentifierList
1571 // ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
1573 void
1574 Parse::var_spec(void*)
1576 // Get the variable names.
1577 Typed_identifier_list til;
1578 this->identifier_list(&til);
1580 Location location = this->location();
1582 Type* type = NULL;
1583 Expression_list* init = NULL;
1584 if (!this->peek_token()->is_op(OPERATOR_EQ))
1586 type = this->type();
1587 if (type->is_error_type())
1589 this->gogo_->mark_locals_used();
1590 while (!this->peek_token()->is_op(OPERATOR_EQ)
1591 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
1592 && !this->peek_token()->is_eof())
1593 this->advance_token();
1595 if (this->peek_token()->is_op(OPERATOR_EQ))
1597 this->advance_token();
1598 init = this->expression_list(NULL, false, true);
1601 else
1603 this->advance_token();
1604 init = this->expression_list(NULL, false, true);
1607 this->init_vars(&til, type, init, false, location);
1609 if (init != NULL)
1610 delete init;
1613 // Create variables. TIL is a list of variable names. If TYPE is not
1614 // NULL, it is the type of all the variables. If INIT is not NULL, it
1615 // is an initializer list for the variables.
1617 void
1618 Parse::init_vars(const Typed_identifier_list* til, Type* type,
1619 Expression_list* init, bool is_coloneq,
1620 Location location)
1622 // Check for an initialization which can yield multiple values.
1623 if (init != NULL && init->size() == 1 && til->size() > 1)
1625 if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq,
1626 location))
1627 return;
1628 if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq,
1629 location))
1630 return;
1631 if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq,
1632 location))
1633 return;
1634 if (this->init_vars_from_type_guard(til, type, *init->begin(),
1635 is_coloneq, location))
1636 return;
1639 if (init != NULL && init->size() != til->size())
1641 if (init->empty() || !init->front()->is_error_expression())
1642 error_at(location, "wrong number of initializations");
1643 init = NULL;
1644 if (type == NULL)
1645 type = Type::make_error_type();
1648 // Note that INIT was already parsed with the old name bindings, so
1649 // we don't have to worry that it will accidentally refer to the
1650 // newly declared variables. But we do have to worry about a mix of
1651 // newly declared variables and old variables if the old variables
1652 // appear in the initializations.
1654 Expression_list::const_iterator pexpr;
1655 if (init != NULL)
1656 pexpr = init->begin();
1657 bool any_new = false;
1658 Expression_list* vars = new Expression_list();
1659 Expression_list* vals = new Expression_list();
1660 for (Typed_identifier_list::const_iterator p = til->begin();
1661 p != til->end();
1662 ++p)
1664 if (init != NULL)
1665 go_assert(pexpr != init->end());
1666 this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq,
1667 false, &any_new, vars, vals);
1668 if (init != NULL)
1669 ++pexpr;
1671 if (init != NULL)
1672 go_assert(pexpr == init->end());
1673 if (is_coloneq && !any_new)
1674 error_at(location, "variables redeclared but no variable is new");
1675 this->finish_init_vars(vars, vals, location);
1678 // See if we need to initialize a list of variables from a function
1679 // call. This returns true if we have set up the variables and the
1680 // initialization.
1682 bool
1683 Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type,
1684 Expression* expr, bool is_coloneq,
1685 Location location)
1687 Call_expression* call = expr->call_expression();
1688 if (call == NULL)
1689 return false;
1691 // This is a function call. We can't check here whether it returns
1692 // the right number of values, but it might. Declare the variables,
1693 // and then assign the results of the call to them.
1695 Named_object* first_var = NULL;
1696 unsigned int index = 0;
1697 bool any_new = false;
1698 Expression_list* ivars = new Expression_list();
1699 Expression_list* ivals = new Expression_list();
1700 for (Typed_identifier_list::const_iterator pv = vars->begin();
1701 pv != vars->end();
1702 ++pv, ++index)
1704 Expression* init = Expression::make_call_result(call, index);
1705 Named_object* no = this->init_var(*pv, type, init, is_coloneq, false,
1706 &any_new, ivars, ivals);
1708 if (this->gogo_->in_global_scope() && no->is_variable())
1710 if (first_var == NULL)
1711 first_var = no;
1712 else
1714 // The subsequent vars have an implicit dependency on
1715 // the first one, so that everything gets initialized in
1716 // the right order and so that we detect cycles
1717 // correctly.
1718 this->gogo_->record_var_depends_on(no->var_value(), first_var);
1723 if (is_coloneq && !any_new)
1724 error_at(location, "variables redeclared but no variable is new");
1726 this->finish_init_vars(ivars, ivals, location);
1728 return true;
1731 // See if we need to initialize a pair of values from a map index
1732 // expression. This returns true if we have set up the variables and
1733 // the initialization.
1735 bool
1736 Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type,
1737 Expression* expr, bool is_coloneq,
1738 Location location)
1740 Index_expression* index = expr->index_expression();
1741 if (index == NULL)
1742 return false;
1743 if (vars->size() != 2)
1744 return false;
1746 // This is an index which is being assigned to two variables. It
1747 // must be a map index. Declare the variables, and then assign the
1748 // results of the map index.
1749 bool any_new = false;
1750 Typed_identifier_list::const_iterator p = vars->begin();
1751 Expression* init = type == NULL ? index : NULL;
1752 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1753 type == NULL, &any_new, NULL, NULL);
1754 if (type == NULL && any_new && val_no->is_variable())
1755 val_no->var_value()->set_type_from_init_tuple();
1756 Expression* val_var = Expression::make_var_reference(val_no, location);
1758 ++p;
1759 Type* var_type = type;
1760 if (var_type == NULL)
1761 var_type = Type::lookup_bool_type();
1762 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1763 &any_new, NULL, NULL);
1764 Expression* present_var = Expression::make_var_reference(no, location);
1766 if (is_coloneq && !any_new)
1767 error_at(location, "variables redeclared but no variable is new");
1769 Statement* s = Statement::make_tuple_map_assignment(val_var, present_var,
1770 index, location);
1772 if (!this->gogo_->in_global_scope())
1773 this->gogo_->add_statement(s);
1774 else if (!val_no->is_sink())
1776 if (val_no->is_variable())
1777 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1779 else if (!no->is_sink())
1781 if (no->is_variable())
1782 no->var_value()->add_preinit_statement(this->gogo_, s);
1784 else
1786 // Execute the map index expression just so that we can fail if
1787 // the map is nil.
1788 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1789 NULL, location);
1790 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1793 return true;
1796 // See if we need to initialize a pair of values from a receive
1797 // expression. This returns true if we have set up the variables and
1798 // the initialization.
1800 bool
1801 Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type,
1802 Expression* expr, bool is_coloneq,
1803 Location location)
1805 Receive_expression* receive = expr->receive_expression();
1806 if (receive == NULL)
1807 return false;
1808 if (vars->size() != 2)
1809 return false;
1811 // This is a receive expression which is being assigned to two
1812 // variables. Declare the variables, and then assign the results of
1813 // the receive.
1814 bool any_new = false;
1815 Typed_identifier_list::const_iterator p = vars->begin();
1816 Expression* init = type == NULL ? receive : NULL;
1817 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1818 type == NULL, &any_new, NULL, NULL);
1819 if (type == NULL && any_new && val_no->is_variable())
1820 val_no->var_value()->set_type_from_init_tuple();
1821 Expression* val_var = Expression::make_var_reference(val_no, location);
1823 ++p;
1824 Type* var_type = type;
1825 if (var_type == NULL)
1826 var_type = Type::lookup_bool_type();
1827 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1828 &any_new, NULL, NULL);
1829 Expression* received_var = Expression::make_var_reference(no, location);
1831 if (is_coloneq && !any_new)
1832 error_at(location, "variables redeclared but no variable is new");
1834 Statement* s = Statement::make_tuple_receive_assignment(val_var,
1835 received_var,
1836 receive->channel(),
1837 location);
1839 if (!this->gogo_->in_global_scope())
1840 this->gogo_->add_statement(s);
1841 else if (!val_no->is_sink())
1843 if (val_no->is_variable())
1844 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1846 else if (!no->is_sink())
1848 if (no->is_variable())
1849 no->var_value()->add_preinit_statement(this->gogo_, s);
1851 else
1853 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1854 NULL, location);
1855 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1858 return true;
1861 // See if we need to initialize a pair of values from a type guard
1862 // expression. This returns true if we have set up the variables and
1863 // the initialization.
1865 bool
1866 Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
1867 Type* type, Expression* expr,
1868 bool is_coloneq, Location location)
1870 Type_guard_expression* type_guard = expr->type_guard_expression();
1871 if (type_guard == NULL)
1872 return false;
1873 if (vars->size() != 2)
1874 return false;
1876 // This is a type guard expression which is being assigned to two
1877 // variables. Declare the variables, and then assign the results of
1878 // the type guard.
1879 bool any_new = false;
1880 Typed_identifier_list::const_iterator p = vars->begin();
1881 Type* var_type = type;
1882 if (var_type == NULL)
1883 var_type = type_guard->type();
1884 Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1885 &any_new, NULL, NULL);
1886 Expression* val_var = Expression::make_var_reference(val_no, location);
1888 ++p;
1889 var_type = type;
1890 if (var_type == NULL)
1891 var_type = Type::lookup_bool_type();
1892 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1893 &any_new, NULL, NULL);
1894 Expression* ok_var = Expression::make_var_reference(no, location);
1896 Expression* texpr = type_guard->expr();
1897 Type* t = type_guard->type();
1898 Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
1899 texpr, t,
1900 location);
1902 if (is_coloneq && !any_new)
1903 error_at(location, "variables redeclared but no variable is new");
1905 if (!this->gogo_->in_global_scope())
1906 this->gogo_->add_statement(s);
1907 else if (!val_no->is_sink())
1909 if (val_no->is_variable())
1910 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1912 else if (!no->is_sink())
1914 if (no->is_variable())
1915 no->var_value()->add_preinit_statement(this->gogo_, s);
1917 else
1919 Named_object* dummy = this->create_dummy_global(type, NULL, location);
1920 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1923 return true;
1926 // Create a single variable. If IS_COLONEQ is true, we permit
1927 // redeclarations in the same block, and we set *IS_NEW when we find a
1928 // new variable which is not a redeclaration.
1930 Named_object*
1931 Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
1932 bool is_coloneq, bool type_from_init, bool* is_new,
1933 Expression_list* vars, Expression_list* vals)
1935 Location location = tid.location();
1937 if (Gogo::is_sink_name(tid.name()))
1939 if (!type_from_init && init != NULL)
1941 if (this->gogo_->in_global_scope())
1942 return this->create_dummy_global(type, init, location);
1943 else if (type == NULL)
1944 this->gogo_->add_statement(Statement::make_statement(init, true));
1945 else
1947 // With both a type and an initializer, create a dummy
1948 // variable so that we will check whether the
1949 // initializer can be assigned to the type.
1950 Variable* var = new Variable(type, init, false, false, false,
1951 location);
1952 var->set_is_used();
1953 static int count;
1954 char buf[30];
1955 snprintf(buf, sizeof buf, "sink$%d", count);
1956 ++count;
1957 return this->gogo_->add_variable(buf, var);
1960 if (type != NULL)
1961 this->gogo_->add_type_to_verify(type);
1962 return this->gogo_->add_sink();
1965 if (is_coloneq)
1967 Named_object* no = this->gogo_->lookup_in_block(tid.name());
1968 if (no != NULL
1969 && (no->is_variable() || no->is_result_variable()))
1971 // INIT may be NULL even when IS_COLONEQ is true for cases
1972 // like v, ok := x.(int).
1973 if (!type_from_init && init != NULL)
1975 go_assert(vars != NULL && vals != NULL);
1976 vars->push_back(Expression::make_var_reference(no, location));
1977 vals->push_back(init);
1979 return no;
1982 *is_new = true;
1983 Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
1984 false, false, location);
1985 Named_object* no = this->gogo_->add_variable(tid.name(), var);
1986 if (!no->is_variable())
1988 // The name is already defined, so we just gave an error.
1989 return this->gogo_->add_sink();
1991 return no;
1994 // Create a dummy global variable to force an initializer to be run in
1995 // the right place. This is used when a sink variable is initialized
1996 // at global scope.
1998 Named_object*
1999 Parse::create_dummy_global(Type* type, Expression* init,
2000 Location location)
2002 if (type == NULL && init == NULL)
2003 type = Type::lookup_bool_type();
2004 Variable* var = new Variable(type, init, true, false, false, location);
2005 static int count;
2006 char buf[30];
2007 snprintf(buf, sizeof buf, "_.%d", count);
2008 ++count;
2009 return this->gogo_->add_variable(buf, var);
2012 // Finish the variable initialization by executing any assignments to
2013 // existing variables when using :=. These must be done as a tuple
2014 // assignment in case of something like n, a, b := 1, b, a.
2016 void
2017 Parse::finish_init_vars(Expression_list* vars, Expression_list* vals,
2018 Location location)
2020 if (vars->empty())
2022 delete vars;
2023 delete vals;
2025 else if (vars->size() == 1)
2027 go_assert(!this->gogo_->in_global_scope());
2028 this->gogo_->add_statement(Statement::make_assignment(vars->front(),
2029 vals->front(),
2030 location));
2031 delete vars;
2032 delete vals;
2034 else
2036 go_assert(!this->gogo_->in_global_scope());
2037 this->gogo_->add_statement(Statement::make_tuple_assignment(vars, vals,
2038 location));
2042 // SimpleVarDecl = identifier ":=" Expression .
2044 // We've already seen the identifier.
2046 // FIXME: We also have to implement
2047 // IdentifierList ":=" ExpressionList
2048 // In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
2049 // tuple assignments here as well.
2051 // If MAY_BE_COMPOSITE_LIT is true, the expression on the right hand
2052 // side may be a composite literal.
2054 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
2055 // RangeClause.
2057 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
2058 // guard (var := expr.("type") using the literal keyword "type").
2060 void
2061 Parse::simple_var_decl_or_assignment(const std::string& name,
2062 Location location,
2063 bool may_be_composite_lit,
2064 Range_clause* p_range_clause,
2065 Type_switch* p_type_switch)
2067 Typed_identifier_list til;
2068 til.push_back(Typed_identifier(name, NULL, location));
2070 // We've seen one identifier. If we see a comma now, this could be
2071 // "a, *p = 1, 2".
2072 if (this->peek_token()->is_op(OPERATOR_COMMA))
2074 go_assert(p_type_switch == NULL);
2075 while (true)
2077 const Token* token = this->advance_token();
2078 if (!token->is_identifier())
2079 break;
2081 std::string id = token->identifier();
2082 bool is_id_exported = token->is_identifier_exported();
2083 Location id_location = token->location();
2085 token = this->advance_token();
2086 if (!token->is_op(OPERATOR_COMMA))
2088 if (token->is_op(OPERATOR_COLONEQ))
2090 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2091 til.push_back(Typed_identifier(id, NULL, location));
2093 else
2094 this->unget_token(Token::make_identifier_token(id,
2095 is_id_exported,
2096 id_location));
2097 break;
2100 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2101 til.push_back(Typed_identifier(id, NULL, location));
2104 // We have a comma separated list of identifiers in TIL. If the
2105 // next token is COLONEQ, then this is a simple var decl, and we
2106 // have the complete list of identifiers. If the next token is
2107 // not COLONEQ, then the only valid parse is a tuple assignment.
2108 // The list of identifiers we have so far is really a list of
2109 // expressions. There are more expressions following.
2111 if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
2113 Expression_list* exprs = new Expression_list;
2114 for (Typed_identifier_list::const_iterator p = til.begin();
2115 p != til.end();
2116 ++p)
2117 exprs->push_back(this->id_to_expression(p->name(),
2118 p->location()));
2120 Expression_list* more_exprs =
2121 this->expression_list(NULL, true, may_be_composite_lit);
2122 for (Expression_list::const_iterator p = more_exprs->begin();
2123 p != more_exprs->end();
2124 ++p)
2125 exprs->push_back(*p);
2126 delete more_exprs;
2128 this->tuple_assignment(exprs, may_be_composite_lit, p_range_clause);
2129 return;
2133 go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
2134 const Token* token = this->advance_token();
2136 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
2138 this->range_clause_decl(&til, p_range_clause);
2139 return;
2142 Expression_list* init;
2143 if (p_type_switch == NULL)
2144 init = this->expression_list(NULL, false, may_be_composite_lit);
2145 else
2147 bool is_type_switch = false;
2148 Expression* expr = this->expression(PRECEDENCE_NORMAL, false,
2149 may_be_composite_lit,
2150 &is_type_switch, NULL);
2151 if (is_type_switch)
2153 p_type_switch->found = true;
2154 p_type_switch->name = name;
2155 p_type_switch->location = location;
2156 p_type_switch->expr = expr;
2157 return;
2160 if (!this->peek_token()->is_op(OPERATOR_COMMA))
2162 init = new Expression_list();
2163 init->push_back(expr);
2165 else
2167 this->advance_token();
2168 init = this->expression_list(expr, false, may_be_composite_lit);
2172 this->init_vars(&til, NULL, init, true, location);
2175 // FunctionDecl = "func" identifier Signature [ Block ] .
2176 // MethodDecl = "func" Receiver identifier Signature [ Block ] .
2178 // Deprecated gcc extension:
2179 // FunctionDecl = "func" identifier Signature
2180 // __asm__ "(" string_lit ")" .
2181 // This extension means a function whose real name is the identifier
2182 // inside the asm. This extension will be removed at some future
2183 // date. It has been replaced with //extern comments.
2185 // SAW_NOINTERFACE is true if we saw a magic //go:nointerface comment,
2186 // which means that we omit the method from the type descriptor.
2188 void
2189 Parse::function_decl(bool saw_nointerface)
2191 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2192 Location location = this->location();
2193 std::string extern_name = this->lex_->extern_name();
2194 const Token* token = this->advance_token();
2196 Typed_identifier* rec = NULL;
2197 if (token->is_op(OPERATOR_LPAREN))
2199 rec = this->receiver();
2200 token = this->peek_token();
2202 else if (saw_nointerface)
2204 warning_at(location, 0,
2205 "ignoring magic //go:nointerface comment before non-method");
2206 saw_nointerface = false;
2209 if (!token->is_identifier())
2211 error_at(this->location(), "expected function name");
2212 return;
2215 std::string name =
2216 this->gogo_->pack_hidden_name(token->identifier(),
2217 token->is_identifier_exported());
2219 this->advance_token();
2221 Function_type* fntype = this->signature(rec, this->location());
2223 Named_object* named_object = NULL;
2225 if (this->peek_token()->is_keyword(KEYWORD_ASM))
2227 if (!this->advance_token()->is_op(OPERATOR_LPAREN))
2229 error_at(this->location(), "expected %<(%>");
2230 return;
2232 token = this->advance_token();
2233 if (!token->is_string())
2235 error_at(this->location(), "expected string");
2236 return;
2238 std::string asm_name = token->string_value();
2239 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
2241 error_at(this->location(), "expected %<)%>");
2242 return;
2244 this->advance_token();
2245 if (!Gogo::is_sink_name(name))
2247 named_object = this->gogo_->declare_function(name, fntype, location);
2248 if (named_object->is_function_declaration())
2249 named_object->func_declaration_value()->set_asm_name(asm_name);
2253 // Check for the easy error of a newline before the opening brace.
2254 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
2256 Location semi_loc = this->location();
2257 if (this->advance_token()->is_op(OPERATOR_LCURLY))
2258 error_at(this->location(),
2259 "unexpected semicolon or newline before %<{%>");
2260 else
2261 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
2262 semi_loc));
2265 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2267 if (named_object == NULL && !Gogo::is_sink_name(name))
2269 if (fntype == NULL)
2270 this->gogo_->add_erroneous_name(name);
2271 else
2273 named_object = this->gogo_->declare_function(name, fntype,
2274 location);
2275 if (!extern_name.empty()
2276 && named_object->is_function_declaration())
2278 Function_declaration* fd =
2279 named_object->func_declaration_value();
2280 fd->set_asm_name(extern_name);
2285 if (saw_nointerface)
2286 warning_at(location, 0,
2287 ("ignoring magic //go:nointerface comment "
2288 "before declaration"));
2290 else
2292 bool hold_is_erroneous_function = this->is_erroneous_function_;
2293 if (fntype == NULL)
2295 fntype = Type::make_function_type(NULL, NULL, NULL, location);
2296 this->is_erroneous_function_ = true;
2297 if (!Gogo::is_sink_name(name))
2298 this->gogo_->add_erroneous_name(name);
2299 name = this->gogo_->pack_hidden_name("_", false);
2301 named_object = this->gogo_->start_function(name, fntype, true, location);
2302 Location end_loc = this->block();
2303 this->gogo_->finish_function(end_loc);
2304 if (saw_nointerface
2305 && !this->is_erroneous_function_
2306 && named_object->is_function())
2307 named_object->func_value()->set_nointerface();
2308 this->is_erroneous_function_ = hold_is_erroneous_function;
2312 // Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
2313 // BaseTypeName = identifier .
2315 Typed_identifier*
2316 Parse::receiver()
2318 go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
2320 std::string name;
2321 const Token* token = this->advance_token();
2322 Location location = token->location();
2323 if (!token->is_op(OPERATOR_MULT))
2325 if (!token->is_identifier())
2327 error_at(this->location(), "method has no receiver");
2328 this->gogo_->mark_locals_used();
2329 while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2330 token = this->advance_token();
2331 if (!token->is_eof())
2332 this->advance_token();
2333 return NULL;
2335 name = token->identifier();
2336 bool is_exported = token->is_identifier_exported();
2337 token = this->advance_token();
2338 if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN))
2340 // An identifier followed by something other than a dot or a
2341 // right parenthesis must be a receiver name followed by a
2342 // type.
2343 name = this->gogo_->pack_hidden_name(name, is_exported);
2345 else
2347 // This must be a type name.
2348 this->unget_token(Token::make_identifier_token(name, is_exported,
2349 location));
2350 token = this->peek_token();
2351 name.clear();
2355 // Here the receiver name is in NAME (it is empty if the receiver is
2356 // unnamed) and TOKEN is the first token in the type.
2358 bool is_pointer = false;
2359 if (token->is_op(OPERATOR_MULT))
2361 is_pointer = true;
2362 token = this->advance_token();
2365 if (!token->is_identifier())
2367 error_at(this->location(), "expected receiver name or type");
2368 this->gogo_->mark_locals_used();
2369 int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0;
2370 while (!token->is_eof())
2372 token = this->advance_token();
2373 if (token->is_op(OPERATOR_LPAREN))
2374 ++c;
2375 else if (token->is_op(OPERATOR_RPAREN))
2377 if (c == 0)
2378 break;
2379 --c;
2382 if (!token->is_eof())
2383 this->advance_token();
2384 return NULL;
2387 Type* type = this->type_name(true);
2389 if (is_pointer && !type->is_error_type())
2390 type = Type::make_pointer_type(type);
2392 if (this->peek_token()->is_op(OPERATOR_RPAREN))
2393 this->advance_token();
2394 else
2396 if (this->peek_token()->is_op(OPERATOR_COMMA))
2397 error_at(this->location(), "method has multiple receivers");
2398 else
2399 error_at(this->location(), "expected %<)%>");
2400 this->gogo_->mark_locals_used();
2401 while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2402 token = this->advance_token();
2403 if (!token->is_eof())
2404 this->advance_token();
2405 return NULL;
2408 return new Typed_identifier(name, type, location);
2411 // Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2412 // Literal = BasicLit | CompositeLit | FunctionLit .
2413 // BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2415 // If MAY_BE_SINK is true, this operand may be "_".
2417 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
2418 // if the entire expression is in parentheses.
2420 Expression*
2421 Parse::operand(bool may_be_sink, bool* is_parenthesized)
2423 const Token* token = this->peek_token();
2424 Expression* ret;
2425 switch (token->classification())
2427 case Token::TOKEN_IDENTIFIER:
2429 Location location = token->location();
2430 std::string id = token->identifier();
2431 bool is_exported = token->is_identifier_exported();
2432 std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2434 Named_object* in_function;
2435 Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2437 Package* package = NULL;
2438 if (named_object != NULL && named_object->is_package())
2440 if (!this->advance_token()->is_op(OPERATOR_DOT)
2441 || !this->advance_token()->is_identifier())
2443 error_at(location, "unexpected reference to package");
2444 return Expression::make_error(location);
2446 package = named_object->package_value();
2447 package->set_used();
2448 id = this->peek_token()->identifier();
2449 is_exported = this->peek_token()->is_identifier_exported();
2450 packed = this->gogo_->pack_hidden_name(id, is_exported);
2451 named_object = package->lookup(packed);
2452 location = this->location();
2453 go_assert(in_function == NULL);
2456 this->advance_token();
2458 if (named_object != NULL
2459 && named_object->is_type()
2460 && !named_object->type_value()->is_visible())
2462 go_assert(package != NULL);
2463 error_at(location, "invalid reference to hidden type %<%s.%s%>",
2464 Gogo::message_name(package->package_name()).c_str(),
2465 Gogo::message_name(id).c_str());
2466 return Expression::make_error(location);
2470 if (named_object == NULL)
2472 if (package != NULL)
2474 std::string n1 = Gogo::message_name(package->package_name());
2475 std::string n2 = Gogo::message_name(id);
2476 if (!is_exported)
2477 error_at(location,
2478 ("invalid reference to unexported identifier "
2479 "%<%s.%s%>"),
2480 n1.c_str(), n2.c_str());
2481 else
2482 error_at(location,
2483 "reference to undefined identifier %<%s.%s%>",
2484 n1.c_str(), n2.c_str());
2485 return Expression::make_error(location);
2488 named_object = this->gogo_->add_unknown_name(packed, location);
2491 if (in_function != NULL
2492 && in_function != this->gogo_->current_function()
2493 && (named_object->is_variable()
2494 || named_object->is_result_variable()))
2495 return this->enclosing_var_reference(in_function, named_object,
2496 location);
2498 switch (named_object->classification())
2500 case Named_object::NAMED_OBJECT_CONST:
2501 return Expression::make_const_reference(named_object, location);
2502 case Named_object::NAMED_OBJECT_TYPE:
2503 return Expression::make_type(named_object->type_value(), location);
2504 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2506 Type* t = Type::make_forward_declaration(named_object);
2507 return Expression::make_type(t, location);
2509 case Named_object::NAMED_OBJECT_VAR:
2510 case Named_object::NAMED_OBJECT_RESULT_VAR:
2511 this->mark_var_used(named_object);
2512 return Expression::make_var_reference(named_object, location);
2513 case Named_object::NAMED_OBJECT_SINK:
2514 if (may_be_sink)
2515 return Expression::make_sink(location);
2516 else
2518 error_at(location, "cannot use _ as value");
2519 return Expression::make_error(location);
2521 case Named_object::NAMED_OBJECT_FUNC:
2522 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2523 return Expression::make_func_reference(named_object, NULL,
2524 location);
2525 case Named_object::NAMED_OBJECT_UNKNOWN:
2527 Unknown_expression* ue =
2528 Expression::make_unknown_reference(named_object, location);
2529 if (this->is_erroneous_function_)
2530 ue->set_no_error_message();
2531 return ue;
2533 case Named_object::NAMED_OBJECT_ERRONEOUS:
2534 return Expression::make_error(location);
2535 default:
2536 go_unreachable();
2539 go_unreachable();
2541 case Token::TOKEN_STRING:
2542 ret = Expression::make_string(token->string_value(), token->location());
2543 this->advance_token();
2544 return ret;
2546 case Token::TOKEN_CHARACTER:
2547 ret = Expression::make_character(token->character_value(), NULL,
2548 token->location());
2549 this->advance_token();
2550 return ret;
2552 case Token::TOKEN_INTEGER:
2553 ret = Expression::make_integer(token->integer_value(), NULL,
2554 token->location());
2555 this->advance_token();
2556 return ret;
2558 case Token::TOKEN_FLOAT:
2559 ret = Expression::make_float(token->float_value(), NULL,
2560 token->location());
2561 this->advance_token();
2562 return ret;
2564 case Token::TOKEN_IMAGINARY:
2566 mpfr_t zero;
2567 mpfr_init_set_ui(zero, 0, GMP_RNDN);
2568 ret = Expression::make_complex(&zero, token->imaginary_value(),
2569 NULL, token->location());
2570 mpfr_clear(zero);
2571 this->advance_token();
2572 return ret;
2575 case Token::TOKEN_KEYWORD:
2576 switch (token->keyword())
2578 case KEYWORD_FUNC:
2579 return this->function_lit();
2580 case KEYWORD_CHAN:
2581 case KEYWORD_INTERFACE:
2582 case KEYWORD_MAP:
2583 case KEYWORD_STRUCT:
2585 Location location = token->location();
2586 return Expression::make_type(this->type(), location);
2588 default:
2589 break;
2591 break;
2593 case Token::TOKEN_OPERATOR:
2594 if (token->is_op(OPERATOR_LPAREN))
2596 this->advance_token();
2597 ret = this->expression(PRECEDENCE_NORMAL, may_be_sink, true, NULL,
2598 NULL);
2599 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2600 error_at(this->location(), "missing %<)%>");
2601 else
2602 this->advance_token();
2603 if (is_parenthesized != NULL)
2604 *is_parenthesized = true;
2605 return ret;
2607 else if (token->is_op(OPERATOR_LSQUARE))
2609 // Here we call array_type directly, as this is the only
2610 // case where an ellipsis is permitted for an array type.
2611 Location location = token->location();
2612 return Expression::make_type(this->array_type(true), location);
2614 break;
2616 default:
2617 break;
2620 error_at(this->location(), "expected operand");
2621 return Expression::make_error(this->location());
2624 // Handle a reference to a variable in an enclosing function. We add
2625 // it to a list of such variables. We return a reference to a field
2626 // in a struct which will be passed on the static chain when calling
2627 // the current function.
2629 Expression*
2630 Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2631 Location location)
2633 go_assert(var->is_variable() || var->is_result_variable());
2635 this->mark_var_used(var);
2637 Named_object* this_function = this->gogo_->current_function();
2638 Named_object* closure = this_function->func_value()->closure_var();
2640 // The last argument to the Enclosing_var constructor is the index
2641 // of this variable in the closure. We add 1 to the current number
2642 // of enclosed variables, because the first field in the closure
2643 // points to the function code.
2644 Enclosing_var ev(var, in_function, this->enclosing_vars_.size() + 1);
2645 std::pair<Enclosing_vars::iterator, bool> ins =
2646 this->enclosing_vars_.insert(ev);
2647 if (ins.second)
2649 // This is a variable we have not seen before. Add a new field
2650 // to the closure type.
2651 this_function->func_value()->add_closure_field(var, location);
2654 Expression* closure_ref = Expression::make_var_reference(closure,
2655 location);
2656 closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location);
2658 // The closure structure holds pointers to the variables, so we need
2659 // to introduce an indirection.
2660 Expression* e = Expression::make_field_reference(closure_ref,
2661 ins.first->index(),
2662 location);
2663 e = Expression::make_unary(OPERATOR_MULT, e, location);
2664 return e;
2667 // CompositeLit = LiteralType LiteralValue .
2668 // LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
2669 // SliceType | MapType | TypeName .
2670 // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
2671 // ElementList = Element { "," Element } .
2672 // Element = [ Key ":" ] Value .
2673 // Key = FieldName | ElementIndex .
2674 // FieldName = identifier .
2675 // ElementIndex = Expression .
2676 // Value = Expression | LiteralValue .
2678 // We have already seen the type if there is one, and we are now
2679 // looking at the LiteralValue. The case "[" "..." "]" ElementType
2680 // will be seen here as an array type whose length is "nil". The
2681 // DEPTH parameter is non-zero if this is an embedded composite
2682 // literal and the type was omitted. It gives the number of steps up
2683 // to the type which was provided. E.g., in [][]int{{1}} it will be
2684 // 1. In [][][]int{{{1}}} it will be 2.
2686 Expression*
2687 Parse::composite_lit(Type* type, int depth, Location location)
2689 go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2690 this->advance_token();
2692 if (this->peek_token()->is_op(OPERATOR_RCURLY))
2694 this->advance_token();
2695 return Expression::make_composite_literal(type, depth, false, NULL,
2696 location);
2699 bool has_keys = false;
2700 Expression_list* vals = new Expression_list;
2701 while (true)
2703 Expression* val;
2704 bool is_type_omitted = false;
2706 const Token* token = this->peek_token();
2708 if (token->is_identifier())
2710 std::string identifier = token->identifier();
2711 bool is_exported = token->is_identifier_exported();
2712 Location location = token->location();
2714 if (this->advance_token()->is_op(OPERATOR_COLON))
2716 // This may be a field name. We don't know for sure--it
2717 // could also be an expression for an array index. We
2718 // don't want to parse it as an expression because may
2719 // trigger various errors, e.g., if this identifier
2720 // happens to be the name of a package.
2721 Gogo* gogo = this->gogo_;
2722 val = this->id_to_expression(gogo->pack_hidden_name(identifier,
2723 is_exported),
2724 location);
2726 else
2728 this->unget_token(Token::make_identifier_token(identifier,
2729 is_exported,
2730 location));
2731 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
2732 NULL);
2735 else if (!token->is_op(OPERATOR_LCURLY))
2736 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
2737 else
2739 // This must be a composite literal inside another composite
2740 // literal, with the type omitted for the inner one.
2741 val = this->composite_lit(type, depth + 1, token->location());
2742 is_type_omitted = true;
2745 token = this->peek_token();
2746 if (!token->is_op(OPERATOR_COLON))
2748 if (has_keys)
2749 vals->push_back(NULL);
2751 else
2753 if (is_type_omitted && !val->is_error_expression())
2755 error_at(this->location(), "unexpected %<:%>");
2756 val = Expression::make_error(this->location());
2759 this->advance_token();
2761 if (!has_keys && !vals->empty())
2763 Expression_list* newvals = new Expression_list;
2764 for (Expression_list::const_iterator p = vals->begin();
2765 p != vals->end();
2766 ++p)
2768 newvals->push_back(NULL);
2769 newvals->push_back(*p);
2771 delete vals;
2772 vals = newvals;
2774 has_keys = true;
2776 if (val->unknown_expression() != NULL)
2777 val->unknown_expression()->set_is_composite_literal_key();
2779 vals->push_back(val);
2781 if (!token->is_op(OPERATOR_LCURLY))
2782 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
2783 else
2785 // This must be a composite literal inside another
2786 // composite literal, with the type omitted for the
2787 // inner one.
2788 val = this->composite_lit(type, depth + 1, token->location());
2791 token = this->peek_token();
2794 vals->push_back(val);
2796 if (token->is_op(OPERATOR_COMMA))
2798 if (this->advance_token()->is_op(OPERATOR_RCURLY))
2800 this->advance_token();
2801 break;
2804 else if (token->is_op(OPERATOR_RCURLY))
2806 this->advance_token();
2807 break;
2809 else
2811 if (token->is_op(OPERATOR_SEMICOLON))
2812 error_at(this->location(),
2813 "need trailing comma before newline in composite literal");
2814 else
2815 error_at(this->location(), "expected %<,%> or %<}%>");
2817 this->gogo_->mark_locals_used();
2818 int depth = 0;
2819 while (!token->is_eof()
2820 && (depth > 0 || !token->is_op(OPERATOR_RCURLY)))
2822 if (token->is_op(OPERATOR_LCURLY))
2823 ++depth;
2824 else if (token->is_op(OPERATOR_RCURLY))
2825 --depth;
2826 token = this->advance_token();
2828 if (token->is_op(OPERATOR_RCURLY))
2829 this->advance_token();
2831 return Expression::make_error(location);
2835 return Expression::make_composite_literal(type, depth, has_keys, vals,
2836 location);
2839 // FunctionLit = "func" Signature Block .
2841 Expression*
2842 Parse::function_lit()
2844 Location location = this->location();
2845 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2846 this->advance_token();
2848 Enclosing_vars hold_enclosing_vars;
2849 hold_enclosing_vars.swap(this->enclosing_vars_);
2851 Function_type* type = this->signature(NULL, location);
2852 bool fntype_is_error = false;
2853 if (type == NULL)
2855 type = Type::make_function_type(NULL, NULL, NULL, location);
2856 fntype_is_error = true;
2859 // For a function literal, the next token must be a '{'. If we
2860 // don't see that, then we may have a type expression.
2861 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2862 return Expression::make_type(type, location);
2864 bool hold_is_erroneous_function = this->is_erroneous_function_;
2865 if (fntype_is_error)
2866 this->is_erroneous_function_ = true;
2868 Bc_stack* hold_break_stack = this->break_stack_;
2869 Bc_stack* hold_continue_stack = this->continue_stack_;
2870 this->break_stack_ = NULL;
2871 this->continue_stack_ = NULL;
2873 Named_object* no = this->gogo_->start_function("", type, true, location);
2875 Location end_loc = this->block();
2877 this->gogo_->finish_function(end_loc);
2879 if (this->break_stack_ != NULL)
2880 delete this->break_stack_;
2881 if (this->continue_stack_ != NULL)
2882 delete this->continue_stack_;
2883 this->break_stack_ = hold_break_stack;
2884 this->continue_stack_ = hold_continue_stack;
2886 this->is_erroneous_function_ = hold_is_erroneous_function;
2888 hold_enclosing_vars.swap(this->enclosing_vars_);
2890 Expression* closure = this->create_closure(no, &hold_enclosing_vars,
2891 location);
2893 return Expression::make_func_reference(no, closure, location);
2896 // Create a closure for the nested function FUNCTION. This is based
2897 // on ENCLOSING_VARS, which is a list of all variables defined in
2898 // enclosing functions and referenced from FUNCTION. A closure is the
2899 // address of a struct which point to the real function code and
2900 // contains the addresses of all the referenced variables. This
2901 // returns NULL if no closure is required.
2903 Expression*
2904 Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
2905 Location location)
2907 if (enclosing_vars->empty())
2908 return NULL;
2910 // Get the variables in order by their field index.
2912 size_t enclosing_var_count = enclosing_vars->size();
2913 std::vector<Enclosing_var> ev(enclosing_var_count);
2914 for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
2915 p != enclosing_vars->end();
2916 ++p)
2918 // Subtract 1 because index 0 is the function code.
2919 ev[p->index() - 1] = *p;
2922 // Build an initializer for a composite literal of the closure's
2923 // type.
2925 Named_object* enclosing_function = this->gogo_->current_function();
2926 Expression_list* initializer = new Expression_list;
2928 initializer->push_back(Expression::make_func_code_reference(function,
2929 location));
2931 for (size_t i = 0; i < enclosing_var_count; ++i)
2933 // Add 1 to i because the first field in the closure is a
2934 // pointer to the function code.
2935 go_assert(ev[i].index() == i + 1);
2936 Named_object* var = ev[i].var();
2937 Expression* ref;
2938 if (ev[i].in_function() == enclosing_function)
2939 ref = Expression::make_var_reference(var, location);
2940 else
2941 ref = this->enclosing_var_reference(ev[i].in_function(), var,
2942 location);
2943 Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
2944 location);
2945 initializer->push_back(refaddr);
2948 Named_object* closure_var = function->func_value()->closure_var();
2949 Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
2950 Expression* cv = Expression::make_struct_composite_literal(st, initializer,
2951 location);
2952 return Expression::make_heap_composite(cv, location);
2955 // PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
2957 // If MAY_BE_SINK is true, this expression may be "_".
2959 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
2960 // literal.
2962 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2963 // guard (var := expr.("type") using the literal keyword "type").
2965 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
2966 // if the entire expression is in parentheses.
2968 Expression*
2969 Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
2970 bool* is_type_switch, bool* is_parenthesized)
2972 Location start_loc = this->location();
2973 bool operand_is_parenthesized = false;
2974 bool whole_is_parenthesized = false;
2976 Expression* ret = this->operand(may_be_sink, &operand_is_parenthesized);
2978 whole_is_parenthesized = operand_is_parenthesized;
2980 // An unknown name followed by a curly brace must be a composite
2981 // literal, and the unknown name must be a type.
2982 if (may_be_composite_lit
2983 && !operand_is_parenthesized
2984 && ret->unknown_expression() != NULL
2985 && this->peek_token()->is_op(OPERATOR_LCURLY))
2987 Named_object* no = ret->unknown_expression()->named_object();
2988 Type* type = Type::make_forward_declaration(no);
2989 ret = Expression::make_type(type, ret->location());
2992 // We handle composite literals and type casts here, as it is the
2993 // easiest way to handle types which are in parentheses, as in
2994 // "((uint))(1)".
2995 if (ret->is_type_expression())
2997 if (this->peek_token()->is_op(OPERATOR_LCURLY))
2999 whole_is_parenthesized = false;
3000 if (!may_be_composite_lit)
3002 Type* t = ret->type();
3003 if (t->named_type() != NULL
3004 || t->forward_declaration_type() != NULL)
3005 error_at(start_loc,
3006 _("parentheses required around this composite literal "
3007 "to avoid parsing ambiguity"));
3009 else if (operand_is_parenthesized)
3010 error_at(start_loc,
3011 "cannot parenthesize type in composite literal");
3012 ret = this->composite_lit(ret->type(), 0, ret->location());
3014 else if (this->peek_token()->is_op(OPERATOR_LPAREN))
3016 whole_is_parenthesized = false;
3017 Location loc = this->location();
3018 this->advance_token();
3019 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
3020 NULL, NULL);
3021 if (this->peek_token()->is_op(OPERATOR_COMMA))
3022 this->advance_token();
3023 if (this->peek_token()->is_op(OPERATOR_ELLIPSIS))
3025 error_at(this->location(),
3026 "invalid use of %<...%> in type conversion");
3027 this->advance_token();
3029 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
3030 error_at(this->location(), "expected %<)%>");
3031 else
3032 this->advance_token();
3033 if (expr->is_error_expression())
3034 ret = expr;
3035 else
3037 Type* t = ret->type();
3038 if (t->classification() == Type::TYPE_ARRAY
3039 && t->array_type()->length() != NULL
3040 && t->array_type()->length()->is_nil_expression())
3042 error_at(ret->location(),
3043 "use of %<[...]%> outside of array literal");
3044 ret = Expression::make_error(loc);
3046 else
3047 ret = Expression::make_cast(t, expr, loc);
3052 while (true)
3054 const Token* token = this->peek_token();
3055 if (token->is_op(OPERATOR_LPAREN))
3057 whole_is_parenthesized = false;
3058 ret = this->call(this->verify_not_sink(ret));
3060 else if (token->is_op(OPERATOR_DOT))
3062 whole_is_parenthesized = false;
3063 ret = this->selector(this->verify_not_sink(ret), is_type_switch);
3064 if (is_type_switch != NULL && *is_type_switch)
3065 break;
3067 else if (token->is_op(OPERATOR_LSQUARE))
3069 whole_is_parenthesized = false;
3070 ret = this->index(this->verify_not_sink(ret));
3072 else
3073 break;
3076 if (whole_is_parenthesized && is_parenthesized != NULL)
3077 *is_parenthesized = true;
3079 return ret;
3082 // Selector = "." identifier .
3083 // TypeGuard = "." "(" QualifiedIdent ")" .
3085 // Note that Operand can expand to QualifiedIdent, which contains a
3086 // ".". That is handled directly in operand when it sees a package
3087 // name.
3089 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3090 // guard (var := expr.("type") using the literal keyword "type").
3092 Expression*
3093 Parse::selector(Expression* left, bool* is_type_switch)
3095 go_assert(this->peek_token()->is_op(OPERATOR_DOT));
3096 Location location = this->location();
3098 const Token* token = this->advance_token();
3099 if (token->is_identifier())
3101 // This could be a field in a struct, or a method in an
3102 // interface, or a method associated with a type. We can't know
3103 // which until we have seen all the types.
3104 std::string name =
3105 this->gogo_->pack_hidden_name(token->identifier(),
3106 token->is_identifier_exported());
3107 if (token->identifier() == "_")
3109 error_at(this->location(), "invalid use of %<_%>");
3110 name = this->gogo_->pack_hidden_name("blank", false);
3112 this->advance_token();
3113 return Expression::make_selector(left, name, location);
3115 else if (token->is_op(OPERATOR_LPAREN))
3117 this->advance_token();
3118 Type* type = NULL;
3119 if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
3120 type = this->type();
3121 else
3123 if (is_type_switch != NULL)
3124 *is_type_switch = true;
3125 else
3127 error_at(this->location(),
3128 "use of %<.(type)%> outside type switch");
3129 type = Type::make_error_type();
3131 this->advance_token();
3133 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
3134 error_at(this->location(), "missing %<)%>");
3135 else
3136 this->advance_token();
3137 if (is_type_switch != NULL && *is_type_switch)
3138 return left;
3139 return Expression::make_type_guard(left, type, location);
3141 else
3143 error_at(this->location(), "expected identifier or %<(%>");
3144 return left;
3148 // Index = "[" Expression "]" .
3149 // Slice = "[" Expression ":" [ Expression ] "]" .
3151 Expression*
3152 Parse::index(Expression* expr)
3154 Location location = this->location();
3155 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
3156 this->advance_token();
3158 Expression* start;
3159 if (!this->peek_token()->is_op(OPERATOR_COLON))
3160 start = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3161 else
3163 mpz_t zero;
3164 mpz_init_set_ui(zero, 0);
3165 start = Expression::make_integer(&zero, NULL, location);
3166 mpz_clear(zero);
3169 Expression* end = NULL;
3170 if (this->peek_token()->is_op(OPERATOR_COLON))
3172 // We use nil to indicate a missing high expression.
3173 if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3174 end = Expression::make_nil(this->location());
3175 else
3176 end = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3178 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
3179 error_at(this->location(), "missing %<]%>");
3180 else
3181 this->advance_token();
3182 return Expression::make_index(expr, start, end, location);
3185 // Call = "(" [ ArgumentList [ "," ] ] ")" .
3186 // ArgumentList = ExpressionList [ "..." ] .
3188 Expression*
3189 Parse::call(Expression* func)
3191 go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
3192 Expression_list* args = NULL;
3193 bool is_varargs = false;
3194 const Token* token = this->advance_token();
3195 if (!token->is_op(OPERATOR_RPAREN))
3197 args = this->expression_list(NULL, false, true);
3198 token = this->peek_token();
3199 if (token->is_op(OPERATOR_ELLIPSIS))
3201 is_varargs = true;
3202 token = this->advance_token();
3205 if (token->is_op(OPERATOR_COMMA))
3206 token = this->advance_token();
3207 if (!token->is_op(OPERATOR_RPAREN))
3208 error_at(this->location(), "missing %<)%>");
3209 else
3210 this->advance_token();
3211 if (func->is_error_expression())
3212 return func;
3213 return Expression::make_call(func, args, is_varargs, func->location());
3216 // Return an expression for a single unqualified identifier.
3218 Expression*
3219 Parse::id_to_expression(const std::string& name, Location location)
3221 Named_object* in_function;
3222 Named_object* named_object = this->gogo_->lookup(name, &in_function);
3223 if (named_object == NULL)
3224 named_object = this->gogo_->add_unknown_name(name, location);
3226 if (in_function != NULL
3227 && in_function != this->gogo_->current_function()
3228 && (named_object->is_variable() || named_object->is_result_variable()))
3229 return this->enclosing_var_reference(in_function, named_object,
3230 location);
3232 switch (named_object->classification())
3234 case Named_object::NAMED_OBJECT_CONST:
3235 return Expression::make_const_reference(named_object, location);
3236 case Named_object::NAMED_OBJECT_VAR:
3237 case Named_object::NAMED_OBJECT_RESULT_VAR:
3238 this->mark_var_used(named_object);
3239 return Expression::make_var_reference(named_object, location);
3240 case Named_object::NAMED_OBJECT_SINK:
3241 return Expression::make_sink(location);
3242 case Named_object::NAMED_OBJECT_FUNC:
3243 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3244 return Expression::make_func_reference(named_object, NULL, location);
3245 case Named_object::NAMED_OBJECT_UNKNOWN:
3247 Unknown_expression* ue =
3248 Expression::make_unknown_reference(named_object, location);
3249 if (this->is_erroneous_function_)
3250 ue->set_no_error_message();
3251 return ue;
3253 case Named_object::NAMED_OBJECT_PACKAGE:
3254 case Named_object::NAMED_OBJECT_TYPE:
3255 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3257 // These cases can arise for a field name in a composite
3258 // literal.
3259 Unknown_expression* ue =
3260 Expression::make_unknown_reference(named_object, location);
3261 if (this->is_erroneous_function_)
3262 ue->set_no_error_message();
3263 return ue;
3265 case Named_object::NAMED_OBJECT_ERRONEOUS:
3266 return Expression::make_error(location);
3267 default:
3268 error_at(this->location(), "unexpected type of identifier");
3269 return Expression::make_error(location);
3273 // Expression = UnaryExpr { binary_op Expression } .
3275 // PRECEDENCE is the precedence of the current operator.
3277 // If MAY_BE_SINK is true, this expression may be "_".
3279 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3280 // literal.
3282 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3283 // guard (var := expr.("type") using the literal keyword "type").
3285 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3286 // if the entire expression is in parentheses.
3288 Expression*
3289 Parse::expression(Precedence precedence, bool may_be_sink,
3290 bool may_be_composite_lit, bool* is_type_switch,
3291 bool *is_parenthesized)
3293 Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
3294 is_type_switch, is_parenthesized);
3296 while (true)
3298 if (is_type_switch != NULL && *is_type_switch)
3299 return left;
3301 const Token* token = this->peek_token();
3302 if (token->classification() != Token::TOKEN_OPERATOR)
3304 // Not a binary_op.
3305 return left;
3308 Precedence right_precedence;
3309 switch (token->op())
3311 case OPERATOR_OROR:
3312 right_precedence = PRECEDENCE_OROR;
3313 break;
3314 case OPERATOR_ANDAND:
3315 right_precedence = PRECEDENCE_ANDAND;
3316 break;
3317 case OPERATOR_EQEQ:
3318 case OPERATOR_NOTEQ:
3319 case OPERATOR_LT:
3320 case OPERATOR_LE:
3321 case OPERATOR_GT:
3322 case OPERATOR_GE:
3323 right_precedence = PRECEDENCE_RELOP;
3324 break;
3325 case OPERATOR_PLUS:
3326 case OPERATOR_MINUS:
3327 case OPERATOR_OR:
3328 case OPERATOR_XOR:
3329 right_precedence = PRECEDENCE_ADDOP;
3330 break;
3331 case OPERATOR_MULT:
3332 case OPERATOR_DIV:
3333 case OPERATOR_MOD:
3334 case OPERATOR_LSHIFT:
3335 case OPERATOR_RSHIFT:
3336 case OPERATOR_AND:
3337 case OPERATOR_BITCLEAR:
3338 right_precedence = PRECEDENCE_MULOP;
3339 break;
3340 default:
3341 right_precedence = PRECEDENCE_INVALID;
3342 break;
3345 if (right_precedence == PRECEDENCE_INVALID)
3347 // Not a binary_op.
3348 return left;
3351 if (is_parenthesized != NULL)
3352 *is_parenthesized = false;
3354 Operator op = token->op();
3355 Location binop_location = token->location();
3357 if (precedence >= right_precedence)
3359 // We've already seen A * B, and we see + C. We want to
3360 // return so that A * B becomes a group.
3361 return left;
3364 this->advance_token();
3366 left = this->verify_not_sink(left);
3367 Expression* right = this->expression(right_precedence, false,
3368 may_be_composite_lit,
3369 NULL, NULL);
3370 left = Expression::make_binary(op, left, right, binop_location);
3374 bool
3375 Parse::expression_may_start_here()
3377 const Token* token = this->peek_token();
3378 switch (token->classification())
3380 case Token::TOKEN_INVALID:
3381 case Token::TOKEN_EOF:
3382 return false;
3383 case Token::TOKEN_KEYWORD:
3384 switch (token->keyword())
3386 case KEYWORD_CHAN:
3387 case KEYWORD_FUNC:
3388 case KEYWORD_MAP:
3389 case KEYWORD_STRUCT:
3390 case KEYWORD_INTERFACE:
3391 return true;
3392 default:
3393 return false;
3395 case Token::TOKEN_IDENTIFIER:
3396 return true;
3397 case Token::TOKEN_STRING:
3398 return true;
3399 case Token::TOKEN_OPERATOR:
3400 switch (token->op())
3402 case OPERATOR_PLUS:
3403 case OPERATOR_MINUS:
3404 case OPERATOR_NOT:
3405 case OPERATOR_XOR:
3406 case OPERATOR_MULT:
3407 case OPERATOR_CHANOP:
3408 case OPERATOR_AND:
3409 case OPERATOR_LPAREN:
3410 case OPERATOR_LSQUARE:
3411 return true;
3412 default:
3413 return false;
3415 case Token::TOKEN_CHARACTER:
3416 case Token::TOKEN_INTEGER:
3417 case Token::TOKEN_FLOAT:
3418 case Token::TOKEN_IMAGINARY:
3419 return true;
3420 default:
3421 go_unreachable();
3425 // UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3427 // If MAY_BE_SINK is true, this expression may be "_".
3429 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3430 // literal.
3432 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3433 // guard (var := expr.("type") using the literal keyword "type").
3435 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3436 // if the entire expression is in parentheses.
3438 Expression*
3439 Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3440 bool* is_type_switch, bool* is_parenthesized)
3442 const Token* token = this->peek_token();
3444 // There is a complex parse for <- chan. The choices are
3445 // Convert x to type <- chan int:
3446 // (<- chan int)(x)
3447 // Receive from (x converted to type chan <- chan int):
3448 // (<- chan <- chan int (x))
3449 // Convert x to type <- chan (<- chan int).
3450 // (<- chan <- chan int)(x)
3451 if (token->is_op(OPERATOR_CHANOP))
3453 Location location = token->location();
3454 if (this->advance_token()->is_keyword(KEYWORD_CHAN))
3456 Expression* expr = this->primary_expr(false, may_be_composite_lit,
3457 NULL, NULL);
3458 if (expr->is_error_expression())
3459 return expr;
3460 else if (!expr->is_type_expression())
3461 return Expression::make_receive(expr, location);
3462 else
3464 if (expr->type()->is_error_type())
3465 return expr;
3467 // We picked up "chan TYPE", but it is not a type
3468 // conversion.
3469 Channel_type* ct = expr->type()->channel_type();
3470 if (ct == NULL)
3472 // This is probably impossible.
3473 error_at(location, "expected channel type");
3474 return Expression::make_error(location);
3476 else if (ct->may_receive())
3478 // <- chan TYPE.
3479 Type* t = Type::make_channel_type(false, true,
3480 ct->element_type());
3481 return Expression::make_type(t, location);
3483 else
3485 // <- chan <- TYPE. Because we skipped the leading
3486 // <-, we parsed this as chan <- TYPE. With the
3487 // leading <-, we parse it as <- chan (<- TYPE).
3488 Type *t = this->reassociate_chan_direction(ct, location);
3489 return Expression::make_type(t, location);
3494 this->unget_token(Token::make_operator_token(OPERATOR_CHANOP, location));
3495 token = this->peek_token();
3498 if (token->is_op(OPERATOR_PLUS)
3499 || token->is_op(OPERATOR_MINUS)
3500 || token->is_op(OPERATOR_NOT)
3501 || token->is_op(OPERATOR_XOR)
3502 || token->is_op(OPERATOR_CHANOP)
3503 || token->is_op(OPERATOR_MULT)
3504 || token->is_op(OPERATOR_AND))
3506 Location location = token->location();
3507 Operator op = token->op();
3508 this->advance_token();
3510 Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL,
3511 NULL);
3512 if (expr->is_error_expression())
3514 else if (op == OPERATOR_MULT && expr->is_type_expression())
3515 expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3516 location);
3517 else if (op == OPERATOR_AND && expr->is_composite_literal())
3518 expr = Expression::make_heap_composite(expr, location);
3519 else if (op != OPERATOR_CHANOP)
3520 expr = Expression::make_unary(op, expr, location);
3521 else
3522 expr = Expression::make_receive(expr, location);
3523 return expr;
3525 else
3526 return this->primary_expr(may_be_sink, may_be_composite_lit,
3527 is_type_switch, is_parenthesized);
3530 // This is called for the obscure case of
3531 // (<- chan <- chan int)(x)
3532 // In unary_expr we remove the leading <- and parse the remainder,
3533 // which gives us
3534 // chan <- (chan int)
3535 // When we add the leading <- back in, we really want
3536 // <- chan (<- chan int)
3537 // This means that we need to reassociate.
3539 Type*
3540 Parse::reassociate_chan_direction(Channel_type *ct, Location location)
3542 Channel_type* ele = ct->element_type()->channel_type();
3543 if (ele == NULL)
3545 error_at(location, "parse error");
3546 return Type::make_error_type();
3548 Type* sub = ele;
3549 if (ele->may_send())
3550 sub = Type::make_channel_type(false, true, ele->element_type());
3551 else
3552 sub = this->reassociate_chan_direction(ele, location);
3553 return Type::make_channel_type(false, true, sub);
3556 // Statement =
3557 // Declaration | LabeledStmt | SimpleStmt |
3558 // GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3559 // FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3560 // DeferStmt .
3562 // LABEL is the label of this statement if it has one.
3564 void
3565 Parse::statement(Label* label)
3567 const Token* token = this->peek_token();
3568 switch (token->classification())
3570 case Token::TOKEN_KEYWORD:
3572 switch (token->keyword())
3574 case KEYWORD_CONST:
3575 case KEYWORD_TYPE:
3576 case KEYWORD_VAR:
3577 this->declaration();
3578 break;
3579 case KEYWORD_FUNC:
3580 case KEYWORD_MAP:
3581 case KEYWORD_STRUCT:
3582 case KEYWORD_INTERFACE:
3583 this->simple_stat(true, NULL, NULL, NULL);
3584 break;
3585 case KEYWORD_GO:
3586 case KEYWORD_DEFER:
3587 this->go_or_defer_stat();
3588 break;
3589 case KEYWORD_RETURN:
3590 this->return_stat();
3591 break;
3592 case KEYWORD_BREAK:
3593 this->break_stat();
3594 break;
3595 case KEYWORD_CONTINUE:
3596 this->continue_stat();
3597 break;
3598 case KEYWORD_GOTO:
3599 this->goto_stat();
3600 break;
3601 case KEYWORD_IF:
3602 this->if_stat();
3603 break;
3604 case KEYWORD_SWITCH:
3605 this->switch_stat(label);
3606 break;
3607 case KEYWORD_SELECT:
3608 this->select_stat(label);
3609 break;
3610 case KEYWORD_FOR:
3611 this->for_stat(label);
3612 break;
3613 default:
3614 error_at(this->location(), "expected statement");
3615 this->advance_token();
3616 break;
3619 break;
3621 case Token::TOKEN_IDENTIFIER:
3623 std::string identifier = token->identifier();
3624 bool is_exported = token->is_identifier_exported();
3625 Location location = token->location();
3626 if (this->advance_token()->is_op(OPERATOR_COLON))
3628 this->advance_token();
3629 this->labeled_stmt(identifier, location);
3631 else
3633 this->unget_token(Token::make_identifier_token(identifier,
3634 is_exported,
3635 location));
3636 this->simple_stat(true, NULL, NULL, NULL);
3639 break;
3641 case Token::TOKEN_OPERATOR:
3642 if (token->is_op(OPERATOR_LCURLY))
3644 Location location = token->location();
3645 this->gogo_->start_block(location);
3646 Location end_loc = this->block();
3647 this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3648 location);
3650 else if (!token->is_op(OPERATOR_SEMICOLON))
3651 this->simple_stat(true, NULL, NULL, NULL);
3652 break;
3654 case Token::TOKEN_STRING:
3655 case Token::TOKEN_CHARACTER:
3656 case Token::TOKEN_INTEGER:
3657 case Token::TOKEN_FLOAT:
3658 case Token::TOKEN_IMAGINARY:
3659 this->simple_stat(true, NULL, NULL, NULL);
3660 break;
3662 default:
3663 error_at(this->location(), "expected statement");
3664 this->advance_token();
3665 break;
3669 bool
3670 Parse::statement_may_start_here()
3672 const Token* token = this->peek_token();
3673 switch (token->classification())
3675 case Token::TOKEN_KEYWORD:
3677 switch (token->keyword())
3679 case KEYWORD_CONST:
3680 case KEYWORD_TYPE:
3681 case KEYWORD_VAR:
3682 case KEYWORD_FUNC:
3683 case KEYWORD_MAP:
3684 case KEYWORD_STRUCT:
3685 case KEYWORD_INTERFACE:
3686 case KEYWORD_GO:
3687 case KEYWORD_DEFER:
3688 case KEYWORD_RETURN:
3689 case KEYWORD_BREAK:
3690 case KEYWORD_CONTINUE:
3691 case KEYWORD_GOTO:
3692 case KEYWORD_IF:
3693 case KEYWORD_SWITCH:
3694 case KEYWORD_SELECT:
3695 case KEYWORD_FOR:
3696 return true;
3698 default:
3699 return false;
3702 break;
3704 case Token::TOKEN_IDENTIFIER:
3705 return true;
3707 case Token::TOKEN_OPERATOR:
3708 if (token->is_op(OPERATOR_LCURLY)
3709 || token->is_op(OPERATOR_SEMICOLON))
3710 return true;
3711 else
3712 return this->expression_may_start_here();
3714 case Token::TOKEN_STRING:
3715 case Token::TOKEN_CHARACTER:
3716 case Token::TOKEN_INTEGER:
3717 case Token::TOKEN_FLOAT:
3718 case Token::TOKEN_IMAGINARY:
3719 return true;
3721 default:
3722 return false;
3726 // LabeledStmt = Label ":" Statement .
3727 // Label = identifier .
3729 void
3730 Parse::labeled_stmt(const std::string& label_name, Location location)
3732 Label* label = this->gogo_->add_label_definition(label_name, location);
3734 if (this->peek_token()->is_op(OPERATOR_RCURLY))
3736 // This is a label at the end of a block. A program is
3737 // permitted to omit a semicolon here.
3738 return;
3741 if (!this->statement_may_start_here())
3743 // Mark the label as used to avoid a useless error about an
3744 // unused label.
3745 label->set_is_used();
3747 error_at(location, "missing statement after label");
3748 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3749 location));
3750 return;
3753 this->statement(label);
3756 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
3757 // Assignment | ShortVarDecl .
3759 // EmptyStmt was handled in Parse::statement.
3761 // In order to make this work for if and switch statements, if
3762 // RETURN_EXP is not NULL, and we see an ExpressionStat, we return the
3763 // expression rather than adding an expression statement to the
3764 // current block. If we see something other than an ExpressionStat,
3765 // we add the statement, set *RETURN_EXP to true if we saw a send
3766 // statement, and return NULL. The handling of send statements is for
3767 // better error messages.
3769 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
3770 // RangeClause.
3772 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
3773 // guard (var := expr.("type") using the literal keyword "type").
3775 Expression*
3776 Parse::simple_stat(bool may_be_composite_lit, bool* return_exp,
3777 Range_clause* p_range_clause, Type_switch* p_type_switch)
3779 const Token* token = this->peek_token();
3781 // An identifier follow by := is a SimpleVarDecl.
3782 if (token->is_identifier())
3784 std::string identifier = token->identifier();
3785 bool is_exported = token->is_identifier_exported();
3786 Location location = token->location();
3788 token = this->advance_token();
3789 if (token->is_op(OPERATOR_COLONEQ)
3790 || token->is_op(OPERATOR_COMMA))
3792 identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
3793 this->simple_var_decl_or_assignment(identifier, location,
3794 may_be_composite_lit,
3795 p_range_clause,
3796 (token->is_op(OPERATOR_COLONEQ)
3797 ? p_type_switch
3798 : NULL));
3799 return NULL;
3802 this->unget_token(Token::make_identifier_token(identifier, is_exported,
3803 location));
3806 Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
3807 may_be_composite_lit,
3808 (p_type_switch == NULL
3809 ? NULL
3810 : &p_type_switch->found),
3811 NULL);
3812 if (p_type_switch != NULL && p_type_switch->found)
3814 p_type_switch->name.clear();
3815 p_type_switch->location = exp->location();
3816 p_type_switch->expr = this->verify_not_sink(exp);
3817 return NULL;
3819 token = this->peek_token();
3820 if (token->is_op(OPERATOR_CHANOP))
3822 this->send_stmt(this->verify_not_sink(exp));
3823 if (return_exp != NULL)
3824 *return_exp = true;
3826 else if (token->is_op(OPERATOR_PLUSPLUS)
3827 || token->is_op(OPERATOR_MINUSMINUS))
3828 this->inc_dec_stat(this->verify_not_sink(exp));
3829 else if (token->is_op(OPERATOR_COMMA)
3830 || token->is_op(OPERATOR_EQ))
3831 this->assignment(exp, may_be_composite_lit, p_range_clause);
3832 else if (token->is_op(OPERATOR_PLUSEQ)
3833 || token->is_op(OPERATOR_MINUSEQ)
3834 || token->is_op(OPERATOR_OREQ)
3835 || token->is_op(OPERATOR_XOREQ)
3836 || token->is_op(OPERATOR_MULTEQ)
3837 || token->is_op(OPERATOR_DIVEQ)
3838 || token->is_op(OPERATOR_MODEQ)
3839 || token->is_op(OPERATOR_LSHIFTEQ)
3840 || token->is_op(OPERATOR_RSHIFTEQ)
3841 || token->is_op(OPERATOR_ANDEQ)
3842 || token->is_op(OPERATOR_BITCLEAREQ))
3843 this->assignment(this->verify_not_sink(exp), may_be_composite_lit,
3844 p_range_clause);
3845 else if (return_exp != NULL)
3846 return this->verify_not_sink(exp);
3847 else
3849 exp = this->verify_not_sink(exp);
3851 if (token->is_op(OPERATOR_COLONEQ))
3853 if (!exp->is_error_expression())
3854 error_at(token->location(), "non-name on left side of %<:=%>");
3855 this->gogo_->mark_locals_used();
3856 while (!token->is_op(OPERATOR_SEMICOLON)
3857 && !token->is_eof())
3858 token = this->advance_token();
3859 return NULL;
3862 this->expression_stat(exp);
3865 return NULL;
3868 bool
3869 Parse::simple_stat_may_start_here()
3871 return this->expression_may_start_here();
3874 // Parse { Statement ";" } which is used in a few places. The list of
3875 // statements may end with a right curly brace, in which case the
3876 // semicolon may be omitted.
3878 void
3879 Parse::statement_list()
3881 while (this->statement_may_start_here())
3883 this->statement(NULL);
3884 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3885 this->advance_token();
3886 else if (this->peek_token()->is_op(OPERATOR_RCURLY))
3887 break;
3888 else
3890 if (!this->peek_token()->is_eof() || !saw_errors())
3891 error_at(this->location(), "expected %<;%> or %<}%> or newline");
3892 if (!this->skip_past_error(OPERATOR_RCURLY))
3893 return;
3898 bool
3899 Parse::statement_list_may_start_here()
3901 return this->statement_may_start_here();
3904 // ExpressionStat = Expression .
3906 void
3907 Parse::expression_stat(Expression* exp)
3909 this->gogo_->add_statement(Statement::make_statement(exp, false));
3912 // SendStmt = Channel "&lt;-" Expression .
3913 // Channel = Expression .
3915 void
3916 Parse::send_stmt(Expression* channel)
3918 go_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
3919 Location loc = this->location();
3920 this->advance_token();
3921 Expression* val = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
3922 NULL);
3923 Statement* s = Statement::make_send_statement(channel, val, loc);
3924 this->gogo_->add_statement(s);
3927 // IncDecStat = Expression ( "++" | "--" ) .
3929 void
3930 Parse::inc_dec_stat(Expression* exp)
3932 const Token* token = this->peek_token();
3934 // Lvalue maps require special handling.
3935 if (exp->index_expression() != NULL)
3936 exp->index_expression()->set_is_lvalue();
3938 if (token->is_op(OPERATOR_PLUSPLUS))
3939 this->gogo_->add_statement(Statement::make_inc_statement(exp));
3940 else if (token->is_op(OPERATOR_MINUSMINUS))
3941 this->gogo_->add_statement(Statement::make_dec_statement(exp));
3942 else
3943 go_unreachable();
3944 this->advance_token();
3947 // Assignment = ExpressionList assign_op ExpressionList .
3949 // EXP is an expression that we have already parsed.
3951 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
3952 // side may be a composite literal.
3954 // If RANGE_CLAUSE is not NULL, then this will recognize a
3955 // RangeClause.
3957 void
3958 Parse::assignment(Expression* expr, bool may_be_composite_lit,
3959 Range_clause* p_range_clause)
3961 Expression_list* vars;
3962 if (!this->peek_token()->is_op(OPERATOR_COMMA))
3964 vars = new Expression_list();
3965 vars->push_back(expr);
3967 else
3969 this->advance_token();
3970 vars = this->expression_list(expr, true, may_be_composite_lit);
3973 this->tuple_assignment(vars, may_be_composite_lit, p_range_clause);
3976 // An assignment statement. LHS is the list of expressions which
3977 // appear on the left hand side.
3979 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
3980 // side may be a composite literal.
3982 // If RANGE_CLAUSE is not NULL, then this will recognize a
3983 // RangeClause.
3985 void
3986 Parse::tuple_assignment(Expression_list* lhs, bool may_be_composite_lit,
3987 Range_clause* p_range_clause)
3989 const Token* token = this->peek_token();
3990 if (!token->is_op(OPERATOR_EQ)
3991 && !token->is_op(OPERATOR_PLUSEQ)
3992 && !token->is_op(OPERATOR_MINUSEQ)
3993 && !token->is_op(OPERATOR_OREQ)
3994 && !token->is_op(OPERATOR_XOREQ)
3995 && !token->is_op(OPERATOR_MULTEQ)
3996 && !token->is_op(OPERATOR_DIVEQ)
3997 && !token->is_op(OPERATOR_MODEQ)
3998 && !token->is_op(OPERATOR_LSHIFTEQ)
3999 && !token->is_op(OPERATOR_RSHIFTEQ)
4000 && !token->is_op(OPERATOR_ANDEQ)
4001 && !token->is_op(OPERATOR_BITCLEAREQ))
4003 error_at(this->location(), "expected assignment operator");
4004 return;
4006 Operator op = token->op();
4007 Location location = token->location();
4009 token = this->advance_token();
4011 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
4013 if (op != OPERATOR_EQ)
4014 error_at(this->location(), "range clause requires %<=%>");
4015 this->range_clause_expr(lhs, p_range_clause);
4016 return;
4019 Expression_list* vals = this->expression_list(NULL, false,
4020 may_be_composite_lit);
4022 // We've parsed everything; check for errors.
4023 if (lhs == NULL || vals == NULL)
4024 return;
4025 for (Expression_list::const_iterator pe = lhs->begin();
4026 pe != lhs->end();
4027 ++pe)
4029 if ((*pe)->is_error_expression())
4030 return;
4031 if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
4032 error_at((*pe)->location(), "cannot use _ as value");
4034 for (Expression_list::const_iterator pe = vals->begin();
4035 pe != vals->end();
4036 ++pe)
4038 if ((*pe)->is_error_expression())
4039 return;
4042 // Map expressions act differently when they are lvalues.
4043 for (Expression_list::iterator plv = lhs->begin();
4044 plv != lhs->end();
4045 ++plv)
4046 if ((*plv)->index_expression() != NULL)
4047 (*plv)->index_expression()->set_is_lvalue();
4049 Call_expression* call;
4050 Index_expression* map_index;
4051 Receive_expression* receive;
4052 Type_guard_expression* type_guard;
4053 if (lhs->size() == vals->size())
4055 Statement* s;
4056 if (lhs->size() > 1)
4058 if (op != OPERATOR_EQ)
4059 error_at(location, "multiple values only permitted with %<=%>");
4060 s = Statement::make_tuple_assignment(lhs, vals, location);
4062 else
4064 if (op == OPERATOR_EQ)
4065 s = Statement::make_assignment(lhs->front(), vals->front(),
4066 location);
4067 else
4068 s = Statement::make_assignment_operation(op, lhs->front(),
4069 vals->front(), location);
4070 delete lhs;
4071 delete vals;
4073 this->gogo_->add_statement(s);
4075 else if (vals->size() == 1
4076 && (call = (*vals->begin())->call_expression()) != NULL)
4078 if (op != OPERATOR_EQ)
4079 error_at(location, "multiple results only permitted with %<=%>");
4080 delete vals;
4081 vals = new Expression_list;
4082 for (unsigned int i = 0; i < lhs->size(); ++i)
4083 vals->push_back(Expression::make_call_result(call, i));
4084 Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
4085 this->gogo_->add_statement(s);
4087 else if (lhs->size() == 2
4088 && vals->size() == 1
4089 && (map_index = (*vals->begin())->index_expression()) != NULL)
4091 if (op != OPERATOR_EQ)
4092 error_at(location, "two values from map requires %<=%>");
4093 Expression* val = lhs->front();
4094 Expression* present = lhs->back();
4095 Statement* s = Statement::make_tuple_map_assignment(val, present,
4096 map_index, location);
4097 this->gogo_->add_statement(s);
4099 else if (lhs->size() == 1
4100 && vals->size() == 2
4101 && (map_index = lhs->front()->index_expression()) != NULL)
4103 if (op != OPERATOR_EQ)
4104 error_at(location, "assigning tuple to map index requires %<=%>");
4105 Expression* val = vals->front();
4106 Expression* should_set = vals->back();
4107 Statement* s = Statement::make_map_assignment(map_index, val, should_set,
4108 location);
4109 this->gogo_->add_statement(s);
4111 else if (lhs->size() == 2
4112 && vals->size() == 1
4113 && (receive = (*vals->begin())->receive_expression()) != NULL)
4115 if (op != OPERATOR_EQ)
4116 error_at(location, "two values from receive requires %<=%>");
4117 Expression* val = lhs->front();
4118 Expression* success = lhs->back();
4119 Expression* channel = receive->channel();
4120 Statement* s = Statement::make_tuple_receive_assignment(val, success,
4121 channel,
4122 location);
4123 this->gogo_->add_statement(s);
4125 else if (lhs->size() == 2
4126 && vals->size() == 1
4127 && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
4129 if (op != OPERATOR_EQ)
4130 error_at(location, "two values from type guard requires %<=%>");
4131 Expression* val = lhs->front();
4132 Expression* ok = lhs->back();
4133 Expression* expr = type_guard->expr();
4134 Type* type = type_guard->type();
4135 Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
4136 expr, type,
4137 location);
4138 this->gogo_->add_statement(s);
4140 else
4142 error_at(location, "number of variables does not match number of values");
4146 // GoStat = "go" Expression .
4147 // DeferStat = "defer" Expression .
4149 void
4150 Parse::go_or_defer_stat()
4152 go_assert(this->peek_token()->is_keyword(KEYWORD_GO)
4153 || this->peek_token()->is_keyword(KEYWORD_DEFER));
4154 bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
4155 Location stat_location = this->location();
4157 this->advance_token();
4158 Location expr_location = this->location();
4160 bool is_parenthesized = false;
4161 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
4162 &is_parenthesized);
4163 Call_expression* call_expr = expr->call_expression();
4164 if (is_parenthesized || call_expr == NULL)
4166 error_at(expr_location, "argument to go/defer must be function call");
4167 return;
4170 // Make it easier to simplify go/defer statements by putting every
4171 // statement in its own block.
4172 this->gogo_->start_block(stat_location);
4173 Statement* stat;
4174 if (is_go)
4175 stat = Statement::make_go_statement(call_expr, stat_location);
4176 else
4177 stat = Statement::make_defer_statement(call_expr, stat_location);
4178 this->gogo_->add_statement(stat);
4179 this->gogo_->add_block(this->gogo_->finish_block(stat_location),
4180 stat_location);
4183 // ReturnStat = "return" [ ExpressionList ] .
4185 void
4186 Parse::return_stat()
4188 go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
4189 Location location = this->location();
4190 this->advance_token();
4191 Expression_list* vals = NULL;
4192 if (this->expression_may_start_here())
4193 vals = this->expression_list(NULL, false, true);
4194 this->gogo_->add_statement(Statement::make_return_statement(vals, location));
4196 if (vals == NULL
4197 && this->gogo_->current_function()->func_value()->results_are_named())
4199 Named_object* function = this->gogo_->current_function();
4200 Function::Results* results = function->func_value()->result_variables();
4201 for (Function::Results::const_iterator p = results->begin();
4202 p != results->end();
4203 ++p)
4205 Named_object* no = this->gogo_->lookup((*p)->name(), NULL);
4206 if (no == NULL)
4207 go_assert(saw_errors());
4208 else if (!no->is_result_variable())
4209 error_at(location, "%qs is shadowed during return",
4210 (*p)->message_name().c_str());
4215 // IfStmt = "if" [ SimpleStmt ";" ] Expression Block
4216 // [ "else" ( IfStmt | Block ) ] .
4218 void
4219 Parse::if_stat()
4221 go_assert(this->peek_token()->is_keyword(KEYWORD_IF));
4222 Location location = this->location();
4223 this->advance_token();
4225 this->gogo_->start_block(location);
4227 bool saw_simple_stat = false;
4228 Expression* cond = NULL;
4229 bool saw_send_stmt = false;
4230 if (this->simple_stat_may_start_here())
4232 cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL);
4233 saw_simple_stat = true;
4235 if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4237 // The SimpleStat is an expression statement.
4238 this->expression_stat(cond);
4239 cond = NULL;
4241 if (cond == NULL)
4243 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4244 this->advance_token();
4245 else if (saw_simple_stat)
4247 if (saw_send_stmt)
4248 error_at(this->location(),
4249 ("send statement used as value; "
4250 "use select for non-blocking send"));
4251 else
4252 error_at(this->location(),
4253 "expected %<;%> after statement in if expression");
4254 if (!this->expression_may_start_here())
4255 cond = Expression::make_error(this->location());
4257 if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY))
4259 error_at(this->location(),
4260 "missing condition in if statement");
4261 cond = Expression::make_error(this->location());
4263 if (cond == NULL)
4264 cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL, NULL);
4267 this->gogo_->start_block(this->location());
4268 Location end_loc = this->block();
4269 Block* then_block = this->gogo_->finish_block(end_loc);
4271 // Check for the easy error of a newline before "else".
4272 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4274 Location semi_loc = this->location();
4275 if (this->advance_token()->is_keyword(KEYWORD_ELSE))
4276 error_at(this->location(),
4277 "unexpected semicolon or newline before %<else%>");
4278 else
4279 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4280 semi_loc));
4283 Block* else_block = NULL;
4284 if (this->peek_token()->is_keyword(KEYWORD_ELSE))
4286 this->gogo_->start_block(this->location());
4287 const Token* token = this->advance_token();
4288 if (token->is_keyword(KEYWORD_IF))
4289 this->if_stat();
4290 else if (token->is_op(OPERATOR_LCURLY))
4291 this->block();
4292 else
4294 error_at(this->location(), "expected %<if%> or %<{%>");
4295 this->statement(NULL);
4297 else_block = this->gogo_->finish_block(this->location());
4300 this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
4301 else_block,
4302 location));
4304 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4305 location);
4308 // SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4309 // ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
4310 // "{" { ExprCaseClause } "}" .
4311 // TypeSwitchStmt = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
4312 // "{" { TypeCaseClause } "}" .
4313 // TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
4315 void
4316 Parse::switch_stat(Label* label)
4318 go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
4319 Location location = this->location();
4320 this->advance_token();
4322 this->gogo_->start_block(location);
4324 bool saw_simple_stat = false;
4325 Expression* switch_val = NULL;
4326 bool saw_send_stmt;
4327 Type_switch type_switch;
4328 bool have_type_switch_block = false;
4329 if (this->simple_stat_may_start_here())
4331 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4332 &type_switch);
4333 saw_simple_stat = true;
4335 if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4337 // The SimpleStat is an expression statement.
4338 this->expression_stat(switch_val);
4339 switch_val = NULL;
4341 if (switch_val == NULL && !type_switch.found)
4343 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4344 this->advance_token();
4345 else if (saw_simple_stat)
4347 if (saw_send_stmt)
4348 error_at(this->location(),
4349 ("send statement used as value; "
4350 "use select for non-blocking send"));
4351 else
4352 error_at(this->location(),
4353 "expected %<;%> after statement in switch expression");
4355 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4357 if (this->peek_token()->is_identifier())
4359 const Token* token = this->peek_token();
4360 std::string identifier = token->identifier();
4361 bool is_exported = token->is_identifier_exported();
4362 Location id_loc = token->location();
4364 token = this->advance_token();
4365 bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
4366 this->unget_token(Token::make_identifier_token(identifier,
4367 is_exported,
4368 id_loc));
4369 if (is_coloneq)
4371 // This must be a TypeSwitchGuard. It is in a
4372 // different block from any initial SimpleStat.
4373 if (saw_simple_stat)
4375 this->gogo_->start_block(id_loc);
4376 have_type_switch_block = true;
4379 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4380 &type_switch);
4381 if (!type_switch.found)
4383 if (switch_val == NULL
4384 || !switch_val->is_error_expression())
4386 error_at(id_loc, "expected type switch assignment");
4387 switch_val = Expression::make_error(id_loc);
4392 if (switch_val == NULL && !type_switch.found)
4394 switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
4395 &type_switch.found, NULL);
4396 if (type_switch.found)
4398 type_switch.name.clear();
4399 type_switch.expr = switch_val;
4400 type_switch.location = switch_val->location();
4406 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4408 Location token_loc = this->location();
4409 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
4410 && this->advance_token()->is_op(OPERATOR_LCURLY))
4411 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4412 else if (this->peek_token()->is_op(OPERATOR_COLONEQ))
4414 error_at(token_loc, "invalid variable name");
4415 this->advance_token();
4416 this->expression(PRECEDENCE_NORMAL, false, false,
4417 &type_switch.found, NULL);
4418 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4419 this->advance_token();
4420 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4422 if (have_type_switch_block)
4423 this->gogo_->add_block(this->gogo_->finish_block(location),
4424 location);
4425 this->gogo_->add_block(this->gogo_->finish_block(location),
4426 location);
4427 return;
4429 if (type_switch.found)
4430 type_switch.expr = Expression::make_error(location);
4432 else
4434 error_at(this->location(), "expected %<{%>");
4435 if (have_type_switch_block)
4436 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4437 location);
4438 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4439 location);
4440 return;
4443 this->advance_token();
4445 Statement* statement;
4446 if (type_switch.found)
4447 statement = this->type_switch_body(label, type_switch, location);
4448 else
4449 statement = this->expr_switch_body(label, switch_val, location);
4451 if (statement != NULL)
4452 this->gogo_->add_statement(statement);
4454 if (have_type_switch_block)
4455 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4456 location);
4458 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4459 location);
4462 // The body of an expression switch.
4463 // "{" { ExprCaseClause } "}"
4465 Statement*
4466 Parse::expr_switch_body(Label* label, Expression* switch_val,
4467 Location location)
4469 Switch_statement* statement = Statement::make_switch_statement(switch_val,
4470 location);
4472 this->push_break_statement(statement, label);
4474 Case_clauses* case_clauses = new Case_clauses();
4475 bool saw_default = false;
4476 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4478 if (this->peek_token()->is_eof())
4480 if (!saw_errors())
4481 error_at(this->location(), "missing %<}%>");
4482 return NULL;
4484 this->expr_case_clause(case_clauses, &saw_default);
4486 this->advance_token();
4488 statement->add_clauses(case_clauses);
4490 this->pop_break_statement();
4492 return statement;
4495 // ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
4496 // FallthroughStat = "fallthrough" .
4498 void
4499 Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
4501 Location location = this->location();
4503 bool is_default = false;
4504 Expression_list* vals = this->expr_switch_case(&is_default);
4506 if (!this->peek_token()->is_op(OPERATOR_COLON))
4508 if (!saw_errors())
4509 error_at(this->location(), "expected %<:%>");
4510 return;
4512 else
4513 this->advance_token();
4515 Block* statements = NULL;
4516 if (this->statement_list_may_start_here())
4518 this->gogo_->start_block(this->location());
4519 this->statement_list();
4520 statements = this->gogo_->finish_block(this->location());
4523 bool is_fallthrough = false;
4524 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4526 Location fallthrough_loc = this->location();
4527 is_fallthrough = true;
4528 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4529 this->advance_token();
4530 if (this->peek_token()->is_op(OPERATOR_RCURLY))
4531 error_at(fallthrough_loc, _("cannot fallthrough final case in switch"));
4534 if (is_default)
4536 if (*saw_default)
4538 error_at(location, "multiple defaults in switch");
4539 return;
4541 *saw_default = true;
4544 if (is_default || vals != NULL)
4545 clauses->add(vals, is_default, statements, is_fallthrough, location);
4548 // ExprSwitchCase = "case" ExpressionList | "default" .
4550 Expression_list*
4551 Parse::expr_switch_case(bool* is_default)
4553 const Token* token = this->peek_token();
4554 if (token->is_keyword(KEYWORD_CASE))
4556 this->advance_token();
4557 return this->expression_list(NULL, false, true);
4559 else if (token->is_keyword(KEYWORD_DEFAULT))
4561 this->advance_token();
4562 *is_default = true;
4563 return NULL;
4565 else
4567 if (!saw_errors())
4568 error_at(this->location(), "expected %<case%> or %<default%>");
4569 if (!token->is_op(OPERATOR_RCURLY))
4570 this->advance_token();
4571 return NULL;
4575 // The body of a type switch.
4576 // "{" { TypeCaseClause } "}" .
4578 Statement*
4579 Parse::type_switch_body(Label* label, const Type_switch& type_switch,
4580 Location location)
4582 Named_object* switch_no = NULL;
4583 if (!type_switch.name.empty())
4585 if (Gogo::is_sink_name(type_switch.name))
4586 error_at(type_switch.location,
4587 "no new variables on left side of %<:=%>");
4588 else
4590 Variable* switch_var = new Variable(NULL, type_switch.expr, false,
4591 false, false,
4592 type_switch.location);
4593 switch_no = this->gogo_->add_variable(type_switch.name, switch_var);
4597 Type_switch_statement* statement =
4598 Statement::make_type_switch_statement(switch_no,
4599 (switch_no == NULL
4600 ? type_switch.expr
4601 : NULL),
4602 location);
4604 this->push_break_statement(statement, label);
4606 Type_case_clauses* case_clauses = new Type_case_clauses();
4607 bool saw_default = false;
4608 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4610 if (this->peek_token()->is_eof())
4612 error_at(this->location(), "missing %<}%>");
4613 return NULL;
4615 this->type_case_clause(switch_no, case_clauses, &saw_default);
4617 this->advance_token();
4619 statement->add_clauses(case_clauses);
4621 this->pop_break_statement();
4623 return statement;
4626 // TypeCaseClause = TypeSwitchCase ":" [ StatementList ] .
4628 void
4629 Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses,
4630 bool* saw_default)
4632 Location location = this->location();
4634 std::vector<Type*> types;
4635 bool is_default = false;
4636 this->type_switch_case(&types, &is_default);
4638 if (!this->peek_token()->is_op(OPERATOR_COLON))
4639 error_at(this->location(), "expected %<:%>");
4640 else
4641 this->advance_token();
4643 Block* statements = NULL;
4644 if (this->statement_list_may_start_here())
4646 this->gogo_->start_block(this->location());
4647 if (switch_no != NULL && types.size() == 1)
4649 Type* type = types.front();
4650 Expression* init = Expression::make_var_reference(switch_no,
4651 location);
4652 init = Expression::make_type_guard(init, type, location);
4653 Variable* v = new Variable(type, init, false, false, false,
4654 location);
4655 v->set_is_type_switch_var();
4656 Named_object* no = this->gogo_->add_variable(switch_no->name(), v);
4658 // We don't want to issue an error if the compiler
4659 // introduced special variable is not used. Instead we want
4660 // to issue an error if the variable defined by the switch
4661 // is not used. That is handled via type_switch_vars_ and
4662 // Parse::mark_var_used.
4663 v->set_is_used();
4664 this->type_switch_vars_[no] = switch_no;
4666 this->statement_list();
4667 statements = this->gogo_->finish_block(this->location());
4670 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4672 error_at(this->location(),
4673 "fallthrough is not permitted in a type switch");
4674 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4675 this->advance_token();
4678 if (is_default)
4680 go_assert(types.empty());
4681 if (*saw_default)
4683 error_at(location, "multiple defaults in type switch");
4684 return;
4686 *saw_default = true;
4687 clauses->add(NULL, false, true, statements, location);
4689 else if (!types.empty())
4691 for (std::vector<Type*>::const_iterator p = types.begin();
4692 p + 1 != types.end();
4693 ++p)
4694 clauses->add(*p, true, false, NULL, location);
4695 clauses->add(types.back(), false, false, statements, location);
4697 else
4698 clauses->add(Type::make_error_type(), false, false, statements, location);
4701 // TypeSwitchCase = "case" type | "default"
4703 // We accept a comma separated list of types.
4705 void
4706 Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
4708 const Token* token = this->peek_token();
4709 if (token->is_keyword(KEYWORD_CASE))
4711 this->advance_token();
4712 while (true)
4714 Type* t = this->type();
4716 if (!t->is_error_type())
4717 types->push_back(t);
4718 else
4720 this->gogo_->mark_locals_used();
4721 token = this->peek_token();
4722 while (!token->is_op(OPERATOR_COLON)
4723 && !token->is_op(OPERATOR_COMMA)
4724 && !token->is_op(OPERATOR_RCURLY)
4725 && !token->is_eof())
4726 token = this->advance_token();
4729 if (!this->peek_token()->is_op(OPERATOR_COMMA))
4730 break;
4731 this->advance_token();
4734 else if (token->is_keyword(KEYWORD_DEFAULT))
4736 this->advance_token();
4737 *is_default = true;
4739 else
4741 error_at(this->location(), "expected %<case%> or %<default%>");
4742 if (!token->is_op(OPERATOR_RCURLY))
4743 this->advance_token();
4747 // SelectStat = "select" "{" { CommClause } "}" .
4749 void
4750 Parse::select_stat(Label* label)
4752 go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
4753 Location location = this->location();
4754 const Token* token = this->advance_token();
4756 if (!token->is_op(OPERATOR_LCURLY))
4758 Location token_loc = token->location();
4759 if (token->is_op(OPERATOR_SEMICOLON)
4760 && this->advance_token()->is_op(OPERATOR_LCURLY))
4761 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4762 else
4764 error_at(this->location(), "expected %<{%>");
4765 return;
4768 this->advance_token();
4770 Select_statement* statement = Statement::make_select_statement(location);
4772 this->push_break_statement(statement, label);
4774 Select_clauses* select_clauses = new Select_clauses();
4775 bool saw_default = false;
4776 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4778 if (this->peek_token()->is_eof())
4780 error_at(this->location(), "expected %<}%>");
4781 return;
4783 this->comm_clause(select_clauses, &saw_default);
4786 this->advance_token();
4788 statement->add_clauses(select_clauses);
4790 this->pop_break_statement();
4792 this->gogo_->add_statement(statement);
4795 // CommClause = CommCase ":" { Statement ";" } .
4797 void
4798 Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
4800 Location location = this->location();
4801 bool is_send = false;
4802 Expression* channel = NULL;
4803 Expression* val = NULL;
4804 Expression* closed = NULL;
4805 std::string varname;
4806 std::string closedname;
4807 bool is_default = false;
4808 bool got_case = this->comm_case(&is_send, &channel, &val, &closed,
4809 &varname, &closedname, &is_default);
4811 if (!is_send
4812 && varname.empty()
4813 && closedname.empty()
4814 && val != NULL
4815 && val->index_expression() != NULL)
4816 val->index_expression()->set_is_lvalue();
4818 if (this->peek_token()->is_op(OPERATOR_COLON))
4819 this->advance_token();
4820 else
4821 error_at(this->location(), "expected colon");
4823 this->gogo_->start_block(this->location());
4825 Named_object* var = NULL;
4826 if (!varname.empty())
4828 // FIXME: LOCATION is slightly wrong here.
4829 Variable* v = new Variable(NULL, channel, false, false, false,
4830 location);
4831 v->set_type_from_chan_element();
4832 var = this->gogo_->add_variable(varname, v);
4835 Named_object* closedvar = NULL;
4836 if (!closedname.empty())
4838 // FIXME: LOCATION is slightly wrong here.
4839 Variable* v = new Variable(Type::lookup_bool_type(), NULL,
4840 false, false, false, location);
4841 closedvar = this->gogo_->add_variable(closedname, v);
4844 this->statement_list();
4846 Block* statements = this->gogo_->finish_block(this->location());
4848 if (is_default)
4850 if (*saw_default)
4852 error_at(location, "multiple defaults in select");
4853 return;
4855 *saw_default = true;
4858 if (got_case)
4859 clauses->add(is_send, channel, val, closed, var, closedvar, is_default,
4860 statements, location);
4861 else if (statements != NULL)
4863 // Add the statements to make sure that any names they define
4864 // are traversed.
4865 this->gogo_->add_block(statements, location);
4869 // CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
4871 bool
4872 Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
4873 Expression** closed, std::string* varname,
4874 std::string* closedname, bool* is_default)
4876 const Token* token = this->peek_token();
4877 if (token->is_keyword(KEYWORD_DEFAULT))
4879 this->advance_token();
4880 *is_default = true;
4882 else if (token->is_keyword(KEYWORD_CASE))
4884 this->advance_token();
4885 if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname,
4886 closedname))
4887 return false;
4889 else
4891 error_at(this->location(), "expected %<case%> or %<default%>");
4892 if (!token->is_op(OPERATOR_RCURLY))
4893 this->advance_token();
4894 return false;
4897 return true;
4900 // RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
4901 // RecvExpr = Expression .
4903 bool
4904 Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val,
4905 Expression** closed, std::string* varname,
4906 std::string* closedname)
4908 const Token* token = this->peek_token();
4909 bool saw_comma = false;
4910 bool closed_is_id = false;
4911 if (token->is_identifier())
4913 Gogo* gogo = this->gogo_;
4914 std::string recv_var = token->identifier();
4915 bool is_rv_exported = token->is_identifier_exported();
4916 Location recv_var_loc = token->location();
4917 token = this->advance_token();
4918 if (token->is_op(OPERATOR_COLONEQ))
4920 // case rv := <-c:
4921 this->advance_token();
4922 Expression* e = this->expression(PRECEDENCE_NORMAL, false, false,
4923 NULL, NULL);
4924 Receive_expression* re = e->receive_expression();
4925 if (re == NULL)
4927 if (!e->is_error_expression())
4928 error_at(this->location(), "expected receive expression");
4929 return false;
4931 if (recv_var == "_")
4933 error_at(recv_var_loc,
4934 "no new variables on left side of %<:=%>");
4935 recv_var = "blank";
4937 *is_send = false;
4938 *varname = gogo->pack_hidden_name(recv_var, is_rv_exported);
4939 *channel = re->channel();
4940 return true;
4942 else if (token->is_op(OPERATOR_COMMA))
4944 token = this->advance_token();
4945 if (token->is_identifier())
4947 std::string recv_closed = token->identifier();
4948 bool is_rc_exported = token->is_identifier_exported();
4949 Location recv_closed_loc = token->location();
4950 closed_is_id = true;
4952 token = this->advance_token();
4953 if (token->is_op(OPERATOR_COLONEQ))
4955 // case rv, rc := <-c:
4956 this->advance_token();
4957 Expression* e = this->expression(PRECEDENCE_NORMAL, false,
4958 false, NULL, NULL);
4959 Receive_expression* re = e->receive_expression();
4960 if (re == NULL)
4962 if (!e->is_error_expression())
4963 error_at(this->location(),
4964 "expected receive expression");
4965 return false;
4967 if (recv_var == "_" && recv_closed == "_")
4969 error_at(recv_var_loc,
4970 "no new variables on left side of %<:=%>");
4971 recv_var = "blank";
4973 *is_send = false;
4974 if (recv_var != "_")
4975 *varname = gogo->pack_hidden_name(recv_var,
4976 is_rv_exported);
4977 if (recv_closed != "_")
4978 *closedname = gogo->pack_hidden_name(recv_closed,
4979 is_rc_exported);
4980 *channel = re->channel();
4981 return true;
4984 this->unget_token(Token::make_identifier_token(recv_closed,
4985 is_rc_exported,
4986 recv_closed_loc));
4989 *val = this->id_to_expression(gogo->pack_hidden_name(recv_var,
4990 is_rv_exported),
4991 recv_var_loc);
4992 saw_comma = true;
4994 else
4995 this->unget_token(Token::make_identifier_token(recv_var,
4996 is_rv_exported,
4997 recv_var_loc));
5000 // If SAW_COMMA is false, then we are looking at the start of the
5001 // send or receive expression. If SAW_COMMA is true, then *VAL is
5002 // set and we just read a comma.
5004 Expression* e;
5005 if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP))
5006 e = this->expression(PRECEDENCE_NORMAL, true, true, NULL, NULL);
5007 else
5009 // case <-c:
5010 *is_send = false;
5011 this->advance_token();
5012 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5014 // The next token should be ':'. If it is '<-', then we have
5015 // case <-c <- v:
5016 // which is to say, send on a channel received from a channel.
5017 if (!this->peek_token()->is_op(OPERATOR_CHANOP))
5018 return true;
5020 e = Expression::make_receive(*channel, (*channel)->location());
5023 if (this->peek_token()->is_op(OPERATOR_EQ))
5025 if (!this->advance_token()->is_op(OPERATOR_CHANOP))
5027 error_at(this->location(), "missing %<<-%>");
5028 return false;
5030 *is_send = false;
5031 this->advance_token();
5032 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5033 if (saw_comma)
5035 // case v, e = <-c:
5036 // *VAL is already set.
5037 if (!e->is_sink_expression())
5038 *closed = e;
5040 else
5042 // case v = <-c:
5043 if (!e->is_sink_expression())
5044 *val = e;
5046 return true;
5049 if (saw_comma)
5051 if (closed_is_id)
5052 error_at(this->location(), "expected %<=%> or %<:=%>");
5053 else
5054 error_at(this->location(), "expected %<=%>");
5055 return false;
5058 if (this->peek_token()->is_op(OPERATOR_CHANOP))
5060 // case c <- v:
5061 *is_send = true;
5062 *channel = this->verify_not_sink(e);
5063 this->advance_token();
5064 *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5065 return true;
5068 error_at(this->location(), "expected %<<-%> or %<=%>");
5069 return false;
5072 // ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
5073 // Condition = Expression .
5075 void
5076 Parse::for_stat(Label* label)
5078 go_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
5079 Location location = this->location();
5080 const Token* token = this->advance_token();
5082 // Open a block to hold any variables defined in the init statement
5083 // of the for statement.
5084 this->gogo_->start_block(location);
5086 Block* init = NULL;
5087 Expression* cond = NULL;
5088 Block* post = NULL;
5089 Range_clause range_clause;
5091 if (!token->is_op(OPERATOR_LCURLY))
5093 if (token->is_keyword(KEYWORD_VAR))
5095 error_at(this->location(),
5096 "var declaration not allowed in for initializer");
5097 this->var_decl();
5100 if (token->is_op(OPERATOR_SEMICOLON))
5101 this->for_clause(&cond, &post);
5102 else
5104 // We might be looking at a Condition, an InitStat, or a
5105 // RangeClause.
5106 bool saw_send_stmt;
5107 cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL);
5108 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5110 if (cond == NULL && !range_clause.found)
5112 if (saw_send_stmt)
5113 error_at(this->location(),
5114 ("send statement used as value; "
5115 "use select for non-blocking send"));
5116 else
5117 error_at(this->location(), "parse error in for statement");
5120 else
5122 if (range_clause.found)
5123 error_at(this->location(), "parse error after range clause");
5125 if (cond != NULL)
5127 // COND is actually an expression statement for
5128 // InitStat at the start of a ForClause.
5129 this->expression_stat(cond);
5130 cond = NULL;
5133 this->for_clause(&cond, &post);
5138 // Build the For_statement and note that it is the current target
5139 // for break and continue statements.
5141 For_statement* sfor;
5142 For_range_statement* srange;
5143 Statement* s;
5144 if (!range_clause.found)
5146 sfor = Statement::make_for_statement(init, cond, post, location);
5147 s = sfor;
5148 srange = NULL;
5150 else
5152 srange = Statement::make_for_range_statement(range_clause.index,
5153 range_clause.value,
5154 range_clause.range,
5155 location);
5156 s = srange;
5157 sfor = NULL;
5160 this->push_break_statement(s, label);
5161 this->push_continue_statement(s, label);
5163 // Gather the block of statements in the loop and add them to the
5164 // For_statement.
5166 this->gogo_->start_block(this->location());
5167 Location end_loc = this->block();
5168 Block* statements = this->gogo_->finish_block(end_loc);
5170 if (sfor != NULL)
5171 sfor->add_statements(statements);
5172 else
5173 srange->add_statements(statements);
5175 // This is no longer the break/continue target.
5176 this->pop_break_statement();
5177 this->pop_continue_statement();
5179 // Add the For_statement to the list of statements, and close out
5180 // the block we started to hold any variables defined in the for
5181 // statement.
5183 this->gogo_->add_statement(s);
5185 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
5186 location);
5189 // ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
5190 // InitStat = SimpleStat .
5191 // PostStat = SimpleStat .
5193 // We have already read InitStat at this point.
5195 void
5196 Parse::for_clause(Expression** cond, Block** post)
5198 go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
5199 this->advance_token();
5200 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5201 *cond = NULL;
5202 else if (this->peek_token()->is_op(OPERATOR_LCURLY))
5204 error_at(this->location(),
5205 "unexpected semicolon or newline before %<{%>");
5206 *cond = NULL;
5207 *post = NULL;
5208 return;
5210 else
5211 *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5212 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5213 error_at(this->location(), "expected semicolon");
5214 else
5215 this->advance_token();
5217 if (this->peek_token()->is_op(OPERATOR_LCURLY))
5218 *post = NULL;
5219 else
5221 this->gogo_->start_block(this->location());
5222 this->simple_stat(false, NULL, NULL, NULL);
5223 *post = this->gogo_->finish_block(this->location());
5227 // RangeClause = IdentifierList ( "=" | ":=" ) "range" Expression .
5229 // This is the := version. It is called with a list of identifiers.
5231 void
5232 Parse::range_clause_decl(const Typed_identifier_list* til,
5233 Range_clause* p_range_clause)
5235 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5236 Location location = this->location();
5238 p_range_clause->found = true;
5240 go_assert(til->size() >= 1);
5241 if (til->size() > 2)
5242 error_at(this->location(), "too many variables for range clause");
5244 this->advance_token();
5245 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL,
5246 NULL);
5247 p_range_clause->range = expr;
5249 bool any_new = false;
5251 const Typed_identifier* pti = &til->front();
5252 Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new,
5253 NULL, NULL);
5254 if (any_new && no->is_variable())
5255 no->var_value()->set_type_from_range_index();
5256 p_range_clause->index = Expression::make_var_reference(no, location);
5258 if (til->size() == 1)
5259 p_range_clause->value = NULL;
5260 else
5262 pti = &til->back();
5263 bool is_new = false;
5264 no = this->init_var(*pti, NULL, expr, true, true, &is_new, NULL, NULL);
5265 if (is_new && no->is_variable())
5266 no->var_value()->set_type_from_range_value();
5267 if (is_new)
5268 any_new = true;
5269 p_range_clause->value = Expression::make_var_reference(no, location);
5272 if (!any_new)
5273 error_at(location, "variables redeclared but no variable is new");
5276 // The = version of RangeClause. This is called with a list of
5277 // expressions.
5279 void
5280 Parse::range_clause_expr(const Expression_list* vals,
5281 Range_clause* p_range_clause)
5283 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5285 p_range_clause->found = true;
5287 go_assert(vals->size() >= 1);
5288 if (vals->size() > 2)
5289 error_at(this->location(), "too many variables for range clause");
5291 this->advance_token();
5292 p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
5293 NULL, NULL);
5295 p_range_clause->index = vals->front();
5296 if (vals->size() == 1)
5297 p_range_clause->value = NULL;
5298 else
5299 p_range_clause->value = vals->back();
5302 // Push a statement on the break stack.
5304 void
5305 Parse::push_break_statement(Statement* enclosing, Label* label)
5307 if (this->break_stack_ == NULL)
5308 this->break_stack_ = new Bc_stack();
5309 this->break_stack_->push_back(std::make_pair(enclosing, label));
5312 // Push a statement on the continue stack.
5314 void
5315 Parse::push_continue_statement(Statement* enclosing, Label* label)
5317 if (this->continue_stack_ == NULL)
5318 this->continue_stack_ = new Bc_stack();
5319 this->continue_stack_->push_back(std::make_pair(enclosing, label));
5322 // Pop the break stack.
5324 void
5325 Parse::pop_break_statement()
5327 this->break_stack_->pop_back();
5330 // Pop the continue stack.
5332 void
5333 Parse::pop_continue_statement()
5335 this->continue_stack_->pop_back();
5338 // Find a break or continue statement given a label name.
5340 Statement*
5341 Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
5343 if (bc_stack == NULL)
5344 return NULL;
5345 for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
5346 p != bc_stack->rend();
5347 ++p)
5349 if (p->second != NULL && p->second->name() == label)
5351 p->second->set_is_used();
5352 return p->first;
5355 return NULL;
5358 // BreakStat = "break" [ identifier ] .
5360 void
5361 Parse::break_stat()
5363 go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
5364 Location location = this->location();
5366 const Token* token = this->advance_token();
5367 Statement* enclosing;
5368 if (!token->is_identifier())
5370 if (this->break_stack_ == NULL || this->break_stack_->empty())
5372 error_at(this->location(),
5373 "break statement not within for or switch or select");
5374 return;
5376 enclosing = this->break_stack_->back().first;
5378 else
5380 enclosing = this->find_bc_statement(this->break_stack_,
5381 token->identifier());
5382 if (enclosing == NULL)
5384 // If there is a label with this name, mark it as used to
5385 // avoid a useless error about an unused label.
5386 this->gogo_->add_label_reference(token->identifier(),
5387 Linemap::unknown_location(), false);
5389 error_at(token->location(), "invalid break label %qs",
5390 Gogo::message_name(token->identifier()).c_str());
5391 this->advance_token();
5392 return;
5394 this->advance_token();
5397 Unnamed_label* label;
5398 if (enclosing->classification() == Statement::STATEMENT_FOR)
5399 label = enclosing->for_statement()->break_label();
5400 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5401 label = enclosing->for_range_statement()->break_label();
5402 else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
5403 label = enclosing->switch_statement()->break_label();
5404 else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
5405 label = enclosing->type_switch_statement()->break_label();
5406 else if (enclosing->classification() == Statement::STATEMENT_SELECT)
5407 label = enclosing->select_statement()->break_label();
5408 else
5409 go_unreachable();
5411 this->gogo_->add_statement(Statement::make_break_statement(label,
5412 location));
5415 // ContinueStat = "continue" [ identifier ] .
5417 void
5418 Parse::continue_stat()
5420 go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
5421 Location location = this->location();
5423 const Token* token = this->advance_token();
5424 Statement* enclosing;
5425 if (!token->is_identifier())
5427 if (this->continue_stack_ == NULL || this->continue_stack_->empty())
5429 error_at(this->location(), "continue statement not within for");
5430 return;
5432 enclosing = this->continue_stack_->back().first;
5434 else
5436 enclosing = this->find_bc_statement(this->continue_stack_,
5437 token->identifier());
5438 if (enclosing == NULL)
5440 // If there is a label with this name, mark it as used to
5441 // avoid a useless error about an unused label.
5442 this->gogo_->add_label_reference(token->identifier(),
5443 Linemap::unknown_location(), false);
5445 error_at(token->location(), "invalid continue label %qs",
5446 Gogo::message_name(token->identifier()).c_str());
5447 this->advance_token();
5448 return;
5450 this->advance_token();
5453 Unnamed_label* label;
5454 if (enclosing->classification() == Statement::STATEMENT_FOR)
5455 label = enclosing->for_statement()->continue_label();
5456 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5457 label = enclosing->for_range_statement()->continue_label();
5458 else
5459 go_unreachable();
5461 this->gogo_->add_statement(Statement::make_continue_statement(label,
5462 location));
5465 // GotoStat = "goto" identifier .
5467 void
5468 Parse::goto_stat()
5470 go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
5471 Location location = this->location();
5472 const Token* token = this->advance_token();
5473 if (!token->is_identifier())
5474 error_at(this->location(), "expected label for goto");
5475 else
5477 Label* label = this->gogo_->add_label_reference(token->identifier(),
5478 location, true);
5479 Statement* s = Statement::make_goto_statement(label, location);
5480 this->gogo_->add_statement(s);
5481 this->advance_token();
5485 // PackageClause = "package" PackageName .
5487 void
5488 Parse::package_clause()
5490 const Token* token = this->peek_token();
5491 Location location = token->location();
5492 std::string name;
5493 if (!token->is_keyword(KEYWORD_PACKAGE))
5495 error_at(this->location(), "program must start with package clause");
5496 name = "ERROR";
5498 else
5500 token = this->advance_token();
5501 if (token->is_identifier())
5503 name = token->identifier();
5504 if (name == "_")
5506 error_at(this->location(), "invalid package name _");
5507 name = "blank";
5509 this->advance_token();
5511 else
5513 error_at(this->location(), "package name must be an identifier");
5514 name = "ERROR";
5517 this->gogo_->set_package_name(name, location);
5520 // ImportDecl = "import" Decl<ImportSpec> .
5522 void
5523 Parse::import_decl()
5525 go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
5526 this->advance_token();
5527 this->decl(&Parse::import_spec, NULL);
5530 // ImportSpec = [ "." | PackageName ] PackageFileName .
5532 void
5533 Parse::import_spec(void*)
5535 const Token* token = this->peek_token();
5536 Location location = token->location();
5538 std::string local_name;
5539 bool is_local_name_exported = false;
5540 if (token->is_op(OPERATOR_DOT))
5542 local_name = ".";
5543 token = this->advance_token();
5545 else if (token->is_identifier())
5547 local_name = token->identifier();
5548 is_local_name_exported = token->is_identifier_exported();
5549 token = this->advance_token();
5552 if (!token->is_string())
5554 error_at(this->location(), "import statement not a string");
5555 this->advance_token();
5556 return;
5559 this->gogo_->import_package(token->string_value(), local_name,
5560 is_local_name_exported, location);
5562 this->advance_token();
5565 // SourceFile = PackageClause ";" { ImportDecl ";" }
5566 // { TopLevelDecl ";" } .
5568 void
5569 Parse::program()
5571 this->package_clause();
5573 const Token* token = this->peek_token();
5574 if (token->is_op(OPERATOR_SEMICOLON))
5575 token = this->advance_token();
5576 else
5577 error_at(this->location(),
5578 "expected %<;%> or newline after package clause");
5580 while (token->is_keyword(KEYWORD_IMPORT))
5582 this->import_decl();
5583 token = this->peek_token();
5584 if (token->is_op(OPERATOR_SEMICOLON))
5585 token = this->advance_token();
5586 else
5587 error_at(this->location(),
5588 "expected %<;%> or newline after import declaration");
5591 while (!token->is_eof())
5593 if (this->declaration_may_start_here())
5594 this->declaration();
5595 else
5597 error_at(this->location(), "expected declaration");
5598 this->gogo_->mark_locals_used();
5600 this->advance_token();
5601 while (!this->peek_token()->is_eof()
5602 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
5603 && !this->peek_token()->is_op(OPERATOR_RCURLY));
5604 if (!this->peek_token()->is_eof()
5605 && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
5606 this->advance_token();
5608 token = this->peek_token();
5609 if (token->is_op(OPERATOR_SEMICOLON))
5610 token = this->advance_token();
5611 else if (!token->is_eof() || !saw_errors())
5613 if (token->is_op(OPERATOR_CHANOP))
5614 error_at(this->location(),
5615 ("send statement used as value; "
5616 "use select for non-blocking send"));
5617 else
5618 error_at(this->location(),
5619 "expected %<;%> or newline after top level declaration");
5620 this->skip_past_error(OPERATOR_INVALID);
5625 // Reset the current iota value.
5627 void
5628 Parse::reset_iota()
5630 this->iota_ = 0;
5633 // Return the current iota value.
5636 Parse::iota_value()
5638 return this->iota_;
5641 // Increment the current iota value.
5643 void
5644 Parse::increment_iota()
5646 ++this->iota_;
5649 // Skip forward to a semicolon or OP. OP will normally be
5650 // OPERATOR_RPAREN or OPERATOR_RCURLY. If we find a semicolon, move
5651 // past it and return. If we find OP, it will be the next token to
5652 // read. Return true if we are OK, false if we found EOF.
5654 bool
5655 Parse::skip_past_error(Operator op)
5657 this->gogo_->mark_locals_used();
5658 const Token* token = this->peek_token();
5659 while (!token->is_op(op))
5661 if (token->is_eof())
5662 return false;
5663 if (token->is_op(OPERATOR_SEMICOLON))
5665 this->advance_token();
5666 return true;
5668 token = this->advance_token();
5670 return true;
5673 // Check that an expression is not a sink.
5675 Expression*
5676 Parse::verify_not_sink(Expression* expr)
5678 if (expr->is_sink_expression())
5680 error_at(expr->location(), "cannot use _ as value");
5681 expr = Expression::make_error(expr->location());
5683 return expr;
5686 // Mark a variable as used.
5688 void
5689 Parse::mark_var_used(Named_object* no)
5691 if (no->is_variable())
5693 no->var_value()->set_is_used();
5695 // When a type switch uses := to define a variable, then for
5696 // each case with a single type we introduce a new variable with
5697 // the appropriate type. When we do, if the newly introduced
5698 // variable is used, then the type switch variable is used.
5699 Type_switch_vars::iterator p = this->type_switch_vars_.find(no);
5700 if (p != this->type_switch_vars_.end())
5701 p->second->var_value()->set_is_used();