compiler: Parse receiver as a single parameter.
[official-gcc.git] / gcc / go / gofrontend / parse.cc
blobb24de608596e878e6de93333fbfb1be3822b260a
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 = Gogo::erroneous_name();
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 (receiver != NULL)
748 names[receiver->name()] = receiver;
749 if (params != NULL)
750 this->check_signature_names(params, &names);
751 if (results != NULL)
752 this->check_signature_names(results, &names);
754 Function_type* ret = Type::make_function_type(receiver, params, results,
755 location);
756 if (is_varargs)
757 ret->set_is_varargs();
758 return ret;
761 // Parameters = "(" [ ParameterList [ "," ] ] ")" .
763 // This returns false on a parse error.
765 bool
766 Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs)
768 *pparams = NULL;
770 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
772 error_at(this->location(), "expected %<(%>");
773 return false;
776 Typed_identifier_list* params = NULL;
777 bool saw_error = false;
779 const Token* token = this->advance_token();
780 if (!token->is_op(OPERATOR_RPAREN))
782 params = this->parameter_list(is_varargs);
783 if (params == NULL)
784 saw_error = true;
785 token = this->peek_token();
788 // The optional trailing comma is picked up in parameter_list.
790 if (!token->is_op(OPERATOR_RPAREN))
791 error_at(this->location(), "expected %<)%>");
792 else
793 this->advance_token();
795 if (saw_error)
796 return false;
798 *pparams = params;
799 return true;
802 // ParameterList = ParameterDecl { "," ParameterDecl } .
804 // This sets *IS_VARARGS if the list ends with an ellipsis.
805 // IS_VARARGS will be NULL if varargs are not permitted.
807 // We pick up an optional trailing comma.
809 // This returns NULL if some error is seen.
811 Typed_identifier_list*
812 Parse::parameter_list(bool* is_varargs)
814 Location location = this->location();
815 Typed_identifier_list* ret = new Typed_identifier_list();
817 bool saw_error = false;
819 // If we see an identifier and then a comma, then we don't know
820 // whether we are looking at a list of identifiers followed by a
821 // type, or a list of types given by name. We have to do an
822 // arbitrary lookahead to figure it out.
824 bool parameters_have_names;
825 const Token* token = this->peek_token();
826 if (!token->is_identifier())
828 // This must be a type which starts with something like '*'.
829 parameters_have_names = false;
831 else
833 std::string name = token->identifier();
834 bool is_exported = token->is_identifier_exported();
835 Location location = token->location();
836 token = this->advance_token();
837 if (!token->is_op(OPERATOR_COMMA))
839 if (token->is_op(OPERATOR_DOT))
841 // This is a qualified identifier, which must turn out
842 // to be a type.
843 parameters_have_names = false;
845 else if (token->is_op(OPERATOR_RPAREN))
847 // A single identifier followed by a parenthesis must be
848 // a type name.
849 parameters_have_names = false;
851 else
853 // An identifier followed by something other than a
854 // comma or a dot or a right parenthesis must be a
855 // parameter name followed by a type.
856 parameters_have_names = true;
859 this->unget_token(Token::make_identifier_token(name, is_exported,
860 location));
862 else
864 // An identifier followed by a comma may be the first in a
865 // list of parameter names followed by a type, or it may be
866 // the first in a list of types without parameter names. To
867 // find out we gather as many identifiers separated by
868 // commas as we can.
869 std::string id_name = this->gogo_->pack_hidden_name(name,
870 is_exported);
871 ret->push_back(Typed_identifier(id_name, NULL, location));
872 bool just_saw_comma = true;
873 while (this->advance_token()->is_identifier())
875 name = this->peek_token()->identifier();
876 is_exported = this->peek_token()->is_identifier_exported();
877 location = this->peek_token()->location();
878 id_name = this->gogo_->pack_hidden_name(name, is_exported);
879 ret->push_back(Typed_identifier(id_name, NULL, location));
880 if (!this->advance_token()->is_op(OPERATOR_COMMA))
882 just_saw_comma = false;
883 break;
887 if (just_saw_comma)
889 // We saw ID1 "," ID2 "," followed by something which
890 // was not an identifier. We must be seeing the start
891 // of a type, and ID1 and ID2 must be types, and the
892 // parameters don't have names.
893 parameters_have_names = false;
895 else if (this->peek_token()->is_op(OPERATOR_RPAREN))
897 // We saw ID1 "," ID2 ")". ID1 and ID2 must be types,
898 // and the parameters don't have names.
899 parameters_have_names = false;
901 else if (this->peek_token()->is_op(OPERATOR_DOT))
903 // We saw ID1 "," ID2 ".". ID2 must be a package name,
904 // ID1 must be a type, and the parameters don't have
905 // names.
906 parameters_have_names = false;
907 this->unget_token(Token::make_identifier_token(name, is_exported,
908 location));
909 ret->pop_back();
910 just_saw_comma = true;
912 else
914 // We saw ID1 "," ID2 followed by something other than
915 // ",", ".", or ")". We must be looking at the start of
916 // a type, and ID1 and ID2 must be parameter names.
917 parameters_have_names = true;
920 if (parameters_have_names)
922 go_assert(!just_saw_comma);
923 // We have just seen ID1, ID2 xxx.
924 Type* type;
925 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
926 type = this->type();
927 else
929 error_at(this->location(), "%<...%> only permits one name");
930 saw_error = true;
931 this->advance_token();
932 type = this->type();
934 for (size_t i = 0; i < ret->size(); ++i)
935 ret->set_type(i, type);
936 if (!this->peek_token()->is_op(OPERATOR_COMMA))
937 return saw_error ? NULL : ret;
938 if (this->advance_token()->is_op(OPERATOR_RPAREN))
939 return saw_error ? NULL : ret;
941 else
943 Typed_identifier_list* tret = new Typed_identifier_list();
944 for (Typed_identifier_list::const_iterator p = ret->begin();
945 p != ret->end();
946 ++p)
948 Named_object* no = this->gogo_->lookup(p->name(), NULL);
949 Type* type;
950 if (no == NULL)
951 no = this->gogo_->add_unknown_name(p->name(),
952 p->location());
954 if (no->is_type())
955 type = no->type_value();
956 else if (no->is_unknown() || no->is_type_declaration())
957 type = Type::make_forward_declaration(no);
958 else
960 error_at(p->location(), "expected %<%s%> to be a type",
961 Gogo::message_name(p->name()).c_str());
962 saw_error = true;
963 type = Type::make_error_type();
965 tret->push_back(Typed_identifier("", type, p->location()));
967 delete ret;
968 ret = tret;
969 if (!just_saw_comma
970 || this->peek_token()->is_op(OPERATOR_RPAREN))
971 return saw_error ? NULL : ret;
976 bool mix_error = false;
977 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error,
978 &saw_error);
979 while (this->peek_token()->is_op(OPERATOR_COMMA))
981 if (this->advance_token()->is_op(OPERATOR_RPAREN))
982 break;
983 if (is_varargs != NULL && *is_varargs)
985 error_at(this->location(), "%<...%> must be last parameter");
986 saw_error = true;
988 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error,
989 &saw_error);
991 if (mix_error)
993 error_at(location, "invalid named/anonymous mix");
994 saw_error = true;
996 if (saw_error)
998 delete ret;
999 return NULL;
1001 return ret;
1004 // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
1006 void
1007 Parse::parameter_decl(bool parameters_have_names,
1008 Typed_identifier_list* til,
1009 bool* is_varargs,
1010 bool* mix_error,
1011 bool* saw_error)
1013 if (!parameters_have_names)
1015 Type* type;
1016 Location location = this->location();
1017 if (!this->peek_token()->is_identifier())
1019 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1020 type = this->type();
1021 else
1023 if (is_varargs == NULL)
1024 error_at(this->location(), "invalid use of %<...%>");
1025 else
1026 *is_varargs = true;
1027 this->advance_token();
1028 if (is_varargs == NULL
1029 && this->peek_token()->is_op(OPERATOR_RPAREN))
1030 type = Type::make_error_type();
1031 else
1033 Type* element_type = this->type();
1034 type = Type::make_array_type(element_type, NULL);
1038 else
1040 type = this->type_name(false);
1041 if (type->is_error_type()
1042 || (!this->peek_token()->is_op(OPERATOR_COMMA)
1043 && !this->peek_token()->is_op(OPERATOR_RPAREN)))
1045 *mix_error = true;
1046 while (!this->peek_token()->is_op(OPERATOR_COMMA)
1047 && !this->peek_token()->is_op(OPERATOR_RPAREN))
1048 this->advance_token();
1051 if (!type->is_error_type())
1052 til->push_back(Typed_identifier("", type, location));
1053 else
1054 *saw_error = true;
1056 else
1058 size_t orig_count = til->size();
1059 if (this->peek_token()->is_identifier())
1060 this->identifier_list(til);
1061 else
1062 *mix_error = true;
1063 size_t new_count = til->size();
1065 Type* type;
1066 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1067 type = this->type();
1068 else
1070 if (is_varargs == NULL)
1072 error_at(this->location(), "invalid use of %<...%>");
1073 *saw_error = true;
1075 else if (new_count > orig_count + 1)
1077 error_at(this->location(), "%<...%> only permits one name");
1078 *saw_error = true;
1080 else
1081 *is_varargs = true;
1082 this->advance_token();
1083 Type* element_type = this->type();
1084 type = Type::make_array_type(element_type, NULL);
1086 for (size_t i = orig_count; i < new_count; ++i)
1087 til->set_type(i, type);
1091 // Result = Parameters | Type .
1093 // This returns false on a parse error.
1095 bool
1096 Parse::result(Typed_identifier_list** presults)
1098 if (this->peek_token()->is_op(OPERATOR_LPAREN))
1099 return this->parameters(presults, NULL);
1100 else
1102 Location location = this->location();
1103 Type* type = this->type();
1104 if (type->is_error_type())
1106 *presults = NULL;
1107 return false;
1109 Typed_identifier_list* til = new Typed_identifier_list();
1110 til->push_back(Typed_identifier("", type, location));
1111 *presults = til;
1112 return true;
1116 // Block = "{" [ StatementList ] "}" .
1118 // Returns the location of the closing brace.
1120 Location
1121 Parse::block()
1123 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
1125 Location loc = this->location();
1126 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1127 && this->advance_token()->is_op(OPERATOR_LCURLY))
1128 error_at(loc, "unexpected semicolon or newline before %<{%>");
1129 else
1131 error_at(this->location(), "expected %<{%>");
1132 return Linemap::unknown_location();
1136 const Token* token = this->advance_token();
1138 if (!token->is_op(OPERATOR_RCURLY))
1140 this->statement_list();
1141 token = this->peek_token();
1142 if (!token->is_op(OPERATOR_RCURLY))
1144 if (!token->is_eof() || !saw_errors())
1145 error_at(this->location(), "expected %<}%>");
1147 this->gogo_->mark_locals_used();
1149 // Skip ahead to the end of the block, in hopes of avoiding
1150 // lots of meaningless errors.
1151 Location ret = token->location();
1152 int nest = 0;
1153 while (!token->is_eof())
1155 if (token->is_op(OPERATOR_LCURLY))
1156 ++nest;
1157 else if (token->is_op(OPERATOR_RCURLY))
1159 --nest;
1160 if (nest < 0)
1162 this->advance_token();
1163 break;
1166 token = this->advance_token();
1167 ret = token->location();
1169 return ret;
1173 Location ret = token->location();
1174 this->advance_token();
1175 return ret;
1178 // InterfaceType = "interface" "{" [ MethodSpecList ] "}" .
1179 // MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] .
1181 Type*
1182 Parse::interface_type()
1184 go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE));
1185 Location location = this->location();
1187 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
1189 Location token_loc = this->location();
1190 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1191 && this->advance_token()->is_op(OPERATOR_LCURLY))
1192 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
1193 else
1195 error_at(this->location(), "expected %<{%>");
1196 return Type::make_error_type();
1199 this->advance_token();
1201 Typed_identifier_list* methods = new Typed_identifier_list();
1202 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1204 this->method_spec(methods);
1205 while (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1207 if (this->advance_token()->is_op(OPERATOR_RCURLY))
1208 break;
1209 this->method_spec(methods);
1211 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1213 error_at(this->location(), "expected %<}%>");
1214 while (!this->advance_token()->is_op(OPERATOR_RCURLY))
1216 if (this->peek_token()->is_eof())
1217 return Type::make_error_type();
1221 this->advance_token();
1223 if (methods->empty())
1225 delete methods;
1226 methods = NULL;
1229 Interface_type* ret = Type::make_interface_type(methods, location);
1230 this->gogo_->record_interface_type(ret);
1231 return ret;
1234 // MethodSpec = MethodName Signature | InterfaceTypeName .
1235 // MethodName = identifier .
1236 // InterfaceTypeName = TypeName .
1238 void
1239 Parse::method_spec(Typed_identifier_list* methods)
1241 const Token* token = this->peek_token();
1242 if (!token->is_identifier())
1244 error_at(this->location(), "expected identifier");
1245 return;
1248 std::string name = token->identifier();
1249 bool is_exported = token->is_identifier_exported();
1250 Location location = token->location();
1252 if (this->advance_token()->is_op(OPERATOR_LPAREN))
1254 // This is a MethodName.
1255 name = this->gogo_->pack_hidden_name(name, is_exported);
1256 Type* type = this->signature(NULL, location);
1257 if (type == NULL)
1258 return;
1259 methods->push_back(Typed_identifier(name, type, location));
1261 else
1263 this->unget_token(Token::make_identifier_token(name, is_exported,
1264 location));
1265 Type* type = this->type_name(false);
1266 if (type->is_error_type()
1267 || (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1268 && !this->peek_token()->is_op(OPERATOR_RCURLY)))
1270 if (this->peek_token()->is_op(OPERATOR_COMMA))
1271 error_at(this->location(),
1272 "name list not allowed in interface type");
1273 else
1274 error_at(location, "expected signature or type name");
1275 this->gogo_->mark_locals_used();
1276 token = this->peek_token();
1277 while (!token->is_eof()
1278 && !token->is_op(OPERATOR_SEMICOLON)
1279 && !token->is_op(OPERATOR_RCURLY))
1280 token = this->advance_token();
1281 return;
1283 // This must be an interface type, but we can't check that now.
1284 // We check it and pull out the methods in
1285 // Interface_type::do_verify.
1286 methods->push_back(Typed_identifier("", type, location));
1290 // Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1292 void
1293 Parse::declaration()
1295 const Token* token = this->peek_token();
1297 bool saw_nointerface = this->lex_->get_and_clear_nointerface();
1298 if (saw_nointerface && !token->is_keyword(KEYWORD_FUNC))
1299 warning_at(token->location(), 0,
1300 "ignoring magic //go:nointerface comment before non-method");
1302 if (token->is_keyword(KEYWORD_CONST))
1303 this->const_decl();
1304 else if (token->is_keyword(KEYWORD_TYPE))
1305 this->type_decl();
1306 else if (token->is_keyword(KEYWORD_VAR))
1307 this->var_decl();
1308 else if (token->is_keyword(KEYWORD_FUNC))
1309 this->function_decl(saw_nointerface);
1310 else
1312 error_at(this->location(), "expected declaration");
1313 this->advance_token();
1317 bool
1318 Parse::declaration_may_start_here()
1320 const Token* token = this->peek_token();
1321 return (token->is_keyword(KEYWORD_CONST)
1322 || token->is_keyword(KEYWORD_TYPE)
1323 || token->is_keyword(KEYWORD_VAR)
1324 || token->is_keyword(KEYWORD_FUNC));
1327 // Decl<P> = P | "(" [ List<P> ] ")" .
1329 void
1330 Parse::decl(void (Parse::*pfn)(void*), void* varg)
1332 if (this->peek_token()->is_eof())
1334 if (!saw_errors())
1335 error_at(this->location(), "unexpected end of file");
1336 return;
1339 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1340 (this->*pfn)(varg);
1341 else
1343 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
1345 this->list(pfn, varg, true);
1346 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1348 error_at(this->location(), "missing %<)%>");
1349 while (!this->advance_token()->is_op(OPERATOR_RPAREN))
1351 if (this->peek_token()->is_eof())
1352 return;
1356 this->advance_token();
1360 // List<P> = P { ";" P } [ ";" ] .
1362 // In order to pick up the trailing semicolon we need to know what
1363 // might follow. This is either a '}' or a ')'.
1365 void
1366 Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren)
1368 (this->*pfn)(varg);
1369 Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY;
1370 while (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1371 || this->peek_token()->is_op(OPERATOR_COMMA))
1373 if (this->peek_token()->is_op(OPERATOR_COMMA))
1374 error_at(this->location(), "unexpected comma");
1375 if (this->advance_token()->is_op(follow))
1376 break;
1377 (this->*pfn)(varg);
1381 // ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1383 void
1384 Parse::const_decl()
1386 go_assert(this->peek_token()->is_keyword(KEYWORD_CONST));
1387 this->advance_token();
1388 this->reset_iota();
1390 Type* last_type = NULL;
1391 Expression_list* last_expr_list = NULL;
1393 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1394 this->const_spec(&last_type, &last_expr_list);
1395 else
1397 this->advance_token();
1398 while (!this->peek_token()->is_op(OPERATOR_RPAREN))
1400 this->const_spec(&last_type, &last_expr_list);
1401 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1402 this->advance_token();
1403 else if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1405 error_at(this->location(), "expected %<;%> or %<)%> or newline");
1406 if (!this->skip_past_error(OPERATOR_RPAREN))
1407 return;
1410 this->advance_token();
1413 if (last_expr_list != NULL)
1414 delete last_expr_list;
1417 // ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
1419 void
1420 Parse::const_spec(Type** last_type, Expression_list** last_expr_list)
1422 Typed_identifier_list til;
1423 this->identifier_list(&til);
1425 Type* type = NULL;
1426 if (this->type_may_start_here())
1428 type = this->type();
1429 *last_type = NULL;
1430 *last_expr_list = NULL;
1433 Expression_list *expr_list;
1434 if (!this->peek_token()->is_op(OPERATOR_EQ))
1436 if (*last_expr_list == NULL)
1438 error_at(this->location(), "expected %<=%>");
1439 return;
1441 type = *last_type;
1442 expr_list = new Expression_list;
1443 for (Expression_list::const_iterator p = (*last_expr_list)->begin();
1444 p != (*last_expr_list)->end();
1445 ++p)
1446 expr_list->push_back((*p)->copy());
1448 else
1450 this->advance_token();
1451 expr_list = this->expression_list(NULL, false, true);
1452 *last_type = type;
1453 if (*last_expr_list != NULL)
1454 delete *last_expr_list;
1455 *last_expr_list = expr_list;
1458 Expression_list::const_iterator pe = expr_list->begin();
1459 for (Typed_identifier_list::iterator pi = til.begin();
1460 pi != til.end();
1461 ++pi, ++pe)
1463 if (pe == expr_list->end())
1465 error_at(this->location(), "not enough initializers");
1466 return;
1468 if (type != NULL)
1469 pi->set_type(type);
1471 if (!Gogo::is_sink_name(pi->name()))
1472 this->gogo_->add_constant(*pi, *pe, this->iota_value());
1473 else
1475 static int count;
1476 char buf[30];
1477 snprintf(buf, sizeof buf, ".$sinkconst%d", count);
1478 ++count;
1479 Typed_identifier ti(std::string(buf), type, pi->location());
1480 Named_object* no = this->gogo_->add_constant(ti, *pe, this->iota_value());
1481 no->const_value()->set_is_sink();
1484 if (pe != expr_list->end())
1485 error_at(this->location(), "too many initializers");
1487 this->increment_iota();
1489 return;
1492 // TypeDecl = "type" Decl<TypeSpec> .
1494 void
1495 Parse::type_decl()
1497 go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE));
1498 this->advance_token();
1499 this->decl(&Parse::type_spec, NULL);
1502 // TypeSpec = identifier Type .
1504 void
1505 Parse::type_spec(void*)
1507 const Token* token = this->peek_token();
1508 if (!token->is_identifier())
1510 error_at(this->location(), "expected identifier");
1511 return;
1513 std::string name = token->identifier();
1514 bool is_exported = token->is_identifier_exported();
1515 Location location = token->location();
1516 token = this->advance_token();
1518 // The scope of the type name starts at the point where the
1519 // identifier appears in the source code. We implement this by
1520 // declaring the type before we read the type definition.
1521 Named_object* named_type = NULL;
1522 if (name != "_")
1524 name = this->gogo_->pack_hidden_name(name, is_exported);
1525 named_type = this->gogo_->declare_type(name, location);
1528 Type* type;
1529 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
1530 type = this->type();
1531 else
1533 error_at(this->location(),
1534 "unexpected semicolon or newline in type declaration");
1535 type = Type::make_error_type();
1536 this->advance_token();
1539 if (type->is_error_type())
1541 this->gogo_->mark_locals_used();
1542 while (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1543 && !this->peek_token()->is_eof())
1544 this->advance_token();
1547 if (name != "_")
1549 if (named_type->is_type_declaration())
1551 Type* ftype = type->forwarded();
1552 if (ftype->forward_declaration_type() != NULL
1553 && (ftype->forward_declaration_type()->named_object()
1554 == named_type))
1556 error_at(location, "invalid recursive type");
1557 type = Type::make_error_type();
1560 this->gogo_->define_type(named_type,
1561 Type::make_named_type(named_type, type,
1562 location));
1563 go_assert(named_type->package() == NULL);
1565 else
1567 // This will probably give a redefinition error.
1568 this->gogo_->add_type(name, type, location);
1573 // VarDecl = "var" Decl<VarSpec> .
1575 void
1576 Parse::var_decl()
1578 go_assert(this->peek_token()->is_keyword(KEYWORD_VAR));
1579 this->advance_token();
1580 this->decl(&Parse::var_spec, NULL);
1583 // VarSpec = IdentifierList
1584 // ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
1586 void
1587 Parse::var_spec(void*)
1589 // Get the variable names.
1590 Typed_identifier_list til;
1591 this->identifier_list(&til);
1593 Location location = this->location();
1595 Type* type = NULL;
1596 Expression_list* init = NULL;
1597 if (!this->peek_token()->is_op(OPERATOR_EQ))
1599 type = this->type();
1600 if (type->is_error_type())
1602 this->gogo_->mark_locals_used();
1603 while (!this->peek_token()->is_op(OPERATOR_EQ)
1604 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
1605 && !this->peek_token()->is_eof())
1606 this->advance_token();
1608 if (this->peek_token()->is_op(OPERATOR_EQ))
1610 this->advance_token();
1611 init = this->expression_list(NULL, false, true);
1614 else
1616 this->advance_token();
1617 init = this->expression_list(NULL, false, true);
1620 this->init_vars(&til, type, init, false, location);
1622 if (init != NULL)
1623 delete init;
1626 // Create variables. TIL is a list of variable names. If TYPE is not
1627 // NULL, it is the type of all the variables. If INIT is not NULL, it
1628 // is an initializer list for the variables.
1630 void
1631 Parse::init_vars(const Typed_identifier_list* til, Type* type,
1632 Expression_list* init, bool is_coloneq,
1633 Location location)
1635 // Check for an initialization which can yield multiple values.
1636 if (init != NULL && init->size() == 1 && til->size() > 1)
1638 if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq,
1639 location))
1640 return;
1641 if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq,
1642 location))
1643 return;
1644 if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq,
1645 location))
1646 return;
1647 if (this->init_vars_from_type_guard(til, type, *init->begin(),
1648 is_coloneq, location))
1649 return;
1652 if (init != NULL && init->size() != til->size())
1654 if (init->empty() || !init->front()->is_error_expression())
1655 error_at(location, "wrong number of initializations");
1656 init = NULL;
1657 if (type == NULL)
1658 type = Type::make_error_type();
1661 // Note that INIT was already parsed with the old name bindings, so
1662 // we don't have to worry that it will accidentally refer to the
1663 // newly declared variables. But we do have to worry about a mix of
1664 // newly declared variables and old variables if the old variables
1665 // appear in the initializations.
1667 Expression_list::const_iterator pexpr;
1668 if (init != NULL)
1669 pexpr = init->begin();
1670 bool any_new = false;
1671 Expression_list* vars = new Expression_list();
1672 Expression_list* vals = new Expression_list();
1673 for (Typed_identifier_list::const_iterator p = til->begin();
1674 p != til->end();
1675 ++p)
1677 if (init != NULL)
1678 go_assert(pexpr != init->end());
1679 this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq,
1680 false, &any_new, vars, vals);
1681 if (init != NULL)
1682 ++pexpr;
1684 if (init != NULL)
1685 go_assert(pexpr == init->end());
1686 if (is_coloneq && !any_new)
1687 error_at(location, "variables redeclared but no variable is new");
1688 this->finish_init_vars(vars, vals, location);
1691 // See if we need to initialize a list of variables from a function
1692 // call. This returns true if we have set up the variables and the
1693 // initialization.
1695 bool
1696 Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type,
1697 Expression* expr, bool is_coloneq,
1698 Location location)
1700 Call_expression* call = expr->call_expression();
1701 if (call == NULL)
1702 return false;
1704 // This is a function call. We can't check here whether it returns
1705 // the right number of values, but it might. Declare the variables,
1706 // and then assign the results of the call to them.
1708 call->set_expected_result_count(vars->size());
1710 Named_object* first_var = NULL;
1711 unsigned int index = 0;
1712 bool any_new = false;
1713 Expression_list* ivars = new Expression_list();
1714 Expression_list* ivals = new Expression_list();
1715 for (Typed_identifier_list::const_iterator pv = vars->begin();
1716 pv != vars->end();
1717 ++pv, ++index)
1719 Expression* init = Expression::make_call_result(call, index);
1720 Named_object* no = this->init_var(*pv, type, init, is_coloneq, false,
1721 &any_new, ivars, ivals);
1723 if (this->gogo_->in_global_scope() && no->is_variable())
1725 if (first_var == NULL)
1726 first_var = no;
1727 else
1729 // The subsequent vars have an implicit dependency on
1730 // the first one, so that everything gets initialized in
1731 // the right order and so that we detect cycles
1732 // correctly.
1733 this->gogo_->record_var_depends_on(no->var_value(), first_var);
1738 if (is_coloneq && !any_new)
1739 error_at(location, "variables redeclared but no variable is new");
1741 this->finish_init_vars(ivars, ivals, location);
1743 return true;
1746 // See if we need to initialize a pair of values from a map index
1747 // expression. This returns true if we have set up the variables and
1748 // the initialization.
1750 bool
1751 Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type,
1752 Expression* expr, bool is_coloneq,
1753 Location location)
1755 Index_expression* index = expr->index_expression();
1756 if (index == NULL)
1757 return false;
1758 if (vars->size() != 2)
1759 return false;
1761 // This is an index which is being assigned to two variables. It
1762 // must be a map index. Declare the variables, and then assign the
1763 // results of the map index.
1764 bool any_new = false;
1765 Typed_identifier_list::const_iterator p = vars->begin();
1766 Expression* init = type == NULL ? index : NULL;
1767 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1768 type == NULL, &any_new, NULL, NULL);
1769 if (type == NULL && any_new && val_no->is_variable())
1770 val_no->var_value()->set_type_from_init_tuple();
1771 Expression* val_var = Expression::make_var_reference(val_no, location);
1773 ++p;
1774 Type* var_type = type;
1775 if (var_type == NULL)
1776 var_type = Type::lookup_bool_type();
1777 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1778 &any_new, NULL, NULL);
1779 Expression* present_var = Expression::make_var_reference(no, location);
1781 if (is_coloneq && !any_new)
1782 error_at(location, "variables redeclared but no variable is new");
1784 Statement* s = Statement::make_tuple_map_assignment(val_var, present_var,
1785 index, location);
1787 if (!this->gogo_->in_global_scope())
1788 this->gogo_->add_statement(s);
1789 else if (!val_no->is_sink())
1791 if (val_no->is_variable())
1792 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1794 else if (!no->is_sink())
1796 if (no->is_variable())
1797 no->var_value()->add_preinit_statement(this->gogo_, s);
1799 else
1801 // Execute the map index expression just so that we can fail if
1802 // the map is nil.
1803 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1804 NULL, location);
1805 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1808 return true;
1811 // See if we need to initialize a pair of values from a receive
1812 // expression. This returns true if we have set up the variables and
1813 // the initialization.
1815 bool
1816 Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type,
1817 Expression* expr, bool is_coloneq,
1818 Location location)
1820 Receive_expression* receive = expr->receive_expression();
1821 if (receive == NULL)
1822 return false;
1823 if (vars->size() != 2)
1824 return false;
1826 // This is a receive expression which is being assigned to two
1827 // variables. Declare the variables, and then assign the results of
1828 // the receive.
1829 bool any_new = false;
1830 Typed_identifier_list::const_iterator p = vars->begin();
1831 Expression* init = type == NULL ? receive : NULL;
1832 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1833 type == NULL, &any_new, NULL, NULL);
1834 if (type == NULL && any_new && val_no->is_variable())
1835 val_no->var_value()->set_type_from_init_tuple();
1836 Expression* val_var = Expression::make_var_reference(val_no, location);
1838 ++p;
1839 Type* var_type = type;
1840 if (var_type == NULL)
1841 var_type = Type::lookup_bool_type();
1842 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1843 &any_new, NULL, NULL);
1844 Expression* received_var = Expression::make_var_reference(no, location);
1846 if (is_coloneq && !any_new)
1847 error_at(location, "variables redeclared but no variable is new");
1849 Statement* s = Statement::make_tuple_receive_assignment(val_var,
1850 received_var,
1851 receive->channel(),
1852 location);
1854 if (!this->gogo_->in_global_scope())
1855 this->gogo_->add_statement(s);
1856 else if (!val_no->is_sink())
1858 if (val_no->is_variable())
1859 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1861 else if (!no->is_sink())
1863 if (no->is_variable())
1864 no->var_value()->add_preinit_statement(this->gogo_, s);
1866 else
1868 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1869 NULL, location);
1870 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1873 return true;
1876 // See if we need to initialize a pair of values from a type guard
1877 // expression. This returns true if we have set up the variables and
1878 // the initialization.
1880 bool
1881 Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
1882 Type* type, Expression* expr,
1883 bool is_coloneq, Location location)
1885 Type_guard_expression* type_guard = expr->type_guard_expression();
1886 if (type_guard == NULL)
1887 return false;
1888 if (vars->size() != 2)
1889 return false;
1891 // This is a type guard expression which is being assigned to two
1892 // variables. Declare the variables, and then assign the results of
1893 // the type guard.
1894 bool any_new = false;
1895 Typed_identifier_list::const_iterator p = vars->begin();
1896 Type* var_type = type;
1897 if (var_type == NULL)
1898 var_type = type_guard->type();
1899 Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1900 &any_new, NULL, NULL);
1901 Expression* val_var = Expression::make_var_reference(val_no, location);
1903 ++p;
1904 var_type = type;
1905 if (var_type == NULL)
1906 var_type = Type::lookup_bool_type();
1907 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1908 &any_new, NULL, NULL);
1909 Expression* ok_var = Expression::make_var_reference(no, location);
1911 Expression* texpr = type_guard->expr();
1912 Type* t = type_guard->type();
1913 Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
1914 texpr, t,
1915 location);
1917 if (is_coloneq && !any_new)
1918 error_at(location, "variables redeclared but no variable is new");
1920 if (!this->gogo_->in_global_scope())
1921 this->gogo_->add_statement(s);
1922 else if (!val_no->is_sink())
1924 if (val_no->is_variable())
1925 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1927 else if (!no->is_sink())
1929 if (no->is_variable())
1930 no->var_value()->add_preinit_statement(this->gogo_, s);
1932 else
1934 Named_object* dummy = this->create_dummy_global(type, NULL, location);
1935 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1938 return true;
1941 // Create a single variable. If IS_COLONEQ is true, we permit
1942 // redeclarations in the same block, and we set *IS_NEW when we find a
1943 // new variable which is not a redeclaration.
1945 Named_object*
1946 Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
1947 bool is_coloneq, bool type_from_init, bool* is_new,
1948 Expression_list* vars, Expression_list* vals)
1950 Location location = tid.location();
1952 if (Gogo::is_sink_name(tid.name()))
1954 if (!type_from_init && init != NULL)
1956 if (this->gogo_->in_global_scope())
1957 return this->create_dummy_global(type, init, location);
1958 else
1960 // Create a dummy variable so that we will check whether the
1961 // initializer can be assigned to the type.
1962 Variable* var = new Variable(type, init, false, false, false,
1963 location);
1964 var->set_is_used();
1965 static int count;
1966 char buf[30];
1967 snprintf(buf, sizeof buf, "sink$%d", count);
1968 ++count;
1969 return this->gogo_->add_variable(buf, var);
1972 if (type != NULL)
1973 this->gogo_->add_type_to_verify(type);
1974 return this->gogo_->add_sink();
1977 if (is_coloneq)
1979 Named_object* no = this->gogo_->lookup_in_block(tid.name());
1980 if (no != NULL
1981 && (no->is_variable() || no->is_result_variable()))
1983 // INIT may be NULL even when IS_COLONEQ is true for cases
1984 // like v, ok := x.(int).
1985 if (!type_from_init && init != NULL)
1987 go_assert(vars != NULL && vals != NULL);
1988 vars->push_back(Expression::make_var_reference(no, location));
1989 vals->push_back(init);
1991 return no;
1994 *is_new = true;
1995 Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
1996 false, false, location);
1997 Named_object* no = this->gogo_->add_variable(tid.name(), var);
1998 if (!no->is_variable())
2000 // The name is already defined, so we just gave an error.
2001 return this->gogo_->add_sink();
2003 return no;
2006 // Create a dummy global variable to force an initializer to be run in
2007 // the right place. This is used when a sink variable is initialized
2008 // at global scope.
2010 Named_object*
2011 Parse::create_dummy_global(Type* type, Expression* init,
2012 Location location)
2014 if (type == NULL && init == NULL)
2015 type = Type::lookup_bool_type();
2016 Variable* var = new Variable(type, init, true, false, false, location);
2017 static int count;
2018 char buf[30];
2019 snprintf(buf, sizeof buf, "_.%d", count);
2020 ++count;
2021 return this->gogo_->add_variable(buf, var);
2024 // Finish the variable initialization by executing any assignments to
2025 // existing variables when using :=. These must be done as a tuple
2026 // assignment in case of something like n, a, b := 1, b, a.
2028 void
2029 Parse::finish_init_vars(Expression_list* vars, Expression_list* vals,
2030 Location location)
2032 if (vars->empty())
2034 delete vars;
2035 delete vals;
2037 else if (vars->size() == 1)
2039 go_assert(!this->gogo_->in_global_scope());
2040 this->gogo_->add_statement(Statement::make_assignment(vars->front(),
2041 vals->front(),
2042 location));
2043 delete vars;
2044 delete vals;
2046 else
2048 go_assert(!this->gogo_->in_global_scope());
2049 this->gogo_->add_statement(Statement::make_tuple_assignment(vars, vals,
2050 location));
2054 // SimpleVarDecl = identifier ":=" Expression .
2056 // We've already seen the identifier.
2058 // FIXME: We also have to implement
2059 // IdentifierList ":=" ExpressionList
2060 // In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
2061 // tuple assignments here as well.
2063 // If MAY_BE_COMPOSITE_LIT is true, the expression on the right hand
2064 // side may be a composite literal.
2066 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
2067 // RangeClause.
2069 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
2070 // guard (var := expr.("type") using the literal keyword "type").
2072 void
2073 Parse::simple_var_decl_or_assignment(const std::string& name,
2074 Location location,
2075 bool may_be_composite_lit,
2076 Range_clause* p_range_clause,
2077 Type_switch* p_type_switch)
2079 Typed_identifier_list til;
2080 til.push_back(Typed_identifier(name, NULL, location));
2082 // We've seen one identifier. If we see a comma now, this could be
2083 // "a, *p = 1, 2".
2084 if (this->peek_token()->is_op(OPERATOR_COMMA))
2086 go_assert(p_type_switch == NULL);
2087 while (true)
2089 const Token* token = this->advance_token();
2090 if (!token->is_identifier())
2091 break;
2093 std::string id = token->identifier();
2094 bool is_id_exported = token->is_identifier_exported();
2095 Location id_location = token->location();
2097 token = this->advance_token();
2098 if (!token->is_op(OPERATOR_COMMA))
2100 if (token->is_op(OPERATOR_COLONEQ))
2102 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2103 til.push_back(Typed_identifier(id, NULL, location));
2105 else
2106 this->unget_token(Token::make_identifier_token(id,
2107 is_id_exported,
2108 id_location));
2109 break;
2112 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2113 til.push_back(Typed_identifier(id, NULL, location));
2116 // We have a comma separated list of identifiers in TIL. If the
2117 // next token is COLONEQ, then this is a simple var decl, and we
2118 // have the complete list of identifiers. If the next token is
2119 // not COLONEQ, then the only valid parse is a tuple assignment.
2120 // The list of identifiers we have so far is really a list of
2121 // expressions. There are more expressions following.
2123 if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
2125 Expression_list* exprs = new Expression_list;
2126 for (Typed_identifier_list::const_iterator p = til.begin();
2127 p != til.end();
2128 ++p)
2129 exprs->push_back(this->id_to_expression(p->name(), p->location(),
2130 true));
2132 Expression_list* more_exprs =
2133 this->expression_list(NULL, true, may_be_composite_lit);
2134 for (Expression_list::const_iterator p = more_exprs->begin();
2135 p != more_exprs->end();
2136 ++p)
2137 exprs->push_back(*p);
2138 delete more_exprs;
2140 this->tuple_assignment(exprs, may_be_composite_lit, p_range_clause);
2141 return;
2145 go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
2146 const Token* token = this->advance_token();
2148 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
2150 this->range_clause_decl(&til, p_range_clause);
2151 return;
2154 Expression_list* init;
2155 if (p_type_switch == NULL)
2156 init = this->expression_list(NULL, false, may_be_composite_lit);
2157 else
2159 bool is_type_switch = false;
2160 Expression* expr = this->expression(PRECEDENCE_NORMAL, false,
2161 may_be_composite_lit,
2162 &is_type_switch, NULL);
2163 if (is_type_switch)
2165 p_type_switch->found = true;
2166 p_type_switch->name = name;
2167 p_type_switch->location = location;
2168 p_type_switch->expr = expr;
2169 return;
2172 if (!this->peek_token()->is_op(OPERATOR_COMMA))
2174 init = new Expression_list();
2175 init->push_back(expr);
2177 else
2179 this->advance_token();
2180 init = this->expression_list(expr, false, may_be_composite_lit);
2184 this->init_vars(&til, NULL, init, true, location);
2187 // FunctionDecl = "func" identifier Signature [ Block ] .
2188 // MethodDecl = "func" Receiver identifier Signature [ Block ] .
2190 // Deprecated gcc extension:
2191 // FunctionDecl = "func" identifier Signature
2192 // __asm__ "(" string_lit ")" .
2193 // This extension means a function whose real name is the identifier
2194 // inside the asm. This extension will be removed at some future
2195 // date. It has been replaced with //extern comments.
2197 // SAW_NOINTERFACE is true if we saw a magic //go:nointerface comment,
2198 // which means that we omit the method from the type descriptor.
2200 void
2201 Parse::function_decl(bool saw_nointerface)
2203 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2204 Location location = this->location();
2205 std::string extern_name = this->lex_->extern_name();
2206 const Token* token = this->advance_token();
2208 Typed_identifier* rec = NULL;
2209 if (token->is_op(OPERATOR_LPAREN))
2211 rec = this->receiver();
2212 token = this->peek_token();
2214 else if (saw_nointerface)
2216 warning_at(location, 0,
2217 "ignoring magic //go:nointerface comment before non-method");
2218 saw_nointerface = false;
2221 if (!token->is_identifier())
2223 error_at(this->location(), "expected function name");
2224 return;
2227 std::string name =
2228 this->gogo_->pack_hidden_name(token->identifier(),
2229 token->is_identifier_exported());
2231 this->advance_token();
2233 Function_type* fntype = this->signature(rec, this->location());
2235 Named_object* named_object = NULL;
2237 if (this->peek_token()->is_keyword(KEYWORD_ASM))
2239 if (!this->advance_token()->is_op(OPERATOR_LPAREN))
2241 error_at(this->location(), "expected %<(%>");
2242 return;
2244 token = this->advance_token();
2245 if (!token->is_string())
2247 error_at(this->location(), "expected string");
2248 return;
2250 std::string asm_name = token->string_value();
2251 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
2253 error_at(this->location(), "expected %<)%>");
2254 return;
2256 this->advance_token();
2257 if (!Gogo::is_sink_name(name))
2259 named_object = this->gogo_->declare_function(name, fntype, location);
2260 if (named_object->is_function_declaration())
2261 named_object->func_declaration_value()->set_asm_name(asm_name);
2265 // Check for the easy error of a newline before the opening brace.
2266 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
2268 Location semi_loc = this->location();
2269 if (this->advance_token()->is_op(OPERATOR_LCURLY))
2270 error_at(this->location(),
2271 "unexpected semicolon or newline before %<{%>");
2272 else
2273 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
2274 semi_loc));
2277 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2279 if (named_object == NULL && !Gogo::is_sink_name(name))
2281 if (fntype == NULL)
2282 this->gogo_->add_erroneous_name(name);
2283 else
2285 named_object = this->gogo_->declare_function(name, fntype,
2286 location);
2287 if (!extern_name.empty()
2288 && named_object->is_function_declaration())
2290 Function_declaration* fd =
2291 named_object->func_declaration_value();
2292 fd->set_asm_name(extern_name);
2297 if (saw_nointerface)
2298 warning_at(location, 0,
2299 ("ignoring magic //go:nointerface comment "
2300 "before declaration"));
2302 else
2304 bool hold_is_erroneous_function = this->is_erroneous_function_;
2305 if (fntype == NULL)
2307 fntype = Type::make_function_type(NULL, NULL, NULL, location);
2308 this->is_erroneous_function_ = true;
2309 if (!Gogo::is_sink_name(name))
2310 this->gogo_->add_erroneous_name(name);
2311 name = this->gogo_->pack_hidden_name("_", false);
2313 named_object = this->gogo_->start_function(name, fntype, true, location);
2314 Location end_loc = this->block();
2315 this->gogo_->finish_function(end_loc);
2316 if (saw_nointerface
2317 && !this->is_erroneous_function_
2318 && named_object->is_function())
2319 named_object->func_value()->set_nointerface();
2320 this->is_erroneous_function_ = hold_is_erroneous_function;
2324 // Receiver = Parameters .
2326 Typed_identifier*
2327 Parse::receiver()
2329 Location location = this->location();
2330 Typed_identifier_list* til;
2331 if (!this->parameters(&til, NULL))
2332 return NULL;
2333 else if (til == NULL || til->empty())
2335 error_at(location, "method has no receiver");
2336 return NULL;
2338 else if (til->size() > 1)
2340 error_at(location, "method has multiple receivers");
2341 return NULL;
2343 else
2344 return &til->front();
2347 // Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2348 // Literal = BasicLit | CompositeLit | FunctionLit .
2349 // BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2351 // If MAY_BE_SINK is true, this operand may be "_".
2353 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
2354 // if the entire expression is in parentheses.
2356 Expression*
2357 Parse::operand(bool may_be_sink, bool* is_parenthesized)
2359 const Token* token = this->peek_token();
2360 Expression* ret;
2361 switch (token->classification())
2363 case Token::TOKEN_IDENTIFIER:
2365 Location location = token->location();
2366 std::string id = token->identifier();
2367 bool is_exported = token->is_identifier_exported();
2368 std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2370 Named_object* in_function;
2371 Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2373 Package* package = NULL;
2374 if (named_object != NULL && named_object->is_package())
2376 if (!this->advance_token()->is_op(OPERATOR_DOT)
2377 || !this->advance_token()->is_identifier())
2379 error_at(location, "unexpected reference to package");
2380 return Expression::make_error(location);
2382 package = named_object->package_value();
2383 package->set_used();
2384 id = this->peek_token()->identifier();
2385 is_exported = this->peek_token()->is_identifier_exported();
2386 packed = this->gogo_->pack_hidden_name(id, is_exported);
2387 named_object = package->lookup(packed);
2388 location = this->location();
2389 go_assert(in_function == NULL);
2392 this->advance_token();
2394 if (named_object != NULL
2395 && named_object->is_type()
2396 && !named_object->type_value()->is_visible())
2398 go_assert(package != NULL);
2399 error_at(location, "invalid reference to hidden type %<%s.%s%>",
2400 Gogo::message_name(package->package_name()).c_str(),
2401 Gogo::message_name(id).c_str());
2402 return Expression::make_error(location);
2406 if (named_object == NULL)
2408 if (package != NULL)
2410 std::string n1 = Gogo::message_name(package->package_name());
2411 std::string n2 = Gogo::message_name(id);
2412 if (!is_exported)
2413 error_at(location,
2414 ("invalid reference to unexported identifier "
2415 "%<%s.%s%>"),
2416 n1.c_str(), n2.c_str());
2417 else
2418 error_at(location,
2419 "reference to undefined identifier %<%s.%s%>",
2420 n1.c_str(), n2.c_str());
2421 return Expression::make_error(location);
2424 named_object = this->gogo_->add_unknown_name(packed, location);
2427 if (in_function != NULL
2428 && in_function != this->gogo_->current_function()
2429 && (named_object->is_variable()
2430 || named_object->is_result_variable()))
2431 return this->enclosing_var_reference(in_function, named_object,
2432 location);
2434 switch (named_object->classification())
2436 case Named_object::NAMED_OBJECT_CONST:
2437 return Expression::make_const_reference(named_object, location);
2438 case Named_object::NAMED_OBJECT_TYPE:
2439 return Expression::make_type(named_object->type_value(), location);
2440 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2442 Type* t = Type::make_forward_declaration(named_object);
2443 return Expression::make_type(t, location);
2445 case Named_object::NAMED_OBJECT_VAR:
2446 case Named_object::NAMED_OBJECT_RESULT_VAR:
2447 // Any left-hand-side can be a sink, so if this can not be
2448 // a sink, then it must be a use of the variable.
2449 if (!may_be_sink)
2450 this->mark_var_used(named_object);
2451 return Expression::make_var_reference(named_object, location);
2452 case Named_object::NAMED_OBJECT_SINK:
2453 if (may_be_sink)
2454 return Expression::make_sink(location);
2455 else
2457 error_at(location, "cannot use _ as value");
2458 return Expression::make_error(location);
2460 case Named_object::NAMED_OBJECT_FUNC:
2461 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2462 return Expression::make_func_reference(named_object, NULL,
2463 location);
2464 case Named_object::NAMED_OBJECT_UNKNOWN:
2466 Unknown_expression* ue =
2467 Expression::make_unknown_reference(named_object, location);
2468 if (this->is_erroneous_function_)
2469 ue->set_no_error_message();
2470 return ue;
2472 case Named_object::NAMED_OBJECT_ERRONEOUS:
2473 return Expression::make_error(location);
2474 default:
2475 go_unreachable();
2478 go_unreachable();
2480 case Token::TOKEN_STRING:
2481 ret = Expression::make_string(token->string_value(), token->location());
2482 this->advance_token();
2483 return ret;
2485 case Token::TOKEN_CHARACTER:
2486 ret = Expression::make_character(token->character_value(), NULL,
2487 token->location());
2488 this->advance_token();
2489 return ret;
2491 case Token::TOKEN_INTEGER:
2492 ret = Expression::make_integer(token->integer_value(), NULL,
2493 token->location());
2494 this->advance_token();
2495 return ret;
2497 case Token::TOKEN_FLOAT:
2498 ret = Expression::make_float(token->float_value(), NULL,
2499 token->location());
2500 this->advance_token();
2501 return ret;
2503 case Token::TOKEN_IMAGINARY:
2505 mpfr_t zero;
2506 mpfr_init_set_ui(zero, 0, GMP_RNDN);
2507 ret = Expression::make_complex(&zero, token->imaginary_value(),
2508 NULL, token->location());
2509 mpfr_clear(zero);
2510 this->advance_token();
2511 return ret;
2514 case Token::TOKEN_KEYWORD:
2515 switch (token->keyword())
2517 case KEYWORD_FUNC:
2518 return this->function_lit();
2519 case KEYWORD_CHAN:
2520 case KEYWORD_INTERFACE:
2521 case KEYWORD_MAP:
2522 case KEYWORD_STRUCT:
2524 Location location = token->location();
2525 return Expression::make_type(this->type(), location);
2527 default:
2528 break;
2530 break;
2532 case Token::TOKEN_OPERATOR:
2533 if (token->is_op(OPERATOR_LPAREN))
2535 this->advance_token();
2536 ret = this->expression(PRECEDENCE_NORMAL, may_be_sink, true, NULL,
2537 NULL);
2538 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2539 error_at(this->location(), "missing %<)%>");
2540 else
2541 this->advance_token();
2542 if (is_parenthesized != NULL)
2543 *is_parenthesized = true;
2544 return ret;
2546 else if (token->is_op(OPERATOR_LSQUARE))
2548 // Here we call array_type directly, as this is the only
2549 // case where an ellipsis is permitted for an array type.
2550 Location location = token->location();
2551 return Expression::make_type(this->array_type(true), location);
2553 break;
2555 default:
2556 break;
2559 error_at(this->location(), "expected operand");
2560 return Expression::make_error(this->location());
2563 // Handle a reference to a variable in an enclosing function. We add
2564 // it to a list of such variables. We return a reference to a field
2565 // in a struct which will be passed on the static chain when calling
2566 // the current function.
2568 Expression*
2569 Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2570 Location location)
2572 go_assert(var->is_variable() || var->is_result_variable());
2574 this->mark_var_used(var);
2576 Named_object* this_function = this->gogo_->current_function();
2577 Named_object* closure = this_function->func_value()->closure_var();
2579 // The last argument to the Enclosing_var constructor is the index
2580 // of this variable in the closure. We add 1 to the current number
2581 // of enclosed variables, because the first field in the closure
2582 // points to the function code.
2583 Enclosing_var ev(var, in_function, this->enclosing_vars_.size() + 1);
2584 std::pair<Enclosing_vars::iterator, bool> ins =
2585 this->enclosing_vars_.insert(ev);
2586 if (ins.second)
2588 // This is a variable we have not seen before. Add a new field
2589 // to the closure type.
2590 this_function->func_value()->add_closure_field(var, location);
2593 Expression* closure_ref = Expression::make_var_reference(closure,
2594 location);
2595 closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location);
2597 // The closure structure holds pointers to the variables, so we need
2598 // to introduce an indirection.
2599 Expression* e = Expression::make_field_reference(closure_ref,
2600 ins.first->index(),
2601 location);
2602 e = Expression::make_unary(OPERATOR_MULT, e, location);
2603 return e;
2606 // CompositeLit = LiteralType LiteralValue .
2607 // LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
2608 // SliceType | MapType | TypeName .
2609 // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
2610 // ElementList = Element { "," Element } .
2611 // Element = [ Key ":" ] Value .
2612 // Key = FieldName | ElementIndex .
2613 // FieldName = identifier .
2614 // ElementIndex = Expression .
2615 // Value = Expression | LiteralValue .
2617 // We have already seen the type if there is one, and we are now
2618 // looking at the LiteralValue. The case "[" "..." "]" ElementType
2619 // will be seen here as an array type whose length is "nil". The
2620 // DEPTH parameter is non-zero if this is an embedded composite
2621 // literal and the type was omitted. It gives the number of steps up
2622 // to the type which was provided. E.g., in [][]int{{1}} it will be
2623 // 1. In [][][]int{{{1}}} it will be 2.
2625 Expression*
2626 Parse::composite_lit(Type* type, int depth, Location location)
2628 go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2629 this->advance_token();
2631 if (this->peek_token()->is_op(OPERATOR_RCURLY))
2633 this->advance_token();
2634 return Expression::make_composite_literal(type, depth, false, NULL,
2635 false, location);
2638 bool has_keys = false;
2639 bool all_are_names = true;
2640 Expression_list* vals = new Expression_list;
2641 while (true)
2643 Expression* val;
2644 bool is_type_omitted = false;
2645 bool is_name = false;
2647 const Token* token = this->peek_token();
2649 if (token->is_identifier())
2651 std::string identifier = token->identifier();
2652 bool is_exported = token->is_identifier_exported();
2653 Location location = token->location();
2655 if (this->advance_token()->is_op(OPERATOR_COLON))
2657 // This may be a field name. We don't know for sure--it
2658 // could also be an expression for an array index. We
2659 // don't want to parse it as an expression because may
2660 // trigger various errors, e.g., if this identifier
2661 // happens to be the name of a package.
2662 Gogo* gogo = this->gogo_;
2663 val = this->id_to_expression(gogo->pack_hidden_name(identifier,
2664 is_exported),
2665 location, false);
2666 is_name = true;
2668 else
2670 this->unget_token(Token::make_identifier_token(identifier,
2671 is_exported,
2672 location));
2673 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
2674 NULL);
2677 else if (!token->is_op(OPERATOR_LCURLY))
2678 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
2679 else
2681 // This must be a composite literal inside another composite
2682 // literal, with the type omitted for the inner one.
2683 val = this->composite_lit(type, depth + 1, token->location());
2684 is_type_omitted = true;
2687 token = this->peek_token();
2688 if (!token->is_op(OPERATOR_COLON))
2690 if (has_keys)
2691 vals->push_back(NULL);
2692 is_name = false;
2694 else
2696 if (is_type_omitted && !val->is_error_expression())
2698 error_at(this->location(), "unexpected %<:%>");
2699 val = Expression::make_error(this->location());
2702 this->advance_token();
2704 if (!has_keys && !vals->empty())
2706 Expression_list* newvals = new Expression_list;
2707 for (Expression_list::const_iterator p = vals->begin();
2708 p != vals->end();
2709 ++p)
2711 newvals->push_back(NULL);
2712 newvals->push_back(*p);
2714 delete vals;
2715 vals = newvals;
2717 has_keys = true;
2719 if (val->unknown_expression() != NULL)
2720 val->unknown_expression()->set_is_composite_literal_key();
2722 vals->push_back(val);
2724 if (!token->is_op(OPERATOR_LCURLY))
2725 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
2726 else
2728 // This must be a composite literal inside another
2729 // composite literal, with the type omitted for the
2730 // inner one.
2731 val = this->composite_lit(type, depth + 1, token->location());
2734 token = this->peek_token();
2737 vals->push_back(val);
2739 if (!is_name)
2740 all_are_names = false;
2742 if (token->is_op(OPERATOR_COMMA))
2744 if (this->advance_token()->is_op(OPERATOR_RCURLY))
2746 this->advance_token();
2747 break;
2750 else if (token->is_op(OPERATOR_RCURLY))
2752 this->advance_token();
2753 break;
2755 else
2757 if (token->is_op(OPERATOR_SEMICOLON))
2758 error_at(this->location(),
2759 "need trailing comma before newline in composite literal");
2760 else
2761 error_at(this->location(), "expected %<,%> or %<}%>");
2763 this->gogo_->mark_locals_used();
2764 int depth = 0;
2765 while (!token->is_eof()
2766 && (depth > 0 || !token->is_op(OPERATOR_RCURLY)))
2768 if (token->is_op(OPERATOR_LCURLY))
2769 ++depth;
2770 else if (token->is_op(OPERATOR_RCURLY))
2771 --depth;
2772 token = this->advance_token();
2774 if (token->is_op(OPERATOR_RCURLY))
2775 this->advance_token();
2777 return Expression::make_error(location);
2781 return Expression::make_composite_literal(type, depth, has_keys, vals,
2782 all_are_names, location);
2785 // FunctionLit = "func" Signature Block .
2787 Expression*
2788 Parse::function_lit()
2790 Location location = this->location();
2791 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2792 this->advance_token();
2794 Enclosing_vars hold_enclosing_vars;
2795 hold_enclosing_vars.swap(this->enclosing_vars_);
2797 Function_type* type = this->signature(NULL, location);
2798 bool fntype_is_error = false;
2799 if (type == NULL)
2801 type = Type::make_function_type(NULL, NULL, NULL, location);
2802 fntype_is_error = true;
2805 // For a function literal, the next token must be a '{'. If we
2806 // don't see that, then we may have a type expression.
2807 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2809 hold_enclosing_vars.swap(this->enclosing_vars_);
2810 return Expression::make_type(type, location);
2813 bool hold_is_erroneous_function = this->is_erroneous_function_;
2814 if (fntype_is_error)
2815 this->is_erroneous_function_ = true;
2817 Bc_stack* hold_break_stack = this->break_stack_;
2818 Bc_stack* hold_continue_stack = this->continue_stack_;
2819 this->break_stack_ = NULL;
2820 this->continue_stack_ = NULL;
2822 Named_object* no = this->gogo_->start_function("", type, true, location);
2824 Location end_loc = this->block();
2826 this->gogo_->finish_function(end_loc);
2828 if (this->break_stack_ != NULL)
2829 delete this->break_stack_;
2830 if (this->continue_stack_ != NULL)
2831 delete this->continue_stack_;
2832 this->break_stack_ = hold_break_stack;
2833 this->continue_stack_ = hold_continue_stack;
2835 this->is_erroneous_function_ = hold_is_erroneous_function;
2837 hold_enclosing_vars.swap(this->enclosing_vars_);
2839 Expression* closure = this->create_closure(no, &hold_enclosing_vars,
2840 location);
2842 return Expression::make_func_reference(no, closure, location);
2845 // Create a closure for the nested function FUNCTION. This is based
2846 // on ENCLOSING_VARS, which is a list of all variables defined in
2847 // enclosing functions and referenced from FUNCTION. A closure is the
2848 // address of a struct which point to the real function code and
2849 // contains the addresses of all the referenced variables. This
2850 // returns NULL if no closure is required.
2852 Expression*
2853 Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
2854 Location location)
2856 if (enclosing_vars->empty())
2857 return NULL;
2859 // Get the variables in order by their field index.
2861 size_t enclosing_var_count = enclosing_vars->size();
2862 std::vector<Enclosing_var> ev(enclosing_var_count);
2863 for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
2864 p != enclosing_vars->end();
2865 ++p)
2867 // Subtract 1 because index 0 is the function code.
2868 ev[p->index() - 1] = *p;
2871 // Build an initializer for a composite literal of the closure's
2872 // type.
2874 Named_object* enclosing_function = this->gogo_->current_function();
2875 Expression_list* initializer = new Expression_list;
2877 initializer->push_back(Expression::make_func_code_reference(function,
2878 location));
2880 for (size_t i = 0; i < enclosing_var_count; ++i)
2882 // Add 1 to i because the first field in the closure is a
2883 // pointer to the function code.
2884 go_assert(ev[i].index() == i + 1);
2885 Named_object* var = ev[i].var();
2886 Expression* ref;
2887 if (ev[i].in_function() == enclosing_function)
2888 ref = Expression::make_var_reference(var, location);
2889 else
2890 ref = this->enclosing_var_reference(ev[i].in_function(), var,
2891 location);
2892 Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
2893 location);
2894 initializer->push_back(refaddr);
2897 Named_object* closure_var = function->func_value()->closure_var();
2898 Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
2899 Expression* cv = Expression::make_struct_composite_literal(st, initializer,
2900 location);
2901 return Expression::make_heap_expression(cv, location);
2904 // PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
2906 // If MAY_BE_SINK is true, this expression may be "_".
2908 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
2909 // literal.
2911 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2912 // guard (var := expr.("type") using the literal keyword "type").
2914 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
2915 // if the entire expression is in parentheses.
2917 Expression*
2918 Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
2919 bool* is_type_switch, bool* is_parenthesized)
2921 Location start_loc = this->location();
2922 bool operand_is_parenthesized = false;
2923 bool whole_is_parenthesized = false;
2925 Expression* ret = this->operand(may_be_sink, &operand_is_parenthesized);
2927 whole_is_parenthesized = operand_is_parenthesized;
2929 // An unknown name followed by a curly brace must be a composite
2930 // literal, and the unknown name must be a type.
2931 if (may_be_composite_lit
2932 && !operand_is_parenthesized
2933 && ret->unknown_expression() != NULL
2934 && this->peek_token()->is_op(OPERATOR_LCURLY))
2936 Named_object* no = ret->unknown_expression()->named_object();
2937 Type* type = Type::make_forward_declaration(no);
2938 ret = Expression::make_type(type, ret->location());
2941 // We handle composite literals and type casts here, as it is the
2942 // easiest way to handle types which are in parentheses, as in
2943 // "((uint))(1)".
2944 if (ret->is_type_expression())
2946 if (this->peek_token()->is_op(OPERATOR_LCURLY))
2948 whole_is_parenthesized = false;
2949 if (!may_be_composite_lit)
2951 Type* t = ret->type();
2952 if (t->named_type() != NULL
2953 || t->forward_declaration_type() != NULL)
2954 error_at(start_loc,
2955 _("parentheses required around this composite literal "
2956 "to avoid parsing ambiguity"));
2958 else if (operand_is_parenthesized)
2959 error_at(start_loc,
2960 "cannot parenthesize type in composite literal");
2961 ret = this->composite_lit(ret->type(), 0, ret->location());
2963 else if (this->peek_token()->is_op(OPERATOR_LPAREN))
2965 whole_is_parenthesized = false;
2966 Location loc = this->location();
2967 this->advance_token();
2968 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
2969 NULL, NULL);
2970 if (this->peek_token()->is_op(OPERATOR_COMMA))
2971 this->advance_token();
2972 if (this->peek_token()->is_op(OPERATOR_ELLIPSIS))
2974 error_at(this->location(),
2975 "invalid use of %<...%> in type conversion");
2976 this->advance_token();
2978 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2979 error_at(this->location(), "expected %<)%>");
2980 else
2981 this->advance_token();
2982 if (expr->is_error_expression())
2983 ret = expr;
2984 else
2986 Type* t = ret->type();
2987 if (t->classification() == Type::TYPE_ARRAY
2988 && t->array_type()->length() != NULL
2989 && t->array_type()->length()->is_nil_expression())
2991 error_at(ret->location(),
2992 "use of %<[...]%> outside of array literal");
2993 ret = Expression::make_error(loc);
2995 else
2996 ret = Expression::make_cast(t, expr, loc);
3001 while (true)
3003 const Token* token = this->peek_token();
3004 if (token->is_op(OPERATOR_LPAREN))
3006 whole_is_parenthesized = false;
3007 ret = this->call(this->verify_not_sink(ret));
3009 else if (token->is_op(OPERATOR_DOT))
3011 whole_is_parenthesized = false;
3012 ret = this->selector(this->verify_not_sink(ret), is_type_switch);
3013 if (is_type_switch != NULL && *is_type_switch)
3014 break;
3016 else if (token->is_op(OPERATOR_LSQUARE))
3018 whole_is_parenthesized = false;
3019 ret = this->index(this->verify_not_sink(ret));
3021 else
3022 break;
3025 if (whole_is_parenthesized && is_parenthesized != NULL)
3026 *is_parenthesized = true;
3028 return ret;
3031 // Selector = "." identifier .
3032 // TypeGuard = "." "(" QualifiedIdent ")" .
3034 // Note that Operand can expand to QualifiedIdent, which contains a
3035 // ".". That is handled directly in operand when it sees a package
3036 // name.
3038 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3039 // guard (var := expr.("type") using the literal keyword "type").
3041 Expression*
3042 Parse::selector(Expression* left, bool* is_type_switch)
3044 go_assert(this->peek_token()->is_op(OPERATOR_DOT));
3045 Location location = this->location();
3047 const Token* token = this->advance_token();
3048 if (token->is_identifier())
3050 // This could be a field in a struct, or a method in an
3051 // interface, or a method associated with a type. We can't know
3052 // which until we have seen all the types.
3053 std::string name =
3054 this->gogo_->pack_hidden_name(token->identifier(),
3055 token->is_identifier_exported());
3056 if (token->identifier() == "_")
3058 error_at(this->location(), "invalid use of %<_%>");
3059 name = Gogo::erroneous_name();
3061 this->advance_token();
3062 return Expression::make_selector(left, name, location);
3064 else if (token->is_op(OPERATOR_LPAREN))
3066 this->advance_token();
3067 Type* type = NULL;
3068 if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
3069 type = this->type();
3070 else
3072 if (is_type_switch != NULL)
3073 *is_type_switch = true;
3074 else
3076 error_at(this->location(),
3077 "use of %<.(type)%> outside type switch");
3078 type = Type::make_error_type();
3080 this->advance_token();
3082 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
3083 error_at(this->location(), "missing %<)%>");
3084 else
3085 this->advance_token();
3086 if (is_type_switch != NULL && *is_type_switch)
3087 return left;
3088 return Expression::make_type_guard(left, type, location);
3090 else
3092 error_at(this->location(), "expected identifier or %<(%>");
3093 return left;
3097 // Index = "[" Expression "]" .
3098 // Slice = "[" Expression ":" [ Expression ] [ ":" Expression ] "]" .
3100 Expression*
3101 Parse::index(Expression* expr)
3103 Location location = this->location();
3104 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
3105 this->advance_token();
3107 Expression* start;
3108 if (!this->peek_token()->is_op(OPERATOR_COLON))
3109 start = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3110 else
3112 mpz_t zero;
3113 mpz_init_set_ui(zero, 0);
3114 start = Expression::make_integer(&zero, NULL, location);
3115 mpz_clear(zero);
3118 Expression* end = NULL;
3119 if (this->peek_token()->is_op(OPERATOR_COLON))
3121 // We use nil to indicate a missing high expression.
3122 if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3123 end = Expression::make_nil(this->location());
3124 else if (this->peek_token()->is_op(OPERATOR_COLON))
3126 error_at(this->location(), "middle index required in 3-index slice");
3127 end = Expression::make_error(this->location());
3129 else
3130 end = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3133 Expression* cap = NULL;
3134 if (this->peek_token()->is_op(OPERATOR_COLON))
3136 if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3138 error_at(this->location(), "final index required in 3-index slice");
3139 cap = Expression::make_error(this->location());
3141 else
3142 cap = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3144 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
3145 error_at(this->location(), "missing %<]%>");
3146 else
3147 this->advance_token();
3148 return Expression::make_index(expr, start, end, cap, location);
3151 // Call = "(" [ ArgumentList [ "," ] ] ")" .
3152 // ArgumentList = ExpressionList [ "..." ] .
3154 Expression*
3155 Parse::call(Expression* func)
3157 go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
3158 Expression_list* args = NULL;
3159 bool is_varargs = false;
3160 const Token* token = this->advance_token();
3161 if (!token->is_op(OPERATOR_RPAREN))
3163 args = this->expression_list(NULL, false, true);
3164 token = this->peek_token();
3165 if (token->is_op(OPERATOR_ELLIPSIS))
3167 is_varargs = true;
3168 token = this->advance_token();
3171 if (token->is_op(OPERATOR_COMMA))
3172 token = this->advance_token();
3173 if (!token->is_op(OPERATOR_RPAREN))
3174 error_at(this->location(), "missing %<)%>");
3175 else
3176 this->advance_token();
3177 if (func->is_error_expression())
3178 return func;
3179 return Expression::make_call(func, args, is_varargs, func->location());
3182 // Return an expression for a single unqualified identifier.
3184 Expression*
3185 Parse::id_to_expression(const std::string& name, Location location,
3186 bool is_lhs)
3188 Named_object* in_function;
3189 Named_object* named_object = this->gogo_->lookup(name, &in_function);
3190 if (named_object == NULL)
3191 named_object = this->gogo_->add_unknown_name(name, location);
3193 if (in_function != NULL
3194 && in_function != this->gogo_->current_function()
3195 && (named_object->is_variable() || named_object->is_result_variable()))
3196 return this->enclosing_var_reference(in_function, named_object,
3197 location);
3199 switch (named_object->classification())
3201 case Named_object::NAMED_OBJECT_CONST:
3202 return Expression::make_const_reference(named_object, location);
3203 case Named_object::NAMED_OBJECT_VAR:
3204 case Named_object::NAMED_OBJECT_RESULT_VAR:
3205 if (!is_lhs)
3206 this->mark_var_used(named_object);
3207 return Expression::make_var_reference(named_object, location);
3208 case Named_object::NAMED_OBJECT_SINK:
3209 return Expression::make_sink(location);
3210 case Named_object::NAMED_OBJECT_FUNC:
3211 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3212 return Expression::make_func_reference(named_object, NULL, location);
3213 case Named_object::NAMED_OBJECT_UNKNOWN:
3215 Unknown_expression* ue =
3216 Expression::make_unknown_reference(named_object, location);
3217 if (this->is_erroneous_function_)
3218 ue->set_no_error_message();
3219 return ue;
3221 case Named_object::NAMED_OBJECT_PACKAGE:
3222 case Named_object::NAMED_OBJECT_TYPE:
3223 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3225 // These cases can arise for a field name in a composite
3226 // literal.
3227 Unknown_expression* ue =
3228 Expression::make_unknown_reference(named_object, location);
3229 if (this->is_erroneous_function_)
3230 ue->set_no_error_message();
3231 return ue;
3233 case Named_object::NAMED_OBJECT_ERRONEOUS:
3234 return Expression::make_error(location);
3235 default:
3236 error_at(this->location(), "unexpected type of identifier");
3237 return Expression::make_error(location);
3241 // Expression = UnaryExpr { binary_op Expression } .
3243 // PRECEDENCE is the precedence of the current operator.
3245 // If MAY_BE_SINK is true, this expression may be "_".
3247 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3248 // literal.
3250 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3251 // guard (var := expr.("type") using the literal keyword "type").
3253 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3254 // if the entire expression is in parentheses.
3256 Expression*
3257 Parse::expression(Precedence precedence, bool may_be_sink,
3258 bool may_be_composite_lit, bool* is_type_switch,
3259 bool *is_parenthesized)
3261 Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
3262 is_type_switch, is_parenthesized);
3264 while (true)
3266 if (is_type_switch != NULL && *is_type_switch)
3267 return left;
3269 const Token* token = this->peek_token();
3270 if (token->classification() != Token::TOKEN_OPERATOR)
3272 // Not a binary_op.
3273 return left;
3276 Precedence right_precedence;
3277 switch (token->op())
3279 case OPERATOR_OROR:
3280 right_precedence = PRECEDENCE_OROR;
3281 break;
3282 case OPERATOR_ANDAND:
3283 right_precedence = PRECEDENCE_ANDAND;
3284 break;
3285 case OPERATOR_EQEQ:
3286 case OPERATOR_NOTEQ:
3287 case OPERATOR_LT:
3288 case OPERATOR_LE:
3289 case OPERATOR_GT:
3290 case OPERATOR_GE:
3291 right_precedence = PRECEDENCE_RELOP;
3292 break;
3293 case OPERATOR_PLUS:
3294 case OPERATOR_MINUS:
3295 case OPERATOR_OR:
3296 case OPERATOR_XOR:
3297 right_precedence = PRECEDENCE_ADDOP;
3298 break;
3299 case OPERATOR_MULT:
3300 case OPERATOR_DIV:
3301 case OPERATOR_MOD:
3302 case OPERATOR_LSHIFT:
3303 case OPERATOR_RSHIFT:
3304 case OPERATOR_AND:
3305 case OPERATOR_BITCLEAR:
3306 right_precedence = PRECEDENCE_MULOP;
3307 break;
3308 default:
3309 right_precedence = PRECEDENCE_INVALID;
3310 break;
3313 if (right_precedence == PRECEDENCE_INVALID)
3315 // Not a binary_op.
3316 return left;
3319 if (is_parenthesized != NULL)
3320 *is_parenthesized = false;
3322 Operator op = token->op();
3323 Location binop_location = token->location();
3325 if (precedence >= right_precedence)
3327 // We've already seen A * B, and we see + C. We want to
3328 // return so that A * B becomes a group.
3329 return left;
3332 this->advance_token();
3334 left = this->verify_not_sink(left);
3335 Expression* right = this->expression(right_precedence, false,
3336 may_be_composite_lit,
3337 NULL, NULL);
3338 left = Expression::make_binary(op, left, right, binop_location);
3342 bool
3343 Parse::expression_may_start_here()
3345 const Token* token = this->peek_token();
3346 switch (token->classification())
3348 case Token::TOKEN_INVALID:
3349 case Token::TOKEN_EOF:
3350 return false;
3351 case Token::TOKEN_KEYWORD:
3352 switch (token->keyword())
3354 case KEYWORD_CHAN:
3355 case KEYWORD_FUNC:
3356 case KEYWORD_MAP:
3357 case KEYWORD_STRUCT:
3358 case KEYWORD_INTERFACE:
3359 return true;
3360 default:
3361 return false;
3363 case Token::TOKEN_IDENTIFIER:
3364 return true;
3365 case Token::TOKEN_STRING:
3366 return true;
3367 case Token::TOKEN_OPERATOR:
3368 switch (token->op())
3370 case OPERATOR_PLUS:
3371 case OPERATOR_MINUS:
3372 case OPERATOR_NOT:
3373 case OPERATOR_XOR:
3374 case OPERATOR_MULT:
3375 case OPERATOR_CHANOP:
3376 case OPERATOR_AND:
3377 case OPERATOR_LPAREN:
3378 case OPERATOR_LSQUARE:
3379 return true;
3380 default:
3381 return false;
3383 case Token::TOKEN_CHARACTER:
3384 case Token::TOKEN_INTEGER:
3385 case Token::TOKEN_FLOAT:
3386 case Token::TOKEN_IMAGINARY:
3387 return true;
3388 default:
3389 go_unreachable();
3393 // UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3395 // If MAY_BE_SINK is true, this expression may be "_".
3397 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3398 // literal.
3400 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3401 // guard (var := expr.("type") using the literal keyword "type").
3403 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3404 // if the entire expression is in parentheses.
3406 Expression*
3407 Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3408 bool* is_type_switch, bool* is_parenthesized)
3410 const Token* token = this->peek_token();
3412 // There is a complex parse for <- chan. The choices are
3413 // Convert x to type <- chan int:
3414 // (<- chan int)(x)
3415 // Receive from (x converted to type chan <- chan int):
3416 // (<- chan <- chan int (x))
3417 // Convert x to type <- chan (<- chan int).
3418 // (<- chan <- chan int)(x)
3419 if (token->is_op(OPERATOR_CHANOP))
3421 Location location = token->location();
3422 if (this->advance_token()->is_keyword(KEYWORD_CHAN))
3424 Expression* expr = this->primary_expr(false, may_be_composite_lit,
3425 NULL, NULL);
3426 if (expr->is_error_expression())
3427 return expr;
3428 else if (!expr->is_type_expression())
3429 return Expression::make_receive(expr, location);
3430 else
3432 if (expr->type()->is_error_type())
3433 return expr;
3435 // We picked up "chan TYPE", but it is not a type
3436 // conversion.
3437 Channel_type* ct = expr->type()->channel_type();
3438 if (ct == NULL)
3440 // This is probably impossible.
3441 error_at(location, "expected channel type");
3442 return Expression::make_error(location);
3444 else if (ct->may_receive())
3446 // <- chan TYPE.
3447 Type* t = Type::make_channel_type(false, true,
3448 ct->element_type());
3449 return Expression::make_type(t, location);
3451 else
3453 // <- chan <- TYPE. Because we skipped the leading
3454 // <-, we parsed this as chan <- TYPE. With the
3455 // leading <-, we parse it as <- chan (<- TYPE).
3456 Type *t = this->reassociate_chan_direction(ct, location);
3457 return Expression::make_type(t, location);
3462 this->unget_token(Token::make_operator_token(OPERATOR_CHANOP, location));
3463 token = this->peek_token();
3466 if (token->is_op(OPERATOR_PLUS)
3467 || token->is_op(OPERATOR_MINUS)
3468 || token->is_op(OPERATOR_NOT)
3469 || token->is_op(OPERATOR_XOR)
3470 || token->is_op(OPERATOR_CHANOP)
3471 || token->is_op(OPERATOR_MULT)
3472 || token->is_op(OPERATOR_AND))
3474 Location location = token->location();
3475 Operator op = token->op();
3476 this->advance_token();
3478 Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL,
3479 NULL);
3480 if (expr->is_error_expression())
3482 else if (op == OPERATOR_MULT && expr->is_type_expression())
3483 expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3484 location);
3485 else if (op == OPERATOR_AND && expr->is_composite_literal())
3486 expr = Expression::make_heap_expression(expr, location);
3487 else if (op != OPERATOR_CHANOP)
3488 expr = Expression::make_unary(op, expr, location);
3489 else
3490 expr = Expression::make_receive(expr, location);
3491 return expr;
3493 else
3494 return this->primary_expr(may_be_sink, may_be_composite_lit,
3495 is_type_switch, is_parenthesized);
3498 // This is called for the obscure case of
3499 // (<- chan <- chan int)(x)
3500 // In unary_expr we remove the leading <- and parse the remainder,
3501 // which gives us
3502 // chan <- (chan int)
3503 // When we add the leading <- back in, we really want
3504 // <- chan (<- chan int)
3505 // This means that we need to reassociate.
3507 Type*
3508 Parse::reassociate_chan_direction(Channel_type *ct, Location location)
3510 Channel_type* ele = ct->element_type()->channel_type();
3511 if (ele == NULL)
3513 error_at(location, "parse error");
3514 return Type::make_error_type();
3516 Type* sub = ele;
3517 if (ele->may_send())
3518 sub = Type::make_channel_type(false, true, ele->element_type());
3519 else
3520 sub = this->reassociate_chan_direction(ele, location);
3521 return Type::make_channel_type(false, true, sub);
3524 // Statement =
3525 // Declaration | LabeledStmt | SimpleStmt |
3526 // GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3527 // FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3528 // DeferStmt .
3530 // LABEL is the label of this statement if it has one.
3532 void
3533 Parse::statement(Label* label)
3535 const Token* token = this->peek_token();
3536 switch (token->classification())
3538 case Token::TOKEN_KEYWORD:
3540 switch (token->keyword())
3542 case KEYWORD_CONST:
3543 case KEYWORD_TYPE:
3544 case KEYWORD_VAR:
3545 this->declaration();
3546 break;
3547 case KEYWORD_FUNC:
3548 case KEYWORD_MAP:
3549 case KEYWORD_STRUCT:
3550 case KEYWORD_INTERFACE:
3551 this->simple_stat(true, NULL, NULL, NULL);
3552 break;
3553 case KEYWORD_GO:
3554 case KEYWORD_DEFER:
3555 this->go_or_defer_stat();
3556 break;
3557 case KEYWORD_RETURN:
3558 this->return_stat();
3559 break;
3560 case KEYWORD_BREAK:
3561 this->break_stat();
3562 break;
3563 case KEYWORD_CONTINUE:
3564 this->continue_stat();
3565 break;
3566 case KEYWORD_GOTO:
3567 this->goto_stat();
3568 break;
3569 case KEYWORD_IF:
3570 this->if_stat();
3571 break;
3572 case KEYWORD_SWITCH:
3573 this->switch_stat(label);
3574 break;
3575 case KEYWORD_SELECT:
3576 this->select_stat(label);
3577 break;
3578 case KEYWORD_FOR:
3579 this->for_stat(label);
3580 break;
3581 default:
3582 error_at(this->location(), "expected statement");
3583 this->advance_token();
3584 break;
3587 break;
3589 case Token::TOKEN_IDENTIFIER:
3591 std::string identifier = token->identifier();
3592 bool is_exported = token->is_identifier_exported();
3593 Location location = token->location();
3594 if (this->advance_token()->is_op(OPERATOR_COLON))
3596 this->advance_token();
3597 this->labeled_stmt(identifier, location);
3599 else
3601 this->unget_token(Token::make_identifier_token(identifier,
3602 is_exported,
3603 location));
3604 this->simple_stat(true, NULL, NULL, NULL);
3607 break;
3609 case Token::TOKEN_OPERATOR:
3610 if (token->is_op(OPERATOR_LCURLY))
3612 Location location = token->location();
3613 this->gogo_->start_block(location);
3614 Location end_loc = this->block();
3615 this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3616 location);
3618 else if (!token->is_op(OPERATOR_SEMICOLON))
3619 this->simple_stat(true, NULL, NULL, NULL);
3620 break;
3622 case Token::TOKEN_STRING:
3623 case Token::TOKEN_CHARACTER:
3624 case Token::TOKEN_INTEGER:
3625 case Token::TOKEN_FLOAT:
3626 case Token::TOKEN_IMAGINARY:
3627 this->simple_stat(true, NULL, NULL, NULL);
3628 break;
3630 default:
3631 error_at(this->location(), "expected statement");
3632 this->advance_token();
3633 break;
3637 bool
3638 Parse::statement_may_start_here()
3640 const Token* token = this->peek_token();
3641 switch (token->classification())
3643 case Token::TOKEN_KEYWORD:
3645 switch (token->keyword())
3647 case KEYWORD_CONST:
3648 case KEYWORD_TYPE:
3649 case KEYWORD_VAR:
3650 case KEYWORD_FUNC:
3651 case KEYWORD_MAP:
3652 case KEYWORD_STRUCT:
3653 case KEYWORD_INTERFACE:
3654 case KEYWORD_GO:
3655 case KEYWORD_DEFER:
3656 case KEYWORD_RETURN:
3657 case KEYWORD_BREAK:
3658 case KEYWORD_CONTINUE:
3659 case KEYWORD_GOTO:
3660 case KEYWORD_IF:
3661 case KEYWORD_SWITCH:
3662 case KEYWORD_SELECT:
3663 case KEYWORD_FOR:
3664 return true;
3666 default:
3667 return false;
3670 break;
3672 case Token::TOKEN_IDENTIFIER:
3673 return true;
3675 case Token::TOKEN_OPERATOR:
3676 if (token->is_op(OPERATOR_LCURLY)
3677 || token->is_op(OPERATOR_SEMICOLON))
3678 return true;
3679 else
3680 return this->expression_may_start_here();
3682 case Token::TOKEN_STRING:
3683 case Token::TOKEN_CHARACTER:
3684 case Token::TOKEN_INTEGER:
3685 case Token::TOKEN_FLOAT:
3686 case Token::TOKEN_IMAGINARY:
3687 return true;
3689 default:
3690 return false;
3694 // LabeledStmt = Label ":" Statement .
3695 // Label = identifier .
3697 void
3698 Parse::labeled_stmt(const std::string& label_name, Location location)
3700 Label* label = this->gogo_->add_label_definition(label_name, location);
3702 if (this->peek_token()->is_op(OPERATOR_RCURLY))
3704 // This is a label at the end of a block. A program is
3705 // permitted to omit a semicolon here.
3706 return;
3709 if (!this->statement_may_start_here())
3711 // Mark the label as used to avoid a useless error about an
3712 // unused label.
3713 if (label != NULL)
3714 label->set_is_used();
3716 error_at(location, "missing statement after label");
3717 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3718 location));
3719 return;
3722 this->statement(label);
3725 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
3726 // Assignment | ShortVarDecl .
3728 // EmptyStmt was handled in Parse::statement.
3730 // In order to make this work for if and switch statements, if
3731 // RETURN_EXP is not NULL, and we see an ExpressionStat, we return the
3732 // expression rather than adding an expression statement to the
3733 // current block. If we see something other than an ExpressionStat,
3734 // we add the statement, set *RETURN_EXP to true if we saw a send
3735 // statement, and return NULL. The handling of send statements is for
3736 // better error messages.
3738 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
3739 // RangeClause.
3741 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
3742 // guard (var := expr.("type") using the literal keyword "type").
3744 Expression*
3745 Parse::simple_stat(bool may_be_composite_lit, bool* return_exp,
3746 Range_clause* p_range_clause, Type_switch* p_type_switch)
3748 const Token* token = this->peek_token();
3750 // An identifier follow by := is a SimpleVarDecl.
3751 if (token->is_identifier())
3753 std::string identifier = token->identifier();
3754 bool is_exported = token->is_identifier_exported();
3755 Location location = token->location();
3757 token = this->advance_token();
3758 if (token->is_op(OPERATOR_COLONEQ)
3759 || token->is_op(OPERATOR_COMMA))
3761 identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
3762 this->simple_var_decl_or_assignment(identifier, location,
3763 may_be_composite_lit,
3764 p_range_clause,
3765 (token->is_op(OPERATOR_COLONEQ)
3766 ? p_type_switch
3767 : NULL));
3768 return NULL;
3771 this->unget_token(Token::make_identifier_token(identifier, is_exported,
3772 location));
3774 else if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
3776 Typed_identifier_list til;
3777 this->range_clause_decl(&til, p_range_clause);
3778 return NULL;
3781 Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
3782 may_be_composite_lit,
3783 (p_type_switch == NULL
3784 ? NULL
3785 : &p_type_switch->found),
3786 NULL);
3787 if (p_type_switch != NULL && p_type_switch->found)
3789 p_type_switch->name.clear();
3790 p_type_switch->location = exp->location();
3791 p_type_switch->expr = this->verify_not_sink(exp);
3792 return NULL;
3794 token = this->peek_token();
3795 if (token->is_op(OPERATOR_CHANOP))
3797 this->send_stmt(this->verify_not_sink(exp));
3798 if (return_exp != NULL)
3799 *return_exp = true;
3801 else if (token->is_op(OPERATOR_PLUSPLUS)
3802 || token->is_op(OPERATOR_MINUSMINUS))
3803 this->inc_dec_stat(this->verify_not_sink(exp));
3804 else if (token->is_op(OPERATOR_COMMA)
3805 || token->is_op(OPERATOR_EQ))
3806 this->assignment(exp, may_be_composite_lit, p_range_clause);
3807 else if (token->is_op(OPERATOR_PLUSEQ)
3808 || token->is_op(OPERATOR_MINUSEQ)
3809 || token->is_op(OPERATOR_OREQ)
3810 || token->is_op(OPERATOR_XOREQ)
3811 || token->is_op(OPERATOR_MULTEQ)
3812 || token->is_op(OPERATOR_DIVEQ)
3813 || token->is_op(OPERATOR_MODEQ)
3814 || token->is_op(OPERATOR_LSHIFTEQ)
3815 || token->is_op(OPERATOR_RSHIFTEQ)
3816 || token->is_op(OPERATOR_ANDEQ)
3817 || token->is_op(OPERATOR_BITCLEAREQ))
3818 this->assignment(this->verify_not_sink(exp), may_be_composite_lit,
3819 p_range_clause);
3820 else if (return_exp != NULL)
3821 return this->verify_not_sink(exp);
3822 else
3824 exp = this->verify_not_sink(exp);
3826 if (token->is_op(OPERATOR_COLONEQ))
3828 if (!exp->is_error_expression())
3829 error_at(token->location(), "non-name on left side of %<:=%>");
3830 this->gogo_->mark_locals_used();
3831 while (!token->is_op(OPERATOR_SEMICOLON)
3832 && !token->is_eof())
3833 token = this->advance_token();
3834 return NULL;
3837 this->expression_stat(exp);
3840 return NULL;
3843 bool
3844 Parse::simple_stat_may_start_here()
3846 return this->expression_may_start_here();
3849 // Parse { Statement ";" } which is used in a few places. The list of
3850 // statements may end with a right curly brace, in which case the
3851 // semicolon may be omitted.
3853 void
3854 Parse::statement_list()
3856 while (this->statement_may_start_here())
3858 this->statement(NULL);
3859 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3860 this->advance_token();
3861 else if (this->peek_token()->is_op(OPERATOR_RCURLY))
3862 break;
3863 else
3865 if (!this->peek_token()->is_eof() || !saw_errors())
3866 error_at(this->location(), "expected %<;%> or %<}%> or newline");
3867 if (!this->skip_past_error(OPERATOR_RCURLY))
3868 return;
3873 bool
3874 Parse::statement_list_may_start_here()
3876 return this->statement_may_start_here();
3879 // ExpressionStat = Expression .
3881 void
3882 Parse::expression_stat(Expression* exp)
3884 this->gogo_->add_statement(Statement::make_statement(exp, false));
3887 // SendStmt = Channel "&lt;-" Expression .
3888 // Channel = Expression .
3890 void
3891 Parse::send_stmt(Expression* channel)
3893 go_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
3894 Location loc = this->location();
3895 this->advance_token();
3896 Expression* val = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
3897 NULL);
3898 Statement* s = Statement::make_send_statement(channel, val, loc);
3899 this->gogo_->add_statement(s);
3902 // IncDecStat = Expression ( "++" | "--" ) .
3904 void
3905 Parse::inc_dec_stat(Expression* exp)
3907 const Token* token = this->peek_token();
3909 // Lvalue maps require special handling.
3910 if (exp->index_expression() != NULL)
3911 exp->index_expression()->set_is_lvalue();
3913 if (token->is_op(OPERATOR_PLUSPLUS))
3914 this->gogo_->add_statement(Statement::make_inc_statement(exp));
3915 else if (token->is_op(OPERATOR_MINUSMINUS))
3916 this->gogo_->add_statement(Statement::make_dec_statement(exp));
3917 else
3918 go_unreachable();
3919 this->advance_token();
3922 // Assignment = ExpressionList assign_op ExpressionList .
3924 // EXP is an expression that we have already parsed.
3926 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
3927 // side may be a composite literal.
3929 // If RANGE_CLAUSE is not NULL, then this will recognize a
3930 // RangeClause.
3932 void
3933 Parse::assignment(Expression* expr, bool may_be_composite_lit,
3934 Range_clause* p_range_clause)
3936 Expression_list* vars;
3937 if (!this->peek_token()->is_op(OPERATOR_COMMA))
3939 vars = new Expression_list();
3940 vars->push_back(expr);
3942 else
3944 this->advance_token();
3945 vars = this->expression_list(expr, true, may_be_composite_lit);
3948 this->tuple_assignment(vars, may_be_composite_lit, p_range_clause);
3951 // An assignment statement. LHS is the list of expressions which
3952 // appear on the left hand side.
3954 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
3955 // side may be a composite literal.
3957 // If RANGE_CLAUSE is not NULL, then this will recognize a
3958 // RangeClause.
3960 void
3961 Parse::tuple_assignment(Expression_list* lhs, bool may_be_composite_lit,
3962 Range_clause* p_range_clause)
3964 const Token* token = this->peek_token();
3965 if (!token->is_op(OPERATOR_EQ)
3966 && !token->is_op(OPERATOR_PLUSEQ)
3967 && !token->is_op(OPERATOR_MINUSEQ)
3968 && !token->is_op(OPERATOR_OREQ)
3969 && !token->is_op(OPERATOR_XOREQ)
3970 && !token->is_op(OPERATOR_MULTEQ)
3971 && !token->is_op(OPERATOR_DIVEQ)
3972 && !token->is_op(OPERATOR_MODEQ)
3973 && !token->is_op(OPERATOR_LSHIFTEQ)
3974 && !token->is_op(OPERATOR_RSHIFTEQ)
3975 && !token->is_op(OPERATOR_ANDEQ)
3976 && !token->is_op(OPERATOR_BITCLEAREQ))
3978 error_at(this->location(), "expected assignment operator");
3979 return;
3981 Operator op = token->op();
3982 Location location = token->location();
3984 token = this->advance_token();
3986 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
3988 if (op != OPERATOR_EQ)
3989 error_at(this->location(), "range clause requires %<=%>");
3990 this->range_clause_expr(lhs, p_range_clause);
3991 return;
3994 Expression_list* vals = this->expression_list(NULL, false,
3995 may_be_composite_lit);
3997 // We've parsed everything; check for errors.
3998 if (lhs == NULL || vals == NULL)
3999 return;
4000 for (Expression_list::const_iterator pe = lhs->begin();
4001 pe != lhs->end();
4002 ++pe)
4004 if ((*pe)->is_error_expression())
4005 return;
4006 if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
4007 error_at((*pe)->location(), "cannot use _ as value");
4009 for (Expression_list::const_iterator pe = vals->begin();
4010 pe != vals->end();
4011 ++pe)
4013 if ((*pe)->is_error_expression())
4014 return;
4017 // Map expressions act differently when they are lvalues.
4018 for (Expression_list::iterator plv = lhs->begin();
4019 plv != lhs->end();
4020 ++plv)
4021 if ((*plv)->index_expression() != NULL)
4022 (*plv)->index_expression()->set_is_lvalue();
4024 Call_expression* call;
4025 Index_expression* map_index;
4026 Receive_expression* receive;
4027 Type_guard_expression* type_guard;
4028 if (lhs->size() == vals->size())
4030 Statement* s;
4031 if (lhs->size() > 1)
4033 if (op != OPERATOR_EQ)
4034 error_at(location, "multiple values only permitted with %<=%>");
4035 s = Statement::make_tuple_assignment(lhs, vals, location);
4037 else
4039 if (op == OPERATOR_EQ)
4040 s = Statement::make_assignment(lhs->front(), vals->front(),
4041 location);
4042 else
4043 s = Statement::make_assignment_operation(op, lhs->front(),
4044 vals->front(), location);
4045 delete lhs;
4046 delete vals;
4048 this->gogo_->add_statement(s);
4050 else if (vals->size() == 1
4051 && (call = (*vals->begin())->call_expression()) != NULL)
4053 if (op != OPERATOR_EQ)
4054 error_at(location, "multiple results only permitted with %<=%>");
4055 call->set_expected_result_count(lhs->size());
4056 delete vals;
4057 vals = new Expression_list;
4058 for (unsigned int i = 0; i < lhs->size(); ++i)
4059 vals->push_back(Expression::make_call_result(call, i));
4060 Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
4061 this->gogo_->add_statement(s);
4063 else if (lhs->size() == 2
4064 && vals->size() == 1
4065 && (map_index = (*vals->begin())->index_expression()) != NULL)
4067 if (op != OPERATOR_EQ)
4068 error_at(location, "two values from map requires %<=%>");
4069 Expression* val = lhs->front();
4070 Expression* present = lhs->back();
4071 Statement* s = Statement::make_tuple_map_assignment(val, present,
4072 map_index, location);
4073 this->gogo_->add_statement(s);
4075 else if (lhs->size() == 1
4076 && vals->size() == 2
4077 && (map_index = lhs->front()->index_expression()) != NULL)
4079 if (op != OPERATOR_EQ)
4080 error_at(location, "assigning tuple to map index requires %<=%>");
4081 Expression* val = vals->front();
4082 Expression* should_set = vals->back();
4083 Statement* s = Statement::make_map_assignment(map_index, val, should_set,
4084 location);
4085 this->gogo_->add_statement(s);
4087 else if (lhs->size() == 2
4088 && vals->size() == 1
4089 && (receive = (*vals->begin())->receive_expression()) != NULL)
4091 if (op != OPERATOR_EQ)
4092 error_at(location, "two values from receive requires %<=%>");
4093 Expression* val = lhs->front();
4094 Expression* success = lhs->back();
4095 Expression* channel = receive->channel();
4096 Statement* s = Statement::make_tuple_receive_assignment(val, success,
4097 channel,
4098 location);
4099 this->gogo_->add_statement(s);
4101 else if (lhs->size() == 2
4102 && vals->size() == 1
4103 && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
4105 if (op != OPERATOR_EQ)
4106 error_at(location, "two values from type guard requires %<=%>");
4107 Expression* val = lhs->front();
4108 Expression* ok = lhs->back();
4109 Expression* expr = type_guard->expr();
4110 Type* type = type_guard->type();
4111 Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
4112 expr, type,
4113 location);
4114 this->gogo_->add_statement(s);
4116 else
4118 error_at(location, "number of variables does not match number of values");
4122 // GoStat = "go" Expression .
4123 // DeferStat = "defer" Expression .
4125 void
4126 Parse::go_or_defer_stat()
4128 go_assert(this->peek_token()->is_keyword(KEYWORD_GO)
4129 || this->peek_token()->is_keyword(KEYWORD_DEFER));
4130 bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
4131 Location stat_location = this->location();
4133 this->advance_token();
4134 Location expr_location = this->location();
4136 bool is_parenthesized = false;
4137 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
4138 &is_parenthesized);
4139 Call_expression* call_expr = expr->call_expression();
4140 if (is_parenthesized || call_expr == NULL)
4142 error_at(expr_location, "argument to go/defer must be function call");
4143 return;
4146 // Make it easier to simplify go/defer statements by putting every
4147 // statement in its own block.
4148 this->gogo_->start_block(stat_location);
4149 Statement* stat;
4150 if (is_go)
4151 stat = Statement::make_go_statement(call_expr, stat_location);
4152 else
4153 stat = Statement::make_defer_statement(call_expr, stat_location);
4154 this->gogo_->add_statement(stat);
4155 this->gogo_->add_block(this->gogo_->finish_block(stat_location),
4156 stat_location);
4159 // ReturnStat = "return" [ ExpressionList ] .
4161 void
4162 Parse::return_stat()
4164 go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
4165 Location location = this->location();
4166 this->advance_token();
4167 Expression_list* vals = NULL;
4168 if (this->expression_may_start_here())
4169 vals = this->expression_list(NULL, false, true);
4170 this->gogo_->add_statement(Statement::make_return_statement(vals, location));
4172 if (vals == NULL
4173 && this->gogo_->current_function()->func_value()->results_are_named())
4175 Named_object* function = this->gogo_->current_function();
4176 Function::Results* results = function->func_value()->result_variables();
4177 for (Function::Results::const_iterator p = results->begin();
4178 p != results->end();
4179 ++p)
4181 Named_object* no = this->gogo_->lookup((*p)->name(), NULL);
4182 if (no == NULL)
4183 go_assert(saw_errors());
4184 else if (!no->is_result_variable())
4185 error_at(location, "%qs is shadowed during return",
4186 (*p)->message_name().c_str());
4191 // IfStmt = "if" [ SimpleStmt ";" ] Expression Block
4192 // [ "else" ( IfStmt | Block ) ] .
4194 void
4195 Parse::if_stat()
4197 go_assert(this->peek_token()->is_keyword(KEYWORD_IF));
4198 Location location = this->location();
4199 this->advance_token();
4201 this->gogo_->start_block(location);
4203 bool saw_simple_stat = false;
4204 Expression* cond = NULL;
4205 bool saw_send_stmt = false;
4206 if (this->simple_stat_may_start_here())
4208 cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL);
4209 saw_simple_stat = true;
4211 if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4213 // The SimpleStat is an expression statement.
4214 this->expression_stat(cond);
4215 cond = NULL;
4217 if (cond == NULL)
4219 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4220 this->advance_token();
4221 else if (saw_simple_stat)
4223 if (saw_send_stmt)
4224 error_at(this->location(),
4225 ("send statement used as value; "
4226 "use select for non-blocking send"));
4227 else
4228 error_at(this->location(),
4229 "expected %<;%> after statement in if expression");
4230 if (!this->expression_may_start_here())
4231 cond = Expression::make_error(this->location());
4233 if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY))
4235 error_at(this->location(),
4236 "missing condition in if statement");
4237 cond = Expression::make_error(this->location());
4239 if (cond == NULL)
4240 cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL, NULL);
4243 // Check for the easy error of a newline before starting the block.
4244 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4246 Location semi_loc = this->location();
4247 if (this->advance_token()->is_op(OPERATOR_LCURLY))
4248 error_at(semi_loc, "missing %<{%> after if clause");
4249 // Otherwise we will get an error when we call this->block
4250 // below.
4253 this->gogo_->start_block(this->location());
4254 Location end_loc = this->block();
4255 Block* then_block = this->gogo_->finish_block(end_loc);
4257 // Check for the easy error of a newline before "else".
4258 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4260 Location semi_loc = this->location();
4261 if (this->advance_token()->is_keyword(KEYWORD_ELSE))
4262 error_at(this->location(),
4263 "unexpected semicolon or newline before %<else%>");
4264 else
4265 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4266 semi_loc));
4269 Block* else_block = NULL;
4270 if (this->peek_token()->is_keyword(KEYWORD_ELSE))
4272 this->gogo_->start_block(this->location());
4273 const Token* token = this->advance_token();
4274 if (token->is_keyword(KEYWORD_IF))
4275 this->if_stat();
4276 else if (token->is_op(OPERATOR_LCURLY))
4277 this->block();
4278 else
4280 error_at(this->location(), "expected %<if%> or %<{%>");
4281 this->statement(NULL);
4283 else_block = this->gogo_->finish_block(this->location());
4286 this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
4287 else_block,
4288 location));
4290 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4291 location);
4294 // SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4295 // ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
4296 // "{" { ExprCaseClause } "}" .
4297 // TypeSwitchStmt = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
4298 // "{" { TypeCaseClause } "}" .
4299 // TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
4301 void
4302 Parse::switch_stat(Label* label)
4304 go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
4305 Location location = this->location();
4306 this->advance_token();
4308 this->gogo_->start_block(location);
4310 bool saw_simple_stat = false;
4311 Expression* switch_val = NULL;
4312 bool saw_send_stmt;
4313 Type_switch type_switch;
4314 bool have_type_switch_block = false;
4315 if (this->simple_stat_may_start_here())
4317 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4318 &type_switch);
4319 saw_simple_stat = true;
4321 if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4323 // The SimpleStat is an expression statement.
4324 this->expression_stat(switch_val);
4325 switch_val = NULL;
4327 if (switch_val == NULL && !type_switch.found)
4329 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4330 this->advance_token();
4331 else if (saw_simple_stat)
4333 if (saw_send_stmt)
4334 error_at(this->location(),
4335 ("send statement used as value; "
4336 "use select for non-blocking send"));
4337 else
4338 error_at(this->location(),
4339 "expected %<;%> after statement in switch expression");
4341 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4343 if (this->peek_token()->is_identifier())
4345 const Token* token = this->peek_token();
4346 std::string identifier = token->identifier();
4347 bool is_exported = token->is_identifier_exported();
4348 Location id_loc = token->location();
4350 token = this->advance_token();
4351 bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
4352 this->unget_token(Token::make_identifier_token(identifier,
4353 is_exported,
4354 id_loc));
4355 if (is_coloneq)
4357 // This must be a TypeSwitchGuard. It is in a
4358 // different block from any initial SimpleStat.
4359 if (saw_simple_stat)
4361 this->gogo_->start_block(id_loc);
4362 have_type_switch_block = true;
4365 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4366 &type_switch);
4367 if (!type_switch.found)
4369 if (switch_val == NULL
4370 || !switch_val->is_error_expression())
4372 error_at(id_loc, "expected type switch assignment");
4373 switch_val = Expression::make_error(id_loc);
4378 if (switch_val == NULL && !type_switch.found)
4380 switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
4381 &type_switch.found, NULL);
4382 if (type_switch.found)
4384 type_switch.name.clear();
4385 type_switch.expr = switch_val;
4386 type_switch.location = switch_val->location();
4392 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4394 Location token_loc = this->location();
4395 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
4396 && this->advance_token()->is_op(OPERATOR_LCURLY))
4397 error_at(token_loc, "missing %<{%> after switch clause");
4398 else if (this->peek_token()->is_op(OPERATOR_COLONEQ))
4400 error_at(token_loc, "invalid variable name");
4401 this->advance_token();
4402 this->expression(PRECEDENCE_NORMAL, false, false,
4403 &type_switch.found, NULL);
4404 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4405 this->advance_token();
4406 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4408 if (have_type_switch_block)
4409 this->gogo_->add_block(this->gogo_->finish_block(location),
4410 location);
4411 this->gogo_->add_block(this->gogo_->finish_block(location),
4412 location);
4413 return;
4415 if (type_switch.found)
4416 type_switch.expr = Expression::make_error(location);
4418 else
4420 error_at(this->location(), "expected %<{%>");
4421 if (have_type_switch_block)
4422 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4423 location);
4424 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4425 location);
4426 return;
4429 this->advance_token();
4431 Statement* statement;
4432 if (type_switch.found)
4433 statement = this->type_switch_body(label, type_switch, location);
4434 else
4435 statement = this->expr_switch_body(label, switch_val, location);
4437 if (statement != NULL)
4438 this->gogo_->add_statement(statement);
4440 if (have_type_switch_block)
4441 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4442 location);
4444 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4445 location);
4448 // The body of an expression switch.
4449 // "{" { ExprCaseClause } "}"
4451 Statement*
4452 Parse::expr_switch_body(Label* label, Expression* switch_val,
4453 Location location)
4455 Switch_statement* statement = Statement::make_switch_statement(switch_val,
4456 location);
4458 this->push_break_statement(statement, label);
4460 Case_clauses* case_clauses = new Case_clauses();
4461 bool saw_default = false;
4462 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4464 if (this->peek_token()->is_eof())
4466 if (!saw_errors())
4467 error_at(this->location(), "missing %<}%>");
4468 return NULL;
4470 this->expr_case_clause(case_clauses, &saw_default);
4472 this->advance_token();
4474 statement->add_clauses(case_clauses);
4476 this->pop_break_statement();
4478 return statement;
4481 // ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
4482 // FallthroughStat = "fallthrough" .
4484 void
4485 Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
4487 Location location = this->location();
4489 bool is_default = false;
4490 Expression_list* vals = this->expr_switch_case(&is_default);
4492 if (!this->peek_token()->is_op(OPERATOR_COLON))
4494 if (!saw_errors())
4495 error_at(this->location(), "expected %<:%>");
4496 return;
4498 else
4499 this->advance_token();
4501 Block* statements = NULL;
4502 if (this->statement_list_may_start_here())
4504 this->gogo_->start_block(this->location());
4505 this->statement_list();
4506 statements = this->gogo_->finish_block(this->location());
4509 bool is_fallthrough = false;
4510 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4512 Location fallthrough_loc = this->location();
4513 is_fallthrough = true;
4514 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4515 this->advance_token();
4516 if (this->peek_token()->is_op(OPERATOR_RCURLY))
4517 error_at(fallthrough_loc, _("cannot fallthrough final case in switch"));
4520 if (is_default)
4522 if (*saw_default)
4524 error_at(location, "multiple defaults in switch");
4525 return;
4527 *saw_default = true;
4530 if (is_default || vals != NULL)
4531 clauses->add(vals, is_default, statements, is_fallthrough, location);
4534 // ExprSwitchCase = "case" ExpressionList | "default" .
4536 Expression_list*
4537 Parse::expr_switch_case(bool* is_default)
4539 const Token* token = this->peek_token();
4540 if (token->is_keyword(KEYWORD_CASE))
4542 this->advance_token();
4543 return this->expression_list(NULL, false, true);
4545 else if (token->is_keyword(KEYWORD_DEFAULT))
4547 this->advance_token();
4548 *is_default = true;
4549 return NULL;
4551 else
4553 if (!saw_errors())
4554 error_at(this->location(), "expected %<case%> or %<default%>");
4555 if (!token->is_op(OPERATOR_RCURLY))
4556 this->advance_token();
4557 return NULL;
4561 // The body of a type switch.
4562 // "{" { TypeCaseClause } "}" .
4564 Statement*
4565 Parse::type_switch_body(Label* label, const Type_switch& type_switch,
4566 Location location)
4568 Named_object* switch_no = NULL;
4569 if (!type_switch.name.empty())
4571 if (Gogo::is_sink_name(type_switch.name))
4572 error_at(type_switch.location,
4573 "no new variables on left side of %<:=%>");
4574 else
4576 Variable* switch_var = new Variable(NULL, type_switch.expr, false,
4577 false, false,
4578 type_switch.location);
4579 switch_no = this->gogo_->add_variable(type_switch.name, switch_var);
4583 Type_switch_statement* statement =
4584 Statement::make_type_switch_statement(switch_no,
4585 (switch_no == NULL
4586 ? type_switch.expr
4587 : NULL),
4588 location);
4590 this->push_break_statement(statement, label);
4592 Type_case_clauses* case_clauses = new Type_case_clauses();
4593 bool saw_default = false;
4594 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4596 if (this->peek_token()->is_eof())
4598 error_at(this->location(), "missing %<}%>");
4599 return NULL;
4601 this->type_case_clause(switch_no, case_clauses, &saw_default);
4603 this->advance_token();
4605 statement->add_clauses(case_clauses);
4607 this->pop_break_statement();
4609 return statement;
4612 // TypeCaseClause = TypeSwitchCase ":" [ StatementList ] .
4614 void
4615 Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses,
4616 bool* saw_default)
4618 Location location = this->location();
4620 std::vector<Type*> types;
4621 bool is_default = false;
4622 this->type_switch_case(&types, &is_default);
4624 if (!this->peek_token()->is_op(OPERATOR_COLON))
4625 error_at(this->location(), "expected %<:%>");
4626 else
4627 this->advance_token();
4629 Block* statements = NULL;
4630 if (this->statement_list_may_start_here())
4632 this->gogo_->start_block(this->location());
4633 if (switch_no != NULL && types.size() == 1)
4635 Type* type = types.front();
4636 Expression* init = Expression::make_var_reference(switch_no,
4637 location);
4638 init = Expression::make_type_guard(init, type, location);
4639 Variable* v = new Variable(type, init, false, false, false,
4640 location);
4641 v->set_is_type_switch_var();
4642 Named_object* no = this->gogo_->add_variable(switch_no->name(), v);
4644 // We don't want to issue an error if the compiler
4645 // introduced special variable is not used. Instead we want
4646 // to issue an error if the variable defined by the switch
4647 // is not used. That is handled via type_switch_vars_ and
4648 // Parse::mark_var_used.
4649 v->set_is_used();
4650 this->type_switch_vars_[no] = switch_no;
4652 this->statement_list();
4653 statements = this->gogo_->finish_block(this->location());
4656 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4658 error_at(this->location(),
4659 "fallthrough is not permitted in a type switch");
4660 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4661 this->advance_token();
4664 if (is_default)
4666 go_assert(types.empty());
4667 if (*saw_default)
4669 error_at(location, "multiple defaults in type switch");
4670 return;
4672 *saw_default = true;
4673 clauses->add(NULL, false, true, statements, location);
4675 else if (!types.empty())
4677 for (std::vector<Type*>::const_iterator p = types.begin();
4678 p + 1 != types.end();
4679 ++p)
4680 clauses->add(*p, true, false, NULL, location);
4681 clauses->add(types.back(), false, false, statements, location);
4683 else
4684 clauses->add(Type::make_error_type(), false, false, statements, location);
4687 // TypeSwitchCase = "case" type | "default"
4689 // We accept a comma separated list of types.
4691 void
4692 Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
4694 const Token* token = this->peek_token();
4695 if (token->is_keyword(KEYWORD_CASE))
4697 this->advance_token();
4698 while (true)
4700 Type* t = this->type();
4702 if (!t->is_error_type())
4703 types->push_back(t);
4704 else
4706 this->gogo_->mark_locals_used();
4707 token = this->peek_token();
4708 while (!token->is_op(OPERATOR_COLON)
4709 && !token->is_op(OPERATOR_COMMA)
4710 && !token->is_op(OPERATOR_RCURLY)
4711 && !token->is_eof())
4712 token = this->advance_token();
4715 if (!this->peek_token()->is_op(OPERATOR_COMMA))
4716 break;
4717 this->advance_token();
4720 else if (token->is_keyword(KEYWORD_DEFAULT))
4722 this->advance_token();
4723 *is_default = true;
4725 else
4727 error_at(this->location(), "expected %<case%> or %<default%>");
4728 if (!token->is_op(OPERATOR_RCURLY))
4729 this->advance_token();
4733 // SelectStat = "select" "{" { CommClause } "}" .
4735 void
4736 Parse::select_stat(Label* label)
4738 go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
4739 Location location = this->location();
4740 const Token* token = this->advance_token();
4742 if (!token->is_op(OPERATOR_LCURLY))
4744 Location token_loc = token->location();
4745 if (token->is_op(OPERATOR_SEMICOLON)
4746 && this->advance_token()->is_op(OPERATOR_LCURLY))
4747 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4748 else
4750 error_at(this->location(), "expected %<{%>");
4751 return;
4754 this->advance_token();
4756 Select_statement* statement = Statement::make_select_statement(location);
4758 this->push_break_statement(statement, label);
4760 Select_clauses* select_clauses = new Select_clauses();
4761 bool saw_default = false;
4762 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4764 if (this->peek_token()->is_eof())
4766 error_at(this->location(), "expected %<}%>");
4767 return;
4769 this->comm_clause(select_clauses, &saw_default);
4772 this->advance_token();
4774 statement->add_clauses(select_clauses);
4776 this->pop_break_statement();
4778 this->gogo_->add_statement(statement);
4781 // CommClause = CommCase ":" { Statement ";" } .
4783 void
4784 Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
4786 Location location = this->location();
4787 bool is_send = false;
4788 Expression* channel = NULL;
4789 Expression* val = NULL;
4790 Expression* closed = NULL;
4791 std::string varname;
4792 std::string closedname;
4793 bool is_default = false;
4794 bool got_case = this->comm_case(&is_send, &channel, &val, &closed,
4795 &varname, &closedname, &is_default);
4797 if (!is_send
4798 && varname.empty()
4799 && closedname.empty()
4800 && val != NULL
4801 && val->index_expression() != NULL)
4802 val->index_expression()->set_is_lvalue();
4804 if (this->peek_token()->is_op(OPERATOR_COLON))
4805 this->advance_token();
4806 else
4807 error_at(this->location(), "expected colon");
4809 this->gogo_->start_block(this->location());
4811 Named_object* var = NULL;
4812 if (!varname.empty())
4814 // FIXME: LOCATION is slightly wrong here.
4815 Variable* v = new Variable(NULL, channel, false, false, false,
4816 location);
4817 v->set_type_from_chan_element();
4818 var = this->gogo_->add_variable(varname, v);
4821 Named_object* closedvar = NULL;
4822 if (!closedname.empty())
4824 // FIXME: LOCATION is slightly wrong here.
4825 Variable* v = new Variable(Type::lookup_bool_type(), NULL,
4826 false, false, false, location);
4827 closedvar = this->gogo_->add_variable(closedname, v);
4830 this->statement_list();
4832 Block* statements = this->gogo_->finish_block(this->location());
4834 if (is_default)
4836 if (*saw_default)
4838 error_at(location, "multiple defaults in select");
4839 return;
4841 *saw_default = true;
4844 if (got_case)
4845 clauses->add(is_send, channel, val, closed, var, closedvar, is_default,
4846 statements, location);
4847 else if (statements != NULL)
4849 // Add the statements to make sure that any names they define
4850 // are traversed.
4851 this->gogo_->add_block(statements, location);
4855 // CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
4857 bool
4858 Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
4859 Expression** closed, std::string* varname,
4860 std::string* closedname, bool* is_default)
4862 const Token* token = this->peek_token();
4863 if (token->is_keyword(KEYWORD_DEFAULT))
4865 this->advance_token();
4866 *is_default = true;
4868 else if (token->is_keyword(KEYWORD_CASE))
4870 this->advance_token();
4871 if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname,
4872 closedname))
4873 return false;
4875 else
4877 error_at(this->location(), "expected %<case%> or %<default%>");
4878 if (!token->is_op(OPERATOR_RCURLY))
4879 this->advance_token();
4880 return false;
4883 return true;
4886 // RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
4887 // RecvExpr = Expression .
4889 bool
4890 Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val,
4891 Expression** closed, std::string* varname,
4892 std::string* closedname)
4894 const Token* token = this->peek_token();
4895 bool saw_comma = false;
4896 bool closed_is_id = false;
4897 if (token->is_identifier())
4899 Gogo* gogo = this->gogo_;
4900 std::string recv_var = token->identifier();
4901 bool is_rv_exported = token->is_identifier_exported();
4902 Location recv_var_loc = token->location();
4903 token = this->advance_token();
4904 if (token->is_op(OPERATOR_COLONEQ))
4906 // case rv := <-c:
4907 this->advance_token();
4908 Expression* e = this->expression(PRECEDENCE_NORMAL, false, false,
4909 NULL, NULL);
4910 Receive_expression* re = e->receive_expression();
4911 if (re == NULL)
4913 if (!e->is_error_expression())
4914 error_at(this->location(), "expected receive expression");
4915 return false;
4917 if (recv_var == "_")
4919 error_at(recv_var_loc,
4920 "no new variables on left side of %<:=%>");
4921 recv_var = Gogo::erroneous_name();
4923 *is_send = false;
4924 *varname = gogo->pack_hidden_name(recv_var, is_rv_exported);
4925 *channel = re->channel();
4926 return true;
4928 else if (token->is_op(OPERATOR_COMMA))
4930 token = this->advance_token();
4931 if (token->is_identifier())
4933 std::string recv_closed = token->identifier();
4934 bool is_rc_exported = token->is_identifier_exported();
4935 Location recv_closed_loc = token->location();
4936 closed_is_id = true;
4938 token = this->advance_token();
4939 if (token->is_op(OPERATOR_COLONEQ))
4941 // case rv, rc := <-c:
4942 this->advance_token();
4943 Expression* e = this->expression(PRECEDENCE_NORMAL, false,
4944 false, NULL, NULL);
4945 Receive_expression* re = e->receive_expression();
4946 if (re == NULL)
4948 if (!e->is_error_expression())
4949 error_at(this->location(),
4950 "expected receive expression");
4951 return false;
4953 if (recv_var == "_" && recv_closed == "_")
4955 error_at(recv_var_loc,
4956 "no new variables on left side of %<:=%>");
4957 recv_var = Gogo::erroneous_name();
4959 *is_send = false;
4960 if (recv_var != "_")
4961 *varname = gogo->pack_hidden_name(recv_var,
4962 is_rv_exported);
4963 if (recv_closed != "_")
4964 *closedname = gogo->pack_hidden_name(recv_closed,
4965 is_rc_exported);
4966 *channel = re->channel();
4967 return true;
4970 this->unget_token(Token::make_identifier_token(recv_closed,
4971 is_rc_exported,
4972 recv_closed_loc));
4975 *val = this->id_to_expression(gogo->pack_hidden_name(recv_var,
4976 is_rv_exported),
4977 recv_var_loc, true);
4978 saw_comma = true;
4980 else
4981 this->unget_token(Token::make_identifier_token(recv_var,
4982 is_rv_exported,
4983 recv_var_loc));
4986 // If SAW_COMMA is false, then we are looking at the start of the
4987 // send or receive expression. If SAW_COMMA is true, then *VAL is
4988 // set and we just read a comma.
4990 Expression* e;
4991 if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP))
4992 e = this->expression(PRECEDENCE_NORMAL, true, true, NULL, NULL);
4993 else
4995 // case <-c:
4996 *is_send = false;
4997 this->advance_token();
4998 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5000 // The next token should be ':'. If it is '<-', then we have
5001 // case <-c <- v:
5002 // which is to say, send on a channel received from a channel.
5003 if (!this->peek_token()->is_op(OPERATOR_CHANOP))
5004 return true;
5006 e = Expression::make_receive(*channel, (*channel)->location());
5009 if (this->peek_token()->is_op(OPERATOR_EQ))
5011 if (!this->advance_token()->is_op(OPERATOR_CHANOP))
5013 error_at(this->location(), "missing %<<-%>");
5014 return false;
5016 *is_send = false;
5017 this->advance_token();
5018 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5019 if (saw_comma)
5021 // case v, e = <-c:
5022 // *VAL is already set.
5023 if (!e->is_sink_expression())
5024 *closed = e;
5026 else
5028 // case v = <-c:
5029 if (!e->is_sink_expression())
5030 *val = e;
5032 return true;
5035 if (saw_comma)
5037 if (closed_is_id)
5038 error_at(this->location(), "expected %<=%> or %<:=%>");
5039 else
5040 error_at(this->location(), "expected %<=%>");
5041 return false;
5044 if (this->peek_token()->is_op(OPERATOR_CHANOP))
5046 // case c <- v:
5047 *is_send = true;
5048 *channel = this->verify_not_sink(e);
5049 this->advance_token();
5050 *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5051 return true;
5054 error_at(this->location(), "expected %<<-%> or %<=%>");
5055 return false;
5058 // ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
5059 // Condition = Expression .
5061 void
5062 Parse::for_stat(Label* label)
5064 go_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
5065 Location location = this->location();
5066 const Token* token = this->advance_token();
5068 // Open a block to hold any variables defined in the init statement
5069 // of the for statement.
5070 this->gogo_->start_block(location);
5072 Block* init = NULL;
5073 Expression* cond = NULL;
5074 Block* post = NULL;
5075 Range_clause range_clause;
5077 if (!token->is_op(OPERATOR_LCURLY))
5079 if (token->is_keyword(KEYWORD_VAR))
5081 error_at(this->location(),
5082 "var declaration not allowed in for initializer");
5083 this->var_decl();
5086 if (token->is_op(OPERATOR_SEMICOLON))
5087 this->for_clause(&cond, &post);
5088 else
5090 // We might be looking at a Condition, an InitStat, or a
5091 // RangeClause.
5092 bool saw_send_stmt;
5093 cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL);
5094 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5096 if (cond == NULL && !range_clause.found)
5098 if (saw_send_stmt)
5099 error_at(this->location(),
5100 ("send statement used as value; "
5101 "use select for non-blocking send"));
5102 else
5103 error_at(this->location(), "parse error in for statement");
5106 else
5108 if (range_clause.found)
5109 error_at(this->location(), "parse error after range clause");
5111 if (cond != NULL)
5113 // COND is actually an expression statement for
5114 // InitStat at the start of a ForClause.
5115 this->expression_stat(cond);
5116 cond = NULL;
5119 this->for_clause(&cond, &post);
5124 // Check for the easy error of a newline before starting the block.
5125 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5127 Location semi_loc = this->location();
5128 if (this->advance_token()->is_op(OPERATOR_LCURLY))
5129 error_at(semi_loc, "missing %<{%> after for clause");
5130 // Otherwise we will get an error when we call this->block
5131 // below.
5134 // Build the For_statement and note that it is the current target
5135 // for break and continue statements.
5137 For_statement* sfor;
5138 For_range_statement* srange;
5139 Statement* s;
5140 if (!range_clause.found)
5142 sfor = Statement::make_for_statement(init, cond, post, location);
5143 s = sfor;
5144 srange = NULL;
5146 else
5148 srange = Statement::make_for_range_statement(range_clause.index,
5149 range_clause.value,
5150 range_clause.range,
5151 location);
5152 s = srange;
5153 sfor = NULL;
5156 this->push_break_statement(s, label);
5157 this->push_continue_statement(s, label);
5159 // Gather the block of statements in the loop and add them to the
5160 // For_statement.
5162 this->gogo_->start_block(this->location());
5163 Location end_loc = this->block();
5164 Block* statements = this->gogo_->finish_block(end_loc);
5166 if (sfor != NULL)
5167 sfor->add_statements(statements);
5168 else
5169 srange->add_statements(statements);
5171 // This is no longer the break/continue target.
5172 this->pop_break_statement();
5173 this->pop_continue_statement();
5175 // Add the For_statement to the list of statements, and close out
5176 // the block we started to hold any variables defined in the for
5177 // statement.
5179 this->gogo_->add_statement(s);
5181 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
5182 location);
5185 // ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
5186 // InitStat = SimpleStat .
5187 // PostStat = SimpleStat .
5189 // We have already read InitStat at this point.
5191 void
5192 Parse::for_clause(Expression** cond, Block** post)
5194 go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
5195 this->advance_token();
5196 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5197 *cond = NULL;
5198 else if (this->peek_token()->is_op(OPERATOR_LCURLY))
5200 error_at(this->location(), "missing %<{%> after for clause");
5201 *cond = NULL;
5202 *post = NULL;
5203 return;
5205 else
5206 *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5207 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5208 error_at(this->location(), "expected semicolon");
5209 else
5210 this->advance_token();
5212 if (this->peek_token()->is_op(OPERATOR_LCURLY))
5213 *post = NULL;
5214 else
5216 this->gogo_->start_block(this->location());
5217 this->simple_stat(false, NULL, NULL, NULL);
5218 *post = this->gogo_->finish_block(this->location());
5222 // RangeClause = [ IdentifierList ( "=" | ":=" ) ] "range" Expression .
5224 // This is the := version. It is called with a list of identifiers.
5226 void
5227 Parse::range_clause_decl(const Typed_identifier_list* til,
5228 Range_clause* p_range_clause)
5230 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5231 Location location = this->location();
5233 p_range_clause->found = true;
5235 if (til->size() > 2)
5236 error_at(this->location(), "too many variables for range clause");
5238 this->advance_token();
5239 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL,
5240 NULL);
5241 p_range_clause->range = expr;
5243 if (til->empty())
5244 return;
5246 bool any_new = false;
5248 const Typed_identifier* pti = &til->front();
5249 Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new,
5250 NULL, NULL);
5251 if (any_new && no->is_variable())
5252 no->var_value()->set_type_from_range_index();
5253 p_range_clause->index = Expression::make_var_reference(no, location);
5255 if (til->size() == 1)
5256 p_range_clause->value = NULL;
5257 else
5259 pti = &til->back();
5260 bool is_new = false;
5261 no = this->init_var(*pti, NULL, expr, true, true, &is_new, NULL, NULL);
5262 if (is_new && no->is_variable())
5263 no->var_value()->set_type_from_range_value();
5264 if (is_new)
5265 any_new = true;
5266 if (!Gogo::is_sink_name(pti->name()))
5267 p_range_clause->value = Expression::make_var_reference(no, location);
5270 if (!any_new)
5271 error_at(location, "variables redeclared but no variable is new");
5274 // The = version of RangeClause. This is called with a list of
5275 // expressions.
5277 void
5278 Parse::range_clause_expr(const Expression_list* vals,
5279 Range_clause* p_range_clause)
5281 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5283 p_range_clause->found = true;
5285 go_assert(vals->size() >= 1);
5286 if (vals->size() > 2)
5287 error_at(this->location(), "too many variables for range clause");
5289 this->advance_token();
5290 p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
5291 NULL, NULL);
5293 if (vals->empty())
5294 return;
5296 p_range_clause->index = vals->front();
5297 if (vals->size() == 1)
5298 p_range_clause->value = NULL;
5299 else
5300 p_range_clause->value = vals->back();
5303 // Push a statement on the break stack.
5305 void
5306 Parse::push_break_statement(Statement* enclosing, Label* label)
5308 if (this->break_stack_ == NULL)
5309 this->break_stack_ = new Bc_stack();
5310 this->break_stack_->push_back(std::make_pair(enclosing, label));
5313 // Push a statement on the continue stack.
5315 void
5316 Parse::push_continue_statement(Statement* enclosing, Label* label)
5318 if (this->continue_stack_ == NULL)
5319 this->continue_stack_ = new Bc_stack();
5320 this->continue_stack_->push_back(std::make_pair(enclosing, label));
5323 // Pop the break stack.
5325 void
5326 Parse::pop_break_statement()
5328 this->break_stack_->pop_back();
5331 // Pop the continue stack.
5333 void
5334 Parse::pop_continue_statement()
5336 this->continue_stack_->pop_back();
5339 // Find a break or continue statement given a label name.
5341 Statement*
5342 Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
5344 if (bc_stack == NULL)
5345 return NULL;
5346 for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
5347 p != bc_stack->rend();
5348 ++p)
5350 if (p->second != NULL && p->second->name() == label)
5352 p->second->set_is_used();
5353 return p->first;
5356 return NULL;
5359 // BreakStat = "break" [ identifier ] .
5361 void
5362 Parse::break_stat()
5364 go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
5365 Location location = this->location();
5367 const Token* token = this->advance_token();
5368 Statement* enclosing;
5369 if (!token->is_identifier())
5371 if (this->break_stack_ == NULL || this->break_stack_->empty())
5373 error_at(this->location(),
5374 "break statement not within for or switch or select");
5375 return;
5377 enclosing = this->break_stack_->back().first;
5379 else
5381 enclosing = this->find_bc_statement(this->break_stack_,
5382 token->identifier());
5383 if (enclosing == NULL)
5385 // If there is a label with this name, mark it as used to
5386 // avoid a useless error about an unused label.
5387 this->gogo_->add_label_reference(token->identifier(),
5388 Linemap::unknown_location(), false);
5390 error_at(token->location(), "invalid break label %qs",
5391 Gogo::message_name(token->identifier()).c_str());
5392 this->advance_token();
5393 return;
5395 this->advance_token();
5398 Unnamed_label* label;
5399 if (enclosing->classification() == Statement::STATEMENT_FOR)
5400 label = enclosing->for_statement()->break_label();
5401 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5402 label = enclosing->for_range_statement()->break_label();
5403 else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
5404 label = enclosing->switch_statement()->break_label();
5405 else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
5406 label = enclosing->type_switch_statement()->break_label();
5407 else if (enclosing->classification() == Statement::STATEMENT_SELECT)
5408 label = enclosing->select_statement()->break_label();
5409 else
5410 go_unreachable();
5412 this->gogo_->add_statement(Statement::make_break_statement(label,
5413 location));
5416 // ContinueStat = "continue" [ identifier ] .
5418 void
5419 Parse::continue_stat()
5421 go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
5422 Location location = this->location();
5424 const Token* token = this->advance_token();
5425 Statement* enclosing;
5426 if (!token->is_identifier())
5428 if (this->continue_stack_ == NULL || this->continue_stack_->empty())
5430 error_at(this->location(), "continue statement not within for");
5431 return;
5433 enclosing = this->continue_stack_->back().first;
5435 else
5437 enclosing = this->find_bc_statement(this->continue_stack_,
5438 token->identifier());
5439 if (enclosing == NULL)
5441 // If there is a label with this name, mark it as used to
5442 // avoid a useless error about an unused label.
5443 this->gogo_->add_label_reference(token->identifier(),
5444 Linemap::unknown_location(), false);
5446 error_at(token->location(), "invalid continue label %qs",
5447 Gogo::message_name(token->identifier()).c_str());
5448 this->advance_token();
5449 return;
5451 this->advance_token();
5454 Unnamed_label* label;
5455 if (enclosing->classification() == Statement::STATEMENT_FOR)
5456 label = enclosing->for_statement()->continue_label();
5457 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5458 label = enclosing->for_range_statement()->continue_label();
5459 else
5460 go_unreachable();
5462 this->gogo_->add_statement(Statement::make_continue_statement(label,
5463 location));
5466 // GotoStat = "goto" identifier .
5468 void
5469 Parse::goto_stat()
5471 go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
5472 Location location = this->location();
5473 const Token* token = this->advance_token();
5474 if (!token->is_identifier())
5475 error_at(this->location(), "expected label for goto");
5476 else
5478 Label* label = this->gogo_->add_label_reference(token->identifier(),
5479 location, true);
5480 Statement* s = Statement::make_goto_statement(label, location);
5481 this->gogo_->add_statement(s);
5482 this->advance_token();
5486 // PackageClause = "package" PackageName .
5488 void
5489 Parse::package_clause()
5491 const Token* token = this->peek_token();
5492 Location location = token->location();
5493 std::string name;
5494 if (!token->is_keyword(KEYWORD_PACKAGE))
5496 error_at(this->location(), "program must start with package clause");
5497 name = "ERROR";
5499 else
5501 token = this->advance_token();
5502 if (token->is_identifier())
5504 name = token->identifier();
5505 if (name == "_")
5507 error_at(this->location(), "invalid package name _");
5508 name = Gogo::erroneous_name();
5510 this->advance_token();
5512 else
5514 error_at(this->location(), "package name must be an identifier");
5515 name = "ERROR";
5518 this->gogo_->set_package_name(name, location);
5521 // ImportDecl = "import" Decl<ImportSpec> .
5523 void
5524 Parse::import_decl()
5526 go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
5527 this->advance_token();
5528 this->decl(&Parse::import_spec, NULL);
5531 // ImportSpec = [ "." | PackageName ] PackageFileName .
5533 void
5534 Parse::import_spec(void*)
5536 const Token* token = this->peek_token();
5537 Location location = token->location();
5539 std::string local_name;
5540 bool is_local_name_exported = false;
5541 if (token->is_op(OPERATOR_DOT))
5543 local_name = ".";
5544 token = this->advance_token();
5546 else if (token->is_identifier())
5548 local_name = token->identifier();
5549 is_local_name_exported = token->is_identifier_exported();
5550 token = this->advance_token();
5553 if (!token->is_string())
5555 error_at(this->location(), "import statement not a string");
5556 this->advance_token();
5557 return;
5560 this->gogo_->import_package(token->string_value(), local_name,
5561 is_local_name_exported, location);
5563 this->advance_token();
5566 // SourceFile = PackageClause ";" { ImportDecl ";" }
5567 // { TopLevelDecl ";" } .
5569 void
5570 Parse::program()
5572 this->package_clause();
5574 const Token* token = this->peek_token();
5575 if (token->is_op(OPERATOR_SEMICOLON))
5576 token = this->advance_token();
5577 else
5578 error_at(this->location(),
5579 "expected %<;%> or newline after package clause");
5581 while (token->is_keyword(KEYWORD_IMPORT))
5583 this->import_decl();
5584 token = this->peek_token();
5585 if (token->is_op(OPERATOR_SEMICOLON))
5586 token = this->advance_token();
5587 else
5588 error_at(this->location(),
5589 "expected %<;%> or newline after import declaration");
5592 while (!token->is_eof())
5594 if (this->declaration_may_start_here())
5595 this->declaration();
5596 else
5598 error_at(this->location(), "expected declaration");
5599 this->gogo_->mark_locals_used();
5601 this->advance_token();
5602 while (!this->peek_token()->is_eof()
5603 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
5604 && !this->peek_token()->is_op(OPERATOR_RCURLY));
5605 if (!this->peek_token()->is_eof()
5606 && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
5607 this->advance_token();
5609 token = this->peek_token();
5610 if (token->is_op(OPERATOR_SEMICOLON))
5611 token = this->advance_token();
5612 else if (!token->is_eof() || !saw_errors())
5614 if (token->is_op(OPERATOR_CHANOP))
5615 error_at(this->location(),
5616 ("send statement used as value; "
5617 "use select for non-blocking send"));
5618 else
5619 error_at(this->location(),
5620 "expected %<;%> or newline after top level declaration");
5621 this->skip_past_error(OPERATOR_INVALID);
5626 // Reset the current iota value.
5628 void
5629 Parse::reset_iota()
5631 this->iota_ = 0;
5634 // Return the current iota value.
5637 Parse::iota_value()
5639 return this->iota_;
5642 // Increment the current iota value.
5644 void
5645 Parse::increment_iota()
5647 ++this->iota_;
5650 // Skip forward to a semicolon or OP. OP will normally be
5651 // OPERATOR_RPAREN or OPERATOR_RCURLY. If we find a semicolon, move
5652 // past it and return. If we find OP, it will be the next token to
5653 // read. Return true if we are OK, false if we found EOF.
5655 bool
5656 Parse::skip_past_error(Operator op)
5658 this->gogo_->mark_locals_used();
5659 const Token* token = this->peek_token();
5660 while (!token->is_op(op))
5662 if (token->is_eof())
5663 return false;
5664 if (token->is_op(OPERATOR_SEMICOLON))
5666 this->advance_token();
5667 return true;
5669 token = this->advance_token();
5671 return true;
5674 // Check that an expression is not a sink.
5676 Expression*
5677 Parse::verify_not_sink(Expression* expr)
5679 if (expr->is_sink_expression())
5681 error_at(expr->location(), "cannot use _ as value");
5682 expr = Expression::make_error(expr->location());
5685 // If this can not be a sink, and it is a variable, then we are
5686 // using the variable, not just assigning to it.
5687 Var_expression* ve = expr->var_expression();
5688 if (ve != NULL)
5689 this->mark_var_used(ve->named_object());
5691 return expr;
5694 // Mark a variable as used.
5696 void
5697 Parse::mark_var_used(Named_object* no)
5699 if (no->is_variable())
5701 no->var_value()->set_is_used();
5703 // When a type switch uses := to define a variable, then for
5704 // each case with a single type we introduce a new variable with
5705 // the appropriate type. When we do, if the newly introduced
5706 // variable is used, then the type switch variable is used.
5707 Type_switch_vars::iterator p = this->type_switch_vars_.find(no);
5708 if (p != this->type_switch_vars_.end())
5709 p->second->var_value()->set_is_used();