void BaseSemanticWalker::setCurrentScope(RefPortugolAST id, 
                                         const SymbolList& params) {
  _currentScopeSymbol = 
      _symtable->getSymbol(id->getText(), params.typeList());

  _symtable->setScope(_currentScopeSymbol);
}
예제 #2
0
//==================================================================
bool ParamsFindP(	ParamList &params,
					const SymbolList &globalSymbols,
					DVec<Float3> &out_vectorP,
					int fromIdx )
{
	bool	gotP = false;

	for (size_t i=fromIdx; i < params.size(); i += 2)
	{
		DASSERT( params[i].type == Param::STR );

		const Symbol* pSymbol = globalSymbols.FindSymbol( params[i] );
		if ( pSymbol && pSymbol->IsName( "P" ) )
		{
			DASSTHROW( (i+1) < params.size(), "Invalid number of arguments" );
			
			const FltVec	&fltVec = params[ i+1 ].NumVec();
			
			DASSTHROW( (fltVec.size() % 3) == 0, "Invalid number of arguments" );
			
			out_vectorP.resize( fltVec.size() / 3 );

			for (size_t iv=0, id=0; iv < fltVec.size(); iv += 3)
				out_vectorP[id++] = Float3( &fltVec[ iv ] );

			return true;
		}
	}
	
	return false;
}
void BaseSemanticWalker::declareProc(const Symbol& s, 
                                     SymbolList& params) {
//checar ambiguidades:
//  f(a : inteiro)
//  f(b : inteiro, ... resto)
//  -> declaracao ambigua

  try {
    _symtable->insertSymbol(s);
  } catch (RedeclarationException e) {
    report(e.symbol().line(), e.symbol().column(),
           std::string("redeclaração: ") + e.symbol().lexeme());
    _symtable->setIgnoreScope();
    return;
  } catch (AmbiguousDeclarationException e) {
    report(e.symbol().line(), e.symbol().column(),
           "declaração ambígua com: " + e.otherSymbol().name());
    _symtable->setIgnoreScope();
    return;
  }
  _symtable->setScope(s);
  params.setScope(s.identifier());

  try {
    _symtable->insertSymbols(params);
  } catch (RedeclarationException e) {
    report(e.symbol().line(), e.symbol().column(),
           std::string("redeclaração: ") + e.symbol().lexeme());
  }  
}
예제 #4
0
SymbolArray parseParameterList(CharacterSource* source)
{
    SymbolList list;
    Symbol parameter = parseParameter(source);
    if (!parameter.valid())
        return list;
    list.add(parameter);
    Span span;
    while (Space::parseCharacter(source, ',', &span)) {
        Symbol parameter = parseParameter(source);
        if (!parameter.valid())
            source->location().throwError("Expected parameter");
        list.add(parameter);
    }
    return list;
}
예제 #5
0
  virtual
  void addPair(const Symbol & symbol, const Symbol & ref)
  {
    testSet.addUniq( symbol );

    symbolMap.addPair( symbol, ref );
  }
SymbolList Grammar::get_reachables() {
	SymbolList reachables;
	reachables.push_back(starting_symbol);
	SymbolList prev_reachables;
	do {
		prev_reachables = reachables;
		for( auto &ch : prev_reachables ) {
			for( auto rule : production_rules[get_nt_index(ch)] ) {
				for( auto &symbol : rule ) {
					if( contains_char(reachables, symbol) || contains_char(terminals, symbol) ) { continue; }
					reachables.push_back(symbol);
				}
			}
		}
	} while( prev_reachables != reachables );
	return reachables;
}
SymbolList Grammar::those_that_product(SymbolList& sl) {
	SymbolList ret;
	for( auto CV : sl ) {
		for( auto nT : non_terminals ) {
			for( auto rule : production_rules[get_nt_index(nT)] ) {
				if( sl.size() != rule.size() ) { continue; }
				for( unsigned int i = 0; i < rule.size(); ++i ) {
					if( !(sl[i] == rule[i]) ) { break; }
					if( i == rule.size() - 1 ) {
						ret.push_back(nT);
					}
				}
			}
		}
	}
	return ret;
}
예제 #8
0
void SymbolTable::insertType(const std::string& name,
                             const SymbolList& fields,
                             int line) {

    //checando por campos duplicados na estrutura
    SymbolList::const_iterator dup = fields.duplicated();
    if (dup != fields.end()) {
        throw RedeclarationException(*dup);
    }

    //checando por redefinicao da estrutura
    if (_typeBuilder->typeList().find(name) != _typeBuilder->typeList().end()) {
        throw RedefinedTypeException(name);
    }

    _typeBuilder->typeList().push_back(
        new Type(_typeBuilder, name, fields, _unit, line));
}
void replace_first_of(SymbolList& sl, const Symbol& of, const Symbol& with) {
	//std::cout << "replace_first_with\n";
	for( unsigned int i = 0; i < sl.size(); ++i ) {
		if( sl[i] == of ) {
			sl[i] = with;
			return;
		}
	}
}
예제 #10
0
void BookPublisher::createBook (const char* symbol, const char* partId) 
{ 
    mBook = new MamdaOrderBook();
    // This turns on the generation of deltas at the order book 
    mBook->generateDeltaMsgs (true);
    if (symbol) mBook->setSymbol (symbol); 
    if (partId) mBook->setPartId (partId); 
    mBookTime.setToNow();
    mBook->setBookTime (mBookTime);
    mSymbolList.push_back (symbol);
}
예제 #11
0
std::string widgetAt(const SymbolGroupValueContext &ctx, int x, int y, std::string *errorMessage)
{
    typedef SymbolGroupValue::SymbolList SymbolList;
    // First, resolve symbol since there are ambiguities. Take the first one which is the
    // overload for (int,int) and call by address instead off name to overcome that.
    const QtInfo &qtInfo = QtInfo::get(ctx);
    const std::string func =
        qtInfo.prependQtModule("QApplication::widgetAt",
                               qtInfo.version >= 5 ? QtInfo::Widgets : QtInfo::Gui);
    const SymbolList symbols = SymbolGroupValue::resolveSymbol(func.c_str(), ctx, errorMessage);
    if (symbols.empty())
        return std::string(); // Not a gui application, likely
    std::ostringstream callStr;
    callStr << std::showbase << std::hex << symbols.front().second
            << std::noshowbase << std::dec << '(' << x << ',' << y << ')';
    std::wstring wOutput;
    if (!ExtensionContext::instance().call(callStr.str(), &wOutput, errorMessage))
        return std::string();
    // Returns: ".call returns\nclass QWidget * 0x00000000`022bf100\nbla...".
    // Chop lines in front and after 'class ...' and convert first line.
    const std::wstring::size_type classPos = wOutput.find(L"class ");
    if (classPos == std::wstring::npos) {
        *errorMessage = msgWidgetParseError(wOutput);
        return std::string();
    }
    wOutput.erase(0, classPos + 6);
    const std::wstring::size_type nlPos = wOutput.find(L'\n');
    if (nlPos != std::wstring::npos)
        wOutput.erase(nlPos, wOutput.size() - nlPos);
    const std::string::size_type addressPos = wOutput.find(L" * 0x");
    if (addressPos == std::string::npos) {
        *errorMessage = msgWidgetParseError(wOutput);
        return std::string();
    }
    // "QWidget * 0x00000000`022bf100" -> "QWidget:0x00000000022bf100"
    wOutput.replace(addressPos, 3, L":");
    const std::string::size_type sepPos = wOutput.find(L'`');
    if (sepPos != std::string::npos)
        wOutput.erase(sepPos, 1);
    return wStringToString(wOutput);
}
예제 #12
0
void AllContainersInFileIterator::Init
(
    CompilerFile *pFile,
    bool fIncludePartialContainers,
    bool fIncludeTransientSymbols
)
{
    if (pFile != NULL)
    {
        SymbolList *pList = pFile->GetNamespaceLevelSymbolList();

        m_pNext = pList->GetFirst();
    }
    else
    {
        m_pNext =  NULL;
    }

    m_fIncludePartialContainers = fIncludePartialContainers;
    m_fIncludeTransientSymbols = fIncludeTransientSymbols;
}
예제 #13
0
  virtual
  void reportResults (CReport & report)
  {
    trial( testSet, notCirc, symbolMap);

    if (testSet.size() == 0) return;

    report.addAtLine(1, "Circularities found");

    stringstream str;

    str << testSet << ends;

    report.addAtLine(2, str.str() );
  }
void BaseSemanticWalker::declareProc(RefPortugolAST id,
                                     SymbolList& params,
                                     Type *rettype) {

  Type *type = _typeBuilder->subprogramType(params.typeList(), rettype);

  Symbol s(id->getText(),
            type,
            _symtable->globalScope(),
            _symtable->unit(),
            id->getLine(),
            id->getColumn());

  declareProc(s, params);

}
void MamaEntitle::readSymbolsFromFile (void) 
{
        /* get subjects from file or interactively */
        FILE* fp = NULL;
        char charbuf[1024];

        if (mFilename && mFilename[0] )
        {
            if ((fp = fopen (mFilename, "r")) == (FILE *)NULL)
            {
                perror (mFilename);
                exit (1);
            }
        }
        else
        {
            fp = stdin;
        }
        if (isatty(fileno (fp)))
        {
            printf ("Enter one symbol per line and terminate with a .\n");
            printf ("Symbol> ");
        }

        while (fgets (charbuf, 1023, fp))
        {
            /* replace newlines with NULLs */
            char *c = charbuf;

            /* Input terminate case */
            if (*c == '.')
                break;

            while ((*c != '\0') && (*c != '\n'))
            {
                c++;
            }
            *c = '\0';

            /* copy the string and subscribe */
            mSymbolList.push_back (strdup (charbuf));
            if (isatty(fileno (fp)))
            {
              printf ("Symbol> ");
            }
        }
}
예제 #16
0
void Preprocessor::setSymbols(const SymbolList& symbols)
{
    uint nb_symbols = symbols.size();
    this->symbols.resize(nb_symbols);

#ifdef PREPROC_KEEP_ORIGINAL_SYMBOLS
    this->original_symbols.resize(nb_symbols);
#endif

    for(uint i=0 ; i < nb_symbols ; i++)
    {
        this->symbols[i] = symbols[i];
#ifdef PREPROC_KEEP_ORIGINAL_SYMBOLS
        this->original_symbols[i] = symbols[i];
#endif
    }
}
std::vector<SymbolList> permutations(const SymbolList& str, const SymbolList& of) {
	std::vector<SymbolList> ret;
	unsigned int size = of.size();
	unsigned int n = factorial(size);
	SymbolList temp = str;
	//std::cout << temp << '\n';
	while( !empty_intersection(temp, of) && temp.size() > 1 ) {
		SymbolList copy = temp;
		for( unsigned int i = 0; i < copy.size(); ++i ) {
			if( contains_char(of, copy[i]) ) {
				copy.erase(copy.begin() + i);
				ret.push_back(copy);
				//std::cout << copy << std::endl;
				break;
			}
		}
		temp = ret.back();
	}
	return ret;
}
예제 #18
0
//==================================================================
bool ParamsFindP(	ParamList &params,
					const SymbolList &globalSymbols,
					Float3	*pOut_vectorP,
					int	expectedN,
					int fromIdx )
{
	bool	gotP = false;
	
	for (size_t i=fromIdx; i < params.size(); i += 2)
	{
		DASSERT( params[i].type == Param::STR );
		
		const Symbol* pSymbol = globalSymbols.FindSymbol( params[i] );
		if ( pSymbol && pSymbol->IsName( "P" ) )
		{
			DASSTHROW( (i+1) < params.size(), "Invalid number of arguments" );
			
			const FltVec	&fltVec = params[ i+1 ].NumVec();

			DASSTHROW( (int)fltVec.size() == 3 * expectedN,
							"Invalid number of arguments."
							 " Expecting %i but it's %u", 3 * expectedN, fltVec.size() );

			DASSTHROW( (int)(fltVec.size() % 3) == 0,
							"Invalid number of arguments."
							 " Should be multiple of 3 but it's %u", fltVec.size() );

			size_t	srcN = fltVec.size();

			for (size_t si=0, di=0; si < srcN; si += 3, di += 1)
				pOut_vectorP[ di ] = Float3( &fltVec[ si ] );
			
			return true;
		}
	}
	
	return false;
}
예제 #19
0
const Symbol&
SymbolTable::getSymbol(const std::string& lexeme, const TypeList& params) {
    //deve considerar promocao de tipos
    //    função f(a:real) ...
    //    f(1);                //resolve para a função "f_real"

//checar:
//  f(a : inteiro)
//  f(b : real)
//  f(2); //primeira versão, sempre!


    SymbolList list = _table[globalScope()].findAllByLexeme(lexeme);

    if (list.size() == 0) {
        throw UndeclaredSymbolException(lexeme);
    }

    //try exact version
    for (SymbolList::iterator it = list.begin(); it != list.end(); ++it) {
        if ((*it).type()->isSubprogram() &&
                (*it).type()->paramTypes().equals(params)) {
            return (*it);
        }
    }

    //tentando promocoes...
    for (SymbolList::iterator it = list.begin(); it != list.end(); ++it) {
        if ((*it).type()->isSubprogram() &&
                (*it).type()->paramTypes().isLValueFor(params)) {
            return (*it);
        }
    }

    throw UnmatchedException(lexeme);

//   std::string id = Symbol::buildIdentifier(lexeme, params);
//   SymbolList::const_iterator it = _table[globalScope()].findByIdentifier(id);
//   if (it == _table[globalScope()].end()) {
//     throw UndeclaredSymbolException(id);
//   }
//   return (*it);
}
예제 #20
0
파일: sc6.cpp 프로젝트: LittleKu/sourcepawn
static void append_debug_tables(SmxBuilder *builder, StringPool &pool, RefPtr<SmxNameTable> names, SymbolList &nativeList)
{
  // We use a separate name table for historical reasons that are no longer
  // necessary. In the future we should just alias this to ".names".
  RefPtr<SmxNameTable> dbgnames = new SmxNameTable(".dbg.strings");
  RefPtr<SmxDebugInfoSection> info = new SmxDebugInfoSection(".dbg.info");
  RefPtr<SmxDebugLineSection> lines = new SmxDebugLineSection(".dbg.lines");
  RefPtr<SmxDebugFileSection> files = new SmxDebugFileSection(".dbg.files");
  RefPtr<SmxDebugSymbolsSection> symbols = new SmxDebugSymbolsSection(".dbg.symbols");
  RefPtr<SmxDebugNativesSection> natives = new SmxDebugNativesSection(".dbg.natives");
  RefPtr<SmxTagSection> tags = new SmxTagSection(".tags");

  stringlist *dbgstrs = get_dbgstrings();

  // State for tracking which file we're on. We replicate the original AMXDBG
  // behavior here which excludes duplicate addresses.
  ucell prev_file_addr = 0;
  const char *prev_file_name = nullptr;

  // Add debug data.
  for (stringlist *iter = dbgstrs; iter; iter = iter->next) {
    if (iter->line[0] == '\0')
      continue;

    DebugString str(iter->line);
    switch (str.kind()) {
      case 'F':
      {
        ucell codeidx = str.parse();
        if (codeidx != prev_file_addr) {
          if (prev_file_name) {
            sp_fdbg_file_t &entry = files->add();
            entry.addr = prev_file_addr;
            entry.name = dbgnames->add(pool, prev_file_name);
          }
          prev_file_addr = codeidx;
        }
        prev_file_name = str.skipspaces();
        break;
      }

      case 'L':
      {
        sp_fdbg_line_t &entry = lines->add();
        entry.addr = str.parse();
        entry.line = str.parse();
        break;
      }

      case 'S':
      {
        sp_fdbg_symbol_t sym;
        sp_fdbg_arraydim_t dims[sDIMEN_MAX];

        sym.addr = str.parse();
        sym.tagid = str.parse();

        str.skipspaces();
        str.expect(':');
        char *name = str.skipspaces();
        char *nameend = str.skipto(' ');
        Atom *atom = pool.add(name, nameend - name);

        sym.codestart = str.parse();
        sym.codeend = str.parse();
        sym.ident = (char)str.parse();
        sym.vclass = (char)str.parse();
        sym.dimcount = 0;
        sym.name = dbgnames->add(atom);

        info->header().num_syms++;

        str.skipspaces();
        if (str.getc() == '[') {
          info->header().num_arrays++;
          for (char *ptr = str.skipspaces(); *ptr != ']'; ptr = str.skipspaces()) {
            dims[sym.dimcount].tagid = str.parse();
            str.skipspaces();
            str.expect(':');
            dims[sym.dimcount].size = str.parse();
            sym.dimcount++;
          }
        }

        symbols->add(&sym, sizeof(sym));
        symbols->add(dims, sizeof(dims[0]) * sym.dimcount);
        break;
      }
    }
  }

  // Add the last file.
  if (prev_file_name) {
    sp_fdbg_file_t &entry = files->add();
    entry.addr = prev_file_addr;
    entry.name = dbgnames->add(pool, prev_file_name);
  }

  // Build the tags table.
  for (constvalue *constptr = tagname_tab.next; constptr; constptr = constptr->next) {
    assert(strlen(constptr->name)>0);

    sp_file_tag_t &tag = tags->add();
    tag.tag_id = constptr->value;
    tag.name = names->add(pool, constptr->name);
  }

  // Finish up debug header statistics.
  info->header().num_files = files->count();
  info->header().num_lines = lines->count();

  // Write natives.
  sp_fdbg_ntvtab_t natives_header;
  natives_header.num_entries = nativeList.length();
  natives->add(&natives_header, sizeof(natives_header));

  for (size_t i = 0; i < nativeList.length(); i++) {
    symbol *sym = nativeList[i];

    sp_fdbg_native_t info;
    info.index = i;
    info.name = dbgnames->add(pool, sym->name);
    info.tagid = sym->tag;
    info.nargs = 0;
    for (arginfo *arg = sym->dim.arglist; arg->ident; arg++)
      info.nargs++;
    natives->add(&info, sizeof(info));

    for (arginfo *arg = sym->dim.arglist; arg->ident; arg++) {
      sp_fdbg_ntvarg_t argout;
      argout.ident = arg->ident;
      argout.tagid = arg->tag;
      argout.dimcount = arg->numdim;
      argout.name = dbgnames->add(pool, arg->name);
      natives->add(&argout, sizeof(argout));

      for (int j = 0; j < argout.dimcount; j++) {
        sp_fdbg_arraydim_t dim;
        dim.tagid = arg->idxtag[j];
        dim.size = arg->dim[j];
        natives->add(&dim, sizeof(dim));
      }
    }
  }

  // Add these in the same order SourceMod 1.6 added them.
  builder->add(files);
  builder->add(symbols);
  builder->add(lines);
  builder->add(natives);
  builder->add(dbgnames);
  builder->add(info);
  builder->add(tags);
}
예제 #21
0
EdSymbolList::EdSymbolList(const SymbolList& list):
  alphabet_(list.getAlphabet()), propagateEvents_(true), content_(list.getContent()), listeners_() {}
예제 #22
0
BasicSymbolList::BasicSymbolList(const SymbolList& list):
  alphabet_(list.getAlphabet()), content_(list.getContent()) {}
예제 #23
0
bool Disassembler::ParseSymbolTable(const list<Token *>::iterator &startiter, const list<Token *>::iterator &EndIter, SymbolList &Symbols, unsigned char Addressability, CallBackFunction)
{
	list<Token *>::iterator TokenIter, StartIter;
	TokenIter = StartIter = startiter;

	//process one symbol at a time
	while(StartIter != EndIter)
	{
		//Get the symbol name
		if(StartIter == EndIter || (*StartIter)->TokenType != TIdentifier)
		{
			CallBack(Error, "Missing symbol name: first cell in symbol table entry.", (*TokenIter)->LocationStack);
			return false;
		}
		string sSymbol = ((IDToken *)(*StartIter))->sIdentifier;
		TokenIter = StartIter++;

		//Check for possible "." which could be for a struct member.
		if(StartIter != EndIter && (*StartIter)->TokenType == TOperator && ((OpToken *)(*StartIter))->Operator == OpPeriod)
		{
			TokenIter = StartIter++;
			//Get past the member label
			if(StartIter != EndIter && (*StartIter)->TokenType == TIdentifier)
			{
				TokenIter = StartIter++;
			}
			else
			{
				CallBack(Error, "Missing member symbol name after struct symbol name and period: first cell in symbol table entry.", (*TokenIter)->LocationStack);
				return false;
			}
		}


		//Get the comma
		if(StartIter == EndIter || (*StartIter)->TokenType != TOperator || ((OpToken *)(*StartIter))->Operator != OpComma)
		{
			CallBack(Error, "Missing comma after symbol name: first cell in symbol table entry.", (*TokenIter)->LocationStack);
			return false;
		}
		TokenIter = StartIter++;

		//Get the symbol type
		SymbolEnum SymbolType = SymVoid;
		if(StartIter == EndIter || (*StartIter)->TokenType != (TokenEnum)TDirective || ((DirToken *)(*StartIter))->Directive != DirMacro)
		{
			if(StartIter == EndIter || (*StartIter)->TokenType != (TokenEnum)TDirective || ((DirToken *)(*StartIter))->Directive != DirExtern)
			{
				if(StartIter == EndIter || (*StartIter)->TokenType != (TokenEnum)TDirective || ((DirToken *)(*StartIter))->Directive != DirDefine)
				{
					if(StartIter == EndIter || (*StartIter)->TokenType != (TokenEnum)TData || ((DataToken *)(*StartIter))->DataType != STRUCT)
					{
						if(StartIter == EndIter || (*StartIter)->TokenType != TIdentifier || ((IDToken *)(*StartIter))->sIdentifier != "member")
						{
							if(StartIter == EndIter || (*StartIter)->TokenType != TIdentifier || ((IDToken *)(*StartIter))->sIdentifier != "label")
							{
								CallBack(Error, "Missing symbol type after symbol name: second cell in symbol table entry.", (*TokenIter)->LocationStack);
								return false;
							}
							else
								SymbolType = SymLabel;
						}
						else
							SymbolType = SymMember;
					}
					else
						SymbolType = SymStruct;
				}
				else
					SymbolType = SymDefine;
			}
			else
				SymbolType = SymExtern;
		}
		else
			SymbolType = SymMacro;
		TokenIter = StartIter++;

		uint64 Address;
		switch(SymbolType)
		{
		case SymMacro:
		case SymDefine:
		case SymStruct:
			//There's nothing else for this entry.
			break;

		case SymMember:
			//Get the comma
			if(StartIter == EndIter || (*StartIter)->TokenType != TOperator || ((OpToken *)(*StartIter))->Operator != OpComma)
			{
				CallBack(Error, "Missing comma after symbol type: second cell in symbol table entry.", (*TokenIter)->LocationStack);
				return false;
			}
			TokenIter = StartIter++;

			//Get the number
			if(StartIter == EndIter || (*StartIter)->TokenType != TInteger)
			{
				CallBack(Error, "Missing struct member symbol offset value: third cell in symbol table entry.", (*TokenIter)->LocationStack);
				return false;
			}
			TokenIter = StartIter++;
			
			break;

		case SymExtern:
		case SymLabel:
			//Get the comma
			if(StartIter == EndIter || (*StartIter)->TokenType != TOperator || ((OpToken *)(*StartIter))->Operator != OpComma)
			{
				CallBack(Error, "Missing comma after symbol type: second cell in symbol table entry.", (*TokenIter)->LocationStack);
				return false;
			}
			TokenIter = StartIter++;

			//Get the number
			if(StartIter == EndIter || (*StartIter)->TokenType != TInteger)
			{
				CallBack(Error, "Missing symbol address: third cell in symbol table entry.", (*TokenIter)->LocationStack);
				return false;
			}
			Address = ((IntegerToken *)(*StartIter))->Integer;
			TokenIter = StartIter++;

			//Get the comma
			if(StartIter == EndIter || (*StartIter)->TokenType != TOperator || ((OpToken *)(*StartIter))->Operator != OpComma)
			{
				CallBack(Error, "Missing comma after symbol address: third cell in symbol table entry.", (*TokenIter)->LocationStack);
				return false;
			}
			TokenIter = StartIter++;

			//Get the number
			if(StartIter == EndIter || (*StartIter)->TokenType != TInteger)
			{
				CallBack(Error, "Missing symbol segment-relative adddress: fourth cell in symbol table entry.", (*TokenIter)->LocationStack);
				return false;
			}
			TokenIter = StartIter++;

			if(SymbolType == SymLabel)
				Symbols.push_back( make_triple((*TokenIter)->LocationStack, Address << Addressability, sSymbol) );

			break;
		}

		//depending on if they saved after viewing in excel, there could be a number of commas at the end.
		while(StartIter != EndIter && (*StartIter)->TokenType == TOperator && ((OpToken *)(*StartIter))->Operator == OpComma)
			TokenIter = StartIter++;
	}

	return true;
}
예제 #24
0
void LexerTests::nominal_test()
{
    cout << "-------------------------------------- Lexer ------------------------------------" << endl;

    ifstream ifs("../../tests/files/correct.lt");
    //Vérification du fichier
    if (!ifs.good())
    {
        ifs.close();
        FAILED(0);
        PRINT("Failed to open file...");
        return;
    }
    Lexer lexer(ifs);
    SymbolList symbols;
    Symbol symbol;
    lexer.MoveForward(); // commence à lire en placant la tete de lecture au debut du flux
    symbol = lexer.GetNext();
    while(symbol.code != S_EOF)
    {   if(symbol.code == S_LEXER_ERROR)
        {   PRINT("Lexer error encountered...");
            break;
        }
        // on récupère les valeurs
        symbols.push_back(symbol);
        // on déplace la tête de lecture
        lexer.MoveForward();
        // on lit le prochain symbole
        symbol = lexer.GetNext();
    }
    symbols.push_back(symbol);
    /*
     * Programme testé : correct.lt
     *
     * 1. var a,b;
     * 2. const c = 4;
     * 3. const d = 6;
     * 4. var e;
     * 5. a := (c+d)*3-5;
     * 6. lire b;
     * 7. ecrire a*b;
     * 8. e := b+d;
     * 9. ecrire e;
     */
    SymbolList expectedSymbols;
#define PUSH_SYM(symbolcode, value) expectedSymbols.push_back(Symbol(symbolcode, value));
    // ligne 1
    PUSH_SYM(S_VAR,"var");PUSH_SYM(S_ID,"a");PUSH_SYM(S_V,",");PUSH_SYM(S_ID,"b");PUSH_SYM(S_PV,";");
    // ligne 2
    PUSH_SYM(S_CONST,"const");PUSH_SYM(S_ID,"c");PUSH_SYM(S_EQ,"=");PUSH_SYM(S_NUM,"4");PUSH_SYM(S_PV,";");
    // ligne 3
    PUSH_SYM(S_CONST,"const");PUSH_SYM(S_ID,"d");PUSH_SYM(S_EQ,"=");PUSH_SYM(S_NUM,"6");PUSH_SYM(S_PV,";");
    // ligne 4
    PUSH_SYM(S_VAR,"var");PUSH_SYM(S_ID,"e");PUSH_SYM(S_PV,";");
    // ligne 5
    PUSH_SYM(S_ID,"a");PUSH_SYM(S_AFFECT,":=");PUSH_SYM(S_PO,"(");PUSH_SYM(S_ID,"c");PUSH_SYM(S_PLUS,"+");PUSH_SYM(S_ID,"d");PUSH_SYM(S_PF,")");PUSH_SYM(S_MULT,"*");PUSH_SYM(S_NUM,"3");PUSH_SYM(S_MINUS,"-");PUSH_SYM(S_NUM,"5");PUSH_SYM(S_PV,";");
    // ligne 6
    PUSH_SYM(S_READ,"lire");PUSH_SYM(S_ID,"b");PUSH_SYM(S_PV,";");
    // ligne 7
    PUSH_SYM(S_WRITE,"ecrire");PUSH_SYM(S_ID,"a");PUSH_SYM(S_MULT,"*");PUSH_SYM(S_ID,"b");PUSH_SYM(S_PV,";");
    // ligne 8
    PUSH_SYM(S_ID,"e");PUSH_SYM(S_AFFECT,":=");PUSH_SYM(S_ID,"b");PUSH_SYM(S_PLUS,"+");PUSH_SYM(S_ID,"d");PUSH_SYM(S_PV,";");
    // ligne 9
    PUSH_SYM(S_WRITE,"ecrire");PUSH_SYM(S_ID,"e");PUSH_SYM(S_PV,";");
    // eof
    PUSH_SYM(S_EOF,"");

    // verification de l'adequation des quatres tableaux
    // -- on vérifie d'abord la taille
    if(symbols.size() != expectedSymbols.size())
    {   FAILED(0);
        PRINT("Les tailles des tableaux ne correspondent pas !");
        PRINT("symbols.size() = " << symbols.size());
        PRINT("expectedSymbols.size() = " << expectedSymbols.size());
    }
    else
    {   list<Symbol>::iterator realSymbol = symbols.begin(), expectedSymbol = expectedSymbols.begin();
        // ici on peut tester que sur un itérateur car on sait que tous les tableaux font la meme taille
        int iter(1);
        bool failed(false);
        while(realSymbol != symbols.end())
        {   // tests de correspondance
            if(realSymbol->code != expectedSymbol->code)
            {   FAILED(iter);
                PRINT("real code = '" << realSymbol->code << "'");
                PRINT("expected code = '" << expectedSymbol->code << "'");
                failed = true;
                break; // sortie du while
            }
            else if(realSymbol->buf != expectedSymbol->buf)
            {   FAILED(iter);
                PRINT("real buf = '" << realSymbol->buf << "'");
                PRINT("expected buf = '" << expectedSymbol->buf << "'");
                failed = true;
                break; // sortie du while
            }
            // incrément des itérateurs
            realSymbol++; expectedSymbol++;
            iter++;
        }
        if(!failed)
        {   SUCCESS(0);
        }
    }


    cout << "-------------------------------------- done -------------------------------------" << endl;
}
예제 #25
0
bool Disassembler::Disassemble(LocationVector &LocationStack, istream &InputStream, SymbolList &Symbols)
{
	bool fRetVal = true;
	unsigned int i, TempChar;
	JMT::ByteData ByteData;

	if(fRunOnce)
		throw "Disassembler called twice on the same program!";
	fRunOnce = true;

	//First read starting address.
	for(i = 0; i < sizeof(uint64); i++)
	{
		TempChar = InputStream.get();
		if(TempChar == -1)	//EOF
			break;
		//The address in the file is always little endian
#ifdef BIG_ENDIAN_BUILD
		ByteData.Bytes[sizeof(uint64) - i - 1] = TempChar;
#else
		ByteData.Bytes[i] = TempChar;
#endif
		LocationStack.rbegin()->second++;
	}
	if(i < sizeof(uint64))
	{
		CallBack(Fatal, "Unexpected end of file.", LocationStack);
		return false;
	}
	StartAddress = ByteData.UI64;

	//Then read ending address
	for(i = 0; i < sizeof(uint64); i++)
	{
		TempChar = InputStream.get();
		if(TempChar == -1)	//EOF
			break;
		//The address in the file is always little endian
#ifdef BIG_ENDIAN_BUILD
		ByteData.Bytes[sizeof(uint64) - i - 1] = TempChar;
#else
		ByteData.Bytes[i] = TempChar;
#endif
		LocationStack.rbegin()->second++;
	}
	if(i < sizeof(uint64))
	{
		CallBack(Fatal, "Unexpected end of file.", LocationStack);
		return false;
	}
	EndAddress = StartAddress + ByteData.UI64;

	//Check addresses
	if(EndAddress < StartAddress)
	{
		CallBack(Fatal, "Program end address is less than start address.", LocationStack);
		return false;
	}

	//Create program origin
	TheProg.fDynamicAddress = false;
	TheProg.Address = StartAddress;

	//Create program segment
	TheProg.Segments.push_back(new Segment(LocationStack, Addressability, 0));

	//Add the pre-existing symbols
	for(SymbolList::iterator SymbolIter = Symbols.begin(); SymbolIter != Symbols.end(); SymbolIter++)
		DisassembleSymbol(SymbolIter->first, SymbolIter->second, SymbolIter->third);

	//Try to disassemble instructions. Instructions have highest priority.
	uint64 Address = StartAddress;
	if(ToLower(TheProg.sFileName.Ext) == "obj")
	{
		if(!DisassembleInstructions(LocationStack, InputStream, Address))
			return false;
	}
	else	//"bin"
	{
		if(!DisassembleData(LocationStack, InputStream, Address))
			return false;
	}

	if(Address < EndAddress)
	{
		CallBack(Error, "Unexpected end of file.", LocationStack);
		return false;
	}

	//Create labels
	list<Element *>::iterator ElemIter = (*TheProg.Segments.begin())->Sequence.begin();
	for(LabelMap::iterator LabelIter = Labels.begin(); LabelIter != Labels.end(); LabelIter++)
	{
		//Find the element this label points to
		while(ElemIter != (*TheProg.Segments.begin())->Sequence.end() && (*ElemIter)->Address < LabelIter->first)
			ElemIter++;

		if(ElemIter == (*TheProg.Segments.begin())->Sequence.end())
		{
			ElemIter--;
			if((*ElemIter)->Address + (*ElemIter)->Size != LabelIter->first)
				throw "Disassembler: Ran out of elements while adding labels!";
			//Label points to end of program
			ElemIter++;
		}
		else if((*ElemIter)->Address != LabelIter->first)
			throw "Disassembler: Label points to inside an instruction!";

		//Add the label to the sequence
		Label *pLabel = new Label(LocationStack, LabelIter->second->sSymbol, *TheProg.Segments.begin());
		(*TheProg.Segments.begin())->Sequence.insert(ElemIter, pLabel);
		LabelIter->second->pLabel = pLabel;
		if(ElemIter != (*TheProg.Segments.begin())->Sequence.end())
		{
			if(!TheProg.TheSymbolTable.ResolveSymbol((*ElemIter)->LocationStack, LabelIter->second->sSymbol, CallBack, SymLabel))
				throw "ResolveSymbol in Disassembler failed!";
			pLabel->pElement = *ElemIter;
		}
		else
			if(!TheProg.TheSymbolTable.ResolveSymbol((*(*TheProg.Segments.begin())->Sequence.rbegin())->LocationStack, LabelIter->second->sSymbol, CallBack, SymLabel))
				throw "ResolveSymbol in Disassembler failed!";
	}

	return fRetVal;
}
bool MamaEntitle::hasSymbols ()
{
    return mSymbolList.empty ();
}
void MamaEntitle::parseCommandLine (int argc, const char* argv[])
{
    int i = 0;
    for (i = 1; i < argc;  )
    {
        if ((strcmp (argv[i], "-S") == 0) ||
            (strcmp (argv[i], "-source") == 0))
        {
            mSource = argv[i + 1];
            i += 2;
        }
        else if (strcmp (argv[i], "-d") == 0)
        {
            mDictSourceName = argv[i + 1];
            i += 2;
        }
        else if (strcmp (argv[i], "-dict_tport") == 0)
        {
            mDictTport = argv[i+1];
            i += 2;
        }
        else if (strcmp (argv[i], "-I") == 0)
        {
            mRequireInitial = 0;
            i++;
        }
        else if ((strcmp (argv[i], "-h") == 0) ||
                 (strcmp (argv[i], "-?") == 0))
        {
            usage (0); 
            i++;
        }
        else if (strcmp (argv[i], "-s") == 0)
        {
            mSymbolList.push_back (argv[i + 1]);
            i += 2; 
        }
        else if (strcmp (argv[i], "-f") == 0)
        {
            mFilename = argv[i + 1];
            i += 2;
        }
        else if (strcmp (argv[i], "-1") == 0)
        {
            mSnapshot = 1;
            i++;
        }
        else if (strcmp (argv[i], "-g") == 0)
        {
            mGroupSubscription = 1;
            i++;
        }
        else if (strcmp (argv[i], "-q") == 0)
        {
            mQuietness++;
            i++;
        }
        else if (strcmp (argv[i], "-threads") == 0)
        {
            mThreads = atoi (argv[i + 1]);
            i += 2;
        }
        else if (strcmp (argv[i], "-tport") == 0)
        {
            mTport = argv[i+1];
            i += 2;
        }
        else if (strcmp (argv[i], "-v") == 0)
        {
            if (mMamaLogLevel == MAMA_LOG_LEVEL_WARN)
            {
                mMamaLogLevel = MAMA_LOG_LEVEL_NORMAL;
                mama_enableLogging (stderr, MAMA_LOG_LEVEL_NORMAL); 
            }
            else if (mMamaLogLevel == MAMA_LOG_LEVEL_NORMAL)
            {
                mMamaLogLevel = MAMA_LOG_LEVEL_FINE;
                mama_enableLogging (stderr, MAMA_LOG_LEVEL_FINE); 
            }
            else if (mMamaLogLevel == MAMA_LOG_LEVEL_FINE)
            {
                mMamaLogLevel = MAMA_LOG_LEVEL_FINER;
                mama_enableLogging (stderr, MAMA_LOG_LEVEL_FINER);
            }
            else
            {
                mMamaLogLevel = MAMA_LOG_LEVEL_FINEST;
                mama_enableLogging (stderr, MAMA_LOG_LEVEL_FINEST);
            }

            i++;
        }
        else if (strcmp ("-m", argv[i]) == 0)
        {
            mMiddleware = argv[i+1];
            i += 2;               
        }
        else if (strcmp (argv[i], "-V") == 0)
        {
            if (mSubscLogLevel == MAMA_LOG_LEVEL_NORMAL)
            {
                mSubscLogLevel = MAMA_LOG_LEVEL_FINE;
            }
            else if (mSubscLogLevel == MAMA_LOG_LEVEL_FINE)
            {
                mSubscLogLevel = MAMA_LOG_LEVEL_FINER;
            }
            else
            {
                mSubscLogLevel = MAMA_LOG_LEVEL_FINEST;
            }

            i++;
        }
        else if (strcmp (argv[i], "-version") == 0)
        {
            printf ("%s\n", Mama::getVersion (mBridgeImpl)); 
            exit (0);
        }
        else if (strcmp (argv[i], "-t") == 0)
        {
            mShutdownTimeout = strtol (argv[i+1], NULL, 10);
            i+=2;
        }
        else
        {
            mFieldList.push_back (argv[i]);
            i++;
        }
    }
}
예제 #28
0
/**
Function to generate ASM File.
@param afileName - ASM File name
@return 0 on success, otherwise throw error
@internalComponent
@released
*/
int FileDump::GenerateAsmFile(const char* afileName)//DumpAsm
{
    DefFile *iDefFile = new DefFile();
    SymbolList *aSymList;
    aSymList = iDefFile->ReadDefFile(iParameterListInterface->DefInput());

    FILE *fptr;

    if((fptr=fopen(afileName,"w"))==NULL)
    {
        throw FileError(FILEOPENERROR,(char*)afileName);
    }
    else
    {
        SymbolList::iterator aItr = aSymList->begin();
        SymbolList::iterator last = aSymList->end();
        Symbol *aSym;

        while( aItr != last)
        {
            aSym = *aItr;

            if(aSym->Absent())
            {
                aItr++;
                continue;
            }

            fputs("\tIMPORT ",fptr);
            fputs(aSym->SymbolName(),fptr);
            //Set the visibility of the symbols as default."DYNAMIC" option is
            //added to remove STV_HIDDEN visibility warnings generated by every
            //export during kernel build
            fputs(" [DYNAMIC]", fptr);
            fputs("\n",fptr);
            aItr++;
        }

        // Create a directive section that instructs the linker to make all listed
        // symbols visible.

        fputs("\n AREA |.directive|, READONLY, NOALLOC\n\n",fptr);

        fputs("\tDCB \"#<SYMEDIT>#\\n\"\n", fptr);

        aItr = aSymList->begin();
        while (aItr != last)
        {
            aSym = *aItr;

            if ( aSym->Absent() )
            {
                aItr++;
                continue;
            }

            // Example:
            //  DCB "EXPORT __ARM_ll_mlass\n"
            fputs("\tDCB \"EXPORT ",fptr);
            fputs(aSym->SymbolName(),fptr);
            fputs("\\n\"\n", fptr);

            aItr++;
        }

        fputs("\n END\n",fptr);
        fclose(fptr);
    }
    return 0;
}
bool subset_of(const SymbolList& in, const SymbolList& of) {
	return intersection(in, of).size() == in.size();
}