Esempio n. 1
0
MidSquareLP::MidSquareLP(const char * _filename, const char * linear_filename) : MidSquare(_filename) {
    ifstream linear_file;
    linear_file.open(linear_filename, ios::in);

    if( !linear_file.is_open() ) {
        cout << "MidSquareLP(): " << "ERROR: " << linear_filename << " Can't be opened" << endl;
    } else {
        string redLine;
        while(linear_file.good()) {
            getline(linear_file, redLine);

            if(redLine.compare("\0") != 0) {
                Record Persona = Parser(redLine);

                unsigned int hashline = HashFunction(Persona.uid);
                unsigned int homeline = hashline;

                while(Collision(hashline) != 0) {
                    hashline++;

                    if(!(hashline < THOUSAND_MOD)) {
                        hashline = 0;
                    }
                    // dosya dolu ise
                    if(hashline == homeline) {
                        cout << "MidSquareLP(): " << "ERROR: " << filename << " Can't write UID: " << Persona.uid << " file is FULL" << endl;
                        break;
                    }
                    // islem sayisini artirma
                    transaction++;
                }
                // Correction control
                if(Collision(hashline) == 0) {
                    Write(Persona, hashline);
                    // islem sayisini artirma
                    transaction++;
                }
            }
        }

        linear_file.clear();
        linear_file.seekg(0, ios::beg);

        while(linear_file.good()) {
            getline(linear_file, redLine);

            if(redLine.compare("\0") != 0) {
                Record Persona = Parser(redLine);

                unsigned int hashline = HashFunction(Persona.uid);
                unsigned int homeline = hashline;
                // adres dolu ve kayit o adreste degil ise
                while((Search(Persona.uid, hashline)).compare(RECORD_FORM) == 0 && Collision(hashline) != 0) {
                    hashline++;

                    if(!(hashline < THOUSAND_MOD)) {
                        hashline = 0;
                    }
                    // kayit dosyada bulunamadi ise
                    if(hashline == homeline) {
                        cout << "MidSquareLP(): " << "ERROR: " << " Can't find UID: " << Persona.uid << " in file " << filename << endl;
                        break;
                    }
                    // islem sayisini artirma
                    transaction++;
                }
                // Correction control
                if((Search(Persona.uid, hashline)).compare(RECORD_FORM) != 0) {
                    // islem sayisini artirma
                    transaction++;
                } else {
                    cout << "MidSquareLP(): " << "ERROR: " << " Can't find UID: " << Persona.uid << " in file " << filename << endl;
                }
            }
        }
        linear_file.close();
    }
}
Esempio n. 2
0
void CEditView::DrawLine( int nLine, HDC hDC, int x, int y, int xDividerStart ) const
{
   int nLineLen = m_pBuffer->GetLineLength( nLine );
   BOOL bUseColor = ( m_pCtrl->UseColorSyntax() && ( nLineLen <= MAXCOL ) );

   int nViewCol = m_nLeftIndex;
   int nBuffColStart = m_pBuffer->ConvertViewColToBufferCol( nLine, nViewCol, FALSE );

   int xLeft = x;

   // highlight this line if appropriate
   BOOL bHighlight = m_pBuffer->IsHighlighted( nLine );
   if ( bHighlight )
   {
      // fill out the rest of the line with the highlight
      RECT rc = m_rcView;
      rc.left = x;
      rc.top = y;
      rc.bottom = y + m_cyLine;
      SetBkColor( hDC, m_pCtrl->GetHighlightedLineColor() );
      ExtTextOut( hDC, 0, 0, ETO_OPAQUE, &rc, NULL, 0, NULL );
   }

   BOOL bMBCS = DBCS_ACTIVE;

#ifdef _UNICODE
   int nRightIndex = m_nRightIndex;
#else
   int nRightIndex = m_nRightIndex + bMBCS * 2;   // always paint two more TCHARs so multibyte chars aren't truncated
#endif

   if ( nBuffColStart < nLineLen )   // else nothing to draw
   {
      // wait for nLine to become available (in case of background syntax parsing)
      m_pBuffer->WaitForLine( nLine );

      LPCTSTR pszLineStart = m_pBuffer->GetLineText( nLine );
      register LPCTSTR psz = pszLineStart + nBuffColStart;
      LPCTSTR pszStart = psz;

      //////////////////////////////////////////////////////////////////////////
      // Step 1: Expand tabs
      //
      BOOL bViewWhitespace = m_pCtrl->DisplayWhitespace();
      TCHAR szLine[ 1000 ];  CharFill( szLine, _T(' '), ARRAY_SIZE( szLine ) );
      int cbTab = m_pBuffer->GetTabSize();
      LPTSTR pszBuff = szLine;
      TCHAR chTab, chSpace;
      if ( bMBCS )
         { chTab = _T('^'); chSpace = _T('`'); }
      else
         { chTab = _T('»'); chSpace = _T('·'); }

      while ( *psz && ( nViewCol <= nRightIndex ) )
      {
         if ( *psz == _T('\t') )
         {
            int nSpaces = ( ( nViewCol / cbTab ) * cbTab ) + cbTab - nViewCol;
            if ( nSpaces )
            {
               if ( bViewWhitespace )
               {
                  if ( psz != pszStart || m_nLeftIndex == m_pBuffer->ConvertBufferColToViewCol( nLine, nBuffColStart ) )
                  {
                     *pszBuff = chTab;
                  }
               }
               pszBuff += nSpaces;
               nViewCol += nSpaces;
            }
         }
         else
         {
            if ( bViewWhitespace && *psz == _T(' ') )
            {
               *pszBuff++ = chSpace;
            }
            else
            {
               *pszBuff++ = *psz;
            }
            nViewCol++;
         }
         psz++;
      }
      //////////////////////////////////////////////////////////////////////////
      // Step 2: Parse the line and assign colors to everything
      //
      DWORD clrLine[ 100 ]; // hiword = token, loword = token offset in szLine
      int nColors = 0;

      if ( bUseColor )
      {
         psz = pszLineStart;
         int nParseLen = m_pBuffer->ConvertViewColToBufferCol( nLine, nRightIndex ) + 20; // +20 is a reasonable max token length
         nParseLen = min( nParseLen, nLineLen );
         nViewCol = 0;
         int nBuffCol = 0;
         int nFirstColorViewCol = m_nLeftIndex;
         BOOL bColorIsVisible = nViewCol >= nFirstColorViewCol;

         CLineParser Parser( m_pBuffer, nLine, nParseLen );

         // pick up where the last line left off -- in a multi-line comment block (or not)
         clrLine[ nColors++ ] = MAKELPARAM( 0, ( WORD ) ( Parser.m_bInComment ? CBuffer::eMultiLineCommentStart :
                                                        ( Parser.m_bInString ?  CBuffer::eStringDelim :
                                                        ( Parser.m_bInTag ?     CBuffer::eTagText :
                                                                     CBuffer::eText ) ) ) );

         while ( Parser.MoreComing() )
         {
            Parser.AcceptToken();

            int nTokenStartCol = nViewCol;
            nBuffCol += Parser.m_nTokenLen;
            if ( Parser.m_bHasTab )
            {
               ASSERT( Parser.m_eToken == CBuffer::eText || Parser.m_eToken == CBuffer::eTagText || Parser.m_eToken == CBuffer::eStringDelim || Parser.m_eToken == CBuffer::eSingleLineComment );
               nViewCol = m_pBuffer->ConvertBufferColToViewCol( nLine, nBuffCol );
            }
            else
            {
               nViewCol += Parser.m_nTokenLen;
            }
            if ( !bColorIsVisible )
            {
               // Assume this token (unless in a comment) will be the first token to cross the left edge
               clrLine[ 0 ] = MAKELPARAM( 0, ( WORD )( Parser.m_bInComment ? CBuffer::eMultiLineCommentStart :
                                                       ( Parser.m_bInString ? CBuffer::eStringDelim : Parser.m_eToken ) ) );

               if ( nViewCol > nFirstColorViewCol )
               {
                  //////////////////////////
                  // token is now in view
                  //
                  bColorIsVisible = TRUE;
                  nTokenStartCol = nFirstColorViewCol;
               }
            }

            // record the token position
            if ( nTokenStartCol > nRightIndex )
            {
               break;
            }

            if ( bColorIsVisible &&
                 !Parser.m_bWasInComment && !Parser.m_bIsCommentEndToken &&
                !Parser.m_bWasInString && !Parser.m_bIsStringEndToken )
            {
               clrLine[ nColors++ ] = MAKELPARAM( nTokenStartCol - m_nLeftIndex, ( WORD ) Parser.m_eToken );
            }

            clrLine[ nColors ] = MAKELPARAM( ( nViewCol > m_nLeftIndex ? nViewCol : nRightIndex ) - m_nLeftIndex, ( WORD ) Parser.m_eToken );

            // don't blow past the local array and corrupt the stack!
            if ( nColors >= ARRAY_SIZE( clrLine ) - 1 )
            {
               nColors = 0;
               goto no_color;
            }

         }
      }
      else
      {
         no_color:

         clrLine[ nColors++ ] = MAKELPARAM( 0, ( WORD ) CBuffer::eText );
         // draw text only as far as is necessary.  We don't want to paint extra characters that aren't
         // in the buffer.  If underline font used on plain text, the underline will extend to the edge of the window.
         // we don't want that.
         int nViewColEnd = m_pBuffer->ConvertBufferColToViewCol( nLine, nLineLen );
         nViewColEnd = min( nRightIndex, nViewColEnd );
         nViewColEnd = max( m_nLeftIndex, nViewColEnd );

         clrLine[ nColors ] = MAKELPARAM( nViewColEnd - m_nLeftIndex, ( WORD ) CBuffer::eText );
      }

      //////////////////////////////////////////////////////////////////////////
      // Step 3: Output the line
      //
      ASSERT( nColors );
      BOOL bFirstToken = TRUE;

      for ( int i = 0; i < nColors; i++ )
      {
         DWORD dwColorInfo = clrLine[ i ];
         CBuffer::LangToken eToken = ( CBuffer::LangToken ) HIWORD( dwColorInfo );
         SetTextColor( hDC, m_pCtrl->GetTokenColor( eToken, TRUE ) );
         COLORREF crBk = bHighlight ? m_pCtrl->GetHighlightedLineColor() : m_pCtrl->GetTokenColor( eToken, FALSE );
         if ( crBk != CLR_INVALID )
         {
            SetBkColor( hDC, crBk );
            SetBkMode( hDC, OPAQUE );
         }
         else
         {
            SetBkMode( hDC, TRANSPARENT );
         }

         long cxExtraSpacing, cyDescentShift;
         SelectObject( hDC, m_pCtrl->GetTokenFont( eToken, cxExtraSpacing, cyDescentShift, m_pCtrl->m_font ) );
         SetTextCharacterExtra( hDC, cxExtraSpacing );

         int nTokenStart = LOWORD( dwColorInfo );
         int nTokenNext = LOWORD( clrLine[ i + 1 ] );
         int cbToken = nTokenNext - nTokenStart;
         if ( cbToken )
         {
            #ifndef _UNICODE
            // The first visible token on the left of the line might be cutoff right
            // in the middle of a multi-byte char.  We need to account for this by not
            // rendering the character (just leave whitespace).
            if ( bFirstToken && _ismbstrail( ( const unsigned char * ) pszLineStart, ( const unsigned char * ) pszStart ) )
            {
               // scan backwards to the lead byte
               LPCTSTR pszLead = pszStart;
               while ( _ismbstrail( ( const unsigned char * ) pszLineStart, ( const unsigned char * ) --pszLead ) )
                  ;
               int cbChar = pszStart - pszLead;
               nTokenStart += cbChar;
               cbToken -= cbChar;
               x += ( cbChar * m_cxChar );
            }
            #endif
            bFirstToken = FALSE;
            ExtTextOut( hDC, x, y - cyDescentShift, 0, NULL, szLine + nTokenStart, cbToken, NULL );
            x += ( cbToken * m_cxChar );
         }
         // don't worry about deselecting the font -- it will be cleaned up by any
         // calling method (as an optimization)
      }
   }

   //////////////////////////////////////////////////////////////////////////
   // Step 4: give the parent window a crack at painting, too.
   //
   DWORD dwStyle = m_pBuffer->GetLineStyle( nLine );
   if ( HAS_FLAG( dwStyle, CML_OWNERDRAW ) )
   {
      CM_DRAWLINEDATA dld;
      dld.hDC = hDC;
      dld.rcLine.left = xLeft;
      dld.rcLine.top = y;
      dld.rcLine.right = m_rcView.right;
      dld.rcLine.bottom = y + m_cyLine;
      dld.nLine = nLine;
      dld.nLeftCol = m_nLeftIndex;
      dld.nRightCol = m_nRightIndex;
      dld.lParam = m_pBuffer->GetItemData( nLine );
      dld.dwStyle = dwStyle;
      m_pCtrl->NotifyParent( CMN_DRAWLINE, ( NMHDR * ) &dld );
   }

   // Draw divider line underneath the line if appropriate
   if ( m_pBuffer->HasDivider( nLine ) )
   {
      COLORREF crDividerLine = m_pCtrl->GetHDividerLineColor();
      COLORREF crWindow = m_pCtrl->GetWindowColor( TRUE );
      // if line will blend in with the background, make it visible (opposite of window color).
      if ( crDividerLine == CLR_INVALID || crDividerLine == crWindow )
         crDividerLine = ( ~crWindow & 0x00ffffff );

      HPEN hPen = CreatePen( PS_SOLID, CY_DIVIDERLINE, crDividerLine );
      HPEN hPenOld = ( HPEN ) SelectObject( hDC, hPen );
      int yLine = y + m_cyLine - 1;
      MoveToEx( hDC, xDividerStart, yLine, NULL );
      LineTo( hDC, m_rcView.right, yLine );
      SelectObject( hDC, hPenOld );
      DeleteObject( hPen );
   }
}
Esempio n. 3
0
int TableGenMain(char *argv0, TableGenAction &Action) {
  RecordKeeper Records;

  try {
    // Parse the input file.
    OwningPtr<MemoryBuffer> File;
    if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename.c_str(), File)) {
      errs() << "Could not open input file '" << InputFilename << "': "
             << ec.message() <<"\n";
      return 1;
    }
    MemoryBuffer *F = File.take();

    // Tell SrcMgr about this buffer, which is what TGParser will pick up.
    SrcMgr.AddNewSourceBuffer(F, SMLoc());

    // Record the location of the include directory so that the lexer can find
    // it later.
    SrcMgr.setIncludeDirs(IncludeDirs);

    TGParser Parser(SrcMgr, Records);

    if (Parser.ParseFile())
      return 1;

    std::string Error;
    tool_output_file Out(OutputFilename.c_str(), Error);
    if (!Error.empty()) {
      errs() << argv0 << ": error opening " << OutputFilename
        << ":" << Error << "\n";
      return 1;
    }
    if (!DependFilename.empty()) {
      if (OutputFilename == "-") {
        errs() << argv0 << ": the option -d must be used together with -o\n";
        return 1;
      }
      tool_output_file DepOut(DependFilename.c_str(), Error);
      if (!Error.empty()) {
        errs() << argv0 << ": error opening " << DependFilename
          << ":" << Error << "\n";
        return 1;
      }
      DepOut.os() << OutputFilename << ":";
      const std::vector<std::string> &Dependencies = Parser.getDependencies();
      for (std::vector<std::string>::const_iterator I = Dependencies.begin(),
                                                          E = Dependencies.end();
           I != E; ++I) {
        DepOut.os() << " " << (*I);
      }
      DepOut.os() << "\n";
      DepOut.keep();
    }

    if (Action(Out.os(), Records))
      return 1;

    // Declare success.
    Out.keep();
    return 0;

  } catch (const TGError &Error) {
    PrintError(Error);
  } catch (const std::string &Error) {
    PrintError(Error);
  } catch (const char *Error) {
    PrintError(Error);
  } catch (...) {
    errs() << argv0 << ": Unknown unexpected exception occurred.\n";
  }

  return 1;
}
Esempio n. 4
0
File: test.cpp Progetto: TakeOver/Z
 Expression* Parse(const std::wstring& s){
         DBG_TRACE();
         auto res = Parser(s).Parse();
         return res;
 }
Esempio n. 5
0
Script::Script(File const &file) : d(new Instance)
{
    d->path = file.path();
    Parser().parse(String::fromUtf8(Block(file)), *this);
}
Esempio n. 6
0
Document::Document( const char* data, int size ) : mParser( 0 ){
cout.begin();
	mParser = NEW Parser( data, size );
cout.end();
}
Esempio n. 7
0
int main(int argc, char **argv, char **envp)
{
    //Buffer to hold our input commands
    char buffer[BUF_LIM];
    
    //Index for cycling through buffer
    int index;
    
    //Stores pointers to token strings
    char *tokens[BUF_LIM];
    
    //Process ID
    pid_t pid;
    
    //Status of process
    int status;
    
    //Used for deciding file descriptors
    int again, in, out, inout, back, err_redir;
    
    //File descriptors
    int fd[2], fdin, fdout;
    
    char returnChar;
    
    //Will display the entire current working directory as a prompt
    shellPrompt();
    
    //used to exit by pressing ctrl+c
    signal(SIGINT, SIG_IGN);
    signal(SIGINT, handle_signal);

    //Get buffer from user and loop the shell
    while(fgets(buffer,BUF_LIM,stdin) != NULL)
    {
        //used to exit by pressing ctrl+c
        signal(SIGINT, SIG_IGN);
        signal(SIGINT, handle_signal);

        //If user hit return, reprint shell prompt and get user input again
        switch(returnChar = buffer[0])
        {
                
            case '\n':
                shellPrompt();
                break;
            default:
                //Parse our buffer command
                Parser(buffer, tokens, &index, &again, &in, &out, &inout, &back, &err_redir);
                
                //If
                if((in && inout) || (out && inout))
                {
                    fprintf(stderr, "Not implemented\n");
                    continue;
                }
                
                //Call fork
                pid = fork();
                
                //Fork doesn't work
                if(pid < 0)
                {
                    perror("fork error");
                    exit(1);
                }
                
                //child process
                else if(!pid)
                {
                    //Execute the command
                    execute(tokens, fd, fdin, fdout, again, in, out, inout, back, err_redir, pid, status);
                    bzero(buffer, BUF_LIM);
                }
                waitpid(pid, &status, 0);
                shellPrompt();
                break;
        }
    }
    return 0;
}
Esempio n. 8
0
int main(void)
{
    
    //Buffer to hold our input commands
    char buffer[BUF_LIM];
    
    //Index for cycling through buffer
    unsigned long int index;
    
    //Stores pointers to token strings
    char *tokens[BUF_LIM];
    
    //Process ID
    pid_t pid;
    
    //Status of process
    int status;
    
    //Used for deciding file descriptors
    unsigned long int in, out, inout, back;
    
    //File descriptors
    int fd[2], fdin, fdout;
    
    //used to exit by pressing ctrl+D
    signal(SIGINT, SIG_IGN);
    signal(SIGINT, handle_signal);
    
    //Loop bash shell so it doesn't return after a single command
    while(1)
    {
        //print prompt - printf reqires %% to print %
        printf("nkunkel$ >> ");
        
        //Get buffer from user
        while(fgets(buffer,BUF_LIM,stdin) != NULL)
        {
            //Checks if cd was called
            if(stringCompare(buffer, "cd"))
            {
                //find beginning of path to cd into
                tokens[0] = strchr(buffer,' ')+1;
                
                //Make sure string ends properly
                *strchr(tokens[0], '\n')='\0';
                
                //Call c
                cd(tokens[0]);
            }
            
            else
            {
                //Parse our buffer command
                Parser(buffer, tokens, index, in, out, inout, back);
                
                //If 
                if((in && inout) || (out && inout))
                {
                    fprintf(stderr, "Not implemented\n");
                    continue;
                }
                
                //Call fork
                pid = fork();
                
                //Fork doesn't work
                if(pid < 0)
                {
                    perror("fork error");
                    exit(1);
                }
                
                //child process
                else if(!pid)
                {
                    //Execute the command
                    execute(tokens, fd, fdin, fdout, in, out, inout, back, pid, status);
                }
            }
        }
    }
}
Esempio n. 9
0
BOOL MySQL(const char * strParas, char * szReturn, int& nSize)
//(CStringList &paramList, char *szReturn)
{
    BOOL bRet = TRUE;

    CString strHost = _T(""), //MySqL Server
        //strDBName = _T("mysql"),//Database Name,default mysql
        strUser = _T(""), //UserName
        strPwd = _T("");// Password
    int nPort = 3306;//MySQL Server Port,default 3306
/////////////////////////////////////////////////////////////////////////////
    const  char   *pszT;//Temp string
    MYSQL		* myData ;//Access Mysql objcect
/////////////////////////////////////////////////////////////////////////////
	CStringList paramList;
	MakeStringListByChar(paramList,strParas);

    POSITION pos = paramList.GetHeadPosition();
    while(pos)
    {
        CString strTemp = paramList.GetNext(pos);
		if(strTemp.Find(__MACHINENAME__, 0) == 0)
		{//Get Host
			strHost = strTemp.Right(strTemp.GetLength() - (int)strlen(__MACHINENAME__));
		}
		else if(strTemp.Find(__PORT__, 0) == 0)
		{//Get Port
			nPort = atoi(strTemp.Right(strTemp.GetLength() - (int)strlen(__PORT__)));
		}
        else if(strTemp.Find(__USERACCOUNT__, 0) == 0)
		{//Get Username
			strUser = strTemp.Right(strTemp.GetLength() - (int)strlen(__USERACCOUNT__));
		}
        else if(strTemp.Find(__PASSWORD__, 0) == 0)
		{//Get password
			strPwd = strTemp.Right(strTemp.GetLength() - (int)strlen(__PASSWORD__));
		}
        /*else if(strTemp.Find(__DBNAME__, 0) == 0)
		{//Get database name
			strDBName = strTemp.Right(strTemp.GetLength() - strlen(__DBNAME__));
		}*/
    }

    if(strHost.IsEmpty())
    {//host is empty
        sprintf(szReturn, "error=%s", FuncGetStringFromIDS("SV_MYSQL",
            "MYSQL_SERVER_HOST_IS_NULL"));
        return FALSE;
    }
    if(nPort <= 0)
    {//Invalid port
        sprintf(szReturn, "error=%s", FuncGetStringFromIDS("SV_MYSQL",
            "MYSQL_SERVER_PORT_IS_BAD"));
        return FALSE;
    }
	printf("----------%s--%s--%s--------\n",strHost,strUser,strPwd);

    if((myData = mysql_init((MYSQL*) 0)) && 
       mysql_real_connect( myData, strHost, strUser, strPwd, NULL, nPort,
			   NULL, 0 ) )
    {
        /*if ( mysql_select_db( myData, strDBName ) < 0 ) 
        {
            sprintf(szReturn, "error=%s(%s)$", FuncGetStringFromIDS("SV_MYSQL",
                "MYSQL_SELECT_DATABASE_FAILED"), strDBName);
	        //printf( "Can't select the %s database !\n", strDBName) ;
	        mysql_close( myData ) ;
	        return FALSE;
        }*/

        pszT = mysql_stat( myData ) ;		//mysql_stat(MYSQL * myData)取得目录数据库系统状况

        if(pszT)
        {
            Parser(pszT, strHost.GetBuffer(strHost.GetLength()), szReturn);
//			mysql_free_result(pszT);
			CString strInput ;
			strInput =szReturn;
			MakeCharByString(szReturn,nSize,strInput);
				

        }
        else
        {
			sprintf(szReturn, "error=%s", FuncGetStringFromIDS("SV_MYSQL",
                "MYSQL_QUERY_STAT_FAILED"));
            mysql_close( myData ) ;
            return FALSE;
        }
    }
    else 
    {
        sprintf(szReturn, "error=%s(%s:%d)$", FuncGetStringFromIDS("SV_MYSQL",
            "MYSQL_CONNECT_DATABASE_FAILED"), strHost, nPort);
        //printf( "Can't connect to the mysql server on port %d !\n",
	    //    MYSQL_PORT ) ;
		fprintf(stderr, "Failed to connect to database: Error: %s\n",
          mysql_error(myData));

        mysql_close( myData ) ;
        return FALSE;
    }
    mysql_close( myData ) ;
    return TRUE;
}
Esempio n. 10
0
Expected<COFFModuleDefinition> parseCOFFModuleDefinition(MemoryBufferRef MB,
                                                         MachineTypes Machine,
                                                         bool MingwDef) {
  return Parser(MB.getBuffer(), Machine, MingwDef).parse();
}
Esempio n. 11
0
void parse(TokenStream & ts, ObjectTable & table, ObjectPool & pool)
{
	Parser(ts, table, pool).run();
}
llvm::ErrorOr<std::unique_ptr<DebugMap>> parseDebugMap(StringRef InputFile,
                                                       StringRef PrependPath,
                                                       bool Verbose) {
  MachODebugMapParser Parser(InputFile, PrependPath, Verbose);
  return Parser.parse();
}
Esempio n. 13
0
MidSquareSO::MidSquareSO(const char * _filename, const char * linear_filename) : MidSquare(_filename) {
    endpoint = THOUSAND_MOD;

    ifstream linear_file;
    linear_file.open(linear_filename, ios::in);

    if( !linear_file.is_open() ) {
        cout << "MidSquareSO(): " << "ERROR: " << linear_filename << " Can't be opened" << endl;
    } else {
        string redLine;
        while(linear_file.good()) {
            getline(linear_file, redLine);

            if(redLine.compare("\0") != 0) {
                Record Persona = Parser(redLine);

                unsigned int hashline = HashFunction(Persona.uid);

                if(Collision(hashline) == 0) {
                    Write(Persona, hashline);
                    // islem sayisini artirma
                    transaction++;
                } else if(Collision(hashline) != 0) {
                    hashline = THOUSAND_MOD;

                    Composer(ONE);
                    endpoint++;

                    while(Collision(hashline) != 0) {
                        hashline++;
                        // islem sayisini artirma
                        transaction++;
                        // dosyanin max. boyutuna ulasmasi
                        if(!(hashline < (ENTRIES_NUM + THOUSAND_MOD))) {
                            cout << "MidSquareSO(): " << "ERROR: " << filename << " Can't write UID: " << Persona.uid << " file is OVERFLOW" << endl;
                            break;
                        }
                    }
                    // Correction control
                    if(Collision(hashline) == 0) {
                        Write(Persona, hashline);
                        // islem sayisini artirma
                        transaction++;
                    }
                }
            }
        }

        linear_file.clear();
        linear_file.seekg(0, ios::beg);

        while(linear_file.good()) {
            getline(linear_file, redLine);

            if(redLine.compare("\0") != 0) {
                Record Persona = Parser(redLine);

                unsigned int hashline = HashFunction(Persona.uid);

                if((Search(Persona.uid, hashline)).compare(RECORD_FORM) != 0) {
                    // islem sayisini artirma
                    transaction++;
                } else {

                    hashline = THOUSAND_MOD;

                    while(((Search(Persona.uid, hashline)).compare(RECORD_FORM) == 0) && (hashline < endpoint)) {
                        hashline++;
                        // islem sayisini artirma
                        transaction++;
                    }
                    // Correction control
                    if((Search(Persona.uid, hashline)).compare(RECORD_FORM) != 0) {
                        // islem sayisini artirma
                        transaction++;
                    } else {
                        cout << "MidSquareSO(): " << "ERROR: " << " Can't find UID: " << Persona.uid << " in file " << filename << endl;
                    }
                }
            }
        }
        linear_file.close();
    }
}
void SeedSearcherMain::CmdLineParameters::secondarySetup (int argc, char** argv)
{
   secondarySetup (Parser (argc, argv));
}
Esempio n. 15
0
 RC::ConstHandle<Value> decode( char const *data, unsigned len )
 {
   return Parser().parse( data, len );
 }
Esempio n. 16
0
std::pair<float, std::vector<std::string>>
NetworkInstance::calculate(const std::string& query)
{
	return Parser(query, nc_).parseQuery().execute();
}
Esempio n. 17
0
int main(int argc, const char * argv[])
{


    /*
     Check input switches
    */
    
    int i=0;
    for (i=0; i < argc; i++)
    {
        if (strcmp(argv[i], "-v") == 0)
        {
            shouldPrintStackTrace = 1;
        }
        else if ( strcmp(argv[i], "-l") == 0)
        {
            shouldPrintLexeme = 1;
        }
        else if (strcmp(argv[i], "-a") == 0)
        {
            shouldPrintAssemblyCode = 1;
        }
    }
    
    //  opens input.txt
    originalInputFileWithPCode = fopen(originalInputFileLocation, "r");

    //  scans in the input and saves it to lexemelist inside the Scanner file
    Scanner(originalInputFileWithPCode);

    
    //  opens and handles the parser call
    //  closes file after so we can open to be read later for the virtual machine
    FILE *mcodeOutput = fopen("mcode.txt", "w");
    
    Parser(tokenList);
    printMcodeToFile(mcodeOutput);
    fclose(mcodeOutput);
    
    //  virtual machine
    mcodeOutput = fopen("mcode.txt", "r" );
    

    
    VirualMachine(mcodeOutput,shouldPrintStackTrace);
    
    //  places print statements here so that if it has to print out anything it it finishes running before printing any of the files out to console
    //  handles prints by printing already made files char by char
    
    if (shouldPrintLexeme == 1) {
        int c;
        //FILE *file;
        lexemeList = fopen("lexemelist.txt", "r");
        if (lexemeList) {
            while ((c = getc(lexemeList)) != EOF)
                putchar(c);
            fclose(lexemeList);
        }
        printf("\n");
        
            if (errorOccured == 0) {
                printf("No errors, program is syntactically correct.\n");
            }
    }
    
    if (shouldPrintAssemblyCode == 1) {
        
        printf("\n");
        printf("Assembly Code:\n");
        int c;
        //FILE *file;
        mcodeOutput = fopen("mcode.txt", "r");
        if (mcodeOutput) {
            while ((c = getc(mcodeOutput)) != EOF)
                putchar(c);
            fclose(mcodeOutput);
        }
        printf("\n");

    }
    
    //  if the -v argument was made then it goes through and prints everything in the file
    if (shouldPrintStackTrace == 1) {
        printf("\n");

        int c;
        FILE *file;
        file = fopen("stacktraceTemp.txt", "r");
        if (file) {
            while ((c = getc(file)) != EOF)
                putchar(c);
            fclose(file);
        }
        printf("\n");
        
    }
    
    fclose(originalInputFileWithPCode);
    
    
    return 0;
}
Esempio n. 18
0
Script::Script(String const &source) : d(new Instance)
{
    Parser().parse(source, *this);
}
Esempio n. 19
0
int main(int argc, char **argv)
{
    int timer_tick_rate;
    char *addr;

    /* world is a global now */
    world = &World;

    if (sock_startup() < 0) {
    	warn("Error initializing sockets\n");
	return 1;
    }

    if (World_init() < 0) {
	warn("Error initializing world\n");
	return 1;
    }

    /*
     * Make output always linebuffered.  By default pipes
     * and remote shells cause stdout to be fully buffered.
     */
    setvbuf(stdout, NULL, _IOLBF, BUFSIZ);
    setvbuf(stderr, NULL, _IOLBF, BUFSIZ);

    /*
     * --- Output copyright notice ---
     */

    xpprintf("  " COPYRIGHT ".\n"
	   "  " TITLE " comes with ABSOLUTELY NO WARRANTY; "
	      "for details see the\n"
	   "  provided COPYING file.\n\n");

    init_error(argv[0]);

    /*seedMT((unsigned)time(NULL) * Get_process_id());*/
    /* Removed seeding random number generator because of server recordings. */

    Groups_init();

    /* Make trigonometric tables */
    Make_table();

    if (!Parser(argc, argv))
	exit(1);

    Init_recording();
    /* Lock the server into memory */
    plock_server(options.pLockServer);

    Asteroid_line_init();
    Wormhole_line_init();
    Walls_init();

    /* Allocate memory for players, shots and messages */
    Alloc_players(Num_bases() + MAX_PSEUDO_PLAYERS + MAX_SPECTATORS);
    spectatorStart = Num_bases() + MAX_PSEUDO_PLAYERS;
    Alloc_shots(MAX_TOTAL_SHOTS);
    Alloc_cells();

    Move_init();
    Robot_init();
    Treasure_init();
    Hitmasks_init();

    Rank_init_saved_scores();

    /*
     * Get server's official name.
     */
    if (options.serverHost) {
	addr = sock_get_addr_by_name(options.serverHost);
	if (addr == NULL) {
	    warn("Failed name lookup on: %s", options.serverHost);
	    exit(1);
	}
	serverAddr = xp_strdup(addr);
	strlcpy(Server.host, options.serverHost, sizeof(Server.host));
    } else
	sock_get_local_hostname(Server.host, sizeof Server.host,
				(options.reportToMetaServer != 0 &&
				 options.searchDomainForXPilot != 0));

    Get_login_name(Server.owner, sizeof Server.owner);

    /* Log, if enabled. */
    Log_game("START");

    if (!Contact_init())
	End_game();

    Meta_init();

    Timing_setup();
    Check_playerlimit();

    if (Setup_net_server() == -1)
	End_game();

#ifndef _WINDOWS
    if (options.NoQuit)
	signal(SIGHUP, SIG_IGN);
    else
	signal(SIGHUP, Handle_signal);
    signal(SIGTERM, Handle_signal);
    signal(SIGINT, Handle_signal);
    signal(SIGPIPE, SIG_IGN);
#ifdef IGNORE_FPE
    signal(SIGFPE, SIG_IGN);
#endif
#endif	/* _WINDOWS */

    /*
     * Set the time the server started
     */
    serverStartTime = time(NULL);

    xpprintf("%s Server runs at %d frames per second\n",
	     showtime(), options.framesPerSecond);

    teamcup_init();

#ifdef SELECT_SCHED
    install_timer_tick(Main_loop, FPS);
#else
    if (options.timerResolution > 0)
	timer_tick_rate = options.timerResolution;
    else
	timer_tick_rate = FPS;

# ifdef _WINDOWS
    /* Windows returns here, we let the worker thread call sched() */
    install_timer_tick(ServerThreadTimerProc, timer_tick_rate);
# else
    install_timer_tick(Main_loop, timer_tick_rate);

# endif
#endif

    sched();
    End_game();

    /* NOT REACHED */
    abort();
}
Esempio n. 20
0
void Script::parse(String const &source)
{
    d->compound.clear();
    Parser().parse(source, *this);
}
Esempio n. 21
0
int main(int argc, const char * argv[])
{
    std::string src = "";
    std::string dest = "";
    
    std::string reg = "[a-zA-F0-9]+\\.opvm";
    
    bool compile = true;
    
    if (argc == 1) {
        printf("\n");
        printf("Usage: opvm-as [-S] src [-o dest] \n");
        printf("\n");
        exit(1);
    }
    else if (strcmp(argv[1], "-S") == 0) {
        compile = false;
        if ( argc >= 3 ) {
            src = argv[2];
            if (argc == 5 && strcmp(argv[3], "-o") == 0) {
                dest = argv[4];
            }
            else {
                dest = "a.out";
            }
        }
        else {
            printf("\n");
            printf("Usage: opvm-as [-S] src [-o dest] \n");
            printf("\n");
            exit(1);
        }
    }
    else if (std::regex_match(argv[1], std::regex(reg))) {
        if ( argc >= 2 ) {
            src = argv[1];
            if (argc == 4 && strcmp(argv[2], "-o") == 0) {
                dest = argv[3];
            }
            else {
                dest = "a.out";
            }
        }
        else {
            printf("\n");
            printf("Usage: opvm-as [-S] src [-o dest] \n");
            printf("\n");
            exit(1);
        }

    }
    else {
        printf("\n");
        printf("Usage: opvm-as [-S] src [-o dest] \n");
        printf("\n");
        exit(1);
    }
    
    std::string oldDest = dest;

    Parser parser = Parser(src, dest);

    if (compile) {
        dest += ".c";
        std::string command = "clang " + dest + " -o " + oldDest + " 2> /dev/null";
        
        std::cout << command << std::endl;
        
        system(command.c_str());
    }
    
    //Parser parser = Parser("/Users/Seanlth/Projects/OPVM_Compiler/OPVM_Compiler/code1.opvm", "/Users/Seanlth/Projects/OPVM_Compiler/code");
    
    return 0;
}
Esempio n. 22
0
 Parser::Parser(string text) {
     Parser();
     root.setNode(text);
 }
Esempio n. 23
0
bool Parser::parseExpression(StringRef Code, Sema *S,
                             VariantValue *Value, Diagnostics *Error) {
  CodeTokenizer Tokenizer(Code, Error);
  return Parser(&Tokenizer, S, Error).parseExpressionImpl(Value);
}
Esempio n. 24
0
bool CDBFormatCSV::Load (IByteStream &Stream, const SOptions &Options, CDBTable &Table, CString *retsError)

//	Load
//
//	Load a CSV file into a table.

	{
	int i;
	CCSVParser Parser(Stream);

	if (Options.bUseUTF8)
		Parser.SetUTF8Format();

	//	Parse the header

	if (!Parser.ParseHeader(retsError))
		return false;

	//	Create columns

	Table.CleanUp();
	const TArray<CString> &Header = Parser.GetHeader();
	for (i = 0; i < Header.GetCount(); i++)
		{
		CDBColumnDef ColDef(Header[i], CDBValue::typeString, i);
		if (!Table.AddCol(ColDef))
			{
			if (retsError) *retsError = strPattern(ERR_BAD_HEADER, Header[i]);
			return false;
			}
		}

	//	Now add all the rows.

	const int ROW_GRANULARITY = 100;
	int iRow = 0;
	while (Parser.HasMore())
		{
		//	Grow the array appropriately by 100s

		if ((iRow % ROW_GRANULARITY) == 0)
			Table.GrowToFit(ROW_GRANULARITY);

		//	Parse the row

		TArray<CString> Row;
		if (!Parser.ParseRow(Row, retsError))
			return false;

		if (!Options.bAllowShortRows && Row.GetCount() < Table.GetColCount())
			{
			if (retsError) *retsError = ERR_NOT_ENOUGH_COLS_IN_ROW;
			return false;
			}

		//	Add each field.

		Table.AddRow();
		for (i = 0; i < Table.GetColCount(); i++)
			{
			if (!Table.SetField(i, iRow, CDBValue::FromHandoff(Row[i])))
				{
				ASSERT(false);	//	Should never happen
				if (retsError) *retsError = ERR_BAD_FIELD_INDEX;
				return false;
				}
			}

		//	Next row

		iRow++;
		}

	return true;
	}
Esempio n. 25
0
ClassDef MocNg::parseClass(clang::CXXRecordDecl* RD, clang::Sema& Sema)
{
    clang::Preprocessor &PP = Sema.getPreprocessor();
    ClassDef Def;
    Def.Record = RD;

    for (auto it = RD->decls_begin(); it != RD->decls_end(); ++it) {
        if (clang::StaticAssertDecl *S = llvm::dyn_cast<clang::StaticAssertDecl>(*it) ) {
            if (auto *E = llvm::dyn_cast<clang::UnaryExprOrTypeTraitExpr>(S->getAssertExpr()))
                if (clang::ParenExpr *PE = llvm::dyn_cast<clang::ParenExpr>(E->getArgumentExpr()))
            {
                llvm::StringRef key = S->getMessage()->getString();
                if (key == "qt_property") {
                    clang::StringLiteral *Val = llvm::dyn_cast<clang::StringLiteral>(PE->getSubExpr());
                    if (Val) {
                        PropertyParser Parser(Val->getString(),
    //                                          Val->getStrTokenLoc(0),
                                            Val->getLocationOfByte(0, PP.getSourceManager(), PP.getLangOpts(), PP.getTargetInfo()),
                                            Sema, Def.Record);
                        Def.Properties.push_back(Parser.parseProperty());
                        Def.addExtra(Parser.Extra);
                    } else {
                        PP.getDiagnostics().Report(S->getLocation(),
                                                   PP.getDiagnostics().getCustomDiagID(clang::DiagnosticsEngine::Error,
                                                   "Invalid Q_PROPERTY annotation"));
                    }
                } else if (key == "qt_private_property") {
                    clang::StringLiteral *Val1 = nullptr, *Val2 = nullptr;
                    std::tie(Val1, Val2) = ExtractLiterals(PE, PP, "Q_PRIVATE_PROPERTY",
                                                           "Invalid Q_PRIVATE_PROPERTY annotation");

                    if (Val1 && Val2) {
                        PropertyParser Parser(Val2->getString(),
                                              Val2->getLocationOfByte(0, PP.getSourceManager(), PP.getLangOpts(), PP.getTargetInfo()),
                                              Sema, Def.Record);
                        PropertyDef P = Parser.parseProperty(true);
                        P.inPrivateClass = Val1->getString();
                        Def.Properties.push_back(std::move(P));
                        Def.addExtra(Parser.Extra);
                    }
                } else if (key == "qt_private_slot") {
                    clang::StringLiteral *Val1 = nullptr, *Val2 = nullptr;
                    std::tie(Val1, Val2) = ExtractLiterals(PE, PP, "Q_PRIVATE_SLOT",
                                                           "Invalid Q_PRIVATE_SLOT annotation");
                    if (Val1 && Val2) {
                        PropertyParser Parser(Val2->getString(),
                                              Val2->getLocationOfByte(0, PP.getSourceManager(), PP.getLangOpts(), PP.getTargetInfo()),
                                              Sema, Def.Record);
                        PrivateSlotDef P = Parser.parsePrivateSlot();
                        P.InPrivateClass = Val1->getString();
                        if (!P.Name.empty()) {
                            Def.PrivateSlotCount += P.NumDefault + 1;
                            Def.PrivateSlots.push_back(std::move(P));
                        }
                    }
                } else if (key == "qt_enums")  {
                    parseEnums(Def, false, PE->getSubExpr(), Sema);
                } else if (key == "qt_flags")  {
                    parseEnums(Def, true, PE->getSubExpr(), Sema);
                } else if (key == "qt_qobject") {
                    Def.HasQObject = true;
                } else if (key == "qt_fake") {
                    Def.HasQGadget = false;
                } else if (key == "qt_qgadget") {
                    Def.HasQGadget = true;
                } else if (key == "qt_classinfo") {
                    clang::StringLiteral *Val1 = nullptr, *Val2 = nullptr;
                    std::tie(Val1, Val2) = ExtractLiterals(PE, PP, "Q_CLASSINFO",
                                                           "Expected string literal in Q_CLASSINFO");

                    if (Val1 && Val2) {
                        Def.ClassInfo.emplace_back(Val1->getString(), Val2->getString());
                    }
                } else if (key == "qt_interfaces") {
                    parseInterfaces(Def, PE->getSubExpr(), Sema);
                } else if (key == "qt_plugin_metadata") {
                    parsePluginMetaData(Def, PE->getSubExpr(), Sema);
                    HasPlugin = true;
                }
            }
        } else if (clang::CXXMethodDecl *M = llvm::dyn_cast<clang::CXXMethodDecl>(*it)) {
            for (auto attr_it = M->specific_attr_begin<clang::AnnotateAttr>();
                attr_it != M->specific_attr_end<clang::AnnotateAttr>();
                ++attr_it) {

                const clang::AnnotateAttr *A = *attr_it;
                if (A->getAnnotation() == "qt_signal") {
                        Def.Signals.push_back(M);
                } else if (A->getAnnotation() == "qt_slot") {
                        Def.Slots.push_back(M);
                } else if (A->getAnnotation() == "qt_invokable" || A->getAnnotation() == "qt_scriptable" ) {
                    if (auto *C = llvm::dyn_cast<clang::CXXConstructorDecl>(M)) {
                            Def.Constructors.push_back(C);
                    } else {
                            Def.Methods.push_back(M);
                    }
                } else if (A->getAnnotation().startswith("qt_revision:")) {
                    Def.RevisionMethodCount++;
                }
            }
        }
    }

    //Check notify Signals
    for (PropertyDef &P: Def.Properties) {
        if (!P.notify.Str.empty()) {
            int Idx = 0;
            for (clang::CXXMethodDecl *MD : Def.Signals) {
                if (MD->getName() == P.notify.Str) {
                    P.notify.notifyId = Idx;
                    P.notify.MD = MD;
                    break;
                }
                Idx += 1 + MD->getNumParams() - MD->getMinRequiredArguments();
            }
            if (P.notify.notifyId < 0 ) {
                PP.getDiagnostics().Report(P.notify.Loc,
                        PP.getDiagnostics().getCustomDiagID(clang::DiagnosticsEngine::Error,
                        "NOTIFY signal '%0' of property '%1' does not exist in class %2"))
                    << P.notify.Str << P.name << Def.Record;
            } else {
                Def.NotifyCount++;
            }
        }

        if (P.revision > 0)
            Def.RevisionPropertyCount++;
    }
    return Def;
}
Esempio n. 26
0
bool dumpStab(StringRef InputFile, ArrayRef<std::string> Archs,
              StringRef PrependPath) {
  MachODebugMapParser Parser(InputFile, Archs, PrependPath, false);
  return Parser.dumpStab();
}
Esempio n. 27
0
Linear::Linear(const char * _filename, const char * random_filename) : Base(_filename) {
    ifstream random_file;
    random_file.open(random_filename, ios::in);

    if( !random_file.is_open() ) {
        cout << "Linear(): " << "ERROR: " << random_filename << " Can't be opened" << endl;
    } else {
        // dosyaya yazma islemi
        string redLine;
        while(random_file.good()) {
            getline(random_file, redLine);

            if(redLine.compare("\0") != 0) {
                Record Persona = Parser(redLine);
                Composer(ONE);

                unsigned int line = 0;

                while(Collision(line) != 0) {
                    line++;
                    // islem sayisini artirma
                    transaction++;
                    // dosya dolu ise
                    if(line >= ENTRIES_NUM) {
                        cout << "Linear(): " << "ERROR: " << filename << " Can't write UID: " << Persona.uid << " file is FULL" << endl;
                        break;
                    }
                }
                // Correction control
                if(Collision(line) == 0) {
                    Write(Persona, line);
                    // islem sayisini artirma
                    transaction++;
                }
            }
        }
        // dosyada arama islemi
        random_file.clear();
        random_file.seekg(0, ios::beg);

        while(random_file.good()) {
            getline(random_file, redLine);

            if(redLine.compare("\0") != 0) {
                Record Persona = Parser(redLine);

                unsigned int line = 0;
                // adres dolu ve kayit o adreste degil ise
                while((Search(Persona.uid, line)).compare(RECORD_FORM) == 0 && line < ENTRIES_NUM) {
                    line++;
                    // islem sayisini artirma
                    transaction++;
                }
                // Correction control
                if((Search(Persona.uid, line)).compare(RECORD_FORM) != 0) {
                    // islem sayisini artirma
                    //transaction++;
                } else {
                    cout << "Linear(): " << "ERROR: " << " Can't find UID: " << Persona.uid << " in file " << filename << endl;
                }
            }
        }
        random_file.close();
    }
}