Exemplo n.º 1
0
void CMonsterSetBase::LoadSetBase(char * filename)
{
	int Token;
	int rcount;
	int copycount;
	BYTE Sdir;

	SMDFile = fopen(filename, "r");

	if ( SMDFile == NULL )
	{
		MsgBox("file open error %s", filename);
		return;
	}

	this->m_Count = 0;

	while ( true )
	{
		Token = GetToken();

		if ( Token == 2 )
			break;

		if ( Token == 1 )
		{
			int Type = TokenNumber;

			while ( true )
			{
				Token = GetToken();

				if ( strcmp("end", TokenString) == 0 )
					break;
				
				this->m_Mp[this->m_Count].m_Type = TokenNumber;
				Token = GetToken();	this->m_Mp[this->m_Count].m_MapNumber = TokenNumber;
				Token = GetToken();	this->m_Mp[this->m_Count].m_Dis = TokenNumber;
				Token = GetToken();	this->m_Mp[this->m_Count].m_X = TokenNumber;
				Token = GetToken();	this->m_Mp[this->m_Count].m_Y = TokenNumber;
				this->m_Mp[this->m_Count].m_ArrangeType = Type;

				if ( Type == 1 || Type == 3 )
				{
					Token = GetToken();	this->m_Mp[this->m_Count].m_W = TokenNumber;
					Token = GetToken();	this->m_Mp[this->m_Count].m_H = TokenNumber;
				}
				else if ( Type == 2 )
				{
					this->m_Mp[this->m_Count].m_W = 0;
					this->m_Mp[this->m_Count].m_H = 0;

					int w = this->m_Mp[this->m_Count].m_X - 3;
					int h = this->m_Mp[this->m_Count].m_Y - 3;

					w += rand() % 7;
					h += rand() % 7;

					this->m_Mp[this->m_Count].m_X = w;
					this->m_Mp[this->m_Count].m_Y = h;
				}
				else if ( Type == 4 )
				{
					this->m_Mp[this->m_Count].m_W = 0;
					this->m_Mp[this->m_Count].m_H = 0;
				}
				else
				{
					this->m_Mp[this->m_Count].m_W = 0;
					this->m_Mp[this->m_Count].m_H = 0;
				}

				Token = GetToken();	this->m_Mp[this->m_Count].m_Dir = TokenNumber;
				Sdir = this->m_Mp[this->m_Count].m_Dir;

				if ( this->m_Mp[this->m_Count].m_Dir == (BYTE)-1 )
					this->m_Mp[this->m_Count].m_Dir = rand() % 8;

				if ( Type == 1 || Type == 3 )
				{
					BYTE w = this->m_Mp[this->m_Count].m_X;
					BYTE h = this->m_Mp[this->m_Count].m_Y;

					Token = GetToken();	rcount = TokenNumber;
					copycount = this->m_Count;

					if ( rcount > 1 )
					{
						for ( int k = 0; k<rcount-1 ; k++ )
						{
							this->m_Count++;

							if ( this->m_Count > OBJ_MAXMONSTER-1 )
							{
								MsgBox("Monster attribute max over %s %d", __FILE__, __LINE__);
								fclose(SMDFile);
								return;
							}

							this->m_Mp[this->m_Count].m_Dis = this->m_Mp[copycount].m_Dis;
							this->m_Mp[this->m_Count].m_Type = this->m_Mp[copycount].m_Type;
							this->m_Mp[this->m_Count].m_MapNumber = this->m_Mp[copycount].m_MapNumber;
							this->m_Mp[this->m_Count].m_W = this->m_Mp[copycount].m_W;
							this->m_Mp[this->m_Count].m_H = this->m_Mp[copycount].m_H;
							this->m_Mp[this->m_Count].m_X = this->m_Mp[copycount].m_X;
							this->m_Mp[this->m_Count].m_Y = this->m_Mp[copycount].m_Y;
							this->m_Mp[this->m_Count].m_ArrangeType = this->m_Mp[copycount].m_ArrangeType;

							if ( Sdir == (BYTE)-1 )
								this->m_Mp[this->m_Count].m_Dir = rand() % 8;
							else
								this->m_Mp[this->m_Count].m_Dir = this->m_Mp[copycount].m_Dir;
						}
					}
				}


				this->m_Count++;

				if ( this->m_Count > OBJ_MAXMONSTER-1 )
				{
					MsgBox("Monster attribute max over %d (%s %d)", this->m_Count, __FILE__, __LINE__);
					fclose(SMDFile);
					return;
				}
			}
		}
	}

	fclose(SMDFile);
}
Exemplo n.º 2
0
EFI_STATUS
EvaluateExpression (
  IN FORM_BROWSER_FORMSET  *FormSet,
  IN FORM_BROWSER_FORM     *Form,
  IN OUT FORM_EXPRESSION   *Expression
  )
/*++

Routine Description:

  Evaluate the result of a HII expression

Arguments:

  FormSet    - FormSet associated with this expression.
  Form       - Form associated with this expression.
  Expression - Expression to be evaluated.

Returns:

  EFI_SUCCESS           - The expression evaluated successfuly
  EFI_NOT_FOUND         - The Question which referenced by a QuestionId could not be found.
  EFI_OUT_OF_RESOURCES  - There is not enough system memory to grow the stack.
  EFI_ACCESS_DENIED     - The pop operation underflowed the stack
  EFI_INVALID_PARAMETER - Syntax error with the Expression

--*/
{
  EFI_STATUS              Status;
  EFI_LIST_ENTRY          *Link;
  EXPRESSION_OPCODE       *OpCode;
  FORM_BROWSER_STATEMENT  *Question;
  FORM_BROWSER_STATEMENT  *Question2;
  UINT16                  Index;
  EFI_HII_VALUE           Data1;
  EFI_HII_VALUE           Data2;
  EFI_HII_VALUE           Data3;
  FORM_EXPRESSION         *RuleExpression;
  EFI_HII_VALUE           *Value;
  INTN                    Result;
  CHAR16                  *StrPtr;

  //
  // Always reset the stack before evaluating an Expression
  //
  ResetExpressionStack ();

  Expression->Result.Type = EFI_IFR_TYPE_OTHER;

  Link = GetFirstNode (&Expression->OpCodeListHead);
  while (!IsNull (&Expression->OpCodeListHead, Link)) {
    OpCode = EXPRESSION_OPCODE_FROM_LINK (Link);

    Link = GetNextNode (&Expression->OpCodeListHead, Link);

    EfiZeroMem (&Data1, sizeof (EFI_HII_VALUE));
    EfiZeroMem (&Data2, sizeof (EFI_HII_VALUE));
    EfiZeroMem (&Data3, sizeof (EFI_HII_VALUE));

    Value = &Data3;
    Value->Type = EFI_IFR_TYPE_BOOLEAN;
    Status = EFI_SUCCESS;

    switch (OpCode->Operand) {
    //
    // Built-in functions
    //
    case EFI_IFR_EQ_ID_VAL_OP:
      Question = IdToQuestion (FormSet, Form, OpCode->QuestionId);
      if (Question == NULL) {
        return EFI_NOT_FOUND;
      }

      Result = CompareHiiValue (&Question->HiiValue, &OpCode->Value, NULL);
      if (Result == EFI_INVALID_PARAMETER) {
        return EFI_INVALID_PARAMETER;
      }
      Value->Value.b = (Result == 0) ? TRUE : FALSE;
      break;

    case EFI_IFR_EQ_ID_ID_OP:
      Question = IdToQuestion (FormSet, Form, OpCode->QuestionId);
      if (Question == NULL) {
        return EFI_NOT_FOUND;
      }

      Question2 = IdToQuestion (FormSet, Form, OpCode->QuestionId2);
      if (Question2 == NULL) {
        return EFI_NOT_FOUND;
      }

      Result = CompareHiiValue (&Question->HiiValue, &Question2->HiiValue, FormSet->HiiHandle);
      if (Result == EFI_INVALID_PARAMETER) {
        return EFI_INVALID_PARAMETER;
      }
      Value->Value.b = (Result == 0) ? TRUE : FALSE;
      break;

    case EFI_IFR_EQ_ID_LIST_OP:
      Question = IdToQuestion (FormSet, Form, OpCode->QuestionId);
      if (Question == NULL) {
        return EFI_NOT_FOUND;
      }

      Value->Value.b = FALSE;
      for (Index =0; Index < OpCode->ListLength; Index++) {
        if (Question->HiiValue.Value.u16 == OpCode->ValueList[Index]) {
          Value->Value.b = TRUE;
          break;
        }
      }
      break;

    case EFI_IFR_DUP_OP:
      Status = PopExpression (Value);
      if (EFI_ERROR (Status)) {
        return Status;
      }

      Status = PushExpression (Value);
      break;

    case EFI_IFR_QUESTION_REF1_OP:
    case EFI_IFR_THIS_OP:
      Question = IdToQuestion (FormSet, Form, OpCode->QuestionId);
      if (Question == NULL) {
        return EFI_NOT_FOUND;
      }

      Value = &Question->HiiValue;
      break;

    case EFI_IFR_QUESTION_REF3_OP:
      if (OpCode->DevicePath == 0) {
        //
        // EFI_IFR_QUESTION_REF3
        // Pop an expression from the expression stack
        //
        Status = PopExpression (Value);
        if (EFI_ERROR (Status)) {
          return Status;
        }

        //
        // Validate the expression value
        //
        if ((Value->Type > EFI_IFR_TYPE_NUM_SIZE_64) || (Value->Value.u64 > 0xffff)) {
          return EFI_NOT_FOUND;
        }

        Question = IdToQuestion (FormSet, Form, Value->Value.u16);
        if (Question == NULL) {
          return EFI_NOT_FOUND;
        }

        //
        // push the questions' value on to the expression stack
        //
        Value = &Question->HiiValue;
      } else {
        //
        // BUGBUG: push 0 for EFI_IFR_QUESTION_REF3_2 and EFI_IFR_QUESTION_REF3_3,
        // since it is impractical to evaluate the value of a Question in another
        // Hii Package list.
        //
        EfiZeroMem (Value, sizeof (EFI_HII_VALUE));
      }
      break;

    case EFI_IFR_RULE_REF_OP:
      //
      // Find expression for this rule
      //
      RuleExpression = RuleIdToExpression (Form, OpCode->RuleId);
      if (RuleExpression == NULL) {
        return EFI_NOT_FOUND;
      }

      //
      // Evaluate this rule expression
      //
      Status = EvaluateExpression (FormSet, Form, RuleExpression);
      if (EFI_ERROR (Status)) {
        return Status;
      }

      Value = &RuleExpression->Result;
      break;

    case EFI_IFR_STRING_REF1_OP:
      Value->Type = EFI_IFR_TYPE_STRING;
      Value->Value.string = OpCode->Value.Value.string;
      break;

    //
    // Constant
    //
    case EFI_IFR_TRUE_OP:
    case EFI_IFR_FALSE_OP:
    case EFI_IFR_ONE_OP:
    case EFI_IFR_ONES_OP:
    case EFI_IFR_UINT8_OP:
    case EFI_IFR_UINT16_OP:
    case EFI_IFR_UINT32_OP:
    case EFI_IFR_UINT64_OP:
    case EFI_IFR_UNDEFINED_OP:
    case EFI_IFR_VERSION_OP:
    case EFI_IFR_ZERO_OP:
      Value = &OpCode->Value;
      break;

    //
    // unary-op
    //
    case EFI_IFR_LENGTH_OP:
      Status = PopExpression (Value);
      if (EFI_ERROR (Status)) {
        return Status;
      }
      if (Value->Type != EFI_IFR_TYPE_STRING) {
        return EFI_INVALID_PARAMETER;
      }

      StrPtr = GetToken (Value->Value.string, FormSet->HiiHandle);
      if (StrPtr == NULL) {
        return EFI_INVALID_PARAMETER;
      }

      Value->Type = EFI_IFR_TYPE_NUM_SIZE_64;
      Value->Value.u64 = EfiStrLen (StrPtr);
      gBS->FreePool (StrPtr);
      break;

    case EFI_IFR_NOT_OP:
      Status = PopExpression (Value);
      if (EFI_ERROR (Status)) {
        return Status;
      }
      if (Value->Type != EFI_IFR_TYPE_BOOLEAN) {
        return EFI_INVALID_PARAMETER;
      }
      Value->Value.b = !Value->Value.b;
      break;

    case EFI_IFR_QUESTION_REF2_OP:
      //
      // Pop an expression from the expression stack
      //
      Status = PopExpression (Value);
      if (EFI_ERROR (Status)) {
        return Status;
      }

      //
      // Validate the expression value
      //
      if ((Value->Type > EFI_IFR_TYPE_NUM_SIZE_64) || (Value->Value.u64 > 0xffff)) {
        return EFI_NOT_FOUND;
      }

      Question = IdToQuestion (FormSet, Form, Value->Value.u16);
      if (Question == NULL) {
        return EFI_NOT_FOUND;
      }

      Value = &Question->HiiValue;
      break;

    case EFI_IFR_STRING_REF2_OP:
      //
      // Pop an expression from the expression stack
      //
      Status = PopExpression (Value);
      if (EFI_ERROR (Status)) {
        return Status;
      }

      //
      // Validate the expression value
      //
      if ((Value->Type > EFI_IFR_TYPE_NUM_SIZE_64) || (Value->Value.u64 > 0xffff)) {
        return EFI_NOT_FOUND;
      }

      Value->Type = EFI_IFR_TYPE_STRING;
      StrPtr = GetToken (Value->Value.u16, FormSet->HiiHandle);
      if (StrPtr == NULL) {
        //
        // If String not exit, push an empty string
        //
        Value->Value.string = NewString (gEmptyString, FormSet->HiiHandle);
      } else {
        Index = (UINT16) Value->Value.u64;
        Value->Value.string = Index;
        gBS->FreePool (StrPtr);
      }
      break;

    case EFI_IFR_TO_BOOLEAN_OP:
      //
      // Pop an expression from the expression stack
      //
      Status = PopExpression (Value);
      if (EFI_ERROR (Status)) {
        return Status;
      }

      //
      // Convert an expression to a Boolean
      //
      if (Value->Type <= EFI_IFR_TYPE_DATE) {
        //
        // When converting from an unsigned integer, zero will be converted to
        // FALSE and any other value will be converted to TRUE.
        //
        Value->Value.b = (Value->Value.u64) ? TRUE : FALSE;

        Value->Type = EFI_IFR_TYPE_BOOLEAN;
      } else if (Value->Type == EFI_IFR_TYPE_STRING) {
        //
        // When converting from a string, if case-insensitive compare
        // with "true" is True, then push True. If a case-insensitive compare
        // with "false" is True, then push False.
        //
        StrPtr = GetToken (Value->Value.string, FormSet->HiiHandle);
        if (StrPtr == NULL) {
          return EFI_INVALID_PARAMETER;
        }

        if ((EfiStrCmp (StrPtr, L"true") == 0) || (EfiStrCmp (StrPtr, L"false") == 0)){
          Value->Value.b = TRUE;
        } else {
          Value->Value.b = FALSE;
        }
        gBS->FreePool (StrPtr);
        Value->Type = EFI_IFR_TYPE_BOOLEAN;
      }
      break;

    case EFI_IFR_TO_STRING_OP:
      Status = IfrToString (FormSet, OpCode->Format, Value);
      break;

    case EFI_IFR_TO_UINT_OP:
      Status = IfrToUint (FormSet, Value);
      break;

    case EFI_IFR_TO_LOWER_OP:
    case EFI_IFR_TO_UPPER_OP:
      Status = InitializeUnicodeCollationProtocol ();
      if (EFI_ERROR (Status)) {
        return Status;
      }

      Status = PopExpression (Value);
      if (EFI_ERROR (Status)) {
        return Status;
      }

      if (Value->Type != EFI_IFR_TYPE_STRING) {
        return EFI_UNSUPPORTED;
      }

      StrPtr = GetToken (Value->Value.string, FormSet->HiiHandle);
      if (StrPtr == NULL) {
        return EFI_NOT_FOUND;
      }

      if (OpCode->Operand == EFI_IFR_TO_LOWER_OP) {
        mUnicodeCollation->StrLwr (mUnicodeCollation, StrPtr);
      } else {
        mUnicodeCollation->StrUpr (mUnicodeCollation, StrPtr);
      }
      Value->Value.string = NewString (StrPtr, FormSet->HiiHandle);
      gBS->FreePool (StrPtr);
      break;

    case EFI_IFR_BITWISE_NOT_OP:
      //
      // Pop an expression from the expression stack
      //
      Status = PopExpression (Value);
      if (EFI_ERROR (Status)) {
        return Status;
      }
      if (Value->Type > EFI_IFR_TYPE_DATE) {
        return EFI_INVALID_PARAMETER;
      }

      Value->Type = EFI_IFR_TYPE_NUM_SIZE_64;
      Value->Value.u64 = ~Value->Value.u64;
      break;

    //
    // binary-op
    //
    case EFI_IFR_ADD_OP:
    case EFI_IFR_SUBTRACT_OP:
    case EFI_IFR_MULTIPLY_OP:
    case EFI_IFR_DIVIDE_OP:
    case EFI_IFR_MODULO_OP:
    case EFI_IFR_BITWISE_AND_OP:
    case EFI_IFR_BITWISE_OR_OP:
    case EFI_IFR_SHIFT_LEFT_OP:
    case EFI_IFR_SHIFT_RIGHT_OP:
      //
      // Pop an expression from the expression stack
      //
      Status = PopExpression (&Data2);
      if (EFI_ERROR (Status)) {
        return Status;
      }
      if (Data2.Type > EFI_IFR_TYPE_DATE) {
        return EFI_INVALID_PARAMETER;
      }

      //
      // Pop another expression from the expression stack
      //
      Status = PopExpression (&Data1);
      if (EFI_ERROR (Status)) {
        return Status;
      }
      if (Data1.Type > EFI_IFR_TYPE_DATE) {
        return EFI_INVALID_PARAMETER;
      }

      Value->Type = EFI_IFR_TYPE_NUM_SIZE_64;

      switch (OpCode->Operand) {
        case EFI_IFR_ADD_OP:
          Value->Value.u64 = Data1.Value.u64 + Data2.Value.u64;
          break;

        case EFI_IFR_SUBTRACT_OP:
          Value->Value.u64 = Data1.Value.u64 - Data2.Value.u64;
          break;

        case EFI_IFR_MULTIPLY_OP:
          Value->Value.u64 = MultU64x32 (Data1.Value.u64, (UINTN) Data2.Value.u64);
          break;

        case EFI_IFR_DIVIDE_OP:
          Value->Value.u64 = DivU64x32 (Data1.Value.u64, (UINTN) Data2.Value.u64, NULL);
          break;

        case EFI_IFR_MODULO_OP:
          DivU64x32 (Data1.Value.u64, (UINTN) Data2.Value.u64, (UINTN *) &Value->Value.u64);
          break;

        case EFI_IFR_BITWISE_AND_OP:
          Value->Value.u64 = Data1.Value.u64 & Data2.Value.u64;
          break;

        case EFI_IFR_BITWISE_OR_OP:
          Value->Value.u64 = Data1.Value.u64 | Data2.Value.u64;
          break;

        case EFI_IFR_SHIFT_LEFT_OP:
          Value->Value.u64 = LShiftU64 (Data1.Value.u64, (UINTN) Data2.Value.u64);
          break;

        case EFI_IFR_SHIFT_RIGHT_OP:
          Value->Value.u64 = RShiftU64 (Data1.Value.u64, (UINTN) Data2.Value.u64);
          break;

        default:
          break;
      }
      break;

    case EFI_IFR_AND_OP:
    case EFI_IFR_OR_OP:
      //
      // Two Boolean operator
      //
      Status = PopExpression (&Data2);
      if (EFI_ERROR (Status)) {
        return Status;
      }
      if (Data2.Type != EFI_IFR_TYPE_BOOLEAN) {
        return EFI_INVALID_PARAMETER;
      }

      //
      // Pop another expression from the expression stack
      //
      Status = PopExpression (&Data1);
      if (EFI_ERROR (Status)) {
        return Status;
      }
      if (Data1.Type != EFI_IFR_TYPE_BOOLEAN) {
        return EFI_INVALID_PARAMETER;
      }

      if (OpCode->Operand == EFI_IFR_AND_OP) {
        Value->Value.b = Data1.Value.b && Data2.Value.b;
      } else {
        Value->Value.b = Data1.Value.b || Data2.Value.b;
      }
      break;

    case EFI_IFR_EQUAL_OP:
    case EFI_IFR_NOT_EQUAL_OP:
    case EFI_IFR_GREATER_EQUAL_OP:
    case EFI_IFR_GREATER_THAN_OP:
    case EFI_IFR_LESS_EQUAL_OP:
    case EFI_IFR_LESS_THAN_OP:
      //
      // Compare two integer, string, boolean or date/time
      //
      Status = PopExpression (&Data2);
      if (EFI_ERROR (Status)) {
        return Status;
      }
      if (Data2.Type > EFI_IFR_TYPE_BOOLEAN && Data2.Type != EFI_IFR_TYPE_STRING) {
        return EFI_INVALID_PARAMETER;
      }

      //
      // Pop another expression from the expression stack
      //
      Status = PopExpression (&Data1);
      if (EFI_ERROR (Status)) {
        return Status;
      }

      Result = CompareHiiValue (&Data1, &Data2, FormSet->HiiHandle);
      if (Result == EFI_INVALID_PARAMETER) {
        return EFI_INVALID_PARAMETER;
      }

      switch (OpCode->Operand) {
      case EFI_IFR_EQUAL_OP:
        Value->Value.b = (Result == 0) ? TRUE : FALSE;
        break;

      case EFI_IFR_NOT_EQUAL_OP:
        Value->Value.b = (Result != 0) ? TRUE : FALSE;
        break;

      case EFI_IFR_GREATER_EQUAL_OP:
        Value->Value.b = (Result >= 0) ? TRUE : FALSE;
        break;

      case EFI_IFR_GREATER_THAN_OP:
        Value->Value.b = (Result > 0) ? TRUE : FALSE;
        break;

      case EFI_IFR_LESS_EQUAL_OP:
        Value->Value.b = (Result <= 0) ? TRUE : FALSE;
        break;

      case EFI_IFR_LESS_THAN_OP:
        Value->Value.b = (Result < 0) ? TRUE : FALSE;
        break;

      default:
        break;
      }
      break;

    case EFI_IFR_MATCH_OP:
      Status = IfrMatch (FormSet, Value);
      break;

    case EFI_IFR_CATENATE_OP:
      Status = IfrCatenate (FormSet, Value);
      break;

    //
    // ternary-op
    //
    case EFI_IFR_CONDITIONAL_OP:
      //
      // Pop third expression from the expression stack
      //
      Status = PopExpression (&Data3);
      if (EFI_ERROR (Status)) {
        return Status;
      }

      //
      // Pop second expression from the expression stack
      //
      Status = PopExpression (&Data2);
      if (EFI_ERROR (Status)) {
        return Status;
      }

      //
      // Pop first expression from the expression stack
      //
      Status = PopExpression (&Data1);
      if (EFI_ERROR (Status)) {
        return Status;
      }
      if (Data1.Type != EFI_IFR_TYPE_BOOLEAN) {
        return EFI_INVALID_PARAMETER;
      }

      if (Data1.Value.b) {
        Value = &Data3;
      } else {
        Value = &Data2;
      }
      break;

    case EFI_IFR_FIND_OP:
      Status = IfrFind (FormSet, OpCode->Format, Value);
      break;

    case EFI_IFR_MID_OP:
      Status = IfrMid (FormSet, Value);
      break;

    case EFI_IFR_TOKEN_OP:
      Status = IfrToken (FormSet, Value);
      break;

    case EFI_IFR_SPAN_OP:
      Status = IfrSpan (FormSet, OpCode->Flags, Value);
      break;

    default:
      break;
    }
    if (EFI_ERROR (Status)) {
      return Status;
    }

    Status = PushExpression (Value);
    if (EFI_ERROR (Status)) {
      return Status;
    }
  }

  //
  // Pop the final result from expression stack
  //
  Value = &Data1;
  Status = PopExpression (Value);
  if (EFI_ERROR (Status)) {
    return Status;
  }

  //
  // After evaluating an expression, there should be only one value left on the expression stack
  //
  if (PopExpression (Value) != EFI_ACCESS_DENIED) {
    return EFI_INVALID_PARAMETER;
  }

  EfiCopyMem (&Expression->Result, Value, sizeof (EFI_HII_VALUE));

  return EFI_SUCCESS;
}
Exemplo n.º 3
0
EFI_STATUS
IfrCatenate (
  IN FORM_BROWSER_FORMSET  *FormSet,
  OUT  EFI_HII_VALUE       *Result
  )
/*++

Routine Description:
  Evaluate opcode EFI_IFR_CATENATE.

Arguments:
  FormSet     - Formset which contains this opcode.
  Result      - Evaluation result for this opcode.

Returns:
  EFI_SUCCESS - Opcode evaluation success.
  Other       - Opcode evaluation failed.

--*/
{
  EFI_STATUS     Status;
  EFI_HII_VALUE  Value;
  CHAR16         *String[2];
  UINTN          Index;
  CHAR16         *StringPtr;

  //
  // String[0] - The second string
  // String[1] - The first string
  //
  String[0] = NULL;
  String[1] = NULL;
  StringPtr = NULL;
  Status = EFI_SUCCESS;

  for (Index = 0; Index < 2; Index++) {
    Status = PopExpression (&Value);
    if (EFI_ERROR (Status)) {
      goto Done;
    }

    if (Value.Type != EFI_IFR_TYPE_STRING) {
      Status = EFI_UNSUPPORTED;
      goto Done;
    }

    String[Index] = GetToken (Value.Value.string, FormSet->HiiHandle);
    if (String== NULL) {
      Status = EFI_NOT_FOUND;
      goto Done;
    }
  }

  StringPtr= EfiLibAllocatePool (EfiStrSize (String[1]) + EfiStrSize (String[0]));
  ASSERT (StringPtr != NULL);
  EfiStrCpy (StringPtr, String[1]);
  EfiStrCat (StringPtr, String[0]);

  Result->Type = EFI_IFR_TYPE_STRING;
  Result->Value.string = NewString (StringPtr, FormSet->HiiHandle);

Done:
  EfiLibSafeFreePool (String[0]);
  EfiLibSafeFreePool (String[1]);
  EfiLibSafeFreePool (StringPtr);

  return Status;
}
Exemplo n.º 4
0
std::string IDSEXT::InvokeMethod(const std::string& command)
{
    int index = command.find_first_of(" ");

    string strCommand = command.substr(0, index);
    string strParam = command.substr(index + 1, command.length());

    Json::Reader reader;
    Json::Value obj;
    if (strCommand == "getVersion") {
        return GetVersion();
    } else if (strCommand == "registerProvider") {
        return RegisterProvider(strParam);
    } else if (strCommand == "setOption") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);

        if (!parse) {
            //fprintf(stderr, "%s\n", "error parsing\n");
            return "unable to parse options";
        }
        int option = obj["option"].asInt();
        const std::string value = obj["value"].asString();
        return( SetOption(option, value) );
    } else if (strCommand == "getToken") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);

        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        std::string tokenType = obj["tokenType"].asString();
        const std::string appliesTo = obj["appliesTo"].asString();

        GetToken(provider, tokenType, appliesTo);
    } else if (strCommand == "clearToken") {
            // parse the JSON
        bool parse = reader.parse(strParam, obj);

        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        std::string tokenType = obj["tokenType"].asString();
        const std::string appliesTo = obj["appliesTo"].asString();

        ClearToken(provider, tokenType, appliesTo);
    } else if (strCommand == "getProperties") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);
        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        int propertyType = obj["propertyType"].asInt();
        int numProps = obj["numProps"].asInt();
        const std::string userProps = obj["userProperties"].asString();
        GetProperties(provider, propertyType, numProps, userProps);
    } else if (strCommand == "getData") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);
        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        int dataType = obj["dataType"].asInt();
        int dataFlags = obj["dataFlags"].asInt();
        const std::string dataName = obj["dataName"].asString();
        GetData(provider, dataType, dataFlags, dataName);
    } else if (strCommand == "createData") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);
        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        int dataType = obj["dataType"].asInt();
        int dataFlags = obj["dataFlags"].asInt();
        const std::string dataName = obj["dataName"].asString();
        const std::string dataValue = obj["dataValue"].asString();
        CreateData(provider, dataType, dataFlags, dataName, dataValue);
    } else if (strCommand == "deleteData") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);
        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        int dataType = obj["dataType"].asInt();
        int dataFlags = obj["dataFlags"].asInt();
        const std::string dataName = obj["dataName"].asString();
        DeleteData(provider, dataType, dataFlags, dataName);
    } else if (strCommand == "setData") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);
        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        int dataType = obj["dataType"].asInt();
        int dataFlags = obj["dataFlags"].asInt();
        const std::string dataName = obj["dataName"].asString();
        const std::string dataValue = obj["dataValue"].asString();
        SetData(provider, dataType, dataFlags, dataName, dataValue);
    } else if (strCommand == "listData") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);
        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        int dataType = obj["dataType"].asInt();
        int dataFlags = obj["dataFlags"].asInt();
        ListData(provider, dataType, dataFlags);
    } else if (strCommand == "challenge") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);
        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        int challengeType = obj["challengeType"].asInt();
        int challengeFlags = obj["challengeFlags"].asInt();
        Challenge(provider, challengeType, challengeFlags);
    } else if (strCommand == "registerNotifier") {
        // parse the JSON
        bool parse = reader.parse(strParam, obj);
        if (!parse) {
            //fprintf(stderr, "%s", "error parsing\n");
            return "unable to parse options";
        }
        event_id = obj["_eventId"].asString();
        std::string provider = obj["provider"].asString();
        int notifierType = obj["notifierType"].asInt();
        int notifierFlags = obj["notifierFlags"].asInt();
        std::string notifierName = obj["notifierName"].asString();
        RegisterNotifier(provider, notifierType, notifierFlags, notifierName);
    }

    return "";
}
Exemplo n.º 5
0
EFI_STATUS
IfrSpan (
  IN FORM_BROWSER_FORMSET  *FormSet,
  IN UINT8                 Flags,
  OUT  EFI_HII_VALUE       *Result
  )
/*++

Routine Description:
  Evaluate opcode EFI_IFR_SPAN.

Arguments:
  FormSet     - Formset which contains this opcode.
  Flags       - FIRST_MATCHING or FIRST_NON_MATCHING.
  Result      - Evaluation result for this opcode.

Returns:
  EFI_SUCCESS - Opcode evaluation success.
  Other       - Opcode evaluation failed.

--*/
{
  EFI_STATUS     Status;
  EFI_HII_VALUE  Value;
  CHAR16         *String[2];
  CHAR16         *Charset;
  UINTN          Base;
  UINTN          Index;
  CHAR16         *StringPtr;
  BOOLEAN        Found;

  Status = PopExpression (&Value);
  if (EFI_ERROR (Status)) {
    return Status;
  }
  if (Value.Type > EFI_IFR_TYPE_NUM_SIZE_64) {
    return EFI_UNSUPPORTED;
  }
  Base = (UINTN) Value.Value.u64;

  //
  // String[0] - Charset
  // String[1] - The string to search
  //
  String[0] = NULL;
  String[1] = NULL;
  for (Index = 0; Index < 2; Index++) {
    Status = PopExpression (&Value);
    if (EFI_ERROR (Status)) {
      goto Done;
    }

    if (Value.Type != EFI_IFR_TYPE_STRING) {
      Status = EFI_UNSUPPORTED;
      goto Done;
    }

    String[Index] = GetToken (Value.Value.string, FormSet->HiiHandle);
    if (String== NULL) {
      Status = EFI_NOT_FOUND;
      goto Done;
    }
  }

  if (Base >= EfiStrLen (String[1])) {
    Status = EFI_UNSUPPORTED;
    goto Done;
  }

  Found = FALSE;
  StringPtr = String[1] + Base;
  Charset = String[0];
  while (*StringPtr != 0 && !Found) {
    Index = 0;
    while (Charset[Index] != 0) {
      if (*StringPtr >= Charset[Index] && *StringPtr <= Charset[Index + 1]) {
        if (Flags == EFI_IFR_FLAGS_FIRST_MATCHING) {
          Found = TRUE;
          break;
        }
      } else {
        if (Flags == EFI_IFR_FLAGS_FIRST_NON_MATCHING) {
          Found = TRUE;
          break;
        }
      }
      //
      // Skip characters pair representing low-end of a range and high-end of a range
      //
      Index += 2;
    }

    if (!Found) {
      StringPtr++;
    }
  }

  Result->Type = EFI_IFR_TYPE_NUM_SIZE_64;
  Result->Value.u64 = StringPtr - String[1];

Done:
  EfiLibSafeFreePool (String[0]);
  EfiLibSafeFreePool (String[1]);

  return Status;
}
Exemplo n.º 6
0
/************************************************************
  NAME         : ParseSlot
  DESCRIPTION  : Parses slot definitions for a
                   defclass statement
  INPUTS       : 1) The logical name of the input source
                 2) The current slot list
                 3) The class precedence list for the class
                    to which this slot is being attached
                    (used to find facets for composite slots)
                 4) A flag indicating if this is a multifield
                    slot or not
                 5) A flag indicating if the type of slot
                    (single or multi) was explicitly
                    specified or not
  RETURNS      : The address of the list of slots,
                   NULL if there was an error
  SIDE EFFECTS : The slot list is allocated
  NOTES        : Assumes "(slot" has already been parsed.
 ************************************************************/
TEMP_SLOT_LINK *ParseSlot(
  Environment *theEnv,
  const char *readSource,
  const char *className,
  TEMP_SLOT_LINK *slist,
  PACKED_CLASS_LINKS *preclist,
  bool multiSlot)
  {
   SlotDescriptor *slot;
   CONSTRAINT_PARSE_RECORD parsedConstraint;
   char specbits[2];
   int rtnCode;
   CLIPSLexeme *newOverrideMsg;

   /* ===============================================================
      Bits in specbits are when slot qualifiers are specified so that
      duplicate or conflicting qualifiers can be detected.

      Shared/local                          bit-0
      Single/multiple                       bit-1
      Read-only/Read-write/Initialize-Only  bit-2
      Inherit/No-inherit                    bit-3
      Composite/Exclusive                   bit-4
      Reactive/Nonreactive                  bit-5
      Default                               bit-6
      Default-dynamic                       bit-7
      Visibility                            bit-8
      Override-message                      bit-9
      =============================================================== */
   SavePPBuffer(theEnv," ");
   specbits[0] = specbits[1] = '\0';
   GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);
   if (DefclassData(theEnv)->ObjectParseToken.tknType != SYMBOL_TOKEN)
     {
      DeleteSlots(theEnv,slist);
      SyntaxErrorMessage(theEnv,"defclass slot");
      return NULL;
     }
   if ((DefclassData(theEnv)->ObjectParseToken.value == (void *) DefclassData(theEnv)->ISA_SYMBOL) ||
       (DefclassData(theEnv)->ObjectParseToken.value == (void *) DefclassData(theEnv)->NAME_SYMBOL))
     {
      DeleteSlots(theEnv,slist);
      SyntaxErrorMessage(theEnv,"defclass slot");
      return NULL;
     }
   slot = NewSlot(theEnv,DefclassData(theEnv)->ObjectParseToken.lexemeValue);
   slist = InsertSlot(theEnv,className,slist,slot);
   if (slist == NULL)
     return NULL;
   if (multiSlot)
     {
      slot->multiple = true;
      SetBitMap(specbits,FIELD_BIT);
     }
      
   GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);
   IncrementIndentDepth(theEnv,3);
   InitializeConstraintParseRecord(&parsedConstraint);
   while (DefclassData(theEnv)->ObjectParseToken.tknType == LEFT_PARENTHESIS_TOKEN)
     {
      PPBackup(theEnv);
      PPCRAndIndent(theEnv);
      SavePPBuffer(theEnv,"(");
      GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);
      if (DefclassData(theEnv)->ObjectParseToken.tknType != SYMBOL_TOKEN)
        {
         SyntaxErrorMessage(theEnv,"defclass slot");
         goto ParseSlotError;
        }
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,DEFAULT_FACET) == 0)
        {
         if (ParseDefaultFacet(theEnv,readSource,specbits,slot) == false)
           goto ParseSlotError;
        }
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,DYNAMIC_FACET) == 0)
        {
         SetBitMap(specbits,DEFAULT_DYNAMIC_BIT);
         if (ParseDefaultFacet(theEnv,readSource,specbits,slot) == false)
           goto ParseSlotError;
        }
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,ACCESS_FACET) == 0)
        {
         rtnCode = ParseSimpleFacet(theEnv,readSource,slot,specbits,ACCESS_FACET,ACCESS_BIT,
                                    SLOT_RDWRT_RLN,SLOT_RDONLY_RLN,SLOT_INIT_RLN,
                                    NULL,NULL);
         if (rtnCode == -1)
           goto ParseSlotError;
         else if (rtnCode == 1)
           slot->noWrite = 1;
         else if (rtnCode == 2)
           slot->initializeOnly = 1;
        }
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,STORAGE_FACET) == 0)
        {
         rtnCode = ParseSimpleFacet(theEnv,readSource,slot,specbits,STORAGE_FACET,STORAGE_BIT,
                                    SLOT_LOCAL_RLN,SLOT_SHARE_RLN,NULL,NULL,NULL);
         if (rtnCode == -1)
           goto ParseSlotError;
         slot->shared = (rtnCode == 0) ? false : true;
        }
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,PROPAGATION_FACET) == 0)
        {
         rtnCode = ParseSimpleFacet(theEnv,readSource,slot,specbits,PROPAGATION_FACET,PROPAGATION_BIT,
                                    SLOT_INH_RLN,SLOT_NO_INH_RLN,NULL,NULL,NULL);
         if (rtnCode == -1)
           goto ParseSlotError;
         slot->noInherit = (rtnCode == 0) ? false : true;
        }
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,SOURCE_FACET) == 0)
        {
         rtnCode = ParseSimpleFacet(theEnv,readSource,slot,specbits,SOURCE_FACET,SOURCE_BIT,
                                    SLOT_EXCLUSIVE_RLN,SLOT_COMPOSITE_RLN,NULL,NULL,NULL);
         if (rtnCode == -1)
           goto ParseSlotError;
         slot->composite = (rtnCode == 0) ? false : true;
        }
#if DEFRULE_CONSTRUCT
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,MATCH_FACET) == 0)
        {
         rtnCode = ParseSimpleFacet(theEnv,readSource,slot,specbits,MATCH_FACET,MATCH_BIT,
                                    SLOT_NONREACTIVE_RLN,SLOT_REACTIVE_RLN,NULL,NULL,NULL);
         if (rtnCode == -1)
           goto ParseSlotError;
         slot->reactive = (rtnCode == 0) ? false : true;
        }
#endif
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,VISIBILITY_FACET) == 0)
        {
         rtnCode = ParseSimpleFacet(theEnv,readSource,slot,specbits,VISIBILITY_FACET,VISIBILITY_BIT,
                                    SLOT_PRIVATE_RLN,SLOT_PUBLIC_RLN,NULL,NULL,NULL);
         if (rtnCode == -1)
           goto ParseSlotError;
         slot->publicVisibility = (rtnCode == 0) ? false : true;
        }
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,CREATE_ACCESSOR_FACET) == 0)
        {
         rtnCode = ParseSimpleFacet(theEnv,readSource,slot,specbits,CREATE_ACCESSOR_FACET,
                                    CREATE_ACCESSOR_BIT,
                                    SLOT_READ_RLN,SLOT_WRITE_RLN,SLOT_RDWRT_RLN,
                                    SLOT_NONE_RLN,NULL);
         if (rtnCode == -1)
           goto ParseSlotError;
         if ((rtnCode == 0) || (rtnCode == 2))
           slot->createReadAccessor = true;
         if ((rtnCode == 1) || (rtnCode == 2))
           slot->createWriteAccessor = true;
        }
      else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,OVERRIDE_MSG_FACET) == 0)
        {
         rtnCode = ParseSimpleFacet(theEnv,readSource,slot,specbits,OVERRIDE_MSG_FACET,OVERRIDE_MSG_BIT,
                                    NULL,NULL,NULL,SLOT_DEFAULT_RLN,&newOverrideMsg);
         if (rtnCode == -1)
           goto ParseSlotError;
         if (rtnCode == 4)
           {
            ReleaseLexeme(theEnv,slot->overrideMessage);
            slot->overrideMessage = newOverrideMsg;
            IncrementLexemeCount(slot->overrideMessage);
           }
         slot->overrideMessageSpecified = true;
        }
      else if (StandardConstraint(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents))
        {
         if (ParseStandardConstraint(theEnv,readSource,DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,
                slot->constraint,&parsedConstraint,true) == false)
           goto ParseSlotError;
        }
      else
        {
         SyntaxErrorMessage(theEnv,"defclass slot");
         goto ParseSlotError;
        }
      GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);
     }
   if (DefclassData(theEnv)->ObjectParseToken.tknType != RIGHT_PARENTHESIS_TOKEN)
     {
      SyntaxErrorMessage(theEnv,"defclass slot");
      goto ParseSlotError;
     }

   if (DefclassData(theEnv)->ClassDefaultsModeValue == CONVENIENCE_MODE)
     {
      if (! TestBitMap(specbits,CREATE_ACCESSOR_BIT))
        {
         slot->createReadAccessor = true;

         if (! slot->noWrite)
           { slot->createWriteAccessor = true; }
        }
     }

   if (slot->composite)
     BuildCompositeFacets(theEnv,slot,preclist,specbits,&parsedConstraint);
   if (CheckForFacetConflicts(theEnv,slot,&parsedConstraint) == false)
     goto ParseSlotError;
   if (CheckConstraintParseConflicts(theEnv,slot->constraint) == false)
     goto ParseSlotError;
   if (EvaluateSlotDefaultValue(theEnv,slot,specbits) == false)
     goto ParseSlotError;
   if ((slot->dynamicDefault == 0) && (slot->noWrite == 1) &&
       (slot->initializeOnly == 0))
     slot->shared = 1;
   slot->constraint = AddConstraint(theEnv,slot->constraint);
   DecrementIndentDepth(theEnv,3);
   return(slist);

ParseSlotError:
   DecrementIndentDepth(theEnv,3);
   DeleteSlots(theEnv,slist);
   return NULL;
  }
Exemplo n.º 7
0
globle int CheckSyntax(
  void *theEnv,
  char *theString,
  DATA_OBJECT_PTR returnValue)
  {
   char *name;
   struct token theToken;
   struct expr *top;
   short rv;

   /*==============================*/
   /* Set the default return value */
   /* (TRUE for problems found).   */
   /*==============================*/

   SetpType(returnValue,SYMBOL);
   SetpValue(returnValue,EnvTrueSymbol(theEnv));

   /*===========================================*/
   /* Create a string source router so that the */
   /* string can be used as an input source.    */
   /*===========================================*/

   if (OpenStringSource(theEnv,"check-syntax",theString,0) == 0)
     { return(TRUE); }

   /*=================================*/
   /* Only expressions and constructs */
   /* can have their syntax checked.  */
   /*=================================*/

   GetToken(theEnv,"check-syntax",&theToken);

   if (theToken.type != LPAREN)
     {
      CloseStringSource(theEnv,"check-syntax");
      SetpValue(returnValue,EnvAddSymbol(theEnv,"MISSING-LEFT-PARENTHESIS"));
      return(TRUE);
     }

   /*========================================*/
   /* The next token should be the construct */
   /* type or function name.                 */
   /*========================================*/

   GetToken(theEnv,"check-syntax",&theToken);
   if (theToken.type != SYMBOL)
     {
      CloseStringSource(theEnv,"check-syntax");
      SetpValue(returnValue,EnvAddSymbol(theEnv,"EXPECTED-SYMBOL-AFTER-LEFT-PARENTHESIS"));
      return(TRUE);
     }

   name = ValueToString(theToken.value);

   /*==============================================*/
   /* Set up a router to capture the error output. */
   /*==============================================*/

   EnvAddRouter(theEnv,"error-capture",40,
              FindErrorCapture, PrintErrorCapture,
              NULL, NULL, NULL);

   /*================================*/
   /* Determine if it's a construct. */
   /*================================*/

   if (FindConstruct(theEnv,name))
     {
      ConstructData(theEnv)->CheckSyntaxMode = TRUE;
      rv = (short) ParseConstruct(theEnv,name,"check-syntax");
      GetToken(theEnv,"check-syntax",&theToken);
      ConstructData(theEnv)->CheckSyntaxMode = FALSE;

      if (rv)
        {
         EnvPrintRouter(theEnv,WERROR,"\nERROR:\n");
         PrintInChunks(theEnv,WERROR,GetPPBuffer(theEnv));
         EnvPrintRouter(theEnv,WERROR,"\n");
        }

      DestroyPPBuffer(theEnv);

      CloseStringSource(theEnv,"check-syntax");

      if ((rv != FALSE) || (ParseFunctionData(theEnv)->WarningString != NULL))
        {
         SetErrorCaptureValues(theEnv,returnValue);
         DeactivateErrorCapture(theEnv);
         return(TRUE);
        }

      if (theToken.type != STOP)
        {
         SetpValue(returnValue,EnvAddSymbol(theEnv,"EXTRANEOUS-INPUT-AFTER-LAST-PARENTHESIS"));
         DeactivateErrorCapture(theEnv);
         return(TRUE);
        }

      SetpType(returnValue,SYMBOL);
      SetpValue(returnValue,EnvFalseSymbol(theEnv));
      DeactivateErrorCapture(theEnv);
      return(FALSE);
     }

   /*=======================*/
   /* Parse the expression. */
   /*=======================*/

   top = Function2Parse(theEnv,"check-syntax",name);
   GetToken(theEnv,"check-syntax",&theToken);
   ClearParsedBindNames(theEnv);
   CloseStringSource(theEnv,"check-syntax");

   if (top == NULL)
     {
      SetErrorCaptureValues(theEnv,returnValue);
      DeactivateErrorCapture(theEnv);
      return(TRUE);
     }

   if (theToken.type != STOP)
     {
      SetpValue(returnValue,EnvAddSymbol(theEnv,"EXTRANEOUS-INPUT-AFTER-LAST-PARENTHESIS"));
      DeactivateErrorCapture(theEnv);
      ReturnExpression(theEnv,top);
      return(TRUE);
     }

   DeactivateErrorCapture(theEnv);

   ReturnExpression(theEnv,top);
   SetpType(returnValue,SYMBOL);
   SetpValue(returnValue,EnvFalseSymbol(theEnv));
   return(FALSE);
  }
Exemplo n.º 8
0
/*
==============
GetToken
==============
*/
qboolean GetToken (qboolean crossline)
{
	char    *token_p;

	if (tokenready)                         // is a token allready waiting?
	{
		tokenready = false;
		return true;
	}

	// printf("script_p %x (%x)\n", script->script_p, script->end_p ); fflush( stdout );

	if (script->script_p >= script->end_p)
	{
		return EndOfScript (crossline);
	}

	tokenready = false;

	// skip space, ctrl chars
skipspace:
	while (*script->script_p <= 32)
	{
		if (script->script_p >= script->end_p)
		{
			return EndOfScript (crossline);
		}
		if (*(script->script_p++) == '\n')
		{
			if (!crossline)
			{
				Error ("Line %i is incomplete\n",scriptline);
			}
			scriptline = ++script->line;
		}
	}

	if (script->script_p >= script->end_p)
	{
		return EndOfScript (crossline);
	}

	// strip single line comments
	if (*script->script_p == ';' || *script->script_p == '#' ||		 // semicolon and # is comment field
		(*script->script_p == '/' && *((script->script_p)+1) == '/')) // also make // a comment field
	{											
		if (!crossline)
			Error ("Line %i is incomplete\n",scriptline);
		while (*script->script_p++ != '\n')
		{
			if (script->script_p >= script->end_p)
			{
				return EndOfScript (crossline);
			}
		}
		scriptline = ++script->line;
		goto skipspace;
	}

	//  strip out matching /* */ comments
	if (*script->script_p == '/' && *((script->script_p)+1) == '*')
	{
		script->script_p += 2;
		while (*script->script_p != '*' || *((script->script_p)+1) != '/')
		{
			if (*script->script_p++ != '\n')
			{
				if (script->script_p >= script->end_p)
				{
					return EndOfScript (crossline);
				}

				scriptline = ++script->line;
			}
		}
		script->script_p += 2;
		goto skipspace;
	}

	// copy token to buffer
	token_p = token;

	if (*script->script_p == '"')
	{
		// quoted token
		script->script_p++;
		while (*script->script_p != '"')
		{
			*token_p++ = *script->script_p++;
			if (script->script_p == script->end_p)
				break;
			if (token_p == &token[MAXTOKEN])
				Error ("Token too large on line %i\n",scriptline);
		}
		script->script_p++;
	}
	else	// regular token
	while ( *script->script_p > 32 && *script->script_p != ';')
	{
		if ( !ExpandMacroToken( token_p ) )
		{
			if ( !ExpandVariableToken( token_p ) )
			{
				*token_p++ = *script->script_p++;
				if (script->script_p == script->end_p)
					break;
				if (token_p == &token[MAXTOKEN])
					Error ("Token too large on line %i\n",scriptline);

			}
		}
	}

	// add null to end of token
	*token_p = 0;

	// check for other commands
	if (!stricmp (token, "$include"))
	{
		GetToken (false);
		AddScriptToStack (token);
		return GetToken (crossline);
	}
	else if (!stricmp (token, "$definemacro"))
	{
		GetToken (false);
		DefineMacro(token);
		return GetToken (crossline);
	}
	else if (!stricmp (token, "$definevariable"))
	{
		GetToken (false);
		DefineVariable(token);
		return GetToken (crossline);
	}
	else if (AddMacroToStack( token ))
	{
		return GetToken (crossline);
	}

	return true;
}
Exemplo n.º 9
0
/*
==============
GetExprToken - use C mathematical operator parsing rules to split tokens instead of whitespace
==============
*/
qboolean GetExprToken (qboolean crossline)
{
	char    *token_p;

	if (tokenready)                         // is a token allready waiting?
	{
		tokenready = false;
		return true;
	}

	if (script->script_p >= script->end_p)
		return EndOfScript (crossline);

	tokenready = false;

//
// skip space
//
skipspace:
	while (*script->script_p <= 32)
	{
		if (script->script_p >= script->end_p)
			return EndOfScript (crossline);
		if (*script->script_p++ == '\n')
		{
			if (!crossline)
				Error ("Line %i is incomplete\n",scriptline);
			scriptline = ++script->line;
		}
	}

	if (script->script_p >= script->end_p)
		return EndOfScript (crossline);

	if (*script->script_p == ';' || *script->script_p == '#' ||		 // semicolon and # is comment field
		(*script->script_p == '/' && *((script->script_p)+1) == '/')) // also make // a comment field
	{											
		if (!crossline)
			Error ("Line %i is incomplete\n",scriptline);
		while (*script->script_p++ != '\n')
			if (script->script_p >= script->end_p)
				return EndOfScript (crossline);
		goto skipspace;
	}

//
// copy token
//
	token_p = token;

	if (*script->script_p == '"')
	{
		// quoted token
		script->script_p++;
		while (*script->script_p != '"')
		{
			*token_p++ = *script->script_p++;
			if (script->script_p == script->end_p)
				break;
			if (token_p == &token[MAXTOKEN])
				Error ("Token too large on line %i\n",scriptline);
		}
		script->script_p++;
	}
	else
	{
		if ( isalpha( *script->script_p ) || *script->script_p == '_' )
		{
			// regular token
			while ( isalnum( *script->script_p ) || *script->script_p == '_' )
			{
				*token_p++ = *script->script_p++;
				if (script->script_p == script->end_p)
					break;
				if (token_p == &token[MAXTOKEN])
					Error ("Token too large on line %i\n",scriptline);
			}
		}
		else if ( isdigit( *script->script_p ) || *script->script_p == '.' )
		{
			// regular token
			while ( isdigit( *script->script_p ) || *script->script_p == '.' )
			{
				*token_p++ = *script->script_p++;
				if (script->script_p == script->end_p)
					break;
				if (token_p == &token[MAXTOKEN])
					Error ("Token too large on line %i\n",scriptline);
			}
		}
		else
		{
			// single char
			*token_p++ = *script->script_p++;
		}
	}

	*token_p = 0;

	if (!stricmp (token, "$include"))
	{
		GetToken (false);
		AddScriptToStack (token);
		return GetToken (crossline);
	}

	return true;
}
Exemplo n.º 10
0
void LoadWadconfig (const char *filename, const char *configname)
{
	int found = 0;
	int count = 0;
	int size;
	char *buffer;
	size = LoadFile (filename, &buffer);
	ParseFromMemory (buffer, size);
	while (GetToken (true))
	{
		bool skip = true;
		if (!stricmp (g_token, configname))
		{
			skip = false;
			found++;
		}
		if (!GetToken (true) || stricmp (g_token, "{"))
		{
			Error ("parsing '%s': missing '{'.", filename);
		}
		while (1)
		{
			if (!GetToken (true))
			{
				Error ("parsing '%s': unexpected end of file.", filename);
			}
			if (!stricmp (g_token, "}"))
			{
				break;
			}
			if (skip)
			{
				continue;
			}
			bool include = false;
			wadpath_t *current;
			if (!stricmp (g_token, "include"))
			{
				include = true;
				if (!GetToken (true))
				{
					Error ("parsing '%s': unexpected end of file.", filename);
				}
			}
			Developer (DEVELOPER_LEVEL_MESSAGE, "LoadWadconfig: adding wad file '%s'.\n", g_token);
			if (g_iNumWadPaths >= MAX_WADPATHS)
			{
				Error ("parsing '%s': too many wad files.", filename);
			}
			count++;
			current = (wadpath_t *)malloc (sizeof (wadpath_t));
			hlassume (current != NULL, assume_NoMemory);
			g_pWadPaths[g_iNumWadPaths] = current;
			g_iNumWadPaths++;
			safe_strncpy (current->path, g_token, _MAX_PATH);
			current->usedbymap = true; // what's this?
			current->usedtextures = 0;
			if (include)
			{
				Developer (DEVELOPER_LEVEL_MESSAGE, "LoadWadcfgfile: including '%s'.\n", current->path);
				g_WadInclude.push_back(current->path);
			}
		}
	}
	if (found == 0)
	{
		Error ("Couldn't find wad configuration '%s' in file '%s'.\n", configname, filename);
	}
	if (found >= 2)
	{
		Error ("Found more than one wad configuration for '%s' in file '%s'.\n", configname, filename);
	}
	free (buffer); // should not be freed because it is still being used as script buffer
	Log ("Using custom wadfile configuration: '%s' (with %i wad%s)\n", configname, count, count > 1 ? "s" : "");
}
Exemplo n.º 11
0
void DefineMacro( char *macroname )
{
	script_t	*pmacro = (script_t *)malloc( sizeof( script_t ) );

	strcpy( pmacro->filename, macroname );
	pmacro->line = script->line;
	pmacro->nummacroparams = 0;

	char *mp = pmacro->macrobuffer;
	char *cp = script->script_p;

	while (TokenAvailable( ))
	{
		GetToken( false );

		if (token[0] == '\\' && token[1] == '\\')
		{
			break;
		}
		cp = script->script_p;

		pmacro->macroparam[pmacro->nummacroparams++] = mp;

		strcpy( mp, token );
		mp += strlen( token ) + 1;

		if (mp >= pmacro->macrobuffer + sizeof( pmacro->macrobuffer ))
			Error("Macro buffer overflow\n");
	}
	// roll back script_p to previous valid location
	script->script_p = cp;

	// find end of macro def
	while (*cp && *cp != '\n')
	{
		//Msg("%d ", *cp );
		if (*cp == '\\' && *(cp+1) == '\\')
		{
			// skip till end of line
			while (*cp && *cp != '\n')
			{
				*cp = ' '; // replace with spaces
				cp++;
			}

			if (*cp)
			{
				cp++;
			}
		}
		else
		{
			cp++;
		}
	}

	int size = (cp - script->script_p);

	pmacro->buffer = (char *)malloc( size + 1);
	memcpy( pmacro->buffer, script->script_p, size );
	pmacro->buffer[size] = '\0';
	pmacro->end_p = &pmacro->buffer[size]; 

	macrolist[nummacros++] = pmacro;

	script->script_p = cp;
}
Exemplo n.º 12
0
static struct expr *ParseAssertSlotValues(
  void *theEnv,
  EXEC_STATUS,
  char *inputSource,
  struct token *tempToken,
  struct templateSlot *slotPtr,
  int *error,
  int constantsOnly)
  {
   struct expr *nextSlot;
   struct expr *newField, *valueList, *lastValue;
   int printError;

   /*=============================*/
   /* Handle a single field slot. */
   /*=============================*/

   if (slotPtr->multislot == FALSE)
     {
      /*=====================*/
      /* Get the slot value. */
      /*=====================*/

      SavePPBuffer(theEnv,execStatus," ");

      newField = GetAssertArgument(theEnv,execStatus,inputSource,tempToken,
                                   error,RPAREN,constantsOnly,&printError);
      if (*error)
        {
         if (printError) SyntaxErrorMessage(theEnv,execStatus,"deftemplate pattern");
         return(NULL);
        }

      /*=================================================*/
      /* A single field slot value must contain a value. */
      /* Only a multifield slot can be empty.            */
      /*=================================================*/

      if (newField == NULL)
       {
        *error = TRUE;
        SingleFieldSlotCardinalityError(theEnv,execStatus,slotPtr->slotName->contents);
        return(NULL);
       }

      /*==============================================*/
      /* A function returning a multifield value can  */
      /* not be called to get the value for the slot. */
      /*==============================================*/

      if ((newField->type == FCALL) ? (ExpressionFunctionType(newField) == 'm') :
                                      (newField->type == MF_VARIABLE))
       {
        *error = TRUE;
        SingleFieldSlotCardinalityError(theEnv,execStatus,slotPtr->slotName->contents);
        ReturnExpression(theEnv,execStatus,newField);
        return(NULL);
       }

      /*============================*/
      /* Move on to the next token. */
      /*============================*/

      GetToken(theEnv,execStatus,inputSource,tempToken);
     }

   /*========================================*/
   /* Handle a multifield slot. Build a list */
   /* of the values stored in the slot.      */
   /*========================================*/

   else
     {
      SavePPBuffer(theEnv,execStatus," ");
      valueList = GetAssertArgument(theEnv,execStatus,inputSource,tempToken,
                                     error,RPAREN,constantsOnly,&printError);
      if (*error)
        {
         if (printError) SyntaxErrorMessage(theEnv,execStatus,"deftemplate pattern");
         return(NULL);
        }

      if (valueList == NULL)
        {
         PPBackup(theEnv,execStatus);
         PPBackup(theEnv,execStatus);
         SavePPBuffer(theEnv,execStatus,")");
        }

      lastValue = valueList;

      while (lastValue != NULL) /* (tempToken->type != RPAREN) */
        {
         if (tempToken->type == RPAREN)
           { SavePPBuffer(theEnv,execStatus," "); }
         else
           {
            /* PPBackup(theEnv,execStatus); */
            SavePPBuffer(theEnv,execStatus," ");
            /* SavePPBuffer(theEnv,execStatus,tempToken->printForm); */
           }

         newField = GetAssertArgument(theEnv,execStatus,inputSource,tempToken,error,RPAREN,constantsOnly,&printError);
         if (*error)
           {
            if (printError) SyntaxErrorMessage(theEnv,execStatus,"deftemplate pattern");
            ReturnExpression(theEnv,execStatus,valueList);
            return(NULL);
           }

         if (newField == NULL)
           {
            PPBackup(theEnv,execStatus);
            PPBackup(theEnv,execStatus);
            SavePPBuffer(theEnv,execStatus,")");
           }

         lastValue->nextArg = newField;
         lastValue = newField;
        }

      newField = valueList;
     }

   /*==========================================================*/
   /* Slot definition must be closed with a right parenthesis. */
   /*==========================================================*/

   if (tempToken->type != RPAREN)
     {
      SingleFieldSlotCardinalityError(theEnv,execStatus,slotPtr->slotName->contents);
      *error = TRUE;
      ReturnExpression(theEnv,execStatus,newField);
      return(NULL);
     }

   /*=========================================================*/
   /* Build and return a structure describing the slot value. */
   /*=========================================================*/

   nextSlot = GenConstant(theEnv,execStatus,SYMBOL,slotPtr->slotName);
   nextSlot->argList = newField;

   return(nextSlot);
  }
Exemplo n.º 13
0
static struct templateSlot *ParseSlotLabel(
  void *theEnv,
  EXEC_STATUS,
  char *inputSource,
  struct token *tempToken,
  struct deftemplate *theDeftemplate,
  int *error,
  int endType)
  {
   struct templateSlot *slotPtr;
   short position;

   /*========================*/
   /* Initialize error flag. */
   /*========================*/

   *error = FALSE;

   /*============================================*/
   /* If token is a right parenthesis, then fact */
   /* template definition is complete.           */
   /*============================================*/

   GetToken(theEnv,execStatus,inputSource,tempToken);
   if (tempToken->type == endType)
     { return(NULL); }

   /*=======================================*/
   /* Put a space between the template name */
   /* and the first slot definition.        */
   /*=======================================*/

   PPBackup(theEnv,execStatus);
   SavePPBuffer(theEnv,execStatus," ");
   SavePPBuffer(theEnv,execStatus,tempToken->printForm);

   /*=======================================================*/
   /* Slot definition begins with opening left parenthesis. */
   /*=======================================================*/

   if (tempToken->type != LPAREN)
     {
      SyntaxErrorMessage(theEnv,execStatus,"deftemplate pattern");
      *error = TRUE;
      return(NULL);
     }

   /*=============================*/
   /* Slot name must be a symbol. */
   /*=============================*/

   GetToken(theEnv,execStatus,inputSource,tempToken);
   if (tempToken->type != SYMBOL)
     {
      SyntaxErrorMessage(theEnv,execStatus,"deftemplate pattern");
      *error = TRUE;
      return(NULL);
     }

   /*======================================================*/
   /* Check that the slot name is valid for this template. */
   /*======================================================*/

   if ((slotPtr = FindSlot(theDeftemplate,(SYMBOL_HN *) tempToken->value,&position)) == NULL)
     {
      InvalidDeftemplateSlotMessage(theEnv,execStatus,ValueToString(tempToken->value),
                                    ValueToString(theDeftemplate->header.name),TRUE);
      *error = TRUE;
      return(NULL);
     }

   /*====================================*/
   /* Return a pointer to the slot name. */
   /*====================================*/

   return(slotPtr);
  }
Exemplo n.º 14
0
void LoadMapSettings(LPSTR szFileName)
{
	if ( (SMDFile = fopen(szFileName, "r")) == NULL )	//ok
	{
		return;
	}

	SMDToken Token;
	int iType = 0;

	while ( true )
	{
		Token = GetToken();

		if (Token == END )
		{
			break;
		}

		iType = TokenNumber;

		while ( true )
		{
			Token = GetToken();

			if ( Token == END )
			{
				break;
			}

			if ( iType >= 0 && iType <= MAX_NUMBER_MAP-1)
			{
				if ( strcmp("end", TokenString) == 0 )
				{
					break;
				}
				
				int ExpSingleInc = 0;
				int ExpPartyInc = 0;
				int DropIncrease = 0;
				int DropExcIncrease = 0;

				ExpSingleInc = TokenNumber;
				
				Token = GetToken();
				ExpPartyInc = TokenNumber;

				Token = GetToken();
				DropIncrease =  TokenNumber;

				Token = GetToken();
				DropExcIncrease = TokenNumber;

				Token = GetToken();
				g_MAP_SETTINGS[iType].drop_zen_increase = TokenNumber;
			
				g_MAP_SETTINGS[iType].exp_increase = ExpSingleInc;
				g_MAP_SETTINGS[iType].exp_party_increase = ExpPartyInc;
				g_MAP_SETTINGS[iType].drop_increase = DropIncrease;
				g_MAP_SETTINGS[iType].drop_exc_increase = DropExcIncrease;
			}
		}
	}

	fclose(SMDFile);
}
Exemplo n.º 15
0
//-----------------------------------------------------------------------------
// (For text buffers only)
// Parse a token from the buffer:
// Grab all text that lies between a starting delimiter + ending delimiter
// (skipping whitespace that leads + trails both delimiters).
// Note the delimiter checks are case-insensitive.
// If successful, the get index is advanced and the function returns true,
// otherwise the index is not advanced and the function returns false.
//-----------------------------------------------------------------------------
bool CUtlBuffer::ParseToken( const char *pStartingDelim, const char *pEndingDelim, char* pString, int nMaxLen )
{
	int nCharsToCopy = 0;
	int nCurrentGet = 0;

	size_t nEndingDelimLen;

	// Starting delimiter is optional
	char emptyBuf = '\0';
	if ( !pStartingDelim )
	{
		pStartingDelim = &emptyBuf;
	}

	// Ending delimiter is not
	Assert( pEndingDelim && pEndingDelim[0] );
	nEndingDelimLen = Q_strlen( pEndingDelim );

	int nStartGet = TellGet();
	char nCurrChar;
	int nTokenStart = -1;
	EatWhiteSpace( );
	while ( *pStartingDelim )
	{
		nCurrChar = *pStartingDelim++;
		if ( !isspace((unsigned char)nCurrChar) )
		{
			if ( tolower( GetChar() ) != tolower( nCurrChar ) )
				goto parseFailed;
		}
		else
		{
			EatWhiteSpace();
		}
	}

	EatWhiteSpace();
	nTokenStart = TellGet();
	if ( !GetToken( pEndingDelim ) )
		goto parseFailed;

	nCurrentGet = TellGet();
	nCharsToCopy = (nCurrentGet - nEndingDelimLen) - nTokenStart;
	if ( nCharsToCopy >= nMaxLen )
	{
		nCharsToCopy = nMaxLen - 1;
	}

	if ( nCharsToCopy > 0 )
	{
		SeekGet( CUtlBuffer::SEEK_HEAD, nTokenStart );
		Get( pString, nCharsToCopy );
		if ( !IsValid() )
			goto parseFailed;

		// Eat trailing whitespace
		for ( ; nCharsToCopy > 0; --nCharsToCopy )
		{
			if ( !isspace( (unsigned char)pString[ nCharsToCopy-1 ] ) )
				break;
		}
	}
	pString[ nCharsToCopy ] = '\0';

	// Advance the Get index
	SeekGet( CUtlBuffer::SEEK_HEAD, nCurrentGet );
	return true;

parseFailed:
	// Revert the get index
	SeekGet( SEEK_HEAD, nStartGet );
	pString[0] = '\0';
	return false;
}
Exemplo n.º 16
0
/*
=================
Cmd_Modelname

Gives a different name/location for the file, instead of the cddir
=================
*/
void Cmd_Modelname (void)
{
	GetToken (false);
	strcpy (modelname, token);
}
Exemplo n.º 17
0
BOOL TMonsterAIGroup::LoadData(LPSTR lpszFileName)
{
	TMonsterAIGroup::s_bDataLoad = FALSE;

	if ( !lpszFileName || !strcmp(lpszFileName, ""))
	{
		MsgBox("[Monster AI Group] - File load error : File Name Error");
		return FALSE;
	}

	try
	{
		SMDToken Token;
		SMDFile = fopen(lpszFileName, "r");	//ok

		if ( SMDFile == NULL )
		{
			MsgBox("[Monster AI Group] - Can't Open %s ", lpszFileName);
			return FALSE;
		}

		int iType = -1;

		while ( true )
		{
			Token = GetToken();

			if ( Token == END )
				break;

			iType = TokenNumber;

			while ( true )
			{
				if ( iType == 0 )
				{
					int iGroupNumber = -1;
					int iGuid = -1;
					int iClass = -1;
					int iRank = -1;
					int iStartAI = 0;
					int iAI01 = 0;
					int iAI02 = 0;
					int iAI03 = 0;
					int iCreateType = -1;
					int iMapNumber = -1;
					int iStartX = -1;
					int iStartY = -1;
					int iStartDir = -1;
					int iRegenType = -1;

					Token = GetToken();

					if ( !strcmp("end", TokenString))
						break;

					iGroupNumber = TokenNumber;

					Token = GetToken();
					iGuid = TokenNumber;

					Token = GetToken();
					iClass = TokenNumber;

					Token = GetToken();
					iRank = TokenNumber;

					Token = GetToken();
					iStartAI = TokenNumber;

					Token = GetToken();
					iAI01 = TokenNumber;

					Token = GetToken();
					iAI02 = TokenNumber;

					Token = GetToken();
					iAI03 = TokenNumber;

					Token = GetToken();
					iCreateType = TokenNumber;

					Token = GetToken();
					iMapNumber = TokenNumber;

					Token = GetToken();
					iStartX = TokenNumber;

					Token = GetToken();
					iStartY = TokenNumber;

					Token = GetToken();
					iStartDir = TokenNumber;

					Token = GetToken();
					iRegenType = TokenNumber;

					if ( iGroupNumber > MAX_MONSTER_AI_GROUP )
					{
						MsgBox("[Monster AI Group] Exceed Max GroupNumber %d",
							iGroupNumber);
						continue;
					}

					if ( iGuid > MAX_MONSTER_AI_GROUP_MEMBER)
					{
						MsgBox("[Monster AI Group] Exceed Max GroupMember %d, %d ",
							iGroupNumber, iGuid);
						continue;
					}

					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iGroupNumber = iGroupNumber;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iGuid = iGuid;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iClass = iClass;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iRank = iRank;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iStartAI = iStartAI;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iAI01 = iAI01;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iAI02 = iAI02;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iAI03 = iAI03;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iCreateType = iCreateType;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iMapNumber = iMapNumber;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iStartX = iStartX;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iStartY = iStartY;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iStartDir = iStartDir;
					TMonsterAIGroup::s_MonsterAIGroupMemberArray[iGroupNumber][iGuid].m_iRegenType = iRegenType;
					
					TMonsterAIGroup::s_iMonsterAIGroupMemberCount[iGroupNumber]++;
				}
			}
		}	// while ( true )

		fclose(SMDFile);

		LogAddC(2, "[Monster AI Group ] - %s file is Loaded", lpszFileName);

		TMonsterAIGroup::s_bDataLoad = TRUE;
	}
	catch ( DWORD )
	{
		MsgBox("[Monster AI Group] - Loading Exception Error (%s) File. ", lpszFileName);
	}

	return FALSE;
}
Exemplo n.º 18
0
/*
=================
Cmd_Base
=================
*/
void Cmd_Base (void)
{
	triangle_t	*ptri;
	int			i, j, k;
	int		time1;
	char	file1[1024];

	GetToken (false);

	if (g_skipmodel || g_release || g_archive)
		return;

	printf ("---------------------\n");
	sprintf (file1, "%s/%s.%s", cdarchive, token, trifileext);
	printf ("%s\n", file1);

	ExpandPathAndArchive (file1);

	sprintf (file1, "%s/%s.%s", cddir, token, trifileext);

	time1 = FileTime (file1);
	if (time1 == -1)
		Error ("%s doesn't exist", file1);

//
// load the base triangles
//
	if (do3ds)
		Load3DSTriangleList (file1, &ptri, &model.num_tris);
	else if (doobj)
		LoadOBJTriangleList (file1, &ptri, &model.num_tris);
	else
		LoadTriangleList (file1, &ptri, &model.num_tris);

//
// get the ST values
//
	BuildST (ptri, model.num_tris);

//
// run through all the base triangles, storing each unique vertex in the
// base vertex list and setting the indirect triangles to point to the base
// vertices
//
	for (i=0 ; i<model.num_tris ; i++)
	{
		for (j=0 ; j<3 ; j++)
		{
			// get the xyz index
			for (k=0 ; k<model.num_xyz ; k++)
				if (VectorCompare (ptri[i].verts[j], base_xyz[k]))
					break;	// this vertex is already in the base vertex list

			if (k == model.num_xyz)
			{ // new index
				VectorCopy (ptri[i].verts[j], base_xyz[model.num_xyz]);
				model.num_xyz++;
			}

			triangles[i].index_xyz[j] = k;

			// get the st index
			for (k=0 ; k<model.num_st ; k++)
				if (triangle_st[i][j][0] == base_st[k].s
				&& triangle_st[i][j][1] == base_st[k].t)
					break;	// this vertex is already in the base vertex list

			if (k == model.num_st)
			{ // new index
				base_st[model.num_st].s = triangle_st[i][j][0];
				base_st[model.num_st].t = triangle_st[i][j][1];
				model.num_st++;
			}

			triangles[i].index_st[j] = k;
		}
	}

	// build triangle strips / fans
	BuildGlCmds ();
}
Exemplo n.º 19
0
/****************************************************************
  NAME         : ParseSimpleFacet
  DESCRIPTION  : Parses the following facets for a slot:
                   access, source, propagation, storage,
                   pattern-match, visibility and override-message
  INPUTS       : 1) The input logical name
                 2) The bitmap indicating which facets have
                    already been parsed
                 3) The name of the facet
                 4) The bit to test/set in arg #2 for this facet
                 5) The facet value string which indicates the
                    facet should be false
                 6) The facet value string which indicates the
                    facet should be true
                 7) An alternate value string for use when the
                    first two don't match (can be NULL)
                 7) An alternate value string for use when the
                    first three don't match (can be NULL)
                    (will be an SF_VARIABLE type)
                 9) A buffer to hold the facet value symbol
                    (can be NULL - only set if args #5 and #6
                     are both NULL)
  RETURNS      : -1 on errors
                  0 if first value string matched
                  1 if second value string matched
                  2 if alternate value string matched
                  3 if variable value string matched
                  4 if facet value buffer was set
  SIDE EFFECTS : Messages printed on errors
                 Bitmap marked indicating facet was parsed
                 Facet value symbol buffer set, if appropriate
  NOTES        : None
 *****************************************************************/
static int ParseSimpleFacet(
  Environment *theEnv,
  const char *readSource,
  SlotDescriptor *slot,
  char *specbits,
  const char *facetName,
  int testBit,
  const char *clearRelation,
  const char *setRelation,
  const char *alternateRelation,
  const char *varRelation,
  CLIPSLexeme **facetSymbolicValue)
  {
   int rtnCode;

   if (TestBitMap(specbits,testBit))
     {
      PrintErrorID(theEnv,"CLSLTPSR",2,false);
      WriteString(theEnv,STDERR,"The '");
      WriteString(theEnv,STDERR,facetName);
      WriteString(theEnv,STDERR,"' facet for slot '");
      WriteString(theEnv,STDERR,slot->slotName->name->contents);
      WriteString(theEnv,STDERR,"' is already specified.\n");
      return -1;
     }
   SetBitMap(specbits,testBit);
   SavePPBuffer(theEnv," ");
   GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);

   /* ===============================
      Check for the variable relation
      =============================== */
   if (DefclassData(theEnv)->ObjectParseToken.tknType == SF_VARIABLE_TOKEN)
     {
      if ((varRelation == NULL) ? false :
          (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,varRelation) == 0))
        rtnCode = 3;
      else
        goto ParseSimpleFacetError;
     }
   else
     {
      if (DefclassData(theEnv)->ObjectParseToken.tknType != SYMBOL_TOKEN)
        goto ParseSimpleFacetError;

      /* ===================================================
         If the facet value buffer is non-NULL
         simply get the value and do not check any relations
         =================================================== */
      if (facetSymbolicValue == NULL)
        {
         if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,clearRelation) == 0)
           rtnCode = 0;
         else if (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,setRelation) == 0)
           rtnCode = 1;
         else if ((alternateRelation == NULL) ? false :
                  (strcmp(DefclassData(theEnv)->ObjectParseToken.lexemeValue->contents,alternateRelation) == 0))
           rtnCode = 2;
         else
           goto ParseSimpleFacetError;
        }
      else
        {
         rtnCode = 4;
         *facetSymbolicValue = DefclassData(theEnv)->ObjectParseToken.lexemeValue;
        }
     }
   GetToken(theEnv,readSource,&DefclassData(theEnv)->ObjectParseToken);
   if (DefclassData(theEnv)->ObjectParseToken.tknType != RIGHT_PARENTHESIS_TOKEN)
     goto ParseSimpleFacetError;
   return(rtnCode);

ParseSimpleFacetError:
   SyntaxErrorMessage(theEnv,"slot facet");
   return(-1);
  }
Exemplo n.º 20
0
/* (), fn(), [], <x, y, z>, . */
Expr *Term15(void)
{
	switch(token) 
	{
		/* 0 parameter functions returning floats */
		case FN_FRAND:
			return MakeFunc(eval_frand, 0, 0);

		/* 0 parameter functions returning vectors */
		case FN_VRAND:
			return MakeFunc(eval_vrand, 0, 1);

		/* 1 parameter functions returning floats */
		case FN_ABS:
			return MakeFunc(eval_abs, 1, 0);
		case FN_ACOS:
			return MakeFunc(eval_acos, 1, 0);
		case FN_ASIN:
			return MakeFunc(eval_asin, 1, 0);
		case FN_ATAN:
			return MakeFunc(eval_atan, 1, 0);
		case FN_CEIL:
			return MakeFunc(eval_ceil, 1, 0);
		case FN_CHECKER:
			return MakeFunc(eval_checker, 1, 0);
		case FN_COS:
			return MakeFunc(eval_cos, 1, 0);
		case FN_COSH:
			return MakeFunc(eval_cosh, 1, 0);
		case FN_EXP:
			return MakeFunc(eval_exp, 1, 0);
		case FN_FLOOR:
			return MakeFunc(eval_floor, 1, 0);
		case FN_INT:
			return MakeFunc(eval_int, 1, 0);
		case FN_IRAND:
			return MakeFunc(eval_irand, 1, 0);
		case FN_LOG:
			return MakeFunc(eval_log, 1, 0);
		case FN_LOG10:
			return MakeFunc(eval_log10, 1, 0);
		case FN_NOISE:
			return MakeFunc(eval_noise, 1, 0);
		case FN_ROUND:
			return MakeFunc(eval_round, 1, 0);
		case FN_SIN:
			return MakeFunc(eval_sin, 1, 0);
		case FN_SINH:
			return MakeFunc(eval_sinh, 1, 0);
		case FN_SQRT:
			return MakeFunc(eval_sqrt, 1, 0);
		case FN_TAN:
			return MakeFunc(eval_tan, 1, 0);
		case FN_TANH:
			return MakeFunc(eval_tanh, 1, 0);
		case FN_VMAG:
			return MakeFunc(eval_vmag, 1, 0);

		/* 1 parameter functions returning vectors */
		case FN_VNOISE:
			return MakeFunc(eval_vnoise, 1, 1);
		case FN_VNORM:
			return MakeFunc(eval_vnorm, 1, 1);

		/* 2 parameter functions returning floats */
		case FN_ATAN2:
			return MakeFunc(eval_atan2, 2, 0);
		case FN_HEXAGON:
			return MakeFunc(eval_hexagon, 2, 0);
		case FN_TURB:
			return MakeFunc(eval_turb, 2, 0);
		case FN_VDOT:
			return MakeFunc(eval_vdot, 2, 0);

		/* 2 parameter functions returning vectors */
		case FN_COLOR_MAP:
			return MakeHandleFunc(eval_color_map,
				DECL_COLOR_MAP, 1, 1);
		case FN_IMAGE_MAP:
			return MakeImageMapFunc(eval_image_map);
		case FN_SMOOTH_IMAGE_MAP:
			return MakeImageMapFunc(eval_smooth_image_map);
		case FN_VCROSS:
			return MakeFunc(eval_vcross, 2, 1);
		case FN_VTURB:
			return MakeFunc(eval_vturb, 2, 1);
		case FN_WRINKLE:
			return MakeFunc(eval_wrinkle, 2, 1);

		/* 3 parameter functions returning floats */
		case FN_CLAMP:
			return MakeFunc(eval_clamp, 3, 0);
		case FN_LEGENDRE:
			return MakeFunc(eval_legendre, 3, 0);
		case FN_LERP:
			return MakeFunc(eval_lerp, 3, 0);

		/* 3 parameter functions with indeterminate return type */
		case FN_CHECKER2:
			return MakeFunc(eval_checker2, 3, 0);

		/* 3 parameter functions returning vectors */
		case FN_VROTATE:
			return MakeFunc(eval_vrotate, 3, 1);
		case FN_VLERP:
			return MakeFunc(eval_vlerp, 3, 1);

		/* 4 parameter functions returning floats */
		case FN_TURB2:
			return MakeFunc(eval_turb2, 4, 0);

		/* 4 parameter functions returning vectors */
		case FN_VTURB2:
			return MakeFunc(eval_vturb2, 4, 1);

		/* 5 parameter functions with indeterminate return type */
		case FN_HEXAGON2:
			return MakeFunc(eval_hexagon2, 5, 0);

		case OP_LPAREN:
		{
			Expr *expr;
			token = GetToken();
			expr = Term0();
			if(token == OP_RPAREN)
				token = GetToken();
			else
				ErrUnknown(token, ")", "expression syntax");
			return expr;
		}
		break;

		case OP_LESSTHAN:  /* starting a vector triplet */
			return MakeVec();

		default:
			break;
	}
	return Atom();
}
vector<CLogModel*> CHistoryItemLogParser::ParseLog(long& lPosition, long lLength, char* pBuffer)
{
	map<long long,string> mapHostMacDict;
	string strFormatLog;
	stringstream strErrorMess;
	int iZbxServerId, iValueType, iMaintenance;	
	string strHost, strKey_, strHostName, strIfAddress, strZbIpAddress, strSerialNumber;
	string strTemp;
	string strValue;
	HostInfo tagHostInfo;
	long long lItemId, lClock, lHostId, lServerId;

	
	vector<CLogModel*> vtHistoryItemModelPtr;

	while (lPosition < lLength) 
	{
		//	ResetHostInfo(tagHostInfo);
			// Init database fields
		lClock = iZbxServerId = lHostId = lItemId = iValueType = lServerId = iMaintenance = 0;
		strKey_ = strValue = strHost = strHostName = strIfAddress = strZbIpAddress = strSerialNumber = "";
		CLogModel* pLogModel = RegisterModel();

		//Parse Clock
		lClock = ParseLong((const char*)pBuffer, lPosition, lLength);

		//Parse ServerId
		iZbxServerId = ParseInt((const char*)pBuffer, lPosition, lLength);

		//Parse HostId
		lHostId = ParseLong((const char*)pBuffer, lPosition, lLength);
			
		// Calculate ServerId
		lServerId = ((lHostId - 10000) * 256) + iZbxServerId;

		//Parse Hostname
		strTemp = GetBlock((const char*)pBuffer, lPosition, lLength);
		if(strTemp.compare("") != 0)
		{
			strHostName = strTemp;
			strHostName = CUtilities::ReplaceBlockBracket(strHostName);
			strHost = strHostName;
		}

		//Parse zb IP Address
		strTemp = GetBlock((const char*)pBuffer, lPosition, lLength);
		if(strTemp.compare("") != 0)
		{
			strIfAddress = strTemp;
			strIfAddress = CUtilities::ReplaceBlockBracket(strIfAddress);
			strZbIpAddress = strIfAddress;
		}

		//Parse Maintenance Status
		iMaintenance = ParseInt((const char*)pBuffer, lPosition, lLength);

		//Parse ItemId
		lItemId = ParseLong((const char*)pBuffer, lPosition, lLength);			
			
		//Parse Key_
		strKey_ = GetItemKey((const char*)pBuffer, lPosition, lLength);
			
		//Parse Value Type
		iValueType = ParseInt((const char*)pBuffer, lPosition, lLength);			

		//Parse Value
		if (strKey_.compare(SYSTEM_INFO) == 0 
			|| strKey_.compare(VB_SYSTEM_INFO) == 0 
			|| strKey_.compare(OS_INFO) == 0)
		{
			try
			{
				//ParseSystemInfo((const char*)pBuffer, lPosition, lLength, lServerId, mapHostMacDict, tagHostInfo);
				strValue = GetValueBlock((const char*)pBuffer, lPosition, lLength);
			}
			catch(exception& ex)
			{
				strErrorMess << ex.what() << " " << __FILE__ << " " << __LINE__;
				strFormatLog = CUtilities::FormatLog(ERROR_MSG, "CHistoryItemLogParser", "ParseLog", strErrorMess.str());
				CUtilities::WriteErrorLog(strFormatLog);
			}
		}
		else if (strKey_.compare(SDK_READ_TEXT) == 0 || strKey_.compare(SDK_READ_TEXT_LINUX) == 0)
		{
			strTemp = GetToken((const char*)pBuffer, lPosition, lLength);
			if (strTemp.compare("") != 0)
			{
				strValue = strTemp;
				strSerialNumber = strValue;
				strSerialNumber.erase(std::find_if(tagHostInfo.strSerialNumber.rbegin(), tagHostInfo.strSerialNumber.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), tagHostInfo.strSerialNumber.end());
			}
		}

		else
			strValue = GetItemValue((const char*)pBuffer, lPosition, lLength);
		
		CHistoryItemModel *pHistoryItemModel = dynamic_cast<CHistoryItemModel*>(pLogModel);

		pHistoryItemModel->SetItemId(lItemId);
		pHistoryItemModel->SetKey_(strKey_);
		pHistoryItemModel->SetValueType(iValueType);
		pHistoryItemModel->SetValue(strValue);
		pHistoryItemModel->SetServerId(lServerId);
		pHistoryItemModel->SetZabbixServerId(iZbxServerId);
		pHistoryItemModel->SetHostId(lHostId);
		pHistoryItemModel->SetSerialNumber(strSerialNumber);
		pHistoryItemModel->SetHost(strHost);
		pHistoryItemModel->SetHostName(strHostName);
		pHistoryItemModel->SetZbIpAddress(strZbIpAddress);
		pHistoryItemModel->SetMaintenance(iMaintenance);
		pHistoryItemModel->SetClock(lClock);

		if (ExtractData(pHistoryItemModel))
		{
			vtHistoryItemModelPtr.push_back(pHistoryItemModel);
		}
		else
		{
			delete pHistoryItemModel;
		}
	}
	return vtHistoryItemModelPtr;
}
Exemplo n.º 22
0
Expr *Atom(void)
{
	Expr *expr = ExprNew();

	switch(token)
	{
		case CV_FLOAT_CONST:
		case CV_INT_CONST:
			expr->v.x = atof(token_buffer);
			break;
		case CV_PI_CONST:
			expr->v.x = PI;
			break;

		case DECL_FLOAT:
		case DECL_VECTOR:
			expr->data = (void *)LValueCopy((LValue *)cur_token->data);
			expr->fn = eval_lvalue;
			expr->isvec = (token == DECL_VECTOR) ? 1 : 0;
			break;

		case RT_D: /* Ray direction "D" variable. */
			expr->data = (void *)&rt_D;
			expr->fn = eval_rtvec;
			expr->isvec = 1;
			break;
		case RT_N: /* World normal "N" variable. */
			expr->data = (void *)&rt_WN;
			expr->fn = eval_rtvec;
			expr->isvec = 1;
			break;
		case RT_O: /* Object point hit "O" variable. */
			expr->data = (void *)&rt_O;
			expr->fn = eval_rtvec;
			expr->isvec = 1;
			break;
		case RT_ON: /* Object normal "N" variable. */
			expr->data = (void *)&rt_ON;
			expr->fn = eval_rtvec;
			expr->isvec = 1;
			break;
		case RT_USCREEN: /* "uscreen" variable. */
			expr->data = (void *)&rt_uscreen;
			expr->fn = eval_rtfloat;
			break;
		case RT_VSCREEN: /* "vscreen" variable. */
			expr->data = (void *)&rt_vscreen;
			expr->fn = eval_rtfloat;
			break;
		case RT_U: /* Object "u" variable. */
			expr->data = (void *)&rt_u;
			expr->fn = eval_rtfloat;
			break;
		case RT_V: /* Object "v" variable. */
			expr->data = (void *)&rt_v;
			expr->fn = eval_rtfloat;
			break;
		case RT_X: /* Object "x" variable. */
			expr->data = (void *)&rt_O.x;
			expr->fn = eval_rtfloat;
			break;
		case RT_Y: /* Object "y" variable. */
			expr->data = (void *)&rt_O.y;
			expr->fn = eval_rtfloat;
			break;
		case RT_Z: /* Object "z" variable. */
			expr->data = (void *)&rt_O.z;
			expr->fn = eval_rtfloat;
			break;

		default:
			ExprDelete(expr);
			return NULL;
	}

	token = GetToken();
	
	return expr;
}
Exemplo n.º 23
0
EFI_STATUS
IfrToken (
  IN FORM_BROWSER_FORMSET  *FormSet,
  OUT  EFI_HII_VALUE       *Result
  )
/*++

Routine Description:
  Evaluate opcode EFI_IFR_TOKEN.

Arguments:
  FormSet     - Formset which contains this opcode.
  Result      - Evaluation result for this opcode.

Returns:
  EFI_SUCCESS - Opcode evaluation success.
  Other       - Opcode evaluation failed.

--*/
{
  EFI_STATUS     Status;
  EFI_HII_VALUE  Value;
  CHAR16         *String[2];
  UINTN          Count;
  CHAR16         *Delimiter;
  CHAR16         *SubString;
  CHAR16         *StringPtr;
  UINTN          Index;

  Status = PopExpression (&Value);
  if (EFI_ERROR (Status)) {
    return Status;
  }
  if (Value.Type > EFI_IFR_TYPE_NUM_SIZE_64) {
    return EFI_UNSUPPORTED;
  }
  Count = (UINTN) Value.Value.u64;

  //
  // String[0] - Delimiter
  // String[1] - The string to search
  //
  String[0] = NULL;
  String[1] = NULL;
  for (Index = 0; Index < 2; Index++) {
    Status = PopExpression (&Value);
    if (EFI_ERROR (Status)) {
      goto Done;
    }

    if (Value.Type != EFI_IFR_TYPE_STRING) {
      Status = EFI_UNSUPPORTED;
      goto Done;
    }

    String[Index] = GetToken (Value.Value.string, FormSet->HiiHandle);
    if (String== NULL) {
      Status = EFI_NOT_FOUND;
      goto Done;
    }
  }

  Delimiter = String[0];
  SubString = String[1];
  while (Count > 0) {
    SubString = EfiStrStr (SubString, Delimiter);
    if (SubString != NULL) {
      //
      // Skip over the delimiter
      //
      SubString = SubString + EfiStrLen (Delimiter);
    } else {
      break;
    }
    Count--;
  }

  if (SubString == NULL) {
    //
    // nth delimited sub-string not found, push an empty string
    //
    SubString = gEmptyString;
  } else {
    //
    // Put a NULL terminator for nth delimited sub-string
    //
    StringPtr = EfiStrStr (SubString, Delimiter);
    if (StringPtr != NULL) {
      *StringPtr = L'\0';
    }
  }

  Result->Type = EFI_IFR_TYPE_STRING;
  Result->Value.string = NewString (SubString, FormSet->HiiHandle);

Done:
  EfiLibSafeFreePool (String[0]);
  EfiLibSafeFreePool (String[1]);

  return Status;
}
Exemplo n.º 24
0
Expr *MakeHandleFunc(void (*fn)(Expr *), int handle_token,
	int nparams, int returns_vec)
{
	Expr *expr = NULL;
	void *data = NULL;
	TOKEN *fntoken = cur_token;
	token = GetToken();
	if(token == OP_LPAREN)
	{
		/*
		 * Look for a handle to a declared type that matches
		 * the type specified by handle_token.
		 */
		token = GetToken();
		if(token == handle_token)
		{
			switch(token)
			{
				case DECL_COLOR_MAP:
					data = (void *)ColorMap_Copy((ColorMap *)cur_token->data);
					break;
			}
		}
		else
		{
			switch(handle_token)
			{
				case DECL_COLOR_MAP:
					ErrUnknown(token, "color map handle id", "expression syntax");
					break;
				default:
					ErrUnknown(token, "handle to a declared item",
						"expression syntax");
					break;
			}
		}
		/* Get the first comma if more params follow. */
		if(nparams > 0)
		{
			token = GetToken();
			if(token != OP_COMMA)
				ErrUnknown(token, ",", "expression syntax");
		}
		if(nparams < 2)
		{
			expr = ExprNew();
			expr->fn = fn;
			expr->data = data;
			expr->isvec = returns_vec ? 1 : 0;
			token = GetToken();
			expr->l = Term0();
			if(token == OP_RPAREN)
			{
				CheckParamCount(expr->l, fntoken->name, nparams);
				token = GetToken();
			}
			else
				ErrUnknown(token, ")", "expression syntax");
		}
		else
		{
			token = GetToken();
			expr = Term0();
			if(token == OP_RPAREN)
			{
				CheckParamCount(expr, fntoken->name, nparams);
				token = GetToken();
				if(expr != NULL)
				{
					expr->fn = fn;
					expr->data = data;
					expr->isvec = returns_vec ? 1 : 0;
				}
				else if(data != NULL)
				{
					switch(token)
					{
						case DECL_COLOR_MAP:
							ColorMap_Delete((ColorMap *)data);
							break;
					}
				}
			}
			else
				ErrUnknown(token, ")", "expression syntax");
		}
	}
	else
		ErrUnknown(token, "(", "expression syntax");
	return expr;
}
Exemplo n.º 25
0
INTN
CompareHiiValue (
  IN  EFI_HII_VALUE   *Value1,
  IN  EFI_HII_VALUE   *Value2,
  IN  EFI_HII_HANDLE  HiiHandle OPTIONAL
  )
/*++

Routine Description:
  Compare two Hii value.

Arguments:
  Value1    - Expression value to compare on left-hand
  Value2    - Expression value to compare on right-hand
  HiiHandle - Only required for string compare

Returns:
  EFI_INVALID_PARAMETER  - Could not perform comparation on two values
  0                      - Two operators equeal
  < 0                    - Value1 is greater than Value2
  > 0                    - Value1 is less than Value2

--*/
{
  INTN    Result;
  INT64   Temp64;
  CHAR16  *Str1;
  CHAR16  *Str2;

  if (Value1->Type >= EFI_IFR_TYPE_OTHER || Value2->Type >= EFI_IFR_TYPE_OTHER ) {
    return EFI_INVALID_PARAMETER;
  }

  if (Value1->Type == EFI_IFR_TYPE_STRING || Value2->Type == EFI_IFR_TYPE_STRING ) {
    if (Value1->Type != Value2->Type) {
      //
      // Both Operator should be type of String
      //
      return EFI_INVALID_PARAMETER;
    }

    if (Value1->Value.string == 0 || Value2->Value.string == 0) {
      //
      // StringId 0 is reserved
      //
      return EFI_INVALID_PARAMETER;
    }

    if (Value1->Value.string == Value2->Value.string) {
      return 0;
    }

    Str1 = GetToken (Value1->Value.string, HiiHandle);
    if (Str1 == NULL) {
      //
      // String not found
      //
      return EFI_INVALID_PARAMETER;
    }

    Str2 = GetToken (Value2->Value.string, HiiHandle);
    if (Str2 == NULL) {
      gBS->FreePool (Str1);
      return EFI_INVALID_PARAMETER;
    }

    Result = EfiStrCmp (Str1, Str2);

    gBS->FreePool (Str1);
    gBS->FreePool (Str2);

    return Result;
  }

  //
  // Take remain types(integer, boolean, date/time) as integer
  //
  Temp64 = (INT64) (Value1->Value.u64 - Value2->Value.u64);
  if (Temp64 > 0) {
    Result = 1;
  } else if (Temp64 < 0) {
    Result = -1;
  } else {
    Result = 0;
  }

  return Result;
}
Exemplo n.º 26
0
int unregisterFromGtm(char *line)
{
	char *token;
	int rc;

	for(;GetToken();)
	{
		if (testToken("-n"))
		{
			if (!GetToken())
				return(inputError("No -n option value was found."));
			Free(myname);
			myname = Strdup(token);
			continue;
		}
		else if (testToken("-Z"))
		{
			if (!GetToken())
				return(inputError("No -Z option value was found."));
			if (testToken("gtm"))
			{
				nodetype = GTM_NODE_GTM;
				continue;
			}
			else if (testToken("gtm_proxy"))
			{
				nodetype = GTM_NODE_GTM_PROXY;
				break;
			}
			else if (testToken("gtm_proxy_postmaster"))
			{
				nodetype = GTM_NODE_GTM_PROXY_POSTMASTER;
				break;
			}
			else if (testToken("coordinator"))
			{
				nodetype = GTM_NODE_COORDINATOR;
				break;
			}
			else if (testToken("datanode"))
			{
				nodetype = GTM_NODE_DATANODE;
				break;
			}
			else
			{
				elog(ERROR, "ERROR: Invalid -Z option value, %s\n", token);
				return(-1);
			}
			continue;
		}
		else
			break;
	}
	if (nodetype == 0)
	{
		elog(ERROR, "ERROR: no node type was specified.\n");
		return(-1);
	}

	if (myname == NULL)
		myname = Strdup(DefaultName);
	
	if (!token)
	{
		fprintf(stderr,"%s: No command specified.\n", progname);
		exit(2);
	}
	if (!GetToken())
	{
		elog(ERROR, "ERROR: unregister: no node name was found to unregister.\n");
		return(-1);
	}
	nodename = Strdup(token);
	rc = process_unregister_command(nodetype, nodename);
	Free(nodename);
	return(rc);
}
Exemplo n.º 27
0
EFI_STATUS
IfrToUint (
  IN FORM_BROWSER_FORMSET  *FormSet,
  OUT  EFI_HII_VALUE       *Result
  )
/*++

Routine Description:
  Evaluate opcode EFI_IFR_TO_UINT.

Arguments:
  FormSet     - Formset which contains this opcode.
  Result      - Evaluation result for this opcode.

Returns:
  EFI_SUCCESS - Opcode evaluation success.
  Other       - Opcode evaluation failed.

--*/
{
  EFI_STATUS     Status;
  EFI_HII_VALUE  Value;
  CHAR16         *String;
  CHAR16         *StringPtr;
  UINTN          BufferSize;

  Status = PopExpression (&Value);
  if (EFI_ERROR (Status)) {
    return Status;
  }

  if (Value.Type >= EFI_IFR_TYPE_OTHER) {
    return EFI_UNSUPPORTED;
  }

  Status = EFI_SUCCESS;
  if (Value.Type == EFI_IFR_TYPE_STRING) {
    String = GetToken (Value.Value.string, FormSet->HiiHandle);
    if (String == NULL) {
      return EFI_NOT_FOUND;
    }

    IfrStrToUpper (String);
    StringPtr = EfiStrStr (String, L"0X");
    if (StringPtr != NULL) {
      //
      // Hex string
      //
      BufferSize = sizeof (UINT64);
      Status = HexStringToBuf ((UINT8 *) &Result->Value.u64, &BufferSize, StringPtr + 2, NULL);
    } else {
      //
      // BUGBUG: Need handle decimal string
      //
    }
    gBS->FreePool (String);
  } else {
    EfiCopyMem (Result, &Value, sizeof (EFI_HII_VALUE));
  }

  Result->Type = EFI_IFR_TYPE_NUM_SIZE_64;
  return Status;
}
Exemplo n.º 28
0
BOOLEAN Deletion_Parameters(LIST Tokens, pDeletionStruct pDeletionParameters, pSTRING pCommandLine)
{
  Token    CurrentToken;         /* Used to hold the token being examined. */
  CARDINAL Error = 0;            /* Used to hold the error return code from LIST operations. */
  BOOLEAN  ReturnValue = FALSE;  /* Used to hold the function return value. */
  pSTRING   pDriveName = NULL;
  pSTRING   pPartitionName = NULL;
  pSTRING   pDriveNumber = NULL;
  pSTRING   pVolumeName = NULL;
  unsigned int TokenPosition;


  /* Get the current token so that we can examine it. */
  GetToken(Tokens,sizeof(Token),&CurrentToken,&TokenPosition,&Error);
  if ( Error )
  {
     /* Report any errors accessing the token list as an internal error! */
     ReportError(Internal_Error);
     return ReturnValue;
  } /* endif */

  /* The next token must be the keyword ALL, PARTITION, or VOLUME */
  switch (CurrentToken.TokenType) {
  case All_CLI:
     pDeletionParameters->NameType = NoNameType;
     pDeletionParameters->DeletionOption = Deletion_None;
     /* All found, advance to next token */
     NextToken(Tokens,&Error);
     SkipOptionalWhitespace(Tokens);

     /* The token following the ALL keyword must be a comma */
     if ( IsComma(Tokens) ) {
        SkipOptionalWhitespace(Tokens);
        GetToken(Tokens,sizeof(Token),&CurrentToken,&TokenPosition,&Error);
        if ( Error) {
           /* Report any errors accessing the token list as an internal error! */
           ReportError(Internal_Error);
           return ReturnValue;
        } /* endif */

        switch (CurrentToken.TokenType) {
        case Compatibility:
           pDeletionParameters->DeletionOption = Deletion_All_Compatibility;
           NextToken(Tokens,&Error);
           ReturnValue = TRUE;
           break;
        case Logical:
           pDeletionParameters->DeletionOption = Deletion_All_Logical;
           NextToken(Tokens,&Error);
           ReturnValue = TRUE;
           break;
        case LVM:
           pDeletionParameters->DeletionOption = Deletion_All_LVM;
           NextToken(Tokens,&Error);
           ReturnValue = TRUE;
           break;
        case Primary:
           pDeletionParameters->DeletionOption = Deletion_All_Primary;
           NextToken(Tokens,&Error);
           ReturnValue = TRUE;
           break;
        case Unused:
           pDeletionParameters->DeletionOption = Deletion_All_Unused;
           NextToken(Tokens,&Error);
           ReturnValue = TRUE;
           break;
        case Volumes:
           pDeletionParameters->DeletionOption = Deletion_All_Volumes;
           NextToken(Tokens,&Error);
           ReturnValue = TRUE;
           break;
        case Eof:
        case SemiColon:
           ReportParseError(Expected_Deletion_Suboption, Tokens, pCommandLine);
           break;
        default:
           ReportParseError(Expected_Deletion_Suboption, Tokens, pCommandLine);
        } /* endswitch */
     } else {
        ReportParseError(Expected_Comma, Tokens, pCommandLine);
     } /* endif */
     break;
  case Partition:
     pDeletionParameters->DeletionOption = Deletion_Partition;
     /* Partition found, advance to next token */
     NextToken(Tokens,&Error);
     SkipOptionalWhitespace(Tokens);

     /* The token following the PARTITION keyword must be a comma */
     if ( IsComma(Tokens) ) {
        SkipOptionalWhitespace(Tokens);
        GetToken(Tokens,sizeof(Token),&CurrentToken,&TokenPosition,&Error);
        if ( Error) {
           /* Report any errors accessing the token list as an internal error! */
           ReportError(Internal_Error);
           return ReturnValue;
        } /* endif */

        /* The token following PARTITION must be a drive number or drive name */
        /* If it is a drive number */
        if ( Drive_Number(Tokens, &pDriveNumber) ) {
           pDeletionParameters->NameType = DriveNumberType;
           pDeletionParameters->pDrive = pDriveNumber;
        } else {
           /* If it is a drive name */
           if ( Drive_Name(Tokens, Comma, &pDriveName) ) {
              pDeletionParameters->NameType = DriveNameType;
              pDeletionParameters->pDrive = pDriveName;
           } else {
              ReportParseError(Expected_Drive_Number_or_Name, Tokens, pCommandLine);
              return ReturnValue;
           } /* endif */
        } /* endif */

        SkipOptionalWhitespace(Tokens);
        /* The next token is a comma, the one following it must be a parition name */
        if ( IsComma(Tokens) ) {
           SkipOptionalWhitespace(Tokens);
           GetToken(Tokens,sizeof(Token),&CurrentToken,&TokenPosition,&Error);
           if ( Error ) {
              /* Report any errors accessing the token list as an internal error! */
              ReportError(Internal_Error);
              return ReturnValue;
           } /* endif */

           pPartitionName = NULL;
           /* The next tokens, up to the next semicolon, must be a Partition name. */
           if ( Partition_Name(Tokens, SemiColon, &pPartitionName) ) {
              pDeletionParameters->pPartitionName = pPartitionName;
              ReturnValue = TRUE;
           } else {
             ReportParseError(Expected_Partition_Name, Tokens, pCommandLine);
           } /* endif */
        } else {
           /* Since the next token was not a comma, assume that the optional */
           /* partition name was not specified. */
           /* When the partition name is not specified, the parser indicates */
           /* that all paritions on the specified drive are to be deleted. */
           pDeletionParameters->DeletionOption = Deletion_Partitions;
           ReturnValue = TRUE;
        } /* endif */
     } else {
        ReportParseError(Expected_Comma, Tokens, pCommandLine);
     } /* endif */
     break;
  case Volume:
     pDeletionParameters->DeletionOption = Deletion_Volume;
     /* Volume found, advance to next token */
     NextToken(Tokens,&Error);
     SkipOptionalWhitespace(Tokens);
     /* The next non-whitespace token must be a comma */
     if ( IsComma(Tokens) ) {
        SkipOptionalWhitespace(Tokens);
        GetToken(Tokens,sizeof(Token),&CurrentToken,&TokenPosition,&Error);
        if ( Error ) {
           ReportError(Internal_Error);
           return ReturnValue;
        } /* endif */

        pVolumeName = NULL;
        /* The next tokens, up to the next semicolon, must be a volume name. */
        if ( Volume_Name(Tokens, SemiColon, &pVolumeName) ) {
           pDeletionParameters->pVolumeName = pVolumeName;
           ReturnValue = TRUE;
        } else {
          ReportParseError(Expected_Volume_Name, Tokens, pCommandLine);
        } /* endif */
     } else {
       ReportParseError(Expected_Comma, Tokens, pCommandLine);
     } /* endif */
     break;
  default:
     ReportParseError(Expected_Deletion_Option, Tokens, pCommandLine);
     break;
  } /* endswitch */

  /* Report any errors accessing the token list as an internal error! */
  if ( Error )
    ReportError(Internal_Error);

  return ReturnValue;

}
Exemplo n.º 29
0
EFI_STATUS
IfrFind (
  IN FORM_BROWSER_FORMSET  *FormSet,
  IN UINT8                 Format,
  OUT  EFI_HII_VALUE       *Result
  )
/*++

Routine Description:
  Evaluate opcode EFI_IFR_FIND.

Arguments:
  FormSet     - Formset which contains this opcode.
  Format      - Case sensitive or insensitive.
  Result      - Evaluation result for this opcode.

Returns:
  EFI_SUCCESS - Opcode evaluation success.
  Other       - Opcode evaluation failed.

--*/
{
  EFI_STATUS     Status;
  EFI_HII_VALUE  Value;
  CHAR16         *String[2];
  UINTN          Base;
  CHAR16         *StringPtr;
  UINTN          Index;

  if (Format > EFI_IFR_FF_CASE_INSENSITIVE) {
    return EFI_UNSUPPORTED;
  }

  Status = PopExpression (&Value);
  if (EFI_ERROR (Status)) {
    return Status;
  }
  if (Value.Type > EFI_IFR_TYPE_NUM_SIZE_64) {
    return EFI_UNSUPPORTED;
  }
  Base = (UINTN) Value.Value.u64;

  //
  // String[0] - sub-string
  // String[1] - The string to search
  //
  String[0] = NULL;
  String[1] = NULL;
  for (Index = 0; Index < 2; Index++) {
    Status = PopExpression (&Value);
    if (EFI_ERROR (Status)) {
      goto Done;
    }

    if (Value.Type != EFI_IFR_TYPE_STRING) {
      Status = EFI_UNSUPPORTED;
      goto Done;
    }

    String[Index] = GetToken (Value.Value.string, FormSet->HiiHandle);
    if (String== NULL) {
      Status = EFI_NOT_FOUND;
      goto Done;
    }

    if (Format == EFI_IFR_FF_CASE_INSENSITIVE) {
      //
      // Case insensitive, convert both string to upper case
      //
      IfrStrToUpper (String[Index]);
    }
  }

  Result->Type = EFI_IFR_TYPE_NUM_SIZE_64;
  if (Base >= EfiStrLen (String[1])) {
    Result->Value.u64 = 0xFFFFFFFFFFFFFFFF;
  } else {
    StringPtr = EfiStrStr (String[1] + Base, String[0]);
    Result->Value.u64 = (StringPtr == NULL) ? 0xFFFFFFFFFFFFFFFF : (StringPtr - String[1]);
  }

Done:
  EfiLibSafeFreePool (String[0]);
  EfiLibSafeFreePool (String[1]);

  return Status;
}
Exemplo n.º 30
0
/*
===============
Cmd_Skin

Skins aren't actually stored in the file, only a reference
is saved out to the header file.
===============
*/
void Cmd_Skin (void)
{
	byte	*palette;
	byte	*pixels;
	int		width, height;
	byte	*cropped;
	int		y;
	char	name[1024], savename[1024];

	GetToken (false);

	if (model.num_skins == MAX_MD2SKINS)
		Error ("model.num_skins == MAX_MD2SKINS");

	if (g_skipmodel)
		return;

	sprintf (name, "%s/%s.lbm", cdarchive, token);
	strcpy (name, ExpandPathAndArchive( name ) );
//	sprintf (name, "%s/%s.lbm", cddir, token);

	if (TokenAvailable())
	{
		GetToken (false);
		sprintf (g_skins[model.num_skins], "%s.pcx", token);
		sprintf (savename, "%s%s.pcx", gamedir, g_skins[model.num_skins]);
	}
	else
	{
		sprintf (savename, "%s/%s.pcx", cddir, token);
		sprintf (g_skins[model.num_skins], "%s/%s.pcx", cdpartial, token);
	}

	model.num_skins++;

	if (g_skipmodel || g_release || g_archive)
		return;

	// load the image
	printf ("loading %s\n", name);
	Load256Image (name, &pixels, &palette, &width, &height);
	RemapZero (pixels, palette, width, height);

	// crop it to the proper size
	cropped = malloc (model.skinwidth*model.skinheight);
	for (y=0 ; y<model.skinheight ; y++)
	{
		memcpy (cropped+y*model.skinwidth,
			pixels+y*width, model.skinwidth);
	}

	// save off the new image
	printf ("saving %s\n", savename);
	CreatePath (savename);
	WritePCXfile (savename, cropped, model.skinwidth,
		model.skinheight, palette);

	free (pixels);
	free (palette);
	free (cropped);
}