blob: 8c42fa2b24f3d9a731368bee00e8e4686b7e282e [file] [log] [blame]
// parse.cc -- Go frontend parser.
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "go-system.h"
#include "lex.h"
#include "gogo.h"
#include "types.h"
#include "statements.h"
#include "expressions.h"
#include "parse.h"
// Struct Parse::Enclosing_var_comparison.
// Return true if v1 should be considered to be less than v2.
bool
Parse::Enclosing_var_comparison::operator()(const Enclosing_var& v1,
const Enclosing_var& v2)
{
if (v1.var() == v2.var())
return false;
const std::string& n1(v1.var()->name());
const std::string& n2(v2.var()->name());
int i = n1.compare(n2);
if (i < 0)
return true;
else if (i > 0)
return false;
// If we get here it means that a single nested function refers to
// two different variables defined in enclosing functions, and both
// variables have the same name. I think this is impossible.
go_unreachable();
}
// Class Parse.
Parse::Parse(Lex* lex, Gogo* gogo)
: lex_(lex),
token_(Token::make_invalid_token(0)),
unget_token_(Token::make_invalid_token(0)),
unget_token_valid_(false),
gogo_(gogo),
break_stack_(NULL),
continue_stack_(NULL),
iota_(0),
enclosing_vars_()
{
}
// Return the current token.
const Token*
Parse::peek_token()
{
if (this->unget_token_valid_)
return &this->unget_token_;
if (this->token_.is_invalid())
this->token_ = this->lex_->next_token();
return &this->token_;
}
// Advance to the next token and return it.
const Token*
Parse::advance_token()
{
if (this->unget_token_valid_)
{
this->unget_token_valid_ = false;
if (!this->token_.is_invalid())
return &this->token_;
}
this->token_ = this->lex_->next_token();
return &this->token_;
}
// Push a token back on the input stream.
void
Parse::unget_token(const Token& token)
{
go_assert(!this->unget_token_valid_);
this->unget_token_ = token;
this->unget_token_valid_ = true;
}
// The location of the current token.
source_location
Parse::location()
{
return this->peek_token()->location();
}
// IdentifierList = identifier { "," identifier } .
void
Parse::identifier_list(Typed_identifier_list* til)
{
const Token* token = this->peek_token();
while (true)
{
if (!token->is_identifier())
{
error_at(this->location(), "expected identifier");
return;
}
std::string name =
this->gogo_->pack_hidden_name(token->identifier(),
token->is_identifier_exported());
til->push_back(Typed_identifier(name, NULL, token->location()));
token = this->advance_token();
if (!token->is_op(OPERATOR_COMMA))
return;
token = this->advance_token();
}
}
// ExpressionList = Expression { "," Expression } .
// If MAY_BE_SINK is true, the expressions in the list may be "_".
Expression_list*
Parse::expression_list(Expression* first, bool may_be_sink)
{
Expression_list* ret = new Expression_list();
if (first != NULL)
ret->push_back(first);
while (true)
{
ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink, true,
NULL));
const Token* token = this->peek_token();
if (!token->is_op(OPERATOR_COMMA))
return ret;
// Most expression lists permit a trailing comma.
source_location location = token->location();
this->advance_token();
if (!this->expression_may_start_here())
{
this->unget_token(Token::make_operator_token(OPERATOR_COMMA,
location));
return ret;
}
}
}
// QualifiedIdent = [ PackageName "." ] identifier .
// PackageName = identifier .
// This sets *PNAME to the identifier and sets *PPACKAGE to the
// package or NULL if there isn't one. This returns true on success,
// false on failure in which case it will have emitted an error
// message.
bool
Parse::qualified_ident(std::string* pname, Named_object** ppackage)
{
const Token* token = this->peek_token();
if (!token->is_identifier())
{
error_at(this->location(), "expected identifier");
return false;
}
std::string name = token->identifier();
bool is_exported = token->is_identifier_exported();
name = this->gogo_->pack_hidden_name(name, is_exported);
token = this->advance_token();
if (!token->is_op(OPERATOR_DOT))
{
*pname = name;
*ppackage = NULL;
return true;
}
Named_object* package = this->gogo_->lookup(name, NULL);
if (package == NULL || !package->is_package())
{
error_at(this->location(), "expected package");
// We expect . IDENTIFIER; skip both.
if (this->advance_token()->is_identifier())
this->advance_token();
return false;
}
package->package_value()->set_used();
token = this->advance_token();
if (!token->is_identifier())
{
error_at(this->location(), "expected identifier");
return false;
}
name = token->identifier();
if (name == "_")
{
error_at(this->location(), "invalid use of %<_%>");
name = "blank";
}
if (package->name() == this->gogo_->package_name())
name = this->gogo_->pack_hidden_name(name,
token->is_identifier_exported());
*pname = name;
*ppackage = package;
this->advance_token();
return true;
}
// Type = TypeName | TypeLit | "(" Type ")" .
// TypeLit =
// ArrayType | StructType | PointerType | FunctionType | InterfaceType |
// SliceType | MapType | ChannelType .
Type*
Parse::type()
{
const Token* token = this->peek_token();
if (token->is_identifier())
return this->type_name(true);
else if (token->is_op(OPERATOR_LSQUARE))
return this->array_type(false);
else if (token->is_keyword(KEYWORD_CHAN)
|| token->is_op(OPERATOR_CHANOP))
return this->channel_type();
else if (token->is_keyword(KEYWORD_INTERFACE))
return this->interface_type();
else if (token->is_keyword(KEYWORD_FUNC))
{
source_location location = token->location();
this->advance_token();
Type* type = this->signature(NULL, location);
if (type == NULL)
return Type::make_error_type();
return type;
}
else if (token->is_keyword(KEYWORD_MAP))
return this->map_type();
else if (token->is_keyword(KEYWORD_STRUCT))
return this->struct_type();
else if (token->is_op(OPERATOR_MULT))
return this->pointer_type();
else if (token->is_op(OPERATOR_LPAREN))
{
this->advance_token();
Type* ret = this->type();
if (this->peek_token()->is_op(OPERATOR_RPAREN))
this->advance_token();
else
{
if (!ret->is_error_type())
error_at(this->location(), "expected %<)%>");
}
return ret;
}
else
{
error_at(token->location(), "expected type");
return Type::make_error_type();
}
}
bool
Parse::type_may_start_here()
{
const Token* token = this->peek_token();
return (token->is_identifier()
|| token->is_op(OPERATOR_LSQUARE)
|| token->is_op(OPERATOR_CHANOP)
|| token->is_keyword(KEYWORD_CHAN)
|| token->is_keyword(KEYWORD_INTERFACE)
|| token->is_keyword(KEYWORD_FUNC)
|| token->is_keyword(KEYWORD_MAP)
|| token->is_keyword(KEYWORD_STRUCT)
|| token->is_op(OPERATOR_MULT)
|| token->is_op(OPERATOR_LPAREN));
}
// TypeName = QualifiedIdent .
// If MAY_BE_NIL is true, then an identifier with the value of the
// predefined constant nil is accepted, returning the nil type.
Type*
Parse::type_name(bool issue_error)
{
source_location location = this->location();
std::string name;
Named_object* package;
if (!this->qualified_ident(&name, &package))
return Type::make_error_type();
Named_object* named_object;
if (package == NULL)
named_object = this->gogo_->lookup(name, NULL);
else
{
named_object = package->package_value()->lookup(name);
if (named_object == NULL
&& issue_error
&& package->name() != this->gogo_->package_name())
{
// Check whether the name is there but hidden.
std::string s = ('.' + package->package_value()->unique_prefix()
+ '.' + package->package_value()->name()
+ '.' + name);
named_object = package->package_value()->lookup(s);
if (named_object != NULL)
{
const std::string& packname(package->package_value()->name());
error_at(location, "invalid reference to hidden type %<%s.%s%>",
Gogo::message_name(packname).c_str(),
Gogo::message_name(name).c_str());
issue_error = false;
}
}
}
bool ok = true;
if (named_object == NULL)
{
if (package == NULL)
named_object = this->gogo_->add_unknown_name(name, location);
else
{
const std::string& packname(package->package_value()->name());
error_at(location, "reference to undefined identifier %<%s.%s%>",
Gogo::message_name(packname).c_str(),
Gogo::message_name(name).c_str());
issue_error = false;
ok = false;
}
}
else if (named_object->is_type())
{
if (!named_object->type_value()->is_visible())
ok = false;
}
else if (named_object->is_unknown() || named_object->is_type_declaration())
;
else
ok = false;
if (!ok)
{
if (issue_error)
error_at(location, "expected type");
return Type::make_error_type();
}
if (named_object->is_type())
return named_object->type_value();
else if (named_object->is_unknown() || named_object->is_type_declaration())
return Type::make_forward_declaration(named_object);
else
go_unreachable();
}
// ArrayType = "[" [ ArrayLength ] "]" ElementType .
// ArrayLength = Expression .
// ElementType = CompleteType .
Type*
Parse::array_type(bool may_use_ellipsis)
{
go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
const Token* token = this->advance_token();
Expression* length = NULL;
if (token->is_op(OPERATOR_RSQUARE))
this->advance_token();
else
{
if (!token->is_op(OPERATOR_ELLIPSIS))
length = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
else if (may_use_ellipsis)
{
// An ellipsis is used in composite literals to represent a
// fixed array of the size of the number of elements. We
// use a length of nil to represent this, and change the
// length when parsing the composite literal.
length = Expression::make_nil(this->location());
this->advance_token();
}
else
{
error_at(this->location(),
"use of %<[...]%> outside of array literal");
length = Expression::make_error(this->location());
this->advance_token();
}
if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
{
error_at(this->location(), "expected %<]%>");
return Type::make_error_type();
}
this->advance_token();
}
Type* element_type = this->type();
return Type::make_array_type(element_type, length);
}
// MapType = "map" "[" KeyType "]" ValueType .
// KeyType = CompleteType .
// ValueType = CompleteType .
Type*
Parse::map_type()
{
source_location location = this->location();
go_assert(this->peek_token()->is_keyword(KEYWORD_MAP));
if (!this->advance_token()->is_op(OPERATOR_LSQUARE))
{
error_at(this->location(), "expected %<[%>");
return Type::make_error_type();
}
this->advance_token();
Type* key_type = this->type();
if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
{
error_at(this->location(), "expected %<]%>");
return Type::make_error_type();
}
this->advance_token();
Type* value_type = this->type();
if (key_type->is_error_type() || value_type->is_error_type())
return Type::make_error_type();
return Type::make_map_type(key_type, value_type, location);
}
// StructType = "struct" "{" { FieldDecl ";" } "}" .
Type*
Parse::struct_type()
{
go_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT));
source_location location = this->location();
if (!this->advance_token()->is_op(OPERATOR_LCURLY))
{
source_location token_loc = this->location();
if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
&& this->advance_token()->is_op(OPERATOR_LCURLY))
error_at(token_loc, "unexpected semicolon or newline before %<{%>");
else
{
error_at(this->location(), "expected %<{%>");
return Type::make_error_type();
}
}
this->advance_token();
Struct_field_list* sfl = new Struct_field_list;
while (!this->peek_token()->is_op(OPERATOR_RCURLY))
{
this->field_decl(sfl);
if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
this->advance_token();
else if (!this->peek_token()->is_op(OPERATOR_RCURLY))
{
error_at(this->location(), "expected %<;%> or %<}%> or newline");
if (!this->skip_past_error(OPERATOR_RCURLY))
return Type::make_error_type();
}
}
this->advance_token();
for (Struct_field_list::const_iterator pi = sfl->begin();
pi != sfl->end();
++pi)
{
if (pi->type()->is_error_type())
return pi->type();
for (Struct_field_list::const_iterator pj = pi + 1;
pj != sfl->end();
++pj)
{
if (pi->field_name() == pj->field_name()
&& !Gogo::is_sink_name(pi->field_name()))
error_at(pi->location(), "duplicate field name %<%s%>",
Gogo::message_name(pi->field_name()).c_str());
}
}
return Type::make_struct_type(sfl, location);
}
// FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] .
// Tag = string_lit .
void
Parse::field_decl(Struct_field_list* sfl)
{
const Token* token = this->peek_token();
source_location location = token->location();
bool is_anonymous;
bool is_anonymous_pointer;
if (token->is_op(OPERATOR_MULT))
{
is_anonymous = true;
is_anonymous_pointer = true;
}
else if (token->is_identifier())
{
std::string id = token->identifier();
bool is_id_exported = token->is_identifier_exported();
source_location id_location = token->location();
token = this->advance_token();
is_anonymous = (token->is_op(OPERATOR_SEMICOLON)
|| token->is_op(OPERATOR_RCURLY)
|| token->is_op(OPERATOR_DOT)
|| token->is_string());
is_anonymous_pointer = false;
this->unget_token(Token::make_identifier_token(id, is_id_exported,
id_location));
}
else
{
error_at(this->location(), "expected field name");
while (!token->is_op(OPERATOR_SEMICOLON)
&& !token->is_op(OPERATOR_RCURLY)
&& !token->is_eof())
token = this->advance_token();
return;
}
if (is_anonymous)
{
if (is_anonymous_pointer)
{
this->advance_token();
if (!this->peek_token()->is_identifier())
{
error_at(this->location(), "expected field name");
while (!token->is_op(OPERATOR_SEMICOLON)
&& !token->is_op(OPERATOR_RCURLY)
&& !token->is_eof())
token = this->advance_token();
return;
}
}
Type* type = this->type_name(true);
std::string tag;
if (this->peek_token()->is_string())
{
tag = this->peek_token()->string_value();
this->advance_token();
}
if (!type->is_error_type())
{
if (is_anonymous_pointer)
type = Type::make_pointer_type(type);
sfl->push_back(Struct_field(Typed_identifier("", type, location)));
if (!tag.empty())
sfl->back().set_tag(tag);
}
}
else
{
Typed_identifier_list til;
while (true)
{
token = this->peek_token();
if (!token->is_identifier())
{
error_at(this->location(), "expected identifier");
return;
}
std::string name =
this->gogo_->pack_hidden_name(token->identifier(),
token->is_identifier_exported());
til.push_back(Typed_identifier(name, NULL, token->location()));
if (!this->advance_token()->is_op(OPERATOR_COMMA))
break;
this->advance_token();
}
Type* type = this->type();
std::string tag;
if (this->peek_token()->is_string())
{
tag = this->peek_token()->string_value();
this->advance_token();
}
for (Typed_identifier_list::iterator p = til.begin();
p != til.end();
++p)
{
p->set_type(type);
sfl->push_back(Struct_field(*p));
if (!tag.empty())
sfl->back().set_tag(tag);
}
}
}
// PointerType = "*" Type .
Type*
Parse::pointer_type()
{
go_assert(this->peek_token()->is_op(OPERATOR_MULT));
this->advance_token();
Type* type = this->type();
if (type->is_error_type())
return type;
return Type::make_pointer_type(type);
}
// ChannelType = Channel | SendChannel | RecvChannel .
// Channel = "chan" ElementType .
// SendChannel = "chan" "<-" ElementType .
// RecvChannel = "<-" "chan" ElementType .
Type*
Parse::channel_type()
{
const Token* token = this->peek_token();
bool send = true;
bool receive = true;
if (token->is_op(OPERATOR_CHANOP))
{
if (!this->advance_token()->is_keyword(KEYWORD_CHAN))
{
error_at(this->location(), "expected %<chan%>");
return Type::make_error_type();
}
send = false;
this->advance_token();
}
else
{
go_assert(token->is_keyword(KEYWORD_CHAN));
if (this->advance_token()->is_op(OPERATOR_CHANOP))
{
receive = false;
this->advance_token();
}
}
// Better error messages for the common error of omitting the
// channel element type.
if (!this->type_may_start_here())
{
token = this->peek_token();
if (token->is_op(OPERATOR_RCURLY))
error_at(this->location(), "unexpected %<}%> in channel type");
else if (token->is_op(OPERATOR_RPAREN))
error_at(this->location(), "unexpected %<)%> in channel type");
else if (token->is_op(OPERATOR_COMMA))
error_at(this->location(), "unexpected comma in channel type");
else
error_at(this->location(), "expected channel element type");
return Type::make_error_type();
}
Type* element_type = this->type();
return Type::make_channel_type(send, receive, element_type);
}
// Give an error for a duplicate parameter or receiver name.
void
Parse::check_signature_names(const Typed_identifier_list* params,
Parse::Names* names)
{
for (Typed_identifier_list::const_iterator p = params->begin();
p != params->end();
++p)
{
if (p->name().empty() || Gogo::is_sink_name(p->name()))
continue;
std::pair<std::string, const Typed_identifier*> val =
std::make_pair(p->name(), &*p);
std::pair<Parse::Names::iterator, bool> ins = names->insert(val);
if (!ins.second)
{
error_at(p->location(), "redefinition of %qs",
Gogo::message_name(p->name()).c_str());
inform(ins.first->second->location(),
"previous definition of %qs was here",
Gogo::message_name(p->name()).c_str());
}
}
}
// Signature = Parameters [ Result ] .
// RECEIVER is the receiver if there is one, or NULL. LOCATION is the
// location of the start of the type.
// This returns NULL on a parse error.
Function_type*
Parse::signature(Typed_identifier* receiver, source_location location)
{
bool is_varargs = false;
Typed_identifier_list* params;
bool params_ok = this->parameters(&params, &is_varargs);
Typed_identifier_list* results = NULL;
if (this->peek_token()->is_op(OPERATOR_LPAREN)
|| this->type_may_start_here())
{
if (!this->result(&results))
return NULL;
}
if (!params_ok)
return NULL;
Parse::Names names;
if (params != NULL)
this->check_signature_names(params, &names);
if (results != NULL)
this->check_signature_names(results, &names);
Function_type* ret = Type::make_function_type(receiver, params, results,
location);
if (is_varargs)
ret->set_is_varargs();
return ret;
}
// Parameters = "(" [ ParameterList [ "," ] ] ")" .
// This returns false on a parse error.
bool
Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs)
{
*pparams = NULL;
if (!this->peek_token()->is_op(OPERATOR_LPAREN))
{
error_at(this->location(), "expected %<(%>");
return false;
}
Typed_identifier_list* params = NULL;
bool saw_error = false;
const Token* token = this->advance_token();
if (!token->is_op(OPERATOR_RPAREN))
{
params = this->parameter_list(is_varargs);
if (params == NULL)
saw_error = true;
token = this->peek_token();
}
// The optional trailing comma is picked up in parameter_list.
if (!token->is_op(OPERATOR_RPAREN))
error_at(this->location(), "expected %<)%>");
else
this->advance_token();
if (saw_error)
return false;
*pparams = params;
return true;
}
// ParameterList = ParameterDecl { "," ParameterDecl } .
// This sets *IS_VARARGS if the list ends with an ellipsis.
// IS_VARARGS will be NULL if varargs are not permitted.
// We pick up an optional trailing comma.
// This returns NULL if some error is seen.
Typed_identifier_list*
Parse::parameter_list(bool* is_varargs)
{
source_location location = this->location();
Typed_identifier_list* ret = new Typed_identifier_list();
bool saw_error = false;
// If we see an identifier and then a comma, then we don't know
// whether we are looking at a list of identifiers followed by a
// type, or a list of types given by name. We have to do an
// arbitrary lookahead to figure it out.
bool parameters_have_names;
const Token* token = this->peek_token();
if (!token->is_identifier())
{
// This must be a type which starts with something like '*'.
parameters_have_names = false;
}
else
{
std::string name = token->identifier();
bool is_exported = token->is_identifier_exported();
source_location location = token->location();
token = this->advance_token();
if (!token->is_op(OPERATOR_COMMA))
{
if (token->is_op(OPERATOR_DOT))
{
// This is a qualified identifier, which must turn out
// to be a type.
parameters_have_names = false;
}
else if (token->is_op(OPERATOR_RPAREN))
{
// A single identifier followed by a parenthesis must be
// a type name.
parameters_have_names = false;
}
else
{
// An identifier followed by something other than a
// comma or a dot or a right parenthesis must be a
// parameter name followed by a type.
parameters_have_names = true;
}
this->unget_token(Token::make_identifier_token(name, is_exported,
location));
}
else
{
// An identifier followed by a comma may be the first in a
// list of parameter names followed by a type, or it may be
// the first in a list of types without parameter names. To
// find out we gather as many identifiers separated by
// commas as we can.
std::string id_name = this->gogo_->pack_hidden_name(name,
is_exported);
ret->push_back(Typed_identifier(id_name, NULL, location));
bool just_saw_comma = true;
while (this->advance_token()->is_identifier())
{
name = this->peek_token()->identifier();
is_exported = this->peek_token()->is_identifier_exported();
location = this->peek_token()->location();
id_name = this->gogo_->pack_hidden_name(name, is_exported);
ret->push_back(Typed_identifier(id_name, NULL, location));
if (!this->advance_token()->is_op(OPERATOR_COMMA))
{
just_saw_comma = false;
break;
}
}
if (just_saw_comma)
{
// We saw ID1 "," ID2 "," followed by something which
// was not an identifier. We must be seeing the start
// of a type, and ID1 and ID2 must be types, and the
// parameters don't have names.
parameters_have_names = false;
}
else if (this->peek_token()->is_op(OPERATOR_RPAREN))
{
// We saw ID1 "," ID2 ")". ID1 and ID2 must be types,
// and the parameters don't have names.
parameters_have_names = false;
}
else if (this->peek_token()->is_op(OPERATOR_DOT))
{
// We saw ID1 "," ID2 ".". ID2 must be a package name,
// ID1 must be a type, and the parameters don't have
// names.
parameters_have_names = false;
this->unget_token(Token::make_identifier_token(name, is_exported,
location));
ret->pop_back();
just_saw_comma = true;
}
else
{
// We saw ID1 "," ID2 followed by something other than
// ",", ".", or ")". We must be looking at the start of
// a type, and ID1 and ID2 must be parameter names.
parameters_have_names = true;
}
if (parameters_have_names)
{
go_assert(!just_saw_comma);
// We have just seen ID1, ID2 xxx.
Type* type;
if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
type = this->type();
else
{
error_at(this->location(), "%<...%> only permits one name");
saw_error = true;
this->advance_token();
type = this->type();
}
for (size_t i = 0; i < ret->size(); ++i)
ret->set_type(i, type);
if (!this->peek_token()->is_op(OPERATOR_COMMA))
return saw_error ? NULL : ret;
if (this->advance_token()->is_op(OPERATOR_RPAREN))
return saw_error ? NULL : ret;
}
else
{
Typed_identifier_list* tret = new Typed_identifier_list();
for (Typed_identifier_list::const_iterator p = ret->begin();
p != ret->end();
++p)
{
Named_object* no = this->gogo_->lookup(p->name(), NULL);
Type* type;
if (no == NULL)
no = this->gogo_->add_unknown_name(p->name(),
p->location());
if (no->is_type())
type = no->type_value();
else if (no->is_unknown() || no->is_type_declaration())
type = Type::make_forward_declaration(no);
else
{
error_at(p->location(), "expected %<%s%> to be a type",
Gogo::message_name(p->name()).c_str());
saw_error = true;
type = Type::make_error_type();
}
tret->push_back(Typed_identifier("", type, p->location()));
}
delete ret;
ret = tret;
if (!just_saw_comma
|| this->peek_token()->is_op(OPERATOR_RPAREN))
return saw_error ? NULL : ret;
}
}
}
bool mix_error = false;
this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
while (this->peek_token()->is_op(OPERATOR_COMMA))
{
if (is_varargs != NULL && *is_varargs)
{
error_at(this->location(), "%<...%> must be last parameter");
saw_error = true;
}
if (this->advance_token()->is_op(OPERATOR_RPAREN))
break;
this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
}
if (mix_error)
{
error_at(location, "invalid named/anonymous mix");
saw_error = true;
}
if (saw_error)
{
delete ret;
return NULL;
}
return ret;
}
// ParameterDecl = [ IdentifierList ] [ "..." ] Type .
void
Parse::parameter_decl(bool parameters_have_names,
Typed_identifier_list* til,
bool* is_varargs,
bool* mix_error)
{
if (!parameters_have_names)
{
Type* type;
source_location location = this->location();
if (!this->peek_token()->is_identifier())
{
if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
type = this->type();
else
{
if (is_varargs == NULL)
error_at(this->location(), "invalid use of %<...%>");
else
*is_varargs = true;
this->advance_token();
if (is_varargs == NULL
&& this->peek_token()->is_op(OPERATOR_RPAREN))
type = Type::make_error_type();
else
{
Type* element_type = this->type();
type = Type::make_array_type(element_type, NULL);
}
}
}
else
{
type = this->type_name(false);
if (type->is_error_type()
|| (!this->peek_token()->is_op(OPERATOR_COMMA)
&& !this->peek_token()->is_op(OPERATOR_RPAREN)))
{
*mix_error = true;
while (!this->peek_token()->is_op(OPERATOR_COMMA)
&& !this->peek_token()->is_op(OPERATOR_RPAREN))
this->advance_token();
}
}
if (!type->is_error_type())
til->push_back(Typed_identifier("", type, location));
}
else
{
size_t orig_count = til->size();
if (this->peek_token()->is_identifier())
this->identifier_list(til);
else
*mix_error = true;
size_t new_count = til->size();
Type* type;
if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
type = this->type();
else
{
if (is_varargs == NULL)
error_at(this->location(), "invalid use of %<...%>");
else if (new_count > orig_count + 1)
error_at(this->location(), "%<...%> only permits one name");
else
*is_varargs = true;
this->advance_token();
Type* element_type = this->type();
type = Type::make_array_type(element_type, NULL);
}
for (size_t i = orig_count; i < new_count; ++i)
til->set_type(i, type);
}
}
// Result = Parameters | Type .
// This returns false on a parse error.
bool
Parse::result(Typed_identifier_list** presults)
{
if (this->peek_token()->is_op(OPERATOR_LPAREN))
return this->parameters(presults, NULL);
else
{
source_location location = this->location();
Type* type = this->type();
if (type->is_error_type())
{
*presults = NULL;
return false;
}
Typed_identifier_list* til = new Typed_identifier_list();
til->push_back(Typed_identifier("", type, location));
*presults = til;
return true;
}
}
// Block = "{" [ StatementList ] "}" .
// Returns the location of the closing brace.
source_location
Parse::block()
{
if (!this->peek_token()->is_op(OPERATOR_LCURLY))
{
source_location loc = this->location();
if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
&& this->advance_token()->is_op(OPERATOR_LCURLY))
error_at(loc, "unexpected semicolon or newline before %<{%>");
else
{
error_at(this->location(), "expected %<{%>");
return UNKNOWN_LOCATION;
}
}
const Token* token = this->advance_token();
if (!token->is_op(OPERATOR_RCURLY))
{
this->statement_list();
token = this->peek_token();
if (!token->is_op(OPERATOR_RCURLY))
{
if (!token->is_eof() || !saw_errors())
error_at(this->location(), "expected %<}%>");
// Skip ahead to the end of the block, in hopes of avoiding
// lots of meaningless errors.
source_location ret = token->location();
int nest = 0;
while (!token->is_eof())
{
if (token->is_op(OPERATOR_LCURLY))
++nest;
else if (token->is_op(OPERATOR_RCURLY))
{
--nest;
if (nest < 0)
{
this->advance_token();
break;
}
}
token = this->advance_token();
ret = token->location();
}
return ret;
}
}
source_location ret = token->location();
this->advance_token();
return ret;
}
// InterfaceType = "interface" "{" [ MethodSpecList ] "}" .
// MethodSpecList = MethodSpec { ";" MethodSpec } [ ";" ] .
Type*
Parse::interface_type()
{
go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE));
source_location location = this->location();
if (!this->advance_token()->is_op(OPERATOR_LCURLY))
{
source_location token_loc = this->location();
if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
&& this->advance_token()->is_op(OPERATOR_LCURLY))
error_at(token_loc, "unexpected semicolon or newline before %<{%>");
else
{
error_at(this->location(), "expected %<{%>");
return Type::make_error_type();
}
}
this->advance_token();
Typed_identifier_list* methods = new Typed_identifier_list();
if (!this->peek_token()->is_op(OPERATOR_RCURLY))
{
this->method_spec(methods);
while (this->peek_token()->is_op(OPERATOR_SEMICOLON))
{
if (this->advance_token()->is_op(OPERATOR_RCURLY))
break;
this->method_spec(methods);
}
if (!this->peek_token()->is_op(OPERATOR_RCURLY))
{
error_at(this->location(), "expected %<}%>");
while (!this->advance_token()->is_op(OPERATOR_RCURLY))
{
if (this->peek_token()->is_eof())
return Type::make_error_type();
}
}
}
this->advance_token();
if (methods->empty())
{
delete methods;
methods = NULL;
}
Interface_type* ret = Type::make_interface_type(methods, location);
this->gogo_->record_interface_type(ret);
return ret;
}
// MethodSpec = MethodName Signature | InterfaceTypeName .
// MethodName = identifier .
// InterfaceTypeName = TypeName .
void
Parse::method_spec(Typed_identifier_list* methods)
{
const Token* token = this->peek_token();
if (!token->is_identifier())
{
error_at(this->location(), "expected identifier");
return;
}
std::string name = token->identifier();
bool is_exported = token->is_identifier_exported();
source_location location = token->location();
if (this->advance_token()->is_op(OPERATOR_LPAREN))
{
// This is a MethodName.
name = this->gogo_->pack_hidden_name(name, is_exported);
Type* type = this->signature(NULL, location);
if (type == NULL)
return;
methods->push_back(Typed_identifier(name, type, location));
}
else
{
this->unget_token(Token::make_identifier_token(name, is_exported,
location));
Type* type = this->type_name(false);
if (type->is_error_type()
|| (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
&& !this->peek_token()->is_op(OPERATOR_RCURLY)))
{
if (this->peek_token()->is_op(OPERATOR_COMMA))
error_at(this->location(),
"name list not allowed in interface type");
else
error_at(location, "expected signature or type name");
token = this->peek_token();
while (!token->is_eof()
&& !token->is_op(OPERATOR_SEMICOLON)
&& !token->is_op(OPERATOR_RCURLY))
token = this->advance_token();
return;
}
// This must be an interface type, but we can't check that now.
// We check it and pull out the methods in
// Interface_type::do_verify.
methods->push_back(Typed_identifier("", type, location));
}
}
// Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
void
Parse::declaration()
{
const Token* token = this->peek_token();
if (token->is_keyword(KEYWORD_CONST))
this->const_decl();
else if (token->is_keyword(KEYWORD_TYPE))
this->type_decl();
else if (token->is_keyword(KEYWORD_VAR))
this->var_decl();
else if (token->is_keyword(KEYWORD_FUNC))
this->function_decl();
else
{
error_at(this->location(), "expected declaration");
this->advance_token();
}
}
bool
Parse::declaration_may_start_here()
{
const Token* token = this->peek_token();
return (token->is_keyword(KEYWORD_CONST)
|| token->is_keyword(KEYWORD_TYPE)
|| token->is_keyword(KEYWORD_VAR)
|| token->is_keyword(KEYWORD_FUNC));
}
// Decl<P> = P | "(" [ List<P> ] ")" .
void
Parse::decl(void (Parse::*pfn)(void*), void* varg)
{
if (this->peek_token()->is_eof())
{
if (!saw_errors())
error_at(this->location(), "unexpected end of file");
return;
}
if (!this->peek_token()->is_op(OPERATOR_LPAREN))
(this->*pfn)(varg);
else
{
if (!this->advance_token()->is_op(OPERATOR_RPAREN))
{
this->list(pfn, varg, true);
if (!this->peek_token()->is_op(OPERATOR_RPAREN))
{
error_at(this->location(), "missing %<)%>");
while (!this->advance_token()->is_op(OPERATOR_RPAREN))
{
if (this->peek_token()->is_eof())
return;
}
}
}
this->advance_token();
}
}
// List<P> = P { ";" P } [ ";" ] .
// In order to pick up the trailing semicolon we need to know what
// might follow. This is either a '}' or a ')'.
void
Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren)
{
(this->*pfn)(varg);
Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY;
while (this->peek_token()->is_op(OPERATOR_SEMICOLON)
|| this->peek_token()->is_op(OPERATOR_COMMA))
{
if (this->peek_token()->is_op(OPERATOR_COMMA))
error_at(this->location(), "unexpected comma");
if (this->advance_token()->is_op(follow))
break;
(this->*pfn)(varg);
}
}
// ConstDecl = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
void
Parse::const_decl()
{
go_assert(this->peek_token()->is_keyword(KEYWORD_CONST));
this->advance_token();
this->reset_iota();
Type* last_type = NULL;
Expression_list* last_expr_list = NULL;
if (!this->peek_token()->is_op(OPERATOR_LPAREN))
this->const_spec(&last_type, &last_expr_list);
else
{
this->advance_token();
while (!this->peek_token()->is_op(OPERATOR_RPAREN))
{
this->const_spec(&last_type, &last_expr_list);
if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
this->advance_token();
else if (!this->peek_token()->is_op(OPERATOR_RPAREN))
{
error_at(this->location(), "expected %<;%> or %<)%> or newline");
if (!this->skip_past_error(OPERATOR_RPAREN))
return;
}
}
this->advance_token();
}
if (last_expr_list != NULL)
delete last_expr_list;
}
// ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
void
Parse::const_spec(Type** last_type, Expression_list** last_expr_list)
{
Typed_identifier_list til;
this->identifier_list(&til);
Type* type = NULL;
if (this->type_may_start_here())
{
type = this->type();
*last_type = NULL;
*last_expr_list = NULL;
}
Expression_list *expr_list;
if (!this->peek_token()->is_op(OPERATOR_EQ))
{
if (*last_expr_list == NULL)
{
error_at(this->location(), "expected %<=%>");
return;
}
type = *last_type;
expr_list = new Expression_list;
for (Expression_list::const_iterator p = (*last_expr_list)->begin();
p != (*last_expr_list)->end();
++p)
expr_list->push_back((*p)->copy());
}
else
{
this->advance_token();
expr_list = this->expression_list(NULL, false);
*last_type = type;
if (*last_expr_list != NULL)
delete *last_expr_list;
*last_expr_list = expr_list;
}
Expression_list::const_iterator pe = expr_list->begin();
for (Typed_identifier_list::iterator pi = til.begin();
pi != til.end();
++pi, ++pe)
{
if (pe == expr_list->end())
{
error_at(this->location(), "not enough initializers");
return;
}
if (type != NULL)
pi->set_type(type);
if (!Gogo::is_sink_name(pi->name()))
this->gogo_->add_constant(*pi, *pe, this->iota_value());
}
if (pe != expr_list->end())
error_at(this->location(), "too many initializers");
this->increment_iota();
return;
}
// TypeDecl = "type" Decl<TypeSpec> .
void
Parse::type_decl()
{
go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE));
this->advance_token();
this->decl(&Parse::type_spec, NULL);
}
// TypeSpec = identifier Type .
void
Parse::type_spec(void*)
{
const Token* token = this->peek_token();
if (!token->is_identifier())
{
error_at(this->location(), "expected identifier");
return;
}
std::string name = token->identifier();
bool is_exported = token->is_identifier_exported();
source_location location = token->location();
token = this->advance_token();
// The scope of the type name starts at the point where the
// identifier appears in the source code. We implement this by
// declaring the type before we read the type definition.
Named_object* named_type = NULL;
if (name != "_")
{
name = this->gogo_->pack_hidden_name(name, is_exported);
named_type = this->gogo_->declare_type(name, location);
}
Type* type;
if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
type = this->type();
else
{
error_at(this->location(),
"unexpected semicolon or newline in type declaration");
type = Type::make_error_type();
this->advance_token();
}
if (type->is_error_type())
{
while (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
&& !this->peek_token()->is_eof())
this->advance_token();
}
if (name != "_")
{
if (named_type->is_type_declaration())
{
Type* ftype = type->forwarded();
if (ftype->forward_declaration_type() != NULL
&& (ftype->forward_declaration_type()->named_object()
== named_type))
{
error_at(location, "invalid recursive type");
type = Type::make_error_type();
}
this->gogo_->define_type(named_type,
Type::make_named_type(named_type, type,
location));
go_assert(named_type->package() == NULL);
}
else
{
// This will probably give a redefinition error.
this->gogo_->add_type(name, type, location);
}
}
}
// VarDecl = "var" Decl<VarSpec> .
void
Parse::var_decl()
{
go_assert(this->peek_token()->is_keyword(KEYWORD_VAR));
this->advance_token();
this->decl(&Parse::var_spec, NULL);
}
// VarSpec = IdentifierList
// ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
void
Parse::var_spec(void*)
{
// Get the variable names.
Typed_identifier_list til;
this->identifier_list(&til);
source_location location = this->location();
Type* type = NULL;
Expression_list* init = NULL;
if (!this->peek_token()->is_op(OPERATOR_EQ))
{
type = this->type();
if (type->is_error_type())
{
while (!this->peek_token()->is_op(OPERATOR_EQ)
&& !this->peek_token()->is_op(OPERATOR_SEMICOLON)
&& !this->peek_token()->is_eof())
this->advance_token();
}
if (this->peek_token()->is_op(OPERATOR_EQ))
{
this->advance_token();
init = this->expression_list(NULL, false);
}
}
else
{
this->advance_token();
init = this->expression_list(NULL, false);
}
this->init_vars(&til, type, init, false, location);
if (init != NULL)
delete init;
}
// Create variables. TIL is a list of variable names. If TYPE is not
// NULL, it is the type of all the variables. If INIT is not NULL, it
// is an initializer list for the variables.
void
Parse::init_vars(const Typed_identifier_list* til, Type* type,
Expression_list* init, bool is_coloneq,
source_location location)
{
// Check for an initialization which can yield multiple values.
if (init != NULL && init->size() == 1 && til->size() > 1)
{
if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq,
location))
return;
if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq,
location))
return;
if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq,
location))
return;
if (this->init_vars_from_type_guard(til, type, *init->begin(),
is_coloneq, location))
return;
}
if (init != NULL && init->size() != til->size())
{
if (init->empty() || !init->front()->is_error_expression())
error_at(location, "wrong number of initializations");
init = NULL;
if (type == NULL)
type = Type::make_error_type();
}
// Note that INIT was already parsed with the old name bindings, so
// we don't have to worry that it will accidentally refer to the
// newly declared variables.
Expression_list::const_iterator pexpr;
if (init != NULL)
pexpr = init->begin();
bool any_new = false;
for (Typed_identifier_list::const_iterator p = til->begin();
p != til->end();
++p)
{
if (init != NULL)
go_assert(pexpr != init->end());
this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq,
false, &any_new);
if (init != NULL)
++pexpr;
}
if (init != NULL)
go_assert(pexpr == init->end());
if (is_coloneq && !any_new)
error_at(location, "variables redeclared but no variable is new");
}
// See if we need to initialize a list of variables from a function
// call. This returns true if we have set up the variables and the
// initialization.
bool
Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type,
Expression* expr, bool is_coloneq,
source_location location)
{
Call_expression* call = expr->call_expression();
if (call == NULL)
return false;
// This is a function call. We can't check here whether it returns
// the right number of values, but it might. Declare the variables,
// and then assign the results of the call to them.
unsigned int index = 0;
bool any_new = false;
for (Typed_identifier_list::const_iterator pv = vars->begin();
pv != vars->end();
++pv, ++index)
{
Expression* init = Expression::make_call_result(call, index);
this->init_var(*pv, type, init, is_coloneq, false, &any_new);
}
if (is_coloneq && !any_new)
error_at(location, "variables redeclared but no variable is new");
return true;
}
// See if we need to initialize a pair of values from a map index
// expression. This returns true if we have set up the variables and
// the initialization.
bool
Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type,
Expression* expr, bool is_coloneq,
source_location location)
{
Index_expression* index = expr->index_expression();
if (index == NULL)
return false;
if (vars->size() != 2)
return false;
// This is an index which is being assigned to two variables. It
// must be a map index. Declare the variables, and then assign the
// results of the map index.
bool any_new = false;
Typed_identifier_list::const_iterator p = vars->begin();
Expression* init = type == NULL ? index : NULL;
Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
type == NULL, &any_new);
if (type == NULL && any_new && val_no->is_variable())
val_no->var_value()->set_type_from_init_tuple();
Expression* val_var = Expression::make_var_reference(val_no, location);
++p;
Type* var_type = type;
if (var_type == NULL)
var_type = Type::lookup_bool_type();
Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
&any_new);
Expression* present_var = Expression::make_var_reference(no, location);
if (is_coloneq && !any_new)
error_at(location, "variables redeclared but no variable is new");
Statement* s = Statement::make_tuple_map_assignment(val_var, present_var,
index, location);
if (!this->gogo_->in_global_scope())
this->gogo_->add_statement(s);
else if (!val_no->is_sink())
{
if (val_no->is_variable())
val_no->var_value()->add_preinit_statement(this->gogo_, s);
}
else if (!no->is_sink())
{
if (no->is_variable())
no->var_value()->add_preinit_statement(this->gogo_, s);
}
else
{
// Execute the map index expression just so that we can fail if
// the map is nil.
Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
NULL, location);
dummy->var_value()->add_preinit_statement(this->gogo_, s);
}
return true;
}
// See if we need to initialize a pair of values from a receive
// expression. This returns true if we have set up the variables and
// the initialization.
bool
Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type,
Expression* expr, bool is_coloneq,
source_location location)
{
Receive_expression* receive = expr->receive_expression();
if (receive == NULL)
return false;
if (vars->size() != 2)
return false;
// This is a receive expression which is being assigned to two
// variables. Declare the variables, and then assign the results of
// the receive.
bool any_new = false;
Typed_identifier_list::const_iterator p = vars->begin();
Expression* init = type == NULL ? receive : NULL;
Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
type == NULL, &any_new);
if (type == NULL && any_new && val_no->is_variable())
val_no->var_value()->set_type_from_init_tuple();
Expression* val_var = Expression::make_var_reference(val_no, location);
++p;
Type* var_type = type;
if (var_type == NULL)
var_type = Type::lookup_bool_type();
Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
&any_new);
Expression* received_var = Expression::make_var_reference(no, location);
if (is_coloneq && !any_new)
error_at(location, "variables redeclared but no variable is new");
Statement* s = Statement::make_tuple_receive_assignment(val_var,
received_var,
receive->channel(),
false,
location);
if (!this->gogo_->in_global_scope())
this->gogo_->add_statement(s);
else if (!val_no->is_sink())
{
if (val_no->is_variable())
val_no->var_value()->add_preinit_statement(this->gogo_, s);
}
else if (!no->is_sink())
{
if (no->is_variable())
no->var_value()->add_preinit_statement(this->gogo_, s);
}
else
{
Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
NULL, location);
dummy->var_value()->add_preinit_statement(this->gogo_, s);
}
return true;
}
// See if we need to initialize a pair of values from a type guard
// expression. This returns true if we have set up the variables and
// the initialization.
bool
Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
Type* type, Expression* expr,
bool is_coloneq, source_location location)
{
Type_guard_expression* type_guard = expr->type_guard_expression();
if (type_guard == NULL)
return false;
if (vars->size() != 2)
return false;
// This is a type guard expression which is being assigned to two
// variables. Declare the variables, and then assign the results of
// the type guard.
bool any_new = false;
Typed_identifier_list::const_iterator p = vars->begin();
Type* var_type = type;
if (var_type == NULL)
var_type = type_guard->type();
Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
&any_new);
Expression* val_var = Expression::make_var_reference(val_no, location);
++p;
var_type = type;
if (var_type == NULL)
var_type = Type::lookup_bool_type();
Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
&any_new);
Expression* ok_var = Expression::make_var_reference(no, location);
Expression* texpr = type_guard->expr();
Type* t = type_guard->type();
Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
texpr, t,
location);
if (is_coloneq && !any_new)
error_at(location, "variables redeclared but no variable is new");
if (!this->gogo_->in_global_scope())
this->gogo_->add_statement(s);
else if (!val_no->is_sink())
{
if (val_no->is_variable())
val_no->var_value()->add_preinit_statement(this->gogo_, s);
}
else if (!no->is_sink())
{
if (no->is_variable())
no->var_value()->add_preinit_statement(this->gogo_, s);
}
else
{
Named_object* dummy = this->create_dummy_global(type, NULL, location);
dummy->var_value()->add_preinit_statement(this->gogo_, s);
}
return true;
}
// Create a single variable. If IS_COLONEQ is true, we permit
// redeclarations in the same block, and we set *IS_NEW when we find a
// new variable which is not a redeclaration.
Named_object*
Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
bool is_coloneq, bool type_from_init, bool* is_new)
{
source_location location = tid.location();
if (Gogo::is_sink_name(tid.name()))
{
if (!type_from_init && init != NULL)
{
if (!this->gogo_->in_global_scope())
this->gogo_->add_statement(Statement::make_statement(init, true));
else
return this->create_dummy_global(type, init, location);
}
return this->gogo_->add_sink();
}
if (is_coloneq)
{
Named_object* no = this->gogo_->lookup_in_block(tid.name());
if (no != NULL
&& (no->is_variable() || no->is_result_variable()))
{
// INIT may be NULL even when IS_COLONEQ is true for cases
// like v, ok := x.(int).
if (!type_from_init && init != NULL)
{
Expression *v = Expression::make_var_reference(no, location);
Statement *s = Statement::make_assignment(v, init, location);
this->gogo_->add_statement(s);
}
return no;
}
}
*is_new = true;
Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
false, false, location);
Named_object* no = this->gogo_->add_variable(tid.name(), var);
if (!no->is_variable())
{
// The name is already defined, so we just gave an error.
return this->gogo_->add_sink();
}
return no;
}
// Create a dummy global variable to force an initializer to be run in
// the right place. This is used when a sink variable is initialized
// at global scope.
Named_object*
Parse::create_dummy_global(Type* type, Expression* init,
source_location location)
{
if (type == NULL && init == NULL)
type = Type::lookup_bool_type();
Variable* var = new Variable(type, init, true, false, false, location);
static int count;
char buf[30];
snprintf(buf, sizeof buf, "_.%d", count);
++count;
return this->gogo_->add_variable(buf, var);
}
// SimpleVarDecl = identifier ":=" Expression .
// We've already seen the identifier.
// FIXME: We also have to implement
// IdentifierList ":=" ExpressionList
// In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
// tuple assignments here as well.
// If P_RANGE_CLAUSE is not NULL, then this will recognize a
// RangeClause.
// If P_TYPE_SWITCH is not NULL, this will recognize a type switch
// guard (var := expr.("type") using the literal keyword "type").
void
Parse::simple_var_decl_or_assignment(const std::string& name,
source_location location,
Range_clause* p_range_clause,
Type_switch* p_type_switch)
{
Typed_identifier_list til;
til.push_back(Typed_identifier(name, NULL, location));
// We've seen one identifier. If we see a comma now, this could be
// "a, *p = 1, 2".
if (this->peek_token()->is_op(OPERATOR_COMMA))
{
go_assert(p_type_switch == NULL);
while (true)
{
const Token* token = this->advance_token();
if (!token->is_identifier())
break;
std::string id = token->identifier();
bool is_id_exported = token->is_identifier_exported();
source_location id_location = token->location();
token = this->advance_token();
if (!token->is_op(OPERATOR_COMMA))
{
if (token->is_op(OPERATOR_COLONEQ))
{
id = this->gogo_->pack_hidden_name(id, is_id_exported);
til.push_back(Typed_identifier(id, NULL, location));
}
else
this->unget_token(Token::make_identifier_token(id,
is_id_exported,
id_location));
break;
}
id = this->gogo_->pack_hidden_name(id, is_id_exported);
til.push_back(Typed_identifier(id, NULL, location));
}
// We have a comma separated list of identifiers in TIL. If the
// next token is COLONEQ, then this is a simple var decl, and we
// have the complete list of identifiers. If the next token is
// not COLONEQ, then the only valid parse is a tuple assignment.
// The list of identifiers we have so far is really a list of
// expressions. There are more expressions following.
if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
{
Expression_list* exprs = new Expression_list;
for (Typed_identifier_list::const_iterator p = til.begin();
p != til.end();
++p)
exprs->push_back(this->id_to_expression(p->name(),
p->location()));
Expression_list* more_exprs = this->expression_list(NULL, true);
for (Expression_list::const_iterator p = more_exprs->begin();
p != more_exprs->end();
++p)
exprs->push_back(*p);
delete more_exprs;
this->tuple_assignment(exprs, p_range_clause);
return;
}
}
go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
const Token* token = this->advance_token();
if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
{
this->range_clause_decl(&til, p_range_clause);
return;
}
Expression_list* init;
if (p_type_switch == NULL)
init = this->expression_list(NULL, false);
else
{
bool is_type_switch = false;
Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
&is_type_switch);
if (is_type_switch)
{
p_type_switch->found = true;
p_type_switch->name = name;
p_type_switch->location = location;
p_type_switch->expr = expr;
return;
}
if (!this->peek_token()->is_op(OPERATOR_COMMA))
{
init = new Expression_list();
init->push_back(expr);
}
else
{
this->advance_token();
init = this->expression_list(expr, false);
}
}
this->init_vars(&til, NULL, init, true, location);
}
// FunctionDecl = "func" identifier Signature [ Block ] .
// MethodDecl = "func" Receiver identifier Signature [ Block ] .
// gcc extension:
// FunctionDecl = "func" identifier Signature
// __asm__ "(" string_lit ")" .
// This extension means a function whose real name is the identifier
// inside the asm.
void
Parse::function_decl()
{
go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
source_location location = this->location();
const Token* token = this->advance_token();
Typed_identifier* rec = NULL;
if (token->is_op(OPERATOR_LPAREN))
{
rec = this->receiver();
token = this->peek_token();
}
if (!token->is_identifier())
{
error_at(this->location(), "expected function name");
return;
}
std::string name =
this->gogo_->pack_hidden_name(token->identifier(),
token->is_identifier_exported());
this->advance_token();
Function_type* fntype = this->signature(rec, this->location());
if (fntype == NULL)
return;
Named_object* named_object = NULL;
if (this->peek_token()->is_keyword(KEYWORD_ASM))
{
if (!this->advance_token()->is_op(OPERATOR_LPAREN))
{
error_at(this->location(), "expected %<(%>");
return;
}
token = this->advance_token();
if (!token->is_string())
{
error_at(this->location(), "expected string");
return;
}
std::string asm_name = token->string_value();
if (!this->advance_token()->is_op(OPERATOR_RPAREN))
{
error_at(this->location(), "expected %<)%>");
return;
}
this->advance_token();
if (!Gogo::is_sink_name(name))
{
named_object = this->gogo_->declare_function(name, fntype, location);
if (named_object->is_function_declaration())
named_object->func_declaration_value()->set_asm_name(asm_name);
}
}
// Check for the easy error of a newline before the opening brace.
if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
{
source_location semi_loc = this->location();
if (this->advance_token()->is_op(OPERATOR_LCURLY))
error_at(this->location(),
"unexpected semicolon or newline before %<{%>");
else
this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
semi_loc));
}
if (!this->peek_token()->is_op(OPERATOR_LCURLY))
{
if (named_object == NULL && !Gogo::is_sink_name(name))
this->gogo_->declare_function(name, fntype, location);
}
else
{
this->gogo_->start_function(name, fntype, true, location);
source_location end_loc = this->block();
this->gogo_->finish_function(end_loc);
}
}
// Receiver = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
// BaseTypeName = identifier .
Typed_identifier*
Parse::receiver()
{
go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
std::string name;
const Token* token = this->advance_token();
source_location location = token->location();
if (!token->is_op(OPERATOR_MULT))
{
if (!token->is_identifier())
{
error_at(this->location(), "method has no receiver");
while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
token = this->advance_token();
if (!token->is_eof())
this->advance_token();
return NULL;
}
name = token->identifier();
bool is_exported = token->is_identifier_exported();
token = this->advance_token();
if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN))
{
// An identifier followed by something other than a dot or a
// right parenthesis must be a receiver name followed by a
// type.
name = this->gogo_->pack_hidden_name(name, is_exported);
}
else
{
// This must be a type name.
this->unget_token(Token::make_identifier_token(name, is_exported,
location));
token = this->peek_token();
name.clear();
}
}
// Here the receiver name is in NAME (it is empty if the receiver is
// unnamed) and TOKEN is the first token in the type.
bool is_pointer = false;
if (token->is_op(OPERATOR_MULT))
{
is_pointer = true;
token = this->advance_token();
}
if (!token->is_identifier())
{
error_at(this->location(), "expected receiver name or type");
int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0;
while (!token->is_eof())
{
token = this->advance_token();
if (token->is_op(OPERATOR_LPAREN))
++c;
else if (token->is_op(OPERATOR_RPAREN))
{
if (c == 0)
break;
--c;
}
}
if (!token->is_eof())
this->advance_token();
return NULL;
}
Type* type = this->type_name(true);
if (is_pointer && !type->is_error_type())
type = Type::make_pointer_type(type);
if (this->peek_token()->is_op(OPERATOR_RPAREN))
this->advance_token();
else
{
if (this->peek_token()->is_op(OPERATOR_COMMA))
error_at(this->location(), "method has multiple receivers");
else
error_at(this->location(), "expected %<)%>");
while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
token = this->advance_token();
if (!token->is_eof())
this->advance_token();
return NULL;
}
return new Typed_identifier(name, type, location);
}
// Operand = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
// Literal = BasicLit | CompositeLit | FunctionLit .
// BasicLit = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
// If MAY_BE_SINK is true, this operand may be "_".
Expression*
Parse::operand(bool may_be_sink)
{
const Token* token = this->peek_token();
Expression* ret;
switch (token->classification())
{
case Token::TOKEN_IDENTIFIER:
{
source_location location = token->location();
std::string id = token->identifier();
bool is_exported = token->is_identifier_exported();
std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
Named_object* in_function;
Named_object* named_object = this->gogo_->lookup(packed, &in_function);
Package* package = NULL;
if (named_object != NULL && named_object->is_package())
{
if (!this->advance_token()->is_op(OPERATOR_DOT)
|| !this->advance_token()->is_identifier())
{
error_at(location, "unexpected reference to package");
return Expression::make_error(location);
}
package = named_object->package_value();
package->set_used();
id = this->peek_token()->identifier();
is_exported = this->peek_token()->is_identifier_exported();
packed = this->gogo_->pack_hidden_name(id, is_exported);
named_object = package->lookup(packed);
location = this->location();
go_assert(in_function == NULL);
}
this->advance_token();
if (named_object != NULL
&& named_object->is_type()
&& !named_object->type_value()->is_visible())
{
go_assert(package != NULL);
error_at(location, "invalid reference to hidden type %<%s.%s%>",
Gogo::message_name(package->name()).c_str(),
Gogo::message_name(id).c_str());
return Expression::make_error(location);
}
if (named_object == NULL)
{
if (package != NULL)
{
std::string n1 = Gogo::message_name(package->name());
std::string n2 = Gogo::message_name(id);
if (!is_exported)
error_at(location,
("invalid reference to unexported identifier "
"%<%s.%s%>"),
n1.c_str(), n2.c_str());
else
error_at(location,
"reference to undefined identifier %<%s.%s%>",
n1.c_str(), n2.c_str());
return Expression::make_error(location);
}
named_object = this->gogo_->add_unknown_name(packed, location);
}
if (in_function != NULL
&& in_function != this->gogo_->current_function()
&& (named_object->is_variable()
|| named_object->is_result_variable()))
return this->enclosing_var_reference(in_function, named_object,
location);
switch (named_object->classification())
{
case Named_object::NAMED_OBJECT_CONST:
return Expression::make_const_reference(named_object, location);
case Named_object::NAMED_OBJECT_TYPE:
return Expression::make_type(named_object->type_value(), location);
case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
{
Type* t = Type::make_forward_declaration(named_object);
return Expression::make_type(t, location);
}
case Named_object::NAMED_OBJECT_VAR:
case Named_object::NAMED_OBJECT_RESULT_VAR:
return Expression::make_var_reference(named_object, location);
case Named_object::NAMED_OBJECT_SINK:
if (may_be_sink)
return Expression::make_sink(location);
else
{
error_at(location, "cannot use _ as value");
return Expression::make_error(location);
}
case Named_object::NAMED_OBJECT_FUNC:
case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
return Expression::make_func_reference(named_object, NULL,
location);
case Named_object::NAMED_OBJECT_UNKNOWN:
return Expression::make_unknown_reference(named_object, location);
default:
go_unreachable();
}
}
go_unreachable();
case Token::TOKEN_STRING:
ret = Expression::make_string(token->string_value(), token->location());
this->advance_token();
return ret;
case Token::TOKEN_INTEGER:
ret = Expression::make_integer(token->integer_value(), NULL,
token->location());
this->advance_token();
return ret;
case Token::TOKEN_FLOAT:
ret = Expression::make_float(token->float_value(), NULL,
token->location());
this->advance_token();
return ret;
case Token::TOKEN_IMAGINARY:
{
mpfr_t zero;
mpfr_init_set_ui(zero, 0, GMP_RNDN);
ret = Expression::make_complex(&zero, token->imaginary_value(),
NULL, token->location());
mpfr_clear(zero);
this->advance_token();
return ret;
}
case Token::TOKEN_KEYWORD:
switch (token->keyword())
{
case KEYWORD_FUNC:
return this->function_lit();
case KEYWORD_CHAN:
case KEYWORD_INTERFACE:
case KEYWORD_MAP:
case KEYWORD_STRUCT:
{
source_location location = token->location();
return Expression::make_type(this->type(), location);
}
default:
break;
}
break;
case Token::TOKEN_OPERATOR:
if (token->is_op(OPERATOR_LPAREN))
{
this->advance_token();
ret = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
if (!this->peek_token()->is_op(OPERATOR_RPAREN))
error_at(this->location(), "missing %<)%>");
else
this->advance_token();
return ret;
}
else if (token->is_op(OPERATOR_LSQUARE))
{
// Here we call array_type directly, as this is the only
// case where an ellipsis is permitted for an array type.
source_location location = token->location();
return Expression::make_type(this->array_type(true), location);
}
break;
default:
break;
}
error_at(this->location(), "expected operand");
return Expression::make_error(this->location());
}
// Handle a reference to a variable in an enclosing function. We add
// it to a list of such variables. We return a reference to a field
// in a struct which will be passed on the static chain when calling
// the current function.
Expression*
Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
source_location location)
{
go_assert(var->is_variable() || var->is_result_variable());
Named_object* this_function = this->gogo_->current_function();
Named_object* closure = this_function->func_value()->closure_var();
Enclosing_var ev(var, in_function, this->enclosing_vars_.size());
std::pair<Enclosing_vars::iterator, bool> ins =
this->enclosing_vars_.insert(ev);
if (ins.second)
{
// This is a variable we have not seen before. Add a new field
// to the closure type.
this_function->func_value()->add_closure_field(var, location);
}
Expression* closure_ref = Expression::make_var_reference(closure,
location);
closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location);
// The closure structure holds pointers to the variables, so we need
// to introduce an indirection.
Expression* e = Expression::make_field_reference(closure_ref,
ins.first->index(),
location);
e = Expression::make_unary(OPERATOR_MULT, e, location);
return e;
}
// CompositeLit = LiteralType LiteralValue .
// LiteralType = StructType | ArrayType | "[" "..." "]" ElementType |
// SliceType | MapType | TypeName .
// LiteralValue = "{" [ ElementList [ "," ] ] "}" .
// ElementList = Element { "," Element } .
// Element = [ Key ":" ] Value .
// Key = FieldName | ElementIndex .
// FieldName = identifier .
// ElementIndex = Expression .
// Value = Expression | LiteralValue .
// We have already seen the type if there is one, and we are now
// looking at the LiteralValue. The case "[" "..." "]" ElementType
// will be seen here as an array type whose length is "nil". The
// DEPTH parameter is non-zero if this is an embedded composite
// literal and the type was omitted. It gives the number of steps up
// to the type which was provided. E.g., in [][]int{{1}} it will be
// 1. In [][][]int{{{1}}} it will be 2.
Expression*
Parse::composite_lit(Type* type, int depth, source_location location)
{
go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
this->advance_token();
if (this->peek_token()->is_op(OPERATOR_RCURLY))
{
this->advance_token();
return Expression::make_composite_literal(type, depth, false, NULL,
location);
}
bool has_keys = false;
Expression_list* vals = new Expression_list;
while (true)
{
Expression* val;
bool is_type_omitted = false;
const Token* token = this->peek_token();
if (token->is_identifier())
{
std::string identifier = token->identifier();
bool is_exported = token->is_identifier_exported();
source_location location = token->location();
if (this->advance_token()->is_op(OPERATOR_COLON))
{
// This may be a field name. We don't know for sure--it
// could also be an expression for an array index. We
// don't want to parse it as an expression because may
// trigger various errors, e.g., if this identifier
// happens to be the name of a package.
Gogo* gogo = this->gogo_;
val = this->id_to_expression(gogo->pack_hidden_name(identifier,
is_exported),
location);
}
else
{
this->unget_token(Token::make_identifier_token(identifier,
is_exported,
location));
val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
}
}
else if (!token->is_op(OPERATOR_LCURLY))
val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
else
{
// This must be a composite literal inside another composite
// literal, with the type omitted for the inner one.
val = this->composite_lit(type, depth + 1, token->location());
is_type_omitted = true;
}
token = this->peek_token();
if (!token->is_op(OPERATOR_COLON))
{
if (has_keys)
vals->push_back(NULL);
}
else
{
if (is_type_omitted && !val->is_error_expression())
{
error_at(this->location(), "unexpected %<:%>");
val = Expression::make_error(this->location());
}
this->advance_token();
if (!has_keys && !vals->empty())
{
Expression_list* newvals = new Expression_list;
for (Expression_list::const_iterator p = vals->begin();
p != vals->end();
++p)
{
newvals->push_back(NULL);
newvals->push_back(*p);
}
delete vals;
vals = newvals;
}
has_keys = true;
if (val->unknown_expression() != NULL)
val->unknown_expression()->set_is_composite_literal_key();
vals->push_back(val);
if (!token->is_op(OPERATOR_LCURLY))
val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
else
{
// This must be a composite literal inside another
// composite literal, with the type omitted for the
// inner one.
val = this->composite_lit(type, depth + 1, token->location());
}
token = this->peek_token();
}
vals->push_back(val);
if (token->is_op(OPERATOR_COMMA))
{
if (this->advance_token()->is_op(OPERATOR_RCURLY))
{
this->advance_token();
break;
}
}
else if (token->is_op(OPERATOR_RCURLY))
{
this->advance_token();
break;
}
else
{
error_at(this->location(), "expected %<,%> or %<}%>");
int depth = 0;
while (!token->is_eof()
&& (depth > 0 || !token->is_op(OPERATOR_RCURLY)))
{
if (token->is_op(OPERATOR_LCURLY))
++depth;
else if (token->is_op(OPERATOR_RCURLY))
--depth;
token = this->advance_token();
}
if (token->is_op(OPERATOR_RCURLY))
this->advance_token();
return Expression::make_error(location);
}
}
return Expression::make_composite_literal(type, depth, has_keys, vals,
location);
}
// FunctionLit = "func" Signature Block .
Expression*
Parse::function_lit()
{
source_location location = this->location();
go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
this->advance_token();
Enclosing_vars hold_enclosing_vars;
hold_enclosing_vars.swap(this->enclosing_vars_);
Function_type* type = this->signature(NULL, location);
if (type == NULL)
type = Type::make_function_type(NULL, NULL, NULL, location);
// For a function literal, the next token must be a '{'. If we
// don't see that, then we may have a type expression.
if (!this->peek_token()->is_op(OPERATOR_LCURLY))
return Expression::make_type(type, location);
Bc_stack* hold_break_stack = this->break_stack_;
Bc_stack* hold_continue_stack = this->continue_stack_;
this->break_stack_ = NULL;
this->continue_stack_ = NULL;
Named_object* no = this->gogo_->start_function("", type, true, location);
source_location end_loc = this->block();
this->gogo_->finish_function(end_loc);
if (this->break_stack_ != NULL)
delete this->break_stack_;
if (this->continue_stack_ != NULL)
delete this->continue_stack_;
this->break_stack_ = hold_break_stack;
this->continue_stack_ = hold_continue_stack;
hold_enclosing_vars.swap(this->enclosing_vars_);
Expression* closure = this->create_closure(no, &hold_enclosing_vars,
location);
return Expression::make_func_reference(no, closure, location);
}
// Create a closure for the nested function FUNCTION. This is based
// on ENCLOSING_VARS, which is a list of all variables defined in
// enclosing functions and referenced from FUNCTION. A closure is the
// address of a struct which contains the addresses of all the
// referenced variables. This returns NULL if no closure is required.
Expression*
Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
source_location location)
{
if (enclosing_vars->empty())
return NULL;
// Get the variables in order by their field index.
size_t enclosing_var_count = enclosing_vars->size();
std::vector<Enclosing_var> ev(enclosing_var_count);
for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
p != enclosing_vars->end();
++p)
ev[p->index()] = *p;
// Build an initializer for a composite literal of the closure's
// type.
Named_object* enclosing_function = this->gogo_->current_function();
Expression_list* initializer = new Expression_list;
for (size_t i = 0; i < enclosing_var_count; ++i)
{
go_assert(ev[i].index() == i);
Named_object* var = ev[i].var();
Expression* ref;
if (ev[i].in_function() == enclosing_function)
ref = Expression::make_var_reference(var, location);
else
ref = this->enclosing_var_reference(ev[i].in_function(), var,
location);
Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
location);
initializer->push_back(refaddr);
}
Named_object* closure_var = function->func_value()->closure_var();
Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
Expression* cv = Expression::make_struct_composite_literal(st, initializer,
location);
return Expression::make_heap_composite(cv, location);
}
// PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
// If MAY_BE_SINK is true, this expression may be "_".
// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
// literal.
// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
// guard (var := expr.("type") using the literal keyword "type").
Expression*
Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
bool* is_type_switch)
{
source_location start_loc = this->location();
bool is_parenthesized = this->peek_token()->is_op(OPERATOR_LPAREN);
Expression* ret = this->operand(may_be_sink);
// An unknown name followed by a curly brace must be a composite
// literal, and the unknown name must be a type.
if (may_be_composite_lit
&& !is_parenthesized
&& ret->unknown_expression() != NULL
&& this->peek_token()->is_op(OPERATOR_LCURLY))
{
Named_object* no = ret->unknown_expression()->named_object();
Type* type = Type::make_forward_declaration(no);
ret = Expression::make_type(type, ret->location());
}
// We handle composite literals and type casts here, as it is the
// easiest way to handle types which are in parentheses, as in
// "((uint))(1)".
if (ret->is_type_expression())
{
if (this->peek_token()->is_op(OPERATOR_LCURLY))
{
if (is_parenthesized)
error_at(start_loc,
"cannot parenthesize type in composite literal");
ret = this->composite_lit(ret->type(), 0, ret->location());
}
else if (this->peek_token()->is_op(OPERATOR_LPAREN))
{
source_location loc = this->location();
this->advance_token();
Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
NULL);
if (this->peek_token()->is_op(OPERATOR_ELLIPSIS))
{
error_at(this->location(),
"invalid use of %<...%> in type conversion");
this->advance_token();
}
if (!this->peek_token()->is_op(OPERATOR_RPAREN))
error_at(this->location(), "expected %<)%>");
else
this->advance_token();
if (expr->is_error_expression())
ret = expr;
else
{
Type* t = ret->type();
if (t->classification() == Type::TYPE_ARRAY
&& t->array_type()->length() != NULL
&& t->array_type()->length()->is_nil_expression())
{
error_at(ret->location(),
"invalid use of %<...%> in type conversion");
ret = Expression::make_error(loc);
}
else
ret = Expression::make_cast(t, expr, loc);
}
}
}
while (true)
{
const Token* token = this->peek_token();
if (token->is_op(OPERATOR_LPAREN))
ret = this->call(this->verify_not_sink(ret));
else if (token->is_op(OPERATOR_DOT))
{
ret = this->selector(this->verify_not_sink(ret), is_type_switch);
if (is_type_switch != NULL && *is_type_switch)
break;
}
else if (token->is_op(OPERATOR_LSQUARE))
ret = this->index(this->verify_not_sink(ret));
else
break;
}
return ret;
}
// Selector = "." identifier .
// TypeGuard = "." "(" QualifiedIdent ")" .
// Note that Operand can expand to QualifiedIdent, which contains a
// ".". That is handled directly in operand when it sees a package
// name.
// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
// guard (var := expr.("type") using the literal keyword "type").
Expression*
Parse::selector(Expression* left, bool* is_type_switch)
{
go_assert(this->peek_token()->is_op(OPERATOR_DOT));
source_location location = this->location();
const Token* token = this->advance_token();
if (token->is_identifier())
{
// This could be a field in a struct, or a method in an
// interface, or a method associated with a type. We can't know
// which until we have seen all the types.
std::string name =
this->gogo_->pack_hidden_name(token->identifier(),
token->is_identifier_exported());
if (token->identifier() == "_")
{
error_at(this->location(), "invalid use of %<_%>");
name = this->gogo_->pack_hidden_name("blank", false);
}
this->advance_token();
return Expression::make_selector(left, name, location);
}
else if (token->is_op(OPERATOR_LPAREN))
{
this->advance_token();
Type* type = NULL;
if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
type = this->type();
else
{
if (is_type_switch != NULL)
*is_type_switch = true;
else
{
error_at(this->location(),
"use of %<.(type)%> outside type switch");
type = Type::make_error_type();
}
this->advance_token();
}
if (!this->peek_token()->is_op(OPERATOR_RPAREN))
error_at(this->location(), "missing %<)%>");
else
this->advance_token();
if (is_type_switch != NULL && *is_type_switch)
return left;
return Expression::make_type_guard(left, type, location);
}
else
{
error_at(this->location(), "expected identifier or %<(%>");
return left;
}
}
// Index = "[" Expression "]" .
// Slice = "[" Expression ":" [ Expression ] "]" .
Expression*
Parse::index(Expression* expr)
{
source_location location = this->location();
go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
this->advance_token();
Expression* start;
if (!this->peek_token()->is_op(OPERATOR_COLON))
start = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
else
{
mpz_t zero;
mpz_init_set_ui(zero, 0);
start = Expression::make_integer(&zero, NULL, location);
mpz_clear(zero);
}
Expression* end = NULL;
if (this->peek_token()->is_op(OPERATOR_COLON))
{
// We use nil to indicate a missing high expression.
if (this->advance_token()->is_op(OPERATOR_RSQUARE))
end = Expression::make_nil(this->location());
else
end = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
}
if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
error_at(this->location(), "missing %<]%>");
else
this->advance_token();
return Expression::make_index(expr, start, end, location);
}
// Call = "(" [ ArgumentList [ "," ] ] ")" .
// ArgumentList = ExpressionList [ "..." ] .
Expression*
Parse::call(Expression* func)
{
go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
Expression_list* args = NULL;
bool is_varargs = false;
const Token* token = this->advance_token();
if (!token->is_op(OPERATOR_RPAREN))
{
args = this->expression_list(NULL, false);
token = this->peek_token();
if (token->is_op(OPERATOR_ELLIPSIS))
{
is_varargs = true;
token = this->advance_token();
}
}
if (token->is_op(OPERATOR_COMMA))
token = this->advance_token();
if (!token->is_op(OPERATOR_RPAREN))
error_at(this->location(), "missing %<)%>");
else
this->advance_token();
if (func->is_error_expression())
return func;
return Expression::make_call(func, args, is_varargs, func->location());
}
// Return an expression for a single unqualified identifier.
Expression*
Parse::id_to_expression(const std::string& name, source_location location)
{
Named_object* in_function;
Named_object* named_object = this->gogo_->lookup(name, &in_function);
if (named_object == NULL)
named_object = this->gogo_->add_unknown_name(name, location);
if (in_function != NULL
&& in_function != this->gogo_->current_function()
&& (named_object->is_variable() || named_object->is_result_variable()))
return this->enclosing_var_reference(in_function, named_object,
location);
switch (named_object->classification())
{
case Named_object::NAMED_OBJECT_CONST:
return Expression::make_const_reference(named_object, location);
case Named_object::NAMED_OBJECT_VAR:
case Named_object::NAMED_OBJECT_RESULT_VAR:
return Expression::make_var_reference(named_object, location);
case Named_object: