Corrected date in changelog
[official-gcc.git] / gcc / go / gofrontend / parse.cc
blob8162abf342b13a7914907cc05610e035a41cacd7
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 "go-diagnostics.h"
12 #include "types.h"
13 #include "statements.h"
14 #include "expressions.h"
15 #include "parse.h"
17 // Struct Parse::Enclosing_var_comparison.
19 // Return true if v1 should be considered to be less than v2.
21 bool
22 Parse::Enclosing_var_comparison::operator()(const Enclosing_var& v1,
23 const Enclosing_var& v2) const
25 if (v1.var() == v2.var())
26 return false;
28 const std::string& n1(v1.var()->name());
29 const std::string& n2(v2.var()->name());
30 int i = n1.compare(n2);
31 if (i < 0)
32 return true;
33 else if (i > 0)
34 return false;
36 // If we get here it means that a single nested function refers to
37 // two different variables defined in enclosing functions, and both
38 // variables have the same name. I think this is impossible.
39 go_unreachable();
42 // Class Parse.
44 Parse::Parse(Lex* lex, Gogo* gogo)
45 : lex_(lex),
46 token_(Token::make_invalid_token(Linemap::unknown_location())),
47 unget_token_(Token::make_invalid_token(Linemap::unknown_location())),
48 unget_token_valid_(false),
49 is_erroneous_function_(false),
50 gogo_(gogo),
51 break_stack_(NULL),
52 continue_stack_(NULL),
53 iota_(0),
54 enclosing_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 go_error_at(this->location(), "expected identifier");
114 return;
116 std::string name =
117 this->gogo_->pack_hidden_name(token->identifier(),
118 token->is_identifier_exported());
119 til->push_back(Typed_identifier(name, NULL, token->location()));
120 token = this->advance_token();
121 if (!token->is_op(OPERATOR_COMMA))
122 return;
123 token = this->advance_token();
127 // ExpressionList = Expression { "," Expression } .
129 // If MAY_BE_COMPOSITE_LIT is true, an expression may be a composite
130 // literal.
132 // If MAY_BE_SINK is true, the expressions in the list may be "_".
134 Expression_list*
135 Parse::expression_list(Expression* first, bool may_be_sink,
136 bool may_be_composite_lit)
138 Expression_list* ret = new Expression_list();
139 if (first != NULL)
140 ret->push_back(first);
141 while (true)
143 ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink,
144 may_be_composite_lit, NULL, NULL));
146 const Token* token = this->peek_token();
147 if (!token->is_op(OPERATOR_COMMA))
148 return ret;
150 // Most expression lists permit a trailing comma.
151 Location location = token->location();
152 this->advance_token();
153 if (!this->expression_may_start_here())
155 this->unget_token(Token::make_operator_token(OPERATOR_COMMA,
156 location));
157 return ret;
162 // QualifiedIdent = [ PackageName "." ] identifier .
163 // PackageName = identifier .
165 // This sets *PNAME to the identifier and sets *PPACKAGE to the
166 // package or NULL if there isn't one. This returns true on success,
167 // false on failure in which case it will have emitted an error
168 // message.
170 bool
171 Parse::qualified_ident(std::string* pname, Named_object** ppackage)
173 const Token* token = this->peek_token();
174 if (!token->is_identifier())
176 go_error_at(this->location(), "expected identifier");
177 return false;
180 std::string name = token->identifier();
181 bool is_exported = token->is_identifier_exported();
182 name = this->gogo_->pack_hidden_name(name, is_exported);
184 token = this->advance_token();
185 if (!token->is_op(OPERATOR_DOT))
187 *pname = name;
188 *ppackage = NULL;
189 return true;
192 Named_object* package = this->gogo_->lookup(name, NULL);
193 if (package == NULL || !package->is_package())
195 go_error_at(this->location(), "expected package");
196 // We expect . IDENTIFIER; skip both.
197 if (this->advance_token()->is_identifier())
198 this->advance_token();
199 return false;
202 package->package_value()->note_usage(Gogo::unpack_hidden_name(name));
204 token = this->advance_token();
205 if (!token->is_identifier())
207 go_error_at(this->location(), "expected identifier");
208 return false;
211 name = token->identifier();
213 if (name == "_")
215 go_error_at(this->location(), "invalid use of %<_%>");
216 name = Gogo::erroneous_name();
219 if (package->name() == this->gogo_->package_name())
220 name = this->gogo_->pack_hidden_name(name,
221 token->is_identifier_exported());
223 *pname = name;
224 *ppackage = package;
226 this->advance_token();
228 return true;
231 // Type = TypeName | TypeLit | "(" Type ")" .
232 // TypeLit =
233 // ArrayType | StructType | PointerType | FunctionType | InterfaceType |
234 // SliceType | MapType | ChannelType .
236 Type*
237 Parse::type()
239 const Token* token = this->peek_token();
240 if (token->is_identifier())
241 return this->type_name(true);
242 else if (token->is_op(OPERATOR_LSQUARE))
243 return this->array_type(false);
244 else if (token->is_keyword(KEYWORD_CHAN)
245 || token->is_op(OPERATOR_CHANOP))
246 return this->channel_type();
247 else if (token->is_keyword(KEYWORD_INTERFACE))
248 return this->interface_type(true);
249 else if (token->is_keyword(KEYWORD_FUNC))
251 Location location = token->location();
252 this->advance_token();
253 Type* type = this->signature(NULL, location);
254 if (type == NULL)
255 return Type::make_error_type();
256 return type;
258 else if (token->is_keyword(KEYWORD_MAP))
259 return this->map_type();
260 else if (token->is_keyword(KEYWORD_STRUCT))
261 return this->struct_type();
262 else if (token->is_op(OPERATOR_MULT))
263 return this->pointer_type();
264 else if (token->is_op(OPERATOR_LPAREN))
266 this->advance_token();
267 Type* ret = this->type();
268 if (this->peek_token()->is_op(OPERATOR_RPAREN))
269 this->advance_token();
270 else
272 if (!ret->is_error_type())
273 go_error_at(this->location(), "expected %<)%>");
275 return ret;
277 else
279 go_error_at(token->location(), "expected type");
280 return Type::make_error_type();
284 bool
285 Parse::type_may_start_here()
287 const Token* token = this->peek_token();
288 return (token->is_identifier()
289 || token->is_op(OPERATOR_LSQUARE)
290 || token->is_op(OPERATOR_CHANOP)
291 || token->is_keyword(KEYWORD_CHAN)
292 || token->is_keyword(KEYWORD_INTERFACE)
293 || token->is_keyword(KEYWORD_FUNC)
294 || token->is_keyword(KEYWORD_MAP)
295 || token->is_keyword(KEYWORD_STRUCT)
296 || token->is_op(OPERATOR_MULT)
297 || token->is_op(OPERATOR_LPAREN));
300 // TypeName = QualifiedIdent .
302 // If MAY_BE_NIL is true, then an identifier with the value of the
303 // predefined constant nil is accepted, returning the nil type.
305 Type*
306 Parse::type_name(bool issue_error)
308 Location location = this->location();
310 std::string name;
311 Named_object* package;
312 if (!this->qualified_ident(&name, &package))
313 return Type::make_error_type();
315 Named_object* named_object;
316 if (package == NULL)
317 named_object = this->gogo_->lookup(name, NULL);
318 else
320 named_object = package->package_value()->lookup(name);
321 if (named_object == NULL
322 && issue_error
323 && package->name() != this->gogo_->package_name())
325 // Check whether the name is there but hidden.
326 std::string s = ('.' + package->package_value()->pkgpath()
327 + '.' + name);
328 named_object = package->package_value()->lookup(s);
329 if (named_object != NULL)
331 Package* p = package->package_value();
332 const std::string& packname(p->package_name());
333 go_error_at(location,
334 "invalid reference to hidden type %<%s.%s%>",
335 Gogo::message_name(packname).c_str(),
336 Gogo::message_name(name).c_str());
337 issue_error = false;
342 bool ok = true;
343 if (named_object == NULL)
345 if (package == NULL)
346 named_object = this->gogo_->add_unknown_name(name, location);
347 else
349 const std::string& packname(package->package_value()->package_name());
350 go_error_at(location, "reference to undefined identifier %<%s.%s%>",
351 Gogo::message_name(packname).c_str(),
352 Gogo::message_name(name).c_str());
353 issue_error = false;
354 ok = false;
357 else if (named_object->is_type())
359 if (!named_object->type_value()->is_visible())
360 ok = false;
362 else if (named_object->is_unknown() || named_object->is_type_declaration())
364 else
365 ok = false;
367 if (!ok)
369 if (issue_error)
370 go_error_at(location, "expected type");
371 return Type::make_error_type();
374 if (named_object->is_type())
375 return named_object->type_value();
376 else if (named_object->is_unknown() || named_object->is_type_declaration())
377 return Type::make_forward_declaration(named_object);
378 else
379 go_unreachable();
382 // ArrayType = "[" [ ArrayLength ] "]" ElementType .
383 // ArrayLength = Expression .
384 // ElementType = CompleteType .
386 Type*
387 Parse::array_type(bool may_use_ellipsis)
389 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
390 const Token* token = this->advance_token();
392 Expression* length = NULL;
393 if (token->is_op(OPERATOR_RSQUARE))
394 this->advance_token();
395 else
397 if (!token->is_op(OPERATOR_ELLIPSIS))
398 length = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
399 else if (may_use_ellipsis)
401 // An ellipsis is used in composite literals to represent a
402 // fixed array of the size of the number of elements. We
403 // use a length of nil to represent this, and change the
404 // length when parsing the composite literal.
405 length = Expression::make_nil(this->location());
406 this->advance_token();
408 else
410 go_error_at(this->location(),
411 "use of %<[...]%> outside of array literal");
412 length = Expression::make_error(this->location());
413 this->advance_token();
415 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
417 go_error_at(this->location(), "expected %<]%>");
418 return Type::make_error_type();
420 this->advance_token();
423 Type* element_type = this->type();
424 if (element_type->is_error_type())
425 return Type::make_error_type();
427 return Type::make_array_type(element_type, length);
430 // MapType = "map" "[" KeyType "]" ValueType .
431 // KeyType = CompleteType .
432 // ValueType = CompleteType .
434 Type*
435 Parse::map_type()
437 Location location = this->location();
438 go_assert(this->peek_token()->is_keyword(KEYWORD_MAP));
439 if (!this->advance_token()->is_op(OPERATOR_LSQUARE))
441 go_error_at(this->location(), "expected %<[%>");
442 return Type::make_error_type();
444 this->advance_token();
446 Type* key_type = this->type();
448 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
450 go_error_at(this->location(), "expected %<]%>");
451 return Type::make_error_type();
453 this->advance_token();
455 Type* value_type = this->type();
457 if (key_type->is_error_type() || value_type->is_error_type())
458 return Type::make_error_type();
460 return Type::make_map_type(key_type, value_type, location);
463 // StructType = "struct" "{" { FieldDecl ";" } "}" .
465 Type*
466 Parse::struct_type()
468 go_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT));
469 Location location = this->location();
470 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
472 Location token_loc = this->location();
473 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
474 && this->advance_token()->is_op(OPERATOR_LCURLY))
475 go_error_at(token_loc, "unexpected semicolon or newline before %<{%>");
476 else
478 go_error_at(this->location(), "expected %<{%>");
479 return Type::make_error_type();
482 this->advance_token();
484 Struct_field_list* sfl = new Struct_field_list;
485 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
487 this->field_decl(sfl);
488 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
489 this->advance_token();
490 else if (!this->peek_token()->is_op(OPERATOR_RCURLY))
492 go_error_at(this->location(), "expected %<;%> or %<}%> or newline");
493 if (!this->skip_past_error(OPERATOR_RCURLY))
494 return Type::make_error_type();
497 this->advance_token();
499 for (Struct_field_list::const_iterator pi = sfl->begin();
500 pi != sfl->end();
501 ++pi)
503 if (pi->type()->is_error_type())
504 return pi->type();
505 for (Struct_field_list::const_iterator pj = pi + 1;
506 pj != sfl->end();
507 ++pj)
509 if (pi->field_name() == pj->field_name()
510 && !Gogo::is_sink_name(pi->field_name()))
511 go_error_at(pi->location(), "duplicate field name %<%s%>",
512 Gogo::message_name(pi->field_name()).c_str());
516 return Type::make_struct_type(sfl, location);
519 // FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] .
520 // Tag = string_lit .
522 void
523 Parse::field_decl(Struct_field_list* sfl)
525 const Token* token = this->peek_token();
526 Location location = token->location();
527 bool is_anonymous;
528 bool is_anonymous_pointer;
529 if (token->is_op(OPERATOR_MULT))
531 is_anonymous = true;
532 is_anonymous_pointer = true;
534 else if (token->is_identifier())
536 std::string id = token->identifier();
537 bool is_id_exported = token->is_identifier_exported();
538 Location id_location = token->location();
539 token = this->advance_token();
540 is_anonymous = (token->is_op(OPERATOR_SEMICOLON)
541 || token->is_op(OPERATOR_RCURLY)
542 || token->is_op(OPERATOR_DOT)
543 || token->is_string());
544 is_anonymous_pointer = false;
545 this->unget_token(Token::make_identifier_token(id, is_id_exported,
546 id_location));
548 else
550 go_error_at(this->location(), "expected field name");
551 this->gogo_->mark_locals_used();
552 while (!token->is_op(OPERATOR_SEMICOLON)
553 && !token->is_op(OPERATOR_RCURLY)
554 && !token->is_eof())
555 token = this->advance_token();
556 return;
559 if (is_anonymous)
561 if (is_anonymous_pointer)
563 this->advance_token();
564 if (!this->peek_token()->is_identifier())
566 go_error_at(this->location(), "expected field name");
567 this->gogo_->mark_locals_used();
568 while (!token->is_op(OPERATOR_SEMICOLON)
569 && !token->is_op(OPERATOR_RCURLY)
570 && !token->is_eof())
571 token = this->advance_token();
572 return;
575 Type* type = this->type_name(true);
577 std::string tag;
578 if (this->peek_token()->is_string())
580 tag = this->peek_token()->string_value();
581 this->advance_token();
584 if (!type->is_error_type())
586 if (is_anonymous_pointer)
587 type = Type::make_pointer_type(type);
588 sfl->push_back(Struct_field(Typed_identifier("", type, location)));
589 if (!tag.empty())
590 sfl->back().set_tag(tag);
593 else
595 Typed_identifier_list til;
596 while (true)
598 token = this->peek_token();
599 if (!token->is_identifier())
601 go_error_at(this->location(), "expected identifier");
602 return;
604 std::string name =
605 this->gogo_->pack_hidden_name(token->identifier(),
606 token->is_identifier_exported());
607 til.push_back(Typed_identifier(name, NULL, token->location()));
608 if (!this->advance_token()->is_op(OPERATOR_COMMA))
609 break;
610 this->advance_token();
613 Type* type = this->type();
615 std::string tag;
616 if (this->peek_token()->is_string())
618 tag = this->peek_token()->string_value();
619 this->advance_token();
622 for (Typed_identifier_list::iterator p = til.begin();
623 p != til.end();
624 ++p)
626 p->set_type(type);
627 sfl->push_back(Struct_field(*p));
628 if (!tag.empty())
629 sfl->back().set_tag(tag);
634 // PointerType = "*" Type .
636 Type*
637 Parse::pointer_type()
639 go_assert(this->peek_token()->is_op(OPERATOR_MULT));
640 this->advance_token();
641 Type* type = this->type();
642 if (type->is_error_type())
643 return type;
644 return Type::make_pointer_type(type);
647 // ChannelType = Channel | SendChannel | RecvChannel .
648 // Channel = "chan" ElementType .
649 // SendChannel = "chan" "<-" ElementType .
650 // RecvChannel = "<-" "chan" ElementType .
652 Type*
653 Parse::channel_type()
655 const Token* token = this->peek_token();
656 bool send = true;
657 bool receive = true;
658 if (token->is_op(OPERATOR_CHANOP))
660 if (!this->advance_token()->is_keyword(KEYWORD_CHAN))
662 go_error_at(this->location(), "expected %<chan%>");
663 return Type::make_error_type();
665 send = false;
666 this->advance_token();
668 else
670 go_assert(token->is_keyword(KEYWORD_CHAN));
671 if (this->advance_token()->is_op(OPERATOR_CHANOP))
673 receive = false;
674 this->advance_token();
678 // Better error messages for the common error of omitting the
679 // channel element type.
680 if (!this->type_may_start_here())
682 token = this->peek_token();
683 if (token->is_op(OPERATOR_RCURLY))
684 go_error_at(this->location(), "unexpected %<}%> in channel type");
685 else if (token->is_op(OPERATOR_RPAREN))
686 go_error_at(this->location(), "unexpected %<)%> in channel type");
687 else if (token->is_op(OPERATOR_COMMA))
688 go_error_at(this->location(), "unexpected comma in channel type");
689 else
690 go_error_at(this->location(), "expected channel element type");
691 return Type::make_error_type();
694 Type* element_type = this->type();
695 return Type::make_channel_type(send, receive, element_type);
698 // Give an error for a duplicate parameter or receiver name.
700 void
701 Parse::check_signature_names(const Typed_identifier_list* params,
702 Parse::Names* names)
704 for (Typed_identifier_list::const_iterator p = params->begin();
705 p != params->end();
706 ++p)
708 if (p->name().empty() || Gogo::is_sink_name(p->name()))
709 continue;
710 std::pair<std::string, const Typed_identifier*> val =
711 std::make_pair(p->name(), &*p);
712 std::pair<Parse::Names::iterator, bool> ins = names->insert(val);
713 if (!ins.second)
715 go_error_at(p->location(), "redefinition of %qs",
716 Gogo::message_name(p->name()).c_str());
717 go_inform(ins.first->second->location(),
718 "previous definition of %qs was here",
719 Gogo::message_name(p->name()).c_str());
724 // Signature = Parameters [ Result ] .
726 // RECEIVER is the receiver if there is one, or NULL. LOCATION is the
727 // location of the start of the type.
729 // This returns NULL on a parse error.
731 Function_type*
732 Parse::signature(Typed_identifier* receiver, Location location)
734 bool is_varargs = false;
735 Typed_identifier_list* params;
736 bool params_ok = this->parameters(&params, &is_varargs);
738 Typed_identifier_list* results = NULL;
739 if (this->peek_token()->is_op(OPERATOR_LPAREN)
740 || this->type_may_start_here())
742 if (!this->result(&results))
743 return NULL;
746 if (!params_ok)
747 return NULL;
749 Parse::Names names;
750 if (receiver != NULL)
751 names[receiver->name()] = receiver;
752 if (params != NULL)
753 this->check_signature_names(params, &names);
754 if (results != NULL)
755 this->check_signature_names(results, &names);
757 Function_type* ret = Type::make_function_type(receiver, params, results,
758 location);
759 if (is_varargs)
760 ret->set_is_varargs();
761 return ret;
764 // Parameters = "(" [ ParameterList [ "," ] ] ")" .
766 // This returns false on a parse error.
768 bool
769 Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs)
771 *pparams = NULL;
773 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
775 go_error_at(this->location(), "expected %<(%>");
776 return false;
779 Typed_identifier_list* params = NULL;
780 bool saw_error = false;
782 const Token* token = this->advance_token();
783 if (!token->is_op(OPERATOR_RPAREN))
785 params = this->parameter_list(is_varargs);
786 if (params == NULL)
787 saw_error = true;
788 token = this->peek_token();
791 // The optional trailing comma is picked up in parameter_list.
793 if (!token->is_op(OPERATOR_RPAREN))
795 go_error_at(this->location(), "expected %<)%>");
796 return false;
798 this->advance_token();
800 if (saw_error)
801 return false;
803 *pparams = params;
804 return true;
807 // ParameterList = ParameterDecl { "," ParameterDecl } .
809 // This sets *IS_VARARGS if the list ends with an ellipsis.
810 // IS_VARARGS will be NULL if varargs are not permitted.
812 // We pick up an optional trailing comma.
814 // This returns NULL if some error is seen.
816 Typed_identifier_list*
817 Parse::parameter_list(bool* is_varargs)
819 Location location = this->location();
820 Typed_identifier_list* ret = new Typed_identifier_list();
822 bool saw_error = false;
824 // If we see an identifier and then a comma, then we don't know
825 // whether we are looking at a list of identifiers followed by a
826 // type, or a list of types given by name. We have to do an
827 // arbitrary lookahead to figure it out.
829 bool parameters_have_names;
830 const Token* token = this->peek_token();
831 if (!token->is_identifier())
833 // This must be a type which starts with something like '*'.
834 parameters_have_names = false;
836 else
838 std::string name = token->identifier();
839 bool is_exported = token->is_identifier_exported();
840 Location location = token->location();
841 token = this->advance_token();
842 if (!token->is_op(OPERATOR_COMMA))
844 if (token->is_op(OPERATOR_DOT))
846 // This is a qualified identifier, which must turn out
847 // to be a type.
848 parameters_have_names = false;
850 else if (token->is_op(OPERATOR_RPAREN))
852 // A single identifier followed by a parenthesis must be
853 // a type name.
854 parameters_have_names = false;
856 else
858 // An identifier followed by something other than a
859 // comma or a dot or a right parenthesis must be a
860 // parameter name followed by a type.
861 parameters_have_names = true;
864 this->unget_token(Token::make_identifier_token(name, is_exported,
865 location));
867 else
869 // An identifier followed by a comma may be the first in a
870 // list of parameter names followed by a type, or it may be
871 // the first in a list of types without parameter names. To
872 // find out we gather as many identifiers separated by
873 // commas as we can.
874 std::string id_name = this->gogo_->pack_hidden_name(name,
875 is_exported);
876 ret->push_back(Typed_identifier(id_name, NULL, location));
877 bool just_saw_comma = true;
878 while (this->advance_token()->is_identifier())
880 name = this->peek_token()->identifier();
881 is_exported = this->peek_token()->is_identifier_exported();
882 location = this->peek_token()->location();
883 id_name = this->gogo_->pack_hidden_name(name, is_exported);
884 ret->push_back(Typed_identifier(id_name, NULL, location));
885 if (!this->advance_token()->is_op(OPERATOR_COMMA))
887 just_saw_comma = false;
888 break;
892 if (just_saw_comma)
894 // We saw ID1 "," ID2 "," followed by something which
895 // was not an identifier. We must be seeing the start
896 // of a type, and ID1 and ID2 must be types, and the
897 // parameters don't have names.
898 parameters_have_names = false;
900 else if (this->peek_token()->is_op(OPERATOR_RPAREN))
902 // We saw ID1 "," ID2 ")". ID1 and ID2 must be types,
903 // and the parameters don't have names.
904 parameters_have_names = false;
906 else if (this->peek_token()->is_op(OPERATOR_DOT))
908 // We saw ID1 "," ID2 ".". ID2 must be a package name,
909 // ID1 must be a type, and the parameters don't have
910 // names.
911 parameters_have_names = false;
912 this->unget_token(Token::make_identifier_token(name, is_exported,
913 location));
914 ret->pop_back();
915 just_saw_comma = true;
917 else
919 // We saw ID1 "," ID2 followed by something other than
920 // ",", ".", or ")". We must be looking at the start of
921 // a type, and ID1 and ID2 must be parameter names.
922 parameters_have_names = true;
925 if (parameters_have_names)
927 go_assert(!just_saw_comma);
928 // We have just seen ID1, ID2 xxx.
929 Type* type;
930 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
931 type = this->type();
932 else
934 go_error_at(this->location(),
935 "%<...%> only permits one name");
936 saw_error = true;
937 this->advance_token();
938 type = this->type();
940 for (size_t i = 0; i < ret->size(); ++i)
941 ret->set_type(i, type);
942 if (!this->peek_token()->is_op(OPERATOR_COMMA))
943 return saw_error ? NULL : ret;
944 if (this->advance_token()->is_op(OPERATOR_RPAREN))
945 return saw_error ? NULL : ret;
947 else
949 Typed_identifier_list* tret = new Typed_identifier_list();
950 for (Typed_identifier_list::const_iterator p = ret->begin();
951 p != ret->end();
952 ++p)
954 Named_object* no = this->gogo_->lookup(p->name(), NULL);
955 Type* type;
956 if (no == NULL)
957 no = this->gogo_->add_unknown_name(p->name(),
958 p->location());
960 if (no->is_type())
961 type = no->type_value();
962 else if (no->is_unknown() || no->is_type_declaration())
963 type = Type::make_forward_declaration(no);
964 else
966 go_error_at(p->location(), "expected %<%s%> to be a type",
967 Gogo::message_name(p->name()).c_str());
968 saw_error = true;
969 type = Type::make_error_type();
971 tret->push_back(Typed_identifier("", type, p->location()));
973 delete ret;
974 ret = tret;
975 if (!just_saw_comma
976 || this->peek_token()->is_op(OPERATOR_RPAREN))
977 return saw_error ? NULL : ret;
982 bool mix_error = false;
983 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error,
984 &saw_error);
985 while (this->peek_token()->is_op(OPERATOR_COMMA))
987 if (this->advance_token()->is_op(OPERATOR_RPAREN))
988 break;
989 if (is_varargs != NULL && *is_varargs)
991 go_error_at(this->location(), "%<...%> must be last parameter");
992 saw_error = true;
994 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error,
995 &saw_error);
997 if (mix_error)
999 go_error_at(location, "invalid named/anonymous mix");
1000 saw_error = true;
1002 if (saw_error)
1004 delete ret;
1005 return NULL;
1007 return ret;
1010 // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
1012 void
1013 Parse::parameter_decl(bool parameters_have_names,
1014 Typed_identifier_list* til,
1015 bool* is_varargs,
1016 bool* mix_error,
1017 bool* saw_error)
1019 if (!parameters_have_names)
1021 Type* type;
1022 Location location = this->location();
1023 if (!this->peek_token()->is_identifier())
1025 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1026 type = this->type();
1027 else
1029 if (is_varargs == NULL)
1030 go_error_at(this->location(), "invalid use of %<...%>");
1031 else
1032 *is_varargs = true;
1033 this->advance_token();
1034 if (is_varargs == NULL
1035 && this->peek_token()->is_op(OPERATOR_RPAREN))
1036 type = Type::make_error_type();
1037 else
1039 Type* element_type = this->type();
1040 type = Type::make_array_type(element_type, NULL);
1044 else
1046 type = this->type_name(false);
1047 if (type->is_error_type()
1048 || (!this->peek_token()->is_op(OPERATOR_COMMA)
1049 && !this->peek_token()->is_op(OPERATOR_RPAREN)))
1051 *mix_error = true;
1052 while (!this->peek_token()->is_op(OPERATOR_COMMA)
1053 && !this->peek_token()->is_op(OPERATOR_RPAREN)
1054 && !this->peek_token()->is_eof())
1055 this->advance_token();
1058 if (!type->is_error_type())
1059 til->push_back(Typed_identifier("", type, location));
1060 else
1061 *saw_error = true;
1063 else
1065 size_t orig_count = til->size();
1066 if (this->peek_token()->is_identifier())
1067 this->identifier_list(til);
1068 else
1069 *mix_error = true;
1070 size_t new_count = til->size();
1072 Type* type;
1073 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1074 type = this->type();
1075 else
1077 if (is_varargs == NULL)
1079 go_error_at(this->location(), "invalid use of %<...%>");
1080 *saw_error = true;
1082 else if (new_count > orig_count + 1)
1084 go_error_at(this->location(), "%<...%> only permits one name");
1085 *saw_error = true;
1087 else
1088 *is_varargs = true;
1089 this->advance_token();
1090 Type* element_type = this->type();
1091 type = Type::make_array_type(element_type, NULL);
1093 for (size_t i = orig_count; i < new_count; ++i)
1094 til->set_type(i, type);
1098 // Result = Parameters | Type .
1100 // This returns false on a parse error.
1102 bool
1103 Parse::result(Typed_identifier_list** presults)
1105 if (this->peek_token()->is_op(OPERATOR_LPAREN))
1106 return this->parameters(presults, NULL);
1107 else
1109 Location location = this->location();
1110 Type* type = this->type();
1111 if (type->is_error_type())
1113 *presults = NULL;
1114 return false;
1116 Typed_identifier_list* til = new Typed_identifier_list();
1117 til->push_back(Typed_identifier("", type, location));
1118 *presults = til;
1119 return true;
1123 // Block = "{" [ StatementList ] "}" .
1125 // Returns the location of the closing brace.
1127 Location
1128 Parse::block()
1130 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
1132 Location loc = this->location();
1133 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1134 && this->advance_token()->is_op(OPERATOR_LCURLY))
1135 go_error_at(loc, "unexpected semicolon or newline before %<{%>");
1136 else
1138 go_error_at(this->location(), "expected %<{%>");
1139 return Linemap::unknown_location();
1143 const Token* token = this->advance_token();
1145 if (!token->is_op(OPERATOR_RCURLY))
1147 this->statement_list();
1148 token = this->peek_token();
1149 if (!token->is_op(OPERATOR_RCURLY))
1151 if (!token->is_eof() || !saw_errors())
1152 go_error_at(this->location(), "expected %<}%>");
1154 this->gogo_->mark_locals_used();
1156 // Skip ahead to the end of the block, in hopes of avoiding
1157 // lots of meaningless errors.
1158 Location ret = token->location();
1159 int nest = 0;
1160 while (!token->is_eof())
1162 if (token->is_op(OPERATOR_LCURLY))
1163 ++nest;
1164 else if (token->is_op(OPERATOR_RCURLY))
1166 --nest;
1167 if (nest < 0)
1169 this->advance_token();
1170 break;
1173 token = this->advance_token();
1174 ret = token->location();
1176 return ret;
1180 Location ret = token->location();
1181 this->advance_token();
1182 return ret;
1185 // InterfaceType = "interface" "{" [ MethodSpecList ] "}" .
1186 // MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] .
1188 Type*
1189 Parse::interface_type(bool record)
1191 go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE));
1192 Location location = this->location();
1194 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
1196 Location token_loc = this->location();
1197 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1198 && this->advance_token()->is_op(OPERATOR_LCURLY))
1199 go_error_at(token_loc, "unexpected semicolon or newline before %<{%>");
1200 else
1202 go_error_at(this->location(), "expected %<{%>");
1203 return Type::make_error_type();
1206 this->advance_token();
1208 Typed_identifier_list* methods = new Typed_identifier_list();
1209 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1211 this->method_spec(methods);
1212 while (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1214 if (this->advance_token()->is_op(OPERATOR_RCURLY))
1215 break;
1216 this->method_spec(methods);
1218 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1220 go_error_at(this->location(), "expected %<}%>");
1221 while (!this->advance_token()->is_op(OPERATOR_RCURLY))
1223 if (this->peek_token()->is_eof())
1224 return Type::make_error_type();
1228 this->advance_token();
1230 if (methods->empty())
1232 delete methods;
1233 methods = NULL;
1236 Interface_type* ret;
1237 if (methods == NULL)
1238 ret = Type::make_empty_interface_type(location);
1239 else
1240 ret = Type::make_interface_type(methods, location);
1241 if (record)
1242 this->gogo_->record_interface_type(ret);
1243 return ret;
1246 // MethodSpec = MethodName Signature | InterfaceTypeName .
1247 // MethodName = identifier .
1248 // InterfaceTypeName = TypeName .
1250 void
1251 Parse::method_spec(Typed_identifier_list* methods)
1253 const Token* token = this->peek_token();
1254 if (!token->is_identifier())
1256 go_error_at(this->location(), "expected identifier");
1257 return;
1260 std::string name = token->identifier();
1261 bool is_exported = token->is_identifier_exported();
1262 Location location = token->location();
1264 if (this->advance_token()->is_op(OPERATOR_LPAREN))
1266 // This is a MethodName.
1267 if (name == "_")
1268 go_error_at(this->location(),
1269 "methods must have a unique non-blank name");
1270 name = this->gogo_->pack_hidden_name(name, is_exported);
1271 Type* type = this->signature(NULL, location);
1272 if (type == NULL)
1273 return;
1274 methods->push_back(Typed_identifier(name, type, location));
1276 else
1278 this->unget_token(Token::make_identifier_token(name, is_exported,
1279 location));
1280 Type* type = this->type_name(false);
1281 if (type->is_error_type()
1282 || (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1283 && !this->peek_token()->is_op(OPERATOR_RCURLY)))
1285 if (this->peek_token()->is_op(OPERATOR_COMMA))
1286 go_error_at(this->location(),
1287 "name list not allowed in interface type");
1288 else
1289 go_error_at(location, "expected signature or type name");
1290 this->gogo_->mark_locals_used();
1291 token = this->peek_token();
1292 while (!token->is_eof()
1293 && !token->is_op(OPERATOR_SEMICOLON)
1294 && !token->is_op(OPERATOR_RCURLY))
1295 token = this->advance_token();
1296 return;
1298 // This must be an interface type, but we can't check that now.
1299 // We check it and pull out the methods in
1300 // Interface_type::do_verify.
1301 methods->push_back(Typed_identifier("", type, location));
1305 // Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1307 void
1308 Parse::declaration()
1310 const Token* token = this->peek_token();
1312 unsigned int pragmas = this->lex_->get_and_clear_pragmas();
1313 if (pragmas != 0
1314 && !token->is_keyword(KEYWORD_FUNC)
1315 && !token->is_keyword(KEYWORD_TYPE))
1316 go_warning_at(token->location(), 0,
1317 "ignoring magic comment before non-function");
1319 if (token->is_keyword(KEYWORD_CONST))
1320 this->const_decl();
1321 else if (token->is_keyword(KEYWORD_TYPE))
1322 this->type_decl(pragmas);
1323 else if (token->is_keyword(KEYWORD_VAR))
1324 this->var_decl();
1325 else if (token->is_keyword(KEYWORD_FUNC))
1326 this->function_decl(pragmas);
1327 else
1329 go_error_at(this->location(), "expected declaration");
1330 this->advance_token();
1334 bool
1335 Parse::declaration_may_start_here()
1337 const Token* token = this->peek_token();
1338 return (token->is_keyword(KEYWORD_CONST)
1339 || token->is_keyword(KEYWORD_TYPE)
1340 || token->is_keyword(KEYWORD_VAR)
1341 || token->is_keyword(KEYWORD_FUNC));
1344 // Decl<P> = P | "(" [ List<P> ] ")" .
1346 void
1347 Parse::decl(void (Parse::*pfn)(void*, unsigned int), void* varg,
1348 unsigned int pragmas)
1350 if (this->peek_token()->is_eof())
1352 if (!saw_errors())
1353 go_error_at(this->location(), "unexpected end of file");
1354 return;
1357 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1358 (this->*pfn)(varg, pragmas);
1359 else
1361 if (pragmas != 0)
1362 go_warning_at(this->location(), 0,
1363 "ignoring magic //go:... comment before group");
1364 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
1366 this->list(pfn, varg, true);
1367 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1369 go_error_at(this->location(), "missing %<)%>");
1370 while (!this->advance_token()->is_op(OPERATOR_RPAREN))
1372 if (this->peek_token()->is_eof())
1373 return;
1377 this->advance_token();
1381 // List<P> = P { ";" P } [ ";" ] .
1383 // In order to pick up the trailing semicolon we need to know what
1384 // might follow. This is either a '}' or a ')'.
1386 void
1387 Parse::list(void (Parse::*pfn)(void*, unsigned int), void* varg,
1388 bool follow_is_paren)
1390 (this->*pfn)(varg, 0);
1391 Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY;
1392 while (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1393 || this->peek_token()->is_op(OPERATOR_COMMA))
1395 if (this->peek_token()->is_op(OPERATOR_COMMA))
1396 go_error_at(this->location(), "unexpected comma");
1397 if (this->advance_token()->is_op(follow))
1398 break;
1399 (this->*pfn)(varg, 0);
1403 // ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1405 void
1406 Parse::const_decl()
1408 go_assert(this->peek_token()->is_keyword(KEYWORD_CONST));
1409 this->advance_token();
1410 this->reset_iota();
1412 Type* last_type = NULL;
1413 Expression_list* last_expr_list = NULL;
1415 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1416 this->const_spec(&last_type, &last_expr_list);
1417 else
1419 this->advance_token();
1420 while (!this->peek_token()->is_op(OPERATOR_RPAREN))
1422 this->const_spec(&last_type, &last_expr_list);
1423 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1424 this->advance_token();
1425 else if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1427 go_error_at(this->location(),
1428 "expected %<;%> or %<)%> or newline");
1429 if (!this->skip_past_error(OPERATOR_RPAREN))
1430 return;
1433 this->advance_token();
1436 if (last_expr_list != NULL)
1437 delete last_expr_list;
1440 // ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
1442 void
1443 Parse::const_spec(Type** last_type, Expression_list** last_expr_list)
1445 Typed_identifier_list til;
1446 this->identifier_list(&til);
1448 Type* type = NULL;
1449 if (this->type_may_start_here())
1451 type = this->type();
1452 *last_type = NULL;
1453 *last_expr_list = NULL;
1456 Expression_list *expr_list;
1457 if (!this->peek_token()->is_op(OPERATOR_EQ))
1459 if (*last_expr_list == NULL)
1461 go_error_at(this->location(), "expected %<=%>");
1462 return;
1464 type = *last_type;
1465 expr_list = new Expression_list;
1466 for (Expression_list::const_iterator p = (*last_expr_list)->begin();
1467 p != (*last_expr_list)->end();
1468 ++p)
1469 expr_list->push_back((*p)->copy());
1471 else
1473 this->advance_token();
1474 expr_list = this->expression_list(NULL, false, true);
1475 *last_type = type;
1476 if (*last_expr_list != NULL)
1477 delete *last_expr_list;
1478 *last_expr_list = expr_list;
1481 Expression_list::const_iterator pe = expr_list->begin();
1482 for (Typed_identifier_list::iterator pi = til.begin();
1483 pi != til.end();
1484 ++pi, ++pe)
1486 if (pe == expr_list->end())
1488 go_error_at(this->location(), "not enough initializers");
1489 return;
1491 if (type != NULL)
1492 pi->set_type(type);
1494 if (!Gogo::is_sink_name(pi->name()))
1495 this->gogo_->add_constant(*pi, *pe, this->iota_value());
1496 else
1498 static int count;
1499 char buf[30];
1500 snprintf(buf, sizeof buf, ".$sinkconst%d", count);
1501 ++count;
1502 Typed_identifier ti(std::string(buf), type, pi->location());
1503 Named_object* no = this->gogo_->add_constant(ti, *pe, this->iota_value());
1504 no->const_value()->set_is_sink();
1507 if (pe != expr_list->end())
1508 go_error_at(this->location(), "too many initializers");
1510 this->increment_iota();
1512 return;
1515 // TypeDecl = "type" Decl<TypeSpec> .
1517 void
1518 Parse::type_decl(unsigned int pragmas)
1520 go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE));
1521 this->advance_token();
1522 this->decl(&Parse::type_spec, NULL, pragmas);
1525 // TypeSpec = identifier ["="] Type .
1527 void
1528 Parse::type_spec(void*, unsigned int pragmas)
1530 const Token* token = this->peek_token();
1531 if (!token->is_identifier())
1533 go_error_at(this->location(), "expected identifier");
1534 return;
1536 std::string name = token->identifier();
1537 bool is_exported = token->is_identifier_exported();
1538 Location location = token->location();
1539 token = this->advance_token();
1541 bool is_alias = false;
1542 if (token->is_op(OPERATOR_EQ))
1544 is_alias = true;
1545 token = this->advance_token();
1548 // The scope of the type name starts at the point where the
1549 // identifier appears in the source code. We implement this by
1550 // declaring the type before we read the type definition.
1551 Named_object* named_type = NULL;
1552 if (name != "_")
1554 name = this->gogo_->pack_hidden_name(name, is_exported);
1555 named_type = this->gogo_->declare_type(name, location);
1558 Type* type;
1559 if (name == "_" && token->is_keyword(KEYWORD_INTERFACE))
1561 // We call Parse::interface_type explicity here because we do not want
1562 // to record an interface with a blank type name.
1563 type = this->interface_type(false);
1565 else if (!token->is_op(OPERATOR_SEMICOLON))
1566 type = this->type();
1567 else
1569 go_error_at(this->location(),
1570 "unexpected semicolon or newline in type declaration");
1571 type = Type::make_error_type();
1572 this->advance_token();
1575 if (type->is_error_type())
1577 this->gogo_->mark_locals_used();
1578 while (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1579 && !this->peek_token()->is_eof())
1580 this->advance_token();
1583 if (name != "_")
1585 if (named_type->is_type_declaration())
1587 Type* ftype = type->forwarded();
1588 if (ftype->forward_declaration_type() != NULL
1589 && (ftype->forward_declaration_type()->named_object()
1590 == named_type))
1592 go_error_at(location, "invalid recursive type");
1593 type = Type::make_error_type();
1596 Named_type* nt = Type::make_named_type(named_type, type, location);
1597 if (is_alias)
1598 nt->set_is_alias();
1600 this->gogo_->define_type(named_type, nt);
1601 go_assert(named_type->package() == NULL);
1603 if ((pragmas & GOPRAGMA_NOTINHEAP) != 0)
1605 nt->set_not_in_heap();
1606 pragmas &= ~GOPRAGMA_NOTINHEAP;
1608 if (pragmas != 0)
1609 go_warning_at(location, 0,
1610 "ignoring magic //go:... comment before type");
1612 else
1614 // This will probably give a redefinition error.
1615 this->gogo_->add_type(name, type, location);
1620 // VarDecl = "var" Decl<VarSpec> .
1622 void
1623 Parse::var_decl()
1625 go_assert(this->peek_token()->is_keyword(KEYWORD_VAR));
1626 this->advance_token();
1627 this->decl(&Parse::var_spec, NULL, 0);
1630 // VarSpec = IdentifierList
1631 // ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
1633 void
1634 Parse::var_spec(void*, unsigned int pragmas)
1636 if (pragmas != 0)
1637 go_warning_at(this->location(), 0,
1638 "ignoring magic //go:... comment before var");
1640 // Get the variable names.
1641 Typed_identifier_list til;
1642 this->identifier_list(&til);
1644 Location location = this->location();
1646 Type* type = NULL;
1647 Expression_list* init = NULL;
1648 if (!this->peek_token()->is_op(OPERATOR_EQ))
1650 type = this->type();
1651 if (type->is_error_type())
1653 this->gogo_->mark_locals_used();
1654 while (!this->peek_token()->is_op(OPERATOR_EQ)
1655 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
1656 && !this->peek_token()->is_eof())
1657 this->advance_token();
1659 if (this->peek_token()->is_op(OPERATOR_EQ))
1661 this->advance_token();
1662 init = this->expression_list(NULL, false, true);
1665 else
1667 this->advance_token();
1668 init = this->expression_list(NULL, false, true);
1671 this->init_vars(&til, type, init, false, location);
1673 if (init != NULL)
1674 delete init;
1677 // Create variables. TIL is a list of variable names. If TYPE is not
1678 // NULL, it is the type of all the variables. If INIT is not NULL, it
1679 // is an initializer list for the variables.
1681 void
1682 Parse::init_vars(const Typed_identifier_list* til, Type* type,
1683 Expression_list* init, bool is_coloneq,
1684 Location location)
1686 // Check for an initialization which can yield multiple values.
1687 if (init != NULL && init->size() == 1 && til->size() > 1)
1689 if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq,
1690 location))
1691 return;
1692 if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq,
1693 location))
1694 return;
1695 if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq,
1696 location))
1697 return;
1698 if (this->init_vars_from_type_guard(til, type, *init->begin(),
1699 is_coloneq, location))
1700 return;
1703 if (init != NULL && init->size() != til->size())
1705 if (init->empty() || !init->front()->is_error_expression())
1706 go_error_at(location, "wrong number of initializations");
1707 init = NULL;
1708 if (type == NULL)
1709 type = Type::make_error_type();
1712 // Note that INIT was already parsed with the old name bindings, so
1713 // we don't have to worry that it will accidentally refer to the
1714 // newly declared variables. But we do have to worry about a mix of
1715 // newly declared variables and old variables if the old variables
1716 // appear in the initializations.
1718 Expression_list::const_iterator pexpr;
1719 if (init != NULL)
1720 pexpr = init->begin();
1721 bool any_new = false;
1722 Expression_list* vars = new Expression_list();
1723 Expression_list* vals = new Expression_list();
1724 for (Typed_identifier_list::const_iterator p = til->begin();
1725 p != til->end();
1726 ++p)
1728 if (init != NULL)
1729 go_assert(pexpr != init->end());
1730 this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq,
1731 false, &any_new, vars, vals);
1732 if (init != NULL)
1733 ++pexpr;
1735 if (init != NULL)
1736 go_assert(pexpr == init->end());
1737 if (is_coloneq && !any_new)
1738 go_error_at(location, "variables redeclared but no variable is new");
1739 this->finish_init_vars(vars, vals, location);
1742 // See if we need to initialize a list of variables from a function
1743 // call. This returns true if we have set up the variables and the
1744 // initialization.
1746 bool
1747 Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type,
1748 Expression* expr, bool is_coloneq,
1749 Location location)
1751 Call_expression* call = expr->call_expression();
1752 if (call == NULL)
1753 return false;
1755 // This is a function call. We can't check here whether it returns
1756 // the right number of values, but it might. Declare the variables,
1757 // and then assign the results of the call to them.
1759 call->set_expected_result_count(vars->size());
1761 Named_object* first_var = NULL;
1762 unsigned int index = 0;
1763 bool any_new = false;
1764 Expression_list* ivars = new Expression_list();
1765 Expression_list* ivals = new Expression_list();
1766 for (Typed_identifier_list::const_iterator pv = vars->begin();
1767 pv != vars->end();
1768 ++pv, ++index)
1770 Expression* init = Expression::make_call_result(call, index);
1771 Named_object* no = this->init_var(*pv, type, init, is_coloneq, false,
1772 &any_new, ivars, ivals);
1774 if (this->gogo_->in_global_scope() && no->is_variable())
1776 if (first_var == NULL)
1777 first_var = no;
1778 else
1780 // If the current object is a redefinition of another object, we
1781 // might have already recorded the dependency relationship between
1782 // it and the first variable. Either way, an error will be
1783 // reported for the redefinition and we don't need to properly
1784 // record dependency information for an invalid program.
1785 if (no->is_redefinition())
1786 continue;
1788 // The subsequent vars have an implicit dependency on
1789 // the first one, so that everything gets initialized in
1790 // the right order and so that we detect cycles
1791 // correctly.
1792 this->gogo_->record_var_depends_on(no->var_value(), first_var);
1797 if (is_coloneq && !any_new)
1798 go_error_at(location, "variables redeclared but no variable is new");
1800 this->finish_init_vars(ivars, ivals, location);
1802 return true;
1805 // See if we need to initialize a pair of values from a map index
1806 // expression. This returns true if we have set up the variables and
1807 // the initialization.
1809 bool
1810 Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type,
1811 Expression* expr, bool is_coloneq,
1812 Location location)
1814 Index_expression* index = expr->index_expression();
1815 if (index == NULL)
1816 return false;
1817 if (vars->size() != 2)
1818 return false;
1820 // This is an index which is being assigned to two variables. It
1821 // must be a map index. Declare the variables, and then assign the
1822 // results of the map index.
1823 bool any_new = false;
1824 Typed_identifier_list::const_iterator p = vars->begin();
1825 Expression* init = type == NULL ? index : NULL;
1826 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1827 type == NULL, &any_new, NULL, NULL);
1828 if (type == NULL && any_new && val_no->is_variable())
1829 val_no->var_value()->set_type_from_init_tuple();
1830 Expression* val_var = Expression::make_var_reference(val_no, location);
1832 ++p;
1833 Type* var_type = type;
1834 if (var_type == NULL)
1835 var_type = Type::lookup_bool_type();
1836 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1837 &any_new, NULL, NULL);
1838 Expression* present_var = Expression::make_var_reference(no, location);
1840 if (is_coloneq && !any_new)
1841 go_error_at(location, "variables redeclared but no variable is new");
1843 Statement* s = Statement::make_tuple_map_assignment(val_var, present_var,
1844 index, location);
1846 if (!this->gogo_->in_global_scope())
1847 this->gogo_->add_statement(s);
1848 else if (!val_no->is_sink())
1850 if (val_no->is_variable())
1851 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1853 else if (!no->is_sink())
1855 if (no->is_variable())
1856 no->var_value()->add_preinit_statement(this->gogo_, s);
1858 else
1860 // Execute the map index expression just so that we can fail if
1861 // the map is nil.
1862 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1863 NULL, location);
1864 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1867 return true;
1870 // See if we need to initialize a pair of values from a receive
1871 // expression. This returns true if we have set up the variables and
1872 // the initialization.
1874 bool
1875 Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type,
1876 Expression* expr, bool is_coloneq,
1877 Location location)
1879 Receive_expression* receive = expr->receive_expression();
1880 if (receive == NULL)
1881 return false;
1882 if (vars->size() != 2)
1883 return false;
1885 // This is a receive expression which is being assigned to two
1886 // variables. Declare the variables, and then assign the results of
1887 // the receive.
1888 bool any_new = false;
1889 Typed_identifier_list::const_iterator p = vars->begin();
1890 Expression* init = type == NULL ? receive : NULL;
1891 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1892 type == NULL, &any_new, NULL, NULL);
1893 if (type == NULL && any_new && val_no->is_variable())
1894 val_no->var_value()->set_type_from_init_tuple();
1895 Expression* val_var = Expression::make_var_reference(val_no, location);
1897 ++p;
1898 Type* var_type = type;
1899 if (var_type == NULL)
1900 var_type = Type::lookup_bool_type();
1901 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1902 &any_new, NULL, NULL);
1903 Expression* received_var = Expression::make_var_reference(no, location);
1905 if (is_coloneq && !any_new)
1906 go_error_at(location, "variables redeclared but no variable is new");
1908 Statement* s = Statement::make_tuple_receive_assignment(val_var,
1909 received_var,
1910 receive->channel(),
1911 location);
1913 if (!this->gogo_->in_global_scope())
1914 this->gogo_->add_statement(s);
1915 else if (!val_no->is_sink())
1917 if (val_no->is_variable())
1918 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1920 else if (!no->is_sink())
1922 if (no->is_variable())
1923 no->var_value()->add_preinit_statement(this->gogo_, s);
1925 else
1927 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1928 NULL, location);
1929 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1932 return true;
1935 // See if we need to initialize a pair of values from a type guard
1936 // expression. This returns true if we have set up the variables and
1937 // the initialization.
1939 bool
1940 Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
1941 Type* type, Expression* expr,
1942 bool is_coloneq, Location location)
1944 Type_guard_expression* type_guard = expr->type_guard_expression();
1945 if (type_guard == NULL)
1946 return false;
1947 if (vars->size() != 2)
1948 return false;
1950 // This is a type guard expression which is being assigned to two
1951 // variables. Declare the variables, and then assign the results of
1952 // the type guard.
1953 bool any_new = false;
1954 Typed_identifier_list::const_iterator p = vars->begin();
1955 Type* var_type = type;
1956 if (var_type == NULL)
1957 var_type = type_guard->type();
1958 Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1959 &any_new, NULL, NULL);
1960 Expression* val_var = Expression::make_var_reference(val_no, location);
1962 ++p;
1963 var_type = type;
1964 if (var_type == NULL)
1965 var_type = Type::lookup_bool_type();
1966 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1967 &any_new, NULL, NULL);
1968 Expression* ok_var = Expression::make_var_reference(no, location);
1970 Expression* texpr = type_guard->expr();
1971 Type* t = type_guard->type();
1972 Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
1973 texpr, t,
1974 location);
1976 if (is_coloneq && !any_new)
1977 go_error_at(location, "variables redeclared but no variable is new");
1979 if (!this->gogo_->in_global_scope())
1980 this->gogo_->add_statement(s);
1981 else if (!val_no->is_sink())
1983 if (val_no->is_variable())
1984 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1986 else if (!no->is_sink())
1988 if (no->is_variable())
1989 no->var_value()->add_preinit_statement(this->gogo_, s);
1991 else
1993 Named_object* dummy = this->create_dummy_global(type, NULL, location);
1994 dummy->var_value()->add_preinit_statement(this->gogo_, s);
1997 return true;
2000 // Create a single variable. If IS_COLONEQ is true, we permit
2001 // redeclarations in the same block, and we set *IS_NEW when we find a
2002 // new variable which is not a redeclaration.
2004 Named_object*
2005 Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
2006 bool is_coloneq, bool type_from_init, bool* is_new,
2007 Expression_list* vars, Expression_list* vals)
2009 Location location = tid.location();
2011 if (Gogo::is_sink_name(tid.name()))
2013 if (!type_from_init && init != NULL)
2015 if (this->gogo_->in_global_scope())
2016 return this->create_dummy_global(type, init, location);
2017 else
2019 // Create a dummy variable so that we will check whether the
2020 // initializer can be assigned to the type.
2021 Variable* var = new Variable(type, init, false, false, false,
2022 location);
2023 var->set_is_used();
2024 static int count;
2025 char buf[30];
2026 snprintf(buf, sizeof buf, "sink$%d", count);
2027 ++count;
2028 return this->gogo_->add_variable(buf, var);
2031 if (type != NULL)
2032 this->gogo_->add_type_to_verify(type);
2033 return this->gogo_->add_sink();
2036 if (is_coloneq)
2038 Named_object* no = this->gogo_->lookup_in_block(tid.name());
2039 if (no != NULL
2040 && (no->is_variable() || no->is_result_variable()))
2042 // INIT may be NULL even when IS_COLONEQ is true for cases
2043 // like v, ok := x.(int).
2044 if (!type_from_init && init != NULL)
2046 go_assert(vars != NULL && vals != NULL);
2047 vars->push_back(Expression::make_var_reference(no, location));
2048 vals->push_back(init);
2050 return no;
2053 *is_new = true;
2054 Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
2055 false, false, location);
2056 Named_object* no = this->gogo_->add_variable(tid.name(), var);
2057 if (!no->is_variable())
2059 // The name is already defined, so we just gave an error.
2060 return this->gogo_->add_sink();
2062 return no;
2065 // Create a dummy global variable to force an initializer to be run in
2066 // the right place. This is used when a sink variable is initialized
2067 // at global scope.
2069 Named_object*
2070 Parse::create_dummy_global(Type* type, Expression* init,
2071 Location location)
2073 if (type == NULL && init == NULL)
2074 type = Type::lookup_bool_type();
2075 Variable* var = new Variable(type, init, true, false, false, location);
2076 static int count;
2077 char buf[30];
2078 snprintf(buf, sizeof buf, "_.%d", count);
2079 ++count;
2080 return this->gogo_->add_variable(buf, var);
2083 // Finish the variable initialization by executing any assignments to
2084 // existing variables when using :=. These must be done as a tuple
2085 // assignment in case of something like n, a, b := 1, b, a.
2087 void
2088 Parse::finish_init_vars(Expression_list* vars, Expression_list* vals,
2089 Location location)
2091 if (vars->empty())
2093 delete vars;
2094 delete vals;
2096 else if (vars->size() == 1)
2098 go_assert(!this->gogo_->in_global_scope());
2099 this->gogo_->add_statement(Statement::make_assignment(vars->front(),
2100 vals->front(),
2101 location));
2102 delete vars;
2103 delete vals;
2105 else
2107 go_assert(!this->gogo_->in_global_scope());
2108 this->gogo_->add_statement(Statement::make_tuple_assignment(vars, vals,
2109 location));
2113 // SimpleVarDecl = identifier ":=" Expression .
2115 // We've already seen the identifier.
2117 // FIXME: We also have to implement
2118 // IdentifierList ":=" ExpressionList
2119 // In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
2120 // tuple assignments here as well.
2122 // If MAY_BE_COMPOSITE_LIT is true, the expression on the right hand
2123 // side may be a composite literal.
2125 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
2126 // RangeClause.
2128 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
2129 // guard (var := expr.("type") using the literal keyword "type").
2131 void
2132 Parse::simple_var_decl_or_assignment(const std::string& name,
2133 Location location,
2134 bool may_be_composite_lit,
2135 Range_clause* p_range_clause,
2136 Type_switch* p_type_switch)
2138 Typed_identifier_list til;
2139 til.push_back(Typed_identifier(name, NULL, location));
2141 std::set<std::string> uniq_idents;
2142 uniq_idents.insert(name);
2143 std::string dup_name;
2144 Location dup_loc;
2146 // We've seen one identifier. If we see a comma now, this could be
2147 // "a, *p = 1, 2".
2148 if (this->peek_token()->is_op(OPERATOR_COMMA))
2150 go_assert(p_type_switch == NULL);
2151 while (true)
2153 const Token* token = this->advance_token();
2154 if (!token->is_identifier())
2155 break;
2157 std::string id = token->identifier();
2158 bool is_id_exported = token->is_identifier_exported();
2159 Location id_location = token->location();
2160 std::pair<std::set<std::string>::iterator, bool> ins;
2162 token = this->advance_token();
2163 if (!token->is_op(OPERATOR_COMMA))
2165 if (token->is_op(OPERATOR_COLONEQ))
2167 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2168 ins = uniq_idents.insert(id);
2169 if (!ins.second && !Gogo::is_sink_name(id))
2170 go_error_at(id_location, "multiple assignments to %s",
2171 Gogo::message_name(id).c_str());
2172 til.push_back(Typed_identifier(id, NULL, location));
2174 else
2175 this->unget_token(Token::make_identifier_token(id,
2176 is_id_exported,
2177 id_location));
2178 break;
2181 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2182 ins = uniq_idents.insert(id);
2183 if (!ins.second && !Gogo::is_sink_name(id))
2185 dup_name = Gogo::message_name(id);
2186 dup_loc = id_location;
2188 til.push_back(Typed_identifier(id, NULL, location));
2191 // We have a comma separated list of identifiers in TIL. If the
2192 // next token is COLONEQ, then this is a simple var decl, and we
2193 // have the complete list of identifiers. If the next token is
2194 // not COLONEQ, then the only valid parse is a tuple assignment.
2195 // The list of identifiers we have so far is really a list of
2196 // expressions. There are more expressions following.
2198 if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
2200 Expression_list* exprs = new Expression_list;
2201 for (Typed_identifier_list::const_iterator p = til.begin();
2202 p != til.end();
2203 ++p)
2204 exprs->push_back(this->id_to_expression(p->name(), p->location(),
2205 true));
2207 Expression_list* more_exprs =
2208 this->expression_list(NULL, true, may_be_composite_lit);
2209 for (Expression_list::const_iterator p = more_exprs->begin();
2210 p != more_exprs->end();
2211 ++p)
2212 exprs->push_back(*p);
2213 delete more_exprs;
2215 this->tuple_assignment(exprs, may_be_composite_lit, p_range_clause);
2216 return;
2220 go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
2221 const Token* token = this->advance_token();
2223 if (!dup_name.empty())
2224 go_error_at(dup_loc, "multiple assignments to %s", dup_name.c_str());
2226 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
2228 this->range_clause_decl(&til, p_range_clause);
2229 return;
2232 Expression_list* init;
2233 if (p_type_switch == NULL)
2234 init = this->expression_list(NULL, false, may_be_composite_lit);
2235 else
2237 bool is_type_switch = false;
2238 Expression* expr = this->expression(PRECEDENCE_NORMAL, false,
2239 may_be_composite_lit,
2240 &is_type_switch, NULL);
2241 if (is_type_switch)
2243 p_type_switch->found = true;
2244 p_type_switch->name = name;
2245 p_type_switch->location = location;
2246 p_type_switch->expr = expr;
2247 return;
2250 if (!this->peek_token()->is_op(OPERATOR_COMMA))
2252 init = new Expression_list();
2253 init->push_back(expr);
2255 else
2257 this->advance_token();
2258 init = this->expression_list(expr, false, may_be_composite_lit);
2262 this->init_vars(&til, NULL, init, true, location);
2265 // FunctionDecl = "func" identifier Signature [ Block ] .
2266 // MethodDecl = "func" Receiver identifier Signature [ Block ] .
2268 // Deprecated gcc extension:
2269 // FunctionDecl = "func" identifier Signature
2270 // __asm__ "(" string_lit ")" .
2271 // This extension means a function whose real name is the identifier
2272 // inside the asm. This extension will be removed at some future
2273 // date. It has been replaced with //extern or //go:linkname comments.
2275 // PRAGMAS is a bitset of magic comments.
2277 void
2278 Parse::function_decl(unsigned int pragmas)
2280 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2281 Location location = this->location();
2282 std::string extern_name = this->lex_->extern_name();
2283 const Token* token = this->advance_token();
2285 bool expected_receiver = false;
2286 Typed_identifier* rec = NULL;
2287 if (token->is_op(OPERATOR_LPAREN))
2289 expected_receiver = true;
2290 rec = this->receiver();
2291 token = this->peek_token();
2294 if (!token->is_identifier())
2296 go_error_at(this->location(), "expected function name");
2297 return;
2300 std::string name =
2301 this->gogo_->pack_hidden_name(token->identifier(),
2302 token->is_identifier_exported());
2304 this->advance_token();
2306 Function_type* fntype = this->signature(rec, this->location());
2308 Named_object* named_object = NULL;
2310 if (this->peek_token()->is_keyword(KEYWORD_ASM))
2312 if (!this->advance_token()->is_op(OPERATOR_LPAREN))
2314 go_error_at(this->location(), "expected %<(%>");
2315 return;
2317 token = this->advance_token();
2318 if (!token->is_string())
2320 go_error_at(this->location(), "expected string");
2321 return;
2323 std::string asm_name = token->string_value();
2324 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
2326 go_error_at(this->location(), "expected %<)%>");
2327 return;
2329 this->advance_token();
2330 if (!Gogo::is_sink_name(name))
2332 named_object = this->gogo_->declare_function(name, fntype, location);
2333 if (named_object->is_function_declaration())
2334 named_object->func_declaration_value()->set_asm_name(asm_name);
2338 // Check for the easy error of a newline before the opening brace.
2339 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
2341 Location semi_loc = this->location();
2342 if (this->advance_token()->is_op(OPERATOR_LCURLY))
2343 go_error_at(this->location(),
2344 "unexpected semicolon or newline before %<{%>");
2345 else
2346 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
2347 semi_loc));
2350 static struct {
2351 unsigned int bit;
2352 const char* name;
2353 bool decl_ok;
2354 bool func_ok;
2355 bool method_ok;
2356 } pragma_check[] =
2358 { GOPRAGMA_NOINTERFACE, "nointerface", false, false, true },
2359 { GOPRAGMA_NOESCAPE, "noescape", true, false, false },
2360 { GOPRAGMA_NORACE, "norace", false, true, true },
2361 { GOPRAGMA_NOSPLIT, "nosplit", false, true, true },
2362 { GOPRAGMA_NOINLINE, "noinline", false, true, true },
2363 { GOPRAGMA_SYSTEMSTACK, "systemstack", false, true, true },
2364 { GOPRAGMA_NOWRITEBARRIER, "nowritebarrier", false, true, true },
2365 { GOPRAGMA_NOWRITEBARRIERREC, "nowritebarrierrec", false, true, true },
2366 { GOPRAGMA_CGOUNSAFEARGS, "cgo_unsafe_args", false, true, true },
2367 { GOPRAGMA_UINTPTRESCAPES, "uintptrescapes", true, true, true },
2370 bool is_decl = !this->peek_token()->is_op(OPERATOR_LCURLY);
2371 if (pragmas != 0)
2373 for (size_t i = 0;
2374 i < sizeof(pragma_check) / sizeof(pragma_check[0]);
2375 ++i)
2377 if ((pragmas & pragma_check[i].bit) == 0)
2378 continue;
2380 if (is_decl)
2382 if (pragma_check[i].decl_ok)
2383 continue;
2384 go_warning_at(location, 0,
2385 ("ignoring magic //go:%s comment "
2386 "before declaration"),
2387 pragma_check[i].name);
2389 else if (rec == NULL)
2391 if (pragma_check[i].func_ok)
2392 continue;
2393 go_warning_at(location, 0,
2394 ("ignoring magic //go:%s comment "
2395 "before function definition"),
2396 pragma_check[i].name);
2398 else
2400 if (pragma_check[i].method_ok)
2401 continue;
2402 go_warning_at(location, 0,
2403 ("ignoring magic //go:%s comment "
2404 "before method definition"),
2405 pragma_check[i].name);
2408 pragmas &= ~ pragma_check[i].bit;
2412 if (is_decl)
2414 if (named_object == NULL)
2416 // Function declarations with the blank identifier as a name are
2417 // mostly ignored since they cannot be called. We make an object
2418 // for this declaration for type-checking purposes.
2419 if (Gogo::is_sink_name(name))
2421 static int count;
2422 char buf[30];
2423 snprintf(buf, sizeof buf, ".$sinkfndecl%d", count);
2424 ++count;
2425 name = std::string(buf);
2428 if (fntype == NULL
2429 || (expected_receiver && rec == NULL))
2430 this->gogo_->add_erroneous_name(name);
2431 else
2433 named_object = this->gogo_->declare_function(name, fntype,
2434 location);
2435 if (!extern_name.empty()
2436 && named_object->is_function_declaration())
2438 Function_declaration* fd =
2439 named_object->func_declaration_value();
2440 fd->set_asm_name(extern_name);
2445 if (pragmas != 0 && named_object->is_function_declaration())
2446 named_object->func_declaration_value()->set_pragmas(pragmas);
2448 else
2450 bool hold_is_erroneous_function = this->is_erroneous_function_;
2451 if (fntype == NULL)
2453 fntype = Type::make_function_type(NULL, NULL, NULL, location);
2454 this->is_erroneous_function_ = true;
2455 if (!Gogo::is_sink_name(name))
2456 this->gogo_->add_erroneous_name(name);
2457 name = this->gogo_->pack_hidden_name("_", false);
2459 named_object = this->gogo_->start_function(name, fntype, true, location);
2460 Location end_loc = this->block();
2461 this->gogo_->finish_function(end_loc);
2463 if (pragmas != 0
2464 && !this->is_erroneous_function_
2465 && named_object->is_function())
2466 named_object->func_value()->set_pragmas(pragmas);
2467 this->is_erroneous_function_ = hold_is_erroneous_function;
2471 // Receiver = Parameters .
2473 Typed_identifier*
2474 Parse::receiver()
2476 Location location = this->location();
2477 Typed_identifier_list* til;
2478 if (!this->parameters(&til, NULL))
2479 return NULL;
2480 else if (til == NULL || til->empty())
2482 go_error_at(location, "method has no receiver");
2483 return NULL;
2485 else if (til->size() > 1)
2487 go_error_at(location, "method has multiple receivers");
2488 return NULL;
2490 else
2491 return &til->front();
2494 // Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2495 // Literal = BasicLit | CompositeLit | FunctionLit .
2496 // BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2498 // If MAY_BE_SINK is true, this operand may be "_".
2500 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
2501 // if the entire expression is in parentheses.
2503 Expression*
2504 Parse::operand(bool may_be_sink, bool* is_parenthesized)
2506 const Token* token = this->peek_token();
2507 Expression* ret;
2508 switch (token->classification())
2510 case Token::TOKEN_IDENTIFIER:
2512 Location location = token->location();
2513 std::string id = token->identifier();
2514 bool is_exported = token->is_identifier_exported();
2515 std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2517 Named_object* in_function;
2518 Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2520 Package* package = NULL;
2521 if (named_object != NULL && named_object->is_package())
2523 if (!this->advance_token()->is_op(OPERATOR_DOT)
2524 || !this->advance_token()->is_identifier())
2526 go_error_at(location, "unexpected reference to package");
2527 return Expression::make_error(location);
2529 package = named_object->package_value();
2530 package->note_usage(id);
2531 id = this->peek_token()->identifier();
2532 is_exported = this->peek_token()->is_identifier_exported();
2533 packed = this->gogo_->pack_hidden_name(id, is_exported);
2534 named_object = package->lookup(packed);
2535 location = this->location();
2536 go_assert(in_function == NULL);
2539 this->advance_token();
2541 if (named_object != NULL
2542 && named_object->is_type()
2543 && !named_object->type_value()->is_visible())
2545 go_assert(package != NULL);
2546 go_error_at(location, "invalid reference to hidden type %<%s.%s%>",
2547 Gogo::message_name(package->package_name()).c_str(),
2548 Gogo::message_name(id).c_str());
2549 return Expression::make_error(location);
2553 if (named_object == NULL)
2555 if (package != NULL)
2557 std::string n1 = Gogo::message_name(package->package_name());
2558 std::string n2 = Gogo::message_name(id);
2559 if (!is_exported)
2560 go_error_at(location,
2561 ("invalid reference to unexported identifier "
2562 "%<%s.%s%>"),
2563 n1.c_str(), n2.c_str());
2564 else
2565 go_error_at(location,
2566 "reference to undefined identifier %<%s.%s%>",
2567 n1.c_str(), n2.c_str());
2568 return Expression::make_error(location);
2571 named_object = this->gogo_->add_unknown_name(packed, location);
2574 if (in_function != NULL
2575 && in_function != this->gogo_->current_function()
2576 && (named_object->is_variable()
2577 || named_object->is_result_variable()))
2578 return this->enclosing_var_reference(in_function, named_object,
2579 may_be_sink, location);
2581 switch (named_object->classification())
2583 case Named_object::NAMED_OBJECT_CONST:
2584 return Expression::make_const_reference(named_object, location);
2585 case Named_object::NAMED_OBJECT_TYPE:
2586 return Expression::make_type(named_object->type_value(), location);
2587 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2589 Type* t = Type::make_forward_declaration(named_object);
2590 return Expression::make_type(t, location);
2592 case Named_object::NAMED_OBJECT_VAR:
2593 case Named_object::NAMED_OBJECT_RESULT_VAR:
2594 // Any left-hand-side can be a sink, so if this can not be
2595 // a sink, then it must be a use of the variable.
2596 if (!may_be_sink)
2597 this->mark_var_used(named_object);
2598 return Expression::make_var_reference(named_object, location);
2599 case Named_object::NAMED_OBJECT_SINK:
2600 if (may_be_sink)
2601 return Expression::make_sink(location);
2602 else
2604 go_error_at(location, "cannot use _ as value");
2605 return Expression::make_error(location);
2607 case Named_object::NAMED_OBJECT_FUNC:
2608 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2609 return Expression::make_func_reference(named_object, NULL,
2610 location);
2611 case Named_object::NAMED_OBJECT_UNKNOWN:
2613 Unknown_expression* ue =
2614 Expression::make_unknown_reference(named_object, location);
2615 if (this->is_erroneous_function_)
2616 ue->set_no_error_message();
2617 return ue;
2619 case Named_object::NAMED_OBJECT_ERRONEOUS:
2620 return Expression::make_error(location);
2621 default:
2622 go_unreachable();
2625 go_unreachable();
2627 case Token::TOKEN_STRING:
2628 ret = Expression::make_string(token->string_value(), token->location());
2629 this->advance_token();
2630 return ret;
2632 case Token::TOKEN_CHARACTER:
2633 ret = Expression::make_character(token->character_value(), NULL,
2634 token->location());
2635 this->advance_token();
2636 return ret;
2638 case Token::TOKEN_INTEGER:
2639 ret = Expression::make_integer_z(token->integer_value(), NULL,
2640 token->location());
2641 this->advance_token();
2642 return ret;
2644 case Token::TOKEN_FLOAT:
2645 ret = Expression::make_float(token->float_value(), NULL,
2646 token->location());
2647 this->advance_token();
2648 return ret;
2650 case Token::TOKEN_IMAGINARY:
2652 mpfr_t zero;
2653 mpfr_init_set_ui(zero, 0, GMP_RNDN);
2654 mpc_t val;
2655 mpc_init2(val, mpc_precision);
2656 mpc_set_fr_fr(val, zero, *token->imaginary_value(), MPC_RNDNN);
2657 mpfr_clear(zero);
2658 ret = Expression::make_complex(&val, NULL, token->location());
2659 mpc_clear(val);
2660 this->advance_token();
2661 return ret;
2664 case Token::TOKEN_KEYWORD:
2665 switch (token->keyword())
2667 case KEYWORD_FUNC:
2668 return this->function_lit();
2669 case KEYWORD_CHAN:
2670 case KEYWORD_INTERFACE:
2671 case KEYWORD_MAP:
2672 case KEYWORD_STRUCT:
2674 Location location = token->location();
2675 return Expression::make_type(this->type(), location);
2677 default:
2678 break;
2680 break;
2682 case Token::TOKEN_OPERATOR:
2683 if (token->is_op(OPERATOR_LPAREN))
2685 this->advance_token();
2686 ret = this->expression(PRECEDENCE_NORMAL, may_be_sink, true, NULL,
2687 NULL);
2688 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2689 go_error_at(this->location(), "missing %<)%>");
2690 else
2691 this->advance_token();
2692 if (is_parenthesized != NULL)
2693 *is_parenthesized = true;
2694 return ret;
2696 else if (token->is_op(OPERATOR_LSQUARE))
2698 // Here we call array_type directly, as this is the only
2699 // case where an ellipsis is permitted for an array type.
2700 Location location = token->location();
2701 return Expression::make_type(this->array_type(true), location);
2703 break;
2705 default:
2706 break;
2709 go_error_at(this->location(), "expected operand");
2710 return Expression::make_error(this->location());
2713 // Handle a reference to a variable in an enclosing function. We add
2714 // it to a list of such variables. We return a reference to a field
2715 // in a struct which will be passed on the static chain when calling
2716 // the current function.
2718 Expression*
2719 Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2720 bool may_be_sink, Location location)
2722 go_assert(var->is_variable() || var->is_result_variable());
2724 // Any left-hand-side can be a sink, so if this can not be
2725 // a sink, then it must be a use of the variable.
2726 if (!may_be_sink)
2727 this->mark_var_used(var);
2729 Named_object* this_function = this->gogo_->current_function();
2730 Named_object* closure = this_function->func_value()->closure_var();
2732 // The last argument to the Enclosing_var constructor is the index
2733 // of this variable in the closure. We add 1 to the current number
2734 // of enclosed variables, because the first field in the closure
2735 // points to the function code.
2736 Enclosing_var ev(var, in_function, this->enclosing_vars_.size() + 1);
2737 std::pair<Enclosing_vars::iterator, bool> ins =
2738 this->enclosing_vars_.insert(ev);
2739 if (ins.second)
2741 // This is a variable we have not seen before. Add a new field
2742 // to the closure type.
2743 this_function->func_value()->add_closure_field(var, location);
2746 Expression* closure_ref = Expression::make_var_reference(closure,
2747 location);
2748 closure_ref =
2749 Expression::make_dereference(closure_ref,
2750 Expression::NIL_CHECK_NOT_NEEDED,
2751 location);
2753 // The closure structure holds pointers to the variables, so we need
2754 // to introduce an indirection.
2755 Expression* e = Expression::make_field_reference(closure_ref,
2756 ins.first->index(),
2757 location);
2758 e = Expression::make_dereference(e, Expression::NIL_CHECK_NOT_NEEDED,
2759 location);
2760 return Expression::make_enclosing_var_reference(e, var, location);
2763 // CompositeLit = LiteralType LiteralValue .
2764 // LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
2765 // SliceType | MapType | TypeName .
2766 // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
2767 // ElementList = Element { "," Element } .
2768 // Element = [ Key ":" ] Value .
2769 // Key = FieldName | ElementIndex .
2770 // FieldName = identifier .
2771 // ElementIndex = Expression .
2772 // Value = Expression | LiteralValue .
2774 // We have already seen the type if there is one, and we are now
2775 // looking at the LiteralValue. The case "[" "..." "]" ElementType
2776 // will be seen here as an array type whose length is "nil". The
2777 // DEPTH parameter is non-zero if this is an embedded composite
2778 // literal and the type was omitted. It gives the number of steps up
2779 // to the type which was provided. E.g., in [][]int{{1}} it will be
2780 // 1. In [][][]int{{{1}}} it will be 2.
2782 Expression*
2783 Parse::composite_lit(Type* type, int depth, Location location)
2785 go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2786 this->advance_token();
2788 if (this->peek_token()->is_op(OPERATOR_RCURLY))
2790 this->advance_token();
2791 return Expression::make_composite_literal(type, depth, false, NULL,
2792 false, location);
2795 bool has_keys = false;
2796 bool all_are_names = true;
2797 Expression_list* vals = new Expression_list;
2798 while (true)
2800 Expression* val;
2801 bool is_type_omitted = false;
2802 bool is_name = false;
2804 const Token* token = this->peek_token();
2806 if (token->is_identifier())
2808 std::string identifier = token->identifier();
2809 bool is_exported = token->is_identifier_exported();
2810 Location location = token->location();
2812 if (this->advance_token()->is_op(OPERATOR_COLON))
2814 // This may be a field name. We don't know for sure--it
2815 // could also be an expression for an array index. We
2816 // don't want to parse it as an expression because may
2817 // trigger various errors, e.g., if this identifier
2818 // happens to be the name of a package.
2819 Gogo* gogo = this->gogo_;
2820 val = this->id_to_expression(gogo->pack_hidden_name(identifier,
2821 is_exported),
2822 location, false);
2823 is_name = true;
2825 else
2827 this->unget_token(Token::make_identifier_token(identifier,
2828 is_exported,
2829 location));
2830 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
2831 NULL);
2834 else if (!token->is_op(OPERATOR_LCURLY))
2835 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
2836 else
2838 // This must be a composite literal inside another composite
2839 // literal, with the type omitted for the inner one.
2840 val = this->composite_lit(type, depth + 1, token->location());
2841 is_type_omitted = true;
2844 token = this->peek_token();
2845 if (!token->is_op(OPERATOR_COLON))
2847 if (has_keys)
2848 vals->push_back(NULL);
2849 is_name = false;
2851 else
2853 if (is_type_omitted)
2855 // VAL is a nested composite literal with an omitted type being
2856 // used a key. Record this information in VAL so that the correct
2857 // type is associated with the literal value if VAL is a
2858 // map literal.
2859 val->complit()->update_key_path(depth);
2862 this->advance_token();
2864 if (!has_keys && !vals->empty())
2866 Expression_list* newvals = new Expression_list;
2867 for (Expression_list::const_iterator p = vals->begin();
2868 p != vals->end();
2869 ++p)
2871 newvals->push_back(NULL);
2872 newvals->push_back(*p);
2874 delete vals;
2875 vals = newvals;
2877 has_keys = true;
2879 if (val->unknown_expression() != NULL)
2880 val->unknown_expression()->set_is_composite_literal_key();
2882 vals->push_back(val);
2884 if (!token->is_op(OPERATOR_LCURLY))
2885 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
2886 else
2888 // This must be a composite literal inside another
2889 // composite literal, with the type omitted for the
2890 // inner one.
2891 val = this->composite_lit(type, depth + 1, token->location());
2894 token = this->peek_token();
2897 vals->push_back(val);
2899 if (!is_name)
2900 all_are_names = false;
2902 if (token->is_op(OPERATOR_COMMA))
2904 if (this->advance_token()->is_op(OPERATOR_RCURLY))
2906 this->advance_token();
2907 break;
2910 else if (token->is_op(OPERATOR_RCURLY))
2912 this->advance_token();
2913 break;
2915 else
2917 if (token->is_op(OPERATOR_SEMICOLON))
2918 go_error_at(this->location(),
2919 ("need trailing comma before newline "
2920 "in composite literal"));
2921 else
2922 go_error_at(this->location(), "expected %<,%> or %<}%>");
2924 this->gogo_->mark_locals_used();
2925 int depth = 0;
2926 while (!token->is_eof()
2927 && (depth > 0 || !token->is_op(OPERATOR_RCURLY)))
2929 if (token->is_op(OPERATOR_LCURLY))
2930 ++depth;
2931 else if (token->is_op(OPERATOR_RCURLY))
2932 --depth;
2933 token = this->advance_token();
2935 if (token->is_op(OPERATOR_RCURLY))
2936 this->advance_token();
2938 return Expression::make_error(location);
2942 return Expression::make_composite_literal(type, depth, has_keys, vals,
2943 all_are_names, location);
2946 // FunctionLit = "func" Signature Block .
2948 Expression*
2949 Parse::function_lit()
2951 Location location = this->location();
2952 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2953 this->advance_token();
2955 Enclosing_vars hold_enclosing_vars;
2956 hold_enclosing_vars.swap(this->enclosing_vars_);
2958 Function_type* type = this->signature(NULL, location);
2959 bool fntype_is_error = false;
2960 if (type == NULL)
2962 type = Type::make_function_type(NULL, NULL, NULL, location);
2963 fntype_is_error = true;
2966 // For a function literal, the next token must be a '{'. If we
2967 // don't see that, then we may have a type expression.
2968 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2970 hold_enclosing_vars.swap(this->enclosing_vars_);
2971 return Expression::make_type(type, location);
2974 bool hold_is_erroneous_function = this->is_erroneous_function_;
2975 if (fntype_is_error)
2976 this->is_erroneous_function_ = true;
2978 Bc_stack* hold_break_stack = this->break_stack_;
2979 Bc_stack* hold_continue_stack = this->continue_stack_;
2980 this->break_stack_ = NULL;
2981 this->continue_stack_ = NULL;
2983 Named_object* no = this->gogo_->start_function("", type, true, location);
2985 Location end_loc = this->block();
2987 this->gogo_->finish_function(end_loc);
2989 if (this->break_stack_ != NULL)
2990 delete this->break_stack_;
2991 if (this->continue_stack_ != NULL)
2992 delete this->continue_stack_;
2993 this->break_stack_ = hold_break_stack;
2994 this->continue_stack_ = hold_continue_stack;
2996 this->is_erroneous_function_ = hold_is_erroneous_function;
2998 hold_enclosing_vars.swap(this->enclosing_vars_);
3000 Expression* closure = this->create_closure(no, &hold_enclosing_vars,
3001 location);
3003 return Expression::make_func_reference(no, closure, location);
3006 // Create a closure for the nested function FUNCTION. This is based
3007 // on ENCLOSING_VARS, which is a list of all variables defined in
3008 // enclosing functions and referenced from FUNCTION. A closure is the
3009 // address of a struct which point to the real function code and
3010 // contains the addresses of all the referenced variables. This
3011 // returns NULL if no closure is required.
3013 Expression*
3014 Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
3015 Location location)
3017 if (enclosing_vars->empty())
3018 return NULL;
3020 // Get the variables in order by their field index.
3022 size_t enclosing_var_count = enclosing_vars->size();
3023 std::vector<Enclosing_var> ev(enclosing_var_count);
3024 for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
3025 p != enclosing_vars->end();
3026 ++p)
3028 // Subtract 1 because index 0 is the function code.
3029 ev[p->index() - 1] = *p;
3032 // Build an initializer for a composite literal of the closure's
3033 // type.
3035 Named_object* enclosing_function = this->gogo_->current_function();
3036 Expression_list* initializer = new Expression_list;
3038 initializer->push_back(Expression::make_func_code_reference(function,
3039 location));
3041 for (size_t i = 0; i < enclosing_var_count; ++i)
3043 // Add 1 to i because the first field in the closure is a
3044 // pointer to the function code.
3045 go_assert(ev[i].index() == i + 1);
3046 Named_object* var = ev[i].var();
3047 Expression* ref;
3048 if (ev[i].in_function() == enclosing_function)
3049 ref = Expression::make_var_reference(var, location);
3050 else
3051 ref = this->enclosing_var_reference(ev[i].in_function(), var,
3052 true, location);
3053 Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
3054 location);
3055 initializer->push_back(refaddr);
3058 Named_object* closure_var = function->func_value()->closure_var();
3059 Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
3060 Expression* cv = Expression::make_struct_composite_literal(st, initializer,
3061 location);
3062 return Expression::make_heap_expression(cv, location);
3065 // PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
3067 // If MAY_BE_SINK is true, this expression may be "_".
3069 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3070 // literal.
3072 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3073 // guard (var := expr.("type") using the literal keyword "type").
3075 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3076 // if the entire expression is in parentheses.
3078 Expression*
3079 Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
3080 bool* is_type_switch, bool* is_parenthesized)
3082 Location start_loc = this->location();
3083 bool operand_is_parenthesized = false;
3084 bool whole_is_parenthesized = false;
3086 Expression* ret = this->operand(may_be_sink, &operand_is_parenthesized);
3088 whole_is_parenthesized = operand_is_parenthesized;
3090 // An unknown name followed by a curly brace must be a composite
3091 // literal, and the unknown name must be a type.
3092 if (may_be_composite_lit
3093 && !operand_is_parenthesized
3094 && ret->unknown_expression() != NULL
3095 && this->peek_token()->is_op(OPERATOR_LCURLY))
3097 Named_object* no = ret->unknown_expression()->named_object();
3098 Type* type = Type::make_forward_declaration(no);
3099 ret = Expression::make_type(type, ret->location());
3102 // We handle composite literals and type casts here, as it is the
3103 // easiest way to handle types which are in parentheses, as in
3104 // "((uint))(1)".
3105 if (ret->is_type_expression())
3107 if (this->peek_token()->is_op(OPERATOR_LCURLY))
3109 whole_is_parenthesized = false;
3110 if (!may_be_composite_lit)
3112 Type* t = ret->type();
3113 if (t->named_type() != NULL
3114 || t->forward_declaration_type() != NULL)
3115 go_error_at(start_loc,
3116 _("parentheses required around this composite "
3117 "literal to avoid parsing ambiguity"));
3119 else if (operand_is_parenthesized)
3120 go_error_at(start_loc,
3121 "cannot parenthesize type in composite literal");
3122 ret = this->composite_lit(ret->type(), 0, ret->location());
3124 else if (this->peek_token()->is_op(OPERATOR_LPAREN))
3126 whole_is_parenthesized = false;
3127 Location loc = this->location();
3128 this->advance_token();
3129 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
3130 NULL, NULL);
3131 if (this->peek_token()->is_op(OPERATOR_COMMA))
3132 this->advance_token();
3133 if (this->peek_token()->is_op(OPERATOR_ELLIPSIS))
3135 go_error_at(this->location(),
3136 "invalid use of %<...%> in type conversion");
3137 this->advance_token();
3139 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
3140 go_error_at(this->location(), "expected %<)%>");
3141 else
3142 this->advance_token();
3143 if (expr->is_error_expression())
3144 ret = expr;
3145 else
3147 Type* t = ret->type();
3148 if (t->classification() == Type::TYPE_ARRAY
3149 && t->array_type()->length() != NULL
3150 && t->array_type()->length()->is_nil_expression())
3152 go_error_at(ret->location(),
3153 "use of %<[...]%> outside of array literal");
3154 ret = Expression::make_error(loc);
3156 else
3157 ret = Expression::make_cast(t, expr, loc);
3162 while (true)
3164 const Token* token = this->peek_token();
3165 if (token->is_op(OPERATOR_LPAREN))
3167 whole_is_parenthesized = false;
3168 ret = this->call(this->verify_not_sink(ret));
3170 else if (token->is_op(OPERATOR_DOT))
3172 whole_is_parenthesized = false;
3173 ret = this->selector(this->verify_not_sink(ret), is_type_switch);
3174 if (is_type_switch != NULL && *is_type_switch)
3175 break;
3177 else if (token->is_op(OPERATOR_LSQUARE))
3179 whole_is_parenthesized = false;
3180 ret = this->index(this->verify_not_sink(ret));
3182 else
3183 break;
3186 if (whole_is_parenthesized && is_parenthesized != NULL)
3187 *is_parenthesized = true;
3189 return ret;
3192 // Selector = "." identifier .
3193 // TypeGuard = "." "(" QualifiedIdent ")" .
3195 // Note that Operand can expand to QualifiedIdent, which contains a
3196 // ".". That is handled directly in operand when it sees a package
3197 // name.
3199 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3200 // guard (var := expr.("type") using the literal keyword "type").
3202 Expression*
3203 Parse::selector(Expression* left, bool* is_type_switch)
3205 go_assert(this->peek_token()->is_op(OPERATOR_DOT));
3206 Location location = this->location();
3208 const Token* token = this->advance_token();
3209 if (token->is_identifier())
3211 // This could be a field in a struct, or a method in an
3212 // interface, or a method associated with a type. We can't know
3213 // which until we have seen all the types.
3214 std::string name =
3215 this->gogo_->pack_hidden_name(token->identifier(),
3216 token->is_identifier_exported());
3217 if (token->identifier() == "_")
3219 go_error_at(this->location(), "invalid use of %<_%>");
3220 name = Gogo::erroneous_name();
3222 this->advance_token();
3223 return Expression::make_selector(left, name, location);
3225 else if (token->is_op(OPERATOR_LPAREN))
3227 this->advance_token();
3228 Type* type = NULL;
3229 if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
3230 type = this->type();
3231 else
3233 if (is_type_switch != NULL)
3234 *is_type_switch = true;
3235 else
3237 go_error_at(this->location(),
3238 "use of %<.(type)%> outside type switch");
3239 type = Type::make_error_type();
3241 this->advance_token();
3243 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
3244 go_error_at(this->location(), "missing %<)%>");
3245 else
3246 this->advance_token();
3247 if (is_type_switch != NULL && *is_type_switch)
3248 return left;
3249 return Expression::make_type_guard(left, type, location);
3251 else
3253 go_error_at(this->location(), "expected identifier or %<(%>");
3254 return left;
3258 // Index = "[" Expression "]" .
3259 // Slice = "[" Expression ":" [ Expression ] [ ":" Expression ] "]" .
3261 Expression*
3262 Parse::index(Expression* expr)
3264 Location location = this->location();
3265 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
3266 this->advance_token();
3268 Expression* start;
3269 if (!this->peek_token()->is_op(OPERATOR_COLON))
3270 start = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3271 else
3272 start = Expression::make_integer_ul(0, NULL, location);
3274 Expression* end = NULL;
3275 if (this->peek_token()->is_op(OPERATOR_COLON))
3277 // We use nil to indicate a missing high expression.
3278 if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3279 end = Expression::make_nil(this->location());
3280 else if (this->peek_token()->is_op(OPERATOR_COLON))
3282 go_error_at(this->location(),
3283 "middle index required in 3-index slice");
3284 end = Expression::make_error(this->location());
3286 else
3287 end = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3290 Expression* cap = NULL;
3291 if (this->peek_token()->is_op(OPERATOR_COLON))
3293 if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3295 go_error_at(this->location(),
3296 "final index required in 3-index slice");
3297 cap = Expression::make_error(this->location());
3299 else
3300 cap = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3302 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
3303 go_error_at(this->location(), "missing %<]%>");
3304 else
3305 this->advance_token();
3306 return Expression::make_index(expr, start, end, cap, location);
3309 // Call = "(" [ ArgumentList [ "," ] ] ")" .
3310 // ArgumentList = ExpressionList [ "..." ] .
3312 Expression*
3313 Parse::call(Expression* func)
3315 go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
3316 Expression_list* args = NULL;
3317 bool is_varargs = false;
3318 const Token* token = this->advance_token();
3319 if (!token->is_op(OPERATOR_RPAREN))
3321 args = this->expression_list(NULL, false, true);
3322 token = this->peek_token();
3323 if (token->is_op(OPERATOR_ELLIPSIS))
3325 is_varargs = true;
3326 token = this->advance_token();
3329 if (token->is_op(OPERATOR_COMMA))
3330 token = this->advance_token();
3331 if (!token->is_op(OPERATOR_RPAREN))
3333 go_error_at(this->location(), "missing %<)%>");
3334 if (!this->skip_past_error(OPERATOR_RPAREN))
3335 return Expression::make_error(this->location());
3337 this->advance_token();
3338 if (func->is_error_expression())
3339 return func;
3340 return Expression::make_call(func, args, is_varargs, func->location());
3343 // Return an expression for a single unqualified identifier.
3345 Expression*
3346 Parse::id_to_expression(const std::string& name, Location location,
3347 bool is_lhs)
3349 Named_object* in_function;
3350 Named_object* named_object = this->gogo_->lookup(name, &in_function);
3351 if (named_object == NULL)
3352 named_object = this->gogo_->add_unknown_name(name, location);
3354 if (in_function != NULL
3355 && in_function != this->gogo_->current_function()
3356 && (named_object->is_variable() || named_object->is_result_variable()))
3357 return this->enclosing_var_reference(in_function, named_object, is_lhs,
3358 location);
3360 switch (named_object->classification())
3362 case Named_object::NAMED_OBJECT_CONST:
3363 return Expression::make_const_reference(named_object, location);
3364 case Named_object::NAMED_OBJECT_VAR:
3365 case Named_object::NAMED_OBJECT_RESULT_VAR:
3366 if (!is_lhs)
3367 this->mark_var_used(named_object);
3368 return Expression::make_var_reference(named_object, location);
3369 case Named_object::NAMED_OBJECT_SINK:
3370 return Expression::make_sink(location);
3371 case Named_object::NAMED_OBJECT_FUNC:
3372 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3373 return Expression::make_func_reference(named_object, NULL, location);
3374 case Named_object::NAMED_OBJECT_UNKNOWN:
3376 Unknown_expression* ue =
3377 Expression::make_unknown_reference(named_object, location);
3378 if (this->is_erroneous_function_)
3379 ue->set_no_error_message();
3380 return ue;
3382 case Named_object::NAMED_OBJECT_PACKAGE:
3383 case Named_object::NAMED_OBJECT_TYPE:
3384 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3386 // These cases can arise for a field name in a composite
3387 // literal. Keep track of these as they might be fake uses of
3388 // the related package.
3389 Unknown_expression* ue =
3390 Expression::make_unknown_reference(named_object, location);
3391 if (named_object->package() != NULL)
3392 named_object->package()->note_fake_usage(ue);
3393 if (this->is_erroneous_function_)
3394 ue->set_no_error_message();
3395 return ue;
3397 case Named_object::NAMED_OBJECT_ERRONEOUS:
3398 return Expression::make_error(location);
3399 default:
3400 go_error_at(this->location(), "unexpected type of identifier");
3401 return Expression::make_error(location);
3405 // Expression = UnaryExpr { binary_op Expression } .
3407 // PRECEDENCE is the precedence of the current operator.
3409 // If MAY_BE_SINK is true, this expression may be "_".
3411 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3412 // literal.
3414 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3415 // guard (var := expr.("type") using the literal keyword "type").
3417 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3418 // if the entire expression is in parentheses.
3420 Expression*
3421 Parse::expression(Precedence precedence, bool may_be_sink,
3422 bool may_be_composite_lit, bool* is_type_switch,
3423 bool *is_parenthesized)
3425 Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
3426 is_type_switch, is_parenthesized);
3428 while (true)
3430 if (is_type_switch != NULL && *is_type_switch)
3431 return left;
3433 const Token* token = this->peek_token();
3434 if (token->classification() != Token::TOKEN_OPERATOR)
3436 // Not a binary_op.
3437 return left;
3440 Precedence right_precedence;
3441 switch (token->op())
3443 case OPERATOR_OROR:
3444 right_precedence = PRECEDENCE_OROR;
3445 break;
3446 case OPERATOR_ANDAND:
3447 right_precedence = PRECEDENCE_ANDAND;
3448 break;
3449 case OPERATOR_EQEQ:
3450 case OPERATOR_NOTEQ:
3451 case OPERATOR_LT:
3452 case OPERATOR_LE:
3453 case OPERATOR_GT:
3454 case OPERATOR_GE:
3455 right_precedence = PRECEDENCE_RELOP;
3456 break;
3457 case OPERATOR_PLUS:
3458 case OPERATOR_MINUS:
3459 case OPERATOR_OR:
3460 case OPERATOR_XOR:
3461 right_precedence = PRECEDENCE_ADDOP;
3462 break;
3463 case OPERATOR_MULT:
3464 case OPERATOR_DIV:
3465 case OPERATOR_MOD:
3466 case OPERATOR_LSHIFT:
3467 case OPERATOR_RSHIFT:
3468 case OPERATOR_AND:
3469 case OPERATOR_BITCLEAR:
3470 right_precedence = PRECEDENCE_MULOP;
3471 break;
3472 default:
3473 right_precedence = PRECEDENCE_INVALID;
3474 break;
3477 if (right_precedence == PRECEDENCE_INVALID)
3479 // Not a binary_op.
3480 return left;
3483 if (is_parenthesized != NULL)
3484 *is_parenthesized = false;
3486 Operator op = token->op();
3487 Location binop_location = token->location();
3489 if (precedence >= right_precedence)
3491 // We've already seen A * B, and we see + C. We want to
3492 // return so that A * B becomes a group.
3493 return left;
3496 this->advance_token();
3498 left = this->verify_not_sink(left);
3499 Expression* right = this->expression(right_precedence, false,
3500 may_be_composite_lit,
3501 NULL, NULL);
3502 left = Expression::make_binary(op, left, right, binop_location);
3506 bool
3507 Parse::expression_may_start_here()
3509 const Token* token = this->peek_token();
3510 switch (token->classification())
3512 case Token::TOKEN_INVALID:
3513 case Token::TOKEN_EOF:
3514 return false;
3515 case Token::TOKEN_KEYWORD:
3516 switch (token->keyword())
3518 case KEYWORD_CHAN:
3519 case KEYWORD_FUNC:
3520 case KEYWORD_MAP:
3521 case KEYWORD_STRUCT:
3522 case KEYWORD_INTERFACE:
3523 return true;
3524 default:
3525 return false;
3527 case Token::TOKEN_IDENTIFIER:
3528 return true;
3529 case Token::TOKEN_STRING:
3530 return true;
3531 case Token::TOKEN_OPERATOR:
3532 switch (token->op())
3534 case OPERATOR_PLUS:
3535 case OPERATOR_MINUS:
3536 case OPERATOR_NOT:
3537 case OPERATOR_XOR:
3538 case OPERATOR_MULT:
3539 case OPERATOR_CHANOP:
3540 case OPERATOR_AND:
3541 case OPERATOR_LPAREN:
3542 case OPERATOR_LSQUARE:
3543 return true;
3544 default:
3545 return false;
3547 case Token::TOKEN_CHARACTER:
3548 case Token::TOKEN_INTEGER:
3549 case Token::TOKEN_FLOAT:
3550 case Token::TOKEN_IMAGINARY:
3551 return true;
3552 default:
3553 go_unreachable();
3557 // UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3559 // If MAY_BE_SINK is true, this expression may be "_".
3561 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3562 // literal.
3564 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3565 // guard (var := expr.("type") using the literal keyword "type").
3567 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3568 // if the entire expression is in parentheses.
3570 Expression*
3571 Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3572 bool* is_type_switch, bool* is_parenthesized)
3574 const Token* token = this->peek_token();
3576 // There is a complex parse for <- chan. The choices are
3577 // Convert x to type <- chan int:
3578 // (<- chan int)(x)
3579 // Receive from (x converted to type chan <- chan int):
3580 // (<- chan <- chan int (x))
3581 // Convert x to type <- chan (<- chan int).
3582 // (<- chan <- chan int)(x)
3583 if (token->is_op(OPERATOR_CHANOP))
3585 Location location = token->location();
3586 if (this->advance_token()->is_keyword(KEYWORD_CHAN))
3588 Expression* expr = this->primary_expr(false, may_be_composite_lit,
3589 NULL, NULL);
3590 if (expr->is_error_expression())
3591 return expr;
3592 else if (!expr->is_type_expression())
3593 return Expression::make_receive(expr, location);
3594 else
3596 if (expr->type()->is_error_type())
3597 return expr;
3599 // We picked up "chan TYPE", but it is not a type
3600 // conversion.
3601 Channel_type* ct = expr->type()->channel_type();
3602 if (ct == NULL)
3604 // This is probably impossible.
3605 go_error_at(location, "expected channel type");
3606 return Expression::make_error(location);
3608 else if (ct->may_receive())
3610 // <- chan TYPE.
3611 Type* t = Type::make_channel_type(false, true,
3612 ct->element_type());
3613 return Expression::make_type(t, location);
3615 else
3617 // <- chan <- TYPE. Because we skipped the leading
3618 // <-, we parsed this as chan <- TYPE. With the
3619 // leading <-, we parse it as <- chan (<- TYPE).
3620 Type *t = this->reassociate_chan_direction(ct, location);
3621 return Expression::make_type(t, location);
3626 this->unget_token(Token::make_operator_token(OPERATOR_CHANOP, location));
3627 token = this->peek_token();
3630 if (token->is_op(OPERATOR_PLUS)
3631 || token->is_op(OPERATOR_MINUS)
3632 || token->is_op(OPERATOR_NOT)
3633 || token->is_op(OPERATOR_XOR)
3634 || token->is_op(OPERATOR_CHANOP)
3635 || token->is_op(OPERATOR_MULT)
3636 || token->is_op(OPERATOR_AND))
3638 Location location = token->location();
3639 Operator op = token->op();
3640 this->advance_token();
3642 Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL,
3643 NULL);
3644 if (expr->is_error_expression())
3646 else if (op == OPERATOR_MULT && expr->is_type_expression())
3647 expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3648 location);
3649 else if (op == OPERATOR_AND && expr->is_composite_literal())
3650 expr = Expression::make_heap_expression(expr, location);
3651 else if (op != OPERATOR_CHANOP)
3652 expr = Expression::make_unary(op, expr, location);
3653 else
3654 expr = Expression::make_receive(expr, location);
3655 return expr;
3657 else
3658 return this->primary_expr(may_be_sink, may_be_composite_lit,
3659 is_type_switch, is_parenthesized);
3662 // This is called for the obscure case of
3663 // (<- chan <- chan int)(x)
3664 // In unary_expr we remove the leading <- and parse the remainder,
3665 // which gives us
3666 // chan <- (chan int)
3667 // When we add the leading <- back in, we really want
3668 // <- chan (<- chan int)
3669 // This means that we need to reassociate.
3671 Type*
3672 Parse::reassociate_chan_direction(Channel_type *ct, Location location)
3674 Channel_type* ele = ct->element_type()->channel_type();
3675 if (ele == NULL)
3677 go_error_at(location, "parse error");
3678 return Type::make_error_type();
3680 Type* sub = ele;
3681 if (ele->may_send())
3682 sub = Type::make_channel_type(false, true, ele->element_type());
3683 else
3684 sub = this->reassociate_chan_direction(ele, location);
3685 return Type::make_channel_type(false, true, sub);
3688 // Statement =
3689 // Declaration | LabeledStmt | SimpleStmt |
3690 // GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3691 // FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3692 // DeferStmt .
3694 // LABEL is the label of this statement if it has one.
3696 void
3697 Parse::statement(Label* label)
3699 const Token* token = this->peek_token();
3700 switch (token->classification())
3702 case Token::TOKEN_KEYWORD:
3704 switch (token->keyword())
3706 case KEYWORD_CONST:
3707 case KEYWORD_TYPE:
3708 case KEYWORD_VAR:
3709 this->declaration();
3710 break;
3711 case KEYWORD_FUNC:
3712 case KEYWORD_MAP:
3713 case KEYWORD_STRUCT:
3714 case KEYWORD_INTERFACE:
3715 this->simple_stat(true, NULL, NULL, NULL);
3716 break;
3717 case KEYWORD_GO:
3718 case KEYWORD_DEFER:
3719 this->go_or_defer_stat();
3720 break;
3721 case KEYWORD_RETURN:
3722 this->return_stat();
3723 break;
3724 case KEYWORD_BREAK:
3725 this->break_stat();
3726 break;
3727 case KEYWORD_CONTINUE:
3728 this->continue_stat();
3729 break;
3730 case KEYWORD_GOTO:
3731 this->goto_stat();
3732 break;
3733 case KEYWORD_IF:
3734 this->if_stat();
3735 break;
3736 case KEYWORD_SWITCH:
3737 this->switch_stat(label);
3738 break;
3739 case KEYWORD_SELECT:
3740 this->select_stat(label);
3741 break;
3742 case KEYWORD_FOR:
3743 this->for_stat(label);
3744 break;
3745 default:
3746 go_error_at(this->location(), "expected statement");
3747 this->advance_token();
3748 break;
3751 break;
3753 case Token::TOKEN_IDENTIFIER:
3755 std::string identifier = token->identifier();
3756 bool is_exported = token->is_identifier_exported();
3757 Location location = token->location();
3758 if (this->advance_token()->is_op(OPERATOR_COLON))
3760 this->advance_token();
3761 this->labeled_stmt(identifier, location);
3763 else
3765 this->unget_token(Token::make_identifier_token(identifier,
3766 is_exported,
3767 location));
3768 this->simple_stat(true, NULL, NULL, NULL);
3771 break;
3773 case Token::TOKEN_OPERATOR:
3774 if (token->is_op(OPERATOR_LCURLY))
3776 Location location = token->location();
3777 this->gogo_->start_block(location);
3778 Location end_loc = this->block();
3779 this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3780 location);
3782 else if (!token->is_op(OPERATOR_SEMICOLON))
3783 this->simple_stat(true, NULL, NULL, NULL);
3784 break;
3786 case Token::TOKEN_STRING:
3787 case Token::TOKEN_CHARACTER:
3788 case Token::TOKEN_INTEGER:
3789 case Token::TOKEN_FLOAT:
3790 case Token::TOKEN_IMAGINARY:
3791 this->simple_stat(true, NULL, NULL, NULL);
3792 break;
3794 default:
3795 go_error_at(this->location(), "expected statement");
3796 this->advance_token();
3797 break;
3801 bool
3802 Parse::statement_may_start_here()
3804 const Token* token = this->peek_token();
3805 switch (token->classification())
3807 case Token::TOKEN_KEYWORD:
3809 switch (token->keyword())
3811 case KEYWORD_CONST:
3812 case KEYWORD_TYPE:
3813 case KEYWORD_VAR:
3814 case KEYWORD_FUNC:
3815 case KEYWORD_MAP:
3816 case KEYWORD_STRUCT:
3817 case KEYWORD_INTERFACE:
3818 case KEYWORD_GO:
3819 case KEYWORD_DEFER:
3820 case KEYWORD_RETURN:
3821 case KEYWORD_BREAK:
3822 case KEYWORD_CONTINUE:
3823 case KEYWORD_GOTO:
3824 case KEYWORD_IF:
3825 case KEYWORD_SWITCH:
3826 case KEYWORD_SELECT:
3827 case KEYWORD_FOR:
3828 return true;
3830 default:
3831 return false;
3834 break;
3836 case Token::TOKEN_IDENTIFIER:
3837 return true;
3839 case Token::TOKEN_OPERATOR:
3840 if (token->is_op(OPERATOR_LCURLY)
3841 || token->is_op(OPERATOR_SEMICOLON))
3842 return true;
3843 else
3844 return this->expression_may_start_here();
3846 case Token::TOKEN_STRING:
3847 case Token::TOKEN_CHARACTER:
3848 case Token::TOKEN_INTEGER:
3849 case Token::TOKEN_FLOAT:
3850 case Token::TOKEN_IMAGINARY:
3851 return true;
3853 default:
3854 return false;
3858 // LabeledStmt = Label ":" Statement .
3859 // Label = identifier .
3861 void
3862 Parse::labeled_stmt(const std::string& label_name, Location location)
3864 Label* label = this->gogo_->add_label_definition(label_name, location);
3866 if (this->peek_token()->is_op(OPERATOR_RCURLY))
3868 // This is a label at the end of a block. A program is
3869 // permitted to omit a semicolon here.
3870 return;
3873 if (!this->statement_may_start_here())
3875 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
3877 // We don't treat the fallthrough keyword as a statement,
3878 // because it can't appear most places where a statement is
3879 // permitted, but it may have a label. We introduce a
3880 // semicolon because the caller expects to see a statement.
3881 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3882 location));
3883 return;
3886 // Mark the label as used to avoid a useless error about an
3887 // unused label.
3888 if (label != NULL)
3889 label->set_is_used();
3891 go_error_at(location, "missing statement after label");
3892 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3893 location));
3894 return;
3897 this->statement(label);
3900 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
3901 // Assignment | ShortVarDecl .
3903 // EmptyStmt was handled in Parse::statement.
3905 // In order to make this work for if and switch statements, if
3906 // RETURN_EXP is not NULL, and we see an ExpressionStat, we return the
3907 // expression rather than adding an expression statement to the
3908 // current block. If we see something other than an ExpressionStat,
3909 // we add the statement, set *RETURN_EXP to true if we saw a send
3910 // statement, and return NULL. The handling of send statements is for
3911 // better error messages.
3913 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
3914 // RangeClause.
3916 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
3917 // guard (var := expr.("type") using the literal keyword "type").
3919 Expression*
3920 Parse::simple_stat(bool may_be_composite_lit, bool* return_exp,
3921 Range_clause* p_range_clause, Type_switch* p_type_switch)
3923 const Token* token = this->peek_token();
3925 // An identifier follow by := is a SimpleVarDecl.
3926 if (token->is_identifier())
3928 std::string identifier = token->identifier();
3929 bool is_exported = token->is_identifier_exported();
3930 Location location = token->location();
3932 token = this->advance_token();
3933 if (token->is_op(OPERATOR_COLONEQ)
3934 || token->is_op(OPERATOR_COMMA))
3936 identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
3937 this->simple_var_decl_or_assignment(identifier, location,
3938 may_be_composite_lit,
3939 p_range_clause,
3940 (token->is_op(OPERATOR_COLONEQ)
3941 ? p_type_switch
3942 : NULL));
3943 return NULL;
3946 this->unget_token(Token::make_identifier_token(identifier, is_exported,
3947 location));
3949 else if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
3951 Typed_identifier_list til;
3952 this->range_clause_decl(&til, p_range_clause);
3953 return NULL;
3956 Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
3957 may_be_composite_lit,
3958 (p_type_switch == NULL
3959 ? NULL
3960 : &p_type_switch->found),
3961 NULL);
3962 if (p_type_switch != NULL && p_type_switch->found)
3964 p_type_switch->name.clear();
3965 p_type_switch->location = exp->location();
3966 p_type_switch->expr = this->verify_not_sink(exp);
3967 return NULL;
3969 token = this->peek_token();
3970 if (token->is_op(OPERATOR_CHANOP))
3972 this->send_stmt(this->verify_not_sink(exp), may_be_composite_lit);
3973 if (return_exp != NULL)
3974 *return_exp = true;
3976 else if (token->is_op(OPERATOR_PLUSPLUS)
3977 || token->is_op(OPERATOR_MINUSMINUS))
3978 this->inc_dec_stat(this->verify_not_sink(exp));
3979 else if (token->is_op(OPERATOR_COMMA)
3980 || token->is_op(OPERATOR_EQ))
3981 this->assignment(exp, may_be_composite_lit, p_range_clause);
3982 else if (token->is_op(OPERATOR_PLUSEQ)
3983 || token->is_op(OPERATOR_MINUSEQ)
3984 || token->is_op(OPERATOR_OREQ)
3985 || token->is_op(OPERATOR_XOREQ)
3986 || token->is_op(OPERATOR_MULTEQ)
3987 || token->is_op(OPERATOR_DIVEQ)
3988 || token->is_op(OPERATOR_MODEQ)
3989 || token->is_op(OPERATOR_LSHIFTEQ)
3990 || token->is_op(OPERATOR_RSHIFTEQ)
3991 || token->is_op(OPERATOR_ANDEQ)
3992 || token->is_op(OPERATOR_BITCLEAREQ))
3993 this->assignment(this->verify_not_sink(exp), may_be_composite_lit,
3994 p_range_clause);
3995 else if (return_exp != NULL)
3996 return this->verify_not_sink(exp);
3997 else
3999 exp = this->verify_not_sink(exp);
4001 if (token->is_op(OPERATOR_COLONEQ))
4003 if (!exp->is_error_expression())
4004 go_error_at(token->location(), "non-name on left side of %<:=%>");
4005 this->gogo_->mark_locals_used();
4006 while (!token->is_op(OPERATOR_SEMICOLON)
4007 && !token->is_eof())
4008 token = this->advance_token();
4009 return NULL;
4012 this->expression_stat(exp);
4015 return NULL;
4018 bool
4019 Parse::simple_stat_may_start_here()
4021 return this->expression_may_start_here();
4024 // Parse { Statement ";" } which is used in a few places. The list of
4025 // statements may end with a right curly brace, in which case the
4026 // semicolon may be omitted.
4028 void
4029 Parse::statement_list()
4031 while (this->statement_may_start_here())
4033 this->statement(NULL);
4034 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4035 this->advance_token();
4036 else if (this->peek_token()->is_op(OPERATOR_RCURLY))
4037 break;
4038 else
4040 if (!this->peek_token()->is_eof() || !saw_errors())
4041 go_error_at(this->location(), "expected %<;%> or %<}%> or newline");
4042 if (!this->skip_past_error(OPERATOR_RCURLY))
4043 return;
4048 bool
4049 Parse::statement_list_may_start_here()
4051 return this->statement_may_start_here();
4054 // ExpressionStat = Expression .
4056 void
4057 Parse::expression_stat(Expression* exp)
4059 this->gogo_->add_statement(Statement::make_statement(exp, false));
4062 // SendStmt = Channel "&lt;-" Expression .
4063 // Channel = Expression .
4065 void
4066 Parse::send_stmt(Expression* channel, bool may_be_composite_lit)
4068 go_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
4069 Location loc = this->location();
4070 this->advance_token();
4071 Expression* val = this->expression(PRECEDENCE_NORMAL, false,
4072 may_be_composite_lit, NULL, NULL);
4073 Statement* s = Statement::make_send_statement(channel, val, loc);
4074 this->gogo_->add_statement(s);
4077 // IncDecStat = Expression ( "++" | "--" ) .
4079 void
4080 Parse::inc_dec_stat(Expression* exp)
4082 const Token* token = this->peek_token();
4083 if (token->is_op(OPERATOR_PLUSPLUS))
4084 this->gogo_->add_statement(Statement::make_inc_statement(exp));
4085 else if (token->is_op(OPERATOR_MINUSMINUS))
4086 this->gogo_->add_statement(Statement::make_dec_statement(exp));
4087 else
4088 go_unreachable();
4089 this->advance_token();
4092 // Assignment = ExpressionList assign_op ExpressionList .
4094 // EXP is an expression that we have already parsed.
4096 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
4097 // side may be a composite literal.
4099 // If RANGE_CLAUSE is not NULL, then this will recognize a
4100 // RangeClause.
4102 void
4103 Parse::assignment(Expression* expr, bool may_be_composite_lit,
4104 Range_clause* p_range_clause)
4106 Expression_list* vars;
4107 if (!this->peek_token()->is_op(OPERATOR_COMMA))
4109 vars = new Expression_list();
4110 vars->push_back(expr);
4112 else
4114 this->advance_token();
4115 vars = this->expression_list(expr, true, may_be_composite_lit);
4118 this->tuple_assignment(vars, may_be_composite_lit, p_range_clause);
4121 // An assignment statement. LHS is the list of expressions which
4122 // appear on the left hand side.
4124 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
4125 // side may be a composite literal.
4127 // If RANGE_CLAUSE is not NULL, then this will recognize a
4128 // RangeClause.
4130 void
4131 Parse::tuple_assignment(Expression_list* lhs, bool may_be_composite_lit,
4132 Range_clause* p_range_clause)
4134 const Token* token = this->peek_token();
4135 if (!token->is_op(OPERATOR_EQ)
4136 && !token->is_op(OPERATOR_PLUSEQ)
4137 && !token->is_op(OPERATOR_MINUSEQ)
4138 && !token->is_op(OPERATOR_OREQ)
4139 && !token->is_op(OPERATOR_XOREQ)
4140 && !token->is_op(OPERATOR_MULTEQ)
4141 && !token->is_op(OPERATOR_DIVEQ)
4142 && !token->is_op(OPERATOR_MODEQ)
4143 && !token->is_op(OPERATOR_LSHIFTEQ)
4144 && !token->is_op(OPERATOR_RSHIFTEQ)
4145 && !token->is_op(OPERATOR_ANDEQ)
4146 && !token->is_op(OPERATOR_BITCLEAREQ))
4148 go_error_at(this->location(), "expected assignment operator");
4149 return;
4151 Operator op = token->op();
4152 Location location = token->location();
4154 token = this->advance_token();
4156 if (lhs == NULL)
4157 return;
4159 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
4161 if (op != OPERATOR_EQ)
4162 go_error_at(this->location(), "range clause requires %<=%>");
4163 this->range_clause_expr(lhs, p_range_clause);
4164 return;
4167 Expression_list* vals = this->expression_list(NULL, false,
4168 may_be_composite_lit);
4170 // We've parsed everything; check for errors.
4171 if (vals == NULL)
4172 return;
4173 for (Expression_list::const_iterator pe = lhs->begin();
4174 pe != lhs->end();
4175 ++pe)
4177 if ((*pe)->is_error_expression())
4178 return;
4179 if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
4180 go_error_at((*pe)->location(), "cannot use _ as value");
4182 for (Expression_list::const_iterator pe = vals->begin();
4183 pe != vals->end();
4184 ++pe)
4186 if ((*pe)->is_error_expression())
4187 return;
4190 Call_expression* call;
4191 Index_expression* map_index;
4192 Receive_expression* receive;
4193 Type_guard_expression* type_guard;
4194 if (lhs->size() == vals->size())
4196 Statement* s;
4197 if (lhs->size() > 1)
4199 if (op != OPERATOR_EQ)
4200 go_error_at(location, "multiple values only permitted with %<=%>");
4201 s = Statement::make_tuple_assignment(lhs, vals, location);
4203 else
4205 if (op == OPERATOR_EQ)
4206 s = Statement::make_assignment(lhs->front(), vals->front(),
4207 location);
4208 else
4209 s = Statement::make_assignment_operation(op, lhs->front(),
4210 vals->front(), location);
4211 delete lhs;
4212 delete vals;
4214 this->gogo_->add_statement(s);
4216 else if (vals->size() == 1
4217 && (call = (*vals->begin())->call_expression()) != NULL)
4219 if (op != OPERATOR_EQ)
4220 go_error_at(location, "multiple results only permitted with %<=%>");
4221 call->set_expected_result_count(lhs->size());
4222 delete vals;
4223 vals = new Expression_list;
4224 for (unsigned int i = 0; i < lhs->size(); ++i)
4225 vals->push_back(Expression::make_call_result(call, i));
4226 Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
4227 this->gogo_->add_statement(s);
4229 else if (lhs->size() == 2
4230 && vals->size() == 1
4231 && (map_index = (*vals->begin())->index_expression()) != NULL)
4233 if (op != OPERATOR_EQ)
4234 go_error_at(location, "two values from map requires %<=%>");
4235 Expression* val = lhs->front();
4236 Expression* present = lhs->back();
4237 Statement* s = Statement::make_tuple_map_assignment(val, present,
4238 map_index, location);
4239 this->gogo_->add_statement(s);
4241 else if (lhs->size() == 2
4242 && vals->size() == 1
4243 && (receive = (*vals->begin())->receive_expression()) != NULL)
4245 if (op != OPERATOR_EQ)
4246 go_error_at(location, "two values from receive requires %<=%>");
4247 Expression* val = lhs->front();
4248 Expression* success = lhs->back();
4249 Expression* channel = receive->channel();
4250 Statement* s = Statement::make_tuple_receive_assignment(val, success,
4251 channel,
4252 location);
4253 this->gogo_->add_statement(s);
4255 else if (lhs->size() == 2
4256 && vals->size() == 1
4257 && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
4259 if (op != OPERATOR_EQ)
4260 go_error_at(location, "two values from type guard requires %<=%>");
4261 Expression* val = lhs->front();
4262 Expression* ok = lhs->back();
4263 Expression* expr = type_guard->expr();
4264 Type* type = type_guard->type();
4265 Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
4266 expr, type,
4267 location);
4268 this->gogo_->add_statement(s);
4270 else
4272 go_error_at(location, ("number of variables does not "
4273 "match number of values"));
4277 // GoStat = "go" Expression .
4278 // DeferStat = "defer" Expression .
4280 void
4281 Parse::go_or_defer_stat()
4283 go_assert(this->peek_token()->is_keyword(KEYWORD_GO)
4284 || this->peek_token()->is_keyword(KEYWORD_DEFER));
4285 bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
4286 Location stat_location = this->location();
4288 this->advance_token();
4289 Location expr_location = this->location();
4291 bool is_parenthesized = false;
4292 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
4293 &is_parenthesized);
4294 Call_expression* call_expr = expr->call_expression();
4295 if (is_parenthesized || call_expr == NULL)
4297 go_error_at(expr_location, "argument to go/defer must be function call");
4298 return;
4301 // Make it easier to simplify go/defer statements by putting every
4302 // statement in its own block.
4303 this->gogo_->start_block(stat_location);
4304 Statement* stat;
4305 if (is_go)
4306 stat = Statement::make_go_statement(call_expr, stat_location);
4307 else
4308 stat = Statement::make_defer_statement(call_expr, stat_location);
4309 this->gogo_->add_statement(stat);
4310 this->gogo_->add_block(this->gogo_->finish_block(stat_location),
4311 stat_location);
4314 // ReturnStat = "return" [ ExpressionList ] .
4316 void
4317 Parse::return_stat()
4319 go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
4320 Location location = this->location();
4321 this->advance_token();
4322 Expression_list* vals = NULL;
4323 if (this->expression_may_start_here())
4324 vals = this->expression_list(NULL, false, true);
4325 this->gogo_->add_statement(Statement::make_return_statement(vals, location));
4327 if (vals == NULL
4328 && this->gogo_->current_function()->func_value()->results_are_named())
4330 Named_object* function = this->gogo_->current_function();
4331 Function::Results* results = function->func_value()->result_variables();
4332 for (Function::Results::const_iterator p = results->begin();
4333 p != results->end();
4334 ++p)
4336 Named_object* no = this->gogo_->lookup((*p)->name(), NULL);
4337 if (no == NULL)
4338 go_assert(saw_errors());
4339 else if (!no->is_result_variable())
4340 go_error_at(location, "%qs is shadowed during return",
4341 (*p)->message_name().c_str());
4346 // IfStmt = "if" [ SimpleStmt ";" ] Expression Block
4347 // [ "else" ( IfStmt | Block ) ] .
4349 void
4350 Parse::if_stat()
4352 go_assert(this->peek_token()->is_keyword(KEYWORD_IF));
4353 Location location = this->location();
4354 this->advance_token();
4356 this->gogo_->start_block(location);
4358 bool saw_simple_stat = false;
4359 Expression* cond = NULL;
4360 bool saw_send_stmt = false;
4361 if (this->simple_stat_may_start_here())
4363 cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL);
4364 saw_simple_stat = true;
4366 if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4368 // The SimpleStat is an expression statement.
4369 this->expression_stat(cond);
4370 cond = NULL;
4372 if (cond == NULL)
4374 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4375 this->advance_token();
4376 else if (saw_simple_stat)
4378 if (saw_send_stmt)
4379 go_error_at(this->location(),
4380 ("send statement used as value; "
4381 "use select for non-blocking send"));
4382 else
4383 go_error_at(this->location(),
4384 "expected %<;%> after statement in if expression");
4385 if (!this->expression_may_start_here())
4386 cond = Expression::make_error(this->location());
4388 if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY))
4390 go_error_at(this->location(),
4391 "missing condition in if statement");
4392 cond = Expression::make_error(this->location());
4394 if (cond == NULL)
4395 cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL, NULL);
4398 // Check for the easy error of a newline before starting the block.
4399 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4401 Location semi_loc = this->location();
4402 if (this->advance_token()->is_op(OPERATOR_LCURLY))
4403 go_error_at(semi_loc, "missing %<{%> after if clause");
4404 // Otherwise we will get an error when we call this->block
4405 // below.
4408 this->gogo_->start_block(this->location());
4409 Location end_loc = this->block();
4410 Block* then_block = this->gogo_->finish_block(end_loc);
4412 // Check for the easy error of a newline before "else".
4413 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4415 Location semi_loc = this->location();
4416 if (this->advance_token()->is_keyword(KEYWORD_ELSE))
4417 go_error_at(this->location(),
4418 "unexpected semicolon or newline before %<else%>");
4419 else
4420 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4421 semi_loc));
4424 Block* else_block = NULL;
4425 if (this->peek_token()->is_keyword(KEYWORD_ELSE))
4427 this->gogo_->start_block(this->location());
4428 const Token* token = this->advance_token();
4429 if (token->is_keyword(KEYWORD_IF))
4430 this->if_stat();
4431 else if (token->is_op(OPERATOR_LCURLY))
4432 this->block();
4433 else
4435 go_error_at(this->location(), "expected %<if%> or %<{%>");
4436 this->statement(NULL);
4438 else_block = this->gogo_->finish_block(this->location());
4441 this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
4442 else_block,
4443 location));
4445 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4446 location);
4449 // SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4450 // ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
4451 // "{" { ExprCaseClause } "}" .
4452 // TypeSwitchStmt = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
4453 // "{" { TypeCaseClause } "}" .
4454 // TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
4456 void
4457 Parse::switch_stat(Label* label)
4459 go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
4460 Location location = this->location();
4461 this->advance_token();
4463 this->gogo_->start_block(location);
4465 bool saw_simple_stat = false;
4466 Expression* switch_val = NULL;
4467 bool saw_send_stmt;
4468 Type_switch type_switch;
4469 bool have_type_switch_block = false;
4470 if (this->simple_stat_may_start_here())
4472 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4473 &type_switch);
4474 saw_simple_stat = true;
4476 if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4478 // The SimpleStat is an expression statement.
4479 this->expression_stat(switch_val);
4480 switch_val = NULL;
4482 if (switch_val == NULL && !type_switch.found)
4484 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4485 this->advance_token();
4486 else if (saw_simple_stat)
4488 if (saw_send_stmt)
4489 go_error_at(this->location(),
4490 ("send statement used as value; "
4491 "use select for non-blocking send"));
4492 else
4493 go_error_at(this->location(),
4494 "expected %<;%> after statement in switch expression");
4496 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4498 if (this->peek_token()->is_identifier())
4500 const Token* token = this->peek_token();
4501 std::string identifier = token->identifier();
4502 bool is_exported = token->is_identifier_exported();
4503 Location id_loc = token->location();
4505 token = this->advance_token();
4506 bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
4507 this->unget_token(Token::make_identifier_token(identifier,
4508 is_exported,
4509 id_loc));
4510 if (is_coloneq)
4512 // This must be a TypeSwitchGuard. It is in a
4513 // different block from any initial SimpleStat.
4514 if (saw_simple_stat)
4516 this->gogo_->start_block(id_loc);
4517 have_type_switch_block = true;
4520 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4521 &type_switch);
4522 if (!type_switch.found)
4524 if (switch_val == NULL
4525 || !switch_val->is_error_expression())
4527 go_error_at(id_loc,
4528 "expected type switch assignment");
4529 switch_val = Expression::make_error(id_loc);
4534 if (switch_val == NULL && !type_switch.found)
4536 switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
4537 &type_switch.found, NULL);
4538 if (type_switch.found)
4540 type_switch.name.clear();
4541 type_switch.expr = switch_val;
4542 type_switch.location = switch_val->location();
4548 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4550 Location token_loc = this->location();
4551 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
4552 && this->advance_token()->is_op(OPERATOR_LCURLY))
4553 go_error_at(token_loc, "missing %<{%> after switch clause");
4554 else if (this->peek_token()->is_op(OPERATOR_COLONEQ))
4556 go_error_at(token_loc, "invalid variable name");
4557 this->advance_token();
4558 this->expression(PRECEDENCE_NORMAL, false, false,
4559 &type_switch.found, NULL);
4560 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4561 this->advance_token();
4562 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4564 if (have_type_switch_block)
4565 this->gogo_->add_block(this->gogo_->finish_block(location),
4566 location);
4567 this->gogo_->add_block(this->gogo_->finish_block(location),
4568 location);
4569 return;
4571 if (type_switch.found)
4572 type_switch.expr = Expression::make_error(location);
4574 else
4576 go_error_at(this->location(), "expected %<{%>");
4577 if (have_type_switch_block)
4578 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4579 location);
4580 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4581 location);
4582 return;
4585 this->advance_token();
4587 Statement* statement;
4588 if (type_switch.found)
4589 statement = this->type_switch_body(label, type_switch, location);
4590 else
4591 statement = this->expr_switch_body(label, switch_val, location);
4593 if (statement != NULL)
4594 this->gogo_->add_statement(statement);
4596 if (have_type_switch_block)
4597 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4598 location);
4600 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4601 location);
4604 // The body of an expression switch.
4605 // "{" { ExprCaseClause } "}"
4607 Statement*
4608 Parse::expr_switch_body(Label* label, Expression* switch_val,
4609 Location location)
4611 Switch_statement* statement = Statement::make_switch_statement(switch_val,
4612 location);
4614 this->push_break_statement(statement, label);
4616 Case_clauses* case_clauses = new Case_clauses();
4617 bool saw_default = false;
4618 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4620 if (this->peek_token()->is_eof())
4622 if (!saw_errors())
4623 go_error_at(this->location(), "missing %<}%>");
4624 return NULL;
4626 this->expr_case_clause(case_clauses, &saw_default);
4628 this->advance_token();
4630 statement->add_clauses(case_clauses);
4632 this->pop_break_statement();
4634 return statement;
4637 // ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
4638 // FallthroughStat = "fallthrough" .
4640 void
4641 Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
4643 Location location = this->location();
4645 bool is_default = false;
4646 Expression_list* vals = this->expr_switch_case(&is_default);
4648 if (!this->peek_token()->is_op(OPERATOR_COLON))
4650 if (!saw_errors())
4651 go_error_at(this->location(), "expected %<:%>");
4652 return;
4654 else
4655 this->advance_token();
4657 Block* statements = NULL;
4658 if (this->statement_list_may_start_here())
4660 this->gogo_->start_block(this->location());
4661 this->statement_list();
4662 statements = this->gogo_->finish_block(this->location());
4665 bool is_fallthrough = false;
4666 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4668 Location fallthrough_loc = this->location();
4669 is_fallthrough = true;
4670 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4671 this->advance_token();
4672 if (this->peek_token()->is_op(OPERATOR_RCURLY))
4673 go_error_at(fallthrough_loc,
4674 _("cannot fallthrough final case in switch"));
4677 if (is_default)
4679 if (*saw_default)
4681 go_error_at(location, "multiple defaults in switch");
4682 return;
4684 *saw_default = true;
4687 if (is_default || vals != NULL)
4688 clauses->add(vals, is_default, statements, is_fallthrough, location);
4691 // ExprSwitchCase = "case" ExpressionList | "default" .
4693 Expression_list*
4694 Parse::expr_switch_case(bool* is_default)
4696 const Token* token = this->peek_token();
4697 if (token->is_keyword(KEYWORD_CASE))
4699 this->advance_token();
4700 return this->expression_list(NULL, false, true);
4702 else if (token->is_keyword(KEYWORD_DEFAULT))
4704 this->advance_token();
4705 *is_default = true;
4706 return NULL;
4708 else
4710 if (!saw_errors())
4711 go_error_at(this->location(), "expected %<case%> or %<default%>");
4712 if (!token->is_op(OPERATOR_RCURLY))
4713 this->advance_token();
4714 return NULL;
4718 // The body of a type switch.
4719 // "{" { TypeCaseClause } "}" .
4721 Statement*
4722 Parse::type_switch_body(Label* label, const Type_switch& type_switch,
4723 Location location)
4725 Expression* init = type_switch.expr;
4726 std::string var_name = type_switch.name;
4727 if (!var_name.empty())
4729 if (Gogo::is_sink_name(var_name))
4731 go_error_at(type_switch.location,
4732 "no new variables on left side of %<:=%>");
4733 var_name.clear();
4735 else
4737 Location loc = type_switch.location;
4738 Temporary_statement* switch_temp =
4739 Statement::make_temporary(NULL, init, loc);
4740 this->gogo_->add_statement(switch_temp);
4741 init = Expression::make_temporary_reference(switch_temp, loc);
4745 Type_switch_statement* statement =
4746 Statement::make_type_switch_statement(var_name, init, location);
4747 this->push_break_statement(statement, label);
4749 Type_case_clauses* case_clauses = new Type_case_clauses();
4750 bool saw_default = false;
4751 std::vector<Named_object*> implicit_vars;
4752 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4754 if (this->peek_token()->is_eof())
4756 go_error_at(this->location(), "missing %<}%>");
4757 return NULL;
4759 this->type_case_clause(var_name, init, case_clauses, &saw_default,
4760 &implicit_vars);
4762 this->advance_token();
4764 statement->add_clauses(case_clauses);
4766 this->pop_break_statement();
4768 // If there is a type switch variable implicitly declared in each case clause,
4769 // check that it is used in at least one of the cases.
4770 if (!var_name.empty())
4772 bool used = false;
4773 for (std::vector<Named_object*>::iterator p = implicit_vars.begin();
4774 p != implicit_vars.end();
4775 ++p)
4777 if ((*p)->var_value()->is_used())
4779 used = true;
4780 break;
4783 if (!used)
4784 go_error_at(type_switch.location, "%qs declared and not used",
4785 Gogo::message_name(var_name).c_str());
4787 return statement;
4790 // TypeCaseClause = TypeSwitchCase ":" [ StatementList ] .
4791 // IMPLICIT_VARS is the list of variables implicitly declared for each type
4792 // case if there is a type switch variable declared.
4794 void
4795 Parse::type_case_clause(const std::string& var_name, Expression* init,
4796 Type_case_clauses* clauses, bool* saw_default,
4797 std::vector<Named_object*>* implicit_vars)
4799 Location location = this->location();
4801 std::vector<Type*> types;
4802 bool is_default = false;
4803 this->type_switch_case(&types, &is_default);
4805 if (!this->peek_token()->is_op(OPERATOR_COLON))
4806 go_error_at(this->location(), "expected %<:%>");
4807 else
4808 this->advance_token();
4810 Block* statements = NULL;
4811 if (this->statement_list_may_start_here())
4813 this->gogo_->start_block(this->location());
4814 if (!var_name.empty())
4816 Type* type = NULL;
4817 Location var_loc = init->location();
4818 if (types.size() == 1)
4820 type = types.front();
4821 init = Expression::make_type_guard(init, type, location);
4824 Variable* v = new Variable(type, init, false, false, false,
4825 var_loc);
4826 v->set_is_used();
4827 v->set_is_type_switch_var();
4828 implicit_vars->push_back(this->gogo_->add_variable(var_name, v));
4830 this->statement_list();
4831 statements = this->gogo_->finish_block(this->location());
4834 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4836 go_error_at(this->location(),
4837 "fallthrough is not permitted in a type switch");
4838 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4839 this->advance_token();
4842 if (is_default)
4844 go_assert(types.empty());
4845 if (*saw_default)
4847 go_error_at(location, "multiple defaults in type switch");
4848 return;
4850 *saw_default = true;
4851 clauses->add(NULL, false, true, statements, location);
4853 else if (!types.empty())
4855 for (std::vector<Type*>::const_iterator p = types.begin();
4856 p + 1 != types.end();
4857 ++p)
4858 clauses->add(*p, true, false, NULL, location);
4859 clauses->add(types.back(), false, false, statements, location);
4861 else
4862 clauses->add(Type::make_error_type(), false, false, statements, location);
4865 // TypeSwitchCase = "case" type | "default"
4867 // We accept a comma separated list of types.
4869 void
4870 Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
4872 const Token* token = this->peek_token();
4873 if (token->is_keyword(KEYWORD_CASE))
4875 this->advance_token();
4876 while (true)
4878 Type* t = this->type();
4880 if (!t->is_error_type())
4881 types->push_back(t);
4882 else
4884 this->gogo_->mark_locals_used();
4885 token = this->peek_token();
4886 while (!token->is_op(OPERATOR_COLON)
4887 && !token->is_op(OPERATOR_COMMA)
4888 && !token->is_op(OPERATOR_RCURLY)
4889 && !token->is_eof())
4890 token = this->advance_token();
4893 if (!this->peek_token()->is_op(OPERATOR_COMMA))
4894 break;
4895 this->advance_token();
4898 else if (token->is_keyword(KEYWORD_DEFAULT))
4900 this->advance_token();
4901 *is_default = true;
4903 else
4905 go_error_at(this->location(), "expected %<case%> or %<default%>");
4906 if (!token->is_op(OPERATOR_RCURLY))
4907 this->advance_token();
4911 // SelectStat = "select" "{" { CommClause } "}" .
4913 void
4914 Parse::select_stat(Label* label)
4916 go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
4917 Location location = this->location();
4918 const Token* token = this->advance_token();
4920 if (!token->is_op(OPERATOR_LCURLY))
4922 Location token_loc = token->location();
4923 if (token->is_op(OPERATOR_SEMICOLON)
4924 && this->advance_token()->is_op(OPERATOR_LCURLY))
4925 go_error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4926 else
4928 go_error_at(this->location(), "expected %<{%>");
4929 return;
4932 this->advance_token();
4934 Select_statement* statement = Statement::make_select_statement(location);
4936 this->push_break_statement(statement, label);
4938 Select_clauses* select_clauses = new Select_clauses();
4939 bool saw_default = false;
4940 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4942 if (this->peek_token()->is_eof())
4944 go_error_at(this->location(), "expected %<}%>");
4945 return;
4947 this->comm_clause(select_clauses, &saw_default);
4950 this->advance_token();
4952 statement->add_clauses(select_clauses);
4954 this->pop_break_statement();
4956 this->gogo_->add_statement(statement);
4959 // CommClause = CommCase ":" { Statement ";" } .
4961 void
4962 Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
4964 Location location = this->location();
4965 bool is_send = false;
4966 Expression* channel = NULL;
4967 Expression* val = NULL;
4968 Expression* closed = NULL;
4969 std::string varname;
4970 std::string closedname;
4971 bool is_default = false;
4972 bool got_case = this->comm_case(&is_send, &channel, &val, &closed,
4973 &varname, &closedname, &is_default);
4975 if (this->peek_token()->is_op(OPERATOR_COLON))
4976 this->advance_token();
4977 else
4978 go_error_at(this->location(), "expected colon");
4980 this->gogo_->start_block(this->location());
4982 Named_object* var = NULL;
4983 if (!varname.empty())
4985 // FIXME: LOCATION is slightly wrong here.
4986 Variable* v = new Variable(NULL, channel, false, false, false,
4987 location);
4988 v->set_type_from_chan_element();
4989 var = this->gogo_->add_variable(varname, v);
4992 Named_object* closedvar = NULL;
4993 if (!closedname.empty())
4995 // FIXME: LOCATION is slightly wrong here.
4996 Variable* v = new Variable(Type::lookup_bool_type(), NULL,
4997 false, false, false, location);
4998 closedvar = this->gogo_->add_variable(closedname, v);
5001 this->statement_list();
5003 Block* statements = this->gogo_->finish_block(this->location());
5005 if (is_default)
5007 if (*saw_default)
5009 go_error_at(location, "multiple defaults in select");
5010 return;
5012 *saw_default = true;
5015 if (got_case)
5016 clauses->add(is_send, channel, val, closed, var, closedvar, is_default,
5017 statements, location);
5018 else if (statements != NULL)
5020 // Add the statements to make sure that any names they define
5021 // are traversed.
5022 this->gogo_->add_block(statements, location);
5026 // CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
5028 bool
5029 Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
5030 Expression** closed, std::string* varname,
5031 std::string* closedname, bool* is_default)
5033 const Token* token = this->peek_token();
5034 if (token->is_keyword(KEYWORD_DEFAULT))
5036 this->advance_token();
5037 *is_default = true;
5039 else if (token->is_keyword(KEYWORD_CASE))
5041 this->advance_token();
5042 if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname,
5043 closedname))
5044 return false;
5046 else
5048 go_error_at(this->location(), "expected %<case%> or %<default%>");
5049 if (!token->is_op(OPERATOR_RCURLY))
5050 this->advance_token();
5051 return false;
5054 return true;
5057 // RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
5058 // RecvExpr = Expression .
5060 bool
5061 Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val,
5062 Expression** closed, std::string* varname,
5063 std::string* closedname)
5065 const Token* token = this->peek_token();
5066 bool saw_comma = false;
5067 bool closed_is_id = false;
5068 if (token->is_identifier())
5070 Gogo* gogo = this->gogo_;
5071 std::string recv_var = token->identifier();
5072 bool is_rv_exported = token->is_identifier_exported();
5073 Location recv_var_loc = token->location();
5074 token = this->advance_token();
5075 if (token->is_op(OPERATOR_COLONEQ))
5077 // case rv := <-c:
5078 this->advance_token();
5079 Expression* e = this->expression(PRECEDENCE_NORMAL, false, false,
5080 NULL, NULL);
5081 Receive_expression* re = e->receive_expression();
5082 if (re == NULL)
5084 if (!e->is_error_expression())
5085 go_error_at(this->location(), "expected receive expression");
5086 return false;
5088 if (recv_var == "_")
5090 go_error_at(recv_var_loc,
5091 "no new variables on left side of %<:=%>");
5092 recv_var = Gogo::erroneous_name();
5094 *is_send = false;
5095 *varname = gogo->pack_hidden_name(recv_var, is_rv_exported);
5096 *channel = re->channel();
5097 return true;
5099 else if (token->is_op(OPERATOR_COMMA))
5101 token = this->advance_token();
5102 if (token->is_identifier())
5104 std::string recv_closed = token->identifier();
5105 bool is_rc_exported = token->is_identifier_exported();
5106 Location recv_closed_loc = token->location();
5107 closed_is_id = true;
5109 token = this->advance_token();
5110 if (token->is_op(OPERATOR_COLONEQ))
5112 // case rv, rc := <-c:
5113 this->advance_token();
5114 Expression* e = this->expression(PRECEDENCE_NORMAL, false,
5115 false, NULL, NULL);
5116 Receive_expression* re = e->receive_expression();
5117 if (re == NULL)
5119 if (!e->is_error_expression())
5120 go_error_at(this->location(),
5121 "expected receive expression");
5122 return false;
5124 if (recv_var == "_" && recv_closed == "_")
5126 go_error_at(recv_var_loc,
5127 "no new variables on left side of %<:=%>");
5128 recv_var = Gogo::erroneous_name();
5130 *is_send = false;
5131 if (recv_var != "_")
5132 *varname = gogo->pack_hidden_name(recv_var,
5133 is_rv_exported);
5134 if (recv_closed != "_")
5135 *closedname = gogo->pack_hidden_name(recv_closed,
5136 is_rc_exported);
5137 *channel = re->channel();
5138 return true;
5141 this->unget_token(Token::make_identifier_token(recv_closed,
5142 is_rc_exported,
5143 recv_closed_loc));
5146 *val = this->id_to_expression(gogo->pack_hidden_name(recv_var,
5147 is_rv_exported),
5148 recv_var_loc, true);
5149 saw_comma = true;
5151 else
5152 this->unget_token(Token::make_identifier_token(recv_var,
5153 is_rv_exported,
5154 recv_var_loc));
5157 // If SAW_COMMA is false, then we are looking at the start of the
5158 // send or receive expression. If SAW_COMMA is true, then *VAL is
5159 // set and we just read a comma.
5161 Expression* e;
5162 if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP))
5163 e = this->expression(PRECEDENCE_NORMAL, true, true, NULL, NULL);
5164 else
5166 // case <-c:
5167 *is_send = false;
5168 this->advance_token();
5169 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5171 // The next token should be ':'. If it is '<-', then we have
5172 // case <-c <- v:
5173 // which is to say, send on a channel received from a channel.
5174 if (!this->peek_token()->is_op(OPERATOR_CHANOP))
5175 return true;
5177 e = Expression::make_receive(*channel, (*channel)->location());
5180 if (!saw_comma && this->peek_token()->is_op(OPERATOR_COMMA))
5182 this->advance_token();
5183 // case v, e = <-c:
5184 if (!e->is_sink_expression())
5185 *val = e;
5186 e = this->expression(PRECEDENCE_NORMAL, true, true, NULL, NULL);
5187 saw_comma = true;
5190 if (this->peek_token()->is_op(OPERATOR_EQ))
5192 if (!this->advance_token()->is_op(OPERATOR_CHANOP))
5194 go_error_at(this->location(), "missing %<<-%>");
5195 return false;
5197 *is_send = false;
5198 this->advance_token();
5199 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5200 if (saw_comma)
5202 // case v, e = <-c:
5203 // *VAL is already set.
5204 if (!e->is_sink_expression())
5205 *closed = e;
5207 else
5209 // case v = <-c:
5210 if (!e->is_sink_expression())
5211 *val = e;
5213 return true;
5216 if (saw_comma)
5218 if (closed_is_id)
5219 go_error_at(this->location(), "expected %<=%> or %<:=%>");
5220 else
5221 go_error_at(this->location(), "expected %<=%>");
5222 return false;
5225 if (this->peek_token()->is_op(OPERATOR_CHANOP))
5227 // case c <- v:
5228 *is_send = true;
5229 *channel = this->verify_not_sink(e);
5230 this->advance_token();
5231 *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5232 return true;
5235 go_error_at(this->location(), "expected %<<-%> or %<=%>");
5236 return false;
5239 // ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
5240 // Condition = Expression .
5242 void
5243 Parse::for_stat(Label* label)
5245 go_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
5246 Location location = this->location();
5247 const Token* token = this->advance_token();
5249 // Open a block to hold any variables defined in the init statement
5250 // of the for statement.
5251 this->gogo_->start_block(location);
5253 Block* init = NULL;
5254 Expression* cond = NULL;
5255 Block* post = NULL;
5256 Range_clause range_clause;
5258 if (!token->is_op(OPERATOR_LCURLY))
5260 if (token->is_keyword(KEYWORD_VAR))
5262 go_error_at(this->location(),
5263 "var declaration not allowed in for initializer");
5264 this->var_decl();
5267 if (token->is_op(OPERATOR_SEMICOLON))
5268 this->for_clause(&cond, &post);
5269 else
5271 // We might be looking at a Condition, an InitStat, or a
5272 // RangeClause.
5273 bool saw_send_stmt;
5274 cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL);
5275 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5277 if (cond == NULL && !range_clause.found)
5279 if (saw_send_stmt)
5280 go_error_at(this->location(),
5281 ("send statement used as value; "
5282 "use select for non-blocking send"));
5283 else
5284 go_error_at(this->location(),
5285 "parse error in for statement");
5288 else
5290 if (range_clause.found)
5291 go_error_at(this->location(), "parse error after range clause");
5293 if (cond != NULL)
5295 // COND is actually an expression statement for
5296 // InitStat at the start of a ForClause.
5297 this->expression_stat(cond);
5298 cond = NULL;
5301 this->for_clause(&cond, &post);
5306 // Check for the easy error of a newline before starting the block.
5307 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5309 Location semi_loc = this->location();
5310 if (this->advance_token()->is_op(OPERATOR_LCURLY))
5311 go_error_at(semi_loc, "missing %<{%> after for clause");
5312 // Otherwise we will get an error when we call this->block
5313 // below.
5316 // Build the For_statement and note that it is the current target
5317 // for break and continue statements.
5319 For_statement* sfor;
5320 For_range_statement* srange;
5321 Statement* s;
5322 if (!range_clause.found)
5324 sfor = Statement::make_for_statement(init, cond, post, location);
5325 s = sfor;
5326 srange = NULL;
5328 else
5330 srange = Statement::make_for_range_statement(range_clause.index,
5331 range_clause.value,
5332 range_clause.range,
5333 location);
5334 s = srange;
5335 sfor = NULL;
5338 this->push_break_statement(s, label);
5339 this->push_continue_statement(s, label);
5341 // Gather the block of statements in the loop and add them to the
5342 // For_statement.
5344 this->gogo_->start_block(this->location());
5345 Location end_loc = this->block();
5346 Block* statements = this->gogo_->finish_block(end_loc);
5348 if (sfor != NULL)
5349 sfor->add_statements(statements);
5350 else
5351 srange->add_statements(statements);
5353 // This is no longer the break/continue target.
5354 this->pop_break_statement();
5355 this->pop_continue_statement();
5357 // Add the For_statement to the list of statements, and close out
5358 // the block we started to hold any variables defined in the for
5359 // statement.
5361 this->gogo_->add_statement(s);
5363 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
5364 location);
5367 // ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
5368 // InitStat = SimpleStat .
5369 // PostStat = SimpleStat .
5371 // We have already read InitStat at this point.
5373 void
5374 Parse::for_clause(Expression** cond, Block** post)
5376 go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
5377 this->advance_token();
5378 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5379 *cond = NULL;
5380 else if (this->peek_token()->is_op(OPERATOR_LCURLY))
5382 go_error_at(this->location(), "missing %<{%> after for clause");
5383 *cond = NULL;
5384 *post = NULL;
5385 return;
5387 else
5388 *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5389 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5390 go_error_at(this->location(), "expected semicolon");
5391 else
5392 this->advance_token();
5394 if (this->peek_token()->is_op(OPERATOR_LCURLY))
5395 *post = NULL;
5396 else
5398 this->gogo_->start_block(this->location());
5399 this->simple_stat(false, NULL, NULL, NULL);
5400 *post = this->gogo_->finish_block(this->location());
5404 // RangeClause = [ IdentifierList ( "=" | ":=" ) ] "range" Expression .
5406 // This is the := version. It is called with a list of identifiers.
5408 void
5409 Parse::range_clause_decl(const Typed_identifier_list* til,
5410 Range_clause* p_range_clause)
5412 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5413 Location location = this->location();
5415 p_range_clause->found = true;
5417 if (til->size() > 2)
5418 go_error_at(this->location(), "too many variables for range clause");
5420 this->advance_token();
5421 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL,
5422 NULL);
5423 p_range_clause->range = expr;
5425 if (til->empty())
5426 return;
5428 bool any_new = false;
5430 const Typed_identifier* pti = &til->front();
5431 Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new,
5432 NULL, NULL);
5433 if (any_new && no->is_variable())
5434 no->var_value()->set_type_from_range_index();
5435 p_range_clause->index = Expression::make_var_reference(no, location);
5437 if (til->size() == 1)
5438 p_range_clause->value = NULL;
5439 else
5441 pti = &til->back();
5442 bool is_new = false;
5443 no = this->init_var(*pti, NULL, expr, true, true, &is_new, NULL, NULL);
5444 if (is_new && no->is_variable())
5445 no->var_value()->set_type_from_range_value();
5446 if (is_new)
5447 any_new = true;
5448 if (!Gogo::is_sink_name(pti->name()))
5449 p_range_clause->value = Expression::make_var_reference(no, location);
5452 if (!any_new)
5453 go_error_at(location, "variables redeclared but no variable is new");
5456 // The = version of RangeClause. This is called with a list of
5457 // expressions.
5459 void
5460 Parse::range_clause_expr(const Expression_list* vals,
5461 Range_clause* p_range_clause)
5463 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5465 p_range_clause->found = true;
5467 go_assert(vals->size() >= 1);
5468 if (vals->size() > 2)
5469 go_error_at(this->location(), "too many variables for range clause");
5471 this->advance_token();
5472 p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
5473 NULL, NULL);
5475 if (vals->empty())
5476 return;
5478 p_range_clause->index = vals->front();
5479 if (vals->size() == 1)
5480 p_range_clause->value = NULL;
5481 else
5482 p_range_clause->value = vals->back();
5485 // Push a statement on the break stack.
5487 void
5488 Parse::push_break_statement(Statement* enclosing, Label* label)
5490 if (this->break_stack_ == NULL)
5491 this->break_stack_ = new Bc_stack();
5492 this->break_stack_->push_back(std::make_pair(enclosing, label));
5495 // Push a statement on the continue stack.
5497 void
5498 Parse::push_continue_statement(Statement* enclosing, Label* label)
5500 if (this->continue_stack_ == NULL)
5501 this->continue_stack_ = new Bc_stack();
5502 this->continue_stack_->push_back(std::make_pair(enclosing, label));
5505 // Pop the break stack.
5507 void
5508 Parse::pop_break_statement()
5510 this->break_stack_->pop_back();
5513 // Pop the continue stack.
5515 void
5516 Parse::pop_continue_statement()
5518 this->continue_stack_->pop_back();
5521 // Find a break or continue statement given a label name.
5523 Statement*
5524 Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
5526 if (bc_stack == NULL)
5527 return NULL;
5528 for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
5529 p != bc_stack->rend();
5530 ++p)
5532 if (p->second != NULL && p->second->name() == label)
5534 p->second->set_is_used();
5535 return p->first;
5538 return NULL;
5541 // BreakStat = "break" [ identifier ] .
5543 void
5544 Parse::break_stat()
5546 go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
5547 Location location = this->location();
5549 const Token* token = this->advance_token();
5550 Statement* enclosing;
5551 if (!token->is_identifier())
5553 if (this->break_stack_ == NULL || this->break_stack_->empty())
5555 go_error_at(this->location(),
5556 "break statement not within for or switch or select");
5557 return;
5559 enclosing = this->break_stack_->back().first;
5561 else
5563 enclosing = this->find_bc_statement(this->break_stack_,
5564 token->identifier());
5565 if (enclosing == NULL)
5567 // If there is a label with this name, mark it as used to
5568 // avoid a useless error about an unused label.
5569 this->gogo_->add_label_reference(token->identifier(),
5570 Linemap::unknown_location(), false);
5572 go_error_at(token->location(), "invalid break label %qs",
5573 Gogo::message_name(token->identifier()).c_str());
5574 this->advance_token();
5575 return;
5577 this->advance_token();
5580 Unnamed_label* label;
5581 if (enclosing->classification() == Statement::STATEMENT_FOR)
5582 label = enclosing->for_statement()->break_label();
5583 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5584 label = enclosing->for_range_statement()->break_label();
5585 else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
5586 label = enclosing->switch_statement()->break_label();
5587 else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
5588 label = enclosing->type_switch_statement()->break_label();
5589 else if (enclosing->classification() == Statement::STATEMENT_SELECT)
5590 label = enclosing->select_statement()->break_label();
5591 else
5592 go_unreachable();
5594 this->gogo_->add_statement(Statement::make_break_statement(label,
5595 location));
5598 // ContinueStat = "continue" [ identifier ] .
5600 void
5601 Parse::continue_stat()
5603 go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
5604 Location location = this->location();
5606 const Token* token = this->advance_token();
5607 Statement* enclosing;
5608 if (!token->is_identifier())
5610 if (this->continue_stack_ == NULL || this->continue_stack_->empty())
5612 go_error_at(this->location(), "continue statement not within for");
5613 return;
5615 enclosing = this->continue_stack_->back().first;
5617 else
5619 enclosing = this->find_bc_statement(this->continue_stack_,
5620 token->identifier());
5621 if (enclosing == NULL)
5623 // If there is a label with this name, mark it as used to
5624 // avoid a useless error about an unused label.
5625 this->gogo_->add_label_reference(token->identifier(),
5626 Linemap::unknown_location(), false);
5628 go_error_at(token->location(), "invalid continue label %qs",
5629 Gogo::message_name(token->identifier()).c_str());
5630 this->advance_token();
5631 return;
5633 this->advance_token();
5636 Unnamed_label* label;
5637 if (enclosing->classification() == Statement::STATEMENT_FOR)
5638 label = enclosing->for_statement()->continue_label();
5639 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5640 label = enclosing->for_range_statement()->continue_label();
5641 else
5642 go_unreachable();
5644 this->gogo_->add_statement(Statement::make_continue_statement(label,
5645 location));
5648 // GotoStat = "goto" identifier .
5650 void
5651 Parse::goto_stat()
5653 go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
5654 Location location = this->location();
5655 const Token* token = this->advance_token();
5656 if (!token->is_identifier())
5657 go_error_at(this->location(), "expected label for goto");
5658 else
5660 Label* label = this->gogo_->add_label_reference(token->identifier(),
5661 location, true);
5662 Statement* s = Statement::make_goto_statement(label, location);
5663 this->gogo_->add_statement(s);
5664 this->advance_token();
5668 // PackageClause = "package" PackageName .
5670 void
5671 Parse::package_clause()
5673 const Token* token = this->peek_token();
5674 Location location = token->location();
5675 std::string name;
5676 if (!token->is_keyword(KEYWORD_PACKAGE))
5678 go_error_at(this->location(), "program must start with package clause");
5679 name = "ERROR";
5681 else
5683 token = this->advance_token();
5684 if (token->is_identifier())
5686 name = token->identifier();
5687 if (name == "_")
5689 go_error_at(this->location(), "invalid package name _");
5690 name = Gogo::erroneous_name();
5692 this->advance_token();
5694 else
5696 go_error_at(this->location(), "package name must be an identifier");
5697 name = "ERROR";
5700 this->gogo_->set_package_name(name, location);
5703 // ImportDecl = "import" Decl<ImportSpec> .
5705 void
5706 Parse::import_decl()
5708 go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
5709 this->advance_token();
5710 this->decl(&Parse::import_spec, NULL, 0);
5713 // ImportSpec = [ "." | PackageName ] PackageFileName .
5715 void
5716 Parse::import_spec(void*, unsigned int pragmas)
5718 if (pragmas != 0)
5719 go_warning_at(this->location(), 0,
5720 "ignoring magic //go:... comment before import");
5722 const Token* token = this->peek_token();
5723 Location location = token->location();
5725 std::string local_name;
5726 bool is_local_name_exported = false;
5727 if (token->is_op(OPERATOR_DOT))
5729 local_name = ".";
5730 token = this->advance_token();
5732 else if (token->is_identifier())
5734 local_name = token->identifier();
5735 is_local_name_exported = token->is_identifier_exported();
5736 token = this->advance_token();
5739 if (!token->is_string())
5741 go_error_at(this->location(), "import statement not a string");
5742 this->advance_token();
5743 return;
5746 this->gogo_->import_package(token->string_value(), local_name,
5747 is_local_name_exported, true, location);
5749 this->advance_token();
5752 // SourceFile = PackageClause ";" { ImportDecl ";" }
5753 // { TopLevelDecl ";" } .
5755 void
5756 Parse::program()
5758 this->package_clause();
5760 const Token* token = this->peek_token();
5761 if (token->is_op(OPERATOR_SEMICOLON))
5762 token = this->advance_token();
5763 else
5764 go_error_at(this->location(),
5765 "expected %<;%> or newline after package clause");
5767 while (token->is_keyword(KEYWORD_IMPORT))
5769 this->import_decl();
5770 token = this->peek_token();
5771 if (token->is_op(OPERATOR_SEMICOLON))
5772 token = this->advance_token();
5773 else
5774 go_error_at(this->location(),
5775 "expected %<;%> or newline after import declaration");
5778 while (!token->is_eof())
5780 if (this->declaration_may_start_here())
5781 this->declaration();
5782 else
5784 go_error_at(this->location(), "expected declaration");
5785 this->gogo_->mark_locals_used();
5787 this->advance_token();
5788 while (!this->peek_token()->is_eof()
5789 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
5790 && !this->peek_token()->is_op(OPERATOR_RCURLY));
5791 if (!this->peek_token()->is_eof()
5792 && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
5793 this->advance_token();
5795 token = this->peek_token();
5796 if (token->is_op(OPERATOR_SEMICOLON))
5797 token = this->advance_token();
5798 else if (!token->is_eof() || !saw_errors())
5800 if (token->is_op(OPERATOR_CHANOP))
5801 go_error_at(this->location(),
5802 ("send statement used as value; "
5803 "use select for non-blocking send"));
5804 else
5805 go_error_at(this->location(),
5806 ("expected %<;%> or newline after top "
5807 "level declaration"));
5808 this->skip_past_error(OPERATOR_INVALID);
5813 // Reset the current iota value.
5815 void
5816 Parse::reset_iota()
5818 this->iota_ = 0;
5821 // Return the current iota value.
5824 Parse::iota_value()
5826 return this->iota_;
5829 // Increment the current iota value.
5831 void
5832 Parse::increment_iota()
5834 ++this->iota_;
5837 // Skip forward to a semicolon or OP. OP will normally be
5838 // OPERATOR_RPAREN or OPERATOR_RCURLY. If we find a semicolon, move
5839 // past it and return. If we find OP, it will be the next token to
5840 // read. Return true if we are OK, false if we found EOF.
5842 bool
5843 Parse::skip_past_error(Operator op)
5845 this->gogo_->mark_locals_used();
5846 const Token* token = this->peek_token();
5847 while (!token->is_op(op))
5849 if (token->is_eof())
5850 return false;
5851 if (token->is_op(OPERATOR_SEMICOLON))
5853 this->advance_token();
5854 return true;
5856 token = this->advance_token();
5858 return true;
5861 // Check that an expression is not a sink.
5863 Expression*
5864 Parse::verify_not_sink(Expression* expr)
5866 if (expr->is_sink_expression())
5868 go_error_at(expr->location(), "cannot use _ as value");
5869 expr = Expression::make_error(expr->location());
5872 // If this can not be a sink, and it is a variable, then we are
5873 // using the variable, not just assigning to it.
5874 if (expr->var_expression() != NULL)
5875 this->mark_var_used(expr->var_expression()->named_object());
5876 else if (expr->enclosed_var_expression() != NULL)
5877 this->mark_var_used(expr->enclosed_var_expression()->variable());
5878 return expr;
5881 // Mark a variable as used.
5883 void
5884 Parse::mark_var_used(Named_object* no)
5886 if (no->is_variable())
5887 no->var_value()->set_is_used();