Beispiel #1
0
/*
 *      NextToken - get next symbol from input stream.
 *
 *      NextToken is the basic lexical analyzer.  It builds
 *      basic tokens out of the characters on the input
 *      stream and sets the following global variables:
 *
 *      lastch:         A look behind buffer.
 *      lastst:         type of last symbol read.
 *      laststr:        last string constant read.
 *      lastid:         last identifier read.
 *      ival:           last integer constant read.
 *      rval:           last real constant read.
 *
 *      NextToken should be called for all your input needs...
 */
void NextToken()
{       register int    i, j;
        SYM             *sp;
		int tch;
restart:        /* we come back here after comments */
		SkipSpaces();
        if( lastch == -1)
                lastst = eof;
        else if(isdigit(lastch))
                getnum();
        else if(isidch(lastch)) {
                getid();
				if( (sp = search(lastid,&defsyms)) != NULL) {
						tch = lastch;
						if (!(lastch==')' && sp->value.s[0]=='(')) {
							if (lstackptr < 19) {
								linstack[lstackptr] = lptr;
								chstack[lstackptr++] = tch;
								lptr = sp->value.s;
							}
							getch();
							goto restart;
						}
						}
                }
        else switch(lastch) {
                case '+':
                        getch();
                        if(lastch == '+') {
                                getch();
                                lastst = autoinc;
                                }
                        else if(lastch == '=') {
                                getch();
                                lastst = asplus;
                                }
                        else lastst = plus;
                        break;
                case '-':
                        getch();
                        if(lastch == '-') {
                                getch();
                                lastst = autodec;
                                }
                        else if(lastch == '=') {
                                getch();
                                lastst = asminus;
                                }
                        else if(lastch == '>') {
                                getch();
                                lastst = pointsto;
                                }
                        else lastst = minus;
                        break;
                case '*':
                        getch();
                        if(lastch == '=') {
                                getch();
                                lastst = astimes;
                                }
                        else lastst = star;
                        break;
                case '/':
                        getch();
                        if(lastch == '=') {
                                getch();
                                lastst = asdivide;
                                }
                        else if(lastch == '*') {
								inComment = TRUE;
                                getch();
                                for(;;) {
                                        if(lastch == '*') {
                                                getch();
                                                if(lastch == '/') {
                                                        //getch();
														inComment = FALSE;
                                                        goto restart;
                                                        }
                                                }
                                        else
                                                getch();
                                        }
                                }
						else if (lastch == '/') {
							inComment = TRUE;
							for(;;) {
								getch();
								if (lastch=='\n') {
									//getch();
									inComment = FALSE;
									goto restart;
								}
							}
						}
                        else lastst = divide;
                        break;
                case '^':
                        getch();
                        lastst = uparrow;
                        break;
                case ';':
                        getch();
                        lastst = semicolon;
                        break;
                case ':':
                        getch();
                        lastst = colon;
                        break;
                case '=':
                        getch();
                        if(lastch == '=') {
                                getch();
                                lastst = eq;
                                }
                        else lastst = assign;
                        break;
                case '>':
                        getch();
                        if(lastch == '=') {
                            getch();
                            lastst = geq;
                        }
                        else if(lastch == '>') {
                            getch();
                            if(lastch == '=') {
                                getch();
                                lastst = asrshift;
                            }
                            else lastst = rshift;
                        }
                        else lastst = gt;
                        break;
                case '<':
                        getch();
                        if(lastch == '=') {
                                getch();
                                lastst = leq;
                                }
                        else if(lastch == '<') {
                                getch();
                                if(lastch == '=') {
                                        getch();
                                        lastst = aslshift;
                                        }
                                else lastst = lshift;
                                }
						else if (lastch == '>') {
							getch();
							lastst = neq;
						}
                        else lastst = lt;
                        break;
                case '\'':
                        getch();
                        ival = getsch();        /* get a string char */
                        if(lastch != '\'')
                                error(ERR_SYNTAX);
                        else
                                getch();
                        lastst = iconst;
                        break;
                case '\"':
                        getch();
                        for(i = 0;i < MAX_STRLEN;++i) {
                                if(lastch == '\"')
                                        break;
                                if((j = getsch()) == -1)
                                        break;
                                else
                                        laststr[i] = j;
                                }
                        laststr[i] = 0;
                        lastst = sconst;
                        if(lastch != '\"')
                                error(ERR_SYNTAX);
                        else
                                getch();
                        break;
                case '!':
                        getch();
                        if(lastch == '=') {
                                getch();
                                lastst = neq;
                                }
                        else lastst = not;
                        break;
                case '%':
                        getch();
                        if(lastch == '=') {
                                getch();
                                lastst = asmodop;
                                }
                        else lastst = modop;
                        break;
                case '~':
                        getch();
                        lastst = compl;
                        break;
                case '.':
                        getch();
                        lastst = dot;
						if (lastch=='.') {
							getch();
							if (lastch=='.') {
								getch();
								lastst = ellipsis;
								strcpy(lastid, "...");
							}
						}
                        break;
                case ',':
                        getch();
                        lastst = comma;
                        break;
                case '&':
                        getch();
                        if( lastch == '&') {
                                lastst = land;
                                getch();
                                }
                        else if( lastch == '=') {
                                lastst = asand;
                                getch();
                                }
                        else
                                lastst = and;
                        break;
                case '|':
                        getch();
                        if(lastch == '|') {
                                lastst = lor;
                                getch();
                                }
                        else if( lastch == '=') {
                                lastst = asor;
                                getch();
                                }
                        else
                                lastst = or;
                        break;
                case '(':
                        getch();
                        lastst = openpa;
                        break;
                case ')':
                        getch();
                        lastst = closepa;
                        break;
                case '[':
                        getch();
                        lastst = openbr;
                        break;
                case ']':
                        getch();
                        lastst = closebr;
                        break;
                case '{':
                        getch();
                        lastst = begin;
                        break;
                case '}':
                        getch();
                        lastst = end;
                        break;
                case '?':
                        getch();
                        lastst = hook;
                        break;
                default:
                        getch();
                        error(ERR_ILLCHAR);
                        goto restart;   /* get a real token */
                }
        if(lastst == id)
                IdentifyKeyword();
}
Beispiel #2
0
void Tokenizer::ReadToken(Token& token)
{
start:

    SkipSpaces();
    token.value_s.clear();

    if (!Good()) {
        token.type = Token::type_eof;
        token.pos_string = "EOF";
        return;
    }

    std::stringstream token_tmp;
    if (!include_stack.empty() && !include_stack.back().name.empty())
        token_tmp << include_stack.back().name << " , ";
    token_tmp << "line " << include_stack.back().line << " , column " << include_stack.back().column;
    token.pos_string = token_tmp.str();

    char c = GetNextChar();
    token.value_s += c;
    // first find what token is it, and handle all except numbers
    switch (c) {
    case '[': {
        token.type = Token::type_section_name;
        token.value_s.clear();
        bool skip_next_eol_char = false;
        while (Good()) {
            c = GetNextChar();
            // std::string has problem with zero characters, replace by space.
            if (c == 0) {
                c = ' ';
            }
            if (c == '\\') {
                if (Good()) {
                    token.value_s += GetNextChar();
                } else {
                    ReportError(token, "Quotes not closed before end of file");
                    return;
                }
            } else if (c == ']') {
                return;
            } else {
                token.value_s += c;
            }
            // handle end of line
            if (skip_next_eol_char) {
                skip_next_eol_char = false;
            } else if (c == 10 || c == 13) {
                //++line;
                //column=1;
                if ((PeekNextChar() == 10 || PeekNextChar() == 13) && (PeekNextChar() != c))
                    skip_next_eol_char = true;
            }
        }
        ReportError(token, "Quotes not closed before end of file");
        return;
    }
    case '{':
        token.type = Token::type_enter_section;
        return;
    case '}':
        token.type = Token::type_leave_section;
        return;
    case ';':
        token.type = Token::type_semicolon;
        return;
    case '=':
        token.type = Token::type_entry_value;
        token.value_s = "";
        while (Good() && PeekNextChar() != ';') {
            unsigned char c_ = GetNextChar();
            token.value_s += c_;
        }
        return;
    case '/': // handle comments
        if (PeekNextChar() == '/') {
            //SkipToEOL();
            if (!include_stack.empty()) {
                std::string tmp;
                std::getline((*include_stack.back().stream), tmp);
                include_stack.back().line += 1;
                include_stack.back().column = 1;
            }

            goto start;
        } else if (PeekNextChar() == '*') { // multi-line comment
            while (Good()) {
                char c1 = GetNextChar();
                if ((c1 == '*') && (PeekNextChar() == '/')) {
                    GetNextChar();
                    break;
                }
            }
            goto start;
        }
    default:
        while (Good() && PeekNextChar() != '=') {
            unsigned char c_ = GetNextChar();
            token.value_s += c_;
        }
        token.type = Token::type_entry_name;
        return;
    }
}
Beispiel #3
0
BOOL WINPROC EXPORT DlgOpenProc(
/************************************************************************/
HWND 	hDlg,
UINT 	msg,
WPARAM 	wParam,
LPARAM 	lParam)
{
BOOL Bool;
ITEMID id;
WORD wMsg, wIndex;
int i, ii, l, fp, hi, lo;
FNAME szDriveNDir, szFileName, szExtension;
HMENU hMenu;
STRING szString;
char cChar;
BOOL bModifySaveName;
static BOOL bDisableCancel;

switch (msg)
    {
    case WM_INITDIALOG:
	SET_CLASS_HBRBACKGROUND(hDlg, ( HBRUSH )GetStockObject(LTGRAY_BRUSH));
	CenterPopup( hDlg );
	if ( !DlgDirList(hDlg, szFileSpec, IDC_FLIST, IDC_FPATH, wFileAttr) )
		{
		lstrcpy( szFileSpec, lstrchr( szFileSpec, '*' ) );
		DlgDirList(hDlg, szFileSpec, IDC_FLIST, IDC_FPATH, wFileAttr);
		}
	SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName, fSaving);
	CheckComboItem( hDlg, IDC_FILETYPES, IDC_ART, IDC_BMP,
		IDC_ART + (idFileType-IDN_ART) );
	SendDlgItemMessage(hDlg, IDC_FNAME, EM_LIMITTEXT, MAX_FNAME_LEN-1, 0L);

	LoadComboWithDrives( hDlg, IDC_DRIVES );
	LoadComboWithDirectories( hDlg, IDC_DIRS, NO );
	CheckDlgButton( hDlg, IDC_SAVEPATH, Save.OKtoSavePath );
	CheckDlgButton( hDlg, IDC_SAVECOMPRESS, Save.Compressed );
	for (i = IDC_ART; bImageOpen && i <= IDC_BMP; ++i)
		{
		ii = i-IDC_ART;
		if (lstrlen(Readers[ii].szDLL))
			{
			lstrcpy(szString, Control.ProgHome);
			lstrcat(szString, Readers[ii].szDLL);
			if (!FileExists(szString))
				{
				if ( GetPrivateProfileString( "Micrografx", "Libraries", "",
					szString, sizeof(STRING), "MGX.INI" ) > 2 )
						FixPath( szString );
				lstrcat(szString, Readers[ii].szDLL);
				if (!FileExists(szString))
					{
					ControlEnable( hDlg, i, NO);
					continue;
					}
				}
			}
		if (fSaving)
			ControlEnable( hDlg, i, lpImage &&
				Readers[ii].bSave[FrameDepth(ImgGetBaseEditFrame(lpImage))] );
		else
			ControlEnable( hDlg, i, Readers[ii].bOpen );
		}
	if ( bImageOpen && lpImage )
		{
		idDataType = lpImage->DataType;
		for (i = IDC_SAVECT; i <= IDC_SAVE24BITCOLOR; ++i)
			ControlEnable( hDlg, i,
			Readers[idFileType-IDN_ART].bTypes[i-IDC_SAVECT]);
		CheckComboItem( hDlg, IDC_DATATYPES, IDC_SAVECT,
			IDC_SAVE24BITCOLOR, idDataType );
		ControlEnable( hDlg, IDC_SAVECOMPRESS,
			Readers[idFileType-IDN_ART].bCompressed );
		}

	SetFocus( GetDlgItem( hDlg, IDC_FNAME ) );
	SendDlgItemMessage(hDlg, IDC_FNAME, EM_SETSEL,
		NULL, MAKELONG(0, 0x7fff));
	bNavigated = NO;
	bDisableCancel = NO;
	return( FALSE );

    case WM_PALETTECHANGED:
	break;

    case WM_MENUSELECT:
	lo = LOWORD(lParam);
	hi = HIWORD(lParam);
	if (hi == 0)
		break;
	if (lo == -1)
		break;
	if (lo & MF_SYSMENU)
		break;
	if (lo & MF_POPUP)
		{
		hMenu = (HMENU)wParam;
		while (GetSubMenu(hMenu, 0))
			hMenu = GetSubMenu(hMenu, 0);
		id = GetMenuItemID(hMenu, 0);
		if (id <= 0)
			break;
		wParam = id - 1;
		}
	HintLine( wParam );
	break;

    case WM_SETCURSOR:
	return( SetupCursor( wParam, lParam, idOpen ) );

    case WM_CLOSE:
	AstralDlgEnd( hDlg, FALSE|2 );
	break;

    case WM_MEASUREITEM:
    case WM_DRAWITEM:
	id = ((LPDRAWITEMSTRUCT)lParam)->CtlID;
	Bool = ( id == IDC_DRIVES || id == IDC_DIRS );
	return( OwnerDraw( hDlg, msg, lParam, Bool ) );
//	break;

    case WM_CTLCOLOR:
	return( (BOOL)SetControlColors( (HDC)wParam, hDlg, (HWND)LOWORD(lParam),
		HIWORD(lParam) ) );

    case WM_COMMAND:
	if (wParam != IDCANCEL)
		bDisableCancel = NO;
	switch(wParam)
	    {
	    case IDC_FILETYPES:
//	    case IDC_ART:
//	    case IDC_TIFF:
//	    case IDC_BMP:
		if ( !(wParam = HandleCombo( hDlg, wParam, lParam )) )
			break;
		idFileType = IDN_ART + (wParam-IDC_ART);
		if (bNavigated)
			{
			LookupExtension( idFileType, szFileSpec );
			}
		else	GetFileLocation( idFileType, szFileSpec );
		for (i = IDC_SAVECT; i <= IDC_SAVE24BITCOLOR; ++i)
			ControlEnable( hDlg, i,
			Readers[idFileType-IDN_ART].bTypes[i-IDC_SAVECT]);
		ControlEnable( hDlg, IDC_SAVECOMPRESS,
			Readers[idFileType-IDN_ART].bCompressed );
		SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName, NO );
		SendMessage( hDlg, WM_COMMAND, IDOK, 0L );
		break;

	    case IDC_DATATYPES:
//	    case IDC_SAVECT:
//	    case IDC_SAVELA:
//	    case IDC_SAVESP: // scatterprint
//	    case IDC_SAVE8BITCOLOR:
//	    case IDC_SAVE24BITCOLOR:
		if ( !(wParam = HandleCombo( hDlg, wParam, lParam )) )
			break;
		idDataType = wParam;
		break;

	    case IDC_SAVEPATH:
		Save.OKtoSavePath = (BOOL)SendDlgItemMessage (hDlg, IDC_SAVEPATH,
		  BM_GETCHECK, 0, 0L);
//		Save.OKtoSavePath = !Save.OKtoSavePath;
//		CheckDlgButton( hDlg, IDC_SAVEPATH, Save.OKtoSavePath );
		break;

	    case IDC_SAVECOMPRESS:
		Save.Compressed = (BOOL)SendDlgItemMessage (hDlg, IDC_SAVECOMPRESS,
		  BM_GETCHECK, 0, 0L);
//		Save.Compressed = !Save.Compressed;
//		CheckDlgButton( hDlg, IDC_SAVECOMPRESS, Save.Compressed );
		break;

	    case IDC_DRIVES:
		wMsg = HIWORD(lParam);
		if ( wMsg != CBN_SELCHANGE )
			break;
		wIndex = SendDlgItemMessage( hDlg, wParam, CB_GETCURSEL, 0, 0L);
		SendDlgItemMessage( hDlg, wParam, CB_GETLBTEXT, wIndex,
			(long)(LPSTR)szDriveNDir );
		id = ExtractStringID( szDriveNDir );
		if (CHDRIVE( *szDriveNDir - 'a' ))
			{
			LoadComboWithDrives(hDlg, IDC_DRIVES);
			break;
			}
		if (!CURRENTDIR(szString, sizeof(szString)))
			{
			GetDlgItemText(hDlg, IDC_FPATH, szString,
				 sizeof(szString));
			CHDRIVE(*szString - 'a');
			LoadComboWithDrives(hDlg, IDC_DRIVES);
			}
//12/15		SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName, NO);
		DlgDirList( hDlg, szFileSpec, IDC_FLIST, IDC_FPATH, wFileAttr );
		LoadComboWithDirectories( hDlg, IDC_DIRS, YES );
		SetDlgItemText( hDlg, IDC_DISKSPACE,
			DriveSize( *szDriveNDir - 'a', szString ) );
		SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName, fSaving );
		bNavigated = YES;
		break;

	    case IDC_DIRS:
		wMsg = HIWORD(lParam);
		if ( wMsg == LBN_DBLCLK )
			{
			SendMessage(hDlg, WM_COMMAND, IDOK, 1L);
			break;
			}
		if ( wMsg != LBN_SELCHANGE )
			break;
		wIndex = SendDlgItemMessage( hDlg, wParam, LB_GETCURSEL, 0, 0L);
		// Figure out how to build the path name based on the selection
		SendDlgItemMessage( hDlg, wParam, LB_GETTEXT, wIndex,
			(long)(LPSTR)szDriveNDir );
		id = ExtractStringID( szDriveNDir );
		if ( id == IDC_PATHICON_OPEN )
			i = 0; // Must start building the path from the root
		else
		if ( id == IDC_PATHICON_ACTIVE )
			i = 9999; // Don't build any path - we're there
		else	i = wIndex; // OK to build a relative path
		szFileName[0] = '\0';
		for ( ; i<=wIndex; i++ )
			{
			SendDlgItemMessage( hDlg, wParam, LB_GETTEXT, i,
				(long)(LPSTR)szDriveNDir );
			id = ExtractStringID( szDriveNDir );
			if ( id == IDC_PATHICON_CLOSED && i != wIndex )
				continue;
			lstrcat( szFileName, SkipSpaces(szDriveNDir) );
			if ( id != IDC_PATHICON_ROOT )
				lstrcat( szFileName, "\\" );
			}
		lstrcat( szFileName, szFileSpec );
		SetFileName(hDlg, IDC_FNAME, szFileName, szSaveName, NO );
		bNavigated = YES;
		break;

	    case IDC_FLIST:
		wMsg = HIWORD(lParam);
		if ( wMsg == LBN_DBLCLK )
			{
			SendMessage(hDlg, WM_COMMAND, IDOK, 1L);
			break;
			}
		if ( wMsg != LBN_SELCHANGE )
			break;
		/* If a directory is selected... */
		if (DlgDirSelectEx(hDlg, szFileName, sizeof(szFileName), wParam))
			lstrcat(szFileName, szFileSpec);
		// 1-2-92 - TMR - always use SetFileName for all FNAME sets
// 		SetDlgItemText(hDlg, IDC_FNAME, szFileName);
		SetFileName(hDlg, IDC_FNAME, szFileName, szSaveName, NO );
		SendDlgItemMessage(hDlg, IDC_FNAME, EM_SETSEL,
			NULL, MAKELONG(0, 0x7fff));
//		SendDlgItemMessage(hDlg, IDC_FNAME, CB_SETEDITSEL,
//			NULL, MAKELONG(0, 0x7fff));
		break;

	    case IDC_FNAME:
		/* If the name is changed, disable OK if its length goes 0 */
		if (HIWORD(lParam) != EN_CHANGE)
//		if (HIWORD(lParam) != CBN_EDITCHANGE)
			break;
		ControlEnable( hDlg, IDOK,
			(BOOL)SendDlgItemMessage( hDlg, wParam,
			WM_GETTEXTLENGTH, 0, 0L));
		
		// 1-2-92 - TMR - make sure Edit Box has focus to make sure
		// that szSaveName only gets overwritten from user input
		// 1-3-92 - TMR - move this after ControlEnable
		if (GetFocus() != GetDlgItem(hDlg, IDC_FNAME))
			break;
		if (fSaving)
			{
			GetDlgItemText(hDlg, IDC_FNAME, szSaveName,
				MAX_FNAME_LEN);
			fUntitled = NO;
			}
		break;

	    case IDC_FPATH:
		wMsg = HIWORD(lParam);
		if ( wMsg == BN_DOUBLECLICKED )
			{
			SendMessage(hDlg, WM_COMMAND, IDOK, 1L);
			break;
			}
		if ( wMsg != BN_CLICKED )
			break;
 		GetDlgItemText(hDlg, wParam, szFileName, sizeof(szFileName));
		if ( !szFileName[0] )
			break;
		FixPath( szFileName );
		lstrcat( szFileName, szFileSpec );
		SetFileName(hDlg, IDC_FNAME, szFileName, szSaveName, NO );
		bNavigated = YES;
		break;

	    case IDOK:
		GetDlgItemText(hDlg, IDC_FNAME, szFileName,sizeof(szFileName));
		bModifySaveName = fSaving && StringsEqual(szFileName,
			szSaveName);
		/* Strip off the drive and directory to make */
		/* a DlgDirlist() call to switch over to them */
		/* Loop backwards over the file name */
		l = lstrlen(szFileName);
		while( --l >= 0 )
		   {
		   cChar = szFileName[l];
		   /* If we find a wildcard, the next DlgDirList() takes */
		   /* care of drive and directory switching; so get out */
		   if ( cChar == '?' || cChar == '*' )
			break;
		   /* If we find a drive or directory, handle it and get out */
		   if ( cChar == '\\' || cChar == ':' )
			{
			lstrcpy(szDriveNDir, szFileName);
			l++;
			szDriveNDir[l] = '\0';
			lstrcat(szDriveNDir, szFileSpec);
			// 1-3-92 - TMR - Handle directory change error
			if (DlgDirList(hDlg, szDriveNDir,
					 IDC_FLIST, IDC_FPATH, wFileAttr))
				lstrcpy( szFileName, &szFileName[l] );
			else
				{
				szDriveNDir[l] = '\0';
				Message(IDS_EDIRECTORYCHANGE,
					 Lowercase(szDriveNDir));
				szFileName[0] = '\0';
				}
			break;
			}
		   }

		// 1-3-92 - TMR add extension if none present
		/* Check to see if the file has an extension... */
		if ( !lstrchr( szFileName, '.' ) ) // if no extension...
		    if ( LookupExtension( idFileType, szExtension ) )
			{
			if (lstrlen(szFileName))
			    lstrcat( szFileName, extension(szExtension) );
			else
			    lstrcat( szFileName, szExtension);
			}
		if (bModifySaveName)
			lstrcpy(szSaveName, szFileName);

		/* Try to display a new list box */
		if ( !szFileName[0] )
			lstrcat(szFileName, szFileSpec);
		if (DlgDirList(hDlg, szFileName, IDC_FLIST, IDC_FPATH,
		    wFileAttr))
			{ /* A wildcard was found and a new list displayed */
			lstrcpy(szFileSpec, szFileName);
			SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName,
				fSaving );
			LoadComboWithDrives( hDlg, IDC_DRIVES );
			LoadComboWithDirectories( hDlg, IDC_DIRS, YES );
			
			break;
			}

		// If there is still a path or wildcards in the name, the
		// file specification must be invalid
		if (lstrchr(szFileName, '\\') || lstrchr(szFileName, ':') ||
		    lstrchr(szFileName, '?') || lstrchr(szFileName, '*'))
			{
			lstrcpy(szString, szFileName);
			stripfile(szString);
			Message(IDS_EDIRECTORYCHANGE, Lowercase(szString));
			lstrcpy(szFileSpec, filename(szFileName));
			lstrcpy(szFileName, szFileSpec); // is this needed?
			SetFileName(hDlg, IDC_FNAME, szFileSpec, szSaveName,
				fSaving );
			break;
			}

		/* No wildcards, and the drive and dir have been changed */
		LoadComboWithDrives( hDlg, IDC_DRIVES );
		LoadComboWithDirectories( hDlg, IDC_DIRS, YES );

		/* Check to see if the file has 8 characters or less... */
		if ( fSaving )
			RemoveWhiteSpace( szFileName );
		FixFileName( szFileName );

		/* Check to see if the file has an extension... */
		if ( !lstrchr( szFileName, '.' ) ) // if no extension...
			if ( LookupExtension( idFileType, szExtension ) )
				lstrcat( szFileName, extension(szExtension) );

		// Build the fully qualified path name
		GetDlgItemText( hDlg, IDC_FPATH, szString, sizeof(szString) );
		FixPath( szString );
		lstrcat( szString, szFileName );

		/* Check to see if the file exists... */
		if ( (fp = _lopen( szString, OF_READ ) ) < 0 )
			{ /* The file does not exist */
			if ( !fSaving )
				{
				Message(IDS_EOPEN, Lowercase(szString));
				break;
				}
			}
		else	{
			_lclose( fp );
			if ( fSaving )
				{
				if ( !AstralAffirm( IDS_OVERWRITEIMAGE,
					Lowercase(szString) ) )
					break;
				}
			}

		lstrcpy( szFileSpec, szString );
		AstralDlgEnd(hDlg, TRUE|2);
		break;

	    case IDC_CANCEL:
	    case IDCANCEL:
		if ( bDisableCancel && !LOWORD(lParam) )
			break;
		GetDlgItemText(hDlg, IDC_FPATH, szFileSpec,sizeof(szFileSpec));
		AstralDlgEnd(hDlg, FALSE|2);
		break;

	    default:
		return( FALSE );
	    }
	break;

    default:
	return( FALSE );
    }

return( TRUE );
}
Beispiel #4
0
bool CRealTextParser::ExtractTag(std::wstring& p_rszLine, Tag& p_rTag)
{
    if (p_rszLine.length() < 2 || p_rszLine.at(0) != '<') {
        if (m_bTryToIgnoreErrors) {
            size_t iTempPos = p_rszLine.find_first_of('<');

            if (iTempPos != std::wstring::npos) {
                p_rszLine = p_rszLine.substr(iTempPos);

                if (p_rszLine.length() < 2) {
                    return false;
                }
            }

        } else {
            return false;
        }
    }

    unsigned int iPos = 1;

    // skip comments
    if (p_rszLine.at(iPos) == '!') {
        p_rTag.m_bComment = true;

        std::wstring szComment;
        GetString(p_rszLine, iPos, szComment, L">");
        p_rTag.m_szName = szComment;

        ++iPos; // Skip >
        if (iPos < p_rszLine.length()) {
            p_rszLine = p_rszLine.substr(iPos);
            return true;
        } else {
            return false;
        }
    } else {
        p_rTag.m_bComment = false;
    }

    if (!SkipSpaces(p_rszLine, iPos)) {
        return false;
    }

    if (p_rszLine.at(iPos) == '/') {
        p_rTag.m_bOpen = false;
        p_rTag.m_bClose = true;
        ++iPos;
    } else {
        p_rTag.m_bOpen = true;
        p_rTag.m_bClose = false;
    }

    if (!GetString(p_rszLine, iPos, p_rTag.m_szName, L"\r\n\t />")) {
        return false;
    }

    p_rTag.m_szName = StringToLower(p_rTag.m_szName);

    if (!GetAttributes(p_rszLine, iPos, p_rTag.m_mapAttributes)) {
        return false;
    }

    if (p_rszLine.at(iPos) == '/') {
        ++iPos;
        p_rTag.m_bClose = true;
    }

    if (p_rszLine.at(iPos) == '>') {
        ++iPos;
        p_rszLine = p_rszLine.substr(iPos);
        return true;
    } else {
        if (m_bTryToIgnoreErrors) {
            size_t iTempPos = p_rszLine.find_first_of('>');

            if (iTempPos != std::wstring::npos) {
                if (iTempPos - 1 >= p_rszLine.length()) {
                    return false;
                }

                p_rszLine = p_rszLine.substr(iTempPos + 1);
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }
}
//***************************************************
int Logic::CompileCommands()
{
  int err=0;
  short BlockDepth;
  short BlockStartDataLoc[MaxBlockDepth+1];
  short BlockLength[MaxBlockDepth+1];
  bool BlockIsIf[MaxBlockDepth+1];
  bool InIf,LastCommandWasReturn,InIfBrackets=false,AwaitingNextTestCommand=false,EncounteredLabel;
  int NumCommandsInIfStatement=0,NumCommandsInIfBrackets=0;

  typedef struct{
    byte LabelNum;
    int DataLoc;
  }TLogicGoto;
  TLogicGoto Gotos[MaxGotos+1];
  short NumGotos,GotoData,CurGoto;

  memset( BlockIsIf,0,sizeof( BlockIsIf));
  InIf = false;
  BlockDepth = 0;
  NumGotos = 0;
  FinishedReading = false;
  CurLine = -1;
  NextLine();
  if(FinishedReading){
    ShowError(CurLine,"Nothing to compile !");
    return 1;
  }
  do{
    LastCommandWasReturn = false;
    if(!InIf){
      if(LinePos < LineLength && LowerCaseLine[LinePos] == '}'){
        LinePos++;
        if(BlockDepth==0)
              ShowError(CurLine,"'}' not at end of any command blocks.");
        else{
//          if (ResPos == BlockStartDataLoc[BlockDepth] + 2)
//                ShowError(CurLine,"Command block must contain at least one command.");
          BlockLength[BlockDepth] = ResPos-BlockStartDataLoc[BlockDepth]-2;
          WriteByteAtLoc(BlockLength[BlockDepth] & 0xff,BlockStartDataLoc[BlockDepth]);
          WriteByteAtLoc((BlockLength[BlockDepth]>>8)&0xff,BlockStartDataLoc[BlockDepth]+1);
          BlockDepth--;
          SkipSpaces();
          if (LinePos >= LineLength && CurLine < EditLines.num-1)NextLine();
          if(LowerCaseLine.substr(LinePos,4) == "else"){
            LinePos+=4;
            SkipSpaces();
            if(! BlockIsIf[BlockDepth+1])
                  ShowError(CurLine,"'else' not allowed after command blocks that start with 'else'.");

            else if(LinePos >= LineLength || LowerCaseLine[LinePos] != '{')
                  ShowError(CurLine,"'{' expected after else.");

            else{
              LinePos++;
              BlockDepth++;
              BlockLength[BlockDepth] +=3;
              WriteByteAtLoc(BlockLength[BlockDepth]&0xff,BlockStartDataLoc[BlockDepth]);
              WriteByteAtLoc((BlockLength[BlockDepth]>>8)&0xff,BlockStartDataLoc[BlockDepth]+1);
              BlockIsIf[BlockDepth] = true;
              WriteByte(0xfe);
              BlockStartDataLoc[BlockDepth] = ResPos;
              WriteByte(0x00);  // block length filled in later.
              WriteByte(0x00);
            }
          }//if(LowerCaseLine.substr(LinePos,4) == "else"
        }//if BlockDepth > 0
      }//if LowerCaseLine[LinePos] == '}'
      else{
        ReadCommandName();
        if(CommandName == "if"){
          WriteByte(0xFF);
          InIf = true;
          SkipSpaces();
          if(LinePos >= LineLength || EditLines.at(CurLine)[LinePos] != '(')
                ShowError(CurLine,"'(' expected at start of if statement.");

          LinePos++;
          InIfBrackets = false;
          NumCommandsInIfStatement = 0;
          AwaitingNextTestCommand = true;
        }
        else if(CommandName == "else")
              ShowError(CurLine,"'}' required before 'else'.");

        else if(CommandName == "goto"){
          if(LinePos >= LineLength || LowerCaseLine[LinePos] != '(')
                ShowError(CurLine,"'(' expected.");
          else{
            LinePos++;
            ReadCommandName();
            CommandName = ReplaceDefine(CommandName);
            if (LabelNum(CommandName) == 0)
                  ShowError(CurLine,"Unknown label "+CommandName+".");
            else if (NumGotos >= MaxGotos)
                  ShowError(CurLine,"Too many labels (max "+IntToStr(MaxLabels)+").");
            else{
              NumGotos++;
              Gotos[NumGotos].LabelNum = LabelNum(CommandName);
              WriteByte(0xFE);
              Gotos[NumGotos].DataLoc = ResPos;
              WriteByte(0x00);
              WriteByte(0x00);
              if(LinePos >= LineLength || LowerCaseLine[LinePos] != ')')
                    ShowError(CurLine,"')' expected after label name.");

              LinePos++;
              if(LinePos >= LineLength || LowerCaseLine[LinePos] != ';')
                    ShowError(CurLine,"';' expected after goto command.");
              LinePos++;
            }
          }
        }
        else{
          CommandNum = FindCommandNum(false,CommandName);
          EncounteredLabel = (LabelNum(CommandName) > 0);
          if (EncounteredLabel && LinePos < LineLength && LowerCaseLine[LinePos] == ':')
            LinePos++;
          else  EncounteredLabel = false;
          EncounteredLabel = (EncounteredLabel && LabelAtStartOfLine(CommandName));
          if(EncounteredLabel){
            Labels[LabelNum(CommandName)].Loc = ResPos;
          }
          else{
            if (CommandNum == 255){ // not found
              if (!AddSpecialSyntax())
                  ShowError(CurLine,"Unknown action command "+EditLines.at(CurLine).substr(CommandNameStartPos,CommandName.length())+".");
            }
            else{
              WriteByte(CommandNum);
              ReadArgs(false,CommandNum);
              if (CommandNum == 0)LastCommandWasReturn = true;
            }
            if (LinePos >= LineLength || EditLines.at(CurLine)[LinePos] != ';')                           ShowError(CurLine,"';' expected after command.");

            LinePos++;
          }//if we found a label
        }//command
      }//if LowerCaseLine[LinePos] != '}'
    }//(!InIf)
//***************************************************
bool Logic::AddSpecialIFSyntax()
{
  int OldLinePos;
  int arg1,arg2;
  bool arg2isvar,AddNOT;
  string ArgText,expr;

  OldLinePos = LinePos;
  LinePos -= CommandName.length();
  ArgText = ReplaceDefine(ReadPlainText());

  if(ArgText[0]=='v'){
    if (NOTOn) ShowError(CurLine,"'!' not allowed before var.");
    arg1=Val(ArgText.substr(1));
    if(arg1<0||arg1>255)
      ShowError(CurLine,"Invalid number given or error in expression syntax.");
    else{
      SkipSpaces();
      expr = ReadExprText();
      SkipSpaces();
      ArgText = ReplaceDefine(ReadPlainText());
      arg2isvar = (ArgText[0]=='v');
      if(arg2isvar)
        arg2=Val(ArgText.substr(1));
      else
        arg2=Val(ArgText);
      if(arg2<0||arg2>255)
       ShowError(CurLine,"Invalid number given or error in expression syntax.");
      else{
        CommandNum=0;
        AddNOT = false;
        if(expr == "==")CommandNum = 0x01;  //equal
        else if(expr == "<")CommandNum = 0x03;  //less
        else if(expr == ">")CommandNum = 0x05;  //greater
        else if(expr == "!="){ CommandNum = 0x01;  AddNOT = true; } //!equal
        else if(expr == ">="){ CommandNum = 0x03;  AddNOT = true; } //!less
        else if(expr == "<="){ CommandNum = 0x05;  AddNOT = true; } //!greater
        else ShowError(CurLine,"Expression syntax error");
        if(CommandNum>0){
          if (arg2isvar)CommandNum++;
           if (AddNOT) WriteByte(0xFD);
           WriteByte(CommandNum);
           WriteByte(arg1);
           WriteByte(arg2);
           return true;
        }
      }
    }
  }//if(ArgText[0]=='v')
  else if(ArgText[0]=='f'){
    arg1 = Val(ArgText.substr(1));
    if(arg1<0||arg1>255)
      ShowError(CurLine,"Invalid number given or error in expression syntax..");
    else{
      WriteByte(0x07);  // isset
      WriteByte(arg1);
      return true;
    }
  }//if(ArgText[0]=='f')
  else LinePos = OldLinePos;
  return false;


}
// -----------------------------------------------------------------------------
// CAknKeyRotatorImpl::GetKeyRotatorCompensationL
// Parses wsini.ini to read key rotator compensation value.
// -----------------------------------------------------------------------------
//
TInt CAknKeyRotatorImpl::GetKeyRotatorCompensationL()
    {
    TInt result = 0;
    HBufC* wsiniText = GetWsiniLC();
    
    // Now look for keyword
    const TInt pos = wsiniText->Find( KAknKeyRotatorKey );
    if ( pos != KErrNotFound )
        {        
        // Keyword was found. Check that it is the beginning of line.
        // Three cases:
        // 1. Keyword could be at the beginning of the file.
        // 2. Keyword could be at the beginning of the file 
        //    after byte ordering marker.
        // 3. Previous character can be end of line marker.
        const TInt previousPos = pos - 1;
        if ( previousPos < 0 || 
             ( !previousPos && 
               IsByteOrderingMarker( (*wsiniText)[ previousPos ] ) ) || 
             IsEndOfLine( (*wsiniText)[ previousPos ] ) )
            {
            TLex text( wsiniText->Mid( pos + KAknKeyRotatorKey().Length() ) );
            
            // First, there must be at least a space after keyword.
            TBool fail = !( SkipSpaces( text ) & EAknWasSpace );
           
            // Case 1: Disabled
            TBool wasDisabled = EFalse;
            if ( !fail )
                {
                wasDisabled = 
                    !text.Remainder().Left( KAknKeyRotatorDisabled().Length() ).
                    CompareF( KAknKeyRotatorDisabled );

                if ( wasDisabled )
                    {
                    // wasDisabled == True, KAknKeyRotatorDisabled was prefix
                    // of text. So skip over it
                    text.Inc( KAknKeyRotatorDisabled().Length() );
                    }
                }
            
            // Case 2: Then follows a sequence of digits, optionally preceded by '-'.
            if ( !wasDisabled && !fail )
                {
                // Check optional -
                TBool negate = EFalse;
                if ( !text.Eos() && text.Peek() == '-' )
                    {
                    negate = ETrue;
                    text.Inc();
                    }
                    
                // Get digit sequence and convert to integer value.
                TPtrC token = GetDigits( text );
                fail = !token.Length() || 
                       ( TLex( token ).Val( result ) != KErrNone );
                
                // Handle negation
                if ( !fail && negate )
                    {
                    result = -result;
                    }
                }

            // That sequence of digits is followed by sequence of spaces until
            // end of line or end of file.
            fail = fail || ( SkipSpaces( text ) & EAknWasCharacter );
            
            if ( !wasDisabled )
                {
                // Finally, that sequence of digits must represent
                // one valid decimal value of the following: 
                // -270, -180, -90, 0, 90, 180, 270.
                fail = fail || !CheckCompensationValue( result );
                }
                
            // If any of above checks failed, use default value 0.
            if ( fail )
                {
                result = 0;
                }
            else
                {
                if ( wasDisabled )
                    {
                    result = KMaxTInt;
                    }
                }
            }
        }
        
    CleanupStack::PopAndDestroy( wsiniText );   
    return result;
    }
Beispiel #8
0
BOOL HandleCommandLine(
/***********************************************************************/
HWND 	hWindow,
LPSTR 	lpszCmdLine,
LPINT 	lpPrint)
{
FNAME szFileName;
LPSTR lp;
BOOL bPassedByClient, bGotImage;
LPIMAGE lpImageDoc;
HWND hWnd;
int i;

bPaintAppActive = TRUE;

*lpPrint = NO;
if ( !lpszCmdLine )
	{ // If no command line, bring up an empty image
	SendMessage( hWindow, WM_COMMAND, IDM_NEW, 0L );
	if ( (hWnd = AstralDlgGet(IDD_MAIN)) && !IsWindowVisible( hWnd ) )
		ShowWindow( hWnd, SW_SHOW );
	return( TRUE );
	}

// Check if we have "[/ | -]embedding" and a possible filename.
// usage: PP ["[-/]embedding"] file1 file2 ...

// See if the command line is being passed by a client
bPassedByClient = NO;
if ( (lp = lstrfind( lpszCmdLine, "embedding" )) &&
	 (lp == lpszCmdLine || lp == (lpszCmdLine+1)) )
	{ // Command line passed by a client
	bPassedByClient = YES;
	lpszCmdLine = SkipSpaces( lp + 9 ); // skip over "embedding"
	}

bGotImage = NO;
while ( *lpszCmdLine )
	{ // Process any files and switches on the command line

	// Skip white space and see if we're done...
	lpszCmdLine = SkipSpaces( lpszCmdLine );
	if ( !(*lpszCmdLine ) )
		break; // If NULL get out

	// Check for any switches preceeding the file name: only /p for now
	while ( *lpszCmdLine == '/' )
		{ // a switch...
		lpszCmdLine++; // Skip over the slash
		if ( !*lpszCmdLine )
			break; // If NULL get out
		if ( *lpszCmdLine == 'p' || *lpszCmdLine == 'P' )
			*lpPrint = YES;
		lpszCmdLine++; // Skip the option character
		lpszCmdLine = SkipSpaces( lpszCmdLine );
		}

	// Skip white space and see if we're done...
	lpszCmdLine = SkipSpaces( lpszCmdLine );
	if ( !(*lpszCmdLine ) )
		break; // If NULL get out

	// Try to zap the space after a single file name
	if ( (lp = lstrfind( lpszCmdLine, " " )) )
		*lp = '\0'; // If we found a space, zap it

	// Copy the full path name into szFileName
#ifdef _MAC
	lstrcpy( szFileName, lpszCmdLine );
#else	
	if ( lstrchr( lpszCmdLine, '\\' ) )
		lstrcpy( szFileName, lpszCmdLine );
	else
		{ // If not a full path name...
		GetCurrentDir( szFileName, sizeof(FNAME) );
		FixPath( szFileName );
		lstrcat( szFileName, lpszCmdLine );
		}
#endif

	// Now we're done with lpszCmdLine, so set it up for the next loop
	if ( lp ) // If we had found a space, there might be more file names
			lpszCmdLine = lp + 1;
	else	lpszCmdLine += lstrlen(lpszCmdLine); // Point to nothing

	// Special handling of documents passed by a client
////if ( bPassedByClient )
////	{ // Loop through documents to see if it's already open
		for ( i=0; i<NumDocs(); i++ )
			{
			hWnd = GetDoc(i);
			if ( !(lpImageDoc = (LPIMAGE)GetWindowLong( hWnd, GWL_IMAGEPTR )))
				continue;
			if ( !StringsEqual( lpImageDoc->CurFile, szFileName ) )
				continue;
			// It's already open....
			SendMessage( hClientAstral, WM_MDIACTIVATE, (WPARAM)hWnd, 0L );
			if ( bPassedByClient )
				lpImageDoc->fOwnedByClient = YES;
			szFileName[0] = '\0'; // Zap it
			bGotImage = YES;
			break;
			}
////	}

	// If we have a file name, open it...
	if ( *szFileName )
		{
		if ( AstralImageLoad( NULL, szFileName, MAYBE, YES ) )
			bGotImage = YES;
		}

	// If the printing option was passed, print it and close it
	if ( *lpPrint && lpImage )
		{
		SendMessage(hWndAstral, WM_COMMAND, IDM_PRINT, 0L );
		CloseImage( NO, NULL );
		}
	}

if ( !bGotImage )
	{
	if ( !idCurrentRoom )
		{
	    GoRoom (hInstAstral, -1, FALSE);
		return( FALSE );
		}
	// If no image was opened via the command line, go to the opening screen
	SendMessage( hWindow, WM_COMMAND, IDM_NEW, 0L );
	}

if ( (hWnd = AstralDlgGet(IDD_MAIN)) && !IsWindowVisible( hWnd ) )
	ShowWindow( hWnd, SW_SHOW );

return( TRUE );
}
Beispiel #9
0
int  main( int argc, char **argv )
/********************************/
{
    int         rc;
    char        *wcl_env;
    char        *p;
    char        *q;
    char        *Cmd;               /* command line parameters            */

#ifndef __WATCOMC__
    _argc = argc;
    _argv = argv;
#endif

    CC_Opts[0] = '\0';

    Switch_Chars[0] = '-';
    Switch_Chars[1] = _dos_switch_char();
    Switch_Chars[2] = '\0';

    MemInit();
    ProcMemInit();
    Word = MemAlloc( MAX_CMD );
    Cmd = MemAlloc( MAX_CMD * 2 );  /* enough for cmd line & wcl variable */

    /* add wcl environment variable to Cmd             */
    /* unless /y is specified in either Cmd or wcl */

    wcl_env = getenv( WCLENV );
    if( wcl_env != NULL ) {
        strcpy( Cmd, wcl_env );
        strcat( Cmd, " " );
        p = Cmd + strlen( Cmd );
        getcmd( p );
        q = Cmd;
        while( (q = strpbrk( q, Switch_Chars )) != NULL ) {
            if( tolower( *(++q) ) == 'y' ) {
                getcmd( Cmd );
                p = Cmd;
                break;
            }
        }
    } else {
        getcmd( Cmd );
        p = Cmd;
    }
    p = SkipSpaces( p );
    if( *p == '\0' || p[0] == '?' && ( p[1] == '\0' || p[1] == ' ' )
        || p[0] == '-' && p[1] == '?' ) {
        Usage();
        rc = 1;
    } else {
        errno = 0; /* Standard C does not require fopen failure to set errno */
        if( (Fp = fopen( TEMPFILE, "w" )) == NULL ) {
            /* Message before banner decision as '@' option uses Fp in Parse() */
            PrintMsg( WclMsgs[UNABLE_TO_OPEN_TEMPORARY_FILE], TEMPFILE,
                strerror( errno ) );
            rc = 1;
        } else {
            initialize_Flags();
            rc = Parse( Cmd );
            if( rc == 0 ) {
                if( !Flags.be_quiet ) {
                    print_banner();
                }
                rc = CompLink();
            }
            if( rc == 1 ) {
                fclose( Fp );
            }
            if( Link_Name != NULL ) {
                if( fname_cmp( Link_Name, TEMPFILE ) != 0 ) {
                    remove( Link_Name );
                    rename( TEMPFILE, Link_Name );
                }
            } else {
                remove( TEMPFILE );
            }
        }
    }
    ProcMemFini();
    MemFree( Cmd );
    MemFree( Word );
    MemFini();
    return( rc == 0 ? 0 : 1 );
}
Beispiel #10
0
static int Parse( char *Cmd )
/***************************/
{
    char        opt;
    char        *end;
    FILE        *atfp;
    char        buffer[_MAX_PATH];
    char        unquoted[_MAX_PATH];
    int         len;
    char        *p;
    int         wcc_option;
    list        *new_item;

    /* Cmd will always begin with at least one */
    /* non-space character if we get this far  */

    for( ;; ) {
        Cmd = SkipSpaces( Cmd );
        if( *Cmd == '\0' )
            break;
        opt = *Cmd;
        if( opt == '-'  ||  opt == Switch_Chars[1] ) {
            Cmd++;
        } else if( opt != '@' ) {
            opt = ' ';
        }

        end = Cmd;
        if( *Cmd == '"' ) {
            end = FindNextWS( end );
        } else {
            end = FindNextWSOrOpt( end, opt, Switch_Chars );
        }
        len = end - Cmd;
        if( len != 0 ) {
            if( opt == ' ' ) {          /* if filename, add to list */
                strncpy( Word, Cmd, len );
                Word[len] = '\0';
                end = ScanFName( end, len );
                UnquoteFName( unquoted, sizeof( unquoted ), Word );
                new_item = MemAlloc( sizeof( list ) );
                new_item->next = NULL;
                new_item->item = MemStrDup( unquoted );
                if( FileExtension( Word, ".lib" ) ) {
                    ListAppend( &Libs_List, new_item );
                } else if( FileExtension( Word, ".res" ) ) {
                    ListAppend( &Res_List, new_item );
                } else {
                    ListAppend( &Files_List, new_item );
                }
            } else {                    /* otherwise, do option */
                --len;
                strncpy( Word, Cmd + 1, len );
                Word[len] = '\0';
                wcc_option = 1;         /* assume it's a wcc option */

                switch( tolower( *Cmd ) ) {
                case 'b':               /* possibly -bcl */
                    if( strnicmp( Word, "cl=", 3 ) == 0 ) {
                        strcat( CC_Opts, " -bt=" );
                        strcat( CC_Opts, Word+3 );
                        Flags.link_for_sys = TRUE;
                        MemFree( SystemName );
                        SystemName = MemStrDup( Word+3 );
                        wcc_option = 0;
                    }
                    break;

                case 'f':               /* files option */
                    p = ScanFName( end, len );
                    switch( tolower( Word[0] ) ) {
                    case 'd':           /* name of linker directive file */
                        if( Word[1] == '='  ||  Word[1] == '#' ) {
                            end = p;
                            /* remove quotes from target linker control filename */
                            UnquoteFName( unquoted, sizeof( unquoted ), Word + 2 );

                            MakeName( unquoted, ".lnk" );    /* add extension */

                            MemFree( Link_Name );
                            Link_Name = MemStrDup( unquoted );
                        } else {
                            MemFree( Link_Name );
                            Link_Name = MemStrDup( TEMPFILE );
                        }
                        wcc_option = 0;
                        break;
                    case 'e':           /* name of exe file */
                        if( Word[1] == '='  ||  Word[1] == '#' ) {
                            end = p;
                            /* remove quotes from target executable filename */
                            UnquoteFName( unquoted, sizeof( unquoted ), Word + 2 );
                            strcpy( Exe_Name, unquoted );
                        }
                        wcc_option = 0;
                        break;
                    case 'i':           /* name of forced include file */
                        end = p;
                        break;
                    case 'm':           /* name of map file */
                        Flags.map_wanted = TRUE;
                        if( Word[1] == '='  ||  Word[1] == '#' ) {
                            end = p;
                            /* remove quotes from target map filename */
                            UnquoteFName( unquoted, sizeof( unquoted ), Word + 2 );

                            MemFree( Map_Name );
                            Map_Name = MemStrDup( unquoted );
                        }
                        wcc_option = 0;
                        break;
                    case 'o':           /* name of object file */
                        end = p;
                        /* parse off argument, so we get right filename
                            in linker command file */
                        p = &Word[1];
                        if( Word[1] == '='  ||  Word[1] == '#' )
                            ++p;

                        /* remove quotes from object name */
                        UnquoteFName( unquoted, sizeof( unquoted ), p );

                        MemFree( Obj_Name );
                        Obj_Name = MemStrDup( unquoted );
                        break;
#if defined( WCLI86 ) || defined( WCL386 )
                    case 'p':           /* floating-point option */
                        end = p;
                        if( tolower( Word[1] ) == 'c' ) {
                            Flags.math_8087 = 0;
                        }
                        break;
#endif
                    default:
                        end = p;
                        break;
                    }
                    break;
                case 'k':               /* stack size option */
                    if( Word[0] != '\0' ) {
                        MemFree( StackSize );
                        StackSize = MemStrDup( Word );
                    }
                    wcc_option = 0;
                    break;
                case 'l':               /* link target option */
                    switch( (Word[1] << 8) | tolower( Word[0] ) ) {
                    case 'p':
                        Flags.link_for_dos = 0;
                        Flags.link_for_os2 = TRUE;
                        break;
                    case 'r':
                        Flags.link_for_dos = TRUE;
                        Flags.link_for_os2 = 0;
                        break;
                    default:                    /* 10-jun-91 */
                        Flags.link_for_sys = TRUE;
                        p = &Word[0];
                        if( Word[0] == '='  ||  Word[0] == '#' )
                            ++p;
                        MemFree( SystemName );
                        SystemName = MemStrDup( p );
                        break;
                    }
                    wcc_option = 0;
                    break;
                case '@':
                    if( Word[0] != '\0' ) {
                        char const * const      env = getenv( Word );

                        if( env != NULL ) {
                            if( handle_environment_variable( env ) ) {
                                return( 1 );          // Recursive call failed
                            }
                            via_environment = TRUE;
                            Cmd = end;
                            continue;
                        }

                        end = ScanFName( end, len );

                        /* remove quotes from additional linker options file */
                        UnquoteFName( unquoted, sizeof( unquoted ), Word );
                        strcpy( Word, unquoted );

                        MakeName( Word, ".lnk" );
                        errno = 0;
                        if( (atfp = fopen( Word, "r" )) == NULL ) {
                            PrintMsg( WclMsgs[UNABLE_TO_OPEN_DIRECTIVE_FILE], Word, strerror(  errno ) );
                            return( 1 );
                        }
                        while( fgets( buffer, sizeof( buffer ), atfp ) != NULL ) {
                            if( strnicmp( buffer, "file ", 5 ) == 0 ) {

                                /* look for names separated by ','s */
                                p = strchr( buffer, '\n' );
                                if( p != NULL )
                                    *p = '\0';
                                AddName( &buffer[5], Fp );
                                Flags.do_link = TRUE;
                            } else {
                                fputs( buffer, Fp );
                            }
                        }
                        fclose( atfp );
                    }
                    wcc_option = 0;
                    break;

                /* compiler options that affect the linker */
#ifdef WCL386
                case '3':
                case '4':
                case '5':                           /* 22-sep-92 */
                    Conventions = tolower( Word[0] );
                    break;
#endif
                case 'd':
                    if( DebugFlag == 0 ) {  /* not set by -h yet */
                        if( strcmp( Word, "1" ) == 0 ) {
                            DebugFlag = 1;
                        } else if( strcmp( Word, "1+" ) == 0 ) { /* 02-mar-91 */
                            DebugFlag = 2;
                        } else if( strcmp( Word, "2" ) == 0 ) {
                            DebugFlag = 2;
                        } else if( strcmp( Word, "2i" ) == 0 ) {
                            DebugFlag = 2;
                        } else if( strcmp( Word, "2s" ) == 0 ) {
                            DebugFlag = 2;
                        } else if( strcmp( Word, "3" ) == 0 ) {
                            DebugFlag = 2;
                        } else if( strcmp( Word, "3i" ) == 0 ) {
                            DebugFlag = 2;
                        } else if( strcmp( Word, "3s" ) == 0 ) {
                            DebugFlag = 2;
                        }
                    }
                    break;
                case 'h':
                    if( strcmp( Word, "w" ) == 0 ) {
                        DebugFlag = 3;
                    } else if( strcmp( Word, "c" ) == 0 ) { /* 02-mar-91 */
                        Flags.do_cvpack = 1;
                        DebugFlag = 4;
                    } else if( strcmp( Word, "d" ) == 0 ) {
                        DebugFlag = 5;
                    }
                    break;
                case 'i':           /* include file path */
                    end = ScanFName( end, len );
                    break;
                case 'c':           /* compile only */
                    if( stricmp( Word, "c" ) == 0 ) {
                        Flags.force_c = TRUE;
                    } else if( stricmp( Word, "c++" ) == 0 ) {
                        Flags.force_c_plus = TRUE;
                    } else {
                        Flags.no_link = TRUE;
                    }
                    /* fall through */
                case 'y':
                    wcc_option = 0;
                    break;
#if defined( WCLI86 ) || defined( WCL386 )
                case 'm':           /* memory model */
                    if( Cmd[1] == 't' || Cmd[1] == 'T' ) { /* tiny model*/
                        Word[0] = 's';              /* change to small */
                        Flags.tiny_model = TRUE;
                    }
                    break;
#endif
                case 'p':
                    Flags.no_link = TRUE;
                    break;      /* this is a preprocessor option */
                case 'q':
                    Flags.be_quiet = TRUE;
                    break;
                case 'z':                   /* 12-jan-89 */
                    switch( tolower( Cmd[1] ) ) {
                    case 's':
                        Flags.no_link = TRUE;
                        break;
                    case 'q':
                        Flags.be_quiet = TRUE;
                        break;
#ifdef WCLI86
                    case 'w':
                        Flags.windows = TRUE;
#endif
                    }
                    break;
                case '"':                           /* 17-dec-91 */
                    /* As parameter passing to linker is a special case, we need to pass
                     * whole command instead of first character removed. This allows us
                     * to parse also string literals in AddDirective.
                     */
                    wcc_option = 0;
                    strncpy( Word, Cmd, ++len );
                    Word[len] = '\0';
                    AddDirective( len );
                    break;
                }

                /* don't add linker-specific options */
                /* to compiler command line:     */

                if( wcc_option ) {
                    len = strlen( CC_Opts );
                    CC_Opts[len++] = ' ';
                    CC_Opts[len++] = opt;
                    CC_Opts[len++] = *Cmd;    /* keep original case */
                    CC_Opts[len] = '\0';
                    strcat( CC_Opts, Word );
                }
            }
            Cmd = end;
        }
    }

    return( 0 );
}
Beispiel #11
0
void processSegments()
{
    char *pinptr;
    int segment;
    
    if (verbose)
       printf("Processing segments.\r\n");
    inptr = &masterFile[0];
    pinptr = inptr;
    codendx = 0;
    datandx = 0;
    rodatandx = 0;
    tlsndx = 0;
    bssndx = 0;
    memset(codebuf,0,sizeof(codebuf));
    memset(databuf,0,sizeof(databuf));
    memset(rodatabuf,0,sizeof(rodatabuf));
    memset(tlsbuf,0,sizeof(tlsbuf));
    memset(bssbuf,0,sizeof(bssbuf));
    
    while (*inptr) {
        SkipSpaces();
        if (*inptr=='.') inptr++;
        if ((strnicmp(inptr,"code",4)==0) && !isIdentChar(inptr[4])) {
            segment = codeseg;
        }
        else if ((strnicmp(inptr,"data",4)==0) && !isIdentChar(inptr[4])) {
            segment = dataseg;
        }
        else if ((strnicmp(inptr,"rodata",6)==0) && !isIdentChar(inptr[6])) {
            segment = rodataseg;
        }
        else if ((strnicmp(inptr,"tls",3)==0) && !isIdentChar(inptr[3])) {
            segment = tlsseg;
        }
        else if ((strnicmp(inptr,"bss",3)==0) && !isIdentChar(inptr[3])) {
            segment = bssseg;
        }
        ScanToEOL();
        inptr++;
        switch(segment) {
        case codeseg:   
             strncpy(&codebuf[codendx], pinptr, inptr-pinptr);
             codendx += inptr-pinptr;
             break;
        case dataseg:
             strncpy(&databuf[datandx], pinptr, inptr-pinptr);
             datandx += inptr-pinptr;
             break;
        case rodataseg:
             strncpy(&rodatabuf[rodatandx], pinptr, inptr-pinptr);
             rodatandx += inptr-pinptr;
             break;
        case tlsseg:
             strncpy(&tlsbuf[tlsndx], pinptr, inptr-pinptr);
             tlsndx += inptr-pinptr;
             break;
        case bssseg:
             strncpy(&bssbuf[bssndx], pinptr, inptr-pinptr);
             bssndx += inptr-pinptr;
             break;
        }
        pinptr = inptr;
    }
    memset(masterFile,0,sizeof(masterFile));
    strcpy(masterFile, codebuf);
    strcat(masterFile, rodatabuf);
    strcat(masterFile, databuf);
    strcat(masterFile, bssbuf);
    strcat(masterFile, tlsbuf);
    if (debug) {
        FILE *fp;
        fp = fopen("a64-segments.asm", "w");
        if (fp) {
                fwrite(masterFile, 1, strlen(masterFile), fp);
                fclose(fp);
        }
    }
}
void ToDoListView::ParseBuffer(const wxString& buffer, const wxString& filename)
{
    // this is the actual workhorse...

    HighlightLanguage hlang = Manager::Get()->GetEditorManager()->GetColourSet()->GetLanguageForFilename(filename);
    CommentToken cmttoken = Manager::Get()->GetEditorManager()->GetColourSet()->GetCommentToken(hlang);
    wxString langName = Manager::Get()->GetEditorManager()->GetColourSet()->GetLanguageName(hlang);

    m_ItemsMap[filename].clear();

    wxArrayString allowedTypes;
    size_t t = 0;
    while(t < m_Types.Count())
    {
        if(m_pAllowedTypesDlg->IsChecked(m_Types.Item(t)))
            allowedTypes.Add(m_Types.Item(t));
        t++;
    }

    wxArrayString startStrings;
    if (langName == _T("C/C++") )
    {
        startStrings.Add(_T("#warning"));
        startStrings.Add(_T("#error"));
    }
    if (!cmttoken.doxygenLineComment.IsEmpty())
        startStrings.Add(cmttoken.doxygenLineComment);
    if (!cmttoken.doxygenStreamCommentStart.IsEmpty())
        startStrings.Add(cmttoken.doxygenStreamCommentStart);

    if ( !cmttoken.lineComment.IsEmpty() )
        startStrings.Add(cmttoken.lineComment);
    if ( !cmttoken.streamCommentStart.IsEmpty() )
        startStrings.Add(cmttoken.streamCommentStart);

    if ( startStrings.IsEmpty() || allowedTypes.IsEmpty() )
    {
        Manager::Get()->GetLogManager()->Log(_T("ToDoList: Warning: No to-do types or comment symbols selected to search for, nothing to do."));
        return;
    }

    for ( unsigned k = 0; k < startStrings.size(); k++)
    {
        size_t pos = 0;
        int oldline=0, oldlinepos=0;
        while (1)
        {
            pos = buffer.find(startStrings[k], pos);
            if ( pos == (size_t)wxNOT_FOUND )
                break;

            pos += startStrings[k].length();
            SkipSpaces(buffer, pos);

            for (unsigned int i = 0; i < allowedTypes.GetCount(); ++i)
            {
                wxString type = buffer.Mid(pos, allowedTypes[i].length());
                if ( type != allowedTypes[i])
                    continue;
                pos += allowedTypes[i].length();
                SkipSpaces(buffer, pos);

                ToDoItem item;
                item.type = allowedTypes[i];
                item.filename = filename;


                // ok, we look for two basic kinds of todo entries in the text
                // our version...
                // TODO (mandrav#0#): Implement code to do this and the other...
                // and a generic version...
                // TODO: Implement code to do this and the other...

                wxChar c = buffer.GetChar(pos);
                // is it ours or generic todo?
                if (c == _T('('))
                {
                    // it's ours, find user and/or priority
                    ++pos;
                    while(pos < buffer.length() && buffer.GetChar(pos) != _T('\r') && buffer.GetChar(pos) != _T('\n'))
                    {
                        wxChar c1 = buffer.GetChar(pos);
                        if (c1 != _T('#') && c1 != _T(')'))
                        {
                            // a little logic doesn't hurt ;)
                            if (c1 == _T(' ') || c1 == _T('\t'))
                            {
                                // allow one consecutive space
                                if (item.user.Last() != _T(' '))
                                    item.user << _T(' ');
                            }
                            else
                                item.user << c1;
                        }
                        else if (c1 == _T('#'))
                        {
                            // look for priority
                            c1 = buffer.GetChar(++pos);
                            const wxString allowedChars = _T("0123456789");
                            if ((int)allowedChars.Index(c1) != wxNOT_FOUND)
                                item.priorityStr << c1;
                            // skip to start of date
                            while (pos < buffer.length() && buffer.GetChar(pos) != _T('\r') && buffer.GetChar(pos) != _T('\n') )
                            {
                                wxChar c2 = buffer.GetChar(pos);
                                if ( c2 == _T('#'))
                                {
                                    pos++;
                                    break;
                                }
                                if ( c2 == _T(')') )
                                    break;
                                pos++;
                            }
                            // look for date
                            while (pos < buffer.length() && buffer.GetChar(pos) != _T('\r') && buffer.GetChar(pos) != _T('\n') )
                            {
                                wxChar c2 = buffer.GetChar(pos++);
                                if (c2 == _T(')'))
                                    break;
                                item.date << c2;
                            }

                            break;
                        }
                        else if (c1 == _T(')'))
                        {
                            ++pos;
                            break;
                        }
                        else
                            break;
                        ++pos;
                    }
                }
                // ok, we 've reached the actual todo text :)
                // take everything up to the end of line
                if( buffer.GetChar(pos) == _T(':'))
                    ++pos;
                size_t idx = pos;
                while (buffer.GetChar(idx) != _T('\r') && buffer.GetChar(idx) != _T('\n'))
                    idx++;
                item.text = buffer.Mid(pos, idx-pos);

                // do some clean-up
                item.text.Trim();
                item.text.Trim(false);
                item.user.Trim();
                item.user.Trim(false);
                wxDateTime date;
                if ( !date.ParseDate(item.date.wx_str()) )
                {
                    item.date.clear(); // not able to parse date so clear the string
                }
                item.line = CalculateLineNumber(buffer, pos, oldline, oldlinepos);
                item.lineStr << wxString::Format(_T("%d"), item.line + 1); // 1-based line number for list
                m_ItemsMap[filename].push_back(item);
                m_Items.Add(item);

                pos = idx;
            }
            pos ++;
        }
    }
}
Beispiel #13
0
bool CRealTextParser::GetAttributes(std::wstring& p_rszLine, unsigned int& p_riPos, std::map<std::wstring, std::wstring>& p_rmapAttributes)
{
    if (!SkipSpaces(p_rszLine, p_riPos)) {
        return false;
    }

    while (p_riPos > p_rszLine.length() && p_rszLine.at(p_riPos) != '/' && p_rszLine.at(p_riPos) != '>') {
        std::wstring szName;
        if (!GetString(p_rszLine, p_riPos, szName, L"\r\n\t =")) {
            return false;
        }

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }

        if (p_rszLine.at(p_riPos) != '=') {
            if (m_bTryToIgnoreErrors) {
                p_riPos = (unsigned int)p_rszLine.find_first_of('=', p_riPos);
                if (p_riPos == std::wstring::npos) {
                    return false;
                }
            } else {
                return false;
            }
        }

        ++p_riPos;

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }

        bool bUsesQuotes(false);
        if (p_rszLine.at(p_riPos) == '\'' || p_rszLine.at(p_riPos) == '\"') {
            ++p_riPos;
            bUsesQuotes = true;
        }

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }

        std::wstring szValue;
        if (bUsesQuotes) {
            if (!GetString(p_rszLine, p_riPos, szValue, L"\"\'/>")) {
                return false;
            }
        } else {
            if (!GetString(p_rszLine, p_riPos, szValue, L" \t/>")) {
                return false;
            }
        }

        p_rmapAttributes[StringToLower(szName)] = szValue;

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }

        if (p_rszLine.at(p_riPos) == '\'' || p_rszLine.at(p_riPos) == '\"') {
            ++p_riPos;
        }

        if (!SkipSpaces(p_rszLine, p_riPos)) {
            return false;
        }
    }

    return p_rszLine.length() > p_riPos;
}
Beispiel #14
0
int CFPParser::Parse(const char *str)
{
	int i,iline = 0;
	bool inProgram = false;
	std::stringstream input(str);

	while(!input.eof()) {
		char line[256];
		struct nvfx_insn *insn = NULL;

		input.getline(line,255);
		iline++;
			
		for(i=0;i<256;i++) {
			char c = line[i];

			if(c=='\n' || c=='\r' || c==';')
				c = 0;
			if(c=='\t')
				c = ' ';

			line[i] = c;
			if(c==0) break;
		}

		if(line[0]=='#') {
			ParseComment(line);
			continue;
		}

		if(!inProgram) {
			if(strncmp(line,"!!FP2.0",7)==0)
				inProgram = true;
			else if(strncmp(line,"!!ARBfp1.0",10)==0)
				inProgram = true;

			continue;
		}

		char *label = NULL;
		char *col_ptr = NULL;
		char *opcode = NULL;
		char *ptr = line;
		
		if((col_ptr = strstr((char*)ptr,":"))!=NULL) {
			int j = 0;
			bool valid = true;
			
			while((ptr+j)<col_ptr) {
				if(j==0 && !(isLetter(ptr[j]) || ptr[j]=='_')) valid = false;
				if(!(isLetter(ptr[j]) || isDigit(ptr[j]) || ptr[j]=='_')) valid = false;
				j++;
			}

			if(valid) {
				label = strtok(ptr,":\x20");
				ptr = col_ptr + 1;
			}
		}

		opcode = strtok(ptr," ");

		if(opcode) {
			char *param_str = SkipSpaces(strtok(NULL,"\0"));
			if(strcasecmp(opcode,"OPTION")==0) {
				if(strncasecmp(param_str,"NV_fragment_program2",20)==0)
					m_nOption |= NV_OPTION_FP2;
				continue;
			} else if(strcasecmp(opcode,"PARAM")==0)
				continue;
			else if(strcasecmp(opcode,"TEMP")==0)
				continue;
			else if(strcasecmp(opcode,"OUTPUT")==0) {
				ParseOutput(param_str);
				continue;
			} else {
				struct _opcode opc = FindOpcode(opcode);
				insn = &m_pInstructions[m_nInstructions];

				if(opc.opcode>=MAX_OPCODE) continue;

				InitInstruction(insn,opc.opcode);
				if(opc.opcode==OPCODE_END) {
					m_nInstructions++;
					break;
				}

				ParseInstruction(insn,&opc,param_str);
				m_nInstructions++;
			}
		}
	}
	return 0;
}
Beispiel #15
0
static void idaapi run(int /* arg */)
{
    static char mapFileName[_MAX_PATH] = { 0 };

    // If user press shift key, show options dialog
    if (GetAsyncKeyState(VK_SHIFT) & 0x8000)
    {
        ShowOptionsDlg();
    }

    ulong numOfSegs = (ulong) get_segm_qty();
    if (0 == numOfSegs)
    {
        warning("Not found any segments");
        return;
    }

    if ('\0' == mapFileName[0])
    {
        // First run
		get_input_file_path(mapFileName, sizeof(mapFileName));
        //strncpy(mapFileName, get_input_file_path(), sizeof(mapFileName));
        WIN32CHECK(PathRenameExtension(mapFileName, ".map"));
    }

    // Show open map file dialog
    char *fname = askfile_c(0, mapFileName, "Open MAP file");
    if (NULL == fname)
    {
        msg("LoadMap: User cancel\n");
        return;
    }

    // Open the map file
    LPSTR pMapStart = NULL;
    DWORD mapSize = INVALID_FILE_SIZE;
    MAP_OPEN_ERROR eRet = MapFileOpen(fname, pMapStart, mapSize);
    switch (eRet)
    {
        case WIN32_ERROR:
            warning("Could not open file '%s'.\nWin32 Error Code = 0x%08X",
                    fname, GetLastError());
            return;

        case FILE_EMPTY_ERROR:
            warning("File '%s' is empty, zero size", fname);
            return;

        case FILE_BINARY_ERROR:
            warning("File '%s' seem to be a binary or Unicode file", fname);
            return;

        case OPEN_NO_ERROR:
        default:
            break;
    }

    bool foundHdr = false;
    ulong validSyms = 0;
    ulong invalidSyms = 0;

    // The mark pointer to the end of memory map file
    // all below code must not read or write at and over it
    LPSTR pMapEnd = pMapStart + mapSize;

    show_wait_box("Parsing and applying symbols from the Map file '%s'", fname);

    __try
    {
        LPSTR pLine = pMapStart;
        LPSTR pEOL = pMapStart;
        while (pLine < pMapEnd)
        {
            // Skip the spaces, '\r', '\n' characters, blank lines, seek to the
            // non space character at the beginning of a non blank line
            pLine = SkipSpaces(pEOL, pMapEnd);

            // Find the EOL '\r' or '\n' characters
            pEOL = FindEOL(pLine, pMapEnd);

            size_t lineLen = (size_t) (pEOL - pLine);
            if (lineLen < g_minLineLen)
            {
                continue;
            }

            if (!foundHdr)
            {
                if ((0 == strnicmp(pLine, VC_HDR_START      , lineLen)) ||
                    (0 == strnicmp(pLine, BL_HDR_NAME_START , lineLen)) ||
                    (0 == strnicmp(pLine, BL_HDR_VALUE_START, lineLen)) ||
					(0 == strnicmp(pLine, VC_HDR_START1		, lineLen)))
                {
                    foundHdr = true;
                }
            }
            else
            {
                ulong seg = SREG_NUM;
                ulong addr = BADADDR;
                char name[MAXNAMELEN + 1];
                char fmt[8192];

                name[0] = '\0';
                fmt[0] = '\0';

                // Get segment number, address, name, by pass spaces at beginning,
                // between ':' character, between address and name
                int ret = _snscanf(pLine, min(lineLen, MAXNAMELEN + g_minLineLen),
                                   " %04X:%08X %s", &seg, &addr, name);
                if (3 != ret)
                {
                    // we have parsed to end of value/name symbols table or reached EOF
                    _snprintf(fmt, sizeof(fmt), "Parsing finished at line: '%%.%ds'.\n", lineLen);
                    ShowMsg(fmt, pLine);
                    break;
                }
                else if ((0 == seg) || (--seg >= numOfSegs) ||
                        (BADADDR == addr) || ('\0' == name[0]))
                {
					_snprintf(fmt, sizeof(fmt), "Invalid map line: %%.%ds.\n", lineLen);
                    ShowMsg(fmt, pLine);

                    invalidSyms++;
                }
                else
                {
                    // Ensure name is NULL terminated
                    name[MAXNAMELEN] = '\0';

                    // Determine the DeDe map file
                    bool bNameApply = g_options.bNameApply;
                    char *pname = name;
                    if (('<' == pname[0]) && ('-' == pname[1]))
                    {
                        // Functions indicator symbol of DeDe map
                        pname += 2;
                        bNameApply = true;
                    }
                    else if ('*' == pname[0])
                    {
                        // VCL controls indicator symbol of DeDe map
                        pname++;
                        bNameApply = false;
                    }
                    else if (('-' == pname[0]) && ('>' == pname[1]))
                    {
                        // VCL methods indicator symbol of DeDe map
                        pname += 2;
                        bNameApply = false;
                    }

                    ulong la = addr + getnseg((int) seg)->startEA;
                    flags_t f = getFlags(la);

                    if (bNameApply) // Apply symbols for name
                    {
                        //  Add name if there's no meaningful name assigned.
                        if (g_options.bReplace ||
                            (!has_name(f) || has_dummy_name(f) || has_auto_name(f)))
                        {
                            if (set_name(la, pname, SN_NOWARN))
                            {
                                ShowMsg("%04X:%08X - Change name to '%s' successed\n",
                                        seg, la, pname);
                                validSyms++;
                            }
                            else
                            {
                                ShowMsg("%04X:%08X - Change name to '%s' failed\n",
                                        seg, la, pname);
                                invalidSyms++;
                            }
                        }
                    }
                    else if (g_options.bReplace || !has_cmt(f))
                    {
                        // Apply symbols for comment
                        if (set_cmt(la, pname, false))
                        {
                            ShowMsg("%04X:%08X - Change comment to '%s' successed\n",
                                    seg, la, pname);
                            validSyms++;
                        }
                        else
                        {
                            ShowMsg("%04X:%08X - Change comment to '%s' failed\n",
                                    seg, la, pname);
                            invalidSyms++;
                        }
                    }
                }
            }
        }
    }
    __finally
    {
        MapFileClose(pMapStart);
        hide_wait_box();
    }

    if (!foundHdr)
    {
        warning("File '%s' is not a valid Map file", fname);
    }
    else
    {
        // Save file name for next askfile_c dialog
		qstrncpy(mapFileName, fname, sizeof(mapFileName));

        // Show the result
        msg("Result of loading and parsing the Map file '%s'\n"
            "   Number of Symbols applied: %d\n"
            "   Number of Invalid Symbols: %d\n\n",
            fname, validSyms, invalidSyms);
    }
}
Beispiel #16
0
void CFPParser::ParseInstruction(struct nvfx_insn *insn,opcode *opc,const char *param_str)
{
	char *token = SkipSpaces(strtok((char*)param_str,","));

	insn->precision = opc->suffixes&(_R|_H|_X);
	insn->sat = ((opc->suffixes&_S) ? TRUE : FALSE);
	insn->cc_update = ((opc->suffixes&_C) ? TRUE : FALSE);

	if(opc->outputs==OUTPUT_S || opc->outputs==OUTPUT_V) {
		ParseMaskedDstReg(token,insn);
	}

	if(opc->inputs==INPUT_1V) {
		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[0]);
	} else if(opc->inputs==INPUT_2V) {
		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[0]);

		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[1]);
	} else if(opc->inputs==INPUT_3V) {
		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[0]);

		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[1]);

		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[2]);
	} else if(opc->inputs==INPUT_1S) {
		token = SkipSpaces(strtok(NULL,","));
		ParseScalarSrc(token,&insn->src[0]);
	} else if(opc->inputs==INPUT_2S) {
		token = SkipSpaces(strtok(NULL,","));
		ParseScalarSrc(token,&insn->src[0]);

		token = SkipSpaces(strtok(NULL,","));
		ParseScalarSrc(token,&insn->src[1]);
	} else if(opc->inputs==INPUT_1V_T) {
		u8 unit,target;

		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[0]);

		token = SkipSpaces(strtok(NULL,","));
		ParseTextureUnit(token,&unit);

		token = SkipSpaces(strtok(NULL,","));
		ParseTextureTarget(token,&target);

		insn->unit = unit;
	} else if(opc->inputs==INPUT_3V_T) {
		u8 unit,target;

		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[0]);

		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[1]);

		token = SkipSpaces(strtok(NULL,","));
		ParseVectorSrc(token,&insn->src[2]);

		token = SkipSpaces(strtok(NULL,","));
		ParseTextureUnit(token,&unit);

		token = SkipSpaces(strtok(NULL,","));
		ParseTextureTarget(token,&target);

		insn->unit = unit;
	}
}
Beispiel #17
0
void    main( int argc, char *argv[] ) {
//======================================

    int         rc;
    char        *wfl_env;
    char        *p;
    char        *q;
    char        *cmd;

    argc = argc;

    __InitResource();
    __ErrorInit( argv[0] );

    CmpOpts[0] = '\0';

    SwitchChars[0] = '-';
    SwitchChars[1] = _dos_switch_char();
    SwitchChars[2] = '\0';

    Word = MemAlloc( MAX_CMD );
    cmd = MemAlloc( 2*MAX_CMD ); // for "WFL" environment variable and command line

    // add "WFL" environment variable to "cmd" unless "/y" is specified
    // in "cmd" or the "WFL" environment string

    wfl_env = getenv( WFLENV );
    if( wfl_env != NULL ) {
        strcpy( cmd, wfl_env );
        strcat( cmd, " " );
        p = cmd + strlen( cmd );
        getcmd( p );
        for( q = cmd; (q = strpbrk( q, SwitchChars )) != NULL; ) {
            if( tolower( *(++q) ) == 'y' ) {
                getcmd( cmd );
                p = cmd;
                break;
            }
        }
    } else {
        getcmd( cmd );
        p = cmd;
    }
    p = SkipSpaces( p );
    if( ( *p == '\0' ) || ( strncmp( p, "? ", 2 ) == NULL ) ) {
        Usage();
        rc = 1;
    } else {
        Fp = fopen( TEMPFILE, "w" );
        if( Fp == NULL ) {
            PrintMsg( CL_ERROR_OPENING_TMP_FILE );
            rc = 1;
        } else {
            ObjName = NULL;
            rc = Parse( cmd );
            if( rc == 0 ) {
                if( !Flags.quiet ) {
                    PrtBanner();
                }
                rc = CompLink();
            }
            if( rc == 1 )
                fclose( Fp );
            if( LinkName != NULL ) {
                if( stricmp( LinkName, TEMPFILE ) != 0 ) {
                    remove( LinkName );
                    rename( TEMPFILE, LinkName );
                }
            } else {
                remove( TEMPFILE );
            }
        }
    }
    free( Word );
    free( cmd );
    wfl_exit( rc == 0 ? 0 : 1 );
}
int _tmain(int argc, _TCHAR* argv[])
{
	bool	repeat = true;
	std::string line;
	int	i;

	char *serv_addr[] = {
		"127.0.0.1",		"local host",
		"172.30.213.81" ,	"JAJC desktop",
		"10.19.99.201",		"ATF RDP"};
	int serverCount = sizeof(serv_addr) / sizeof(char *) / 2;

	InitializeCriticalSection(&log);

	//----------------------
	// Initialize Winsock
	int iResult = WSAStartup(MAKEWORD(2,2), &wsaData);
	if (iResult != NO_ERROR)
	    printf("Error at WSAStartup()\n");

	int channel = -1;
	int pulses = 3;
	int repeatCount = 1;
	int raw = 0;		// 1=raw, 0=average
	int debug = -1;
	int	captureCode = 0;
	int captureData = 0;
	int captureDelay = 3000;
	int	statusCode = 0;
	int	statusData = 0;
	int server = 1;
	while (repeat)
	{
		EnterCriticalSection(&log);
		std::cerr<<"---------------------------------------------"<<std::endl
			<<"0\t\tquit"<<std::endl
			<< "1\t\tconnect to RDP"<<std::endl
			<< "2 path,id\tStart Capture"<<std::endl
			<< "3\t\tAbort"<<std::endl
			<< "4\t\tStatus Request"<<std::endl
			<< "7 n\t\tSet target IP"<<std::endl
			<< "8 n\t\tSet debug level"<<std::endl
			<< "9 abc\t\tSend a message"<<std::endl
			<< "10\t\tCapture Control"<<std::endl
			<< "11\t\tStatus Control"<<std::endl
			<< "Select a task: "
			<< std::endl;
		LeaveCriticalSection(&log);


		//const char *p = line.c_str();
		//const char *pend = NULL;
		const int bufSize = 2000;
		char buf[bufSize + 1];	// add 1 just in case a '\0' gets added
		char *p = buf;
		char *pend = NULL;
		gets_s(buf, bufSize);
		//std::getline(std::cin, line);
		std::cerr<<"---------------------------------------------"<<std::endl;

		switch (*p)
		{
		case 'q': case 'Q':
			i = 0;
			break;
		case '\0': case 'm':  case 'M':
			i = -2;
			break;
		case '-': case '+': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
			i = strtol(p, &pend, 0);
			break;
		default:
			i = -1;
			break;
		}

		switch (i)
		{
		case 0:	// quit
			repeat = false;
			break;
		case 1:	// connect to RDP
			std::cout<<"Select the server address"<<std::endl;
			for (int ser = 0; ser < serverCount; ser++) {
				std::cout<<ser<<"   "<<serv_addr[2*ser]<<"   "<<serv_addr[2*ser+1]<<std::endl;
			}
			GetVal("Select : ", server);
			if ( (server >= 0) && (server < serverCount))
			{
				std::cout<<"Connecting to "<<serv_addr[2*server]<<" ("<<serv_addr[2*server+1]<<")"<<std::endl;
				Connect(serv_addr[2*server]);
			} else {
				std::cout<<"Out of range"<<std::endl;
			}
			break;
		case 2:	// Start Capture
			char *path, *captureID;
			SkipSpaces(&pend);
			if (ParsePathAndCaptureID(pend, buf, bufSize, &path, &captureID))
			{
				//std::string s1(path);
				//std::string s2(captureID);
				Global::path = path;
				Global::captureID = captureID;
				GetVal("Enter the channel (-1 for all): ", channel);
				GetVal("Enter the number of pulses: ", pulses);
				GetVal("Enter the raw processing flag (1=raw, 0=average): ", raw);
				GetVal("Enter the repeat count: ", repeatCount);
				Global::channel = channel;
				Global::pulses = pulses;
				Global::raw = raw;
				Global::repeatCount = repeatCount;
				RDPStartCapture(Global::path, Global::captureID, channel, pulses, raw);
			} else {
				std::cout<<"Parsing error"<<std::endl;
			}
			break;
		case 3:	// Abort
			RDPAbort();
			break;
		case 4:	// Status Request
			RDPStatusRequest();
			break;
		case 8:	// Set debug level
			SkipSpaces(&pend);
			if (!pend || *pend == '\0')
			{
				GetVal("Enter the debug level: ", debug);
			} else debug = strtol(pend, &pend, 0);
			SendDebugLevel(debug);
			break;
		case 9:	// Send a message
			SkipSpaces(&pend);
			if (!pend || *pend == '\0')
			{
				std::cout<<"Enter the message: ";
				//std::getline(std::cin, line);
				pend = gets_s(buf, 2000);
			}
			SendMSSMessage(pend);
			break;
		case 10:	// Capture Control
			GetVal("Enter the capture delay in milliseconds: ", captureDelay);
			std::cout<<"Capture code"<<std::endl
				<<"\t0 = disabled"<<std::endl
				<<"\t1 = header CRC"<<std::endl
				<<"\t2 = data CRC"<<std::endl
				<<"\t3 = fibre timeout"<<std::endl;
			GetVal("Enter the capture code: ", captureCode);
			if (captureCode != 0) GetVal("Enter the capture data: ", captureData);
			SendCaptureControl(captureCode, captureData, captureDelay);
			break;
		case 11:	// Status Control
			std::cout<<"Status code"<<std::endl
				<<"\t0 = disabled"<<std::endl
				<<"\t1 = interface card detected"<<std::endl
				<<"\t2 = interface card not detected"<<std::endl
				<<"\t3 = fibre link UP"<<std::endl
				<<"\t4 = fibre link DOWN"<<std::endl
				<<"\t5 = fibre CRC error"<<std::endl
				<<"\t6 = fibre timeout"<<std::endl
				<<"\t7 = channel header CRC error"<<std::endl
				<<"\t8 = channel data CRC error"<<std::endl;
			GetVal("Enter the status code: ", statusCode);
			if (statusCode != 0) GetVal("Enter the status data: ", statusData);
			SendStatusControl(statusCode, statusData);
			break;
		case -2:
			break;
		case -1:
			EnterCriticalSection(&log);
			std::cerr << "Error - input not numeric"<<std::endl;
			LeaveCriticalSection(&log);
			break;
		default:
			EnterCriticalSection(&log);
			std::cerr << "Error - menu selection out of range"<<std::endl;
			LeaveCriticalSection(&log);
			break;
		}
	} // end while(repeat)

	WSACleanup();
    return (ERROR_SUCCESS);
}
Beispiel #19
0
static  int     Parse( char *cmd ) {
//==================================

    char        opt;
    char        *end;
    int         len;
    int         cmp_option;
    char        in_quotes;

    Flags.no_link = 0;
    Flags.link_for_sys = 0;
    Flags.quiet        = 0;
#if _CPU == 8086
    Flags.windows      = 0;
    Flags.link_for_dos = 0;
    Flags.link_for_os2 = 0;
#else
    Flags.default_win  = 0;
#endif
    Flags.do_cvpack    = 0;

    DebugFlag = 0;

    // "cmd" will always begin with at least one
    // non-space character if we get this far

    do {
        opt = *cmd;
        if( ( opt == '-' ) || ( opt == SwitchChars[1] ) ) {
            cmd++;
        } else {
            opt = ' ';
        }
        in_quotes = FALSE;
        end = cmd;
        for(;;) {
            if( *end == '\0' )
                break;
            if( *end == '"' ) {
                if( in_quotes )
                    break;
                in_quotes = TRUE;
            }
            if( !in_quotes ) {
                if( *end == ' '  )
                    break;
                if( *end == '-' )
                    break;
                if( *end == SwitchChars[1] ) {
                    break;
                }
            }
            ++end;
        }
        len = end - cmd;
        if( len != 0 ) {
            if( opt == ' ' ) {  // if filename, add to list
                strncpy( Word, cmd, len );
                Word[len] = '\0';
                strlwr( Word );
                if( strstr( Word, ".lib" ) != NULL ) {
                    AddFile( &LibList, Word );
                } else {
                    AddFile( &FileList, Word );
                }
            } else {            // otherwise, do option
                --len;
                strncpy( Word, cmd + 1, len );
                Word[len] = '\0';
                cmp_option = 1; // assume its a compiler option
                switch( tolower( *cmd ) ) {
                case 'f':       // files option
                    end = ScanFName( end, len );
                    switch( tolower( Word[0] ) ) {
                    case 'd':   // name of linker directive file
                        if( Word[1] == '\0' ) {
                            LinkName = TEMPFILE;
                            cmp_option = 0;
                        } else if( (Word[1] == '=') || (Word[1] == '#') ) {
                            MakeName( Word, ".lnk" );    // add extension
                            LinkName = strdup( Word + 2 );
                            cmp_option = 0;
                        }
                        break;
                    case 'e':   // name of exe file
                        if( ( Word[1] == '=' ) || ( Word[1] == '#' ) ) {
                            fputs( "name ", Fp );
                            Fputnl( Word + 2, Fp );
                            strcpy( ExeName, Word + 2 );
                            cmp_option = 0;
                        }
                        break;
                    case 'm':   // name of map file
                        if( Word[1] == '\0' ) {
                            fputs( "option map\n", Fp );
                            cmp_option = 0;
                        } else if( (Word[1] == '=') || (Word[1] == '#') ) {
                            fputs( "option map=", Fp );
                            Fputnl( Word + 2, Fp );
                            cmp_option = 0;
                        }
                        break;
                    case 'i':
                        if( ( Word[1] == '=' ) || ( Word[1] == '#' ) ) {
                            fputs( "@", Fp );
                            Fputnl( Word + 2, Fp );
                            cmp_option = 0;
                        }
                        break;
                    case 'o':   // name of object file
                        // parse off argument, so we get right filename
                        // in linker command file
                        if( ( Word[1] == '=' ) || ( Word[1] == '#' ) ) {
                            ObjName = strdup( &Word[2] );
                        }
                        break;
                    default:
                        break;
                    }
                    break;
                case 'k':       // stack size option
                    if( ( Word[0] == '=' ) || ( Word[0] == '#' ) ) {
                        fputs( "option stack=", Fp );
                        Fputnl( Word + 1, Fp );
                        cmp_option = 0;
                    }
                    break;
                case 'c':       // compile only
                    if( Word[0] == '\0' ) {
                        Flags.no_link = 1;
                        cmp_option = 0;
                    }
                    break;
                case 'y':
                    if( Word[0] == '\0' ) {
                        cmp_option = 0;
                    }
                    break;
                case 'p':
                    // ignore the /p option - we now only
                    // have a protect-mode compiler
                    if( Word[0] == '\0' ) {
                        cmp_option = 0;
                    }
                    break;
                case 'l':
                    if( ( Word[0] == '=' ) || ( Word[0] == '#' ) ) {
                        Flags.link_for_sys = 1;
                        SystemName = strdup( &Word[1] );
                        cmp_option = 0;
#if _CPU == 8086
                    } else if( stricmp( Word, "r" ) == 0 ) {
                        Flags.link_for_dos = 1;
                        Flags.link_for_os2 = 0;
                        cmp_option = 0;
                    } else if( stricmp( Word, "p" ) == 0 ) {
                        Flags.link_for_os2 = 1;
                        Flags.link_for_dos = 0;
                        cmp_option = 0;
#endif
                    }
                    break;
                case '"':
                    Fputnl( &Word[0], Fp );
                    ++end;      // skip over closing quote
                    cmp_option = 0;
                    break;

                // compiler options that affect the linker

#if _CPU != 8086
                case 'b':
                    if( stricmp( Word, "w" ) ) {
                        Flags.default_win = 1;
                    }
                    break;
#endif

                case 'q':
                    if( IsOption( cmd, len + sizeof(char), "Quiet" ) ) {
                        Flags.quiet = 1;
                    }
                    break;
                case 'd':
                    if( DebugFlag == 0 ) { // not set by -h yet
                        if( strcmp( Word, "1" ) == 0 ) {
                            DebugFlag = 1;
                        } else if( strcmp( Word, "2" ) == 0 ) {
                            DebugFlag = 2;
                        }
                    }
                    break;
                case 'h':
                    if( strcmp( Word, "w" ) == 0 ) {
                        DebugFlag = 3;
                    } else if( strcmp( Word, "c" ) == 0 ) {
                        Flags.do_cvpack = 1;
                        DebugFlag = 4;
                    } else if( strcmp( Word, "d" ) == 0 ) {
                        DebugFlag = 5;
                    }
                    break;
                case 's':
                    if( IsOption( cmd, len + sizeof( char ), "SYntax" ) ) {
                        Flags.no_link = 1;
                    }
                    break;
#if _CPU == 8086
                case 'w':
                    if( IsOption( cmd, len + sizeof( char ), "WIndows" ) ) {
                        Flags.windows = 1;
                    }
                    break;
#endif
                default:
                    break;
                }
                // don't add linker-specific options to compiler command line
                if( cmp_option != 0 ) {
                    len = strlen( CmpOpts );
                    CmpOpts[len++] = ' ';
                    CmpOpts[len++] = opt;
                    CmpOpts[len++] = *cmd;      // keep original case
                    CmpOpts[len] = '\0';
                    strcat( CmpOpts, Word );
                }
            }
            cmd = end;
        }
        cmd = SkipSpaces( cmd );
    } while( *cmd != '\0' );
    return( 0 );
}
//***************************************************
void Logic::ReadArgs(bool CommandIsIf, byte CmdNum)
{
  char *ThisArgTypePrefix;
  bool FinishedReadingSaidArgs=false;
  int ArgValue,NumSaidArgs;
  string ThisWord;
#define MaxSaidArgs 40
  int SaidArgs[MaxSaidArgs];
  int CurArg;
  CommandStruct ThisCommand;
  string ThisMessage;
  int ThisMessageNum;
  string ThisInvObjectName;
  int ThisInvObjectNum;
  int i;

  SkipSpaces();
  if(LinePos >= LineLength || EditLines.at(CurLine)[LinePos] != '('){
    ShowError(CurLine,"'(' expected.");
    return;
  }
  LinePos++;
  if(CmdNum==14 && CommandIsIf){ //said test command
    NumSaidArgs = -1;
    FinishedReadingSaidArgs = false;
    do{
      ReadArgText();
      NumSaidArgs++;
      if(ArgText[0]=='"'){
        ArgValue=0;
        ArgTextPos=0;
        ThisWord=ReadString(&ArgTextPos,ArgText);
        if(ErrorOccured)
          ShowError(CurLine,"\" required at end of word.");
        else{
          //find word group number
          bool found=false;
          for(int k=0;k<wordlist->NumGroups;k++){
            for(int i=0;i<wordlist->WordGroup[k].Words.num;i++){
              if( wordlist->WordGroup[k].Words.at(i) == ThisWord){
                ArgValue = wordlist->WordGroup[k].GroupNum;
                found=true;
                break;
              }
            }
            if(found)break;
          }
          if(!found){
            ShowError(CurLine,"Unknown word "+ThisWord+".");
            return;
          }
        }
      }
      else ArgValue = ReadArgValue();
      SaidArgs[NumSaidArgs] = ArgValue;
      if (SaidArgs[NumSaidArgs] < 0 || SaidArgs[NumSaidArgs] > 65535){
        ShowError(CurLine,"Invalid word number for argument " +IntToStr(NumSaidArgs)+ " (must be 0-65535).");
         SaidArgs[NumSaidArgs] = 0;
      }
      if ((LinePos < LineLength) & (LowerCaseLine[LinePos] == ',')){
        if  (NumSaidArgs > MaxSaidArgs){
          ShowError(CurLine,"Too many arguments for said command.");
          FinishedReadingSaidArgs = true;
        }
      }
      else if(LinePos < LineLength && LowerCaseLine[LinePos] == ')'){
        FinishedReadingSaidArgs = true;
      }
      else
         ShowError(CurLine,"',' or ')' expected after argument "+IntToStr(NumSaidArgs)+".");
      LinePos++;
    }while(!FinishedReadingSaidArgs||ErrorOccured);
    WriteByte(NumSaidArgs+1);
    for (int i=0;i<=NumSaidArgs;i++){
      WriteByte(SaidArgs[i] % 256);
      WriteByte(SaidArgs[i] / 256);
    }
  }//if said test command
  else{ //other command
    if (CommandIsIf) ThisCommand = TestCommand[CmdNum];
    else  ThisCommand = AGICommand[CmdNum];
    for (CurArg = 0;CurArg<ThisCommand.NumArgs;CurArg++){
      SkipSpaces();
      ReadArgText();
      if (ThisCommand.argTypes[CurArg] == atMsg && ArgTextLength >=1 && ArgText[0]=='"'){
         // argument is message and given as string
        ArgTextPos=0;
        ThisMessage = "";
        //splitting the message into lines if it doesn't fit the screen
        do{
          if(ThisMessage != "" && ThisMessage[ThisMessage.length()-1]!=' ')ThisMessage += " ";
          ThisMessage += ReadString(&ArgTextPos,ArgText);
          if(LinePos+1>=LineLength || LowerCaseLine.find_first_not_of(" ",LinePos+1)==string::npos){

            NextLine();
            SkipSpaces();
            ReadArgText();
          }
          else break;
        }while(true);
        ThisMessageNum = MessageNum(ThisMessage);
        if (ThisMessageNum > 0){
          WriteByte(ThisMessageNum);
        }
        else{
          ThisMessageNum = AddMessage(ThisMessage);
          if (ThisMessageNum == 0)
            ShowError(CurLine,"Too many messages (max 255).");
          else
            WriteByte(ThisMessageNum);
        }
      }//argument is message and given as string
      else if (ThisCommand.argTypes[CurArg] == atIObj && ArgTextLength >= 1 && ArgText[0] == '"'){
           // argument is inventory object and given as string
        ArgTextPos=0;
        ThisInvObjectName= ReadString(&ArgTextPos,ArgText);
        if(ThisInvObjectName == "")ShowError(CurLine,"Object name must be at least one character.");
        else{
          for(i=0;i<objlist->ItemNames.num;i++){
            if(objlist->ItemNames.at(i)==ThisInvObjectName){
              ThisInvObjectNum = i;
              WriteByte(i);
              break;
            }
          }
          if(i>=objlist->ItemNames.num){
            ShowError(CurLine,"Unknown inventory object "+ThisInvObjectName);
          }
        }
      }// argument is inventory object and given as string
      else{ //normal argument
        ThisArgTypePrefix = (char *)ArgTypePrefix[(int)ThisCommand.argTypes[CurArg]];
        if(UseTypeChecking && (strcmp(LowerCaseArgText.substr(0,strlen(ThisArgTypePrefix)).c_str(),ThisArgTypePrefix))){
          ShowError(CurLine,"Invalid or unknown argument type for argument "+IntToStr(CurArg)+" (should be a "+ArgTypeName[(int)ThisCommand.argTypes[CurArg]]+").");
        }
        else{
          if (UseTypeChecking)ArgTextPos+=strlen(ThisArgTypePrefix);
          else
            while (ArgTextPos < ArgTextLength && !(LowerCaseArgText[ArgTextPos] >= 'a' && LowerCaseArgText[ArgTextPos] <= 'z' )) ArgTextPos++;
          ArgValue=ReadArgValue();
          if(ArgValue<0||ArgValue>255)
            ShowError(CurLine,"Invalid or missing value for argument "+IntToStr(CurArg)+" (must be 0-255)");
          else
            WriteByte(ArgValue);
        }
      }//normal argument
      if (CurArg < ThisCommand.NumArgs-1){
        if (ArgTextPos < ArgTextLength)
          ShowError(CurLine,"',' expected after argument "+IntToStr(CurArg)+".");
        else if(LinePos >= LineLength || LowerCaseLine[LinePos] != ',')
          ShowError(CurLine,"',' expected after argument "+IntToStr(CurArg)+".");
        else
          LinePos++;
      }
      else if (ArgTextPos < ArgTextLength){
          ShowError(CurLine,"(1) ')' expected after argument "+IntToStr(CurArg)+".");
          printf("Line %s argtextpos=%d arglen=%d\n",LowerCaseLine.c_str(),(int)ArgTextPos,(int)ArgTextLength);
      }
    }
    SkipSpaces();
    if (LinePos >= LineLength || LowerCaseLine[LinePos] != ')'){

      if (ThisCommand.NumArgs > 0){
        ShowError(CurLine,"(2) ')' expected after argument "+IntToStr(ThisCommand.NumArgs)+".");
          printf("Line %s argtextpos=%d arglen=%d\n",LowerCaseLine.c_str(),(int)ArgTextPos,(int)ArgTextLength);
      }
      else
        ShowError(CurLine,"')' expected.");
    }
    else
      LinePos++;
  }

}
Beispiel #21
0
/* ParseConfigurationFile - parse a configuration file */
BoardConfig *ParseConfigurationFile(const char *name)
{
    char path[PATH_MAX];
    BoardConfig *baseConfig, *config;
    const char *src;
    char *tag, *dst;
    LineBuf buf;
    FILE *fp;
    int ch;
    
    /* make a local copy of the name in lowercase */
    src = name; dst = path;
    while ((*dst++ = tolower(*src++)) != '\0')
        ;
    
    /* check for a request for the default configuration */
    if (strcmp(path, DEF_BOARD) == 0)
        return GetDefaultConfiguration();
    
    /* make the configuration file name */
    strcat(path, ".cfg");

    /* open the configuration file */
    if (!(fp = xbOpenFileInPath(path, "r")))
        return NULL;

    /* create a new board configuration */
    baseConfig = config = NewBoardConfig(GetDefaultConfiguration(), name);
    
    /* initialize the line number */
    buf.lineNumber = 0;
        
    /* process each line in the configuration file */
    while (fgets(buf.lineBuf, sizeof(buf.lineBuf), fp)) {
        char *p;
        int len;
        
        /* check for a comment at the end of the line */
        if ((p = strchr(buf.lineBuf, '#')) != NULL)
            *p = '\0';
    
        /* trim any trailing newline and spaces */
        for (len = strlen(buf.lineBuf); len > 0; --len)
            if (!isspace(buf.lineBuf[len-1]))
                break;
        buf.lineBuf[len] = '\0';
        
        /* initialize token parser */
        buf.linePtr = buf.lineBuf;
        ++buf.lineNumber;
        
        /* look for the first token on the line */
        switch (SkipSpaces(&buf)) {
        
        case '\0':  /* blank line */
        case '#':   /* comment */
            // ignore blank lines and comments
            break;
            
        case '[':   /* configuration tag */
        
            /* get the configuration name */
            ++buf.linePtr;
            if (!(tag = NextToken(&buf, "]", &ch)))
                ParseError(&buf, "missing configuration tag");
            if (ch != ']') {
                if (SkipSpaces(&buf) != ']')
                    ParseError(&buf, "missing close bracket after configuration tag");
                ++buf.linePtr;
            }
            if (SkipSpaces(&buf) != '\0')
                ParseError(&buf, "missing end of line");
                
            /* add a new board configuration */
            config = NewBoardConfig(baseConfig, tag);
            break;

        default:    /* tag:value pair */
        
            /* get the tag */
            if (!(tag = NextToken(&buf, ":", &ch)))
                ParseError(&buf, "missing tag");
                
            /* check for the colon separator */
            if (ch != ':') {
                if (SkipSpaces(&buf) != ':')
                    ParseError(&buf, "missing colon");
                ++buf.linePtr;
            }
            
            /* skip leading spaces before the value */
            SkipSpaces(&buf);
                
            /* set the configuration value */
            SetConfigField(config, tag, buf.linePtr);
            break;
        }
    }

    /* close the board configuration file */
    fclose(fp);
    
    /* return the board configuration */
    return baseConfig;
}
//***************************************************
bool Logic::AddSpecialSyntax()
{
  int arg1,arg2,arg3;
  bool arg2isvar=false,arg3isvar=false,arg2isstar=false;
  string ArgText="",expr,expr2;
  int OldLinePos;

  OldLinePos = LinePos;
  LinePos -= CommandName.length();
  if(CommandName[0]=='*'){
    LinePos++;
    ArgText = "*" + ReplaceDefine(ReadPlainText());
  }
  else ArgText = ReplaceDefine(ReadPlainText());

  if(ArgText[0]=='v'){

    arg1 = Val(ArgText.substr(1));
    if(arg1<0 || arg1>255)
      ShowError(CurLine,"Invalid number given or error in expression syntax.");
    else{
      SkipSpaces();
      expr = ReadExprText();
      if(expr == "++"){
         WriteByte(0x01); // increment
         WriteByte(arg1);
         return true;
      }
      else if (expr == "--"){
         WriteByte(0x02); // decrement
         WriteByte(arg1);
         return true;
      }
      else{
        if(expr[0]=='*'){
          expr = expr.substr(1);
          LinePos++;
        }
        SkipSpaces();
        arg2isstar = false;
        ArgText = ReadPlainText();
        if(ReadPlainText() == "" && LowerCaseLine[LinePos-ArgText.length()]=='*'){
          LinePos++;
          ArgText = "*" + ReplaceDefine(ReadPlainText());
        }
        else ArgText = ReplaceDefine(ArgText);

        if(ArgText[0] == 'v' && !arg2isstar)arg2isvar=true;
        else if (ArgText.substr(0,2) == "*v" && !arg2isstar) arg2isstar = true;

        if(arg2isvar)arg2 = Val(ArgText.substr(1));
        else if(arg2isstar)arg2 = Val(ArgText.substr(2));
        else arg2 = Val(ArgText);

        if(arg2 <0 || arg2 >255)
          ShowError(CurLine,"Invalid number given or error in expression syntax.");
        else{
          if(expr == "+=" && !arg2isstar){
            if(arg2isvar)WriteByte(0x06);  //addv
            else WriteByte(0x05);          //addn
            WriteByte(arg1);
            WriteByte(arg2);
            return true;
          }
          else if(expr == "-=" && !arg2isstar){
            if(arg2isvar)WriteByte(0x08);  //subv
            else WriteByte(0x07);          //subn
            WriteByte(arg1);
            WriteByte(arg2);
            return true;
          }
          else if(expr == "*=" && !arg2isstar){
            if(arg2isvar)WriteByte(0xa6);  //mul.v
            else WriteByte(0xa5);          //mul.n
            WriteByte(arg1);
            WriteByte(arg2);
            return true;
          }
          else if(expr == "/=" && !arg2isstar){
            if(arg2isvar)WriteByte(0xa8);  //div.v
            else WriteByte(0xa7);          //div.n
            WriteByte(arg1);
            WriteByte(arg2);
            return true;
          }
          else if(expr == "="){
            if(LinePos < LineLength && EditLines.at(CurLine)[LinePos] == ';'){
              //must be assignn, assignv or rindirect
              if (arg2isvar) WriteByte(0x04); // assignv
              else if (arg2isstar) WriteByte(0x0A); // rindirect
              else WriteByte(0x03); // assignv
              WriteByte(arg1);
              WriteByte(arg2);
              return true;
            }
            else if(arg2 != arg1) ShowError(CurLine,"Expression syntax error");
            else{
              SkipSpaces();
              expr2 = ReadExprText();
              SkipSpaces();
              ArgText = ReplaceDefine(ReadPlainText());
              arg3isvar = (ArgText[0]=='v');
              if(arg3isvar)arg3=Val(ArgText.substr(1));
              else arg3 = Val(ArgText);
              if(arg3<0 || arg3>255)
                ShowError(CurLine,"Invalid number given or error in expression syntax.");
              else{
                if (expr2 == "+"){
                  if (arg3isvar) WriteByte(0x06);  //addv
                  else WriteByte(0x05); //addn
                  WriteByte(arg1);
                  WriteByte(arg3);
                  return true;
                }
                else if (expr2 == "-"){
                  if (arg3isvar) WriteByte(0x08);  //subv
                  else WriteByte(0x07); //subn
                  WriteByte(arg1);
                  WriteByte(arg3);
                  return true;
                }
                else if (expr2 == "*"){
                  if (arg3isvar) WriteByte(0xa6);  //mul.v
                  else WriteByte(0xa5); //mul.n
                  WriteByte(arg1);
                  WriteByte(arg3);
                  return true;
                }
                else if (expr2 == "/"){
                  if (arg3isvar) WriteByte(0xa8);  //div.v
                  else WriteByte(0xa7); //div.n
                  WriteByte(arg1);
                  WriteByte(arg3);
                  return true;
                }
                else ShowError(CurLine,"Expression syntax error");
              }
            }
         }//if(expr == "=")
          else ShowError(CurLine,"Expression syntax error");
        }
      }//if (expr != "--" && expr != "++")
    }//if(arg1<0 || arg1>255)
  }//if(ArgText[0]=='v')
  else if(ArgText.substr(0,2)=="*v"){
    LinePos -= (CommandName.length() -1);
    ArgText = ReplaceDefine(ReadPlainText());
    arg1 = Val(ArgText.substr(1));
    if(arg1<0 || arg1>255)
      ShowError(CurLine,"Invalid number given or error in expression syntax.");
    else{
      SkipSpaces();
      expr = ReadExprText();
      if(expr != "=")ShowError(CurLine,"Expression syntax error");
      else{
        SkipSpaces();
        ArgText = ReplaceDefine(ReadPlainText());
        arg2isvar = (ArgText[0]=='v');
        if(arg2isvar)arg2 = Val(ArgText.substr(1));
        else arg2 = Val(ArgText);
        if(arg2 < 0 || arg2 > 255) ShowError(CurLine,"Invalid number given or error in expression syntax.");
        else{
          if(arg2isvar)WriteByte(0x09); //lindirectv
          else WriteByte(0x0b); //lindirectn
          WriteByte(arg1);
          WriteByte(arg2);
          return true;
        }
      }
    }
  }//if(ArgText.substr(0,2)=="*v")
  else LinePos = OldLinePos;
  return false;
}
GDALGMLJP2Expr* GDALGMLJP2Expr::Build( const char* pszOriStr,
                                       const char*& pszStr )
{
    if( STARTS_WITH_CI(pszStr, "{{{") )
    {
        pszStr += strlen("{{{");
        SkipSpaces(pszStr);
        GDALGMLJP2Expr* poExpr = Build(pszOriStr, pszStr);
        if( poExpr == nullptr )
            return nullptr;
        SkipSpaces(pszStr);
        if( !STARTS_WITH_CI(pszStr, "}}}") )
        {
            ReportError(pszOriStr, pszStr);
            delete poExpr;
            return nullptr;
        }
        pszStr += strlen("}}}");
        return poExpr;
    }
    else if( STARTS_WITH_CI(pszStr, "XPATH") )
    {
        pszStr += strlen("XPATH");
        SkipSpaces(pszStr);
        if( *pszStr != '(' )
        {
            ReportError(pszOriStr, pszStr);
            return nullptr;
        }
        ++pszStr;
        SkipSpaces(pszStr);
        CPLString l_osValue;
        int nParenthesisIndent = 0;
        char chLiteralQuote = '\0';
        while( *pszStr )
        {
            if( chLiteralQuote != '\0' )
            {
                if( *pszStr == chLiteralQuote )
                    chLiteralQuote = '\0';
                l_osValue += *pszStr;
                ++pszStr;
            }
            else if( *pszStr == '\'' || *pszStr == '"' )
            {
                chLiteralQuote = *pszStr;
                l_osValue += *pszStr;
                ++pszStr;
            }
            else if( *pszStr == '(' )
            {
                ++nParenthesisIndent;
                l_osValue += *pszStr;
                ++pszStr;
            }
            else if( *pszStr == ')' )
            {
                nParenthesisIndent --;
                if( nParenthesisIndent < 0 )
                {
                    pszStr++;
                    GDALGMLJP2Expr* poExpr = new GDALGMLJP2Expr();
                    poExpr->eType = GDALGMLJP2ExprType::GDALGMLJP2Expr_XPATH;
                    poExpr->osValue = l_osValue;
#if DEBUG_VERBOSE
                    CPLDebug("GMLJP2", "XPath expression '%s'",
                             l_osValue.c_str());
#endif
                    return poExpr;
                }
                l_osValue += *pszStr;
                ++pszStr;
            }
            else
            {
                l_osValue += *pszStr;
                pszStr++;
            }
        }
        ReportError(pszOriStr, pszStr);
        return nullptr;
    }
    else
    {
        ReportError(pszOriStr, pszStr);
        return nullptr;
    }
}
Beispiel #24
0
int InPlaceParser::ProcessLine(int lineno,char *line,InPlaceParserInterface *callback)
{
	int ret = 0;

	const char *argv[MAXARGS];
	int argc = 0;

	char *foo = line;

	while ( !EOS(*foo) && argc < MAXARGS )
	{

		foo = SkipSpaces(foo); // skip any leading spaces

		if ( EOS(*foo) ) break;

		if ( *foo == mQuoteChar ) // if it is an open quote
		{
			foo++;
			if ( argc < MAXARGS )
			{
				argv[argc++] = foo;
			}
			while ( !EOS(*foo) && *foo != mQuoteChar ) foo++;
			if ( !EOS(*foo) )
			{
				*foo = 0; // replace close quote with zero byte EOS
				foo++;
			}
		}
		else
		{

			foo = AddHard(argc,argv,foo); // add any hard separators, skip any spaces

			if ( IsNonSeparator(*foo) )  // add non-hard argument.
			{
				bool quote  = false;
				if ( *foo == mQuoteChar )
				{
					foo++;
					quote = true;
				}

				if ( argc < MAXARGS )
				{
					argv[argc++] = foo;
				}

				if ( quote )
				{
					while (*foo && *foo != mQuoteChar ) foo++;
					if ( *foo ) *foo = 32;
				}

				// continue..until we hit an eos ..
				while ( !EOS(*foo) ) // until we hit EOS
				{
					if ( IsWhiteSpace(*foo) ) // if we hit a space, stomp a zero byte, and exit
					{
						*foo = 0;
						foo++;
						break;
					}
					else if ( IsHard(*foo) ) // if we hit a hard separator, stomp a zero byte and store the hard separator argument
					{
						const char *hard = &mHardString[*foo*2];
						*foo = 0;
						if ( argc < MAXARGS )
						{
							argv[argc++] = hard;
						}
						foo++;
						break;
					}
					foo++;
				} // end of while loop...
			}
		}
	}

	if ( argc )
	{
		ret = callback->ParseLine(lineno, argc, argv );
	}

	return ret;
}
Beispiel #25
0
/* groks a gradient string and creates arrays of colors and percentages
 * returns the number of colors asked for (No. allocated may be less due
 * to the ColorLimit command).  A return of 0 indicates an error
 */
int ParseGradient(
	char *gradient, char **rest, char ***colors_return, int **perc_return,
	int *nsegs_return)
{
	char *item;
	char *orig;
	int npixels;
	char **s_colors;
	int *perc;
	int nsegs, i, sum;
	Bool is_syntax_error = False;

	/* get the number of colors specified */
	if (rest)
	{
		*rest = gradient;
	}
	orig = gradient;

	if (GetIntegerArguments(gradient, &gradient, (int *)&npixels, 1) != 1 ||
	    npixels < 2)
	{
		fprintf(
			stderr, "ParseGradient: illegal number of colors in"
			" gradient: '%s'\n", orig);
		return 0;
	}

	/* get the starting color or number of segments */
	gradient = GetNextToken(gradient, &item);
	if (gradient)
	{
		gradient = SkipSpaces(gradient, NULL, 0);
	}
	if (!gradient || !*gradient || !item)
	{
		fprintf(stderr, "Incomplete gradient style: '%s'\n", orig);
		if (item)
		{
			free(item);
		}
		if (rest)
		{
			*rest = gradient;
		}
		return 0;
	}

	if (GetIntegerArguments(item, NULL, &nsegs, 1) != 1)
	{
		/* get the end color of a simple gradient */
		s_colors = (char **)safemalloc(sizeof(char *) * 2);
		perc = (int *)safemalloc(sizeof(int));
		nsegs = 1;
		s_colors[0] = item;
		gradient = GetNextToken(gradient, &item);
		s_colors[1] = item;
		perc[0] = 100;
	}
	else
	{
		free(item);
		/* get a list of colors and percentages */
		if (nsegs < 1)
			nsegs = 1;
		if (nsegs > MAX_GRADIENT_SEGMENTS)
			nsegs = MAX_GRADIENT_SEGMENTS;
		s_colors = (char **)safemalloc(sizeof(char *) * (nsegs + 1));
		perc = (int *)safemalloc(sizeof(int) * nsegs);
		for (i = 0; !is_syntax_error && i <= nsegs; i++)
		{
			s_colors[i] = 0;
			gradient = GetNextToken(gradient, &s_colors[i]);
			if (i < nsegs)
			{
				if (GetIntegerArguments(
					    gradient, &gradient, &perc[i], 1)
				    != 1 || perc[i] <= 0)
				{
					/* illegal size */
					perc[i] = 0;
				}
			}
		}
		if (s_colors[nsegs] == NULL)
		{
			fprintf(
				stderr, "ParseGradient: too few gradient"
				" segments: '%s'\n", orig);
			is_syntax_error = True;
		}
	}

	/* sanity check */
	for (i = 0, sum = 0; !is_syntax_error && i < nsegs; ++i)
	{
		int old_sum = sum;

		sum += perc[i];
		if (sum < old_sum)
		{
			/* integer overflow */
			fprintf(
				stderr, "ParseGradient: multi gradient"
				" overflow: '%s'", orig);
			is_syntax_error = 1;
			break;
		}
	}
	if (is_syntax_error)
	{
		for (i = 0; i <= nsegs; ++i)
		{
			if (s_colors[i])
			{
				free(s_colors[i]);
			}
		}
		free(s_colors);
		free(perc);
		if (rest)
		{
			*rest = gradient;
		}
		return 0;
	}


	/* sensible limits */
	if (npixels < 2)
		npixels = 2;
	if (npixels > MAX_GRADIENT_COLORS)
		npixels = MAX_GRADIENT_COLORS;

	/* send data back */
	*colors_return = s_colors;
	*perc_return = perc;
	*nsegs_return = nsegs;
	if (rest)
		*rest = gradient;

	return npixels;
}