Example #1
0
Pegasus::Boolean CIMClient::verifyCertificate(Pegasus::SSLCertificateInfo &ci, void *data)
{
    if (!ci.getResponseCode()) {
        // Pre-verify of the certificate failed, immediate return
        return false;
    }

    CIMClient *fake_this = reinterpret_cast<CIMClient*>(data);
    Pegasus::String hostname(fake_this->m_url_info.hostname());

    // Verify against DNS names
    Pegasus::Array<Pegasus::String> dnsNames = ci.getSubjectAltNames().getDnsNames();
    for (Pegasus::Uint32 i = 0; i < dnsNames.size(); ++i) {
        if (matchPattern(dnsNames[i], hostname))
            return true;
    }

    // Verify against IP addresses
    Pegasus::Array<Pegasus::String> ipAddresses = ci.getSubjectAltNames().getIpAddresses();
    for (Pegasus::Uint32 i = 0; i < ipAddresses.size(); ++i) {
        if (matchPattern(ipAddresses[i], hostname))
            return true;
    }

    // Verify against Common Name
    return matchPattern(ci.getSubjectCommonName(), hostname);
}
Example #2
0
File: parser.c Project: WCP52/gpha
/**
 * Parse boolean parameter as described in the spec SCPI-99 7.3 Boolean Program Data
 * @param context
 * @param value
 * @param mandatory
 * @return 
 */
scpi_bool_t SCPI_ParamBool(scpi_t * context, scpi_bool_t * value, scpi_bool_t mandatory) {
    const char * param;
    size_t param_len;
    size_t num_len;
    int32_t i;

    if (!value) {
        return FALSE;
    }

    if (!SCPI_ParamString(context, &param, &param_len, mandatory)) {
        return FALSE;
    }

    if (matchPattern("ON", 2, param, param_len)) {
        *value = TRUE;
    } else if (matchPattern("OFF", 3, param, param_len)) {
        *value = FALSE;
    } else {
        num_len = strToLong(param, &i);

        if (num_len != param_len) {
            SCPI_ErrorPush(context, SCPI_ERROR_SUFFIX_NOT_ALLOWED);
            return FALSE;
        }

        *value = i ? TRUE : FALSE;
    }

    return TRUE;
}
 bool matchPattern(string& pattern, int index, TrieNode* node) {
     if (index == pattern.size()-1)  {
         if (pattern[index] == '.') {
             if (node->children.size() != 0 && node->hasChildWithMaker()) {
                 // There has to be at least one child with a maker
                 return true;
             }
         } else {
             TrieNode* child = node->findChild(pattern[index]);
             if (child != NULL && child->marker) {
                 return true;
             }
         }
         return false;
     }
     
     if (pattern[index] == '.') {
         bool result = false;
         for (int i = 0; i < node->children.size(); ++i) {
              result |= matchPattern(pattern, index+1, node->children[i]);
         }
         return result;
     } else {
          TrieNode* child = node->findChild(pattern[index]);
          if (!child) {
              return false;
          }
          
          return matchPattern(pattern, index+1, child);
     }
     
 }
Example #4
0
int main(void)
{
    unsigned char buffer[1024];
    unsigned int i = 0;
    unsigned int ones = 0, zeroes = 0;
    unsigned int pattern2[4] = {0,0,0,0};

    TPM_setlog(0);

    printf("Counting number of '1's and '0's of the rng.\n");
    while (i < 10) {
        uint32_t bufferSize = sizeof(buffer);
        unsigned int j = 0;
        uint32_t ret;
        ret = TPM_GetRandom(bufferSize,
                            buffer, &bufferSize);
        if (0 != ret) {
            printf("Error %s from TPM_GetRandom.\n",
                   TPM_GetErrMsg(ret));
            exit (ret);
        }
        while (j < bufferSize) {
            unsigned int c = countOnes(buffer[j]);
            ones += c;
            zeroes += (8-c);
            pattern2[0] += matchPattern(buffer[j], 0x0, 2);
            pattern2[1] += matchPattern(buffer[j], 0x1, 2);
            pattern2[2] += matchPattern(buffer[j], 0x2, 2);
            pattern2[3] += matchPattern(buffer[j], 0x3, 2);
            j++;
        }
        ret = TPM_StirRandom(buffer, 10);
        if (0 != ret) {
            printf("Error %s from TPM_StirRandom.\n",
                   TPM_GetErrMsg(ret));
            exit(ret);
        }
        i++;
    }
    printf("Percentage of '1': %d percent.\n", (ones*100)/(ones+zeroes));
    printf("Percentage of '00' bits:  %d percent\n",
           (pattern2[0]*200)/(ones+zeroes));
    printf("Percentage of '01' bits:  %d percent\n",
           (pattern2[1]*200)/(ones+zeroes));
    printf("Percentage of '10' bits:  %d percent\n",
           (pattern2[2]*200)/(ones+zeroes));
    printf("Percentage of '11' bits:  %d percent\n",
           (pattern2[3]*200)/(ones+zeroes));
    return 0;
}
Example #5
0
/**
 * Convert parameter to choice
 * @param context
 * @param parameter - should be PROGRAM_MNEMONIC
 * @param options - NULL terminated list of choices
 * @param value - index to options
 * @return
 */
scpi_bool_t SCPI_ParamToChoice(scpi_t * context, scpi_parameter_t * parameter, const scpi_choice_def_t * options, int32_t * value) {
    size_t res;
    scpi_bool_t result = FALSE;

    if (!options || !value) {
        SCPI_ErrorPush(context, SCPI_ERROR_SYSTEM_ERROR);
        return FALSE;
    }

    if (parameter->type == SCPI_TOKEN_PROGRAM_MNEMONIC) {
        for (res = 0; options[res].name; ++res) {
            if (matchPattern(options[res].name, strlen(options[res].name), parameter->ptr, parameter->len, NULL)) {
                *value = options[res].tag;
                result = TRUE;
                break;
            }
        }

        if (!result) {
            SCPI_ErrorPush(context, SCPI_ERROR_ILLEGAL_PARAMETER_VALUE);
        }
    } else {
        SCPI_ErrorPush(context, SCPI_ERROR_DATA_TYPE_ERROR);
    }

    return result;
}
Example #6
0
void vfs::CVirtualFileSystem::CMatchingIterator::next()
{
	if(nextFileMatch())
	{
		return;
	}
	while(nextLocationMatch())
	{
		_vfile_iter = _vloc_iter->second->iterate();
		if(!_vfile_iter.end())
		{
			bool bExclusiveVLoc = _vloc_iter->second->getIsExclusive();
			vfs::IBaseFile* pFile = NULL;
			if(bExclusiveVLoc)
			{
				pFile = _vfile_iter.value()->file(vfs::CVirtualFile::SF_STOP_ON_WRITABLE_PROFILE);
			}
			else
			{
				pFile = _vfile_iter.value()->file(vfs::CVirtualFile::SF_TOP);
			}
			if(pFile && matchPattern(m_sFilePattern(),pFile->getName()()))
			{
				return;
			}
			else if(nextFileMatch())
			{
				return;
			}
		}
	}
}
Example #7
0
void vfs::CVirtualProfile::FileIterImpl::next()
{
	if(!fiter.end())
	{
		fiter.next();
	}
	while(!iter.end())
	{
		while(!fiter.end())
		{
			file = fiter.value();
			if( matchPattern(m_pattern(), file->getPath()()) )
			{
				return;
			}
			fiter.next();
		}
		iter.next();
		if(!iter.end())
		{
			fiter = iter.value()->begin();
		}
	}
	file = NULL;
}
Example #8
0
bool ResponseSkill::viewFilter(const CardItem *to_select) const{
    if(to_select->isEquipped())
        return false;

    const Card *card = to_select->getFilteredCard();
    return matchPattern(Self, card);
}
Example #9
0
bool VMsgLog::matchLine( int index, char* file, int& line, int& offset, char* help )
{
    file[0] = '\0';     line = 0; offset = 0; help[0] = '\0';
    for( int i=0; i<_config->logScanPatterns().count(); i++ ) {
        WString& p = *(WString*)_config->logScanPatterns()[i];
        if( matchPattern( p, index, file, line, offset, help ) ) {
            WFileName f( file );
            while( index > 0 ) {
                index --;
                WString* data = (WString*)_data[index];
                if( data->match( "cd *" ) ) {
                    WString dir( &(*data)[3] );
                    int dirLen = dir.size()-1;
                    if( dir[dirLen] != '\\' ) {
                        dir.concat( '\\' );
                    }
                    f.absoluteTo( dir );
                    strcpy( file, f );
                    break;
                }
            }
            return TRUE;
        }
    }
    return FALSE;
}
Example #10
0
bool vfs::CVirtualFileSystem::CMatchingIterator::nextFileMatch()
{
	bool bExclusiveVLoc = false;
	if( _vloc_iter != m_VFS->m_mapFS.end() )
	{
		bExclusiveVLoc = _vloc_iter->second->getIsExclusive();
	}
	while(!_vfile_iter.end())
	{
		_vfile_iter.next();
		if(!_vfile_iter.end())
		{
			vfs::IBaseFile* pFile = NULL;
			if(bExclusiveVLoc)
			{
				pFile = _vfile_iter.value()->file(vfs::CVirtualFile::SF_STOP_ON_WRITABLE_PROFILE);
			}
			else
			{
				pFile = _vfile_iter.value()->file(vfs::CVirtualFile::SF_TOP);
			}
			if(pFile)
			{
				vfs::Path const& filename = pFile->getName();
				if(matchPattern(m_sFilePattern(),filename()))
				{
					return true;
				}
			}
		}
	}
	return false;
}
Example #11
0
/**
 * Compare pattern and command
 * @param pattern
 * @param cmd - command
 * @param len - max search length
 * @return TRUE if pattern matches, FALSE otherwise
 */
bool_t matchCommand(const char * pattern, const char * cmd, size_t len) {
    int result = FALSE;
    
    const char * pattern_ptr = pattern;
    int pattern_len = strlen(pattern);
    const char * pattern_end = pattern + pattern_len;
    
    const char * cmd_ptr = cmd;
    size_t cmd_len = SCPI_strnlen(cmd, len);
    const char * cmd_end = cmd + cmd_len;
    
    /* TODO: now it is possible to send command ":*IDN?" which is incorrect */
    if (iscolon(cmd_ptr[0])) {
        cmd_len --;
        cmd_ptr ++;
    }
    
    while (1) {
        int pattern_sep_pos = patternSeparatorPos(pattern_ptr, pattern_end - pattern_ptr);
        int cmd_sep_pos = cmdSeparatorPos(cmd_ptr, cmd_end - cmd_ptr);
        
        if (matchPattern(pattern_ptr, pattern_sep_pos, cmd_ptr, cmd_sep_pos)) {
            pattern_ptr = pattern_ptr + pattern_sep_pos;
            cmd_ptr = cmd_ptr + cmd_sep_pos;
            result = TRUE;
            
            /* command is complete */
            if ((pattern_ptr == pattern_end) && (cmd_ptr >= cmd_end)) {
                break;
            }
            
            /* pattern complete, but command not */
            if ((pattern_ptr == pattern_end) && (cmd_ptr < cmd_end)) {
                result = FALSE;
                break;
            }
            
            /* command complete, but pattern not */
            if (cmd_ptr >= cmd_end) {
                result = FALSE;
                break;
            }
            
            /* both command and patter contains command separator at this position */
            if ((pattern_ptr[0] == cmd_ptr[0]) && ((pattern_ptr[0] == ':') || (pattern_ptr[0] == '?'))) {
                pattern_ptr = pattern_ptr + 1;
                cmd_ptr = cmd_ptr + 1;
            } else {
                result = FALSE;
                break;
            }
        } else {
            result = FALSE;
            break;
        }
    }
    
    return result;
}
Example #12
0
vfs::CVirtualFileSystem::CMatchingIterator::CMatchingIterator(vfs::Path const& sPattern, vfs::CVirtualFileSystem* pVFS)
: tBaseClass(), m_VFS(pVFS)
{
	if(sPattern() == vfs::Const::STAR())
	{
		m_sLocPattern =  vfs::Path(vfs::Const::STAR());
		m_sFilePattern = vfs::Path(vfs::Const::STAR());
	}
	else
	{
		sPattern.splitLast(m_sLocPattern,m_sFilePattern);
	}

	_vloc_iter = m_VFS->m_mapFS.begin();
	while(_vloc_iter != m_VFS->m_mapFS.end())
	{
		if( matchPattern(m_sLocPattern(),_vloc_iter->second->cPath()) )
		{
			bool bExclusiveVLoc = _vloc_iter->second->getIsExclusive();
			_vfile_iter = _vloc_iter->second->iterate();
			while(!_vfile_iter.end())
			{
				vfs::IBaseFile* pFile = NULL;
				if(bExclusiveVLoc)
				{
					pFile = _vfile_iter.value()->file(vfs::CVirtualFile::SF_STOP_ON_WRITABLE_PROFILE);
				}
				else
				{
					pFile = _vfile_iter.value()->file(vfs::CVirtualFile::SF_TOP);
				}
				if(pFile)
				{
					vfs::Path const& filename = pFile->getName();
					if( matchPattern(m_sFilePattern(),filename()) )
					{
						return;
					}
				}
				_vfile_iter.next();
			}
		}
		_vloc_iter++;
	}
}
Example #13
0
CTransferRules::EAction CTransferRules::applyRule(vfs::String const& sStr)
{
	tPatternList::iterator sit = m_listRules.begin();
	for(; sit != m_listRules.end(); ++sit)
	{
		if(matchPattern(sit->pattern(), sStr))
		{
			return sit->action;
		}
	}
	return m_eDefaultAction;
}
void ApplyShaders(std::string name, AtNode* node, std::vector<std::string> tags, ProcArgs & args)
{
   bool foundInPath = false;
   AtNode* appliedShader = NULL;
   for(std::map<std::string, AtNode*>::iterator it = args.shaders.begin(); it != args.shaders.end(); ++it) 
   {

     //check both path & tag
     if(it->first.find("/") != std::string::npos)
     {
       if(name.find(it->first) != std::string::npos)
       {
         appliedShader = it->second;
         foundInPath = true;
       }
     }
     else if(matchPattern(name,it->first)) // based on wildcard expression
     {

        AiMsgDebug("[ABC] Shader pattern '%s' matched %s",it->first.c_str(), name.c_str());
        appliedShader = it->second;
        foundInPath = true;
     }
     else if(foundInPath == false)
     {
       if (std::find(tags.begin(), tags.end(), it->first) != tags.end())
       {
         AiMsgDebug("[ABC] Shader tag '%s' matched tag on %s",it->first.c_str(), name.c_str());
         appliedShader = it->second;
       }
     }
   }

   if(appliedShader != NULL)
   {
     std::string newName = std::string(AiNodeGetName(appliedShader)) + std::string("_") + name;
     AtArray* shaders = AiArrayAllocate( 1 , 1, AI_TYPE_NODE);
     
     AiMsgDebug("[ABC] Assigning shader  %s to %s", AiNodeGetName(appliedShader), AiNodeGetName(node));
     AiArraySetPtr(shaders, 0, appliedShader);
     
     AiNodeSetArray(node, "shader", shaders);
   }
   else
   {
     AtArray* shaders = AiNodeGetArray(args.proceduralNode, "shader");
     if (shaders->nelements != 0)
        AiNodeSetArray(node, "shader", AiArrayCopy(shaders));
   }
}
Example #15
0
bool vfs::CVirtualFileSystem::CMatchingIterator::nextLocationMatch()
{
	while(_vloc_iter != m_VFS->m_mapFS.end())
	{
		_vloc_iter++;
		if(_vloc_iter != m_VFS->m_mapFS.end())
		{
			if(matchPattern(m_sLocPattern(),_vloc_iter->second->cPath()))
			{
				return true;
			}
		}
	}
	return false;
}
Example #16
0
/**
 * Match string constant to one of special number values
 * @param specs specifications of special numbers (patterns)
 * @param str string to be recognised
 * @param len length of string
 * @param value resultin value
 * @return TRUE if str matches one of specs patterns
 */
scpi_bool_t SCPIParser::translateSpecialNumber(const scpi_special_number_def_t * specs, const char * str, size_t len, scpi_number_t * value) {
    int i;

    value->value = 0.0;
    value->unit = SCPI_UNIT_NONE;
    value->type = SCPI_NUM_NUMBER;

    if (specs == NULL) {
        return FALSE;
    }

    for (i = 0; specs[i].name != NULL; i++) {
        if (matchPattern(specs[i].name, strlen(specs[i].name), str, len)) {
            value->type = specs[i].type;
            return TRUE;
        }
    }

    return FALSE;
}
 // Returns if the word is in the data structure. A word could
 // contain the dot character '.' to represent any one letter.
 bool search(string word) {
     matchPattern(word, 0, root);
     /*
     TrieNode* current = root;
     TrieNode* next;
     for (int i = 0; i < word.size(); ++i) {
         next = current->findChild(word[i]);
         if (next) {
             current = next;
         } else {
             return false;
         }
     }
     
     if (next->marker == false) {
         return false;
     }
     
     return true;*/
 }
Example #18
0
vfs::CVirtualProfile::FileIterImpl::FileIterImpl(vfs::Path const& sPattern, CVirtualProfile* profile)
: tBaseClass(), m_pattern(sPattern), m_profile(profile)
{
	VFS_THROW_IFF(profile, L"");
	iter = m_profile->begin();
	while(!iter.end())
	{
		fiter = iter.value()->begin();
		while(!fiter.end())
		{
			file = fiter.value();
			if( matchPattern(m_pattern(), file->getPath()()) )
			{
				return;
			}
			fiter.next();
		}
		iter.next();
	}
	file = NULL;
}
Example #19
0
void VSearch::searchFirstPhaseFile(const QString &p_basePath,
                                   const QString &p_filePath,
                                   const QSharedPointer<VSearchResult> &p_result)
{
    Q_ASSERT(testTarget(VSearchConfig::Note));

    QString name = VUtils::fileNameFromPath(p_filePath);
    if (!matchPattern(name)) {
        return;
    }

    if (testObject(VSearchConfig::Name)) {
        if (matchNonContent(name)) {
            VSearchResultItem *item = new VSearchResultItem(VSearchResultItem::Note,
                                                            VSearchResultItem::LineNumber,
                                                            name,
                                                            p_filePath);
            QSharedPointer<VSearchResultItem> pitem(item);
            emit resultItemAdded(pitem);
        }
    }

    if (testObject(VSearchConfig::Path)) {
        QString normFilePath(QDir(p_basePath).relativeFilePath(p_filePath));
        removeSlashFromPath(normFilePath);
        if (matchNonContent(normFilePath)) {
            VSearchResultItem *item = new VSearchResultItem(VSearchResultItem::Note,
                                                            VSearchResultItem::LineNumber,
                                                            name,
                                                            p_filePath);
            QSharedPointer<VSearchResultItem> pitem(item);
            emit resultItemAdded(pitem);
        }
    }

    if (testObject(VSearchConfig::Content)) {
        // Add an item for second phase process.
        p_result->addSecondPhaseItem(p_filePath);
    }
}
Example #20
0
File: parser.c Project: WCP52/gpha
/**
 * Parse choice parameter
 * @param context
 * @param options
 * @param value
 * @param mandatory
 * @return 
 */
scpi_bool_t SCPI_ParamChoice(scpi_t * context, const char * options[], int32_t * value, scpi_bool_t mandatory) {
    const char * param;
    size_t param_len;
    size_t res;

    if (!options || !value) {
        return FALSE;
    }

    if (!SCPI_ParamString(context, &param, &param_len, mandatory)) {
        return FALSE;
    }

    for (res = 0; options[res]; ++res) {
        if (matchPattern(options[res], strlen(options[res]), param, param_len)) {
            *value = res;
            return TRUE;
        }
    }

    SCPI_ErrorPush(context, SCPI_ERROR_ILLEGAL_PARAMETER_VALUE);
    return FALSE;
}
void DirectoryStructure::setPattern( string sPattern )
{

	vsFileList.clear();
	
	DIR *d;
	struct dirent *dir;
	d = opendir(sDirectory.c_str());
	if (d)
	{
	  while ((dir = readdir(d)) != NULL)
	  {
	    string sFilename( dir->d_name );
	    if( matchPattern( sPattern, sFilename) )
		    vsFileList.push_back( sFilename );
	  }

	  closedir(d);
	}
	
	resetListIterator();
	iFileCount = vsFileList.size();
}
void ApplyOverrides(std::string name, AtNode* node, std::vector<std::string> tags, ProcArgs & args)
{
   bool foundInPath = false;
   for(std::vector<std::string>::iterator it=args.overrides.begin(); it!=args.overrides.end(); ++it)
   {
      Json::Value overrides;                        
      if(it->find("/") != std::string::npos) // Based on path
      {
        if(name.find(*it) != std::string::npos)
        {
          overrides = args.overrideRoot[*it];
          foundInPath = true;
        }
      } 
      else if(matchPattern(name,*it)) // based on wildcard expression
      {
          overrides = args.overrideRoot[*it];
          foundInPath = true;
      }
      else if(foundInPath == false)
      {
        if (std::find(tags.begin(), tags.end(), *it) != tags.end())
        {
          overrides = args.overrideRoot[*it];
        }
      }

      if(overrides.size() > 0)
      {
        for( Json::ValueIterator itr = overrides.begin() ; itr != overrides.end() ; itr++ ) 
        {
          std::string attribute = itr.key().asString();

          const AtNodeEntry* nodeEntry = AiNodeGetNodeEntry(node);
          const AtParamEntry* paramEntry = AiNodeEntryLookUpParameter(nodeEntry, attribute.c_str());

          if ( paramEntry != NULL && attribute!="invert_normals" || attribute == "matte")
          {

            Json::Value val = args.overrideRoot[*it][itr.key().asString()];
            if( val.isString() ) 
              AiNodeSetStr(node, attribute.c_str(), val.asCString());
            else if( val.isBool() )
            {
              if(attribute == "matte")
              {
                  AiMsgDebug("[ABC] adding enable_matte to %s", AiNodeGetName(node));
                  AddUserGeomParams(node,"enable_matte",AI_TYPE_BOOLEAN);
                  AiNodeSetBool(node,"enable_matte", val.asBool());
              }
              else
              {
                  AiNodeSetBool(node, attribute.c_str(), val.asBool());
              }
            }
            else if( val.isInt() ) 
            {
              //make the difference between Byte & int!
              int typeEntry = AiParamGetType(paramEntry);
              if(typeEntry == AI_TYPE_BYTE)
              { 
                if(attribute=="visibility")
                {
                  AtByte attrViz = val.asInt();
                  // special case, we must determine it against the general viz.
                  AtByte procViz = AiNodeGetByte( args.proceduralNode, "visibility" );
                  AtByte compViz = AI_RAY_ALL;
                  {
                    compViz &= ~AI_RAY_GLOSSY;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_GLOSSY;
                    else
                      attrViz &= ~AI_RAY_GLOSSY;
                    compViz &= ~AI_RAY_DIFFUSE;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_DIFFUSE;
                    else
                      attrViz &= ~AI_RAY_DIFFUSE;
                    compViz &= ~AI_RAY_REFRACTED;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_REFRACTED;
                    else
                      attrViz &= ~AI_RAY_REFRACTED;
                    compViz &= ~AI_RAY_REFLECTED;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_REFLECTED;
                    else
                      attrViz &= ~AI_RAY_REFLECTED;
                    compViz &= ~AI_RAY_SHADOW;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_SHADOW;
                    else
                      attrViz &= ~AI_RAY_SHADOW;
                    compViz &= ~AI_RAY_CAMERA;
                    if(procViz > compViz)
                      procViz &= ~AI_RAY_CAMERA;
                    else
                      attrViz &= ~AI_RAY_CAMERA;
                  }

                  AiNodeSetByte(node, attribute.c_str(), attrViz);
                }
                else
                  AiNodeSetByte(node, attribute.c_str(), val.asInt());
              }
              else 
                AiNodeSetInt(node, attribute.c_str(), val.asInt());
            }
            else if( val.isUInt() ) 
              AiNodeSetUInt(node, attribute.c_str(), val.asUInt());
            else if( val.isDouble() ) 
              AiNodeSetFlt(node, attribute.c_str(), val.asDouble());
          }
        }
      }

   }
}
Example #23
0
/*
 * matchPattern- literal text and match the following identifiers:
 *              %f - filename
 *              %i - fortran style error identifier
 *              %l - line number
 *              %o - offset (column)
 *              %h - error idetifier (ex E100)
 *              %* - any text
 */
bool VMsgLog::matchPattern( const char* p, int index, char* file, int& line, int& offset, char* help )
{
    WString str( *(WString*)_data[index] );
    int i = 0, j = 0; int k, kk;
    while( p[i] != '<' ) {
        if( p[i] == '\0' ) return FALSE;
        i++;
    }
    i++;
    for(;;) {
        if( p[i] == '\0' ) return FALSE;
        if( p[i] == '>' ) break;
        if( strncmp( &p[i], "%f", 2 ) == 0 ) {
            i += 2;
            k = 0;
            if( isalpha( str[j] ) && str[j+1]==':' ) {
                file[k++] = str[j++];
                file[k++] = str[j++];
            }
            for( kk = -1; kk != k ; ) {
                kk = k;
                if( str[j] == '\\' || str[j] == '/' ) file[k++] = str[j++];
                while( isalnum( str[j] ) || str[j] == '.'
                        || str[j] == '_' || str[j] == '-' ) {
                    file[k++] = str[j++];
                }
            }
            file[k] = '\0';
        } else if( strncmp( &p[i], "%l", 2 ) == 0 ) {
            i += 2;
            line = 0;
            for(;;) {
                if( !isdigit( str[j] ) ) break;
                line = line*10 + (str[j++]-'0');
            }
        } else if( strncmp( &p[i], "%o", 2 ) == 0 ) {
            i += 2;
            offset = 0;
            for(;;) {
                if( !isdigit( str[j] ) ) break;
                offset = offset*10 + (str[j++]-'0');
            }
        } else if( strncmp( &p[i], "%h", 2 ) == 0 ) {
            i += 2;
            if( str[j] == 'E' || str[j] == 'W' || str[j] == 'N' ) {
//              help[k++] = str[j++];   drw 12/13/94 k could be uninitialized
                j++;
            }
            for( k=0; isdigit( str[j] ); ) {
                help[k++] = str[j++];
            }
            help[k] = '\0';
        // this is a kludge to get fortran help working
        } else if( strncmp( &p[i], "%i", 2 ) == 0 ) {
            i += 2;
            if( !parseFortranId( str, j, help ) ) break;
        } else if( strncmp( &p[i], "%*", 2 ) == 0 ) {
            i += 2;
            for(;;) {
                if( p[i] != '>' && str[j] == p[i] ) break;
                if( str[j] == '\0' ) break;
                j++;
            }
        } else if( p[i] == str[j] ) {
            i++; j++;
        } else {
            break;
        }
    }
    if( p[i]=='>' && str[j]=='\0' ) {
        while( p[i] != '<' ) {
            if( p[i] == '\0' ) return TRUE;
            i++;
        }
        while( index > 0 ) {
            index -= 1;
            int l, o;
            if( matchPattern( &p[i], index, file, l, o, help ) ) return TRUE;
        }
    }
    return FALSE;
}
void ApplyUserAttributes(std::string name, AtNode* node,std::vector<std::string> tags,ProcArgs & args)
{

   bool foundInPath = false;
   for(std::vector<std::string>::iterator it=args.userAttributes.begin(); it!=args.userAttributes.end(); ++it)
   {
      Json::Value userAttributes;                        
      if(it->find("/") != std::string::npos) // Based on path
      {
        if(name.find(*it) != std::string::npos)
        {
          userAttributes = args.userAttributesRoot[*it];
          foundInPath = true;
        }
      } 
      else if(matchPattern(name,*it)) // based on wildcard expression
      {
          userAttributes = args.userAttributesRoot[*it];
          foundInPath = true;
      }
      else if(foundInPath == false)
      {
        if (std::find(tags.begin(), tags.end(), *it) != tags.end())
        {
          userAttributes = args.userAttributesRoot[*it];
        }
      }

      if(userAttributes.size() > 0)
      {
        for( Json::ValueIterator itr = userAttributes.begin() ; itr != userAttributes.end() ; itr++ ) 
        {
            std::string attribute = itr.key().asString();

            if( AiNodeLookUpUserParameter(node,attribute.c_str()))
              continue;

            const AtNodeEntry* nodeEntry = AiNodeGetNodeEntry(node);
            Json::Value val = args.userAttributesRoot[*it][attribute];
            if( val.isString() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_STRING);
              AiNodeSetStr(node, attribute.c_str(), val.asCString());
            } 
            else if( val.isBool() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_BOOLEAN);
              AiNodeSetBool(node, attribute.c_str(), val.asBool());
            }
            else if( val.isInt() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_INT);
              AiNodeSetInt(node, attribute.c_str(), val.asInt());
            }
            else if( val.isUInt() ) 
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_UINT);
              AiNodeSetUInt(node, attribute.c_str(), val.asUInt());
            }
            else if(val.isDouble())
            {
              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_FLOAT);
              AiNodeSetFlt(node, attribute.c_str(), val.asDouble());
            }
            else if(val.isArray()) 
            {              

              // in the future we will convert to an arnold array type for now lets just 
              // write out a json string

              AddUserGeomParams(node,attribute.c_str(),AI_TYPE_STRING);
              Json::FastWriter writer;
              AiNodeSetStr(node, attribute.c_str(), writer.write(val).c_str());
              
              // AddUserGeomParams(node,attribute.c_str(),AI_TYPE_ARRAY );

              // // get the type of the first entry, this will be our key as to
              // // what type of data is in this array
              // Json::Value firstValue = val[0];
              // if (firstValue.isString())
              // {
              //   AtArray* arrayValues = AiArrayAllocate( val.size() , 1, AI_TYPE_STRING);

              //   for( uint idx = 0 ; idx != val.size() ; idx++ ) 
              //   {
              //     AiMsgInfo("[ABC] adding string %s to user array attribute '%s'",val[idx].asCString(),attribute.c_str());
              //     AiArraySetStr(arrayValues,idx,val[idx].asCString());
              //   }

              //   AiNodeSetArray(node, attribute.c_str(), arrayValues);         
              // }
     
            }

            // TODO color, matrix, vector

         }
      }
   }
}
Example #25
0
/**
 * Questa funzione legge e scrive un'agenda effettuando controlli 
 * necessari a verificare che il file sia stato formattato correttamente 
 * e che la conversione sia corretta
 *
 * \param fagenda nome del file agenda
 * \param ftest nome del file in cui verranno scritte le voci covertite
 */
void run_testagenda (char *fagenda, char* ftest) {
    char record[LRECORD+2], pbu[MAXNTEST][LRECORD+1], pb[LRECORD+1];
    evento_t* ev[MAXNTEST];
    FILE *fsa;

    /* prossima posizione libera nell'array di eventi */
    int i=0;
    int l,k;

    /*
     * Apertura del file agenda
     */
    fsa = fopen(fagenda, "r");
    CU_ASSERT_PTR_NOT_NULL_FATAL(fsa); 


    /*
     * Lettura e caricamento eventi nell'array
     */
    while(fgets(record,LRECORD + 2,fsa) != NULL) {
	 CU_ASSERT_EQUAL_FATAL(record[LRECORD], '\n');
	 record[LRECORD]='\0';
	 strncpy(pbu[i],record,LRECORD+1);
	 CU_TEST_FATAL(i < MAXNTEST);
	 ev[i]=convertiRecord(record);
	 CU_ASSERT_NOT_EQUAL_FATAL(ev[i],NULL);
	 i++;
	 
    }
    fclose(fsa);
    printf("lette %d voci\n",i);

    /*
     * Trasformazione voci nel formato stringa
     */
    for ( l=0; l<i; l++ ) {
	int ret;
	/* printf("confron ta la mia %s, che viene da %s,%s,%s, con    la sua %s\n", pb, ev[l]->data, ev[l]->utente, ev[l]->descrizione ,pbu[l]); */
	convertiEvento(ev[l],pb);
	/* printf("confronta la mia %s, che viene da %s con la sua %s\n", pb, ev[l]->data ,pbu[l]); */
	ret=strncmp(pbu[l],pb,LRECORD+1);
	CU_ASSERT_EQUAL_FATAL(ret, 0);
    }

    /*
     * Verifica funzione di matchPattern
     */
    
    for (k=0;pattern[k]!=NULL; k++) {
	int cont = 0;
	for(l=0;l<i;l++) {
	    cont+=matchPattern(pattern[k],ev[l]);
/*	    printf(" pattern %s : %d occurrences \n",pattern[k],cont);*/
	}
	 CU_ASSERT_EQUAL_FATAL(cont, npatternmatch[k]); 
    }

    /*
     * Verifica funzione di matchData
     */
    for (k=0;date[k]!=NULL; k++) {
	int cont = 0;
	for(l=0;l<i;l++) {
	    cont+=matchData(date[k],ev[l]);
	}
	/* printf("cont: %d  nmatch %d\n", cont, nmatch[k]); */
	CU_ASSERT_EQUAL_FATAL(cont, nmatch[k]); 
    }

    /* 
     * Test di creazione di una nuova agenda 
     */

    fsa=fopen(ftest,"w");
    CU_ASSERT_PTR_NOT_NULL_FATAL(fsa); 
    for ( l=0; l<i; l++ ) {
	convertiEvento(ev[l],pb);
        CU_ASSERT_NOT_EQUAL_FATAL(fputs(pb,fsa), EOF);
	fputs("\n",fsa);
    }
    fclose(fsa);
    
}
Example #26
0
bool ResponseSkill::viewFilter(const Card *card) const
{
    return matchPattern(Self, card);
}
Example #27
0
Expression::Ptr ExpressionFactory::createExpression(const Tokenizer::Ptr &tokenizer,
                                                    const StaticContext::Ptr &context,
                                                    const QXmlQuery::QueryLanguage lang,
                                                    const SequenceType::Ptr &requiredType,
                                                    const QUrl &queryURI,
                                                    const QXmlName &initialTemplateName)
{
    Q_ASSERT(context);
    Q_ASSERT(requiredType);
    Q_ASSERT(queryURI.isValid());

    Tokenizer::Ptr effectiveTokenizer(tokenizer);
#ifdef Patternist_DEBUG
    effectiveTokenizer = Tokenizer::Ptr(new TokenRevealer(queryURI, tokenizer));
#endif

    OptimizationPasses::Coordinator::init();

    const ParserContext::Ptr info(new ParserContext(context, lang, effectiveTokenizer.data()));
    info->initialTemplateName = initialTemplateName;

    effectiveTokenizer->setParserContext(info);

    const int bisonRetval = QPatternist::XPathparse(info.data());

    Q_ASSERT_X(bisonRetval == 0, Q_FUNC_INFO,
               "We shouldn't be able to get an error, because we throw exceptions.");
    Q_UNUSED(bisonRetval); /* Needed when not compiled in debug mode, since bisonRetval won't
                            * be used in the Q_ASSERT_X above. */

    Expression::Ptr result(info->queryBody);

    if(!result)
    {
        context->error(QtXmlPatterns::tr("A library module cannot be evaluated "
                                         "directly. It must be imported from a "
                                         "main module."),
                       ReportContext::XPST0003,
                       QSourceLocation(queryURI, 1, 1));
    }

    /* Optimization: I think many things are done in the wrong order below. We
     * probably want everything typechecked before compressing, since we can
     * have references all over the place(variable references, template
     * invocations, function callsites). This could even be a source to bugs.
     */

    /* Here, we type check user declared functions and global variables. This
     * means that variables and functions that are not used are type
     * checked(which they otherwise wouldn't have been), and those which are
     * used, are type-checked twice, unfortunately. */

    const bool hasExternalFocus = context->contextItemType();

    if(lang == QXmlQuery::XSLT20)
    {
        /* Bind xsl:call-template instructions to their template bodies.
         *
         * We do this before type checking and compressing them, because a
         * CallTemplate obviously needs its template before being compressed.
         *
         * Also, we do this before type checking and compressing user
         * functions, since they can contain template call sites.
         */
        for(int i = 0; i < info->templateCalls.count(); ++i)
        {
            CallTemplate *const site = info->templateCalls.at(i)->as<CallTemplate>();
            const QXmlName targetName(site->name());
            const Template::Ptr t(info->namedTemplates.value(targetName));

            if(t)
                site->setTemplate(t);
            else
            {
                context->error(QtXmlPatterns::tr("No template by name %1 exists.").arg(formatKeyword(context->namePool(), targetName)),
                               ReportContext::XTSE0650,
                               site);
            }
        }
    }

    /* Type check and compress user functions. */
    {
        const UserFunction::List::const_iterator end(info->userFunctions.constEnd());
        UserFunction::List::const_iterator it(info->userFunctions.constBegin());

        /* If the query has a focus(which is common, in the case of a
         * stylesheet), we must ensure that the focus isn't visible in the
         * function body. */
        StaticContext::Ptr effectiveContext;

        if(hasExternalFocus)
        {
            effectiveContext = StaticContext::Ptr(new StaticFocusContext(ItemType::Ptr(),
                                                                         context));
        }
        else
            effectiveContext = context;

        for(; it != end; ++it)
        {
            pDebug() << "-----      User Function Typecheck      -----";
            registerLastPath((*it)->body());

            /* We will most likely call body()->typeCheck() again, once for
             * each callsite. That is, it will be called from
             * UserFunctionCallsite::typeCheck(), which will be called
             * indirectly when we check the query body. */
            const Expression::Ptr typeCheck((*it)->body()->typeCheck(effectiveContext,
                                                                     (*it)->signature()->returnType()));
            /* We don't have to call (*it)->setBody(typeCheck) here since it's
             * only used directly below. */
            processTreePass(typeCheck, UserFunctionTypeCheck);
            pDebug() << "------------------------------";

            pDebug() << "-----      User Function Compress      -----";
            const Expression::Ptr comp(typeCheck->compress(effectiveContext));
            (*it)->setBody(comp);
            processTreePass(comp, UserFunctionCompression);
            pDebug() << "------------------------------";
        }
    }

    /* Type check and compress global variables. */
    {
        const VariableDeclaration::Stack::const_iterator vend(info->variables.constEnd());
        VariableDeclaration::Stack::const_iterator vit(info->variables.constBegin());
        for(; vit != vend; ++vit)
        {
            Q_ASSERT(*vit);
            /* This is a bit murky, the global variable will have it
             * Expression::typeCheck() function called from all its references,
             * but we also want to check it here globally, so we do
             * typechecking using a proper focus. */
            if((*vit)->type == VariableDeclaration::ExternalVariable)
                continue;

            pDebug() << "-----      Global Variable Typecheck      -----";
            Q_ASSERT((*vit)->expression());
            /* We supply ZeroOrMoreItems, meaning the variable can evaluate to anything. */
            // FIXME which is a source to bugs
            // TODO What about compressing variables?
            const Expression::Ptr
            nev((*vit)->expression()->typeCheck(context, CommonSequenceTypes::ZeroOrMoreItems));
            processTreePass(nev, GlobalVariableTypeCheck);
            pDebug() << "------------------------------";
        }
    }

    /* Do all tests specific to XSL-T. */
    if(lang == QXmlQuery::XSLT20)
    {
        /* Type check and compress named templates. */
        {
            pDebug() << "Have " << info->namedTemplates.count() << "named templates";

            QMutableHashIterator<QXmlName, Template::Ptr> it(info->namedTemplates);

            while(it.hasNext())
            {
                it.next();
                processNamedTemplate(it.key(), it.value()->body, TemplateInitial);

                it.value()->body = it.value()->body->typeCheck(context, CommonSequenceTypes::ZeroOrMoreItems);
                processNamedTemplate(it.key(), it.value()->body, TemplateTypeCheck);

                it.value()->body = it.value()->body->compress(context);
                processNamedTemplate(it.key(), it.value()->body, TemplateCompress);

                it.value()->compileParameters(context);
            }
        }

        /* Type check and compress template rules. */
        {
            QHashIterator<QXmlName, TemplateMode::Ptr> it(info->templateRules);

            /* Since a pattern can exist of AxisStep, its typeCheck() stage
             * requires a focus. In the case that we're invoked with a name but
             * no focus, this will yield a compile error, unless we declare a
             * focus manually. This only needs to be done for the pattern
             * expression, since the static type of the pattern is used as the
             * static type for the focus of the template body. */
            StaticContext::Ptr patternContext;
            if(hasExternalFocus)
                patternContext = context;
            else
                patternContext = StaticContext::Ptr(new StaticFocusContext(BuiltinTypes::node, context));

            /* For each template pattern. */
            while(it.hasNext())
            {
                it.next();
                const TemplateMode::Ptr &mode = it.value();
                const int len = mode->templatePatterns.count();
                TemplatePattern::ID currentTemplateID = -1;
                bool hasDoneItOnce = false;

                /* For each template pattern. */
                for(int i = 0; i < len; ++i)
                {
                    /* We can't use references for these two members, since we
                     * assign to them. */
                    const TemplatePattern::Ptr &pattern = mode->templatePatterns.at(i);
                    Expression::Ptr matchPattern(pattern->matchPattern());

                    processTemplateRule(pattern->templateTarget()->body,
                                        pattern, mode->name(), TemplateInitial);

                    matchPattern = matchPattern->typeCheck(patternContext, CommonSequenceTypes::ZeroOrMoreItems);
                    matchPattern = matchPattern->compress(patternContext);
                    pattern->setMatchPattern(matchPattern);

                    if(currentTemplateID == -1 && hasDoneItOnce)
                    {
                        currentTemplateID = pattern->id();
                        continue;
                    }
                    else if(currentTemplateID == pattern->id() && hasDoneItOnce)
                    {
                        hasDoneItOnce = false;
                        continue;
                    }

                    hasDoneItOnce = true;
                    currentTemplateID = pattern->id();
                    Expression::Ptr body(pattern->templateTarget()->body);

                    /* Patterns for a new template has started, we must
                     * deal with the body & parameters. */
                    {
                        /* TODO type is wrong, it has to be the union of all
                         * patterns. */
                        const StaticContext::Ptr focusContext(new StaticFocusContext(matchPattern->staticType()->itemType(),
                                                                                     context));
                        body = body->typeCheck(focusContext, CommonSequenceTypes::ZeroOrMoreItems);

                        pattern->templateTarget()->compileParameters(focusContext);
                    }

                    processTemplateRule(body, pattern, mode->name(), TemplateTypeCheck);

                    body = body->compress(context);

                    pattern->templateTarget()->body = body;
                    processTemplateRule(body, pattern, mode->name(), TemplateCompress);
                }

                mode->finalize();
            }
        }

        /* Add templates in mode #all to all other modes.
         *
         * We do this after the templates has been typechecked and compressed,
         * since otherwise it will be done N times for the built-in templates,
         * where N is the count of different templates, instead of once. */
        {
            const QXmlName nameModeAll(QXmlName(StandardNamespaces::InternalXSLT,
                                                StandardLocalNames::all));
            const TemplateMode::Ptr &modeAll = info->templateRules[nameModeAll];

            Q_ASSERT_X(modeAll, Q_FUNC_INFO,
                       "We should at least have the builtin templates.");
            QHashIterator<QXmlName, TemplateMode::Ptr> it(info->templateRules);

            while(it.hasNext())
            {
                it.next();

                /* Don't add mode #all to mode #all. */
                if(it.key()  == nameModeAll)
                    continue;

                it.value()->addMode(modeAll);
            }
        }
    }

    /* Type check and compress the query body. */
    {
        pDebug() << "----- Initial AST build. -----";
        processTreePass(result, QueryBodyInitial);
        pDebug() << "------------------------------";

        pDebug() << "-----     Type Check     -----";
        registerLastPath(result);
        result->rewrite(result, result->typeCheck(context, requiredType), context);
        processTreePass(result, QueryBodyTypeCheck);
        pDebug() << "------------------------------";

        pDebug() << "-----      Compress      -----";
        result->rewrite(result, result->compress(context), context);
        processTreePass(result, QueryBodyCompression);
        pDebug() << "------------------------------";
    }

    return result;
}
wxString TagEntry::FormatComment()
{
    if(m_isCommentForamtted) return m_formattedComment;
    m_isCommentForamtted = true;
    m_formattedComment.Clear();
    
    // Send the plugins an event requesting tooltip for this tag
    if(IsMethod()) {

        if(IsConstructor())
            m_formattedComment << wxT("<b>[Constructor]</b>\n");

        else if(IsDestructor())
            m_formattedComment << wxT("<b>[Destructor]</b>\n");

        TagEntryPtr p(new TagEntry(*this));
        m_formattedComment << wxT("<code>")
               << TagsManagerST::Get()->FormatFunction(p, FunctionFormat_WithVirtual | FunctionFormat_Arg_Per_Line)
               << wxT("</code>\n");
        m_formattedComment.Replace(GetName(), wxT("<b>") + GetName() + wxT("</b>"));
    } else if(IsClass()) {

        m_formattedComment << wxT("<b>Kind:</b> ");
        m_formattedComment << GetKind() << "\n";

        if(GetInheritsAsString().IsEmpty() == false) {
            m_formattedComment << wxT("<b>Inherits:</b> ");
            m_formattedComment << GetInheritsAsString() << wxT("\n");
        }

    } else if(IsMacro() || IsTypedef() || IsContainer() || GetKind() == wxT("member") ||
              GetKind() == wxT("variable")) {

        m_formattedComment << wxT("<b>Kind:</b> ");
        m_formattedComment << GetKind() << "\n";

        m_formattedComment << wxT("<b>Match Pattern:</b> ");

        // Prettify the match pattern
        wxString matchPattern(GetPattern());
        matchPattern.Trim().Trim(false);

        if(matchPattern.StartsWith(wxT("/^"))) {
            matchPattern.Replace(wxT("/^"), wxT(""));
        }

        if(matchPattern.EndsWith(wxT("$/"))) {
            matchPattern.Replace(wxT("$/"), wxT(""));
        }

        matchPattern.Replace(wxT("\t"), wxT(" "));
        while(matchPattern.Replace(wxT("  "), wxT(" "))) {
        }

        matchPattern.Trim().Trim(false);

        // BUG#3082954: limit the size of the 'match pattern' to a reasonable size (200 chars)
        matchPattern = TagsManagerST::Get()->WrapLines(matchPattern);
        matchPattern.Replace(GetName(), wxT("<b>") + GetName() + wxT("</b>"));
        m_formattedComment << wxT("<code>") << matchPattern << wxT("</code>\n");

    }

    // Add comment section
    wxString tagComment;
    if(!GetFile().IsEmpty()) {
        
        CommentParseResult comments;
        ::ParseComments(GetFile().mb_str(wxConvUTF8).data(), comments);
    
        // search for comment in the current line, the line above it and 2 above it
        // use the first match we got
        for(size_t i = 0; i < 3; i++) {
            wxString comment = comments.getCommentForLine(GetLine()-i);
            if(!comment.IsEmpty()) {
                SetComment(comment);
                break;
            }
        }
    }
    
    if(!GetComment().IsEmpty()) {
        wxString theComment;
        theComment = GetComment();

        theComment = TagsManagerST::Get()->WrapLines(theComment);
        theComment.Trim(false);
        wxString tagComment = wxString::Format(wxT("%s\n"), theComment.c_str());
        if(m_formattedComment.IsEmpty() == false) {
            m_formattedComment.Trim().Trim(false);
            m_formattedComment << wxT("\n<hr>");
        }
        m_formattedComment << tagComment;
    }

    // Update all "doxy" comments and surround them with <green> tags
    static wxRegEx reDoxyParam("([@\\\\]{1}param)[ \t]+([_a-z][a-z0-9_]*)?", wxRE_DEFAULT | wxRE_ICASE);
    static wxRegEx reDoxyBrief("([@\\\\]{1}(brief|details))[ \t]*", wxRE_DEFAULT | wxRE_ICASE);
    static wxRegEx reDoxyThrow("([@\\\\]{1}(throw|throws))[ \t]*", wxRE_DEFAULT | wxRE_ICASE);
    static wxRegEx reDoxyReturn("([@\\\\]{1}(return|retval|returns))[ \t]*", wxRE_DEFAULT | wxRE_ICASE);
    static wxRegEx reDoxyToDo("([@\\\\]{1}todo)[ \t]*", wxRE_DEFAULT | wxRE_ICASE);
    static wxRegEx reDoxyRemark("([@\\\\]{1}(remarks|remark))[ \t]*", wxRE_DEFAULT | wxRE_ICASE);
    static wxRegEx reDate("([@\\\\]{1}date)[ \t]*", wxRE_DEFAULT | wxRE_ICASE);
    static wxRegEx reFN("([@\\\\]{1}fn)[ \t]*", wxRE_DEFAULT | wxRE_ICASE);

    if(reDoxyParam.IsValid() && reDoxyParam.Matches(m_formattedComment)) {
        reDoxyParam.ReplaceAll(&m_formattedComment, "\n<b>Parameter</b>\n<i>\\2</i>");
    }

    if(reDoxyBrief.IsValid() && reDoxyBrief.Matches(m_formattedComment)) {
        reDoxyBrief.ReplaceAll(&m_formattedComment, "");
    }

    if(reDoxyThrow.IsValid() && reDoxyThrow.Matches(m_formattedComment)) {
        reDoxyThrow.ReplaceAll(&m_formattedComment, "\n<b>Throws</b>\n");
    }

    if(reDoxyReturn.IsValid() && reDoxyReturn.Matches(m_formattedComment)) {
        reDoxyReturn.ReplaceAll(&m_formattedComment, "\n<b>Returns</b>\n");
    }

    if(reDoxyToDo.IsValid() && reDoxyToDo.Matches(m_formattedComment)) {
        reDoxyToDo.ReplaceAll(&m_formattedComment, "\n<b>TODO</b>\n");
    }

    if(reDoxyRemark.IsValid() && reDoxyRemark.Matches(m_formattedComment)) {
        reDoxyRemark.ReplaceAll(&m_formattedComment, "\n  ");
    }

    if(reDate.IsValid() && reDate.Matches(m_formattedComment)) {
        reDate.ReplaceAll(&m_formattedComment, "<b>Date</b> ");
    }

    if(reFN.IsValid() && reFN.Matches(m_formattedComment)) {
        size_t fnStart, fnLen, fnEnd;
        if(reFN.GetMatch(&fnStart, &fnLen)) {
            fnEnd = m_formattedComment.find('\n', fnStart);
            if(fnEnd != wxString::npos) {
                // remove the string from fnStart -> fnEnd (including ther terminating \n)
                m_formattedComment.Remove(fnStart, (fnEnd - fnStart) + 1);
            }
        }
    }

    // if nothing to display skip this
    m_formattedComment.Trim().Trim(false);
    return m_formattedComment;
}
Example #29
0
/**
 * Compare pattern and command
 * @param pattern eg. [:MEASure]:VOLTage:DC?
 * @param cmd - command
 * @param len - max search length
 * @return TRUE if pattern matches, FALSE otherwise
 */
scpi_bool_t matchCommand(const char * pattern, const char * cmd, size_t len, int32_t *numbers, size_t numbers_len) {
    scpi_bool_t result = FALSE;
    int leftFlag = 0; // flag for '[' on left
    int rightFlag = 0; // flag for ']' on right
    int cmd_sep_pos = 0;

    size_t numbers_idx = 0;
    int32_t *number_ptr = NULL;

    const char * pattern_ptr = pattern;
    int pattern_len = strlen(pattern);
    const char * pattern_end = pattern + pattern_len;

    const char * cmd_ptr = cmd;
    size_t cmd_len = SCPIDEFINE_strnlen(cmd, len);
    const char * cmd_end = cmd + cmd_len;

    /* now support optional keywords in pattern style, e.g. [:MEASure]:VOLTage:DC? */
    if (pattern_ptr[0] == '[') { // skip first '['
        pattern_len--;
        pattern_ptr++;
        leftFlag++;
    }
    if (pattern_ptr[0] == ':') { // skip first ':'
        pattern_len--;
        pattern_ptr++;
    }

    if (cmd_ptr[0] == ':') {
        /* handle errornouse ":*IDN?" */
        if ((cmd_len >= 2) && (cmd_ptr[1] != '*')) {
            cmd_len--;
            cmd_ptr++;
        }
    }

    while (1) {
        int pattern_sep_pos = patternSeparatorPos(pattern_ptr, pattern_end - pattern_ptr);

        if ((leftFlag > 0) && (rightFlag > 0)) {
            leftFlag--;
            rightFlag--;
        } else {
            cmd_sep_pos = cmdSeparatorPos(cmd_ptr, cmd_end - cmd_ptr);
        }

        if (pattern_ptr[pattern_sep_pos - 1] == '#') {
            if (numbers && (numbers_idx < numbers_len)) {
                number_ptr = numbers + numbers_idx;
                *number_ptr = 1; // default value
            } else {
                number_ptr = NULL;
            }
            numbers_idx++;
        } else {
            number_ptr = NULL;
        }

        if (matchPattern(pattern_ptr, pattern_sep_pos, cmd_ptr, cmd_sep_pos, number_ptr)) {
            pattern_ptr = pattern_ptr + pattern_sep_pos;
            cmd_ptr = cmd_ptr + cmd_sep_pos;
            result = TRUE;

            /* command is complete */
            if ((pattern_ptr == pattern_end) && (cmd_ptr >= cmd_end)) {
                break;
            }

            /* pattern complete, but command not */
            if ((pattern_ptr == pattern_end) && (cmd_ptr < cmd_end)) {
                result = FALSE;
                break;
            }

            /* command complete, but pattern not */
            if (cmd_ptr >= cmd_end) {
                if (cmd_end == cmd_ptr) {
                    if (cmd_ptr[0] == pattern_ptr[pattern_end - pattern_ptr - 1]) {
                        break; /* exist optional keyword, command is complete */
                    }
                    if (']' == pattern_ptr[pattern_end - pattern_ptr - 1]) {
                        break; /* exist optional keyword, command is complete */
                    }
                }
                result = FALSE;
                break;
            }

            /* both command and patter contains command separator at this position */
            if ((pattern_ptr[0] == cmd_ptr[0]) && ((pattern_ptr[0] == ':') || (pattern_ptr[0] == '?'))) {
                pattern_ptr = pattern_ptr + 1;
                cmd_ptr = cmd_ptr + 1;
            } else if ((pattern_ptr[1] == cmd_ptr[0])
                    && (pattern_ptr[0] == '[')
                    && (pattern_ptr[1] == ':')) {
                pattern_ptr = pattern_ptr + 2; // for skip '[' in "[:"
                cmd_ptr = cmd_ptr + 1;
                leftFlag++;
            } else if ((pattern_ptr[1] == cmd_ptr[0])
                    && (pattern_ptr[0] == ']')
                    && (pattern_ptr[1] == ':')) {
                pattern_ptr = pattern_ptr + 2; // for skip ']' in "]:"
                cmd_ptr = cmd_ptr + 1;
            } else if ((pattern_ptr[2] == cmd_ptr[0])
                    && (pattern_ptr[0] == ']')
                    && (pattern_ptr[1] == '[')
                    && (pattern_ptr[2] == ':')) {
                pattern_ptr = pattern_ptr + 3; // for skip '][' in "][:"
                cmd_ptr = cmd_ptr + 1;
                leftFlag++;
            } else if (((pattern_ptr[0] == ']')
                    || (pattern_ptr[0] == '['))
                    && (*(pattern_end - 1) == '?') // last is '?'
                    && (cmd_ptr[0] == '?')) {
                result = TRUE; // exist optional keyword, and they are end with '?'
                break; // command is complete  OK
            } else {
                result = FALSE;
                break;
            }
        } else {
            pattern_ptr = pattern_ptr + pattern_sep_pos;
            if ((pattern_ptr[0] == ']') && (pattern_ptr[1] == ':')) {
                pattern_ptr = pattern_ptr + 2; // for skip ']' in "]:" , pattern_ptr continue, while cmd_ptr remain unchanged
                rightFlag++;
            } else if ((pattern_ptr[0] == ']')
                    && (pattern_ptr[1] == '[')
                    && (pattern_ptr[2] == ':')) {
                pattern_ptr = pattern_ptr + 3; // for skip ']' in "][:" , pattern_ptr continue, while cmd_ptr remain unchanged
                rightFlag++;
            } else {
                result = FALSE;
                break;
            }
        }
    }

    return result;
}
Example #30
0
void VSearch::searchFirstPhase(VFile *p_file,
                               const QSharedPointer<VSearchResult> &p_result,
                               bool p_searchContent)
{
    Q_ASSERT(testTarget(VSearchConfig::Note));

    QString name = p_file->getName();
    if (!matchPattern(name)) {
        return;
    }

    QString filePath = p_file->fetchPath();
    if (testObject(VSearchConfig::Name)) {
        if (matchNonContent(name)) {
            VSearchResultItem *item = new VSearchResultItem(VSearchResultItem::Note,
                                                            VSearchResultItem::LineNumber,
                                                            name,
                                                            filePath);
            QSharedPointer<VSearchResultItem> pitem(item);
            emit resultItemAdded(pitem);
        }
    }

    if (testObject(VSearchConfig::Path)) {
        QString normFilePath;
        if (p_file->getType() == FileType::Note) {
            normFilePath = static_cast<VNoteFile *>(p_file)->fetchRelativePath();
        } else {
            normFilePath = filePath;
        }

        removeSlashFromPath(normFilePath);
        if (matchNonContent(normFilePath)) {
            VSearchResultItem *item = new VSearchResultItem(VSearchResultItem::Note,
                                                            VSearchResultItem::LineNumber,
                                                            name,
                                                            filePath);
            QSharedPointer<VSearchResultItem> pitem(item);
            emit resultItemAdded(pitem);
        }
    }

    if (testObject(VSearchConfig::Outline)) {
        VSearchResultItem *item = searchForOutline(p_file);
        if (item) {
            QSharedPointer<VSearchResultItem> pitem(item);
            emit resultItemAdded(pitem);
        }
    }

    if (testObject(VSearchConfig::Tag)) {
        VSearchResultItem *item = searchForTag(p_file);
        if (item) {
            QSharedPointer<VSearchResultItem> pitem(item);
            emit resultItemAdded(pitem);
        }
    }

    if (testObject(VSearchConfig::Content)) {
        // Search content in first phase.
        if (p_searchContent) {
            VSearchResultItem *item = searchForContent(p_file);
            if (item) {
                QSharedPointer<VSearchResultItem> pitem(item);
                emit resultItemAdded(pitem);
            }
        } else {
            // Add an item for second phase process.
            p_result->addSecondPhaseItem(filePath);
        }
    }
}