Skip to content
Snippets Groups Projects
DescentParse.h 24.7 KiB
Newer Older
/**************************************************************************/
/*                                                                        */
/*  This file is part of Frama-Clang                                      */
/*                                                                        */
Virgile Prevosto's avatar
Virgile Prevosto committed
/*  Copyright (C) 2012-2022                                               */
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643
/*    CEA (Commissariat à l'énergie atomique et aux énergies              */
/*         alternatives)                                                  */
/*                                                                        */
/*  you can redistribute it and/or modify it under the terms of the GNU   */
/*  Lesser General Public License as published by the Free Software       */
/*  Foundation, version 2.1.                                              */
/*                                                                        */
/*  It is distributed in the hope that it will be useful,                 */
/*  but WITHOUT ANY WARRANTY; without even the implied warranty of        */
/*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         */
/*  GNU Lesser General Public License for more details.                   */
/*                                                                        */
/*  See the GNU Lesser General Public License version 2.1                 */
/*  for more details (enclosed in the file LICENSE).                      */
/*                                                                        */
/**************************************************************************/

//
// Description:
//   Definition of a generic descent parser.
//

#ifndef DescentParserH
#define DescentParserH

#include <iostream>
#include <list>
#include <vector>
#include <memory>
#include <assert.h>
#include <cstring>

/** @file */

/*! @def DefineParameters(ReservedBytes, FormatParameters)
 *  @brief Define many bitfields likely to be grouped. This definition is
 *    compatible with a class hierarchy as soon as the sum of the reserved bits
 *    does not exceed 32.
 *
 *  ReservedBytes is the number of bits reseved for the current class. \n
 *  FormatParameters is the inherited class that contains the params() and 
 *    queryParams() definition -- it is a class derived from FormatParameters.
 *    \n
 *  For example:
 *  \code{cpp}
 *  class Foo : public FormatParameters {
 *  protected:
 *    DefineParameters(5, FormatParameters)
 *  };
 *  \endcode
 *  is equivalent to
 *  \code{cpp}
 *    unsigned ownField : 5;
 *  \endcode
 *  But it has more grouping capabilities.
 */
#define DefineParameters(ReservedBytes, FormatParameters)                      \
  unsigned int& params() { return FormatParameters::params(); }                \
  const unsigned int& queryParams() const                                      \
    { return FormatParameters::queryParams(); }                                \
  static const int START_OF_MASK = FormatParameters::END_OF_MASK;              \
  static const int END_INHERITED_OF_MASK = FormatParameters::END_OF_MASK;      \
  static const int END_OF_MASK = ReservedBytes + START_OF_MASK;                \
  static const unsigned int MASK                                               \
    = ((1 << END_OF_MASK)-1) & ~((1 << START_OF_MASK)-1);                      \
  void clearOwnField() { params() &= ~MASK; }                                  \
  void mergeOwnField(int uField)                                               \
    { params() |= (MASK & (uField << START_OF_MASK)); }                        \
  void intersectOwnField(int uField)                                           \
    { params() &= (MASK & (uField << START_OF_MASK)); }                        \
  void setOwnField(int uField)                                                 \
    { FormatParameters::params() &= ~MASK;                                     \
      params() |= (MASK & (uField << START_OF_MASK));                          \
    }                                                                          \
  bool hasOwnField() const { return queryParams() & MASK; }                    \
  int queryOwnField() const { return (queryParams() & MASK) >> START_OF_MASK; }\
  void setLocalField() { params() &= ((1 << END_OF_MASK)-1); }                 \
  bool hasFieldExtensions() const                                              \
    { return (queryParams() & ~((1 << END_OF_MASK)-1)) != 0; }                 \
  unsigned int queryFieldExtensions() const                                    \
    { return queryParams() >> END_OF_MASK; }

/*! @def DefineSubParameters(Name, ReservedBytes, FormatParameters)
 *  @brief Create a subfield in a given group of bitfields. The sum of
 *    ReservedBytes for all the subfields should be equal to the
 *    ReservedBytes of the group of bitfields.
 *
 *  For example:
 *  \code{cpp}
 *  class Foo : public FormatParameters {
 *  protected:
 *    DefineParameters(5, FormatParameters)
 *    DefineSubParameters(Type, 3, INHERITED)
 *    DefineSubParameters(Verbose, 1, Type)
 *    DefineSubParameters(Pretty, 1, Verbose)
 *  };
 *  \endcode
 *  is equivalent to
 *  \code{cpp}
 *    unsigned type : 3;
 *    bool verbose : 1;
 *    bool pretty : 1;
 *  \endcode
 *  But it has more grouping capabilities.
 */
#define DefineSubParameters(Name, ReservedBytes, FormatParameters)             \
  static const int START_##Name##_OF_MASK = END_##FormatParameters##_OF_MASK;  \
  static const int END_##Name##_OF_MASK                                        \
    = ReservedBytes + END_##FormatParameters##_OF_MASK;                        \
  static const unsigned int Name##_MASK                                        \
    = ((1 << END_##Name##_OF_MASK)-1)                                          \
        & ~((1 << END_##FormatParameters##_OF_MASK)-1);                        \
  void clear##Name##Field() { params() &= ~Name##_MASK; }                      \
  void merge##Name##Field(int uField)                                          \
    { params() |= (Name##_MASK & (uField << START_##Name##_OF_MASK)); }        \
  void intersect##Name##Field(int uField)                                      \
    { params() &= (~Name##_MASK | (Name##_MASK                                 \
          & (uField << START_##Name##_OF_MASK)));                              \
    }                                                                          \
  void set##Name##Field(int uField)                                            \
    { params() &= ~Name##_MASK;                                                \
      params() |= (Name##_MASK & (uField << START_##Name##_OF_MASK));          \
    }                                                                          \
  bool has##Name##Field() const { return queryParams() & Name##_MASK; }        \
  int query##Name##Field() const                                               \
    { return (queryParams() & Name##_MASK) >> START_##Name##_OF_MASK; }

/*! @class FormatParameters
 *  @brief Defines a base class whose derived classes have grouping
 *    bitfield capabilities.
 *
 *  @sa{ DefineParameters, DefineSubParameters }
 */
class FormatParameters {
private:
  unsigned int _params;

protected:
  unsigned int& params() { return _params; }
  const unsigned int& queryParams() const { return _params; }
  static const int END_OF_MASK = 0;
  static const unsigned int MASK = 0;

  public:
  FormatParameters() : _params(0) {}
  FormatParameters(const FormatParameters& source) : _params(source._params) {}
  FormatParameters& operator=(const FormatParameters& source)
    { _params = source._params;
      return *this;
    }
};

namespace Parser {

/*! @class TTextBuffer
 *  @brief Defines a stream of characters that have been read by the Lexer.
 */
template<typename CharType>
class TTextBuffer {
public:
  typedef std::basic_string<CharType> StringBuffer;
  typedef std::list<StringBuffer*> BuffersList;

private:
  typedef TTextBuffer<CharType> thisType;
  BuffersList _buffers;
  std::unique_ptr<StringBuffer> _current;
  unsigned _position;

  void performMove()
    { int defaultSize = _current->capacity();
      _buffers.push_back(_current.release());
      _current.reset(new StringBuffer);
      _current->reserve(defaultSize);
    }
  void completeRead(const CharType* string, int length);
  void completeRead(const StringBuffer& source, size_t position, size_t count);
  void completeWrite(StringBuffer& out);
  CharType completeQueryChar(int index) const;
  int queryPlace() const
    { return _current.get() ? _current->capacity() - _position : 0; }

public:
  TTextBuffer(int defaultLength=5000)
    : _current(new StringBuffer), _position(0)
    { _current->reserve(defaultLength); }


  TTextBuffer(const thisType& source)
    : _buffers(source._buffers),
      _current(const_cast<thisType&>(source)._current.release()),
      _position(source._position) {}

  void clear()
    { typename BuffersList::iterator iterEnd = _buffers.end();
      for(typename BuffersList::iterator iter = _buffers.begin();
          iter != iterEnd; ++iter) {
        StringBuffer* buffer = *iter;
        if (buffer)
          { delete buffer; buffer = NULL; };
      };
      _current->clear();
    }
  thisType& operator<<(CharType ch);
  thisType& operator<<(const CharType* string);
  thisType& readFrom(const StringBuffer& text, size_t position, size_t length);
  thisType& operator>>(StringBuffer& buffer);
  bool isEmpty() const
    { return _buffers.empty() && _current->length() == _position; }
  bool hasOnlyCurrent() const { return _buffers.empty(); }
  const char* current()
    { assert(_buffers.empty() && _current.get()
          && _position <= _current->length());
      return &_current->c_str()[_position];
    }
  CharType getChar(int index) const
    { CharType result;
      if (_current->empty()) {
        assert(_current.get() && ((int) _position >= -index)
            && (index + (int) _position) <= (int) _current->length());
        result = _current->c_str()[index + _position];
      }
      else
        result = completeQueryChar(index); 
      return result;
    }
};

template<typename CharType>
inline TTextBuffer<CharType>&
TTextBuffer<CharType>::operator<<(CharType ch) {
  if (queryPlace() == 0)
    performMove();
  _current->append(1, ch);
  return *this;
}

template<typename CharType>
inline TTextBuffer<CharType>&
TTextBuffer<CharType>::operator<<(const CharType* string) {
  int length = strlen(string);
  if (queryPlace() < length)
    completeRead(string, length);
  else
    _current->append(string, length);
  return *this;
}

template<typename CharType>
inline TTextBuffer<CharType>&
TTextBuffer<CharType>::readFrom(const StringBuffer& string, size_t position,
    size_t count) {
  if (queryPlace() < (int) count)
    completeRead(string, position, count);
  else
    _current->append(string, position, count);
  return *this;
}

template<class TypeSubString>
inline TTextBuffer<TypeSubString>&
TTextBuffer<TypeSubString>::operator>>(StringBuffer& string) {
  if (!_buffers.empty())
    completeWrite(string);
  else {
    string.append(*_current);
    _current->clear();
  };
  return *this;
}

typedef TTextBuffer<char> TextBuffer;

/******************************************/
/* Définition of the template TStateStack */
/******************************************/

/*! @class Base
 *  @brief Gives an access to parsing rules. The parsing rules correspond to
 *    inherited attributes in attribute grammars. They should inherit from
 *    Base::RuleResult. The synthesized attributes may be stored in the
 *    fields of the inherited attributes.
 */
class Base {
public:
  class RuleResult {
  public:
    virtual ~RuleResult() {}
    virtual RuleResult* clone() const { return new RuleResult(*this); }
  };
  enum ReadResult
    { RRNeedChars, RRContinueLexing, RRHasToken, RRContinueParsing,
      RRFinished
    };
};

/*! @class TStateStack
 *  @brief Represents the stack of the grammar rules waiting for a reduction.
 *  The methods shift and reduce enable to push and to pop on the stack.
 */
template <class TypeArguments>
class TStateStack : public Base {
private:
  typedef TStateStack<TypeArguments> thisType;

public:
  typedef TypeArguments ParseArgument;
  class VirtualParseState {
  private:
    int _point;
    std::unique_ptr<RuleResult> _ruleResult;

  public:
    VirtualParseState() : _point(0) {}
    VirtualParseState(const VirtualParseState& source)
      : _point(source._point),
        _ruleResult(source._ruleResult.get()
            ? source._ruleResult->clone() : NULL) {}
    virtual ~VirtualParseState() {}

    virtual VirtualParseState* clone() const
      { return new VirtualParseState(*this); }
    int& point() { return _point; }
    const int& point() const { return _point; }
    virtual ReadResult operator()(TStateStack<TypeArguments>& stateStack,
        ParseArgument& arguments) 
      { assert(false); return RRFinished; }

    bool hasResult() const { return _ruleResult.get(); }
    RuleResult& getResult() const { return *_ruleResult; }
    void setResult(RuleResult* ruleResult)
      { assert(!_ruleResult.get());
        _ruleResult.reset(ruleResult);
      }
    void changeResult(RuleResult* ruleResult)
      { _ruleResult.reset(ruleResult); }
    void freeResult() { _ruleResult.reset(); }
    RuleResult* extractResult() { return _ruleResult.release(); }
  };

  template <class TypeObject, typename ReadPointerMethod>
  class TParseState : public VirtualParseState {
  private:
    ReadPointerMethod _readMethod;
    TypeObject* _object;
    typedef VirtualParseState inherited;
    typedef TParseState<TypeObject, ReadPointerMethod> thisType;

  public:
    TParseState() : _object(NULL), _readMethod(NULL) {}
    TParseState(TypeObject& object, const ReadPointerMethod& readMethodSource)
      : _readMethod(readMethodSource), _object(&object) {}
    TParseState(const thisType& source)
      : inherited(source), _readMethod(source._readMethod),
        _object(source._object) {}
    virtual VirtualParseState* clone() const { return new thisType(*this); }

    virtual ReadResult operator()(
        TStateStack<TypeArguments>& stateStack, ParseArgument& arguments) 
      { return (_object->*_readMethod)(stateStack, arguments); }
    const ReadPointerMethod& getStateMethod() const { return _readMethod; }
    void change(TypeObject& object, ReadPointerMethod readMethod, int point)
      { _object = &object;
        _readMethod = readMethod;
        inherited::point() = point;
      }
    bool hasObjectRead(const TypeObject& object, ReadPointerMethod readMethod)
      { return (_object == &object) && (_readMethod == readMethod); }
    bool hasMethodRead(ReadPointerMethod readMethod)
      { return (_readMethod == readMethod); }
  };

  template <class TypeObject, typename ReadPointerMethod,
            class TypeParseMultiState>
  class TLevelParseState : public VirtualParseState {
  private:
    ReadPointerMethod _readMethod;
    TypeObject* _object;
    typedef VirtualParseState inherited;
    typedef TLevelParseState<TypeObject, ReadPointerMethod, TypeParseMultiState>
      thisType;

  public:
    TLevelParseState() : _object(NULL), _readMethod(NULL) {}
    TLevelParseState(TypeObject& object, const ReadPointerMethod& readMethod)
      : _readMethod(readMethod), _object(&object) {}
    TLevelParseState(const thisType& source)
      : inherited(source), _readMethod(source._readMethod),
        _object(source._object) {}
    virtual VirtualParseState* clone() const { return new thisType(*this); }

    virtual ReadResult operator()(TStateStack<TypeArguments>& stateStack,
        ParseArgument& arguments) 
      { return (_object->*_readMethod)((TypeParseMultiState&) stateStack,
          (typename TypeParseMultiState::ParseArgument&) arguments);
      }
    const ReadPointerMethod& getStateMethod() const { return _readMethod; }
    void change(TypeObject& object, ReadPointerMethod readMethod, int point)
      { _object = &object;
        _readMethod = readMethod;
        inherited::point() = point;
      }
    bool hasObjectRead(const TypeObject& object, ReadPointerMethod readMethod)
        const
      { return (_object == &object) && (_readMethod == readMethod); }
    bool hasMethodRead(ReadPointerMethod readMethod) const
      { return (_readMethod == readMethod); }
  };

protected:
  typedef std::vector<VirtualParseState*> ArrayParseStates;

private:
  ArrayParseStates _states;

protected:
  ArrayParseStates& states() { return _states; }
  const ArrayParseStates& states() const { return _states; }

  template <class TypeObject, typename ReadPointerMethod, class SpecializedThis>
  thisType& _shift(TypeObject& object, ReadPointerMethod parseMethod,
      SpecializedThis* thisState)
    { _states.add(new TLevelParseState<TypeObject, ReadPointerMethod,
          SpecializedThis>(object, parseMethod));
      return *this;
    }
  template <class TypeObject, typename ReadPointerMethod, class SpecializedThis>
  SpecializedThis& _change(TypeObject& object, ReadPointerMethod parseMethod,
      int point, SpecializedThis* thisState)
    { typedef TLevelParseState<TypeObject, ReadPointerMethod,
          SpecializedThis> ParseState;
      assert(!_states.empty()
          && dynamic_cast<ParseState*>(_states.back()) != NULL);
      ((ParseState&) *_states.back()).change(object, parseMethod, point);
      return (SpecializedThis&) *this;
    }
  template <class TypeObject, typename ReadPointerMethod, class SpecializedThis>
  bool _tisAlive(TypeObject& object, ReadPointerMethod parseMethod, int uLevel,
      SpecializedThis* thisState)
    { typedef TLevelParseState<TypeObject, ReadPointerMethod, SpecializedThis>
          ParseState;
      return (_states.count() > uLevel)
          && dynamic_cast<ParseState*>(&_states[uLevel])
          && ((ParseState&) _states[uLevel]).hasObjectRead(object, parseMethod);
    }
  template <class TypeObject, typename ReadPointerMethod, class SpecializedThis>
  bool _tisAlive(TypeObject* object, ReadPointerMethod parseMethod, int level,
      SpecializedThis* thisState)
    { typedef TLevelParseState<TypeObject, ReadPointerMethod, SpecializedThis>
          ParseState;
      return (_states.size() > level)
          && dynamic_cast<ParseState*>(_states[level])
          && ((ParseState&) *_states[level]).hasMethodRead(parseMethod);
    }
  template <class TypeObject, typename ReadPointerMethod, class SpecializedThis>
  bool _tisParentAlive(TypeObject* object, ReadPointerMethod parseMethod,
      SpecializedThis* thisState)
    { typedef TLevelParseState<TypeObject, ReadPointerMethod, SpecializedThis>
          ParseState;
      int count = _states.size();
      return (count > 1) && dynamic_cast<ParseState*>(_states[count-2])
          && ((ParseState&) *_states[count-2]).hasMethodRead(parseMethod);
    }

public:
  TStateStack() {}
  TStateStack(const thisType& source)
    { typename ArrayParseStates::const_iterator iterEnd = source._states.end();
      for (typename ArrayParseStates::const_iterator
          iter = source._states.begin(); iter != iterEnd; ++iter) {
        VirtualParseState* state = *iter;
        _states.push_back(state->clone());
      };
    }
  ~TStateStack()
    { typename ArrayParseStates::iterator iterEnd = _states.end();
      for (typename ArrayParseStates::iterator iter = _states.begin();
          iter != iterEnd; ++iter) {
        VirtualParseState*& state = *iter;
        if (state)
          { delete state; state = NULL; }
      };
    }

  void clear()
    { typename ArrayParseStates::iterator iterEnd = _states.end();
      for (typename ArrayParseStates::iterator iter = _states.begin();
          iter != iterEnd; ++iter) {
        VirtualParseState*& state = *iter;
        if (state)
          { delete state; state = NULL; }
      };
      _states.clear();
    }
  void swap(thisType& source) { _states.swap(source._states); }

  ReadResult parse(ParseArgument& arguments)
    { if (_states.empty()) return Base::RRFinished;
      return (*_states.back())(*this, arguments);
    }
  template <class TypeObject, typename ReadPointerMethod>
  thisType& shift(TypeObject& object, ReadPointerMethod parseMethod)
    { _states.push_back(new TParseState<TypeObject, ReadPointerMethod>(
          object, parseMethod));
      return *this;
    }
  template <class TypeObject, typename ReadPointerMethod>
  thisType& change(TypeObject& object, ReadPointerMethod parseMethod, int point)
    { typedef TParseState<TypeObject, ReadPointerMethod> ParseState;
      assert(!_states.empty()
          && dynamic_cast<ParseState*>(_states.back()) != NULL);
      ((ParseState&) *_states.back()).change(object, parseMethod, point);
      return *this;
    }
  template <class TypeObject, typename ReadPointerMethod>
  bool tisAlive(TypeObject& object, ReadPointerMethod parseMethod, int level)
    { typedef TParseState<TypeObject, ReadPointerMethod> ParseState;
      int count = _states.size();
      return (count > level) && dynamic_cast<ParseState*>(_states[level])
        && ((ParseState&) *_states[level]).hasObjectRead(object, parseMethod);
    }
  template <class TypeObject, typename ReadPointerMethod>
  bool tisAlive(TypeObject* object, ReadPointerMethod parseMethod, int level)
    { typedef TParseState<TypeObject, ReadPointerMethod> ParseState;
      int count = _states.size();
      return (count > level) && dynamic_cast<ParseState*>(&_states[level])
        && ((ParseState&) _states[level]).hasMethodRead(parseMethod);
    }
  template <class TypeObject, typename ReadPointerMethod>
  bool tisParentAlive(TypeObject* object, ReadPointerMethod parseMethod)
    { typedef TParseState<TypeObject, ReadPointerMethod> ParseState;
      int count = _states.size();
      return (count > 1) && dynamic_cast<ParseState*>(&_states[count-2])
        && ((ParseState&) _states[count-2]).hasMethodRead(parseMethod);
    }
  bool isAlive(int level, int point) const
    { return (_states.size() > level) && (_states[level].point() == point); }
  bool isLessThan(int uLevel, int uPoint) const
    { return (_states.size() > uLevel) && (_states[uLevel].point() < uPoint); }
  thisType& reduce()
    { assert(!_states.empty());
      VirtualParseState* oldState = _states.back();
      if (oldState) delete oldState;
      _states.pop_back();
      return *this;
    }

  const int& point() const
    { assert(!_states.empty()); return _states.back()->point(); }
  int& point() { return _states.back()->point(); }
  int getLevel() const { return _states.size()-1; }

  VirtualParseState& last()
    { assert(!_states.empty()); return *_states.back(); }
  const VirtualParseState& last() const
    { assert(!_states.empty()); return *_states.back(); }
  bool isEmpty() const { return _states.empty(); }
  const VirtualParseState& upLast() const
    { typename ArrayParseStates::const_reverse_iterator iter = _states.rbegin();
      assert(iter != _states.rend());
      ++iter;
      assert(iter != _states.rend());
      return **iter;
    }

  void absorbRuleResult(RuleResult* result)
    { last().setResult(result); }
  void changeRuleResult(RuleResult* result)
    { last().changeResult(result); }
  void freeRuleResult() { last().freeResult(); }
  bool hasRuleResult() const { return last().hasResult(); }
  bool hasParentRuleResult() const { return upLast().hasResult(); }

  class ObjectReference {
  private:
    RuleResult& _result;

  public:
    ObjectReference(RuleResult& result) : _result(result) {}
    ObjectReference(const ObjectReference& orSource)
      : _result(orSource._result) {}

    template <class Type> operator Type*() const
      { return (Type*) &_result; }
  };

  class ObjectKeepReference {
  private:
    RuleResult* _result;

  public:
    ObjectKeepReference(RuleResult* result) : _result(result) {}
    ObjectKeepReference(const ObjectKeepReference& source)
      : _result(source._result)
      { const_cast<ObjectKeepReference&>(source)._result = NULL; }
    ~ObjectKeepReference() { if (_result) delete _result; }

    template <class Type> operator Type*()
      { assert(dynamic_cast<Type*>(_result));
        Type* result = (Type*) _result;
        _result = NULL;
        return result;
      }
  };

  class RuleAccess {
  public:
    template <class TypeObject>
    class TCastFromRule {
    private:
      TypeObject* poObject;
      
    public:
      explicit TCastFromRule(const ObjectReference& result)
        : poObject((TypeObject*) result) {}
      operator TypeObject&() const { return *poObject; }
      TypeObject& operator*() const { return *poObject; }
      TypeObject* operator->() const { return poObject; }
      TypeObject* get() const { return poObject; }
    };
  };
  
  RuleResult* extractRuleResult()
    { return last().extractResult(); }
  ObjectReference getRuleResult() const
    { return ObjectReference(last().getResult()); }
  ObjectReference getRuleResultAt(int uLevel) const
    { return ObjectReference(_states[uLevel].getResult()); }
  ObjectKeepReference extractSRuleResult()
    { return ObjectKeepReference(last().extractResult()); }
  ObjectReference getParentRuleResult() const
    { return ObjectReference(upLast().getResult()); }
};

} // end of namespace Parser

#endif // DescentParserH