OpenCores
URL https://opencores.org/ocsvn/openrisc/openrisc/trunk

Subversion Repositories openrisc

[/] [openrisc/] [trunk/] [gnu-dev/] [or1k-gcc/] [gcc/] [go/] [gofrontend/] [parse.cc] - Blame information for rev 718

Go to most recent revision | Details | Compare with Previous | View Log

Line No. Rev Author Line
1 714 jeremybenn
// parse.cc -- Go frontend parser.
2
 
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.
6
 
7
#include "go-system.h"
8
 
9
#include "lex.h"
10
#include "gogo.h"
11
#include "types.h"
12
#include "statements.h"
13
#include "expressions.h"
14
#include "parse.h"
15
 
16
// Struct Parse::Enclosing_var_comparison.
17
 
18
// Return true if v1 should be considered to be less than v2.
19
 
20
bool
21
Parse::Enclosing_var_comparison::operator()(const Enclosing_var& v1,
22
                                            const Enclosing_var& v2)
23
{
24
  if (v1.var() == v2.var())
25
    return false;
26
 
27
  const std::string& n1(v1.var()->name());
28
  const std::string& n2(v2.var()->name());
29
  int i = n1.compare(n2);
30
  if (i < 0)
31
    return true;
32
  else if (i > 0)
33
    return false;
34
 
35
  // If we get here it means that a single nested function refers to
36
  // two different variables defined in enclosing functions, and both
37
  // variables have the same name.  I think this is impossible.
38
  go_unreachable();
39
}
40
 
41
// Class Parse.
42
 
43
Parse::Parse(Lex* lex, Gogo* gogo)
44
  : lex_(lex),
45
    token_(Token::make_invalid_token(Linemap::unknown_location())),
46
    unget_token_(Token::make_invalid_token(Linemap::unknown_location())),
47
    unget_token_valid_(false),
48
    is_erroneous_function_(false),
49
    gogo_(gogo),
50
    break_stack_(NULL),
51
    continue_stack_(NULL),
52
    iota_(0),
53
    enclosing_vars_(),
54
    type_switch_vars_()
55
{
56
}
57
 
58
// Return the current token.
59
 
60
const Token*
61
Parse::peek_token()
62
{
63
  if (this->unget_token_valid_)
64
    return &this->unget_token_;
65
  if (this->token_.is_invalid())
66
    this->token_ = this->lex_->next_token();
67
  return &this->token_;
68
}
69
 
70
// Advance to the next token and return it.
71
 
72
const Token*
73
Parse::advance_token()
74
{
75
  if (this->unget_token_valid_)
76
    {
77
      this->unget_token_valid_ = false;
78
      if (!this->token_.is_invalid())
79
        return &this->token_;
80
    }
81
  this->token_ = this->lex_->next_token();
82
  return &this->token_;
83
}
84
 
85
// Push a token back on the input stream.
86
 
87
void
88
Parse::unget_token(const Token& token)
89
{
90
  go_assert(!this->unget_token_valid_);
91
  this->unget_token_ = token;
92
  this->unget_token_valid_ = true;
93
}
94
 
95
// The location of the current token.
96
 
97
Location
98
Parse::location()
99
{
100
  return this->peek_token()->location();
101
}
102
 
103
// IdentifierList = identifier { "," identifier } .
104
 
105
void
106
Parse::identifier_list(Typed_identifier_list* til)
107
{
108
  const Token* token = this->peek_token();
109
  while (true)
110
    {
111
      if (!token->is_identifier())
112
        {
113
          error_at(this->location(), "expected identifier");
114
          return;
115
        }
116
      std::string name =
117
        this->gogo_->pack_hidden_name(token->identifier(),
118
                                      token->is_identifier_exported());
119
      til->push_back(Typed_identifier(name, NULL, token->location()));
120
      token = this->advance_token();
121
      if (!token->is_op(OPERATOR_COMMA))
122
        return;
123
      token = this->advance_token();
124
    }
125
}
126
 
127
// ExpressionList = Expression { "," Expression } .
128
 
129
// If MAY_BE_SINK is true, the expressions in the list may be "_".
130
 
131
Expression_list*
132
Parse::expression_list(Expression* first, bool may_be_sink)
133
{
134
  Expression_list* ret = new Expression_list();
135
  if (first != NULL)
136
    ret->push_back(first);
137
  while (true)
138
    {
139
      ret->push_back(this->expression(PRECEDENCE_NORMAL, may_be_sink, true,
140
                                      NULL));
141
 
142
      const Token* token = this->peek_token();
143
      if (!token->is_op(OPERATOR_COMMA))
144
        return ret;
145
 
146
      // Most expression lists permit a trailing comma.
147
      Location location = token->location();
148
      this->advance_token();
149
      if (!this->expression_may_start_here())
150
        {
151
          this->unget_token(Token::make_operator_token(OPERATOR_COMMA,
152
                                                       location));
153
          return ret;
154
        }
155
    }
156
}
157
 
158
// QualifiedIdent = [ PackageName "." ] identifier .
159
// PackageName = identifier .
160
 
161
// This sets *PNAME to the identifier and sets *PPACKAGE to the
162
// package or NULL if there isn't one.  This returns true on success,
163
// false on failure in which case it will have emitted an error
164
// message.
165
 
166
bool
167
Parse::qualified_ident(std::string* pname, Named_object** ppackage)
168
{
169
  const Token* token = this->peek_token();
170
  if (!token->is_identifier())
171
    {
172
      error_at(this->location(), "expected identifier");
173
      return false;
174
    }
175
 
176
  std::string name = token->identifier();
177
  bool is_exported = token->is_identifier_exported();
178
  name = this->gogo_->pack_hidden_name(name, is_exported);
179
 
180
  token = this->advance_token();
181
  if (!token->is_op(OPERATOR_DOT))
182
    {
183
      *pname = name;
184
      *ppackage = NULL;
185
      return true;
186
    }
187
 
188
  Named_object* package = this->gogo_->lookup(name, NULL);
189
  if (package == NULL || !package->is_package())
190
    {
191
      error_at(this->location(), "expected package");
192
      // We expect . IDENTIFIER; skip both.
193
      if (this->advance_token()->is_identifier())
194
        this->advance_token();
195
      return false;
196
    }
197
 
198
  package->package_value()->set_used();
199
 
200
  token = this->advance_token();
201
  if (!token->is_identifier())
202
    {
203
      error_at(this->location(), "expected identifier");
204
      return false;
205
    }
206
 
207
  name = token->identifier();
208
 
209
  if (name == "_")
210
    {
211
      error_at(this->location(), "invalid use of %<_%>");
212
      name = "blank";
213
    }
214
 
215
  if (package->name() == this->gogo_->package_name())
216
    name = this->gogo_->pack_hidden_name(name,
217
                                         token->is_identifier_exported());
218
 
219
  *pname = name;
220
  *ppackage = package;
221
 
222
  this->advance_token();
223
 
224
  return true;
225
}
226
 
227
// Type = TypeName | TypeLit | "(" Type ")" .
228
// TypeLit =
229
//      ArrayType | StructType | PointerType | FunctionType | InterfaceType |
230
//      SliceType | MapType | ChannelType .
231
 
232
Type*
233
Parse::type()
234
{
235
  const Token* token = this->peek_token();
236
  if (token->is_identifier())
237
    return this->type_name(true);
238
  else if (token->is_op(OPERATOR_LSQUARE))
239
    return this->array_type(false);
240
  else if (token->is_keyword(KEYWORD_CHAN)
241
           || token->is_op(OPERATOR_CHANOP))
242
    return this->channel_type();
243
  else if (token->is_keyword(KEYWORD_INTERFACE))
244
    return this->interface_type();
245
  else if (token->is_keyword(KEYWORD_FUNC))
246
    {
247
      Location location = token->location();
248
      this->advance_token();
249
      Type* type = this->signature(NULL, location);
250
      if (type == NULL)
251
        return Type::make_error_type();
252
      return type;
253
    }
254
  else if (token->is_keyword(KEYWORD_MAP))
255
    return this->map_type();
256
  else if (token->is_keyword(KEYWORD_STRUCT))
257
    return this->struct_type();
258
  else if (token->is_op(OPERATOR_MULT))
259
    return this->pointer_type();
260
  else if (token->is_op(OPERATOR_LPAREN))
261
    {
262
      this->advance_token();
263
      Type* ret = this->type();
264
      if (this->peek_token()->is_op(OPERATOR_RPAREN))
265
        this->advance_token();
266
      else
267
        {
268
          if (!ret->is_error_type())
269
            error_at(this->location(), "expected %<)%>");
270
        }
271
      return ret;
272
    }
273
  else
274
    {
275
      error_at(token->location(), "expected type");
276
      return Type::make_error_type();
277
    }
278
}
279
 
280
bool
281
Parse::type_may_start_here()
282
{
283
  const Token* token = this->peek_token();
284
  return (token->is_identifier()
285
          || token->is_op(OPERATOR_LSQUARE)
286
          || token->is_op(OPERATOR_CHANOP)
287
          || token->is_keyword(KEYWORD_CHAN)
288
          || token->is_keyword(KEYWORD_INTERFACE)
289
          || token->is_keyword(KEYWORD_FUNC)
290
          || token->is_keyword(KEYWORD_MAP)
291
          || token->is_keyword(KEYWORD_STRUCT)
292
          || token->is_op(OPERATOR_MULT)
293
          || token->is_op(OPERATOR_LPAREN));
294
}
295
 
296
// TypeName = QualifiedIdent .
297
 
298
// If MAY_BE_NIL is true, then an identifier with the value of the
299
// predefined constant nil is accepted, returning the nil type.
300
 
301
Type*
302
Parse::type_name(bool issue_error)
303
{
304
  Location location = this->location();
305
 
306
  std::string name;
307
  Named_object* package;
308
  if (!this->qualified_ident(&name, &package))
309
    return Type::make_error_type();
310
 
311
  Named_object* named_object;
312
  if (package == NULL)
313
    named_object = this->gogo_->lookup(name, NULL);
314
  else
315
    {
316
      named_object = package->package_value()->lookup(name);
317
      if (named_object == NULL
318
          && issue_error
319
          && package->name() != this->gogo_->package_name())
320
        {
321
          // Check whether the name is there but hidden.
322
          std::string s = ('.' + package->package_value()->unique_prefix()
323
                           + '.' + package->package_value()->name()
324
                           + '.' + name);
325
          named_object = package->package_value()->lookup(s);
326
          if (named_object != NULL)
327
            {
328
              const std::string& packname(package->package_value()->name());
329
              error_at(location, "invalid reference to hidden type %<%s.%s%>",
330
                       Gogo::message_name(packname).c_str(),
331
                       Gogo::message_name(name).c_str());
332
              issue_error = false;
333
            }
334
        }
335
    }
336
 
337
  bool ok = true;
338
  if (named_object == NULL)
339
    {
340
      if (package == NULL)
341
        named_object = this->gogo_->add_unknown_name(name, location);
342
      else
343
        {
344
          const std::string& packname(package->package_value()->name());
345
          error_at(location, "reference to undefined identifier %<%s.%s%>",
346
                   Gogo::message_name(packname).c_str(),
347
                   Gogo::message_name(name).c_str());
348
          issue_error = false;
349
          ok = false;
350
        }
351
    }
352
  else if (named_object->is_type())
353
    {
354
      if (!named_object->type_value()->is_visible())
355
        ok = false;
356
    }
357
  else if (named_object->is_unknown() || named_object->is_type_declaration())
358
    ;
359
  else
360
    ok = false;
361
 
362
  if (!ok)
363
    {
364
      if (issue_error)
365
        error_at(location, "expected type");
366
      return Type::make_error_type();
367
    }
368
 
369
  if (named_object->is_type())
370
    return named_object->type_value();
371
  else if (named_object->is_unknown() || named_object->is_type_declaration())
372
    return Type::make_forward_declaration(named_object);
373
  else
374
    go_unreachable();
375
}
376
 
377
// ArrayType = "[" [ ArrayLength ] "]" ElementType .
378
// ArrayLength = Expression .
379
// ElementType = CompleteType .
380
 
381
Type*
382
Parse::array_type(bool may_use_ellipsis)
383
{
384
  go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
385
  const Token* token = this->advance_token();
386
 
387
  Expression* length = NULL;
388
  if (token->is_op(OPERATOR_RSQUARE))
389
    this->advance_token();
390
  else
391
    {
392
      if (!token->is_op(OPERATOR_ELLIPSIS))
393
        length = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
394
      else if (may_use_ellipsis)
395
        {
396
          // An ellipsis is used in composite literals to represent a
397
          // fixed array of the size of the number of elements.  We
398
          // use a length of nil to represent this, and change the
399
          // length when parsing the composite literal.
400
          length = Expression::make_nil(this->location());
401
          this->advance_token();
402
        }
403
      else
404
        {
405
          error_at(this->location(),
406
                   "use of %<[...]%> outside of array literal");
407
          length = Expression::make_error(this->location());
408
          this->advance_token();
409
        }
410
      if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
411
        {
412
          error_at(this->location(), "expected %<]%>");
413
          return Type::make_error_type();
414
        }
415
      this->advance_token();
416
    }
417
 
418
  Type* element_type = this->type();
419
 
420
  return Type::make_array_type(element_type, length);
421
}
422
 
423
// MapType = "map" "[" KeyType "]" ValueType .
424
// KeyType = CompleteType .
425
// ValueType = CompleteType .
426
 
427
Type*
428
Parse::map_type()
429
{
430
  Location location = this->location();
431
  go_assert(this->peek_token()->is_keyword(KEYWORD_MAP));
432
  if (!this->advance_token()->is_op(OPERATOR_LSQUARE))
433
    {
434
      error_at(this->location(), "expected %<[%>");
435
      return Type::make_error_type();
436
    }
437
  this->advance_token();
438
 
439
  Type* key_type = this->type();
440
 
441
  if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
442
    {
443
      error_at(this->location(), "expected %<]%>");
444
      return Type::make_error_type();
445
    }
446
  this->advance_token();
447
 
448
  Type* value_type = this->type();
449
 
450
  if (key_type->is_error_type() || value_type->is_error_type())
451
    return Type::make_error_type();
452
 
453
  return Type::make_map_type(key_type, value_type, location);
454
}
455
 
456
// StructType     = "struct" "{" { FieldDecl ";" } "}" .
457
 
458
Type*
459
Parse::struct_type()
460
{
461
  go_assert(this->peek_token()->is_keyword(KEYWORD_STRUCT));
462
  Location location = this->location();
463
  if (!this->advance_token()->is_op(OPERATOR_LCURLY))
464
    {
465
      Location token_loc = this->location();
466
      if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
467
          && this->advance_token()->is_op(OPERATOR_LCURLY))
468
        error_at(token_loc, "unexpected semicolon or newline before %<{%>");
469
      else
470
        {
471
          error_at(this->location(), "expected %<{%>");
472
          return Type::make_error_type();
473
        }
474
    }
475
  this->advance_token();
476
 
477
  Struct_field_list* sfl = new Struct_field_list;
478
  while (!this->peek_token()->is_op(OPERATOR_RCURLY))
479
    {
480
      this->field_decl(sfl);
481
      if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
482
        this->advance_token();
483
      else if (!this->peek_token()->is_op(OPERATOR_RCURLY))
484
        {
485
          error_at(this->location(), "expected %<;%> or %<}%> or newline");
486
          if (!this->skip_past_error(OPERATOR_RCURLY))
487
            return Type::make_error_type();
488
        }
489
    }
490
  this->advance_token();
491
 
492
  for (Struct_field_list::const_iterator pi = sfl->begin();
493
       pi != sfl->end();
494
       ++pi)
495
    {
496
      if (pi->type()->is_error_type())
497
        return pi->type();
498
      for (Struct_field_list::const_iterator pj = pi + 1;
499
           pj != sfl->end();
500
           ++pj)
501
        {
502
          if (pi->field_name() == pj->field_name()
503
              && !Gogo::is_sink_name(pi->field_name()))
504
            error_at(pi->location(), "duplicate field name %<%s%>",
505
                     Gogo::message_name(pi->field_name()).c_str());
506
        }
507
    }
508
 
509
  return Type::make_struct_type(sfl, location);
510
}
511
 
512
// FieldDecl = (IdentifierList CompleteType | TypeName) [ Tag ] .
513
// Tag = string_lit .
514
 
515
void
516
Parse::field_decl(Struct_field_list* sfl)
517
{
518
  const Token* token = this->peek_token();
519
  Location location = token->location();
520
  bool is_anonymous;
521
  bool is_anonymous_pointer;
522
  if (token->is_op(OPERATOR_MULT))
523
    {
524
      is_anonymous = true;
525
      is_anonymous_pointer = true;
526
    }
527
  else if (token->is_identifier())
528
    {
529
      std::string id = token->identifier();
530
      bool is_id_exported = token->is_identifier_exported();
531
      Location id_location = token->location();
532
      token = this->advance_token();
533
      is_anonymous = (token->is_op(OPERATOR_SEMICOLON)
534
                      || token->is_op(OPERATOR_RCURLY)
535
                      || token->is_op(OPERATOR_DOT)
536
                      || token->is_string());
537
      is_anonymous_pointer = false;
538
      this->unget_token(Token::make_identifier_token(id, is_id_exported,
539
                                                     id_location));
540
    }
541
  else
542
    {
543
      error_at(this->location(), "expected field name");
544
      this->gogo_->mark_locals_used();
545
      while (!token->is_op(OPERATOR_SEMICOLON)
546
             && !token->is_op(OPERATOR_RCURLY)
547
             && !token->is_eof())
548
        token = this->advance_token();
549
      return;
550
    }
551
 
552
  if (is_anonymous)
553
    {
554
      if (is_anonymous_pointer)
555
        {
556
          this->advance_token();
557
          if (!this->peek_token()->is_identifier())
558
            {
559
              error_at(this->location(), "expected field name");
560
              this->gogo_->mark_locals_used();
561
              while (!token->is_op(OPERATOR_SEMICOLON)
562
                     && !token->is_op(OPERATOR_RCURLY)
563
                     && !token->is_eof())
564
                token = this->advance_token();
565
              return;
566
            }
567
        }
568
      Type* type = this->type_name(true);
569
 
570
      std::string tag;
571
      if (this->peek_token()->is_string())
572
        {
573
          tag = this->peek_token()->string_value();
574
          this->advance_token();
575
        }
576
 
577
      if (!type->is_error_type())
578
        {
579
          if (is_anonymous_pointer)
580
            type = Type::make_pointer_type(type);
581
          sfl->push_back(Struct_field(Typed_identifier("", type, location)));
582
          if (!tag.empty())
583
            sfl->back().set_tag(tag);
584
        }
585
    }
586
  else
587
    {
588
      Typed_identifier_list til;
589
      while (true)
590
        {
591
          token = this->peek_token();
592
          if (!token->is_identifier())
593
            {
594
              error_at(this->location(), "expected identifier");
595
              return;
596
            }
597
          std::string name =
598
            this->gogo_->pack_hidden_name(token->identifier(),
599
                                          token->is_identifier_exported());
600
          til.push_back(Typed_identifier(name, NULL, token->location()));
601
          if (!this->advance_token()->is_op(OPERATOR_COMMA))
602
            break;
603
          this->advance_token();
604
        }
605
 
606
      Type* type = this->type();
607
 
608
      std::string tag;
609
      if (this->peek_token()->is_string())
610
        {
611
          tag = this->peek_token()->string_value();
612
          this->advance_token();
613
        }
614
 
615
      for (Typed_identifier_list::iterator p = til.begin();
616
           p != til.end();
617
           ++p)
618
        {
619
          p->set_type(type);
620
          sfl->push_back(Struct_field(*p));
621
          if (!tag.empty())
622
            sfl->back().set_tag(tag);
623
        }
624
    }
625
}
626
 
627
// PointerType = "*" Type .
628
 
629
Type*
630
Parse::pointer_type()
631
{
632
  go_assert(this->peek_token()->is_op(OPERATOR_MULT));
633
  this->advance_token();
634
  Type* type = this->type();
635
  if (type->is_error_type())
636
    return type;
637
  return Type::make_pointer_type(type);
638
}
639
 
640
// ChannelType   = Channel | SendChannel | RecvChannel .
641
// Channel       = "chan" ElementType .
642
// SendChannel   = "chan" "<-" ElementType .
643
// RecvChannel   = "<-" "chan" ElementType .
644
 
645
Type*
646
Parse::channel_type()
647
{
648
  const Token* token = this->peek_token();
649
  bool send = true;
650
  bool receive = true;
651
  if (token->is_op(OPERATOR_CHANOP))
652
    {
653
      if (!this->advance_token()->is_keyword(KEYWORD_CHAN))
654
        {
655
          error_at(this->location(), "expected %<chan%>");
656
          return Type::make_error_type();
657
        }
658
      send = false;
659
      this->advance_token();
660
    }
661
  else
662
    {
663
      go_assert(token->is_keyword(KEYWORD_CHAN));
664
      if (this->advance_token()->is_op(OPERATOR_CHANOP))
665
        {
666
          receive = false;
667
          this->advance_token();
668
        }
669
    }
670
 
671
  // Better error messages for the common error of omitting the
672
  // channel element type.
673
  if (!this->type_may_start_here())
674
    {
675
      token = this->peek_token();
676
      if (token->is_op(OPERATOR_RCURLY))
677
        error_at(this->location(), "unexpected %<}%> in channel type");
678
      else if (token->is_op(OPERATOR_RPAREN))
679
        error_at(this->location(), "unexpected %<)%> in channel type");
680
      else if (token->is_op(OPERATOR_COMMA))
681
        error_at(this->location(), "unexpected comma in channel type");
682
      else
683
        error_at(this->location(), "expected channel element type");
684
      return Type::make_error_type();
685
    }
686
 
687
  Type* element_type = this->type();
688
  return Type::make_channel_type(send, receive, element_type);
689
}
690
 
691
// Give an error for a duplicate parameter or receiver name.
692
 
693
void
694
Parse::check_signature_names(const Typed_identifier_list* params,
695
                             Parse::Names* names)
696
{
697
  for (Typed_identifier_list::const_iterator p = params->begin();
698
       p != params->end();
699
       ++p)
700
    {
701
      if (p->name().empty() || Gogo::is_sink_name(p->name()))
702
        continue;
703
      std::pair<std::string, const Typed_identifier*> val =
704
        std::make_pair(p->name(), &*p);
705
      std::pair<Parse::Names::iterator, bool> ins = names->insert(val);
706
      if (!ins.second)
707
        {
708
          error_at(p->location(), "redefinition of %qs",
709
                   Gogo::message_name(p->name()).c_str());
710
          inform(ins.first->second->location(),
711
                 "previous definition of %qs was here",
712
                 Gogo::message_name(p->name()).c_str());
713
        }
714
    }
715
}
716
 
717
// Signature      = Parameters [ Result ] .
718
 
719
// RECEIVER is the receiver if there is one, or NULL.  LOCATION is the
720
// location of the start of the type.
721
 
722
// This returns NULL on a parse error.
723
 
724
Function_type*
725
Parse::signature(Typed_identifier* receiver, Location location)
726
{
727
  bool is_varargs = false;
728
  Typed_identifier_list* params;
729
  bool params_ok = this->parameters(&params, &is_varargs);
730
 
731
  Typed_identifier_list* results = NULL;
732
  if (this->peek_token()->is_op(OPERATOR_LPAREN)
733
      || this->type_may_start_here())
734
    {
735
      if (!this->result(&results))
736
        return NULL;
737
    }
738
 
739
  if (!params_ok)
740
    return NULL;
741
 
742
  Parse::Names names;
743
  if (params != NULL)
744
    this->check_signature_names(params, &names);
745
  if (results != NULL)
746
    this->check_signature_names(results, &names);
747
 
748
  Function_type* ret = Type::make_function_type(receiver, params, results,
749
                                                location);
750
  if (is_varargs)
751
    ret->set_is_varargs();
752
  return ret;
753
}
754
 
755
// Parameters     = "(" [ ParameterList [ "," ] ] ")" .
756
 
757
// This returns false on a parse error.
758
 
759
bool
760
Parse::parameters(Typed_identifier_list** pparams, bool* is_varargs)
761
{
762
  *pparams = NULL;
763
 
764
  if (!this->peek_token()->is_op(OPERATOR_LPAREN))
765
    {
766
      error_at(this->location(), "expected %<(%>");
767
      return false;
768
    }
769
 
770
  Typed_identifier_list* params = NULL;
771
  bool saw_error = false;
772
 
773
  const Token* token = this->advance_token();
774
  if (!token->is_op(OPERATOR_RPAREN))
775
    {
776
      params = this->parameter_list(is_varargs);
777
      if (params == NULL)
778
        saw_error = true;
779
      token = this->peek_token();
780
    }
781
 
782
  // The optional trailing comma is picked up in parameter_list.
783
 
784
  if (!token->is_op(OPERATOR_RPAREN))
785
    error_at(this->location(), "expected %<)%>");
786
  else
787
    this->advance_token();
788
 
789
  if (saw_error)
790
    return false;
791
 
792
  *pparams = params;
793
  return true;
794
}
795
 
796
// ParameterList  = ParameterDecl { "," ParameterDecl } .
797
 
798
// This sets *IS_VARARGS if the list ends with an ellipsis.
799
// IS_VARARGS will be NULL if varargs are not permitted.
800
 
801
// We pick up an optional trailing comma.
802
 
803
// This returns NULL if some error is seen.
804
 
805
Typed_identifier_list*
806
Parse::parameter_list(bool* is_varargs)
807
{
808
  Location location = this->location();
809
  Typed_identifier_list* ret = new Typed_identifier_list();
810
 
811
  bool saw_error = false;
812
 
813
  // If we see an identifier and then a comma, then we don't know
814
  // whether we are looking at a list of identifiers followed by a
815
  // type, or a list of types given by name.  We have to do an
816
  // arbitrary lookahead to figure it out.
817
 
818
  bool parameters_have_names;
819
  const Token* token = this->peek_token();
820
  if (!token->is_identifier())
821
    {
822
      // This must be a type which starts with something like '*'.
823
      parameters_have_names = false;
824
    }
825
  else
826
    {
827
      std::string name = token->identifier();
828
      bool is_exported = token->is_identifier_exported();
829
      Location location = token->location();
830
      token = this->advance_token();
831
      if (!token->is_op(OPERATOR_COMMA))
832
        {
833
          if (token->is_op(OPERATOR_DOT))
834
            {
835
              // This is a qualified identifier, which must turn out
836
              // to be a type.
837
              parameters_have_names = false;
838
            }
839
          else if (token->is_op(OPERATOR_RPAREN))
840
            {
841
              // A single identifier followed by a parenthesis must be
842
              // a type name.
843
              parameters_have_names = false;
844
            }
845
          else
846
            {
847
              // An identifier followed by something other than a
848
              // comma or a dot or a right parenthesis must be a
849
              // parameter name followed by a type.
850
              parameters_have_names = true;
851
            }
852
 
853
          this->unget_token(Token::make_identifier_token(name, is_exported,
854
                                                         location));
855
        }
856
      else
857
        {
858
          // An identifier followed by a comma may be the first in a
859
          // list of parameter names followed by a type, or it may be
860
          // the first in a list of types without parameter names.  To
861
          // find out we gather as many identifiers separated by
862
          // commas as we can.
863
          std::string id_name = this->gogo_->pack_hidden_name(name,
864
                                                              is_exported);
865
          ret->push_back(Typed_identifier(id_name, NULL, location));
866
          bool just_saw_comma = true;
867
          while (this->advance_token()->is_identifier())
868
            {
869
              name = this->peek_token()->identifier();
870
              is_exported = this->peek_token()->is_identifier_exported();
871
              location = this->peek_token()->location();
872
              id_name = this->gogo_->pack_hidden_name(name, is_exported);
873
              ret->push_back(Typed_identifier(id_name, NULL, location));
874
              if (!this->advance_token()->is_op(OPERATOR_COMMA))
875
                {
876
                  just_saw_comma = false;
877
                  break;
878
                }
879
            }
880
 
881
          if (just_saw_comma)
882
            {
883
              // We saw ID1 "," ID2 "," followed by something which
884
              // was not an identifier.  We must be seeing the start
885
              // of a type, and ID1 and ID2 must be types, and the
886
              // parameters don't have names.
887
              parameters_have_names = false;
888
            }
889
          else if (this->peek_token()->is_op(OPERATOR_RPAREN))
890
            {
891
              // We saw ID1 "," ID2 ")".  ID1 and ID2 must be types,
892
              // and the parameters don't have names.
893
              parameters_have_names = false;
894
            }
895
          else if (this->peek_token()->is_op(OPERATOR_DOT))
896
            {
897
              // We saw ID1 "," ID2 ".".  ID2 must be a package name,
898
              // ID1 must be a type, and the parameters don't have
899
              // names.
900
              parameters_have_names = false;
901
              this->unget_token(Token::make_identifier_token(name, is_exported,
902
                                                             location));
903
              ret->pop_back();
904
              just_saw_comma = true;
905
            }
906
          else
907
            {
908
              // We saw ID1 "," ID2 followed by something other than
909
              // ",", ".", or ")".  We must be looking at the start of
910
              // a type, and ID1 and ID2 must be parameter names.
911
              parameters_have_names = true;
912
            }
913
 
914
          if (parameters_have_names)
915
            {
916
              go_assert(!just_saw_comma);
917
              // We have just seen ID1, ID2 xxx.
918
              Type* type;
919
              if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
920
                type = this->type();
921
              else
922
                {
923
                  error_at(this->location(), "%<...%> only permits one name");
924
                  saw_error = true;
925
                  this->advance_token();
926
                  type = this->type();
927
                }
928
              for (size_t i = 0; i < ret->size(); ++i)
929
                ret->set_type(i, type);
930
              if (!this->peek_token()->is_op(OPERATOR_COMMA))
931
                return saw_error ? NULL : ret;
932
              if (this->advance_token()->is_op(OPERATOR_RPAREN))
933
                return saw_error ? NULL : ret;
934
            }
935
          else
936
            {
937
              Typed_identifier_list* tret = new Typed_identifier_list();
938
              for (Typed_identifier_list::const_iterator p = ret->begin();
939
                   p != ret->end();
940
                   ++p)
941
                {
942
                  Named_object* no = this->gogo_->lookup(p->name(), NULL);
943
                  Type* type;
944
                  if (no == NULL)
945
                    no = this->gogo_->add_unknown_name(p->name(),
946
                                                       p->location());
947
 
948
                  if (no->is_type())
949
                    type = no->type_value();
950
                  else if (no->is_unknown() || no->is_type_declaration())
951
                    type = Type::make_forward_declaration(no);
952
                  else
953
                    {
954
                      error_at(p->location(), "expected %<%s%> to be a type",
955
                               Gogo::message_name(p->name()).c_str());
956
                      saw_error = true;
957
                      type = Type::make_error_type();
958
                    }
959
                  tret->push_back(Typed_identifier("", type, p->location()));
960
                }
961
              delete ret;
962
              ret = tret;
963
              if (!just_saw_comma
964
                  || this->peek_token()->is_op(OPERATOR_RPAREN))
965
                return saw_error ? NULL : ret;
966
            }
967
        }
968
    }
969
 
970
  bool mix_error = false;
971
  this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
972
  while (this->peek_token()->is_op(OPERATOR_COMMA))
973
    {
974
      if (is_varargs != NULL && *is_varargs)
975
        {
976
          error_at(this->location(), "%<...%> must be last parameter");
977
          saw_error = true;
978
        }
979
      if (this->advance_token()->is_op(OPERATOR_RPAREN))
980
        break;
981
      this->parameter_decl(parameters_have_names, ret, is_varargs, &mix_error);
982
    }
983
  if (mix_error)
984
    {
985
      error_at(location, "invalid named/anonymous mix");
986
      saw_error = true;
987
    }
988
  if (saw_error)
989
    {
990
      delete ret;
991
      return NULL;
992
    }
993
  return ret;
994
}
995
 
996
// ParameterDecl  = [ IdentifierList ] [ "..." ] Type .
997
 
998
void
999
Parse::parameter_decl(bool parameters_have_names,
1000
                      Typed_identifier_list* til,
1001
                      bool* is_varargs,
1002
                      bool* mix_error)
1003
{
1004
  if (!parameters_have_names)
1005
    {
1006
      Type* type;
1007
      Location location = this->location();
1008
      if (!this->peek_token()->is_identifier())
1009
        {
1010
          if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1011
            type = this->type();
1012
          else
1013
            {
1014
              if (is_varargs == NULL)
1015
                error_at(this->location(), "invalid use of %<...%>");
1016
              else
1017
                *is_varargs = true;
1018
              this->advance_token();
1019
              if (is_varargs == NULL
1020
                  && this->peek_token()->is_op(OPERATOR_RPAREN))
1021
                type = Type::make_error_type();
1022
              else
1023
                {
1024
                  Type* element_type = this->type();
1025
                  type = Type::make_array_type(element_type, NULL);
1026
                }
1027
            }
1028
        }
1029
      else
1030
        {
1031
          type = this->type_name(false);
1032
          if (type->is_error_type()
1033
              || (!this->peek_token()->is_op(OPERATOR_COMMA)
1034
                  && !this->peek_token()->is_op(OPERATOR_RPAREN)))
1035
            {
1036
              *mix_error = true;
1037
              while (!this->peek_token()->is_op(OPERATOR_COMMA)
1038
                     && !this->peek_token()->is_op(OPERATOR_RPAREN))
1039
                this->advance_token();
1040
            }
1041
        }
1042
      if (!type->is_error_type())
1043
        til->push_back(Typed_identifier("", type, location));
1044
    }
1045
  else
1046
    {
1047
      size_t orig_count = til->size();
1048
      if (this->peek_token()->is_identifier())
1049
        this->identifier_list(til);
1050
      else
1051
        *mix_error = true;
1052
      size_t new_count = til->size();
1053
 
1054
      Type* type;
1055
      if (!this->peek_token()->is_op(OPERATOR_ELLIPSIS))
1056
        type = this->type();
1057
      else
1058
        {
1059
          if (is_varargs == NULL)
1060
            error_at(this->location(), "invalid use of %<...%>");
1061
          else if (new_count > orig_count + 1)
1062
            error_at(this->location(), "%<...%> only permits one name");
1063
          else
1064
            *is_varargs = true;
1065
          this->advance_token();
1066
          Type* element_type = this->type();
1067
          type = Type::make_array_type(element_type, NULL);
1068
        }
1069
      for (size_t i = orig_count; i < new_count; ++i)
1070
        til->set_type(i, type);
1071
    }
1072
}
1073
 
1074
// Result         = Parameters | Type .
1075
 
1076
// This returns false on a parse error.
1077
 
1078
bool
1079
Parse::result(Typed_identifier_list** presults)
1080
{
1081
  if (this->peek_token()->is_op(OPERATOR_LPAREN))
1082
    return this->parameters(presults, NULL);
1083
  else
1084
    {
1085
      Location location = this->location();
1086
      Type* type = this->type();
1087
      if (type->is_error_type())
1088
        {
1089
          *presults = NULL;
1090
          return false;
1091
        }
1092
      Typed_identifier_list* til = new Typed_identifier_list();
1093
      til->push_back(Typed_identifier("", type, location));
1094
      *presults = til;
1095
      return true;
1096
    }
1097
}
1098
 
1099
// Block = "{" [ StatementList ] "}" .
1100
 
1101
// Returns the location of the closing brace.
1102
 
1103
Location
1104
Parse::block()
1105
{
1106
  if (!this->peek_token()->is_op(OPERATOR_LCURLY))
1107
    {
1108
      Location loc = this->location();
1109
      if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1110
          && this->advance_token()->is_op(OPERATOR_LCURLY))
1111
        error_at(loc, "unexpected semicolon or newline before %<{%>");
1112
      else
1113
        {
1114
          error_at(this->location(), "expected %<{%>");
1115
          return Linemap::unknown_location();
1116
        }
1117
    }
1118
 
1119
  const Token* token = this->advance_token();
1120
 
1121
  if (!token->is_op(OPERATOR_RCURLY))
1122
    {
1123
      this->statement_list();
1124
      token = this->peek_token();
1125
      if (!token->is_op(OPERATOR_RCURLY))
1126
        {
1127
          if (!token->is_eof() || !saw_errors())
1128
            error_at(this->location(), "expected %<}%>");
1129
 
1130
          this->gogo_->mark_locals_used();
1131
 
1132
          // Skip ahead to the end of the block, in hopes of avoiding
1133
          // lots of meaningless errors.
1134
          Location ret = token->location();
1135
          int nest = 0;
1136
          while (!token->is_eof())
1137
            {
1138
              if (token->is_op(OPERATOR_LCURLY))
1139
                ++nest;
1140
              else if (token->is_op(OPERATOR_RCURLY))
1141
                {
1142
                  --nest;
1143
                  if (nest < 0)
1144
                    {
1145
                      this->advance_token();
1146
                      break;
1147
                    }
1148
                }
1149
              token = this->advance_token();
1150
              ret = token->location();
1151
            }
1152
          return ret;
1153
        }
1154
    }
1155
 
1156
  Location ret = token->location();
1157
  this->advance_token();
1158
  return ret;
1159
}
1160
 
1161
// InterfaceType      = "interface" "{" [ MethodSpecList ] "}" .
1162
// MethodSpecList     = MethodSpec { ";" MethodSpec } [ ";" ] .
1163
 
1164
Type*
1165
Parse::interface_type()
1166
{
1167
  go_assert(this->peek_token()->is_keyword(KEYWORD_INTERFACE));
1168
  Location location = this->location();
1169
 
1170
  if (!this->advance_token()->is_op(OPERATOR_LCURLY))
1171
    {
1172
      Location token_loc = this->location();
1173
      if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1174
          && this->advance_token()->is_op(OPERATOR_LCURLY))
1175
        error_at(token_loc, "unexpected semicolon or newline before %<{%>");
1176
      else
1177
        {
1178
          error_at(this->location(), "expected %<{%>");
1179
          return Type::make_error_type();
1180
        }
1181
    }
1182
  this->advance_token();
1183
 
1184
  Typed_identifier_list* methods = new Typed_identifier_list();
1185
  if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1186
    {
1187
      this->method_spec(methods);
1188
      while (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1189
        {
1190
          if (this->advance_token()->is_op(OPERATOR_RCURLY))
1191
            break;
1192
          this->method_spec(methods);
1193
        }
1194
      if (!this->peek_token()->is_op(OPERATOR_RCURLY))
1195
        {
1196
          error_at(this->location(), "expected %<}%>");
1197
          while (!this->advance_token()->is_op(OPERATOR_RCURLY))
1198
            {
1199
              if (this->peek_token()->is_eof())
1200
                return Type::make_error_type();
1201
            }
1202
        }
1203
    }
1204
  this->advance_token();
1205
 
1206
  if (methods->empty())
1207
    {
1208
      delete methods;
1209
      methods = NULL;
1210
    }
1211
 
1212
  Interface_type* ret = Type::make_interface_type(methods, location);
1213
  this->gogo_->record_interface_type(ret);
1214
  return ret;
1215
}
1216
 
1217
// MethodSpec         = MethodName Signature | InterfaceTypeName .
1218
// MethodName         = identifier .
1219
// InterfaceTypeName  = TypeName .
1220
 
1221
void
1222
Parse::method_spec(Typed_identifier_list* methods)
1223
{
1224
  const Token* token = this->peek_token();
1225
  if (!token->is_identifier())
1226
    {
1227
      error_at(this->location(), "expected identifier");
1228
      return;
1229
    }
1230
 
1231
  std::string name = token->identifier();
1232
  bool is_exported = token->is_identifier_exported();
1233
  Location location = token->location();
1234
 
1235
  if (this->advance_token()->is_op(OPERATOR_LPAREN))
1236
    {
1237
      // This is a MethodName.
1238
      name = this->gogo_->pack_hidden_name(name, is_exported);
1239
      Type* type = this->signature(NULL, location);
1240
      if (type == NULL)
1241
        return;
1242
      methods->push_back(Typed_identifier(name, type, location));
1243
    }
1244
  else
1245
    {
1246
      this->unget_token(Token::make_identifier_token(name, is_exported,
1247
                                                     location));
1248
      Type* type = this->type_name(false);
1249
      if (type->is_error_type()
1250
          || (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1251
              && !this->peek_token()->is_op(OPERATOR_RCURLY)))
1252
        {
1253
          if (this->peek_token()->is_op(OPERATOR_COMMA))
1254
            error_at(this->location(),
1255
                     "name list not allowed in interface type");
1256
          else
1257
            error_at(location, "expected signature or type name");
1258
          this->gogo_->mark_locals_used();
1259
          token = this->peek_token();
1260
          while (!token->is_eof()
1261
                 && !token->is_op(OPERATOR_SEMICOLON)
1262
                 && !token->is_op(OPERATOR_RCURLY))
1263
            token = this->advance_token();
1264
          return;
1265
        }
1266
      // This must be an interface type, but we can't check that now.
1267
      // We check it and pull out the methods in
1268
      // Interface_type::do_verify.
1269
      methods->push_back(Typed_identifier("", type, location));
1270
    }
1271
}
1272
 
1273
// Declaration = ConstDecl | TypeDecl | VarDecl | FunctionDecl | MethodDecl .
1274
 
1275
void
1276
Parse::declaration()
1277
{
1278
  const Token* token = this->peek_token();
1279
  if (token->is_keyword(KEYWORD_CONST))
1280
    this->const_decl();
1281
  else if (token->is_keyword(KEYWORD_TYPE))
1282
    this->type_decl();
1283
  else if (token->is_keyword(KEYWORD_VAR))
1284
    this->var_decl();
1285
  else if (token->is_keyword(KEYWORD_FUNC))
1286
    this->function_decl();
1287
  else
1288
    {
1289
      error_at(this->location(), "expected declaration");
1290
      this->advance_token();
1291
    }
1292
}
1293
 
1294
bool
1295
Parse::declaration_may_start_here()
1296
{
1297
  const Token* token = this->peek_token();
1298
  return (token->is_keyword(KEYWORD_CONST)
1299
          || token->is_keyword(KEYWORD_TYPE)
1300
          || token->is_keyword(KEYWORD_VAR)
1301
          || token->is_keyword(KEYWORD_FUNC));
1302
}
1303
 
1304
// Decl<P> = P | "(" [ List<P> ] ")" .
1305
 
1306
void
1307
Parse::decl(void (Parse::*pfn)(void*), void* varg)
1308
{
1309
  if (this->peek_token()->is_eof())
1310
    {
1311
      if (!saw_errors())
1312
        error_at(this->location(), "unexpected end of file");
1313
      return;
1314
    }
1315
 
1316
  if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1317
    (this->*pfn)(varg);
1318
  else
1319
    {
1320
      if (!this->advance_token()->is_op(OPERATOR_RPAREN))
1321
        {
1322
          this->list(pfn, varg, true);
1323
          if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1324
            {
1325
              error_at(this->location(), "missing %<)%>");
1326
              while (!this->advance_token()->is_op(OPERATOR_RPAREN))
1327
                {
1328
                  if (this->peek_token()->is_eof())
1329
                    return;
1330
                }
1331
            }
1332
        }
1333
      this->advance_token();
1334
    }
1335
}
1336
 
1337
// List<P> = P { ";" P } [ ";" ] .
1338
 
1339
// In order to pick up the trailing semicolon we need to know what
1340
// might follow.  This is either a '}' or a ')'.
1341
 
1342
void
1343
Parse::list(void (Parse::*pfn)(void*), void* varg, bool follow_is_paren)
1344
{
1345
  (this->*pfn)(varg);
1346
  Operator follow = follow_is_paren ? OPERATOR_RPAREN : OPERATOR_RCURLY;
1347
  while (this->peek_token()->is_op(OPERATOR_SEMICOLON)
1348
         || this->peek_token()->is_op(OPERATOR_COMMA))
1349
    {
1350
      if (this->peek_token()->is_op(OPERATOR_COMMA))
1351
        error_at(this->location(), "unexpected comma");
1352
      if (this->advance_token()->is_op(follow))
1353
        break;
1354
      (this->*pfn)(varg);
1355
    }
1356
}
1357
 
1358
// ConstDecl      = "const" ( ConstSpec | "(" { ConstSpec ";" } ")" ) .
1359
 
1360
void
1361
Parse::const_decl()
1362
{
1363
  go_assert(this->peek_token()->is_keyword(KEYWORD_CONST));
1364
  this->advance_token();
1365
  this->reset_iota();
1366
 
1367
  Type* last_type = NULL;
1368
  Expression_list* last_expr_list = NULL;
1369
 
1370
  if (!this->peek_token()->is_op(OPERATOR_LPAREN))
1371
    this->const_spec(&last_type, &last_expr_list);
1372
  else
1373
    {
1374
      this->advance_token();
1375
      while (!this->peek_token()->is_op(OPERATOR_RPAREN))
1376
        {
1377
          this->const_spec(&last_type, &last_expr_list);
1378
          if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
1379
            this->advance_token();
1380
          else if (!this->peek_token()->is_op(OPERATOR_RPAREN))
1381
            {
1382
              error_at(this->location(), "expected %<;%> or %<)%> or newline");
1383
              if (!this->skip_past_error(OPERATOR_RPAREN))
1384
                return;
1385
            }
1386
        }
1387
      this->advance_token();
1388
    }
1389
 
1390
  if (last_expr_list != NULL)
1391
    delete last_expr_list;
1392
}
1393
 
1394
// ConstSpec = IdentifierList [ [ CompleteType ] "=" ExpressionList ] .
1395
 
1396
void
1397
Parse::const_spec(Type** last_type, Expression_list** last_expr_list)
1398
{
1399
  Typed_identifier_list til;
1400
  this->identifier_list(&til);
1401
 
1402
  Type* type = NULL;
1403
  if (this->type_may_start_here())
1404
    {
1405
      type = this->type();
1406
      *last_type = NULL;
1407
      *last_expr_list = NULL;
1408
    }
1409
 
1410
  Expression_list *expr_list;
1411
  if (!this->peek_token()->is_op(OPERATOR_EQ))
1412
    {
1413
      if (*last_expr_list == NULL)
1414
        {
1415
          error_at(this->location(), "expected %<=%>");
1416
          return;
1417
        }
1418
      type = *last_type;
1419
      expr_list = new Expression_list;
1420
      for (Expression_list::const_iterator p = (*last_expr_list)->begin();
1421
           p != (*last_expr_list)->end();
1422
           ++p)
1423
        expr_list->push_back((*p)->copy());
1424
    }
1425
  else
1426
    {
1427
      this->advance_token();
1428
      expr_list = this->expression_list(NULL, false);
1429
      *last_type = type;
1430
      if (*last_expr_list != NULL)
1431
        delete *last_expr_list;
1432
      *last_expr_list = expr_list;
1433
    }
1434
 
1435
  Expression_list::const_iterator pe = expr_list->begin();
1436
  for (Typed_identifier_list::iterator pi = til.begin();
1437
       pi != til.end();
1438
       ++pi, ++pe)
1439
    {
1440
      if (pe == expr_list->end())
1441
        {
1442
          error_at(this->location(), "not enough initializers");
1443
          return;
1444
        }
1445
      if (type != NULL)
1446
        pi->set_type(type);
1447
 
1448
      if (!Gogo::is_sink_name(pi->name()))
1449
        this->gogo_->add_constant(*pi, *pe, this->iota_value());
1450
    }
1451
  if (pe != expr_list->end())
1452
    error_at(this->location(), "too many initializers");
1453
 
1454
  this->increment_iota();
1455
 
1456
  return;
1457
}
1458
 
1459
// TypeDecl = "type" Decl<TypeSpec> .
1460
 
1461
void
1462
Parse::type_decl()
1463
{
1464
  go_assert(this->peek_token()->is_keyword(KEYWORD_TYPE));
1465
  this->advance_token();
1466
  this->decl(&Parse::type_spec, NULL);
1467
}
1468
 
1469
// TypeSpec = identifier Type .
1470
 
1471
void
1472
Parse::type_spec(void*)
1473
{
1474
  const Token* token = this->peek_token();
1475
  if (!token->is_identifier())
1476
    {
1477
      error_at(this->location(), "expected identifier");
1478
      return;
1479
    }
1480
  std::string name = token->identifier();
1481
  bool is_exported = token->is_identifier_exported();
1482
  Location location = token->location();
1483
  token = this->advance_token();
1484
 
1485
  // The scope of the type name starts at the point where the
1486
  // identifier appears in the source code.  We implement this by
1487
  // declaring the type before we read the type definition.
1488
  Named_object* named_type = NULL;
1489
  if (name != "_")
1490
    {
1491
      name = this->gogo_->pack_hidden_name(name, is_exported);
1492
      named_type = this->gogo_->declare_type(name, location);
1493
    }
1494
 
1495
  Type* type;
1496
  if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
1497
    type = this->type();
1498
  else
1499
    {
1500
      error_at(this->location(),
1501
               "unexpected semicolon or newline in type declaration");
1502
      type = Type::make_error_type();
1503
      this->advance_token();
1504
    }
1505
 
1506
  if (type->is_error_type())
1507
    {
1508
      this->gogo_->mark_locals_used();
1509
      while (!this->peek_token()->is_op(OPERATOR_SEMICOLON)
1510
             && !this->peek_token()->is_eof())
1511
        this->advance_token();
1512
    }
1513
 
1514
  if (name != "_")
1515
    {
1516
      if (named_type->is_type_declaration())
1517
        {
1518
          Type* ftype = type->forwarded();
1519
          if (ftype->forward_declaration_type() != NULL
1520
              && (ftype->forward_declaration_type()->named_object()
1521
                  == named_type))
1522
            {
1523
              error_at(location, "invalid recursive type");
1524
              type = Type::make_error_type();
1525
            }
1526
 
1527
          this->gogo_->define_type(named_type,
1528
                                   Type::make_named_type(named_type, type,
1529
                                                         location));
1530
          go_assert(named_type->package() == NULL);
1531
        }
1532
      else
1533
        {
1534
          // This will probably give a redefinition error.
1535
          this->gogo_->add_type(name, type, location);
1536
        }
1537
    }
1538
}
1539
 
1540
// VarDecl = "var" Decl<VarSpec> .
1541
 
1542
void
1543
Parse::var_decl()
1544
{
1545
  go_assert(this->peek_token()->is_keyword(KEYWORD_VAR));
1546
  this->advance_token();
1547
  this->decl(&Parse::var_spec, NULL);
1548
}
1549
 
1550
// VarSpec = IdentifierList
1551
//             ( CompleteType [ "=" ExpressionList ] | "=" ExpressionList ) .
1552
 
1553
void
1554
Parse::var_spec(void*)
1555
{
1556
  // Get the variable names.
1557
  Typed_identifier_list til;
1558
  this->identifier_list(&til);
1559
 
1560
  Location location = this->location();
1561
 
1562
  Type* type = NULL;
1563
  Expression_list* init = NULL;
1564
  if (!this->peek_token()->is_op(OPERATOR_EQ))
1565
    {
1566
      type = this->type();
1567
      if (type->is_error_type())
1568
        {
1569
          this->gogo_->mark_locals_used();
1570
          while (!this->peek_token()->is_op(OPERATOR_EQ)
1571
                 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
1572
                 && !this->peek_token()->is_eof())
1573
            this->advance_token();
1574
        }
1575
      if (this->peek_token()->is_op(OPERATOR_EQ))
1576
        {
1577
          this->advance_token();
1578
          init = this->expression_list(NULL, false);
1579
        }
1580
    }
1581
  else
1582
    {
1583
      this->advance_token();
1584
      init = this->expression_list(NULL, false);
1585
    }
1586
 
1587
  this->init_vars(&til, type, init, false, location);
1588
 
1589
  if (init != NULL)
1590
    delete init;
1591
}
1592
 
1593
// Create variables.  TIL is a list of variable names.  If TYPE is not
1594
// NULL, it is the type of all the variables.  If INIT is not NULL, it
1595
// is an initializer list for the variables.
1596
 
1597
void
1598
Parse::init_vars(const Typed_identifier_list* til, Type* type,
1599
                 Expression_list* init, bool is_coloneq,
1600
                 Location location)
1601
{
1602
  // Check for an initialization which can yield multiple values.
1603
  if (init != NULL && init->size() == 1 && til->size() > 1)
1604
    {
1605
      if (this->init_vars_from_call(til, type, *init->begin(), is_coloneq,
1606
                                    location))
1607
        return;
1608
      if (this->init_vars_from_map(til, type, *init->begin(), is_coloneq,
1609
                                   location))
1610
        return;
1611
      if (this->init_vars_from_receive(til, type, *init->begin(), is_coloneq,
1612
                                       location))
1613
        return;
1614
      if (this->init_vars_from_type_guard(til, type, *init->begin(),
1615
                                          is_coloneq, location))
1616
        return;
1617
    }
1618
 
1619
  if (init != NULL && init->size() != til->size())
1620
    {
1621
      if (init->empty() || !init->front()->is_error_expression())
1622
        error_at(location, "wrong number of initializations");
1623
      init = NULL;
1624
      if (type == NULL)
1625
        type = Type::make_error_type();
1626
    }
1627
 
1628
  // Note that INIT was already parsed with the old name bindings, so
1629
  // we don't have to worry that it will accidentally refer to the
1630
  // newly declared variables.
1631
 
1632
  Expression_list::const_iterator pexpr;
1633
  if (init != NULL)
1634
    pexpr = init->begin();
1635
  bool any_new = false;
1636
  for (Typed_identifier_list::const_iterator p = til->begin();
1637
       p != til->end();
1638
       ++p)
1639
    {
1640
      if (init != NULL)
1641
        go_assert(pexpr != init->end());
1642
      this->init_var(*p, type, init == NULL ? NULL : *pexpr, is_coloneq,
1643
                     false, &any_new);
1644
      if (init != NULL)
1645
        ++pexpr;
1646
    }
1647
  if (init != NULL)
1648
    go_assert(pexpr == init->end());
1649
  if (is_coloneq && !any_new)
1650
    error_at(location, "variables redeclared but no variable is new");
1651
}
1652
 
1653
// See if we need to initialize a list of variables from a function
1654
// call.  This returns true if we have set up the variables and the
1655
// initialization.
1656
 
1657
bool
1658
Parse::init_vars_from_call(const Typed_identifier_list* vars, Type* type,
1659
                           Expression* expr, bool is_coloneq,
1660
                           Location location)
1661
{
1662
  Call_expression* call = expr->call_expression();
1663
  if (call == NULL)
1664
    return false;
1665
 
1666
  // This is a function call.  We can't check here whether it returns
1667
  // the right number of values, but it might.  Declare the variables,
1668
  // and then assign the results of the call to them.
1669
 
1670
  unsigned int index = 0;
1671
  bool any_new = false;
1672
  for (Typed_identifier_list::const_iterator pv = vars->begin();
1673
       pv != vars->end();
1674
       ++pv, ++index)
1675
    {
1676
      Expression* init = Expression::make_call_result(call, index);
1677
      this->init_var(*pv, type, init, is_coloneq, false, &any_new);
1678
    }
1679
 
1680
  if (is_coloneq && !any_new)
1681
    error_at(location, "variables redeclared but no variable is new");
1682
 
1683
  return true;
1684
}
1685
 
1686
// See if we need to initialize a pair of values from a map index
1687
// expression.  This returns true if we have set up the variables and
1688
// the initialization.
1689
 
1690
bool
1691
Parse::init_vars_from_map(const Typed_identifier_list* vars, Type* type,
1692
                          Expression* expr, bool is_coloneq,
1693
                          Location location)
1694
{
1695
  Index_expression* index = expr->index_expression();
1696
  if (index == NULL)
1697
    return false;
1698
  if (vars->size() != 2)
1699
    return false;
1700
 
1701
  // This is an index which is being assigned to two variables.  It
1702
  // must be a map index.  Declare the variables, and then assign the
1703
  // results of the map index.
1704
  bool any_new = false;
1705
  Typed_identifier_list::const_iterator p = vars->begin();
1706
  Expression* init = type == NULL ? index : NULL;
1707
  Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1708
                                        type == NULL, &any_new);
1709
  if (type == NULL && any_new && val_no->is_variable())
1710
    val_no->var_value()->set_type_from_init_tuple();
1711
  Expression* val_var = Expression::make_var_reference(val_no, location);
1712
 
1713
  ++p;
1714
  Type* var_type = type;
1715
  if (var_type == NULL)
1716
    var_type = Type::lookup_bool_type();
1717
  Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1718
                                    &any_new);
1719
  Expression* present_var = Expression::make_var_reference(no, location);
1720
 
1721
  if (is_coloneq && !any_new)
1722
    error_at(location, "variables redeclared but no variable is new");
1723
 
1724
  Statement* s = Statement::make_tuple_map_assignment(val_var, present_var,
1725
                                                      index, location);
1726
 
1727
  if (!this->gogo_->in_global_scope())
1728
    this->gogo_->add_statement(s);
1729
  else if (!val_no->is_sink())
1730
    {
1731
      if (val_no->is_variable())
1732
        val_no->var_value()->add_preinit_statement(this->gogo_, s);
1733
    }
1734
  else if (!no->is_sink())
1735
    {
1736
      if (no->is_variable())
1737
        no->var_value()->add_preinit_statement(this->gogo_, s);
1738
    }
1739
  else
1740
    {
1741
      // Execute the map index expression just so that we can fail if
1742
      // the map is nil.
1743
      Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1744
                                                      NULL, location);
1745
      dummy->var_value()->add_preinit_statement(this->gogo_, s);
1746
    }
1747
 
1748
  return true;
1749
}
1750
 
1751
// See if we need to initialize a pair of values from a receive
1752
// expression.  This returns true if we have set up the variables and
1753
// the initialization.
1754
 
1755
bool
1756
Parse::init_vars_from_receive(const Typed_identifier_list* vars, Type* type,
1757
                              Expression* expr, bool is_coloneq,
1758
                              Location location)
1759
{
1760
  Receive_expression* receive = expr->receive_expression();
1761
  if (receive == NULL)
1762
    return false;
1763
  if (vars->size() != 2)
1764
    return false;
1765
 
1766
  // This is a receive expression which is being assigned to two
1767
  // variables.  Declare the variables, and then assign the results of
1768
  // the receive.
1769
  bool any_new = false;
1770
  Typed_identifier_list::const_iterator p = vars->begin();
1771
  Expression* init = type == NULL ? receive : NULL;
1772
  Named_object* val_no = this->init_var(*p, type, init, is_coloneq,
1773
                                        type == NULL, &any_new);
1774
  if (type == NULL && any_new && val_no->is_variable())
1775
    val_no->var_value()->set_type_from_init_tuple();
1776
  Expression* val_var = Expression::make_var_reference(val_no, location);
1777
 
1778
  ++p;
1779
  Type* var_type = type;
1780
  if (var_type == NULL)
1781
    var_type = Type::lookup_bool_type();
1782
  Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1783
                                    &any_new);
1784
  Expression* received_var = Expression::make_var_reference(no, location);
1785
 
1786
  if (is_coloneq && !any_new)
1787
    error_at(location, "variables redeclared but no variable is new");
1788
 
1789
  Statement* s = Statement::make_tuple_receive_assignment(val_var,
1790
                                                          received_var,
1791
                                                          receive->channel(),
1792
                                                          location);
1793
 
1794
  if (!this->gogo_->in_global_scope())
1795
    this->gogo_->add_statement(s);
1796
  else if (!val_no->is_sink())
1797
    {
1798
      if (val_no->is_variable())
1799
        val_no->var_value()->add_preinit_statement(this->gogo_, s);
1800
    }
1801
  else if (!no->is_sink())
1802
    {
1803
      if (no->is_variable())
1804
        no->var_value()->add_preinit_statement(this->gogo_, s);
1805
    }
1806
  else
1807
    {
1808
      Named_object* dummy = this->create_dummy_global(Type::lookup_bool_type(),
1809
                                                      NULL, location);
1810
      dummy->var_value()->add_preinit_statement(this->gogo_, s);
1811
    }
1812
 
1813
  return true;
1814
}
1815
 
1816
// See if we need to initialize a pair of values from a type guard
1817
// expression.  This returns true if we have set up the variables and
1818
// the initialization.
1819
 
1820
bool
1821
Parse::init_vars_from_type_guard(const Typed_identifier_list* vars,
1822
                                 Type* type, Expression* expr,
1823
                                 bool is_coloneq, Location location)
1824
{
1825
  Type_guard_expression* type_guard = expr->type_guard_expression();
1826
  if (type_guard == NULL)
1827
    return false;
1828
  if (vars->size() != 2)
1829
    return false;
1830
 
1831
  // This is a type guard expression which is being assigned to two
1832
  // variables.  Declare the variables, and then assign the results of
1833
  // the type guard.
1834
  bool any_new = false;
1835
  Typed_identifier_list::const_iterator p = vars->begin();
1836
  Type* var_type = type;
1837
  if (var_type == NULL)
1838
    var_type = type_guard->type();
1839
  Named_object* val_no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1840
                                        &any_new);
1841
  Expression* val_var = Expression::make_var_reference(val_no, location);
1842
 
1843
  ++p;
1844
  var_type = type;
1845
  if (var_type == NULL)
1846
    var_type = Type::lookup_bool_type();
1847
  Named_object* no = this->init_var(*p, var_type, NULL, is_coloneq, false,
1848
                                    &any_new);
1849
  Expression* ok_var = Expression::make_var_reference(no, location);
1850
 
1851
  Expression* texpr = type_guard->expr();
1852
  Type* t = type_guard->type();
1853
  Statement* s = Statement::make_tuple_type_guard_assignment(val_var, ok_var,
1854
                                                             texpr, t,
1855
                                                             location);
1856
 
1857
  if (is_coloneq && !any_new)
1858
    error_at(location, "variables redeclared but no variable is new");
1859
 
1860
  if (!this->gogo_->in_global_scope())
1861
    this->gogo_->add_statement(s);
1862
  else if (!val_no->is_sink())
1863
    {
1864
      if (val_no->is_variable())
1865
        val_no->var_value()->add_preinit_statement(this->gogo_, s);
1866
    }
1867
  else if (!no->is_sink())
1868
    {
1869
      if (no->is_variable())
1870
        no->var_value()->add_preinit_statement(this->gogo_, s);
1871
    }
1872
  else
1873
    {
1874
      Named_object* dummy = this->create_dummy_global(type, NULL, location);
1875
      dummy->var_value()->add_preinit_statement(this->gogo_, s);
1876
    }
1877
 
1878
  return true;
1879
}
1880
 
1881
// Create a single variable.  If IS_COLONEQ is true, we permit
1882
// redeclarations in the same block, and we set *IS_NEW when we find a
1883
// new variable which is not a redeclaration.
1884
 
1885
Named_object*
1886
Parse::init_var(const Typed_identifier& tid, Type* type, Expression* init,
1887
                bool is_coloneq, bool type_from_init, bool* is_new)
1888
{
1889
  Location location = tid.location();
1890
 
1891
  if (Gogo::is_sink_name(tid.name()))
1892
    {
1893
      if (!type_from_init && init != NULL)
1894
        {
1895
          if (this->gogo_->in_global_scope())
1896
            return this->create_dummy_global(type, init, location);
1897
          else if (type == NULL)
1898
            this->gogo_->add_statement(Statement::make_statement(init, true));
1899
          else
1900
            {
1901
              // With both a type and an initializer, create a dummy
1902
              // variable so that we will check whether the
1903
              // initializer can be assigned to the type.
1904
              Variable* var = new Variable(type, init, false, false, false,
1905
                                           location);
1906
              var->set_is_used();
1907
              static int count;
1908
              char buf[30];
1909
              snprintf(buf, sizeof buf, "sink$%d", count);
1910
              ++count;
1911
              return this->gogo_->add_variable(buf, var);
1912
            }
1913
        }
1914
      if (type != NULL)
1915
        this->gogo_->add_type_to_verify(type);
1916
      return this->gogo_->add_sink();
1917
    }
1918
 
1919
  if (is_coloneq)
1920
    {
1921
      Named_object* no = this->gogo_->lookup_in_block(tid.name());
1922
      if (no != NULL
1923
          && (no->is_variable() || no->is_result_variable()))
1924
        {
1925
          // INIT may be NULL even when IS_COLONEQ is true for cases
1926
          // like v, ok := x.(int).
1927
          if (!type_from_init && init != NULL)
1928
            {
1929
              Expression *v = Expression::make_var_reference(no, location);
1930
              Statement *s = Statement::make_assignment(v, init, location);
1931
              this->gogo_->add_statement(s);
1932
            }
1933
          return no;
1934
        }
1935
    }
1936
  *is_new = true;
1937
  Variable* var = new Variable(type, init, this->gogo_->in_global_scope(),
1938
                               false, false, location);
1939
  Named_object* no = this->gogo_->add_variable(tid.name(), var);
1940
  if (!no->is_variable())
1941
    {
1942
      // The name is already defined, so we just gave an error.
1943
      return this->gogo_->add_sink();
1944
    }
1945
  return no;
1946
}
1947
 
1948
// Create a dummy global variable to force an initializer to be run in
1949
// the right place.  This is used when a sink variable is initialized
1950
// at global scope.
1951
 
1952
Named_object*
1953
Parse::create_dummy_global(Type* type, Expression* init,
1954
                           Location location)
1955
{
1956
  if (type == NULL && init == NULL)
1957
    type = Type::lookup_bool_type();
1958
  Variable* var = new Variable(type, init, true, false, false, location);
1959
  static int count;
1960
  char buf[30];
1961
  snprintf(buf, sizeof buf, "_.%d", count);
1962
  ++count;
1963
  return this->gogo_->add_variable(buf, var);
1964
}
1965
 
1966
// SimpleVarDecl = identifier ":=" Expression .
1967
 
1968
// We've already seen the identifier.
1969
 
1970
// FIXME: We also have to implement
1971
//  IdentifierList ":=" ExpressionList
1972
// In order to support both "a, b := 1, 0" and "a, b = 1, 0" we accept
1973
// tuple assignments here as well.
1974
 
1975
// If P_RANGE_CLAUSE is not NULL, then this will recognize a
1976
// RangeClause.
1977
 
1978
// If P_TYPE_SWITCH is not NULL, this will recognize a type switch
1979
// guard (var := expr.("type") using the literal keyword "type").
1980
 
1981
void
1982
Parse::simple_var_decl_or_assignment(const std::string& name,
1983
                                     Location location,
1984
                                     Range_clause* p_range_clause,
1985
                                     Type_switch* p_type_switch)
1986
{
1987
  Typed_identifier_list til;
1988
  til.push_back(Typed_identifier(name, NULL, location));
1989
 
1990
  // We've seen one identifier.  If we see a comma now, this could be
1991
  // "a, *p = 1, 2".
1992
  if (this->peek_token()->is_op(OPERATOR_COMMA))
1993
    {
1994
      go_assert(p_type_switch == NULL);
1995
      while (true)
1996
        {
1997
          const Token* token = this->advance_token();
1998
          if (!token->is_identifier())
1999
            break;
2000
 
2001
          std::string id = token->identifier();
2002
          bool is_id_exported = token->is_identifier_exported();
2003
          Location id_location = token->location();
2004
 
2005
          token = this->advance_token();
2006
          if (!token->is_op(OPERATOR_COMMA))
2007
            {
2008
              if (token->is_op(OPERATOR_COLONEQ))
2009
                {
2010
                  id = this->gogo_->pack_hidden_name(id, is_id_exported);
2011
                  til.push_back(Typed_identifier(id, NULL, location));
2012
                }
2013
              else
2014
                this->unget_token(Token::make_identifier_token(id,
2015
                                                               is_id_exported,
2016
                                                               id_location));
2017
              break;
2018
            }
2019
 
2020
          id = this->gogo_->pack_hidden_name(id, is_id_exported);
2021
          til.push_back(Typed_identifier(id, NULL, location));
2022
        }
2023
 
2024
      // We have a comma separated list of identifiers in TIL.  If the
2025
      // next token is COLONEQ, then this is a simple var decl, and we
2026
      // have the complete list of identifiers.  If the next token is
2027
      // not COLONEQ, then the only valid parse is a tuple assignment.
2028
      // The list of identifiers we have so far is really a list of
2029
      // expressions.  There are more expressions following.
2030
 
2031
      if (!this->peek_token()->is_op(OPERATOR_COLONEQ))
2032
        {
2033
          Expression_list* exprs = new Expression_list;
2034
          for (Typed_identifier_list::const_iterator p = til.begin();
2035
               p != til.end();
2036
               ++p)
2037
            exprs->push_back(this->id_to_expression(p->name(),
2038
                                                    p->location()));
2039
 
2040
          Expression_list* more_exprs = this->expression_list(NULL, true);
2041
          for (Expression_list::const_iterator p = more_exprs->begin();
2042
               p != more_exprs->end();
2043
               ++p)
2044
            exprs->push_back(*p);
2045
          delete more_exprs;
2046
 
2047
          this->tuple_assignment(exprs, p_range_clause);
2048
          return;
2049
        }
2050
    }
2051
 
2052
  go_assert(this->peek_token()->is_op(OPERATOR_COLONEQ));
2053
  const Token* token = this->advance_token();
2054
 
2055
  if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
2056
    {
2057
      this->range_clause_decl(&til, p_range_clause);
2058
      return;
2059
    }
2060
 
2061
  Expression_list* init;
2062
  if (p_type_switch == NULL)
2063
    init = this->expression_list(NULL, false);
2064
  else
2065
    {
2066
      bool is_type_switch = false;
2067
      Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
2068
                                          &is_type_switch);
2069
      if (is_type_switch)
2070
        {
2071
          p_type_switch->found = true;
2072
          p_type_switch->name = name;
2073
          p_type_switch->location = location;
2074
          p_type_switch->expr = expr;
2075
          return;
2076
        }
2077
 
2078
      if (!this->peek_token()->is_op(OPERATOR_COMMA))
2079
        {
2080
          init = new Expression_list();
2081
          init->push_back(expr);
2082
        }
2083
      else
2084
        {
2085
          this->advance_token();
2086
          init = this->expression_list(expr, false);
2087
        }
2088
    }
2089
 
2090
  this->init_vars(&til, NULL, init, true, location);
2091
}
2092
 
2093
// FunctionDecl = "func" identifier Signature [ Block ] .
2094
// MethodDecl = "func" Receiver identifier Signature [ Block ] .
2095
 
2096
// Deprecated gcc extension:
2097
//   FunctionDecl = "func" identifier Signature
2098
//                    __asm__ "(" string_lit ")" .
2099
// This extension means a function whose real name is the identifier
2100
// inside the asm.  This extension will be removed at some future
2101
// date.  It has been replaced with //extern comments.
2102
 
2103
void
2104
Parse::function_decl()
2105
{
2106
  go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2107
  Location location = this->location();
2108
  std::string extern_name = this->lex_->extern_name();
2109
  const Token* token = this->advance_token();
2110
 
2111
  Typed_identifier* rec = NULL;
2112
  if (token->is_op(OPERATOR_LPAREN))
2113
    {
2114
      rec = this->receiver();
2115
      token = this->peek_token();
2116
    }
2117
 
2118
  if (!token->is_identifier())
2119
    {
2120
      error_at(this->location(), "expected function name");
2121
      return;
2122
    }
2123
 
2124
  std::string name =
2125
    this->gogo_->pack_hidden_name(token->identifier(),
2126
                                  token->is_identifier_exported());
2127
 
2128
  this->advance_token();
2129
 
2130
  Function_type* fntype = this->signature(rec, this->location());
2131
 
2132
  Named_object* named_object = NULL;
2133
 
2134
  if (this->peek_token()->is_keyword(KEYWORD_ASM))
2135
    {
2136
      if (!this->advance_token()->is_op(OPERATOR_LPAREN))
2137
        {
2138
          error_at(this->location(), "expected %<(%>");
2139
          return;
2140
        }
2141
      token = this->advance_token();
2142
      if (!token->is_string())
2143
        {
2144
          error_at(this->location(), "expected string");
2145
          return;
2146
        }
2147
      std::string asm_name = token->string_value();
2148
      if (!this->advance_token()->is_op(OPERATOR_RPAREN))
2149
        {
2150
          error_at(this->location(), "expected %<)%>");
2151
          return;
2152
        }
2153
      this->advance_token();
2154
      if (!Gogo::is_sink_name(name))
2155
        {
2156
          named_object = this->gogo_->declare_function(name, fntype, location);
2157
          if (named_object->is_function_declaration())
2158
            named_object->func_declaration_value()->set_asm_name(asm_name);
2159
        }
2160
    }
2161
 
2162
  // Check for the easy error of a newline before the opening brace.
2163
  if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
2164
    {
2165
      Location semi_loc = this->location();
2166
      if (this->advance_token()->is_op(OPERATOR_LCURLY))
2167
        error_at(this->location(),
2168
                 "unexpected semicolon or newline before %<{%>");
2169
      else
2170
        this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
2171
                                                     semi_loc));
2172
    }
2173
 
2174
  if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2175
    {
2176
      if (named_object == NULL && !Gogo::is_sink_name(name))
2177
        {
2178
          if (fntype == NULL)
2179
            this->gogo_->add_erroneous_name(name);
2180
          else
2181
            {
2182
              named_object = this->gogo_->declare_function(name, fntype,
2183
                                                           location);
2184
              if (!extern_name.empty()
2185
                  && named_object->is_function_declaration())
2186
                {
2187
                  Function_declaration* fd =
2188
                    named_object->func_declaration_value();
2189
                  fd->set_asm_name(extern_name);
2190
                }
2191
            }
2192
        }
2193
    }
2194
  else
2195
    {
2196
      bool hold_is_erroneous_function = this->is_erroneous_function_;
2197
      if (fntype == NULL)
2198
        {
2199
          fntype = Type::make_function_type(NULL, NULL, NULL, location);
2200
          this->is_erroneous_function_ = true;
2201
          if (!Gogo::is_sink_name(name))
2202
            this->gogo_->add_erroneous_name(name);
2203
          name = this->gogo_->pack_hidden_name("_", false);
2204
        }
2205
      this->gogo_->start_function(name, fntype, true, location);
2206
      Location end_loc = this->block();
2207
      this->gogo_->finish_function(end_loc);
2208
      this->is_erroneous_function_ = hold_is_erroneous_function;
2209
    }
2210
}
2211
 
2212
// Receiver     = "(" [ identifier ] [ "*" ] BaseTypeName ")" .
2213
// BaseTypeName = identifier .
2214
 
2215
Typed_identifier*
2216
Parse::receiver()
2217
{
2218
  go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
2219
 
2220
  std::string name;
2221
  const Token* token = this->advance_token();
2222
  Location location = token->location();
2223
  if (!token->is_op(OPERATOR_MULT))
2224
    {
2225
      if (!token->is_identifier())
2226
        {
2227
          error_at(this->location(), "method has no receiver");
2228
          this->gogo_->mark_locals_used();
2229
          while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2230
            token = this->advance_token();
2231
          if (!token->is_eof())
2232
            this->advance_token();
2233
          return NULL;
2234
        }
2235
      name = token->identifier();
2236
      bool is_exported = token->is_identifier_exported();
2237
      token = this->advance_token();
2238
      if (!token->is_op(OPERATOR_DOT) && !token->is_op(OPERATOR_RPAREN))
2239
        {
2240
          // An identifier followed by something other than a dot or a
2241
          // right parenthesis must be a receiver name followed by a
2242
          // type.
2243
          name = this->gogo_->pack_hidden_name(name, is_exported);
2244
        }
2245
      else
2246
        {
2247
          // This must be a type name.
2248
          this->unget_token(Token::make_identifier_token(name, is_exported,
2249
                                                         location));
2250
          token = this->peek_token();
2251
          name.clear();
2252
        }
2253
    }
2254
 
2255
  // Here the receiver name is in NAME (it is empty if the receiver is
2256
  // unnamed) and TOKEN is the first token in the type.
2257
 
2258
  bool is_pointer = false;
2259
  if (token->is_op(OPERATOR_MULT))
2260
    {
2261
      is_pointer = true;
2262
      token = this->advance_token();
2263
    }
2264
 
2265
  if (!token->is_identifier())
2266
    {
2267
      error_at(this->location(), "expected receiver name or type");
2268
      this->gogo_->mark_locals_used();
2269
      int c = token->is_op(OPERATOR_LPAREN) ? 1 : 0;
2270
      while (!token->is_eof())
2271
        {
2272
          token = this->advance_token();
2273
          if (token->is_op(OPERATOR_LPAREN))
2274
            ++c;
2275
          else if (token->is_op(OPERATOR_RPAREN))
2276
            {
2277
              if (c == 0)
2278
                break;
2279
              --c;
2280
            }
2281
        }
2282
      if (!token->is_eof())
2283
        this->advance_token();
2284
      return NULL;
2285
    }
2286
 
2287
  Type* type = this->type_name(true);
2288
 
2289
  if (is_pointer && !type->is_error_type())
2290
    type = Type::make_pointer_type(type);
2291
 
2292
  if (this->peek_token()->is_op(OPERATOR_RPAREN))
2293
    this->advance_token();
2294
  else
2295
    {
2296
      if (this->peek_token()->is_op(OPERATOR_COMMA))
2297
        error_at(this->location(), "method has multiple receivers");
2298
      else
2299
        error_at(this->location(), "expected %<)%>");
2300
      this->gogo_->mark_locals_used();
2301
      while (!token->is_eof() && !token->is_op(OPERATOR_RPAREN))
2302
        token = this->advance_token();
2303
      if (!token->is_eof())
2304
        this->advance_token();
2305
      return NULL;
2306
    }
2307
 
2308
  return new Typed_identifier(name, type, location);
2309
}
2310
 
2311
// Operand    = Literal | QualifiedIdent | MethodExpr | "(" Expression ")" .
2312
// Literal    = BasicLit | CompositeLit | FunctionLit .
2313
// BasicLit   = int_lit | float_lit | imaginary_lit | char_lit | string_lit .
2314
 
2315
// If MAY_BE_SINK is true, this operand may be "_".
2316
 
2317
Expression*
2318
Parse::operand(bool may_be_sink)
2319
{
2320
  const Token* token = this->peek_token();
2321
  Expression* ret;
2322
  switch (token->classification())
2323
    {
2324
    case Token::TOKEN_IDENTIFIER:
2325
      {
2326
        Location location = token->location();
2327
        std::string id = token->identifier();
2328
        bool is_exported = token->is_identifier_exported();
2329
        std::string packed = this->gogo_->pack_hidden_name(id, is_exported);
2330
 
2331
        Named_object* in_function;
2332
        Named_object* named_object = this->gogo_->lookup(packed, &in_function);
2333
 
2334
        Package* package = NULL;
2335
        if (named_object != NULL && named_object->is_package())
2336
          {
2337
            if (!this->advance_token()->is_op(OPERATOR_DOT)
2338
                || !this->advance_token()->is_identifier())
2339
              {
2340
                error_at(location, "unexpected reference to package");
2341
                return Expression::make_error(location);
2342
              }
2343
            package = named_object->package_value();
2344
            package->set_used();
2345
            id = this->peek_token()->identifier();
2346
            is_exported = this->peek_token()->is_identifier_exported();
2347
            packed = this->gogo_->pack_hidden_name(id, is_exported);
2348
            named_object = package->lookup(packed);
2349
            location = this->location();
2350
            go_assert(in_function == NULL);
2351
          }
2352
 
2353
        this->advance_token();
2354
 
2355
        if (named_object != NULL
2356
            && named_object->is_type()
2357
            && !named_object->type_value()->is_visible())
2358
          {
2359
            go_assert(package != NULL);
2360
            error_at(location, "invalid reference to hidden type %<%s.%s%>",
2361
                     Gogo::message_name(package->name()).c_str(),
2362
                     Gogo::message_name(id).c_str());
2363
            return Expression::make_error(location);
2364
          }
2365
 
2366
 
2367
        if (named_object == NULL)
2368
          {
2369
            if (package != NULL)
2370
              {
2371
                std::string n1 = Gogo::message_name(package->name());
2372
                std::string n2 = Gogo::message_name(id);
2373
                if (!is_exported)
2374
                  error_at(location,
2375
                           ("invalid reference to unexported identifier "
2376
                            "%<%s.%s%>"),
2377
                           n1.c_str(), n2.c_str());
2378
                else
2379
                  error_at(location,
2380
                           "reference to undefined identifier %<%s.%s%>",
2381
                           n1.c_str(), n2.c_str());
2382
                return Expression::make_error(location);
2383
              }
2384
 
2385
            named_object = this->gogo_->add_unknown_name(packed, location);
2386
          }
2387
 
2388
        if (in_function != NULL
2389
            && in_function != this->gogo_->current_function()
2390
            && (named_object->is_variable()
2391
                || named_object->is_result_variable()))
2392
          return this->enclosing_var_reference(in_function, named_object,
2393
                                               location);
2394
 
2395
        switch (named_object->classification())
2396
          {
2397
          case Named_object::NAMED_OBJECT_CONST:
2398
            return Expression::make_const_reference(named_object, location);
2399
          case Named_object::NAMED_OBJECT_TYPE:
2400
            return Expression::make_type(named_object->type_value(), location);
2401
          case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
2402
            {
2403
              Type* t = Type::make_forward_declaration(named_object);
2404
              return Expression::make_type(t, location);
2405
            }
2406
          case Named_object::NAMED_OBJECT_VAR:
2407
          case Named_object::NAMED_OBJECT_RESULT_VAR:
2408
            this->mark_var_used(named_object);
2409
            return Expression::make_var_reference(named_object, location);
2410
          case Named_object::NAMED_OBJECT_SINK:
2411
            if (may_be_sink)
2412
              return Expression::make_sink(location);
2413
            else
2414
              {
2415
                error_at(location, "cannot use _ as value");
2416
                return Expression::make_error(location);
2417
              }
2418
          case Named_object::NAMED_OBJECT_FUNC:
2419
          case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
2420
            return Expression::make_func_reference(named_object, NULL,
2421
                                                   location);
2422
          case Named_object::NAMED_OBJECT_UNKNOWN:
2423
            {
2424
              Unknown_expression* ue =
2425
                Expression::make_unknown_reference(named_object, location);
2426
              if (this->is_erroneous_function_)
2427
                ue->set_no_error_message();
2428
              return ue;
2429
            }
2430
          case Named_object::NAMED_OBJECT_ERRONEOUS:
2431
            return Expression::make_error(location);
2432
          default:
2433
            go_unreachable();
2434
          }
2435
      }
2436
      go_unreachable();
2437
 
2438
    case Token::TOKEN_STRING:
2439
      ret = Expression::make_string(token->string_value(), token->location());
2440
      this->advance_token();
2441
      return ret;
2442
 
2443
    case Token::TOKEN_CHARACTER:
2444
      ret = Expression::make_character(token->character_value(), NULL,
2445
                                       token->location());
2446
      this->advance_token();
2447
      return ret;
2448
 
2449
    case Token::TOKEN_INTEGER:
2450
      ret = Expression::make_integer(token->integer_value(), NULL,
2451
                                     token->location());
2452
      this->advance_token();
2453
      return ret;
2454
 
2455
    case Token::TOKEN_FLOAT:
2456
      ret = Expression::make_float(token->float_value(), NULL,
2457
                                   token->location());
2458
      this->advance_token();
2459
      return ret;
2460
 
2461
    case Token::TOKEN_IMAGINARY:
2462
      {
2463
        mpfr_t zero;
2464
        mpfr_init_set_ui(zero, 0, GMP_RNDN);
2465
        ret = Expression::make_complex(&zero, token->imaginary_value(),
2466
                                       NULL, token->location());
2467
        mpfr_clear(zero);
2468
        this->advance_token();
2469
        return ret;
2470
      }
2471
 
2472
    case Token::TOKEN_KEYWORD:
2473
      switch (token->keyword())
2474
        {
2475
        case KEYWORD_FUNC:
2476
          return this->function_lit();
2477
        case KEYWORD_CHAN:
2478
        case KEYWORD_INTERFACE:
2479
        case KEYWORD_MAP:
2480
        case KEYWORD_STRUCT:
2481
          {
2482
            Location location = token->location();
2483
            return Expression::make_type(this->type(), location);
2484
          }
2485
        default:
2486
          break;
2487
        }
2488
      break;
2489
 
2490
    case Token::TOKEN_OPERATOR:
2491
      if (token->is_op(OPERATOR_LPAREN))
2492
        {
2493
          this->advance_token();
2494
          ret = this->expression(PRECEDENCE_NORMAL, may_be_sink, true, NULL);
2495
          if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2496
            error_at(this->location(), "missing %<)%>");
2497
          else
2498
            this->advance_token();
2499
          return ret;
2500
        }
2501
      else if (token->is_op(OPERATOR_LSQUARE))
2502
        {
2503
          // Here we call array_type directly, as this is the only
2504
          // case where an ellipsis is permitted for an array type.
2505
          Location location = token->location();
2506
          return Expression::make_type(this->array_type(true), location);
2507
        }
2508
      break;
2509
 
2510
    default:
2511
      break;
2512
    }
2513
 
2514
  error_at(this->location(), "expected operand");
2515
  return Expression::make_error(this->location());
2516
}
2517
 
2518
// Handle a reference to a variable in an enclosing function.  We add
2519
// it to a list of such variables.  We return a reference to a field
2520
// in a struct which will be passed on the static chain when calling
2521
// the current function.
2522
 
2523
Expression*
2524
Parse::enclosing_var_reference(Named_object* in_function, Named_object* var,
2525
                               Location location)
2526
{
2527
  go_assert(var->is_variable() || var->is_result_variable());
2528
 
2529
  this->mark_var_used(var);
2530
 
2531
  Named_object* this_function = this->gogo_->current_function();
2532
  Named_object* closure = this_function->func_value()->closure_var();
2533
 
2534
  Enclosing_var ev(var, in_function, this->enclosing_vars_.size());
2535
  std::pair<Enclosing_vars::iterator, bool> ins =
2536
    this->enclosing_vars_.insert(ev);
2537
  if (ins.second)
2538
    {
2539
      // This is a variable we have not seen before.  Add a new field
2540
      // to the closure type.
2541
      this_function->func_value()->add_closure_field(var, location);
2542
    }
2543
 
2544
  Expression* closure_ref = Expression::make_var_reference(closure,
2545
                                                           location);
2546
  closure_ref = Expression::make_unary(OPERATOR_MULT, closure_ref, location);
2547
 
2548
  // The closure structure holds pointers to the variables, so we need
2549
  // to introduce an indirection.
2550
  Expression* e = Expression::make_field_reference(closure_ref,
2551
                                                   ins.first->index(),
2552
                                                   location);
2553
  e = Expression::make_unary(OPERATOR_MULT, e, location);
2554
  return e;
2555
}
2556
 
2557
// CompositeLit  = LiteralType LiteralValue .
2558
// LiteralType   = StructType | ArrayType | "[" "..." "]" ElementType |
2559
//                 SliceType | MapType | TypeName .
2560
// LiteralValue  = "{" [ ElementList [ "," ] ] "}" .
2561
// ElementList   = Element { "," Element } .
2562
// Element       = [ Key ":" ] Value .
2563
// Key           = FieldName | ElementIndex .
2564
// FieldName     = identifier .
2565
// ElementIndex  = Expression .
2566
// Value         = Expression | LiteralValue .
2567
 
2568
// We have already seen the type if there is one, and we are now
2569
// looking at the LiteralValue.  The case "[" "..."  "]" ElementType
2570
// will be seen here as an array type whose length is "nil".  The
2571
// DEPTH parameter is non-zero if this is an embedded composite
2572
// literal and the type was omitted.  It gives the number of steps up
2573
// to the type which was provided.  E.g., in [][]int{{1}} it will be
2574
// 1.  In [][][]int{{{1}}} it will be 2.
2575
 
2576
Expression*
2577
Parse::composite_lit(Type* type, int depth, Location location)
2578
{
2579
  go_assert(this->peek_token()->is_op(OPERATOR_LCURLY));
2580
  this->advance_token();
2581
 
2582
  if (this->peek_token()->is_op(OPERATOR_RCURLY))
2583
    {
2584
      this->advance_token();
2585
      return Expression::make_composite_literal(type, depth, false, NULL,
2586
                                                location);
2587
    }
2588
 
2589
  bool has_keys = false;
2590
  Expression_list* vals = new Expression_list;
2591
  while (true)
2592
    {
2593
      Expression* val;
2594
      bool is_type_omitted = false;
2595
 
2596
      const Token* token = this->peek_token();
2597
 
2598
      if (token->is_identifier())
2599
        {
2600
          std::string identifier = token->identifier();
2601
          bool is_exported = token->is_identifier_exported();
2602
          Location location = token->location();
2603
 
2604
          if (this->advance_token()->is_op(OPERATOR_COLON))
2605
            {
2606
              // This may be a field name.  We don't know for sure--it
2607
              // could also be an expression for an array index.  We
2608
              // don't want to parse it as an expression because may
2609
              // trigger various errors, e.g., if this identifier
2610
              // happens to be the name of a package.
2611
              Gogo* gogo = this->gogo_;
2612
              val = this->id_to_expression(gogo->pack_hidden_name(identifier,
2613
                                                                  is_exported),
2614
                                           location);
2615
            }
2616
          else
2617
            {
2618
              this->unget_token(Token::make_identifier_token(identifier,
2619
                                                             is_exported,
2620
                                                             location));
2621
              val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2622
            }
2623
        }
2624
      else if (!token->is_op(OPERATOR_LCURLY))
2625
        val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2626
      else
2627
        {
2628
          // This must be a composite literal inside another composite
2629
          // literal, with the type omitted for the inner one.
2630
          val = this->composite_lit(type, depth + 1, token->location());
2631
          is_type_omitted = true;
2632
        }
2633
 
2634
      token = this->peek_token();
2635
      if (!token->is_op(OPERATOR_COLON))
2636
        {
2637
          if (has_keys)
2638
            vals->push_back(NULL);
2639
        }
2640
      else
2641
        {
2642
          if (is_type_omitted && !val->is_error_expression())
2643
            {
2644
              error_at(this->location(), "unexpected %<:%>");
2645
              val = Expression::make_error(this->location());
2646
            }
2647
 
2648
          this->advance_token();
2649
 
2650
          if (!has_keys && !vals->empty())
2651
            {
2652
              Expression_list* newvals = new Expression_list;
2653
              for (Expression_list::const_iterator p = vals->begin();
2654
                   p != vals->end();
2655
                   ++p)
2656
                {
2657
                  newvals->push_back(NULL);
2658
                  newvals->push_back(*p);
2659
                }
2660
              delete vals;
2661
              vals = newvals;
2662
            }
2663
          has_keys = true;
2664
 
2665
          if (val->unknown_expression() != NULL)
2666
            val->unknown_expression()->set_is_composite_literal_key();
2667
 
2668
          vals->push_back(val);
2669
 
2670
          if (!token->is_op(OPERATOR_LCURLY))
2671
            val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
2672
          else
2673
            {
2674
              // This must be a composite literal inside another
2675
              // composite literal, with the type omitted for the
2676
              // inner one.
2677
              val = this->composite_lit(type, depth + 1, token->location());
2678
            }
2679
 
2680
          token = this->peek_token();
2681
        }
2682
 
2683
      vals->push_back(val);
2684
 
2685
      if (token->is_op(OPERATOR_COMMA))
2686
        {
2687
          if (this->advance_token()->is_op(OPERATOR_RCURLY))
2688
            {
2689
              this->advance_token();
2690
              break;
2691
            }
2692
        }
2693
      else if (token->is_op(OPERATOR_RCURLY))
2694
        {
2695
          this->advance_token();
2696
          break;
2697
        }
2698
      else
2699
        {
2700
          error_at(this->location(), "expected %<,%> or %<}%>");
2701
 
2702
          this->gogo_->mark_locals_used();
2703
          int depth = 0;
2704
          while (!token->is_eof()
2705
                 && (depth > 0 || !token->is_op(OPERATOR_RCURLY)))
2706
            {
2707
              if (token->is_op(OPERATOR_LCURLY))
2708
                ++depth;
2709
              else if (token->is_op(OPERATOR_RCURLY))
2710
                --depth;
2711
              token = this->advance_token();
2712
            }
2713
          if (token->is_op(OPERATOR_RCURLY))
2714
            this->advance_token();
2715
 
2716
          return Expression::make_error(location);
2717
        }
2718
    }
2719
 
2720
  return Expression::make_composite_literal(type, depth, has_keys, vals,
2721
                                            location);
2722
}
2723
 
2724
// FunctionLit = "func" Signature Block .
2725
 
2726
Expression*
2727
Parse::function_lit()
2728
{
2729
  Location location = this->location();
2730
  go_assert(this->peek_token()->is_keyword(KEYWORD_FUNC));
2731
  this->advance_token();
2732
 
2733
  Enclosing_vars hold_enclosing_vars;
2734
  hold_enclosing_vars.swap(this->enclosing_vars_);
2735
 
2736
  Function_type* type = this->signature(NULL, location);
2737
  bool fntype_is_error = false;
2738
  if (type == NULL)
2739
    {
2740
      type = Type::make_function_type(NULL, NULL, NULL, location);
2741
      fntype_is_error = true;
2742
    }
2743
 
2744
  // For a function literal, the next token must be a '{'.  If we
2745
  // don't see that, then we may have a type expression.
2746
  if (!this->peek_token()->is_op(OPERATOR_LCURLY))
2747
    return Expression::make_type(type, location);
2748
 
2749
  bool hold_is_erroneous_function = this->is_erroneous_function_;
2750
  if (fntype_is_error)
2751
    this->is_erroneous_function_ = true;
2752
 
2753
  Bc_stack* hold_break_stack = this->break_stack_;
2754
  Bc_stack* hold_continue_stack = this->continue_stack_;
2755
  this->break_stack_ = NULL;
2756
  this->continue_stack_ = NULL;
2757
 
2758
  Named_object* no = this->gogo_->start_function("", type, true, location);
2759
 
2760
  Location end_loc = this->block();
2761
 
2762
  this->gogo_->finish_function(end_loc);
2763
 
2764
  if (this->break_stack_ != NULL)
2765
    delete this->break_stack_;
2766
  if (this->continue_stack_ != NULL)
2767
    delete this->continue_stack_;
2768
  this->break_stack_ = hold_break_stack;
2769
  this->continue_stack_ = hold_continue_stack;
2770
 
2771
  this->is_erroneous_function_ = hold_is_erroneous_function;
2772
 
2773
  hold_enclosing_vars.swap(this->enclosing_vars_);
2774
 
2775
  Expression* closure = this->create_closure(no, &hold_enclosing_vars,
2776
                                             location);
2777
 
2778
  return Expression::make_func_reference(no, closure, location);
2779
}
2780
 
2781
// Create a closure for the nested function FUNCTION.  This is based
2782
// on ENCLOSING_VARS, which is a list of all variables defined in
2783
// enclosing functions and referenced from FUNCTION.  A closure is the
2784
// address of a struct which contains the addresses of all the
2785
// referenced variables.  This returns NULL if no closure is required.
2786
 
2787
Expression*
2788
Parse::create_closure(Named_object* function, Enclosing_vars* enclosing_vars,
2789
                      Location location)
2790
{
2791
  if (enclosing_vars->empty())
2792
    return NULL;
2793
 
2794
  // Get the variables in order by their field index.
2795
 
2796
  size_t enclosing_var_count = enclosing_vars->size();
2797
  std::vector<Enclosing_var> ev(enclosing_var_count);
2798
  for (Enclosing_vars::const_iterator p = enclosing_vars->begin();
2799
       p != enclosing_vars->end();
2800
       ++p)
2801
    ev[p->index()] = *p;
2802
 
2803
  // Build an initializer for a composite literal of the closure's
2804
  // type.
2805
 
2806
  Named_object* enclosing_function = this->gogo_->current_function();
2807
  Expression_list* initializer = new Expression_list;
2808
  for (size_t i = 0; i < enclosing_var_count; ++i)
2809
    {
2810
      go_assert(ev[i].index() == i);
2811
      Named_object* var = ev[i].var();
2812
      Expression* ref;
2813
      if (ev[i].in_function() == enclosing_function)
2814
        ref = Expression::make_var_reference(var, location);
2815
      else
2816
        ref = this->enclosing_var_reference(ev[i].in_function(), var,
2817
                                            location);
2818
      Expression* refaddr = Expression::make_unary(OPERATOR_AND, ref,
2819
                                                   location);
2820
      initializer->push_back(refaddr);
2821
    }
2822
 
2823
  Named_object* closure_var = function->func_value()->closure_var();
2824
  Struct_type* st = closure_var->var_value()->type()->deref()->struct_type();
2825
  Expression* cv = Expression::make_struct_composite_literal(st, initializer,
2826
                                                             location);
2827
  return Expression::make_heap_composite(cv, location);
2828
}
2829
 
2830
// PrimaryExpr = Operand { Selector | Index | Slice | TypeGuard | Call } .
2831
 
2832
// If MAY_BE_SINK is true, this expression may be "_".
2833
 
2834
// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
2835
// literal.
2836
 
2837
// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2838
// guard (var := expr.("type") using the literal keyword "type").
2839
 
2840
Expression*
2841
Parse::primary_expr(bool may_be_sink, bool may_be_composite_lit,
2842
                    bool* is_type_switch)
2843
{
2844
  Location start_loc = this->location();
2845
  bool is_parenthesized = this->peek_token()->is_op(OPERATOR_LPAREN);
2846
 
2847
  Expression* ret = this->operand(may_be_sink);
2848
 
2849
  // An unknown name followed by a curly brace must be a composite
2850
  // literal, and the unknown name must be a type.
2851
  if (may_be_composite_lit
2852
      && !is_parenthesized
2853
      && ret->unknown_expression() != NULL
2854
      && this->peek_token()->is_op(OPERATOR_LCURLY))
2855
    {
2856
      Named_object* no = ret->unknown_expression()->named_object();
2857
      Type* type = Type::make_forward_declaration(no);
2858
      ret = Expression::make_type(type, ret->location());
2859
    }
2860
 
2861
  // We handle composite literals and type casts here, as it is the
2862
  // easiest way to handle types which are in parentheses, as in
2863
  // "((uint))(1)".
2864
  if (ret->is_type_expression())
2865
    {
2866
      if (this->peek_token()->is_op(OPERATOR_LCURLY))
2867
        {
2868
          if (is_parenthesized)
2869
            error_at(start_loc,
2870
                     "cannot parenthesize type in composite literal");
2871
          ret = this->composite_lit(ret->type(), 0, ret->location());
2872
        }
2873
      else if (this->peek_token()->is_op(OPERATOR_LPAREN))
2874
        {
2875
          Location loc = this->location();
2876
          this->advance_token();
2877
          Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true,
2878
                                              NULL);
2879
          if (this->peek_token()->is_op(OPERATOR_ELLIPSIS))
2880
            {
2881
              error_at(this->location(),
2882
                       "invalid use of %<...%> in type conversion");
2883
              this->advance_token();
2884
            }
2885
          if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2886
            error_at(this->location(), "expected %<)%>");
2887
          else
2888
            this->advance_token();
2889
          if (expr->is_error_expression())
2890
            ret = expr;
2891
          else
2892
            {
2893
              Type* t = ret->type();
2894
              if (t->classification() == Type::TYPE_ARRAY
2895
                  && t->array_type()->length() != NULL
2896
                  && t->array_type()->length()->is_nil_expression())
2897
                {
2898
                  error_at(ret->location(),
2899
                           "invalid use of %<...%> in type conversion");
2900
                  ret = Expression::make_error(loc);
2901
                }
2902
              else
2903
                ret = Expression::make_cast(t, expr, loc);
2904
            }
2905
        }
2906
    }
2907
 
2908
  while (true)
2909
    {
2910
      const Token* token = this->peek_token();
2911
      if (token->is_op(OPERATOR_LPAREN))
2912
        ret = this->call(this->verify_not_sink(ret));
2913
      else if (token->is_op(OPERATOR_DOT))
2914
        {
2915
          ret = this->selector(this->verify_not_sink(ret), is_type_switch);
2916
          if (is_type_switch != NULL && *is_type_switch)
2917
            break;
2918
        }
2919
      else if (token->is_op(OPERATOR_LSQUARE))
2920
        ret = this->index(this->verify_not_sink(ret));
2921
      else
2922
        break;
2923
    }
2924
 
2925
  return ret;
2926
}
2927
 
2928
// Selector = "." identifier .
2929
// TypeGuard = "." "(" QualifiedIdent ")" .
2930
 
2931
// Note that Operand can expand to QualifiedIdent, which contains a
2932
// ".".  That is handled directly in operand when it sees a package
2933
// name.
2934
 
2935
// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
2936
// guard (var := expr.("type") using the literal keyword "type").
2937
 
2938
Expression*
2939
Parse::selector(Expression* left, bool* is_type_switch)
2940
{
2941
  go_assert(this->peek_token()->is_op(OPERATOR_DOT));
2942
  Location location = this->location();
2943
 
2944
  const Token* token = this->advance_token();
2945
  if (token->is_identifier())
2946
    {
2947
      // This could be a field in a struct, or a method in an
2948
      // interface, or a method associated with a type.  We can't know
2949
      // which until we have seen all the types.
2950
      std::string name =
2951
        this->gogo_->pack_hidden_name(token->identifier(),
2952
                                      token->is_identifier_exported());
2953
      if (token->identifier() == "_")
2954
        {
2955
          error_at(this->location(), "invalid use of %<_%>");
2956
          name = this->gogo_->pack_hidden_name("blank", false);
2957
        }
2958
      this->advance_token();
2959
      return Expression::make_selector(left, name, location);
2960
    }
2961
  else if (token->is_op(OPERATOR_LPAREN))
2962
    {
2963
      this->advance_token();
2964
      Type* type = NULL;
2965
      if (!this->peek_token()->is_keyword(KEYWORD_TYPE))
2966
        type = this->type();
2967
      else
2968
        {
2969
          if (is_type_switch != NULL)
2970
            *is_type_switch = true;
2971
          else
2972
            {
2973
              error_at(this->location(),
2974
                       "use of %<.(type)%> outside type switch");
2975
              type = Type::make_error_type();
2976
            }
2977
          this->advance_token();
2978
        }
2979
      if (!this->peek_token()->is_op(OPERATOR_RPAREN))
2980
        error_at(this->location(), "missing %<)%>");
2981
      else
2982
        this->advance_token();
2983
      if (is_type_switch != NULL && *is_type_switch)
2984
        return left;
2985
      return Expression::make_type_guard(left, type, location);
2986
    }
2987
  else
2988
    {
2989
      error_at(this->location(), "expected identifier or %<(%>");
2990
      return left;
2991
    }
2992
}
2993
 
2994
// Index          = "[" Expression "]" .
2995
// Slice          = "[" Expression ":" [ Expression ] "]" .
2996
 
2997
Expression*
2998
Parse::index(Expression* expr)
2999
{
3000
  Location location = this->location();
3001
  go_assert(this->peek_token()->is_op(OPERATOR_LSQUARE));
3002
  this->advance_token();
3003
 
3004
  Expression* start;
3005
  if (!this->peek_token()->is_op(OPERATOR_COLON))
3006
    start = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3007
  else
3008
    {
3009
      mpz_t zero;
3010
      mpz_init_set_ui(zero, 0);
3011
      start = Expression::make_integer(&zero, NULL, location);
3012
      mpz_clear(zero);
3013
    }
3014
 
3015
  Expression* end = NULL;
3016
  if (this->peek_token()->is_op(OPERATOR_COLON))
3017
    {
3018
      // We use nil to indicate a missing high expression.
3019
      if (this->advance_token()->is_op(OPERATOR_RSQUARE))
3020
        end = Expression::make_nil(this->location());
3021
      else
3022
        end = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3023
    }
3024
  if (!this->peek_token()->is_op(OPERATOR_RSQUARE))
3025
    error_at(this->location(), "missing %<]%>");
3026
  else
3027
    this->advance_token();
3028
  return Expression::make_index(expr, start, end, location);
3029
}
3030
 
3031
// Call           = "(" [ ArgumentList [ "," ] ] ")" .
3032
// ArgumentList   = ExpressionList [ "..." ] .
3033
 
3034
Expression*
3035
Parse::call(Expression* func)
3036
{
3037
  go_assert(this->peek_token()->is_op(OPERATOR_LPAREN));
3038
  Expression_list* args = NULL;
3039
  bool is_varargs = false;
3040
  const Token* token = this->advance_token();
3041
  if (!token->is_op(OPERATOR_RPAREN))
3042
    {
3043
      args = this->expression_list(NULL, false);
3044
      token = this->peek_token();
3045
      if (token->is_op(OPERATOR_ELLIPSIS))
3046
        {
3047
          is_varargs = true;
3048
          token = this->advance_token();
3049
        }
3050
    }
3051
  if (token->is_op(OPERATOR_COMMA))
3052
    token = this->advance_token();
3053
  if (!token->is_op(OPERATOR_RPAREN))
3054
    error_at(this->location(), "missing %<)%>");
3055
  else
3056
    this->advance_token();
3057
  if (func->is_error_expression())
3058
    return func;
3059
  return Expression::make_call(func, args, is_varargs, func->location());
3060
}
3061
 
3062
// Return an expression for a single unqualified identifier.
3063
 
3064
Expression*
3065
Parse::id_to_expression(const std::string& name, Location location)
3066
{
3067
  Named_object* in_function;
3068
  Named_object* named_object = this->gogo_->lookup(name, &in_function);
3069
  if (named_object == NULL)
3070
    named_object = this->gogo_->add_unknown_name(name, location);
3071
 
3072
  if (in_function != NULL
3073
      && in_function != this->gogo_->current_function()
3074
      && (named_object->is_variable() || named_object->is_result_variable()))
3075
    return this->enclosing_var_reference(in_function, named_object,
3076
                                         location);
3077
 
3078
  switch (named_object->classification())
3079
    {
3080
    case Named_object::NAMED_OBJECT_CONST:
3081
      return Expression::make_const_reference(named_object, location);
3082
    case Named_object::NAMED_OBJECT_VAR:
3083
    case Named_object::NAMED_OBJECT_RESULT_VAR:
3084
      this->mark_var_used(named_object);
3085
      return Expression::make_var_reference(named_object, location);
3086
    case Named_object::NAMED_OBJECT_SINK:
3087
      return Expression::make_sink(location);
3088
    case Named_object::NAMED_OBJECT_FUNC:
3089
    case Named_object::NAMED_OBJECT_FUNC_DECLARATION:
3090
      return Expression::make_func_reference(named_object, NULL, location);
3091
    case Named_object::NAMED_OBJECT_UNKNOWN:
3092
      {
3093
        Unknown_expression* ue =
3094
          Expression::make_unknown_reference(named_object, location);
3095
        if (this->is_erroneous_function_)
3096
          ue->set_no_error_message();
3097
        return ue;
3098
      }
3099
    case Named_object::NAMED_OBJECT_PACKAGE:
3100
    case Named_object::NAMED_OBJECT_TYPE:
3101
    case Named_object::NAMED_OBJECT_TYPE_DECLARATION:
3102
      {
3103
        // These cases can arise for a field name in a composite
3104
        // literal.
3105
        Unknown_expression* ue =
3106
          Expression::make_unknown_reference(named_object, location);
3107
        if (this->is_erroneous_function_)
3108
          ue->set_no_error_message();
3109
        return ue;
3110
      }
3111
    case Named_object::NAMED_OBJECT_ERRONEOUS:
3112
      return Expression::make_error(location);
3113
    default:
3114
      error_at(this->location(), "unexpected type of identifier");
3115
      return Expression::make_error(location);
3116
    }
3117
}
3118
 
3119
// Expression = UnaryExpr { binary_op Expression } .
3120
 
3121
// PRECEDENCE is the precedence of the current operator.
3122
 
3123
// If MAY_BE_SINK is true, this expression may be "_".
3124
 
3125
// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3126
// literal.
3127
 
3128
// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3129
// guard (var := expr.("type") using the literal keyword "type").
3130
 
3131
Expression*
3132
Parse::expression(Precedence precedence, bool may_be_sink,
3133
                  bool may_be_composite_lit, bool* is_type_switch)
3134
{
3135
  Expression* left = this->unary_expr(may_be_sink, may_be_composite_lit,
3136
                                      is_type_switch);
3137
 
3138
  while (true)
3139
    {
3140
      if (is_type_switch != NULL && *is_type_switch)
3141
        return left;
3142
 
3143
      const Token* token = this->peek_token();
3144
      if (token->classification() != Token::TOKEN_OPERATOR)
3145
        {
3146
          // Not a binary_op.
3147
          return left;
3148
        }
3149
 
3150
      Precedence right_precedence;
3151
      switch (token->op())
3152
        {
3153
        case OPERATOR_OROR:
3154
          right_precedence = PRECEDENCE_OROR;
3155
          break;
3156
        case OPERATOR_ANDAND:
3157
          right_precedence = PRECEDENCE_ANDAND;
3158
          break;
3159
        case OPERATOR_EQEQ:
3160
        case OPERATOR_NOTEQ:
3161
        case OPERATOR_LT:
3162
        case OPERATOR_LE:
3163
        case OPERATOR_GT:
3164
        case OPERATOR_GE:
3165
          right_precedence = PRECEDENCE_RELOP;
3166
          break;
3167
        case OPERATOR_PLUS:
3168
        case OPERATOR_MINUS:
3169
        case OPERATOR_OR:
3170
        case OPERATOR_XOR:
3171
          right_precedence = PRECEDENCE_ADDOP;
3172
          break;
3173
        case OPERATOR_MULT:
3174
        case OPERATOR_DIV:
3175
        case OPERATOR_MOD:
3176
        case OPERATOR_LSHIFT:
3177
        case OPERATOR_RSHIFT:
3178
        case OPERATOR_AND:
3179
        case OPERATOR_BITCLEAR:
3180
          right_precedence = PRECEDENCE_MULOP;
3181
          break;
3182
        default:
3183
          right_precedence = PRECEDENCE_INVALID;
3184
          break;
3185
        }
3186
 
3187
      if (right_precedence == PRECEDENCE_INVALID)
3188
        {
3189
          // Not a binary_op.
3190
          return left;
3191
        }
3192
 
3193
      Operator op = token->op();
3194
      Location binop_location = token->location();
3195
 
3196
      if (precedence >= right_precedence)
3197
        {
3198
          // We've already seen A * B, and we see + C.  We want to
3199
          // return so that A * B becomes a group.
3200
          return left;
3201
        }
3202
 
3203
      this->advance_token();
3204
 
3205
      left = this->verify_not_sink(left);
3206
      Expression* right = this->expression(right_precedence, false,
3207
                                           may_be_composite_lit,
3208
                                           NULL);
3209
      left = Expression::make_binary(op, left, right, binop_location);
3210
    }
3211
}
3212
 
3213
bool
3214
Parse::expression_may_start_here()
3215
{
3216
  const Token* token = this->peek_token();
3217
  switch (token->classification())
3218
    {
3219
    case Token::TOKEN_INVALID:
3220
    case Token::TOKEN_EOF:
3221
      return false;
3222
    case Token::TOKEN_KEYWORD:
3223
      switch (token->keyword())
3224
        {
3225
        case KEYWORD_CHAN:
3226
        case KEYWORD_FUNC:
3227
        case KEYWORD_MAP:
3228
        case KEYWORD_STRUCT:
3229
        case KEYWORD_INTERFACE:
3230
          return true;
3231
        default:
3232
          return false;
3233
        }
3234
    case Token::TOKEN_IDENTIFIER:
3235
      return true;
3236
    case Token::TOKEN_STRING:
3237
      return true;
3238
    case Token::TOKEN_OPERATOR:
3239
      switch (token->op())
3240
        {
3241
        case OPERATOR_PLUS:
3242
        case OPERATOR_MINUS:
3243
        case OPERATOR_NOT:
3244
        case OPERATOR_XOR:
3245
        case OPERATOR_MULT:
3246
        case OPERATOR_CHANOP:
3247
        case OPERATOR_AND:
3248
        case OPERATOR_LPAREN:
3249
        case OPERATOR_LSQUARE:
3250
          return true;
3251
        default:
3252
          return false;
3253
        }
3254
    case Token::TOKEN_CHARACTER:
3255
    case Token::TOKEN_INTEGER:
3256
    case Token::TOKEN_FLOAT:
3257
    case Token::TOKEN_IMAGINARY:
3258
      return true;
3259
    default:
3260
      go_unreachable();
3261
    }
3262
}
3263
 
3264
// UnaryExpr = unary_op UnaryExpr | PrimaryExpr .
3265
 
3266
// If MAY_BE_SINK is true, this expression may be "_".
3267
 
3268
// If MAY_BE_COMPOSITE_LIT is true, this expression may be a composite
3269
// literal.
3270
 
3271
// If IS_TYPE_SWITCH is not NULL, this will recognize a type switch
3272
// guard (var := expr.("type") using the literal keyword "type").
3273
 
3274
Expression*
3275
Parse::unary_expr(bool may_be_sink, bool may_be_composite_lit,
3276
                  bool* is_type_switch)
3277
{
3278
  const Token* token = this->peek_token();
3279
  if (token->is_op(OPERATOR_PLUS)
3280
      || token->is_op(OPERATOR_MINUS)
3281
      || token->is_op(OPERATOR_NOT)
3282
      || token->is_op(OPERATOR_XOR)
3283
      || token->is_op(OPERATOR_CHANOP)
3284
      || token->is_op(OPERATOR_MULT)
3285
      || token->is_op(OPERATOR_AND))
3286
    {
3287
      Location location = token->location();
3288
      Operator op = token->op();
3289
      this->advance_token();
3290
 
3291
      if (op == OPERATOR_CHANOP
3292
          && this->peek_token()->is_keyword(KEYWORD_CHAN))
3293
        {
3294
          // This is "<- chan" which must be the start of a type.
3295
          this->unget_token(Token::make_operator_token(op, location));
3296
          return Expression::make_type(this->type(), location);
3297
        }
3298
 
3299
      Expression* expr = this->unary_expr(false, may_be_composite_lit, NULL);
3300
      if (expr->is_error_expression())
3301
        ;
3302
      else if (op == OPERATOR_MULT && expr->is_type_expression())
3303
        expr = Expression::make_type(Type::make_pointer_type(expr->type()),
3304
                                     location);
3305
      else if (op == OPERATOR_AND && expr->is_composite_literal())
3306
        expr = Expression::make_heap_composite(expr, location);
3307
      else if (op != OPERATOR_CHANOP)
3308
        expr = Expression::make_unary(op, expr, location);
3309
      else
3310
        expr = Expression::make_receive(expr, location);
3311
      return expr;
3312
    }
3313
  else
3314
    return this->primary_expr(may_be_sink, may_be_composite_lit,
3315
                              is_type_switch);
3316
}
3317
 
3318
// Statement =
3319
//      Declaration | LabeledStmt | SimpleStmt |
3320
//      GoStmt | ReturnStmt | BreakStmt | ContinueStmt | GotoStmt |
3321
//      FallthroughStmt | Block | IfStmt | SwitchStmt | SelectStmt | ForStmt |
3322
//      DeferStmt .
3323
 
3324
// LABEL is the label of this statement if it has one.
3325
 
3326
void
3327
Parse::statement(Label* label)
3328
{
3329
  const Token* token = this->peek_token();
3330
  switch (token->classification())
3331
    {
3332
    case Token::TOKEN_KEYWORD:
3333
      {
3334
        switch (token->keyword())
3335
          {
3336
          case KEYWORD_CONST:
3337
          case KEYWORD_TYPE:
3338
          case KEYWORD_VAR:
3339
            this->declaration();
3340
            break;
3341
          case KEYWORD_FUNC:
3342
          case KEYWORD_MAP:
3343
          case KEYWORD_STRUCT:
3344
          case KEYWORD_INTERFACE:
3345
            this->simple_stat(true, NULL, NULL, NULL);
3346
            break;
3347
          case KEYWORD_GO:
3348
          case KEYWORD_DEFER:
3349
            this->go_or_defer_stat();
3350
            break;
3351
          case KEYWORD_RETURN:
3352
            this->return_stat();
3353
            break;
3354
          case KEYWORD_BREAK:
3355
            this->break_stat();
3356
            break;
3357
          case KEYWORD_CONTINUE:
3358
            this->continue_stat();
3359
            break;
3360
          case KEYWORD_GOTO:
3361
            this->goto_stat();
3362
            break;
3363
          case KEYWORD_IF:
3364
            this->if_stat();
3365
            break;
3366
          case KEYWORD_SWITCH:
3367
            this->switch_stat(label);
3368
            break;
3369
          case KEYWORD_SELECT:
3370
            this->select_stat(label);
3371
            break;
3372
          case KEYWORD_FOR:
3373
            this->for_stat(label);
3374
            break;
3375
          default:
3376
            error_at(this->location(), "expected statement");
3377
            this->advance_token();
3378
            break;
3379
          }
3380
      }
3381
      break;
3382
 
3383
    case Token::TOKEN_IDENTIFIER:
3384
      {
3385
        std::string identifier = token->identifier();
3386
        bool is_exported = token->is_identifier_exported();
3387
        Location location = token->location();
3388
        if (this->advance_token()->is_op(OPERATOR_COLON))
3389
          {
3390
            this->advance_token();
3391
            this->labeled_stmt(identifier, location);
3392
          }
3393
        else
3394
          {
3395
            this->unget_token(Token::make_identifier_token(identifier,
3396
                                                           is_exported,
3397
                                                           location));
3398
            this->simple_stat(true, NULL, NULL, NULL);
3399
          }
3400
      }
3401
      break;
3402
 
3403
    case Token::TOKEN_OPERATOR:
3404
      if (token->is_op(OPERATOR_LCURLY))
3405
        {
3406
          Location location = token->location();
3407
          this->gogo_->start_block(location);
3408
          Location end_loc = this->block();
3409
          this->gogo_->add_block(this->gogo_->finish_block(end_loc),
3410
                                 location);
3411
        }
3412
      else if (!token->is_op(OPERATOR_SEMICOLON))
3413
        this->simple_stat(true, NULL, NULL, NULL);
3414
      break;
3415
 
3416
    case Token::TOKEN_STRING:
3417
    case Token::TOKEN_CHARACTER:
3418
    case Token::TOKEN_INTEGER:
3419
    case Token::TOKEN_FLOAT:
3420
    case Token::TOKEN_IMAGINARY:
3421
      this->simple_stat(true, NULL, NULL, NULL);
3422
      break;
3423
 
3424
    default:
3425
      error_at(this->location(), "expected statement");
3426
      this->advance_token();
3427
      break;
3428
    }
3429
}
3430
 
3431
bool
3432
Parse::statement_may_start_here()
3433
{
3434
  const Token* token = this->peek_token();
3435
  switch (token->classification())
3436
    {
3437
    case Token::TOKEN_KEYWORD:
3438
      {
3439
        switch (token->keyword())
3440
          {
3441
          case KEYWORD_CONST:
3442
          case KEYWORD_TYPE:
3443
          case KEYWORD_VAR:
3444
          case KEYWORD_FUNC:
3445
          case KEYWORD_MAP:
3446
          case KEYWORD_STRUCT:
3447
          case KEYWORD_INTERFACE:
3448
          case KEYWORD_GO:
3449
          case KEYWORD_DEFER:
3450
          case KEYWORD_RETURN:
3451
          case KEYWORD_BREAK:
3452
          case KEYWORD_CONTINUE:
3453
          case KEYWORD_GOTO:
3454
          case KEYWORD_IF:
3455
          case KEYWORD_SWITCH:
3456
          case KEYWORD_SELECT:
3457
          case KEYWORD_FOR:
3458
            return true;
3459
 
3460
          default:
3461
            return false;
3462
          }
3463
      }
3464
      break;
3465
 
3466
    case Token::TOKEN_IDENTIFIER:
3467
      return true;
3468
 
3469
    case Token::TOKEN_OPERATOR:
3470
      if (token->is_op(OPERATOR_LCURLY)
3471
          || token->is_op(OPERATOR_SEMICOLON))
3472
        return true;
3473
      else
3474
        return this->expression_may_start_here();
3475
 
3476
    case Token::TOKEN_STRING:
3477
    case Token::TOKEN_CHARACTER:
3478
    case Token::TOKEN_INTEGER:
3479
    case Token::TOKEN_FLOAT:
3480
    case Token::TOKEN_IMAGINARY:
3481
      return true;
3482
 
3483
    default:
3484
      return false;
3485
    }
3486
}
3487
 
3488
// LabeledStmt = Label ":" Statement .
3489
// Label       = identifier .
3490
 
3491
void
3492
Parse::labeled_stmt(const std::string& label_name, Location location)
3493
{
3494
  Label* label = this->gogo_->add_label_definition(label_name, location);
3495
 
3496
  if (this->peek_token()->is_op(OPERATOR_RCURLY))
3497
    {
3498
      // This is a label at the end of a block.  A program is
3499
      // permitted to omit a semicolon here.
3500
      return;
3501
    }
3502
 
3503
  if (!this->statement_may_start_here())
3504
    {
3505
      // Mark the label as used to avoid a useless error about an
3506
      // unused label.
3507
      label->set_is_used();
3508
 
3509
      error_at(location, "missing statement after label");
3510
      this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
3511
                                                   location));
3512
      return;
3513
    }
3514
 
3515
  this->statement(label);
3516
}
3517
 
3518
// SimpleStmt = EmptyStmt | ExpressionStmt | SendStmt | IncDecStmt |
3519
//      Assignment | ShortVarDecl .
3520
 
3521
// EmptyStmt was handled in Parse::statement.
3522
 
3523
// In order to make this work for if and switch statements, if
3524
// RETURN_EXP is not NULL, and we see an ExpressionStat, we return the
3525
// expression rather than adding an expression statement to the
3526
// current block.  If we see something other than an ExpressionStat,
3527
// we add the statement, set *RETURN_EXP to true if we saw a send
3528
// statement, and return NULL.  The handling of send statements is for
3529
// better error messages.
3530
 
3531
// If P_RANGE_CLAUSE is not NULL, then this will recognize a
3532
// RangeClause.
3533
 
3534
// If P_TYPE_SWITCH is not NULL, this will recognize a type switch
3535
// guard (var := expr.("type") using the literal keyword "type").
3536
 
3537
Expression*
3538
Parse::simple_stat(bool may_be_composite_lit, bool* return_exp,
3539
                   Range_clause* p_range_clause, Type_switch* p_type_switch)
3540
{
3541
  const Token* token = this->peek_token();
3542
 
3543
  // An identifier follow by := is a SimpleVarDecl.
3544
  if (token->is_identifier())
3545
    {
3546
      std::string identifier = token->identifier();
3547
      bool is_exported = token->is_identifier_exported();
3548
      Location location = token->location();
3549
 
3550
      token = this->advance_token();
3551
      if (token->is_op(OPERATOR_COLONEQ)
3552
          || token->is_op(OPERATOR_COMMA))
3553
        {
3554
          identifier = this->gogo_->pack_hidden_name(identifier, is_exported);
3555
          this->simple_var_decl_or_assignment(identifier, location,
3556
                                              p_range_clause,
3557
                                              (token->is_op(OPERATOR_COLONEQ)
3558
                                               ? p_type_switch
3559
                                               : NULL));
3560
          return NULL;
3561
        }
3562
 
3563
      this->unget_token(Token::make_identifier_token(identifier, is_exported,
3564
                                                     location));
3565
    }
3566
 
3567
  Expression* exp = this->expression(PRECEDENCE_NORMAL, true,
3568
                                     may_be_composite_lit,
3569
                                     (p_type_switch == NULL
3570
                                      ? NULL
3571
                                      : &p_type_switch->found));
3572
  if (p_type_switch != NULL && p_type_switch->found)
3573
    {
3574
      p_type_switch->name.clear();
3575
      p_type_switch->location = exp->location();
3576
      p_type_switch->expr = this->verify_not_sink(exp);
3577
      return NULL;
3578
    }
3579
  token = this->peek_token();
3580
  if (token->is_op(OPERATOR_CHANOP))
3581
    {
3582
      this->send_stmt(this->verify_not_sink(exp));
3583
      if (return_exp != NULL)
3584
        *return_exp = true;
3585
    }
3586
  else if (token->is_op(OPERATOR_PLUSPLUS)
3587
           || token->is_op(OPERATOR_MINUSMINUS))
3588
    this->inc_dec_stat(this->verify_not_sink(exp));
3589
  else if (token->is_op(OPERATOR_COMMA)
3590
           || token->is_op(OPERATOR_EQ))
3591
    this->assignment(exp, p_range_clause);
3592
  else if (token->is_op(OPERATOR_PLUSEQ)
3593
           || token->is_op(OPERATOR_MINUSEQ)
3594
           || token->is_op(OPERATOR_OREQ)
3595
           || token->is_op(OPERATOR_XOREQ)
3596
           || token->is_op(OPERATOR_MULTEQ)
3597
           || token->is_op(OPERATOR_DIVEQ)
3598
           || token->is_op(OPERATOR_MODEQ)
3599
           || token->is_op(OPERATOR_LSHIFTEQ)
3600
           || token->is_op(OPERATOR_RSHIFTEQ)
3601
           || token->is_op(OPERATOR_ANDEQ)
3602
           || token->is_op(OPERATOR_BITCLEAREQ))
3603
    this->assignment(this->verify_not_sink(exp), p_range_clause);
3604
  else if (return_exp != NULL)
3605
    return this->verify_not_sink(exp);
3606
  else
3607
    {
3608
      exp = this->verify_not_sink(exp);
3609
 
3610
      if (token->is_op(OPERATOR_COLONEQ))
3611
        {
3612
          if (!exp->is_error_expression())
3613
            error_at(token->location(), "non-name on left side of %<:=%>");
3614
          this->gogo_->mark_locals_used();
3615
          while (!token->is_op(OPERATOR_SEMICOLON)
3616
                 && !token->is_eof())
3617
            token = this->advance_token();
3618
          return NULL;
3619
        }
3620
 
3621
      this->expression_stat(exp);
3622
    }
3623
 
3624
  return NULL;
3625
}
3626
 
3627
bool
3628
Parse::simple_stat_may_start_here()
3629
{
3630
  return this->expression_may_start_here();
3631
}
3632
 
3633
// Parse { Statement ";" } which is used in a few places.  The list of
3634
// statements may end with a right curly brace, in which case the
3635
// semicolon may be omitted.
3636
 
3637
void
3638
Parse::statement_list()
3639
{
3640
  while (this->statement_may_start_here())
3641
    {
3642
      this->statement(NULL);
3643
      if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3644
        this->advance_token();
3645
      else if (this->peek_token()->is_op(OPERATOR_RCURLY))
3646
        break;
3647
      else
3648
        {
3649
          if (!this->peek_token()->is_eof() || !saw_errors())
3650
            error_at(this->location(), "expected %<;%> or %<}%> or newline");
3651
          if (!this->skip_past_error(OPERATOR_RCURLY))
3652
            return;
3653
        }
3654
    }
3655
}
3656
 
3657
bool
3658
Parse::statement_list_may_start_here()
3659
{
3660
  return this->statement_may_start_here();
3661
}
3662
 
3663
// ExpressionStat = Expression .
3664
 
3665
void
3666
Parse::expression_stat(Expression* exp)
3667
{
3668
  this->gogo_->add_statement(Statement::make_statement(exp, false));
3669
}
3670
 
3671
// SendStmt = Channel "&lt;-" Expression .
3672
// Channel  = Expression .
3673
 
3674
void
3675
Parse::send_stmt(Expression* channel)
3676
{
3677
  go_assert(this->peek_token()->is_op(OPERATOR_CHANOP));
3678
  Location loc = this->location();
3679
  this->advance_token();
3680
  Expression* val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3681
  Statement* s = Statement::make_send_statement(channel, val, loc);
3682
  this->gogo_->add_statement(s);
3683
}
3684
 
3685
// IncDecStat = Expression ( "++" | "--" ) .
3686
 
3687
void
3688
Parse::inc_dec_stat(Expression* exp)
3689
{
3690
  const Token* token = this->peek_token();
3691
 
3692
  // Lvalue maps require special handling.
3693
  if (exp->index_expression() != NULL)
3694
    exp->index_expression()->set_is_lvalue();
3695
 
3696
  if (token->is_op(OPERATOR_PLUSPLUS))
3697
    this->gogo_->add_statement(Statement::make_inc_statement(exp));
3698
  else if (token->is_op(OPERATOR_MINUSMINUS))
3699
    this->gogo_->add_statement(Statement::make_dec_statement(exp));
3700
  else
3701
    go_unreachable();
3702
  this->advance_token();
3703
}
3704
 
3705
// Assignment = ExpressionList assign_op ExpressionList .
3706
 
3707
// EXP is an expression that we have already parsed.
3708
 
3709
// If RANGE_CLAUSE is not NULL, then this will recognize a
3710
// RangeClause.
3711
 
3712
void
3713
Parse::assignment(Expression* expr, Range_clause* p_range_clause)
3714
{
3715
  Expression_list* vars;
3716
  if (!this->peek_token()->is_op(OPERATOR_COMMA))
3717
    {
3718
      vars = new Expression_list();
3719
      vars->push_back(expr);
3720
    }
3721
  else
3722
    {
3723
      this->advance_token();
3724
      vars = this->expression_list(expr, true);
3725
    }
3726
 
3727
  this->tuple_assignment(vars, p_range_clause);
3728
}
3729
 
3730
// An assignment statement.  LHS is the list of expressions which
3731
// appear on the left hand side.
3732
 
3733
// If RANGE_CLAUSE is not NULL, then this will recognize a
3734
// RangeClause.
3735
 
3736
void
3737
Parse::tuple_assignment(Expression_list* lhs, Range_clause* p_range_clause)
3738
{
3739
  const Token* token = this->peek_token();
3740
  if (!token->is_op(OPERATOR_EQ)
3741
      && !token->is_op(OPERATOR_PLUSEQ)
3742
      && !token->is_op(OPERATOR_MINUSEQ)
3743
      && !token->is_op(OPERATOR_OREQ)
3744
      && !token->is_op(OPERATOR_XOREQ)
3745
      && !token->is_op(OPERATOR_MULTEQ)
3746
      && !token->is_op(OPERATOR_DIVEQ)
3747
      && !token->is_op(OPERATOR_MODEQ)
3748
      && !token->is_op(OPERATOR_LSHIFTEQ)
3749
      && !token->is_op(OPERATOR_RSHIFTEQ)
3750
      && !token->is_op(OPERATOR_ANDEQ)
3751
      && !token->is_op(OPERATOR_BITCLEAREQ))
3752
    {
3753
      error_at(this->location(), "expected assignment operator");
3754
      return;
3755
    }
3756
  Operator op = token->op();
3757
  Location location = token->location();
3758
 
3759
  token = this->advance_token();
3760
 
3761
  if (p_range_clause != NULL && token->is_keyword(KEYWORD_RANGE))
3762
    {
3763
      if (op != OPERATOR_EQ)
3764
        error_at(this->location(), "range clause requires %<=%>");
3765
      this->range_clause_expr(lhs, p_range_clause);
3766
      return;
3767
    }
3768
 
3769
  Expression_list* vals = this->expression_list(NULL, false);
3770
 
3771
  // We've parsed everything; check for errors.
3772
  if (lhs == NULL || vals == NULL)
3773
    return;
3774
  for (Expression_list::const_iterator pe = lhs->begin();
3775
       pe != lhs->end();
3776
       ++pe)
3777
    {
3778
      if ((*pe)->is_error_expression())
3779
        return;
3780
      if (op != OPERATOR_EQ && (*pe)->is_sink_expression())
3781
        error_at((*pe)->location(), "cannot use _ as value");
3782
    }
3783
  for (Expression_list::const_iterator pe = vals->begin();
3784
       pe != vals->end();
3785
       ++pe)
3786
    {
3787
      if ((*pe)->is_error_expression())
3788
        return;
3789
    }
3790
 
3791
  // Map expressions act differently when they are lvalues.
3792
  for (Expression_list::iterator plv = lhs->begin();
3793
       plv != lhs->end();
3794
       ++plv)
3795
    if ((*plv)->index_expression() != NULL)
3796
      (*plv)->index_expression()->set_is_lvalue();
3797
 
3798
  Call_expression* call;
3799
  Index_expression* map_index;
3800
  Receive_expression* receive;
3801
  Type_guard_expression* type_guard;
3802
  if (lhs->size() == vals->size())
3803
    {
3804
      Statement* s;
3805
      if (lhs->size() > 1)
3806
        {
3807
          if (op != OPERATOR_EQ)
3808
            error_at(location, "multiple values only permitted with %<=%>");
3809
          s = Statement::make_tuple_assignment(lhs, vals, location);
3810
        }
3811
      else
3812
        {
3813
          if (op == OPERATOR_EQ)
3814
            s = Statement::make_assignment(lhs->front(), vals->front(),
3815
                                           location);
3816
          else
3817
            s = Statement::make_assignment_operation(op, lhs->front(),
3818
                                                     vals->front(), location);
3819
          delete lhs;
3820
          delete vals;
3821
        }
3822
      this->gogo_->add_statement(s);
3823
    }
3824
  else if (vals->size() == 1
3825
           && (call = (*vals->begin())->call_expression()) != NULL)
3826
    {
3827
      if (op != OPERATOR_EQ)
3828
        error_at(location, "multiple results only permitted with %<=%>");
3829
      delete vals;
3830
      vals = new Expression_list;
3831
      for (unsigned int i = 0; i < lhs->size(); ++i)
3832
        vals->push_back(Expression::make_call_result(call, i));
3833
      Statement* s = Statement::make_tuple_assignment(lhs, vals, location);
3834
      this->gogo_->add_statement(s);
3835
    }
3836
  else if (lhs->size() == 2
3837
           && vals->size() == 1
3838
           && (map_index = (*vals->begin())->index_expression()) != NULL)
3839
    {
3840
      if (op != OPERATOR_EQ)
3841
        error_at(location, "two values from map requires %<=%>");
3842
      Expression* val = lhs->front();
3843
      Expression* present = lhs->back();
3844
      Statement* s = Statement::make_tuple_map_assignment(val, present,
3845
                                                          map_index, location);
3846
      this->gogo_->add_statement(s);
3847
    }
3848
  else if (lhs->size() == 1
3849
           && vals->size() == 2
3850
           && (map_index = lhs->front()->index_expression()) != NULL)
3851
    {
3852
      if (op != OPERATOR_EQ)
3853
        error_at(location, "assigning tuple to map index requires %<=%>");
3854
      Expression* val = vals->front();
3855
      Expression* should_set = vals->back();
3856
      Statement* s = Statement::make_map_assignment(map_index, val, should_set,
3857
                                                    location);
3858
      this->gogo_->add_statement(s);
3859
    }
3860
  else if (lhs->size() == 2
3861
           && vals->size() == 1
3862
           && (receive = (*vals->begin())->receive_expression()) != NULL)
3863
    {
3864
      if (op != OPERATOR_EQ)
3865
        error_at(location, "two values from receive requires %<=%>");
3866
      Expression* val = lhs->front();
3867
      Expression* success = lhs->back();
3868
      Expression* channel = receive->channel();
3869
      Statement* s = Statement::make_tuple_receive_assignment(val, success,
3870
                                                              channel,
3871
                                                              location);
3872
      this->gogo_->add_statement(s);
3873
    }
3874
  else if (lhs->size() == 2
3875
           && vals->size() == 1
3876
           && (type_guard = (*vals->begin())->type_guard_expression()) != NULL)
3877
    {
3878
      if (op != OPERATOR_EQ)
3879
        error_at(location, "two values from type guard requires %<=%>");
3880
      Expression* val = lhs->front();
3881
      Expression* ok = lhs->back();
3882
      Expression* expr = type_guard->expr();
3883
      Type* type = type_guard->type();
3884
      Statement* s = Statement::make_tuple_type_guard_assignment(val, ok,
3885
                                                                 expr, type,
3886
                                                                 location);
3887
      this->gogo_->add_statement(s);
3888
    }
3889
  else
3890
    {
3891
      error_at(location, "number of variables does not match number of values");
3892
    }
3893
}
3894
 
3895
// GoStat = "go" Expression .
3896
// DeferStat = "defer" Expression .
3897
 
3898
void
3899
Parse::go_or_defer_stat()
3900
{
3901
  go_assert(this->peek_token()->is_keyword(KEYWORD_GO)
3902
             || this->peek_token()->is_keyword(KEYWORD_DEFER));
3903
  bool is_go = this->peek_token()->is_keyword(KEYWORD_GO);
3904
  Location stat_location = this->location();
3905
  this->advance_token();
3906
  Location expr_location = this->location();
3907
  Expression* expr = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
3908
  Call_expression* call_expr = expr->call_expression();
3909
  if (call_expr == NULL)
3910
    {
3911
      error_at(expr_location, "expected call expression");
3912
      return;
3913
    }
3914
 
3915
  // Make it easier to simplify go/defer statements by putting every
3916
  // statement in its own block.
3917
  this->gogo_->start_block(stat_location);
3918
  Statement* stat;
3919
  if (is_go)
3920
    stat = Statement::make_go_statement(call_expr, stat_location);
3921
  else
3922
    stat = Statement::make_defer_statement(call_expr, stat_location);
3923
  this->gogo_->add_statement(stat);
3924
  this->gogo_->add_block(this->gogo_->finish_block(stat_location),
3925
                         stat_location);
3926
}
3927
 
3928
// ReturnStat = "return" [ ExpressionList ] .
3929
 
3930
void
3931
Parse::return_stat()
3932
{
3933
  go_assert(this->peek_token()->is_keyword(KEYWORD_RETURN));
3934
  Location location = this->location();
3935
  this->advance_token();
3936
  Expression_list* vals = NULL;
3937
  if (this->expression_may_start_here())
3938
    vals = this->expression_list(NULL, false);
3939
  this->gogo_->add_statement(Statement::make_return_statement(vals, location));
3940
 
3941
  if (vals == NULL
3942
      && this->gogo_->current_function()->func_value()->results_are_named())
3943
    {
3944
      Named_object* function = this->gogo_->current_function();
3945
      Function::Results* results = function->func_value()->result_variables();
3946
      for (Function::Results::const_iterator p = results->begin();
3947
           p != results->end();
3948
           ++p)
3949
        {
3950
          Named_object* no = this->gogo_->lookup((*p)->name(), NULL);
3951
          go_assert(no != NULL);
3952
          if (!no->is_result_variable())
3953
            error_at(location, "%qs is shadowed during return",
3954
                     (*p)->message_name().c_str());
3955
        }
3956
    }
3957
}
3958
 
3959
// IfStmt = "if" [ SimpleStmt ";" ] Expression Block
3960
//          [ "else" ( IfStmt | Block ) ] .
3961
 
3962
void
3963
Parse::if_stat()
3964
{
3965
  go_assert(this->peek_token()->is_keyword(KEYWORD_IF));
3966
  Location location = this->location();
3967
  this->advance_token();
3968
 
3969
  this->gogo_->start_block(location);
3970
 
3971
  bool saw_simple_stat = false;
3972
  Expression* cond = NULL;
3973
  bool saw_send_stmt;
3974
  if (this->simple_stat_may_start_here())
3975
    {
3976
      cond = this->simple_stat(false, &saw_send_stmt, NULL, NULL);
3977
      saw_simple_stat = true;
3978
    }
3979
  if (cond != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
3980
    {
3981
      // The SimpleStat is an expression statement.
3982
      this->expression_stat(cond);
3983
      cond = NULL;
3984
    }
3985
  if (cond == NULL)
3986
    {
3987
      if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
3988
        this->advance_token();
3989
      else if (saw_simple_stat)
3990
        {
3991
          if (saw_send_stmt)
3992
            error_at(this->location(),
3993
                     ("send statement used as value; "
3994
                      "use select for non-blocking send"));
3995
          else
3996
            error_at(this->location(),
3997
                     "expected %<;%> after statement in if expression");
3998
          if (!this->expression_may_start_here())
3999
            cond = Expression::make_error(this->location());
4000
        }
4001
      if (cond == NULL && this->peek_token()->is_op(OPERATOR_LCURLY))
4002
        {
4003
          error_at(this->location(),
4004
                   "missing condition in if statement");
4005
          cond = Expression::make_error(this->location());
4006
        }
4007
      if (cond == NULL)
4008
        cond = this->expression(PRECEDENCE_NORMAL, false, false, NULL);
4009
    }
4010
 
4011
  this->gogo_->start_block(this->location());
4012
  Location end_loc = this->block();
4013
  Block* then_block = this->gogo_->finish_block(end_loc);
4014
 
4015
  // Check for the easy error of a newline before "else".
4016
  if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4017
    {
4018
      Location semi_loc = this->location();
4019
      if (this->advance_token()->is_keyword(KEYWORD_ELSE))
4020
        error_at(this->location(),
4021
                 "unexpected semicolon or newline before %<else%>");
4022
      else
4023
        this->unget_token(Token::make_operator_token(OPERATOR_SEMICOLON,
4024
                                                     semi_loc));
4025
    }
4026
 
4027
  Block* else_block = NULL;
4028
  if (this->peek_token()->is_keyword(KEYWORD_ELSE))
4029
    {
4030
      this->gogo_->start_block(this->location());
4031
      const Token* token = this->advance_token();
4032
      if (token->is_keyword(KEYWORD_IF))
4033
        this->if_stat();
4034
      else if (token->is_op(OPERATOR_LCURLY))
4035
        this->block();
4036
      else
4037
        {
4038
          error_at(this->location(), "expected %<if%> or %<{%>");
4039
          this->statement(NULL);
4040
        }
4041
      else_block = this->gogo_->finish_block(this->location());
4042
    }
4043
 
4044
  this->gogo_->add_statement(Statement::make_if_statement(cond, then_block,
4045
                                                          else_block,
4046
                                                          location));
4047
 
4048
  this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4049
                         location);
4050
}
4051
 
4052
// SwitchStmt = ExprSwitchStmt | TypeSwitchStmt .
4053
// ExprSwitchStmt = "switch" [ [ SimpleStat ] ";" ] [ Expression ]
4054
//                      "{" { ExprCaseClause } "}" .
4055
// TypeSwitchStmt  = "switch" [ [ SimpleStat ] ";" ] TypeSwitchGuard
4056
//                      "{" { TypeCaseClause } "}" .
4057
// TypeSwitchGuard = [ identifier ":=" ] Expression "." "(" "type" ")" .
4058
 
4059
void
4060
Parse::switch_stat(Label* label)
4061
{
4062
  go_assert(this->peek_token()->is_keyword(KEYWORD_SWITCH));
4063
  Location location = this->location();
4064
  this->advance_token();
4065
 
4066
  this->gogo_->start_block(location);
4067
 
4068
  bool saw_simple_stat = false;
4069
  Expression* switch_val = NULL;
4070
  bool saw_send_stmt;
4071
  Type_switch type_switch;
4072
  bool have_type_switch_block = false;
4073
  if (this->simple_stat_may_start_here())
4074
    {
4075
      switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4076
                                     &type_switch);
4077
      saw_simple_stat = true;
4078
    }
4079
  if (switch_val != NULL && this->peek_token()->is_op(OPERATOR_SEMICOLON))
4080
    {
4081
      // The SimpleStat is an expression statement.
4082
      this->expression_stat(switch_val);
4083
      switch_val = NULL;
4084
    }
4085
  if (switch_val == NULL && !type_switch.found)
4086
    {
4087
      if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4088
        this->advance_token();
4089
      else if (saw_simple_stat)
4090
        {
4091
          if (saw_send_stmt)
4092
            error_at(this->location(),
4093
                     ("send statement used as value; "
4094
                      "use select for non-blocking send"));
4095
          else
4096
            error_at(this->location(),
4097
                     "expected %<;%> after statement in switch expression");
4098
        }
4099
      if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4100
        {
4101
          if (this->peek_token()->is_identifier())
4102
            {
4103
              const Token* token = this->peek_token();
4104
              std::string identifier = token->identifier();
4105
              bool is_exported = token->is_identifier_exported();
4106
              Location id_loc = token->location();
4107
 
4108
              token = this->advance_token();
4109
              bool is_coloneq = token->is_op(OPERATOR_COLONEQ);
4110
              this->unget_token(Token::make_identifier_token(identifier,
4111
                                                             is_exported,
4112
                                                             id_loc));
4113
              if (is_coloneq)
4114
                {
4115
                  // This must be a TypeSwitchGuard.  It is in a
4116
                  // different block from any initial SimpleStat.
4117
                  if (saw_simple_stat)
4118
                    {
4119
                      this->gogo_->start_block(id_loc);
4120
                      have_type_switch_block = true;
4121
                    }
4122
 
4123
                  switch_val = this->simple_stat(false, &saw_send_stmt, NULL,
4124
                                                 &type_switch);
4125
                  if (!type_switch.found)
4126
                    {
4127
                      if (switch_val == NULL
4128
                          || !switch_val->is_error_expression())
4129
                        {
4130
                          error_at(id_loc, "expected type switch assignment");
4131
                          switch_val = Expression::make_error(id_loc);
4132
                        }
4133
                    }
4134
                }
4135
            }
4136
          if (switch_val == NULL && !type_switch.found)
4137
            {
4138
              switch_val = this->expression(PRECEDENCE_NORMAL, false, false,
4139
                                            &type_switch.found);
4140
              if (type_switch.found)
4141
                {
4142
                  type_switch.name.clear();
4143
                  type_switch.expr = switch_val;
4144
                  type_switch.location = switch_val->location();
4145
                }
4146
            }
4147
        }
4148
    }
4149
 
4150
  if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4151
    {
4152
      Location token_loc = this->location();
4153
      if (this->peek_token()->is_op(OPERATOR_SEMICOLON)
4154
          && this->advance_token()->is_op(OPERATOR_LCURLY))
4155
        error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4156
      else if (this->peek_token()->is_op(OPERATOR_COLONEQ))
4157
        {
4158
          error_at(token_loc, "invalid variable name");
4159
          this->advance_token();
4160
          this->expression(PRECEDENCE_NORMAL, false, false,
4161
                           &type_switch.found);
4162
          if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4163
            this->advance_token();
4164
          if (!this->peek_token()->is_op(OPERATOR_LCURLY))
4165
            {
4166
              if (have_type_switch_block)
4167
                this->gogo_->add_block(this->gogo_->finish_block(location),
4168
                                       location);
4169
              this->gogo_->add_block(this->gogo_->finish_block(location),
4170
                                     location);
4171
              return;
4172
            }
4173
          if (type_switch.found)
4174
            type_switch.expr = Expression::make_error(location);
4175
        }
4176
      else
4177
        {
4178
          error_at(this->location(), "expected %<{%>");
4179
          if (have_type_switch_block)
4180
            this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4181
                                   location);
4182
          this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4183
                                 location);
4184
          return;
4185
        }
4186
    }
4187
  this->advance_token();
4188
 
4189
  Statement* statement;
4190
  if (type_switch.found)
4191
    statement = this->type_switch_body(label, type_switch, location);
4192
  else
4193
    statement = this->expr_switch_body(label, switch_val, location);
4194
 
4195
  if (statement != NULL)
4196
    this->gogo_->add_statement(statement);
4197
 
4198
  if (have_type_switch_block)
4199
    this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4200
                           location);
4201
 
4202
  this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4203
                         location);
4204
}
4205
 
4206
// The body of an expression switch.
4207
//   "{" { ExprCaseClause } "}"
4208
 
4209
Statement*
4210
Parse::expr_switch_body(Label* label, Expression* switch_val,
4211
                        Location location)
4212
{
4213
  Switch_statement* statement = Statement::make_switch_statement(switch_val,
4214
                                                                 location);
4215
 
4216
  this->push_break_statement(statement, label);
4217
 
4218
  Case_clauses* case_clauses = new Case_clauses();
4219
  bool saw_default = false;
4220
  while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4221
    {
4222
      if (this->peek_token()->is_eof())
4223
        {
4224
          if (!saw_errors())
4225
            error_at(this->location(), "missing %<}%>");
4226
          return NULL;
4227
        }
4228
      this->expr_case_clause(case_clauses, &saw_default);
4229
    }
4230
  this->advance_token();
4231
 
4232
  statement->add_clauses(case_clauses);
4233
 
4234
  this->pop_break_statement();
4235
 
4236
  return statement;
4237
}
4238
 
4239
// ExprCaseClause = ExprSwitchCase ":" [ StatementList ] .
4240
// FallthroughStat = "fallthrough" .
4241
 
4242
void
4243
Parse::expr_case_clause(Case_clauses* clauses, bool* saw_default)
4244
{
4245
  Location location = this->location();
4246
 
4247
  bool is_default = false;
4248
  Expression_list* vals = this->expr_switch_case(&is_default);
4249
 
4250
  if (!this->peek_token()->is_op(OPERATOR_COLON))
4251
    {
4252
      if (!saw_errors())
4253
        error_at(this->location(), "expected %<:%>");
4254
      return;
4255
    }
4256
  else
4257
    this->advance_token();
4258
 
4259
  Block* statements = NULL;
4260
  if (this->statement_list_may_start_here())
4261
    {
4262
      this->gogo_->start_block(this->location());
4263
      this->statement_list();
4264
      statements = this->gogo_->finish_block(this->location());
4265
    }
4266
 
4267
  bool is_fallthrough = false;
4268
  if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4269
    {
4270
      is_fallthrough = true;
4271
      if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4272
        this->advance_token();
4273
    }
4274
 
4275
  if (is_default)
4276
    {
4277
      if (*saw_default)
4278
        {
4279
          error_at(location, "multiple defaults in switch");
4280
          return;
4281
        }
4282
      *saw_default = true;
4283
    }
4284
 
4285
  if (is_default || vals != NULL)
4286
    clauses->add(vals, is_default, statements, is_fallthrough, location);
4287
}
4288
 
4289
// ExprSwitchCase = "case" ExpressionList | "default" .
4290
 
4291
Expression_list*
4292
Parse::expr_switch_case(bool* is_default)
4293
{
4294
  const Token* token = this->peek_token();
4295
  if (token->is_keyword(KEYWORD_CASE))
4296
    {
4297
      this->advance_token();
4298
      return this->expression_list(NULL, false);
4299
    }
4300
  else if (token->is_keyword(KEYWORD_DEFAULT))
4301
    {
4302
      this->advance_token();
4303
      *is_default = true;
4304
      return NULL;
4305
    }
4306
  else
4307
    {
4308
      if (!saw_errors())
4309
        error_at(this->location(), "expected %<case%> or %<default%>");
4310
      if (!token->is_op(OPERATOR_RCURLY))
4311
        this->advance_token();
4312
      return NULL;
4313
    }
4314
}
4315
 
4316
// The body of a type switch.
4317
//   "{" { TypeCaseClause } "}" .
4318
 
4319
Statement*
4320
Parse::type_switch_body(Label* label, const Type_switch& type_switch,
4321
                        Location location)
4322
{
4323
  Named_object* switch_no = NULL;
4324
  if (!type_switch.name.empty())
4325
    {
4326
      if (Gogo::is_sink_name(type_switch.name))
4327
        error_at(type_switch.location,
4328
                 "no new variables on left side of %<:=%>");
4329
      else
4330
        {
4331
          Variable* switch_var = new Variable(NULL, type_switch.expr, false,
4332
                                              false, false,
4333
                                              type_switch.location);
4334
          switch_no = this->gogo_->add_variable(type_switch.name, switch_var);
4335
        }
4336
    }
4337
 
4338
  Type_switch_statement* statement =
4339
    Statement::make_type_switch_statement(switch_no,
4340
                                          (switch_no == NULL
4341
                                           ? type_switch.expr
4342
                                           : NULL),
4343
                                          location);
4344
 
4345
  this->push_break_statement(statement, label);
4346
 
4347
  Type_case_clauses* case_clauses = new Type_case_clauses();
4348
  bool saw_default = false;
4349
  while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4350
    {
4351
      if (this->peek_token()->is_eof())
4352
        {
4353
          error_at(this->location(), "missing %<}%>");
4354
          return NULL;
4355
        }
4356
      this->type_case_clause(switch_no, case_clauses, &saw_default);
4357
    }
4358
  this->advance_token();
4359
 
4360
  statement->add_clauses(case_clauses);
4361
 
4362
  this->pop_break_statement();
4363
 
4364
  return statement;
4365
}
4366
 
4367
// TypeCaseClause  = TypeSwitchCase ":" [ StatementList ] .
4368
 
4369
void
4370
Parse::type_case_clause(Named_object* switch_no, Type_case_clauses* clauses,
4371
                        bool* saw_default)
4372
{
4373
  Location location = this->location();
4374
 
4375
  std::vector<Type*> types;
4376
  bool is_default = false;
4377
  this->type_switch_case(&types, &is_default);
4378
 
4379
  if (!this->peek_token()->is_op(OPERATOR_COLON))
4380
    error_at(this->location(), "expected %<:%>");
4381
  else
4382
    this->advance_token();
4383
 
4384
  Block* statements = NULL;
4385
  if (this->statement_list_may_start_here())
4386
    {
4387
      this->gogo_->start_block(this->location());
4388
      if (switch_no != NULL && types.size() == 1)
4389
        {
4390
          Type* type = types.front();
4391
          Expression* init = Expression::make_var_reference(switch_no,
4392
                                                            location);
4393
          init = Expression::make_type_guard(init, type, location);
4394
          Variable* v = new Variable(type, init, false, false, false,
4395
                                     location);
4396
          v->set_is_type_switch_var();
4397
          Named_object* no = this->gogo_->add_variable(switch_no->name(), v);
4398
 
4399
          // We don't want to issue an error if the compiler
4400
          // introduced special variable is not used.  Instead we want
4401
          // to issue an error if the variable defined by the switch
4402
          // is not used.  That is handled via type_switch_vars_ and
4403
          // Parse::mark_var_used.
4404
          v->set_is_used();
4405
          this->type_switch_vars_[no] = switch_no;
4406
        }
4407
      this->statement_list();
4408
      statements = this->gogo_->finish_block(this->location());
4409
    }
4410
 
4411
  if (this->peek_token()->is_keyword(KEYWORD_FALLTHROUGH))
4412
    {
4413
      error_at(this->location(),
4414
               "fallthrough is not permitted in a type switch");
4415
      if (this->advance_token()->is_op(OPERATOR_SEMICOLON))
4416
        this->advance_token();
4417
    }
4418
 
4419
  if (is_default)
4420
    {
4421
      go_assert(types.empty());
4422
      if (*saw_default)
4423
        {
4424
          error_at(location, "multiple defaults in type switch");
4425
          return;
4426
        }
4427
      *saw_default = true;
4428
      clauses->add(NULL, false, true, statements, location);
4429
    }
4430
  else if (!types.empty())
4431
    {
4432
      for (std::vector<Type*>::const_iterator p = types.begin();
4433
           p + 1 != types.end();
4434
           ++p)
4435
        clauses->add(*p, true, false, NULL, location);
4436
      clauses->add(types.back(), false, false, statements, location);
4437
    }
4438
  else
4439
    clauses->add(Type::make_error_type(), false, false, statements, location);
4440
}
4441
 
4442
// TypeSwitchCase  = "case" type | "default"
4443
 
4444
// We accept a comma separated list of types.
4445
 
4446
void
4447
Parse::type_switch_case(std::vector<Type*>* types, bool* is_default)
4448
{
4449
  const Token* token = this->peek_token();
4450
  if (token->is_keyword(KEYWORD_CASE))
4451
    {
4452
      this->advance_token();
4453
      while (true)
4454
        {
4455
          Type* t = this->type();
4456
 
4457
          if (!t->is_error_type())
4458
            types->push_back(t);
4459
          else
4460
            {
4461
              this->gogo_->mark_locals_used();
4462
              token = this->peek_token();
4463
              while (!token->is_op(OPERATOR_COLON)
4464
                     && !token->is_op(OPERATOR_COMMA)
4465
                     && !token->is_op(OPERATOR_RCURLY)
4466
                     && !token->is_eof())
4467
                token = this->advance_token();
4468
            }
4469
 
4470
          if (!this->peek_token()->is_op(OPERATOR_COMMA))
4471
            break;
4472
          this->advance_token();
4473
        }
4474
    }
4475
  else if (token->is_keyword(KEYWORD_DEFAULT))
4476
    {
4477
      this->advance_token();
4478
      *is_default = true;
4479
    }
4480
  else
4481
    {
4482
      error_at(this->location(), "expected %<case%> or %<default%>");
4483
      if (!token->is_op(OPERATOR_RCURLY))
4484
        this->advance_token();
4485
    }
4486
}
4487
 
4488
// SelectStat = "select" "{" { CommClause } "}" .
4489
 
4490
void
4491
Parse::select_stat(Label* label)
4492
{
4493
  go_assert(this->peek_token()->is_keyword(KEYWORD_SELECT));
4494
  Location location = this->location();
4495
  const Token* token = this->advance_token();
4496
 
4497
  if (!token->is_op(OPERATOR_LCURLY))
4498
    {
4499
      Location token_loc = token->location();
4500
      if (token->is_op(OPERATOR_SEMICOLON)
4501
          && this->advance_token()->is_op(OPERATOR_LCURLY))
4502
        error_at(token_loc, "unexpected semicolon or newline before %<{%>");
4503
      else
4504
        {
4505
          error_at(this->location(), "expected %<{%>");
4506
          return;
4507
        }
4508
    }
4509
  this->advance_token();
4510
 
4511
  Select_statement* statement = Statement::make_select_statement(location);
4512
 
4513
  this->push_break_statement(statement, label);
4514
 
4515
  Select_clauses* select_clauses = new Select_clauses();
4516
  bool saw_default = false;
4517
  while (!this->peek_token()->is_op(OPERATOR_RCURLY))
4518
    {
4519
      if (this->peek_token()->is_eof())
4520
        {
4521
          error_at(this->location(), "expected %<}%>");
4522
          return;
4523
        }
4524
      this->comm_clause(select_clauses, &saw_default);
4525
    }
4526
 
4527
  this->advance_token();
4528
 
4529
  statement->add_clauses(select_clauses);
4530
 
4531
  this->pop_break_statement();
4532
 
4533
  this->gogo_->add_statement(statement);
4534
}
4535
 
4536
// CommClause = CommCase ":" { Statement ";" } .
4537
 
4538
void
4539
Parse::comm_clause(Select_clauses* clauses, bool* saw_default)
4540
{
4541
  Location location = this->location();
4542
  bool is_send = false;
4543
  Expression* channel = NULL;
4544
  Expression* val = NULL;
4545
  Expression* closed = NULL;
4546
  std::string varname;
4547
  std::string closedname;
4548
  bool is_default = false;
4549
  bool got_case = this->comm_case(&is_send, &channel, &val, &closed,
4550
                                  &varname, &closedname, &is_default);
4551
 
4552
  if (!is_send
4553
      && varname.empty()
4554
      && closedname.empty()
4555
      && val != NULL
4556
      && val->index_expression() != NULL)
4557
    val->index_expression()->set_is_lvalue();
4558
 
4559
  if (this->peek_token()->is_op(OPERATOR_COLON))
4560
    this->advance_token();
4561
  else
4562
    error_at(this->location(), "expected colon");
4563
 
4564
  this->gogo_->start_block(this->location());
4565
 
4566
  Named_object* var = NULL;
4567
  if (!varname.empty())
4568
    {
4569
      // FIXME: LOCATION is slightly wrong here.
4570
      Variable* v = new Variable(NULL, channel, false, false, false,
4571
                                 location);
4572
      v->set_type_from_chan_element();
4573
      var = this->gogo_->add_variable(varname, v);
4574
    }
4575
 
4576
  Named_object* closedvar = NULL;
4577
  if (!closedname.empty())
4578
    {
4579
      // FIXME: LOCATION is slightly wrong here.
4580
      Variable* v = new Variable(Type::lookup_bool_type(), NULL,
4581
                                 false, false, false, location);
4582
      closedvar = this->gogo_->add_variable(closedname, v);
4583
    }
4584
 
4585
  this->statement_list();
4586
 
4587
  Block* statements = this->gogo_->finish_block(this->location());
4588
 
4589
  if (is_default)
4590
    {
4591
      if (*saw_default)
4592
        {
4593
          error_at(location, "multiple defaults in select");
4594
          return;
4595
        }
4596
      *saw_default = true;
4597
    }
4598
 
4599
  if (got_case)
4600
    clauses->add(is_send, channel, val, closed, var, closedvar, is_default,
4601
                 statements, location);
4602
  else if (statements != NULL)
4603
    {
4604
      // Add the statements to make sure that any names they define
4605
      // are traversed.
4606
      this->gogo_->add_block(statements, location);
4607
    }
4608
}
4609
 
4610
// CommCase   = "case" ( SendStmt | RecvStmt ) | "default" .
4611
 
4612
bool
4613
Parse::comm_case(bool* is_send, Expression** channel, Expression** val,
4614
                 Expression** closed, std::string* varname,
4615
                 std::string* closedname, bool* is_default)
4616
{
4617
  const Token* token = this->peek_token();
4618
  if (token->is_keyword(KEYWORD_DEFAULT))
4619
    {
4620
      this->advance_token();
4621
      *is_default = true;
4622
    }
4623
  else if (token->is_keyword(KEYWORD_CASE))
4624
    {
4625
      this->advance_token();
4626
      if (!this->send_or_recv_stmt(is_send, channel, val, closed, varname,
4627
                                   closedname))
4628
        return false;
4629
    }
4630
  else
4631
    {
4632
      error_at(this->location(), "expected %<case%> or %<default%>");
4633
      if (!token->is_op(OPERATOR_RCURLY))
4634
        this->advance_token();
4635
      return false;
4636
    }
4637
 
4638
  return true;
4639
}
4640
 
4641
// RecvStmt   = [ Expression [ "," Expression ] ( "=" | ":=" ) ] RecvExpr .
4642
// RecvExpr   = Expression .
4643
 
4644
bool
4645
Parse::send_or_recv_stmt(bool* is_send, Expression** channel, Expression** val,
4646
                         Expression** closed, std::string* varname,
4647
                         std::string* closedname)
4648
{
4649
  const Token* token = this->peek_token();
4650
  bool saw_comma = false;
4651
  bool closed_is_id = false;
4652
  if (token->is_identifier())
4653
    {
4654
      Gogo* gogo = this->gogo_;
4655
      std::string recv_var = token->identifier();
4656
      bool is_rv_exported = token->is_identifier_exported();
4657
      Location recv_var_loc = token->location();
4658
      token = this->advance_token();
4659
      if (token->is_op(OPERATOR_COLONEQ))
4660
        {
4661
          // case rv := <-c:
4662
          this->advance_token();
4663
          Expression* e = this->expression(PRECEDENCE_NORMAL, false, false,
4664
                                           NULL);
4665
          Receive_expression* re = e->receive_expression();
4666
          if (re == NULL)
4667
            {
4668
              if (!e->is_error_expression())
4669
                error_at(this->location(), "expected receive expression");
4670
              return false;
4671
            }
4672
          if (recv_var == "_")
4673
            {
4674
              error_at(recv_var_loc,
4675
                       "no new variables on left side of %<:=%>");
4676
              recv_var = "blank";
4677
            }
4678
          *is_send = false;
4679
          *varname = gogo->pack_hidden_name(recv_var, is_rv_exported);
4680
          *channel = re->channel();
4681
          return true;
4682
        }
4683
      else if (token->is_op(OPERATOR_COMMA))
4684
        {
4685
          token = this->advance_token();
4686
          if (token->is_identifier())
4687
            {
4688
              std::string recv_closed = token->identifier();
4689
              bool is_rc_exported = token->is_identifier_exported();
4690
              Location recv_closed_loc = token->location();
4691
              closed_is_id = true;
4692
 
4693
              token = this->advance_token();
4694
              if (token->is_op(OPERATOR_COLONEQ))
4695
                {
4696
                  // case rv, rc := <-c:
4697
                  this->advance_token();
4698
                  Expression* e = this->expression(PRECEDENCE_NORMAL, false,
4699
                                                   false, NULL);
4700
                  Receive_expression* re = e->receive_expression();
4701
                  if (re == NULL)
4702
                    {
4703
                      if (!e->is_error_expression())
4704
                        error_at(this->location(),
4705
                                 "expected receive expression");
4706
                      return false;
4707
                    }
4708
                  if (recv_var == "_" && recv_closed == "_")
4709
                    {
4710
                      error_at(recv_var_loc,
4711
                               "no new variables on left side of %<:=%>");
4712
                      recv_var = "blank";
4713
                    }
4714
                  *is_send = false;
4715
                  if (recv_var != "_")
4716
                    *varname = gogo->pack_hidden_name(recv_var,
4717
                                                      is_rv_exported);
4718
                  if (recv_closed != "_")
4719
                    *closedname = gogo->pack_hidden_name(recv_closed,
4720
                                                         is_rc_exported);
4721
                  *channel = re->channel();
4722
                  return true;
4723
                }
4724
 
4725
              this->unget_token(Token::make_identifier_token(recv_closed,
4726
                                                             is_rc_exported,
4727
                                                             recv_closed_loc));
4728
            }
4729
 
4730
          *val = this->id_to_expression(gogo->pack_hidden_name(recv_var,
4731
                                                               is_rv_exported),
4732
                                        recv_var_loc);
4733
          saw_comma = true;
4734
        }
4735
      else
4736
        this->unget_token(Token::make_identifier_token(recv_var,
4737
                                                       is_rv_exported,
4738
                                                       recv_var_loc));
4739
    }
4740
 
4741
  // If SAW_COMMA is false, then we are looking at the start of the
4742
  // send or receive expression.  If SAW_COMMA is true, then *VAL is
4743
  // set and we just read a comma.
4744
 
4745
  Expression* e;
4746
  if (saw_comma || !this->peek_token()->is_op(OPERATOR_CHANOP))
4747
    e = this->expression(PRECEDENCE_NORMAL, true, true, NULL);
4748
  else
4749
    {
4750
      // case <-c:
4751
      *is_send = false;
4752
      this->advance_token();
4753
      *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4754
 
4755
      // The next token should be ':'.  If it is '<-', then we have
4756
      // case <-c <- v:
4757
      // which is to say, send on a channel received from a channel.
4758
      if (!this->peek_token()->is_op(OPERATOR_CHANOP))
4759
        return true;
4760
 
4761
      e = Expression::make_receive(*channel, (*channel)->location());
4762
    }
4763
 
4764
  if (this->peek_token()->is_op(OPERATOR_EQ))
4765
    {
4766
      if (!this->advance_token()->is_op(OPERATOR_CHANOP))
4767
        {
4768
          error_at(this->location(), "missing %<<-%>");
4769
          return false;
4770
        }
4771
      *is_send = false;
4772
      this->advance_token();
4773
      *channel = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4774
      if (saw_comma)
4775
        {
4776
          // case v, e = <-c:
4777
          // *VAL is already set.
4778
          if (!e->is_sink_expression())
4779
            *closed = e;
4780
        }
4781
      else
4782
        {
4783
          // case v = <-c:
4784
          if (!e->is_sink_expression())
4785
            *val = e;
4786
        }
4787
      return true;
4788
    }
4789
 
4790
  if (saw_comma)
4791
    {
4792
      if (closed_is_id)
4793
        error_at(this->location(), "expected %<=%> or %<:=%>");
4794
      else
4795
        error_at(this->location(), "expected %<=%>");
4796
      return false;
4797
    }
4798
 
4799
  if (this->peek_token()->is_op(OPERATOR_CHANOP))
4800
    {
4801
      // case c <- v:
4802
      *is_send = true;
4803
      *channel = this->verify_not_sink(e);
4804
      this->advance_token();
4805
      *val = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4806
      return true;
4807
    }
4808
 
4809
  error_at(this->location(), "expected %<<-%> or %<=%>");
4810
  return false;
4811
}
4812
 
4813
// ForStat = "for" [ Condition | ForClause | RangeClause ] Block .
4814
// Condition = Expression .
4815
 
4816
void
4817
Parse::for_stat(Label* label)
4818
{
4819
  go_assert(this->peek_token()->is_keyword(KEYWORD_FOR));
4820
  Location location = this->location();
4821
  const Token* token = this->advance_token();
4822
 
4823
  // Open a block to hold any variables defined in the init statement
4824
  // of the for statement.
4825
  this->gogo_->start_block(location);
4826
 
4827
  Block* init = NULL;
4828
  Expression* cond = NULL;
4829
  Block* post = NULL;
4830
  Range_clause range_clause;
4831
 
4832
  if (!token->is_op(OPERATOR_LCURLY))
4833
    {
4834
      if (token->is_keyword(KEYWORD_VAR))
4835
        {
4836
          error_at(this->location(),
4837
                   "var declaration not allowed in for initializer");
4838
          this->var_decl();
4839
        }
4840
 
4841
      if (token->is_op(OPERATOR_SEMICOLON))
4842
        this->for_clause(&cond, &post);
4843
      else
4844
        {
4845
          // We might be looking at a Condition, an InitStat, or a
4846
          // RangeClause.
4847
          bool saw_send_stmt;
4848
          cond = this->simple_stat(false, &saw_send_stmt, &range_clause, NULL);
4849
          if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
4850
            {
4851
              if (cond == NULL && !range_clause.found)
4852
                {
4853
                  if (saw_send_stmt)
4854
                    error_at(this->location(),
4855
                             ("send statement used as value; "
4856
                              "use select for non-blocking send"));
4857
                  else
4858
                    error_at(this->location(), "parse error in for statement");
4859
                }
4860
            }
4861
          else
4862
            {
4863
              if (range_clause.found)
4864
                error_at(this->location(), "parse error after range clause");
4865
 
4866
              if (cond != NULL)
4867
                {
4868
                  // COND is actually an expression statement for
4869
                  // InitStat at the start of a ForClause.
4870
                  this->expression_stat(cond);
4871
                  cond = NULL;
4872
                }
4873
 
4874
              this->for_clause(&cond, &post);
4875
            }
4876
        }
4877
    }
4878
 
4879
  // Build the For_statement and note that it is the current target
4880
  // for break and continue statements.
4881
 
4882
  For_statement* sfor;
4883
  For_range_statement* srange;
4884
  Statement* s;
4885
  if (!range_clause.found)
4886
    {
4887
      sfor = Statement::make_for_statement(init, cond, post, location);
4888
      s = sfor;
4889
      srange = NULL;
4890
    }
4891
  else
4892
    {
4893
      srange = Statement::make_for_range_statement(range_clause.index,
4894
                                                   range_clause.value,
4895
                                                   range_clause.range,
4896
                                                   location);
4897
      s = srange;
4898
      sfor = NULL;
4899
    }
4900
 
4901
  this->push_break_statement(s, label);
4902
  this->push_continue_statement(s, label);
4903
 
4904
  // Gather the block of statements in the loop and add them to the
4905
  // For_statement.
4906
 
4907
  this->gogo_->start_block(this->location());
4908
  Location end_loc = this->block();
4909
  Block* statements = this->gogo_->finish_block(end_loc);
4910
 
4911
  if (sfor != NULL)
4912
    sfor->add_statements(statements);
4913
  else
4914
    srange->add_statements(statements);
4915
 
4916
  // This is no longer the break/continue target.
4917
  this->pop_break_statement();
4918
  this->pop_continue_statement();
4919
 
4920
  // Add the For_statement to the list of statements, and close out
4921
  // the block we started to hold any variables defined in the for
4922
  // statement.
4923
 
4924
  this->gogo_->add_statement(s);
4925
 
4926
  this->gogo_->add_block(this->gogo_->finish_block(this->location()),
4927
                         location);
4928
}
4929
 
4930
// ForClause = [ InitStat ] ";" [ Condition ] ";" [ PostStat ] .
4931
// InitStat = SimpleStat .
4932
// PostStat = SimpleStat .
4933
 
4934
// We have already read InitStat at this point.
4935
 
4936
void
4937
Parse::for_clause(Expression** cond, Block** post)
4938
{
4939
  go_assert(this->peek_token()->is_op(OPERATOR_SEMICOLON));
4940
  this->advance_token();
4941
  if (this->peek_token()->is_op(OPERATOR_SEMICOLON))
4942
    *cond = NULL;
4943
  else if (this->peek_token()->is_op(OPERATOR_LCURLY))
4944
    {
4945
      error_at(this->location(),
4946
               "unexpected semicolon or newline before %<{%>");
4947
      *cond = NULL;
4948
      *post = NULL;
4949
      return;
4950
    }
4951
  else
4952
    *cond = this->expression(PRECEDENCE_NORMAL, false, true, NULL);
4953
  if (!this->peek_token()->is_op(OPERATOR_SEMICOLON))
4954
    error_at(this->location(), "expected semicolon");
4955
  else
4956
    this->advance_token();
4957
 
4958
  if (this->peek_token()->is_op(OPERATOR_LCURLY))
4959
    *post = NULL;
4960
  else
4961
    {
4962
      this->gogo_->start_block(this->location());
4963
      this->simple_stat(false, NULL, NULL, NULL);
4964
      *post = this->gogo_->finish_block(this->location());
4965
    }
4966
}
4967
 
4968
// RangeClause = IdentifierList ( "=" | ":=" ) "range" Expression .
4969
 
4970
// This is the := version.  It is called with a list of identifiers.
4971
 
4972
void
4973
Parse::range_clause_decl(const Typed_identifier_list* til,
4974
                         Range_clause* p_range_clause)
4975
{
4976
  go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
4977
  Location location = this->location();
4978
 
4979
  p_range_clause->found = true;
4980
 
4981
  go_assert(til->size() >= 1);
4982
  if (til->size() > 2)
4983
    error_at(this->location(), "too many variables for range clause");
4984
 
4985
  this->advance_token();
4986
  Expression* expr = this->expression(PRECEDENCE_NORMAL, false, false, NULL);
4987
  p_range_clause->range = expr;
4988
 
4989
  bool any_new = false;
4990
 
4991
  const Typed_identifier* pti = &til->front();
4992
  Named_object* no = this->init_var(*pti, NULL, expr, true, true, &any_new);
4993
  if (any_new && no->is_variable())
4994
    no->var_value()->set_type_from_range_index();
4995
  p_range_clause->index = Expression::make_var_reference(no, location);
4996
 
4997
  if (til->size() == 1)
4998
    p_range_clause->value = NULL;
4999
  else
5000
    {
5001
      pti = &til->back();
5002
      bool is_new = false;
5003
      no = this->init_var(*pti, NULL, expr, true, true, &is_new);
5004
      if (is_new && no->is_variable())
5005
        no->var_value()->set_type_from_range_value();
5006
      if (is_new)
5007
        any_new = true;
5008
      p_range_clause->value = Expression::make_var_reference(no, location);
5009
    }
5010
 
5011
  if (!any_new)
5012
    error_at(location, "variables redeclared but no variable is new");
5013
}
5014
 
5015
// The = version of RangeClause.  This is called with a list of
5016
// expressions.
5017
 
5018
void
5019
Parse::range_clause_expr(const Expression_list* vals,
5020
                         Range_clause* p_range_clause)
5021
{
5022
  go_assert(this->peek_token()->is_keyword(KEYWORD_RANGE));
5023
 
5024
  p_range_clause->found = true;
5025
 
5026
  go_assert(vals->size() >= 1);
5027
  if (vals->size() > 2)
5028
    error_at(this->location(), "too many variables for range clause");
5029
 
5030
  this->advance_token();
5031
  p_range_clause->range = this->expression(PRECEDENCE_NORMAL, false, false,
5032
                                           NULL);
5033
 
5034
  p_range_clause->index = vals->front();
5035
  if (vals->size() == 1)
5036
    p_range_clause->value = NULL;
5037
  else
5038
    p_range_clause->value = vals->back();
5039
}
5040
 
5041
// Push a statement on the break stack.
5042
 
5043
void
5044
Parse::push_break_statement(Statement* enclosing, Label* label)
5045
{
5046
  if (this->break_stack_ == NULL)
5047
    this->break_stack_ = new Bc_stack();
5048
  this->break_stack_->push_back(std::make_pair(enclosing, label));
5049
}
5050
 
5051
// Push a statement on the continue stack.
5052
 
5053
void
5054
Parse::push_continue_statement(Statement* enclosing, Label* label)
5055
{
5056
  if (this->continue_stack_ == NULL)
5057
    this->continue_stack_ = new Bc_stack();
5058
  this->continue_stack_->push_back(std::make_pair(enclosing, label));
5059
}
5060
 
5061
// Pop the break stack.
5062
 
5063
void
5064
Parse::pop_break_statement()
5065
{
5066
  this->break_stack_->pop_back();
5067
}
5068
 
5069
// Pop the continue stack.
5070
 
5071
void
5072
Parse::pop_continue_statement()
5073
{
5074
  this->continue_stack_->pop_back();
5075
}
5076
 
5077
// Find a break or continue statement given a label name.
5078
 
5079
Statement*
5080
Parse::find_bc_statement(const Bc_stack* bc_stack, const std::string& label)
5081
{
5082
  if (bc_stack == NULL)
5083
    return NULL;
5084
  for (Bc_stack::const_reverse_iterator p = bc_stack->rbegin();
5085
       p != bc_stack->rend();
5086
       ++p)
5087
    {
5088
      if (p->second != NULL && p->second->name() == label)
5089
        {
5090
          p->second->set_is_used();
5091
          return p->first;
5092
        }
5093
    }
5094
  return NULL;
5095
}
5096
 
5097
// BreakStat = "break" [ identifier ] .
5098
 
5099
void
5100
Parse::break_stat()
5101
{
5102
  go_assert(this->peek_token()->is_keyword(KEYWORD_BREAK));
5103
  Location location = this->location();
5104
 
5105
  const Token* token = this->advance_token();
5106
  Statement* enclosing;
5107
  if (!token->is_identifier())
5108
    {
5109
      if (this->break_stack_ == NULL || this->break_stack_->empty())
5110
        {
5111
          error_at(this->location(),
5112
                   "break statement not within for or switch or select");
5113
          return;
5114
        }
5115
      enclosing = this->break_stack_->back().first;
5116
    }
5117
  else
5118
    {
5119
      enclosing = this->find_bc_statement(this->break_stack_,
5120
                                          token->identifier());
5121
      if (enclosing == NULL)
5122
        {
5123
          // If there is a label with this name, mark it as used to
5124
          // avoid a useless error about an unused label.
5125
          this->gogo_->add_label_reference(token->identifier(),
5126
                                           Linemap::unknown_location(), false);
5127
 
5128
          error_at(token->location(), "invalid break label %qs",
5129
                   Gogo::message_name(token->identifier()).c_str());
5130
          this->advance_token();
5131
          return;
5132
        }
5133
      this->advance_token();
5134
    }
5135
 
5136
  Unnamed_label* label;
5137
  if (enclosing->classification() == Statement::STATEMENT_FOR)
5138
    label = enclosing->for_statement()->break_label();
5139
  else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5140
    label = enclosing->for_range_statement()->break_label();
5141
  else if (enclosing->classification() == Statement::STATEMENT_SWITCH)
5142
    label = enclosing->switch_statement()->break_label();
5143
  else if (enclosing->classification() == Statement::STATEMENT_TYPE_SWITCH)
5144
    label = enclosing->type_switch_statement()->break_label();
5145
  else if (enclosing->classification() == Statement::STATEMENT_SELECT)
5146
    label = enclosing->select_statement()->break_label();
5147
  else
5148
    go_unreachable();
5149
 
5150
  this->gogo_->add_statement(Statement::make_break_statement(label,
5151
                                                             location));
5152
}
5153
 
5154
// ContinueStat = "continue" [ identifier ] .
5155
 
5156
void
5157
Parse::continue_stat()
5158
{
5159
  go_assert(this->peek_token()->is_keyword(KEYWORD_CONTINUE));
5160
  Location location = this->location();
5161
 
5162
  const Token* token = this->advance_token();
5163
  Statement* enclosing;
5164
  if (!token->is_identifier())
5165
    {
5166
      if (this->continue_stack_ == NULL || this->continue_stack_->empty())
5167
        {
5168
          error_at(this->location(), "continue statement not within for");
5169
          return;
5170
        }
5171
      enclosing = this->continue_stack_->back().first;
5172
    }
5173
  else
5174
    {
5175
      enclosing = this->find_bc_statement(this->continue_stack_,
5176
                                          token->identifier());
5177
      if (enclosing == NULL)
5178
        {
5179
          // If there is a label with this name, mark it as used to
5180
          // avoid a useless error about an unused label.
5181
          this->gogo_->add_label_reference(token->identifier(),
5182
                                           Linemap::unknown_location(), false);
5183
 
5184
          error_at(token->location(), "invalid continue label %qs",
5185
                   Gogo::message_name(token->identifier()).c_str());
5186
          this->advance_token();
5187
          return;
5188
        }
5189
      this->advance_token();
5190
    }
5191
 
5192
  Unnamed_label* label;
5193
  if (enclosing->classification() == Statement::STATEMENT_FOR)
5194
    label = enclosing->for_statement()->continue_label();
5195
  else if (enclosing->classification() == Statement::STATEMENT_FOR_RANGE)
5196
    label = enclosing->for_range_statement()->continue_label();
5197
  else
5198
    go_unreachable();
5199
 
5200
  this->gogo_->add_statement(Statement::make_continue_statement(label,
5201
                                                                location));
5202
}
5203
 
5204
// GotoStat = "goto" identifier .
5205
 
5206
void
5207
Parse::goto_stat()
5208
{
5209
  go_assert(this->peek_token()->is_keyword(KEYWORD_GOTO));
5210
  Location location = this->location();
5211
  const Token* token = this->advance_token();
5212
  if (!token->is_identifier())
5213
    error_at(this->location(), "expected label for goto");
5214
  else
5215
    {
5216
      Label* label = this->gogo_->add_label_reference(token->identifier(),
5217
                                                      location, true);
5218
      Statement* s = Statement::make_goto_statement(label, location);
5219
      this->gogo_->add_statement(s);
5220
      this->advance_token();
5221
    }
5222
}
5223
 
5224
// PackageClause = "package" PackageName .
5225
 
5226
void
5227
Parse::package_clause()
5228
{
5229
  const Token* token = this->peek_token();
5230
  Location location = token->location();
5231
  std::string name;
5232
  if (!token->is_keyword(KEYWORD_PACKAGE))
5233
    {
5234
      error_at(this->location(), "program must start with package clause");
5235
      name = "ERROR";
5236
    }
5237
  else
5238
    {
5239
      token = this->advance_token();
5240
      if (token->is_identifier())
5241
        {
5242
          name = token->identifier();
5243
          if (name == "_")
5244
            {
5245
              error_at(this->location(), "invalid package name _");
5246
              name = "blank";
5247
            }
5248
          this->advance_token();
5249
        }
5250
      else
5251
        {
5252
          error_at(this->location(), "package name must be an identifier");
5253
          name = "ERROR";
5254
        }
5255
    }
5256
  this->gogo_->set_package_name(name, location);
5257
}
5258
 
5259
// ImportDecl = "import" Decl<ImportSpec> .
5260
 
5261
void
5262
Parse::import_decl()
5263
{
5264
  go_assert(this->peek_token()->is_keyword(KEYWORD_IMPORT));
5265
  this->advance_token();
5266
  this->decl(&Parse::import_spec, NULL);
5267
}
5268
 
5269
// ImportSpec = [ "." | PackageName ] PackageFileName .
5270
 
5271
void
5272
Parse::import_spec(void*)
5273
{
5274
  const Token* token = this->peek_token();
5275
  Location location = token->location();
5276
 
5277
  std::string local_name;
5278
  bool is_local_name_exported = false;
5279
  if (token->is_op(OPERATOR_DOT))
5280
    {
5281
      local_name = ".";
5282
      token = this->advance_token();
5283
    }
5284
  else if (token->is_identifier())
5285
    {
5286
      local_name = token->identifier();
5287
      is_local_name_exported = token->is_identifier_exported();
5288
      token = this->advance_token();
5289
    }
5290
 
5291
  if (!token->is_string())
5292
    {
5293
      error_at(this->location(), "missing import package name");
5294
      return;
5295
    }
5296
 
5297
  this->gogo_->import_package(token->string_value(), local_name,
5298
                              is_local_name_exported, location);
5299
 
5300
  this->advance_token();
5301
}
5302
 
5303
// SourceFile       = PackageClause ";" { ImportDecl ";" }
5304
//                      { TopLevelDecl ";" } .
5305
 
5306
void
5307
Parse::program()
5308
{
5309
  this->package_clause();
5310
 
5311
  const Token* token = this->peek_token();
5312
  if (token->is_op(OPERATOR_SEMICOLON))
5313
    token = this->advance_token();
5314
  else
5315
    error_at(this->location(),
5316
             "expected %<;%> or newline after package clause");
5317
 
5318
  while (token->is_keyword(KEYWORD_IMPORT))
5319
    {
5320
      this->import_decl();
5321
      token = this->peek_token();
5322
      if (token->is_op(OPERATOR_SEMICOLON))
5323
        token = this->advance_token();
5324
      else
5325
        error_at(this->location(),
5326
                 "expected %<;%> or newline after import declaration");
5327
    }
5328
 
5329
  while (!token->is_eof())
5330
    {
5331
      if (this->declaration_may_start_here())
5332
        this->declaration();
5333
      else
5334
        {
5335
          error_at(this->location(), "expected declaration");
5336
          this->gogo_->mark_locals_used();
5337
          do
5338
            this->advance_token();
5339
          while (!this->peek_token()->is_eof()
5340
                 && !this->peek_token()->is_op(OPERATOR_SEMICOLON)
5341
                 && !this->peek_token()->is_op(OPERATOR_RCURLY));
5342
          if (!this->peek_token()->is_eof()
5343
              && !this->peek_token()->is_op(OPERATOR_SEMICOLON))
5344
            this->advance_token();
5345
        }
5346
      token = this->peek_token();
5347
      if (token->is_op(OPERATOR_SEMICOLON))
5348
        token = this->advance_token();
5349
      else if (!token->is_eof() || !saw_errors())
5350
        {
5351
          if (token->is_op(OPERATOR_CHANOP))
5352
            error_at(this->location(),
5353
                     ("send statement used as value; "
5354
                      "use select for non-blocking send"));
5355
          else
5356
            error_at(this->location(),
5357
                     "expected %<;%> or newline after top level declaration");
5358
          this->skip_past_error(OPERATOR_INVALID);
5359
        }
5360
    }
5361
}
5362
 
5363
// Reset the current iota value.
5364
 
5365
void
5366
Parse::reset_iota()
5367
{
5368
  this->iota_ = 0;
5369
}
5370
 
5371
// Return the current iota value.
5372
 
5373
int
5374
Parse::iota_value()
5375
{
5376
  return this->iota_;
5377
}
5378
 
5379
// Increment the current iota value.
5380
 
5381
void
5382
Parse::increment_iota()
5383
{
5384
  ++this->iota_;
5385
}
5386
 
5387
// Skip forward to a semicolon or OP.  OP will normally be
5388
// OPERATOR_RPAREN or OPERATOR_RCURLY.  If we find a semicolon, move
5389
// past it and return.  If we find OP, it will be the next token to
5390
// read.  Return true if we are OK, false if we found EOF.
5391
 
5392
bool
5393
Parse::skip_past_error(Operator op)
5394
{
5395
  this->gogo_->mark_locals_used();
5396
  const Token* token = this->peek_token();
5397
  while (!token->is_op(op))
5398
    {
5399
      if (token->is_eof())
5400
        return false;
5401
      if (token->is_op(OPERATOR_SEMICOLON))
5402
        {
5403
          this->advance_token();
5404
          return true;
5405
        }
5406
      token = this->advance_token();
5407
    }
5408
  return true;
5409
}
5410
 
5411
// Check that an expression is not a sink.
5412
 
5413
Expression*
5414
Parse::verify_not_sink(Expression* expr)
5415
{
5416
  if (expr->is_sink_expression())
5417
    {
5418
      error_at(expr->location(), "cannot use _ as value");
5419
      expr = Expression::make_error(expr->location());
5420
    }
5421
  return expr;
5422
}
5423
 
5424
// Mark a variable as used.
5425
 
5426
void
5427
Parse::mark_var_used(Named_object* no)
5428
{
5429
  if (no->is_variable())
5430
    {
5431
      no->var_value()->set_is_used();
5432
 
5433
      // When a type switch uses := to define a variable, then for
5434
      // each case with a single type we introduce a new variable with
5435
      // the appropriate type.  When we do, if the newly introduced
5436
      // variable is used, then the type switch variable is used.
5437
      Type_switch_vars::iterator p = this->type_switch_vars_.find(no);
5438
      if (p != this->type_switch_vars_.end())
5439
        p->second->var_value()->set_is_used();
5440
    }
5441
}

powered by: WebSVN 2.1.0

© copyright 1999-2024 OpenCores.org, equivalent to Oliscience, all rights reserved. OpenCores®, registered trademark.