Exemple #1
0
int32_t M2VParser::WriteData(binary* data, uint32_t dataSize){
  //If we are at EOS
  if(m_eos)
    return -1;

  if(mpgBuf->Feed(data, dataSize)){
    return -1;
  }

  //Fill the chunks buffer
  while(mpgBuf->GetState() == MPEG2_BUFFER_STATE_CHUNK_READY){
    MPEGChunk * c = mpgBuf->ReadChunk();
    if(c) chunks.push_back(c);
  }

  if(needInit){
    if(InitParser() == 0)
      needInit = false;
  }

  FillQueues();
  if(buffers.empty()){
    parserState = MPV_PARSER_STATE_NEED_DATA;
  }else{
    parserState = MPV_PARSER_STATE_FRAME;
  }

  return 0;
}
Exemple #2
0
wxObject* wx28HtmlParser::Parse(const wxString& source)
{
    InitParser(source);
    DoParsing();
    wxObject *result = GetProduct();
    DoneParser();
    return result;
}
Exemple #3
0
main(int argc,char **argv)
{
 progname= argv[0];             /*Get the program name */
 inpf= InitParser(argc,argv);
 if (!inpf) exit(1);            /*Abort in case of illegal input file */
 LineSeek(0);                   /*Position on the begin of a file */
 InitSymbols(predef_sym);       /*Create the symbols table */
 yyparse();                     /*Do parsing */
 Main(argc,argv);               /*User applied 'main' program */
 exit(0);
}
NS_IMETHODIMP
nsSAXXMLReader::OnStartRequest(nsIRequest *aRequest, nsISupports *aContext)
{
  NS_ENSURE_TRUE(mIsAsyncParse, NS_ERROR_FAILURE);
  nsresult rv;
  rv = EnsureBaseURI();
  NS_ENSURE_SUCCESS(rv, rv);
  nsCOMPtr<nsIChannel> channel = do_QueryInterface(aRequest);
  rv = InitParser(mParserObserver, channel);
  NS_ENSURE_SUCCESS(rv, rv);
  // we don't need or want this anymore
  mParserObserver = nullptr;
  return mListener->OnStartRequest(aRequest, aContext);
}
Exemple #5
0
int XmlReadBlockWithAttributes(char* fileName,_searchParameters* searchParam,_searchProperty *searchProperty,char *result,U8 resLen)
{
    FILE *fp;
    char ch;
    int status;
//    typedef struct
//{
//    int noOfAttributes; // No of attributes to search.
//    int dataOfAttribute; // Index of the attribute who's data is fetched.
//    XMLResultType resultType; // Type of data (only tag, body and both)
//}attributeProperty;

//    attributeProperty attProperty;
//    attProperty.dataOfAttribute = 2; // Pull data from second search element.
//    attProperty.noOfAttributes = 3; // Totally three search elements are used.
//    attProperty.resultType =XMLDATA_TAG_BODY; // Get tag and body.
//    attributeParam attParam[3];
//
//    attParam[0].block = "<Det ";
//    attParam[0].attribute = "Type=";
//    attParam[0].key = "\"MAS-3B\"";
//
//    attParam[1].block = block;
//    attParam[1].attribute = attribute;
//    attParam[1].key = key;
//
//    attParam[2].block = ;
//    attParam[2].attribute = "Unit=";
//    attParam[2].key = ;

    // Open the file.
    if( (fp=(FILE *)fopen(fileName,"r")) == NULL)
        printf("File not found!\n");
    InitParser();
    do {
        ch = getc(fp);
       status = ExtractXMLData(ch,searchParam,searchProperty,result,resLen);
    } while(ch!=EOF && status == 0);

//    printf("\nBlock: %s\n",block);
//    printf("attribute: %s\n",attribute);
//    printf("key: %s\n",key);
//    printf("result: %s\n",result);
    fclose(fp);
    EndParser();
    return status;
}
Exemple #6
0
/// HIFN Gets all of the exports from the library owned by the parser.
/// HIRET Returns a list containing all of the exports owned by the parser.
/// HIRET This list, and the items in it, should not be disposed.
/// HIPAR parser/The parser from which to get the names of the symbols.
ListType GetExports(SymbolParser *parser) {
    InitParser(parser);
    if (parser->exports) {
        return parser->exports;
    }
    
    PIMAGE_EXPORT_DIRECTORY exports = (BYTE *)parser->module + parser->header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
    void *names = (BYTE *)parser->module + exports->AddressOfNames;
    
    ListType exportedNames = ListCreate(sizeof(char *));
    
    for (int i = 0; i < exports->NumberOfNames; i++) {
        char *name = (char *)(BYTE *)parser->module + ((DWORD *)names)[i];
        ListInsertItem(exportedNames, &name, i);
    }
    
    parser->exports = exportedNames;
    return parser->exports;
}
Exemple #7
0
int main(int argc, char **argv)
{
    char buffer[c_nMaxTextSize];
    ParserContext context(buffer);
    CommandArgs args;

    if (ParseArgs(argc, argv, &args) < 0) return LUBE_FAIL;

    InitParser(&context, args.pszSourcePath);
    DoCompiling(args.pszSource);

    if (0 != g_nErrorNumber) {
        fprintf(stderr, "[INFO] lubc (0x1001) : Aborting compilation.\n");
        exit(g_nErrorNumber);
    }

    if (args.dwAttribs & Command_p_Preview) {
        PreviewResult(context.m_pLube);
    }
    if (args.dwAttribs & Command_o_GenLBO) {
        SaveLube(context.m_pLube, args.pszLBO);
    }
    return LUBE_OK;
}
NS_IMETHODIMP
nsSAXXMLReader::ParseFromStream(nsIInputStream *aStream,
                                const char *aCharset,
                                const char *aContentType)
{
  // Don't call this in the middle of an async parse
  NS_ENSURE_TRUE(!mIsAsyncParse, NS_ERROR_FAILURE);

  NS_ENSURE_ARG(aStream);
  NS_ENSURE_ARG(aContentType);

  // Put the nsCOMPtr out here so we hold a ref to the stream as needed
  nsresult rv;
  nsCOMPtr<nsIInputStream> bufferedStream;
  if (!NS_InputStreamIsBuffered(aStream)) {
    rv = NS_NewBufferedInputStream(getter_AddRefs(bufferedStream),
                                   aStream, 4096);
    NS_ENSURE_SUCCESS(rv, rv);
    aStream = bufferedStream;
  }
 
  rv = EnsureBaseURI();
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIChannel> parserChannel;
  rv = NS_NewInputStreamChannel(getter_AddRefs(parserChannel), mBaseURI,
                                aStream, nsDependentCString(aContentType));
  if (!parserChannel || NS_FAILED(rv))
    return NS_ERROR_FAILURE;

  if (aCharset)
    parserChannel->SetContentCharset(nsDependentCString(aCharset));

  rv = InitParser(nullptr, parserChannel);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = mListener->OnStartRequest(parserChannel, nullptr);
  if (NS_FAILED(rv))
    parserChannel->Cancel(rv);

  /* When parsing a new document, we need to clear the XML identifiers.
     HandleStartDTD will set these values from the DTD declaration tag.
     We won't have them, of course, if there's a well-formedness error
     before the DTD tag (such as a space before an XML declaration).
   */
  mSystemId.Truncate();
  mPublicId.Truncate();

  nsresult status;
  parserChannel->GetStatus(&status);
  
  uint64_t offset = 0;
  while (NS_SUCCEEDED(rv) && NS_SUCCEEDED(status)) {
    uint64_t available;
    rv = aStream->Available(&available);
    if (rv == NS_BASE_STREAM_CLOSED) {
      rv = NS_OK;
      available = 0;
    }
    if (NS_FAILED(rv)) {
      parserChannel->Cancel(rv);
      break;
    }
    if (! available)
      break; // blocking input stream has none available when done

    if (available > UINT32_MAX)
      available = UINT32_MAX;

    rv = mListener->OnDataAvailable(parserChannel, nullptr,
                                    aStream,
                                    offset,
                                    (uint32_t)available);
    if (NS_SUCCEEDED(rv))
      offset += available;
    else
      parserChannel->Cancel(rv);
    parserChannel->GetStatus(&status);
  }
  rv = mListener->OnStopRequest(parserChannel, nullptr, status);
  mListener = nullptr;

  return rv;
}
Exemple #9
0
//---------------------------------------------------------------------------
// ParseCommandLine
//
// This routine parses the command line given.  If the command line is valid,
// then it is assumed that the user's intention is to execute the test given
// and then exit -- without using the UI for anything.  Else, we display the
// usage message box (if the cmdline wasn't valid), and return.
//
// RETURNS:     NULL if cmdline was valid (script run made, or attempted),
//                   or if command line was invalid and usage was given,
//              OR pointer to script to load if /RUN not present given.
//
//              NOTE:   If no script was given, this function returns a ptr
//                      to a null string.
//---------------------------------------------------------------------------
HANDLE *ParseCommandLine (LPSTR cmdline)
{
    CHAR    *tok, *scr;
    INT     doit = 0, scriptfound = 0;
    static  HANDLE  hScr[9] = {NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL};

#ifdef DEBUG
    fDiags = 0;
#endif
    // We always return at least one file name, so allocate it now
    //-----------------------------------------------------------------------
    listflag = 0;
    if (!(hScr[0] = LocalAlloc (LHND, 128)))
        {
        MPError (NULL, MB_OK | MB_ICONEXCLAMATION, IDS_OUTOFMEM);
        return (NULL);
        }
    scr = LocalLock (hScr[0]);

    // Return now if no cmdline args given
    //-----------------------------------------------------------------------
    scr[0] = 0;
    tok = GetCmdToken(cmdline);
    if (!tok)
        return (hScr);

    do
        {
        // Check here for the /T (testmode) switch and get its parameter
        //-------------------------------------------------------------------
        if (!_stricmp (tok, "/T") || !_stricmp (tok, "-T"))
            {
            tok = GetCmdToken(cmdline);
            if (!tok)
                {
                Usage();
                return (NULL);
                }
            lstrcpy (tmbuf, tok);
            }

        // Here we check for /C (command) switch
        //-------------------------------------------------------------------
        else if (!_stricmp (tok, "/C") || !_stricmp (tok, "-C"))
            {
            tok = GetCmdToken(cmdline);
            if (!tok)
                {
                Usage();
                return (NULL);
                }
            lstrcpy (cmdbuf, tok);
            }

        // /NOE (no error dialog)
        //-------------------------------------------------------------------
        else if (!_stricmp (tok, "/NOE") || !_stricmp (tok, "-NOE"))
            {
            NOERRDLG = 1;
            }

        // /A (filename) switch (produce assembly listing/diagnostics)
        //-------------------------------------------------------------------
        else if (!_stricmp (tok, "/A") || !_stricmp (tok, "-A"))
            {
            tok = GetCmdToken (cmdline);
            if (!tok)
                {
                Usage();
                return (NULL);
                }
            SetAssemblyListFile (tok);
            }

        // /RUN switch
        //-------------------------------------------------------------------
        else if (!_stricmp (tok, "/RUN") || !_stricmp (tok, "-RUN"))
            {
            doit = 1;
            }
#ifdef DEBUG
        else if (!_stricmp (tok, "/DIAG") || !_stricmp (tok, "-DIAG"))
            {
            fDiags = 1;
            }
#endif

        // /D (define) switch
        //-------------------------------------------------------------------
        else if (!_stricmp (tok, "/D") || !_stricmp (tok, "-D"))
            {
            tok = GetCmdToken(cmdline);
            if (!tok)
                {
                Usage();
                return (NULL);
                }
            if (SymCount == 16)
                {
                MPError (NULL, MB_OK | MB_ICONSTOP, IDS_MANYSYMBOLS);
                return (NULL);
                }
            _fstrncpy (DefSym[SymCount], tok, MAXSYMLEN);
            DefSym[SymCount++][MAXSYMLEN] = 0;
            }

        // If this was nothing above, we assume it's a script name
        //-------------------------------------------------------------------
        else if (scriptfound < 8)
            {
            if (!hScr[scriptfound])
                {
                if (!(hScr[scriptfound] = LocalAlloc (LHND, 128)))
                    {
                    MPError (NULL, MB_OK | MB_ICONEXCLAMATION, IDS_OUTOFMEM);
                    return (NULL);
                    }
                scr = LocalLock (hScr[scriptfound]);
                }
            lstrcpy (scr, tok);
            LocalUnlock (hScr[scriptfound]);
            scriptfound += 1;
            }

        // Must have given too many script names
        //-------------------------------------------------------------------
        else
            {
            Usage ();
            return (NULL);
            }
        }
    while (tok = GetCmdToken(cmdline));

    // No error dialog gets nullified if we're running the environment
    //-----------------------------------------------------------------------
    if (NOERRDLG && (!doit))
        NOERRDLG = 0;

    // Return a pointer to the scripts given if no /RUN switch given
    //-----------------------------------------------------------------------
    if (!doit)
        return (hScr);

    // Give an error if no script name found, or more than one
    //-----------------------------------------------------------------------
    if (scriptfound != 1)
        {
        Usage ();
        return (NULL);
        }

    // Okay, we got a valid cmdline and we need to run.  Send the script to
    // the parsing engine.
    //
    // NEW:  Create a simple window which stays minimized and behind every
    // NEW:  other window.  The window text for this will contain the name
    // NEW:  of the script running.
    //-----------------------------------------------------------------------
    EnsureExt (scr, 80);
    AnsiUpper (scr);
    Command = cmdbuf;
    TestMode = tmbuf;

    // KLUDGE:  Call peekmessage to yield once...
    {
    MSG     msg;
    CHAR    buf[256], fmt[40];

    PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE);

    // Change the window text of the viewport for this guy...
    //-----------------------------------------------------------------------
    if (LoadString (hInst, IDS_VPRUNTITLE, fmt, sizeof(fmt)))
        {
        wsprintf (buf, fmt, (LPSTR)scr);
        SetWindowText (hwndViewPort, buf);
        }
    }

    // Here's where we create the dummy window
    //-----------------------------------------------------------------------
    hwndDummy = CreateWindow (szRBRun, (LPSTR)scr,
                              WS_OVERLAPPED|WS_SYSMENU,
                              0, 0, 0, 0, NULL, NULL, hInst, NULL);
    SetWindowPos (hwndDummy, (HWND)1, 0, 0, 0, 0,
                  SWP_NOSIZE | SWP_NOMOVE | SWP_NOACTIVATE);
    ShowWindow (hwndDummy, SW_SHOWMINNOACTIVE);

    // Okay, here we go.
    //-----------------------------------------------------------------------
    if (InitParser ())
	{
	// HACKHACK: ntbldrus (kenhia) - on x86, complains about uninit var
	//	     41 lines below (in final else WITHIN this if block)
	HCURSOR hOld = 0;

        // Initialize the scanner
        //-------------------------------------------------------------------
        if (BeginScan (scr, CBLoaderImmediate, SymCount, DefPtrs))
            {
#ifdef DEBUG
            if (fDiags)
                OpenDiagFile (scr);
#endif
            hOld = SetCursor (LoadCursor (NULL, IDC_WAIT));
            if (!PcodeCompile())
                {
                if (PcodeFixup(0))
                    {
                    SetCursor (hOld);
                    PcodeExecute(PE_RUN, NULL);
                    DestroyWindow (hwndDummy);
                    DestroyWindow (hwndViewPort);
                    exit (ExitVal);
                    }
                else
                    {
                    SetCursor (hOld);
                    DestroyWindow (hwndDummy);
                    DestroyWindow (hwndViewPort);
                    exit (1);
                    }
                }
            else
                {
                SetCursor (hOld);
                DestroyWindow (hwndDummy);
                DestroyWindow (hwndViewPort);
                exit (1);
                }
            EndScan ();
            }
        else
            {
            SetCursor (hOld);
            AbortParser();
            MPError (NULL, MB_OK | MB_ICONSTOP, IDS_CANTREAD, (LPSTR)scr);
            DestroyWindow (hwndDummy);
            DestroyWindow (hwndViewPort);
            exit (1);
            }
        }
    else
        MPError (NULL, MB_OK | MB_ICONSTOP, IDS_CANTINIT);

    DestroyWindow (hwndViewPort);
    DestroyWindow (hwndDummy);
    exit (1);
}
Exemple #10
0
int
main(int argc, char **argv)
{

    char *strNiffFile = NULL;
    FILE *pFILENiff;
    NIFFIOFile *pnf;
    NIFFIOParser *pparser;

    long bytesRead;
    unsigned char extraByte;
    unsigned long extraCount;
    FILE       *lily_out = stdout;
    char       *lily_file = NULL;
    int         i;
    int         option;
    int         do_chording = 1;
    int         do_beams = 0;

    Progname = argv[0];

    /*
     * Check command line arguments
     */
    option = 0;
    for (i = 1; i < argc; i++) {
        if (0) {
#if VERBOSE
        } else if (strcmp(argv[i], "-v") == 0) {
            xly_verbose = 1;
#endif
        } else if (strcmp(argv[i], "-o") == 0) {
            lily_file = argv[++i];
        } else if (strcmp(argv[i], "--no-chords") == 0) {
            do_chording = 0;
        } else if (strcmp(argv[i], "--beam") == 0) {
            do_beams = 1;
        } else if (argv[i][0] != '-' && option == 0) {
            strNiffFile = argv[i];
            option++;
        } else {
			fprintf(stderr, "No such option: \"%s\"\n", argv[i]);
			fprintf(stderr, "Usage:\n");
#if VERBOSE
			fprintf(stderr, "\t-v\tverbose\n");
#endif
			fprintf(stderr, "\t-o <file>\toutput file name\n");
			fprintf(stderr, "\t--no-chords\tvoices i.s.o. chords\n");
			fprintf(stderr, "\t--beam\tretain beaming\n");
		}
    }

    /*
     * Open the riff file
     */
    if (strNiffFile == NULL) {
        pFILENiff = stdin;
    } else {
        pFILENiff = fopen(strNiffFile, "rb");
        if (!pFILENiff)
        {
            perror("Can't open NIFF File");
            return 1;
        }

        if (lily_file == NULL) {
            char *f = strdup(strNiffFile);
            char *dot = strrchr(f, '.');
            if (dot != NULL) {
                if (strcasecmp(dot, ".nif") == 0 ||
                        strcasecmp(dot, ".niff") == 0) {
                    strcpy(dot, ".ly");
                    lily_file = f;
                    fprintf(stderr, "Output to file %s\n", lily_file);
                }
            }
        }
    }
    
    /* 
     * Initialize the niffio file
     */

    pnf = NIFFIOFileNewSTDC(pFILENiff);
    if (!pnf)
        doerror("Can't create new NIFFIOFile");

#if 0
    pnf = NIFFIOFileNew();
    if (pnf == 0)
    {
        doerror("Can't allocate NIFFIOFile");
    }

    if (! NIFFIOFileInit(pnf, pFILENiff, 
                         STDCRIFFRead, STDCRIFFWrite, 
                         STDCRIFFSeek, STDCRIFFTell))
    {
        doerror("Can't initialize NIFFIOFile");
    }
#endif
    /*
     * Initialize the parser 
     */
    pparser = InitParser();

    NIFFIOParserSetTracing(pparser, 0);

    fprintf(stderr, "Now parse niff input %s\n",
            strNiffFile == NULL ? "-" : strNiffFile);
    NIFFIOParseFile(pparser, pnf,  0, 0 );

    if (lily_file != NULL && strcmp(lily_file, "-") != 0) {
        lily_out = fopen(lily_file, "w");
        if (lily_out == NULL) {
            perror("Can't create lily file");
            return 2;
        }
    }

    fprintf(stderr, "Now generate lily output... \n");
    xly_dump(lily_out, do_chording, do_beams);

    /*
     * Check for any extra bytes past the Form
     */
    extraCount = 0;

    while ((bytesRead = NIFFIORead(pnf, &extraByte , 1)) == 1)
    {
        extraCount +=1;
    }

    if (extraCount != 0)
    {
        fprintf(stderr,"%s:WARNING:Found %lu extra bytes after Form\n",
                Progname,
                extraCount);
        return 1;
    }

    /*
     * Clean up
     */

#if 0
    NIFFIOParserDelete(pparser);

    NIFFIOFileDelete(pnf);
#endif
    fclose(pFILENiff);

    fclose(lily_out);

    fprintf(stderr, "niff2ly completed\n");

    return 0;
}
Exemple #11
0
void setup_Rmainloop(void)
{
    volatile int doneit;
    volatile SEXP baseEnv;
    SEXP cmd;
    char deferred_warnings[11][250];
    volatile int ndeferred_warnings = 0;

    /* In case this is a silly limit: 2^32 -3 has been seen and
     * casting to intptr_r relies on this being smaller than 2^31 on a
     * 32-bit platform. */
    if(R_CStackLimit > 100000000U) 
	R_CStackLimit = (uintptr_t)-1;
    /* make sure we have enough head room to handle errors */
    if(R_CStackLimit != -1)
	R_CStackLimit = (uintptr_t)(0.95 * R_CStackLimit);

    InitConnections(); /* needed to get any output at all */

    /* Initialize the interpreter's internal structures. */

#ifdef HAVE_LOCALE_H
#ifdef Win32
    {
	char *p, Rlocale[1000]; /* Windows' locales can be very long */
	p = getenv("LC_ALL");
	strncpy(Rlocale, p ? p : "", 1000);
        Rlocale[1000 - 1] = '\0';
	if(!(p = getenv("LC_CTYPE"))) p = Rlocale;
	/* We'd like to use warning, but need to defer.
	   Also cannot translate. */
	if(!setlocale(LC_CTYPE, p))
	    snprintf(deferred_warnings[ndeferred_warnings++], 250,
		     "Setting LC_CTYPE=%s failed\n", p);
	if((p = getenv("LC_COLLATE"))) {
	    if(!setlocale(LC_COLLATE, p))
		snprintf(deferred_warnings[ndeferred_warnings++], 250,
			 "Setting LC_COLLATE=%s failed\n", p);
	} else setlocale(LC_COLLATE, Rlocale);
	if((p = getenv("LC_TIME"))) {
	    if(!setlocale(LC_TIME, p))
		snprintf(deferred_warnings[ndeferred_warnings++], 250,
			 "Setting LC_TIME=%s failed\n", p);
	} else setlocale(LC_TIME, Rlocale);
	if((p = getenv("LC_MONETARY"))) {
	    if(!setlocale(LC_MONETARY, p))
		snprintf(deferred_warnings[ndeferred_warnings++], 250,
			 "Setting LC_MONETARY=%s failed\n", p);
	} else setlocale(LC_MONETARY, Rlocale);
	/* Windows does not have LC_MESSAGES */

	/* We set R_ARCH here: Unix does it in the shell front-end */
	char Rarch[30];
	strcpy(Rarch, "R_ARCH=/");
	strcat(Rarch, R_ARCH);
	putenv(Rarch);
    }
#else /* not Win32 */
    if(!setlocale(LC_CTYPE, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_CTYPE failed, using \"C\"\n");
    if(!setlocale(LC_COLLATE, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_COLLATE failed, using \"C\"\n");
    if(!setlocale(LC_TIME, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_TIME failed, using \"C\"\n");
#ifdef ENABLE_NLS
    if(!setlocale(LC_MESSAGES, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_MESSAGES failed, using \"C\"\n");
#endif
    /* NB: we do not set LC_NUMERIC */
#ifdef LC_MONETARY
    if(!setlocale(LC_MONETARY, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_MONETARY failed, using \"C\"\n");
#endif
#ifdef LC_PAPER
    if(!setlocale(LC_PAPER, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_PAPER failed, using \"C\"\n");
#endif
#ifdef LC_MEASUREMENT
    if(!setlocale(LC_MEASUREMENT, ""))
	snprintf(deferred_warnings[ndeferred_warnings++], 250,
		 "Setting LC_MEASUREMENT failed, using \"C\"\n");
#endif
#endif /* not Win32 */
#endif

    /* make sure srand is called before R_tmpnam, PR#14381 */
    srand(TimeToSeed());

    InitArithmetic();
    InitParser();
    InitTempDir(); /* must be before InitEd */
    InitMemory();
    InitStringHash(); /* must be before InitNames */
    InitNames();
    InitBaseEnv();
    InitGlobalEnv();
    InitDynload();
    InitOptions();
    InitEd();
    InitGraphics();
    InitTypeTables(); /* must be before InitS3DefaultTypes */
    InitS3DefaultTypes();
    
    R_Is_Running = 1;
    R_check_locale();

    /* Initialize the global context for error handling. */
    /* This provides a target for any non-local gotos */
    /* which occur during error handling */

    R_Toplevel.nextcontext = NULL;
    R_Toplevel.callflag = CTXT_TOPLEVEL;
    R_Toplevel.cstacktop = 0;
    R_Toplevel.promargs = R_NilValue;
    R_Toplevel.callfun = R_NilValue;
    R_Toplevel.call = R_NilValue;
    R_Toplevel.cloenv = R_BaseEnv;
    R_Toplevel.sysparent = R_BaseEnv;
    R_Toplevel.conexit = R_NilValue;
    R_Toplevel.vmax = NULL;
    R_Toplevel.nodestack = R_BCNodeStackTop;
#ifdef BC_INT_STACK
    R_Toplevel.intstack = R_BCIntStackTop;
#endif
    R_Toplevel.cend = NULL;
    R_Toplevel.intsusp = FALSE;
    R_Toplevel.handlerstack = R_HandlerStack;
    R_Toplevel.restartstack = R_RestartStack;
    R_Toplevel.srcref = R_NilValue;
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    R_ExitContext = NULL;

    R_Warnings = R_NilValue;

    /* This is the same as R_BaseEnv, but this marks the environment
       of functions as the namespace and not the package. */
    baseEnv = R_BaseNamespace;

    /* Set up some global variables */
    Init_R_Variables(baseEnv);

    /* On initial entry we open the base language package and begin by
       running the repl on it.
       If there is an error we pass on to the repl.
       Perhaps it makes more sense to quit gracefully?
    */

#ifdef RMIN_ONLY
    /* This is intended to support a minimal build for experimentation. */
    if (R_SignalHandlers) init_signal_handlers();
#else
    FILE *fp = R_OpenLibraryFile("base");
    if (fp == NULL)
	R_Suicide(_("unable to open the base package\n"));

    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (R_SignalHandlers) init_signal_handlers();
    if (!doneit) {
	doneit = 1;
	R_ReplFile(fp, baseEnv);
    }
    fclose(fp);
#endif

    /* This is where we source the system-wide, the site's and the
       user's profile (in that order).  If there is an error, we
       drop through to further processing.
    */
    R_IoBufferInit(&R_ConsoleIob);
    R_LoadProfile(R_OpenSysInitFile(), baseEnv);
    /* These are the same bindings, so only lock them once */
    R_LockEnvironment(R_BaseNamespace, TRUE);
#ifdef NOTYET
    /* methods package needs to trample here */
    R_LockEnvironment(R_BaseEnv, TRUE);
#endif
    /* At least temporarily unlock some bindings used in graphics */
    R_unLockBinding(R_DeviceSymbol, R_BaseEnv);
    R_unLockBinding(R_DevicesSymbol, R_BaseEnv);
    R_unLockBinding(install(".Library.site"), R_BaseEnv);

    /* require(methods) if it is in the default packages */
    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	PROTECT(cmd = install(".OptRequireMethods"));
	R_CurrentExpr = findVar(cmd, R_GlobalEnv);
	if (R_CurrentExpr != R_UnboundValue &&
	    TYPEOF(R_CurrentExpr) == CLOSXP) {
		PROTECT(R_CurrentExpr = lang1(cmd));
		R_CurrentExpr = eval(R_CurrentExpr, R_GlobalEnv);
		UNPROTECT(1);
	}
	UNPROTECT(1);
    }

    if (strcmp(R_GUIType, "Tk") == 0) {
	char buf[PATH_MAX];

	snprintf(buf, PATH_MAX, "%s/library/tcltk/exec/Tk-frontend.R", R_Home);
	R_LoadProfile(R_fopen(buf, "r"), R_GlobalEnv);
    }

    /* Print a platform and version dependent greeting and a pointer to
     * the copyleft.
     */
    if(!R_Quiet) PrintGreeting();
 
    R_LoadProfile(R_OpenSiteFile(), baseEnv);
    R_LockBinding(install(".Library.site"), R_BaseEnv);
    R_LoadProfile(R_OpenInitFile(), R_GlobalEnv);

    /* This is where we try to load a user's saved data.
       The right thing to do here is very platform dependent.
       E.g. under Unix we look in a special hidden file and on the Mac
       we look in any documents which might have been double clicked on
       or dropped on the application.
    */
    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	R_InitialData();
    }
    else {
    	if (! SETJMP(R_Toplevel.cjmpbuf)) {
	    warning(_("unable to restore saved data in %s\n"), get_workspace_name());
	}
    }
    
    /* Initial Loading is done.
       At this point we try to invoke the .First Function.
       If there is an error we continue. */

    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	PROTECT(cmd = install(".First"));
	R_CurrentExpr = findVar(cmd, R_GlobalEnv);
	if (R_CurrentExpr != R_UnboundValue &&
	    TYPEOF(R_CurrentExpr) == CLOSXP) {
		PROTECT(R_CurrentExpr = lang1(cmd));
		R_CurrentExpr = eval(R_CurrentExpr, R_GlobalEnv);
		UNPROTECT(1);
	}
	UNPROTECT(1);
    }
    /* Try to invoke the .First.sys function, which loads the default packages.
       If there is an error we continue. */

    doneit = 0;
    SETJMP(R_Toplevel.cjmpbuf);
    R_GlobalContext = R_ToplevelContext = R_SessionContext = &R_Toplevel;
    if (!doneit) {
	doneit = 1;
	PROTECT(cmd = install(".First.sys"));
	R_CurrentExpr = findVar(cmd, baseEnv);
	if (R_CurrentExpr != R_UnboundValue &&
	    TYPEOF(R_CurrentExpr) == CLOSXP) {
		PROTECT(R_CurrentExpr = lang1(cmd));
		R_CurrentExpr = eval(R_CurrentExpr, R_GlobalEnv);
		UNPROTECT(1);
	}
	UNPROTECT(1);
    }
    {
	int i;
	for(i = 0 ; i < ndeferred_warnings; i++)
	    warning(deferred_warnings[i]);
    }
    if (R_CollectWarnings) {
	REprintf(_("During startup - "));
	PrintWarnings();
    }

    /* trying to do this earlier seems to run into bootstrapping issues. */
    R_init_jit_enabled();
    R_Is_Running = 2;
}
int startup(int argc, char *argv[])
{ int i, len;  FULL_CHAR *arg;
  OBJECT t, y, res, s;			/* current token, parser output      */
  BOOLEAN stdin_seen;			/* TRUE when stdin file seen         */
  int source_file_count;		/* number of source files in command */
  FULL_CHAR *cross_db;			/* name of cross reference database  */
  FULL_CHAR *outfile;			/* name of output file               */
  FULL_CHAR *lib;			/* name of library directory         */
  FILE *out_fp;
  long MemCheckLong;
  FULL_CHAR oname[MAX_BUFF], oval[MAX_BUFF], buff[MAX_BUFF], *p;
  int bp;  OBJECT z;
  BOOLEAN seen_wordcount;
#if LOCALE_ON
  char catname[MAX_BUFF], *loc;
#endif

  /* find the name of the library directory, from envt or else from -D */
  lib = AsciiToFull(getenv("LOUTLIB"));
  if( lib == (FULL_CHAR *) NULL )
    lib = AsciiToFull(LIB_DIR);

  /* set locale if that's what we are doing */
#if LOCALE_ON
  loc = setlocale(LC_MESSAGES, "");
  if( loc == (char *) NULL )
  { Error(1, 6, "unable to initialize locale", WARN, no_fpos);
    loc = "C";
  }
  sprintf(catname, "%s/%s/%s/LC_MESSAGES/errors.%s",
    lib, LOCALE_DIR, loc, loc);
  MsgCat = catopen(catname, 0);
#endif

  /* initialise various modules, add current directory to search paths */
  TotalWordCount = 0;
  seen_wordcount = FALSE;
  BackEnd = PS_BackEnd;
  PlainCharWidth = PLAIN_WIDTH;
  PlainCharHeight = PLAIN_HEIGHT;
  PlainFormFeed = FALSE;
  InitializeAll = FALSE;
  UseCollate = COLLATE;
  AllowCrossDb = TRUE;
  InMemoryDbIndexes = TRUE;
  Encapsulated = FALSE;
  SafeExecution = SAFE_DFT ? TRUE : FALSE;
  Kern = TRUE;
  MemInit();
  InitSym();
  LexInit();
  InitFiles();
  AddToPath(SOURCE_PATH,   MakeWord(WORD, STR_EMPTY, no_fpos));
  AddToPath(DATABASE_PATH, MakeWord(WORD, STR_EMPTY, no_fpos));
  AddToPath(INCLUDE_PATH,  MakeWord(WORD, STR_EMPTY, no_fpos));

  /* read command line */
  stdin_seen = FALSE;
  AltErrorFormat = FALSE;
  cross_db = CROSS_DB;
  outfile = STR_STDOUT;
  source_file_count = 0;
  New(CommandOptions, ACAT);
  for( i = 1;  i < argc;  i++ )
  {
    if( *argv[i] == CH_HYPHEN ) switch( *(argv[i]+1) )
    {
      case CH_FLAG_OUTFILE:
     
	/* read name of output file */
	if( (outfile = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 7, "usage: -o <filename>", FATAL, no_fpos);
	if( StringEndsWith(outfile, SOURCE_SUFFIX) )
	  Error(1, 28, "-o: output file name %s ends with %s",
	    FATAL, no_fpos, outfile, SOURCE_SUFFIX);
	break;


      case CH_FLAG_SUPPRESS:
     
	/* suppress references to OldCrossDb and NewCrossDb */
	AllowCrossDb = FALSE;
	break;


      case CH_FLAG_MEMCR:
     
	/* don't use in-memory database indexes */
	InMemoryDbIndexes = FALSE;
	break;


      case CH_FLAG_NOKERN:
     
	/* suppress kerning */
	Kern = FALSE;
	break;


      case CH_FLAG_NOCOLLATE:
     
	/* suppress local collation */
	UseCollate = FALSE;
	break;


      case CH_FLAG_COLLATE:
     
	/* invoke local collation */
	UseCollate = TRUE;
	break;


      case CH_FLAG_CROSS:
     
	/* read name of cross reference database */
	if( (cross_db = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 8, "usage: -c <filename>", FATAL, no_fpos);
	break;


      case CH_FLAG_ERRFILE:
     
	/* read log file name */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 9, "usage: -e <filename>", FATAL, no_fpos);
	ErrorInit(arg);
	break;


      case CH_FLAG_ALTERR:
     
	/* alternative error message format */
	AltErrorFormat = TRUE;
	break;


      case CH_FLAG_EPSFIRST:
     
	/* -EPS produces encapsulated PostScript output */
	if( !StringEqual(AsciiToFull(argv[i]+1), STR_EPS) )
	  Error(1, 10, "usage: -EPS", FATAL, no_fpos);
	Encapsulated = TRUE;
	break;


      case CH_FLAG_DIRPATH:
     
	/* add directory to database and sysdatabase paths */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 11, "usage: -D <directoryname>", FATAL, no_fpos);
	AddToPath(DATABASE_PATH, MakeWord(WORD, arg, no_fpos));
	AddToPath(SYSDATABASE_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_ENCPATH:
     
	/* add directory to character mapping path */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 12, "usage: -C <directoryname>", FATAL, no_fpos);
	AddToPath(MAPPING_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_FNTPATH:
     
	/* add directory to font path */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 13, "usage: -F <directoryname>", FATAL, no_fpos);
	AddToPath(FONT_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_HYPPATH:
     
	/* add directory to hyph path */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 14, "usage: -H <directoryname>", FATAL, no_fpos);
	AddToPath(HYPH_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_INCPATH:
     
	/* add directory to include and sysinclude paths */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 15, "usage: -I <directoryname>", FATAL, no_fpos);
	AddToPath(INCLUDE_PATH, MakeWord(WORD, arg, no_fpos));
	AddToPath(SYSINCLUDE_PATH, MakeWord(WORD, arg, no_fpos));
	break;


      case CH_FLAG_INCLUDE:
     
	/* read sysinclude file and strip any .lt suffix */
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 16, "usage: -i <filename>", FATAL, no_fpos);
	len = StringLength(arg) - StringLength(SOURCE_SUFFIX);
	if( len >= 0 && StringEqual(&arg[len], SOURCE_SUFFIX) )
	  StringCopy(&arg[len], STR_EMPTY);
	debug0(DFS, D, "  calling DefineFile from main (1)");
	DefineFile(arg, STR_EMPTY, no_fpos, SOURCE_FILE, SYSINCLUDE_PATH);
	break;


      case CH_FLAG_HYPHEN:
     
	/* declare hyphenation file */
	if( FirstFile(HYPH_FILE) != NO_FILE )
	  Error(1, 17, "two -h options illegal", FATAL, no_fpos);
	if( (arg = GetArg(argv, argc, &i)) == NULL )
	  Error(1, 18, "usage: -h <filename>", FATAL, no_fpos);
	debug0(DFS, D, "  calling DefineFile from main (2)");
	DefineFile(arg, STR_EMPTY, no_fpos, HYPH_FILE, INCLUDE_PATH);
	DefineFile(arg, HYPH_SUFFIX, no_fpos, HYPH_PACKED_FILE, INCLUDE_PATH);
	break;


      case CH_FLAG_VERSION:
     
	fprintf(stderr, "%s\n", LOUT_VERSION);
	fprintf(stderr, "%-28s %s\n",
	  "Basser Lout written by:", "Jeffrey H. Kingston ([email protected])");
	fprintf(stderr, "%-28s %s\n",
	  "Free source available from:", "ftp://ftp.cs.usyd.edu.au/jeff/lout");
	fprintf(stderr, "%-28s %s %s\n",
	  "This executable compiled:", __TIME__, __DATE__);
	fprintf(stderr, "%-28s %s%s%s\n", "System include directory:",
	  lib, STR_DIR, INCL_DIR);
	fprintf(stderr, "%-28s %s%s%s\n", "System database directory:",
	  lib, STR_DIR, DATA_DIR);
	fprintf(stderr, "Database index files created afresh automatically:%s\n",
	  USE_STAT ? " yes" : " no");
	fprintf(stderr, "Safe execution (disabling system()) is default:%s\n",
	  SAFE_DFT ? " yes" : " no");
	fprintf(stderr, "strcoll() used for sorting by default:%s\n",
	  COLLATE ? " yes" : " no");
	fprintf(stderr, "PDF compression on:%s\n",
	  PDF_COMPRESSION ? " yes" : " no");
	fprintf(stderr, "Debugging (-d, -dd, -ddd flags) available:%s\n",
	  DEBUG_ON ? " yes" : " no");
	fprintf(stderr, "\n");
	fprintf(stderr, "Basser Lout comes with ABSOLUTELY NO WARRANTY.\n");
	fprintf(stderr, "This is free software, and you are welcome to\n");
	fprintf(stderr, "redistribute it under certain conditions.  For\n");
	fprintf(stderr, "details on both points, consult the GNU General\n");
	fprintf(stderr, "Public License (distributed with this software).\n");
	exit(0);
	break;


      case CH_FLAG_WORDS:
     
	seen_wordcount = TRUE;
	break;


      case CH_FLAG_PDF:

	BackEnd = PDF_BackEnd;
	break;


      case CH_FLAG_FFPLAIN:

	if( StringEqual(AsciiToFull(argv[i]+1), STR_PDF) )
	{
	  BackEnd = PDF_BackEnd;
	  break;
	}
	PlainFormFeed = TRUE;
	/* NB NO BREAK */


      case CH_FLAG_PLAIN:
     
	BackEnd = Plain_BackEnd;
	if( *(argv[i]+2) != '\0' )
	{ float len1, len2;  FULL_CHAR units1, units2;
	  if( sscanf(argv[i]+2, "%f%c%f%c",&len1,&units1,&len2,&units2) != 4 )
	  { Error(1, 19, "usage: lout -%c<length><length>",
	      FATAL, no_fpos, *(argv[i]+1));
	  }
	  switch( units1 )
	  {
	    case CH_UNIT_CM:	PlainCharWidth = len1 * CM; break;
	    case CH_UNIT_IN:	PlainCharWidth = len1 * IN; break;
	    case CH_UNIT_PT:	PlainCharWidth = len1 * PT; break;
	    case CH_UNIT_EM:	PlainCharWidth = len1 * EM; break;

	    default:	Error(1, 20, "lout -%c: units must be c, i, p, or m",
				  FATAL, no_fpos, *(argv[i]+1));
				break;
	  }
	  switch( units2 )
	  {
	    case CH_UNIT_CM:	PlainCharHeight = len2 * CM; break;
	    case CH_UNIT_IN:	PlainCharHeight = len2 * IN; break;
	    case CH_UNIT_PT:	PlainCharHeight = len2 * PT; break;
	    case CH_UNIT_EM:	PlainCharHeight = len2 * EM; break;

	    default:	Error(1, 21, "lout -%c: units must be c, i, p, or m",
				  FATAL, no_fpos, *(argv[i]+1));
				break;
	  }
	}
	break;


      case CH_FLAG_INITALL:

	InitializeAll = TRUE;
	AllowCrossDb = FALSE;
	break;


      case CH_FLAG_USAGE:

	PrintUsage(stderr);
	exit(0);
	break;


      case CH_FLAG_DEBUG:
     
	debug_init(AsciiToFull(argv[i]));
	break;


      case CH_FLAG_MEMCHECK:

	sscanf(argv[i], "-m%ld", &MemCheckLong);
	MemCheck = (POINTER) MemCheckLong;
	fprintf(stderr, "checking memory location %ld\n", (long) MemCheck);
	break;


      case '\0':
     
	/* read stdin as file name */
	if( stdin_seen )
	  Error(1, 23, "standard input specified twice", FATAL, no_fpos);
	stdin_seen = TRUE;
	debug0(DFS, D, "  calling DefineFile from main (3)");
	DefineFile(STR_STDIN, STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH);
	break;


      case CH_FLAG_OPTION:

	/* read command-line document option */
	if( sscanf(argv[i]+2, "%[^{ ] { %[^}] }", oname, oval) != 2 ||
	  StringLength(oname) == 0 || StringLength(oval) == 0 )
	  Error(1, 24, "error in command-line option %s", FATAL, no_fpos,
	    argv[i]+2);
	y = MakeWord(WORD, oname, no_fpos);
	Link(CommandOptions, y);
	New(y, ACAT);
	Link(CommandOptions, y);
	bp = 0;
	for( p = oval;  *p != '\0';  p++ )  switch( *p )
	{
	  case ' ':
	  case '\t':
	  case '\n':
	  case '{':
	  case '}':

	    if( bp > 0 )
	    { buff[bp++] = '\0';
	      if( Down(y) != y ) 
	      { OBJECT g;
		New(g, GAP_OBJ);
		hspace(g) = 1;  vspace(g) = 0;
		FposCopy(fpos(g), *no_fpos);
		Link(y, g);
	      }
	      z = MakeWord(WORD, buff, no_fpos);
	      Link(y, z);
	      bp = 0;
	    }
	    break;


	  default:

	    buff[bp++] = *p;
	    break;
	}
	if( bp > 0 )
	{ buff[bp++] = '\0';
	  z = MakeWord(WORD, buff, no_fpos);
	  Link(y, z);
	}
	if( Down(y) == y )
	  Error(1, 25, "error in command-line option %s", FATAL, no_fpos,
	    argv[i]+2);
	break;


      case CH_FLAG_SAFE:

	/* ensure safe execution by disabling system calls */
	SafeExecution = TRUE;
	break;

      case CH_FLAG_UNSAFE:

	/* allow unsafe execution */
	SafeExecution = FALSE;
	break;

      default:
     
	PrintUsage(stderr);
	Error(1, 26, "unknown command line flag %s", FATAL, no_fpos, argv[i]);
	break;

    }
    else
    {   /* argument is source file, strip any .lout suffix and define it */
	arg = AsciiToFull(argv[i]);
	len = StringLength(arg) - StringLength(SOURCE_SUFFIX);
	if( len >= 0 && StringEqual(&arg[len], SOURCE_SUFFIX) )
	  StringCopy(&arg[len], STR_EMPTY);
	debug0(DFS, D, "  calling DefineFile from main (4)");
	DefineFile(AsciiToFull(argv[i]), STR_EMPTY, no_fpos,
	    SOURCE_FILE, SOURCE_PATH);
	source_file_count++;
    }
  } /* for */

  if( UseCollate )
  {
    if (!setlocale (LC_COLLATE, ""))
      Error(1, 30, "unable to initialize collation", WARN, no_fpos);
  }

  /* start timing if required */
  ifdebug(DPP, D, ProfileOn("main"));

  /* open output file, or stdout if none specified, and initialize printer */
  if( StringEqual(outfile, STR_STDOUT) )
  {
#if OS_DOS
    /* For DOS/Win32 we need to set binary mode on stdout to prevent
       PDF compressed streams and xrefs from being corrupted - Uwe 12/98 */
    if( BackEnd->code != PLAINTEXT &&
	_setmode(_fileno(stdout), _O_BINARY) == -1 )
      Error(1, 31, "cannot set binary mode on stdout", FATAL, no_fpos);
#endif
    out_fp = stdout;
  }
  else
  { out_fp = StringFOpen(outfile,
		BackEnd->code == PLAINTEXT ? WRITE_TEXT : WRITE_BINARY);
    if( out_fp == null )
      Error(1, 27, "cannot open output file %s", FATAL, no_fpos, outfile);
  }

  /* initialize miscellaneous modules */
  ColourInit();
  LanguageInit();
  BackEnd->PrintInitialize(out_fp);

  /* append default directories to file search paths */
  AddToPath(FONT_PATH,      MakeWordThree(lib, STR_DIR, AsciiToFull(FONT_DIR)));
  AddToPath(HYPH_PATH,      MakeWordThree(lib, STR_DIR, AsciiToFull(HYPH_DIR)));
  AddToPath(MAPPING_PATH,   MakeWordThree(lib, STR_DIR, AsciiToFull(MAPS_DIR)));
  AddToPath(SYSDATABASE_PATH,MakeWordThree(lib,STR_DIR, AsciiToFull(DATA_DIR)));
  AddToPath(DATABASE_PATH,  MakeWordThree(lib, STR_DIR, AsciiToFull(DATA_DIR)));
  AddToPath(SYSINCLUDE_PATH,MakeWordThree(lib, STR_DIR, AsciiToFull(INCL_DIR)));
  AddToPath(INCLUDE_PATH,   MakeWordThree(lib, STR_DIR, AsciiToFull(INCL_DIR)));

  /* use stdin if no source files were mentioned */
  if( source_file_count == 0 )
  { debug0(DFS, D, "  calling DefineFile from main (5)");
    DefineFile(STR_STDIN, STR_EMPTY, no_fpos, SOURCE_FILE, SOURCE_PATH);
  }

  /* load predefined symbols into symbol table */
  StartSym      = nilobj;  /* Not a mistake */
  StartSym      = load(KW_START,        0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  GalleySym     = load(KW_GALLEY,       0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  ForceGalleySym= load(KW_FORCE_GALLEY, 0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  InputSym      = load(KW_INPUT,        0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  PrintSym      = load(KW_PRINT,        0, FALSE,  FALSE,  TRUE,  NO_PREC     );
  FilterInSym   = load(KW_FILTERIN,     0, FALSE,  FALSE,  FALSE, NO_PREC     );
  FilterOutSym  = load(KW_FILTEROUT,    0, FALSE,  FALSE,  FALSE, NO_PREC     );
  FilterErrSym  = load(KW_FILTERERR,    0, FALSE,  FALSE,  FALSE, NO_PREC     );
  OptGallSym    = load(KW_OPTGALL,      0, FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  VerbatimSym   = load(KW_VERBATIM,VERBATIM,FALSE, TRUE,   FALSE, DEFAULT_PREC);
  RawVerbatimSym= load(KW_RAWVERBATIM,RAW_VERBATIM,FALSE,TRUE,FALSE,DEFAULT_PREC);


  load(KW_BEGIN,        BEGIN,          FALSE,  FALSE,  FALSE, BEGIN_PREC  );
  load(KW_END,          END,            FALSE,  FALSE,  FALSE, END_PREC    );
  load(KW_ENV,          ENV,            FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_ENVA,         ENVA,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_ENVB,         ENVB,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_ENVC,         ENVC,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_ENVD,         ENVD,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_CENV,         CENV,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_CLOS,         CLOS,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_LVIS,         LVIS,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_LUSE,         LUSE,           FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_LEO,          LEO,            FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_LBR,          LBR,            FALSE,  FALSE,  FALSE, LBR_PREC    );
  load(KW_RBR,          RBR,            FALSE,  FALSE,  FALSE, RBR_PREC    );
  load(KW_INCLUDE,      INCLUDE,        FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_SYSINCLUDE,   SYS_INCLUDE,    FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_PREPEND,      PREPEND,        FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_SYSPREPEND,   SYS_PREPEND,    FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_DATABASE,     DATABASE,       FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_SYSDATABASE,  SYS_DATABASE,   FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_USE,          USE,            FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_NOT_REVEALED, NOT_REVEALED,   FALSE,  FALSE,  FALSE, NO_PREC     );
  load(KW_CASE,         CASE,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_YIELD,        YIELD,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_BACKEND,      BACKEND,        FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_XCHAR,        XCHAR,          FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_FONT,         FONT,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_SPACE,        SPACE,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_YUNIT,        YUNIT,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_ZUNIT,        ZUNIT,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_BREAK,        BREAK,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_UNDERLINE,    UNDERLINE,      FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_COLOUR,       COLOUR,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_COLOR,        COLOUR,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_OUTLINE,      OUTLINE,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_LANGUAGE,     LANGUAGE,       TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_CURR_LANG,    CURR_LANG,      FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_CURR_FAMILY,  CURR_FAMILY,    FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_CURR_FACE,    CURR_FACE,      FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_CURR_YUNIT,   CURR_YUNIT,     FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_CURR_ZUNIT,   CURR_ZUNIT,     FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_COMMON,       COMMON,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_RUMP,         RUMP,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_MELD,         MELD,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_INSERT,       INSERT,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_ONE_OF,       ONE_OF,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_NEXT,         NEXT,           FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_PLUS,         PLUS,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_MINUS,        MINUS,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_OPEN,         OPEN,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_TAGGED,       TAGGED,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_WIDE,         WIDE,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HIGH,         HIGH,           TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HSHIFT,       HSHIFT,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VSHIFT,       VSHIFT,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_BEGIN_HEADER, BEGIN_HEADER,   TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_END_HEADER,   END_HEADER,     FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_SET_HEADER,   SET_HEADER,     TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_CLEAR_HEADER, CLEAR_HEADER,   FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_ONE_COL,      ONE_COL,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_ONE_ROW,      ONE_ROW,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HSCALE,       HSCALE,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VSCALE,       VSCALE,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HCOVER,       HCOVER,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VCOVER,       VCOVER,         FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_KERN_SHRINK,  KERN_SHRINK,    TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_SCALE,        SCALE,          TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HCONTRACT,    HCONTRACT,      FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VCONTRACT,    VCONTRACT,      FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HLIMITED,     HLIMITED,       FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VLIMITED,     VLIMITED,       FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HEXPAND,      HEXPAND,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VEXPAND,      VEXPAND,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_STARTHVSPAN,  START_HVSPAN,   FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_STARTHSPAN,   START_HSPAN,    FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_STARTVSPAN,   START_VSPAN,    FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HSPAN,        HSPAN,          FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_VSPAN,        VSPAN,          FALSE,  FALSE,  FALSE, DEFAULT_PREC);
  load(KW_PADJUST,      PADJUST,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_HADJUST,      HADJUST,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_VADJUST,      VADJUST,        FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_ROTATE,       ROTATE,         TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_BACKGROUND,   BACKGROUND,     TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_INCGRAPHIC,   INCGRAPHIC,     FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_SINCGRAPHIC,  SINCGRAPHIC,    FALSE,  TRUE,   FALSE, DEFAULT_PREC);
  load(KW_PLAINGRAPHIC, PLAIN_GRAPHIC,  TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_GRAPHIC,      GRAPHIC,        TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_LINK_SOURCE,   LINK_SOURCE,     TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_LINK_DEST,    LINK_DEST,      TRUE,   TRUE,   FALSE, DEFAULT_PREC);
  load(KW_CROSS,        CROSS,          TRUE,   TRUE,   FALSE, CROSSOP_PREC);
  load(KW_FORCE_CROSS,  FORCE_CROSS,    TRUE,   TRUE,   FALSE, CROSSOP_PREC);
  load(KW_NULL,         NULL_CLOS,      FALSE,  FALSE,  TRUE,  NO_PREC     );
  load(KW_PAGE_LABEL,   PAGE_LABEL,     FALSE,  TRUE,   TRUE,  DEFAULT_PREC);

#define setcat(s, mk, jn)  has_mark(s)=mk, has_join(s)=jn

  s=load(KW_VCAT_NN, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,FALSE,FALSE);
  s=load(KW_VCAT_MN, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,TRUE, FALSE);
  s=load(KW_VCAT_NJ, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,FALSE,TRUE);
  s=load(KW_VCAT_MJ, VCAT, TRUE, TRUE, FALSE, VCAT_PREC); setcat(s,TRUE, TRUE);
  s=load(KW_HCAT_NN, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,FALSE,FALSE);
  s=load(KW_HCAT_MN, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,TRUE, FALSE);
  s=load(KW_HCAT_NJ, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,FALSE,TRUE);
  s=load(KW_HCAT_MJ, HCAT, TRUE, TRUE, FALSE, HCAT_PREC); setcat(s,TRUE, TRUE);
  s=load(KW_ACAT_NJ, ACAT, TRUE, TRUE, FALSE, ACAT_PREC); setcat(s,FALSE,TRUE);
  s=load(KW_ACAT_MJ, ACAT, TRUE, TRUE, FALSE, ACAT_PREC); setcat(s,TRUE, TRUE);

  /* intialize fonts and load @FontDef symbol */
  FontInit();

  /* intialize current time and load @Moment symbol */
  InitTime();

  /* initialize filter module */
  FilterInit();

  /* initialize enviroment table module */
  EnvInit();

  /* initialise scope chain to <StartSym> */
  PushScope(StartSym, FALSE, FALSE);

  /* initialise lexical analyser */
  LexPush(FirstFile(SOURCE_FILE), 0, SOURCE_FILE, 1, FALSE);

  /* process input files */
  InitParser(cross_db);
  t = NewToken(BEGIN, no_fpos, 0, 0, BEGIN_PREC, StartSym);
  res = Parse(&t, StartSym, TRUE, TRUE);
  debug0(DGT, D, "calling TransferEnd(res) from main()");
  DisposeObject(CommandOptions);
  TransferEnd(res);
  TransferClose();

  /* close various modules */
  BackEnd->PrintAfterLastPage();
  BackEnd->LinkCheck();
  CrossClose();
  CloseFiles();

  /* remove any leftover filter temporary files */
  FilterScavenge(TRUE);

  /* print word count, if required */
  if( seen_wordcount )
    Error(1, 29, "total of all words printed: %d", WARN,no_fpos,TotalWordCount);

  /* check for unbalanced error blocks */
  CheckErrorBlocks();

  /* wrapup */
  ifdebug(DST, DD, CheckSymSpread() );
  ifdebug(ANY, D, DeleteEverySym() );
  debug0(DMA, D, "at end of run:");
  ifdebug(DMA, D, DebugMemory() );
  ifdebug(DPP, D, ProfileOff("main"));
  ifdebug(DPP, D, ProfilePrint());
  ifdebug(DET, D, EnvDebug());

#if LOCALE_ON
  catclose(MsgCat);
#endif

  exit(0);
  return 0;
} /* end main */
Exemple #13
0
//---------------------------------------------------------------------------
// ParseCommandLine
//
// This routine parses the command line given.  If the command line is valid,
// then it is assumed that the user's intention is to execute the test given
// and then exit -- without using the UI for anything.  Else, we display the
// usage message box (if the cmdline wasn't valid), and return.
//
// RETURNS:     NULL if cmdline was valid (script run made, or attempted),
//                   or if command line was invalid and usage was given,
//              OR pointer to script to load if /RUN not present given.
//
//              NOTE:   If no script was given, this function returns a ptr
//                      to a null string.
//---------------------------------------------------------------------------
CHAR *ParseCommandLine (LPSTR cmdline)
{
    CHAR    *tok;
    INT     scriptfound = 0;
    static  CHAR    tm[80], cmd[80], scr[128];

    // Return now if no cmdline args given
    //-----------------------------------------------------------------------
    scr[0] = 0;

    while (tok = GetCmdToken(cmdline))
        {
        if (!_stricmp (tok, "/T") || !_stricmp (tok, "-T"))
            {
            tok = GetCmdToken(cmdline);
            if (!tok)
                {
                Usage();
                return (NULL);
                }
            lstrcpy (tm, tok);
            }
        else if (!_stricmp (tok, "/C") || !_stricmp (tok, "-C"))
            {
            tok = GetCmdToken(cmdline);
            if (!tok)
                {
                Usage();
                return (NULL);
                }
            lstrcpy (cmd, tok);
            }
        else if (!_stricmp (tok, "/RUN") || !_stricmp (tok, "-RUN"))
            {
            // Here only for compatibility with wattdrvr
            }
        else if (!_stricmp (tok, "/D") || !_stricmp (tok, "-D"))
            {
            tok = GetCmdToken(cmdline);
            if (!tok)
                {
                Usage();
                return (NULL);
                }
            if (SymCount == 16)
                {
                MPError (NULL, MB_OK | MB_ICONSTOP, IDS_CANTINIT);
                return (NULL);
                }
            lstrcpy (DefSym[SymCount++], tok);
            }
        else if (!scriptfound)
            {
            lstrcpy (scr, tok);
            scriptfound = -1;
            }
        else
            {
            Usage ();
            return (NULL);
            }
        }

    // If no script name was given, create one using the module file name and
    // replacing its extension with .WTD
    //-----------------------------------------------------------------------
    if (!scriptfound)
        {
        INT     l, i;

        GetModuleFileName (hInst, scr, sizeof(scr));
        l = lstrlen (scr);
        for (i=0; i<=4; i++)
            if (scr[l-i] == '.')
                {
                strcpy (scr+l-i, ".MST");
                break;
                }
        }

    // Okay, we got a valid cmdline and we need to run.  Send the script to
    // the parsing engine.
    //-----------------------------------------------------------------------
    EnsureExt (scr, 80);
    Command = cmd;
    TestMode = tm;
    if (InitParser ())
        {
        // Initialize the scanner, and start the compilation.
        //-------------------------------------------------------------------
        if (BeginScan (scr, CBLoaderImmediate, SymCount, DefPtrs))
            {
            if (!PcodeCompile())
                {
                if (PcodeFixup(0))
                    {
                    PcodeExecute(PE_RUN, NULL);
                    }
                }
            }
        else
            {
            AbortParser();
            MPError (NULL, MB_OK | MB_ICONSTOP, IDS_CANTREAD, (LPSTR)scr);
            }
        }
    else
        MPError (NULL, MB_OK | MB_ICONSTOP, IDS_CANTINIT);
    return (NULL);

}
Exemple #14
0
NS_IMETHODIMP
nsSAXXMLReader::ParseFromStream(nsIInputStream *aStream,
                                const char *aCharset,
                                const char *aContentType)
{
  // Don't call this in the middle of an async parse
  NS_ENSURE_TRUE(!mIsAsyncParse, NS_ERROR_FAILURE);

  NS_ENSURE_ARG(aStream);
  NS_ENSURE_ARG(aContentType);

  // Put the nsCOMPtr out here so we hold a ref to the stream as needed
  nsresult rv;
  nsCOMPtr<nsIInputStream> bufferedStream;
  if (!NS_InputStreamIsBuffered(aStream)) {
    rv = NS_NewBufferedInputStream(getter_AddRefs(bufferedStream),
                                   aStream, 4096);
    NS_ENSURE_SUCCESS(rv, rv);
    aStream = bufferedStream;
  }
 
  rv = EnsureBaseURI();
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsIChannel> parserChannel;
  rv = NS_NewInputStreamChannel(getter_AddRefs(parserChannel), mBaseURI,
                                aStream, nsDependentCString(aContentType));
  if (!parserChannel || NS_FAILED(rv))
    return NS_ERROR_FAILURE;

  if (aCharset)
    parserChannel->SetContentCharset(nsDependentCString(aCharset));

  rv = InitParser(nsnull, parserChannel);
  NS_ENSURE_SUCCESS(rv, rv);

  rv = mListener->OnStartRequest(parserChannel, nsnull);
  if (NS_FAILED(rv))
    parserChannel->Cancel(rv);
  nsresult status;
  parserChannel->GetStatus(&status);
  
  PRUint32 offset = 0;
  while (NS_SUCCEEDED(rv) && NS_SUCCEEDED(status)) {
    PRUint32 available;
    rv = aStream->Available(&available);
    if (rv == NS_BASE_STREAM_CLOSED) {
      rv = NS_OK;
      available = 0;
    }
    if (NS_FAILED(rv)) {
      parserChannel->Cancel(rv);
      break;
    }
    if (! available)
      break; // blocking input stream has none available when done

    rv = mListener->OnDataAvailable(parserChannel, nsnull,
                                    aStream, offset, available);
    if (NS_SUCCEEDED(rv))
      offset += available;
    else
      parserChannel->Cancel(rv);
    parserChannel->GetStatus(&status);
  }
  rv = mListener->OnStopRequest(parserChannel, nsnull, status);
  mListener = nsnull;

  return rv;
}
Exemple #15
0
/// HIFN Loads a function with the given name from the loaded module.
/// HIRET A pointer to the loaded function.
/// HIPAR parser/The parser from which to load the function.
/// HIPAR functionName/The name of the function to be loaded.
void *LoadFunction(SymbolParser *parser, const char *functionName) {
    InitParser(parser);
    
    return GetProcAddress(parser->module, functionName);
}