Ejemplo n.º 1
0
void VipsBitReachability::test(){
  std::function<Machine*(std::string)> get_machine = 
    [](std::string rmm){
    std::stringstream ss(rmm);
    PPLexer lex(ss);
    return new Machine(Parser::p_test(lex));
  };

  /* Test 1: Dekker */
  {
    Machine *m = get_machine
      ("forbidden CS CS\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: x := 1;\n"
       "  read: y = 0;\n"
       "CS:\n"
       "  write: x := 0;\n"
       "  goto L1\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: y := 1;\n"
       "  read: x = 0;\n"
       "CS:\n"
       "  write: y := 0;\n"
       "  goto L1\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#1 Simple Dekker",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 2: Dekker 1 syncwr */
  {
    Machine *m = get_machine
      ("forbidden CS CS\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  syncwr: x := 1;\n"
       "  read: y = 0;\n"
       "CS:\n"
       "  write: x := 0;\n"
       "  goto L1\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: y := 1;\n"
       "  read: x = 0;\n"
       "CS:\n"
       "  write: y := 0;\n"
       "  goto L1\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#2 Simple Dekker",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 3: Dekker 1 syncwr (other process) */
  {
    Machine *m = get_machine
      ("forbidden CS CS\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: x := 1;\n"
       "  read: y = 0;\n"
       "CS:\n"
       "  write: x := 0;\n"
       "  goto L1\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  syncwr: y := 1;\n"
       "  read: x = 0;\n"
       "CS:\n"
       "  write: y := 0;\n"
       "  goto L1\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#3 Simple Dekker",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 4: Dekker syncwr in both processes */
  {
    Machine *m = get_machine
      ("forbidden CS CS\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  syncwr: x := 1;\n"
       "  read: y = 0;\n"
       "CS:\n"
       "  write: x := 0;\n"
       "  goto L1\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  syncwr: y := 1;\n"
       "  read: x = 0;\n"
       "CS:\n"
       "  write: y := 0;\n"
       "  goto L1\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#4 Simple Dekker",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 5: Dekker fence in one process */
  {
    Machine *m = get_machine
      ("forbidden CS CS\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: x := 1;\n"
       "  fence;\n"
       "  read: y = 0;\n"
       "CS:\n"
       "  write: x := 0;\n"
       "  goto L1\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: y := 1;\n"
       "  read: x = 0;\n"
       "CS:\n"
       "  write: y := 0;\n"
       "  goto L1\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#5 Simple Dekker",res->result == REACHABLE);

    delete res;
    delete m;
  }
  /* Test 6: Dekker fence in one process */
  {
    Machine *m = get_machine
      ("forbidden CS CS\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: x := 1;\n"
       "  read: y = 0;\n"
       "CS:\n"
       "  write: x := 0;\n"
       "  goto L1\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: y := 1;\n"
       "  fence;\n"
       "  read: x = 0;\n"
       "CS:\n"
       "  write: y := 0;\n"
       "  goto L1\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#6 Simple Dekker",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 7: Dekker fence in both processes */
  {
    Machine *m = get_machine
      ("forbidden CS CS\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: x := 1;\n"
       "  fence;\n"
       "  read: y = 0;\n"
       "CS:\n"
       "  write: x := 0;\n"
       "  goto L1\n"
       "process\n"
       "text\n"
       "L1:\n"
       "  write: y := 1;\n"
       "  fence;\n"
       "  read: x = 0;\n"
       "CS:\n"
       "  write: y := 0;\n"
       "  goto L1\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#7 Simple Dekker",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

  /* Test 8: IRIW */
  {
    Machine *m = get_machine
      ("forbidden * * END END\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "  write: x := 1\n"
       "process\n"
       "text\n"
       "  write: y := 1\n"
       "process\n"
       "text\n"
       "  read: x = 1;\n"
       "  read: y = 0;\n"
       "  END: nop\n"
       "process\n"
       "text\n"
       "  read: y = 1;\n"
       "  read: x = 0;\n"
       "  END: nop\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#8 IRIW (with R->R relaxation)",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 9: IRIW */
  {
    Machine *m = get_machine
      ("forbidden * * END END\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "  write: x := 1\n"
       "process\n"
       "text\n"
       "  write: y := 1\n"
       "process\n"
       "text\n"
       "  read: x = 1;\n"
       "  fence;\n"
       "  read: y = 0;\n"
       "  END: nop\n"
       "process\n"
       "text\n"
       "  read: y = 1;\n"
       "  fence;\n"
       "  read: x = 0;\n"
       "  END: nop\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#9 IRIW (with R->R fence)",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

  /* Test 10: IRIW */
  {
    Machine *m = get_machine
      ("forbidden * * END END\n"
       "data\n"
       "  x = 0 : [0:1]\n"
       "  y = 0 : [0:1]\n"
       "process\n"
       "text\n"
       "  write: x := 1\n"
       "process\n"
       "text\n"
       "  write: y := 1\n"
       "process\n"
       "registers\n"
       "  $r0 = * : [0:1]\n"
       "text\n"
       "  read: $r0 := x;\n"
       "  if $r0 = 1 then{\n"
       "    read: y = 0;\n"
       "    END: nop\n"
       "  }\n"
       "process\n"
       "registers\n"
       "  $r0 = * : [0:1]\n"
       "text\n"
       "  read: $r0 := y;\n"
       "  if $r0 = 1 then{\n"
       "    read: x = 0;\n"
       "    END: nop\n"
       "  }\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#10 IRIW (with R->R ctrl dependency)",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 11: CAS-lock */
  {
    Machine *m = get_machine
      ("forbidden\n"
       "  BAD *\n"
       "\n"
       "data\n"
       "  l = 0 : [0:1]\n"
       "  x = 0 : [0:1]\n"
       "\n"
       "macro lock()\n"
       "  cas(l,0,1);\n"
       "  fence\n"
       "endmacro\n"
       "\n"
       "macro unlock()\n"
       "  fence;\n"
       "  syncwr: l := 0\n"
       "endmacro\n"
       "\n"
       "process\n"
       "registers\n"
       "  $r0 = 0 : [0:1]\n"
       "text\n"
       "  L0:\n"
       "  lock();\n"
       "  read: $r0 := x;\n"
       "  if $r0 = 1 then goto BAD;\n"
       "  unlock();\n"
       "  goto L0;\n"
       "BAD: nop\n"
       "\n"
       "process\n"
       "text\n"
       "L0:\n"
       "  lock();\n"
       "  write: x := 1;\n"
       "  write: x := 0;\n"
       "  unlock();\n"
       "  goto L0\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#11 CAS-lock (correct)",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

  /* Test 12: CAS-lock */
  {
    Machine *m = get_machine
      ("forbidden\n"
       "  BAD *\n"
       "\n"
       "data\n"
       "  l = 0 : [0:1]\n"
       "  x = 0 : [0:1]\n"
       "\n"
       "macro lock()\n"
       "  cas(l,0,1);\n"
       "  fence\n"
       "endmacro\n"
       "\n"
       "macro unlock()\n"
       "  syncwr: l := 0;\n" /* <- swapped order between syncwr and fence */
       "  fence\n"
       "endmacro\n"
       "\n"
       "process\n"
       "registers\n"
       "  $r0 = 0 : [0:1]\n"
       "text\n"
       "  L0:\n"
       "  lock();\n"
       "  read: $r0 := x;\n"
       "  if $r0 = 1 then goto BAD;\n"
       "  unlock();\n"
       "  goto L0;\n"
       "BAD: nop\n"
       "\n"
       "process\n"
       "text\n"
       "L0:\n"
       "  lock();\n"
       "  write: x := 1;\n"
       "  write: x := 0;\n"
       "  unlock();\n"
       "  goto L0\n"
       );

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#12 CAS-lock (incorrect)",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 13: Syncrd (dekker) */
  {
    Machine *m = get_machine(R"(
forbidden
  CS CS

data
  x = 0 : [0:1]
  y = 0 : [0:1]

process
text
  syncwr: x := 1;
  syncrd: y = 0;
CS: nop

process
text
  syncwr: y := 1;
  syncrd: x = 0;
CS: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#13 Syncrd",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

  /* Test 14: Syncrd (dekker variation) */
  {
    Machine *m = get_machine(R"(
forbidden
  CS CS

data
  x = 0 : [0:1]
  y = 0 : [0:1]

process
text
  syncwr: x := 1;
  syncrd: y = 1;
CS: nop

process
text
  syncwr: y := 1;
  syncrd: x = 0;
CS: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#14 Syncrd",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 15: Syncrd (dekker) */
  {
    Machine *m = get_machine(R"(
forbidden
  CS CS

data
  x = 0 : [0:1]
  y = 0 : [0:1]

process
registers
  $r0 = 0 : [0:1]
text
  syncwr: x := 1;
  syncrd: $r0 := y;
  assume: $r0 = 0;
CS: nop

process
registers
  $r0 = 0 : [0:1]
text
  syncwr: y := 1;
  syncrd: $r0 := x;
  assume: $r0 = 0;
CS: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#15 Syncrd",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

  /* Test 16: Syncrd (dekker variation) */
  {
    Machine *m = get_machine(R"(
forbidden
  CS CS

data
  x = 0 : [0:1]
  y = 0 : [0:1]

process
registers
  $r0 = 0 : [0:1]
text
  syncwr: x := 1;
  syncrd: $r0 := y;
  assume: $r0 = 0;
CS: nop

process
registers
  $r0 = 0 : [0:1]
text
  syncwr: y := 1;
  syncrd: $r0 := x;
  assume: $r0 = 1;
CS: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#16 Syncrd",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 17: Syncrd (dekker) */
  {
    Machine *m = get_machine(R"(
forbidden
  CS CS

data
  x = 0 : [0:1]
  y = 0 : [0:1]

process
text
  write: x := 1;
  syncrd: x = 1;
  syncrd: y = 0;
CS: nop

process
text
  write: y := 1;
  syncrd: y = 1;
  syncrd: x = 0;
CS: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#17 Syncrd (rowe)",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 18: Syncrd (dekker) */
  {
    Machine *m = get_machine(R"(
forbidden
  CS CS

data
  x = 0 : [0:1]
  y = 0 : [0:1]

process
registers
  $r0 = 0 : [0:1]
text
  write: x := 1;
  syncrd: $r0 := x;
  syncrd: y = 0;
CS: nop

process
registers
  $r0 = 0 : [0:1]
text
  write: y := 1;
  syncrd: $r0 := y;
  syncrd: x = 0;
CS: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#18 Syncrd (rowe)",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 19: Syncrd (dekker) */
  {
    Machine *m = get_machine(R"(
forbidden
  CS CS

data
  x = 0 : [0:1]
  y = 0 : [0:1]

process
text
  write: x := 1;
  syncrd: x = 0;
  syncrd: y = 0;
CS: nop

process
text
  write: y := 1;
  syncrd: y = 1;
  syncrd: x = 0;
CS: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#19 Syncrd (rowe)",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

  /* Test 20: Syncrd (dekker) */
  {
    Machine *m = get_machine(R"(
forbidden
  L0 CS CS

data
  x = 0 : [0:1]
  y = 0 : [0:1]
  z = 0 : [0:1]

process
text
  L0: write: z := 0;
  goto L0

process
text
  write: x := 1;
  write: z := 1;
  syncrd: z = 0;
  syncrd: y = 0;
CS: nop

process
text
  write: y := 1;
  write: z := 1;
  syncrd: z = 0;
  syncrd: x = 0;
CS: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#20 Syncrd (rowe)",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 21: Syncrd (dekker) */
  {
    Machine *m = get_machine(R"(
forbidden
  L0 CS CS

data
  x = 0 : [0:1]
  y = 0 : [0:1]
  z = 0 : [0:1]

process
text
  L0: write: z := 0;
  goto L0

process
text
  write: x := 1;
  write: z := 1;
  syncrd: z = 1;
  syncrd: y = 0;
CS: nop

process
text
  write: y := 1;
  write: z := 1;
  syncrd: z = 0;
  syncrd: x = 0;
CS: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#21 Syncrd (rowe)",res->result == REACHABLE);

    delete res;
    delete m;
  }

  /* Test 22: Syncrd (coherence) */
  {
    Machine *m = get_machine(R"(
forbidden
  END END

data
  x = 0 : [0:1]

process
text
  write: x := 1;
END: nop

process
text
  syncrd: x = 1;
  read: x = 0;
END: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#22 Syncrd (coherence)",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

  /* Test 23: Syncrd (coherence) */
  {
    Machine *m = get_machine(R"(
forbidden
  END END

data
  x = 0 : [0:1]

process
text
  write: x := 1;
END: nop

process
text
  syncrd: x = 1;
  syncrd: x = 0;
END: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#23 Syncrd (coherence)",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

  /* Test 24: Syncrd (coherence) */
  {
    Machine *m = get_machine(R"(
forbidden
  END END

data
  x = 0 : [0:1]

process
text
  write: x := 1;
END: nop

process
registers
  $r0 = 0 : [0:1]
text
  syncrd: $r0 := x;
  assume: $r0 = 1;
  read: x = 0;
END: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#24 Syncrd (coherence)",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

  /* Test 25: Syncrd (coherence) */
  {
    Machine *m = get_machine(R"(
forbidden
  END END

data
  x = 0 : [0:1]

process
text
  write: x := 1;
END: nop

process
registers
  $r0 = 0 : [0:1]
text
  syncrd: $r0 := x;
  assume: $r0 = 1;
  syncrd: x = 0;
END: nop
)");

    VipsBitReachability reach;

    Arg arg(*m);
    Result *res = reach.reachability(&arg);
    Test::inner_test("#25 Syncrd (coherence)",res->result == UNREACHABLE);

    delete res;
    delete m;
  }

};
Ejemplo n.º 2
0
TPtrC TfrLex::TrimLeft( const TDesC& aText )
{
TLex lex( aText );
lex.SkipSpaceAndMark();
return lex.Remainder();
}
LOCAL_C void processConfigL()
	{

	// Create a CCrashConfig object, the configuration client-side 
	// object of the CoreDump Server .
    RCoreDumpSession coredumpinterface;

	TInt ret = coredumpinterface.Connect();

	if( KErrNone != ret )
		{
		LOG_MSG2( "requestConfigLoadL():: Could not create a Core Dump configuration object, error=%d", ret );
		User::Leave( ret );
		}

	TUint crashes = 1;

    TInt argc = User::CommandLineLength();
    TPtrC configFile(KNullDesC);	
	HBufC* args = NULL;
    if(argc > 0)
    {
        args = HBufC::NewLC(User::CommandLineLength());
        TPtr argv = args->Des();
	    User::CommandLine(argv);

	    TLex lex(*args);

        while(!lex.Eos())
        {
            if(lex.Get() == '-')
            {
                TChar c = lex.Get();
                if(c == '-')
                {
                    TPtrC16 token = lex.NextToken();
                    c = token[0];
                }

                lex.SkipSpace();
                switch(c)
                {
                case 'c':
                    lex.Val(crashes);
                    break;
                case 'f':
                    configFile.Set(lex.NextToken());
                    break;
                default:
                    User::Leave(KErrArgument);
                }
            }
            lex.SkipSpace();
        }
    }

    TRAPD(err, coredumpinterface.LoadConfigL( configFile ));

    if(err != KErrNone)
    {
	LOG_MSG2("unable to load config file! err:%d\n", err );
    coredumpinterface.Disconnect();
    User::Leave(err);
    }

	LOG_MSG2( "Will wait for %u crashes\n", crashes );

	RProperty crashCountProperty;
	User::LeaveIfError( crashCountProperty.Attach( KCoreDumpServUid, ECrashCount ) );

	TInt crashCount = 0;
	do
		{
		
		User::After(5000000);
		ret = crashCountProperty.Get( crashCount );
		LOG_MSG2( "  crashCountProperty.Get( crashCount )=%d\n", crashCount );
		if ( KErrNone != ret )
			{
			break;
			}
		}
	while( crashes > crashCount );

    crashCountProperty.Close();
	if(args)
        {
        CleanupStack::PopAndDestroy(args);  
        }
    coredumpinterface.Disconnect();
	LOG_MSG( "  returned from CleanupStack::PopAndDestroy( cmd );" );

	}
/**
Sets the Message UID by converting the given string value into an integer.
@param aMessageUid string containing the UID value.
@return KErrNone if the coversion was successful.  Otherwise a system-wide error code will be given.
*/
TInt TMessageFlagInfo::SetMessageUid(const TDesC8& aMessageUid)
	{
	TLex8 lex(aMessageUid);
	return lex.Val(iMessageUid);
	}
Ejemplo n.º 5
0
 TokenType nextTokenType()
 {
     m_currentTokenType = lex(m_currentElement);
     return m_currentTokenType;
 }
// -----------------------------------------------------------------------------
// parse passed data
// ID + RETURN or LEAVE has to be found
// -----------------------------------------------------------------------------
//
TBool CConfigurationHandler::ParseData( TDesC8& aData, 
										CONFIGURATION_ITEM& aItem )
	{
	// get value for ID=
	HBufC8* id = GetTokenValue(aData, KId);

	if( !id )
		{
		RDebug::Print(_L("[TESTPLUGIN] CConfigurationHandler::ParseData ID= not found") );
		delete id;
		return EFalse;
		}

	// store index to action array
	aItem.iActionIndex = FindActionIndex(*id);
	delete id;


	// get value for TYPE=
	HBufC8* type = GetTokenValue(aData, KType);
	if( !type )
		{
		RDebug::Print(_L("[TESTPLUGIN] CConfigurationHandler::ParseData TYPE= not found") );
		delete type;
		return EFalse;
		}
	
	// todo is numeric check when needed
	// get value for RETURN=
	aItem.iIsLeaveValue = EFalse;
	HBufC8* strvalue = GetTokenValue(aData, KReturn);
	if( !strvalue )
		{
		delete strvalue; strvalue = NULL;
		// get value for LEAVE= as return value was not found
		strvalue = GetTokenValue(aData, KLeave);
		aItem.iIsLeaveValue = ETrue;
		}

	if( !strvalue )
		{
		RDebug::Print(_L("[TESTPLUGIN] CConfigurationHandler::ParseData: No RETURN= or LEAVE= found") );
		return EFalse;
		}


	// optional parameter
	HBufC8* persistant = GetTokenValue(aData, KPersistant );
	if( persistant )
		{
		TBool b;
		TLex8 l(*persistant);
		l.Val(b); 
		aItem.iIsPersistant = b;
		}
	else
		{
		aItem.iIsPersistant = EFalse;
		}
	delete persistant;
	
	if( type->Compare(_L8("TInt"))==KErrNone )
		{
		TInt v = 0;
		TLex8 lex(*strvalue);
		lex.Val(v);
		aItem.iValuePtr = new TInt(v); 
		}
	else if( type->Compare(_L8("TUint"))==KErrNone )
		{
		TUint v = 0;
		TLex8 lex(*strvalue);
		lex.Val(v);
		aItem.iValuePtr = new TUint(v); 
		}
	else if( type->Compare(_L8("TUid"))==KErrNone )
		{
		TInt v = 0;
		TLex8 lex(*strvalue);
		lex.Val(v);

		TUid u;
		u.iUid = v;
		aItem.iValuePtr = new TUid(u); 
		}
	else if( type->Compare(_L8("TBool"))==KErrNone )
		{
		TBool b;
		TLex8 l(*strvalue);
		l.Val(b); 
		aItem.iValuePtr = new TBool(b); 
		}
	else if( type->Compare(_L8("TDesC8"))==KErrNone )
		{
		HBufC8* buf = HBufC8::NewL(strvalue->Length()); 
		TPtr8 des = buf->Des();
		des.Append(*strvalue);
		aItem.iValuePtr = buf;
		}
	else if( type->Compare(_L8("CCCPCallParameters"))==KErrNone )
		{
		//CCCPCallParameters		
		}
	else
		{
		RDebug::Print(_L("[TESTPLUGIN] CConfigurationHandler::ParseData: No valid type found") );
		return EFalse;
		}


	delete type;
	delete strvalue;
	
	return ETrue;
	}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
	int i, r;
	struct lexer_state ls;

	/* step 1 */
	init_cpp();

	/* step 2 */
	no_special_macros = 0;
	emit_defines = emit_assertions = 0;

	/* step 3 -- with assertions */
	init_tables(1);

	/* step 4 -- no default include path */
	init_include_path(0);

	/* step 5 -- no need to reset the two emit_* variables set in 2 */
	emit_dependencies = 0;

	/* step 6 -- we work with stdin, this is not a real filename */
	set_init_filename("[stdin]", 0);

	/* step 7 -- we make sure that assertions are on, and pragma are
	   handled */
	init_lexer_state(&ls);
	init_lexer_mode(&ls);
	ls.flags |= HANDLE_ASSERTIONS | HANDLE_PRAGMA | LINE_NUM;

	/* step 8 -- input is from stdin */
	ls.input = stdin;

	/* step 9 -- we do not have any macro to define, but we add any
	   argument as an include path */
	for (i = 1; i < argc; i ++) add_incpath(argv[i]);

	/* step 10 -- we are a lexer and we want CONTEXT tokens */
	enter_file(&ls, ls.flags);

	/* read tokens until end-of-input is reached -- errors (non-zero
	   return values different from CPPERR_EOF) are ignored */
	while ((r = lex(&ls)) < CPPERR_EOF) {
		if (r) {
			/* error condition -- no token was retrieved */
			continue;
		}
		/* we print each token: its numerical value, and its
		   string content; if this is a PRAGMA token, the
		   string content is in fact a compressed token list,
		   that we uncompress and print. */
		if (ls.ctok->type == PRAGMA) {
			unsigned char *c = (unsigned char *)(ls.ctok->name);

			printf("line %ld: <#pragma>\n", ls.line);
			for (; *c; c ++) {
				int t = *c;

				if (STRING_TOKEN(t)) {
					printf("  <%2d>  ", t);
					for (c ++; *c != PRAGMA_TOKEN_END;
						c ++) putchar(*c);
					putchar('\n');
				} else {
					printf("  <%2d>  `%s'\n", t,
						operators_name[t]);
				}
			}
		} else if (ls.ctok->type == CONTEXT) {
			printf("new context: file '%s', line %ld\n",
				ls.ctok->name, ls.ctok->line);
		} else if (ls.ctok->type == NEWLINE) {
			printf("[newline]\n");
		} else {
			printf("line %ld: <%2d>  `%s'\n", ls.ctok->line,
				ls.ctok->type,
				STRING_TOKEN(ls.ctok->type) ? ls.ctok->name
				: operators_name[ls.ctok->type]);
		}
	}
	return 0;
}
void PreprocessorCallback::MacroExpands(const clang::Token& MacroNameTok,
                                        const clang::MacroInfo* MI,
                                        clang::SourceRange Range)
{
    if (disabled)
        return;

    clang::SourceLocation loc = MacroNameTok.getLocation();
    if (!loc.isValid() || !loc.isFileID())
        return;
    clang::SourceManager &sm = annotator.getSourceMgr();
    clang::FileID FID = sm.getFileID(loc);
    if (!annotator.shouldProcess(FID))
        return;

    const char *begin = sm.getCharacterData(Range.getBegin());
    int len = sm.getCharacterData(Range.getEnd()) - begin;
    len += clang::Lexer::MeasureTokenLength(Range.getEnd(), sm, PP.getLangOpts());

    std::string copy(begin, len);
    begin = copy.c_str();
    clang::Lexer lex(loc, PP.getLangOpts(), begin, begin, begin + len);
    std::vector<clang::Token> tokens;
    std::string expansion;

    //Lousely based on code from clang::html::HighlightMacros

    // Lex all the tokens in raw mode, to avoid entering #includes or expanding
    // macros.
    clang::Token tok;
    do {
        lex.LexFromRawLexer(tok);

        // If this is a # at the start of a line, discard it from the token stream.
        // We don't want the re-preprocess step to see #defines, #includes or other
        // preprocessor directives.
        if (tok.is(clang::tok::hash) && tok.isAtStartOfLine())
            continue;

        // If this is a ## token, change its kind to unknown so that repreprocessing
        // it will not produce an error.
        if (tok.is(clang::tok::hashhash))
            tok.setKind(clang::tok::unknown);

        // If this raw token is an identifier, the raw lexer won't have looked up
        // the corresponding identifier info for it.  Do this now so that it will be
        // macro expanded when we re-preprocess it.
        if (tok.is(clang::tok::raw_identifier))
            PP.LookUpIdentifierInfo(tok);

        tokens.push_back(tok);

    } while(!tok.is(clang::tok::eof));

    // Temporarily change the diagnostics object so that we ignore any generated
    // diagnostics from this pass.
    clang::DiagnosticsEngine TmpDiags(PP.getDiagnostics().getDiagnosticIDs(),
#if CLANG_VERSION_MAJOR!=3 || CLANG_VERSION_MINOR>=2
                                      &PP.getDiagnostics().getDiagnosticOptions(),
#endif
                                      new clang::IgnoringDiagConsumer);

    disabled = true;
    clang::DiagnosticsEngine *OldDiags = &PP.getDiagnostics();
    PP.setDiagnostics(TmpDiags);

    PP.EnterTokenStream(tokens.data(), tokens.size(), false, false);

    PP.Lex(tok);
    while(tok.isNot(clang::tok::eof)) {
        // If the tokens were already space separated, or if they must be to avoid
        // them being implicitly pasted, add a space between them.
        if (tok.hasLeadingSpace())
            expansion += ' ';
           // ConcatInfo.AvoidConcat(PrevPrevTok, PrevTok, Tok)) //FIXME
        // Escape any special characters in the token text.
        expansion += PP.getSpelling(tok);
        PP.Lex(tok);
    }

    PP.setDiagnostics(*OldDiags);
    disabled = false;

    expansion = Generator::escapeAttr(expansion);

    clang::SourceLocation defLoc = MI->getDefinitionLoc();
    clang::FileID defFID = sm.getFileID(defLoc);
    std::string link;
    if (defFID != FID)
        link = annotator.pathTo(FID, defFID);
    std::string tag = "class=\"macro\" href=\"" % link % "#" % llvm::Twine(sm.getExpansionLineNumber(defLoc)).str()
                    % "\" title=\"" % expansion % "\"";
    annotator.generator(FID).addTag("a", tag, sm.getFileOffset(loc), MacroNameTok.getLength());
}
Ejemplo n.º 9
0
void SEditorColourSet::LoadAvailableSets()
{
    // no need for syntax highlighting if batch building
    if (Manager::IsBatchBuild())
        return;

    //?EditorLexerLoader lex(this);
    EditorLexerLoader lex((EditorColourSet*)this);
    wxDir dir;
    wxString filename;
    FileManager *fm = FileManager::Get();
    std::list<LoaderBase*> loaders;
    int count = 0;

    // user paths first
    wxString path = ConfigManager::GetFolder(sdDataUser) + _T("/lexers/");
    if (dir.Open(path))
    {
        #if wxCHECK_VERSION(2, 9, 0)
        Manager::Get()->GetLogManager()->Log(F(_("Scanning for lexers in %s..."), path.wx_str()));
        #else
        Manager::Get()->GetLogManager()->Log(F(_("Scanning for lexers in %s..."), path.c_str()));
        #endif
        bool ok = dir.GetFirst(&filename, _T("lexer_*.xml"), wxDIR_FILES);
        while(ok)
        {
            loaders.push_back(fm->Load(path + filename));
            ok = dir.GetNext(&filename);
            ++count;
        }
        Manager::Get()->GetLogManager()->Log(F(_("Found %d lexers"), count));
        count = 0;
    }

    // global paths next
    path = ConfigManager::GetFolder(sdDataGlobal) + _T("/lexers/");
    if (dir.Open(path))
    {
        #if wxCHECK_VERSION(2, 9, 0)
        Manager::Get()->GetLogManager()->Log(F(_("Scanning for lexers in %s..."), path.wx_str()));
        #else
        Manager::Get()->GetLogManager()->Log(F(_("Scanning for lexers in %s..."), path.c_str()));
        #endif
        bool ok = dir.GetFirst(&filename, _T("lexer_*.xml"), wxDIR_FILES);
        while(ok)
        {
            loaders.push_back(fm->Load(path + filename));
            ok = dir.GetNext(&filename);
            ++count;
        }
        Manager::Get()->GetLogManager()->Log(F(_("Found %d lexers"), count));
    }

    for(std::list<LoaderBase*>::iterator it = loaders.begin(); it != loaders.end(); ++it)
        lex.Load(*it);

    ::Delete(loaders);


    for (SOptionSetsMap::iterator it = m_Sets.begin(); it != m_Sets.end(); ++it)
    {
        wxString lang = it->second.m_Langs;
        if (lang.IsEmpty())
            continue;

        // keep the original filemasks and keywords, so we know what needs saving later
        for (int i = 0; i <= wxSCI_KEYWORDSET_MAX; ++i)
        {
            it->second.m_originalKeywords[i] = it->second.m_Keywords[i];
        }
        it->second.m_originalFileMasks = it->second.m_FileMasks;

        // remove old settings, no longer used
        unsigned int i = 0;
        while (i < it->second.m_Colours.GetCount())
        {
            SOptionColour* opt = it->second.m_Colours.Item(i);
            // valid values are:
            if (opt->value < 0 &&               // styles >= 0
                opt->value != cbSELECTION &&    // cbSELECTION
                opt->value != cbHIGHLIGHT_LINE) // cbHIGHLIGHT_LINE
            {
                it->second.m_Colours.Remove(opt);
                delete opt;
            }
            else
                ++i;
        }
    }
}
Ejemplo n.º 10
0
int
extoken_fn(register Expr_t* ex)
{
	register int	c;
	register char*	s;
	register int	q;
	char*		e;

	if (ex->eof || ex->errors)
		return 0;
 again:
	for (;;) switch (c = lex(ex))
	{
	case 0:
		goto eof;
	case '/':
		switch (q = lex(ex))
		{
		case '*':
			for (;;) switch (lex(ex))
			{
			case '\n':
				BUMP (error_info.line);
				continue;
			case '*':
				switch (lex(ex))
				{
				case 0:
					goto eof;
				case '\n':
					BUMP (error_info.line);
					break;
				case '*':
					exunlex(ex, '*');
					break;
				case '/':
					goto again;
				}
				break;
			}
			break;
		case '/':
			while ((c = lex(ex)) != '\n')
				if (!c)
					goto eof;
			break;
		default:
			goto opeq;
		}
		/*FALLTHROUGH*/
	case '\n':
		BUMP (error_info.line);
		/*FALLTHROUGH*/
	case ' ':
	case '\t':
		break;
	case '(':
	case '{':
	case '[':
		ex->input->nesting++;
		return exlval.op = c;
	case ')':
	case '}':
	case ']':
		ex->input->nesting--;
		return exlval.op = c;
	case '+':
	case '-':
		if ((q = lex(ex)) == c)
			return exlval.op = c == '+' ? INC : DEC;
		goto opeq;
	case '*':
	case '%':
	case '^':
		q = lex(ex);
	opeq:
		exlval.op = c;
		if (q == '=')
			c = '=';
		else if (q == '%' && c == '%')
		{
			if (ex->input->fp)
				ex->more = (const char*)ex->input->fp;
			else ex->more = ex->input->sp;
			goto eof;
		}
		else exunlex(ex, q);
		return c;
	case '&':
	case '|':
		if ((q = lex(ex)) == '=')
		{
			exlval.op = c;
			return '=';
		}
		if (q == c)
			c = c == '&' ? AND : OR;
		else exunlex(ex, q);
		return exlval.op = c;
	case '<':
	case '>':
		if ((q = lex(ex)) == c)
		{
			exlval.op = c = c == '<' ? LS : RS;
			if ((q = lex(ex)) == '=')
				c = '=';
			else exunlex(ex, q);
			return c;
		}
		goto relational;
	case '=':
	case '!':
		q = lex(ex);
	relational:
		if (q == '=') switch (c)
		{
		case '<':
			c = LE;
			break;
		case '>':
			c = GE;
			break;
		case '=':
			c = EQ;
			break;
		case '!':
			c = NE;
			break;
		}
		else exunlex(ex, q);
		return exlval.op = c;
	case '#':
		if (!ex->linewrap && !(ex->disc->flags & EX_PURE))
		{
			s = ex->linep - 1;
			while (s > ex->line && isspace(*(s - 1)))
				s--;
			if (s == ex->line)
			{
				switch (extoken_fn(ex))
				{
				case DYNAMIC:
				case ID:
				case NAME:
					s = exlval.id->name;
					break;
				default:
					s = "";
					break;
				}
				if (streq(s, "include"))
				{
					if (extoken_fn(ex) != STRING)
						exerror("#%s: string argument expected", s);
					else if (!expush(ex, exlval.string, 1, NiL, NiL))
					{
						setcontext(ex);
						goto again;
					}
				}
				else exerror("unknown directive");
			}
		}
		return exlval.op = c;
	case '\'':
	case '"':
		q = c;
		sfstrset(ex->tmp, 0);
		ex->input->nesting++;
		while ((c = lex(ex)) != q)
		{
			if (c == '\\')
			{
				sfputc(ex->tmp, c);
				c = lex(ex);
			}
			if (!c)
			{
				exerror("unterminated %c string", q);
				goto eof;
			}
			if (c == '\n')
			{
				BUMP (error_info.line);
			}
			sfputc(ex->tmp, c);
		}
		ex->input->nesting--;
		s = sfstruse(ex->tmp);
		if (q == '"' || (ex->disc->flags & EX_CHARSTRING))
		{
			if (!(exlval.string = vmstrdup(ex->vm, s)))
				goto eof;
			stresc(exlval.string);
			return STRING;
		}
		exlval.integer = chrtoi(s);
		return INTEGER;
	case '.':
		if (isdigit(c = lex(ex)))
		{
			sfstrset(ex->tmp, 0);
			sfputc(ex->tmp, '0');
			sfputc(ex->tmp, '.');
			goto floating;
		}
		exunlex(ex, c);
		return exlval.op = '.';
	case '0': case '1': case '2': case '3': case '4':
	case '5': case '6': case '7': case '8': case '9':
		sfstrset(ex->tmp, 0);
		sfputc(ex->tmp, c);
		q = INTEGER;
		if ((c = lex(ex)) == 'x' || c == 'X')
		{
			sfputc(ex->tmp, c);
			for (;;)
			{
				switch (c = lex(ex))
				{
				case '0': case '1': case '2': case '3': case '4':
				case '5': case '6': case '7': case '8': case '9':
				case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': 
				case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': 
					sfputc(ex->tmp, c);
					continue;
				}
				break;
			}
		}
		else
		{
			while (isdigit(c))
			{
				sfputc(ex->tmp, c);
				c = lex(ex);
			}
			if (c == '#')
			{
				sfputc(ex->tmp, c);
				/* s = sfstruse(ex->tmp); */
				/* b = strtol(s, NiL, 10); */
				do
				{
					sfputc(ex->tmp, c);
				} while (isalnum(c = lex(ex)));
			}
			else
			{
				if (c == '.')
				{
				floating:
					q = FLOATING;
					sfputc(ex->tmp, c);
					while (isdigit(c = lex(ex)))
						sfputc(ex->tmp, c);
				}
				if (c == 'e' || c == 'E')
				{
					q = FLOATING;
					sfputc(ex->tmp, c);
					if ((c = lex(ex)) == '-' || c == '+')
					{
						sfputc(ex->tmp, c);
						c = lex(ex);
					}
					while (isdigit(c))
					{
						sfputc(ex->tmp, c);
						c = lex(ex);
					}
				}
			}
		}
		s = sfstruse(ex->tmp);
		if (q == FLOATING)
			exlval.floating = strtod(s, &e);
		else
		{
			if (c == 'u' || c == 'U')
			{
				q = UNSIGNED;
				c = lex(ex);
				exlval.integer = strToL(s, &e);
			}
			else
				exlval.integer = strToL(s, &e);
			if (*e)
			{
				*--e = 1;
				exlval.integer *= strton(e, &e, NiL, 0);
			}
		}
		exunlex(ex, c);
		if (*e || isalpha(c) || c == '_' || c == '$')
		{
			exerror("%s: invalid numeric constant", s);
			goto eof;
		}
		return q;
	default:
		if (isalpha(c) || c == '_' || c == '$')
		{
			sfstrset(ex->tmp, 0);
			sfputc(ex->tmp, c);
			while (isalnum(c = lex(ex)) || c == '_' || c == '$')
				sfputc(ex->tmp, c);
			exunlex(ex, c);
			s = sfstruse(ex->tmp);
			if (!(exlval.id = (Exid_t*)dtmatch(ex->symbols, s)))
			{
				if (!(exlval.id = newof(0, Exid_t, 1, strlen(s) - EX_NAMELEN + 1)))
				{
					exerror("out of space");
					goto eof;
				}
				strcpy(exlval.id->name, s);
				exlval.id->lex = NAME;
				dtinsert((ex->formals || !ex->symbols->view) ? ex->symbols : ex->symbols->view, exlval.id);
			}

			/*
			 * lexical analyzer state controlled by the grammar
			 */

			switch (exlval.id->lex)
			{
			case DECLARE:
				if (exlval.id->index == CHAR)
				{
					/*
					 * `char*' === `string'
					 * the * must immediately follow char
					 */

					if (c == '*')
					{
						lex(ex);
						exlval.id = id_string;
					}
				}
				break;
			case NAME:
				/*
				 * action labels are disambiguated from ?:
				 * through the expr.nolabel grammar hook
				 * the : must immediately follow labels
				 */

				if (c == ':' && !expr.nolabel)
					return LABEL;
				break;
			case PRAGMA:
				/*
				 * user specific statement stripped and
				 * passed as string
				 */

				{
					int	b;
					int	n;
					int	pc = 0;
					int	po;
					int	t;

					/*UNDENT...*/
	sfstrset(ex->tmp, 0);
	b = 1;
	n = 0;
	po = 0;
	t = 0;
	for (c = t = lex(ex);; c = lex(ex))
	{
		switch (c)
		{
		case 0:
			goto eof;
		case '/':
			switch (q = lex(ex))
			{
			case '*':
				for (;;)
				{
					switch (lex(ex))
					{
					case '\n':
						BUMP (error_info.line);
						continue;
					case '*':
						switch (lex(ex))
						{
						case 0:
							goto eof;
						case '\n':
							BUMP (error_info.line);
							continue;
						case '*':
							exunlex(ex, '*');
							continue;
						case '/':
							break;
						default:
							continue;
						}
						break;
					}
					if (!b++)
						goto eof;
					sfputc(ex->tmp, ' ');
					break;
				}
				break;
			case '/':
				while ((c = lex(ex)) != '\n')
					if (!c)
						goto eof;
				BUMP (error_info.line);
				b = 1;
				sfputc(ex->tmp, '\n');
				break;
			default:
				b = 0;
				sfputc(ex->tmp, c);
				sfputc(ex->tmp, q);
				break;
			}
			continue;
		case '\n':
			BUMP (error_info.line);
			b = 1;
			sfputc(ex->tmp, '\n');
			continue;
		case ' ':
		case '\t':
			if (!b++)
				goto eof;
			sfputc(ex->tmp, ' ');
			continue;
		case '(':
		case '{':
		case '[':
			b = 0;
			if (!po)
			{
				switch (po = c)
				{
				case '(':
					pc = ')';
					break;
				case '{':
					pc = '}';
					break;
				case '[':
					pc = ']';
					break;
				}
				n++;
			}
			else if (c == po)
				n++;
			sfputc(ex->tmp, c);
			continue;
		case ')':
		case '}':
		case ']':
			b = 0;
			if (!po)
			{
				exunlex(ex, c);
				break;
			}
			sfputc(ex->tmp, c);
			if (c == pc && --n <= 0)
			{
				if (t == po)
					break;
				po = 0;
			}
			continue;
		case ';':
			b = 0;
			if (!n)
				break;
			sfputc(ex->tmp, c);
			continue;
		case '\'':
		case '"':
			b = 0;
			sfputc(ex->tmp, c);
			ex->input->nesting++;
			q = c;
			while ((c = lex(ex)) != q)
			{
				if (c == '\\')
				{
					sfputc(ex->tmp, c);
					c = lex(ex);
				}
				if (!c)
				{
					exerror("unterminated %c string", q);
					goto eof;
				}
				if (c == '\n')
				{
					BUMP (error_info.line);
				}
				sfputc(ex->tmp, c);
			}
			ex->input->nesting--;
			continue;
		default:
			b = 0;
			sfputc(ex->tmp, c);
			continue;
		}
		break;
	}
	(*ex->disc->reff)(ex, NiL, exlval.id, NiL, sfstruse(ex->tmp), 0, ex->disc);

					/*..INDENT*/
				}
				goto again;
			}
			return exlval.id->lex;
		}
		return exlval.op = c;
	}
 eof:
	ex->eof = 1;
	return exlval.op = ';';
}
Ejemplo n.º 11
0
// ---------------------------------------------------------
// TCodParser::AttrLineL()
// ---------------------------------------------------------
//
TBool TCodParser::AttrLineL(CMediaObjectData *& aMediaObject)
    {
    SkipWhiteSpace();  // Skip lines which contain only WS and LF at the end.
    while ( IsEndOfLine() )
        {
        NextLine();
        SkipWhiteSpace();
        }
    TBool ok( ETrue );
    if ( iCurP < iEndP )
        {
        // Still has something to read.
        switch( AttrName() )
            {
            case ECodName:
                {
                if ( Colon() )
                    {
                    ok = aMediaObject->SetNameL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }

            case ECodVendor:
                {
                if ( Colon() )
                    {
                    ok = iData->SetVendorL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }

            case ECodDescription:
                {
                if ( Colon() )
                    {
                    ok = aMediaObject->SetDescriptionL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }

            case ECodSize:
                {
                if ( Colon() )
                    {
                    // Parse as TUint - negative not allowed.
                    TUint size;
                    TLex lex( AttrValue() );
                    if ( !lex.Val( size ) )
                        {
                        aMediaObject->SetSize( size );
                        }
                    else
                        {
                        ok = EFalse;
                        }
                    EndOfLine();
                    }
                break;
                }

            case ECodInstallNotify:
                {
                if ( Colon() )
                    {
                    ok = aMediaObject->SetInstallNotifyL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }

            case ECodNextUrl:
                {
                if ( Colon() )
                    {
                    ok = iData->SetNextUrlL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }

            case ECodNextUrlAtError:
                {
                if ( Colon() )
                    {
                    ok = iData->SetNextUrlAtErrorL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }

            case ECodInfoUrl:
                {
                if ( Colon() )
                    {
                    ok = aMediaObject->SetInfoUrlL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }

            case ECodPrice:
                {
                if ( Colon() )
                    {
                    ok = aMediaObject->SetPriceL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }

            case ECodIcon:
                {
                if ( Colon() )
                    {
                    ok = aMediaObject->SetIconL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }
            case ECodType:
                {
                if ( Colon() )
                    {
                    ok = aMediaObject->SetTypeL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }
            case ECodUrl:
                {
                if ( Colon() )
                    {
                    ok = aMediaObject->SetUrlL( AttrValue() );
                    EndOfLine();
                    }
                break;
                }

            case ECodUnknownAttr:
                {
                // Name unknown; check colon anyway (syntax check).
                ok = Colon();
                // Rest of the line goes unchecked.
                break;
                }

            default:
                {
                // Unexpected value.
                CodPanic( ECodInternal );
                }

            }
        if ( !ok )
            {
            Error( KErrCodInvalidDescriptor );
            }
        NextLine();     // Step past LF.
        return ETrue;   // More lines to go.
        }
    else
        {
        // EOF reached; done.
        // Note: not expecting EOF in any other place than here (well-formed
        // COD has complete attrlines. If EOF is found some other place, it
        // is a syntax error.
        return EFalse;
        }
    }
Ejemplo n.º 12
0
TVerdict CForceRemove::doTestStepL()
	{

#ifndef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK
	// Wait up to 30 seconds to ensure both SWIS and the sisregistry server
	// have shut down
	_LIT(KSisRegistryServerName, "!SisRegistryServer");
	_LIT(KInstallServerName, "!InstallServer");
	TInt delaytime = 30; 

	while (delaytime-- > 0)
		{
		TFullName serverName;
		TFindServer find(KInstallServerName);
		if (KErrNotFound == find.Next(serverName))
			{
			find.Find(KSisRegistryServerName);
			if (KErrNotFound == find.Next(serverName))
				{
				break;
				}
			}
		User::After(1000000); // wait a second until the next test
		}
#endif // SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK
	
	TPtrC name;
	RTestUtilSessionSwi testutil;
	User::LeaveIfError(testutil.Connect());
	CleanupClosePushL(testutil);
	
	// If file deletion fails we'll try moving the file to a temp directory
	// for another process to clean up later.
	
	TTime currentTime;
	currentTime.UniversalTime();
	
	_LIT(KTempPathFormat, "\\temp\\%Lu");
	TDriveUnit sysDrive (RFs::GetSystemDrive());
	TBuf<128> tempPathFormat(sysDrive.Name());
	tempPathFormat.Append(KTempPathFormat);
	
	TFileName targetPath;
	targetPath.Format(tempPathFormat, currentTime.Int64());
	
	_LIT(KNumFiles, "numfiles");

#ifdef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK
	RArray<TUint> removeUids;
	CleanupClosePushL(removeUids);
#endif

	TInt num(0);
	GetIntFromConfig(ConfigSection(), KNumFiles, num);

	// Get the file names and use testutil to remove them
	for (TInt i = 0; i < num; ++i)
		{
		_LIT(KFile, "file");
		TBuf<32> key(KFile);
		key.AppendNum(i);
		
		if (!GetStringFromConfig(ConfigSection(), key, name))
			continue;
			
		INFO_PRINTF2(_L("ForceRemove - trying to delete file %S"), &name);

		TInt err = testutil.Delete(name);
		if (err != KErrNone && err != KErrNotFound && err != KErrPathNotFound)
			{
			INFO_PRINTF3(_L("RTestUtilSessionSwi::Delete(%S) returned %d, attempting move instead."), &name, err);
			TFileName source(name);
			TParsePtr parse(source);
			TFileName dest(targetPath);
			dest.Append(parse.Path());
			if (parse.DrivePresent())
				{
				dest[0] = source[0];
				}
			testutil.MkDirAll(dest);
			dest.Append(parse.NameAndExt());

			err = testutil.Move(source, dest);
			
			if (err != KErrNone)
				{
				INFO_PRINTF4(_L("Attempt to move from %S to %S returned %d"),
							&source, &dest, err);
				}
			}
#ifdef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK
		_LIT(KRegistryPath, "\\sys\\install\\sisregistry\\");
		if (name.FindF(KRegistryPath) == KErrNotFound)
			continue;

		// Extract the uid and add it to our list
		TInt slashPos = name.LocateReverse('\\');
		TPtrC ptrUid = name.Mid(slashPos + 1);
		if (ptrUid.Length() != 8)
			continue;

		TUint uid = 0; 
		TLex lex(ptrUid);
		if (lex.Val(uid, EHex) == KErrNone)
			{
			removeUids.InsertInOrder(uid);	// Will not allow duplicates
			}
#endif
		}

#ifdef SYMBIAN_UNIVERSAL_INSTALL_FRAMEWORK
	// Use the sisregistry folder uid to remove the package entries from SCR
	// Note that we remove packages present in ROM too due to two reasons:
	// This is exactly what ForceRemove used to do (delete entire registry folder containing ALL reg files)
	// After deleting an entry SWIRegistry re-registers ROM apps (missing ones)
	TInt count = removeUids.Count();

	RSisRegistryAccessSession regWrite;
	TInt err = regWrite.Connect();
	User::LeaveIfError(err);
	CleanupClosePushL(regWrite);

	Swi::RSisRegistrySession regRead;
	User::LeaveIfError(regRead.Connect());
	CleanupClosePushL(regRead);
	for (TInt i = 0; i < count; ++i)
		{ 
		TUid uid = TUid::Uid(removeUids[i]);
		Swi::RSisRegistryEntry entry;
		CleanupClosePushL(entry);
		if (entry.Open(regRead, uid) == KErrNone)
			{
			// Get its augmentations
			RPointerArray<Swi::CSisRegistryPackage> augmentations;
			CleanupResetAndDestroy<RPointerArray<Swi::CSisRegistryPackage> >::PushL(augmentations);
			
			entry.AugmentationsL(augmentations);
			TInt augCount = augmentations.Count();
			for (TInt j = 0; j < augCount; ++j)
				{
				// Remove it
				TInt dummyTime;
				regWrite.DeleteEntryL(*augmentations[j], dummyTime);
				}
			// Finally remove the base package entry
			Swi::CSisRegistryPackage* package = entry.PackageL();
			CleanupStack::PushL(package);
			TInt dummyTime;
			regWrite.DeleteEntryL(*package,dummyTime);
			CleanupStack::PopAndDestroy(2, &augmentations); // package
			}
		CleanupStack::PopAndDestroy(&entry);
		}
	CleanupStack::PopAndDestroy(3, &removeUids);	// regWrite, regRead
#endif
	
	CleanupStack::PopAndDestroy(&testutil);
	
	return EPass;
	}
Ejemplo n.º 13
0
void TestLex::test_tokenizefile_test2()
{
    Lex lex(m_SymbolTable);
    TokenList *tokens = lex.tokenizeFile("test2.cpp");
}
Ejemplo n.º 14
0
void TestLex::test_tokenizeFile_nullString_emptyVector()
{
    Lex lex(m_SymbolTable);
    TokenList *tokens = lex.tokenizeFile(NULL);
    assert(tokens->length() == 0);
}
Ejemplo n.º 15
0
static JSON*
jsonobj(Lex *l)
{
	JSON *j;
	JSONEl *e;
	JSONEl **ln;
	int obj;

	if((j = mallocz(sizeof(*j), 1)) == nil)
		return nil;

	if(lex(l) < 0){
error:
		free(j);
		return nil;
	}
	switch(l->t){
	case TEOF:
		werrstr("json: unexpected eof");
		goto error;
	case TNULL:
		j->t = JSONNull;
		break;
	case TTRUE:
		j->t = JSONBool;
		j->n = 1;
		break;
	case TFALSE:
		j->t = JSONBool;
		j->n = 0;
		break;
	case TSTRING:
		j->t = JSONString;
		if((j->s = strdup(l->buf)) == nil)
			goto error;
		break;
	case TNUM:
		j->t = JSONNumber;
		j->n = l->n;
		break;
	case '{':
	case '[':
		obj = l->t == '{';
		ln = &j->first;
		e = nil;
		if(obj){
			j->t = JSONObject;
			if(lex(l) < 0)
				goto abort;
			if(l->t == '}')
				return j;
			goto firstobj;
		}else{
			j->t = JSONArray;
			l->canjmp = 1;
			if(setjmp(l->jmp) > 0){
				free(e);
				return j;
			}
		}
		for(;;){
			if(obj){
				if(lex(l) < 0)
					goto abort;
			firstobj:
				if(l->t != TSTRING){
					werrstr("json: syntax error, not string");
					goto abort;
				}
				if((e = mallocz(sizeof(*e), 1)) == nil)
					goto abort;
				e->name = strdup(l->buf);
				if(e->name == nil || lex(l) < 0){
					free(e);
					goto abort;
				}
				if(l->t != ':'){
					werrstr("json: syntax error, not colon");
					free(e);
					goto abort;
				}
			}else{
				if((e = mallocz(sizeof(*e), 1)) == nil)
					goto abort;
			}
			e->val = jsonobj(l);
			if(e->val == nil){
				free(e);
				goto abort;
			}
			*ln = e;
			ln = &e->next;
			if(lex(l) < 0)
				goto abort;
			if(l->t == (obj ? '}' : ']'))
				break;
			if(l->t != ','){
				werrstr("json: syntax error, neither comma nor ending paren");
				goto abort;
			}
		}
		break;
	abort:
		jsonfree(j);
		return nil;
	case ']': case '}': case ',': case ':':
		werrstr("json: unexpected %C", l->t);
		goto error;
	default:
		werrstr("json: the front fell off");
		goto error;
	}
	return j;
}
int main ()
{
    char buffer [] = "int buffer [1024]";
    return !lex (buffer, buffer + sizeof (buffer));
}
Ejemplo n.º 17
0
static void next(void)
{
	g.lookahead = lex();
}
Ejemplo n.º 18
0
Archivo: lex.c Proyecto: coyizumi/cs111
/*
 * Execute a single command.
 * Command functions return 0 for success, 1 for error, and -1
 * for abort.  A 1 or -1 aborts a load or source.  A -1 aborts
 * the interactive command loop.
 * Contxt is non-zero if called while composing mail.
 */
int
execute(char linebuf[], int contxt)
{
	char word[LINESIZE];
	char *arglist[MAXARGC];
	const struct cmd *com;
	char *cp, *cp2;
	int c, muvec[2];
	int e = 1;

	/*
	 * Strip the white space away from the beginning
	 * of the command, then scan out a word, which
	 * consists of anything except digits and white space.
	 *
	 * Handle ! escapes differently to get the correct
	 * lexical conventions.
	 */

	for (cp = linebuf; isspace((unsigned char)*cp); cp++)
		;
	if (*cp == '!') {
		if (sourcing) {
			printf("Can't \"!\" while sourcing\n");
			goto out;
		}
		shell(cp+1);
		return (0);
	}
	cp2 = word;
	while (*cp != '\0' && strchr(" \t0123456789$^.:/-+*'\"", *cp) == NULL)
		*cp2++ = *cp++;
	*cp2 = '\0';

	/*
	 * Look up the command; if not found, bitch.
	 * Normally, a blank command would map to the
	 * first command in the table; while sourcing,
	 * however, we ignore blank lines to eliminate
	 * confusion.
	 */

	if (sourcing && *word == '\0')
		return (0);
	com = lex(word);
	if (com == NULL) {
		printf("Unknown command: \"%s\"\n", word);
		goto out;
	}

	/*
	 * See if we should execute the command -- if a conditional
	 * we always execute it, otherwise, check the state of cond.
	 */

	if ((com->c_argtype & F) == 0)
		if ((cond == CRCV && !rcvmode) || (cond == CSEND && rcvmode))
			return (0);

	/*
	 * Process the arguments to the command, depending
	 * on the type he expects.  Default to an error.
	 * If we are sourcing an interactive command, it's
	 * an error.
	 */

	if (!rcvmode && (com->c_argtype & M) == 0) {
		printf("May not execute \"%s\" while sending\n",
		    com->c_name);
		goto out;
	}
	if (sourcing && com->c_argtype & I) {
		printf("May not execute \"%s\" while sourcing\n",
		    com->c_name);
		goto out;
	}
	if (readonly && com->c_argtype & W) {
		printf("May not execute \"%s\" -- message file is read only\n",
		   com->c_name);
		goto out;
	}
	if (contxt && com->c_argtype & R) {
		printf("Cannot recursively invoke \"%s\"\n", com->c_name);
		goto out;
	}
	switch (com->c_argtype & ~(F|P|I|M|T|W|R)) {
	case MSGLIST:
		/*
		 * A message list defaulting to nearest forward
		 * legal message.
		 */
		if (msgvec == 0) {
			printf("Illegal use of \"message list\"\n");
			break;
		}
		if ((c = getmsglist(cp, msgvec, com->c_msgflag)) < 0)
			break;
		if (c  == 0) {
			*msgvec = first(com->c_msgflag, com->c_msgmask);
			msgvec[1] = 0;
		}
		if (*msgvec == 0) {
			printf("No applicable messages\n");
			break;
		}
		e = (*com->c_func)(msgvec);
		break;

	case NDMLIST:
		/*
		 * A message list with no defaults, but no error
		 * if none exist.
		 */
		if (msgvec == 0) {
			printf("Illegal use of \"message list\"\n");
			break;
		}
		if (getmsglist(cp, msgvec, com->c_msgflag) < 0)
			break;
		e = (*com->c_func)(msgvec);
		break;

	case STRLIST:
		/*
		 * Just the straight string, with
		 * leading blanks removed.
		 */
		while (isspace((unsigned char)*cp))
			cp++;
		e = (*com->c_func)(cp);
		break;

	case RAWLIST:
		/*
		 * A vector of strings, in shell style.
		 */
		if ((c = getrawlist(cp, arglist,
		    sizeof(arglist) / sizeof(*arglist))) < 0)
			break;
		if (c < com->c_minargs) {
			printf("%s requires at least %d arg(s)\n",
			    com->c_name, com->c_minargs);
			break;
		}
		if (c > com->c_maxargs) {
			printf("%s takes no more than %d arg(s)\n",
			    com->c_name, com->c_maxargs);
			break;
		}
		e = (*com->c_func)(arglist);
		break;

	case NOLIST:
		/*
		 * Just the constant zero, for exiting,
		 * eg.
		 */
		e = (*com->c_func)(0);
		break;

	default:
		errx(1, "Unknown argtype");
	}

out:
	/*
	 * Exit the current source file on
	 * error.
	 */
	if (e) {
		if (e < 0)
			return (1);
		if (loading)
			return (1);
		if (sourcing)
			unstack();
		return (0);
	}
	if (com == NULL)
		return (0);
	if (value("autoprint") != NULL && com->c_argtype & P)
		if ((dot->m_flag & MDELETED) == 0) {
			muvec[0] = dot - &message[0] + 1;
			muvec[1] = 0;
			type(muvec);
		}
	if (!sourcing && (com->c_argtype & T) == 0)
		sawcom = 1;
	return (0);
}
Ejemplo n.º 19
0
static void
backeval(struct blk_buf *bb, struct Strbuf *word, Char *cp, int literal)
{
    ssize_t icnt;
    Char c, *ip;
    struct command faket;
    int    hadnl;
    int     pvec[2], quoted;
    Char   *fakecom[2], ibuf[BUFSIZE];
    char    tibuf[BUFSIZE];

    hadnl = 0;
    icnt = 0;
    quoted = (literal || (cp[0] & QUOTE)) ? QUOTE : 0;
    faket.t_dtyp = NODE_COMMAND;
    faket.t_dflg = F_BACKQ;
    faket.t_dlef = 0;
    faket.t_drit = 0;
    faket.t_dspr = 0;
    faket.t_dcom = fakecom;
    fakecom[0] = STRfakecom1;
    fakecom[1] = 0;

    /*
     * We do the psave job to temporarily change the current job so that the
     * following fork is considered a separate job.  This is so that when
     * backquotes are used in a builtin function that calls glob the "current
     * job" is not corrupted.  We only need one level of pushed jobs as long as
     * we are sure to fork here.
     */
    psavejob();
    cleanup_push(&faket, psavejob_cleanup); /* faket is only a marker */

    /*
     * It would be nicer if we could integrate this redirection more with the
     * routines in sh.sem.c by doing a fake execute on a builtin function that
     * was piped out.
     */
    mypipe(pvec);
    cleanup_push(&pvec[0], open_cleanup);
    cleanup_push(&pvec[1], open_cleanup);
    if (pfork(&faket, -1) == 0) {
	jmp_buf_t osetexit;
	struct command *t;
	size_t omark;

	xclose(pvec[0]);
	(void) dmove(pvec[1], 1);
	(void) dmove(SHDIAG,  2);
	initdesc();
	closem();
	arginp = cp;
	for (arginp = cp; *cp; cp++) {
	    *cp &= TRIM;
	    if (is_set(STRcsubstnonl) && (*cp == '\n' || *cp == '\r'))
		*cp = ' ';
	}

        /*
	 * In the child ``forget'' everything about current aliases or
	 * eval vectors.
	 */
	alvec = NULL;
	evalvec = NULL;
	alvecp = NULL;
	evalp = NULL;

	omark = cleanup_push_mark();
	getexit(osetexit);
	for (;;) {
	    (void) setexit();
	    justpr = 0;
	    
	    if (haderr) {
		/* unwind */
		doneinp = 0;
		cleanup_pop_mark(omark);
		resexit(osetexit);
		reset();
	    }
	    if (seterr) {
		xfree(seterr);
		seterr = NULL;
	    }

	    (void) lex(&paraml);
	    cleanup_push(&paraml, lex_cleanup);
	    if (seterr)
		stderror(ERR_OLD);
	    alias(&paraml);
	    t = syntax(paraml.next, &paraml, 0);
	    if (t == NULL)
		return;
	    cleanup_push(t, syntax_cleanup);
	    /* The F_BACKQ flag must set so the job output is correct if
	     * printexitvalue is set.  If it's not set, the job output
	     * will have "Exit N" appended where N is the exit status. */
	    t->t_dflg = F_BACKQ|F_NOFORK;
	    if (seterr)
		stderror(ERR_OLD);
#ifdef SIGTSTP
	    signal(SIGTSTP, SIG_IGN);
#endif
#ifdef SIGTTIN
	    signal(SIGTTIN, SIG_IGN);
#endif
#ifdef SIGTTOU
	    signal(SIGTTOU, SIG_IGN);
#endif
	    execute(t, -1, NULL, NULL, TRUE);

	    cleanup_until(&paraml);
	}
    }
    cleanup_until(&pvec[1]);
    c = 0;
    ip = NULL;
    do {
	ssize_t     cnt = 0;
	char   *tmp;

	tmp = tibuf;
	for (;;) {
	    while (icnt == 0) {
		int     i, eof;

		ip = ibuf;
		icnt = xread(pvec[0], tmp, tibuf + BUFSIZE - tmp);
		eof = 0;
		if (icnt <= 0) {
		    if (tmp == tibuf)
			goto eof;
		    icnt = 0;
		    eof = 1;
		}
		icnt += tmp - tibuf;
		i = 0;
		tmp = tibuf;
		while (tmp < tibuf + icnt) {
		    int len;

		    len = normal_mbtowc(&ip[i], tmp, tibuf + icnt - tmp);
		    if (len == -1) {
		        reset_mbtowc();
		        if (!eof && (size_t)(tibuf + icnt - tmp) < MB_CUR_MAX) {
			    break; /* Maybe a partial character */
			}
			ip[i] = (unsigned char) *tmp | INVALID_BYTE; /* Error */
		    }
		    if (len <= 0)
		        len = 1;
		    i++;
		    tmp += len;
		}
		if (tmp != tibuf)
		    memmove (tibuf, tmp, tibuf + icnt - tmp);
		tmp = tibuf + (tibuf + icnt - tmp);
		icnt = i;
	    }
	    if (hadnl)
		break;
	    --icnt;
	    c = (*ip++ & TRIM);
	    if (c == 0)
		break;
#if defined(WINNT_NATIVE) || defined(__CYGWIN__)
	    if (c == '\r')
	    	c = ' ';
#endif /* WINNT_NATIVE || __CYGWIN__ */
	    if (c == '\n') {
		/*
		 * Continue around the loop one more time, so that we can eat
		 * the last newline without terminating this word.
		 */
		hadnl = 1;
		continue;
	    }
	    if (!quoted && (c == ' ' || c == '\t'))
		break;
	    cnt++;
	    Strbuf_append1(word, c | quoted);
	}
	/*
	 * Unless at end-of-file, we will form a new word here if there were
	 * characters in the word, or in any case when we take text literally.
	 * If we didn't make empty words here when literal was set then we
	 * would lose blank lines.
	 */
	if (c != 0 && (cnt || literal))
	    pword(bb, word);
	hadnl = 0;
    } while (c > 0);
 eof:
    cleanup_until(&pvec[0]);
    pwait();
    cleanup_until(&faket); /* psavejob_cleanup(); */
}
// ---------------------------------------------------------------------------
// CAppMngr2SisxRuntime::GetInstallationFilesL()
// ---------------------------------------------------------------------------
//
void CAppMngr2SisxRuntime::GetInstallationFilesL(
        RPointerArray<CAppMngr2PackageInfo>& aPackageInfos,
        const RPointerArray<CAppMngr2RecognizedFile>& aFileList,
        RFs& aFsSession, TRequestStatus& aStatus )
    {
    TInt fileCount = aFileList.Count();
    FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: fileCount = %d", fileCount );
    if( fileCount )
        {
        // Check if this is the memory card installer daemon private folder.
        // All files are from the same directory, 
        CAppMngr2RecognizedFile* firstFile = aFileList[ 0 ];
        if( firstFile->FileName().Find( KAppMngr2DaemonPrivateFolder ) == KErrNotFound )
            {
            // No, it isn't. Process all files in aFileList and create package info objects.
            FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: normal folder" );
            for( TInt index = 0; index < fileCount; index++ )
                {
                CAppMngr2RecognizedFile* file = aFileList[ index ];
                
                TPtrC fileName = file->FileName();
                FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: file %S", &fileName );
                CreateNewPackageL( fileName, aPackageInfos, aFsSession );
                }
            }
        else
            {
            // It is. Process only those files that are not installed.
            FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: swidaemon private folder" );
            RArray<TUid> uids;
            CleanupClosePushL( uids );
            iSisRegistrySession.InstalledUidsL( uids );
            
            for( TInt index = 0; index < fileCount; index++ )
                {
                CAppMngr2RecognizedFile* recFile = aFileList[ index ];
                
                TPtrC fileName = recFile->FileName();
                FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: file %S", &fileName );
                
                // extract UID name from full path name
                TParsePtrC parse( fileName );
                TPtrC uidName = parse.Name().Left( KUidLength );
                FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: uidName %S", &uidName );
                
                // convert UID name to numerical form
                TLex lex( uidName );
                TUint32 uidValue;
                TInt lexError = lex.Val( uidValue, EHex );
                if( lexError == KErrNone )
                    {
                    // It's an UID name, try to display package name instead
                    FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: value %08x", uidValue );
                    
                    // check if this UID is already installed
                    TUid fileUid;
                    fileUid.iUid = uidValue;
                    if( uids.Find( fileUid ) == KErrNotFound )
                        {
                        FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: not installed" );
                        // Not installed, must be displayed. 
                        CreateNewPackageL( fileName, aPackageInfos, aFsSession );
                        }
                    else
                        {
                        FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: is installed" );
                        // Installed, two possible cases here. The package is in the
                        // SWI daemon private folder in memory card because:
                        // 1) memory card application is installed in use normally, or
                        // 2) the same application is already in ROM/internal drive.
                        // In case 1) this item MAY NOT be displayed here as it is already
                        // displayed in "Installed apps" side. In case of 2) it MUST be
                        // displayed, so that user can remove it from memory card. Cases
                        // 1) and 2) can be identified by checking the memory card's
                        // "unknown" list. If the sis package is unknown, it is case 2),
                        // as applications that are installed in use, are always known.
                        TChar driveLetter = parse.Drive()[ 0 ];
                        TInt driveNumber = 0;
                        User::LeaveIfError( RFs::CharToDrive( driveLetter, driveNumber ) );
                        CAppMngr2SisxUnknownList* unknownSisx = CAppMngr2SisxUnknownList::NewLC(
                                driveNumber );
                        TInt unknownIndex = unknownSisx->FindPkgWithUID( fileUid );
                        FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: unknownIndex %d",
                                unknownIndex );
                        if( unknownIndex >= 0 && unknownIndex < unknownSisx->PkgCount() )
                            {
                            // It is unknown package after all, add it to the list.
                            CreateNewPackageL( fileName, aPackageInfos, aFsSession );
                            }
                        CleanupStack::PopAndDestroy( unknownSisx );
                        }
                    }
                else
                    {
                    // Not an UID name, must be displayed.
                    FLOG( "CAppMngr2SisxRuntime::GetInstallationFilesL: not UID name (lexErr %d)",
                            lexError );
                    CreateNewPackageL( fileName, aPackageInfos, aFsSession );
                    }
                }

            CleanupStack::PopAndDestroy( &uids );
            }
        }
    TRequestStatus* status = &aStatus;
    User::RequestComplete( status, KErrNone );
    }
int main ()
{
    const char buffer [] = "int buffer [1024]";
    std::istringstream is (buffer);
    return !lex (is, sizeof (buffer));
}
Ejemplo n.º 22
0
/* The lexer is in charge of reading the file.
 * Some of sub-lexer (like eatComment) also read file.
 * lexing is finished when the lexer return Tok_EOF */
static objcKeyword lex (lexingState * st)
{
	int retType;

	/* handling data input here */
	while (st->cp == NULL || st->cp[0] == '\0')
	{
		st->cp = fileReadLine ();
		if (st->cp == NULL)
			return Tok_EOF;

		return Tok_EOL;
	}

	if (isAlpha (*st->cp))
	{
		readIdentifier (st);
		retType = lookupKeyword (vStringValue (st->name), Lang_ObjectiveC);

		if (retType == -1)	/* If it's not a keyword */
		{
			return ObjcIDENTIFIER;
		}
		else
		{
			return retType;
		}
	}
	else if (*st->cp == '@')
	{
		readIdentifierObjcDirective (st);
		retType = lookupKeyword (vStringValue (st->name), Lang_ObjectiveC);

		if (retType == -1)	/* If it's not a keyword */
		{
			return Tok_any;
		}
		else
		{
			return retType;
		}
	}
	else if (isSpace (*st->cp))
	{
		eatWhiteSpace (st);
		return lex (st);
	}
	else
		switch (*st->cp)
		{
		case '(':
			st->cp++;
			return Tok_PARL;

		case '\\':
			st->cp++;
			return Tok_Backslash;

		case '#':
			st->cp++;
			return Tok_Sharp;

		case '/':
			if (st->cp[1] == '*')	/* ergl, a comment */
			{
				eatComment (st);
				return lex (st);
			}
			else if (st->cp[1] == '/')
			{
				st->cp = NULL;
				return lex (st);
			}
			else
			{
				st->cp++;
				return Tok_any;
			}
			break;

		case ')':
			st->cp++;
			return Tok_PARR;
		case '{':
			st->cp++;
			return Tok_CurlL;
		case '}':
			st->cp++;
			return Tok_CurlR;
		case '[':
			st->cp++;
			return Tok_SQUAREL;
		case ']':
			st->cp++;
			return Tok_SQUARER;
		case ',':
			st->cp++;
			return Tok_COMA;
		case ';':
			st->cp++;
			return Tok_semi;
		case ':':
			st->cp++;
			return Tok_dpoint;
		case '"':
			eatString (st);
			return Tok_any;
		case '+':
			st->cp++;
			return Tok_PLUS;
		case '-':
			st->cp++;
			return Tok_MINUS;

		default:
			st->cp++;
			break;
		}

	/* default return if nothing is recognized,
	 * shouldn't happen, but at least, it will
	 * be handled without destroying the parsing. */
	return Tok_any;
}
Ejemplo n.º 23
0
// SendRequestL
// Creates the msg from the data elements passed in the descriptor array
// and sends over socket connection.
// Then waits until a response is received from the slave.
// Caller has to pass in empty HBufC8.
TInt CSender::SendRequestL(CRpsMsg& aRpsMsg, HBufC8** aResp)
	{
	
	// Generate request data buf
	HBufC8* msg = NULL;
	aRpsMsg.ExternalizeL(msg);
	CleanupStack::PushL(msg);

	// Send the msg over the socket
	TRequestStatus sendStatus;
	iSendSocket.Send(*msg, 0, sendStatus);
	User::WaitForRequest(sendStatus);
	CleanupStack::PopAndDestroy(msg);
	if(sendStatus != KErrNone)
		{
		RDEBUGPRINTLOGGER2(_L("CSender::SendRequestL Send error [%d]"),sendStatus.Int());
		return sendStatus.Int();
		}

	// Expect a response msg back from slave synchronously.
	// Return an error if resp not received in time-out.
	// Else pass the response msg up to the caller.

	// Expect the msg header+length
	TRequestStatus recvStatus;
	iBufferPreRead.Delete(0, iBufferPreRead.Length());
	iSendSocket.Recv(iBufferPreRead, 0, recvStatus);
	
	// ** TODO: check for error value in recvStatus (-191 returned if slave has crashed) **
	TInt ret = GetRequestOrTimeOut(recvStatus, KRespFromSlaveTimeout);
	if (recvStatus.Int() != KErrNone)
		{
		RDEBUGPRINTLOGGER2(_L("CSender::SendRequestL Recv error [%d]"),recvStatus.Int());
		}
		
	if(ret != KErrNone)
		{
		// We didn't receive a response within timelimit. 
		return ret;
		}
	 
	// Receive the rest of the msg.
	// Get msg length from pre-read
	TUint msgLen(0);
	TLex8 lex(iBufferPreRead.Right(KMaxMsgLenChars));
	lex.Val(msgLen);

	__ASSERT_ALWAYS(msgLen > KRespSocketPreReadSize, User::Panic(KPanicMsgFormat, 303)); // TODO - panic number?
	
	// Now read the rest of msg
	iBuffer.Close();
	iBuffer.CreateL(msgLen - KReqstSocketPreReadSize);
	// Recv operation should complete immediately if msg has been formatted correctly
	iSendSocket.Recv(iBuffer, 0, recvStatus);
	ret = GetRequestOrTimeOut(recvStatus, KRespFromSlaveTimeout);
	if(ret != KErrNone)
		{
		// We didn't receive a response within timelimit. 
		return ret;
		}
	// Check status of Recv operation
	if(recvStatus != KErrNone)
		{
		return recvStatus.Int();
		}
	
	iBufferAll.Close();
	iBufferAll.CreateL(msgLen);		// Give HandleRequestL the entire msg
	iBufferAll += iBufferPreRead;
	iBufferAll += iBuffer;
	
	// For debug ...
	RBuf16 buf;
	buf.CreateL(iBufferAll.Length());
	buf.Copy(iBufferAll);
	buf.Close();
	
	// Passing entire response msg to caller
	// Caller owns memory
	*aResp = iBufferAll.AllocL();
	
	iBufferPreRead.Delete(0, iBufferPreRead.Length());
	iBuffer.Close();
	iBufferAll.Close();

	return KErrNone;
	}
Ejemplo n.º 24
0
Archivo: parse.c Proyecto: AAAJet/ooc
int putsymbol (const void * sym, FILE * fp)
{
	return fprintf(fp, "\tname %s\n\tlex %d\n",
									name(sym), lex(sym));
}
Ejemplo n.º 25
0
int
main (int argc, char *argv[])
try
{
  if (argc < 2)
    return EXIT_FAILURE;

  if (!strcmp (argv[1], "--version"))
    {
      puts ("yaccpp v0.1");
      return EXIT_SUCCESS;
    }

  if (!strcmp (argv[1], "--help"))
    {
      puts ("usage: yaccpp <file> [file]...");
      return EXIT_SUCCESS;
    }

  symbol_table local_symtab;
  symtab = &local_symtab;

  std::vector<std::string> files (argv + 1, argv + argc);;

#if 0
  std::copy (files.begin (), files.end (), std::ostream_iterator<std::string> (std::cout, "\n"));
#endif

  lexer lex (files);
  parser parse (lex);

  if (node_ptr doc = parse ())
    {
      phases::run ("nop", doc);
      phases::run ("anon_rules", doc);
      phases::run ("cardinality", doc);
      phases::run ("insert_syms", doc);
      phases::run ("scobind", doc);
      phases::run ("resolve_refs", doc);
      phases::run ("call_macros", doc);
      return EXIT_SUCCESS;
      phases::run ("print", doc);
      phases::run ("xmlprint", doc);
    }
  else
    {
      return EXIT_FAILURE;
    }

#if 0
  BOOST_FOREACH (node *n, node::nodes)
    printf ("%p : %d\n", n, n ? n->index : -1);
#endif

  assert (node::audit_hash ());
  node::compress_hash ();
  assert (node::audit_hash ());

#if 0
  BOOST_FOREACH (node *n, node::nodes)
    printf ("%p : %d\n", n, n ? n->index : -1);
#endif

  return EXIT_SUCCESS;
}
catch (std::runtime_error const &e)
{
  printf ("runtime error: %s\n", e.what ());
  return EXIT_FAILURE;
}
catch (std::exception const &e)
{
  puts (e.what ());
  return EXIT_FAILURE;
}
Ejemplo n.º 26
0
void CRepositoryCacheManager::ConstructL(RFs& aFs)
	{
	CTimer::ConstructL();
	
	BSUL::CIniFile16* iniFile = NULL;
	TInt res = KErrNone;
	TBuf<KMaxFileName> iniFileName;
	
	iniFileName.Copy( *TServerResources::iInstallDirectory );
	iniFileName.Append( KCacheMgrIniFile );	
	TRAP(res, iniFile = BSUL::CIniFile16::NewL(aFs, iniFileName, ETrue));
	if(res==KErrNotFound)
		{
		// if RomDirectory exists
		if (TServerResources::iRomDirectory)
			{
			iniFileName.Copy( *TServerResources::iRomDirectory );
			iniFileName.Append( KCacheMgrIniFile );	
			TRAP(res, iniFile = BSUL::CIniFile16::NewL(aFs, iniFileName, ETrue));
			}
		if(res==KErrNotFound)
			{
			__CENTREP_TRACE1("CENTREP: Central Repository Cache Parameters ini file %S not found. Default values will be used.", &KCacheMgrIniFile);
			return;
			}
		}
	if (res != KErrNone)
		{
		User::Leave(res);
		}
		
	CleanupStack::PushL(iniFile);
	
	TBuf<20> buffer;
	TPtrC ptr(buffer);
	
	// find the value
	res = iniFile->FindVar(KCacheLit(), KDefaultCacheSizeLit(), ptr);
	TLex lex(ptr);

	TBool valueFound = EFalse;
	
	// if the value can't be found or can't be converted into a positive integer, use the default
	if (res != KErrNone || lex.Val(iCacheSize) != KErrNone || iCacheSize < 0)	
		{
		iCacheSize = KDefaultCacheSize;
		}
	else
		{
		valueFound = ETrue;			
		}
		
	// if the value can be found, convert it
	if (iniFile->FindVar(KCacheLit(), KDefaultEvictionTimeoutLit(), ptr) == KErrNone)
		{
		TInt tempTimeout;
		lex.Assign(ptr);
		// if the value can be converted into a positive integer, assign it to iDefaultTimeout.
		if (lex.Val(tempTimeout) == KErrNone && tempTimeout >= 0)
			{
			iDefaultTimeout = tempTimeout;
			valueFound = ETrue;
			}
		}
	
#ifdef _DEBUG
	// in Debug mode, if the Cache ini file exists either in install directory or 
	// rom directory but does not contains the correct section "CoarseGrainedCache"
	// nor any key of "size" and "timeout", the server panics.
	if(! valueFound)
	{
	Panic(ECacheIniFileCorrupted);
	}
#else
	UNUSED_VAR(valueFound);
#endif		

	CleanupStack::PopAndDestroy(iniFile);
	}
Ejemplo n.º 27
0
TBool TfrLex::ValF( const TDesC& aText, const TDesC& aTerm )
{
TLex lex( aText );
return ( ValF( lex, aTerm ) == KErrNone );
}
Ejemplo n.º 28
0
/*
 * La procedure "fscanf_Face_list" lit en ascii une liste de faces.
 * Entree :
 * lp		Liste de faces a lire.
 */ 
void fscanf_Face_list (Face_list *lp)
{
	static	char	proc_name[] = "fscanf_Face_list";

	Face	*fp;	/* face courante	*/
	Face	*fend;	/* borne de "fp"	*/

	
	/* Lecture du nombre de faces de la liste	*/

	if (lex () != T_INT)
		lexerr ("start","integer expected (number of faces)", NULL);
	lp->nbr = (Index) myint;

	/* Allocation dynamique de la liste de faces.	*/

	if (lp->nbr == 0)
		lp->ptr = NULL;
	else if ((lp->ptr = (Face *) malloc (lp->nbr * sizeof (Face)))
		== NULL) {
		perror (proc_name);
		exit (1);
	}

	/* Lecture des faces de la liste une a une.	*/

	fp   = lp->ptr;
	fend = fp + lp->nbr;
	for (; fp < fend; fp++) {
		Vertex_list	*lp = &fp->vertex;
		Index		*vp;	/* sommet courant	*/
		Index		*vend;	/* borne de "vp"	*/

		/* Lecture du type polygonale de la face.	*/

		if (lex () != T_INT)
		  lexerr ("start", "boolean expected (0=FALSE|~0=TRUE)", NULL);
		fp->is_polygonal = (myint ? 1 : 0);

		/* Lecture du nombre de sommets de la face.	*/

		if (lex () != T_INT)
		  lexerr ("start", "integer expected (number of vertices)", NULL);
		lp->nbr = (Index) myint;

		/* Allocation dynamique du polygone de la face.	*/

		if (lp->nbr <= DEFAULT_VSIZE)
			lp->ptr = lp->tbl;
		else if ((lp->ptr = (Index *) malloc (lp->nbr * sizeof (Index)))
			== NULL) {
			perror (proc_name);
			exit (1);
		}

		/* Lecture des sommets de la face un a un.	*/

		vp   = lp->ptr;
		vend = vp + lp->nbr;
		for (; vp < vend; *vp++ = (Index) myint)
		if (lex () != T_INT)
		  lexerr ("start", "integer expected (index of points 3D)", NULL);
	}
}	
// ---------------------------------------------------------------------------
// CAtPhbkGetPhoneStoreInfo::ParseResponseL
// other items were commented in a header
// ---------------------------------------------------------------------------
void CAtPhbkGetPhoneStoreInfo::ParseResponseL(const TDesC8& /*aResponseBuf*/)
	{
	if( iState == ESetPhoneStoreComplete )
		{
		if (CurrentLine().Match(KLtsyOkString) == 0)
			{
			iError = KErrNone;
			}
		else
			{
			iError = KErrGeneral;
			}
		}
	else if( iState == EGetPhoneStoreInfoComplete )
		{
		/**
		* Here is an Example 
		* +CPBS: "SM",6,250  
        * ADN phonebook is selected,6 locations are used and 
        * total 250 locations are available
		*/
		iError = KErrNone;
		RArray<TPtrC8> array;
		CleanupClosePushL(array);
		iParser->ParseRespondedBuffer(array,Buffer());
		//remove AT+CPBS
		if(array[0].MatchF(KAnyATCommand) != KErrNotFound)
			{
			array.Remove(0);
			}
		TInt count = array.Count();
#ifdef _DEBUG			
		for( TInt i=0;i<count;i++ )
			{
		    LOGTEXT3(_L8("CAtPhbkGetPhoneStoreInfo::ParseResponseL\tarray[%d]=%S"),
		    		      i,&array[i]);     
			}
#endif			
		if (count <= 1)
			{
			CleanupStack::PopAndDestroy();
			iError = KErrNotFound;
			return;
			}
		if(array[0].MatchF(KCPBSResponseString) == KErrNotFound)
			{
			CleanupStack::PopAndDestroy();
			iError = KErrNotFound;
			return;
			}
				
		//parse used
		TLex8 lex(array[2]);
		TUint16 val;
		TInt ret = lex.Val(val,EDecimal);
		if(ret != KErrNone)
			{
			CleanupStack::PopAndDestroy();
			iError = ret;
			return;
			}
		iPhoneStoreInfo.iUsedEntries = val;
		
		//parse total
		TLex8 lex1(array[3]);
		ret = lex1.Val(val,EDecimal);
		if(ret != KErrNone)
			{
			CleanupStack::PopAndDestroy();
			iError = ret;
			return;
			}
		iPhoneStoreInfo.iTotalEntries = val;
		iPhoneStoreInfo.iType = RMobilePhoneStore::EPhoneBookStore;
	    LOGTEXT3(_L8("CAtPhbkGetPhoneStoreInfo::ParseResponseL\tPreferred store used=%d, total=%d"), 
	    		                                iPhoneStoreInfo.iUsedEntries,iPhoneStoreInfo.iTotalEntries);
		CleanupStack::PopAndDestroy(&array);
		}
	else 
		{
		/**
		* Parse result of AT+CPMS? 
		* Response:+CPMS:<mem1>,<used1>,<total1>,<mem2>,<used2>,<total2>
		* Here only the first mem is used. mem1 is SM
		*/
		iError = KErrNone;
		RArray<TPtrC8> array;
		CleanupClosePushL(array);
		iParser->ParseRespondedBuffer(array,Buffer());
		if(array[0].MatchF(KAnyATCommand) != KErrNotFound)
			{
			array.Remove(0);
			}
		TInt Count = array.Count();
		if (Count <= 1)
			{
			CleanupStack::PopAndDestroy();
			iError = KErrNotFound;
			return;
			}
		if(array[0].MatchF(KCPMSResponseString) == KErrNotFound)
			{
			CleanupStack::PopAndDestroy();
			iError = KErrNotFound;
			return;
			}
		//parse name 
		TPtrC8 name(array[1]);
		
		//parse used
		TLex8 lex(array[2]);
		TUint16 val;
		TInt ret = lex.Val(val,EDecimal);
		if(ret != KErrNone)
			{
			CleanupStack::PopAndDestroy();
			iError = ret;
			return;
			}
		iPhoneStoreInfo.iUsedEntries = val;
		
		//parse total
		TLex8 lex1(array[3]);
		ret = lex1.Val(val,EDecimal);
		if(ret != KErrNone)
			{
			CleanupStack::PopAndDestroy();
			iError = ret;
			return;
			}
		iPhoneStoreInfo.iTotalEntries = val;
		iPhoneStoreInfo.iType = RMobilePhoneStore::EShortMessageStore;
		LOGTEXT3(_L8("CAtPhbkGetPhoneStoreInfo::ParseResponseL\tPreferred store used=%d, total=%d"), 
			    		                        iPhoneStoreInfo.iUsedEntries,iPhoneStoreInfo.iTotalEntries);
		CleanupStack::PopAndDestroy(&array);
		}
	}
Ejemplo n.º 30
0
parse()
{
	char		*values[MAXDEPTH];	/*    value stack	 */
	short		states[MAXDEPTH];	/*    state stack	 */
	register short	*yyps;		/* pointer to state stack	 */
	register short	*act;		/* pointer to performing action	 */
	register int	state;		/* current parser state		 */
	register int	next_state;
	register int	token;		/* current input token number	 */
	register int	i;
	register int	errorflag;	/* error recovery flag		 */

	state = 0;
	token = -1;
	errorflag = 0;
	yyps = &states[-1];
	yypv = &values[-1];

stack:
	*++yyps = state;	/* push state into state stack */
	*++yypv = yyval;	/* push value into value stack */
new_state:
	/* set act to point to the parsing actions for the new state */
	i = yypact[state + 1];
	act = &yyact[i];

next_action:		/* get the next action, and perform it */
	next_state = ACTION(*act);
	switch (OPERATION(*act++))	/* switch on operation */
	{
	  case SKIP:
		if (token < 0)	/* get next token */
			token = lex();
		if (next_state != token)
			act++;
		goto next_action;	/* get next action */

	  case SHIFT:		/* goto next_state */
		state = next_state;
		yyval = yylval;	/* $i = value of last token */
		token = -1;
		if (errorflag)
			errorflag--;
		goto stack;	/* stack new state and value */

	  case REDUCE:		/* rule next_state */
		yyps -= yyr2[next_state];	/* pop state stack */
		yypv -= yyr2[next_state];	/* pop value stack */
		yyval = yypv[1];		/* $$ = $1	   */

		if (yyactr(next_state))
			 goto abort;

		/* consult goto table to find next state */
		i = yyr1[next_state];
		i = yypgo[i];
		act = &yygo[i];
		next_state = *yyps;
		for ( ; *act != next_state && *act >= 0; act += 2)
			continue;
		state = act[1];
		goto stack;  /* stack new state and value */

	  case ACCEPT:
		return (0);

	  case ERROR:		/* attempt to resume parsing */
		switch (errorflag)
		{
		  case 0:	/* brand new syntax error */
			amxerror(88);

		  case 1:	 /* incompletely recovered error, try again */
			errorflag = 2;

			/* find a state where "error" is a legal SHIFT */
			while (yyps >= states)
			{
				/* search yyps actions */
				i = *yyps;
				i = yypact[i + 1];
				act = &yyact[i];
				for ( ; OPERATION(*act) == SKIP; act += 2)
					if (*act == SHIFT_ON_ERROR)
						goto found;

				/* the current yyps has no shift */
				/* on "error", pop stack	 */
				yyps--;
				yypv--;
			}

			/* there is no state on the stack */
			/* with an error shift ... abort  */
abort:
			return (1);

found:	/* we have a state with a shift on "error", resume parsing */
			state =  ACTION(act[1]);
			goto stack;

		  case 2:	/* no shift yet; clobber input char */
				/* don't discard EOF; quit          */
			if (!token)
				goto abort;
			token = -1;
			goto new_state;   /* try again in the same state */

		}
	}

	/*NOTREACHED*/
}