Exemplo n.º 1
0
void Branch__functions(caStack* stack)
{
    Branch* branch = as_branch(circa_input(stack, 0));
    if (branch == NULL)
        return circa_output_error(stack, "NULL branch");

    caValue* output = circa_output(stack, 0);
    set_list(output, 0);

    for (BranchIteratorFlat it(branch); it.unfinished(); it.advance()) {
        Term* term = *it;
        if (is_function(term)) {
            set_branch(list_append(output), function_contents(as_function(term)));
        }
    }
}
Exemplo n.º 2
0
int parser_t::get_lineno() const
{
    int lineno = -1;
    if (! execution_contexts.empty())
    {
        lineno = execution_contexts.back()->get_current_line_number();

        /* If we are executing a function, we have to add in its offset */
        const wchar_t *function_name = is_function();
        if (function_name != NULL)
        {
            lineno += function_get_definition_offset(function_name);
        }

    }
    return lineno;
}
Exemplo n.º 3
0
static BOOL CALLBACK
enum_functions_callback (SYMBOL_INFO * sym_info,
                         gulong symbol_size,
                         gpointer user_context)
{
  GArray * result = user_context;

  (void) symbol_size;

  if (is_function (sym_info))
  {
    gpointer address = GSIZE_TO_POINTER (sym_info->Address);
    g_array_append_val (result, address);
  }

  return TRUE;
}
Exemplo n.º 4
0
Term ProcDelVertex(Term t, List ind)
{
	List l, pl;
	
	if(lagr_hash==NULL)
	{
		ErrorInfo(107);
		puts("DelVertex: no vertices");
		return 0;
	}
	
	
	if(!is_compound(t)||CompoundArity(t)!=1)
	{
		ErrorInfo(107);
		puts("wrong call to DelVertex");
		return 0;
	}
	
	pl=CompoundArg1(t);
	if(!is_list(pl))
	{
		ErrorInfo(107);
		puts("wrong call to DelVertex");
		return 0;
	}
	
	for(l=pl;l;l=ListTail(l))
		if(is_function(ListFirst(l),0))
			ChangeList(l,CallFunction(ListFirst(l),0));
	
	pl=SortedList(pl,acmp);
	
	l=finda2(pl,1);
	
	if(is_empty_list(l))
	{
	WarningInfo(108);printf("DelVertex: vertex ");
	WriteTerm(pl); puts(" not found");
	return 0;
	}
	
	
	return 0;
}
Exemplo n.º 5
0
void native_patch_apply_patch(NativePatch* module, Block* block)
{
    // Walk through list of patches, and try to find any functions to apply them to.
    std::map<std::string, EvaluateFunc>::const_iterator it;
    for (it = module->patches.begin(); it != module->patches.end(); ++it) {
        std::string const& name = it->first;
        EvaluateFunc evaluateFunc = it->second;

        Term* term = find_local_name(block, name.c_str());

        if (term == NULL)
            continue;
        if (!is_function(term))
            continue;

        install_function(term, evaluateFunc);
    }
}
Exemplo n.º 6
0
void list_initialize_parameter_from_type_decl(Block* typeDecl, caValue* parameter)
{
    set_list(parameter, 2);
    caValue* types = set_list(list_get(parameter, 0), 0);
    caValue* names = set_list(list_get(parameter, 1), 0);

    // Iterate through the type definition.
    for (int i=0; i < typeDecl->length(); i++) {
        Term* term = typeDecl->get(i);

        if (!is_function(term))
            continue;

        Type* type = function_get_output_type(term, 0);

        set_type(list_append(types), type);
        set_string(list_append(names), term->name);
    }
}
Exemplo n.º 7
0
void write_statement(CppWriter& writer, Term* term)
{
    if (is_comment(term)) {
        if (term->stringProp("comment") != "") {
            writer.write("//");
            writer.write(term->stringProp("comment"));
        }
    } else if (is_function(term)) {
        write_function(writer, term);
    } else if (is_statement(term)) {
        if (term->name != "") {
            write_type_name(writer, term->type);
            writer.write(" ");
            writer.write(term->name);
            writer.write(" = ");
        }
        write_expression(writer, term);
        writer.write(";");
    }
}
Exemplo n.º 8
0
void write_term(SourceWriter* writer, Term* term)
{
    if (is_comment(term)) {
        if (is_empty_comment(term))
            return;

        writer->write("// ");
        writer->write(term->stringProp("comment","").c_str());
        writer->newline();
        return;
    }

    if (is_function(term)) {
        write_function(writer, term);
        return;
    }

    writer->write(get_unique_name(term));
    writer->write(" = ");

    if (is_value(term)) {
        write_term_value(writer, term);
    } else {
        // function call syntax
        writer->write(term->function->name.c_str());
        writer->write("(");

        // write inputs
        for (int i=0; i < term->numInputs(); i++) {
            if (i > 0) {
                writer->write(", ");
            }
            writer->write(get_unique_name(term));
        }
    }

    writer->write(";");
    writer->newline();
}
Exemplo n.º 9
0
/*******************************************************************
 *         output_module16
 *
 * Output code for a 16-bit module.
 */
static void output_module16( DLLSPEC *spec )
{
    ORDDEF **typelist;
    ORDDEF *entry_point = NULL;
    int i, j, nb_funcs;

    /* store the main entry point as ordinal 0 */

    if (!spec->ordinals)
    {
        assert(spec->limit == 0);
        spec->ordinals = xmalloc( sizeof(spec->ordinals[0]) );
        spec->ordinals[0] = NULL;
    }
    if (spec->init_func && !(spec->characteristics & IMAGE_FILE_DLL))
    {
        entry_point = xmalloc( sizeof(*entry_point) );
        entry_point->type = TYPE_PASCAL;
        entry_point->ordinal = 0;
        entry_point->lineno = 0;
        entry_point->flags = FLAG_REGISTER;
        entry_point->name = NULL;
        entry_point->link_name = xstrdup( spec->init_func );
        entry_point->export_name = NULL;
        entry_point->u.func.nb_args = 0;
        assert( !spec->ordinals[0] );
        spec->ordinals[0] = entry_point;
    }

    /* Build sorted list of all argument types, without duplicates */

    typelist = xmalloc( (spec->limit + 1) * sizeof(*typelist) );

    for (i = nb_funcs = 0; i <= spec->limit; i++)
    {
        ORDDEF *odp = spec->ordinals[i];
        if (!odp) continue;
        if (is_function( odp )) typelist[nb_funcs++] = odp;
    }

    nb_funcs = sort_func_list( typelist, nb_funcs, callfrom16_type_compare );

    /* Output the module structure */

    output( "\n/* module data */\n\n" );
    output( "\t.data\n" );
    output( "\t.align %d\n", get_alignment(4) );
	output("\t.globl __wine_spec_dos_header\n");
	output("__wine_spec_dos_header:\n");
	output("\t.globl _wine_spec_dos_header\n");
	output("_wine_spec_dos_header:\n");
    output( ".L__wine_spec_dos_header:\n" );
    output( "\t.short 0x5a4d\n" );                                         /* e_magic */
    output( "\t.short 0\n" );                                              /* e_cblp */
    output( "\t.short 0\n" );                                              /* e_cp */
    output( "\t.short 0\n" );                                              /* e_crlc */
    output( "\t.short 0\n" );                                              /* e_cparhdr */
    output( "\t.short 0\n" );                                              /* e_minalloc */
    output( "\t.short 0\n" );                                              /* e_maxalloc */
    output( "\t.short 0\n" );                                              /* e_ss */
    output( "\t.short 0\n" );                                              /* e_sp */
    output( "\t.short 0\n" );                                              /* e_csum */
    output( "\t.short 0\n" );                                              /* e_ip */
    output( "\t.short 0\n" );                                              /* e_cs */
    output( "\t.short 0\n" );                                              /* e_lfarlc */
    output( "\t.short 0\n" );                                              /* e_ovno */
    output( "\t.short 0,0,0,0\n" );                                        /* e_res */
    output( "\t.short 0\n" );                                              /* e_oemid */
    output( "\t.short 0\n" );                                              /* e_oeminfo */
    output( "\t.short 0,0,0,0,0,0,0,0,0,0\n" );                            /* e_res2 */
    output( "\t.long .L__wine_spec_ne_header-.L__wine_spec_dos_header\n" );/* e_lfanew */

    output( ".L__wine_spec_ne_header:\n" );
    output( "\t.short 0x454e\n" );                                         /* ne_magic */
    output( "\t.byte 0\n" );                                               /* ne_ver */
    output( "\t.byte 0\n" );                                               /* ne_rev */
    output( "\t.short .L__wine_spec_ne_enttab-.L__wine_spec_ne_header\n" );/* ne_enttab */
    output( "\t.short .L__wine_spec_ne_enttab_end-.L__wine_spec_ne_enttab\n" );/* ne_cbenttab */
    output( "\t.long 0\n" );                                               /* ne_crc */
    output( "\t.short 0x%04x\n", NE_FFLAGS_SINGLEDATA |                    /* ne_flags */
             ((spec->characteristics & IMAGE_FILE_DLL) ? NE_FFLAGS_LIBMODULE : 0) );
    output( "\t.short 2\n" );                                              /* ne_autodata */
    output( "\t.short %u\n", spec->heap_size );                            /* ne_heap */
    output( "\t.short 0\n" );                                              /* ne_stack */
    if (!entry_point) output( "\t.long 0\n" );                             /* ne_csip */
    else output( "\t.short .L__wine_%s_0-.L__wine_spec_code_segment,1\n",
                 make_c_identifier(spec->dll_name) );
    output( "\t.short 0,2\n" );                                            /* ne_sssp */
    output( "\t.short 2\n" );                                              /* ne_cseg */
    output( "\t.short 0\n" );                                              /* ne_cmod */
    output( "\t.short 0\n" );                                              /* ne_cbnrestab */
    output( "\t.short .L__wine_spec_ne_segtab-.L__wine_spec_ne_header\n" );/* ne_segtab */
    output( "\t.short .L__wine_spec_ne_rsrctab-.L__wine_spec_ne_header\n" );   /* ne_rsrctab */
    output( "\t.short .L__wine_spec_ne_restab-.L__wine_spec_ne_header\n" );    /* ne_restab */
    output( "\t.short .L__wine_spec_ne_modtab-.L__wine_spec_ne_header\n" );    /* ne_modtab */
    output( "\t.short .L__wine_spec_ne_imptab-.L__wine_spec_ne_header\n" );    /* ne_imptab */
    output( "\t.long 0\n" );                                   /* ne_nrestab */
    output( "\t.short 0\n" );                                  /* ne_cmovent */
    output( "\t.short 0\n" );                                  /* ne_align */
    output( "\t.short 0\n" );                                  /* ne_cres */
    output( "\t.byte 0x02\n" );                                /* ne_exetyp = NE_OSFLAGS_WINDOWS */
    output( "\t.byte 0x08\n" );                                /* ne_flagsothers = NE_AFLAGS_FASTLOAD */
    output( "\t.short 0\n" );                                  /* ne_pretthunks */
    output( "\t.short 0\n" );                                  /* ne_psegrefbytes */
    output( "\t.short 0\n" );                                  /* ne_swaparea */
    output( "\t.short 0\n" );                                  /* ne_expver */

    /* segment table */

    output( "\n.L__wine_spec_ne_segtab:\n" );

    /* code segment entry */

    output( "\t.short .L__wine_spec_code_segment-.L__wine_spec_dos_header\n" );         /* filepos */
    output( "\t.short .L__wine_spec_code_segment_end-.L__wine_spec_code_segment\n" );   /* size */
    output( "\t.short 0x2000\n" );                                                      /* flags = NE_SEGFLAGS_32BIT */
    output( "\t.short .L__wine_spec_code_segment_end-.L__wine_spec_code_segment\n" );   /* minsize */

    /* data segment entry */

    output( "\t.short .L__wine_spec_data_segment-.L__wine_spec_dos_header\n" );         /* filepos */
    output( "\t.short .L__wine_spec_data_segment_end-.L__wine_spec_data_segment\n" );   /* size */
    output( "\t.short 0x0001\n" );                                                      /* flags = NE_SEGFLAGS_DATA */
    output( "\t.short .L__wine_spec_data_segment_end-.L__wine_spec_data_segment\n" );   /* minsize */

    /* resource directory */

    output_res16_directory( spec );

    /* resident names table */

    output( "\n\t.align %d\n", get_alignment(2) );
    output( ".L__wine_spec_ne_restab:\n" );
    output_resident_name( spec->dll_name, 0 );
    for (i = 1; i <= spec->limit; i++)
    {
        ORDDEF *odp = spec->ordinals[i];
        if (!odp || !odp->name[0]) continue;
        if (odp->flags & FLAG_EXPORT32) continue;
        output_resident_name( odp->name, i );
    }
    output( "\t.byte 0\n" );

    /* imported names table */

    output( "\n\t.align %d\n", get_alignment(2) );
    output( ".L__wine_spec_ne_modtab:\n" );
    output( ".L__wine_spec_ne_imptab:\n" );
    output( "\t.byte 0,0\n" );

    /* entry table */

    output( "\n.L__wine_spec_ne_enttab:\n" );
    output_entry_table( spec );
    output( ".L__wine_spec_ne_enttab_end:\n" );

    /* code segment */

    output( "\n\t.align %d\n", get_alignment(2) );
    output( ".L__wine_spec_code_segment:\n" );

    for ( i = 0; i < nb_funcs; i++ )
    {
        unsigned int arg_types[2];
        int nop_words, pos, argsize = 0;

        if ( typelist[i]->type == TYPE_PASCAL )
            argsize = get_function_argsize( typelist[i] );

        /* build the arg types bit fields */
        arg_types[0] = arg_types[1] = 0;
        for (j = pos = 0; j < typelist[i]->u.func.nb_args && pos < 20; j++, pos++)
        {
            int type = 0;
            switch (typelist[i]->u.func.args[j])
            {
            case ARG_WORD:   type = ARG16_WORD; break;
            case ARG_SWORD:  type = ARG16_SWORD; break;
            case ARG_SEGPTR: type = ARG16_LONG; break;
            case ARG_SEGSTR: type = ARG16_SEGSTR; break;
            case ARG_LONG:   type = ARG16_LONG; break;
            case ARG_PTR:    type = ARG16_PTR; break;
            case ARG_STR:    type = ARG16_STR; break;
            case ARG_WSTR:   type = ARG16_PTR; break;
            case ARG_FLOAT:  type = ARG16_LONG; break;
            case ARG_INT128: type = ARG16_PTR; break;
            case ARG_INT64:
            case ARG_DOUBLE:
                type = ARG16_LONG;
                arg_types[pos / 10] |= type << (3 * (pos % 10));
                pos++;
                break;
            }
            if (pos < 20) arg_types[pos / 10] |= type << (3 * (pos % 10));
        }
        if (typelist[i]->type == TYPE_VARARGS && pos < 20)
            arg_types[pos / 10] |= ARG16_VARARG << (3 * (pos % 10));

        output( ".L__wine_spec_callfrom16_%s:\n", get_callfrom16_name(typelist[i]) );
        output( "\tpushl $.L__wine_spec_call16_%s\n", get_relay_name(typelist[i]) );
        output( "\tlcall $0,$0\n" );

        if (typelist[i]->flags & FLAG_REGISTER)
        {
            nop_words = 4;
        }
        else if (typelist[i]->flags & FLAG_RET16)
        {
            output( "\torw %%ax,%%ax\n" );
            output( "\tnop\n" );  /* so that the lretw is aligned */
            nop_words = 2;
        }
        else
        {
            output( "\tshld $16,%%eax,%%edx\n" );
            output( "\torl %%eax,%%eax\n" );
            nop_words = 1;
        }

        if (argsize)
        {
            output( "\tlretw $%u\n", argsize );
            nop_words--;
        }
        else output( "\tlretw\n" );

        if (nop_words) output( "\t%s\n", nop_sequence[nop_words-1] );

        /* the movl is here so that the code contains only valid instructions, */
        /* it's never actually executed, we only care about the arg_types[] values */
        output( "\t.short 0x86c7\n" );
        output( "\t.long 0x%08x,0x%08x\n", arg_types[0], arg_types[1] );
    }

    for (i = 0; i <= spec->limit; i++)
    {
        ORDDEF *odp = spec->ordinals[i];
        if (!odp || !is_function( odp )) continue;
        output( ".L__wine_%s_%u:\n", make_c_identifier(spec->dll_name), i );
        output( "\tpushw %%bp\n" );
        output( "\tpushl $%s\n",
                 asm_name_stdcall16( odp->type == TYPE_STUB ? get_stub_name( odp, spec ) : odp->link_name , odp));
        output( "\tcallw .L__wine_spec_callfrom16_%s\n", get_callfrom16_name( odp ) );
    }
    output( ".L__wine_spec_code_segment_end:\n" );

    /* data segment */

    output( "\n.L__wine_spec_data_segment:\n" );
    output( "\t.byte 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0\n" );  /* instance data */
    for (i = 0; i <= spec->limit; i++)
    {
        ORDDEF *odp = spec->ordinals[i];
        if (!odp || odp->type != TYPE_VARIABLE) continue;
        output( ".L__wine_%s_%u:\n", make_c_identifier(spec->dll_name), i );
        output( "\t.long " );
        for (j = 0; j < odp->u.var.n_values-1; j++)
            output( "0x%08x,", odp->u.var.values[j] );
        output( "0x%08x\n", odp->u.var.values[j] );
    }
    output( ".L__wine_spec_data_segment_end:\n" );

    /* resource data */

    if (spec->nb_resources)
    {
        output( "\n.L__wine_spec_resource_data:\n" );
        output_res16_data( spec );
    }

    output( "\t.byte 0\n" );  /* make sure the last symbol points to something */

    /* relay functions */

    nb_funcs = sort_func_list( typelist, nb_funcs, relay_type_compare );
    if (nb_funcs)
    {
        output( "\n/* relay functions */\n\n" );
        output( "\t.text\n" );
        for ( i = 0; i < nb_funcs; i++ ) output_call16_function( typelist[i] );
        output( "\t.data\n" );
        output( "wine_ldt_copy_ptr:\n" );
        output( "\t.long %s\n", asm_name("_imp__wine_ldt_copy") );
    }

    free( typelist );
}
gboolean
ifnet_init (gchar * config_file)
{
	GIOChannel *channel = NULL;
	gchar *line;

	/* Handle multiple lines with brackets */
	gboolean complete = TRUE;

	gboolean openrc_style = TRUE;

	/* line buffer */
	GString *buf;

	net_parser_data_changed = FALSE;

	conn_table = g_hash_table_new (g_str_hash, g_str_equal);
	global_settings_table = g_hash_table_new (g_str_hash, g_str_equal);
	functions_list = NULL;

	if (g_file_test (config_file, G_FILE_TEST_IS_REGULAR))
		channel = g_io_channel_new_file (config_file, "r", NULL);
	if (channel == NULL) {
		nm_log_warn (LOGD_SETTINGS, "Can't open %s", config_file);
		return FALSE;
	}

	buf = g_string_new (NULL);
	while (g_io_channel_read_line
	       (channel, &line, NULL, NULL, NULL) != G_IO_STATUS_EOF) {
		g_strstrip (line);
		/* convert multiple lines to a complete line and
		 * pass it to init_block_by_line() */
		if (is_function (line)) {
			strip_function (channel, line);
			continue;
		}

		// New openrc style, bash arrays are not allowed. We only care about '"'
		if (openrc_style && line[0] != '#' && line[0] != '\0'
				&& !strchr (line, '(') && !strchr (line, ')')) {
			gchar *tmp = line;

			while ((tmp = strchr (tmp, '"')) != NULL) {
				complete = !complete;
				++tmp;
			}

			append_line (buf, line);
			// Add "(separator) for routes. It will be easier for later parsing
			if (strstr (buf->str, "via"))
				g_string_append_printf (buf, "\"");

			if (!complete)
				continue;

			strip_string (buf->str, '"');

			init_block_by_line (buf->str);
			g_string_free (buf, TRUE);
			buf = g_string_new (NULL);
		}
		// Old bash arrays for baselayout-1, to be deleted
		else if (line[0] != '#' && line[0] != '\0') {
			if (!complete) {
				complete =
				    g_strrstr (line,
					       ")") == NULL ? FALSE : TRUE;

				append_line (buf, line);
				if (!complete) {
					openrc_style = FALSE;
					continue;
				}
				else {
					openrc_style = TRUE;
				}
			} else {
				complete =
				    (g_strrstr (line, "(") != NULL
				     && g_strrstr (line, ")") != NULL)
				    || g_strrstr (line, "(") == NULL;

				append_line (buf, line);
				if (!complete)
				{
					openrc_style = FALSE;
					continue;
				} else {
					openrc_style = TRUE;
				}
			}
			init_block_by_line (buf->str);
			g_string_free (buf, TRUE);
			buf = g_string_new (NULL);
		} else
			/* Blank line or comment line */
			g_free (line);
	}

	g_string_free (buf, TRUE);
	g_io_channel_shutdown (channel, FALSE, NULL);
	g_io_channel_unref (channel);
	return TRUE;
}
Exemplo n.º 11
0
Term ExpandTerm(Term t)
	{
	List il=0;
	Term res;
	/*puts("");
	WriteTerm(t);
	puts("\n");*/
	if(is_compound(t) && (CompoundName(t)==OPR_USCORE || CompoundName(t)==OPR_CARET))
		{
		t=SplitIndices(t,&il);
		if(t==0)
			longjmp(alg1_jmp_buf,1);
		}
	if(is_function(t,NULL))
		return ExpandTerm(CallFunction(t,il));
	if(is_float(t))
		{
		ErrorInfo(303);
		printf(" illegal use of floating point number %f.\n",FloatValue(t));
		FreeAtomic(t);
		longjmp(alg1_jmp_buf,1);
		}
	if(is_integer(t))
		{
		if(IntegerValue(t)==0)
			return 0;
		
		if(il)
			{
			ErrorInfo(304);
			puts("Integer can't have indices.\n");
			longjmp(alg1_jmp_buf,1);
			}
			
		res=MakeCompound(A_MTERM,4);
		SetCompoundArg(res,1,t);
		SetCompoundArg(res,2,NewInteger(1));
		return AppendFirst(0,res);
		}
		
	if(t==A_I)
		{
		res=MakeCompound(A_MTERM,4);
		SetCompoundArg(res,1,NewInteger(1));
		SetCompoundArg(res,2,NewInteger(-1));
		return AppendFirst(0,res);
		}
		
	if(is_atom(t) || (is_compound(t) && CompoundName(t)==A_FBRACET) ||
		(is_compound(t) && CompoundName(t)==A_ALG1 && CompoundArity(t)==2) ||
		(is_compound(t) && (CompoundName(t)==A_SIN || CompoundName(t)==A_COS)
		 	&& CompoundArity(t)<3 && is_integer(CompoundArg1(t))))
		 return AtomicTo1(t,il);
	
	if(!is_empty_list(il))
		{
		ErrorInfo(307);
		printf(" bad indices ");
		WriteTerm(il);
		printf(" in expression.\n");
		longjmp(alg1_jmp_buf,1);
		}


	if(opSetGpm && is_compound(t) && CompoundArity(t)==2 && CompoundArg1(t)==NewInteger(1)
			&& is_atom(CompoundArg2(t))
			&& (CompoundArg2(t)==A_GAMMA5 || GetAtomProperty(CompoundArg2(t),A_GAMMA5))
			&& (CompoundName(t)==OPR_PLUS || CompoundName(t)==OPR_MINUS))
	{
		Term ret,sp;
		ret=MakeCompound(A_MTERM,4);
		SetCompoundArg(ret,1,NewInteger(2));
		SetCompoundArg(ret,2,NewInteger(1));
		sp=MakeCompound(OPR_SPECIAL,2);
		if(CompoundName(t)==OPR_PLUS)
			SetCompoundArg(sp,2,A_GAMMAP);
		else
			SetCompoundArg(sp,2,A_GAMMAM);
		SetCompoundArg(sp,1,CopyTerm(GetAtomProperty(A_GAMMA5,PROP_INDEX)));
		SetCompoundArg(ret,3,AppendLast(NewList(),sp));
		return AppendLast(NewList(),ret);
	}
		

	
	
	if(is_compound(t) && CompoundName(t)==OPR_PLUS && CompoundArity(t)==2)
		{
		Term t1,t2;
		t1=ConsumeCompoundArg(t,1);
		t2=ConsumeCompoundArg(t,2);
		FreeAtomic(t);
		t1=ExpandTerm(t1);
		t2=ExpandTerm(t2);
		return ConcatList(t1,t2);
		}
		
	if(is_compound(t) && CompoundName(t)==OPR_MINUS && CompoundArity(t)==2)
		{
		Term t1,t2;
		t1=ConsumeCompoundArg(t,1);
		t2=ConsumeCompoundArg(t,2);
		FreeAtomic(t);
		t1=ExpandTerm(t1);
		t2=ExpandTerm(t2);
		mult_no(t2,-1);
		return ConcatList(t1,t2);
		}
		
	if(is_compound(t) && CompoundName(t)==OPR_MINUS && CompoundArity(t)==1)
		{
		Term t1;
		t1=ConsumeCompoundArg(t,1);
		FreeAtomic(t);
		t1=ExpandTerm(t1);
		mult_no(t1,-1);
		return t1;
		}
	
	if(is_compound(t) && CompoundName(t)==OPR_MLT && CompoundArity(t)==2)
		{
		Term t1,t2;
		t1=ConsumeCompoundArg(t,1);
		t2=ConsumeCompoundArg(t,2);
		FreeAtomic(t);
		t1=ExpandTerm(t1);
		t2=ExpandTerm(t2);
		return multiply_l(t1,t2);
		}
		
	if(is_compound(t) && CompoundName(t)==OPR_DIV && CompoundArity(t)==2)
		{
		Term t1,t2,t2s;
		t1=ConsumeCompoundArg(t,1);
		t2=ConsumeCompoundArg(t,2);
		FreeAtomic(t);
		t1=ExpandTerm(t1);
		t2s=CopyTerm(t2);
		t2=ExpandTerm(t2);
		if(ListLength(t2)!=1)
			{
			ErrorInfo(306);
			printf(" cannot divide by \'");
			WriteTerm(t2s); printf("\'.\n");
			FreeAtomic(t1); FreeAtomic(t2); FreeAtomic(t2s);
			longjmp(alg1_jmp_buf,1);
			}
		FreeAtomic(t2s);
		invert_term(ListFirst(t2));
		return multiply_l(t1,t2);
		}
		
	if(is_compound(t) && CompoundName(t)==OPR_POW && CompoundArity(t)==2)
		{
		Term t1,t2,ret;
		int i,pp;
		t1=ConsumeCompoundArg(t,1);
		t2=ConsumeCompoundArg(t,2);
		FreeAtomic(t);
		if(!is_integer(t2) || IntegerValue(t2)<1)
			{
			ErrorInfo(307);
			printf(" illegal power \'");
			WriteTerm(t2); printf("\'.\n");
			FreeAtomic(t1); FreeAtomic(t2);
			longjmp(alg1_jmp_buf,1);
			}
		pp=IntegerValue(t2);
		t1=ExpandTerm(t1);
		ret=CopyTerm(t1);
		for(i=2;i<=pp;i++)
			{
			Term tmp;
			tmp=CopyTerm(t1);
			ret=multiply_l(ret,tmp);
			}
		FreeAtomic(t1);
		return ret;
		}
	
	ErrorInfo(309);
	printf("bad expression ");
	WriteTerm(t);
	puts("");
	longjmp(alg1_jmp_buf,1);	
	
	}
Exemplo n.º 12
0
Value*
mouse_track_cf(Value** arg_list, int count)
{
	// mouseTrack [on:node|#any] [prompt:"msg"] [snap:#2D|#3D] [trackCallback:fn|#(fn,arg)]

	// set up value local array to hold mouse tracker command mode Value*'s
	Value** vavl;
	value_local_array(vavl, sizeof(tmvl) / sizeof(Value*));
	tmvl* vl = (tmvl*)vavl;
	// show any prompt
	Value*	pv = key_arg(prompt);
	const TCHAR*	prompt = NULL;
	if  (pv != &unsupplied)
	{
		prompt = pv->to_string();
		mprintf(_T("%s "), prompt);
		mflush();
	}
	// setup snap
	Value* sv = key_arg_or_default(snap, n_2D);
	if (sv != n_2D && sv != n_3D)
		throw RuntimeError (MaxSDK::GetResourceStringAsMSTR(IDS_BAD_SNAP_MODE), sv);
	// setup track callback fn
	Value* tcb = NULL;
	Value* tcbarg = NULL;
	Value *tcbv = key_arg(trackCallback);
	if (tcbv != &unsupplied)
	{
		if (is_array(tcbv))  // an array,  #(fn, arg), dig out fn & arg
		{
			Array* tcba = (Array*)tcbv;
			if (tcba->size != 2)
				throw RuntimeError (MaxSDK::GetResourceStringAsMSTR(IDS_BAD_MOVE_CALLBACK_ARGS), tcbv);
			tcb = tcba->data[0];
			if (!is_function(tcb))
				throw RuntimeError (MaxSDK::GetResourceStringAsMSTR(IDS_BAD_MOVE_CALLBACK_ARGS), tcb);
			tcbarg = tcba->data[1];
		}
		else  // just the fn
		{
			tcb = tcbv;
			if (!is_function(tcb))
				throw RuntimeError (MaxSDK::GetResourceStringAsMSTR(IDS_BAD_MOVE_CALLBACK_ARGS), tcbv);
		}
	}

	// pickup any node to track on
	vl->node_val = key_arg(on);

	NodeTab& nodeTab = theTrackMouseCommandMode.proc.nodeTab;
	nodeTab.SetCount(0);
	if( vl->node_val->_is_collection() ) { //Multiple nodes specified
		Value* args[2] = { NULL, (Value*)&nodeTab };
		node_map m = { NULL, collect_nodes, args, 2 };
		vl->node_val->map(m);
	}
	else if( vl->node_val != &unsupplied ) { //Single node specified
		INode* node = vl->node_val->to_node();
		nodeTab.Append( 1, &node );
	}
	for( int i=(nodeTab.Count()-1); i>=0; i--)
		if( nodeTab[i]==NULL ) nodeTab.Delete(i,1); //Delete null nodes

	// set up pickpoint options, enter trackmouse command mode & wait for it to signal completion
	end_track_mouse = FALSE;
	theTrackMouseCommandMode.proc.vl = vl;
	theTrackMouseCommandMode.proc.snap_mode = sv;
	theTrackMouseCommandMode.proc.track_callback = tcb;
	theTrackMouseCommandMode.proc.track_callback_arg = tcbarg;
	theTrackMouseCommandMode.proc.start_track();
	//Changed from Set to Push to prevent an exception when the maxscript code changes the command mode
	//Similar to fix done to MouseTool.cpp - line 661
	MAXScript_interface->PushCommandMode(&theTrackMouseCommandMode);

	// process windows messages until point picked or canceled or keyboard message
    MSG wmsg;
    while (GetMessage(&wmsg, NULL, 0,0))
	{		
		if (wmsg.message == WM_KEYUP && (TCHAR)wmsg.wParam == VK_ESCAPE)
			end_track_mouse = TRUE;
		else if (wmsg.message == WM_KEYUP || wmsg.message == WM_KEYDOWN)
			continue;
		else if (wmsg.message != WM_RBUTTONUP)  // ignore rmousebuttonup's - they mess focus
			MAXScript_interface->TranslateAndDispatchMAXMessage(wmsg);

		if (end_track_mouse)
			break;
	}
	if (!end_track_mouse)
	{
		// we came out of message loop because of a quit, repost the quit and throw a SignalException
		theTrackMouseCommandMode.proc.end_track();
		MAXScript_interface->DeleteMode(&theTrackMouseCommandMode);
		throw SignalException();
	}

	// pickup result value & dismiss input modes
	theTrackMouseCommandMode.proc.end_track();
	MAXScript_interface->DeleteMode(&theTrackMouseCommandMode);
	Value* result = vl->result;
	pop_value_local_array(vavl);
	return_protected(result);
}
Exemplo n.º 13
0
static void
fetch_symtab(Elf *elf, char *filename, mod_info_t *module)
{
	Elf_Scn		*scn = NULL, *sym = NULL;
	GElf_Word	strndx = 0;
	size_t		i, nsyms, nfuncs;
	Elf_Data	*symdata;
	nltype		*nl, *npe;

	while ((scn = elf_nextscn(elf, scn)) != NULL) {

		GElf_Shdr shdr;

		if (gelf_getshdr(scn, &shdr) == NULL)
			continue;

		if (shdr.sh_type == SHT_SYMTAB ||
					shdr.sh_type == SHT_DYNSYM) {
			GElf_Xword chk = shdr.sh_size / shdr.sh_entsize;

			nsyms = (size_t)(shdr.sh_size / shdr.sh_entsize);

			if (chk != (GElf_Xword) nsyms) {
				(void) fprintf(stderr, "%s: can't handle"
					"more than 2^32 symbols", cmdname);
				exit(ERR_INPUT);
			}

			strndx = shdr.sh_link;
			sym = scn;
		}

		/*
		 * If we've found a real symbol table, we're done.
		 */
		if (shdr.sh_type == SHT_SYMTAB)
			break;
	}

	if (sym == NULL || strndx == 0) {
		(void) fprintf(stderr, "%s: missing symbol table in %s\n",
						    cmdname, filename);
		exit(ERR_ELF);
	}

	if ((symdata = elf_getdata(scn, NULL)) == NULL) {
		(void) fprintf(stderr, "%s: can't read symbol data from %s\n",
						    cmdname, filename);
		exit(ERR_ELF);
	}

	if ((npe = nl = (nltype *) calloc(nsyms, sizeof (nltype))) == NULL) {
		(void) fprintf(stderr, "%s: can't alloc %x bytes for symbols\n",
					cmdname, nsyms * sizeof (nltype));
		exit(ERR_ELF);
	}

	/*
	 * Now we need to cruise through the symbol table eliminating
	 * all non-functions from consideration, and making strings
	 * real.
	 */
	nfuncs = 0;

	for (i = 1; i < nsyms; i++) {
		GElf_Sym	gsym;
		char		*name;

		(void) gelf_getsym(symdata, i, &gsym);

		name = elf_strptr(elf, strndx, gsym.st_name);

		/*
		 * We're interested in this symbol if it's a function
		 */
		if (is_function(elf, &gsym)) {

			npe->name = name;
			npe->value = gsym.st_value;
			npe->size = gsym.st_size;
			npe->info = gsym.st_info;

			npe++;
			nfuncs++;
		}

		if (strcmp(name, PRF_END) == 0)
			module->data_end = gsym.st_value;
	}

	if (npe == nl) {
		(void) fprintf(stderr, "%s: no valid functions in %s\n",
						    cmdname, filename);
		exit(ERR_INPUT);
	}

	/*
	 * And finally, sort the symbols by increasing address
	 * and remove the duplicates.
	 */
	qsort(nl, nfuncs, sizeof (nltype), cmp_by_address);
	rm_dups(nl, &nfuncs);

	module->nl = nl;
	module->nfuncs = nfuncs;
}
Exemplo n.º 14
0
Term ProcChVertex(Term t, List ind)
{
	List l, pl, ml;
	Term rpl;
	Atom a1, a2;
	int pli;
	int ii;
	
	if(lagr_hash==NULL)
	{
		ErrorInfo(107);
		puts("ChVertex: no vertices");
		return 0;
	}
	
	
	if(!is_compound(t)||CompoundArity(t)!=2)
	{
		ErrorInfo(107);
		puts("wrong call to ChVertex");
		return 0;
	}
	
	pl=CompoundArg1(t);
	for(l=pl;l;l=ListTail(l))
		if(is_function(ListFirst(l),0))
			ChangeList(l,CallFunction(ListFirst(l),0));
	
	rpl=CompoundArg2(t);
	if(!is_list(pl)|| !is_compound(rpl) || CompoundArity(rpl)!=2)
	{
		ErrorInfo(107);
		puts("wrong call to ChVertex");
		return 0;
	}
	a1=CompoundArg1(rpl);a2=CompoundArg2(rpl);
	if(!is_parameter(a1)||!is_parameter(a2))
	{
		ErrorInfo(107);
		puts("wrong call to ChVertex");
		return 0;
	}

	pl=SortedList(pl,acmp);
	
	l=finda2(pl,0);
	
	if(is_empty_list(l))
	{
	WarningInfo(108);printf("ChVertex: vertex ");
	WriteTerm(pl); puts(" not found");
	return 0;
	}
	
	ml=CompoundArgN(ListFirst(l),5);
	ii=0;
		
	for(l=ml;l;l=ListTail(l))
	{
		List l1;
		for(l1=CompoundArg2(ListFirst(l));l1;l1=ListTail(l1))
			if(CompoundArg1(ListFirst(l1))==a1)
			{
				SetCompoundArg(ListFirst(l1),1,a2);ii++;
			}
	}
	
	
	if(ii==0)
	{
	WarningInfo(107);printf("ChVertex: vertex ");WriteTerm(pl);
			printf("has no '%s' within.\n",AtomValue(a1));
	}	
	
	return 0;
}
Exemplo n.º 15
0
bool is_function(Term* term)
{
    if (term == NULL)
        return false;
    return is_value(term) && is_function(&term->value);
}
Exemplo n.º 16
0
static const char *
process_scope(PyObject *out, const char *start, const char *buff,
			  const char *end,
			  PyObject *var_matcher, PyObject *func_matcher,
			  const char endchar, PyObject *envvar_callback)
{
	const char *p = NULL;
	const char *window_start = NULL, *window_end = NULL;
	const char *new_p = NULL;
	const char *com_start = NULL;
	char *s = NULL;
	char *e = NULL;
	char *temp_string = NULL;

	regmatch_t matches[3];
	p = buff;
	matches[0].rm_so = matches[1].rm_so = matches[2].rm_so = -1;

	window_start = buff;
	window_end = NULL;
	while (p < end && *p != endchar) {

		/* wander forward to the next non space */
		if (window_end != NULL) {
			if (out) {
				PyObject *string = PyString_FromStringAndSize(
					window_start, window_end - window_start);
				if (!string)
					return NULL;
				PyObject *result = PyObject_CallMethodObjArgs(
					out, write_str, string, NULL);
				Py_DECREF(string);
				if (!result)
					return NULL;
				Py_DECREF(result);
			}
			window_start = p;
			window_end = NULL;
		}
		com_start = p;
		if (isspace(*p)) {
			++p;
			continue;
		}

		/* ignore comments */
		if (*p == '#') {
			p = walk_statement_pound(start, p, endchar);
			continue;
		}

		if(NULL != (new_p = is_function(p, &s, &e))) {
			if(-1 == asprintf(&temp_string, "%.*s", (int)(e - s), s))
				return NULL;
			INFO("matched func name '%s'", temp_string);
			/* output it if it doesn't match */

			new_p = process_scope(
				NULL, start, new_p, end, NULL, NULL, '}', NULL);
			INFO("ended processing  '%s'", temp_string);
			if (func_matcher) {
				int regex_result = regex_matches(func_matcher, temp_string);
				if (-1 == regex_result) {
					free(temp_string);
					return NULL;
				}
				if (regex_result) {
					/* well, it matched.  so it gets skipped. */
					INFO("filtering func '%s'", temp_string);
					window_end = com_start;
				}
			}

			free(temp_string);
			if(!new_p)
				return NULL;
			p = new_p;
			++p;
			continue;
		}
		// check for env assignment
		if (NULL == (new_p = is_envvar(p, &s, &e))) {
			//exactly as it sounds, non env assignment.
			p = walk_command_complex(start, p, end,
				endchar, COMMAND_PARSING);
			if (!p)
				return NULL;
			// icky icky icky icky
			if (p < end && *p != endchar)
				++p;
		} else {
			//env assignment
			if(-1 == asprintf(&temp_string, "%.*s", (int)(e - s), s))
				return NULL;
			INFO("matched env assign '%s'", temp_string);

			do_envvar_callback(envvar_callback, temp_string);

			if (var_matcher) {
				int regex_result = regex_matches(var_matcher, temp_string);
				if (-1 == regex_result) {
					free(temp_string);
					return NULL;
				}
				if (regex_result) {
					//this would be filtered.
					INFO("filtering var '%s'", temp_string);
					window_end = com_start;
				}
			}

			free(temp_string);

			p = new_p;
			if (p >= end) {
				return p;
			}

			while(p < end && !isspace(*p) && ';' != *p) {
				if ('\'' == *p)
					p = walk_statement_no_parsing(p + 1, end, '\'') + 1;
				else if ('"' == *p || '`' == *p)
					p = walk_command_escaped_parsing(start, p + 1, end,
						*p) + 1;
				else if ('(' == *p) {
					p = walk_command_escaped_parsing(start, p + 1, end,
						')') + 1;
				} else if ('$' == *p) {
					++p;
					if (p >= end) {
						continue;
					}
					p = walk_dollar_expansion(start, p, end, endchar,
						endchar);
					continue;
				} else {
					// blah=cah ; single word.
					p = walk_command_complex(start, p, end, ' ',
						SPACE_PARSING);
					if (!p) {
						return NULL;
					}
				}
			}
		}
	}

	if (out) {
		if (window_end == NULL)
			window_end = p;
		if (window_end > end)
			window_end = end;
		PyObject *string = PyString_FromStringAndSize(
			window_start, window_end - window_start);
		if (!string)
			return NULL;
		PyObject *result = PyObject_CallMethodObjArgs(
			out, write_str, string, NULL);
		Py_DECREF(string);
		if (!result)
			return NULL;
		Py_DECREF(result);
	}

	return p;
}
Exemplo n.º 17
0
void ProcessTerm(Term t)
	{
	Term res;
	Atom procc=0;
	char regbuf[80];

	if(is_compound(t)&&CompoundName(t)==OPR_LOCAL)
			{
			List l1,la=ConsumeCompoundArg(t,1);
			if(l_pro==0)
				{
				ErrorInfo(0);
				puts("local: must be within template.");
				return;
				}
			la=CommaToList(la);
			for(l1=la;l1;l1=ListTail(l1))
				l_ali=AppendLast(l_ali,
					InterfSetAlias(MakeCompound1(OPR_ALIAS,ListFirst(l1)),0));
			RemoveList(la);
			return;
			}

/*	if(is_compound(t) && GetAtomProperty(CompoundName(t),OPR_ALIAS))
	{*/
	
	if(!is_compound(t) || (CompoundName(t)!=OPR_ALIAS && 
			CompoundName(t)!=OPR_IN && CompoundName(t)!=OPR_WHERE) )
	{
		t=ProcessAlias(t);
		proc_hash(t);
	}
		/*WriteTerm(t);puts("");*/
	/*}*/
	
	if(is_list(t))
	{
		List l, alisav;
		l_pro++;
		alisav=l_ali;
		l_ali=0;		
		for(l=t;l;l=ListTail(l))
			ProcessTerm(ListFirst(l));
		if(l_ali)
			RemoveAlias(l_ali);
		RemoveList(t);
		l_pro--;
		l_ali=alisav;
		return;
	}


    if(is_atom(t))
		procc=t;
	if(is_compound(t))
		{
		procc=CompoundName(t);
		}
    if(procc==0)
		{
        if(!IsTermInput())
			printf("File \"%s\", line %d: ",CurrentInputFile(),
				CurrentInputLine());
		printf("Not a valid operator \'");
		WriteTerm(t);
		printf("\'.\n");
		FreeAtomic(t);
		return;
		}

	if(!IsTermInput())
		sprintf(regbuf, "ProcTerm: File %s, line %d: %s statement.",
			CurrentInputFile(), CurrentInputLine(), AtomValue(procc));
	else
		sprintf(regbuf, "(tty): %s statement.",AtomValue(procc));

	RegisterLine(regbuf);

	if(!is_function(t,NULL))
		{
        if(!IsTermInput())
			printf("File \"%s\", line %d: ",CurrentInputFile(),
				CurrentInputLine());
		printf("Unknown operator \'%s\' in expression\n\t",AtomValue(procc));
		WriteTerm(t);
		puts("");
		FreeAtomic(t);
		UnregisterLine();
		return;
		}

    if(is_compound(t) && ((VerbMode && CompoundName(t)==OPR_LTERM) ||
			VerbMode==3))
    	{
    	char sment[1024];
    	sWriteTerm(sment,t);
    	sment[55]='.';
    	sment[56]='.';
    	sment[57]='.';
    	sment[58]=0;
    	printf("%s:%3d: %s\n",CurrentInputFile(),CurrentInputLine(),sment);
    	}
    	
	res=CallFunction(t,0);
	if(res!=0 && (IsTermInput()))
		{
		if(is_compound(res) && CompoundArity(t)==2 && 
				CompoundName(res)==A_ALG1)
			res=Alg1ToExpr(res);
		if(is_list(res))
			DumpList(res);
		else
			{
			WriteTerm(res);
			puts("");
			}
		FreeAtomic(res);
		}
	UnregisterLine();
	}
Exemplo n.º 18
0
/* Cover both external declarations, functions, and local declarations (with
 * optional initialization code) inside functions.
 */
struct block *declaration(struct block *parent)
{
    struct typetree *base;
    enum symtype symtype;
    enum linkage linkage;
    int stc = '$';

    base = declaration_specifiers(&stc);
    switch (stc) {
    case EXTERN:
        symtype = SYM_DECLARATION;
        linkage = LINK_EXTERN;
        break;
    case STATIC:
        symtype = SYM_TENTATIVE;
        linkage = LINK_INTERN;
        break;
    case TYPEDEF:
        symtype = SYM_TYPEDEF;
        linkage = LINK_NONE;
        break;
    default:
        if (!ns_ident.current_depth) {
            symtype = SYM_TENTATIVE;
            linkage = LINK_EXTERN;
        } else {
            symtype = SYM_DEFINITION;
            linkage = LINK_NONE;
        }
        break;
    }

    while (1) {
        struct definition *def;
        const char *name = NULL;
        const struct typetree *type;
        struct symbol *sym;

        type = declarator(base, &name);
        if (!name) {
            consume(';');
            return parent;
        }

        sym = sym_add(&ns_ident, name, type, symtype, linkage);
        if (ns_ident.current_depth) {
            assert(ns_ident.current_depth > 1);
            def = current_func();
            def->locals = sym_list_add(def->locals, sym);
        }

        switch (peek().token) {
        case ';':
            consume(';');
            return parent;
        case '=':
            if (sym->symtype == SYM_DECLARATION) {
                error("Extern symbol '%s' cannot be initialized.", sym->name);
                exit(1);
            }
            if (!sym->depth && sym->symtype == SYM_DEFINITION) {
                error("Symbol '%s' was already defined.", sym->name);
                exit(1);
            }
            consume('=');
            sym->symtype = SYM_DEFINITION;
            if (sym->linkage == LINK_NONE) {
                assert(parent);
                parent = initializer(parent, var_direct(sym));
            } else {
                assert(sym->depth || !parent);
                def = push_back_definition(sym);
                initializer(def->body, var_direct(sym));
            }
            assert(size_of(&sym->type) > 0);
            if (peek().token != ',') {
                consume(';');
                return parent;
            }
            break;
        case '{': {
            int i;
            if (!is_function(&sym->type) || sym->depth) {
                error("Invalid function definition.");
                exit(1);
            }
            assert(!parent);
            assert(sym->linkage != LINK_NONE);
            sym->symtype = SYM_DEFINITION;
            def = push_back_definition(sym);
            push_scope(&ns_ident);
            define_builtin__func__(sym->name);
            for (i = 0; i < nmembers(&sym->type); ++i) {
                name = get_member(&sym->type, i)->name;
                type = get_member(&sym->type, i)->type;
                symtype = SYM_DEFINITION;
                linkage = LINK_NONE;
                if (!name) {
                    error("Missing parameter name at position %d.", i + 1);
                    exit(1);
                }
                def->params = sym_list_add(def->params,
                    sym_add(&ns_ident, name, type, symtype, linkage));
            }
            parent = block(def->body);
            pop_scope(&ns_ident);
            return parent;
        }
        default:
            break;
        }
        consume(',');
    }
}
Exemplo n.º 19
0
static bool shunting_yard(const TCHAR *input, TCHAR *output)
{
    const TCHAR *strpos = input, *strend = input + _tcslen(input);
    TCHAR c, *outpos = output;
 
    TCHAR stack[STACK_SIZE];       // operator stack
    unsigned int sl = 0;  // stack length
    TCHAR    sc;          // used for record stack element
 
    while(strpos < strend)   {
		if (sl >= STACK_SIZE)
			return false;

		// read one token from the input stream
        c = *strpos;
        if(c != ' ')    {
            // If the token is a number (identifier), then add it to the output queue.
            if(is_ident(c))  {
                *outpos = c; ++outpos;
            }
            // If the token is a function token, then push it onto the stack.
            else if(is_function(c))   {
                stack[sl] = c;
                ++sl;
            }
            // If the token is a function argument separator (e.g., a comma):
            else if(c == ',')   {
                bool pe = false;
                while(sl > 0)   {
                    sc = stack[sl - 1];
                    if(sc == '(')  {
                        pe = true;
                        break;
                    }
                    else  {
                        // Until the token at the top of the stack is a left parenthesis,
                        // pop operators off the stack onto the output queue.
                        *outpos = sc; 
                        ++outpos;
                        sl--;
                    }
                }
                // If no left parentheses are encountered, either the separator was misplaced
                // or parentheses were mismatched.
                if(!pe)   {
                    calc_log ((_T("Error: separator or parentheses mismatched\n")));
                    return false;
                }
            }
            // If the token is an operator, op1, then:
            else if(is_operator(c))  {
                while(sl > 0)    {
                    sc = stack[sl - 1];
                    // While there is an operator token, o2, at the top of the stack
                    // op1 is left-associative and its precedence is less than or equal to that of op2,
                    // or op1 is right-associative and its precedence is less than that of op2,
                    if(is_operator(sc) &&
                        ((op_left_assoc(c) && (op_preced(c) <= op_preced(sc))) ||
                           (!op_left_assoc(c) && (op_preced(c) < op_preced(sc)))))   {
                        // Pop o2 off the stack, onto the output queue;
                        *outpos = sc; 
                        ++outpos;
                        sl--;
                    }
                    else   {
                        break;
                    }
                }
                // push op1 onto the stack.
                stack[sl] = c;
                ++sl;
            }
            // If the token is a left parenthesis, then push it onto the stack.
            else if(c == '(')   {
                stack[sl] = c;
                ++sl;
            }
            // If the token is a right parenthesis:
            else if(c == ')')    {
                bool pe = false;
                // Until the token at the top of the stack is a left parenthesis,
                // pop operators off the stack onto the output queue
                while(sl > 0)     {
                    sc = stack[sl - 1];
                    if(sc == '(')    {
                        pe = true;
                        break;
                    }
                    else  {
                        *outpos = sc; 
                        ++outpos;
                        sl--;
                    }
                }
                // If the stack runs out without finding a left parenthesis, then there are mismatched parentheses.
                if(!pe)  {
                    calc_log ((_T("Error: parentheses mismatched\n")));
                    return false;
                }
                // Pop the left parenthesis from the stack, but not onto the output queue.
                sl--;
                // If the token at the top of the stack is a function token, pop it onto the output queue.
                if(sl > 0)   {
                    sc = stack[sl - 1];
                    if(is_function(sc))   {
                        *outpos = sc; 
                        ++outpos;
                        sl--;
                    }
                }
            }
            else  {
                calc_log ((_T("Unknown token %c\n"), c));
                return false; // Unknown token
            }
        }
        ++strpos;
    }
    // When there are no more tokens to read:
    // While there are still operator tokens in the stack:
    while(sl > 0)  {
        sc = stack[sl - 1];
        if(sc == '(' || sc == ')')   {
            printf("Error: parentheses mismatched\n");
            return false;
        }
        *outpos = sc; 
        ++outpos;
        --sl;
    }
    *outpos = 0; // Null terminator
    return true;
}
Exemplo n.º 20
0
static bool execution_order(const TCHAR *input, double *outval)
{
    const TCHAR *strpos = input, *strend = input + _tcslen(input);
    TCHAR c, res[4];
    unsigned int sl = 0, rn = 0;
	struct calcstack stack[STACK_SIZE] = { {0, .0} }, *sc, *sc2;
	double val = 0;
	int i;
	bool ok = false;

	// While there are input tokens left
    while(strpos < strend)  {

		if (sl >= STACK_SIZE)
			return false;

               // Read the next token from input.
		c = *strpos;
                // If the token is a value or identifier
        if(is_ident(c))    {
                        // Push it onto the stack.
			stack[sl].s = chartostack (c);
            ++sl;
        }
                // Otherwise, the token is an operator  (operator here includes both operators, and functions).
        else if(is_operator(c) || is_function(c))    {
                        _stprintf(res, _T("_%02d"), rn);
                        calc_log ((_T("%s = "), res));
                        ++rn;
                        // It is known a priori that the operator takes n arguments.
                        unsigned int nargs = op_arg_count(c);
                        // If there are fewer than n values on the stack
                        if(sl < nargs) {
                                // (Error) The user has not input sufficient values in the expression.
                                return false;
                        }
                        // Else, Pop the top n values from the stack.
                        // Evaluate the operator, with the values as arguments.
                        if(is_function(c)) {
                                calc_log ((_T("%c("), c));
                                while(nargs > 0){
                                        sc = &stack[sl - nargs]; // to remove reverse order of arguments
                                        if(nargs > 1)   {
                                                calc_log ((_T("%s, "), sc));
                                        }
                                        else {
                                                calc_log ((_T("%s)\n"), sc));
                                        }
                                        --nargs;
                                }
                                sl-=op_arg_count(c);
                        }
                        else   {
                                if(nargs == 1) {
                                        sc = &stack[sl - 1];
                                        sl--;
										val = docalc1 (c, sc, val);
										calc_log ((_T("%c %s = %f;\n"), c, stacktostr(sc), val));
                               }
                                else   {
                                        sc = &stack[sl - 2];
                                        calc_log ((_T("%s %c "), stacktostr(sc), c));
                                        sc2 = &stack[sl - 1];
										val = docalc2 (c, sc, sc2);
                                         sl--;sl--;
                                        calc_log ((_T("%s = %f;\n"), stacktostr(sc2), val));
                               }
                        }
                        // Push the returned results, if any, back onto the stack.
						stack[sl].val = val;
						stack[sl].s = NULL;
            ++sl;
        }
        ++strpos;
    }
        // If there is only one value in the stack
        // That value is the result of the calculation.
        if(sl == 1) {
                sc = &stack[sl - 1];
                sl--;
				calc_log ((_T("result = %f\n"), val));
				if (outval)
					*outval = val;
				ok = true;
		}
		for (i = 0; i < STACK_SIZE; i++)
			xfree (stack[i].s);
 
		// If there are more values in the stack
        // (Error) The user input has too many values.

		return ok;
}
Exemplo n.º 21
0
bool execution_order(const char *input) {
    printf("order: (arguments in reverse order)\n");
    const char *strpos = input, *strend = input + strlen(input);
    char c, res[4];
    unsigned int sl = 0, sc, stack[32], rn = 0;
        // While there are input tokens left
    while(strpos < strend)  {
                // Read the next token from input.
        c = *strpos;
                // If the token is a value or identifier
        if(is_ident(c))    {
                        // Push it onto the stack.
            stack[sl] = c;
            ++sl;
        }
                // Otherwise, the token is an operator  (operator here includes both operators, and functions).
        else if(is_operator(c) || is_function(c))    {
                        sprintf(res, "_%02d", rn);
                        printf("%s = ", res);
                        ++rn;
                        // It is known a priori that the operator takes n arguments.
                        unsigned int nargs = op_arg_count(c);
                        // If there are fewer than n values on the stack
                        if(sl < nargs) {
                                // (Error) The user has not input sufficient values in the expression.
                                return false;
                        }
                        // Else, Pop the top n values from the stack.
                        // Evaluate the operator, with the values as arguments.
                        if(is_function(c)) {
                                printf("%c(", c);
                                while(nargs > 0)        {
                                        sc = stack[sl - 1];
                                        sl--;
                                        if(nargs > 1)   {
                                                printf("%s, ", &sc);
                                        }
                                        else {
                                                printf("%s)\n", &sc);
                                        }
                                        --nargs;
                                }
                        }
                        else   {
                                if(nargs == 1) {
                                        sc = stack[sl - 1];
                                        sl--;
                                        printf("%c %s;\n", c, &sc);
                                }
                                else   {
                                        sc = stack[sl - 1];
                                        sl--;
                                        printf("%s %c ", &sc, c);
                                        sc = stack[sl - 1];
                                        sl--;
                                        printf("%s;\n",&sc);
                                }
                        }
                        // Push the returned results, if any, back onto the stack.
            stack[sl] = *(unsigned int*)res;
            ++sl;
        }
        ++strpos;
    }
        // If there is only one value in the stack
        // That value is the result of the calculation.
        if(sl == 1) {
                sc = stack[sl - 1];
                sl--;
                printf("%s is a result\n", &sc);
                return true;
        }
        // If there are more values in the stack
        // (Error) The user input has too many values.
        return false;
}
Exemplo n.º 22
0
spFile* CJSourceParser::Parse( char* start, char* end )
{
    // set up state variables
    mCurVis       = SP_VIS_PRIVATE;

    spFile* pTopCtx = new spFile();
    mpCurCtx        = pTopCtx;

    mIsVirtual    = 0;
    mIsTemplate   = 0;
    mNestingLevel = 0;

    m_cur = start;

    mpStart = start;
    mpEnd   = end;

    _gSrcEnd   = mpEnd; // let all the C-functions "smell" the end of file
    _gSrcStart = start;

    _gLineNo   = 0;

    clear_commets_queue();

    // main parsing loop

    do
    {
        if ( !get_next_token( m_cur ) )
            // end of source reached
            return pTopCtx;

        if ( memcmp( m_cur, "ScriptSection( const string&",
                     strlen( "ScriptSection( const string&" )
                   ) == 0
            )
        {
            // int o = 0;
            // ++o;
        }

        switch (*m_cur)
        {
            case '#' :
                {
                    AddMacroNode( m_cur );
                    continue;
                }

            case ':' :
                {
                    skip_token( m_cur );
                    continue;
                }

            case ';' :
                {
                    skip_token( m_cur );
                    continue;
                }

            case ')' :
                {
                    skip_token( m_cur );
                    continue;
                }

            case '=' :
                {
                    skip_token( m_cur );
                    continue;
                }

            default: break;
        }

        // 'const' is a part of the return type, not a keyword here
        if ( strncmp(m_cur, "const", 5) != 0 && is_keyword( m_cur ) )
        {
            // parses, token, if token identifies
            // the container context (e.g. class/namespace)
            // the corresponding context object is created
            // and set as current context

            ParseKeyword( m_cur );
            continue;
        }

        if ( *m_cur >= _T('0') && *m_cur <= _T('9') )
        {
            skip_token( m_cur );
            continue;
        }

        if ( *m_cur == _T('}') )
        {
            if ( mCurCtxType != SP_CTX_CLASS )
            {
                // FOR NOW:: disable the below assertion

                // DBG:: unexpected closing-bracket found
                //ASSERT(0);

                skip_token( m_cur ); // just skip it
                continue;
            }

            if ( mpCurCtx->GetType() == SP_CTX_CLASS )
            {
                int curOfs = ( (m_cur+1) - _gSrcStart );

                mpCurCtx->mContextLength = ( curOfs - mpCurCtx->mSrcOffset );
            }

            --mNestingLevel;

            // terminate operation/class/namespace context
            // TBD:: check if it's really this type of context

            wxASSERT( mpCurCtx );
            mpCurCtx = mpCurCtx->GetOutterContext();
            wxASSERT( mpCurCtx );

            if ( mNestingLevel == 0 )
            {

                mCurCtxType = SP_CTX_FILE;

                // not-nested class delclaration finished,
                // rest template flag in any case
                mIsTemplate = 0;
            }

            skip_token( m_cur );
            continue;
        }

        bool isAMacro = false;

        if ( is_function( m_cur, isAMacro ) )
        {
            if ( isAMacro )
            {
                skip_token( m_cur );
                continue;
            }

            char* savedPos = m_cur;

            int tmpLnNo;
            store_line_no( tmpLnNo );
            wxUnusedVar( tmpLnNo );

            isAMacro = false;

            if ( !ParseNameAndRetVal( m_cur, isAMacro ) )
            {
                if ( !isAMacro )
                {
                    m_cur = savedPos;
                    SkipFunction( m_cur );
                }
                continue;
            }

            if ( !ParseArguments( m_cur ) )
            {
                // failure while parsing arguments,
                // remove enclosing operation context

                spContext* pFailed = mpCurCtx;
                mpCurCtx = mpCurCtx->GetOutterContext();
                mpCurCtx->RemoveChild( pFailed );

                skip_to_eol( m_cur );
                //m_cur = savedPos;
            }
            else
            {
                // otherwise, successfully close operation context:

                clear_commets_queue();

                SkipFunctionBody( m_cur );

                mpCurCtx = mpCurCtx->GetOutterContext();

                // DBG::
                wxASSERT( mpCurCtx );

            }
        }
        else // otherwise it's declaration of a variable;
        {
            // now, the cursor point to the end of statement (';' token)

            if ( mCurCtxType != SP_CTX_CLASS )
            {
                // non-class members are ignored

                skip_token( m_cur ); // skip the end of statement
                continue;
            }

            ParseMemberVar( m_cur );
        }

    } while( 1 );
}
Exemplo n.º 23
0
Term ProcCoefVrt(Term t, List ind)
{
	List l,pl,ml;
	int  ii;
	Term a2;
	int g=0, g5=0, re=0, im=0, abbr=0, cmplx=0;
	
	if(!is_compound(t) || CompoundArity(t)>2 || !is_list(CompoundArg1(t)))
	{
		ErrorInfo(0);
		puts("wrong parameters of CoefVrt function.");
		return 0;
	}
	
	if(lagr_hash==NULL)
	{
		ErrorInfo(107);
		puts("CoefVrt: no vertices");
		return 0;
	}
	
	mmm=0;
	if(CompoundArity(t)==2)
	{
		List ol=CompoundArg2(t);
		if(!is_list(ol))
		{
		ErrorInfo(107);
		puts("CoefVrt: second argument is not a list.");
		return 0;
		}
		for(;ol;ol=ListTail(ol))
		{
			Term o=ListFirst(ol);
			if(is_compound(o))
			{
				o=CompoundArg1(o);
				if(!is_atom(o) || !is_particle(o,0))
				{
					ErrorInfo(0);
					printf("CoefVrt: ");WriteTerm(o);
					puts(" is not a particle.\n");
					return 0;
				}
				mmm=o;
				continue;
			}
			if(!is_atom(o))
			{
				ErrorInfo(0);
				printf("CoefVrt: ");WriteTerm(o);
				puts(" is not an option.\n");
				return 0;
			}
			if(strcmp("gamma",AtomValue(o))==0)
			{
				g++;
				continue;
			}
			if(strcmp("gamma5",AtomValue(o))==0)
			{
				g5++;
				continue;
			}
			if(strcmp("re",AtomValue(o))==0)
			{
				re++;
				continue;
			}
			if(strcmp("im",AtomValue(o))==0)
			{
				im++;
				continue;
			}
			if(strcmp("abbr",AtomValue(o))==0)
			{
				abbr++;
				continue;
			}
			{
				ErrorInfo(0);
				printf("CoefVrt: ");WriteTerm(o);
				puts(" is not an option.\n");
				return 0;
			}
		}
	}
			
	if(re&&im)
		re=im=0;
			
	pl=ConsumeCompoundArg(t,1);
	for(l=pl;l;l=ListTail(l))
		if(is_function(ListFirst(l),0))
			ChangeList(l,CallFunction(ListFirst(l),0));

/*	for(l=pl;l;l=ListTail(l))
	{
		Term aa=ListFirst(l);
		if(is_compound(aa)&&CompoundName(aa)==A_ANTI)
			ChangeList(l,GetAtomProperty(CompoundArg1(aa),A_ANTI));
	}*/
	pl=SortedList(pl,acmp);
	
	l=finda2(pl,0);
	
	if(mmm && !mmmpos)
	{
		ErrorInfo(0);
		printf("CoefVrt: particle ");
		WriteTerm(mmm);
		puts(" not found in the vertex");
		return 0;
	}
	
		
	
	
	if(is_empty_list(l))
	{
	ErrorInfo(108);
	printf("CoefVrt: vertex ");
	WriteTerm(pl);
	puts(" not found");
	return NewInteger(0);
	}
	
	a2=CopyTerm(ListFirst(l));
	
	
	alg2_symmetrize(a2);
	alg2_common_n(a2);
	{
		int sv=kill_gamma_pm;
		kill_gamma_pm=1;
		alg2_red_1pm5(a2);
		kill_gamma_pm=sv;
	}
	alg2_recommon_n(a2);
		
	ml=ConsumeCompoundArg(a2,5);
	for(l=ml;l;l=ListTail(l))
	{
		List l1,ll;
		int tg=0, tg5=0, tm=0;
		for(l1=CompoundArgN(ListFirst(l),3);l1;l1=ListTail(l1))
		{
			Term tt=ListFirst(l1);
			if(CompoundName(tt)==OPR_SPECIAL && CompoundArg1(tt)==A_GAMMA)
				tg++;
			if(CompoundName(tt)==OPR_SPECIAL && CompoundArg1(tt)==A_GAMMA5)
				tg5++;
			if(CompoundName(tt)==A_MOMENT && CompoundArg1(tt)==
						NewInteger(mmmpos))
				tm++;
		}
		if(g!=tg || g5!=tg5 || (mmm && !tm))
		{
			SetCompoundArg(ListFirst(l),1,0);
			continue;
		}
		if(!re && !im)
			continue;
		for(l1=CompoundArg2(ListFirst(l));l1;l1=ListTail(l1))
			if(GetAtomProperty(CompoundArg1(ListFirst(l1)),A_ANTI))
				cmplx++;
	}

	if( (re||im) && !cmplx)
		for(l=ml;l;l=ListTail(l))
		{
		List ll,l1;
		if(CompoundArg1(ListFirst(l))==0)
			continue;
		ll=ConsumeCompoundArg(ListFirst(l),2);
		for(l1=ll;l1;l1=ListTail(l1))
			if(CompoundArg1(ListFirst(l1))==A_I)
				break;
		if( (re && l1) || (im && !l1) )
			SetCompoundArg(ListFirst(l),1,0);
		if(im && l1)
			ll=CutFromList(ll,l1);
		SetCompoundArg(ListFirst(l),2,ll);
		}

		
rpt:
	for(l=ml;l;l=ListTail(l))
		if(CompoundArg1(ListFirst(l))==0)
		{
			ml=CutFromList(ml,l);
			break;
		}
	if(l)
		goto rpt;
	
	SetCompoundArg(a2,5,ml);
	alg2_recommon_n(a2);
	alg2_common_s(a2);
	alg2_red_cos(a2);
	alg2_red_orth(a2);
	alg2_red_sico(a2);
	alg2_red_comsico(a2);
	alg2_recommon_n(a2);
	if(abbr)
	{
		int trisv=opTriHeu;
		alg2_eval_vrt(a2);
		doing_abbr=0;
		opTriHeu=trisv;
	}
	
	{
	int n,d;
	Term cf;
	Term res;
	n=IntegerValue(CompoundArg1(CompoundArg2(a2)));
	d=IntegerValue(CompoundArg2(CompoundArg2(a2)));
	cf=l2expr(CompoundArgN(a2,3),n);
	ml=CompoundArgN(a2,5);
	if(ml==0)
		return NewInteger(0);
	res=l2expr(CompoundArg2(ListFirst(ml)),
			IntegerValue(CompoundArg1(ListFirst(ml))));
	for(l=ListTail(ml);l;l=ListTail(l))
	{
		Term ccc;
		n=IntegerValue(CompoundArg1(ListFirst(l)));
		ccc=l2expr(CompoundArg2(ListFirst(l)),n>0?n:-n);
		if(n>0)
			res=MakeCompound2(OPR_PLUS,res,ccc);
		else
			res=MakeCompound2(OPR_MINUS,res,ccc);
	}
	if(res==NewInteger(1))
		res=cf;
	else
		res=MakeCompound2(OPR_MLT,cf,res);
	if(d!=1)
		res=MakeCompound2(OPR_DIV,res,NewInteger(d));
	if( (im||re) && cmplx)
		res=MakeCompound1(NewAtom(re?"creal":"cimag",0),res);
		
	return res;
	}
	return a2;
	
}
Exemplo n.º 24
0
static struct block *unary_expression(struct block *block)
{
    struct var value;

    switch (peek().token) {
    case '&':
        consume('&');
        block = cast_expression(block);
        block->expr = eval_addr(block, block->expr);
        break;
    case '*':
        consume('*');
        block = cast_expression(block);
        block->expr = eval_deref(block, block->expr);
        break;
    case '!':
        consume('!');
        block = cast_expression(block);
        block->expr = eval_expr(block, IR_OP_EQ, var_int(0), block->expr);
        break;
    case '~':
        consume('~');
        block = cast_expression(block);
        block->expr = eval_expr(block, IR_NOT, block->expr);
        break;
    case '+':
        consume('+');
        block = cast_expression(block);
        block->expr.lvalue = 0;
        break;
    case '-':
        consume('-');
        block = cast_expression(block);
        block->expr = eval_expr(block, IR_OP_SUB, var_int(0), block->expr);
        break;
    case SIZEOF: {
        struct typetree *type;
        struct block *head = cfg_block_init(), *tail;
        consume(SIZEOF);
        if (peek().token == '(') {
            switch (peekn(2).token) {
            case FIRST(type_name):
                consume('(');
                type = declaration_specifiers(NULL);
                if (peek().token != ')') {
                    type = declarator(type, NULL);
                }
                consume(')');
                break;
            default:
                tail = unary_expression(head);
                type = (struct typetree *) tail->expr.type;
                break;
            }
        } else {
            tail = unary_expression(head);
            type = (struct typetree *) tail->expr.type;
        }
        if (is_function(type)) {
            error("Cannot apply 'sizeof' to function type.");
        }
        if (!size_of(type)) {
            error("Cannot apply 'sizeof' to incomplete type.");
        }
        block->expr = var_int(size_of(type));
        break;
    }
    case INCREMENT:
        consume(INCREMENT);
        block = unary_expression(block);
        value = block->expr;
        block->expr = eval_expr(block, IR_OP_ADD, value, var_int(1));
        block->expr = eval_assign(block, value, block->expr);
        break;
    case DECREMENT:
        consume(DECREMENT);
        block = unary_expression(block);
        value = block->expr;
        block->expr = eval_expr(block, IR_OP_SUB, value, var_int(1));
        block->expr = eval_assign(block, value, block->expr);
        break;
    default:
        block = postfix_expression(block);
        break;
    }

    return block;
}
Exemplo n.º 25
0
void infix2rpn(char *expr, RPNEntry ***rpne, int *nrpne) {
    Array *rpn = array_new(32, 16);
    Stack *stack_ops = stack_new(16);
    //static char token[64];
    char *token;
    int tokenlen;
    int i;

    int uminus = 1;
    int inoperand = 0;
    //printf("%s:-> ", expr);

    char lookahead;

    for(token = gettoken(expr, &tokenlen, &lookahead);token != NULL; token = gettoken(NULL, &tokenlen, &lookahead)) {
        if (uminus) {
            if (*token == T_MINUS) {
                *token = T_UMINUS;
            }
            uminus = 0;
        }

        if (is_function(token, tokenlen)) {
            stack_push(stack_ops, token);
        } else if (is_operand(token)) {
            array_add(rpn, token);
        } else if (is_arg_separator(token)) {
            while(!stack_empty(stack_ops) && !is_lparen(stack_peek(stack_ops))) {
                array_add(rpn, stack_pop(stack_ops));
            }
        } else if (is_operator(token)) {
            uminus = 1;
            if (stack_empty(stack_ops)) {
                stack_push(stack_ops, token);
            } else {
                if (compare_ops(token, stack_peek(stack_ops))) {
                    array_add(rpn, stack_pop(stack_ops));
                }
                stack_push(stack_ops, token);
            }
        } else if (is_lparen(token)) {
            uminus = 1;
            stack_push(stack_ops, token);
        } else if (is_rparen(token)) {
            while(!stack_empty(stack_ops) && !is_lparen(stack_peek(stack_ops))) {
                array_add(rpn, stack_pop(stack_ops));
            }
            stack_pop(stack_ops);
        } else {
            // errorski
        }
    }
    while (!stack_empty(stack_ops)) {
        array_add(rpn, stack_pop(stack_ops));
    }

    stack_free(&stack_ops);
    *rpne = (RPNEntry **)malloc(rpn->count * sizeof(RPNEntry*));
    for (i = 0; i < rpn->count; i++) {
        token = array_get(rpn, i);
        (*rpne)[i] = new_rpnentry(token, strlen(token));
    }
    *nrpne = rpn->count;
    array_free(&rpn);
}
Exemplo n.º 26
0
bool Type::compatible(const Type& type) const {
	if (_types.size() == 0 or type._types.size() == 0) {
		return true;
	}
	if (is_any()) {
		return true;
	}
	if (this->is_primitive() && type.is_polymorphic()) {
		return false;
	}
	if (this->temporary and not type.temporary) {
		return false; // type not compatible with type&&
	}
	if (not this->constant and type.constant) {
		return false; // 'const type' not compatible with 'type'
	}
	if ((is_array() && type.is_array()) || (is_set() && type.is_set()) || (is_map() && type.is_map()) || (is_function() && type.is_function())) {
		return _types[0]->compatible(type._types[0].get());
	}
	if (_types[0] != type._types[0]) {
		// 'Integer' is compatible with 'Float'
		if (this->is_real() and type.is_integer()) {
			return true;
		}
		// 'Boolean' is compatible with 'Integer'
		if (this->is_integer() and type.is_bool()) {
			return true;
		}
		// 'Integer' is compatible with 'Long'
		if (this->is_long() and type.is_integer()) {
			return true;
		}
		// All numbers types are compatible with the base 'Number' type
		if (dynamic_cast<const Number_type*>(_types[0].get()) and (type.is_integer() or type.is_long() or type.is_real())) {
			return true;
		}
		return false;
	}
	return true;
}
Exemplo n.º 27
0
bool calls_function_by_value(Term* term)
{
    return !is_function(term->function);
}
Exemplo n.º 28
0
Arquivo: cli.c Projeto: htw-ai/algo
int cli_function(char str[], StudentList** sl, int* sl_length)
{
    printf("\n");
    if(is_function("PUSH", str)) return cli_push(sl, sl_length);
    if(is_function("UNSHIFT", str)) return cli_unshift(sl, sl_length);
    if(is_function("PRINT_ALL", str)) return cli_print_all(*sl);
    if(is_function("LENGTH", str)) return cli_length(sl_length);
    if(is_function("DELETE", str)) return cli_delete(sl, sl_length);
    if(is_function("DELETE_ALL", str)) return cli_delete_all(*sl, sl_length);
    if(is_function("FIND_ID", str)) return cli_find_id(*sl);
    if(is_function("QUERY", str)) return cli_query(*sl);
    if(is_function("SORT_STUDIENGANG", str)) return cli_sort_studiengang(*sl);
    if(is_function("SORT_MARTRIKEL", str)) return cli_sort_martikel(*sl);
    if(is_function("QUIT", str)) return 1;

    printf("No such Function\n");
    return 0;
}
Exemplo n.º 29
0
static bool execute(char *buffer, bool *data)
{
    char *token, **ops, *o1, *o2;
    bool *output, res;
    int n_o, n_q, sz_o, sz_q;;

    sz_o = 8192;
    sz_q = 8192;
    ops = malloc(sz_q * sizeof(char *));
    output = malloc(sz_o * sizeof(bool));
    n_o = n_q = 0;


    for (token = strtok(buffer, " "); token; token = strtok(NULL, " ")) {
        if (strncmp(token, "b", 1) == 0) {
            push_bit(data[atoi(token + 1)], &output, &n_o, &sz_o);
        } else if (is_function(token)) {
            push_op(token, &ops, &n_q, &sz_q);
        } else if (strncmp(token, ",", 1) == 0) {
            while (strncmp(peek_op(ops, n_q), "(", 1) != 0) {
                token = pop_op(ops, &n_q);
                if (is_operator(token)) {
                    push_bit(operator(token, pop_bit(output, &n_o), pop_bit(output, &n_o)), &output, &n_o, &sz_o);
                } else {
                    push_bit(function(token, output, &n_o), &output, &n_o, &sz_o);
                }
            }
        } else if (is_operator(token)) {
            o1 = token;
            while (peek_op(ops, n_q) && is_operator(peek_op(ops, n_q))) {
                o2 = peek_op(ops, n_q);
                if (operator_precedence(o1) <= operator_precedence(o2)) {
                    push_bit(operator(pop_op(ops, &n_q), pop_bit(output, &n_o), pop_bit(output, &n_o)), &output, &n_o, &sz_o);
                } else {
                    break;
                }
            }
            push_op(o1, &ops, &n_q, &sz_q);
        } else if (strncmp(token, "(", 1) == 0) {
            push_op(token, &ops, &n_q, &sz_q);
        } else if (strncmp(token, ")", 1) == 0) {
            while (strncmp(peek_op(ops, n_q), "(", 1) != 0) {
                token = pop_op(ops, &n_q);
                if (is_operator(token)) {
                    push_bit(operator(token, pop_bit(output, &n_o), pop_bit(output, &n_o)), &output, &n_o, &sz_o);
                } else {
                    push_bit(function(token, output, &n_o), &output, &n_o, &sz_o);
                }
            }

            token = pop_op(ops, &n_q); /* pop the left bracket */

            if (peek_op(ops, n_q) && is_function(peek_op(ops, n_q))) {
                push_bit(function(pop_op(ops, &n_q), output, &n_o), &output, &n_o, &sz_o);
            }
        } else {
            fprintf(stderr, "ERROR: unknown symbol: %s\n", token);
            exit(EXIT_FAILURE);
        }
    }

    while ((token = pop_op(ops, &n_q))) {
        if (is_operator(token)) {
            push_bit(operator(token, pop_bit(output, &n_o), pop_bit(output, &n_o)), &output, &n_o, &sz_o);
        } else {
            push_bit(function(token, output, &n_o), &output, &n_o, &sz_o);
        }
    }

    res = output[0];

    free(output);
    free(ops);

    return res;
}
Exemplo n.º 30
0
static struct block *postfix_expression(struct block *block)
{
    struct var root;

    block = primary_expression(block);
    root = block->expr;

    while (1) {
        const struct member *field;
        const struct typetree *type;
        struct var expr, copy, *arg;
        struct token tok;
        int i, j;

        switch ((tok = peek()).token) {
        case '[':
            do {
                /* Evaluate a[b] = *(a + b). The semantics of pointer arithmetic
                 * takes care of multiplying b with the correct width. */
                consume('[');
                block = expression(block);
                root = eval_expr(block, IR_OP_ADD, root, block->expr);
                root = eval_deref(block, root);
                consume(']');
            } while (peek().token == '[');
            break;
        case '(':
            type = root.type;
            if (is_pointer(root.type) && is_function(root.type->next))
                type = type_deref(root.type);
            else if (!is_function(root.type)) {
                error("Expression must have type pointer to function, was %t.",
                    root.type);
                exit(1);
            }
            consume('(');
            arg = calloc(nmembers(type), sizeof(*arg));
            for (i = 0; i < nmembers(type); ++i) {
                if (peek().token == ')') {
                    error("Too few arguments, expected %d but got %d.",
                        nmembers(type), i);
                    exit(1);
                }
                block = assignment_expression(block);
                arg[i] = block->expr;
                /* todo: type check here. */
                if (i < nmembers(type) - 1) {
                    consume(',');
                }
            }
            while (is_vararg(type) && peek().token != ')') {
                consume(',');
                arg = realloc(arg, (i + 1) * sizeof(*arg));
                block = assignment_expression(block);
                arg[i] = block->expr;
                i++;
            }
            consume(')');
            for (j = 0; j < i; ++j)
                param(block, arg[j]);
            free(arg);
            root = eval_call(block, root);
            break;
        case '.':
            consume('.');
            tok = consume(IDENTIFIER);
            field = find_type_member(root.type, tok.strval);
            if (!field) {
                error("Invalid field access, no member named '%s'.",
                    tok.strval);
                exit(1);
            }
            root.type = field->type;
            root.offset += field->offset;
            break;
        case ARROW:
            consume(ARROW);
            tok = consume(IDENTIFIER);
            if (is_pointer(root.type) && is_struct_or_union(root.type->next)) {
                field = find_type_member(type_deref(root.type), tok.strval);
                if (!field) {
                    error("Invalid field access, no member named '%s'.",
                        tok.strval);
                    exit(1);
                }

                /* Make it look like a pointer to the field type, then perform
                 * normal dereferencing. */
                root.type = type_init(T_POINTER, field->type);
                root = eval_deref(block, root);
                root.offset = field->offset;
            } else {
                error("Invalid field access.");
                exit(1);
            }
            break;
        case INCREMENT:
            consume(INCREMENT);
            copy = create_var(root.type);
            eval_assign(block, copy, root);
            expr = eval_expr(block, IR_OP_ADD, root, var_int(1));
            eval_assign(block, root, expr);
            root = copy;
            break;
        case DECREMENT:
            consume(DECREMENT);
            copy = create_var(root.type);
            eval_assign(block, copy, root);
            expr = eval_expr(block, IR_OP_SUB, root, var_int(1));
            eval_assign(block, root, expr);
            root = copy;
            break;
        default:
            block->expr = root;
            return block;
        }
    }
}