Daily bump.
[official-gcc.git] / gcc / go / gofrontend / parse.cc
bloba4e4ae344b671dc059e6ab7964deff59007c670b
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 enclosing_vars_()
57 // Return the current token.
59 const Token*
60 Parse::peek_token()
62 if (this->unget_token_valid_)
63 return &this->unget_token_;
64 if (this->token_.is_invalid())
65 this->token_ = this->lex_->next_token();
66 return &this->token_;
69 // Advance to the next token and return it.
71 const Token*
72 Parse::advance_token()
74 if (this->unget_token_valid_)
76 this->unget_token_valid_ = false;
77 if (!this->token_.is_invalid())
78 return &this->token_;
80 this->token_ = this->lex_->next_token();
81 return &this->token_;
84 // Push a token back on the input stream.
86 void
87 Parse::unget_token(const Token& token)
89 go_assert(!this->unget_token_valid_);
90 this->unget_token_ = token;
91 this->unget_token_valid_ = true;
94 // The location of the current token.
96 Location
97 Parse::location()
99 return this->peek_token()->location();
102 // IdentifierList = identifier { "," identifier } .
104 void
105 Parse::identifier_list(Typed_identifier_list* til)
107 const Token* token = this->peek_token();
108 while (true)
110 if (!token->is_identifier())
112 go_error_at(this->location(), "expected identifier");
113 return;
115 std::string name =
116 this->gogo_->pack_hidden_name(token->identifier(),
117 token->is_identifier_exported());
118 til->push_back(Typed_identifier(name, NULL, token->location()));
119 token = this->advance_token();
120 if (!token->is_op(OPERATOR_COMMA))
121 return;
122 token = this->advance_token();
126 // ExpressionList = Expression { "," Expression } .
128 // If MAY_BE_COMPOSITE_LIT is true, an expression may be a composite
129 // literal.
131 // If MAY_BE_SINK is true, the expressions in the list may be "_".
133 Expression_list*
134 Parse::expression_list(Expression* first, bool may_be_sink,
135 bool may_be_composite_lit)
137 Expression_list* ret = new Expression_list();
138 if (first != NULL)
139 ret->push_back(first);
140 while (true)
142 ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink,
143 may_be_composite_lit, NULL, NULL));
145 const Token* token = this->peek_token();
146 if (!token->is_op(OPERATOR_COMMA))
147 return ret;
149 // Most expression lists permit a trailing comma.
150 Location location = token->location();
151 this->advance_token();
152 if (!this->expression_may_start_here())
154 this->unget_token(Token::make_operator_token(OPERATOR_COMMA,
155 location));
156 return ret;
161 // QualifiedIdent = [ PackageName "." ] identifier .
162 // PackageName = identifier .
164 // This sets *PNAME to the identifier and sets *PPACKAGE to the
165 // package or NULL if there isn't one. This returns true on success,
166 // false on failure in which case it will have emitted an error
167 // message.
169 bool
170 Parse::qualified_ident(std::string* pname, Named_object** ppackage)
172 const Token* token = this->peek_token();
173 if (!token->is_identifier())
175 go_error_at(this->location(), "expected identifier");
176 return false;
179 std::string name = token->identifier();
180 bool is_exported = token->is_identifier_exported();
181 name = this->gogo_->pack_hidden_name(name, is_exported);
183 token = this->advance_token();
184 if (!token->is_op(OPERATOR_DOT))
186 *pname = name;
187 *ppackage = NULL;
188 return true;
191 Named_object* package = this->gogo_->lookup(name, NULL);
192 if (package == NULL || !package->is_package())
194 if (package == NULL)
195 go_error_at(this->location(), "reference to undefined name %qs",
196 Gogo::message_name(name).c_str());
197 else
198 go_error_at(this->location(), "expected package");
199 // We expect . IDENTIFIER; skip both.
200 if (this->advance_token()->is_identifier())
201 this->advance_token();
202 return false;
205 package->package_value()->note_usage(Gogo::unpack_hidden_name(name));
207 token = this->advance_token();
208 if (!token->is_identifier())
210 go_error_at(this->location(), "expected identifier");
211 return false;
214 name = token->identifier();
216 if (name == "_")
218 go_error_at(this->location(), "invalid use of %<_%>");
219 name = Gogo::erroneous_name();
222 if (package->name() == this->gogo_->package_name())
223 name = this->gogo_->pack_hidden_name(name,
224 token->is_identifier_exported());
226 *pname = name;
227 *ppackage = package;
229 this->advance_token();
231 return true;
234 // Type = TypeName | TypeLit | "(" Type ")" .
235 // TypeLit =
236 // ArrayType | StructType | PointerType | FunctionType | InterfaceType |
237 // SliceType | MapType | ChannelType .
239 Type*
240 Parse::type()
242 const Token* token = this->peek_token();
243 if (token->is_identifier())
244 return this->type_name(true);
245 else if (token->is_op(OPERATOR_LSQUARE))
246 return this->array_type(false);
247 else if (token->is_keyword(KEYWORD_CHAN)
248 || token->is_op(OPERATOR_CHANOP))
249 return this->channel_type();
250 else if (token->is_keyword(KEYWORD_INTERFACE))
251 return this->interface_type(true);
252 else if (token->is_keyword(KEYWORD_FUNC))
254 Location location = token->location();
255 this->advance_token();
256 Type* type = this->signature(NULL, location);
257 if (type == NULL)
258 return Type::make_error_type();
259 return type;
261 else if (token->is_keyword(KEYWORD_MAP))
262 return this->map_type();
263 else if (token->is_keyword(KEYWORD_STRUCT))
264 return this->struct_type();
265 else if (token->is_op(OPERATOR_MULT))
266 return this->pointer_type();
267 else if (token->is_op(OPERATOR_LPAREN))
269 this->advance_token();
270 Type* ret = this->type();
271 if (this->peek_token()->is_op(OPERATOR_RPAREN))
272 this->advance_token();
273 else
275 if (!ret->is_error_type())
276 go_error_at(this->location(), "expected %<)%>");
278 return ret;
280 else
282 go_error_at(token->location(), "expected type");
283 return Type::make_error_type();
287 bool
288 Parse::type_may_start_here()
290 const Token* token = this->peek_token();
291 return (token->is_identifier()
292 || token->is_op(OPERATOR_LSQUARE)
293 || token->is_op(OPERATOR_CHANOP)
294 || token->is_keyword(KEYWORD_CHAN)
295 || token->is_keyword(KEYWORD_INTERFACE)
296 || token->is_keyword(KEYWORD_FUNC)
297 || token->is_keyword(KEYWORD_MAP)
298 || token->is_keyword(KEYWORD_STRUCT)
299 || token->is_op(OPERATOR_MULT)
300 || token->is_op(OPERATOR_LPAREN));
303 // TypeName = QualifiedIdent .
305 // If MAY_BE_NIL is true, then an identifier with the value of the
306 // predefined constant nil is accepted, returning the nil type.
308 Type*
309 Parse::type_name(bool issue_error)
311 Location location = this->location();
313 std::string name;
314 Named_object* package;
315 if (!this->qualified_ident(&name, &package))
316 return Type::make_error_type();
318 Named_object* named_object;
319 if (package == NULL)
320 named_object = this->gogo_->lookup(name, NULL);
321 else
323 named_object = package->package_value()->lookup(name);
324 if (named_object == NULL
325 && issue_error
326 && package->name() != this->gogo_->package_name())
328 // Check whether the name is there but hidden.
329 std::string s = ('.' + package->package_value()->pkgpath()
330 + '.' + name);
331 named_object = package->package_value()->lookup(s);
332 if (named_object != NULL)
334 Package* p = package->package_value();
335 const std::string& packname(p->package_name());
336 go_error_at(location,
337 "invalid reference to hidden type %<%s.%s%>",
338 Gogo::message_name(packname).c_str(),
339 Gogo::message_name(name).c_str());
340 issue_error = false;
345 bool ok = true;
346 if (named_object == NULL)
348 if (package == NULL)
349 named_object = this->gogo_->add_unknown_name(name, location);
350 else
352 const std::string& packname(package->package_value()->package_name());
353 go_error_at(location, "reference to undefined identifier %<%s.%s%>",
354 Gogo::message_name(packname).c_str(),
355 Gogo::message_name(name).c_str());
356 issue_error = false;
357 ok = false;
360 else if (named_object->is_type())
362 if (!named_object->type_value()->is_visible())
363 ok = false;
365 else if (named_object->is_unknown() || named_object->is_type_declaration())
367 else
368 ok = false;
370 if (!ok)
372 if (issue_error)
373 go_error_at(location, "expected type");
374 return Type::make_error_type();
377 if (named_object->is_type())
378 return named_object->type_value();
379 else if (named_object->is_unknown() || named_object->is_type_declaration())
380 return Type::make_forward_declaration(named_object);
381 else
382 go_unreachable();
385 // ArrayType = "[" [ ArrayLength ] "]" ElementType .
386 // ArrayLength = Expression .
387 // ElementType = CompleteType .
389 Type*
390 Parse::array_type(bool may_use_ellipsis)
392 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
393 const Token* token = this->advance_token();
395 Expression* length = NULL;
396 if (token->is_op(OPERATOR_RSQUARE))
397 this->advance_token();
398 else
400 if (!token->is_op(OPERATOR_ELLIPSIS))
401 length = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
402 else if (may_use_ellipsis)
404 // An ellipsis is used in composite literals to represent a
405 // fixed array of the size of the number of elements. We
406 // use a length of nil to represent this, and change the
407 // length when parsing the composite literal.
408 length = Expression::make_nil(this->location());
409 this->advance_token();
411 else
413 go_error_at(this->location(),
414 "use of %<[...]%> outside of array literal");
415 length = Expression::make_error(this->location());
416 this->advance_token();
418 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
420 go_error_at(this->location(), "expected %<]%>");
421 return Type::make_error_type();
423 this->advance_token();
426 Type* element_type = this->type();
427 if (element_type->is_error_type())
428 return Type::make_error_type();
430 return Type::make_array_type(element_type, length);
433 // MapType = "map" "[" KeyType "]" ValueType .
434 // KeyType = CompleteType .
435 // ValueType = CompleteType .
437 Type*
438 Parse::map_type()
440 Location location = this->location();
441 go_assert(this->peek_token()->is_keyword(KEYWORD_MAP));
442 if (!this->advance_token()->is_op(OPERATOR_LSQUARE))
444 go_error_at(this->location(), "expected %<[%>");
445 return Type::make_error_type();
447 this->advance_token();
449 Type* key_type = this->type();
451 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
453 go_error_at(this->location(), "expected %<]%>");
454 return Type::make_error_type();
456 this->advance_token();
458 Type* value_type = this->type();
460 if (key_type->is_error_type() || value_type->is_error_type())
461 return Type::make_error_type();
463 return Type::make_map_type(key_type, value_type, location);
466 // StructType = "struct" "{" { FieldDecl ";" } "}" .
468 Type*
469 Parse::struct_type()
471 go_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT));
472 Location location = this->location();
473 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
475 Location token_loc = this->location();
476 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
477 && this->advance_token()->is_op(OPERATOR_LCURLY))
478 go_error_at(token_loc, "unexpected semicolon or newline before %<{%>");
479 else
481 go_error_at(this->location(), "expected %<{%>");
482 return Type::make_error_type();
485 this->advance_token();
487 Struct_field_list* sfl = new Struct_field_list;
488 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
490 this->field_decl(sfl);
491 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
492 this->advance_token();
493 else if (!this->peek_token()->is_op(OPERATOR_RCURLY))
495 go_error_at(this->location(), "expected %<;%> or %<}%> or newline");
496 if (!this->skip_past_error(OPERATOR_RCURLY))
497 return Type::make_error_type();
500 this->advance_token();
502 for (Struct_field_list::const_iterator pi = sfl->begin();
503 pi != sfl->end();
504 ++pi)
506 if (pi->type()->is_error_type())
507 return pi->type();
508 for (Struct_field_list::const_iterator pj = pi + 1;
509 pj != sfl->end();
510 ++pj)
512 if (pi->field_name() == pj->field_name()
513 && !Gogo::is_sink_name(pi->field_name()))
514 go_error_at(pi->location(), "duplicate field name %<%s%>",
515 Gogo::message_name(pi->field_name()).c_str());
519 return Type::make_struct_type(sfl, location);
522 // FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] .
523 // Tag = string_lit .
525 void
526 Parse::field_decl(Struct_field_list* sfl)
528 const Token* token = this->peek_token();
529 Location location = token->location();
530 bool is_anonymous;
531 bool is_anonymous_pointer;
532 if (token->is_op(OPERATOR_MULT))
534 is_anonymous = true;
535 is_anonymous_pointer = true;
537 else if (token->is_identifier())
539 std::string id = token->identifier();
540 bool is_id_exported = token->is_identifier_exported();
541 Location id_location = token->location();
542 token = this->advance_token();
543 is_anonymous = (token->is_op(OPERATOR_SEMICOLON)
544 || token->is_op(OPERATOR_RCURLY)
545 || token->is_op(OPERATOR_DOT)
546 || token->is_string());
547 is_anonymous_pointer = false;
548 this->unget_token(Token::make_identifier_token(id, is_id_exported,
549 id_location));
551 else
553 go_error_at(this->location(), "expected field name");
554 this->gogo_->mark_locals_used();
555 while (!token->is_op(OPERATOR_SEMICOLON)
556 && !token->is_op(OPERATOR_RCURLY)
557 && !token->is_eof())
558 token = this->advance_token();
559 return;
562 if (is_anonymous)
564 if (is_anonymous_pointer)
566 this->advance_token();
567 if (!this->peek_token()->is_identifier())
569 go_error_at(this->location(), "expected field name");
570 this->gogo_->mark_locals_used();
571 while (!token->is_op(OPERATOR_SEMICOLON)
572 && !token->is_op(OPERATOR_RCURLY)
573 && !token->is_eof())
574 token = this->advance_token();
575 return;
578 Type* type = this->type_name(true);
580 std::string tag;
581 if (this->peek_token()->is_string())
583 tag = this->peek_token()->string_value();
584 this->advance_token();
587 if (!type->is_error_type())
589 if (is_anonymous_pointer)
590 type = Type::make_pointer_type(type);
591 sfl->push_back(Struct_field(Typed_identifier("", type, location)));
592 if (!tag.empty())
593 sfl->back().set_tag(tag);
596 else
598 Typed_identifier_list til;
599 while (true)
601 token = this->peek_token();
602 if (!token->is_identifier())
604 go_error_at(this->location(), "expected identifier");
605 return;
607 std::string name =
608 this->gogo_->pack_hidden_name(token->identifier(),
609 token->is_identifier_exported());
610 til.push_back(Typed_identifier(name, NULL, token->location()));
611 if (!this->advance_token()->is_op(OPERATOR_COMMA))
612 break;
613 this->advance_token();
616 Type* type = this->type();
618 std::string tag;
619 if (this->peek_token()->is_string())
621 tag = this->peek_token()->string_value();
622 this->advance_token();
625 for (Typed_identifier_list::iterator p = til.begin();
626 p != til.end();
627 ++p)
629 p->set_type(type);
630 sfl->push_back(Struct_field(*p));
631 if (!tag.empty())
632 sfl->back().set_tag(tag);
637 // PointerType = "*" Type .
639 Type*
640 Parse::pointer_type()
642 go_assert(this->peek_token()->is_op(OPERATOR_MULT));
643 this->advance_token();
644 Type* type = this->type();
645 if (type->is_error_type())
646 return type;
647 return Type::make_pointer_type(type);
650 // ChannelType = Channel | SendChannel | RecvChannel .
651 // Channel = "chan" ElementType .
652 // SendChannel = "chan" "<-" ElementType .
653 // RecvChannel = "<-" "chan" ElementType .
655 Type*
656 Parse::channel_type()
658 const Token* token = this->peek_token();
659 bool send = true;
660 bool receive = true;
661 if (token->is_op(OPERATOR_CHANOP))
663 if (!this->advance_token()->is_keyword(KEYWORD_CHAN))
665 go_error_at(this->location(), "expected %<chan%>");
666 return Type::make_error_type();
668 send = false;
669 this->advance_token();
671 else
673 go_assert(token->is_keyword(KEYWORD_CHAN));
674 if (this->advance_token()->is_op(OPERATOR_CHANOP))
676 receive = false;
677 this->advance_token();
681 // Better error messages for the common error of omitting the
682 // channel element type.
683 if (!this->type_may_start_here())
685 token = this->peek_token();
686 if (token->is_op(OPERATOR_RCURLY))
687 go_error_at(this->location(), "unexpected %<}%> in channel type");
688 else if (token->is_op(OPERATOR_RPAREN))
689 go_error_at(this->location(), "unexpected %<)%> in channel type");
690 else if (token->is_op(OPERATOR_COMMA))
691 go_error_at(this->location(), "unexpected comma in channel type");
692 else
693 go_error_at(this->location(), "expected channel element type");
694 return Type::make_error_type();
697 Type* element_type = this->type();
698 return Type::make_channel_type(send, receive, element_type);
701 // Give an error for a duplicate parameter or receiver name.
703 void
704 Parse::check_signature_names(const Typed_identifier_list* params,
705 Parse::Names* names)
707 for (Typed_identifier_list::const_iterator p = params->begin();
708 p != params->end();
709 ++p)
711 if (p->name().empty() || Gogo::is_sink_name(p->name()))
712 continue;
713 std::pair<std::string, const Typed_identifier*> val =
714 std::make_pair(p->name(), &*p);
715 std::pair<Parse::Names::iterator, bool> ins = names->insert(val);
716 if (!ins.second)
718 go_error_at(p->location(), "redefinition of %qs",
719 Gogo::message_name(p->name()).c_str());
720 go_inform(ins.first->second->location(),
721 "previous definition of %qs was here",
722 Gogo::message_name(p->name()).c_str());
727 // Signature = Parameters [ Result ] .
729 // RECEIVER is the receiver if there is one, or NULL. LOCATION is the
730 // location of the start of the type.
732 // This returns NULL on a parse error.
734 Function_type*
735 Parse::signature(Typed_identifier* receiver, Location location)
737 bool is_varargs = false;
738 Typed_identifier_list* params;
739 bool params_ok = this->parameters(&params, &is_varargs);
741 Typed_identifier_list* results = NULL;
742 if (this->peek_token()->is_op(OPERATOR_LPAREN)
743 || this->type_may_start_here())
745 if (!this->result(&results))
746 return NULL;
749 if (!params_ok)
750 return NULL;
752 Parse::Names names;
753 if (receiver != NULL)
754 names[receiver->name()] = receiver;
755 if (params != NULL)
756 this->check_signature_names(params, &names);
757 if (results != NULL)
758 this->check_signature_names(results, &names);
760 Function_type* ret = Type::make_function_type(receiver, params, results,
761 location);
762 if (is_varargs)
763 ret->set_is_varargs();
764 return ret;
767 // Parameters = "(" [ ParameterList [ "," ] ] ")" .
769 // This returns false on a parse error.
771 bool
772 Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs)
774 *pparams = NULL;
776 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
778 go_error_at(this->location(), "expected %<(%>");
779 return false;
782 Typed_identifier_list* params = NULL;
783 bool saw_error = false;
785 const Token* token = this->advance_token();
786 if (!token->is_op(OPERATOR_RPAREN))
788 params = this->parameter_list(is_varargs);
789 if (params == NULL)
790 saw_error = true;
791 token = this->peek_token();
794 // The optional trailing comma is picked up in parameter_list.
796 if (!token->is_op(OPERATOR_RPAREN))
798 go_error_at(this->location(), "expected %<)%>");
799 return false;
801 this->advance_token();
803 if (saw_error)
804 return false;
806 *pparams = params;
807 return true;
810 // ParameterList = ParameterDecl { "," ParameterDecl } .
812 // This sets *IS_VARARGS if the list ends with an ellipsis.
813 // IS_VARARGS will be NULL if varargs are not permitted.
815 // We pick up an optional trailing comma.
817 // This returns NULL if some error is seen.
819 Typed_identifier_list*
820 Parse::parameter_list(bool* is_varargs)
822 Location location = this->location();
823 Typed_identifier_list* ret = new Typed_identifier_list();
825 bool saw_error = false;
827 // If we see an identifier and then a comma, then we don't know
828 // whether we are looking at a list of identifiers followed by a
829 // type, or a list of types given by name. We have to do an
830 // arbitrary lookahead to figure it out.
832 bool parameters_have_names;
833 const Token* token = this->peek_token();
834 if (!token->is_identifier())
836 // This must be a type which starts with something like '*'.
837 parameters_have_names = false;
839 else
841 std::string name = token->identifier();
842 bool is_exported = token->is_identifier_exported();
843 Location id_location = token->location();
844 token = this->advance_token();
845 if (!token->is_op(OPERATOR_COMMA))
847 if (token->is_op(OPERATOR_DOT))
849 // This is a qualified identifier, which must turn out
850 // to be a type.
851 parameters_have_names = false;
853 else if (token->is_op(OPERATOR_RPAREN))
855 // A single identifier followed by a parenthesis must be
856 // a type name.
857 parameters_have_names = false;
859 else
861 // An identifier followed by something other than a
862 // comma or a dot or a right parenthesis must be a
863 // parameter name followed by a type.
864 parameters_have_names = true;
867 this->unget_token(Token::make_identifier_token(name, is_exported,
868 id_location));
870 else
872 // An identifier followed by a comma may be the first in a
873 // list of parameter names followed by a type, or it may be
874 // the first in a list of types without parameter names. To
875 // find out we gather as many identifiers separated by
876 // commas as we can.
877 std::string id_name = this->gogo_->pack_hidden_name(name,
878 is_exported);
879 ret->push_back(Typed_identifier(id_name, NULL, id_location));
880 bool just_saw_comma = true;
881 while (this->advance_token()->is_identifier())
883 name = this->peek_token()->identifier();
884 is_exported = this->peek_token()->is_identifier_exported();
885 id_location = this->peek_token()->location();
886 id_name = this->gogo_->pack_hidden_name(name, is_exported);
887 ret->push_back(Typed_identifier(id_name, NULL, id_location));
888 if (!this->advance_token()->is_op(OPERATOR_COMMA))
890 just_saw_comma = false;
891 break;
895 if (just_saw_comma)
897 // We saw ID1 "," ID2 "," followed by something which
898 // was not an identifier. We must be seeing the start
899 // of a type, and ID1 and ID2 must be types, and the
900 // parameters don't have names.
901 parameters_have_names = false;
903 else if (this->peek_token()->is_op(OPERATOR_RPAREN))
905 // We saw ID1 "," ID2 ")". ID1 and ID2 must be types,
906 // and the parameters don't have names.
907 parameters_have_names = false;
909 else if (this->peek_token()->is_op(OPERATOR_DOT))
911 // We saw ID1 "," ID2 ".". ID2 must be a package name,
912 // ID1 must be a type, and the parameters don't have
913 // names.
914 parameters_have_names = false;
915 this->unget_token(Token::make_identifier_token(name, is_exported,
916 id_location));
917 ret->pop_back();
918 just_saw_comma = true;
920 else
922 // We saw ID1 "," ID2 followed by something other than
923 // ",", ".", or ")". We must be looking at the start of
924 // a type, and ID1 and ID2 must be parameter names.
925 parameters_have_names = true;
928 if (parameters_have_names)
930 go_assert(!just_saw_comma);
931 // We have just seen ID1, ID2 xxx.
932 Type* type;
933 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
934 type = this->type();
935 else
937 go_error_at(this->location(),
938 "%<...%> only permits one name");
939 saw_error = true;
940 this->advance_token();
941 type = this->type();
943 for (size_t i = 0; i < ret->size(); ++i)
944 ret->set_type(i, type);
945 if (!this->peek_token()->is_op(OPERATOR_COMMA))
946 return saw_error ? NULL : ret;
947 if (this->advance_token()->is_op(OPERATOR_RPAREN))
948 return saw_error ? NULL : ret;
950 else
952 Typed_identifier_list* tret = new Typed_identifier_list();
953 for (Typed_identifier_list::const_iterator p = ret->begin();
954 p != ret->end();
955 ++p)
957 Named_object* no = this->gogo_->lookup(p->name(), NULL);
958 Type* type;
959 if (no == NULL)
960 no = this->gogo_->add_unknown_name(p->name(),
961 p->location());
963 if (no->is_type())
964 type = no->type_value();
965 else if (no->is_unknown() || no->is_type_declaration())
966 type = Type::make_forward_declaration(no);
967 else
969 go_error_at(p->location(), "expected %<%s%> to be a type",
970 Gogo::message_name(p->name()).c_str());
971 saw_error = true;
972 type = Type::make_error_type();
974 tret->push_back(Typed_identifier("", type, p->location()));
976 delete ret;
977 ret = tret;
978 if (!just_saw_comma
979 || this->peek_token()->is_op(OPERATOR_RPAREN))
980 return saw_error ? NULL : ret;
985 bool mix_error = false;
986 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error,
987 &saw_error);
988 while (this->peek_token()->is_op(OPERATOR_COMMA))
990 if (this->advance_token()->is_op(OPERATOR_RPAREN))
991 break;
992 if (is_varargs != NULL && *is_varargs)
994 go_error_at(this->location(), "%<...%> must be last parameter");
995 saw_error = true;
997 this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error,
998 &saw_error);
1000 if (mix_error)
1002 go_error_at(location, "mixed named and unnamed function parameters");
1003 saw_error = true;
1005 if (saw_error)
1007 delete ret;
1008 return NULL;
1010 return ret;
1013 // ParameterDecl = [ IdentifierList ] [ "..." ] Type .
1015 void
1016 Parse::parameter_decl(bool parameters_have_names,
1017 Typed_identifier_list* til,
1018 bool* is_varargs,
1019 bool* mix_error,
1020 bool* saw_error)
1022 if (!parameters_have_names)
1024 Type* type;
1025 Location location = this->location();
1026 if (!this->peek_token()->is_identifier())
1028 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1029 type = this->type();
1030 else
1032 if (is_varargs == NULL)
1033 go_error_at(this->location(), "invalid use of %<...%>");
1034 else
1035 *is_varargs = true;
1036 this->advance_token();
1037 if (is_varargs == NULL
1038 && this->peek_token()->is_op(OPERATOR_RPAREN))
1039 type = Type::make_error_type();
1040 else
1042 Type* element_type = this->type();
1043 type = Type::make_array_type(element_type, NULL);
1047 else
1049 type = this->type_name(false);
1050 if (type->is_error_type()
1051 || (!this->peek_token()->is_op(OPERATOR_COMMA)
1052 && !this->peek_token()->is_op(OPERATOR_RPAREN)))
1054 *mix_error = true;
1055 while (!this->peek_token()->is_op(OPERATOR_COMMA)
1056 && !this->peek_token()->is_op(OPERATOR_RPAREN)
1057 && !this->peek_token()->is_eof())
1058 this->advance_token();
1061 if (!type->is_error_type())
1062 til->push_back(Typed_identifier("", type, location));
1063 else
1064 *saw_error = true;
1066 else
1068 size_t orig_count = til->size();
1069 if (this->peek_token()->is_identifier())
1070 this->identifier_list(til);
1071 else
1072 *mix_error = true;
1073 size_t new_count = til->size();
1075 Type* type;
1076 if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1077 type = this->type();
1078 else
1080 if (is_varargs == NULL)
1082 go_error_at(this->location(), "invalid use of %<...%>");
1083 *saw_error = true;
1085 else if (new_count > orig_count + 1)
1087 go_error_at(this->location(), "%<...%> only permits one name");
1088 *saw_error = true;
1090 else
1091 *is_varargs = true;
1092 this->advance_token();
1093 Type* element_type = this->type();
1094 type = Type::make_array_type(element_type, NULL);
1096 for (size_t i = orig_count; i < new_count; ++i)
1097 til->set_type(i, type);
1101 // Result = Parameters | Type .
1103 // This returns false on a parse error.
1105 bool
1106 Parse::result(Typed_identifier_list** presults)
1108 if (this->peek_token()->is_op(OPERATOR_LPAREN))
1109 return this->parameters(presults, NULL);
1110 else
1112 Location location = this->location();
1113 Type* type = this->type();
1114 if (type->is_error_type())
1116 *presults = NULL;
1117 return false;
1119 Typed_identifier_list* til = new Typed_identifier_list();
1120 til->push_back(Typed_identifier("", type, location));
1121 *presults = til;
1122 return true;
1126 // Block = "{" [ StatementList ] "}" .
1128 // Returns the location of the closing brace.
1130 Location
1131 Parse::block()
1133 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
1135 Location loc = this->location();
1136 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1137 && this->advance_token()->is_op(OPERATOR_LCURLY))
1138 go_error_at(loc, "unexpected semicolon or newline before %<{%>");
1139 else
1141 go_error_at(this->location(), "expected %<{%>");
1142 return Linemap::unknown_location();
1146 const Token* token = this->advance_token();
1148 if (!token->is_op(OPERATOR_RCURLY))
1150 this->statement_list();
1151 token = this->peek_token();
1152 if (!token->is_op(OPERATOR_RCURLY))
1154 if (!token->is_eof() || !saw_errors())
1155 go_error_at(this->location(), "expected %<}%>");
1157 this->gogo_->mark_locals_used();
1159 // Skip ahead to the end of the block, in hopes of avoiding
1160 // lots of meaningless errors.
1161 Location ret = token->location();
1162 int nest = 0;
1163 while (!token->is_eof())
1165 if (token->is_op(OPERATOR_LCURLY))
1166 ++nest;
1167 else if (token->is_op(OPERATOR_RCURLY))
1169 --nest;
1170 if (nest < 0)
1172 this->advance_token();
1173 break;
1176 token = this->advance_token();
1177 ret = token->location();
1179 return ret;
1183 Location ret = token->location();
1184 this->advance_token();
1185 return ret;
1188 // InterfaceType = "interface" "{" [ MethodSpecList ] "}" .
1189 // MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] .
1191 Type*
1192 Parse::interface_type(bool record)
1194 go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE));
1195 Location location = this->location();
1197 if (!this->advance_token()->is_op(OPERATOR_LCURLY))
1199 Location token_loc = this->location();
1200 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1201 && this->advance_token()->is_op(OPERATOR_LCURLY))
1202 go_error_at(token_loc, "unexpected semicolon or newline before %<{%>");
1203 else
1205 go_error_at(this->location(), "expected %<{%>");
1206 return Type::make_error_type();
1209 this->advance_token();
1211 Typed_identifier_list* methods = new Typed_identifier_list();
1212 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1214 this->method_spec(methods);
1215 while (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1217 if (this->advance_token()->is_op(OPERATOR_RCURLY))
1218 break;
1219 this->method_spec(methods);
1221 if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1223 go_error_at(this->location(), "expected %<}%>");
1224 while (!this->advance_token()->is_op(OPERATOR_RCURLY))
1226 if (this->peek_token()->is_eof())
1227 return Type::make_error_type();
1231 this->advance_token();
1233 if (methods->empty())
1235 delete methods;
1236 methods = NULL;
1239 Interface_type* ret;
1240 if (methods == NULL)
1241 ret = Type::make_empty_interface_type(location);
1242 else
1243 ret = Type::make_interface_type(methods, location);
1244 if (record)
1245 this->gogo_->record_interface_type(ret);
1246 return ret;
1249 // MethodSpec = MethodName Signature | InterfaceTypeName .
1250 // MethodName = identifier .
1251 // InterfaceTypeName = TypeName .
1253 void
1254 Parse::method_spec(Typed_identifier_list* methods)
1256 const Token* token = this->peek_token();
1257 if (!token->is_identifier())
1259 go_error_at(this->location(), "expected identifier");
1260 return;
1263 std::string name = token->identifier();
1264 bool is_exported = token->is_identifier_exported();
1265 Location location = token->location();
1267 if (this->advance_token()->is_op(OPERATOR_LPAREN))
1269 // This is a MethodName.
1270 if (name == "_")
1271 go_error_at(this->location(),
1272 "methods must have a unique non-blank name");
1273 name = this->gogo_->pack_hidden_name(name, is_exported);
1274 Type* type = this->signature(NULL, location);
1275 if (type == NULL)
1276 return;
1277 methods->push_back(Typed_identifier(name, type, location));
1279 else
1281 this->unget_token(Token::make_identifier_token(name, is_exported,
1282 location));
1283 Type* type = this->type_name(false);
1284 if (type->is_error_type()
1285 || (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1286 && !this->peek_token()->is_op(OPERATOR_RCURLY)))
1288 if (this->peek_token()->is_op(OPERATOR_COMMA))
1289 go_error_at(this->location(),
1290 "name list not allowed in interface type");
1291 else
1292 go_error_at(location, "expected signature or type name");
1293 this->gogo_->mark_locals_used();
1294 token = this->peek_token();
1295 while (!token->is_eof()
1296 && !token->is_op(OPERATOR_SEMICOLON)
1297 && !token->is_op(OPERATOR_RCURLY))
1298 token = this->advance_token();
1299 return;
1301 // This must be an interface type, but we can't check that now.
1302 // We check it and pull out the methods in
1303 // Interface_type::do_verify.
1304 methods->push_back(Typed_identifier("", type, location));
1308 // Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1310 void
1311 Parse::declaration()
1313 const Token* token = this->peek_token();
1314 if (token->is_keyword(KEYWORD_CONST))
1315 this->const_decl();
1316 else if (token->is_keyword(KEYWORD_TYPE))
1317 this->type_decl();
1318 else if (token->is_keyword(KEYWORD_VAR))
1319 this->var_decl();
1320 else if (token->is_keyword(KEYWORD_FUNC))
1321 this->function_decl();
1322 else
1324 go_error_at(this->location(), "expected declaration");
1325 this->advance_token();
1329 bool
1330 Parse::declaration_may_start_here()
1332 const Token* token = this->peek_token();
1333 return (token->is_keyword(KEYWORD_CONST)
1334 || token->is_keyword(KEYWORD_TYPE)
1335 || token->is_keyword(KEYWORD_VAR)
1336 || token->is_keyword(KEYWORD_FUNC));
1339 // Decl<P> = P | "(" [ List<P> ] ")" .
1341 void
1342 Parse::decl(void (Parse::*pfn)())
1344 if (this->peek_token()->is_eof())
1346 if (!saw_errors())
1347 go_error_at(this->location(), "unexpected end of file");
1348 return;
1351 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1352 (this->*pfn)();
1353 else
1355 if (this->lex_->get_and_clear_pragmas() != 0)
1356 go_error_at(this->location(),
1357 "ignoring compiler directive before group");
1358 if (this->lex_->has_embeds())
1360 this->lex_->clear_embeds();
1361 go_error_at(this->location(),
1362 "ignoring %<//go:embed%> comment before group");
1364 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
1366 this->list(pfn, 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)(), bool follow_is_paren)
1389 (this->*pfn)();
1390 Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY;
1391 while (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1392 || this->peek_token()->is_op(OPERATOR_COMMA))
1394 if (this->peek_token()->is_op(OPERATOR_COMMA))
1395 go_error_at(this->location(), "unexpected comma");
1396 if (this->advance_token()->is_op(follow))
1397 break;
1398 (this->*pfn)();
1402 // ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1404 void
1405 Parse::const_decl()
1407 go_assert(this->peek_token()->is_keyword(KEYWORD_CONST));
1408 this->advance_token();
1410 int iota = 0;
1411 Type* last_type = NULL;
1412 Expression_list* last_expr_list = NULL;
1414 if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1415 this->const_spec(iota, &last_type, &last_expr_list);
1416 else
1418 this->advance_token();
1419 while (!this->peek_token()->is_op(OPERATOR_RPAREN))
1421 this->const_spec(iota, &last_type, &last_expr_list);
1422 ++iota;
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(int iota, Type** last_type, Expression_list** last_expr_list)
1445 this->check_directives();
1447 Location loc = this->location();
1448 Typed_identifier_list til;
1449 this->identifier_list(&til);
1451 Type* type = NULL;
1452 if (this->type_may_start_here())
1454 type = this->type();
1455 *last_type = NULL;
1456 *last_expr_list = NULL;
1459 Expression_list *expr_list;
1460 if (!this->peek_token()->is_op(OPERATOR_EQ))
1462 if (*last_expr_list == NULL)
1464 go_error_at(this->location(), "expected %<=%>");
1465 return;
1467 type = *last_type;
1468 expr_list = new Expression_list;
1469 for (Expression_list::const_iterator p = (*last_expr_list)->begin();
1470 p != (*last_expr_list)->end();
1471 ++p)
1473 Expression* copy = (*p)->copy();
1474 copy->set_location(loc);
1475 this->update_references(&copy);
1476 expr_list->push_back(copy);
1479 else
1481 this->advance_token();
1482 expr_list = this->expression_list(NULL, false, true);
1483 *last_type = type;
1484 if (*last_expr_list != NULL)
1485 delete *last_expr_list;
1486 *last_expr_list = expr_list;
1489 Expression_list::const_iterator pe = expr_list->begin();
1490 for (Typed_identifier_list::iterator pi = til.begin();
1491 pi != til.end();
1492 ++pi, ++pe)
1494 if (pe == expr_list->end())
1496 go_error_at(this->location(), "not enough initializers");
1497 return;
1499 if (type != NULL)
1500 pi->set_type(type);
1502 if (!Gogo::is_sink_name(pi->name()))
1503 this->gogo_->add_constant(*pi, *pe, iota);
1504 else
1506 static int count;
1507 char buf[30];
1508 snprintf(buf, sizeof buf, ".$sinkconst%d", count);
1509 ++count;
1510 Typed_identifier ti(std::string(buf), type, pi->location());
1511 Named_object* no = this->gogo_->add_constant(ti, *pe, iota);
1512 no->const_value()->set_is_sink();
1515 if (pe != expr_list->end())
1516 go_error_at(this->location(), "too many initializers");
1518 return;
1521 // Update any references to names to refer to the current names,
1522 // for weird cases like
1524 // const X = 1
1525 // func F() {
1526 // const (
1527 // X = X + X
1528 // Y
1529 // )
1530 // }
1532 // where the X + X for the first X is the outer X, but the X + X
1533 // copied for Y is the inner X.
1535 class Update_references : public Traverse
1537 public:
1538 Update_references(Gogo* gogo)
1539 : Traverse(traverse_expressions),
1540 gogo_(gogo)
1544 expression(Expression**);
1546 private:
1547 Gogo* gogo_;
1551 Update_references::expression(Expression** pexpr)
1553 Named_object* old_no;
1554 switch ((*pexpr)->classification())
1556 case Expression::EXPRESSION_CONST_REFERENCE:
1557 old_no = (*pexpr)->const_expression()->named_object();
1558 break;
1559 case Expression::EXPRESSION_VAR_REFERENCE:
1560 old_no = (*pexpr)->var_expression()->named_object();
1561 break;
1562 case Expression::EXPRESSION_ENCLOSED_VAR_REFERENCE:
1563 old_no = (*pexpr)->enclosed_var_expression()->variable();
1564 break;
1565 case Expression::EXPRESSION_FUNC_REFERENCE:
1566 old_no = (*pexpr)->func_expression()->named_object();
1567 break;
1568 case Expression::EXPRESSION_UNKNOWN_REFERENCE:
1569 old_no = (*pexpr)->unknown_expression()->named_object();
1570 break;
1571 default:
1572 return TRAVERSE_CONTINUE;
1575 if (old_no->package() != NULL)
1577 // This is a qualified reference, so it can't have changed in
1578 // scope. FIXME: This probably doesn't handle dot imports
1579 // correctly.
1580 return TRAVERSE_CONTINUE;
1583 Named_object* in_function;
1584 Named_object* new_no = this->gogo_->lookup(old_no->name(), &in_function);
1585 if (new_no == old_no)
1586 return TRAVERSE_CONTINUE;
1588 // The new name must be a constant, since that is all we have
1589 // introduced into scope.
1590 if (!new_no->is_const())
1592 go_assert(saw_errors());
1593 return TRAVERSE_CONTINUE;
1596 *pexpr = Expression::make_const_reference(new_no, (*pexpr)->location());
1598 return TRAVERSE_CONTINUE;
1601 void
1602 Parse::update_references(Expression** pexpr)
1604 Update_references ur(this->gogo_);
1605 ur.expression(pexpr);
1606 (*pexpr)->traverse_subexpressions(&ur);
1609 // TypeDecl = "type" Decl<TypeSpec> .
1611 void
1612 Parse::type_decl()
1614 go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE));
1615 this->advance_token();
1616 this->decl(&Parse::type_spec);
1619 // TypeSpec = identifier ["="] Type .
1621 void
1622 Parse::type_spec()
1624 unsigned int pragmas = this->lex_->get_and_clear_pragmas();
1625 this->check_directives();
1627 const Token* token = this->peek_token();
1628 if (!token->is_identifier())
1630 go_error_at(this->location(), "expected identifier");
1631 return;
1633 std::string name = token->identifier();
1634 bool is_exported = token->is_identifier_exported();
1635 Location location = token->location();
1636 token = this->advance_token();
1638 bool is_alias = false;
1639 if (token->is_op(OPERATOR_EQ))
1641 is_alias = true;
1642 token = this->advance_token();
1645 // The scope of the type name starts at the point where the
1646 // identifier appears in the source code. We implement this by
1647 // declaring the type before we read the type definition.
1648 Named_object* named_type = NULL;
1649 if (name != "_")
1651 name = this->gogo_->pack_hidden_name(name, is_exported);
1652 named_type = this->gogo_->declare_type(name, location);
1655 Type* type;
1656 if (name == "_" && token->is_keyword(KEYWORD_INTERFACE))
1658 // We call Parse::interface_type explicity here because we do not want
1659 // to record an interface with a blank type name.
1660 type = this->interface_type(false);
1662 else if (!token->is_op(OPERATOR_SEMICOLON))
1663 type = this->type();
1664 else
1666 go_error_at(this->location(),
1667 "unexpected semicolon or newline in type declaration");
1668 type = Type::make_error_type();
1671 if (type->is_error_type())
1673 this->gogo_->mark_locals_used();
1674 while (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1675 && !this->peek_token()->is_eof())
1676 this->advance_token();
1679 if (name != "_")
1681 if (named_type->is_type_declaration())
1683 Type* ftype = type->forwarded();
1684 if (ftype->forward_declaration_type() != NULL
1685 && (ftype->forward_declaration_type()->named_object()
1686 == named_type))
1688 go_error_at(location, "invalid recursive type");
1689 type = Type::make_error_type();
1692 Named_type* nt = Type::make_named_type(named_type, type, location);
1693 if (is_alias)
1694 nt->set_is_alias();
1696 this->gogo_->define_type(named_type, nt);
1697 go_assert(named_type->package() == NULL);
1699 if ((pragmas & GOPRAGMA_NOTINHEAP) != 0)
1701 nt->set_not_in_heap();
1702 pragmas &= ~GOPRAGMA_NOTINHEAP;
1704 if (pragmas != 0)
1705 go_warning_at(location, 0,
1706 "ignoring magic %<//go:...%> comment before type");
1708 else
1710 // This will probably give a redefinition error.
1711 this->gogo_->add_type(name, type, location);
1716 // VarDecl = "var" Decl<VarSpec> .
1718 void
1719 Parse::var_decl()
1721 go_assert(this->peek_token()->is_keyword(KEYWORD_VAR));
1722 this->advance_token();
1723 this->decl(&Parse::var_spec);
1726 // VarSpec = IdentifierList
1727 // ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
1729 void
1730 Parse::var_spec()
1732 Location loc = this->location();
1734 std::vector<std::string>* embeds = NULL;
1735 if (this->lex_->has_embeds())
1737 if (!this->gogo_->current_file_imported_embed())
1738 go_error_at(loc, "invalid go:embed: missing import %<embed%>");
1739 else
1741 embeds = new(std::vector<std::string>);
1742 this->lex_->get_and_clear_embeds(embeds);
1746 this->check_directives();
1748 // Get the variable names.
1749 Typed_identifier_list til;
1750 this->identifier_list(&til);
1752 if (embeds != NULL)
1754 if (!this->gogo_->in_global_scope())
1756 go_error_at(loc, "go:embed only permitted at package scope");
1757 embeds = NULL;
1759 if (til.size() > 1)
1761 go_error_at(loc, "go:embed cannot apply to multiple vars");
1762 embeds = NULL;
1766 Location location = this->location();
1768 Type* type = NULL;
1769 Expression_list* init = NULL;
1770 if (!this->peek_token()->is_op(OPERATOR_EQ))
1772 type = this->type();
1773 if (type->is_error_type())
1775 this->gogo_->mark_locals_used();
1776 while (!this->peek_token()->is_op(OPERATOR_EQ)
1777 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
1778 && !this->peek_token()->is_eof())
1779 this->advance_token();
1781 if (this->peek_token()->is_op(OPERATOR_EQ))
1783 this->advance_token();
1784 init = this->expression_list(NULL, false, true);
1787 else
1789 this->advance_token();
1790 init = this->expression_list(NULL, false, true);
1793 if (embeds != NULL && init != NULL)
1795 go_error_at(loc, "go:embed cannot apply to var with initializer");
1796 embeds = NULL;
1799 this->init_vars(&til, type, init, false, embeds, location);
1801 if (init != NULL)
1802 delete init;
1805 // Create variables. TIL is a list of variable names. If TYPE is not
1806 // NULL, it is the type of all the variables. If INIT is not NULL, it
1807 // is an initializer list for the variables.
1809 void
1810 Parse::init_vars(const Typed_identifier_list* til, Type* type,
1811 Expression_list* init, bool is_coloneq,
1812 std::vector<std::string>* embeds, Location location)
1814 // Check for an initialization which can yield multiple values.
1815 if (init != NULL && init->size() == 1 && til->size() > 1)
1817 go_assert(embeds == NULL);
1818 if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq,
1819 location))
1820 return;
1821 if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq,
1822 location))
1823 return;
1824 if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq,
1825 location))
1826 return;
1827 if (this->init_vars_from_type_guard(til, type, *init->begin(),
1828 is_coloneq, location))
1829 return;
1832 if (init != NULL && init->size() != til->size())
1834 if (init->empty() || !init->front()->is_error_expression())
1835 go_error_at(location, "wrong number of initializations");
1836 init = NULL;
1837 if (type == NULL)
1838 type = Type::make_error_type();
1841 // Note that INIT was already parsed with the old name bindings, so
1842 // we don't have to worry that it will accidentally refer to the
1843 // newly declared variables. But we do have to worry about a mix of
1844 // newly declared variables and old variables if the old variables
1845 // appear in the initializations.
1847 Expression_list::const_iterator pexpr;
1848 if (init != NULL)
1849 pexpr = init->begin();
1850 bool any_new = false;
1851 Expression_list* vars = new Expression_list();
1852 Expression_list* vals = new Expression_list();
1853 for (Typed_identifier_list::const_iterator p = til->begin();
1854 p != til->end();
1855 ++p)
1857 if (init != NULL)
1858 go_assert(pexpr != init->end());
1859 Named_object* no = this->init_var(*p, type,
1860 init == NULL ? NULL : *pexpr,
1861 is_coloneq, false, &any_new,
1862 vars, vals);
1863 if (embeds != NULL && no->is_variable())
1864 no->var_value()->set_embeds(embeds);
1865 if (init != NULL)
1866 ++pexpr;
1868 if (init != NULL)
1869 go_assert(pexpr == init->end());
1870 if (is_coloneq && !any_new)
1871 go_error_at(location, "variables redeclared but no variable is new");
1872 this->finish_init_vars(vars, vals, location);
1875 // See if we need to initialize a list of variables from a function
1876 // call. This returns true if we have set up the variables and the
1877 // initialization.
1879 bool
1880 Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type,
1881 Expression* expr, bool is_coloneq,
1882 Location location)
1884 Call_expression* call = expr->call_expression();
1885 if (call == NULL)
1886 return false;
1888 // This is a function call. We can't check here whether it returns
1889 // the right number of values, but it might. Declare the variables,
1890 // and then assign the results of the call to them.
1892 call->set_expected_result_count(vars->size());
1894 Named_object* first_var = NULL;
1895 unsigned int index = 0;
1896 bool any_new = false;
1897 Expression_list* ivars = new Expression_list();
1898 Expression_list* ivals = new Expression_list();
1899 for (Typed_identifier_list::const_iterator pv = vars->begin();
1900 pv != vars->end();
1901 ++pv, ++index)
1903 Expression* init = Expression::make_call_result(call, index);
1904 Named_object* no = this->init_var(*pv, type, init, is_coloneq, false,
1905 &any_new, ivars, ivals);
1907 if (this->gogo_->in_global_scope() && no->is_variable())
1909 if (first_var == NULL)
1910 first_var = no;
1911 else
1913 // If the current object is a redefinition of another object, we
1914 // might have already recorded the dependency relationship between
1915 // it and the first variable. Either way, an error will be
1916 // reported for the redefinition and we don't need to properly
1917 // record dependency information for an invalid program.
1918 if (no->is_redefinition())
1919 continue;
1921 // The subsequent vars have an implicit dependency on
1922 // the first one, so that everything gets initialized in
1923 // the right order and so that we detect cycles
1924 // correctly.
1925 this->gogo_->record_var_depends_on(no->var_value(), first_var);
1930 if (is_coloneq && !any_new)
1931 go_error_at(location, "variables redeclared but no variable is new");
1933 this->finish_init_vars(ivars, ivals, location);
1935 return true;
1938 // See if we need to initialize a pair of values from a map index
1939 // expression. This returns true if we have set up the variables and
1940 // the initialization.
1942 bool
1943 Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type,
1944 Expression* expr, bool is_coloneq,
1945 Location location)
1947 Index_expression* index = expr->index_expression();
1948 if (index == NULL)
1949 return false;
1950 if (vars->size() != 2)
1951 return false;
1953 // This is an index which is being assigned to two variables. It
1954 // must be a map index. Declare the variables, and then assign the
1955 // results of the map index.
1956 bool any_new = false;
1957 Typed_identifier_list::const_iterator p = vars->begin();
1958 Expression* init = type == NULL ? index : NULL;
1959 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1960 type == NULL, &any_new, NULL, NULL);
1961 if (type == NULL && any_new && val_no->is_variable())
1962 val_no->var_value()->set_type_from_init_tuple();
1963 Expression* val_var = Expression::make_var_reference(val_no, location);
1965 ++p;
1966 Type* var_type = type;
1967 if (var_type == NULL)
1968 var_type = Type::lookup_bool_type();
1969 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1970 &any_new, NULL, NULL);
1971 Expression* present_var = Expression::make_var_reference(no, location);
1973 if (is_coloneq && !any_new)
1974 go_error_at(location, "variables redeclared but no variable is new");
1976 Statement* s = Statement::make_tuple_map_assignment(val_var, present_var,
1977 index, location);
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())
1985 val_no->var_value()->add_preinit_statement(this->gogo_, s);
1986 if (no->is_variable())
1987 this->gogo_->record_var_depends_on(no->var_value(), val_no);
1990 else if (!no->is_sink())
1992 if (no->is_variable())
1993 no->var_value()->add_preinit_statement(this->gogo_, s);
1995 else
1997 // Execute the map index expression just so that we can fail if
1998 // the map is nil.
1999 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
2000 NULL, location);
2001 dummy->var_value()->add_preinit_statement(this->gogo_, s);
2004 return true;
2007 // See if we need to initialize a pair of values from a receive
2008 // expression. This returns true if we have set up the variables and
2009 // the initialization.
2011 bool
2012 Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type,
2013 Expression* expr, bool is_coloneq,
2014 Location location)
2016 Receive_expression* receive = expr->receive_expression();
2017 if (receive == NULL)
2018 return false;
2019 if (vars->size() != 2)
2020 return false;
2022 // This is a receive expression which is being assigned to two
2023 // variables. Declare the variables, and then assign the results of
2024 // the receive.
2025 bool any_new = false;
2026 Typed_identifier_list::const_iterator p = vars->begin();
2027 Expression* init = type == NULL ? receive : NULL;
2028 Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
2029 type == NULL, &any_new, NULL, NULL);
2030 if (type == NULL && any_new && val_no->is_variable())
2031 val_no->var_value()->set_type_from_init_tuple();
2032 Expression* val_var = Expression::make_var_reference(val_no, location);
2034 ++p;
2035 Type* var_type = type;
2036 if (var_type == NULL)
2037 var_type = Type::lookup_bool_type();
2038 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
2039 &any_new, NULL, NULL);
2040 Expression* received_var = Expression::make_var_reference(no, location);
2042 if (is_coloneq && !any_new)
2043 go_error_at(location, "variables redeclared but no variable is new");
2045 Statement* s = Statement::make_tuple_receive_assignment(val_var,
2046 received_var,
2047 receive->channel(),
2048 location);
2050 if (!this->gogo_->in_global_scope())
2051 this->gogo_->add_statement(s);
2052 else if (!val_no->is_sink())
2054 if (val_no->is_variable())
2056 val_no->var_value()->add_preinit_statement(this->gogo_, s);
2057 if (no->is_variable())
2058 this->gogo_->record_var_depends_on(no->var_value(), val_no);
2061 else if (!no->is_sink())
2063 if (no->is_variable())
2064 no->var_value()->add_preinit_statement(this->gogo_, s);
2066 else
2068 Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
2069 NULL, location);
2070 dummy->var_value()->add_preinit_statement(this->gogo_, s);
2073 return true;
2076 // See if we need to initialize a pair of values from a type guard
2077 // expression. This returns true if we have set up the variables and
2078 // the initialization.
2080 bool
2081 Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
2082 Type* type, Expression* expr,
2083 bool is_coloneq, Location location)
2085 Type_guard_expression* type_guard = expr->type_guard_expression();
2086 if (type_guard == NULL)
2087 return false;
2088 if (vars->size() != 2)
2089 return false;
2091 // This is a type guard expression which is being assigned to two
2092 // variables. Declare the variables, and then assign the results of
2093 // the type guard.
2094 bool any_new = false;
2095 Typed_identifier_list::const_iterator p = vars->begin();
2096 Type* var_type = type;
2097 if (var_type == NULL)
2098 var_type = type_guard->type();
2099 Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
2100 &any_new, NULL, NULL);
2101 Expression* val_var = Expression::make_var_reference(val_no, location);
2103 ++p;
2104 var_type = type;
2105 if (var_type == NULL)
2106 var_type = Type::lookup_bool_type();
2107 Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
2108 &any_new, NULL, NULL);
2109 Expression* ok_var = Expression::make_var_reference(no, location);
2111 Expression* texpr = type_guard->expr();
2112 Type* t = type_guard->type();
2113 Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
2114 texpr, t,
2115 location);
2117 if (is_coloneq && !any_new)
2118 go_error_at(location, "variables redeclared but no variable is new");
2120 if (!this->gogo_->in_global_scope())
2121 this->gogo_->add_statement(s);
2122 else if (!val_no->is_sink())
2124 if (val_no->is_variable())
2126 val_no->var_value()->add_preinit_statement(this->gogo_, s);
2127 if (no->is_variable())
2128 this->gogo_->record_var_depends_on(no->var_value(), val_no);
2131 else if (!no->is_sink())
2133 if (no->is_variable())
2134 no->var_value()->add_preinit_statement(this->gogo_, s);
2136 else
2138 Named_object* dummy = this->create_dummy_global(type, NULL, location);
2139 dummy->var_value()->add_preinit_statement(this->gogo_, s);
2142 return true;
2145 // Create a single variable. If IS_COLONEQ is true, we permit
2146 // redeclarations in the same block, and we set *IS_NEW when we find a
2147 // new variable which is not a redeclaration.
2149 Named_object*
2150 Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
2151 bool is_coloneq, bool type_from_init, bool* is_new,
2152 Expression_list* vars, Expression_list* vals)
2154 Location location = tid.location();
2156 if (Gogo::is_sink_name(tid.name()))
2158 if (!type_from_init && init != NULL)
2160 if (this->gogo_->in_global_scope())
2161 return this->create_dummy_global(type, init, location);
2162 else
2164 // Create a dummy variable so that we will check whether the
2165 // initializer can be assigned to the type.
2166 Variable* var = new Variable(type, init, false, false, false,
2167 location);
2168 var->set_is_used();
2169 static int count;
2170 char buf[30];
2171 snprintf(buf, sizeof buf, "sink$%d", count);
2172 ++count;
2173 return this->gogo_->add_variable(buf, var);
2176 if (type != NULL)
2177 this->gogo_->add_type_to_verify(type);
2178 return this->gogo_->add_sink();
2181 if (is_coloneq)
2183 Named_object* no = this->gogo_->lookup_in_block(tid.name());
2184 if (no != NULL
2185 && (no->is_variable() || no->is_result_variable()))
2187 // INIT may be NULL even when IS_COLONEQ is true for cases
2188 // like v, ok := x.(int).
2189 if (!type_from_init && init != NULL)
2191 go_assert(vars != NULL && vals != NULL);
2192 vars->push_back(Expression::make_var_reference(no, location));
2193 vals->push_back(init);
2195 return no;
2198 *is_new = true;
2199 Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
2200 false, false, location);
2201 Named_object* no = this->gogo_->add_variable(tid.name(), var);
2202 if (!no->is_variable())
2204 // The name is already defined, so we just gave an error.
2205 return this->gogo_->add_sink();
2207 return no;
2210 // Create a dummy global variable to force an initializer to be run in
2211 // the right place. This is used when a sink variable is initialized
2212 // at global scope.
2214 Named_object*
2215 Parse::create_dummy_global(Type* type, Expression* init,
2216 Location location)
2218 if (type == NULL && init == NULL)
2219 type = Type::lookup_bool_type();
2220 Variable* var = new Variable(type, init, true, false, false, location);
2221 var->set_is_global_sink();
2222 static int count;
2223 char buf[30];
2224 snprintf(buf, sizeof buf, "_.%d", count);
2225 ++count;
2226 return this->gogo_->add_variable(buf, var);
2229 // Finish the variable initialization by executing any assignments to
2230 // existing variables when using :=. These must be done as a tuple
2231 // assignment in case of something like n, a, b := 1, b, a.
2233 void
2234 Parse::finish_init_vars(Expression_list* vars, Expression_list* vals,
2235 Location location)
2237 if (vars->empty())
2239 delete vars;
2240 delete vals;
2242 else if (vars->size() == 1)
2244 go_assert(!this->gogo_->in_global_scope());
2245 this->gogo_->add_statement(Statement::make_assignment(vars->front(),
2246 vals->front(),
2247 location));
2248 delete vars;
2249 delete vals;
2251 else
2253 go_assert(!this->gogo_->in_global_scope());
2254 this->gogo_->add_statement(Statement::make_tuple_assignment(vars, vals,
2255 location));
2259 // SimpleVarDecl = identifier ":=" Expression .
2261 // We've already seen the identifier.
2263 // FIXME: We also have to implement
2264 // IdentifierList ":=" ExpressionList
2265 // In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
2266 // tuple assignments here as well.
2268 // If MAY_BE_COMPOSITE_LIT is true, the expression on the right hand
2269 // side may be a composite literal.
2271 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
2272 // RangeClause.
2274 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
2275 // guard (var := expr.("type") using the literal keyword "type").
2277 void
2278 Parse::simple_var_decl_or_assignment(const std::string& name,
2279 Location location,
2280 bool may_be_composite_lit,
2281 Range_clause* p_range_clause,
2282 Type_switch* p_type_switch)
2284 Typed_identifier_list til;
2285 til.push_back(Typed_identifier(name, NULL, location));
2287 std::set<std::string> uniq_idents;
2288 uniq_idents.insert(name);
2289 std::string dup_name;
2290 Location dup_loc;
2292 // We've seen one identifier. If we see a comma now, this could be
2293 // "a, *p = 1, 2".
2294 if (this->peek_token()->is_op(OPERATOR_COMMA))
2296 go_assert(p_type_switch == NULL);
2297 while (true)
2299 const Token* token = this->advance_token();
2300 if (!token->is_identifier())
2301 break;
2303 std::string id = token->identifier();
2304 bool is_id_exported = token->is_identifier_exported();
2305 Location id_location = token->location();
2306 std::pair<std::set<std::string>::iterator, bool> ins;
2308 token = this->advance_token();
2309 if (!token->is_op(OPERATOR_COMMA))
2311 if (token->is_op(OPERATOR_COLONEQ))
2313 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2314 ins = uniq_idents.insert(id);
2315 if (!ins.second && !Gogo::is_sink_name(id))
2317 // Use %s to print := to avoid -Wformat-diag warning.
2318 go_error_at(id_location,
2319 "%qs repeated on left side of %s",
2320 Gogo::message_name(id).c_str(), ":=");
2321 id = this->gogo_->pack_hidden_name("_", false);
2323 til.push_back(Typed_identifier(id, NULL, location));
2325 else
2326 this->unget_token(Token::make_identifier_token(id,
2327 is_id_exported,
2328 id_location));
2329 break;
2332 id = this->gogo_->pack_hidden_name(id, is_id_exported);
2333 ins = uniq_idents.insert(id);
2334 std::string name = id;
2335 if (!ins.second && !Gogo::is_sink_name(id))
2337 dup_name = Gogo::message_name(id);
2338 dup_loc = id_location;
2339 id = this->gogo_->pack_hidden_name("_", false);
2341 til.push_back(Typed_identifier(id, NULL, location));
2344 // We have a comma separated list of identifiers in TIL. If the
2345 // next token is COLONEQ, then this is a simple var decl, and we
2346 // have the complete list of identifiers. If the next token is
2347 // not COLONEQ, then the only valid parse is a tuple assignment.
2348 // The list of identifiers we have so far is really a list of
2349 // expressions. There are more expressions following.
2351 if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
2353 Expression_list* exprs = new Expression_list;
2354 for (Typed_identifier_list::const_iterator p = til.begin();
2355 p != til.end();
2356 ++p)
2357 exprs->push_back(this->id_to_expression(p->name(), p->location(),
2358 true, false));
2360 Expression_list* more_exprs =
2361 this->expression_list(NULL, true, may_be_composite_lit);
2362 for (Expression_list::const_iterator p = more_exprs->begin();
2363 p != more_exprs->end();
2364 ++p)
2365 exprs->push_back(*p);
2366 delete more_exprs;
2368 this->tuple_assignment(exprs, may_be_composite_lit, p_range_clause);
2369 return;
2373 go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
2374 const Token* token = this->advance_token();
2376 if (!dup_name.empty())
2378 // Use %s to print := to avoid -Wformat-diag warning.
2379 go_error_at(dup_loc, "%qs repeated on left side of %s",
2380 dup_name.c_str(), ":=");
2383 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
2385 this->range_clause_decl(&til, p_range_clause);
2386 return;
2389 Expression_list* init;
2390 if (p_type_switch == NULL)
2391 init = this->expression_list(NULL, false, may_be_composite_lit);
2392 else
2394 bool is_type_switch = false;
2395 Expression* expr = this->expression(PRECEDENCE_NORMAL, false,
2396 may_be_composite_lit,
2397 &is_type_switch, NULL);
2398 if (is_type_switch)
2400 p_type_switch->found = true;
2401 p_type_switch->name = name;
2402 p_type_switch->location = location;
2403 p_type_switch->expr = expr;
2404 return;
2407 if (!this->peek_token()->is_op(OPERATOR_COMMA))
2409 init = new Expression_list();
2410 init->push_back(expr);
2412 else
2414 this->advance_token();
2415 init = this->expression_list(expr, false, may_be_composite_lit);
2419 this->init_vars(&til, NULL, init, true, NULL, location);
2422 // FunctionDecl = "func" identifier Signature [ Block ] .
2423 // MethodDecl = "func" Receiver identifier Signature [ Block ] .
2425 // Deprecated gcc extension:
2426 // FunctionDecl = "func" identifier Signature
2427 // __asm__ "(" string_lit ")" .
2428 // This extension means a function whose real name is the identifier
2429 // inside the asm. This extension will be removed at some future
2430 // date. It has been replaced with //extern or //go:linkname comments.
2432 // PRAGMAS is a bitset of magic comments.
2434 void
2435 Parse::function_decl()
2437 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2439 unsigned int pragmas = this->lex_->get_and_clear_pragmas();
2440 this->check_directives();
2442 Location location = this->location();
2443 std::string extern_name = this->lex_->extern_name();
2444 const Token* token = this->advance_token();
2446 bool expected_receiver = false;
2447 Typed_identifier* rec = NULL;
2448 if (token->is_op(OPERATOR_LPAREN))
2450 expected_receiver = true;
2451 rec = this->receiver();
2452 token = this->peek_token();
2455 if (!token->is_identifier())
2457 go_error_at(this->location(), "expected function name");
2458 return;
2461 std::string name =
2462 this->gogo_->pack_hidden_name(token->identifier(),
2463 token->is_identifier_exported());
2465 this->advance_token();
2467 Function_type* fntype = this->signature(rec, this->location());
2469 Named_object* named_object = NULL;
2471 if (this->peek_token()->is_keyword(KEYWORD_ASM))
2473 if (!this->advance_token()->is_op(OPERATOR_LPAREN))
2475 go_error_at(this->location(), "expected %<(%>");
2476 return;
2478 token = this->advance_token();
2479 if (!token->is_string())
2481 go_error_at(this->location(), "expected string");
2482 return;
2484 std::string asm_name = token->string_value();
2485 if (!this->advance_token()->is_op(OPERATOR_RPAREN))
2487 go_error_at(this->location(), "expected %<)%>");
2488 return;
2490 this->advance_token();
2491 if (!Gogo::is_sink_name(name))
2493 named_object = this->gogo_->declare_function(name, fntype, location);
2494 if (named_object->is_function_declaration())
2495 named_object->func_declaration_value()->set_asm_name(asm_name);
2499 // Check for the easy error of a newline before the opening brace.
2500 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
2502 Location semi_loc = this->location();
2503 if (this->advance_token()->is_op(OPERATOR_LCURLY))
2504 go_error_at(this->location(),
2505 "unexpected semicolon or newline before %<{%>");
2506 else
2507 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
2508 semi_loc));
2511 static struct {
2512 unsigned int bit;
2513 const char* name;
2514 bool decl_ok;
2515 bool func_ok;
2516 bool method_ok;
2517 } pragma_check[] =
2519 { GOPRAGMA_NOINTERFACE, "nointerface", false, false, true },
2520 { GOPRAGMA_NOESCAPE, "noescape", true, false, false },
2521 { GOPRAGMA_NORACE, "norace", false, true, true },
2522 { GOPRAGMA_NOSPLIT, "nosplit", false, true, true },
2523 { GOPRAGMA_NOINLINE, "noinline", false, true, true },
2524 { GOPRAGMA_SYSTEMSTACK, "systemstack", false, true, true },
2525 { GOPRAGMA_NOWRITEBARRIER, "nowritebarrier", false, true, true },
2526 { GOPRAGMA_NOWRITEBARRIERREC, "nowritebarrierrec", false, true,
2527 true },
2528 { GOPRAGMA_YESWRITEBARRIERREC, "yeswritebarrierrec", false, true,
2529 true },
2530 { GOPRAGMA_CGOUNSAFEARGS, "cgo_unsafe_args", false, true, true },
2531 { GOPRAGMA_UINTPTRESCAPES, "uintptrescapes", true, true, true },
2534 bool is_decl = !this->peek_token()->is_op(OPERATOR_LCURLY);
2535 if (pragmas != 0)
2537 for (size_t i = 0;
2538 i < sizeof(pragma_check) / sizeof(pragma_check[0]);
2539 ++i)
2541 if ((pragmas & pragma_check[i].bit) == 0)
2542 continue;
2544 if (is_decl)
2546 if (pragma_check[i].decl_ok)
2547 continue;
2548 go_warning_at(location, 0,
2549 ("ignoring magic %<//go:%s%> comment "
2550 "before declaration"),
2551 pragma_check[i].name);
2553 else if (rec == NULL)
2555 if (pragma_check[i].func_ok)
2556 continue;
2557 go_warning_at(location, 0,
2558 ("ignoring magic %<//go:%s%> comment "
2559 "before function definition"),
2560 pragma_check[i].name);
2562 else
2564 if (pragma_check[i].method_ok)
2565 continue;
2566 go_warning_at(location, 0,
2567 ("ignoring magic %<//go:%s%> comment "
2568 "before method definition"),
2569 pragma_check[i].name);
2572 pragmas &= ~ pragma_check[i].bit;
2576 if (is_decl)
2578 if (named_object == NULL)
2580 // Function declarations with the blank identifier as a name are
2581 // mostly ignored since they cannot be called. We make an object
2582 // for this declaration for type-checking purposes.
2583 if (Gogo::is_sink_name(name))
2585 static int count;
2586 char buf[30];
2587 snprintf(buf, sizeof buf, ".$sinkfndecl%d", count);
2588 ++count;
2589 name = std::string(buf);
2592 if (fntype == NULL
2593 || (expected_receiver && rec == NULL))
2594 this->gogo_->add_erroneous_name(name);
2595 else
2597 named_object = this->gogo_->declare_function(name, fntype,
2598 location);
2599 if (!extern_name.empty()
2600 && named_object->is_function_declaration())
2602 Function_declaration* fd =
2603 named_object->func_declaration_value();
2604 fd->set_asm_name(extern_name);
2609 if (pragmas != 0 && named_object->is_function_declaration())
2610 named_object->func_declaration_value()->set_pragmas(pragmas);
2612 else
2614 bool hold_is_erroneous_function = this->is_erroneous_function_;
2615 if (fntype == NULL)
2617 fntype = Type::make_function_type(NULL, NULL, NULL, location);
2618 this->is_erroneous_function_ = true;
2619 if (!Gogo::is_sink_name(name))
2620 this->gogo_->add_erroneous_name(name);
2621 name = this->gogo_->pack_hidden_name("_", false);
2623 named_object = this->gogo_->start_function(name, fntype, true, location);
2624 Location end_loc = this->block();
2625 this->gogo_->finish_function(end_loc);
2627 if (pragmas != 0
2628 && !this->is_erroneous_function_
2629 && named_object->is_function())
2630 named_object->func_value()->set_pragmas(pragmas);
2631 this->is_erroneous_function_ = hold_is_erroneous_function;
2635 // Receiver = Parameters .
2637 Typed_identifier*
2638 Parse::receiver()
2640 Location location = this->location();
2641 Typed_identifier_list* til;
2642 if (!this->parameters(&til, NULL))
2643 return NULL;
2644 else if (til == NULL || til->empty())
2646 go_error_at(location, "method has no receiver");
2647 return NULL;
2649 else if (til->size() > 1)
2651 go_error_at(location, "method has multiple receivers");
2652 return NULL;
2654 else
2655 return &til->front();
2658 // Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2659 // Literal = BasicLit | CompositeLit | FunctionLit .
2660 // BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2662 // If MAY_BE_SINK is true, this operand may be "_".
2664 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
2665 // if the entire expression is in parentheses.
2667 Expression*
2668 Parse::operand(bool may_be_sink, bool* is_parenthesized)
2670 const Token* token = this->peek_token();
2671 Expression* ret;
2672 switch (token->classification())
2674 case Token::TOKEN_IDENTIFIER:
2676 Location location = token->location();
2677 std::string id = token->identifier();
2678 bool is_exported = token->is_identifier_exported();
2679 std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2681 Named_object* in_function;
2682 Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2684 Package* package = NULL;
2685 if (named_object != NULL && named_object->is_package())
2687 if (!this->advance_token()->is_op(OPERATOR_DOT)
2688 || !this->advance_token()->is_identifier())
2690 go_error_at(location, "unexpected reference to package");
2691 return Expression::make_error(location);
2693 package = named_object->package_value();
2694 package->note_usage(id);
2695 id = this->peek_token()->identifier();
2696 is_exported = this->peek_token()->is_identifier_exported();
2697 packed = this->gogo_->pack_hidden_name(id, is_exported);
2698 named_object = package->lookup(packed);
2699 location = this->location();
2700 go_assert(in_function == NULL);
2703 this->advance_token();
2705 if (named_object != NULL
2706 && named_object->is_type()
2707 && !named_object->type_value()->is_visible())
2709 go_assert(package != NULL);
2710 go_error_at(location, "invalid reference to hidden type %<%s.%s%>",
2711 Gogo::message_name(package->package_name()).c_str(),
2712 Gogo::message_name(id).c_str());
2713 return Expression::make_error(location);
2717 if (named_object == NULL)
2719 if (package != NULL)
2721 std::string n1 = Gogo::message_name(package->package_name());
2722 std::string n2 = Gogo::message_name(id);
2723 if (!is_exported)
2724 go_error_at(location,
2725 ("invalid reference to unexported identifier "
2726 "%<%s.%s%>"),
2727 n1.c_str(), n2.c_str());
2728 else
2729 go_error_at(location,
2730 "reference to undefined identifier %<%s.%s%>",
2731 n1.c_str(), n2.c_str());
2732 return Expression::make_error(location);
2735 named_object = this->gogo_->add_unknown_name(packed, location);
2738 if (in_function != NULL
2739 && in_function != this->gogo_->current_function()
2740 && (named_object->is_variable()
2741 || named_object->is_result_variable()))
2742 return this->enclosing_var_reference(in_function, named_object,
2743 may_be_sink, location);
2745 switch (named_object->classification())
2747 case Named_object::NAMED_OBJECT_CONST:
2748 return Expression::make_const_reference(named_object, location);
2749 case Named_object::NAMED_OBJECT_TYPE:
2750 return Expression::make_type(named_object->type_value(), location);
2751 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2753 Type* t = Type::make_forward_declaration(named_object);
2754 return Expression::make_type(t, location);
2756 case Named_object::NAMED_OBJECT_VAR:
2757 case Named_object::NAMED_OBJECT_RESULT_VAR:
2758 // Any left-hand-side can be a sink, so if this can not be
2759 // a sink, then it must be a use of the variable.
2760 if (!may_be_sink)
2761 this->mark_var_used(named_object);
2762 return Expression::make_var_reference(named_object, location);
2763 case Named_object::NAMED_OBJECT_SINK:
2764 if (may_be_sink)
2765 return Expression::make_sink(location);
2766 else
2768 go_error_at(location, "cannot use %<_%> as value");
2769 return Expression::make_error(location);
2771 case Named_object::NAMED_OBJECT_FUNC:
2772 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2773 return Expression::make_func_reference(named_object, NULL,
2774 location);
2775 case Named_object::NAMED_OBJECT_UNKNOWN:
2777 Unknown_expression* ue =
2778 Expression::make_unknown_reference(named_object, location);
2779 if (this->is_erroneous_function_)
2780 ue->set_no_error_message();
2781 return ue;
2783 case Named_object::NAMED_OBJECT_ERRONEOUS:
2784 return Expression::make_error(location);
2785 default:
2786 go_unreachable();
2789 go_unreachable();
2791 case Token::TOKEN_STRING:
2792 ret = Expression::make_string(token->string_value(), token->location());
2793 this->advance_token();
2794 return ret;
2796 case Token::TOKEN_CHARACTER:
2797 ret = Expression::make_character(token->character_value(), NULL,
2798 token->location());
2799 this->advance_token();
2800 return ret;
2802 case Token::TOKEN_INTEGER:
2803 ret = Expression::make_integer_z(token->integer_value(), NULL,
2804 token->location());
2805 this->advance_token();
2806 return ret;
2808 case Token::TOKEN_FLOAT:
2809 ret = Expression::make_float(token->float_value(), NULL,
2810 token->location());
2811 this->advance_token();
2812 return ret;
2814 case Token::TOKEN_IMAGINARY:
2816 mpfr_t zero;
2817 mpfr_init_set_ui(zero, 0, MPFR_RNDN);
2818 mpc_t val;
2819 mpc_init2(val, mpc_precision);
2820 mpc_set_fr_fr(val, zero, *token->imaginary_value(), MPC_RNDNN);
2821 mpfr_clear(zero);
2822 ret = Expression::make_complex(&val, NULL, token->location());
2823 mpc_clear(val);
2824 this->advance_token();
2825 return ret;
2828 case Token::TOKEN_KEYWORD:
2829 switch (token->keyword())
2831 case KEYWORD_FUNC:
2832 return this->function_lit();
2833 case KEYWORD_CHAN:
2834 case KEYWORD_INTERFACE:
2835 case KEYWORD_MAP:
2836 case KEYWORD_STRUCT:
2838 Location location = token->location();
2839 return Expression::make_type(this->type(), location);
2841 default:
2842 break;
2844 break;
2846 case Token::TOKEN_OPERATOR:
2847 if (token->is_op(OPERATOR_LPAREN))
2849 this->advance_token();
2850 ret = this->expression(PRECEDENCE_NORMAL, may_be_sink, true, NULL,
2851 NULL);
2852 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2853 go_error_at(this->location(), "missing %<)%>");
2854 else
2855 this->advance_token();
2856 if (is_parenthesized != NULL)
2857 *is_parenthesized = true;
2858 return ret;
2860 else if (token->is_op(OPERATOR_LSQUARE))
2862 // Here we call array_type directly, as this is the only
2863 // case where an ellipsis is permitted for an array type.
2864 Location location = token->location();
2865 return Expression::make_type(this->array_type(true), location);
2867 break;
2869 default:
2870 break;
2873 go_error_at(this->location(), "expected operand");
2874 return Expression::make_error(this->location());
2877 // Handle a reference to a variable in an enclosing function. We add
2878 // it to a list of such variables. We return a reference to a field
2879 // in a struct which will be passed on the static chain when calling
2880 // the current function.
2882 Expression*
2883 Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2884 bool may_be_sink, Location location)
2886 go_assert(var->is_variable() || var->is_result_variable());
2888 // Any left-hand-side can be a sink, so if this can not be
2889 // a sink, then it must be a use of the variable.
2890 if (!may_be_sink)
2891 this->mark_var_used(var);
2893 Named_object* this_function = this->gogo_->current_function();
2894 Named_object* closure = this_function->func_value()->closure_var();
2896 // The last argument to the Enclosing_var constructor is the index
2897 // of this variable in the closure. We add 1 to the current number
2898 // of enclosed variables, because the first field in the closure
2899 // points to the function code.
2900 Enclosing_var ev(var, in_function, this->enclosing_vars_.size() + 1);
2901 std::pair<Enclosing_vars::iterator, bool> ins =
2902 this->enclosing_vars_.insert(ev);
2903 if (ins.second)
2905 // This is a variable we have not seen before. Add a new field
2906 // to the closure type.
2907 this_function->func_value()->add_closure_field(var, location);
2910 Expression* closure_ref = Expression::make_var_reference(closure,
2911 location);
2912 closure_ref =
2913 Expression::make_dereference(closure_ref,
2914 Expression::NIL_CHECK_NOT_NEEDED,
2915 location);
2917 // The closure structure holds pointers to the variables, so we need
2918 // to introduce an indirection.
2919 Expression* e = Expression::make_field_reference(closure_ref,
2920 ins.first->index(),
2921 location);
2922 e = Expression::make_dereference(e, Expression::NIL_CHECK_NOT_NEEDED,
2923 location);
2924 return Expression::make_enclosing_var_reference(e, var, location);
2927 // CompositeLit = LiteralType LiteralValue .
2928 // LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
2929 // SliceType | MapType | TypeName .
2930 // LiteralValue = "{" [ ElementList [ "," ] ] "}" .
2931 // ElementList = Element { "," Element } .
2932 // Element = [ Key ":" ] Value .
2933 // Key = FieldName | ElementIndex .
2934 // FieldName = identifier .
2935 // ElementIndex = Expression .
2936 // Value = Expression | LiteralValue .
2938 // We have already seen the type if there is one, and we are now
2939 // looking at the LiteralValue. The case "[" "..." "]" ElementType
2940 // will be seen here as an array type whose length is "nil". The
2941 // DEPTH parameter is non-zero if this is an embedded composite
2942 // literal and the type was omitted. It gives the number of steps up
2943 // to the type which was provided. E.g., in [][]int{{1}} it will be
2944 // 1. In [][][]int{{{1}}} it will be 2.
2946 Expression*
2947 Parse::composite_lit(Type* type, int depth, Location location)
2949 go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2950 this->advance_token();
2952 if (this->peek_token()->is_op(OPERATOR_RCURLY))
2954 this->advance_token();
2955 return Expression::make_composite_literal(type, depth, false, NULL,
2956 false, location);
2959 bool has_keys = false;
2960 bool all_are_names = true;
2961 Expression_list* vals = new Expression_list;
2962 while (true)
2964 Expression* val;
2965 bool is_type_omitted = false;
2966 bool is_name = false;
2968 const Token* token = this->peek_token();
2970 if (token->is_identifier())
2972 std::string identifier = token->identifier();
2973 bool is_exported = token->is_identifier_exported();
2974 Location id_location = token->location();
2976 if (this->advance_token()->is_op(OPERATOR_COLON))
2978 // This may be a field name. We don't know for sure--it
2979 // could also be an expression for an array index. We
2980 // don't want to parse it as an expression because may
2981 // trigger various errors, e.g., if this identifier
2982 // happens to be the name of a package.
2983 Gogo* gogo = this->gogo_;
2984 val = this->id_to_expression(gogo->pack_hidden_name(identifier,
2985 is_exported),
2986 id_location, false, true);
2987 is_name = true;
2989 else
2991 this->unget_token(Token::make_identifier_token(identifier,
2992 is_exported,
2993 id_location));
2994 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
2995 NULL);
2998 else if (!token->is_op(OPERATOR_LCURLY))
2999 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3000 else
3002 // This must be a composite literal inside another composite
3003 // literal, with the type omitted for the inner one.
3004 val = this->composite_lit(type, depth + 1, token->location());
3005 is_type_omitted = true;
3008 token = this->peek_token();
3009 if (!token->is_op(OPERATOR_COLON))
3011 if (has_keys)
3012 vals->push_back(NULL);
3013 is_name = false;
3015 else
3017 if (is_type_omitted)
3019 // VAL is a nested composite literal with an omitted type being
3020 // used a key. Record this information in VAL so that the correct
3021 // type is associated with the literal value if VAL is a
3022 // map literal.
3023 val->complit()->update_key_path(depth);
3026 this->advance_token();
3028 if (!has_keys && !vals->empty())
3030 Expression_list* newvals = new Expression_list;
3031 for (Expression_list::const_iterator p = vals->begin();
3032 p != vals->end();
3033 ++p)
3035 newvals->push_back(NULL);
3036 newvals->push_back(*p);
3038 delete vals;
3039 vals = newvals;
3041 has_keys = true;
3043 vals->push_back(val);
3045 if (!token->is_op(OPERATOR_LCURLY))
3046 val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3047 else
3049 // This must be a composite literal inside another
3050 // composite literal, with the type omitted for the
3051 // inner one.
3052 val = this->composite_lit(type, depth + 1, token->location());
3055 token = this->peek_token();
3058 vals->push_back(val);
3060 if (!is_name)
3061 all_are_names = false;
3063 if (token->is_op(OPERATOR_COMMA))
3065 if (this->advance_token()->is_op(OPERATOR_RCURLY))
3067 this->advance_token();
3068 break;
3071 else if (token->is_op(OPERATOR_RCURLY))
3073 this->advance_token();
3074 break;
3076 else
3078 if (token->is_op(OPERATOR_SEMICOLON))
3079 go_error_at(this->location(),
3080 ("need trailing comma before newline "
3081 "in composite literal"));
3082 else
3083 go_error_at(this->location(), "expected %<,%> or %<}%>");
3085 this->gogo_->mark_locals_used();
3086 int edepth = 0;
3087 while (!token->is_eof()
3088 && (edepth > 0 || !token->is_op(OPERATOR_RCURLY)))
3090 if (token->is_op(OPERATOR_LCURLY))
3091 ++edepth;
3092 else if (token->is_op(OPERATOR_RCURLY))
3093 --edepth;
3094 token = this->advance_token();
3096 if (token->is_op(OPERATOR_RCURLY))
3097 this->advance_token();
3099 return Expression::make_error(location);
3103 return Expression::make_composite_literal(type, depth, has_keys, vals,
3104 all_are_names, location);
3107 // FunctionLit = "func" Signature Block .
3109 Expression*
3110 Parse::function_lit()
3112 Location location = this->location();
3113 go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
3114 this->advance_token();
3116 Enclosing_vars hold_enclosing_vars;
3117 hold_enclosing_vars.swap(this->enclosing_vars_);
3119 Function_type* type = this->signature(NULL, location);
3120 bool fntype_is_error = false;
3121 if (type == NULL)
3123 type = Type::make_function_type(NULL, NULL, NULL, location);
3124 fntype_is_error = true;
3127 // For a function literal, the next token must be a '{'. If we
3128 // don't see that, then we may have a type expression.
3129 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
3131 hold_enclosing_vars.swap(this->enclosing_vars_);
3132 return Expression::make_type(type, location);
3135 bool hold_is_erroneous_function = this->is_erroneous_function_;
3136 if (fntype_is_error)
3137 this->is_erroneous_function_ = true;
3139 Bc_stack* hold_break_stack = this->break_stack_;
3140 Bc_stack* hold_continue_stack = this->continue_stack_;
3141 this->break_stack_ = NULL;
3142 this->continue_stack_ = NULL;
3144 Named_object* no = this->gogo_->start_function("", type, true, location);
3146 Location end_loc = this->block();
3148 this->gogo_->finish_function(end_loc);
3150 if (this->break_stack_ != NULL)
3151 delete this->break_stack_;
3152 if (this->continue_stack_ != NULL)
3153 delete this->continue_stack_;
3154 this->break_stack_ = hold_break_stack;
3155 this->continue_stack_ = hold_continue_stack;
3157 this->is_erroneous_function_ = hold_is_erroneous_function;
3159 hold_enclosing_vars.swap(this->enclosing_vars_);
3161 Expression* closure = this->create_closure(no, &hold_enclosing_vars,
3162 location);
3164 return Expression::make_func_reference(no, closure, location);
3167 // Create a closure for the nested function FUNCTION. This is based
3168 // on ENCLOSING_VARS, which is a list of all variables defined in
3169 // enclosing functions and referenced from FUNCTION. A closure is the
3170 // address of a struct which point to the real function code and
3171 // contains the addresses of all the referenced variables. This
3172 // returns NULL if no closure is required.
3174 Expression*
3175 Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
3176 Location location)
3178 if (enclosing_vars->empty())
3179 return NULL;
3181 // Get the variables in order by their field index.
3183 size_t enclosing_var_count = enclosing_vars->size();
3184 std::vector<Enclosing_var> ev(enclosing_var_count);
3185 for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
3186 p != enclosing_vars->end();
3187 ++p)
3189 // Subtract 1 because index 0 is the function code.
3190 ev[p->index() - 1] = *p;
3193 // Build an initializer for a composite literal of the closure's
3194 // type.
3196 Named_object* enclosing_function = this->gogo_->current_function();
3197 Expression_list* initializer = new Expression_list;
3199 initializer->push_back(Expression::make_func_code_reference(function,
3200 location));
3202 for (size_t i = 0; i < enclosing_var_count; ++i)
3204 // Add 1 to i because the first field in the closure is a
3205 // pointer to the function code.
3206 go_assert(ev[i].index() == i + 1);
3207 Named_object* var = ev[i].var();
3208 Expression* ref;
3209 if (ev[i].in_function() == enclosing_function)
3210 ref = Expression::make_var_reference(var, location);
3211 else
3212 ref = this->enclosing_var_reference(ev[i].in_function(), var,
3213 true, location);
3214 Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
3215 location);
3216 initializer->push_back(refaddr);
3219 Named_object* closure_var = function->func_value()->closure_var();
3220 Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
3221 Expression* cv = Expression::make_struct_composite_literal(st, initializer,
3222 location);
3223 return Expression::make_heap_expression(cv, location);
3226 // PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
3228 // If MAY_BE_SINK is true, this expression may be "_".
3230 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3231 // literal.
3233 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3234 // guard (var := expr.("type") using the literal keyword "type").
3236 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3237 // if the entire expression is in parentheses.
3239 Expression*
3240 Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
3241 bool* is_type_switch, bool* is_parenthesized)
3243 Location start_loc = this->location();
3244 bool operand_is_parenthesized = false;
3245 bool whole_is_parenthesized = false;
3247 Expression* ret = this->operand(may_be_sink, &operand_is_parenthesized);
3249 whole_is_parenthesized = operand_is_parenthesized;
3251 // An unknown name followed by a curly brace must be a composite
3252 // literal, and the unknown name must be a type.
3253 if (may_be_composite_lit
3254 && !operand_is_parenthesized
3255 && ret->unknown_expression() != NULL
3256 && this->peek_token()->is_op(OPERATOR_LCURLY))
3258 Named_object* no = ret->unknown_expression()->named_object();
3259 Type* type = Type::make_forward_declaration(no);
3260 ret = Expression::make_type(type, ret->location());
3263 // We handle composite literals and type casts here, as it is the
3264 // easiest way to handle types which are in parentheses, as in
3265 // "((uint))(1)".
3266 if (ret->is_type_expression())
3268 if (this->peek_token()->is_op(OPERATOR_LCURLY))
3270 whole_is_parenthesized = false;
3271 if (!may_be_composite_lit)
3273 Type* t = ret->type();
3274 if (t->named_type() != NULL
3275 || t->forward_declaration_type() != NULL)
3276 go_error_at(start_loc,
3277 _("parentheses required around this composite "
3278 "literal to avoid parsing ambiguity"));
3280 else if (operand_is_parenthesized)
3281 go_error_at(start_loc,
3282 "cannot parenthesize type in composite literal");
3283 ret = this->composite_lit(ret->type(), 0, ret->location());
3285 else if (this->peek_token()->is_op(OPERATOR_LPAREN))
3287 whole_is_parenthesized = false;
3288 Location loc = this->location();
3289 this->advance_token();
3290 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
3291 NULL, NULL);
3292 if (this->peek_token()->is_op(OPERATOR_COMMA))
3293 this->advance_token();
3294 if (this->peek_token()->is_op(OPERATOR_ELLIPSIS))
3296 go_error_at(this->location(),
3297 "invalid use of %<...%> in type conversion");
3298 this->advance_token();
3300 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
3301 go_error_at(this->location(), "expected %<)%>");
3302 else
3303 this->advance_token();
3304 if (expr->is_error_expression())
3305 ret = expr;
3306 else
3308 Type* t = ret->type();
3309 if (t->classification() == Type::TYPE_ARRAY
3310 && t->array_type()->length() != NULL
3311 && t->array_type()->length()->is_nil_expression())
3313 go_error_at(ret->location(),
3314 "use of %<[...]%> outside of array literal");
3315 ret = Expression::make_error(loc);
3317 else
3318 ret = Expression::make_cast(t, expr, loc);
3323 while (true)
3325 const Token* token = this->peek_token();
3326 if (token->is_op(OPERATOR_LPAREN))
3328 whole_is_parenthesized = false;
3329 ret = this->call(this->verify_not_sink(ret));
3331 else if (token->is_op(OPERATOR_DOT))
3333 whole_is_parenthesized = false;
3334 ret = this->selector(this->verify_not_sink(ret), is_type_switch);
3335 if (is_type_switch != NULL && *is_type_switch)
3336 break;
3338 else if (token->is_op(OPERATOR_LSQUARE))
3340 whole_is_parenthesized = false;
3341 ret = this->index(this->verify_not_sink(ret));
3343 else
3344 break;
3347 if (whole_is_parenthesized && is_parenthesized != NULL)
3348 *is_parenthesized = true;
3350 return ret;
3353 // Selector = "." identifier .
3354 // TypeGuard = "." "(" QualifiedIdent ")" .
3356 // Note that Operand can expand to QualifiedIdent, which contains a
3357 // ".". That is handled directly in operand when it sees a package
3358 // name.
3360 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3361 // guard (var := expr.("type") using the literal keyword "type").
3363 Expression*
3364 Parse::selector(Expression* left, bool* is_type_switch)
3366 go_assert(this->peek_token()->is_op(OPERATOR_DOT));
3367 Location location = this->location();
3369 const Token* token = this->advance_token();
3370 if (token->is_identifier())
3372 // This could be a field in a struct, or a method in an
3373 // interface, or a method associated with a type. We can't know
3374 // which until we have seen all the types.
3375 std::string name =
3376 this->gogo_->pack_hidden_name(token->identifier(),
3377 token->is_identifier_exported());
3378 if (token->identifier() == "_")
3380 go_error_at(this->location(), "invalid use of %<_%>");
3381 name = Gogo::erroneous_name();
3383 this->advance_token();
3384 return Expression::make_selector(left, name, location);
3386 else if (token->is_op(OPERATOR_LPAREN))
3388 this->advance_token();
3389 Type* type = NULL;
3390 if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
3391 type = this->type();
3392 else
3394 if (is_type_switch != NULL)
3395 *is_type_switch = true;
3396 else
3398 go_error_at(this->location(),
3399 "use of %<.(type)%> outside type switch");
3400 type = Type::make_error_type();
3402 this->advance_token();
3404 if (!this->peek_token()->is_op(OPERATOR_RPAREN))
3405 go_error_at(this->location(), "missing %<)%>");
3406 else
3407 this->advance_token();
3408 if (is_type_switch != NULL && *is_type_switch)
3409 return left;
3410 return Expression::make_type_guard(left, type, location);
3412 else
3414 go_error_at(this->location(), "expected identifier or %<(%>");
3415 return left;
3419 // Index = "[" Expression "]" .
3420 // Slice = "[" Expression ":" [ Expression ] [ ":" Expression ] "]" .
3422 Expression*
3423 Parse::index(Expression* expr)
3425 Location location = this->location();
3426 go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
3427 this->advance_token();
3429 Expression* start;
3430 if (!this->peek_token()->is_op(OPERATOR_COLON))
3431 start = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3432 else
3433 start = Expression::make_integer_ul(0, NULL, location);
3435 Expression* end = NULL;
3436 if (this->peek_token()->is_op(OPERATOR_COLON))
3438 // We use nil to indicate a missing high expression.
3439 if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3440 end = Expression::make_nil(this->location());
3441 else if (this->peek_token()->is_op(OPERATOR_COLON))
3443 go_error_at(this->location(),
3444 "middle index required in 3-index slice");
3445 end = Expression::make_error(this->location());
3447 else
3448 end = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3451 Expression* cap = NULL;
3452 if (this->peek_token()->is_op(OPERATOR_COLON))
3454 if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3456 go_error_at(this->location(),
3457 "final index required in 3-index slice");
3458 cap = Expression::make_error(this->location());
3460 else
3461 cap = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
3463 if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
3464 go_error_at(this->location(), "missing %<]%>");
3465 else
3466 this->advance_token();
3467 return Expression::make_index(expr, start, end, cap, location);
3470 // Call = "(" [ ArgumentList [ "," ] ] ")" .
3471 // ArgumentList = ExpressionList [ "..." ] .
3473 Expression*
3474 Parse::call(Expression* func)
3476 go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
3477 Expression_list* args = NULL;
3478 bool is_varargs = false;
3479 const Token* token = this->advance_token();
3480 if (!token->is_op(OPERATOR_RPAREN))
3482 args = this->expression_list(NULL, false, true);
3483 token = this->peek_token();
3484 if (token->is_op(OPERATOR_ELLIPSIS))
3486 is_varargs = true;
3487 token = this->advance_token();
3490 if (token->is_op(OPERATOR_COMMA))
3491 token = this->advance_token();
3492 if (!token->is_op(OPERATOR_RPAREN))
3494 go_error_at(this->location(), "missing %<)%>");
3495 if (!this->skip_past_error(OPERATOR_RPAREN))
3496 return Expression::make_error(this->location());
3498 this->advance_token();
3499 if (func->is_error_expression())
3500 return func;
3501 return Expression::make_call(func, args, is_varargs, func->location());
3504 // Return an expression for a single unqualified identifier.
3506 Expression*
3507 Parse::id_to_expression(const std::string& name, Location location,
3508 bool is_lhs, bool is_composite_literal_key)
3510 Named_object* in_function;
3511 Named_object* named_object = this->gogo_->lookup(name, &in_function);
3512 if (named_object == NULL)
3514 if (is_composite_literal_key)
3516 // This is a composite literal key, which means that it
3517 // could just be a struct field name, so avoid confusion by
3518 // not adding it to the bindings. We'll look up the name
3519 // later during the determine types phase if necessary.
3520 return Expression::make_composite_literal_key(name, location);
3522 named_object = this->gogo_->add_unknown_name(name, location);
3525 if (in_function != NULL
3526 && in_function != this->gogo_->current_function()
3527 && (named_object->is_variable() || named_object->is_result_variable()))
3528 return this->enclosing_var_reference(in_function, named_object, is_lhs,
3529 location);
3531 switch (named_object->classification())
3533 case Named_object::NAMED_OBJECT_CONST:
3534 return Expression::make_const_reference(named_object, location);
3535 case Named_object::NAMED_OBJECT_VAR:
3536 case Named_object::NAMED_OBJECT_RESULT_VAR:
3537 if (!is_lhs)
3538 this->mark_var_used(named_object);
3539 return Expression::make_var_reference(named_object, location);
3540 case Named_object::NAMED_OBJECT_SINK:
3541 return Expression::make_sink(location);
3542 case Named_object::NAMED_OBJECT_FUNC:
3543 case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3544 return Expression::make_func_reference(named_object, NULL, location);
3545 case Named_object::NAMED_OBJECT_UNKNOWN:
3547 Unknown_expression* ue =
3548 Expression::make_unknown_reference(named_object, location);
3549 if (this->is_erroneous_function_)
3550 ue->set_no_error_message();
3551 return ue;
3553 case Named_object::NAMED_OBJECT_PACKAGE:
3554 case Named_object::NAMED_OBJECT_TYPE:
3555 case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3557 // These cases can arise for a field name in a composite
3558 // literal. Keep track of these as they might be fake uses of
3559 // the related package.
3560 Unknown_expression* ue =
3561 Expression::make_unknown_reference(named_object, location);
3562 if (named_object->package() != NULL)
3563 named_object->package()->note_fake_usage(ue);
3564 if (this->is_erroneous_function_)
3565 ue->set_no_error_message();
3566 return ue;
3568 case Named_object::NAMED_OBJECT_ERRONEOUS:
3569 return Expression::make_error(location);
3570 default:
3571 go_error_at(this->location(), "unexpected type of identifier");
3572 return Expression::make_error(location);
3576 // Expression = UnaryExpr { binary_op Expression } .
3578 // PRECEDENCE is the precedence of the current operator.
3580 // If MAY_BE_SINK is true, this expression may be "_".
3582 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3583 // literal.
3585 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3586 // guard (var := expr.("type") using the literal keyword "type").
3588 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3589 // if the entire expression is in parentheses.
3591 Expression*
3592 Parse::expression(Precedence precedence, bool may_be_sink,
3593 bool may_be_composite_lit, bool* is_type_switch,
3594 bool *is_parenthesized)
3596 Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
3597 is_type_switch, is_parenthesized);
3599 while (true)
3601 if (is_type_switch != NULL && *is_type_switch)
3602 return left;
3604 const Token* token = this->peek_token();
3605 if (token->classification() != Token::TOKEN_OPERATOR)
3607 // Not a binary_op.
3608 return left;
3611 Precedence right_precedence;
3612 switch (token->op())
3614 case OPERATOR_OROR:
3615 right_precedence = PRECEDENCE_OROR;
3616 break;
3617 case OPERATOR_ANDAND:
3618 right_precedence = PRECEDENCE_ANDAND;
3619 break;
3620 case OPERATOR_EQEQ:
3621 case OPERATOR_NOTEQ:
3622 case OPERATOR_LT:
3623 case OPERATOR_LE:
3624 case OPERATOR_GT:
3625 case OPERATOR_GE:
3626 right_precedence = PRECEDENCE_RELOP;
3627 break;
3628 case OPERATOR_PLUS:
3629 case OPERATOR_MINUS:
3630 case OPERATOR_OR:
3631 case OPERATOR_XOR:
3632 right_precedence = PRECEDENCE_ADDOP;
3633 break;
3634 case OPERATOR_MULT:
3635 case OPERATOR_DIV:
3636 case OPERATOR_MOD:
3637 case OPERATOR_LSHIFT:
3638 case OPERATOR_RSHIFT:
3639 case OPERATOR_AND:
3640 case OPERATOR_BITCLEAR:
3641 right_precedence = PRECEDENCE_MULOP;
3642 break;
3643 default:
3644 right_precedence = PRECEDENCE_INVALID;
3645 break;
3648 if (right_precedence == PRECEDENCE_INVALID)
3650 // Not a binary_op.
3651 return left;
3654 if (is_parenthesized != NULL)
3655 *is_parenthesized = false;
3657 Operator op = token->op();
3658 Location binop_location = token->location();
3660 if (precedence >= right_precedence)
3662 // We've already seen A * B, and we see + C. We want to
3663 // return so that A * B becomes a group.
3664 return left;
3667 this->advance_token();
3669 left = this->verify_not_sink(left);
3670 Expression* right = this->expression(right_precedence, false,
3671 may_be_composite_lit,
3672 NULL, NULL);
3673 left = Expression::make_binary(op, left, right, binop_location);
3677 bool
3678 Parse::expression_may_start_here()
3680 const Token* token = this->peek_token();
3681 switch (token->classification())
3683 case Token::TOKEN_INVALID:
3684 case Token::TOKEN_EOF:
3685 return false;
3686 case Token::TOKEN_KEYWORD:
3687 switch (token->keyword())
3689 case KEYWORD_CHAN:
3690 case KEYWORD_FUNC:
3691 case KEYWORD_MAP:
3692 case KEYWORD_STRUCT:
3693 case KEYWORD_INTERFACE:
3694 return true;
3695 default:
3696 return false;
3698 case Token::TOKEN_IDENTIFIER:
3699 return true;
3700 case Token::TOKEN_STRING:
3701 return true;
3702 case Token::TOKEN_OPERATOR:
3703 switch (token->op())
3705 case OPERATOR_PLUS:
3706 case OPERATOR_MINUS:
3707 case OPERATOR_NOT:
3708 case OPERATOR_XOR:
3709 case OPERATOR_MULT:
3710 case OPERATOR_CHANOP:
3711 case OPERATOR_AND:
3712 case OPERATOR_LPAREN:
3713 case OPERATOR_LSQUARE:
3714 return true;
3715 default:
3716 return false;
3718 case Token::TOKEN_CHARACTER:
3719 case Token::TOKEN_INTEGER:
3720 case Token::TOKEN_FLOAT:
3721 case Token::TOKEN_IMAGINARY:
3722 return true;
3723 default:
3724 go_unreachable();
3728 // UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3730 // If MAY_BE_SINK is true, this expression may be "_".
3732 // If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3733 // literal.
3735 // If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3736 // guard (var := expr.("type") using the literal keyword "type").
3738 // If IS_PARENTHESIZED is not NULL, *IS_PARENTHESIZED is set to true
3739 // if the entire expression is in parentheses.
3741 Expression*
3742 Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3743 bool* is_type_switch, bool* is_parenthesized)
3745 const Token* token = this->peek_token();
3747 // There is a complex parse for <- chan. The choices are
3748 // Convert x to type <- chan int:
3749 // (<- chan int)(x)
3750 // Receive from (x converted to type chan <- chan int):
3751 // (<- chan <- chan int (x))
3752 // Convert x to type <- chan (<- chan int).
3753 // (<- chan <- chan int)(x)
3754 if (token->is_op(OPERATOR_CHANOP))
3756 Location location = token->location();
3757 if (this->advance_token()->is_keyword(KEYWORD_CHAN))
3759 Expression* expr = this->primary_expr(false, may_be_composite_lit,
3760 NULL, NULL);
3761 if (expr->is_error_expression())
3762 return expr;
3763 else if (!expr->is_type_expression())
3764 return Expression::make_receive(expr, location);
3765 else
3767 if (expr->type()->is_error_type())
3768 return expr;
3770 // We picked up "chan TYPE", but it is not a type
3771 // conversion.
3772 Channel_type* ct = expr->type()->channel_type();
3773 if (ct == NULL)
3775 // This is probably impossible.
3776 go_error_at(location, "expected channel type");
3777 return Expression::make_error(location);
3779 else if (ct->may_receive())
3781 // <- chan TYPE.
3782 Type* t = Type::make_channel_type(false, true,
3783 ct->element_type());
3784 return Expression::make_type(t, location);
3786 else
3788 // <- chan <- TYPE. Because we skipped the leading
3789 // <-, we parsed this as chan <- TYPE. With the
3790 // leading <-, we parse it as <- chan (<- TYPE).
3791 Type *t = this->reassociate_chan_direction(ct, location);
3792 return Expression::make_type(t, location);
3797 this->unget_token(Token::make_operator_token(OPERATOR_CHANOP, location));
3798 token = this->peek_token();
3801 if (token->is_op(OPERATOR_PLUS)
3802 || token->is_op(OPERATOR_MINUS)
3803 || token->is_op(OPERATOR_NOT)
3804 || token->is_op(OPERATOR_XOR)
3805 || token->is_op(OPERATOR_CHANOP)
3806 || token->is_op(OPERATOR_MULT)
3807 || token->is_op(OPERATOR_AND))
3809 Location location = token->location();
3810 Operator op = token->op();
3811 this->advance_token();
3813 Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL,
3814 NULL);
3815 if (expr->is_error_expression())
3817 else if (op == OPERATOR_MULT && expr->is_type_expression())
3818 expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3819 location);
3820 else if (op == OPERATOR_AND && expr->is_composite_literal())
3821 expr = Expression::make_heap_expression(expr, location);
3822 else if (op != OPERATOR_CHANOP)
3823 expr = Expression::make_unary(op, expr, location);
3824 else
3825 expr = Expression::make_receive(expr, location);
3826 return expr;
3828 else
3829 return this->primary_expr(may_be_sink, may_be_composite_lit,
3830 is_type_switch, is_parenthesized);
3833 // This is called for the obscure case of
3834 // (<- chan <- chan int)(x)
3835 // In unary_expr we remove the leading <- and parse the remainder,
3836 // which gives us
3837 // chan <- (chan int)
3838 // When we add the leading <- back in, we really want
3839 // <- chan (<- chan int)
3840 // This means that we need to reassociate.
3842 Type*
3843 Parse::reassociate_chan_direction(Channel_type *ct, Location location)
3845 Channel_type* ele = ct->element_type()->channel_type();
3846 if (ele == NULL)
3848 go_error_at(location, "parse error");
3849 return Type::make_error_type();
3851 Type* sub = ele;
3852 if (ele->may_send())
3853 sub = Type::make_channel_type(false, true, ele->element_type());
3854 else
3855 sub = this->reassociate_chan_direction(ele, location);
3856 return Type::make_channel_type(false, true, sub);
3859 // Statement =
3860 // Declaration | LabeledStmt | SimpleStmt |
3861 // GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3862 // FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3863 // DeferStmt .
3865 // LABEL is the label of this statement if it has one.
3867 void
3868 Parse::statement(Label* label)
3870 const Token* token = this->peek_token();
3871 switch (token->classification())
3873 case Token::TOKEN_KEYWORD:
3875 switch (token->keyword())
3877 case KEYWORD_CONST:
3878 case KEYWORD_TYPE:
3879 case KEYWORD_VAR:
3880 this->declaration();
3881 break;
3882 case KEYWORD_FUNC:
3883 case KEYWORD_MAP:
3884 case KEYWORD_STRUCT:
3885 case KEYWORD_INTERFACE:
3886 this->simple_stat(true, NULL, NULL, NULL);
3887 break;
3888 case KEYWORD_GO:
3889 case KEYWORD_DEFER:
3890 this->go_or_defer_stat();
3891 break;
3892 case KEYWORD_RETURN:
3893 this->return_stat();
3894 break;
3895 case KEYWORD_BREAK:
3896 this->break_stat();
3897 break;
3898 case KEYWORD_CONTINUE:
3899 this->continue_stat();
3900 break;
3901 case KEYWORD_GOTO:
3902 this->goto_stat();
3903 break;
3904 case KEYWORD_IF:
3905 this->if_stat();
3906 break;
3907 case KEYWORD_SWITCH:
3908 this->switch_stat(label);
3909 break;
3910 case KEYWORD_SELECT:
3911 this->select_stat(label);
3912 break;
3913 case KEYWORD_FOR:
3914 this->for_stat(label);
3915 break;
3916 default:
3917 go_error_at(this->location(), "expected statement");
3918 this->advance_token();
3919 break;
3922 break;
3924 case Token::TOKEN_IDENTIFIER:
3926 std::string identifier = token->identifier();
3927 bool is_exported = token->is_identifier_exported();
3928 Location location = token->location();
3929 if (this->advance_token()->is_op(OPERATOR_COLON))
3931 this->advance_token();
3932 this->labeled_stmt(identifier, location);
3934 else
3936 this->unget_token(Token::make_identifier_token(identifier,
3937 is_exported,
3938 location));
3939 this->simple_stat(true, NULL, NULL, NULL);
3942 break;
3944 case Token::TOKEN_OPERATOR:
3945 if (token->is_op(OPERATOR_LCURLY))
3947 Location location = token->location();
3948 this->gogo_->start_block(location);
3949 Location end_loc = this->block();
3950 this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3951 location);
3953 else if (!token->is_op(OPERATOR_SEMICOLON))
3954 this->simple_stat(true, NULL, NULL, NULL);
3955 break;
3957 case Token::TOKEN_STRING:
3958 case Token::TOKEN_CHARACTER:
3959 case Token::TOKEN_INTEGER:
3960 case Token::TOKEN_FLOAT:
3961 case Token::TOKEN_IMAGINARY:
3962 this->simple_stat(true, NULL, NULL, NULL);
3963 break;
3965 default:
3966 go_error_at(this->location(), "expected statement");
3967 this->advance_token();
3968 break;
3972 bool
3973 Parse::statement_may_start_here()
3975 const Token* token = this->peek_token();
3976 switch (token->classification())
3978 case Token::TOKEN_KEYWORD:
3980 switch (token->keyword())
3982 case KEYWORD_CONST:
3983 case KEYWORD_TYPE:
3984 case KEYWORD_VAR:
3985 case KEYWORD_FUNC:
3986 case KEYWORD_MAP:
3987 case KEYWORD_STRUCT:
3988 case KEYWORD_INTERFACE:
3989 case KEYWORD_GO:
3990 case KEYWORD_DEFER:
3991 case KEYWORD_RETURN:
3992 case KEYWORD_BREAK:
3993 case KEYWORD_CONTINUE:
3994 case KEYWORD_GOTO:
3995 case KEYWORD_IF:
3996 case KEYWORD_SWITCH:
3997 case KEYWORD_SELECT:
3998 case KEYWORD_FOR:
3999 return true;
4001 default:
4002 return false;
4005 break;
4007 case Token::TOKEN_IDENTIFIER:
4008 return true;
4010 case Token::TOKEN_OPERATOR:
4011 if (token->is_op(OPERATOR_LCURLY)
4012 || token->is_op(OPERATOR_SEMICOLON))
4013 return true;
4014 else
4015 return this->expression_may_start_here();
4017 case Token::TOKEN_STRING:
4018 case Token::TOKEN_CHARACTER:
4019 case Token::TOKEN_INTEGER:
4020 case Token::TOKEN_FLOAT:
4021 case Token::TOKEN_IMAGINARY:
4022 return true;
4024 default:
4025 return false;
4029 // LabeledStmt = Label ":" Statement .
4030 // Label = identifier .
4032 void
4033 Parse::labeled_stmt(const std::string& label_name, Location location)
4035 Label* label = this->gogo_->add_label_definition(label_name, location);
4037 if (this->peek_token()->is_op(OPERATOR_RCURLY))
4039 // This is a label at the end of a block. A program is
4040 // permitted to omit a semicolon here.
4041 return;
4044 if (!this->statement_may_start_here())
4046 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4048 // We don't treat the fallthrough keyword as a statement,
4049 // because it can't appear most places where a statement is
4050 // permitted, but it may have a label. We introduce a
4051 // semicolon because the caller expects to see a statement.
4052 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4053 location));
4054 return;
4057 // Mark the label as used to avoid a useless error about an
4058 // unused label.
4059 if (label != NULL)
4060 label->set_is_used();
4062 go_error_at(location, "missing statement after label");
4063 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4064 location));
4065 return;
4068 this->statement(label);
4071 // SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
4072 // Assignment | ShortVarDecl .
4074 // EmptyStmt was handled in Parse::statement.
4076 // In order to make this work for if and switch statements, if
4077 // RETURN_EXP is not NULL, and we see an ExpressionStat, we return the
4078 // expression rather than adding an expression statement to the
4079 // current block. If we see something other than an ExpressionStat,
4080 // we add the statement, set *RETURN_EXP to true if we saw a send
4081 // statement, and return NULL. The handling of send statements is for
4082 // better error messages.
4084 // If P_RANGE_CLAUSE is not NULL, then this will recognize a
4085 // RangeClause.
4087 // If P_TYPE_SWITCH is not NULL, this will recognize a type switch
4088 // guard (var := expr.("type") using the literal keyword "type").
4090 Expression*
4091 Parse::simple_stat(bool may_be_composite_lit, bool* return_exp,
4092 Range_clause* p_range_clause, Type_switch* p_type_switch)
4094 const Token* token = this->peek_token();
4096 // An identifier follow by := is a SimpleVarDecl.
4097 if (token->is_identifier())
4099 std::string identifier = token->identifier();
4100 bool is_exported = token->is_identifier_exported();
4101 Location location = token->location();
4103 token = this->advance_token();
4104 if (token->is_op(OPERATOR_COLONEQ)
4105 || token->is_op(OPERATOR_COMMA))
4107 identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
4108 this->simple_var_decl_or_assignment(identifier, location,
4109 may_be_composite_lit,
4110 p_range_clause,
4111 (token->is_op(OPERATOR_COLONEQ)
4112 ? p_type_switch
4113 : NULL));
4114 return NULL;
4117 this->unget_token(Token::make_identifier_token(identifier, is_exported,
4118 location));
4120 else if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
4122 Typed_identifier_list til;
4123 this->range_clause_decl(&til, p_range_clause);
4124 return NULL;
4127 Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
4128 may_be_composite_lit,
4129 (p_type_switch == NULL
4130 ? NULL
4131 : &p_type_switch->found),
4132 NULL);
4133 if (p_type_switch != NULL && p_type_switch->found)
4135 p_type_switch->name.clear();
4136 p_type_switch->location = exp->location();
4137 p_type_switch->expr = this->verify_not_sink(exp);
4138 return NULL;
4140 token = this->peek_token();
4141 if (token->is_op(OPERATOR_CHANOP))
4143 this->send_stmt(this->verify_not_sink(exp), may_be_composite_lit);
4144 if (return_exp != NULL)
4145 *return_exp = true;
4147 else if (token->is_op(OPERATOR_PLUSPLUS)
4148 || token->is_op(OPERATOR_MINUSMINUS))
4149 this->inc_dec_stat(this->verify_not_sink(exp));
4150 else if (token->is_op(OPERATOR_COMMA)
4151 || token->is_op(OPERATOR_EQ))
4152 this->assignment(exp, may_be_composite_lit, p_range_clause);
4153 else if (token->is_op(OPERATOR_PLUSEQ)
4154 || token->is_op(OPERATOR_MINUSEQ)
4155 || token->is_op(OPERATOR_OREQ)
4156 || token->is_op(OPERATOR_XOREQ)
4157 || token->is_op(OPERATOR_MULTEQ)
4158 || token->is_op(OPERATOR_DIVEQ)
4159 || token->is_op(OPERATOR_MODEQ)
4160 || token->is_op(OPERATOR_LSHIFTEQ)
4161 || token->is_op(OPERATOR_RSHIFTEQ)
4162 || token->is_op(OPERATOR_ANDEQ)
4163 || token->is_op(OPERATOR_BITCLEAREQ))
4164 this->assignment(this->verify_not_sink(exp), may_be_composite_lit,
4165 p_range_clause);
4166 else if (return_exp != NULL)
4167 return this->verify_not_sink(exp);
4168 else
4170 exp = this->verify_not_sink(exp);
4172 if (token->is_op(OPERATOR_COLONEQ))
4174 if (!exp->is_error_expression())
4175 go_error_at(token->location(), "non-name on left side of %<:=%>");
4176 this->gogo_->mark_locals_used();
4177 while (!token->is_op(OPERATOR_SEMICOLON)
4178 && !token->is_eof())
4179 token = this->advance_token();
4180 return NULL;
4183 this->expression_stat(exp);
4186 return NULL;
4189 bool
4190 Parse::simple_stat_may_start_here()
4192 return this->expression_may_start_here();
4195 // Parse { Statement ";" } which is used in a few places. The list of
4196 // statements may end with a right curly brace, in which case the
4197 // semicolon may be omitted.
4199 void
4200 Parse::statement_list()
4202 while (this->statement_may_start_here())
4204 this->statement(NULL);
4205 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4206 this->advance_token();
4207 else if (this->peek_token()->is_op(OPERATOR_RCURLY))
4208 break;
4209 else
4211 if (!this->peek_token()->is_eof() || !saw_errors())
4212 go_error_at(this->location(), "expected %<;%> or %<}%> or newline");
4213 if (!this->skip_past_error(OPERATOR_RCURLY))
4214 return;
4219 bool
4220 Parse::statement_list_may_start_here()
4222 return this->statement_may_start_here();
4225 // ExpressionStat = Expression .
4227 void
4228 Parse::expression_stat(Expression* exp)
4230 this->gogo_->add_statement(Statement::make_statement(exp, false));
4233 // SendStmt = Channel "&lt;-" Expression .
4234 // Channel = Expression .
4236 void
4237 Parse::send_stmt(Expression* channel, bool may_be_composite_lit)
4239 go_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
4240 Location loc = this->location();
4241 this->advance_token();
4242 Expression* val = this->expression(PRECEDENCE_NORMAL, false,
4243 may_be_composite_lit, NULL, NULL);
4244 Statement* s = Statement::make_send_statement(channel, val, loc);
4245 this->gogo_->add_statement(s);
4248 // IncDecStat = Expression ( "++" | "--" ) .
4250 void
4251 Parse::inc_dec_stat(Expression* exp)
4253 const Token* token = this->peek_token();
4254 if (token->is_op(OPERATOR_PLUSPLUS))
4255 this->gogo_->add_statement(Statement::make_inc_statement(exp));
4256 else if (token->is_op(OPERATOR_MINUSMINUS))
4257 this->gogo_->add_statement(Statement::make_dec_statement(exp));
4258 else
4259 go_unreachable();
4260 this->advance_token();
4263 // Assignment = ExpressionList assign_op ExpressionList .
4265 // EXP is an expression that we have already parsed.
4267 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
4268 // side may be a composite literal.
4270 // If RANGE_CLAUSE is not NULL, then this will recognize a
4271 // RangeClause.
4273 void
4274 Parse::assignment(Expression* expr, bool may_be_composite_lit,
4275 Range_clause* p_range_clause)
4277 Expression_list* vars;
4278 if (!this->peek_token()->is_op(OPERATOR_COMMA))
4280 vars = new Expression_list();
4281 vars->push_back(expr);
4283 else
4285 this->advance_token();
4286 vars = this->expression_list(expr, true, may_be_composite_lit);
4289 this->tuple_assignment(vars, may_be_composite_lit, p_range_clause);
4292 // An assignment statement. LHS is the list of expressions which
4293 // appear on the left hand side.
4295 // If MAY_BE_COMPOSITE_LIT is true, an expression on the right hand
4296 // side may be a composite literal.
4298 // If RANGE_CLAUSE is not NULL, then this will recognize a
4299 // RangeClause.
4301 void
4302 Parse::tuple_assignment(Expression_list* lhs, bool may_be_composite_lit,
4303 Range_clause* p_range_clause)
4305 const Token* token = this->peek_token();
4306 if (!token->is_op(OPERATOR_EQ)
4307 && !token->is_op(OPERATOR_PLUSEQ)
4308 && !token->is_op(OPERATOR_MINUSEQ)
4309 && !token->is_op(OPERATOR_OREQ)
4310 && !token->is_op(OPERATOR_XOREQ)
4311 && !token->is_op(OPERATOR_MULTEQ)
4312 && !token->is_op(OPERATOR_DIVEQ)
4313 && !token->is_op(OPERATOR_MODEQ)
4314 && !token->is_op(OPERATOR_LSHIFTEQ)
4315 && !token->is_op(OPERATOR_RSHIFTEQ)
4316 && !token->is_op(OPERATOR_ANDEQ)
4317 && !token->is_op(OPERATOR_BITCLEAREQ))
4319 go_error_at(this->location(), "expected assignment operator");
4320 return;
4322 Operator op = token->op();
4323 Location location = token->location();
4325 token = this->advance_token();
4327 if (lhs == NULL)
4328 return;
4330 if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
4332 if (op != OPERATOR_EQ)
4333 go_error_at(this->location(), "range clause requires %<=%>");
4334 this->range_clause_expr(lhs, p_range_clause);
4335 return;
4338 Expression_list* vals = this->expression_list(NULL, false,
4339 may_be_composite_lit);
4341 // We've parsed everything; check for errors.
4342 if (vals == NULL)
4343 return;
4344 for (Expression_list::const_iterator pe = lhs->begin();
4345 pe != lhs->end();
4346 ++pe)
4348 if ((*pe)->is_error_expression())
4349 return;
4350 if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
4351 go_error_at((*pe)->location(), "cannot use %<_%> as value");
4353 for (Expression_list::const_iterator pe = vals->begin();
4354 pe != vals->end();
4355 ++pe)
4357 if ((*pe)->is_error_expression())
4358 return;
4361 Call_expression* call;
4362 Index_expression* map_index;
4363 Receive_expression* receive;
4364 Type_guard_expression* type_guard;
4365 if (lhs->size() == vals->size())
4367 Statement* s;
4368 if (lhs->size() > 1)
4370 if (op != OPERATOR_EQ)
4371 go_error_at(location, "multiple values only permitted with %<=%>");
4372 s = Statement::make_tuple_assignment(lhs, vals, location);
4374 else
4376 if (op == OPERATOR_EQ)
4377 s = Statement::make_assignment(lhs->front(), vals->front(),
4378 location);
4379 else
4380 s = Statement::make_assignment_operation(op, lhs->front(),
4381 vals->front(), location);
4382 delete lhs;
4383 delete vals;
4385 this->gogo_->add_statement(s);
4387 else if (vals->size() == 1
4388 && (call = (*vals->begin())->call_expression()) != NULL)
4390 if (op != OPERATOR_EQ)
4391 go_error_at(location, "multiple results only permitted with %<=%>");
4392 call->set_expected_result_count(lhs->size());
4393 delete vals;
4394 vals = new Expression_list;
4395 for (unsigned int i = 0; i < lhs->size(); ++i)
4396 vals->push_back(Expression::make_call_result(call, i));
4397 Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
4398 this->gogo_->add_statement(s);
4400 else if (lhs->size() == 2
4401 && vals->size() == 1
4402 && (map_index = (*vals->begin())->index_expression()) != NULL)
4404 if (op != OPERATOR_EQ)
4405 go_error_at(location, "two values from map requires %<=%>");
4406 Expression* val = lhs->front();
4407 Expression* present = lhs->back();
4408 Statement* s = Statement::make_tuple_map_assignment(val, present,
4409 map_index, location);
4410 this->gogo_->add_statement(s);
4412 else if (lhs->size() == 2
4413 && vals->size() == 1
4414 && (receive = (*vals->begin())->receive_expression()) != NULL)
4416 if (op != OPERATOR_EQ)
4417 go_error_at(location, "two values from receive requires %<=%>");
4418 Expression* val = lhs->front();
4419 Expression* success = lhs->back();
4420 Expression* channel = receive->channel();
4421 Statement* s = Statement::make_tuple_receive_assignment(val, success,
4422 channel,
4423 location);
4424 this->gogo_->add_statement(s);
4426 else if (lhs->size() == 2
4427 && vals->size() == 1
4428 && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
4430 if (op != OPERATOR_EQ)
4431 go_error_at(location, "two values from type guard requires %<=%>");
4432 Expression* val = lhs->front();
4433 Expression* ok = lhs->back();
4434 Expression* expr = type_guard->expr();
4435 Type* type = type_guard->type();
4436 Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
4437 expr, type,
4438 location);
4439 this->gogo_->add_statement(s);
4441 else
4443 go_error_at(location, ("number of variables does not "
4444 "match number of values"));
4448 // GoStat = "go" Expression .
4449 // DeferStat = "defer" Expression .
4451 void
4452 Parse::go_or_defer_stat()
4454 go_assert(this->peek_token()->is_keyword(KEYWORD_GO)
4455 || this->peek_token()->is_keyword(KEYWORD_DEFER));
4456 bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
4457 Location stat_location = this->location();
4459 this->advance_token();
4460 Location expr_location = this->location();
4462 bool is_parenthesized = false;
4463 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL,
4464 &is_parenthesized);
4465 Call_expression* call_expr = expr->call_expression();
4466 if (is_parenthesized || call_expr == NULL)
4468 go_error_at(expr_location, "argument to go/defer must be function call");
4469 return;
4472 // Make it easier to simplify go/defer statements by putting every
4473 // statement in its own block.
4474 this->gogo_->start_block(stat_location);
4475 Statement* stat;
4476 if (is_go)
4478 stat = Statement::make_go_statement(call_expr, stat_location);
4479 call_expr->set_is_concurrent();
4481 else
4483 stat = Statement::make_defer_statement(call_expr, stat_location);
4484 call_expr->set_is_deferred();
4486 this->gogo_->add_statement(stat);
4487 this->gogo_->add_block(this->gogo_->finish_block(stat_location),
4488 stat_location);
4491 // ReturnStat = "return" [ ExpressionList ] .
4493 void
4494 Parse::return_stat()
4496 go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
4497 Location location = this->location();
4498 this->advance_token();
4499 Expression_list* vals = NULL;
4500 if (this->expression_may_start_here())
4501 vals = this->expression_list(NULL, false, true);
4502 Named_object* function = this->gogo_->current_function();
4503 this->gogo_->add_statement(Statement::make_return_statement(function, vals,
4504 location));
4506 if (vals == NULL && function->func_value()->results_are_named())
4508 Function::Results* results = function->func_value()->result_variables();
4509 for (Function::Results::const_iterator p = results->begin();
4510 p != results->end();
4511 ++p)
4513 Named_object* no = this->gogo_->lookup((*p)->name(), NULL);
4514 if (no == NULL)
4515 go_assert(saw_errors());
4516 else if (!no->is_result_variable())
4517 go_error_at(location, "%qs is shadowed during return",
4518 (*p)->message_name().c_str());
4523 // IfStmt = "if" [ SimpleStmt ";" ] Expression Block
4524 // [ "else" ( IfStmt | Block ) ] .
4526 void
4527 Parse::if_stat()
4529 go_assert(this->peek_token()->is_keyword(KEYWORD_IF));
4530 Location location = this->location();
4531 this->advance_token();
4533 this->gogo_->start_block(location);
4535 bool saw_simple_stat = false;
4536 Expression* cond = NULL;
4537 bool saw_send_stmt = false;
4538 if (this->simple_stat_may_start_here())
4540 cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL);
4541 saw_simple_stat = true;
4543 if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4545 // The SimpleStat is an expression statement.
4546 this->expression_stat(cond);
4547 cond = NULL;
4549 if (cond == NULL)
4551 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4552 this->advance_token();
4553 else if (saw_simple_stat)
4555 if (saw_send_stmt)
4556 go_error_at(this->location(),
4557 ("send statement used as value; "
4558 "use select for non-blocking send"));
4559 else
4560 go_error_at(this->location(),
4561 "expected %<;%> after statement in if expression");
4562 if (!this->expression_may_start_here())
4563 cond = Expression::make_error(this->location());
4565 if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY))
4567 go_error_at(this->location(),
4568 "missing condition in if statement");
4569 cond = Expression::make_error(this->location());
4571 if (cond == NULL)
4572 cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL, NULL);
4575 // Check for the easy error of a newline before starting the block.
4576 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4578 Location semi_loc = this->location();
4579 if (this->advance_token()->is_op(OPERATOR_LCURLY))
4580 go_error_at(semi_loc, "unexpected semicolon or newline, expecting %<{%> after if clause");
4581 // Otherwise we will get an error when we call this->block
4582 // below.
4585 this->gogo_->start_block(this->location());
4586 Location end_loc = this->block();
4587 Block* then_block = this->gogo_->finish_block(end_loc);
4589 // Check for the easy error of a newline before "else".
4590 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4592 Location semi_loc = this->location();
4593 if (this->advance_token()->is_keyword(KEYWORD_ELSE))
4594 go_error_at(this->location(),
4595 "unexpected semicolon or newline before %<else%>");
4596 else
4597 this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4598 semi_loc));
4601 Block* else_block = NULL;
4602 if (this->peek_token()->is_keyword(KEYWORD_ELSE))
4604 this->gogo_->start_block(this->location());
4605 const Token* token = this->advance_token();
4606 if (token->is_keyword(KEYWORD_IF))
4607 this->if_stat();
4608 else if (token->is_op(OPERATOR_LCURLY))
4609 this->block();
4610 else
4612 go_error_at(this->location(), "expected %<if%> or %<{%>");
4613 this->statement(NULL);
4615 else_block = this->gogo_->finish_block(this->location());
4618 this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
4619 else_block,
4620 location));
4622 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4623 location);
4626 // SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4627 // ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
4628 // "{" { ExprCaseClause } "}" .
4629 // TypeSwitchStmt = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
4630 // "{" { TypeCaseClause } "}" .
4631 // TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
4633 void
4634 Parse::switch_stat(Label* label)
4636 go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
4637 Location location = this->location();
4638 this->advance_token();
4640 this->gogo_->start_block(location);
4642 bool saw_simple_stat = false;
4643 Expression* switch_val = NULL;
4644 bool saw_send_stmt = false;
4645 Type_switch type_switch;
4646 bool have_type_switch_block = false;
4647 if (this->simple_stat_may_start_here())
4649 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4650 &type_switch);
4651 saw_simple_stat = true;
4653 if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4655 // The SimpleStat is an expression statement.
4656 this->expression_stat(switch_val);
4657 switch_val = NULL;
4659 if (switch_val == NULL && !type_switch.found)
4661 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4662 this->advance_token();
4663 else if (saw_simple_stat)
4665 if (saw_send_stmt)
4666 go_error_at(this->location(),
4667 ("send statement used as value; "
4668 "use select for non-blocking send"));
4669 else
4670 go_error_at(this->location(),
4671 "expected %<;%> after statement in switch expression");
4673 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4675 if (this->peek_token()->is_identifier())
4677 const Token* token = this->peek_token();
4678 std::string identifier = token->identifier();
4679 bool is_exported = token->is_identifier_exported();
4680 Location id_loc = token->location();
4682 token = this->advance_token();
4683 bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
4684 this->unget_token(Token::make_identifier_token(identifier,
4685 is_exported,
4686 id_loc));
4687 if (is_coloneq)
4689 // This must be a TypeSwitchGuard. It is in a
4690 // different block from any initial SimpleStat.
4691 if (saw_simple_stat)
4693 this->gogo_->start_block(id_loc);
4694 have_type_switch_block = true;
4697 switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4698 &type_switch);
4699 if (!type_switch.found)
4701 if (switch_val == NULL
4702 || !switch_val->is_error_expression())
4704 go_error_at(id_loc,
4705 "expected type switch assignment");
4706 switch_val = Expression::make_error(id_loc);
4711 if (switch_val == NULL && !type_switch.found)
4713 switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
4714 &type_switch.found, NULL);
4715 if (type_switch.found)
4717 type_switch.name.clear();
4718 type_switch.expr = switch_val;
4719 type_switch.location = switch_val->location();
4725 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4727 Location token_loc = this->location();
4728 if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
4729 && this->advance_token()->is_op(OPERATOR_LCURLY))
4730 go_error_at(token_loc, "missing %<{%> after switch clause");
4731 else if (this->peek_token()->is_op(OPERATOR_COLONEQ))
4733 go_error_at(token_loc, "invalid variable name");
4734 this->advance_token();
4735 this->expression(PRECEDENCE_NORMAL, false, false,
4736 &type_switch.found, NULL);
4737 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4738 this->advance_token();
4739 if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4741 if (have_type_switch_block)
4742 this->gogo_->add_block(this->gogo_->finish_block(location),
4743 location);
4744 this->gogo_->add_block(this->gogo_->finish_block(location),
4745 location);
4746 return;
4748 if (type_switch.found)
4749 type_switch.expr = Expression::make_error(location);
4751 else
4753 go_error_at(this->location(), "expected %<{%>");
4754 if (have_type_switch_block)
4755 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4756 location);
4757 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4758 location);
4759 return;
4762 this->advance_token();
4764 Statement* statement;
4765 if (type_switch.found)
4766 statement = this->type_switch_body(label, type_switch, location);
4767 else
4768 statement = this->expr_switch_body(label, switch_val, location);
4770 if (statement != NULL)
4771 this->gogo_->add_statement(statement);
4773 if (have_type_switch_block)
4774 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4775 location);
4777 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4778 location);
4781 // The body of an expression switch.
4782 // "{" { ExprCaseClause } "}"
4784 Statement*
4785 Parse::expr_switch_body(Label* label, Expression* switch_val,
4786 Location location)
4788 Switch_statement* statement = Statement::make_switch_statement(switch_val,
4789 location);
4791 this->push_break_statement(statement, label);
4793 Case_clauses* case_clauses = new Case_clauses();
4794 bool saw_default = false;
4795 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4797 if (this->peek_token()->is_eof())
4799 if (!saw_errors())
4800 go_error_at(this->location(), "missing %<}%>");
4801 return NULL;
4803 this->expr_case_clause(case_clauses, &saw_default);
4805 this->advance_token();
4807 statement->add_clauses(case_clauses);
4809 this->pop_break_statement();
4811 return statement;
4814 // ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
4815 // FallthroughStat = "fallthrough" .
4817 void
4818 Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
4820 Location location = this->location();
4822 bool is_default = false;
4823 Expression_list* vals = this->expr_switch_case(&is_default);
4825 if (!this->peek_token()->is_op(OPERATOR_COLON))
4827 if (!saw_errors())
4828 go_error_at(this->location(), "expected %<:%>");
4829 return;
4831 else
4832 this->advance_token();
4834 Block* statements = NULL;
4835 if (this->statement_list_may_start_here())
4837 this->gogo_->start_block(this->location());
4838 this->statement_list();
4839 statements = this->gogo_->finish_block(this->location());
4842 bool is_fallthrough = false;
4843 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4845 Location fallthrough_loc = this->location();
4846 is_fallthrough = true;
4847 while (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4849 if (this->peek_token()->is_op(OPERATOR_RCURLY))
4850 go_error_at(fallthrough_loc,
4851 _("cannot fallthrough final case in switch"));
4852 else if (!this->peek_token()->is_keyword(KEYWORD_CASE)
4853 && !this->peek_token()->is_keyword(KEYWORD_DEFAULT))
4855 go_error_at(fallthrough_loc, "fallthrough statement out of place");
4856 while (!this->peek_token()->is_keyword(KEYWORD_CASE)
4857 && !this->peek_token()->is_keyword(KEYWORD_DEFAULT)
4858 && !this->peek_token()->is_op(OPERATOR_RCURLY)
4859 && !this->peek_token()->is_eof())
4861 if (this->statement_may_start_here())
4862 this->statement_list();
4863 else
4864 this->advance_token();
4869 if (is_default)
4871 if (*saw_default)
4873 go_error_at(location, "multiple defaults in switch");
4874 return;
4876 *saw_default = true;
4879 if (is_default || vals != NULL)
4880 clauses->add(vals, is_default, statements, is_fallthrough, location);
4883 // ExprSwitchCase = "case" ExpressionList | "default" .
4885 Expression_list*
4886 Parse::expr_switch_case(bool* is_default)
4888 const Token* token = this->peek_token();
4889 if (token->is_keyword(KEYWORD_CASE))
4891 this->advance_token();
4892 return this->expression_list(NULL, false, true);
4894 else if (token->is_keyword(KEYWORD_DEFAULT))
4896 this->advance_token();
4897 *is_default = true;
4898 return NULL;
4900 else
4902 if (!saw_errors())
4903 go_error_at(this->location(), "expected %<case%> or %<default%>");
4904 if (!token->is_op(OPERATOR_RCURLY))
4905 this->advance_token();
4906 return NULL;
4910 // The body of a type switch.
4911 // "{" { TypeCaseClause } "}" .
4913 Statement*
4914 Parse::type_switch_body(Label* label, const Type_switch& type_switch,
4915 Location location)
4917 Expression* init = type_switch.expr;
4918 std::string var_name = type_switch.name;
4919 if (!var_name.empty())
4921 if (Gogo::is_sink_name(var_name))
4923 go_error_at(type_switch.location,
4924 "no new variables on left side of %<:=%>");
4925 var_name.clear();
4927 else
4929 Location loc = type_switch.location;
4930 Temporary_statement* switch_temp =
4931 Statement::make_temporary(NULL, init, loc);
4932 this->gogo_->add_statement(switch_temp);
4933 init = Expression::make_temporary_reference(switch_temp, loc);
4937 Type_switch_statement* statement =
4938 Statement::make_type_switch_statement(init, location);
4939 this->push_break_statement(statement, label);
4941 Type_case_clauses* case_clauses = new Type_case_clauses();
4942 bool saw_default = false;
4943 std::vector<Named_object*> implicit_vars;
4944 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4946 if (this->peek_token()->is_eof())
4948 go_error_at(this->location(), "missing %<}%>");
4949 return NULL;
4951 this->type_case_clause(var_name, init, case_clauses, &saw_default,
4952 &implicit_vars);
4954 this->advance_token();
4956 statement->add_clauses(case_clauses);
4958 this->pop_break_statement();
4960 // If there is a type switch variable implicitly declared in each case clause,
4961 // check that it is used in at least one of the cases.
4962 if (!var_name.empty())
4964 bool used = false;
4965 for (std::vector<Named_object*>::iterator p = implicit_vars.begin();
4966 p != implicit_vars.end();
4967 ++p)
4969 if ((*p)->var_value()->is_used())
4971 used = true;
4972 break;
4975 if (!used)
4976 go_error_at(type_switch.location, "%qs declared but not used",
4977 Gogo::message_name(var_name).c_str());
4979 return statement;
4982 // TypeCaseClause = TypeSwitchCase ":" [ StatementList ] .
4983 // IMPLICIT_VARS is the list of variables implicitly declared for each type
4984 // case if there is a type switch variable declared.
4986 void
4987 Parse::type_case_clause(const std::string& var_name, Expression* init,
4988 Type_case_clauses* clauses, bool* saw_default,
4989 std::vector<Named_object*>* implicit_vars)
4991 Location location = this->location();
4993 std::vector<Type*> types;
4994 bool is_default = false;
4995 this->type_switch_case(&types, &is_default);
4997 if (!this->peek_token()->is_op(OPERATOR_COLON))
4998 go_error_at(this->location(), "expected %<:%>");
4999 else
5000 this->advance_token();
5002 Block* statements = NULL;
5003 if (this->statement_list_may_start_here())
5005 this->gogo_->start_block(this->location());
5006 if (!var_name.empty())
5008 Type* type = NULL;
5009 Location var_loc = init->location();
5010 if (types.size() == 1)
5012 type = types.front();
5013 init = Expression::make_type_guard(init, type, location);
5016 Variable* v = new Variable(type, init, false, false, false,
5017 var_loc);
5018 v->set_is_used();
5019 v->set_is_type_switch_var();
5020 implicit_vars->push_back(this->gogo_->add_variable(var_name, v));
5022 this->statement_list();
5023 statements = this->gogo_->finish_block(this->location());
5026 if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
5028 go_error_at(this->location(),
5029 "fallthrough is not permitted in a type switch");
5030 if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
5031 this->advance_token();
5034 if (is_default)
5036 go_assert(types.empty());
5037 if (*saw_default)
5039 go_error_at(location, "multiple defaults in type switch");
5040 return;
5042 *saw_default = true;
5043 clauses->add(NULL, false, true, statements, location);
5045 else if (!types.empty())
5047 for (std::vector<Type*>::const_iterator p = types.begin();
5048 p + 1 != types.end();
5049 ++p)
5050 clauses->add(*p, true, false, NULL, location);
5051 clauses->add(types.back(), false, false, statements, location);
5053 else
5054 clauses->add(Type::make_error_type(), false, false, statements, location);
5057 // TypeSwitchCase = "case" type | "default"
5059 // We accept a comma separated list of types.
5061 void
5062 Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
5064 const Token* token = this->peek_token();
5065 if (token->is_keyword(KEYWORD_CASE))
5067 this->advance_token();
5068 while (true)
5070 Type* t = this->type();
5072 if (!t->is_error_type())
5073 types->push_back(t);
5074 else
5076 this->gogo_->mark_locals_used();
5077 token = this->peek_token();
5078 while (!token->is_op(OPERATOR_COLON)
5079 && !token->is_op(OPERATOR_COMMA)
5080 && !token->is_op(OPERATOR_RCURLY)
5081 && !token->is_eof())
5082 token = this->advance_token();
5085 if (!this->peek_token()->is_op(OPERATOR_COMMA))
5086 break;
5087 this->advance_token();
5090 else if (token->is_keyword(KEYWORD_DEFAULT))
5092 this->advance_token();
5093 *is_default = true;
5095 else
5097 go_error_at(this->location(), "expected %<case%> or %<default%>");
5098 if (!token->is_op(OPERATOR_RCURLY))
5099 this->advance_token();
5103 // SelectStat = "select" "{" { CommClause } "}" .
5105 void
5106 Parse::select_stat(Label* label)
5108 go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
5109 Location location = this->location();
5110 const Token* token = this->advance_token();
5112 if (!token->is_op(OPERATOR_LCURLY))
5114 Location token_loc = token->location();
5115 if (token->is_op(OPERATOR_SEMICOLON)
5116 && this->advance_token()->is_op(OPERATOR_LCURLY))
5117 go_error_at(token_loc, "unexpected semicolon or newline before %<{%>");
5118 else
5120 go_error_at(this->location(), "expected %<{%>");
5121 return;
5124 this->advance_token();
5126 Select_statement* statement = Statement::make_select_statement(location);
5128 this->push_break_statement(statement, label);
5130 Select_clauses* select_clauses = new Select_clauses();
5131 bool saw_default = false;
5132 while (!this->peek_token()->is_op(OPERATOR_RCURLY))
5134 if (this->peek_token()->is_eof())
5136 go_error_at(this->location(), "expected %<}%>");
5137 return;
5139 this->comm_clause(select_clauses, &saw_default);
5142 this->advance_token();
5144 statement->add_clauses(select_clauses);
5146 this->pop_break_statement();
5148 this->gogo_->add_statement(statement);
5151 // CommClause = CommCase ":" { Statement ";" } .
5153 void
5154 Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
5156 Location location = this->location();
5157 bool is_send = false;
5158 Expression* channel = NULL;
5159 Expression* val = NULL;
5160 Expression* closed = NULL;
5161 std::string varname;
5162 std::string closedname;
5163 bool is_default = false;
5164 bool got_case = this->comm_case(&is_send, &channel, &val, &closed,
5165 &varname, &closedname, &is_default);
5167 if (this->peek_token()->is_op(OPERATOR_COLON))
5168 this->advance_token();
5169 else
5170 go_error_at(this->location(), "expected colon");
5172 this->gogo_->start_block(this->location());
5174 Named_object* var = NULL;
5175 if (!varname.empty())
5177 // FIXME: LOCATION is slightly wrong here.
5178 Variable* v = new Variable(NULL, channel, false, false, false,
5179 location);
5180 v->set_type_from_chan_element();
5181 var = this->gogo_->add_variable(varname, v);
5184 Named_object* closedvar = NULL;
5185 if (!closedname.empty())
5187 // FIXME: LOCATION is slightly wrong here.
5188 Variable* v = new Variable(Type::lookup_bool_type(), NULL,
5189 false, false, false, location);
5190 closedvar = this->gogo_->add_variable(closedname, v);
5193 this->statement_list();
5195 Block* statements = this->gogo_->finish_block(this->location());
5197 if (is_default)
5199 if (*saw_default)
5201 go_error_at(location, "multiple defaults in select");
5202 return;
5204 *saw_default = true;
5207 if (got_case)
5208 clauses->add(is_send, channel, val, closed, var, closedvar, is_default,
5209 statements, location);
5210 else if (statements != NULL)
5212 // Add the statements to make sure that any names they define
5213 // are traversed.
5214 this->gogo_->add_block(statements, location);
5218 // CommCase = "case" ( SendStmt | RecvStmt ) | "default" .
5220 bool
5221 Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
5222 Expression** closed, std::string* varname,
5223 std::string* closedname, bool* is_default)
5225 const Token* token = this->peek_token();
5226 if (token->is_keyword(KEYWORD_DEFAULT))
5228 this->advance_token();
5229 *is_default = true;
5231 else if (token->is_keyword(KEYWORD_CASE))
5233 this->advance_token();
5234 if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname,
5235 closedname))
5236 return false;
5238 else
5240 go_error_at(this->location(), "expected %<case%> or %<default%>");
5241 if (!token->is_op(OPERATOR_RCURLY))
5242 this->advance_token();
5243 return false;
5246 return true;
5249 // RecvStmt = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
5250 // RecvExpr = Expression .
5252 bool
5253 Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val,
5254 Expression** closed, std::string* varname,
5255 std::string* closedname)
5257 const Token* token = this->peek_token();
5258 bool saw_comma = false;
5259 bool closed_is_id = false;
5260 if (token->is_identifier())
5262 Gogo* gogo = this->gogo_;
5263 std::string recv_var = token->identifier();
5264 bool is_rv_exported = token->is_identifier_exported();
5265 Location recv_var_loc = token->location();
5266 token = this->advance_token();
5267 if (token->is_op(OPERATOR_COLONEQ))
5269 // case rv := <-c:
5270 this->advance_token();
5271 Expression* e = this->expression(PRECEDENCE_NORMAL, false, false,
5272 NULL, NULL);
5273 Receive_expression* re = e->receive_expression();
5274 if (re == NULL)
5276 if (!e->is_error_expression())
5277 go_error_at(this->location(), "expected receive expression");
5278 return false;
5280 if (recv_var == "_")
5282 go_error_at(recv_var_loc,
5283 "no new variables on left side of %<:=%>");
5284 recv_var = Gogo::erroneous_name();
5286 *is_send = false;
5287 *varname = gogo->pack_hidden_name(recv_var, is_rv_exported);
5288 *channel = re->channel();
5289 return true;
5291 else if (token->is_op(OPERATOR_COMMA))
5293 token = this->advance_token();
5294 if (token->is_identifier())
5296 std::string recv_closed = token->identifier();
5297 bool is_rc_exported = token->is_identifier_exported();
5298 Location recv_closed_loc = token->location();
5299 closed_is_id = true;
5301 token = this->advance_token();
5302 if (token->is_op(OPERATOR_COLONEQ))
5304 // case rv, rc := <-c:
5305 this->advance_token();
5306 Expression* e = this->expression(PRECEDENCE_NORMAL, false,
5307 false, NULL, NULL);
5308 Receive_expression* re = e->receive_expression();
5309 if (re == NULL)
5311 if (!e->is_error_expression())
5312 go_error_at(this->location(),
5313 "expected receive expression");
5314 return false;
5316 if (recv_var == "_" && recv_closed == "_")
5318 go_error_at(recv_var_loc,
5319 "no new variables on left side of %<:=%>");
5320 recv_var = Gogo::erroneous_name();
5322 *is_send = false;
5323 if (recv_var != "_")
5324 *varname = gogo->pack_hidden_name(recv_var,
5325 is_rv_exported);
5326 if (recv_closed != "_")
5327 *closedname = gogo->pack_hidden_name(recv_closed,
5328 is_rc_exported);
5329 *channel = re->channel();
5330 return true;
5333 this->unget_token(Token::make_identifier_token(recv_closed,
5334 is_rc_exported,
5335 recv_closed_loc));
5338 *val = this->id_to_expression(gogo->pack_hidden_name(recv_var,
5339 is_rv_exported),
5340 recv_var_loc, true, false);
5341 saw_comma = true;
5343 else
5344 this->unget_token(Token::make_identifier_token(recv_var,
5345 is_rv_exported,
5346 recv_var_loc));
5349 // If SAW_COMMA is false, then we are looking at the start of the
5350 // send or receive expression. If SAW_COMMA is true, then *VAL is
5351 // set and we just read a comma.
5353 Expression* e;
5354 if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP))
5356 e = this->expression(PRECEDENCE_NORMAL, true, true, NULL, NULL);
5357 if (e->receive_expression() != NULL)
5359 *is_send = false;
5360 *channel = e->receive_expression()->channel();
5361 // This is 'case (<-c):'. We now expect ':'. If we see
5362 // '<-', then we have case (<-c)<-v:
5363 if (!this->peek_token()->is_op(OPERATOR_CHANOP))
5364 return true;
5367 else
5369 // case <-c:
5370 *is_send = false;
5371 this->advance_token();
5372 *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5374 // The next token should be ':'. If it is '<-', then we have
5375 // case <-c <- v:
5376 // which is to say, send on a channel received from a channel.
5377 if (!this->peek_token()->is_op(OPERATOR_CHANOP))
5378 return true;
5380 e = Expression::make_receive(*channel, (*channel)->location());
5383 if (!saw_comma && this->peek_token()->is_op(OPERATOR_COMMA))
5385 this->advance_token();
5386 // case v, e = <-c:
5387 if (!e->is_sink_expression())
5388 *val = e;
5389 e = this->expression(PRECEDENCE_NORMAL, true, true, NULL, NULL);
5390 saw_comma = true;
5393 if (this->peek_token()->is_op(OPERATOR_EQ))
5395 *is_send = false;
5396 this->advance_token();
5397 Location recvloc = this->location();
5398 Expression* recvexpr = this->expression(PRECEDENCE_NORMAL, false,
5399 true, NULL, NULL);
5400 if (recvexpr->receive_expression() == NULL)
5402 go_error_at(recvloc, "missing %<<-%>");
5403 return false;
5405 *channel = recvexpr->receive_expression()->channel();
5406 if (saw_comma)
5408 // case v, e = <-c:
5409 // *VAL is already set.
5410 if (!e->is_sink_expression())
5411 *closed = e;
5413 else
5415 // case v = <-c:
5416 if (!e->is_sink_expression())
5417 *val = e;
5419 return true;
5422 if (saw_comma)
5424 if (closed_is_id)
5425 go_error_at(this->location(), "expected %<=%> or %<:=%>");
5426 else
5427 go_error_at(this->location(), "expected %<=%>");
5428 return false;
5431 if (this->peek_token()->is_op(OPERATOR_CHANOP))
5433 // case c <- v:
5434 *is_send = true;
5435 *channel = this->verify_not_sink(e);
5436 this->advance_token();
5437 *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5438 return true;
5441 go_error_at(this->location(), "expected %<<-%> or %<=%>");
5442 return false;
5445 // ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
5446 // Condition = Expression .
5448 void
5449 Parse::for_stat(Label* label)
5451 go_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
5452 Location location = this->location();
5453 const Token* token = this->advance_token();
5455 // Open a block to hold any variables defined in the init statement
5456 // of the for statement.
5457 this->gogo_->start_block(location);
5459 Block* init = NULL;
5460 Expression* cond = NULL;
5461 Block* post = NULL;
5462 Range_clause range_clause;
5464 if (!token->is_op(OPERATOR_LCURLY))
5466 if (token->is_keyword(KEYWORD_VAR))
5468 go_error_at(this->location(),
5469 "var declaration not allowed in for initializer");
5470 this->var_decl();
5473 if (token->is_op(OPERATOR_SEMICOLON))
5474 this->for_clause(&cond, &post);
5475 else
5477 // We might be looking at a Condition, an InitStat, or a
5478 // RangeClause.
5479 bool saw_send_stmt = false;
5480 cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL);
5481 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5483 if (cond == NULL && !range_clause.found)
5485 if (saw_send_stmt)
5486 go_error_at(this->location(),
5487 ("send statement used as value; "
5488 "use select for non-blocking send"));
5489 else
5490 go_error_at(this->location(),
5491 "parse error in for statement");
5494 else
5496 if (range_clause.found)
5497 go_error_at(this->location(), "parse error after range clause");
5499 if (cond != NULL)
5501 // COND is actually an expression statement for
5502 // InitStat at the start of a ForClause.
5503 this->expression_stat(cond);
5504 cond = NULL;
5507 this->for_clause(&cond, &post);
5512 // Check for the easy error of a newline before starting the block.
5513 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5515 Location semi_loc = this->location();
5516 if (this->advance_token()->is_op(OPERATOR_LCURLY))
5517 go_error_at(semi_loc, "unexpected semicolon or newline, expecting %<{%> after for clause");
5518 // Otherwise we will get an error when we call this->block
5519 // below.
5522 // Build the For_statement and note that it is the current target
5523 // for break and continue statements.
5525 For_statement* sfor;
5526 For_range_statement* srange;
5527 Statement* s;
5528 if (!range_clause.found)
5530 sfor = Statement::make_for_statement(init, cond, post, location);
5531 s = sfor;
5532 srange = NULL;
5534 else
5536 srange = Statement::make_for_range_statement(range_clause.index,
5537 range_clause.value,
5538 range_clause.range,
5539 location);
5540 s = srange;
5541 sfor = NULL;
5544 this->push_break_statement(s, label);
5545 this->push_continue_statement(s, label);
5547 // Gather the block of statements in the loop and add them to the
5548 // For_statement.
5550 this->gogo_->start_block(this->location());
5551 Location end_loc = this->block();
5552 Block* statements = this->gogo_->finish_block(end_loc);
5554 if (sfor != NULL)
5555 sfor->add_statements(statements);
5556 else
5557 srange->add_statements(statements);
5559 // This is no longer the break/continue target.
5560 this->pop_break_statement();
5561 this->pop_continue_statement();
5563 // Add the For_statement to the list of statements, and close out
5564 // the block we started to hold any variables defined in the for
5565 // statement.
5567 this->gogo_->add_statement(s);
5569 this->gogo_->add_block(this->gogo_->finish_block(this->location()),
5570 location);
5573 // ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
5574 // InitStat = SimpleStat .
5575 // PostStat = SimpleStat .
5577 // We have already read InitStat at this point.
5579 void
5580 Parse::for_clause(Expression** cond, Block** post)
5582 go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
5583 this->advance_token();
5584 if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
5585 *cond = NULL;
5586 else if (this->peek_token()->is_op(OPERATOR_LCURLY))
5588 go_error_at(this->location(), "unexpected semicolon or newline, expecting %<{%> after for clause");
5589 *cond = NULL;
5590 *post = NULL;
5591 return;
5593 else
5594 *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL, NULL);
5595 if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
5596 go_error_at(this->location(), "expected semicolon");
5597 else
5598 this->advance_token();
5600 if (this->peek_token()->is_op(OPERATOR_LCURLY))
5601 *post = NULL;
5602 else
5604 this->gogo_->start_block(this->location());
5605 this->simple_stat(false, NULL, NULL, NULL);
5606 *post = this->gogo_->finish_block(this->location());
5610 // RangeClause = [ IdentifierList ( "=" | ":=" ) ] "range" Expression .
5612 // This is the := version. It is called with a list of identifiers.
5614 void
5615 Parse::range_clause_decl(const Typed_identifier_list* til,
5616 Range_clause* p_range_clause)
5618 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5619 Location location = this->location();
5621 p_range_clause->found = true;
5623 if (til->size() > 2)
5624 go_error_at(this->location(), "too many variables for range clause");
5626 this->advance_token();
5627 Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL,
5628 NULL);
5629 p_range_clause->range = expr;
5631 if (til->empty())
5632 return;
5634 bool any_new = false;
5636 const Typed_identifier* pti = &til->front();
5637 Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new,
5638 NULL, NULL);
5639 if (any_new && no->is_variable())
5640 no->var_value()->set_type_from_range_index();
5641 p_range_clause->index = Expression::make_var_reference(no, location);
5643 if (til->size() == 1)
5644 p_range_clause->value = NULL;
5645 else
5647 pti = &til->back();
5648 bool is_new = false;
5649 no = this->init_var(*pti, NULL, expr, true, true, &is_new, NULL, NULL);
5650 if (is_new && no->is_variable())
5651 no->var_value()->set_type_from_range_value();
5652 if (is_new)
5653 any_new = true;
5654 p_range_clause->value = Expression::make_var_reference(no, location);
5657 if (!any_new)
5658 go_error_at(location, "variables redeclared but no variable is new");
5661 // The = version of RangeClause. This is called with a list of
5662 // expressions.
5664 void
5665 Parse::range_clause_expr(const Expression_list* vals,
5666 Range_clause* p_range_clause)
5668 go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5670 p_range_clause->found = true;
5672 go_assert(vals->size() >= 1);
5673 if (vals->size() > 2)
5674 go_error_at(this->location(), "too many variables for range clause");
5676 this->advance_token();
5677 p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
5678 NULL, NULL);
5680 if (vals->empty())
5681 return;
5683 p_range_clause->index = vals->front();
5684 if (vals->size() == 1)
5685 p_range_clause->value = NULL;
5686 else
5687 p_range_clause->value = vals->back();
5690 // Push a statement on the break stack.
5692 void
5693 Parse::push_break_statement(Statement* enclosing, Label* label)
5695 if (this->break_stack_ == NULL)
5696 this->break_stack_ = new Bc_stack();
5697 this->break_stack_->push_back(std::make_pair(enclosing, label));
5700 // Push a statement on the continue stack.
5702 void
5703 Parse::push_continue_statement(Statement* enclosing, Label* label)
5705 if (this->continue_stack_ == NULL)
5706 this->continue_stack_ = new Bc_stack();
5707 this->continue_stack_->push_back(std::make_pair(enclosing, label));
5710 // Pop the break stack.
5712 void
5713 Parse::pop_break_statement()
5715 this->break_stack_->pop_back();
5718 // Pop the continue stack.
5720 void
5721 Parse::pop_continue_statement()
5723 this->continue_stack_->pop_back();
5726 // Find a break or continue statement given a label name.
5728 Statement*
5729 Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
5731 if (bc_stack == NULL)
5732 return NULL;
5733 for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
5734 p != bc_stack->rend();
5735 ++p)
5737 if (p->second != NULL && p->second->name() == label)
5739 p->second->set_is_used();
5740 return p->first;
5743 return NULL;
5746 // BreakStat = "break" [ identifier ] .
5748 void
5749 Parse::break_stat()
5751 go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
5752 Location location = this->location();
5754 const Token* token = this->advance_token();
5755 Statement* enclosing;
5756 if (!token->is_identifier())
5758 if (this->break_stack_ == NULL || this->break_stack_->empty())
5760 go_error_at(this->location(),
5761 "break statement not within for or switch or select");
5762 return;
5764 enclosing = this->break_stack_->back().first;
5766 else
5768 enclosing = this->find_bc_statement(this->break_stack_,
5769 token->identifier());
5770 if (enclosing == NULL)
5772 // If there is a label with this name, mark it as used to
5773 // avoid a useless error about an unused label.
5774 this->gogo_->add_label_reference(token->identifier(),
5775 Linemap::unknown_location(), false);
5777 go_error_at(token->location(), "invalid break label %qs",
5778 Gogo::message_name(token->identifier()).c_str());
5779 this->advance_token();
5780 return;
5782 this->advance_token();
5785 Unnamed_label* label;
5786 if (enclosing->classification() == Statement::STATEMENT_FOR)
5787 label = enclosing->for_statement()->break_label();
5788 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5789 label = enclosing->for_range_statement()->break_label();
5790 else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
5791 label = enclosing->switch_statement()->break_label();
5792 else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
5793 label = enclosing->type_switch_statement()->break_label();
5794 else if (enclosing->classification() == Statement::STATEMENT_SELECT)
5795 label = enclosing->select_statement()->break_label();
5796 else
5797 go_unreachable();
5799 this->gogo_->add_statement(Statement::make_break_statement(label,
5800 location));
5803 // ContinueStat = "continue" [ identifier ] .
5805 void
5806 Parse::continue_stat()
5808 go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
5809 Location location = this->location();
5811 const Token* token = this->advance_token();
5812 Statement* enclosing;
5813 if (!token->is_identifier())
5815 if (this->continue_stack_ == NULL || this->continue_stack_->empty())
5817 go_error_at(this->location(), "continue statement not within for");
5818 return;
5820 enclosing = this->continue_stack_->back().first;
5822 else
5824 enclosing = this->find_bc_statement(this->continue_stack_,
5825 token->identifier());
5826 if (enclosing == NULL)
5828 // If there is a label with this name, mark it as used to
5829 // avoid a useless error about an unused label.
5830 this->gogo_->add_label_reference(token->identifier(),
5831 Linemap::unknown_location(), false);
5833 go_error_at(token->location(), "invalid continue label %qs",
5834 Gogo::message_name(token->identifier()).c_str());
5835 this->advance_token();
5836 return;
5838 this->advance_token();
5841 Unnamed_label* label;
5842 if (enclosing->classification() == Statement::STATEMENT_FOR)
5843 label = enclosing->for_statement()->continue_label();
5844 else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5845 label = enclosing->for_range_statement()->continue_label();
5846 else
5847 go_unreachable();
5849 this->gogo_->add_statement(Statement::make_continue_statement(label,
5850 location));
5853 // GotoStat = "goto" identifier .
5855 void
5856 Parse::goto_stat()
5858 go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
5859 Location location = this->location();
5860 const Token* token = this->advance_token();
5861 if (!token->is_identifier())
5862 go_error_at(this->location(), "expected label for goto");
5863 else
5865 Label* label = this->gogo_->add_label_reference(token->identifier(),
5866 location, true);
5867 Statement* s = Statement::make_goto_statement(label, location);
5868 this->gogo_->add_statement(s);
5869 this->advance_token();
5873 // PackageClause = "package" PackageName .
5875 void
5876 Parse::package_clause()
5878 const Token* token = this->peek_token();
5879 Location location = token->location();
5880 std::string name;
5881 if (!token->is_keyword(KEYWORD_PACKAGE))
5883 go_error_at(this->location(), "program must start with package clause");
5884 name = "ERROR";
5886 else
5888 token = this->advance_token();
5889 if (token->is_identifier())
5891 name = token->identifier();
5892 if (name == "_")
5894 go_error_at(this->location(), "invalid package name %<_%>");
5895 name = Gogo::erroneous_name();
5897 this->advance_token();
5899 else
5901 go_error_at(this->location(), "package name must be an identifier");
5902 name = "ERROR";
5905 this->gogo_->set_package_name(name, location);
5908 // ImportDecl = "import" Decl<ImportSpec> .
5910 void
5911 Parse::import_decl()
5913 go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
5914 this->advance_token();
5915 this->decl(&Parse::import_spec);
5918 // ImportSpec = [ "." | PackageName ] PackageFileName .
5920 void
5921 Parse::import_spec()
5923 this->check_directives();
5925 const Token* token = this->peek_token();
5926 Location location = token->location();
5928 std::string local_name;
5929 bool is_local_name_exported = false;
5930 if (token->is_op(OPERATOR_DOT))
5932 local_name = ".";
5933 token = this->advance_token();
5935 else if (token->is_identifier())
5937 local_name = token->identifier();
5938 is_local_name_exported = token->is_identifier_exported();
5939 token = this->advance_token();
5942 if (!token->is_string())
5944 go_error_at(this->location(), "import path must be a string");
5945 this->advance_token();
5946 return;
5949 this->gogo_->import_package(token->string_value(), local_name,
5950 is_local_name_exported, true, location);
5952 this->advance_token();
5955 // SourceFile = PackageClause ";" { ImportDecl ";" }
5956 // { TopLevelDecl ";" } .
5958 void
5959 Parse::program()
5961 this->package_clause();
5963 const Token* token = this->peek_token();
5964 if (token->is_op(OPERATOR_SEMICOLON))
5965 token = this->advance_token();
5966 else
5967 go_error_at(this->location(),
5968 "expected %<;%> or newline after package clause");
5970 while (token->is_keyword(KEYWORD_IMPORT))
5972 this->import_decl();
5973 token = this->peek_token();
5974 if (token->is_op(OPERATOR_SEMICOLON))
5975 token = this->advance_token();
5976 else
5977 go_error_at(this->location(),
5978 "expected %<;%> or newline after import declaration");
5981 while (!token->is_eof())
5983 if (this->declaration_may_start_here())
5984 this->declaration();
5985 else
5987 go_error_at(this->location(), "expected declaration");
5988 this->gogo_->mark_locals_used();
5990 this->advance_token();
5991 while (!this->peek_token()->is_eof()
5992 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
5993 && !this->peek_token()->is_op(OPERATOR_RCURLY));
5994 if (!this->peek_token()->is_eof()
5995 && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
5996 this->advance_token();
5998 token = this->peek_token();
5999 if (token->is_op(OPERATOR_SEMICOLON))
6000 token = this->advance_token();
6001 else if (!token->is_eof() || !saw_errors())
6003 if (token->is_op(OPERATOR_CHANOP))
6004 go_error_at(this->location(),
6005 ("send statement used as value; "
6006 "use select for non-blocking send"));
6007 else
6008 go_error_at(this->location(),
6009 ("expected %<;%> or newline after top "
6010 "level declaration"));
6011 this->skip_past_error(OPERATOR_INVALID);
6015 this->check_directives();
6018 // If there are any pending compiler directives, clear them and give
6019 // an error. This is called when directives are not permitted.
6021 void
6022 Parse::check_directives()
6024 if (this->lex_->get_and_clear_pragmas() != 0)
6025 go_error_at(this->location(), "misplaced compiler directive");
6026 if (this->lex_->has_embeds())
6028 this->lex_->clear_embeds();
6029 go_error_at(this->location(), "misplaced go:embed directive");
6033 // Skip forward to a semicolon or OP. OP will normally be
6034 // OPERATOR_RPAREN or OPERATOR_RCURLY. If we find a semicolon, move
6035 // past it and return. If we find OP, it will be the next token to
6036 // read. Return true if we are OK, false if we found EOF.
6038 bool
6039 Parse::skip_past_error(Operator op)
6041 this->gogo_->mark_locals_used();
6042 const Token* token = this->peek_token();
6043 while (!token->is_op(op))
6045 if (token->is_eof())
6046 return false;
6047 if (token->is_op(OPERATOR_SEMICOLON))
6049 this->advance_token();
6050 return true;
6052 token = this->advance_token();
6054 return true;
6057 // Check that an expression is not a sink.
6059 Expression*
6060 Parse::verify_not_sink(Expression* expr)
6062 if (expr->is_sink_expression())
6064 go_error_at(expr->location(), "cannot use %<_%> as value");
6065 expr = Expression::make_error(expr->location());
6068 // If this can not be a sink, and it is a variable, then we are
6069 // using the variable, not just assigning to it.
6070 if (expr->var_expression() != NULL)
6071 this->mark_var_used(expr->var_expression()->named_object());
6072 else if (expr->enclosed_var_expression() != NULL)
6073 this->mark_var_used(expr->enclosed_var_expression()->variable());
6074 return expr;
6077 // Mark a variable as used.
6079 void
6080 Parse::mark_var_used(Named_object* no)
6082 if (no->is_variable())
6083 no->var_value()->set_is_used();