2012-05-01 François Dumont <fdumont@gcc.gnu.org>
[official-gcc.git] / gcc / go / gofrontend / parse.cc
blob7a567a1cd14065c3cd64b7d3ea16297024b66a43
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_SINK is true, the expressions in the list may be "_".
131 Expression_list*
132 Parse::expression_list(Expression* first, bool may_be_sink)
134 Expression_list* ret = new Expression_list();
135 if (first != NULL)
136 ret->push_back(first);
137 while (true)
139 ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink, true,
140 NULL));
142 const Token* token = this->peek_token();
143 if (!token->is_op(OPERATOR_COMMA))
144 return ret;
146 // Most expression lists permit a trailing comma.
147 Location location = token->location();
148 this->advance_token();
149 if (!this->expression_may_start_here())
151 this->unget_token(Token::make_operator_token(OPERATOR_COMMA,
152 location));
153 return ret;
158 // QualifiedIdent = [ PackageName "." ] identifier .
159 // PackageName = identifier .
161 // This sets *PNAME to the identifier and sets *PPACKAGE to the
162 // package or NULL if there isn't one. This returns true on success,
163 // false on failure in which case it will have emitted an error
164 // message.
166 bool
167 Parse::qualified_ident(std::string* pname, Named_object** ppackage)
169 const Token* token = this->peek_token();
170 if (!token->is_identifier())
172 error_at(this->location(), "expected identifier");
173 return false;
176 std::string name = token->identifier();
177 bool is_exported = token->is_identifier_exported();
178 name = this->gogo_->pack_hidden_name(name, is_exported);
180 token = this->advance_token();
181 if (!token->is_op(OPERATOR_DOT))
183 *pname = name;
184 *ppackage = NULL;
185 return true;
188 Named_object* package = this->gogo_->lookup(name, NULL);
189 if (package == NULL || !package->is_package())
191 error_at(this->location(), "expected package");
192 // We expect . IDENTIFIER; skip both.
193 if (this->advance_token()->is_identifier())
194 this->advance_token();
195 return false;
198 package->package_value()->set_used();
200 token = this->advance_token();
201 if (!token->is_identifier())
203 error_at(this->location(), "expected identifier");
204 return false;
207 name = token->identifier();
209 if (name == "_")
211 error_at(this->location(), "invalid use of %<_%>");
212 name = "blank";
215 if (package->name() == this->gogo_->package_name())
216 name = this->gogo_->pack_hidden_name(name,
217 token->is_identifier_exported());
219 *pname = name;
220 *ppackage = package;
222 this->advance_token();
224 return true;
227 // Type = TypeName | TypeLit | "(" Type ")" .
228 // TypeLit =
229 // ArrayType | StructType | PointerType | FunctionType | InterfaceType |
230 // SliceType | MapType | ChannelType .
232 Type*
233 Parse::type()
235 const Token* token = this->peek_token();
236 if (token->is_identifier())
237 return this->type_name(true);
238 else if (token->is_op(OPERATOR_LSQUARE))
239 return this->array_type(false);
240 else if (token->is_keyword(KEYWORD_CHAN)
241 || token->is_op(OPERATOR_CHANOP))
242 return this->channel_type();
243 else if (token->is_keyword(KEYWORD_INTERFACE))
244 return this->interface_type();
245 else if (token->is_keyword(KEYWORD_FUNC))
247 Location location = token->location();
248 this->advance_token();
249 Type* type = this->signature(NULL, location);
250 if (type == NULL)
251 return Type::make_error_type();
252 return type;
254 else if (token->is_keyword(KEYWORD_MAP))
255 return this->map_type();
256 else if (token->is_keyword(KEYWORD_STRUCT))
257 return this->struct_type();
258 else if (token->is_op(OPERATOR_MULT))
259 return this->pointer_type();
260 else if (token->is_op(OPERATOR_LPAREN))
262 this->advance_token();
263 Type* ret = this->type();
264 if (this->peek_token()->is_op(OPERATOR_RPAREN))
265 this->advance_token();
266 else
268 if (!ret->is_error_type())
269 error_at(this->location(), "expected %<)%>");
271 return ret;
273 else
275 error_at(token->location(), "expected type");
276 return Type::make_error_type();
280 bool
281 Parse::type_may_start_here()
283 const Token* token = this->peek_token();
284 return (token->is_identifier()
285 || token->is_op(OPERATOR_LSQUARE)
286 || token->is_op(OPERATOR_CHANOP)
287 || token->is_keyword(KEYWORD_CHAN)
288 || token->is_keyword(KEYWORD_INTERFACE)
289 || token->is_keyword(KEYWORD_FUNC)
290 || token->is_keyword(KEYWORD_MAP)
291 || token->is_keyword(KEYWORD_STRUCT)
292 || token->is_op(OPERATOR_MULT)
293 || token->is_op(OPERATOR_LPAREN));
296 // TypeName = QualifiedIdent .
298 // If MAY_BE_NIL is true, then an identifier with the value of the
299 // predefined constant nil is accepted, returning the nil type.
301 Type*
302 Parse::type_name(bool issue_error)
304 Location location = this->location();
306 std::string name;
307 Named_object* package;
308 if (!this->qualified_ident(&name, &package))
309 return Type::make_error_type();
311 Named_object* named_object;
312 if (package == NULL)
313 named_object = this->gogo_->lookup(name, NULL);
314 else
316 named_object = package->package_value()->lookup(name);
317 if (named_object == NULL
318 && issue_error
319 && package->name() != this->gogo_->package_name())
321 // Check whether the name is there but hidden.
322 std::string s = ('.' + package->package_value()->unique_prefix()
323 + '.' + package->package_value()->name()
324 + '.' + name);
325 named_object = package->package_value()->lookup(s);
326 if (named_object != NULL)
328 const std::string& packname(package->package_value()->name());
329 error_at(location, "invalid reference to hidden type %<%s.%s%>",
330 Gogo::message_name(packname).c_str(),
331 Gogo::message_name(name).c_str());
332 issue_error = false;
337 bool ok = true;
338 if (named_object == NULL)
340 if (package == NULL)
341 named_object = this->gogo_->add_unknown_name(name, location);
342 else
344 const std::string& packname(package->package_value()->name());
345 error_at(location, "reference to undefined identifier %<%s.%s%>",
346 Gogo::message_name(packname).c_str(),
347 Gogo::message_name(name).c_str());
348 issue_error = false;
349 ok = false;
352 else if (named_object->is_type())
354 if (!named_object->type_value()->is_visible())
355 ok = false;
357 else if (named_object->is_unknown() || named_object->is_type_declaration())
359 else
360 ok = false;
362 if (!ok)
364 if (issue_error)
365 error_at(location, "expected type");
366 return Type::make_error_type();
369 if (named_object->is_type())
370 return named_object->type_value();
371 else if (named_object->is_unknown() || named_object->is_type_declaration())
372 return Type::make_forward_declaration(named_object);
373 else
374 go_unreachable();
377 // ArrayType = "[" [ ArrayLength ] "]" ElementType .
378 // ArrayLength = Expression .
379 // ElementType = CompleteType .
381 Type*
382 Parse::array_type(bool may_use_ellipsis)
384 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
385 const Token* token = this->advance_token();
387 Expression* length = NULL;
388 if (token->is_op(OPERATOR_RSQUARE))
389 this->advance_token();
390 else
392 if (!token->is_op(OPERATOR_ELLIPSIS))
393 length = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
394 else if (may_use_ellipsis)
396 // An ellipsis is used in composite literals to represent a
397 // fixed array of the size of the number of elements. We
398 // use a length of nil to represent this, and change the
399 // length when parsing the composite literal.
400 length = Expression::make_nil(this->location());
401 this->advance_token();
403 else
405 error_at(this->location(),
406 "use of %<[...]%> outside of array literal");
407 length = Expression::make_error(this->location());
408 this->advance_token();
410 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
412 error_at(this->location(), "expected %<]%>");
413 return Type::make_error_type();
415 this->advance_token();
418 Type* element_type = this->type();
420 return Type::make_array_type(element_type, length);
423 // MapType = "map" "[" KeyType "]" ValueType .
424 // KeyType = CompleteType .
425 // ValueType = CompleteType .
427 Type*
428 Parse::map_type()
430 Location location = this->location();
431 go_assert(this->peek_token()->is_keyword(KEYWORD_MAP));
432 if (!this->advance_token()->is_op(OPERATOR_LSQUARE))
434 error_at(this->location(), "expected %<[%>");
435 return Type::make_error_type();
437 this->advance_token();
439 Type* key_type = this->type();
441 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
443 error_at(this->location(), "expected %<]%>");
444 return Type::make_error_type();
446 this->advance_token();
448 Type* value_type = this->type();
450 if (key_type->is_error_type() || value_type->is_error_type())
451 return Type::make_error_type();
453 return Type::make_map_type(key_type, value_type, location);
456 // StructType = "struct" "{" { FieldDecl ";" } "}" .
458 Type*
459 Parse::struct_type()
461 go_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT));
462 Location location = this->location();
463 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
465 Location token_loc = this->location();
466 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
467 && this->advance_token()->is_op(OPERATOR_LCURLY))
468 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
469 else
471 error_at(this->location(), "expected %<{%>");
472 return Type::make_error_type();
475 this->advance_token();
477 Struct_field_list* sfl = new Struct_field_list;
478 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
480 this->field_decl(sfl);
481 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
482 this->advance_token();
483 else if (!this->peek_token()->is_op(OPERATOR_RCURLY))
485 error_at(this->location(), "expected %<;%> or %<}%> or newline");
486 if (!this->skip_past_error(OPERATOR_RCURLY))
487 return Type::make_error_type();
490 this->advance_token();
492 for (Struct_field_list::const_iterator pi = sfl->begin();
493 pi != sfl->end();
494 ++pi)
496 if (pi->type()->is_error_type())
497 return pi->type();
498 for (Struct_field_list::const_iterator pj = pi + 1;
499 pj != sfl->end();
500 ++pj)
502 if (pi->field_name() == pj->field_name()
503 && !Gogo::is_sink_name(pi->field_name()))
504 error_at(pi->location(), "duplicate field name %<%s%>",
505 Gogo::message_name(pi->field_name()).c_str());
509 return Type::make_struct_type(sfl, location);
512 // FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] .
513 // Tag = string_lit .
515 void
516 Parse::field_decl(Struct_field_list* sfl)
518 const Token* token = this->peek_token();
519 Location location = token->location();
520 bool is_anonymous;
521 bool is_anonymous_pointer;
522 if (token->is_op(OPERATOR_MULT))
524 is_anonymous = true;
525 is_anonymous_pointer = true;
527 else if (token->is_identifier())
529 std::string id = token->identifier();
530 bool is_id_exported = token->is_identifier_exported();
531 Location id_location = token->location();
532 token = this->advance_token();
533 is_anonymous = (token->is_op(OPERATOR_SEMICOLON)
534 || token->is_op(OPERATOR_RCURLY)
535 || token->is_op(OPERATOR_DOT)
536 || token->is_string());
537 is_anonymous_pointer = false;
538 this->unget_token(Token::make_identifier_token(id, is_id_exported,
539 id_location));
541 else
543 error_at(this->location(), "expected field name");
544 this->gogo_->mark_locals_used();
545 while (!token->is_op(OPERATOR_SEMICOLON)
546 && !token->is_op(OPERATOR_RCURLY)
547 && !token->is_eof())
548 token = this->advance_token();
549 return;
552 if (is_anonymous)
554 if (is_anonymous_pointer)
556 this->advance_token();
557 if (!this->peek_token()->is_identifier())
559 error_at(this->location(), "expected field name");
560 this->gogo_->mark_locals_used();
561 while (!token->is_op(OPERATOR_SEMICOLON)
562 && !token->is_op(OPERATOR_RCURLY)
563 && !token->is_eof())
564 token = this->advance_token();
565 return;
568 Type* type = this->type_name(true);
570 std::string tag;
571 if (this->peek_token()->is_string())
573 tag = this->peek_token()->string_value();
574 this->advance_token();
577 if (!type->is_error_type())
579 if (is_anonymous_pointer)
580 type = Type::make_pointer_type(type);
581 sfl->push_back(Struct_field(Typed_identifier("", type, location)));
582 if (!tag.empty())
583 sfl->back().set_tag(tag);
586 else
588 Typed_identifier_list til;
589 while (true)
591 token = this->peek_token();
592 if (!token->is_identifier())
594 error_at(this->location(), "expected identifier");
595 return;
597 std::string name =
598 this->gogo_->pack_hidden_name(token->identifier(),
599 token->is_identifier_exported());
600 til.push_back(Typed_identifier(name, NULL, token->location()));
601 if (!this->advance_token()->is_op(OPERATOR_COMMA))
602 break;
603 this->advance_token();
606 Type* type = this->type();
608 std::string tag;
609 if (this->peek_token()->is_string())
611 tag = this->peek_token()->string_value();
612 this->advance_token();
615 for (Typed_identifier_list::iterator p = til.begin();
616 p != til.end();
617 ++p)
619 p->set_type(type);
620 sfl->push_back(Struct_field(*p));
621 if (!tag.empty())
622 sfl->back().set_tag(tag);
627 // PointerType = "*" Type .
629 Type*
630 Parse::pointer_type()
632 go_assert(this->peek_token()->is_op(OPERATOR_MULT));
633 this->advance_token();
634 Type* type = this->type();
635 if (type->is_error_type())
636 return type;
637 return Type::make_pointer_type(type);
640 // ChannelType = Channel | SendChannel | RecvChannel .
641 // Channel = "chan" ElementType .
642 // SendChannel = "chan" "<-" ElementType .
643 // RecvChannel = "<-" "chan" ElementType .
645 Type*
646 Parse::channel_type()
648 const Token* token = this->peek_token();
649 bool send = true;
650 bool receive = true;
651 if (token->is_op(OPERATOR_CHANOP))
653 if (!this->advance_token()->is_keyword(KEYWORD_CHAN))
655 error_at(this->location(), "expected %<chan%>");
656 return Type::make_error_type();
658 send = false;
659 this->advance_token();
661 else
663 go_assert(token->is_keyword(KEYWORD_CHAN));
664 if (this->advance_token()->is_op(OPERATOR_CHANOP))
666 receive = false;
667 this->advance_token();
671 // Better error messages for the common error of omitting the
672 // channel element type.
673 if (!this->type_may_start_here())
675 token = this->peek_token();
676 if (token->is_op(OPERATOR_RCURLY))
677 error_at(this->location(), "unexpected %<}%> in channel type");
678 else if (token->is_op(OPERATOR_RPAREN))
679 error_at(this->location(), "unexpected %<)%> in channel type");
680 else if (token->is_op(OPERATOR_COMMA))
681 error_at(this->location(), "unexpected comma in channel type");
682 else
683 error_at(this->location(), "expected channel element type");
684 return Type::make_error_type();
687 Type* element_type = this->type();
688 return Type::make_channel_type(send, receive, element_type);
691 // Give an error for a duplicate parameter or receiver name.
693 void
694 Parse::check_signature_names(const Typed_identifier_list* params,
695 Parse::Names* names)
697 for (Typed_identifier_list::const_iterator p = params->begin();
698 p != params->end();
699 ++p)
701 if (p->name().empty() || Gogo::is_sink_name(p->name()))
702 continue;
703 std::pair<std::string, const Typed_identifier*> val =
704 std::make_pair(p->name(), &*p);
705 std::pair<Parse::Names::iterator, bool> ins = names->insert(val);
706 if (!ins.second)
708 error_at(p->location(), "redefinition of %qs",
709 Gogo::message_name(p->name()).c_str());
710 inform(ins.first->second->location(),
711 "previous definition of %qs was here",
712 Gogo::message_name(p->name()).c_str());
717 // Signature = Parameters [ Result ] .
719 // RECEIVER is the receiver if there is one, or NULL. LOCATION is the
720 // location of the start of the type.
722 // This returns NULL on a parse error.
724 Function_type*
725 Parse::signature(Typed_identifier* receiver, Location location)
727 bool is_varargs = false;
728 Typed_identifier_list* params;
729 bool params_ok = this->parameters(&params, &is_varargs);
731 Typed_identifier_list* results = NULL;
732 if (this->peek_token()->is_op(OPERATOR_LPAREN)
733 || this->type_may_start_here())
735 if (!this->result(&results))
736 return NULL;
739 if (!params_ok)
740 return NULL;
742 Parse::Names names;
743 if (params != NULL)
744 this->check_signature_names(params, &names);
745 if (results != NULL)
746 this->check_signature_names(results, &names);
748 Function_type* ret = Type::make_function_type(receiver, params, results,
749 location);
750 if (is_varargs)
751 ret->set_is_varargs();
752 return ret;
755 // Parameters = "(" [ ParameterList [ "," ] ] ")" .
757 // This returns false on a parse error.
759 bool
760 Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs)
762 *pparams = NULL;
764 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
766 error_at(this->location(), "expected %<(%>");
767 return false;
770 Typed_identifier_list* params = NULL;
771 bool saw_error = false;
773 const Token* token = this->advance_token();
774 if (!token->is_op(OPERATOR_RPAREN))
776 params = this->parameter_list(is_varargs);
777 if (params == NULL)
778 saw_error = true;
779 token = this->peek_token();
782 // The optional trailing comma is picked up in parameter_list.
784 if (!token->is_op(OPERATOR_RPAREN))
785 error_at(this->location(), "expected %<)%>");
786 else
787 this->advance_token();
789 if (saw_error)
790 return false;
792 *pparams = params;
793 return true;
796 // ParameterList = ParameterDecl { "," ParameterDecl } .
798 // This sets *IS_VARARGS if the list ends with an ellipsis.
799 // IS_VARARGS will be NULL if varargs are not permitted.
801 // We pick up an optional trailing comma.
803 // This returns NULL if some error is seen.
805 Typed_identifier_list*
806 Parse::parameter_list(bool* is_varargs)
808 Location location = this->location();
809 Typed_identifier_list* ret = new Typed_identifier_list();
811 bool saw_error = false;
813 // If we see an identifier and then a comma, then we don't know
814 // whether we are looking at a list of identifiers followed by a
815 // type, or a list of types given by name. We have to do an
816 // arbitrary lookahead to figure it out.
818 bool parameters_have_names;
819 const Token* token = this->peek_token();
820 if (!token->is_identifier())
822 // This must be a type which starts with something like '*'.
823 parameters_have_names = false;
825 else
827 std::string name = token->identifier();
828 bool is_exported = token->is_identifier_exported();
829 Location location = token->location();
830 token = this->advance_token();
831 if (!token->is_op(OPERATOR_COMMA))
833 if (token->is_op(OPERATOR_DOT))
835 // This is a qualified identifier, which must turn out
836 // to be a type.
837 parameters_have_names = false;
839 else if (token->is_op(OPERATOR_RPAREN))
841 // A single identifier followed by a parenthesis must be
842 // a type name.
843 parameters_have_names = false;
845 else
847 // An identifier followed by something other than a
848 // comma or a dot or a right parenthesis must be a
849 // parameter name followed by a type.
850 parameters_have_names = true;
853 this->unget_token(Token::make_identifier_token(name, is_exported,
854 location));
856 else
858 // An identifier followed by a comma may be the first in a
859 // list of parameter names followed by a type, or it may be
860 // the first in a list of types without parameter names. To
861 // find out we gather as many identifiers separated by
862 // commas as we can.
863 std::string id_name = this->gogo_->pack_hidden_name(name,
864 is_exported);
865 ret->push_back(Typed_identifier(id_name, NULL, location));
866 bool just_saw_comma = true;
867 while (this->advance_token()->is_identifier())
869 name = this->peek_token()->identifier();
870 is_exported = this->peek_token()->is_identifier_exported();
871 location = this->peek_token()->location();
872 id_name = this->gogo_->pack_hidden_name(name, is_exported);
873 ret->push_back(Typed_identifier(id_name, NULL, location));
874 if (!this->advance_token()->is_op(OPERATOR_COMMA))
876 just_saw_comma = false;
877 break;
881 if (just_saw_comma)
883 // We saw ID1 "," ID2 "," followed by something which
884 // was not an identifier. We must be seeing the start
885 // of a type, and ID1 and ID2 must be types, and the
886 // parameters don't have names.
887 parameters_have_names = false;
889 else if (this->peek_token()->is_op(OPERATOR_RPAREN))
891 // We saw ID1 "," ID2 ")". ID1 and ID2 must be types,
892 // and the parameters don't have names.
893 parameters_have_names = false;
895 else if (this->peek_token()->is_op(OPERATOR_DOT))
897 // We saw ID1 "," ID2 ".". ID2 must be a package name,
898 // ID1 must be a type, and the parameters don't have
899 // names.
900 parameters_have_names = false;
901 this->unget_token(Token::make_identifier_token(name, is_exported,
902 location));
903 ret->pop_back();
904 just_saw_comma = true;
906 else
908 // We saw ID1 "," ID2 followed by something other than
909 // ",", ".", or ")". We must be looking at the start of
910 // a type, and ID1 and ID2 must be parameter names.
911 parameters_have_names = true;
914 if (parameters_have_names)
916 go_assert(!just_saw_comma);
917 // We have just seen ID1, ID2 xxx.
918 Type* type;
919 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
920 type = this->type();
921 else
923 error_at(this->location(), "%<...%> only permits one name");
924 saw_error = true;
925 this->advance_token();
926 type = this->type();
928 for (size_t i = 0; i < ret->size(); ++i)
929 ret->set_type(i, type);
930 if (!this->peek_token()->is_op(OPERATOR_COMMA))
931 return saw_error ? NULL : ret;
932 if (this->advance_token()->is_op(OPERATOR_RPAREN))
933 return saw_error ? NULL : ret;
935 else
937 Typed_identifier_list* tret = new Typed_identifier_list();
938 for (Typed_identifier_list::const_iterator p = ret->begin();
939 p != ret->end();
940 ++p)
942 Named_object* no = this->gogo_->lookup(p->name(), NULL);
943 Type* type;
944 if (no == NULL)
945 no = this->gogo_->add_unknown_name(p->name(),
946 p->location());
948 if (no->is_type())
949 type = no->type_value();
950 else if (no->is_unknown() || no->is_type_declaration())
951 type = Type::make_forward_declaration(no);
952 else
954 error_at(p->location(), "expected %<%s%> to be a type",
955 Gogo::message_name(p->name()).c_str());
956 saw_error = true;
957 type = Type::make_error_type();
959 tret->push_back(Typed_identifier("", type, p->location()));
961 delete ret;
962 ret = tret;
963 if (!just_saw_comma
964 || this->peek_token()->is_op(OPERATOR_RPAREN))
965 return saw_error ? NULL : ret;
970 bool mix_error = false;
971 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
972 while (this->peek_token()->is_op(OPERATOR_COMMA))
974 if (is_varargs != NULL && *is_varargs)
976 error_at(this->location(), "%<...%> must be last parameter");
977 saw_error = true;
979 if (this->advance_token()->is_op(OPERATOR_RPAREN))
980 break;
981 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
983 if (mix_error)
985 error_at(location, "invalid named/anonymous mix");
986 saw_error = true;
988 if (saw_error)
990 delete ret;
991 return NULL;
993 return ret;
996 // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
998 void
999 Parse::parameter_decl(bool parameters_have_names,
1000 Typed_identifier_list* til,
1001 bool* is_varargs,
1002 bool* mix_error)
1004 if (!parameters_have_names)
1006 Type* type;
1007 Location location = this->location();
1008 if (!this->peek_token()->is_identifier())
1010 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1011 type = this->type();
1012 else
1014 if (is_varargs == NULL)
1015 error_at(this->location(), "invalid use of %<...%>");
1016 else
1017 *is_varargs = true;
1018 this->advance_token();
1019 if (is_varargs == NULL
1020 && this->peek_token()->is_op(OPERATOR_RPAREN))
1021 type = Type::make_error_type();
1022 else
1024 Type* element_type = this->type();
1025 type = Type::make_array_type(element_type, NULL);
1029 else
1031 type = this->type_name(false);
1032 if (type->is_error_type()
1033 || (!this->peek_token()->is_op(OPERATOR_COMMA)
1034 && !this->peek_token()->is_op(OPERATOR_RPAREN)))
1036 *mix_error = true;
1037 while (!this->peek_token()->is_op(OPERATOR_COMMA)
1038 && !this->peek_token()->is_op(OPERATOR_RPAREN))
1039 this->advance_token();
1042 if (!type->is_error_type())
1043 til->push_back(Typed_identifier("", type, location));
1045 else
1047 size_t orig_count = til->size();
1048 if (this->peek_token()->is_identifier())
1049 this->identifier_list(til);
1050 else
1051 *mix_error = true;
1052 size_t new_count = til->size();
1054 Type* type;
1055 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1056 type = this->type();
1057 else
1059 if (is_varargs == NULL)
1060 error_at(this->location(), "invalid use of %<...%>");
1061 else if (new_count > orig_count + 1)
1062 error_at(this->location(), "%<...%> only permits one name");
1063 else
1064 *is_varargs = true;
1065 this->advance_token();
1066 Type* element_type = this->type();
1067 type = Type::make_array_type(element_type, NULL);
1069 for (size_t i = orig_count; i < new_count; ++i)
1070 til->set_type(i, type);
1074 // Result = Parameters | Type .
1076 // This returns false on a parse error.
1078 bool
1079 Parse::result(Typed_identifier_list** presults)
1081 if (this->peek_token()->is_op(OPERATOR_LPAREN))
1082 return this->parameters(presults, NULL);
1083 else
1085 Location location = this->location();
1086 Type* type = this->type();
1087 if (type->is_error_type())
1089 *presults = NULL;
1090 return false;
1092 Typed_identifier_list* til = new Typed_identifier_list();
1093 til->push_back(Typed_identifier("", type, location));
1094 *presults = til;
1095 return true;
1099 // Block = "{" [ StatementList ] "}" .
1101 // Returns the location of the closing brace.
1103 Location
1104 Parse::block()
1106 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
1108 Location loc = this->location();
1109 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1110 && this->advance_token()->is_op(OPERATOR_LCURLY))
1111 error_at(loc, "unexpected semicolon or newline before %<{%>");
1112 else
1114 error_at(this->location(), "expected %<{%>");
1115 return Linemap::unknown_location();
1119 const Token* token = this->advance_token();
1121 if (!token->is_op(OPERATOR_RCURLY))
1123 this->statement_list();
1124 token = this->peek_token();
1125 if (!token->is_op(OPERATOR_RCURLY))
1127 if (!token->is_eof() || !saw_errors())
1128 error_at(this->location(), "expected %<}%>");
1130 this->gogo_->mark_locals_used();
1132 // Skip ahead to the end of the block, in hopes of avoiding
1133 // lots of meaningless errors.
1134 Location ret = token->location();
1135 int nest = 0;
1136 while (!token->is_eof())
1138 if (token->is_op(OPERATOR_LCURLY))
1139 ++nest;
1140 else if (token->is_op(OPERATOR_RCURLY))
1142 --nest;
1143 if (nest < 0)
1145 this->advance_token();
1146 break;
1149 token = this->advance_token();
1150 ret = token->location();
1152 return ret;
1156 Location ret = token->location();
1157 this->advance_token();
1158 return ret;
1161 // InterfaceType = "interface" "{" [ MethodSpecList ] "}" .
1162 // MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] .
1164 Type*
1165 Parse::interface_type()
1167 go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE));
1168 Location location = this->location();
1170 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
1172 Location token_loc = this->location();
1173 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1174 && this->advance_token()->is_op(OPERATOR_LCURLY))
1175 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
1176 else
1178 error_at(this->location(), "expected %<{%>");
1179 return Type::make_error_type();
1182 this->advance_token();
1184 Typed_identifier_list* methods = new Typed_identifier_list();
1185 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1187 this->method_spec(methods);
1188 while (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1190 if (this->advance_token()->is_op(OPERATOR_RCURLY))
1191 break;
1192 this->method_spec(methods);
1194 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1196 error_at(this->location(), "expected %<}%>");
1197 while (!this->advance_token()->is_op(OPERATOR_RCURLY))
1199 if (this->peek_token()->is_eof())
1200 return Type::make_error_type();
1204 this->advance_token();
1206 if (methods->empty())
1208 delete methods;
1209 methods = NULL;
1212 Interface_type* ret = Type::make_interface_type(methods, location);
1213 this->gogo_->record_interface_type(ret);
1214 return ret;
1217 // MethodSpec = MethodName Signature | InterfaceTypeName .
1218 // MethodName = identifier .
1219 // InterfaceTypeName = TypeName .
1221 void
1222 Parse::method_spec(Typed_identifier_list* methods)
1224 const Token* token = this->peek_token();
1225 if (!token->is_identifier())
1227 error_at(this->location(), "expected identifier");
1228 return;
1231 std::string name = token->identifier();
1232 bool is_exported = token->is_identifier_exported();
1233 Location location = token->location();
1235 if (this->advance_token()->is_op(OPERATOR_LPAREN))
1237 // This is a MethodName.
1238 name = this->gogo_->pack_hidden_name(name, is_exported);
1239 Type* type = this->signature(NULL, location);
1240 if (type == NULL)
1241 return;
1242 methods->push_back(Typed_identifier(name, type, location));
1244 else
1246 this->unget_token(Token::make_identifier_token(name, is_exported,
1247 location));
1248 Type* type = this->type_name(false);
1249 if (type->is_error_type()
1250 || (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1251 && !this->peek_token()->is_op(OPERATOR_RCURLY)))
1253 if (this->peek_token()->is_op(OPERATOR_COMMA))
1254 error_at(this->location(),
1255 "name list not allowed in interface type");
1256 else
1257 error_at(location, "expected signature or type name");
1258 this->gogo_->mark_locals_used();
1259 token = this->peek_token();
1260 while (!token->is_eof()
1261 && !token->is_op(OPERATOR_SEMICOLON)
1262 && !token->is_op(OPERATOR_RCURLY))
1263 token = this->advance_token();
1264 return;
1266 // This must be an interface type, but we can't check that now.
1267 // We check it and pull out the methods in
1268 // Interface_type::do_verify.
1269 methods->push_back(Typed_identifier("", type, location));
1273 // Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1275 void
1276 Parse::declaration()
1278 const Token* token = this->peek_token();
1279 if (token->is_keyword(KEYWORD_CONST))
1280 this->const_decl();
1281 else if (token->is_keyword(KEYWORD_TYPE))
1282 this->type_decl();
1283 else if (token->is_keyword(KEYWORD_VAR))
1284 this->var_decl();
1285 else if (token->is_keyword(KEYWORD_FUNC))
1286 this->function_decl();
1287 else
1289 error_at(this->location(), "expected declaration");
1290 this->advance_token();
1294 bool
1295 Parse::declaration_may_start_here()
1297 const Token* token = this->peek_token();
1298 return (token->is_keyword(KEYWORD_CONST)
1299 || token->is_keyword(KEYWORD_TYPE)
1300 || token->is_keyword(KEYWORD_VAR)
1301 || token->is_keyword(KEYWORD_FUNC));
1304 // Decl<P> = P | "(" [ List<P> ] ")" .
1306 void
1307 Parse::decl(void (Parse::*pfn)(void*), void* varg)
1309 if (this->peek_token()->is_eof())
1311 if (!saw_errors())
1312 error_at(this->location(), "unexpected end of file");
1313 return;
1316 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1317 (this->*pfn)(varg);
1318 else
1320 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
1322 this->list(pfn, varg, true);
1323 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1325 error_at(this->location(), "missing %<)%>");
1326 while (!this->advance_token()->is_op(OPERATOR_RPAREN))
1328 if (this->peek_token()->is_eof())
1329 return;
1333 this->advance_token();
1337 // List<P> = P { ";" P } [ ";" ] .
1339 // In order to pick up the trailing semicolon we need to know what
1340 // might follow. This is either a '}' or a ')'.
1342 void
1343 Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren)
1345 (this->*pfn)(varg);
1346 Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY;
1347 while (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1348 || this->peek_token()->is_op(OPERATOR_COMMA))
1350 if (this->peek_token()->is_op(OPERATOR_COMMA))
1351 error_at(this->location(), "unexpected comma");
1352 if (this->advance_token()->is_op(follow))
1353 break;
1354 (this->*pfn)(varg);
1358 // ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1360 void
1361 Parse::const_decl()
1363 go_assert(this->peek_token()->is_keyword(KEYWORD_CONST));
1364 this->advance_token();
1365 this->reset_iota();
1367 Type* last_type = NULL;
1368 Expression_list* last_expr_list = NULL;
1370 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1371 this->const_spec(&last_type, &last_expr_list);
1372 else
1374 this->advance_token();
1375 while (!this->peek_token()->is_op(OPERATOR_RPAREN))
1377 this->const_spec(&last_type, &last_expr_list);
1378 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1379 this->advance_token();
1380 else if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1382 error_at(this->location(), "expected %<;%> or %<)%> or newline");
1383 if (!this->skip_past_error(OPERATOR_RPAREN))
1384 return;
1387 this->advance_token();
1390 if (last_expr_list != NULL)
1391 delete last_expr_list;
1394 // ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
1396 void
1397 Parse::const_spec(Type** last_type, Expression_list** last_expr_list)
1399 Typed_identifier_list til;
1400 this->identifier_list(&til);
1402 Type* type = NULL;
1403 if (this->type_may_start_here())
1405 type = this->type();
1406 *last_type = NULL;
1407 *last_expr_list = NULL;
1410 Expression_list *expr_list;
1411 if (!this->peek_token()->is_op(OPERATOR_EQ))
1413 if (*last_expr_list == NULL)
1415 error_at(this->location(), "expected %<=%>");
1416 return;
1418 type = *last_type;
1419 expr_list = new Expression_list;
1420 for (Expression_list::const_iterator p = (*last_expr_list)->begin();
1421 p != (*last_expr_list)->end();
1422 ++p)
1423 expr_list->push_back((*p)->copy());
1425 else
1427 this->advance_token();
1428 expr_list = this->expression_list(NULL, false);
1429 *last_type = type;
1430 if (*last_expr_list != NULL)
1431 delete *last_expr_list;
1432 *last_expr_list = expr_list;
1435 Expression_list::const_iterator pe = expr_list->begin();
1436 for (Typed_identifier_list::iterator pi = til.begin();
1437 pi != til.end();
1438 ++pi, ++pe)
1440 if (pe == expr_list->end())
1442 error_at(this->location(), "not enough initializers");
1443 return;
1445 if (type != NULL)
1446 pi->set_type(type);
1448 if (!Gogo::is_sink_name(pi->name()))
1449 this->gogo_->add_constant(*pi, *pe, this->iota_value());
1451 if (pe != expr_list->end())
1452 error_at(this->location(), "too many initializers");
1454 this->increment_iota();
1456 return;
1459 // TypeDecl = "type" Decl<TypeSpec> .
1461 void
1462 Parse::type_decl()
1464 go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE));
1465 this->advance_token();
1466 this->decl(&Parse::type_spec, NULL);
1469 // TypeSpec = identifier Type .
1471 void
1472 Parse::type_spec(void*)
1474 const Token* token = this->peek_token();
1475 if (!token->is_identifier())
1477 error_at(this->location(), "expected identifier");
1478 return;
1480 std::string name = token->identifier();
1481 bool is_exported = token->is_identifier_exported();
1482 Location location = token->location();
1483 token = this->advance_token();
1485 // The scope of the type name starts at the point where the
1486 // identifier appears in the source code. We implement this by
1487 // declaring the type before we read the type definition.
1488 Named_object* named_type = NULL;
1489 if (name != "_")
1491 name = this->gogo_->pack_hidden_name(name, is_exported);
1492 named_type = this->gogo_->declare_type(name, location);
1495 Type* type;
1496 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
1497 type = this->type();
1498 else
1500 error_at(this->location(),
1501 "unexpected semicolon or newline in type declaration");
1502 type = Type::make_error_type();
1503 this->advance_token();
1506 if (type->is_error_type())
1508 this->gogo_->mark_locals_used();
1509 while (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1510 && !this->peek_token()->is_eof())
1511 this->advance_token();
1514 if (name != "_")
1516 if (named_type->is_type_declaration())
1518 Type* ftype = type->forwarded();
1519 if (ftype->forward_declaration_type() != NULL
1520 && (ftype->forward_declaration_type()->named_object()
1521 == named_type))
1523 error_at(location, "invalid recursive type");
1524 type = Type::make_error_type();
1527 this->gogo_->define_type(named_type,
1528 Type::make_named_type(named_type, type,
1529 location));
1530 go_assert(named_type->package() == NULL);
1532 else
1534 // This will probably give a redefinition error.
1535 this->gogo_->add_type(name, type, location);
1540 // VarDecl = "var" Decl<VarSpec> .
1542 void
1543 Parse::var_decl()
1545 go_assert(this->peek_token()->is_keyword(KEYWORD_VAR));
1546 this->advance_token();
1547 this->decl(&Parse::var_spec, NULL);
1550 // VarSpec = IdentifierList
1551 // ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
1553 void
1554 Parse::var_spec(void*)
1556 // Get the variable names.
1557 Typed_identifier_list til;
1558 this->identifier_list(&til);
1560 Location location = this->location();
1562 Type* type = NULL;
1563 Expression_list* init = NULL;
1564 if (!this->peek_token()->is_op(OPERATOR_EQ))
1566 type = this->type();
1567 if (type->is_error_type())
1569 this->gogo_->mark_locals_used();
1570 while (!this->peek_token()->is_op(OPERATOR_EQ)
1571 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
1572 && !this->peek_token()->is_eof())
1573 this->advance_token();
1575 if (this->peek_token()->is_op(OPERATOR_EQ))
1577 this->advance_token();
1578 init = this->expression_list(NULL, false);
1581 else
1583 this->advance_token();
1584 init = this->expression_list(NULL, false);
1587 this->init_vars(&til, type, init, false, location);
1589 if (init != NULL)
1590 delete init;
1593 // Create variables. TIL is a list of variable names. If TYPE is not
1594 // NULL, it is the type of all the variables. If INIT is not NULL, it
1595 // is an initializer list for the variables.
1597 void
1598 Parse::init_vars(const Typed_identifier_list* til, Type* type,
1599 Expression_list* init, bool is_coloneq,
1600 Location location)
1602 // Check for an initialization which can yield multiple values.
1603 if (init != NULL && init->size() == 1 && til->size() > 1)
1605 if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq,
1606 location))
1607 return;
1608 if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq,
1609 location))
1610 return;
1611 if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq,
1612 location))
1613 return;
1614 if (this->init_vars_from_type_guard(til, type, *init->begin(),
1615 is_coloneq, location))
1616 return;
1619 if (init != NULL && init->size() != til->size())
1621 if (init->empty() || !init->front()->is_error_expression())
1622 error_at(location, "wrong number of initializations");
1623 init = NULL;
1624 if (type == NULL)
1625 type = Type::make_error_type();
1628 // Note that INIT was already parsed with the old name bindings, so
1629 // we don't have to worry that it will accidentally refer to the
1630 // newly declared variables.
1632 Expression_list::const_iterator pexpr;
1633 if (init != NULL)
1634 pexpr = init->begin();
1635 bool any_new = false;
1636 for (Typed_identifier_list::const_iterator p = til->begin();
1637 p != til->end();
1638 ++p)
1640 if (init != NULL)
1641 go_assert(pexpr != init->end());
1642 this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq,
1643 false, &any_new);
1644 if (init != NULL)
1645 ++pexpr;
1647 if (init != NULL)
1648 go_assert(pexpr == init->end());
1649 if (is_coloneq && !any_new)
1650 error_at(location, "variables redeclared but no variable is new");
1653 // See if we need to initialize a list of variables from a function
1654 // call. This returns true if we have set up the variables and the
1655 // initialization.
1657 bool
1658 Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type,
1659 Expression* expr, bool is_coloneq,
1660 Location location)
1662 Call_expression* call = expr->call_expression();
1663 if (call == NULL)
1664 return false;
1666 // This is a function call. We can't check here whether it returns
1667 // the right number of values, but it might. Declare the variables,
1668 // and then assign the results of the call to them.
1670 unsigned int index = 0;
1671 bool any_new = false;
1672 for (Typed_identifier_list::const_iterator pv = vars->begin();
1673 pv != vars->end();
1674 ++pv, ++index)
1676 Expression* init = Expression::make_call_result(call, index);
1677 this->init_var(*pv, type, init, is_coloneq, false, &any_new);
1680 if (is_coloneq && !any_new)
1681 error_at(location, "variables redeclared but no variable is new");
1683 return true;
1686 // See if we need to initialize a pair of values from a map index
1687 // expression. This returns true if we have set up the variables and
1688 // the initialization.
1690 bool
1691 Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type,
1692 Expression* expr, bool is_coloneq,
1693 Location location)
1695 Index_expression* index = expr->index_expression();
1696 if (index == NULL)
1697 return false;
1698 if (vars->size() != 2)
1699 return false;
1701 // This is an index which is being assigned to two variables. It
1702 // must be a map index. Declare the variables, and then assign the
1703 // results of the map index.
1704 bool any_new = false;
1705 Typed_identifier_list::const_iterator p = vars->begin();
1706 Expression* init = type == NULL ? index : NULL;
1707 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1708 type == NULL, &any_new);
1709 if (type == NULL && any_new && val_no->is_variable())
1710 val_no->var_value()->set_type_from_init_tuple();
1711 Expression* val_var = Expression::make_var_reference(val_no, location);
1713 ++p;
1714 Type* var_type = type;
1715 if (var_type == NULL)
1716 var_type = Type::lookup_bool_type();
1717 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1718 &any_new);
1719 Expression* present_var = Expression::make_var_reference(no, location);
1721 if (is_coloneq && !any_new)
1722 error_at(location, "variables redeclared but no variable is new");
1724 Statement* s = Statement::make_tuple_map_assignment(val_var, present_var,
1725 index, location);
1727 if (!this->gogo_->in_global_scope())
1728 this->gogo_->add_statement(s);
1729 else if (!val_no->is_sink())
1731 if (val_no->is_variable())
1732 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1734 else if (!no->is_sink())
1736 if (no->is_variable())
1737 no->var_value()->add_preinit_statement(this->gogo_, s);
1739 else
1741 // Execute the map index expression just so that we can fail if
1742 // the map is nil.
1743 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1744 NULL, location);
1745 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1748 return true;
1751 // See if we need to initialize a pair of values from a receive
1752 // expression. This returns true if we have set up the variables and
1753 // the initialization.
1755 bool
1756 Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type,
1757 Expression* expr, bool is_coloneq,
1758 Location location)
1760 Receive_expression* receive = expr->receive_expression();
1761 if (receive == NULL)
1762 return false;
1763 if (vars->size() != 2)
1764 return false;
1766 // This is a receive expression which is being assigned to two
1767 // variables. Declare the variables, and then assign the results of
1768 // the receive.
1769 bool any_new = false;
1770 Typed_identifier_list::const_iterator p = vars->begin();
1771 Expression* init = type == NULL ? receive : NULL;
1772 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1773 type == NULL, &any_new);
1774 if (type == NULL && any_new && val_no->is_variable())
1775 val_no->var_value()->set_type_from_init_tuple();
1776 Expression* val_var = Expression::make_var_reference(val_no, location);
1778 ++p;
1779 Type* var_type = type;
1780 if (var_type == NULL)
1781 var_type = Type::lookup_bool_type();
1782 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1783 &any_new);
1784 Expression* received_var = Expression::make_var_reference(no, location);
1786 if (is_coloneq && !any_new)
1787 error_at(location, "variables redeclared but no variable is new");
1789 Statement* s = Statement::make_tuple_receive_assignment(val_var,
1790 received_var,
1791 receive->channel(),
1792 location);
1794 if (!this->gogo_->in_global_scope())
1795 this->gogo_->add_statement(s);
1796 else if (!val_no->is_sink())
1798 if (val_no->is_variable())
1799 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1801 else if (!no->is_sink())
1803 if (no->is_variable())
1804 no->var_value()->add_preinit_statement(this->gogo_, s);
1806 else
1808 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1809 NULL, location);
1810 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1813 return true;
1816 // See if we need to initialize a pair of values from a type guard
1817 // expression. This returns true if we have set up the variables and
1818 // the initialization.
1820 bool
1821 Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
1822 Type* type, Expression* expr,
1823 bool is_coloneq, Location location)
1825 Type_guard_expression* type_guard = expr->type_guard_expression();
1826 if (type_guard == NULL)
1827 return false;
1828 if (vars->size() != 2)
1829 return false;
1831 // This is a type guard expression which is being assigned to two
1832 // variables. Declare the variables, and then assign the results of
1833 // the type guard.
1834 bool any_new = false;
1835 Typed_identifier_list::const_iterator p = vars->begin();
1836 Type* var_type = type;
1837 if (var_type == NULL)
1838 var_type = type_guard->type();
1839 Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1840 &any_new);
1841 Expression* val_var = Expression::make_var_reference(val_no, location);
1843 ++p;
1844 var_type = type;
1845 if (var_type == NULL)
1846 var_type = Type::lookup_bool_type();
1847 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1848 &any_new);
1849 Expression* ok_var = Expression::make_var_reference(no, location);
1851 Expression* texpr = type_guard->expr();
1852 Type* t = type_guard->type();
1853 Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
1854 texpr, t,
1855 location);
1857 if (is_coloneq && !any_new)
1858 error_at(location, "variables redeclared but no variable is new");
1860 if (!this->gogo_->in_global_scope())
1861 this->gogo_->add_statement(s);
1862 else if (!val_no->is_sink())
1864 if (val_no->is_variable())
1865 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1867 else if (!no->is_sink())
1869 if (no->is_variable())
1870 no->var_value()->add_preinit_statement(this->gogo_, s);
1872 else
1874 Named_object* dummy = this->create_dummy_global(type, NULL, location);
1875 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1878 return true;
1881 // Create a single variable. If IS_COLONEQ is true, we permit
1882 // redeclarations in the same block, and we set *IS_NEW when we find a
1883 // new variable which is not a redeclaration.
1885 Named_object*
1886 Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
1887 bool is_coloneq, bool type_from_init, bool* is_new)
1889 Location location = tid.location();
1891 if (Gogo::is_sink_name(tid.name()))
1893 if (!type_from_init && init != NULL)
1895 if (this->gogo_->in_global_scope())
1896 return this->create_dummy_global(type, init, location);
1897 else if (type == NULL)
1898 this->gogo_->add_statement(Statement::make_statement(init, true));
1899 else
1901 // With both a type and an initializer, create a dummy
1902 // variable so that we will check whether the
1903 // initializer can be assigned to the type.
1904 Variable* var = new Variable(type, init, false, false, false,
1905 location);
1906 var->set_is_used();
1907 static int count;
1908 char buf[30];
1909 snprintf(buf, sizeof buf, "sink$%d", count);
1910 ++count;
1911 return this->gogo_->add_variable(buf, var);
1914 if (type != NULL)
1915 this->gogo_->add_type_to_verify(type);
1916 return this->gogo_->add_sink();
1919 if (is_coloneq)
1921 Named_object* no = this->gogo_->lookup_in_block(tid.name());
1922 if (no != NULL
1923 && (no->is_variable() || no->is_result_variable()))
1925 // INIT may be NULL even when IS_COLONEQ is true for cases
1926 // like v, ok := x.(int).
1927 if (!type_from_init && init != NULL)
1929 Expression *v = Expression::make_var_reference(no, location);
1930 Statement *s = Statement::make_assignment(v, init, location);
1931 this->gogo_->add_statement(s);
1933 return no;
1936 *is_new = true;
1937 Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
1938 false, false, location);
1939 Named_object* no = this->gogo_->add_variable(tid.name(), var);
1940 if (!no->is_variable())
1942 // The name is already defined, so we just gave an error.
1943 return this->gogo_->add_sink();
1945 return no;
1948 // Create a dummy global variable to force an initializer to be run in
1949 // the right place. This is used when a sink variable is initialized
1950 // at global scope.
1952 Named_object*
1953 Parse::create_dummy_global(Type* type, Expression* init,
1954 Location location)
1956 if (type == NULL && init == NULL)
1957 type = Type::lookup_bool_type();
1958 Variable* var = new Variable(type, init, true, false, false, location);
1959 static int count;
1960 char buf[30];
1961 snprintf(buf, sizeof buf, "_.%d", count);
1962 ++count;
1963 return this->gogo_->add_variable(buf, var);
1966 // SimpleVarDecl = identifier ":=" Expression .
1968 // We've already seen the identifier.
1970 // FIXME: We also have to implement
1971 // IdentifierList ":=" ExpressionList
1972 // In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
1973 // tuple assignments here as well.
1975 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
1976 // RangeClause.
1978 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
1979 // guard (var := expr.("type") using the literal keyword "type").
1981 void
1982 Parse::simple_var_decl_or_assignment(const std::string& name,
1983 Location location,
1984 Range_clause* p_range_clause,
1985 Type_switch* p_type_switch)
1987 Typed_identifier_list til;
1988 til.push_back(Typed_identifier(name, NULL, location));
1990 // We've seen one identifier. If we see a comma now, this could be
1991 // "a, *p = 1, 2".
1992 if (this->peek_token()->is_op(OPERATOR_COMMA))
1994 go_assert(p_type_switch == NULL);
1995 while (true)
1997 const Token* token = this->advance_token();
1998 if (!token->is_identifier())
1999 break;
2001 std::string id = token->identifier();
2002 bool is_id_exported = token->is_identifier_exported();
2003 Location id_location = token->location();
2005 token = this->advance_token();
2006 if (!token->is_op(OPERATOR_COMMA))
2008 if (token->is_op(OPERATOR_COLONEQ))
2010 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2011 til.push_back(Typed_identifier(id, NULL, location));
2013 else
2014 this->unget_token(Token::make_identifier_token(id,
2015 is_id_exported,
2016 id_location));
2017 break;
2020 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2021 til.push_back(Typed_identifier(id, NULL, location));
2024 // We have a comma separated list of identifiers in TIL. If the
2025 // next token is COLONEQ, then this is a simple var decl, and we
2026 // have the complete list of identifiers. If the next token is
2027 // not COLONEQ, then the only valid parse is a tuple assignment.
2028 // The list of identifiers we have so far is really a list of
2029 // expressions. There are more expressions following.
2031 if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
2033 Expression_list* exprs = new Expression_list;
2034 for (Typed_identifier_list::const_iterator p = til.begin();
2035 p != til.end();
2036 ++p)
2037 exprs->push_back(this->id_to_expression(p->name(),
2038 p->location()));
2040 Expression_list* more_exprs = this->expression_list(NULL, true);
2041 for (Expression_list::const_iterator p = more_exprs->begin();
2042 p != more_exprs->end();
2043 ++p)
2044 exprs->push_back(*p);
2045 delete more_exprs;
2047 this->tuple_assignment(exprs, p_range_clause);
2048 return;
2052 go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
2053 const Token* token = this->advance_token();
2055 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
2057 this->range_clause_decl(&til, p_range_clause);
2058 return;
2061 Expression_list* init;
2062 if (p_type_switch == NULL)
2063 init = this->expression_list(NULL, false);
2064 else
2066 bool is_type_switch = false;
2067 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
2068 &is_type_switch);
2069 if (is_type_switch)
2071 p_type_switch->found = true;
2072 p_type_switch->name = name;
2073 p_type_switch->location = location;
2074 p_type_switch->expr = expr;
2075 return;
2078 if (!this->peek_token()->is_op(OPERATOR_COMMA))
2080 init = new Expression_list();
2081 init->push_back(expr);
2083 else
2085 this->advance_token();
2086 init = this->expression_list(expr, false);
2090 this->init_vars(&til, NULL, init, true, location);
2093 // FunctionDecl = "func" identifier Signature [ Block ] .
2094 // MethodDecl = "func" Receiver identifier Signature [ Block ] .
2096 // Deprecated gcc extension:
2097 // FunctionDecl = "func" identifier Signature
2098 // __asm__ "(" string_lit ")" .
2099 // This extension means a function whose real name is the identifier
2100 // inside the asm. This extension will be removed at some future
2101 // date. It has been replaced with //extern comments.
2103 void
2104 Parse::function_decl()
2106 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2107 Location location = this->location();
2108 std::string extern_name = this->lex_->extern_name();
2109 const Token* token = this->advance_token();
2111 Typed_identifier* rec = NULL;
2112 if (token->is_op(OPERATOR_LPAREN))
2114 rec = this->receiver();
2115 token = this->peek_token();
2118 if (!token->is_identifier())
2120 error_at(this->location(), "expected function name");
2121 return;
2124 std::string name =
2125 this->gogo_->pack_hidden_name(token->identifier(),
2126 token->is_identifier_exported());
2128 this->advance_token();
2130 Function_type* fntype = this->signature(rec, this->location());
2132 Named_object* named_object = NULL;
2134 if (this->peek_token()->is_keyword(KEYWORD_ASM))
2136 if (!this->advance_token()->is_op(OPERATOR_LPAREN))
2138 error_at(this->location(), "expected %<(%>");
2139 return;
2141 token = this->advance_token();
2142 if (!token->is_string())
2144 error_at(this->location(), "expected string");
2145 return;
2147 std::string asm_name = token->string_value();
2148 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
2150 error_at(this->location(), "expected %<)%>");
2151 return;
2153 this->advance_token();
2154 if (!Gogo::is_sink_name(name))
2156 named_object = this->gogo_->declare_function(name, fntype, location);
2157 if (named_object->is_function_declaration())
2158 named_object->func_declaration_value()->set_asm_name(asm_name);
2162 // Check for the easy error of a newline before the opening brace.
2163 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
2165 Location semi_loc = this->location();
2166 if (this->advance_token()->is_op(OPERATOR_LCURLY))
2167 error_at(this->location(),
2168 "unexpected semicolon or newline before %<{%>");
2169 else
2170 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
2171 semi_loc));
2174 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2176 if (named_object == NULL && !Gogo::is_sink_name(name))
2178 if (fntype == NULL)
2179 this->gogo_->add_erroneous_name(name);
2180 else
2182 named_object = this->gogo_->declare_function(name, fntype,
2183 location);
2184 if (!extern_name.empty()
2185 && named_object->is_function_declaration())
2187 Function_declaration* fd =
2188 named_object->func_declaration_value();
2189 fd->set_asm_name(extern_name);
2194 else
2196 bool hold_is_erroneous_function = this->is_erroneous_function_;
2197 if (fntype == NULL)
2199 fntype = Type::make_function_type(NULL, NULL, NULL, location);
2200 this->is_erroneous_function_ = true;
2201 if (!Gogo::is_sink_name(name))
2202 this->gogo_->add_erroneous_name(name);
2203 name = this->gogo_->pack_hidden_name("_", false);
2205 this->gogo_->start_function(name, fntype, true, location);
2206 Location end_loc = this->block();
2207 this->gogo_->finish_function(end_loc);
2208 this->is_erroneous_function_ = hold_is_erroneous_function;
2212 // Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
2213 // BaseTypeName = identifier .
2215 Typed_identifier*
2216 Parse::receiver()
2218 go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
2220 std::string name;
2221 const Token* token = this->advance_token();
2222 Location location = token->location();
2223 if (!token->is_op(OPERATOR_MULT))
2225 if (!token->is_identifier())
2227 error_at(this->location(), "method has no receiver");
2228 this->gogo_->mark_locals_used();
2229 while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2230 token = this->advance_token();
2231 if (!token->is_eof())
2232 this->advance_token();
2233 return NULL;
2235 name = token->identifier();
2236 bool is_exported = token->is_identifier_exported();
2237 token = this->advance_token();
2238 if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN))
2240 // An identifier followed by something other than a dot or a
2241 // right parenthesis must be a receiver name followed by a
2242 // type.
2243 name = this->gogo_->pack_hidden_name(name, is_exported);
2245 else
2247 // This must be a type name.
2248 this->unget_token(Token::make_identifier_token(name, is_exported,
2249 location));
2250 token = this->peek_token();
2251 name.clear();
2255 // Here the receiver name is in NAME (it is empty if the receiver is
2256 // unnamed) and TOKEN is the first token in the type.
2258 bool is_pointer = false;
2259 if (token->is_op(OPERATOR_MULT))
2261 is_pointer = true;
2262 token = this->advance_token();
2265 if (!token->is_identifier())
2267 error_at(this->location(), "expected receiver name or type");
2268 this->gogo_->mark_locals_used();
2269 int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0;
2270 while (!token->is_eof())
2272 token = this->advance_token();
2273 if (token->is_op(OPERATOR_LPAREN))
2274 ++c;
2275 else if (token->is_op(OPERATOR_RPAREN))
2277 if (c == 0)
2278 break;
2279 --c;
2282 if (!token->is_eof())
2283 this->advance_token();
2284 return NULL;
2287 Type* type = this->type_name(true);
2289 if (is_pointer && !type->is_error_type())
2290 type = Type::make_pointer_type(type);
2292 if (this->peek_token()->is_op(OPERATOR_RPAREN))
2293 this->advance_token();
2294 else
2296 if (this->peek_token()->is_op(OPERATOR_COMMA))
2297 error_at(this->location(), "method has multiple receivers");
2298 else
2299 error_at(this->location(), "expected %<)%>");
2300 this->gogo_->mark_locals_used();
2301 while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2302 token = this->advance_token();
2303 if (!token->is_eof())
2304 this->advance_token();
2305 return NULL;
2308 return new Typed_identifier(name, type, location);
2311 // Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2312 // Literal = BasicLit | CompositeLit | FunctionLit .
2313 // BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2315 // If MAY_BE_SINK is true, this operand may be "_".
2317 Expression*
2318 Parse::operand(bool may_be_sink)
2320 const Token* token = this->peek_token();
2321 Expression* ret;
2322 switch (token->classification())
2324 case Token::TOKEN_IDENTIFIER:
2326 Location location = token->location();
2327 std::string id = token->identifier();
2328 bool is_exported = token->is_identifier_exported();
2329 std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2331 Named_object* in_function;
2332 Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2334 Package* package = NULL;
2335 if (named_object != NULL && named_object->is_package())
2337 if (!this->advance_token()->is_op(OPERATOR_DOT)
2338 || !this->advance_token()->is_identifier())
2340 error_at(location, "unexpected reference to package");
2341 return Expression::make_error(location);
2343 package = named_object->package_value();
2344 package->set_used();
2345 id = this->peek_token()->identifier();
2346 is_exported = this->peek_token()->is_identifier_exported();
2347 packed = this->gogo_->pack_hidden_name(id, is_exported);
2348 named_object = package->lookup(packed);
2349 location = this->location();
2350 go_assert(in_function == NULL);
2353 this->advance_token();
2355 if (named_object != NULL
2356 && named_object->is_type()
2357 && !named_object->type_value()->is_visible())
2359 go_assert(package != NULL);
2360 error_at(location, "invalid reference to hidden type %<%s.%s%>",
2361 Gogo::message_name(package->name()).c_str(),
2362 Gogo::message_name(id).c_str());
2363 return Expression::make_error(location);
2367 if (named_object == NULL)
2369 if (package != NULL)
2371 std::string n1 = Gogo::message_name(package->name());
2372 std::string n2 = Gogo::message_name(id);
2373 if (!is_exported)
2374 error_at(location,
2375 ("invalid reference to unexported identifier "
2376 "%<%s.%s%>"),
2377 n1.c_str(), n2.c_str());
2378 else
2379 error_at(location,
2380 "reference to undefined identifier %<%s.%s%>",
2381 n1.c_str(), n2.c_str());
2382 return Expression::make_error(location);
2385 named_object = this->gogo_->add_unknown_name(packed, location);
2388 if (in_function != NULL
2389 && in_function != this->gogo_->current_function()
2390 && (named_object->is_variable()
2391 || named_object->is_result_variable()))
2392 return this->enclosing_var_reference(in_function, named_object,
2393 location);
2395 switch (named_object->classification())
2397 case Named_object::NAMED_OBJECT_CONST:
2398 return Expression::make_const_reference(named_object, location);
2399 case Named_object::NAMED_OBJECT_TYPE:
2400 return Expression::make_type(named_object->type_value(), location);
2401 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2403 Type* t = Type::make_forward_declaration(named_object);
2404 return Expression::make_type(t, location);
2406 case Named_object::NAMED_OBJECT_VAR:
2407 case Named_object::NAMED_OBJECT_RESULT_VAR:
2408 this->mark_var_used(named_object);
2409 return Expression::make_var_reference(named_object, location);
2410 case Named_object::NAMED_OBJECT_SINK:
2411 if (may_be_sink)
2412 return Expression::make_sink(location);
2413 else
2415 error_at(location, "cannot use _ as value");
2416 return Expression::make_error(location);
2418 case Named_object::NAMED_OBJECT_FUNC:
2419 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2420 return Expression::make_func_reference(named_object, NULL,
2421 location);
2422 case Named_object::NAMED_OBJECT_UNKNOWN:
2424 Unknown_expression* ue =
2425 Expression::make_unknown_reference(named_object, location);
2426 if (this->is_erroneous_function_)
2427 ue->set_no_error_message();
2428 return ue;
2430 case Named_object::NAMED_OBJECT_ERRONEOUS:
2431 return Expression::make_error(location);
2432 default:
2433 go_unreachable();
2436 go_unreachable();
2438 case Token::TOKEN_STRING:
2439 ret = Expression::make_string(token->string_value(), token->location());
2440 this->advance_token();
2441 return ret;
2443 case Token::TOKEN_CHARACTER:
2444 ret = Expression::make_character(token->character_value(), NULL,
2445 token->location());
2446 this->advance_token();
2447 return ret;
2449 case Token::TOKEN_INTEGER:
2450 ret = Expression::make_integer(token->integer_value(), NULL,
2451 token->location());
2452 this->advance_token();
2453 return ret;
2455 case Token::TOKEN_FLOAT:
2456 ret = Expression::make_float(token->float_value(), NULL,
2457 token->location());
2458 this->advance_token();
2459 return ret;
2461 case Token::TOKEN_IMAGINARY:
2463 mpfr_t zero;
2464 mpfr_init_set_ui(zero, 0, GMP_RNDN);
2465 ret = Expression::make_complex(&zero, token->imaginary_value(),
2466 NULL, token->location());
2467 mpfr_clear(zero);
2468 this->advance_token();
2469 return ret;
2472 case Token::TOKEN_KEYWORD:
2473 switch (token->keyword())
2475 case KEYWORD_FUNC:
2476 return this->function_lit();
2477 case KEYWORD_CHAN:
2478 case KEYWORD_INTERFACE:
2479 case KEYWORD_MAP:
2480 case KEYWORD_STRUCT:
2482 Location location = token->location();
2483 return Expression::make_type(this->type(), location);
2485 default:
2486 break;
2488 break;
2490 case Token::TOKEN_OPERATOR:
2491 if (token->is_op(OPERATOR_LPAREN))
2493 this->advance_token();
2494 ret = this->expression(PRECEDENCE_NORMAL, may_be_sink, true, NULL);
2495 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2496 error_at(this->location(), "missing %<)%>");
2497 else
2498 this->advance_token();
2499 return ret;
2501 else if (token->is_op(OPERATOR_LSQUARE))
2503 // Here we call array_type directly, as this is the only
2504 // case where an ellipsis is permitted for an array type.
2505 Location location = token->location();
2506 return Expression::make_type(this->array_type(true), location);
2508 break;
2510 default:
2511 break;
2514 error_at(this->location(), "expected operand");
2515 return Expression::make_error(this->location());
2518 // Handle a reference to a variable in an enclosing function. We add
2519 // it to a list of such variables. We return a reference to a field
2520 // in a struct which will be passed on the static chain when calling
2521 // the current function.
2523 Expression*
2524 Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2525 Location location)
2527 go_assert(var->is_variable() || var->is_result_variable());
2529 this->mark_var_used(var);
2531 Named_object* this_function = this->gogo_->current_function();
2532 Named_object* closure = this_function->func_value()->closure_var();
2534 Enclosing_var ev(var, in_function, this->enclosing_vars_.size());
2535 std::pair<Enclosing_vars::iterator, bool> ins =
2536 this->enclosing_vars_.insert(ev);
2537 if (ins.second)
2539 // This is a variable we have not seen before. Add a new field
2540 // to the closure type.
2541 this_function->func_value()->add_closure_field(var, location);
2544 Expression* closure_ref = Expression::make_var_reference(closure,
2545 location);
2546 closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location);
2548 // The closure structure holds pointers to the variables, so we need
2549 // to introduce an indirection.
2550 Expression* e = Expression::make_field_reference(closure_ref,
2551 ins.first->index(),
2552 location);
2553 e = Expression::make_unary(OPERATOR_MULT, e, location);
2554 return e;
2557 // CompositeLit = LiteralType LiteralValue .
2558 // LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
2559 // SliceType | MapType | TypeName .
2560 // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
2561 // ElementList = Element { "," Element } .
2562 // Element = [ Key ":" ] Value .
2563 // Key = FieldName | ElementIndex .
2564 // FieldName = identifier .
2565 // ElementIndex = Expression .
2566 // Value = Expression | LiteralValue .
2568 // We have already seen the type if there is one, and we are now
2569 // looking at the LiteralValue. The case "[" "..." "]" ElementType
2570 // will be seen here as an array type whose length is "nil". The
2571 // DEPTH parameter is non-zero if this is an embedded composite
2572 // literal and the type was omitted. It gives the number of steps up
2573 // to the type which was provided. E.g., in [][]int{{1}} it will be
2574 // 1. In [][][]int{{{1}}} it will be 2.
2576 Expression*
2577 Parse::composite_lit(Type* type, int depth, Location location)
2579 go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2580 this->advance_token();
2582 if (this->peek_token()->is_op(OPERATOR_RCURLY))
2584 this->advance_token();
2585 return Expression::make_composite_literal(type, depth, false, NULL,
2586 location);
2589 bool has_keys = false;
2590 Expression_list* vals = new Expression_list;
2591 while (true)
2593 Expression* val;
2594 bool is_type_omitted = false;
2596 const Token* token = this->peek_token();
2598 if (token->is_identifier())
2600 std::string identifier = token->identifier();
2601 bool is_exported = token->is_identifier_exported();
2602 Location location = token->location();
2604 if (this->advance_token()->is_op(OPERATOR_COLON))
2606 // This may be a field name. We don't know for sure--it
2607 // could also be an expression for an array index. We
2608 // don't want to parse it as an expression because may
2609 // trigger various errors, e.g., if this identifier
2610 // happens to be the name of a package.
2611 Gogo* gogo = this->gogo_;
2612 val = this->id_to_expression(gogo->pack_hidden_name(identifier,
2613 is_exported),
2614 location);
2616 else
2618 this->unget_token(Token::make_identifier_token(identifier,
2619 is_exported,
2620 location));
2621 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2624 else if (!token->is_op(OPERATOR_LCURLY))
2625 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2626 else
2628 // This must be a composite literal inside another composite
2629 // literal, with the type omitted for the inner one.
2630 val = this->composite_lit(type, depth + 1, token->location());
2631 is_type_omitted = true;
2634 token = this->peek_token();
2635 if (!token->is_op(OPERATOR_COLON))
2637 if (has_keys)
2638 vals->push_back(NULL);
2640 else
2642 if (is_type_omitted && !val->is_error_expression())
2644 error_at(this->location(), "unexpected %<:%>");
2645 val = Expression::make_error(this->location());
2648 this->advance_token();
2650 if (!has_keys && !vals->empty())
2652 Expression_list* newvals = new Expression_list;
2653 for (Expression_list::const_iterator p = vals->begin();
2654 p != vals->end();
2655 ++p)
2657 newvals->push_back(NULL);
2658 newvals->push_back(*p);
2660 delete vals;
2661 vals = newvals;
2663 has_keys = true;
2665 if (val->unknown_expression() != NULL)
2666 val->unknown_expression()->set_is_composite_literal_key();
2668 vals->push_back(val);
2670 if (!token->is_op(OPERATOR_LCURLY))
2671 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2672 else
2674 // This must be a composite literal inside another
2675 // composite literal, with the type omitted for the
2676 // inner one.
2677 val = this->composite_lit(type, depth + 1, token->location());
2680 token = this->peek_token();
2683 vals->push_back(val);
2685 if (token->is_op(OPERATOR_COMMA))
2687 if (this->advance_token()->is_op(OPERATOR_RCURLY))
2689 this->advance_token();
2690 break;
2693 else if (token->is_op(OPERATOR_RCURLY))
2695 this->advance_token();
2696 break;
2698 else
2700 error_at(this->location(), "expected %<,%> or %<}%>");
2702 this->gogo_->mark_locals_used();
2703 int depth = 0;
2704 while (!token->is_eof()
2705 && (depth > 0 || !token->is_op(OPERATOR_RCURLY)))
2707 if (token->is_op(OPERATOR_LCURLY))
2708 ++depth;
2709 else if (token->is_op(OPERATOR_RCURLY))
2710 --depth;
2711 token = this->advance_token();
2713 if (token->is_op(OPERATOR_RCURLY))
2714 this->advance_token();
2716 return Expression::make_error(location);
2720 return Expression::make_composite_literal(type, depth, has_keys, vals,
2721 location);
2724 // FunctionLit = "func" Signature Block .
2726 Expression*
2727 Parse::function_lit()
2729 Location location = this->location();
2730 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2731 this->advance_token();
2733 Enclosing_vars hold_enclosing_vars;
2734 hold_enclosing_vars.swap(this->enclosing_vars_);
2736 Function_type* type = this->signature(NULL, location);
2737 bool fntype_is_error = false;
2738 if (type == NULL)
2740 type = Type::make_function_type(NULL, NULL, NULL, location);
2741 fntype_is_error = true;
2744 // For a function literal, the next token must be a '{'. If we
2745 // don't see that, then we may have a type expression.
2746 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2747 return Expression::make_type(type, location);
2749 bool hold_is_erroneous_function = this->is_erroneous_function_;
2750 if (fntype_is_error)
2751 this->is_erroneous_function_ = true;
2753 Bc_stack* hold_break_stack = this->break_stack_;
2754 Bc_stack* hold_continue_stack = this->continue_stack_;
2755 this->break_stack_ = NULL;
2756 this->continue_stack_ = NULL;
2758 Named_object* no = this->gogo_->start_function("", type, true, location);
2760 Location end_loc = this->block();
2762 this->gogo_->finish_function(end_loc);
2764 if (this->break_stack_ != NULL)
2765 delete this->break_stack_;
2766 if (this->continue_stack_ != NULL)
2767 delete this->continue_stack_;
2768 this->break_stack_ = hold_break_stack;
2769 this->continue_stack_ = hold_continue_stack;
2771 this->is_erroneous_function_ = hold_is_erroneous_function;
2773 hold_enclosing_vars.swap(this->enclosing_vars_);
2775 Expression* closure = this->create_closure(no, &hold_enclosing_vars,
2776 location);
2778 return Expression::make_func_reference(no, closure, location);
2781 // Create a closure for the nested function FUNCTION. This is based
2782 // on ENCLOSING_VARS, which is a list of all variables defined in
2783 // enclosing functions and referenced from FUNCTION. A closure is the
2784 // address of a struct which contains the addresses of all the
2785 // referenced variables. This returns NULL if no closure is required.
2787 Expression*
2788 Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
2789 Location location)
2791 if (enclosing_vars->empty())
2792 return NULL;
2794 // Get the variables in order by their field index.
2796 size_t enclosing_var_count = enclosing_vars->size();
2797 std::vector<Enclosing_var> ev(enclosing_var_count);
2798 for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
2799 p != enclosing_vars->end();
2800 ++p)
2801 ev[p->index()] = *p;
2803 // Build an initializer for a composite literal of the closure's
2804 // type.
2806 Named_object* enclosing_function = this->gogo_->current_function();
2807 Expression_list* initializer = new Expression_list;
2808 for (size_t i = 0; i < enclosing_var_count; ++i)
2810 go_assert(ev[i].index() == i);
2811 Named_object* var = ev[i].var();
2812 Expression* ref;
2813 if (ev[i].in_function() == enclosing_function)
2814 ref = Expression::make_var_reference(var, location);
2815 else
2816 ref = this->enclosing_var_reference(ev[i].in_function(), var,
2817 location);
2818 Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
2819 location);
2820 initializer->push_back(refaddr);
2823 Named_object* closure_var = function->func_value()->closure_var();
2824 Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
2825 Expression* cv = Expression::make_struct_composite_literal(st, initializer,
2826 location);
2827 return Expression::make_heap_composite(cv, location);
2830 // PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
2832 // If MAY_BE_SINK is true, this expression may be "_".
2834 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
2835 // literal.
2837 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2838 // guard (var := expr.("type") using the literal keyword "type").
2840 Expression*
2841 Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
2842 bool* is_type_switch)
2844 Location start_loc = this->location();
2845 bool is_parenthesized = this->peek_token()->is_op(OPERATOR_LPAREN);
2847 Expression* ret = this->operand(may_be_sink);
2849 // An unknown name followed by a curly brace must be a composite
2850 // literal, and the unknown name must be a type.
2851 if (may_be_composite_lit
2852 && !is_parenthesized
2853 && ret->unknown_expression() != NULL
2854 && this->peek_token()->is_op(OPERATOR_LCURLY))
2856 Named_object* no = ret->unknown_expression()->named_object();
2857 Type* type = Type::make_forward_declaration(no);
2858 ret = Expression::make_type(type, ret->location());
2861 // We handle composite literals and type casts here, as it is the
2862 // easiest way to handle types which are in parentheses, as in
2863 // "((uint))(1)".
2864 if (ret->is_type_expression())
2866 if (this->peek_token()->is_op(OPERATOR_LCURLY))
2868 if (!may_be_composite_lit)
2870 Type* t = ret->type();
2871 if (t->named_type() != NULL
2872 || t->forward_declaration_type() != NULL)
2873 error_at(start_loc,
2874 _("parentheses required around this composite literal"
2875 "to avoid parsing ambiguity"));
2877 else if (is_parenthesized)
2878 error_at(start_loc,
2879 "cannot parenthesize type in composite literal");
2880 ret = this->composite_lit(ret->type(), 0, ret->location());
2882 else if (this->peek_token()->is_op(OPERATOR_LPAREN))
2884 Location loc = this->location();
2885 this->advance_token();
2886 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
2887 NULL);
2888 if (this->peek_token()->is_op(OPERATOR_ELLIPSIS))
2890 error_at(this->location(),
2891 "invalid use of %<...%> in type conversion");
2892 this->advance_token();
2894 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2895 error_at(this->location(), "expected %<)%>");
2896 else
2897 this->advance_token();
2898 if (expr->is_error_expression())
2899 ret = expr;
2900 else
2902 Type* t = ret->type();
2903 if (t->classification() == Type::TYPE_ARRAY
2904 && t->array_type()->length() != NULL
2905 && t->array_type()->length()->is_nil_expression())
2907 error_at(ret->location(),
2908 "invalid use of %<...%> in type conversion");
2909 ret = Expression::make_error(loc);
2911 else
2912 ret = Expression::make_cast(t, expr, loc);
2917 while (true)
2919 const Token* token = this->peek_token();
2920 if (token->is_op(OPERATOR_LPAREN))
2921 ret = this->call(this->verify_not_sink(ret));
2922 else if (token->is_op(OPERATOR_DOT))
2924 ret = this->selector(this->verify_not_sink(ret), is_type_switch);
2925 if (is_type_switch != NULL && *is_type_switch)
2926 break;
2928 else if (token->is_op(OPERATOR_LSQUARE))
2929 ret = this->index(this->verify_not_sink(ret));
2930 else
2931 break;
2934 return ret;
2937 // Selector = "." identifier .
2938 // TypeGuard = "." "(" QualifiedIdent ")" .
2940 // Note that Operand can expand to QualifiedIdent, which contains a
2941 // ".". That is handled directly in operand when it sees a package
2942 // name.
2944 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2945 // guard (var := expr.("type") using the literal keyword "type").
2947 Expression*
2948 Parse::selector(Expression* left, bool* is_type_switch)
2950 go_assert(this->peek_token()->is_op(OPERATOR_DOT));
2951 Location location = this->location();
2953 const Token* token = this->advance_token();
2954 if (token->is_identifier())
2956 // This could be a field in a struct, or a method in an
2957 // interface, or a method associated with a type. We can't know
2958 // which until we have seen all the types.
2959 std::string name =
2960 this->gogo_->pack_hidden_name(token->identifier(),
2961 token->is_identifier_exported());
2962 if (token->identifier() == "_")
2964 error_at(this->location(), "invalid use of %<_%>");
2965 name = this->gogo_->pack_hidden_name("blank", false);
2967 this->advance_token();
2968 return Expression::make_selector(left, name, location);
2970 else if (token->is_op(OPERATOR_LPAREN))
2972 this->advance_token();
2973 Type* type = NULL;
2974 if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
2975 type = this->type();
2976 else
2978 if (is_type_switch != NULL)
2979 *is_type_switch = true;
2980 else
2982 error_at(this->location(),
2983 "use of %<.(type)%> outside type switch");
2984 type = Type::make_error_type();
2986 this->advance_token();
2988 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2989 error_at(this->location(), "missing %<)%>");
2990 else
2991 this->advance_token();
2992 if (is_type_switch != NULL && *is_type_switch)
2993 return left;
2994 return Expression::make_type_guard(left, type, location);
2996 else
2998 error_at(this->location(), "expected identifier or %<(%>");
2999 return left;
3003 // Index = "[" Expression "]" .
3004 // Slice = "[" Expression ":" [ Expression ] "]" .
3006 Expression*
3007 Parse::index(Expression* expr)
3009 Location location = this->location();
3010 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
3011 this->advance_token();
3013 Expression* start;
3014 if (!this->peek_token()->is_op(OPERATOR_COLON))
3015 start = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3016 else
3018 mpz_t zero;
3019 mpz_init_set_ui(zero, 0);
3020 start = Expression::make_integer(&zero, NULL, location);
3021 mpz_clear(zero);
3024 Expression* end = NULL;
3025 if (this->peek_token()->is_op(OPERATOR_COLON))
3027 // We use nil to indicate a missing high expression.
3028 if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3029 end = Expression::make_nil(this->location());
3030 else
3031 end = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3033 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
3034 error_at(this->location(), "missing %<]%>");
3035 else
3036 this->advance_token();
3037 return Expression::make_index(expr, start, end, location);
3040 // Call = "(" [ ArgumentList [ "," ] ] ")" .
3041 // ArgumentList = ExpressionList [ "..." ] .
3043 Expression*
3044 Parse::call(Expression* func)
3046 go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
3047 Expression_list* args = NULL;
3048 bool is_varargs = false;
3049 const Token* token = this->advance_token();
3050 if (!token->is_op(OPERATOR_RPAREN))
3052 args = this->expression_list(NULL, false);
3053 token = this->peek_token();
3054 if (token->is_op(OPERATOR_ELLIPSIS))
3056 is_varargs = true;
3057 token = this->advance_token();
3060 if (token->is_op(OPERATOR_COMMA))
3061 token = this->advance_token();
3062 if (!token->is_op(OPERATOR_RPAREN))
3063 error_at(this->location(), "missing %<)%>");
3064 else
3065 this->advance_token();
3066 if (func->is_error_expression())
3067 return func;
3068 return Expression::make_call(func, args, is_varargs, func->location());
3071 // Return an expression for a single unqualified identifier.
3073 Expression*
3074 Parse::id_to_expression(const std::string& name, Location location)
3076 Named_object* in_function;
3077 Named_object* named_object = this->gogo_->lookup(name, &in_function);
3078 if (named_object == NULL)
3079 named_object = this->gogo_->add_unknown_name(name, location);
3081 if (in_function != NULL
3082 && in_function != this->gogo_->current_function()
3083 && (named_object->is_variable() || named_object->is_result_variable()))
3084 return this->enclosing_var_reference(in_function, named_object,
3085 location);
3087 switch (named_object->classification())
3089 case Named_object::NAMED_OBJECT_CONST:
3090 return Expression::make_const_reference(named_object, location);
3091 case Named_object::NAMED_OBJECT_VAR:
3092 case Named_object::NAMED_OBJECT_RESULT_VAR:
3093 this->mark_var_used(named_object);
3094 return Expression::make_var_reference(named_object, location);
3095 case Named_object::NAMED_OBJECT_SINK:
3096 return Expression::make_sink(location);
3097 case Named_object::NAMED_OBJECT_FUNC:
3098 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3099 return Expression::make_func_reference(named_object, NULL, location);
3100 case Named_object::NAMED_OBJECT_UNKNOWN:
3102 Unknown_expression* ue =
3103 Expression::make_unknown_reference(named_object, location);
3104 if (this->is_erroneous_function_)
3105 ue->set_no_error_message();
3106 return ue;
3108 case Named_object::NAMED_OBJECT_PACKAGE:
3109 case Named_object::NAMED_OBJECT_TYPE:
3110 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3112 // These cases can arise for a field name in a composite
3113 // literal.
3114 Unknown_expression* ue =
3115 Expression::make_unknown_reference(named_object, location);
3116 if (this->is_erroneous_function_)
3117 ue->set_no_error_message();
3118 return ue;
3120 case Named_object::NAMED_OBJECT_ERRONEOUS:
3121 return Expression::make_error(location);
3122 default:
3123 error_at(this->location(), "unexpected type of identifier");
3124 return Expression::make_error(location);
3128 // Expression = UnaryExpr { binary_op Expression } .
3130 // PRECEDENCE is the precedence of the current operator.
3132 // If MAY_BE_SINK is true, this expression may be "_".
3134 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3135 // literal.
3137 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3138 // guard (var := expr.("type") using the literal keyword "type").
3140 Expression*
3141 Parse::expression(Precedence precedence, bool may_be_sink,
3142 bool may_be_composite_lit, bool* is_type_switch)
3144 Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
3145 is_type_switch);
3147 while (true)
3149 if (is_type_switch != NULL && *is_type_switch)
3150 return left;
3152 const Token* token = this->peek_token();
3153 if (token->classification() != Token::TOKEN_OPERATOR)
3155 // Not a binary_op.
3156 return left;
3159 Precedence right_precedence;
3160 switch (token->op())
3162 case OPERATOR_OROR:
3163 right_precedence = PRECEDENCE_OROR;
3164 break;
3165 case OPERATOR_ANDAND:
3166 right_precedence = PRECEDENCE_ANDAND;
3167 break;
3168 case OPERATOR_EQEQ:
3169 case OPERATOR_NOTEQ:
3170 case OPERATOR_LT:
3171 case OPERATOR_LE:
3172 case OPERATOR_GT:
3173 case OPERATOR_GE:
3174 right_precedence = PRECEDENCE_RELOP;
3175 break;
3176 case OPERATOR_PLUS:
3177 case OPERATOR_MINUS:
3178 case OPERATOR_OR:
3179 case OPERATOR_XOR:
3180 right_precedence = PRECEDENCE_ADDOP;
3181 break;
3182 case OPERATOR_MULT:
3183 case OPERATOR_DIV:
3184 case OPERATOR_MOD:
3185 case OPERATOR_LSHIFT:
3186 case OPERATOR_RSHIFT:
3187 case OPERATOR_AND:
3188 case OPERATOR_BITCLEAR:
3189 right_precedence = PRECEDENCE_MULOP;
3190 break;
3191 default:
3192 right_precedence = PRECEDENCE_INVALID;
3193 break;
3196 if (right_precedence == PRECEDENCE_INVALID)
3198 // Not a binary_op.
3199 return left;
3202 Operator op = token->op();
3203 Location binop_location = token->location();
3205 if (precedence >= right_precedence)
3207 // We've already seen A * B, and we see + C. We want to
3208 // return so that A * B becomes a group.
3209 return left;
3212 this->advance_token();
3214 left = this->verify_not_sink(left);
3215 Expression* right = this->expression(right_precedence, false,
3216 may_be_composite_lit,
3217 NULL);
3218 left = Expression::make_binary(op, left, right, binop_location);
3222 bool
3223 Parse::expression_may_start_here()
3225 const Token* token = this->peek_token();
3226 switch (token->classification())
3228 case Token::TOKEN_INVALID:
3229 case Token::TOKEN_EOF:
3230 return false;
3231 case Token::TOKEN_KEYWORD:
3232 switch (token->keyword())
3234 case KEYWORD_CHAN:
3235 case KEYWORD_FUNC:
3236 case KEYWORD_MAP:
3237 case KEYWORD_STRUCT:
3238 case KEYWORD_INTERFACE:
3239 return true;
3240 default:
3241 return false;
3243 case Token::TOKEN_IDENTIFIER:
3244 return true;
3245 case Token::TOKEN_STRING:
3246 return true;
3247 case Token::TOKEN_OPERATOR:
3248 switch (token->op())
3250 case OPERATOR_PLUS:
3251 case OPERATOR_MINUS:
3252 case OPERATOR_NOT:
3253 case OPERATOR_XOR:
3254 case OPERATOR_MULT:
3255 case OPERATOR_CHANOP:
3256 case OPERATOR_AND:
3257 case OPERATOR_LPAREN:
3258 case OPERATOR_LSQUARE:
3259 return true;
3260 default:
3261 return false;
3263 case Token::TOKEN_CHARACTER:
3264 case Token::TOKEN_INTEGER:
3265 case Token::TOKEN_FLOAT:
3266 case Token::TOKEN_IMAGINARY:
3267 return true;
3268 default:
3269 go_unreachable();
3273 // UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3275 // If MAY_BE_SINK is true, this expression may be "_".
3277 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3278 // literal.
3280 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3281 // guard (var := expr.("type") using the literal keyword "type").
3283 Expression*
3284 Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3285 bool* is_type_switch)
3287 const Token* token = this->peek_token();
3288 if (token->is_op(OPERATOR_PLUS)
3289 || token->is_op(OPERATOR_MINUS)
3290 || token->is_op(OPERATOR_NOT)
3291 || token->is_op(OPERATOR_XOR)
3292 || token->is_op(OPERATOR_CHANOP)
3293 || token->is_op(OPERATOR_MULT)
3294 || token->is_op(OPERATOR_AND))
3296 Location location = token->location();
3297 Operator op = token->op();
3298 this->advance_token();
3300 if (op == OPERATOR_CHANOP
3301 && this->peek_token()->is_keyword(KEYWORD_CHAN))
3303 // This is "<- chan" which must be the start of a type.
3304 this->unget_token(Token::make_operator_token(op, location));
3305 return Expression::make_type(this->type(), location);
3308 Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL);
3309 if (expr->is_error_expression())
3311 else if (op == OPERATOR_MULT && expr->is_type_expression())
3312 expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3313 location);
3314 else if (op == OPERATOR_AND && expr->is_composite_literal())
3315 expr = Expression::make_heap_composite(expr, location);
3316 else if (op != OPERATOR_CHANOP)
3317 expr = Expression::make_unary(op, expr, location);
3318 else
3319 expr = Expression::make_receive(expr, location);
3320 return expr;
3322 else
3323 return this->primary_expr(may_be_sink, may_be_composite_lit,
3324 is_type_switch);
3327 // Statement =
3328 // Declaration | LabeledStmt | SimpleStmt |
3329 // GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3330 // FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3331 // DeferStmt .
3333 // LABEL is the label of this statement if it has one.
3335 void
3336 Parse::statement(Label* label)
3338 const Token* token = this->peek_token();
3339 switch (token->classification())
3341 case Token::TOKEN_KEYWORD:
3343 switch (token->keyword())
3345 case KEYWORD_CONST:
3346 case KEYWORD_TYPE:
3347 case KEYWORD_VAR:
3348 this->declaration();
3349 break;
3350 case KEYWORD_FUNC:
3351 case KEYWORD_MAP:
3352 case KEYWORD_STRUCT:
3353 case KEYWORD_INTERFACE:
3354 this->simple_stat(true, NULL, NULL, NULL);
3355 break;
3356 case KEYWORD_GO:
3357 case KEYWORD_DEFER:
3358 this->go_or_defer_stat();
3359 break;
3360 case KEYWORD_RETURN:
3361 this->return_stat();
3362 break;
3363 case KEYWORD_BREAK:
3364 this->break_stat();
3365 break;
3366 case KEYWORD_CONTINUE:
3367 this->continue_stat();
3368 break;
3369 case KEYWORD_GOTO:
3370 this->goto_stat();
3371 break;
3372 case KEYWORD_IF:
3373 this->if_stat();
3374 break;
3375 case KEYWORD_SWITCH:
3376 this->switch_stat(label);
3377 break;
3378 case KEYWORD_SELECT:
3379 this->select_stat(label);
3380 break;
3381 case KEYWORD_FOR:
3382 this->for_stat(label);
3383 break;
3384 default:
3385 error_at(this->location(), "expected statement");
3386 this->advance_token();
3387 break;
3390 break;
3392 case Token::TOKEN_IDENTIFIER:
3394 std::string identifier = token->identifier();
3395 bool is_exported = token->is_identifier_exported();
3396 Location location = token->location();
3397 if (this->advance_token()->is_op(OPERATOR_COLON))
3399 this->advance_token();
3400 this->labeled_stmt(identifier, location);
3402 else
3404 this->unget_token(Token::make_identifier_token(identifier,
3405 is_exported,
3406 location));
3407 this->simple_stat(true, NULL, NULL, NULL);
3410 break;
3412 case Token::TOKEN_OPERATOR:
3413 if (token->is_op(OPERATOR_LCURLY))
3415 Location location = token->location();
3416 this->gogo_->start_block(location);
3417 Location end_loc = this->block();
3418 this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3419 location);
3421 else if (!token->is_op(OPERATOR_SEMICOLON))
3422 this->simple_stat(true, NULL, NULL, NULL);
3423 break;
3425 case Token::TOKEN_STRING:
3426 case Token::TOKEN_CHARACTER:
3427 case Token::TOKEN_INTEGER:
3428 case Token::TOKEN_FLOAT:
3429 case Token::TOKEN_IMAGINARY:
3430 this->simple_stat(true, NULL, NULL, NULL);
3431 break;
3433 default:
3434 error_at(this->location(), "expected statement");
3435 this->advance_token();
3436 break;
3440 bool
3441 Parse::statement_may_start_here()
3443 const Token* token = this->peek_token();
3444 switch (token->classification())
3446 case Token::TOKEN_KEYWORD:
3448 switch (token->keyword())
3450 case KEYWORD_CONST:
3451 case KEYWORD_TYPE:
3452 case KEYWORD_VAR:
3453 case KEYWORD_FUNC:
3454 case KEYWORD_MAP:
3455 case KEYWORD_STRUCT:
3456 case KEYWORD_INTERFACE:
3457 case KEYWORD_GO:
3458 case KEYWORD_DEFER:
3459 case KEYWORD_RETURN:
3460 case KEYWORD_BREAK:
3461 case KEYWORD_CONTINUE:
3462 case KEYWORD_GOTO:
3463 case KEYWORD_IF:
3464 case KEYWORD_SWITCH:
3465 case KEYWORD_SELECT:
3466 case KEYWORD_FOR:
3467 return true;
3469 default:
3470 return false;
3473 break;
3475 case Token::TOKEN_IDENTIFIER:
3476 return true;
3478 case Token::TOKEN_OPERATOR:
3479 if (token->is_op(OPERATOR_LCURLY)
3480 || token->is_op(OPERATOR_SEMICOLON))
3481 return true;
3482 else
3483 return this->expression_may_start_here();
3485 case Token::TOKEN_STRING:
3486 case Token::TOKEN_CHARACTER:
3487 case Token::TOKEN_INTEGER:
3488 case Token::TOKEN_FLOAT:
3489 case Token::TOKEN_IMAGINARY:
3490 return true;
3492 default:
3493 return false;
3497 // LabeledStmt = Label ":" Statement .
3498 // Label = identifier .
3500 void
3501 Parse::labeled_stmt(const std::string& label_name, Location location)
3503 Label* label = this->gogo_->add_label_definition(label_name, location);
3505 if (this->peek_token()->is_op(OPERATOR_RCURLY))
3507 // This is a label at the end of a block. A program is
3508 // permitted to omit a semicolon here.
3509 return;
3512 if (!this->statement_may_start_here())
3514 // Mark the label as used to avoid a useless error about an
3515 // unused label.
3516 label->set_is_used();
3518 error_at(location, "missing statement after label");
3519 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3520 location));
3521 return;
3524 this->statement(label);
3527 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
3528 // Assignment | ShortVarDecl .
3530 // EmptyStmt was handled in Parse::statement.
3532 // In order to make this work for if and switch statements, if
3533 // RETURN_EXP is not NULL, and we see an ExpressionStat, we return the
3534 // expression rather than adding an expression statement to the
3535 // current block. If we see something other than an ExpressionStat,
3536 // we add the statement, set *RETURN_EXP to true if we saw a send
3537 // statement, and return NULL. The handling of send statements is for
3538 // better error messages.
3540 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
3541 // RangeClause.
3543 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
3544 // guard (var := expr.("type") using the literal keyword "type").
3546 Expression*
3547 Parse::simple_stat(bool may_be_composite_lit, bool* return_exp,
3548 Range_clause* p_range_clause, Type_switch* p_type_switch)
3550 const Token* token = this->peek_token();
3552 // An identifier follow by := is a SimpleVarDecl.
3553 if (token->is_identifier())
3555 std::string identifier = token->identifier();
3556 bool is_exported = token->is_identifier_exported();
3557 Location location = token->location();
3559 token = this->advance_token();
3560 if (token->is_op(OPERATOR_COLONEQ)
3561 || token->is_op(OPERATOR_COMMA))
3563 identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
3564 this->simple_var_decl_or_assignment(identifier, location,
3565 p_range_clause,
3566 (token->is_op(OPERATOR_COLONEQ)
3567 ? p_type_switch
3568 : NULL));
3569 return NULL;
3572 this->unget_token(Token::make_identifier_token(identifier, is_exported,
3573 location));
3576 Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
3577 may_be_composite_lit,
3578 (p_type_switch == NULL
3579 ? NULL
3580 : &p_type_switch->found));
3581 if (p_type_switch != NULL && p_type_switch->found)
3583 p_type_switch->name.clear();
3584 p_type_switch->location = exp->location();
3585 p_type_switch->expr = this->verify_not_sink(exp);
3586 return NULL;
3588 token = this->peek_token();
3589 if (token->is_op(OPERATOR_CHANOP))
3591 this->send_stmt(this->verify_not_sink(exp));
3592 if (return_exp != NULL)
3593 *return_exp = true;
3595 else if (token->is_op(OPERATOR_PLUSPLUS)
3596 || token->is_op(OPERATOR_MINUSMINUS))
3597 this->inc_dec_stat(this->verify_not_sink(exp));
3598 else if (token->is_op(OPERATOR_COMMA)
3599 || token->is_op(OPERATOR_EQ))
3600 this->assignment(exp, p_range_clause);
3601 else if (token->is_op(OPERATOR_PLUSEQ)
3602 || token->is_op(OPERATOR_MINUSEQ)
3603 || token->is_op(OPERATOR_OREQ)
3604 || token->is_op(OPERATOR_XOREQ)
3605 || token->is_op(OPERATOR_MULTEQ)
3606 || token->is_op(OPERATOR_DIVEQ)
3607 || token->is_op(OPERATOR_MODEQ)
3608 || token->is_op(OPERATOR_LSHIFTEQ)
3609 || token->is_op(OPERATOR_RSHIFTEQ)
3610 || token->is_op(OPERATOR_ANDEQ)
3611 || token->is_op(OPERATOR_BITCLEAREQ))
3612 this->assignment(this->verify_not_sink(exp), p_range_clause);
3613 else if (return_exp != NULL)
3614 return this->verify_not_sink(exp);
3615 else
3617 exp = this->verify_not_sink(exp);
3619 if (token->is_op(OPERATOR_COLONEQ))
3621 if (!exp->is_error_expression())
3622 error_at(token->location(), "non-name on left side of %<:=%>");
3623 this->gogo_->mark_locals_used();
3624 while (!token->is_op(OPERATOR_SEMICOLON)
3625 && !token->is_eof())
3626 token = this->advance_token();
3627 return NULL;
3630 this->expression_stat(exp);
3633 return NULL;
3636 bool
3637 Parse::simple_stat_may_start_here()
3639 return this->expression_may_start_here();
3642 // Parse { Statement ";" } which is used in a few places. The list of
3643 // statements may end with a right curly brace, in which case the
3644 // semicolon may be omitted.
3646 void
3647 Parse::statement_list()
3649 while (this->statement_may_start_here())
3651 this->statement(NULL);
3652 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3653 this->advance_token();
3654 else if (this->peek_token()->is_op(OPERATOR_RCURLY))
3655 break;
3656 else
3658 if (!this->peek_token()->is_eof() || !saw_errors())
3659 error_at(this->location(), "expected %<;%> or %<}%> or newline");
3660 if (!this->skip_past_error(OPERATOR_RCURLY))
3661 return;
3666 bool
3667 Parse::statement_list_may_start_here()
3669 return this->statement_may_start_here();
3672 // ExpressionStat = Expression .
3674 void
3675 Parse::expression_stat(Expression* exp)
3677 this->gogo_->add_statement(Statement::make_statement(exp, false));
3680 // SendStmt = Channel "&lt;-" Expression .
3681 // Channel = Expression .
3683 void
3684 Parse::send_stmt(Expression* channel)
3686 go_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
3687 Location loc = this->location();
3688 this->advance_token();
3689 Expression* val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3690 Statement* s = Statement::make_send_statement(channel, val, loc);
3691 this->gogo_->add_statement(s);
3694 // IncDecStat = Expression ( "++" | "--" ) .
3696 void
3697 Parse::inc_dec_stat(Expression* exp)
3699 const Token* token = this->peek_token();
3701 // Lvalue maps require special handling.
3702 if (exp->index_expression() != NULL)
3703 exp->index_expression()->set_is_lvalue();
3705 if (token->is_op(OPERATOR_PLUSPLUS))
3706 this->gogo_->add_statement(Statement::make_inc_statement(exp));
3707 else if (token->is_op(OPERATOR_MINUSMINUS))
3708 this->gogo_->add_statement(Statement::make_dec_statement(exp));
3709 else
3710 go_unreachable();
3711 this->advance_token();
3714 // Assignment = ExpressionList assign_op ExpressionList .
3716 // EXP is an expression that we have already parsed.
3718 // If RANGE_CLAUSE is not NULL, then this will recognize a
3719 // RangeClause.
3721 void
3722 Parse::assignment(Expression* expr, Range_clause* p_range_clause)
3724 Expression_list* vars;
3725 if (!this->peek_token()->is_op(OPERATOR_COMMA))
3727 vars = new Expression_list();
3728 vars->push_back(expr);
3730 else
3732 this->advance_token();
3733 vars = this->expression_list(expr, true);
3736 this->tuple_assignment(vars, p_range_clause);
3739 // An assignment statement. LHS is the list of expressions which
3740 // appear on the left hand side.
3742 // If RANGE_CLAUSE is not NULL, then this will recognize a
3743 // RangeClause.
3745 void
3746 Parse::tuple_assignment(Expression_list* lhs, Range_clause* p_range_clause)
3748 const Token* token = this->peek_token();
3749 if (!token->is_op(OPERATOR_EQ)
3750 && !token->is_op(OPERATOR_PLUSEQ)
3751 && !token->is_op(OPERATOR_MINUSEQ)
3752 && !token->is_op(OPERATOR_OREQ)
3753 && !token->is_op(OPERATOR_XOREQ)
3754 && !token->is_op(OPERATOR_MULTEQ)
3755 && !token->is_op(OPERATOR_DIVEQ)
3756 && !token->is_op(OPERATOR_MODEQ)
3757 && !token->is_op(OPERATOR_LSHIFTEQ)
3758 && !token->is_op(OPERATOR_RSHIFTEQ)
3759 && !token->is_op(OPERATOR_ANDEQ)
3760 && !token->is_op(OPERATOR_BITCLEAREQ))
3762 error_at(this->location(), "expected assignment operator");
3763 return;
3765 Operator op = token->op();
3766 Location location = token->location();
3768 token = this->advance_token();
3770 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
3772 if (op != OPERATOR_EQ)
3773 error_at(this->location(), "range clause requires %<=%>");
3774 this->range_clause_expr(lhs, p_range_clause);
3775 return;
3778 Expression_list* vals = this->expression_list(NULL, false);
3780 // We've parsed everything; check for errors.
3781 if (lhs == NULL || vals == NULL)
3782 return;
3783 for (Expression_list::const_iterator pe = lhs->begin();
3784 pe != lhs->end();
3785 ++pe)
3787 if ((*pe)->is_error_expression())
3788 return;
3789 if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
3790 error_at((*pe)->location(), "cannot use _ as value");
3792 for (Expression_list::const_iterator pe = vals->begin();
3793 pe != vals->end();
3794 ++pe)
3796 if ((*pe)->is_error_expression())
3797 return;
3800 // Map expressions act differently when they are lvalues.
3801 for (Expression_list::iterator plv = lhs->begin();
3802 plv != lhs->end();
3803 ++plv)
3804 if ((*plv)->index_expression() != NULL)
3805 (*plv)->index_expression()->set_is_lvalue();
3807 Call_expression* call;
3808 Index_expression* map_index;
3809 Receive_expression* receive;
3810 Type_guard_expression* type_guard;
3811 if (lhs->size() == vals->size())
3813 Statement* s;
3814 if (lhs->size() > 1)
3816 if (op != OPERATOR_EQ)
3817 error_at(location, "multiple values only permitted with %<=%>");
3818 s = Statement::make_tuple_assignment(lhs, vals, location);
3820 else
3822 if (op == OPERATOR_EQ)
3823 s = Statement::make_assignment(lhs->front(), vals->front(),
3824 location);
3825 else
3826 s = Statement::make_assignment_operation(op, lhs->front(),
3827 vals->front(), location);
3828 delete lhs;
3829 delete vals;
3831 this->gogo_->add_statement(s);
3833 else if (vals->size() == 1
3834 && (call = (*vals->begin())->call_expression()) != NULL)
3836 if (op != OPERATOR_EQ)
3837 error_at(location, "multiple results only permitted with %<=%>");
3838 delete vals;
3839 vals = new Expression_list;
3840 for (unsigned int i = 0; i < lhs->size(); ++i)
3841 vals->push_back(Expression::make_call_result(call, i));
3842 Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
3843 this->gogo_->add_statement(s);
3845 else if (lhs->size() == 2
3846 && vals->size() == 1
3847 && (map_index = (*vals->begin())->index_expression()) != NULL)
3849 if (op != OPERATOR_EQ)
3850 error_at(location, "two values from map requires %<=%>");
3851 Expression* val = lhs->front();
3852 Expression* present = lhs->back();
3853 Statement* s = Statement::make_tuple_map_assignment(val, present,
3854 map_index, location);
3855 this->gogo_->add_statement(s);
3857 else if (lhs->size() == 1
3858 && vals->size() == 2
3859 && (map_index = lhs->front()->index_expression()) != NULL)
3861 if (op != OPERATOR_EQ)
3862 error_at(location, "assigning tuple to map index requires %<=%>");
3863 Expression* val = vals->front();
3864 Expression* should_set = vals->back();
3865 Statement* s = Statement::make_map_assignment(map_index, val, should_set,
3866 location);
3867 this->gogo_->add_statement(s);
3869 else if (lhs->size() == 2
3870 && vals->size() == 1
3871 && (receive = (*vals->begin())->receive_expression()) != NULL)
3873 if (op != OPERATOR_EQ)
3874 error_at(location, "two values from receive requires %<=%>");
3875 Expression* val = lhs->front();
3876 Expression* success = lhs->back();
3877 Expression* channel = receive->channel();
3878 Statement* s = Statement::make_tuple_receive_assignment(val, success,
3879 channel,
3880 location);
3881 this->gogo_->add_statement(s);
3883 else if (lhs->size() == 2
3884 && vals->size() == 1
3885 && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
3887 if (op != OPERATOR_EQ)
3888 error_at(location, "two values from type guard requires %<=%>");
3889 Expression* val = lhs->front();
3890 Expression* ok = lhs->back();
3891 Expression* expr = type_guard->expr();
3892 Type* type = type_guard->type();
3893 Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
3894 expr, type,
3895 location);
3896 this->gogo_->add_statement(s);
3898 else
3900 error_at(location, "number of variables does not match number of values");
3904 // GoStat = "go" Expression .
3905 // DeferStat = "defer" Expression .
3907 void
3908 Parse::go_or_defer_stat()
3910 go_assert(this->peek_token()->is_keyword(KEYWORD_GO)
3911 || this->peek_token()->is_keyword(KEYWORD_DEFER));
3912 bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
3913 Location stat_location = this->location();
3914 this->advance_token();
3915 Location expr_location = this->location();
3916 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3917 Call_expression* call_expr = expr->call_expression();
3918 if (call_expr == NULL)
3920 error_at(expr_location, "expected call expression");
3921 return;
3924 // Make it easier to simplify go/defer statements by putting every
3925 // statement in its own block.
3926 this->gogo_->start_block(stat_location);
3927 Statement* stat;
3928 if (is_go)
3929 stat = Statement::make_go_statement(call_expr, stat_location);
3930 else
3931 stat = Statement::make_defer_statement(call_expr, stat_location);
3932 this->gogo_->add_statement(stat);
3933 this->gogo_->add_block(this->gogo_->finish_block(stat_location),
3934 stat_location);
3937 // ReturnStat = "return" [ ExpressionList ] .
3939 void
3940 Parse::return_stat()
3942 go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
3943 Location location = this->location();
3944 this->advance_token();
3945 Expression_list* vals = NULL;
3946 if (this->expression_may_start_here())
3947 vals = this->expression_list(NULL, false);
3948 this->gogo_->add_statement(Statement::make_return_statement(vals, location));
3950 if (vals == NULL
3951 && this->gogo_->current_function()->func_value()->results_are_named())
3953 Named_object* function = this->gogo_->current_function();
3954 Function::Results* results = function->func_value()->result_variables();
3955 for (Function::Results::const_iterator p = results->begin();
3956 p != results->end();
3957 ++p)
3959 Named_object* no = this->gogo_->lookup((*p)->name(), NULL);
3960 if (no == NULL)
3961 go_assert(saw_errors());
3962 else if (!no->is_result_variable())
3963 error_at(location, "%qs is shadowed during return",
3964 (*p)->message_name().c_str());
3969 // IfStmt = "if" [ SimpleStmt ";" ] Expression Block
3970 // [ "else" ( IfStmt | Block ) ] .
3972 void
3973 Parse::if_stat()
3975 go_assert(this->peek_token()->is_keyword(KEYWORD_IF));
3976 Location location = this->location();
3977 this->advance_token();
3979 this->gogo_->start_block(location);
3981 bool saw_simple_stat = false;
3982 Expression* cond = NULL;
3983 bool saw_send_stmt = false;
3984 if (this->simple_stat_may_start_here())
3986 cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL);
3987 saw_simple_stat = true;
3989 if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
3991 // The SimpleStat is an expression statement.
3992 this->expression_stat(cond);
3993 cond = NULL;
3995 if (cond == NULL)
3997 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3998 this->advance_token();
3999 else if (saw_simple_stat)
4001 if (saw_send_stmt)
4002 error_at(this->location(),
4003 ("send statement used as value; "
4004 "use select for non-blocking send"));
4005 else
4006 error_at(this->location(),
4007 "expected %<;%> after statement in if expression");
4008 if (!this->expression_may_start_here())
4009 cond = Expression::make_error(this->location());
4011 if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY))
4013 error_at(this->location(),
4014 "missing condition in if statement");
4015 cond = Expression::make_error(this->location());
4017 if (cond == NULL)
4018 cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL);
4021 this->gogo_->start_block(this->location());
4022 Location end_loc = this->block();
4023 Block* then_block = this->gogo_->finish_block(end_loc);
4025 // Check for the easy error of a newline before "else".
4026 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4028 Location semi_loc = this->location();
4029 if (this->advance_token()->is_keyword(KEYWORD_ELSE))
4030 error_at(this->location(),
4031 "unexpected semicolon or newline before %<else%>");
4032 else
4033 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4034 semi_loc));
4037 Block* else_block = NULL;
4038 if (this->peek_token()->is_keyword(KEYWORD_ELSE))
4040 this->gogo_->start_block(this->location());
4041 const Token* token = this->advance_token();
4042 if (token->is_keyword(KEYWORD_IF))
4043 this->if_stat();
4044 else if (token->is_op(OPERATOR_LCURLY))
4045 this->block();
4046 else
4048 error_at(this->location(), "expected %<if%> or %<{%>");
4049 this->statement(NULL);
4051 else_block = this->gogo_->finish_block(this->location());
4054 this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
4055 else_block,
4056 location));
4058 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4059 location);
4062 // SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4063 // ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
4064 // "{" { ExprCaseClause } "}" .
4065 // TypeSwitchStmt = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
4066 // "{" { TypeCaseClause } "}" .
4067 // TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
4069 void
4070 Parse::switch_stat(Label* label)
4072 go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
4073 Location location = this->location();
4074 this->advance_token();
4076 this->gogo_->start_block(location);
4078 bool saw_simple_stat = false;
4079 Expression* switch_val = NULL;
4080 bool saw_send_stmt;
4081 Type_switch type_switch;
4082 bool have_type_switch_block = false;
4083 if (this->simple_stat_may_start_here())
4085 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4086 &type_switch);
4087 saw_simple_stat = true;
4089 if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4091 // The SimpleStat is an expression statement.
4092 this->expression_stat(switch_val);
4093 switch_val = NULL;
4095 if (switch_val == NULL && !type_switch.found)
4097 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4098 this->advance_token();
4099 else if (saw_simple_stat)
4101 if (saw_send_stmt)
4102 error_at(this->location(),
4103 ("send statement used as value; "
4104 "use select for non-blocking send"));
4105 else
4106 error_at(this->location(),
4107 "expected %<;%> after statement in switch expression");
4109 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4111 if (this->peek_token()->is_identifier())
4113 const Token* token = this->peek_token();
4114 std::string identifier = token->identifier();
4115 bool is_exported = token->is_identifier_exported();
4116 Location id_loc = token->location();
4118 token = this->advance_token();
4119 bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
4120 this->unget_token(Token::make_identifier_token(identifier,
4121 is_exported,
4122 id_loc));
4123 if (is_coloneq)
4125 // This must be a TypeSwitchGuard. It is in a
4126 // different block from any initial SimpleStat.
4127 if (saw_simple_stat)
4129 this->gogo_->start_block(id_loc);
4130 have_type_switch_block = true;
4133 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4134 &type_switch);
4135 if (!type_switch.found)
4137 if (switch_val == NULL
4138 || !switch_val->is_error_expression())
4140 error_at(id_loc, "expected type switch assignment");
4141 switch_val = Expression::make_error(id_loc);
4146 if (switch_val == NULL && !type_switch.found)
4148 switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
4149 &type_switch.found);
4150 if (type_switch.found)
4152 type_switch.name.clear();
4153 type_switch.expr = switch_val;
4154 type_switch.location = switch_val->location();
4160 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4162 Location token_loc = this->location();
4163 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
4164 && this->advance_token()->is_op(OPERATOR_LCURLY))
4165 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4166 else if (this->peek_token()->is_op(OPERATOR_COLONEQ))
4168 error_at(token_loc, "invalid variable name");
4169 this->advance_token();
4170 this->expression(PRECEDENCE_NORMAL, false, false,
4171 &type_switch.found);
4172 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4173 this->advance_token();
4174 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4176 if (have_type_switch_block)
4177 this->gogo_->add_block(this->gogo_->finish_block(location),
4178 location);
4179 this->gogo_->add_block(this->gogo_->finish_block(location),
4180 location);
4181 return;
4183 if (type_switch.found)
4184 type_switch.expr = Expression::make_error(location);
4186 else
4188 error_at(this->location(), "expected %<{%>");
4189 if (have_type_switch_block)
4190 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4191 location);
4192 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4193 location);
4194 return;
4197 this->advance_token();
4199 Statement* statement;
4200 if (type_switch.found)
4201 statement = this->type_switch_body(label, type_switch, location);
4202 else
4203 statement = this->expr_switch_body(label, switch_val, location);
4205 if (statement != NULL)
4206 this->gogo_->add_statement(statement);
4208 if (have_type_switch_block)
4209 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4210 location);
4212 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4213 location);
4216 // The body of an expression switch.
4217 // "{" { ExprCaseClause } "}"
4219 Statement*
4220 Parse::expr_switch_body(Label* label, Expression* switch_val,
4221 Location location)
4223 Switch_statement* statement = Statement::make_switch_statement(switch_val,
4224 location);
4226 this->push_break_statement(statement, label);
4228 Case_clauses* case_clauses = new Case_clauses();
4229 bool saw_default = false;
4230 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4232 if (this->peek_token()->is_eof())
4234 if (!saw_errors())
4235 error_at(this->location(), "missing %<}%>");
4236 return NULL;
4238 this->expr_case_clause(case_clauses, &saw_default);
4240 this->advance_token();
4242 statement->add_clauses(case_clauses);
4244 this->pop_break_statement();
4246 return statement;
4249 // ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
4250 // FallthroughStat = "fallthrough" .
4252 void
4253 Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
4255 Location location = this->location();
4257 bool is_default = false;
4258 Expression_list* vals = this->expr_switch_case(&is_default);
4260 if (!this->peek_token()->is_op(OPERATOR_COLON))
4262 if (!saw_errors())
4263 error_at(this->location(), "expected %<:%>");
4264 return;
4266 else
4267 this->advance_token();
4269 Block* statements = NULL;
4270 if (this->statement_list_may_start_here())
4272 this->gogo_->start_block(this->location());
4273 this->statement_list();
4274 statements = this->gogo_->finish_block(this->location());
4277 bool is_fallthrough = false;
4278 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4280 is_fallthrough = true;
4281 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4282 this->advance_token();
4285 if (is_default)
4287 if (*saw_default)
4289 error_at(location, "multiple defaults in switch");
4290 return;
4292 *saw_default = true;
4295 if (is_default || vals != NULL)
4296 clauses->add(vals, is_default, statements, is_fallthrough, location);
4299 // ExprSwitchCase = "case" ExpressionList | "default" .
4301 Expression_list*
4302 Parse::expr_switch_case(bool* is_default)
4304 const Token* token = this->peek_token();
4305 if (token->is_keyword(KEYWORD_CASE))
4307 this->advance_token();
4308 return this->expression_list(NULL, false);
4310 else if (token->is_keyword(KEYWORD_DEFAULT))
4312 this->advance_token();
4313 *is_default = true;
4314 return NULL;
4316 else
4318 if (!saw_errors())
4319 error_at(this->location(), "expected %<case%> or %<default%>");
4320 if (!token->is_op(OPERATOR_RCURLY))
4321 this->advance_token();
4322 return NULL;
4326 // The body of a type switch.
4327 // "{" { TypeCaseClause } "}" .
4329 Statement*
4330 Parse::type_switch_body(Label* label, const Type_switch& type_switch,
4331 Location location)
4333 Named_object* switch_no = NULL;
4334 if (!type_switch.name.empty())
4336 if (Gogo::is_sink_name(type_switch.name))
4337 error_at(type_switch.location,
4338 "no new variables on left side of %<:=%>");
4339 else
4341 Variable* switch_var = new Variable(NULL, type_switch.expr, false,
4342 false, false,
4343 type_switch.location);
4344 switch_no = this->gogo_->add_variable(type_switch.name, switch_var);
4348 Type_switch_statement* statement =
4349 Statement::make_type_switch_statement(switch_no,
4350 (switch_no == NULL
4351 ? type_switch.expr
4352 : NULL),
4353 location);
4355 this->push_break_statement(statement, label);
4357 Type_case_clauses* case_clauses = new Type_case_clauses();
4358 bool saw_default = false;
4359 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4361 if (this->peek_token()->is_eof())
4363 error_at(this->location(), "missing %<}%>");
4364 return NULL;
4366 this->type_case_clause(switch_no, case_clauses, &saw_default);
4368 this->advance_token();
4370 statement->add_clauses(case_clauses);
4372 this->pop_break_statement();
4374 return statement;
4377 // TypeCaseClause = TypeSwitchCase ":" [ StatementList ] .
4379 void
4380 Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses,
4381 bool* saw_default)
4383 Location location = this->location();
4385 std::vector<Type*> types;
4386 bool is_default = false;
4387 this->type_switch_case(&types, &is_default);
4389 if (!this->peek_token()->is_op(OPERATOR_COLON))
4390 error_at(this->location(), "expected %<:%>");
4391 else
4392 this->advance_token();
4394 Block* statements = NULL;
4395 if (this->statement_list_may_start_here())
4397 this->gogo_->start_block(this->location());
4398 if (switch_no != NULL && types.size() == 1)
4400 Type* type = types.front();
4401 Expression* init = Expression::make_var_reference(switch_no,
4402 location);
4403 init = Expression::make_type_guard(init, type, location);
4404 Variable* v = new Variable(type, init, false, false, false,
4405 location);
4406 v->set_is_type_switch_var();
4407 Named_object* no = this->gogo_->add_variable(switch_no->name(), v);
4409 // We don't want to issue an error if the compiler
4410 // introduced special variable is not used. Instead we want
4411 // to issue an error if the variable defined by the switch
4412 // is not used. That is handled via type_switch_vars_ and
4413 // Parse::mark_var_used.
4414 v->set_is_used();
4415 this->type_switch_vars_[no] = switch_no;
4417 this->statement_list();
4418 statements = this->gogo_->finish_block(this->location());
4421 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4423 error_at(this->location(),
4424 "fallthrough is not permitted in a type switch");
4425 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4426 this->advance_token();
4429 if (is_default)
4431 go_assert(types.empty());
4432 if (*saw_default)
4434 error_at(location, "multiple defaults in type switch");
4435 return;
4437 *saw_default = true;
4438 clauses->add(NULL, false, true, statements, location);
4440 else if (!types.empty())
4442 for (std::vector<Type*>::const_iterator p = types.begin();
4443 p + 1 != types.end();
4444 ++p)
4445 clauses->add(*p, true, false, NULL, location);
4446 clauses->add(types.back(), false, false, statements, location);
4448 else
4449 clauses->add(Type::make_error_type(), false, false, statements, location);
4452 // TypeSwitchCase = "case" type | "default"
4454 // We accept a comma separated list of types.
4456 void
4457 Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
4459 const Token* token = this->peek_token();
4460 if (token->is_keyword(KEYWORD_CASE))
4462 this->advance_token();
4463 while (true)
4465 Type* t = this->type();
4467 if (!t->is_error_type())
4468 types->push_back(t);
4469 else
4471 this->gogo_->mark_locals_used();
4472 token = this->peek_token();
4473 while (!token->is_op(OPERATOR_COLON)
4474 && !token->is_op(OPERATOR_COMMA)
4475 && !token->is_op(OPERATOR_RCURLY)
4476 && !token->is_eof())
4477 token = this->advance_token();
4480 if (!this->peek_token()->is_op(OPERATOR_COMMA))
4481 break;
4482 this->advance_token();
4485 else if (token->is_keyword(KEYWORD_DEFAULT))
4487 this->advance_token();
4488 *is_default = true;
4490 else
4492 error_at(this->location(), "expected %<case%> or %<default%>");
4493 if (!token->is_op(OPERATOR_RCURLY))
4494 this->advance_token();
4498 // SelectStat = "select" "{" { CommClause } "}" .
4500 void
4501 Parse::select_stat(Label* label)
4503 go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
4504 Location location = this->location();
4505 const Token* token = this->advance_token();
4507 if (!token->is_op(OPERATOR_LCURLY))
4509 Location token_loc = token->location();
4510 if (token->is_op(OPERATOR_SEMICOLON)
4511 && this->advance_token()->is_op(OPERATOR_LCURLY))
4512 error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4513 else
4515 error_at(this->location(), "expected %<{%>");
4516 return;
4519 this->advance_token();
4521 Select_statement* statement = Statement::make_select_statement(location);
4523 this->push_break_statement(statement, label);
4525 Select_clauses* select_clauses = new Select_clauses();
4526 bool saw_default = false;
4527 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4529 if (this->peek_token()->is_eof())
4531 error_at(this->location(), "expected %<}%>");
4532 return;
4534 this->comm_clause(select_clauses, &saw_default);
4537 this->advance_token();
4539 statement->add_clauses(select_clauses);
4541 this->pop_break_statement();
4543 this->gogo_->add_statement(statement);
4546 // CommClause = CommCase ":" { Statement ";" } .
4548 void
4549 Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
4551 Location location = this->location();
4552 bool is_send = false;
4553 Expression* channel = NULL;
4554 Expression* val = NULL;
4555 Expression* closed = NULL;
4556 std::string varname;
4557 std::string closedname;
4558 bool is_default = false;
4559 bool got_case = this->comm_case(&is_send, &channel, &val, &closed,
4560 &varname, &closedname, &is_default);
4562 if (!is_send
4563 && varname.empty()
4564 && closedname.empty()
4565 && val != NULL
4566 && val->index_expression() != NULL)
4567 val->index_expression()->set_is_lvalue();
4569 if (this->peek_token()->is_op(OPERATOR_COLON))
4570 this->advance_token();
4571 else
4572 error_at(this->location(), "expected colon");
4574 this->gogo_->start_block(this->location());
4576 Named_object* var = NULL;
4577 if (!varname.empty())
4579 // FIXME: LOCATION is slightly wrong here.
4580 Variable* v = new Variable(NULL, channel, false, false, false,
4581 location);
4582 v->set_type_from_chan_element();
4583 var = this->gogo_->add_variable(varname, v);
4586 Named_object* closedvar = NULL;
4587 if (!closedname.empty())
4589 // FIXME: LOCATION is slightly wrong here.
4590 Variable* v = new Variable(Type::lookup_bool_type(), NULL,
4591 false, false, false, location);
4592 closedvar = this->gogo_->add_variable(closedname, v);
4595 this->statement_list();
4597 Block* statements = this->gogo_->finish_block(this->location());
4599 if (is_default)
4601 if (*saw_default)
4603 error_at(location, "multiple defaults in select");
4604 return;
4606 *saw_default = true;
4609 if (got_case)
4610 clauses->add(is_send, channel, val, closed, var, closedvar, is_default,
4611 statements, location);
4612 else if (statements != NULL)
4614 // Add the statements to make sure that any names they define
4615 // are traversed.
4616 this->gogo_->add_block(statements, location);
4620 // CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
4622 bool
4623 Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
4624 Expression** closed, std::string* varname,
4625 std::string* closedname, bool* is_default)
4627 const Token* token = this->peek_token();
4628 if (token->is_keyword(KEYWORD_DEFAULT))
4630 this->advance_token();
4631 *is_default = true;
4633 else if (token->is_keyword(KEYWORD_CASE))
4635 this->advance_token();
4636 if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname,
4637 closedname))
4638 return false;
4640 else
4642 error_at(this->location(), "expected %<case%> or %<default%>");
4643 if (!token->is_op(OPERATOR_RCURLY))
4644 this->advance_token();
4645 return false;
4648 return true;
4651 // RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
4652 // RecvExpr = Expression .
4654 bool
4655 Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val,
4656 Expression** closed, std::string* varname,
4657 std::string* closedname)
4659 const Token* token = this->peek_token();
4660 bool saw_comma = false;
4661 bool closed_is_id = false;
4662 if (token->is_identifier())
4664 Gogo* gogo = this->gogo_;
4665 std::string recv_var = token->identifier();
4666 bool is_rv_exported = token->is_identifier_exported();
4667 Location recv_var_loc = token->location();
4668 token = this->advance_token();
4669 if (token->is_op(OPERATOR_COLONEQ))
4671 // case rv := <-c:
4672 this->advance_token();
4673 Expression* e = this->expression(PRECEDENCE_NORMAL, false, false,
4674 NULL);
4675 Receive_expression* re = e->receive_expression();
4676 if (re == NULL)
4678 if (!e->is_error_expression())
4679 error_at(this->location(), "expected receive expression");
4680 return false;
4682 if (recv_var == "_")
4684 error_at(recv_var_loc,
4685 "no new variables on left side of %<:=%>");
4686 recv_var = "blank";
4688 *is_send = false;
4689 *varname = gogo->pack_hidden_name(recv_var, is_rv_exported);
4690 *channel = re->channel();
4691 return true;
4693 else if (token->is_op(OPERATOR_COMMA))
4695 token = this->advance_token();
4696 if (token->is_identifier())
4698 std::string recv_closed = token->identifier();
4699 bool is_rc_exported = token->is_identifier_exported();
4700 Location recv_closed_loc = token->location();
4701 closed_is_id = true;
4703 token = this->advance_token();
4704 if (token->is_op(OPERATOR_COLONEQ))
4706 // case rv, rc := <-c:
4707 this->advance_token();
4708 Expression* e = this->expression(PRECEDENCE_NORMAL, false,
4709 false, NULL);
4710 Receive_expression* re = e->receive_expression();
4711 if (re == NULL)
4713 if (!e->is_error_expression())
4714 error_at(this->location(),
4715 "expected receive expression");
4716 return false;
4718 if (recv_var == "_" && recv_closed == "_")
4720 error_at(recv_var_loc,
4721 "no new variables on left side of %<:=%>");
4722 recv_var = "blank";
4724 *is_send = false;
4725 if (recv_var != "_")
4726 *varname = gogo->pack_hidden_name(recv_var,
4727 is_rv_exported);
4728 if (recv_closed != "_")
4729 *closedname = gogo->pack_hidden_name(recv_closed,
4730 is_rc_exported);
4731 *channel = re->channel();
4732 return true;
4735 this->unget_token(Token::make_identifier_token(recv_closed,
4736 is_rc_exported,
4737 recv_closed_loc));
4740 *val = this->id_to_expression(gogo->pack_hidden_name(recv_var,
4741 is_rv_exported),
4742 recv_var_loc);
4743 saw_comma = true;
4745 else
4746 this->unget_token(Token::make_identifier_token(recv_var,
4747 is_rv_exported,
4748 recv_var_loc));
4751 // If SAW_COMMA is false, then we are looking at the start of the
4752 // send or receive expression. If SAW_COMMA is true, then *VAL is
4753 // set and we just read a comma.
4755 Expression* e;
4756 if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP))
4757 e = this->expression(PRECEDENCE_NORMAL, true, true, NULL);
4758 else
4760 // case <-c:
4761 *is_send = false;
4762 this->advance_token();
4763 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4765 // The next token should be ':'. If it is '<-', then we have
4766 // case <-c <- v:
4767 // which is to say, send on a channel received from a channel.
4768 if (!this->peek_token()->is_op(OPERATOR_CHANOP))
4769 return true;
4771 e = Expression::make_receive(*channel, (*channel)->location());
4774 if (this->peek_token()->is_op(OPERATOR_EQ))
4776 if (!this->advance_token()->is_op(OPERATOR_CHANOP))
4778 error_at(this->location(), "missing %<<-%>");
4779 return false;
4781 *is_send = false;
4782 this->advance_token();
4783 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4784 if (saw_comma)
4786 // case v, e = <-c:
4787 // *VAL is already set.
4788 if (!e->is_sink_expression())
4789 *closed = e;
4791 else
4793 // case v = <-c:
4794 if (!e->is_sink_expression())
4795 *val = e;
4797 return true;
4800 if (saw_comma)
4802 if (closed_is_id)
4803 error_at(this->location(), "expected %<=%> or %<:=%>");
4804 else
4805 error_at(this->location(), "expected %<=%>");
4806 return false;
4809 if (this->peek_token()->is_op(OPERATOR_CHANOP))
4811 // case c <- v:
4812 *is_send = true;
4813 *channel = this->verify_not_sink(e);
4814 this->advance_token();
4815 *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4816 return true;
4819 error_at(this->location(), "expected %<<-%> or %<=%>");
4820 return false;
4823 // ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
4824 // Condition = Expression .
4826 void
4827 Parse::for_stat(Label* label)
4829 go_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
4830 Location location = this->location();
4831 const Token* token = this->advance_token();
4833 // Open a block to hold any variables defined in the init statement
4834 // of the for statement.
4835 this->gogo_->start_block(location);
4837 Block* init = NULL;
4838 Expression* cond = NULL;
4839 Block* post = NULL;
4840 Range_clause range_clause;
4842 if (!token->is_op(OPERATOR_LCURLY))
4844 if (token->is_keyword(KEYWORD_VAR))
4846 error_at(this->location(),
4847 "var declaration not allowed in for initializer");
4848 this->var_decl();
4851 if (token->is_op(OPERATOR_SEMICOLON))
4852 this->for_clause(&cond, &post);
4853 else
4855 // We might be looking at a Condition, an InitStat, or a
4856 // RangeClause.
4857 bool saw_send_stmt;
4858 cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL);
4859 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
4861 if (cond == NULL && !range_clause.found)
4863 if (saw_send_stmt)
4864 error_at(this->location(),
4865 ("send statement used as value; "
4866 "use select for non-blocking send"));
4867 else
4868 error_at(this->location(), "parse error in for statement");
4871 else
4873 if (range_clause.found)
4874 error_at(this->location(), "parse error after range clause");
4876 if (cond != NULL)
4878 // COND is actually an expression statement for
4879 // InitStat at the start of a ForClause.
4880 this->expression_stat(cond);
4881 cond = NULL;
4884 this->for_clause(&cond, &post);
4889 // Build the For_statement and note that it is the current target
4890 // for break and continue statements.
4892 For_statement* sfor;
4893 For_range_statement* srange;
4894 Statement* s;
4895 if (!range_clause.found)
4897 sfor = Statement::make_for_statement(init, cond, post, location);
4898 s = sfor;
4899 srange = NULL;
4901 else
4903 srange = Statement::make_for_range_statement(range_clause.index,
4904 range_clause.value,
4905 range_clause.range,
4906 location);
4907 s = srange;
4908 sfor = NULL;
4911 this->push_break_statement(s, label);
4912 this->push_continue_statement(s, label);
4914 // Gather the block of statements in the loop and add them to the
4915 // For_statement.
4917 this->gogo_->start_block(this->location());
4918 Location end_loc = this->block();
4919 Block* statements = this->gogo_->finish_block(end_loc);
4921 if (sfor != NULL)
4922 sfor->add_statements(statements);
4923 else
4924 srange->add_statements(statements);
4926 // This is no longer the break/continue target.
4927 this->pop_break_statement();
4928 this->pop_continue_statement();
4930 // Add the For_statement to the list of statements, and close out
4931 // the block we started to hold any variables defined in the for
4932 // statement.
4934 this->gogo_->add_statement(s);
4936 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4937 location);
4940 // ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
4941 // InitStat = SimpleStat .
4942 // PostStat = SimpleStat .
4944 // We have already read InitStat at this point.
4946 void
4947 Parse::for_clause(Expression** cond, Block** post)
4949 go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
4950 this->advance_token();
4951 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4952 *cond = NULL;
4953 else if (this->peek_token()->is_op(OPERATOR_LCURLY))
4955 error_at(this->location(),
4956 "unexpected semicolon or newline before %<{%>");
4957 *cond = NULL;
4958 *post = NULL;
4959 return;
4961 else
4962 *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4963 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
4964 error_at(this->location(), "expected semicolon");
4965 else
4966 this->advance_token();
4968 if (this->peek_token()->is_op(OPERATOR_LCURLY))
4969 *post = NULL;
4970 else
4972 this->gogo_->start_block(this->location());
4973 this->simple_stat(false, NULL, NULL, NULL);
4974 *post = this->gogo_->finish_block(this->location());
4978 // RangeClause = IdentifierList ( "=" | ":=" ) "range" Expression .
4980 // This is the := version. It is called with a list of identifiers.
4982 void
4983 Parse::range_clause_decl(const Typed_identifier_list* til,
4984 Range_clause* p_range_clause)
4986 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
4987 Location location = this->location();
4989 p_range_clause->found = true;
4991 go_assert(til->size() >= 1);
4992 if (til->size() > 2)
4993 error_at(this->location(), "too many variables for range clause");
4995 this->advance_token();
4996 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL);
4997 p_range_clause->range = expr;
4999 bool any_new = false;
5001 const Typed_identifier* pti = &til->front();
5002 Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new);
5003 if (any_new && no->is_variable())
5004 no->var_value()->set_type_from_range_index();
5005 p_range_clause->index = Expression::make_var_reference(no, location);
5007 if (til->size() == 1)
5008 p_range_clause->value = NULL;
5009 else
5011 pti = &til->back();
5012 bool is_new = false;
5013 no = this->init_var(*pti, NULL, expr, true, true, &is_new);
5014 if (is_new && no->is_variable())
5015 no->var_value()->set_type_from_range_value();
5016 if (is_new)
5017 any_new = true;
5018 p_range_clause->value = Expression::make_var_reference(no, location);
5021 if (!any_new)
5022 error_at(location, "variables redeclared but no variable is new");
5025 // The = version of RangeClause. This is called with a list of
5026 // expressions.
5028 void
5029 Parse::range_clause_expr(const Expression_list* vals,
5030 Range_clause* p_range_clause)
5032 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5034 p_range_clause->found = true;
5036 go_assert(vals->size() >= 1);
5037 if (vals->size() > 2)
5038 error_at(this->location(), "too many variables for range clause");
5040 this->advance_token();
5041 p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
5042 NULL);
5044 p_range_clause->index = vals->front();
5045 if (vals->size() == 1)
5046 p_range_clause->value = NULL;
5047 else
5048 p_range_clause->value = vals->back();
5051 // Push a statement on the break stack.
5053 void
5054 Parse::push_break_statement(Statement* enclosing, Label* label)
5056 if (this->break_stack_ == NULL)
5057 this->break_stack_ = new Bc_stack();
5058 this->break_stack_->push_back(std::make_pair(enclosing, label));
5061 // Push a statement on the continue stack.
5063 void
5064 Parse::push_continue_statement(Statement* enclosing, Label* label)
5066 if (this->continue_stack_ == NULL)
5067 this->continue_stack_ = new Bc_stack();
5068 this->continue_stack_->push_back(std::make_pair(enclosing, label));
5071 // Pop the break stack.
5073 void
5074 Parse::pop_break_statement()
5076 this->break_stack_->pop_back();
5079 // Pop the continue stack.
5081 void
5082 Parse::pop_continue_statement()
5084 this->continue_stack_->pop_back();
5087 // Find a break or continue statement given a label name.
5089 Statement*
5090 Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
5092 if (bc_stack == NULL)
5093 return NULL;
5094 for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
5095 p != bc_stack->rend();
5096 ++p)
5098 if (p->second != NULL && p->second->name() == label)
5100 p->second->set_is_used();
5101 return p->first;
5104 return NULL;
5107 // BreakStat = "break" [ identifier ] .
5109 void
5110 Parse::break_stat()
5112 go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
5113 Location location = this->location();
5115 const Token* token = this->advance_token();
5116 Statement* enclosing;
5117 if (!token->is_identifier())
5119 if (this->break_stack_ == NULL || this->break_stack_->empty())
5121 error_at(this->location(),
5122 "break statement not within for or switch or select");
5123 return;
5125 enclosing = this->break_stack_->back().first;
5127 else
5129 enclosing = this->find_bc_statement(this->break_stack_,
5130 token->identifier());
5131 if (enclosing == NULL)
5133 // If there is a label with this name, mark it as used to
5134 // avoid a useless error about an unused label.
5135 this->gogo_->add_label_reference(token->identifier(),
5136 Linemap::unknown_location(), false);
5138 error_at(token->location(), "invalid break label %qs",
5139 Gogo::message_name(token->identifier()).c_str());
5140 this->advance_token();
5141 return;
5143 this->advance_token();
5146 Unnamed_label* label;
5147 if (enclosing->classification() == Statement::STATEMENT_FOR)
5148 label = enclosing->for_statement()->break_label();
5149 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5150 label = enclosing->for_range_statement()->break_label();
5151 else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
5152 label = enclosing->switch_statement()->break_label();
5153 else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
5154 label = enclosing->type_switch_statement()->break_label();
5155 else if (enclosing->classification() == Statement::STATEMENT_SELECT)
5156 label = enclosing->select_statement()->break_label();
5157 else
5158 go_unreachable();
5160 this->gogo_->add_statement(Statement::make_break_statement(label,
5161 location));
5164 // ContinueStat = "continue" [ identifier ] .
5166 void
5167 Parse::continue_stat()
5169 go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
5170 Location location = this->location();
5172 const Token* token = this->advance_token();
5173 Statement* enclosing;
5174 if (!token->is_identifier())
5176 if (this->continue_stack_ == NULL || this->continue_stack_->empty())
5178 error_at(this->location(), "continue statement not within for");
5179 return;
5181 enclosing = this->continue_stack_->back().first;
5183 else
5185 enclosing = this->find_bc_statement(this->continue_stack_,
5186 token->identifier());
5187 if (enclosing == NULL)
5189 // If there is a label with this name, mark it as used to
5190 // avoid a useless error about an unused label.
5191 this->gogo_->add_label_reference(token->identifier(),
5192 Linemap::unknown_location(), false);
5194 error_at(token->location(), "invalid continue label %qs",
5195 Gogo::message_name(token->identifier()).c_str());
5196 this->advance_token();
5197 return;
5199 this->advance_token();
5202 Unnamed_label* label;
5203 if (enclosing->classification() == Statement::STATEMENT_FOR)
5204 label = enclosing->for_statement()->continue_label();
5205 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5206 label = enclosing->for_range_statement()->continue_label();
5207 else
5208 go_unreachable();
5210 this->gogo_->add_statement(Statement::make_continue_statement(label,
5211 location));
5214 // GotoStat = "goto" identifier .
5216 void
5217 Parse::goto_stat()
5219 go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
5220 Location location = this->location();
5221 const Token* token = this->advance_token();
5222 if (!token->is_identifier())
5223 error_at(this->location(), "expected label for goto");
5224 else
5226 Label* label = this->gogo_->add_label_reference(token->identifier(),
5227 location, true);
5228 Statement* s = Statement::make_goto_statement(label, location);
5229 this->gogo_->add_statement(s);
5230 this->advance_token();
5234 // PackageClause = "package" PackageName .
5236 void
5237 Parse::package_clause()
5239 const Token* token = this->peek_token();
5240 Location location = token->location();
5241 std::string name;
5242 if (!token->is_keyword(KEYWORD_PACKAGE))
5244 error_at(this->location(), "program must start with package clause");
5245 name = "ERROR";
5247 else
5249 token = this->advance_token();
5250 if (token->is_identifier())
5252 name = token->identifier();
5253 if (name == "_")
5255 error_at(this->location(), "invalid package name _");
5256 name = "blank";
5258 this->advance_token();
5260 else
5262 error_at(this->location(), "package name must be an identifier");
5263 name = "ERROR";
5266 this->gogo_->set_package_name(name, location);
5269 // ImportDecl = "import" Decl<ImportSpec> .
5271 void
5272 Parse::import_decl()
5274 go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
5275 this->advance_token();
5276 this->decl(&Parse::import_spec, NULL);
5279 // ImportSpec = [ "." | PackageName ] PackageFileName .
5281 void
5282 Parse::import_spec(void*)
5284 const Token* token = this->peek_token();
5285 Location location = token->location();
5287 std::string local_name;
5288 bool is_local_name_exported = false;
5289 if (token->is_op(OPERATOR_DOT))
5291 local_name = ".";
5292 token = this->advance_token();
5294 else if (token->is_identifier())
5296 local_name = token->identifier();
5297 is_local_name_exported = token->is_identifier_exported();
5298 token = this->advance_token();
5301 if (!token->is_string())
5303 error_at(this->location(), "missing import package name");
5304 return;
5307 this->gogo_->import_package(token->string_value(), local_name,
5308 is_local_name_exported, location);
5310 this->advance_token();
5313 // SourceFile = PackageClause ";" { ImportDecl ";" }
5314 // { TopLevelDecl ";" } .
5316 void
5317 Parse::program()
5319 this->package_clause();
5321 const Token* token = this->peek_token();
5322 if (token->is_op(OPERATOR_SEMICOLON))
5323 token = this->advance_token();
5324 else
5325 error_at(this->location(),
5326 "expected %<;%> or newline after package clause");
5328 while (token->is_keyword(KEYWORD_IMPORT))
5330 this->import_decl();
5331 token = this->peek_token();
5332 if (token->is_op(OPERATOR_SEMICOLON))
5333 token = this->advance_token();
5334 else
5335 error_at(this->location(),
5336 "expected %<;%> or newline after import declaration");
5339 while (!token->is_eof())
5341 if (this->declaration_may_start_here())
5342 this->declaration();
5343 else
5345 error_at(this->location(), "expected declaration");
5346 this->gogo_->mark_locals_used();
5348 this->advance_token();
5349 while (!this->peek_token()->is_eof()
5350 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
5351 && !this->peek_token()->is_op(OPERATOR_RCURLY));
5352 if (!this->peek_token()->is_eof()
5353 && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
5354 this->advance_token();
5356 token = this->peek_token();
5357 if (token->is_op(OPERATOR_SEMICOLON))
5358 token = this->advance_token();
5359 else if (!token->is_eof() || !saw_errors())
5361 if (token->is_op(OPERATOR_CHANOP))
5362 error_at(this->location(),
5363 ("send statement used as value; "
5364 "use select for non-blocking send"));
5365 else
5366 error_at(this->location(),
5367 "expected %<;%> or newline after top level declaration");
5368 this->skip_past_error(OPERATOR_INVALID);
5373 // Reset the current iota value.
5375 void
5376 Parse::reset_iota()
5378 this->iota_ = 0;
5381 // Return the current iota value.
5384 Parse::iota_value()
5386 return this->iota_;
5389 // Increment the current iota value.
5391 void
5392 Parse::increment_iota()
5394 ++this->iota_;
5397 // Skip forward to a semicolon or OP. OP will normally be
5398 // OPERATOR_RPAREN or OPERATOR_RCURLY. If we find a semicolon, move
5399 // past it and return. If we find OP, it will be the next token to
5400 // read. Return true if we are OK, false if we found EOF.
5402 bool
5403 Parse::skip_past_error(Operator op)
5405 this->gogo_->mark_locals_used();
5406 const Token* token = this->peek_token();
5407 while (!token->is_op(op))
5409 if (token->is_eof())
5410 return false;
5411 if (token->is_op(OPERATOR_SEMICOLON))
5413 this->advance_token();
5414 return true;
5416 token = this->advance_token();
5418 return true;
5421 // Check that an expression is not a sink.
5423 Expression*
5424 Parse::verify_not_sink(Expression* expr)
5426 if (expr->is_sink_expression())
5428 error_at(expr->location(), "cannot use _ as value");
5429 expr = Expression::make_error(expr->location());
5431 return expr;
5434 // Mark a variable as used.
5436 void
5437 Parse::mark_var_used(Named_object* no)
5439 if (no->is_variable())
5441 no->var_value()->set_is_used();
5443 // When a type switch uses := to define a variable, then for
5444 // each case with a single type we introduce a new variable with
5445 // the appropriate type. When we do, if the newly introduced
5446 // variable is used, then the type switch variable is used.
5447 Type_switch_vars::iterator p = this->type_switch_vars_.find(no);
5448 if (p != this->type_switch_vars_.end())
5449 p->second->var_value()->set_is_used();