compiler: Error if receiver and parameter have same name.
[official-gcc.git] / gcc / go / gofrontend / parse.cc
blob9c7d8277efa2863effaf91f763003b88f79ec0d6
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 while (this->peek_token()->is_op(OPERATOR_COMMA))
980 if (this->advance_token()->is_op(OPERATOR_RPAREN))
981 break;
982 if (is_varargs != NULL && *is_varargs)
984 error_at(this->location(), "%<...%> must be last parameter");
985 saw_error = true;
987 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
989 if (mix_error)
991 error_at(location, "invalid named/anonymous mix");
992 saw_error = true;
994 if (saw_error)
996 delete ret;
997 return NULL;
999 return ret;
1002 // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
1004 void
1005 Parse::parameter_decl(bool parameters_have_names,
1006 Typed_identifier_list* til,
1007 bool* is_varargs,
1008 bool* mix_error)
1010 if (!parameters_have_names)
1012 Type* type;
1013 Location location = this->location();
1014 if (!this->peek_token()->is_identifier())
1016 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1017 type = this->type();
1018 else
1020 if (is_varargs == NULL)
1021 error_at(this->location(), "invalid use of %<...%>");
1022 else
1023 *is_varargs = true;
1024 this->advance_token();
1025 if (is_varargs == NULL
1026 && this->peek_token()->is_op(OPERATOR_RPAREN))
1027 type = Type::make_error_type();
1028 else
1030 Type* element_type = this->type();
1031 type = Type::make_array_type(element_type, NULL);
1035 else
1037 type = this->type_name(false);
1038 if (type->is_error_type()
1039 || (!this->peek_token()->is_op(OPERATOR_COMMA)
1040 && !this->peek_token()->is_op(OPERATOR_RPAREN)))
1042 *mix_error = true;
1043 while (!this->peek_token()->is_op(OPERATOR_COMMA)
1044 && !this->peek_token()->is_op(OPERATOR_RPAREN))
1045 this->advance_token();
1048 if (!type->is_error_type())
1049 til->push_back(Typed_identifier("", type, location));
1051 else
1053 size_t orig_count = til->size();
1054 if (this->peek_token()->is_identifier())
1055 this->identifier_list(til);
1056 else
1057 *mix_error = true;
1058 size_t new_count = til->size();
1060 Type* type;
1061 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1062 type = this->type();
1063 else
1065 if (is_varargs == NULL)
1066 error_at(this->location(), "invalid use of %<...%>");
1067 else if (new_count > orig_count + 1)
1068 error_at(this->location(), "%<...%> only permits one name");
1069 else
1070 *is_varargs = true;
1071 this->advance_token();
1072 Type* element_type = this->type();
1073 type = Type::make_array_type(element_type, NULL);
1075 for (size_t i = orig_count; i < new_count; ++i)
1076 til->set_type(i, type);
1080 // Result = Parameters | Type .
1082 // This returns false on a parse error.
1084 bool
1085 Parse::result(Typed_identifier_list** presults)
1087 if (this->peek_token()->is_op(OPERATOR_LPAREN))
1088 return this->parameters(presults, NULL);
1089 else
1091 Location location = this->location();
1092 Type* type = this->type();
1093 if (type->is_error_type())
1095 *presults = NULL;
1096 return false;
1098 Typed_identifier_list* til = new Typed_identifier_list();
1099 til->push_back(Typed_identifier("", type, location));
1100 *presults = til;
1101 return true;
1105 // Block = "{" [ StatementList ] "}" .
1107 // Returns the location of the closing brace.
1109 Location
1110 Parse::block()
1112 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
1114 Location loc = this->location();
1115 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1116 && this->advance_token()->is_op(OPERATOR_LCURLY))
1117 error_at(loc, "unexpected semicolon or newline before %<{%>");
1118 else
1120 error_at(this->location(), "expected %<{%>");
1121 return Linemap::unknown_location();
1125 const Token* token = this->advance_token();
1127 if (!token->is_op(OPERATOR_RCURLY))
1129 this->statement_list();
1130 token = this->peek_token();
1131 if (!token->is_op(OPERATOR_RCURLY))
1133 if (!token->is_eof() || !saw_errors())
1134 error_at(this->location(), "expected %<}%>");
1136 this->gogo_->mark_locals_used();
1138 // Skip ahead to the end of the block, in hopes of avoiding
1139 // lots of meaningless errors.
1140 Location ret = token->location();
1141 int nest = 0;
1142 while (!token->is_eof())
1144 if (token->is_op(OPERATOR_LCURLY))
1145 ++nest;
1146 else if (token->is_op(OPERATOR_RCURLY))
1148 --nest;
1149 if (nest < 0)
1151 this->advance_token();
1152 break;
1155 token = this->advance_token();
1156 ret = token->location();
1158 return ret;
1162 Location ret = token->location();
1163 this->advance_token();
1164 return ret;
1167 // InterfaceType = "interface" "{" [ MethodSpecList ] "}" .
1168 // MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] .
1170 Type*
1171 Parse::interface_type()
1173 go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE));
1174 Location location = this->location();
1176 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
1178 Location token_loc = this->location();
1179 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1180 && this->advance_token()->is_op(OPERATOR_LCURLY))
1181 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
1182 else
1184 error_at(this->location(), "expected %<{%>");
1185 return Type::make_error_type();
1188 this->advance_token();
1190 Typed_identifier_list* methods = new Typed_identifier_list();
1191 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1193 this->method_spec(methods);
1194 while (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1196 if (this->advance_token()->is_op(OPERATOR_RCURLY))
1197 break;
1198 this->method_spec(methods);
1200 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1202 error_at(this->location(), "expected %<}%>");
1203 while (!this->advance_token()->is_op(OPERATOR_RCURLY))
1205 if (this->peek_token()->is_eof())
1206 return Type::make_error_type();
1210 this->advance_token();
1212 if (methods->empty())
1214 delete methods;
1215 methods = NULL;
1218 Interface_type* ret = Type::make_interface_type(methods, location);
1219 this->gogo_->record_interface_type(ret);
1220 return ret;
1223 // MethodSpec = MethodName Signature | InterfaceTypeName .
1224 // MethodName = identifier .
1225 // InterfaceTypeName = TypeName .
1227 void
1228 Parse::method_spec(Typed_identifier_list* methods)
1230 const Token* token = this->peek_token();
1231 if (!token->is_identifier())
1233 error_at(this->location(), "expected identifier");
1234 return;
1237 std::string name = token->identifier();
1238 bool is_exported = token->is_identifier_exported();
1239 Location location = token->location();
1241 if (this->advance_token()->is_op(OPERATOR_LPAREN))
1243 // This is a MethodName.
1244 name = this->gogo_->pack_hidden_name(name, is_exported);
1245 Type* type = this->signature(NULL, location);
1246 if (type == NULL)
1247 return;
1248 methods->push_back(Typed_identifier(name, type, location));
1250 else
1252 this->unget_token(Token::make_identifier_token(name, is_exported,
1253 location));
1254 Type* type = this->type_name(false);
1255 if (type->is_error_type()
1256 || (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1257 && !this->peek_token()->is_op(OPERATOR_RCURLY)))
1259 if (this->peek_token()->is_op(OPERATOR_COMMA))
1260 error_at(this->location(),
1261 "name list not allowed in interface type");
1262 else
1263 error_at(location, "expected signature or type name");
1264 this->gogo_->mark_locals_used();
1265 token = this->peek_token();
1266 while (!token->is_eof()
1267 && !token->is_op(OPERATOR_SEMICOLON)
1268 && !token->is_op(OPERATOR_RCURLY))
1269 token = this->advance_token();
1270 return;
1272 // This must be an interface type, but we can't check that now.
1273 // We check it and pull out the methods in
1274 // Interface_type::do_verify.
1275 methods->push_back(Typed_identifier("", type, location));
1279 // Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1281 void
1282 Parse::declaration()
1284 const Token* token = this->peek_token();
1286 bool saw_nointerface = this->lex_->get_and_clear_nointerface();
1287 if (saw_nointerface && !token->is_keyword(KEYWORD_FUNC))
1288 warning_at(token->location(), 0,
1289 "ignoring magic //go:nointerface comment before non-method");
1291 if (token->is_keyword(KEYWORD_CONST))
1292 this->const_decl();
1293 else if (token->is_keyword(KEYWORD_TYPE))
1294 this->type_decl();
1295 else if (token->is_keyword(KEYWORD_VAR))
1296 this->var_decl();
1297 else if (token->is_keyword(KEYWORD_FUNC))
1298 this->function_decl(saw_nointerface);
1299 else
1301 error_at(this->location(), "expected declaration");
1302 this->advance_token();
1306 bool
1307 Parse::declaration_may_start_here()
1309 const Token* token = this->peek_token();
1310 return (token->is_keyword(KEYWORD_CONST)
1311 || token->is_keyword(KEYWORD_TYPE)
1312 || token->is_keyword(KEYWORD_VAR)
1313 || token->is_keyword(KEYWORD_FUNC));
1316 // Decl<P> = P | "(" [ List<P> ] ")" .
1318 void
1319 Parse::decl(void (Parse::*pfn)(void*), void* varg)
1321 if (this->peek_token()->is_eof())
1323 if (!saw_errors())
1324 error_at(this->location(), "unexpected end of file");
1325 return;
1328 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1329 (this->*pfn)(varg);
1330 else
1332 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
1334 this->list(pfn, varg, true);
1335 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1337 error_at(this->location(), "missing %<)%>");
1338 while (!this->advance_token()->is_op(OPERATOR_RPAREN))
1340 if (this->peek_token()->is_eof())
1341 return;
1345 this->advance_token();
1349 // List<P> = P { ";" P } [ ";" ] .
1351 // In order to pick up the trailing semicolon we need to know what
1352 // might follow. This is either a '}' or a ')'.
1354 void
1355 Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren)
1357 (this->*pfn)(varg);
1358 Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY;
1359 while (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1360 || this->peek_token()->is_op(OPERATOR_COMMA))
1362 if (this->peek_token()->is_op(OPERATOR_COMMA))
1363 error_at(this->location(), "unexpected comma");
1364 if (this->advance_token()->is_op(follow))
1365 break;
1366 (this->*pfn)(varg);
1370 // ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1372 void
1373 Parse::const_decl()
1375 go_assert(this->peek_token()->is_keyword(KEYWORD_CONST));
1376 this->advance_token();
1377 this->reset_iota();
1379 Type* last_type = NULL;
1380 Expression_list* last_expr_list = NULL;
1382 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1383 this->const_spec(&last_type, &last_expr_list);
1384 else
1386 this->advance_token();
1387 while (!this->peek_token()->is_op(OPERATOR_RPAREN))
1389 this->const_spec(&last_type, &last_expr_list);
1390 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1391 this->advance_token();
1392 else if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1394 error_at(this->location(), "expected %<;%> or %<)%> or newline");
1395 if (!this->skip_past_error(OPERATOR_RPAREN))
1396 return;
1399 this->advance_token();
1402 if (last_expr_list != NULL)
1403 delete last_expr_list;
1406 // ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
1408 void
1409 Parse::const_spec(Type** last_type, Expression_list** last_expr_list)
1411 Typed_identifier_list til;
1412 this->identifier_list(&til);
1414 Type* type = NULL;
1415 if (this->type_may_start_here())
1417 type = this->type();
1418 *last_type = NULL;
1419 *last_expr_list = NULL;
1422 Expression_list *expr_list;
1423 if (!this->peek_token()->is_op(OPERATOR_EQ))
1425 if (*last_expr_list == NULL)
1427 error_at(this->location(), "expected %<=%>");
1428 return;
1430 type = *last_type;
1431 expr_list = new Expression_list;
1432 for (Expression_list::const_iterator p = (*last_expr_list)->begin();
1433 p != (*last_expr_list)->end();
1434 ++p)
1435 expr_list->push_back((*p)->copy());
1437 else
1439 this->advance_token();
1440 expr_list = this->expression_list(NULL, false, true);
1441 *last_type = type;
1442 if (*last_expr_list != NULL)
1443 delete *last_expr_list;
1444 *last_expr_list = expr_list;
1447 Expression_list::const_iterator pe = expr_list->begin();
1448 for (Typed_identifier_list::iterator pi = til.begin();
1449 pi != til.end();
1450 ++pi, ++pe)
1452 if (pe == expr_list->end())
1454 error_at(this->location(), "not enough initializers");
1455 return;
1457 if (type != NULL)
1458 pi->set_type(type);
1460 if (!Gogo::is_sink_name(pi->name()))
1461 this->gogo_->add_constant(*pi, *pe, this->iota_value());
1462 else
1464 static int count;
1465 char buf[30];
1466 snprintf(buf, sizeof buf, ".$sinkconst%d", count);
1467 ++count;
1468 Typed_identifier ti(std::string(buf), type, pi->location());
1469 Named_object* no = this->gogo_->add_constant(ti, *pe, this->iota_value());
1470 no->const_value()->set_is_sink();
1473 if (pe != expr_list->end())
1474 error_at(this->location(), "too many initializers");
1476 this->increment_iota();
1478 return;
1481 // TypeDecl = "type" Decl<TypeSpec> .
1483 void
1484 Parse::type_decl()
1486 go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE));
1487 this->advance_token();
1488 this->decl(&Parse::type_spec, NULL);
1491 // TypeSpec = identifier Type .
1493 void
1494 Parse::type_spec(void*)
1496 const Token* token = this->peek_token();
1497 if (!token->is_identifier())
1499 error_at(this->location(), "expected identifier");
1500 return;
1502 std::string name = token->identifier();
1503 bool is_exported = token->is_identifier_exported();
1504 Location location = token->location();
1505 token = this->advance_token();
1507 // The scope of the type name starts at the point where the
1508 // identifier appears in the source code. We implement this by
1509 // declaring the type before we read the type definition.
1510 Named_object* named_type = NULL;
1511 if (name != "_")
1513 name = this->gogo_->pack_hidden_name(name, is_exported);
1514 named_type = this->gogo_->declare_type(name, location);
1517 Type* type;
1518 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
1519 type = this->type();
1520 else
1522 error_at(this->location(),
1523 "unexpected semicolon or newline in type declaration");
1524 type = Type::make_error_type();
1525 this->advance_token();
1528 if (type->is_error_type())
1530 this->gogo_->mark_locals_used();
1531 while (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1532 && !this->peek_token()->is_eof())
1533 this->advance_token();
1536 if (name != "_")
1538 if (named_type->is_type_declaration())
1540 Type* ftype = type->forwarded();
1541 if (ftype->forward_declaration_type() != NULL
1542 && (ftype->forward_declaration_type()->named_object()
1543 == named_type))
1545 error_at(location, "invalid recursive type");
1546 type = Type::make_error_type();
1549 this->gogo_->define_type(named_type,
1550 Type::make_named_type(named_type, type,
1551 location));
1552 go_assert(named_type->package() == NULL);
1554 else
1556 // This will probably give a redefinition error.
1557 this->gogo_->add_type(name, type, location);
1562 // VarDecl = "var" Decl<VarSpec> .
1564 void
1565 Parse::var_decl()
1567 go_assert(this->peek_token()->is_keyword(KEYWORD_VAR));
1568 this->advance_token();
1569 this->decl(&Parse::var_spec, NULL);
1572 // VarSpec = IdentifierList
1573 // ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
1575 void
1576 Parse::var_spec(void*)
1578 // Get the variable names.
1579 Typed_identifier_list til;
1580 this->identifier_list(&til);
1582 Location location = this->location();
1584 Type* type = NULL;
1585 Expression_list* init = NULL;
1586 if (!this->peek_token()->is_op(OPERATOR_EQ))
1588 type = this->type();
1589 if (type->is_error_type())
1591 this->gogo_->mark_locals_used();
1592 while (!this->peek_token()->is_op(OPERATOR_EQ)
1593 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
1594 && !this->peek_token()->is_eof())
1595 this->advance_token();
1597 if (this->peek_token()->is_op(OPERATOR_EQ))
1599 this->advance_token();
1600 init = this->expression_list(NULL, false, true);
1603 else
1605 this->advance_token();
1606 init = this->expression_list(NULL, false, true);
1609 this->init_vars(&til, type, init, false, location);
1611 if (init != NULL)
1612 delete init;
1615 // Create variables. TIL is a list of variable names. If TYPE is not
1616 // NULL, it is the type of all the variables. If INIT is not NULL, it
1617 // is an initializer list for the variables.
1619 void
1620 Parse::init_vars(const Typed_identifier_list* til, Type* type,
1621 Expression_list* init, bool is_coloneq,
1622 Location location)
1624 // Check for an initialization which can yield multiple values.
1625 if (init != NULL && init->size() == 1 && til->size() > 1)
1627 if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq,
1628 location))
1629 return;
1630 if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq,
1631 location))
1632 return;
1633 if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq,
1634 location))
1635 return;
1636 if (this->init_vars_from_type_guard(til, type, *init->begin(),
1637 is_coloneq, location))
1638 return;
1641 if (init != NULL && init->size() != til->size())
1643 if (init->empty() || !init->front()->is_error_expression())
1644 error_at(location, "wrong number of initializations");
1645 init = NULL;
1646 if (type == NULL)
1647 type = Type::make_error_type();
1650 // Note that INIT was already parsed with the old name bindings, so
1651 // we don't have to worry that it will accidentally refer to the
1652 // newly declared variables. But we do have to worry about a mix of
1653 // newly declared variables and old variables if the old variables
1654 // appear in the initializations.
1656 Expression_list::const_iterator pexpr;
1657 if (init != NULL)
1658 pexpr = init->begin();
1659 bool any_new = false;
1660 Expression_list* vars = new Expression_list();
1661 Expression_list* vals = new Expression_list();
1662 for (Typed_identifier_list::const_iterator p = til->begin();
1663 p != til->end();
1664 ++p)
1666 if (init != NULL)
1667 go_assert(pexpr != init->end());
1668 this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq,
1669 false, &any_new, vars, vals);
1670 if (init != NULL)
1671 ++pexpr;
1673 if (init != NULL)
1674 go_assert(pexpr == init->end());
1675 if (is_coloneq && !any_new)
1676 error_at(location, "variables redeclared but no variable is new");
1677 this->finish_init_vars(vars, vals, location);
1680 // See if we need to initialize a list of variables from a function
1681 // call. This returns true if we have set up the variables and the
1682 // initialization.
1684 bool
1685 Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type,
1686 Expression* expr, bool is_coloneq,
1687 Location location)
1689 Call_expression* call = expr->call_expression();
1690 if (call == NULL)
1691 return false;
1693 // This is a function call. We can't check here whether it returns
1694 // the right number of values, but it might. Declare the variables,
1695 // and then assign the results of the call to them.
1697 Named_object* first_var = NULL;
1698 unsigned int index = 0;
1699 bool any_new = false;
1700 Expression_list* ivars = new Expression_list();
1701 Expression_list* ivals = new Expression_list();
1702 for (Typed_identifier_list::const_iterator pv = vars->begin();
1703 pv != vars->end();
1704 ++pv, ++index)
1706 Expression* init = Expression::make_call_result(call, index);
1707 Named_object* no = this->init_var(*pv, type, init, is_coloneq, false,
1708 &any_new, ivars, ivals);
1710 if (this->gogo_->in_global_scope() && no->is_variable())
1712 if (first_var == NULL)
1713 first_var = no;
1714 else
1716 // The subsequent vars have an implicit dependency on
1717 // the first one, so that everything gets initialized in
1718 // the right order and so that we detect cycles
1719 // correctly.
1720 this->gogo_->record_var_depends_on(no->var_value(), first_var);
1725 if (is_coloneq && !any_new)
1726 error_at(location, "variables redeclared but no variable is new");
1728 this->finish_init_vars(ivars, ivals, location);
1730 return true;
1733 // See if we need to initialize a pair of values from a map index
1734 // expression. This returns true if we have set up the variables and
1735 // the initialization.
1737 bool
1738 Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type,
1739 Expression* expr, bool is_coloneq,
1740 Location location)
1742 Index_expression* index = expr->index_expression();
1743 if (index == NULL)
1744 return false;
1745 if (vars->size() != 2)
1746 return false;
1748 // This is an index which is being assigned to two variables. It
1749 // must be a map index. Declare the variables, and then assign the
1750 // results of the map index.
1751 bool any_new = false;
1752 Typed_identifier_list::const_iterator p = vars->begin();
1753 Expression* init = type == NULL ? index : NULL;
1754 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1755 type == NULL, &any_new, NULL, NULL);
1756 if (type == NULL && any_new && val_no->is_variable())
1757 val_no->var_value()->set_type_from_init_tuple();
1758 Expression* val_var = Expression::make_var_reference(val_no, location);
1760 ++p;
1761 Type* var_type = type;
1762 if (var_type == NULL)
1763 var_type = Type::lookup_bool_type();
1764 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1765 &any_new, NULL, NULL);
1766 Expression* present_var = Expression::make_var_reference(no, location);
1768 if (is_coloneq && !any_new)
1769 error_at(location, "variables redeclared but no variable is new");
1771 Statement* s = Statement::make_tuple_map_assignment(val_var, present_var,
1772 index, location);
1774 if (!this->gogo_->in_global_scope())
1775 this->gogo_->add_statement(s);
1776 else if (!val_no->is_sink())
1778 if (val_no->is_variable())
1779 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1781 else if (!no->is_sink())
1783 if (no->is_variable())
1784 no->var_value()->add_preinit_statement(this->gogo_, s);
1786 else
1788 // Execute the map index expression just so that we can fail if
1789 // the map is nil.
1790 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1791 NULL, location);
1792 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1795 return true;
1798 // See if we need to initialize a pair of values from a receive
1799 // expression. This returns true if we have set up the variables and
1800 // the initialization.
1802 bool
1803 Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type,
1804 Expression* expr, bool is_coloneq,
1805 Location location)
1807 Receive_expression* receive = expr->receive_expression();
1808 if (receive == NULL)
1809 return false;
1810 if (vars->size() != 2)
1811 return false;
1813 // This is a receive expression which is being assigned to two
1814 // variables. Declare the variables, and then assign the results of
1815 // the receive.
1816 bool any_new = false;
1817 Typed_identifier_list::const_iterator p = vars->begin();
1818 Expression* init = type == NULL ? receive : NULL;
1819 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1820 type == NULL, &any_new, NULL, NULL);
1821 if (type == NULL && any_new && val_no->is_variable())
1822 val_no->var_value()->set_type_from_init_tuple();
1823 Expression* val_var = Expression::make_var_reference(val_no, location);
1825 ++p;
1826 Type* var_type = type;
1827 if (var_type == NULL)
1828 var_type = Type::lookup_bool_type();
1829 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1830 &any_new, NULL, NULL);
1831 Expression* received_var = Expression::make_var_reference(no, location);
1833 if (is_coloneq && !any_new)
1834 error_at(location, "variables redeclared but no variable is new");
1836 Statement* s = Statement::make_tuple_receive_assignment(val_var,
1837 received_var,
1838 receive->channel(),
1839 location);
1841 if (!this->gogo_->in_global_scope())
1842 this->gogo_->add_statement(s);
1843 else if (!val_no->is_sink())
1845 if (val_no->is_variable())
1846 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1848 else if (!no->is_sink())
1850 if (no->is_variable())
1851 no->var_value()->add_preinit_statement(this->gogo_, s);
1853 else
1855 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1856 NULL, location);
1857 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1860 return true;
1863 // See if we need to initialize a pair of values from a type guard
1864 // expression. This returns true if we have set up the variables and
1865 // the initialization.
1867 bool
1868 Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
1869 Type* type, Expression* expr,
1870 bool is_coloneq, Location location)
1872 Type_guard_expression* type_guard = expr->type_guard_expression();
1873 if (type_guard == NULL)
1874 return false;
1875 if (vars->size() != 2)
1876 return false;
1878 // This is a type guard expression which is being assigned to two
1879 // variables. Declare the variables, and then assign the results of
1880 // the type guard.
1881 bool any_new = false;
1882 Typed_identifier_list::const_iterator p = vars->begin();
1883 Type* var_type = type;
1884 if (var_type == NULL)
1885 var_type = type_guard->type();
1886 Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1887 &any_new, NULL, NULL);
1888 Expression* val_var = Expression::make_var_reference(val_no, location);
1890 ++p;
1891 var_type = type;
1892 if (var_type == NULL)
1893 var_type = Type::lookup_bool_type();
1894 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1895 &any_new, NULL, NULL);
1896 Expression* ok_var = Expression::make_var_reference(no, location);
1898 Expression* texpr = type_guard->expr();
1899 Type* t = type_guard->type();
1900 Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
1901 texpr, t,
1902 location);
1904 if (is_coloneq && !any_new)
1905 error_at(location, "variables redeclared but no variable is new");
1907 if (!this->gogo_->in_global_scope())
1908 this->gogo_->add_statement(s);
1909 else if (!val_no->is_sink())
1911 if (val_no->is_variable())
1912 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1914 else if (!no->is_sink())
1916 if (no->is_variable())
1917 no->var_value()->add_preinit_statement(this->gogo_, s);
1919 else
1921 Named_object* dummy = this->create_dummy_global(type, NULL, location);
1922 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1925 return true;
1928 // Create a single variable. If IS_COLONEQ is true, we permit
1929 // redeclarations in the same block, and we set *IS_NEW when we find a
1930 // new variable which is not a redeclaration.
1932 Named_object*
1933 Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
1934 bool is_coloneq, bool type_from_init, bool* is_new,
1935 Expression_list* vars, Expression_list* vals)
1937 Location location = tid.location();
1939 if (Gogo::is_sink_name(tid.name()))
1941 if (!type_from_init && init != NULL)
1943 if (this->gogo_->in_global_scope())
1944 return this->create_dummy_global(type, init, location);
1945 else
1947 // Create a dummy variable so that we will check whether the
1948 // initializer can be assigned to the type.
1949 Variable* var = new Variable(type, init, false, false, false,
1950 location);
1951 var->set_is_used();
1952 static int count;
1953 char buf[30];
1954 snprintf(buf, sizeof buf, "sink$%d", count);
1955 ++count;
1956 return this->gogo_->add_variable(buf, var);
1959 if (type != NULL)
1960 this->gogo_->add_type_to_verify(type);
1961 return this->gogo_->add_sink();
1964 if (is_coloneq)
1966 Named_object* no = this->gogo_->lookup_in_block(tid.name());
1967 if (no != NULL
1968 && (no->is_variable() || no->is_result_variable()))
1970 // INIT may be NULL even when IS_COLONEQ is true for cases
1971 // like v, ok := x.(int).
1972 if (!type_from_init && init != NULL)
1974 go_assert(vars != NULL && vals != NULL);
1975 vars->push_back(Expression::make_var_reference(no, location));
1976 vals->push_back(init);
1978 return no;
1981 *is_new = true;
1982 Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
1983 false, false, location);
1984 Named_object* no = this->gogo_->add_variable(tid.name(), var);
1985 if (!no->is_variable())
1987 // The name is already defined, so we just gave an error.
1988 return this->gogo_->add_sink();
1990 return no;
1993 // Create a dummy global variable to force an initializer to be run in
1994 // the right place. This is used when a sink variable is initialized
1995 // at global scope.
1997 Named_object*
1998 Parse::create_dummy_global(Type* type, Expression* init,
1999 Location location)
2001 if (type == NULL && init == NULL)
2002 type = Type::lookup_bool_type();
2003 Variable* var = new Variable(type, init, true, false, false, location);
2004 static int count;
2005 char buf[30];
2006 snprintf(buf, sizeof buf, "_.%d", count);
2007 ++count;
2008 return this->gogo_->add_variable(buf, var);
2011 // Finish the variable initialization by executing any assignments to
2012 // existing variables when using :=. These must be done as a tuple
2013 // assignment in case of something like n, a, b := 1, b, a.
2015 void
2016 Parse::finish_init_vars(Expression_list* vars, Expression_list* vals,
2017 Location location)
2019 if (vars->empty())
2021 delete vars;
2022 delete vals;
2024 else if (vars->size() == 1)
2026 go_assert(!this->gogo_->in_global_scope());
2027 this->gogo_->add_statement(Statement::make_assignment(vars->front(),
2028 vals->front(),
2029 location));
2030 delete vars;
2031 delete vals;
2033 else
2035 go_assert(!this->gogo_->in_global_scope());
2036 this->gogo_->add_statement(Statement::make_tuple_assignment(vars, vals,
2037 location));
2041 // SimpleVarDecl = identifier ":=" Expression .
2043 // We've already seen the identifier.
2045 // FIXME: We also have to implement
2046 // IdentifierList ":=" ExpressionList
2047 // In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
2048 // tuple assignments here as well.
2050 // If MAY_BE_COMPOSITE_LIT is true, the expression on the right hand
2051 // side may be a composite literal.
2053 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
2054 // RangeClause.
2056 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
2057 // guard (var := expr.("type") using the literal keyword "type").
2059 void
2060 Parse::simple_var_decl_or_assignment(const std::string& name,
2061 Location location,
2062 bool may_be_composite_lit,
2063 Range_clause* p_range_clause,
2064 Type_switch* p_type_switch)
2066 Typed_identifier_list til;
2067 til.push_back(Typed_identifier(name, NULL, location));
2069 // We've seen one identifier. If we see a comma now, this could be
2070 // "a, *p = 1, 2".
2071 if (this->peek_token()->is_op(OPERATOR_COMMA))
2073 go_assert(p_type_switch == NULL);
2074 while (true)
2076 const Token* token = this->advance_token();
2077 if (!token->is_identifier())
2078 break;
2080 std::string id = token->identifier();
2081 bool is_id_exported = token->is_identifier_exported();
2082 Location id_location = token->location();
2084 token = this->advance_token();
2085 if (!token->is_op(OPERATOR_COMMA))
2087 if (token->is_op(OPERATOR_COLONEQ))
2089 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2090 til.push_back(Typed_identifier(id, NULL, location));
2092 else
2093 this->unget_token(Token::make_identifier_token(id,
2094 is_id_exported,
2095 id_location));
2096 break;
2099 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2100 til.push_back(Typed_identifier(id, NULL, location));
2103 // We have a comma separated list of identifiers in TIL. If the
2104 // next token is COLONEQ, then this is a simple var decl, and we
2105 // have the complete list of identifiers. If the next token is
2106 // not COLONEQ, then the only valid parse is a tuple assignment.
2107 // The list of identifiers we have so far is really a list of
2108 // expressions. There are more expressions following.
2110 if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
2112 Expression_list* exprs = new Expression_list;
2113 for (Typed_identifier_list::const_iterator p = til.begin();
2114 p != til.end();
2115 ++p)
2116 exprs->push_back(this->id_to_expression(p->name(),
2117 p->location()));
2119 Expression_list* more_exprs =
2120 this->expression_list(NULL, true, may_be_composite_lit);
2121 for (Expression_list::const_iterator p = more_exprs->begin();
2122 p != more_exprs->end();
2123 ++p)
2124 exprs->push_back(*p);
2125 delete more_exprs;
2127 this->tuple_assignment(exprs, may_be_composite_lit, p_range_clause);
2128 return;
2132 go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
2133 const Token* token = this->advance_token();
2135 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
2137 this->range_clause_decl(&til, p_range_clause);
2138 return;
2141 Expression_list* init;
2142 if (p_type_switch == NULL)
2143 init = this->expression_list(NULL, false, may_be_composite_lit);
2144 else
2146 bool is_type_switch = false;
2147 Expression* expr = this->expression(PRECEDENCE_NORMAL, false,
2148 may_be_composite_lit,
2149 &is_type_switch, NULL);
2150 if (is_type_switch)
2152 p_type_switch->found = true;
2153 p_type_switch->name = name;
2154 p_type_switch->location = location;
2155 p_type_switch->expr = expr;
2156 return;
2159 if (!this->peek_token()->is_op(OPERATOR_COMMA))
2161 init = new Expression_list();
2162 init->push_back(expr);
2164 else
2166 this->advance_token();
2167 init = this->expression_list(expr, false, may_be_composite_lit);
2171 this->init_vars(&til, NULL, init, true, location);
2174 // FunctionDecl = "func" identifier Signature [ Block ] .
2175 // MethodDecl = "func" Receiver identifier Signature [ Block ] .
2177 // Deprecated gcc extension:
2178 // FunctionDecl = "func" identifier Signature
2179 // __asm__ "(" string_lit ")" .
2180 // This extension means a function whose real name is the identifier
2181 // inside the asm. This extension will be removed at some future
2182 // date. It has been replaced with //extern comments.
2184 // SAW_NOINTERFACE is true if we saw a magic //go:nointerface comment,
2185 // which means that we omit the method from the type descriptor.
2187 void
2188 Parse::function_decl(bool saw_nointerface)
2190 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2191 Location location = this->location();
2192 std::string extern_name = this->lex_->extern_name();
2193 const Token* token = this->advance_token();
2195 Typed_identifier* rec = NULL;
2196 if (token->is_op(OPERATOR_LPAREN))
2198 rec = this->receiver();
2199 token = this->peek_token();
2201 else if (saw_nointerface)
2203 warning_at(location, 0,
2204 "ignoring magic //go:nointerface comment before non-method");
2205 saw_nointerface = false;
2208 if (!token->is_identifier())
2210 error_at(this->location(), "expected function name");
2211 return;
2214 std::string name =
2215 this->gogo_->pack_hidden_name(token->identifier(),
2216 token->is_identifier_exported());
2218 this->advance_token();
2220 Function_type* fntype = this->signature(rec, this->location());
2222 Named_object* named_object = NULL;
2224 if (this->peek_token()->is_keyword(KEYWORD_ASM))
2226 if (!this->advance_token()->is_op(OPERATOR_LPAREN))
2228 error_at(this->location(), "expected %<(%>");
2229 return;
2231 token = this->advance_token();
2232 if (!token->is_string())
2234 error_at(this->location(), "expected string");
2235 return;
2237 std::string asm_name = token->string_value();
2238 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
2240 error_at(this->location(), "expected %<)%>");
2241 return;
2243 this->advance_token();
2244 if (!Gogo::is_sink_name(name))
2246 named_object = this->gogo_->declare_function(name, fntype, location);
2247 if (named_object->is_function_declaration())
2248 named_object->func_declaration_value()->set_asm_name(asm_name);
2252 // Check for the easy error of a newline before the opening brace.
2253 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
2255 Location semi_loc = this->location();
2256 if (this->advance_token()->is_op(OPERATOR_LCURLY))
2257 error_at(this->location(),
2258 "unexpected semicolon or newline before %<{%>");
2259 else
2260 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
2261 semi_loc));
2264 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2266 if (named_object == NULL && !Gogo::is_sink_name(name))
2268 if (fntype == NULL)
2269 this->gogo_->add_erroneous_name(name);
2270 else
2272 named_object = this->gogo_->declare_function(name, fntype,
2273 location);
2274 if (!extern_name.empty()
2275 && named_object->is_function_declaration())
2277 Function_declaration* fd =
2278 named_object->func_declaration_value();
2279 fd->set_asm_name(extern_name);
2284 if (saw_nointerface)
2285 warning_at(location, 0,
2286 ("ignoring magic //go:nointerface comment "
2287 "before declaration"));
2289 else
2291 bool hold_is_erroneous_function = this->is_erroneous_function_;
2292 if (fntype == NULL)
2294 fntype = Type::make_function_type(NULL, NULL, NULL, location);
2295 this->is_erroneous_function_ = true;
2296 if (!Gogo::is_sink_name(name))
2297 this->gogo_->add_erroneous_name(name);
2298 name = this->gogo_->pack_hidden_name("_", false);
2300 named_object = this->gogo_->start_function(name, fntype, true, location);
2301 Location end_loc = this->block();
2302 this->gogo_->finish_function(end_loc);
2303 if (saw_nointerface
2304 && !this->is_erroneous_function_
2305 && named_object->is_function())
2306 named_object->func_value()->set_nointerface();
2307 this->is_erroneous_function_ = hold_is_erroneous_function;
2311 // Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
2312 // BaseTypeName = identifier .
2314 Typed_identifier*
2315 Parse::receiver()
2317 go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
2319 std::string name;
2320 const Token* token = this->advance_token();
2321 Location location = token->location();
2322 if (!token->is_op(OPERATOR_MULT))
2324 if (!token->is_identifier())
2326 error_at(this->location(), "method has no receiver");
2327 this->gogo_->mark_locals_used();
2328 while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2329 token = this->advance_token();
2330 if (!token->is_eof())
2331 this->advance_token();
2332 return NULL;
2334 name = token->identifier();
2335 bool is_exported = token->is_identifier_exported();
2336 token = this->advance_token();
2337 if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN))
2339 // An identifier followed by something other than a dot or a
2340 // right parenthesis must be a receiver name followed by a
2341 // type.
2342 name = this->gogo_->pack_hidden_name(name, is_exported);
2344 else
2346 // This must be a type name.
2347 this->unget_token(Token::make_identifier_token(name, is_exported,
2348 location));
2349 token = this->peek_token();
2350 name.clear();
2354 // Here the receiver name is in NAME (it is empty if the receiver is
2355 // unnamed) and TOKEN is the first token in the type.
2357 bool is_pointer = false;
2358 if (token->is_op(OPERATOR_MULT))
2360 is_pointer = true;
2361 token = this->advance_token();
2364 if (!token->is_identifier())
2366 error_at(this->location(), "expected receiver name or type");
2367 this->gogo_->mark_locals_used();
2368 int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0;
2369 while (!token->is_eof())
2371 token = this->advance_token();
2372 if (token->is_op(OPERATOR_LPAREN))
2373 ++c;
2374 else if (token->is_op(OPERATOR_RPAREN))
2376 if (c == 0)
2377 break;
2378 --c;
2381 if (!token->is_eof())
2382 this->advance_token();
2383 return NULL;
2386 Type* type = this->type_name(true);
2388 if (is_pointer && !type->is_error_type())
2389 type = Type::make_pointer_type(type);
2391 if (this->peek_token()->is_op(OPERATOR_RPAREN))
2392 this->advance_token();
2393 else
2395 if (this->peek_token()->is_op(OPERATOR_COMMA))
2396 error_at(this->location(), "method has multiple receivers");
2397 else
2398 error_at(this->location(), "expected %<)%>");
2399 this->gogo_->mark_locals_used();
2400 while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2401 token = this->advance_token();
2402 if (!token->is_eof())
2403 this->advance_token();
2404 return NULL;
2407 return new Typed_identifier(name, type, location);
2410 // Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2411 // Literal = BasicLit | CompositeLit | FunctionLit .
2412 // BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2414 // If MAY_BE_SINK is true, this operand may be "_".
2416 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
2417 // if the entire expression is in parentheses.
2419 Expression*
2420 Parse::operand(bool may_be_sink, bool* is_parenthesized)
2422 const Token* token = this->peek_token();
2423 Expression* ret;
2424 switch (token->classification())
2426 case Token::TOKEN_IDENTIFIER:
2428 Location location = token->location();
2429 std::string id = token->identifier();
2430 bool is_exported = token->is_identifier_exported();
2431 std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2433 Named_object* in_function;
2434 Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2436 Package* package = NULL;
2437 if (named_object != NULL && named_object->is_package())
2439 if (!this->advance_token()->is_op(OPERATOR_DOT)
2440 || !this->advance_token()->is_identifier())
2442 error_at(location, "unexpected reference to package");
2443 return Expression::make_error(location);
2445 package = named_object->package_value();
2446 package->set_used();
2447 id = this->peek_token()->identifier();
2448 is_exported = this->peek_token()->is_identifier_exported();
2449 packed = this->gogo_->pack_hidden_name(id, is_exported);
2450 named_object = package->lookup(packed);
2451 location = this->location();
2452 go_assert(in_function == NULL);
2455 this->advance_token();
2457 if (named_object != NULL
2458 && named_object->is_type()
2459 && !named_object->type_value()->is_visible())
2461 go_assert(package != NULL);
2462 error_at(location, "invalid reference to hidden type %<%s.%s%>",
2463 Gogo::message_name(package->package_name()).c_str(),
2464 Gogo::message_name(id).c_str());
2465 return Expression::make_error(location);
2469 if (named_object == NULL)
2471 if (package != NULL)
2473 std::string n1 = Gogo::message_name(package->package_name());
2474 std::string n2 = Gogo::message_name(id);
2475 if (!is_exported)
2476 error_at(location,
2477 ("invalid reference to unexported identifier "
2478 "%<%s.%s%>"),
2479 n1.c_str(), n2.c_str());
2480 else
2481 error_at(location,
2482 "reference to undefined identifier %<%s.%s%>",
2483 n1.c_str(), n2.c_str());
2484 return Expression::make_error(location);
2487 named_object = this->gogo_->add_unknown_name(packed, location);
2490 if (in_function != NULL
2491 && in_function != this->gogo_->current_function()
2492 && (named_object->is_variable()
2493 || named_object->is_result_variable()))
2494 return this->enclosing_var_reference(in_function, named_object,
2495 location);
2497 switch (named_object->classification())
2499 case Named_object::NAMED_OBJECT_CONST:
2500 return Expression::make_const_reference(named_object, location);
2501 case Named_object::NAMED_OBJECT_TYPE:
2502 return Expression::make_type(named_object->type_value(), location);
2503 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2505 Type* t = Type::make_forward_declaration(named_object);
2506 return Expression::make_type(t, location);
2508 case Named_object::NAMED_OBJECT_VAR:
2509 case Named_object::NAMED_OBJECT_RESULT_VAR:
2510 this->mark_var_used(named_object);
2511 return Expression::make_var_reference(named_object, location);
2512 case Named_object::NAMED_OBJECT_SINK:
2513 if (may_be_sink)
2514 return Expression::make_sink(location);
2515 else
2517 error_at(location, "cannot use _ as value");
2518 return Expression::make_error(location);
2520 case Named_object::NAMED_OBJECT_FUNC:
2521 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2522 return Expression::make_func_reference(named_object, NULL,
2523 location);
2524 case Named_object::NAMED_OBJECT_UNKNOWN:
2526 Unknown_expression* ue =
2527 Expression::make_unknown_reference(named_object, location);
2528 if (this->is_erroneous_function_)
2529 ue->set_no_error_message();
2530 return ue;
2532 case Named_object::NAMED_OBJECT_ERRONEOUS:
2533 return Expression::make_error(location);
2534 default:
2535 go_unreachable();
2538 go_unreachable();
2540 case Token::TOKEN_STRING:
2541 ret = Expression::make_string(token->string_value(), token->location());
2542 this->advance_token();
2543 return ret;
2545 case Token::TOKEN_CHARACTER:
2546 ret = Expression::make_character(token->character_value(), NULL,
2547 token->location());
2548 this->advance_token();
2549 return ret;
2551 case Token::TOKEN_INTEGER:
2552 ret = Expression::make_integer(token->integer_value(), NULL,
2553 token->location());
2554 this->advance_token();
2555 return ret;
2557 case Token::TOKEN_FLOAT:
2558 ret = Expression::make_float(token->float_value(), NULL,
2559 token->location());
2560 this->advance_token();
2561 return ret;
2563 case Token::TOKEN_IMAGINARY:
2565 mpfr_t zero;
2566 mpfr_init_set_ui(zero, 0, GMP_RNDN);
2567 ret = Expression::make_complex(&zero, token->imaginary_value(),
2568 NULL, token->location());
2569 mpfr_clear(zero);
2570 this->advance_token();
2571 return ret;
2574 case Token::TOKEN_KEYWORD:
2575 switch (token->keyword())
2577 case KEYWORD_FUNC:
2578 return this->function_lit();
2579 case KEYWORD_CHAN:
2580 case KEYWORD_INTERFACE:
2581 case KEYWORD_MAP:
2582 case KEYWORD_STRUCT:
2584 Location location = token->location();
2585 return Expression::make_type(this->type(), location);
2587 default:
2588 break;
2590 break;
2592 case Token::TOKEN_OPERATOR:
2593 if (token->is_op(OPERATOR_LPAREN))
2595 this->advance_token();
2596 ret = this->expression(PRECEDENCE_NORMAL, may_be_sink, true, NULL,
2597 NULL);
2598 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2599 error_at(this->location(), "missing %<)%>");
2600 else
2601 this->advance_token();
2602 if (is_parenthesized != NULL)
2603 *is_parenthesized = true;
2604 return ret;
2606 else if (token->is_op(OPERATOR_LSQUARE))
2608 // Here we call array_type directly, as this is the only
2609 // case where an ellipsis is permitted for an array type.
2610 Location location = token->location();
2611 return Expression::make_type(this->array_type(true), location);
2613 break;
2615 default:
2616 break;
2619 error_at(this->location(), "expected operand");
2620 return Expression::make_error(this->location());
2623 // Handle a reference to a variable in an enclosing function. We add
2624 // it to a list of such variables. We return a reference to a field
2625 // in a struct which will be passed on the static chain when calling
2626 // the current function.
2628 Expression*
2629 Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2630 Location location)
2632 go_assert(var->is_variable() || var->is_result_variable());
2634 this->mark_var_used(var);
2636 Named_object* this_function = this->gogo_->current_function();
2637 Named_object* closure = this_function->func_value()->closure_var();
2639 // The last argument to the Enclosing_var constructor is the index
2640 // of this variable in the closure. We add 1 to the current number
2641 // of enclosed variables, because the first field in the closure
2642 // points to the function code.
2643 Enclosing_var ev(var, in_function, this->enclosing_vars_.size() + 1);
2644 std::pair<Enclosing_vars::iterator, bool> ins =
2645 this->enclosing_vars_.insert(ev);
2646 if (ins.second)
2648 // This is a variable we have not seen before. Add a new field
2649 // to the closure type.
2650 this_function->func_value()->add_closure_field(var, location);
2653 Expression* closure_ref = Expression::make_var_reference(closure,
2654 location);
2655 closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location);
2657 // The closure structure holds pointers to the variables, so we need
2658 // to introduce an indirection.
2659 Expression* e = Expression::make_field_reference(closure_ref,
2660 ins.first->index(),
2661 location);
2662 e = Expression::make_unary(OPERATOR_MULT, e, location);
2663 return e;
2666 // CompositeLit = LiteralType LiteralValue .
2667 // LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
2668 // SliceType | MapType | TypeName .
2669 // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
2670 // ElementList = Element { "," Element } .
2671 // Element = [ Key ":" ] Value .
2672 // Key = FieldName | ElementIndex .
2673 // FieldName = identifier .
2674 // ElementIndex = Expression .
2675 // Value = Expression | LiteralValue .
2677 // We have already seen the type if there is one, and we are now
2678 // looking at the LiteralValue. The case "[" "..." "]" ElementType
2679 // will be seen here as an array type whose length is "nil". The
2680 // DEPTH parameter is non-zero if this is an embedded composite
2681 // literal and the type was omitted. It gives the number of steps up
2682 // to the type which was provided. E.g., in [][]int{{1}} it will be
2683 // 1. In [][][]int{{{1}}} it will be 2.
2685 Expression*
2686 Parse::composite_lit(Type* type, int depth, Location location)
2688 go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2689 this->advance_token();
2691 if (this->peek_token()->is_op(OPERATOR_RCURLY))
2693 this->advance_token();
2694 return Expression::make_composite_literal(type, depth, false, NULL,
2695 false, location);
2698 bool has_keys = false;
2699 bool all_are_names = true;
2700 Expression_list* vals = new Expression_list;
2701 while (true)
2703 Expression* val;
2704 bool is_type_omitted = false;
2705 bool is_name = false;
2707 const Token* token = this->peek_token();
2709 if (token->is_identifier())
2711 std::string identifier = token->identifier();
2712 bool is_exported = token->is_identifier_exported();
2713 Location location = token->location();
2715 if (this->advance_token()->is_op(OPERATOR_COLON))
2717 // This may be a field name. We don't know for sure--it
2718 // could also be an expression for an array index. We
2719 // don't want to parse it as an expression because may
2720 // trigger various errors, e.g., if this identifier
2721 // happens to be the name of a package.
2722 Gogo* gogo = this->gogo_;
2723 val = this->id_to_expression(gogo->pack_hidden_name(identifier,
2724 is_exported),
2725 location);
2726 is_name = true;
2728 else
2730 this->unget_token(Token::make_identifier_token(identifier,
2731 is_exported,
2732 location));
2733 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
2734 NULL);
2737 else if (!token->is_op(OPERATOR_LCURLY))
2738 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
2739 else
2741 // This must be a composite literal inside another composite
2742 // literal, with the type omitted for the inner one.
2743 val = this->composite_lit(type, depth + 1, token->location());
2744 is_type_omitted = true;
2747 token = this->peek_token();
2748 if (!token->is_op(OPERATOR_COLON))
2750 if (has_keys)
2751 vals->push_back(NULL);
2752 is_name = false;
2754 else
2756 if (is_type_omitted && !val->is_error_expression())
2758 error_at(this->location(), "unexpected %<:%>");
2759 val = Expression::make_error(this->location());
2762 this->advance_token();
2764 if (!has_keys && !vals->empty())
2766 Expression_list* newvals = new Expression_list;
2767 for (Expression_list::const_iterator p = vals->begin();
2768 p != vals->end();
2769 ++p)
2771 newvals->push_back(NULL);
2772 newvals->push_back(*p);
2774 delete vals;
2775 vals = newvals;
2777 has_keys = true;
2779 if (val->unknown_expression() != NULL)
2780 val->unknown_expression()->set_is_composite_literal_key();
2782 vals->push_back(val);
2784 if (!token->is_op(OPERATOR_LCURLY))
2785 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
2786 else
2788 // This must be a composite literal inside another
2789 // composite literal, with the type omitted for the
2790 // inner one.
2791 val = this->composite_lit(type, depth + 1, token->location());
2794 token = this->peek_token();
2797 vals->push_back(val);
2799 if (!is_name)
2800 all_are_names = false;
2802 if (token->is_op(OPERATOR_COMMA))
2804 if (this->advance_token()->is_op(OPERATOR_RCURLY))
2806 this->advance_token();
2807 break;
2810 else if (token->is_op(OPERATOR_RCURLY))
2812 this->advance_token();
2813 break;
2815 else
2817 if (token->is_op(OPERATOR_SEMICOLON))
2818 error_at(this->location(),
2819 "need trailing comma before newline in composite literal");
2820 else
2821 error_at(this->location(), "expected %<,%> or %<}%>");
2823 this->gogo_->mark_locals_used();
2824 int depth = 0;
2825 while (!token->is_eof()
2826 && (depth > 0 || !token->is_op(OPERATOR_RCURLY)))
2828 if (token->is_op(OPERATOR_LCURLY))
2829 ++depth;
2830 else if (token->is_op(OPERATOR_RCURLY))
2831 --depth;
2832 token = this->advance_token();
2834 if (token->is_op(OPERATOR_RCURLY))
2835 this->advance_token();
2837 return Expression::make_error(location);
2841 return Expression::make_composite_literal(type, depth, has_keys, vals,
2842 all_are_names, location);
2845 // FunctionLit = "func" Signature Block .
2847 Expression*
2848 Parse::function_lit()
2850 Location location = this->location();
2851 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2852 this->advance_token();
2854 Enclosing_vars hold_enclosing_vars;
2855 hold_enclosing_vars.swap(this->enclosing_vars_);
2857 Function_type* type = this->signature(NULL, location);
2858 bool fntype_is_error = false;
2859 if (type == NULL)
2861 type = Type::make_function_type(NULL, NULL, NULL, location);
2862 fntype_is_error = true;
2865 // For a function literal, the next token must be a '{'. If we
2866 // don't see that, then we may have a type expression.
2867 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2868 return Expression::make_type(type, location);
2870 bool hold_is_erroneous_function = this->is_erroneous_function_;
2871 if (fntype_is_error)
2872 this->is_erroneous_function_ = true;
2874 Bc_stack* hold_break_stack = this->break_stack_;
2875 Bc_stack* hold_continue_stack = this->continue_stack_;
2876 this->break_stack_ = NULL;
2877 this->continue_stack_ = NULL;
2879 Named_object* no = this->gogo_->start_function("", type, true, location);
2881 Location end_loc = this->block();
2883 this->gogo_->finish_function(end_loc);
2885 if (this->break_stack_ != NULL)
2886 delete this->break_stack_;
2887 if (this->continue_stack_ != NULL)
2888 delete this->continue_stack_;
2889 this->break_stack_ = hold_break_stack;
2890 this->continue_stack_ = hold_continue_stack;
2892 this->is_erroneous_function_ = hold_is_erroneous_function;
2894 hold_enclosing_vars.swap(this->enclosing_vars_);
2896 Expression* closure = this->create_closure(no, &hold_enclosing_vars,
2897 location);
2899 return Expression::make_func_reference(no, closure, location);
2902 // Create a closure for the nested function FUNCTION. This is based
2903 // on ENCLOSING_VARS, which is a list of all variables defined in
2904 // enclosing functions and referenced from FUNCTION. A closure is the
2905 // address of a struct which point to the real function code and
2906 // contains the addresses of all the referenced variables. This
2907 // returns NULL if no closure is required.
2909 Expression*
2910 Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
2911 Location location)
2913 if (enclosing_vars->empty())
2914 return NULL;
2916 // Get the variables in order by their field index.
2918 size_t enclosing_var_count = enclosing_vars->size();
2919 std::vector<Enclosing_var> ev(enclosing_var_count);
2920 for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
2921 p != enclosing_vars->end();
2922 ++p)
2924 // Subtract 1 because index 0 is the function code.
2925 ev[p->index() - 1] = *p;
2928 // Build an initializer for a composite literal of the closure's
2929 // type.
2931 Named_object* enclosing_function = this->gogo_->current_function();
2932 Expression_list* initializer = new Expression_list;
2934 initializer->push_back(Expression::make_func_code_reference(function,
2935 location));
2937 for (size_t i = 0; i < enclosing_var_count; ++i)
2939 // Add 1 to i because the first field in the closure is a
2940 // pointer to the function code.
2941 go_assert(ev[i].index() == i + 1);
2942 Named_object* var = ev[i].var();
2943 Expression* ref;
2944 if (ev[i].in_function() == enclosing_function)
2945 ref = Expression::make_var_reference(var, location);
2946 else
2947 ref = this->enclosing_var_reference(ev[i].in_function(), var,
2948 location);
2949 Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
2950 location);
2951 initializer->push_back(refaddr);
2954 Named_object* closure_var = function->func_value()->closure_var();
2955 Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
2956 Expression* cv = Expression::make_struct_composite_literal(st, initializer,
2957 location);
2958 return Expression::make_heap_composite(cv, location);
2961 // PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
2963 // If MAY_BE_SINK is true, this expression may be "_".
2965 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
2966 // literal.
2968 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2969 // guard (var := expr.("type") using the literal keyword "type").
2971 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
2972 // if the entire expression is in parentheses.
2974 Expression*
2975 Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
2976 bool* is_type_switch, bool* is_parenthesized)
2978 Location start_loc = this->location();
2979 bool operand_is_parenthesized = false;
2980 bool whole_is_parenthesized = false;
2982 Expression* ret = this->operand(may_be_sink, &operand_is_parenthesized);
2984 whole_is_parenthesized = operand_is_parenthesized;
2986 // An unknown name followed by a curly brace must be a composite
2987 // literal, and the unknown name must be a type.
2988 if (may_be_composite_lit
2989 && !operand_is_parenthesized
2990 && ret->unknown_expression() != NULL
2991 && this->peek_token()->is_op(OPERATOR_LCURLY))
2993 Named_object* no = ret->unknown_expression()->named_object();
2994 Type* type = Type::make_forward_declaration(no);
2995 ret = Expression::make_type(type, ret->location());
2998 // We handle composite literals and type casts here, as it is the
2999 // easiest way to handle types which are in parentheses, as in
3000 // "((uint))(1)".
3001 if (ret->is_type_expression())
3003 if (this->peek_token()->is_op(OPERATOR_LCURLY))
3005 whole_is_parenthesized = false;
3006 if (!may_be_composite_lit)
3008 Type* t = ret->type();
3009 if (t->named_type() != NULL
3010 || t->forward_declaration_type() != NULL)
3011 error_at(start_loc,
3012 _("parentheses required around this composite literal "
3013 "to avoid parsing ambiguity"));
3015 else if (operand_is_parenthesized)
3016 error_at(start_loc,
3017 "cannot parenthesize type in composite literal");
3018 ret = this->composite_lit(ret->type(), 0, ret->location());
3020 else if (this->peek_token()->is_op(OPERATOR_LPAREN))
3022 whole_is_parenthesized = false;
3023 Location loc = this->location();
3024 this->advance_token();
3025 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
3026 NULL, NULL);
3027 if (this->peek_token()->is_op(OPERATOR_COMMA))
3028 this->advance_token();
3029 if (this->peek_token()->is_op(OPERATOR_ELLIPSIS))
3031 error_at(this->location(),
3032 "invalid use of %<...%> in type conversion");
3033 this->advance_token();
3035 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
3036 error_at(this->location(), "expected %<)%>");
3037 else
3038 this->advance_token();
3039 if (expr->is_error_expression())
3040 ret = expr;
3041 else
3043 Type* t = ret->type();
3044 if (t->classification() == Type::TYPE_ARRAY
3045 && t->array_type()->length() != NULL
3046 && t->array_type()->length()->is_nil_expression())
3048 error_at(ret->location(),
3049 "use of %<[...]%> outside of array literal");
3050 ret = Expression::make_error(loc);
3052 else
3053 ret = Expression::make_cast(t, expr, loc);
3058 while (true)
3060 const Token* token = this->peek_token();
3061 if (token->is_op(OPERATOR_LPAREN))
3063 whole_is_parenthesized = false;
3064 ret = this->call(this->verify_not_sink(ret));
3066 else if (token->is_op(OPERATOR_DOT))
3068 whole_is_parenthesized = false;
3069 ret = this->selector(this->verify_not_sink(ret), is_type_switch);
3070 if (is_type_switch != NULL && *is_type_switch)
3071 break;
3073 else if (token->is_op(OPERATOR_LSQUARE))
3075 whole_is_parenthesized = false;
3076 ret = this->index(this->verify_not_sink(ret));
3078 else
3079 break;
3082 if (whole_is_parenthesized && is_parenthesized != NULL)
3083 *is_parenthesized = true;
3085 return ret;
3088 // Selector = "." identifier .
3089 // TypeGuard = "." "(" QualifiedIdent ")" .
3091 // Note that Operand can expand to QualifiedIdent, which contains a
3092 // ".". That is handled directly in operand when it sees a package
3093 // name.
3095 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3096 // guard (var := expr.("type") using the literal keyword "type").
3098 Expression*
3099 Parse::selector(Expression* left, bool* is_type_switch)
3101 go_assert(this->peek_token()->is_op(OPERATOR_DOT));
3102 Location location = this->location();
3104 const Token* token = this->advance_token();
3105 if (token->is_identifier())
3107 // This could be a field in a struct, or a method in an
3108 // interface, or a method associated with a type. We can't know
3109 // which until we have seen all the types.
3110 std::string name =
3111 this->gogo_->pack_hidden_name(token->identifier(),
3112 token->is_identifier_exported());
3113 if (token->identifier() == "_")
3115 error_at(this->location(), "invalid use of %<_%>");
3116 name = Gogo::erroneous_name();
3118 this->advance_token();
3119 return Expression::make_selector(left, name, location);
3121 else if (token->is_op(OPERATOR_LPAREN))
3123 this->advance_token();
3124 Type* type = NULL;
3125 if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
3126 type = this->type();
3127 else
3129 if (is_type_switch != NULL)
3130 *is_type_switch = true;
3131 else
3133 error_at(this->location(),
3134 "use of %<.(type)%> outside type switch");
3135 type = Type::make_error_type();
3137 this->advance_token();
3139 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
3140 error_at(this->location(), "missing %<)%>");
3141 else
3142 this->advance_token();
3143 if (is_type_switch != NULL && *is_type_switch)
3144 return left;
3145 return Expression::make_type_guard(left, type, location);
3147 else
3149 error_at(this->location(), "expected identifier or %<(%>");
3150 return left;
3154 // Index = "[" Expression "]" .
3155 // Slice = "[" Expression ":" [ Expression ] "]" .
3157 Expression*
3158 Parse::index(Expression* expr)
3160 Location location = this->location();
3161 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
3162 this->advance_token();
3164 Expression* start;
3165 if (!this->peek_token()->is_op(OPERATOR_COLON))
3166 start = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3167 else
3169 mpz_t zero;
3170 mpz_init_set_ui(zero, 0);
3171 start = Expression::make_integer(&zero, NULL, location);
3172 mpz_clear(zero);
3175 Expression* end = NULL;
3176 if (this->peek_token()->is_op(OPERATOR_COLON))
3178 // We use nil to indicate a missing high expression.
3179 if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3180 end = Expression::make_nil(this->location());
3181 else
3182 end = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3184 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
3185 error_at(this->location(), "missing %<]%>");
3186 else
3187 this->advance_token();
3188 return Expression::make_index(expr, start, end, location);
3191 // Call = "(" [ ArgumentList [ "," ] ] ")" .
3192 // ArgumentList = ExpressionList [ "..." ] .
3194 Expression*
3195 Parse::call(Expression* func)
3197 go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
3198 Expression_list* args = NULL;
3199 bool is_varargs = false;
3200 const Token* token = this->advance_token();
3201 if (!token->is_op(OPERATOR_RPAREN))
3203 args = this->expression_list(NULL, false, true);
3204 token = this->peek_token();
3205 if (token->is_op(OPERATOR_ELLIPSIS))
3207 is_varargs = true;
3208 token = this->advance_token();
3211 if (token->is_op(OPERATOR_COMMA))
3212 token = this->advance_token();
3213 if (!token->is_op(OPERATOR_RPAREN))
3214 error_at(this->location(), "missing %<)%>");
3215 else
3216 this->advance_token();
3217 if (func->is_error_expression())
3218 return func;
3219 return Expression::make_call(func, args, is_varargs, func->location());
3222 // Return an expression for a single unqualified identifier.
3224 Expression*
3225 Parse::id_to_expression(const std::string& name, Location location)
3227 Named_object* in_function;
3228 Named_object* named_object = this->gogo_->lookup(name, &in_function);
3229 if (named_object == NULL)
3230 named_object = this->gogo_->add_unknown_name(name, location);
3232 if (in_function != NULL
3233 && in_function != this->gogo_->current_function()
3234 && (named_object->is_variable() || named_object->is_result_variable()))
3235 return this->enclosing_var_reference(in_function, named_object,
3236 location);
3238 switch (named_object->classification())
3240 case Named_object::NAMED_OBJECT_CONST:
3241 return Expression::make_const_reference(named_object, location);
3242 case Named_object::NAMED_OBJECT_VAR:
3243 case Named_object::NAMED_OBJECT_RESULT_VAR:
3244 this->mark_var_used(named_object);
3245 return Expression::make_var_reference(named_object, location);
3246 case Named_object::NAMED_OBJECT_SINK:
3247 return Expression::make_sink(location);
3248 case Named_object::NAMED_OBJECT_FUNC:
3249 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3250 return Expression::make_func_reference(named_object, NULL, location);
3251 case Named_object::NAMED_OBJECT_UNKNOWN:
3253 Unknown_expression* ue =
3254 Expression::make_unknown_reference(named_object, location);
3255 if (this->is_erroneous_function_)
3256 ue->set_no_error_message();
3257 return ue;
3259 case Named_object::NAMED_OBJECT_PACKAGE:
3260 case Named_object::NAMED_OBJECT_TYPE:
3261 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3263 // These cases can arise for a field name in a composite
3264 // literal.
3265 Unknown_expression* ue =
3266 Expression::make_unknown_reference(named_object, location);
3267 if (this->is_erroneous_function_)
3268 ue->set_no_error_message();
3269 return ue;
3271 case Named_object::NAMED_OBJECT_ERRONEOUS:
3272 return Expression::make_error(location);
3273 default:
3274 error_at(this->location(), "unexpected type of identifier");
3275 return Expression::make_error(location);
3279 // Expression = UnaryExpr { binary_op Expression } .
3281 // PRECEDENCE is the precedence of the current operator.
3283 // If MAY_BE_SINK is true, this expression may be "_".
3285 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3286 // literal.
3288 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3289 // guard (var := expr.("type") using the literal keyword "type").
3291 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3292 // if the entire expression is in parentheses.
3294 Expression*
3295 Parse::expression(Precedence precedence, bool may_be_sink,
3296 bool may_be_composite_lit, bool* is_type_switch,
3297 bool *is_parenthesized)
3299 Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
3300 is_type_switch, is_parenthesized);
3302 while (true)
3304 if (is_type_switch != NULL && *is_type_switch)
3305 return left;
3307 const Token* token = this->peek_token();
3308 if (token->classification() != Token::TOKEN_OPERATOR)
3310 // Not a binary_op.
3311 return left;
3314 Precedence right_precedence;
3315 switch (token->op())
3317 case OPERATOR_OROR:
3318 right_precedence = PRECEDENCE_OROR;
3319 break;
3320 case OPERATOR_ANDAND:
3321 right_precedence = PRECEDENCE_ANDAND;
3322 break;
3323 case OPERATOR_EQEQ:
3324 case OPERATOR_NOTEQ:
3325 case OPERATOR_LT:
3326 case OPERATOR_LE:
3327 case OPERATOR_GT:
3328 case OPERATOR_GE:
3329 right_precedence = PRECEDENCE_RELOP;
3330 break;
3331 case OPERATOR_PLUS:
3332 case OPERATOR_MINUS:
3333 case OPERATOR_OR:
3334 case OPERATOR_XOR:
3335 right_precedence = PRECEDENCE_ADDOP;
3336 break;
3337 case OPERATOR_MULT:
3338 case OPERATOR_DIV:
3339 case OPERATOR_MOD:
3340 case OPERATOR_LSHIFT:
3341 case OPERATOR_RSHIFT:
3342 case OPERATOR_AND:
3343 case OPERATOR_BITCLEAR:
3344 right_precedence = PRECEDENCE_MULOP;
3345 break;
3346 default:
3347 right_precedence = PRECEDENCE_INVALID;
3348 break;
3351 if (right_precedence == PRECEDENCE_INVALID)
3353 // Not a binary_op.
3354 return left;
3357 if (is_parenthesized != NULL)
3358 *is_parenthesized = false;
3360 Operator op = token->op();
3361 Location binop_location = token->location();
3363 if (precedence >= right_precedence)
3365 // We've already seen A * B, and we see + C. We want to
3366 // return so that A * B becomes a group.
3367 return left;
3370 this->advance_token();
3372 left = this->verify_not_sink(left);
3373 Expression* right = this->expression(right_precedence, false,
3374 may_be_composite_lit,
3375 NULL, NULL);
3376 left = Expression::make_binary(op, left, right, binop_location);
3380 bool
3381 Parse::expression_may_start_here()
3383 const Token* token = this->peek_token();
3384 switch (token->classification())
3386 case Token::TOKEN_INVALID:
3387 case Token::TOKEN_EOF:
3388 return false;
3389 case Token::TOKEN_KEYWORD:
3390 switch (token->keyword())
3392 case KEYWORD_CHAN:
3393 case KEYWORD_FUNC:
3394 case KEYWORD_MAP:
3395 case KEYWORD_STRUCT:
3396 case KEYWORD_INTERFACE:
3397 return true;
3398 default:
3399 return false;
3401 case Token::TOKEN_IDENTIFIER:
3402 return true;
3403 case Token::TOKEN_STRING:
3404 return true;
3405 case Token::TOKEN_OPERATOR:
3406 switch (token->op())
3408 case OPERATOR_PLUS:
3409 case OPERATOR_MINUS:
3410 case OPERATOR_NOT:
3411 case OPERATOR_XOR:
3412 case OPERATOR_MULT:
3413 case OPERATOR_CHANOP:
3414 case OPERATOR_AND:
3415 case OPERATOR_LPAREN:
3416 case OPERATOR_LSQUARE:
3417 return true;
3418 default:
3419 return false;
3421 case Token::TOKEN_CHARACTER:
3422 case Token::TOKEN_INTEGER:
3423 case Token::TOKEN_FLOAT:
3424 case Token::TOKEN_IMAGINARY:
3425 return true;
3426 default:
3427 go_unreachable();
3431 // UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3433 // If MAY_BE_SINK is true, this expression may be "_".
3435 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3436 // literal.
3438 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3439 // guard (var := expr.("type") using the literal keyword "type").
3441 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3442 // if the entire expression is in parentheses.
3444 Expression*
3445 Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3446 bool* is_type_switch, bool* is_parenthesized)
3448 const Token* token = this->peek_token();
3450 // There is a complex parse for <- chan. The choices are
3451 // Convert x to type <- chan int:
3452 // (<- chan int)(x)
3453 // Receive from (x converted to type chan <- chan int):
3454 // (<- chan <- chan int (x))
3455 // Convert x to type <- chan (<- chan int).
3456 // (<- chan <- chan int)(x)
3457 if (token->is_op(OPERATOR_CHANOP))
3459 Location location = token->location();
3460 if (this->advance_token()->is_keyword(KEYWORD_CHAN))
3462 Expression* expr = this->primary_expr(false, may_be_composite_lit,
3463 NULL, NULL);
3464 if (expr->is_error_expression())
3465 return expr;
3466 else if (!expr->is_type_expression())
3467 return Expression::make_receive(expr, location);
3468 else
3470 if (expr->type()->is_error_type())
3471 return expr;
3473 // We picked up "chan TYPE", but it is not a type
3474 // conversion.
3475 Channel_type* ct = expr->type()->channel_type();
3476 if (ct == NULL)
3478 // This is probably impossible.
3479 error_at(location, "expected channel type");
3480 return Expression::make_error(location);
3482 else if (ct->may_receive())
3484 // <- chan TYPE.
3485 Type* t = Type::make_channel_type(false, true,
3486 ct->element_type());
3487 return Expression::make_type(t, location);
3489 else
3491 // <- chan <- TYPE. Because we skipped the leading
3492 // <-, we parsed this as chan <- TYPE. With the
3493 // leading <-, we parse it as <- chan (<- TYPE).
3494 Type *t = this->reassociate_chan_direction(ct, location);
3495 return Expression::make_type(t, location);
3500 this->unget_token(Token::make_operator_token(OPERATOR_CHANOP, location));
3501 token = this->peek_token();
3504 if (token->is_op(OPERATOR_PLUS)
3505 || token->is_op(OPERATOR_MINUS)
3506 || token->is_op(OPERATOR_NOT)
3507 || token->is_op(OPERATOR_XOR)
3508 || token->is_op(OPERATOR_CHANOP)
3509 || token->is_op(OPERATOR_MULT)
3510 || token->is_op(OPERATOR_AND))
3512 Location location = token->location();
3513 Operator op = token->op();
3514 this->advance_token();
3516 Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL,
3517 NULL);
3518 if (expr->is_error_expression())
3520 else if (op == OPERATOR_MULT && expr->is_type_expression())
3521 expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3522 location);
3523 else if (op == OPERATOR_AND && expr->is_composite_literal())
3524 expr = Expression::make_heap_composite(expr, location);
3525 else if (op != OPERATOR_CHANOP)
3526 expr = Expression::make_unary(op, expr, location);
3527 else
3528 expr = Expression::make_receive(expr, location);
3529 return expr;
3531 else
3532 return this->primary_expr(may_be_sink, may_be_composite_lit,
3533 is_type_switch, is_parenthesized);
3536 // This is called for the obscure case of
3537 // (<- chan <- chan int)(x)
3538 // In unary_expr we remove the leading <- and parse the remainder,
3539 // which gives us
3540 // chan <- (chan int)
3541 // When we add the leading <- back in, we really want
3542 // <- chan (<- chan int)
3543 // This means that we need to reassociate.
3545 Type*
3546 Parse::reassociate_chan_direction(Channel_type *ct, Location location)
3548 Channel_type* ele = ct->element_type()->channel_type();
3549 if (ele == NULL)
3551 error_at(location, "parse error");
3552 return Type::make_error_type();
3554 Type* sub = ele;
3555 if (ele->may_send())
3556 sub = Type::make_channel_type(false, true, ele->element_type());
3557 else
3558 sub = this->reassociate_chan_direction(ele, location);
3559 return Type::make_channel_type(false, true, sub);
3562 // Statement =
3563 // Declaration | LabeledStmt | SimpleStmt |
3564 // GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3565 // FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3566 // DeferStmt .
3568 // LABEL is the label of this statement if it has one.
3570 void
3571 Parse::statement(Label* label)
3573 const Token* token = this->peek_token();
3574 switch (token->classification())
3576 case Token::TOKEN_KEYWORD:
3578 switch (token->keyword())
3580 case KEYWORD_CONST:
3581 case KEYWORD_TYPE:
3582 case KEYWORD_VAR:
3583 this->declaration();
3584 break;
3585 case KEYWORD_FUNC:
3586 case KEYWORD_MAP:
3587 case KEYWORD_STRUCT:
3588 case KEYWORD_INTERFACE:
3589 this->simple_stat(true, NULL, NULL, NULL);
3590 break;
3591 case KEYWORD_GO:
3592 case KEYWORD_DEFER:
3593 this->go_or_defer_stat();
3594 break;
3595 case KEYWORD_RETURN:
3596 this->return_stat();
3597 break;
3598 case KEYWORD_BREAK:
3599 this->break_stat();
3600 break;
3601 case KEYWORD_CONTINUE:
3602 this->continue_stat();
3603 break;
3604 case KEYWORD_GOTO:
3605 this->goto_stat();
3606 break;
3607 case KEYWORD_IF:
3608 this->if_stat();
3609 break;
3610 case KEYWORD_SWITCH:
3611 this->switch_stat(label);
3612 break;
3613 case KEYWORD_SELECT:
3614 this->select_stat(label);
3615 break;
3616 case KEYWORD_FOR:
3617 this->for_stat(label);
3618 break;
3619 default:
3620 error_at(this->location(), "expected statement");
3621 this->advance_token();
3622 break;
3625 break;
3627 case Token::TOKEN_IDENTIFIER:
3629 std::string identifier = token->identifier();
3630 bool is_exported = token->is_identifier_exported();
3631 Location location = token->location();
3632 if (this->advance_token()->is_op(OPERATOR_COLON))
3634 this->advance_token();
3635 this->labeled_stmt(identifier, location);
3637 else
3639 this->unget_token(Token::make_identifier_token(identifier,
3640 is_exported,
3641 location));
3642 this->simple_stat(true, NULL, NULL, NULL);
3645 break;
3647 case Token::TOKEN_OPERATOR:
3648 if (token->is_op(OPERATOR_LCURLY))
3650 Location location = token->location();
3651 this->gogo_->start_block(location);
3652 Location end_loc = this->block();
3653 this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3654 location);
3656 else if (!token->is_op(OPERATOR_SEMICOLON))
3657 this->simple_stat(true, NULL, NULL, NULL);
3658 break;
3660 case Token::TOKEN_STRING:
3661 case Token::TOKEN_CHARACTER:
3662 case Token::TOKEN_INTEGER:
3663 case Token::TOKEN_FLOAT:
3664 case Token::TOKEN_IMAGINARY:
3665 this->simple_stat(true, NULL, NULL, NULL);
3666 break;
3668 default:
3669 error_at(this->location(), "expected statement");
3670 this->advance_token();
3671 break;
3675 bool
3676 Parse::statement_may_start_here()
3678 const Token* token = this->peek_token();
3679 switch (token->classification())
3681 case Token::TOKEN_KEYWORD:
3683 switch (token->keyword())
3685 case KEYWORD_CONST:
3686 case KEYWORD_TYPE:
3687 case KEYWORD_VAR:
3688 case KEYWORD_FUNC:
3689 case KEYWORD_MAP:
3690 case KEYWORD_STRUCT:
3691 case KEYWORD_INTERFACE:
3692 case KEYWORD_GO:
3693 case KEYWORD_DEFER:
3694 case KEYWORD_RETURN:
3695 case KEYWORD_BREAK:
3696 case KEYWORD_CONTINUE:
3697 case KEYWORD_GOTO:
3698 case KEYWORD_IF:
3699 case KEYWORD_SWITCH:
3700 case KEYWORD_SELECT:
3701 case KEYWORD_FOR:
3702 return true;
3704 default:
3705 return false;
3708 break;
3710 case Token::TOKEN_IDENTIFIER:
3711 return true;
3713 case Token::TOKEN_OPERATOR:
3714 if (token->is_op(OPERATOR_LCURLY)
3715 || token->is_op(OPERATOR_SEMICOLON))
3716 return true;
3717 else
3718 return this->expression_may_start_here();
3720 case Token::TOKEN_STRING:
3721 case Token::TOKEN_CHARACTER:
3722 case Token::TOKEN_INTEGER:
3723 case Token::TOKEN_FLOAT:
3724 case Token::TOKEN_IMAGINARY:
3725 return true;
3727 default:
3728 return false;
3732 // LabeledStmt = Label ":" Statement .
3733 // Label = identifier .
3735 void
3736 Parse::labeled_stmt(const std::string& label_name, Location location)
3738 Label* label = this->gogo_->add_label_definition(label_name, location);
3740 if (this->peek_token()->is_op(OPERATOR_RCURLY))
3742 // This is a label at the end of a block. A program is
3743 // permitted to omit a semicolon here.
3744 return;
3747 if (!this->statement_may_start_here())
3749 // Mark the label as used to avoid a useless error about an
3750 // unused label.
3751 label->set_is_used();
3753 error_at(location, "missing statement after label");
3754 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3755 location));
3756 return;
3759 this->statement(label);
3762 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
3763 // Assignment | ShortVarDecl .
3765 // EmptyStmt was handled in Parse::statement.
3767 // In order to make this work for if and switch statements, if
3768 // RETURN_EXP is not NULL, and we see an ExpressionStat, we return the
3769 // expression rather than adding an expression statement to the
3770 // current block. If we see something other than an ExpressionStat,
3771 // we add the statement, set *RETURN_EXP to true if we saw a send
3772 // statement, and return NULL. The handling of send statements is for
3773 // better error messages.
3775 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
3776 // RangeClause.
3778 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
3779 // guard (var := expr.("type") using the literal keyword "type").
3781 Expression*
3782 Parse::simple_stat(bool may_be_composite_lit, bool* return_exp,
3783 Range_clause* p_range_clause, Type_switch* p_type_switch)
3785 const Token* token = this->peek_token();
3787 // An identifier follow by := is a SimpleVarDecl.
3788 if (token->is_identifier())
3790 std::string identifier = token->identifier();
3791 bool is_exported = token->is_identifier_exported();
3792 Location location = token->location();
3794 token = this->advance_token();
3795 if (token->is_op(OPERATOR_COLONEQ)
3796 || token->is_op(OPERATOR_COMMA))
3798 identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
3799 this->simple_var_decl_or_assignment(identifier, location,
3800 may_be_composite_lit,
3801 p_range_clause,
3802 (token->is_op(OPERATOR_COLONEQ)
3803 ? p_type_switch
3804 : NULL));
3805 return NULL;
3808 this->unget_token(Token::make_identifier_token(identifier, is_exported,
3809 location));
3812 Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
3813 may_be_composite_lit,
3814 (p_type_switch == NULL
3815 ? NULL
3816 : &p_type_switch->found),
3817 NULL);
3818 if (p_type_switch != NULL && p_type_switch->found)
3820 p_type_switch->name.clear();
3821 p_type_switch->location = exp->location();
3822 p_type_switch->expr = this->verify_not_sink(exp);
3823 return NULL;
3825 token = this->peek_token();
3826 if (token->is_op(OPERATOR_CHANOP))
3828 this->send_stmt(this->verify_not_sink(exp));
3829 if (return_exp != NULL)
3830 *return_exp = true;
3832 else if (token->is_op(OPERATOR_PLUSPLUS)
3833 || token->is_op(OPERATOR_MINUSMINUS))
3834 this->inc_dec_stat(this->verify_not_sink(exp));
3835 else if (token->is_op(OPERATOR_COMMA)
3836 || token->is_op(OPERATOR_EQ))
3837 this->assignment(exp, may_be_composite_lit, p_range_clause);
3838 else if (token->is_op(OPERATOR_PLUSEQ)
3839 || token->is_op(OPERATOR_MINUSEQ)
3840 || token->is_op(OPERATOR_OREQ)
3841 || token->is_op(OPERATOR_XOREQ)
3842 || token->is_op(OPERATOR_MULTEQ)
3843 || token->is_op(OPERATOR_DIVEQ)
3844 || token->is_op(OPERATOR_MODEQ)
3845 || token->is_op(OPERATOR_LSHIFTEQ)
3846 || token->is_op(OPERATOR_RSHIFTEQ)
3847 || token->is_op(OPERATOR_ANDEQ)
3848 || token->is_op(OPERATOR_BITCLEAREQ))
3849 this->assignment(this->verify_not_sink(exp), may_be_composite_lit,
3850 p_range_clause);
3851 else if (return_exp != NULL)
3852 return this->verify_not_sink(exp);
3853 else
3855 exp = this->verify_not_sink(exp);
3857 if (token->is_op(OPERATOR_COLONEQ))
3859 if (!exp->is_error_expression())
3860 error_at(token->location(), "non-name on left side of %<:=%>");
3861 this->gogo_->mark_locals_used();
3862 while (!token->is_op(OPERATOR_SEMICOLON)
3863 && !token->is_eof())
3864 token = this->advance_token();
3865 return NULL;
3868 this->expression_stat(exp);
3871 return NULL;
3874 bool
3875 Parse::simple_stat_may_start_here()
3877 return this->expression_may_start_here();
3880 // Parse { Statement ";" } which is used in a few places. The list of
3881 // statements may end with a right curly brace, in which case the
3882 // semicolon may be omitted.
3884 void
3885 Parse::statement_list()
3887 while (this->statement_may_start_here())
3889 this->statement(NULL);
3890 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3891 this->advance_token();
3892 else if (this->peek_token()->is_op(OPERATOR_RCURLY))
3893 break;
3894 else
3896 if (!this->peek_token()->is_eof() || !saw_errors())
3897 error_at(this->location(), "expected %<;%> or %<}%> or newline");
3898 if (!this->skip_past_error(OPERATOR_RCURLY))
3899 return;
3904 bool
3905 Parse::statement_list_may_start_here()
3907 return this->statement_may_start_here();
3910 // ExpressionStat = Expression .
3912 void
3913 Parse::expression_stat(Expression* exp)
3915 this->gogo_->add_statement(Statement::make_statement(exp, false));
3918 // SendStmt = Channel "&lt;-" Expression .
3919 // Channel = Expression .
3921 void
3922 Parse::send_stmt(Expression* channel)
3924 go_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
3925 Location loc = this->location();
3926 this->advance_token();
3927 Expression* val = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
3928 NULL);
3929 Statement* s = Statement::make_send_statement(channel, val, loc);
3930 this->gogo_->add_statement(s);
3933 // IncDecStat = Expression ( "++" | "--" ) .
3935 void
3936 Parse::inc_dec_stat(Expression* exp)
3938 const Token* token = this->peek_token();
3940 // Lvalue maps require special handling.
3941 if (exp->index_expression() != NULL)
3942 exp->index_expression()->set_is_lvalue();
3944 if (token->is_op(OPERATOR_PLUSPLUS))
3945 this->gogo_->add_statement(Statement::make_inc_statement(exp));
3946 else if (token->is_op(OPERATOR_MINUSMINUS))
3947 this->gogo_->add_statement(Statement::make_dec_statement(exp));
3948 else
3949 go_unreachable();
3950 this->advance_token();
3953 // Assignment = ExpressionList assign_op ExpressionList .
3955 // EXP is an expression that we have already parsed.
3957 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
3958 // side may be a composite literal.
3960 // If RANGE_CLAUSE is not NULL, then this will recognize a
3961 // RangeClause.
3963 void
3964 Parse::assignment(Expression* expr, bool may_be_composite_lit,
3965 Range_clause* p_range_clause)
3967 Expression_list* vars;
3968 if (!this->peek_token()->is_op(OPERATOR_COMMA))
3970 vars = new Expression_list();
3971 vars->push_back(expr);
3973 else
3975 this->advance_token();
3976 vars = this->expression_list(expr, true, may_be_composite_lit);
3979 this->tuple_assignment(vars, may_be_composite_lit, p_range_clause);
3982 // An assignment statement. LHS is the list of expressions which
3983 // appear on the left hand side.
3985 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
3986 // side may be a composite literal.
3988 // If RANGE_CLAUSE is not NULL, then this will recognize a
3989 // RangeClause.
3991 void
3992 Parse::tuple_assignment(Expression_list* lhs, bool may_be_composite_lit,
3993 Range_clause* p_range_clause)
3995 const Token* token = this->peek_token();
3996 if (!token->is_op(OPERATOR_EQ)
3997 && !token->is_op(OPERATOR_PLUSEQ)
3998 && !token->is_op(OPERATOR_MINUSEQ)
3999 && !token->is_op(OPERATOR_OREQ)
4000 && !token->is_op(OPERATOR_XOREQ)
4001 && !token->is_op(OPERATOR_MULTEQ)
4002 && !token->is_op(OPERATOR_DIVEQ)
4003 && !token->is_op(OPERATOR_MODEQ)
4004 && !token->is_op(OPERATOR_LSHIFTEQ)
4005 && !token->is_op(OPERATOR_RSHIFTEQ)
4006 && !token->is_op(OPERATOR_ANDEQ)
4007 && !token->is_op(OPERATOR_BITCLEAREQ))
4009 error_at(this->location(), "expected assignment operator");
4010 return;
4012 Operator op = token->op();
4013 Location location = token->location();
4015 token = this->advance_token();
4017 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
4019 if (op != OPERATOR_EQ)
4020 error_at(this->location(), "range clause requires %<=%>");
4021 this->range_clause_expr(lhs, p_range_clause);
4022 return;
4025 Expression_list* vals = this->expression_list(NULL, false,
4026 may_be_composite_lit);
4028 // We've parsed everything; check for errors.
4029 if (lhs == NULL || vals == NULL)
4030 return;
4031 for (Expression_list::const_iterator pe = lhs->begin();
4032 pe != lhs->end();
4033 ++pe)
4035 if ((*pe)->is_error_expression())
4036 return;
4037 if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
4038 error_at((*pe)->location(), "cannot use _ as value");
4040 for (Expression_list::const_iterator pe = vals->begin();
4041 pe != vals->end();
4042 ++pe)
4044 if ((*pe)->is_error_expression())
4045 return;
4048 // Map expressions act differently when they are lvalues.
4049 for (Expression_list::iterator plv = lhs->begin();
4050 plv != lhs->end();
4051 ++plv)
4052 if ((*plv)->index_expression() != NULL)
4053 (*plv)->index_expression()->set_is_lvalue();
4055 Call_expression* call;
4056 Index_expression* map_index;
4057 Receive_expression* receive;
4058 Type_guard_expression* type_guard;
4059 if (lhs->size() == vals->size())
4061 Statement* s;
4062 if (lhs->size() > 1)
4064 if (op != OPERATOR_EQ)
4065 error_at(location, "multiple values only permitted with %<=%>");
4066 s = Statement::make_tuple_assignment(lhs, vals, location);
4068 else
4070 if (op == OPERATOR_EQ)
4071 s = Statement::make_assignment(lhs->front(), vals->front(),
4072 location);
4073 else
4074 s = Statement::make_assignment_operation(op, lhs->front(),
4075 vals->front(), location);
4076 delete lhs;
4077 delete vals;
4079 this->gogo_->add_statement(s);
4081 else if (vals->size() == 1
4082 && (call = (*vals->begin())->call_expression()) != NULL)
4084 if (op != OPERATOR_EQ)
4085 error_at(location, "multiple results only permitted with %<=%>");
4086 delete vals;
4087 vals = new Expression_list;
4088 for (unsigned int i = 0; i < lhs->size(); ++i)
4089 vals->push_back(Expression::make_call_result(call, i));
4090 Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
4091 this->gogo_->add_statement(s);
4093 else if (lhs->size() == 2
4094 && vals->size() == 1
4095 && (map_index = (*vals->begin())->index_expression()) != NULL)
4097 if (op != OPERATOR_EQ)
4098 error_at(location, "two values from map requires %<=%>");
4099 Expression* val = lhs->front();
4100 Expression* present = lhs->back();
4101 Statement* s = Statement::make_tuple_map_assignment(val, present,
4102 map_index, location);
4103 this->gogo_->add_statement(s);
4105 else if (lhs->size() == 1
4106 && vals->size() == 2
4107 && (map_index = lhs->front()->index_expression()) != NULL)
4109 if (op != OPERATOR_EQ)
4110 error_at(location, "assigning tuple to map index requires %<=%>");
4111 Expression* val = vals->front();
4112 Expression* should_set = vals->back();
4113 Statement* s = Statement::make_map_assignment(map_index, val, should_set,
4114 location);
4115 this->gogo_->add_statement(s);
4117 else if (lhs->size() == 2
4118 && vals->size() == 1
4119 && (receive = (*vals->begin())->receive_expression()) != NULL)
4121 if (op != OPERATOR_EQ)
4122 error_at(location, "two values from receive requires %<=%>");
4123 Expression* val = lhs->front();
4124 Expression* success = lhs->back();
4125 Expression* channel = receive->channel();
4126 Statement* s = Statement::make_tuple_receive_assignment(val, success,
4127 channel,
4128 location);
4129 this->gogo_->add_statement(s);
4131 else if (lhs->size() == 2
4132 && vals->size() == 1
4133 && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
4135 if (op != OPERATOR_EQ)
4136 error_at(location, "two values from type guard requires %<=%>");
4137 Expression* val = lhs->front();
4138 Expression* ok = lhs->back();
4139 Expression* expr = type_guard->expr();
4140 Type* type = type_guard->type();
4141 Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
4142 expr, type,
4143 location);
4144 this->gogo_->add_statement(s);
4146 else
4148 error_at(location, "number of variables does not match number of values");
4152 // GoStat = "go" Expression .
4153 // DeferStat = "defer" Expression .
4155 void
4156 Parse::go_or_defer_stat()
4158 go_assert(this->peek_token()->is_keyword(KEYWORD_GO)
4159 || this->peek_token()->is_keyword(KEYWORD_DEFER));
4160 bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
4161 Location stat_location = this->location();
4163 this->advance_token();
4164 Location expr_location = this->location();
4166 bool is_parenthesized = false;
4167 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
4168 &is_parenthesized);
4169 Call_expression* call_expr = expr->call_expression();
4170 if (is_parenthesized || call_expr == NULL)
4172 error_at(expr_location, "argument to go/defer must be function call");
4173 return;
4176 // Make it easier to simplify go/defer statements by putting every
4177 // statement in its own block.
4178 this->gogo_->start_block(stat_location);
4179 Statement* stat;
4180 if (is_go)
4181 stat = Statement::make_go_statement(call_expr, stat_location);
4182 else
4183 stat = Statement::make_defer_statement(call_expr, stat_location);
4184 this->gogo_->add_statement(stat);
4185 this->gogo_->add_block(this->gogo_->finish_block(stat_location),
4186 stat_location);
4189 // ReturnStat = "return" [ ExpressionList ] .
4191 void
4192 Parse::return_stat()
4194 go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
4195 Location location = this->location();
4196 this->advance_token();
4197 Expression_list* vals = NULL;
4198 if (this->expression_may_start_here())
4199 vals = this->expression_list(NULL, false, true);
4200 this->gogo_->add_statement(Statement::make_return_statement(vals, location));
4202 if (vals == NULL
4203 && this->gogo_->current_function()->func_value()->results_are_named())
4205 Named_object* function = this->gogo_->current_function();
4206 Function::Results* results = function->func_value()->result_variables();
4207 for (Function::Results::const_iterator p = results->begin();
4208 p != results->end();
4209 ++p)
4211 Named_object* no = this->gogo_->lookup((*p)->name(), NULL);
4212 if (no == NULL)
4213 go_assert(saw_errors());
4214 else if (!no->is_result_variable())
4215 error_at(location, "%qs is shadowed during return",
4216 (*p)->message_name().c_str());
4221 // IfStmt = "if" [ SimpleStmt ";" ] Expression Block
4222 // [ "else" ( IfStmt | Block ) ] .
4224 void
4225 Parse::if_stat()
4227 go_assert(this->peek_token()->is_keyword(KEYWORD_IF));
4228 Location location = this->location();
4229 this->advance_token();
4231 this->gogo_->start_block(location);
4233 bool saw_simple_stat = false;
4234 Expression* cond = NULL;
4235 bool saw_send_stmt = false;
4236 if (this->simple_stat_may_start_here())
4238 cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL);
4239 saw_simple_stat = true;
4241 if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4243 // The SimpleStat is an expression statement.
4244 this->expression_stat(cond);
4245 cond = NULL;
4247 if (cond == NULL)
4249 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4250 this->advance_token();
4251 else if (saw_simple_stat)
4253 if (saw_send_stmt)
4254 error_at(this->location(),
4255 ("send statement used as value; "
4256 "use select for non-blocking send"));
4257 else
4258 error_at(this->location(),
4259 "expected %<;%> after statement in if expression");
4260 if (!this->expression_may_start_here())
4261 cond = Expression::make_error(this->location());
4263 if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY))
4265 error_at(this->location(),
4266 "missing condition in if statement");
4267 cond = Expression::make_error(this->location());
4269 if (cond == NULL)
4270 cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL, NULL);
4273 this->gogo_->start_block(this->location());
4274 Location end_loc = this->block();
4275 Block* then_block = this->gogo_->finish_block(end_loc);
4277 // Check for the easy error of a newline before "else".
4278 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4280 Location semi_loc = this->location();
4281 if (this->advance_token()->is_keyword(KEYWORD_ELSE))
4282 error_at(this->location(),
4283 "unexpected semicolon or newline before %<else%>");
4284 else
4285 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4286 semi_loc));
4289 Block* else_block = NULL;
4290 if (this->peek_token()->is_keyword(KEYWORD_ELSE))
4292 this->gogo_->start_block(this->location());
4293 const Token* token = this->advance_token();
4294 if (token->is_keyword(KEYWORD_IF))
4295 this->if_stat();
4296 else if (token->is_op(OPERATOR_LCURLY))
4297 this->block();
4298 else
4300 error_at(this->location(), "expected %<if%> or %<{%>");
4301 this->statement(NULL);
4303 else_block = this->gogo_->finish_block(this->location());
4306 this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
4307 else_block,
4308 location));
4310 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4311 location);
4314 // SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4315 // ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
4316 // "{" { ExprCaseClause } "}" .
4317 // TypeSwitchStmt = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
4318 // "{" { TypeCaseClause } "}" .
4319 // TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
4321 void
4322 Parse::switch_stat(Label* label)
4324 go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
4325 Location location = this->location();
4326 this->advance_token();
4328 this->gogo_->start_block(location);
4330 bool saw_simple_stat = false;
4331 Expression* switch_val = NULL;
4332 bool saw_send_stmt;
4333 Type_switch type_switch;
4334 bool have_type_switch_block = false;
4335 if (this->simple_stat_may_start_here())
4337 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4338 &type_switch);
4339 saw_simple_stat = true;
4341 if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4343 // The SimpleStat is an expression statement.
4344 this->expression_stat(switch_val);
4345 switch_val = NULL;
4347 if (switch_val == NULL && !type_switch.found)
4349 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4350 this->advance_token();
4351 else if (saw_simple_stat)
4353 if (saw_send_stmt)
4354 error_at(this->location(),
4355 ("send statement used as value; "
4356 "use select for non-blocking send"));
4357 else
4358 error_at(this->location(),
4359 "expected %<;%> after statement in switch expression");
4361 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4363 if (this->peek_token()->is_identifier())
4365 const Token* token = this->peek_token();
4366 std::string identifier = token->identifier();
4367 bool is_exported = token->is_identifier_exported();
4368 Location id_loc = token->location();
4370 token = this->advance_token();
4371 bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
4372 this->unget_token(Token::make_identifier_token(identifier,
4373 is_exported,
4374 id_loc));
4375 if (is_coloneq)
4377 // This must be a TypeSwitchGuard. It is in a
4378 // different block from any initial SimpleStat.
4379 if (saw_simple_stat)
4381 this->gogo_->start_block(id_loc);
4382 have_type_switch_block = true;
4385 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4386 &type_switch);
4387 if (!type_switch.found)
4389 if (switch_val == NULL
4390 || !switch_val->is_error_expression())
4392 error_at(id_loc, "expected type switch assignment");
4393 switch_val = Expression::make_error(id_loc);
4398 if (switch_val == NULL && !type_switch.found)
4400 switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
4401 &type_switch.found, NULL);
4402 if (type_switch.found)
4404 type_switch.name.clear();
4405 type_switch.expr = switch_val;
4406 type_switch.location = switch_val->location();
4412 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4414 Location token_loc = this->location();
4415 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
4416 && this->advance_token()->is_op(OPERATOR_LCURLY))
4417 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4418 else if (this->peek_token()->is_op(OPERATOR_COLONEQ))
4420 error_at(token_loc, "invalid variable name");
4421 this->advance_token();
4422 this->expression(PRECEDENCE_NORMAL, false, false,
4423 &type_switch.found, NULL);
4424 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4425 this->advance_token();
4426 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4428 if (have_type_switch_block)
4429 this->gogo_->add_block(this->gogo_->finish_block(location),
4430 location);
4431 this->gogo_->add_block(this->gogo_->finish_block(location),
4432 location);
4433 return;
4435 if (type_switch.found)
4436 type_switch.expr = Expression::make_error(location);
4438 else
4440 error_at(this->location(), "expected %<{%>");
4441 if (have_type_switch_block)
4442 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4443 location);
4444 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4445 location);
4446 return;
4449 this->advance_token();
4451 Statement* statement;
4452 if (type_switch.found)
4453 statement = this->type_switch_body(label, type_switch, location);
4454 else
4455 statement = this->expr_switch_body(label, switch_val, location);
4457 if (statement != NULL)
4458 this->gogo_->add_statement(statement);
4460 if (have_type_switch_block)
4461 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4462 location);
4464 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4465 location);
4468 // The body of an expression switch.
4469 // "{" { ExprCaseClause } "}"
4471 Statement*
4472 Parse::expr_switch_body(Label* label, Expression* switch_val,
4473 Location location)
4475 Switch_statement* statement = Statement::make_switch_statement(switch_val,
4476 location);
4478 this->push_break_statement(statement, label);
4480 Case_clauses* case_clauses = new Case_clauses();
4481 bool saw_default = false;
4482 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4484 if (this->peek_token()->is_eof())
4486 if (!saw_errors())
4487 error_at(this->location(), "missing %<}%>");
4488 return NULL;
4490 this->expr_case_clause(case_clauses, &saw_default);
4492 this->advance_token();
4494 statement->add_clauses(case_clauses);
4496 this->pop_break_statement();
4498 return statement;
4501 // ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
4502 // FallthroughStat = "fallthrough" .
4504 void
4505 Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
4507 Location location = this->location();
4509 bool is_default = false;
4510 Expression_list* vals = this->expr_switch_case(&is_default);
4512 if (!this->peek_token()->is_op(OPERATOR_COLON))
4514 if (!saw_errors())
4515 error_at(this->location(), "expected %<:%>");
4516 return;
4518 else
4519 this->advance_token();
4521 Block* statements = NULL;
4522 if (this->statement_list_may_start_here())
4524 this->gogo_->start_block(this->location());
4525 this->statement_list();
4526 statements = this->gogo_->finish_block(this->location());
4529 bool is_fallthrough = false;
4530 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4532 Location fallthrough_loc = this->location();
4533 is_fallthrough = true;
4534 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4535 this->advance_token();
4536 if (this->peek_token()->is_op(OPERATOR_RCURLY))
4537 error_at(fallthrough_loc, _("cannot fallthrough final case in switch"));
4540 if (is_default)
4542 if (*saw_default)
4544 error_at(location, "multiple defaults in switch");
4545 return;
4547 *saw_default = true;
4550 if (is_default || vals != NULL)
4551 clauses->add(vals, is_default, statements, is_fallthrough, location);
4554 // ExprSwitchCase = "case" ExpressionList | "default" .
4556 Expression_list*
4557 Parse::expr_switch_case(bool* is_default)
4559 const Token* token = this->peek_token();
4560 if (token->is_keyword(KEYWORD_CASE))
4562 this->advance_token();
4563 return this->expression_list(NULL, false, true);
4565 else if (token->is_keyword(KEYWORD_DEFAULT))
4567 this->advance_token();
4568 *is_default = true;
4569 return NULL;
4571 else
4573 if (!saw_errors())
4574 error_at(this->location(), "expected %<case%> or %<default%>");
4575 if (!token->is_op(OPERATOR_RCURLY))
4576 this->advance_token();
4577 return NULL;
4581 // The body of a type switch.
4582 // "{" { TypeCaseClause } "}" .
4584 Statement*
4585 Parse::type_switch_body(Label* label, const Type_switch& type_switch,
4586 Location location)
4588 Named_object* switch_no = NULL;
4589 if (!type_switch.name.empty())
4591 if (Gogo::is_sink_name(type_switch.name))
4592 error_at(type_switch.location,
4593 "no new variables on left side of %<:=%>");
4594 else
4596 Variable* switch_var = new Variable(NULL, type_switch.expr, false,
4597 false, false,
4598 type_switch.location);
4599 switch_no = this->gogo_->add_variable(type_switch.name, switch_var);
4603 Type_switch_statement* statement =
4604 Statement::make_type_switch_statement(switch_no,
4605 (switch_no == NULL
4606 ? type_switch.expr
4607 : NULL),
4608 location);
4610 this->push_break_statement(statement, label);
4612 Type_case_clauses* case_clauses = new Type_case_clauses();
4613 bool saw_default = false;
4614 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4616 if (this->peek_token()->is_eof())
4618 error_at(this->location(), "missing %<}%>");
4619 return NULL;
4621 this->type_case_clause(switch_no, case_clauses, &saw_default);
4623 this->advance_token();
4625 statement->add_clauses(case_clauses);
4627 this->pop_break_statement();
4629 return statement;
4632 // TypeCaseClause = TypeSwitchCase ":" [ StatementList ] .
4634 void
4635 Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses,
4636 bool* saw_default)
4638 Location location = this->location();
4640 std::vector<Type*> types;
4641 bool is_default = false;
4642 this->type_switch_case(&types, &is_default);
4644 if (!this->peek_token()->is_op(OPERATOR_COLON))
4645 error_at(this->location(), "expected %<:%>");
4646 else
4647 this->advance_token();
4649 Block* statements = NULL;
4650 if (this->statement_list_may_start_here())
4652 this->gogo_->start_block(this->location());
4653 if (switch_no != NULL && types.size() == 1)
4655 Type* type = types.front();
4656 Expression* init = Expression::make_var_reference(switch_no,
4657 location);
4658 init = Expression::make_type_guard(init, type, location);
4659 Variable* v = new Variable(type, init, false, false, false,
4660 location);
4661 v->set_is_type_switch_var();
4662 Named_object* no = this->gogo_->add_variable(switch_no->name(), v);
4664 // We don't want to issue an error if the compiler
4665 // introduced special variable is not used. Instead we want
4666 // to issue an error if the variable defined by the switch
4667 // is not used. That is handled via type_switch_vars_ and
4668 // Parse::mark_var_used.
4669 v->set_is_used();
4670 this->type_switch_vars_[no] = switch_no;
4672 this->statement_list();
4673 statements = this->gogo_->finish_block(this->location());
4676 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4678 error_at(this->location(),
4679 "fallthrough is not permitted in a type switch");
4680 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4681 this->advance_token();
4684 if (is_default)
4686 go_assert(types.empty());
4687 if (*saw_default)
4689 error_at(location, "multiple defaults in type switch");
4690 return;
4692 *saw_default = true;
4693 clauses->add(NULL, false, true, statements, location);
4695 else if (!types.empty())
4697 for (std::vector<Type*>::const_iterator p = types.begin();
4698 p + 1 != types.end();
4699 ++p)
4700 clauses->add(*p, true, false, NULL, location);
4701 clauses->add(types.back(), false, false, statements, location);
4703 else
4704 clauses->add(Type::make_error_type(), false, false, statements, location);
4707 // TypeSwitchCase = "case" type | "default"
4709 // We accept a comma separated list of types.
4711 void
4712 Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
4714 const Token* token = this->peek_token();
4715 if (token->is_keyword(KEYWORD_CASE))
4717 this->advance_token();
4718 while (true)
4720 Type* t = this->type();
4722 if (!t->is_error_type())
4723 types->push_back(t);
4724 else
4726 this->gogo_->mark_locals_used();
4727 token = this->peek_token();
4728 while (!token->is_op(OPERATOR_COLON)
4729 && !token->is_op(OPERATOR_COMMA)
4730 && !token->is_op(OPERATOR_RCURLY)
4731 && !token->is_eof())
4732 token = this->advance_token();
4735 if (!this->peek_token()->is_op(OPERATOR_COMMA))
4736 break;
4737 this->advance_token();
4740 else if (token->is_keyword(KEYWORD_DEFAULT))
4742 this->advance_token();
4743 *is_default = true;
4745 else
4747 error_at(this->location(), "expected %<case%> or %<default%>");
4748 if (!token->is_op(OPERATOR_RCURLY))
4749 this->advance_token();
4753 // SelectStat = "select" "{" { CommClause } "}" .
4755 void
4756 Parse::select_stat(Label* label)
4758 go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
4759 Location location = this->location();
4760 const Token* token = this->advance_token();
4762 if (!token->is_op(OPERATOR_LCURLY))
4764 Location token_loc = token->location();
4765 if (token->is_op(OPERATOR_SEMICOLON)
4766 && this->advance_token()->is_op(OPERATOR_LCURLY))
4767 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4768 else
4770 error_at(this->location(), "expected %<{%>");
4771 return;
4774 this->advance_token();
4776 Select_statement* statement = Statement::make_select_statement(location);
4778 this->push_break_statement(statement, label);
4780 Select_clauses* select_clauses = new Select_clauses();
4781 bool saw_default = false;
4782 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4784 if (this->peek_token()->is_eof())
4786 error_at(this->location(), "expected %<}%>");
4787 return;
4789 this->comm_clause(select_clauses, &saw_default);
4792 this->advance_token();
4794 statement->add_clauses(select_clauses);
4796 this->pop_break_statement();
4798 this->gogo_->add_statement(statement);
4801 // CommClause = CommCase ":" { Statement ";" } .
4803 void
4804 Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
4806 Location location = this->location();
4807 bool is_send = false;
4808 Expression* channel = NULL;
4809 Expression* val = NULL;
4810 Expression* closed = NULL;
4811 std::string varname;
4812 std::string closedname;
4813 bool is_default = false;
4814 bool got_case = this->comm_case(&is_send, &channel, &val, &closed,
4815 &varname, &closedname, &is_default);
4817 if (!is_send
4818 && varname.empty()
4819 && closedname.empty()
4820 && val != NULL
4821 && val->index_expression() != NULL)
4822 val->index_expression()->set_is_lvalue();
4824 if (this->peek_token()->is_op(OPERATOR_COLON))
4825 this->advance_token();
4826 else
4827 error_at(this->location(), "expected colon");
4829 this->gogo_->start_block(this->location());
4831 Named_object* var = NULL;
4832 if (!varname.empty())
4834 // FIXME: LOCATION is slightly wrong here.
4835 Variable* v = new Variable(NULL, channel, false, false, false,
4836 location);
4837 v->set_type_from_chan_element();
4838 var = this->gogo_->add_variable(varname, v);
4841 Named_object* closedvar = NULL;
4842 if (!closedname.empty())
4844 // FIXME: LOCATION is slightly wrong here.
4845 Variable* v = new Variable(Type::lookup_bool_type(), NULL,
4846 false, false, false, location);
4847 closedvar = this->gogo_->add_variable(closedname, v);
4850 this->statement_list();
4852 Block* statements = this->gogo_->finish_block(this->location());
4854 if (is_default)
4856 if (*saw_default)
4858 error_at(location, "multiple defaults in select");
4859 return;
4861 *saw_default = true;
4864 if (got_case)
4865 clauses->add(is_send, channel, val, closed, var, closedvar, is_default,
4866 statements, location);
4867 else if (statements != NULL)
4869 // Add the statements to make sure that any names they define
4870 // are traversed.
4871 this->gogo_->add_block(statements, location);
4875 // CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
4877 bool
4878 Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
4879 Expression** closed, std::string* varname,
4880 std::string* closedname, bool* is_default)
4882 const Token* token = this->peek_token();
4883 if (token->is_keyword(KEYWORD_DEFAULT))
4885 this->advance_token();
4886 *is_default = true;
4888 else if (token->is_keyword(KEYWORD_CASE))
4890 this->advance_token();
4891 if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname,
4892 closedname))
4893 return false;
4895 else
4897 error_at(this->location(), "expected %<case%> or %<default%>");
4898 if (!token->is_op(OPERATOR_RCURLY))
4899 this->advance_token();
4900 return false;
4903 return true;
4906 // RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
4907 // RecvExpr = Expression .
4909 bool
4910 Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val,
4911 Expression** closed, std::string* varname,
4912 std::string* closedname)
4914 const Token* token = this->peek_token();
4915 bool saw_comma = false;
4916 bool closed_is_id = false;
4917 if (token->is_identifier())
4919 Gogo* gogo = this->gogo_;
4920 std::string recv_var = token->identifier();
4921 bool is_rv_exported = token->is_identifier_exported();
4922 Location recv_var_loc = token->location();
4923 token = this->advance_token();
4924 if (token->is_op(OPERATOR_COLONEQ))
4926 // case rv := <-c:
4927 this->advance_token();
4928 Expression* e = this->expression(PRECEDENCE_NORMAL, false, false,
4929 NULL, NULL);
4930 Receive_expression* re = e->receive_expression();
4931 if (re == NULL)
4933 if (!e->is_error_expression())
4934 error_at(this->location(), "expected receive expression");
4935 return false;
4937 if (recv_var == "_")
4939 error_at(recv_var_loc,
4940 "no new variables on left side of %<:=%>");
4941 recv_var = Gogo::erroneous_name();
4943 *is_send = false;
4944 *varname = gogo->pack_hidden_name(recv_var, is_rv_exported);
4945 *channel = re->channel();
4946 return true;
4948 else if (token->is_op(OPERATOR_COMMA))
4950 token = this->advance_token();
4951 if (token->is_identifier())
4953 std::string recv_closed = token->identifier();
4954 bool is_rc_exported = token->is_identifier_exported();
4955 Location recv_closed_loc = token->location();
4956 closed_is_id = true;
4958 token = this->advance_token();
4959 if (token->is_op(OPERATOR_COLONEQ))
4961 // case rv, rc := <-c:
4962 this->advance_token();
4963 Expression* e = this->expression(PRECEDENCE_NORMAL, false,
4964 false, NULL, NULL);
4965 Receive_expression* re = e->receive_expression();
4966 if (re == NULL)
4968 if (!e->is_error_expression())
4969 error_at(this->location(),
4970 "expected receive expression");
4971 return false;
4973 if (recv_var == "_" && recv_closed == "_")
4975 error_at(recv_var_loc,
4976 "no new variables on left side of %<:=%>");
4977 recv_var = Gogo::erroneous_name();
4979 *is_send = false;
4980 if (recv_var != "_")
4981 *varname = gogo->pack_hidden_name(recv_var,
4982 is_rv_exported);
4983 if (recv_closed != "_")
4984 *closedname = gogo->pack_hidden_name(recv_closed,
4985 is_rc_exported);
4986 *channel = re->channel();
4987 return true;
4990 this->unget_token(Token::make_identifier_token(recv_closed,
4991 is_rc_exported,
4992 recv_closed_loc));
4995 *val = this->id_to_expression(gogo->pack_hidden_name(recv_var,
4996 is_rv_exported),
4997 recv_var_loc);
4998 saw_comma = true;
5000 else
5001 this->unget_token(Token::make_identifier_token(recv_var,
5002 is_rv_exported,
5003 recv_var_loc));
5006 // If SAW_COMMA is false, then we are looking at the start of the
5007 // send or receive expression. If SAW_COMMA is true, then *VAL is
5008 // set and we just read a comma.
5010 Expression* e;
5011 if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP))
5012 e = this->expression(PRECEDENCE_NORMAL, true, true, NULL, NULL);
5013 else
5015 // case <-c:
5016 *is_send = false;
5017 this->advance_token();
5018 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5020 // The next token should be ':'. If it is '<-', then we have
5021 // case <-c <- v:
5022 // which is to say, send on a channel received from a channel.
5023 if (!this->peek_token()->is_op(OPERATOR_CHANOP))
5024 return true;
5026 e = Expression::make_receive(*channel, (*channel)->location());
5029 if (this->peek_token()->is_op(OPERATOR_EQ))
5031 if (!this->advance_token()->is_op(OPERATOR_CHANOP))
5033 error_at(this->location(), "missing %<<-%>");
5034 return false;
5036 *is_send = false;
5037 this->advance_token();
5038 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5039 if (saw_comma)
5041 // case v, e = <-c:
5042 // *VAL is already set.
5043 if (!e->is_sink_expression())
5044 *closed = e;
5046 else
5048 // case v = <-c:
5049 if (!e->is_sink_expression())
5050 *val = e;
5052 return true;
5055 if (saw_comma)
5057 if (closed_is_id)
5058 error_at(this->location(), "expected %<=%> or %<:=%>");
5059 else
5060 error_at(this->location(), "expected %<=%>");
5061 return false;
5064 if (this->peek_token()->is_op(OPERATOR_CHANOP))
5066 // case c <- v:
5067 *is_send = true;
5068 *channel = this->verify_not_sink(e);
5069 this->advance_token();
5070 *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5071 return true;
5074 error_at(this->location(), "expected %<<-%> or %<=%>");
5075 return false;
5078 // ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
5079 // Condition = Expression .
5081 void
5082 Parse::for_stat(Label* label)
5084 go_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
5085 Location location = this->location();
5086 const Token* token = this->advance_token();
5088 // Open a block to hold any variables defined in the init statement
5089 // of the for statement.
5090 this->gogo_->start_block(location);
5092 Block* init = NULL;
5093 Expression* cond = NULL;
5094 Block* post = NULL;
5095 Range_clause range_clause;
5097 if (!token->is_op(OPERATOR_LCURLY))
5099 if (token->is_keyword(KEYWORD_VAR))
5101 error_at(this->location(),
5102 "var declaration not allowed in for initializer");
5103 this->var_decl();
5106 if (token->is_op(OPERATOR_SEMICOLON))
5107 this->for_clause(&cond, &post);
5108 else
5110 // We might be looking at a Condition, an InitStat, or a
5111 // RangeClause.
5112 bool saw_send_stmt;
5113 cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL);
5114 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5116 if (cond == NULL && !range_clause.found)
5118 if (saw_send_stmt)
5119 error_at(this->location(),
5120 ("send statement used as value; "
5121 "use select for non-blocking send"));
5122 else
5123 error_at(this->location(), "parse error in for statement");
5126 else
5128 if (range_clause.found)
5129 error_at(this->location(), "parse error after range clause");
5131 if (cond != NULL)
5133 // COND is actually an expression statement for
5134 // InitStat at the start of a ForClause.
5135 this->expression_stat(cond);
5136 cond = NULL;
5139 this->for_clause(&cond, &post);
5144 // Build the For_statement and note that it is the current target
5145 // for break and continue statements.
5147 For_statement* sfor;
5148 For_range_statement* srange;
5149 Statement* s;
5150 if (!range_clause.found)
5152 sfor = Statement::make_for_statement(init, cond, post, location);
5153 s = sfor;
5154 srange = NULL;
5156 else
5158 srange = Statement::make_for_range_statement(range_clause.index,
5159 range_clause.value,
5160 range_clause.range,
5161 location);
5162 s = srange;
5163 sfor = NULL;
5166 this->push_break_statement(s, label);
5167 this->push_continue_statement(s, label);
5169 // Gather the block of statements in the loop and add them to the
5170 // For_statement.
5172 this->gogo_->start_block(this->location());
5173 Location end_loc = this->block();
5174 Block* statements = this->gogo_->finish_block(end_loc);
5176 if (sfor != NULL)
5177 sfor->add_statements(statements);
5178 else
5179 srange->add_statements(statements);
5181 // This is no longer the break/continue target.
5182 this->pop_break_statement();
5183 this->pop_continue_statement();
5185 // Add the For_statement to the list of statements, and close out
5186 // the block we started to hold any variables defined in the for
5187 // statement.
5189 this->gogo_->add_statement(s);
5191 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
5192 location);
5195 // ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
5196 // InitStat = SimpleStat .
5197 // PostStat = SimpleStat .
5199 // We have already read InitStat at this point.
5201 void
5202 Parse::for_clause(Expression** cond, Block** post)
5204 go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
5205 this->advance_token();
5206 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5207 *cond = NULL;
5208 else if (this->peek_token()->is_op(OPERATOR_LCURLY))
5210 error_at(this->location(),
5211 "unexpected semicolon or newline before %<{%>");
5212 *cond = NULL;
5213 *post = NULL;
5214 return;
5216 else
5217 *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5218 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5219 error_at(this->location(), "expected semicolon");
5220 else
5221 this->advance_token();
5223 if (this->peek_token()->is_op(OPERATOR_LCURLY))
5224 *post = NULL;
5225 else
5227 this->gogo_->start_block(this->location());
5228 this->simple_stat(false, NULL, NULL, NULL);
5229 *post = this->gogo_->finish_block(this->location());
5233 // RangeClause = IdentifierList ( "=" | ":=" ) "range" Expression .
5235 // This is the := version. It is called with a list of identifiers.
5237 void
5238 Parse::range_clause_decl(const Typed_identifier_list* til,
5239 Range_clause* p_range_clause)
5241 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5242 Location location = this->location();
5244 p_range_clause->found = true;
5246 go_assert(til->size() >= 1);
5247 if (til->size() > 2)
5248 error_at(this->location(), "too many variables for range clause");
5250 this->advance_token();
5251 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL,
5252 NULL);
5253 p_range_clause->range = expr;
5255 bool any_new = false;
5257 const Typed_identifier* pti = &til->front();
5258 Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new,
5259 NULL, NULL);
5260 if (any_new && no->is_variable())
5261 no->var_value()->set_type_from_range_index();
5262 p_range_clause->index = Expression::make_var_reference(no, location);
5264 if (til->size() == 1)
5265 p_range_clause->value = NULL;
5266 else
5268 pti = &til->back();
5269 bool is_new = false;
5270 no = this->init_var(*pti, NULL, expr, true, true, &is_new, NULL, NULL);
5271 if (is_new && no->is_variable())
5272 no->var_value()->set_type_from_range_value();
5273 if (is_new)
5274 any_new = true;
5275 if (!Gogo::is_sink_name(pti->name()))
5276 p_range_clause->value = Expression::make_var_reference(no, location);
5279 if (!any_new)
5280 error_at(location, "variables redeclared but no variable is new");
5283 // The = version of RangeClause. This is called with a list of
5284 // expressions.
5286 void
5287 Parse::range_clause_expr(const Expression_list* vals,
5288 Range_clause* p_range_clause)
5290 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5292 p_range_clause->found = true;
5294 go_assert(vals->size() >= 1);
5295 if (vals->size() > 2)
5296 error_at(this->location(), "too many variables for range clause");
5298 this->advance_token();
5299 p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
5300 NULL, NULL);
5302 p_range_clause->index = vals->front();
5303 if (vals->size() == 1)
5304 p_range_clause->value = NULL;
5305 else
5306 p_range_clause->value = vals->back();
5309 // Push a statement on the break stack.
5311 void
5312 Parse::push_break_statement(Statement* enclosing, Label* label)
5314 if (this->break_stack_ == NULL)
5315 this->break_stack_ = new Bc_stack();
5316 this->break_stack_->push_back(std::make_pair(enclosing, label));
5319 // Push a statement on the continue stack.
5321 void
5322 Parse::push_continue_statement(Statement* enclosing, Label* label)
5324 if (this->continue_stack_ == NULL)
5325 this->continue_stack_ = new Bc_stack();
5326 this->continue_stack_->push_back(std::make_pair(enclosing, label));
5329 // Pop the break stack.
5331 void
5332 Parse::pop_break_statement()
5334 this->break_stack_->pop_back();
5337 // Pop the continue stack.
5339 void
5340 Parse::pop_continue_statement()
5342 this->continue_stack_->pop_back();
5345 // Find a break or continue statement given a label name.
5347 Statement*
5348 Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
5350 if (bc_stack == NULL)
5351 return NULL;
5352 for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
5353 p != bc_stack->rend();
5354 ++p)
5356 if (p->second != NULL && p->second->name() == label)
5358 p->second->set_is_used();
5359 return p->first;
5362 return NULL;
5365 // BreakStat = "break" [ identifier ] .
5367 void
5368 Parse::break_stat()
5370 go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
5371 Location location = this->location();
5373 const Token* token = this->advance_token();
5374 Statement* enclosing;
5375 if (!token->is_identifier())
5377 if (this->break_stack_ == NULL || this->break_stack_->empty())
5379 error_at(this->location(),
5380 "break statement not within for or switch or select");
5381 return;
5383 enclosing = this->break_stack_->back().first;
5385 else
5387 enclosing = this->find_bc_statement(this->break_stack_,
5388 token->identifier());
5389 if (enclosing == NULL)
5391 // If there is a label with this name, mark it as used to
5392 // avoid a useless error about an unused label.
5393 this->gogo_->add_label_reference(token->identifier(),
5394 Linemap::unknown_location(), false);
5396 error_at(token->location(), "invalid break label %qs",
5397 Gogo::message_name(token->identifier()).c_str());
5398 this->advance_token();
5399 return;
5401 this->advance_token();
5404 Unnamed_label* label;
5405 if (enclosing->classification() == Statement::STATEMENT_FOR)
5406 label = enclosing->for_statement()->break_label();
5407 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5408 label = enclosing->for_range_statement()->break_label();
5409 else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
5410 label = enclosing->switch_statement()->break_label();
5411 else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
5412 label = enclosing->type_switch_statement()->break_label();
5413 else if (enclosing->classification() == Statement::STATEMENT_SELECT)
5414 label = enclosing->select_statement()->break_label();
5415 else
5416 go_unreachable();
5418 this->gogo_->add_statement(Statement::make_break_statement(label,
5419 location));
5422 // ContinueStat = "continue" [ identifier ] .
5424 void
5425 Parse::continue_stat()
5427 go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
5428 Location location = this->location();
5430 const Token* token = this->advance_token();
5431 Statement* enclosing;
5432 if (!token->is_identifier())
5434 if (this->continue_stack_ == NULL || this->continue_stack_->empty())
5436 error_at(this->location(), "continue statement not within for");
5437 return;
5439 enclosing = this->continue_stack_->back().first;
5441 else
5443 enclosing = this->find_bc_statement(this->continue_stack_,
5444 token->identifier());
5445 if (enclosing == NULL)
5447 // If there is a label with this name, mark it as used to
5448 // avoid a useless error about an unused label.
5449 this->gogo_->add_label_reference(token->identifier(),
5450 Linemap::unknown_location(), false);
5452 error_at(token->location(), "invalid continue label %qs",
5453 Gogo::message_name(token->identifier()).c_str());
5454 this->advance_token();
5455 return;
5457 this->advance_token();
5460 Unnamed_label* label;
5461 if (enclosing->classification() == Statement::STATEMENT_FOR)
5462 label = enclosing->for_statement()->continue_label();
5463 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5464 label = enclosing->for_range_statement()->continue_label();
5465 else
5466 go_unreachable();
5468 this->gogo_->add_statement(Statement::make_continue_statement(label,
5469 location));
5472 // GotoStat = "goto" identifier .
5474 void
5475 Parse::goto_stat()
5477 go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
5478 Location location = this->location();
5479 const Token* token = this->advance_token();
5480 if (!token->is_identifier())
5481 error_at(this->location(), "expected label for goto");
5482 else
5484 Label* label = this->gogo_->add_label_reference(token->identifier(),
5485 location, true);
5486 Statement* s = Statement::make_goto_statement(label, location);
5487 this->gogo_->add_statement(s);
5488 this->advance_token();
5492 // PackageClause = "package" PackageName .
5494 void
5495 Parse::package_clause()
5497 const Token* token = this->peek_token();
5498 Location location = token->location();
5499 std::string name;
5500 if (!token->is_keyword(KEYWORD_PACKAGE))
5502 error_at(this->location(), "program must start with package clause");
5503 name = "ERROR";
5505 else
5507 token = this->advance_token();
5508 if (token->is_identifier())
5510 name = token->identifier();
5511 if (name == "_")
5513 error_at(this->location(), "invalid package name _");
5514 name = Gogo::erroneous_name();
5516 this->advance_token();
5518 else
5520 error_at(this->location(), "package name must be an identifier");
5521 name = "ERROR";
5524 this->gogo_->set_package_name(name, location);
5527 // ImportDecl = "import" Decl<ImportSpec> .
5529 void
5530 Parse::import_decl()
5532 go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
5533 this->advance_token();
5534 this->decl(&Parse::import_spec, NULL);
5537 // ImportSpec = [ "." | PackageName ] PackageFileName .
5539 void
5540 Parse::import_spec(void*)
5542 const Token* token = this->peek_token();
5543 Location location = token->location();
5545 std::string local_name;
5546 bool is_local_name_exported = false;
5547 if (token->is_op(OPERATOR_DOT))
5549 local_name = ".";
5550 token = this->advance_token();
5552 else if (token->is_identifier())
5554 local_name = token->identifier();
5555 is_local_name_exported = token->is_identifier_exported();
5556 token = this->advance_token();
5559 if (!token->is_string())
5561 error_at(this->location(), "import statement not a string");
5562 this->advance_token();
5563 return;
5566 this->gogo_->import_package(token->string_value(), local_name,
5567 is_local_name_exported, location);
5569 this->advance_token();
5572 // SourceFile = PackageClause ";" { ImportDecl ";" }
5573 // { TopLevelDecl ";" } .
5575 void
5576 Parse::program()
5578 this->package_clause();
5580 const Token* token = this->peek_token();
5581 if (token->is_op(OPERATOR_SEMICOLON))
5582 token = this->advance_token();
5583 else
5584 error_at(this->location(),
5585 "expected %<;%> or newline after package clause");
5587 while (token->is_keyword(KEYWORD_IMPORT))
5589 this->import_decl();
5590 token = this->peek_token();
5591 if (token->is_op(OPERATOR_SEMICOLON))
5592 token = this->advance_token();
5593 else
5594 error_at(this->location(),
5595 "expected %<;%> or newline after import declaration");
5598 while (!token->is_eof())
5600 if (this->declaration_may_start_here())
5601 this->declaration();
5602 else
5604 error_at(this->location(), "expected declaration");
5605 this->gogo_->mark_locals_used();
5607 this->advance_token();
5608 while (!this->peek_token()->is_eof()
5609 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
5610 && !this->peek_token()->is_op(OPERATOR_RCURLY));
5611 if (!this->peek_token()->is_eof()
5612 && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
5613 this->advance_token();
5615 token = this->peek_token();
5616 if (token->is_op(OPERATOR_SEMICOLON))
5617 token = this->advance_token();
5618 else if (!token->is_eof() || !saw_errors())
5620 if (token->is_op(OPERATOR_CHANOP))
5621 error_at(this->location(),
5622 ("send statement used as value; "
5623 "use select for non-blocking send"));
5624 else
5625 error_at(this->location(),
5626 "expected %<;%> or newline after top level declaration");
5627 this->skip_past_error(OPERATOR_INVALID);
5632 // Reset the current iota value.
5634 void
5635 Parse::reset_iota()
5637 this->iota_ = 0;
5640 // Return the current iota value.
5643 Parse::iota_value()
5645 return this->iota_;
5648 // Increment the current iota value.
5650 void
5651 Parse::increment_iota()
5653 ++this->iota_;
5656 // Skip forward to a semicolon or OP. OP will normally be
5657 // OPERATOR_RPAREN or OPERATOR_RCURLY. If we find a semicolon, move
5658 // past it and return. If we find OP, it will be the next token to
5659 // read. Return true if we are OK, false if we found EOF.
5661 bool
5662 Parse::skip_past_error(Operator op)
5664 this->gogo_->mark_locals_used();
5665 const Token* token = this->peek_token();
5666 while (!token->is_op(op))
5668 if (token->is_eof())
5669 return false;
5670 if (token->is_op(OPERATOR_SEMICOLON))
5672 this->advance_token();
5673 return true;
5675 token = this->advance_token();
5677 return true;
5680 // Check that an expression is not a sink.
5682 Expression*
5683 Parse::verify_not_sink(Expression* expr)
5685 if (expr->is_sink_expression())
5687 error_at(expr->location(), "cannot use _ as value");
5688 expr = Expression::make_error(expr->location());
5690 return expr;
5693 // Mark a variable as used.
5695 void
5696 Parse::mark_var_used(Named_object* no)
5698 if (no->is_variable())
5700 no->var_value()->set_is_used();
5702 // When a type switch uses := to define a variable, then for
5703 // each case with a single type we introduce a new variable with
5704 // the appropriate type. When we do, if the newly introduced
5705 // variable is used, then the type switch variable is used.
5706 Type_switch_vars::iterator p = this->type_switch_vars_.find(no);
5707 if (p != this->type_switch_vars_.end())
5708 p->second->var_value()->set_is_used();