Пример #1
0
// Parse a template declaration.
//
//    tempate-declaration:
//      'template' '<' template-parameter-list '>' [requires-clause] declaration
//
// FIXME: Support explicit template instantiations in one way or
// another.
Decl&
Parser::template_declaration()
{
  #if 0
  require(tk::template_tok);

  // Build a psuedo-scope.
  //
  // FIXME: Merge this with template parameter scope. I don't think
  // that it's serving a very useful purpose.
  // Template_scope& tmp = cxt.make_template_scope();
  Enter_scope tscope(cxt, tmp);

  // TODO: Allow >> to close the template parameter list in the
  // case of default template arguments.
  Enter_template_parameter_scope pscope(cxt);
  match(tk::lt_tok);
  tmp.parms = template_parameter_list();
  match(tk::gt_tok);

  // Parse the optional requires clause, followed by the parameterized
  // declaration.
  if (tk::next_token_is(tk::requires_tok)) {
    // TODO: How are dependent names resolved in a requires clause?
    tmp.cons = &requires_clause();
    // Enter_scope cscope(cxt, cxt.make_constrained_scope(*tmp.cons));
    Parsing_template save(*this, &tmp.parms, tmp.cons);
    return declaration();
  } else {
    Parsing_template save(*this, &tmp.parms);
    return declaration();
  }
  #endif
  lingo_unreachable();
}
Пример #2
0
int declaration_list(void) {
	if( declaration() ) {
	} else if( declaration_list() ) {
		declaration();
	} else {
		abort();
	}
}
Пример #3
0
Parameter::Parameter(const std::string& decl, Function* pFunction):
	Decl(handleDecl(decl), 0), // handle init values
	_type(),
	_isRef(false),
	_isPointer(false),
	_isConst(false)
{
	std::size_t pos = declaration().rfind(name());
	std::string tmp;
	if (pos == 0 && name().size() == declaration().size())
		tmp = declaration();
	else
		tmp = declaration().substr(0, pos);
	_type = Poco::trim(tmp);
	std::size_t rightCut = _type.size();
	while (rightCut > 0 && (_type[rightCut-1] == '&' || _type[rightCut-1] == '*' || _type[rightCut-1] == '\t' || _type[rightCut-1] == ' '))
	{
		if (_type[rightCut-1] == '&')
			_isRef = true;
		if (_type[rightCut-1] == '*')
			_isPointer = true;
		--rightCut;
	}
	_type = Poco::trim(_type.substr(0, rightCut));
	if (_type.find("const ") == 0)
	{
		_isConst = true;
		_type = _type.substr(6);
	}
	if (_type.find("const\t") == 0)
	{
		_type = _type.substr(6);
		_isConst = true;
	}

	Poco::trimInPlace(_type);
	pos = decl.find("=");
	_hasDefaultValue = (pos != std::string::npos);
	if (_hasDefaultValue)
	{
		_defaultDecl = decl.substr(pos + 1);
		Poco::trimInPlace(_defaultDecl);
		std::size_t posStart = _defaultDecl.find("(");
		std::size_t posEnd = _defaultDecl.rfind(")");
		if (posStart != std::string::npos && posEnd != std::string::npos)
		{
			_defaultValue = _defaultDecl.substr(posStart + 1, posEnd-posStart - 1);
		}
		else
		{
			poco_assert (posStart == std::string::npos && posEnd == std::string::npos);
			_defaultValue = _defaultDecl;
		}
		Poco::trimInPlace(_defaultValue);
	}
}
Пример #4
0
void CodeRuntimeBinding::updateValue(){
    if ( m_converter ){
        QString code = m_converter->serialize()->toCode(
            sender()->property(declaration()->identifierChain().last().toUtf8()), 0
        );
        if ( !code.isEmpty() ){
            declaration()->document()->updateBindingValue(this, code);
            m_modifiedByEngine = true;
        }
    }
}
Пример #5
0
QVariant CompletionItem::data(const QModelIndex& index, int role, const KDevelop::CodeCompletionModel* model) const
{
    switch(role)
    {
        case Qt::DisplayRole:
        {
            if (index.column() == CodeCompletionModel::Prefix && m_prefix != "") {
                return m_prefix;
            }
            break;
        }
        case CodeCompletionModel::BestMatchesCount:
            return 5;
        case CodeCompletionModel::MatchQuality:
        {
            if(!declaration())
                return QVariant();
            //type aliases are actually different types
            if(declaration()->isTypeAlias())
                return QVariant();
            AbstractType::Ptr typeToMatch = static_cast<go::CodeCompletionContext*>(model->completionContext().data())->typeToMatch();
            if(!typeToMatch)
                return QVariant();
            AbstractType::Ptr declType = declaration()->abstractType();
            if (!declType)
                return QVariant();
            //ignore constants
            typeToMatch->setModifiers(AbstractType::NoModifiers);
            declType->setModifiers(AbstractType::NoModifiers);
            if(declType->equals(typeToMatch.constData()))
            {
                return QVariant(10);
            }
            else if(declType->whichType() == AbstractType::TypeFunction)
            {
                GoFunctionType* function = fastCast<GoFunctionType*>(declType.constData());
                auto args = function->returnArguments();
                if(args.size() != 0)
                {
                    AbstractType::Ptr first = args.first();
                    first->setModifiers(AbstractType::NoModifiers);
                    if(first->equals(typeToMatch.constData()))
                        return QVariant(10);
                }
            }else
            {
                return QVariant();
            }
        }
    }
    return NormalDeclarationCompletionItem::data(index, role, model);
}
Пример #6
0
/* EBNF: declaration-list -> declaration {declaration} */
static TreeNode * declaration_list(void)
{ TreeNode * t = declaration();
  TreeNode * p = t;
  TreeNode * newNode = NULL;

  /* {declaration} */
  while (token != ENDFILE)
  { newNode = declaration();
    if ((newNode != NULL) && (p != NULL))
    { p->sibling = newNode;
      p = newNode;
    }
  }
  return t;
}
Пример #7
0
TOKEN external_declaration(void)
{
    TOKEN ext_declaration = NULL;
    SYMBOL sym = symalloc(); //symbol for the declaration we are dealing with
    //used as a temporary place to aggregate data about the declaration until
    //we can install the symbol

    //NOTE: we check for a global declaration first because we can easily use
    //the information we aggregate in the SYMBOL sym and pass it on rather than
    //having to backtrack like we would if we looked for a function definition first
    setStorageClass(sym, STATIC_STORAGE_CLASS);
    ext_declaration = declaration(sym);
    if( NULL == ext_declaration )
    {
        //we have a function definition instead of a global variable declaration
        //and functions default to external storage
        setStorageClass(sym, EXTERNAL_STORAGE_CLASS); 
        ext_declaration = function_definition(sym);
    }
    else
    {
        ext_declaration = NULL; //we don't want the variable declaration to make its way into the parse tree, so return NULL
    }

    return ext_declaration;
}
Пример #8
0
struct definition parse(void)
{
    static struct definition last_def_returned;
    struct definition def = {0};

    while (!defs.len && peek().token != END) {
        /* Parse a declaration, which can include definitions that will fill
         * up the buffer. Tentative declarations will only affect the symbol
         * table. */
        declaration(NULL);
        clear_definition(&fallback);
    }

    if (defs.cur < defs.len) {
        def = defs.def[defs.cur++];
        if (defs.cur == defs.len) {
            /* Clear definition list once the last entry is returned. No leaks
             * after everything is consumed. */
            free(defs.def);
            memset(&defs, 0, sizeof(defs));
        }
    }

    /* Clear memory allocated for previous result. Parse is called until no
     * more input can be consumed, letting us free all memory. */
    if (last_def_returned.symbol)
        clear_definition(&last_def_returned);

    last_def_returned = def;
    return def;
}
Пример #9
0
double statement()
    //Handle 'let' and 'const' keywords
{
    Token t = ts.get();
    switch(t.kind) {
        case let:
            return declaration(false);
            break;
        case con:
            return declaration(true);
            break;
        default:
            ts.putback(t);
            return expression();
    }
}
Пример #10
0
void test_declaration()
{
    const char *tokensv[] = { "int", "a" };
    unsigned int tokensc = 2;
    const char *expected_calls[] = {
        /* eat the 'int' */
        "lex_advance",
        "lex_look_ahead",
        "stack_assign_name",
        "lex_look_ahead",
        "stack_frame_size",
        /* subract 4 from the stack */
        "output_stack_allocate",
    };
    unsigned int count = 6;
    ecc_context *ctx;
    mock_data *data;

    ctx = init_fake_context(tokensv, tokensc);

    /* mock out the stack frame size response */
    data = (mock_data *)ctx->data;
    data->mock_return_uint_vals[0] = 1;

    declaration(ctx, tokensv[0]);

    check_expected_calls(ctx, "test_declaration", expected_calls, count);

}
Пример #11
0
void CodeGenerator::codeGeneration(vector<Node> parseTree)
{
    // set up print function
    llvmCode.push_back("@istr = private constant[4 x i8] c\"%d\\0A\\00\"\n");
    llvmCode.push_back("@fstr = private constant[4 x i8] c\"%f\\0A\\00\"\n");
    llvmCode.push_back("declare i32 @printf(i8*, ...)\n\n");

    // scan the tree to generate the code
    for (vector<Node>::iterator it = parseTree.begin(); it != parseTree.end();
         it++) {
        // Start analyzing the tree
        if (it->symbol == "DeclList'")  // declaration of variable or function
            appendVectors(llvmCode, declaration(it));
        else if (it->symbol == "VarDecl")  // declaration of variable (could be array)
            appendVectors(llvmCode,varDecl(it));
        else if (it->symbol == "Stmt")  // statement is appeared
            appendVectors(llvmCode, statement(it));
        else if (it->symbol == "{") {
            llvmCode.push_back("{\n");
            instruction = 0;
        }
        else if (it->symbol == "}")
            llvmCode.push_back("}\n");
    }
    exportLlvmCode();
}
Пример #12
0
static
stmt_code(stream, node, brk, cont, ret) {
    /* Handle the null expression. */
    if ( !node ) return;

    auto op = node[0];

    /* For debugging purposes, put a blank line between each statement. */
    fputs("\n", stream);

    if      ( op == 'dcls' ) declaration( stream, node );

    else if ( op == 'brea' ) branch( stream, brk );
    else if ( op == 'cont' ) branch( stream, cont ); 
    else if ( op == 'retu' ) return_stmt( stream, node, ret );
    else if ( op == 'goto' ) goto_stmt( stream, node );

    else if ( op == 'if'   ) if_stmt( stream, node, brk, cont, ret );
    else if ( op == 'whil' ) while_stmt( stream, node, brk, cont, ret );
    else if ( op == 'for'  ) for_stmt( stream, node, brk, cont, ret );
    else if ( op == 'do'   ) do_stmt( stream, node, brk, cont, ret );
    else if ( op == 'swit' ) switch_stmt( stream, node, brk, cont, ret );
    else if ( op == 'case' 
          ||  op == 'defa' ) case_stmt( stream, node, brk, cont, ret );
    
    else if ( op == ':'    ) label_stmt( stream, node, brk, cont, ret );
    else if ( op == '{}'   ) do_block( stream, node, brk, cont, ret );
    else                     expr_code( stream, node, 0 );
}
Пример #13
0
void
bind_names ( node_t *root )
{
	if (root != NULL) {
		switch (root->type.index) {
			
			case PROGRAM:
				program(root);
				break;
			case FUNCTION_LIST:
				bind_functions(root);
				break;
			case FUNCTION:
				function(root);
				break;
			case VARIABLE:
				variable(root);
				break;
			case BLOCK:
				block(root);
				break;
			case DECLARATION:
				declaration(root);
				break;
			case TEXT:
				string(root);
				break;
			default: 
				skipNode(root);
				break;
		
		}

	}
}
Пример #14
0
std::string Function::signature() const
{
	std::string signature(declaration());
	if (signature.compare(0, 8, "virtual ") == 0)
		signature.erase(0, 8);
	else if (signature.compare(0, 7, "static ") == 0)
		signature.erase(0, 8);
	if (signature.compare(0, 7, "inline ") == 0)
		signature.erase(0, 7);
	signature += "(";
	bool isFirst = true;
	for (Iterator it = begin(); it != end(); ++it)
	{
		if (isFirst)
			isFirst = false;
		else
			signature += ", ";
		std::string arg = (*it)->declaration();
		std::string::size_type pos = arg.size() - 1;
		while (pos > 0 && !std::isspace(arg[pos])) --pos;
		while (pos > 0 && std::isspace(arg[pos])) --pos;
		signature.append(arg, 0, pos + 1);
	}
	signature += ")";
	if (_flags & FN_CONST)
		signature += " const";
	return signature;
}
Пример #15
0
DeclarationsPtr Parser::parseArgumentList()
{
    IdentifiersPtr identifiers = parseIdentifierList();
    if (m_errorCode > ErrorCodes::NoError) {
        return DeclarationsPtr();
    }

    if (!match(TokenType::Colon)) {
        reportError(ErrorCodes::ExpectedColon);
        return DeclarationsPtr();
    }

    TypePtr type = parseType();
    if (m_errorCode > ErrorCodes::NoError) {
        return DeclarationsPtr();
    }

    DeclarationsPtr declarations(new Declarations);
    for (std::vector<IdentifierPtr>::const_iterator i = identifiers->list.begin(); i != identifiers->list.end(); ++i) {
        DeclarationPtr declaration(new Declaration);
        declaration->id = *i;
        declaration->type = type;

        declarations->list.push_back(declaration);
    }

    DeclarationsPtr rest = parseArgumentList_r();
    if (rest) {
        declarations->list.insert(declarations->list.end(), rest->list.begin(), rest->list.end());
    }

    return declarations;
}
Пример #16
0
Файл: parse.c Проект: pexcn/Lily
void program()
{
	int entry_flag  = 0;
	Symbol *p, *q;
	
	/* before parse insert read && write func */
	p = insert_global_sym(FUNCTION,"read");
	q = insert_global_sym(FUNCTION,"write");
	if(!p || !q){
		fprintf(stderr, "init read write function error\n");
		exit(0);
	}
	
	token = get_token();
	
	while(token == TOK_INT || token == TOK_PVOID
	      || token == TOK_VOID || token == TOK_CHAR
	      || token == TOK_PINT || token == TOK_PCHAR)
	{
		entry_flag = 1;
		declaration(token);
	}
	
	if(entry_flag){
		gen_code("stp\n");
		printf("succeed!!  exit()\n");
	}else{
		fprintf(stderr, "line %d: %s does not name a type\n", save_line, save_word );
	}
	
}
Пример #17
0
void direct_declaration(void)
{
  if (token.type == NAME)
    strcpy(name, token.value);
  else
    if (token.type == LEFT_PARENS)
      {
        declaration();
        if (token.type != RIGHT_PARENS)
          {
            fprintf(stderr, "missing ) on line %d\n", line);
            n_errors++;
          }
      }
    else
      {
        fprintf(stderr, "expected name or (dcl) on line %d\n", line);
        n_errors++;
      }
  for(gettoken();
      token.type == BOTH_PARENS || token.type == BRACKETS;
      gettoken())
    if (token.type == BOTH_PARENS)
      strcat(description, " function returning");
    else
      {
        strcat(description, " array");
        strcat(description, token.value);
        strcat(description, " of");
      }
}
Пример #18
0
void Parser::parseIf(){
	//then we know we have to parse an expression
	getNext();

	if(curr->type!=L_PAREN){
		//then throw an exception
		throw new YottaError(SYNTAX_ERROR, ERROR_MSG[8], curr->line, curr->ch);
	}

	//else start parsing an expression
	expression();

	//next we make sure we have a closing bracket
	if(curr->type!=R_PAREN){
		throw new YottaError(SYNTAX_ERROR, ERROR_MSG[9], curr->line, curr->ch);
	}

	getNext();

	IF_STATEMENT_FLAG++;

	//let's see if we have an opening left curly brace
	if(curr->type==L_CURLY){
		//then we would parse until we find a }

		while(curr->type!=R_CURLY){
			//then continue parsing
			declaration();

			if(curr->type==NULL_TOKEN){
				throw new YottaError(SYNTAX_ERROR, ERROR_MSG[12], curr->line, curr->ch-1);
			}
		}
	}
}
Пример #19
0
int external_declaration(void) {
	if( function_definition() ) {
	} else if( declaration() ) {
	} else {
		abort();
	}
}
Пример #20
0
bool Wiinnertag::CreateExample(const string &filepath)
{
	if(filepath.size() == 0)
		return false;

	CreateSubfolder(filepath.c_str());

	string fullpath = filepath;
	if(fullpath[fullpath.size()-1] != '/')
		fullpath += '/';
	fullpath += "Wiinnertag.xml";

	TiXmlDocument xmlDoc;

	TiXmlDeclaration declaration("1.0", "UTF-8", "");
	xmlDoc.InsertEndChild(declaration);

	TiXmlElement Tag("Tag");
	Tag.SetAttribute("URL", "http://www.wiinnertag.com/wiinnertag_scripts/update_sign.php?key={KEY}&game_id={ID6}");
	Tag.SetAttribute("Key", "1234567890");
	xmlDoc.InsertEndChild(Tag);

	xmlDoc.SaveFile(fullpath);

	return true;
}
Пример #21
0
void FunctionDeclarationCompletionItem::executed(KTextEditor::View* view, const KTextEditor::Range& word)
{
    qCDebug(KDEV_PYTHON_CODECOMPLETION) << "FunctionDeclarationCompletionItem executed";
    KTextEditor::Document* document = view->document();
    auto resolvedDecl = Helper::resolveAliasDeclaration(declaration().data());
    DUChainReadLocker lock;
    auto functionDecl = Helper::functionForCalled(resolvedDecl).declaration;
    lock.unlock();
    if ( ! functionDecl && (! resolvedDecl || ! resolvedDecl->abstractType()
                           || resolvedDecl->abstractType()->whichType() != AbstractType::TypeStructure) ) {
        qCritical(KDEV_PYTHON_CODECOMPLETION) << "ERROR: could not get declaration data, not executing completion item!";
        return;
    }
    QString suffix = "()";
    KTextEditor::Range checkPrefix(word.start().line(), 0, word.start().line(), word.start().column());
    KTextEditor::Range checkSuffix(word.end().line(), word.end().column(), word.end().line(), document->lineLength(word.end().line()));
    if ( m_doNotCall || document->text(checkSuffix).trimmed().startsWith('(')
         || document->text(checkPrefix).trimmed().endsWith('@')
         || (functionDecl && Helper::findDecoratorByName(functionDecl, QLatin1String("property"))) )
    {
        // don't insert brackets if they're already there,
        // the item is a decorator, or if it's an import item.
        suffix.clear();
    }
    // place cursor behind bracktes by default
    int skip = 2;
    if ( functionDecl ) {
        bool needsArguments = false;
        int argumentCount = functionDecl->type<FunctionType>()->arguments().length();
        if ( functionDecl->context()->type() == KDevelop::DUContext::Class ) {
            // it's a member function, so it has the implicit self
            // TODO static methods
            needsArguments = argumentCount > 1;
        }
        else {
            // it's a free function
            needsArguments = argumentCount > 0;
        }
        if ( needsArguments ) {
            // place cursor in brackets if there's parameters
            skip = 1;
        }
    }
    document->replaceText(word, declaration()->identifier().toString() + suffix);
    view->setCursorPosition( Cursor(word.end().line(), word.end().column() + skip) );
}
Пример #22
0
Node<MemberNode>::Link TypeParser::member(Visibility vis, bool isStatic) {
  Trace mbTrace = current().trace;
  auto parsedAsDecl = declaration();
  auto mbNode = Node<MemberNode>::make(parsedAsDecl->getIdentifier(), parsedAsDecl->getTypeInfo().getEvalTypeList(), isStatic, vis == INVALID ? PRIVATE : vis);
  mbNode->setTrace(mbTrace);
  if (parsedAsDecl->getChildren().size() > 0) mbNode->setInit(Node<ExpressionNode>::staticPtrCast(parsedAsDecl->removeChild(0)));
  return mbNode;
}
Пример #23
0
void declarations(void){
	
	if(lookahead == CHAR || lookahead == INT){
      declaration();
      declarations();
	}

}
Пример #24
0
static
void
exec(const Ast *ast) {
//printf("executing "); pn(ast);
	Value *v;
	switch(ast->class) {
	case N_BLOCK:
		block(ast);
		return;
	case N_IF:
		ifstat(ast);
		return;
	case N_WHILE:
		whilestat(ast);
		return;
	case N_DECLARATION:
		declaration(ast);
		return;
	case N_FUNCTION:
		return;
	case N_RETURN:
		returnstat(ast);
		return;
	case N_CALL:
	case N_ASSIGNMENT:
	case N_IDENTIFIER:
	case N_NEG:
	case N_NOT:
	case N_EQ:
	case N_NEQ:
	case N_AND:
	case N_IOR:
	case N_XOR:
	case N_LT:
	case N_LE:
	case N_GE:
	case N_GT:
	case N_ADD:
	case N_SUB:
	case N_MUL:
	case N_DIV:
	case N_POW:
	case N_MOD:
	case N_BOOLEAN:
	case N_INTEGER:
	case N_FLOAT:
	case N_STRING:
	case N_SET:
	case N_R:
		v = eval(ast);
//do { print_tree(2, ast); dprintf(2, " evaluates to "); pv(v); } while(0);
		value_free(v);
		return;
	}
printf("EXECFAIL %d ", ast->class); pn(ast);
	assert(false && "should not be reached");
}
Пример #25
0
TOKEN declaration_list(SYMBOL s)
{
    TOKEN dec_list = declaration(s);
    if( dec_list != NULL)
    {
        //FIXME this might be a bug, but I'm not sure yet
        set_token_link(dec_list, declaration_list(s));
    }
    return dec_list;
}
Пример #26
0
double statement(){
	Token t = ts.get();
	switch(t.kind){
		case let:
			return declaration();	// 変数の宣言
		default:
			ts.putback(t);
			return expression();
	}
}
Пример #27
0
// トークンが"let"であればDecleartion
// それ以外であればExpressionとして処理
double statement()
{
	Token t = ts.get();
	switch(t.kind) {
		case let:
			return declaration();
		default:
			ts.unget(t);
			return expression();
	}
}
Пример #28
0
double statement(Token_stream& ts)
{
	Token t = ts.get();
	switch (t.kind) {
	case let:
		return declaration(ts);
	default:
		ts.putback(t);
		return expression(ts);
	}
}
Пример #29
0
    /*=============================================================================
    -- Returns true if the token is a declaration (#declaration).
    =============================================================================*/
    bool HMLFile::TokenIsDeclaration(String dec)
    {
        //add the # if it isn't already there
        String declaration(dec);
        if (declaration[0] != "#")
            declaration.Insert("#", 0);

        if (GetToken() == declaration.GetStd())
            return true;

        return false;
    }
Пример #30
0
double statement()
{
  Token t = ts.get();
  switch (t.kind)
  {
    case LET:     // how to get a token that is more than 1 characters long
      return declaration();
    default:
      ts.putback(t);
      return expression();
  }
}