sagexx_ug (1158317), страница 7

Файл №1158317 sagexx_ug (Раздаточные материалы) 7 страницаsagexx_ug (1158317) страница 72019-09-18СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 7)

As with the other classes thereis a `variant()' which identies the subclass and an integer identier `id()' that is unique for eachsymbol. The symbols in each le are organized as a list which is accessible from the le object as`SgFile::firstSymbol()' and the following symbol to the current symbol is located with `next()'.Every symbol has a character string `identifier()', a `type()', which is described in detail below,and a statement called `scope()' that is the statement in which declaration is scoped. (It is thecontrol parent of the declaration statement). The statement where the variable is declared is givenby `declaredInStmt()'.In addition, there are functions that can be used to generate a copy of the symbol.

Thereare three forms of the copy. The basic copy make a simple copy of the symbol table entry. Thelevel one copy also generates new type information (?correct?). The level two copy also copies thedeclaration body.class SgSymbol {Chapter 5: Symbols106public:// basic class containsPTR_SYMB thesymb;SgSymbol(int variant, char *identifier, SgType &t,SgStatement &scope);SgSymbol(int variant, char *identifier, SgStatement &scope);SgSymbol(int variant, char *name);SgSymbol(int variant);SgSymbol(PTR_SYMB symb);intvariant();intid();// unique identifierchar *identifier();// the text name for the symbol.SgType *type();// the type of the symbolvoidsetType(SgType &t);// the type of the symbolSgStatement * scope(); // the SgControlStatement where defined.SgSymbol *next();// next symbol reference.SgStatement * declaredInStmt(); // the declaration statementSgSymbol ©();SgSymbol ©Level1(); // copy also parametersSgSymbol ©Level2(); // copy parameters, body alsointattributes();// the Fortran 90 attributesvoidsetAttribute(int attribute);voidremoveAttribute(int attribute);voiddeclareTheSymbol(SgStatement &st);SgStatement * body(); // the body of the symbol if has one (like, function call, clas};SgSymbol is used in the following places in the example programs: see [Restructure - addStuToProgram], page 135 see [Instrument - Fortran Program Transformations], page 140 see [Instrument - InitFunctionTable], page 141 see [Instrument - InsertFCallNode], page 142 see [Instrument - pCxx Program Transformations], page 147 see [Instrument - isReferenceToMethodOfElement], page 147 see [Instrument - isReferenceToClassOfElement], page 148 see [Instrument - isReferenceToCollection], page 150 see [Instrument - ListCollectionInvocations], page 153 see [Instrument - InsertCCallNode], page 155 see [Instrument - CTimingInstrumentSub], page 156 see hundenedi [Expand Syntax], page hundenedi see [Expand Syntax - isReferenceToElementField], page 160 see [Expand Syntax - SearchInExpForCollectionArrayRef], page 162Chapter 5: Symbolsseeseeseeseeseeseesee[Expand Syntax - ReplaceWithGetElemPart], page 163[Expand Syntax - Init], page 166[Dump Info - classifyStatements], page 170[Dump Info - doRoutineHeader], page 176[Dump Info - doSymb], page 179[Dump Info - doSymbAttribs], page 179[Dump Info - classifySymbols], page 185Member Functions:SgSymbol(int variant, char *identier, SgType &t, SgStatement &scope)SgSymbol(int variant, char *identier, SgStatement &scope)SgSymbol(int variant, char *name)SgSymbol(int variant)SgSymbol(PTR SYMB symb)int variant()int id()char * identier()SgType * type()void setType(SgType &t)SgStatement * scope()SgSymbol * next()SgStatement * declaredInStmt()SgSymbol & copy()SgSymbol & copyLevel1()SgSymbol & copyLevel2()int attributes()void setAttribute(int attribute)void removeAttribute(int attribute)void declareTheSymbol(SgStatement &st)107Chapter 5: Symbols108SgStatement * body()If the symbol refers to a function, struct, subroutine or class, this returns a pointer to theSgStatement object that is the declaration of the symbol.SgSymbol UsageAs an example of how to traverse the symbol table, consider the problem of looking for a symboltable entry for a given member function in a given class.

There are several ways to do this. Thescheme shown below will search the table for the class by name. Then it searches the eld list forthe member function and returns the pointer to the symbol object if it is found.SgSymbol *memberFunction(char *className, char *functionName){SgSymbol *s, *fld;SgClassSymb *cl;SgMemberFuncSymb *f;int i;for (s=file.firstSymbol(); s ; s = s->next())if (!strcmp(s->identifier(), className))break;if (s == NULL)return NULL;}if (cl = isSgClassSymb(s)){i = 1;while(fld = cl->field(i++)){if ((f = isSgMemberFuncSymb(fld)) &&!strcmp(f->identifier(), functionName))return f;}}return NULL;As another example, consider the task of generating temporary variables that match the typeand initial constructor parameters of a given variable symbol.

More specically, consider thedeclarationsint *x[100], y[34];myClass object(parm1, parm2);Chapter 5: Symbols109Each of these statements is of class SgVarDeclStmt which has a type and an expression list. Inthe rst case the expression list has two items (called values in SgExprListExp): `x[100], y[34]',and the second declaration has one item `object(parm1, parm2)'. The following function createsa new temporary symbol with name Ti where i is an integer counter and given a symbol tableentry, nds the declaration of the symbol, and creates an identical declaration for the temporary.char name_counter = '0';SgSymbol * DeclareTemporaryLike(SgSymbol * x){SgStatement *old_decl_stmt;SgSymbol *tmp;SgVarDeclStmt *decl_stmt;SgExpression *exp;char *name;SgExprListExp *elist;// now find the declaration statement for x and get// the correct initializing expression.old_decl_stmt = x.declaredInStmt()// get the expression list of variables delcaredexp = old_decl_stmt->expr(0);// look for the reference to our symbol x.while(elist = isSgExprListExp(exp)){if((elist->value())->isSymbolInExpression(*x)break;exp = elist->next();}if(exp == NULL) return NULL;// now create a new expression list and// and a new declaration statementelist = new SgExprListExp(*(exp->copy());decl_stmt = new SgVarDeclStmt(*elist,old_decl_stmt->type());// create a new variable of the same class// generate the name as "_Ti" where i is counter.name = new char(10);sprintf(name, "_T%c", name_counter++);tmp = new SgVariableSymb(name, (x->type())->copy(), *scope);}// replace x with the new variable and insert// the new decl statement after the old one.decl_stmt->replaceSymbBySymb(*x, *tmp);old_decl_stmt->insertStmtAfter(*decl_stmt);return tmp;Chapter 5: Symbols1105.2 SgVariableSymbRepresents variable symbols, for all languages.Variant: VARIABLE NAMEFor usage,see [SgExpression Usage], page 74;see [SgSubscriptExp Usage], page 88.For base class, see Section 5.1 [SgSymbol], page 105.class SgVariableSymb: public SgSymbol {public:SgVariableSymb(char *identifier, SgType &t, SgStatement &scope);SgVariableSymb(char *identifier, SgType &t);SgVariableSymb(char *identifier, SgStatement &scope);SgVariableSymb(char *identifier);#if 0intisAttributeSet(int attribute);voidsetAttribute(int attribute);intnumberOfUses();SgStatement * useStmt(int i);SgExpression * useExpr(int i);intnumberOfDefs();#endif};// number of uses.// statement where i-th use occurs// expression where i-th use occursSgVariableSymb is used in the following places in the example programs: see [Restructure - addStuToProgram], page 135 see hundenedi [Expand Syntax], page hundenedi see [Expand Syntax - ReplaceWithGetElemPart], page 163 see [Expand Syntax - Init], page 166 see [Dump Info - classifySymbols], page 185Member Functions:SgVariableSymb(char *identier, SgType &t, SgStatement &scope)SgVariableSymb(char *identier, SgType &t)Chapter 5: SymbolsSgVariableSymb(char *identier, SgStatement &scope)SgVariableSymb(char *identier)int isAttributeSet(int attribute)void setAttribute(int attribute)int numberOfUses()Returns the number of uses.SgStatement * useStmt(int i)Returns the ith use of the variable.SgExpression * useExpr(int i)Returns the ith expression in which the variable is used.int numberOfDefs()The number of denitions of the variable.5.3 SgConstantSymbRepresents symbols for constants, for all languages.Variant: CONST NAMEFor base class, see Section 5.1 [SgSymbol], page 105.class SgConstantSymb: public SgSymbol {public:SgConstantSymb(char *identifier, SgStatement &scope,SgExpression &value);SgExpression * constantValue();};SgConstantSymb is used in the following places in the example programs: see [Dump Info - classifySymbols], page 185Member Functions:SgConstantSymb(char *identier, SgStatement &scope, SgExpression &value)111Chapter 5: Symbols112SgExpression * constantValue()5.4 SgFunctionSymbRepresents symbols for subroutines, symbols for functions, and symbols for main programs, for alllanguages.Variants: PROGRAM NAME, PROCEDURE NAME, MEMBER FUNC and FUNCTION NAME.For base class, see Section 5.1 [SgSymbol], page 105.class SgFunctionSymb: public SgSymbol {// a subroutine, function or main program// variant == PROGRAM_NAME, PROCEDURE_NAME, or FUNCTION_NAMEpublic:SgFunctionSymb(int variant);SgFunctionSymb(int variant, char *identifier, SgType &t,SgStatement &scope);voidaddParameter(int n, SgSymbol ¶meters);voidinsertParameter(int position, SgSymbol &symb);intnumberOfParameters();SgSymbol * parameter(int i);SgSymbol * result();voidsetResult(SgSymbol &symbol);#if 0intisRecursive();intsetRecursive();#endif};SgFunctionSymb is used in the following places in the example programs: see [Instrument - InitSymbols], page 140 see [Instrument - CInitSymbols], page 155 see hundenedi [Expand Syntax], page hundenedi see [Expand Syntax - ReplaceWithGetElemPart], page 163 see [Expand Syntax - Init], page 166 see [Dump Info - classifySymbols], page 185Member Functions:Chapter 5: SymbolsSgFunctionSymb(int variant)SgFunctionSymb(int variant, char *identier, SgType &t, SgStatement &scope)void addParameter(int n, SgSymbol ¶meters)void insertParameter(int position, SgSymbol &symb)int numberOfParameters()Returns number of parameters in the formal parameter list (of a function).SgSymbol * parameter(int i)Returns the ith parameter in the formal parameter list (of a function).SgSymbol * result()For Fortran, returns a pointer to the result symbol.void setResult(SgSymbol &symbol)For Fortran.int isRecursive()For Fortran, returns TRUE if the function is recursive.int setRecursive()5.5 SgLabelSymbRepresents C label symbols.Variant: LABEL NAMEFor base class, see Section 5.1 [SgSymbol], page 105.class SgLabelSymb: public SgSymbol {public:SgLabelSymb(char *name);};Member Functions:SgLabelSymb(char *name)113Chapter 5: Symbols1145.6 SgTypeSymbRepresents C typedef'ed symbols.Variant: TYPE NAMEFor base class, see Section 5.1 [SgSymbol], page 105.class SgTypeSymb: public SgSymbol {#if 0public:SgTypeSymb(char *name, SgType &baseType);SgType & baseType();};Member Functions:SgTypeSymb(char *name, SgType &baseType)SgType & baseType()The type the symbol represents.5.7 SgClassSymbRepresents C symbols for classes, symbols for unions, symbols for structs, and symbols for collections.Variants: CLASS NAME, UNION NAME, STRUCT NAME and COLLECTION NAME.For usage, see [SgSymbol Usage], page 108.For base class, see Section 5.1 [SgSymbol], page 105.class SgClassSymb: public SgSymbol {public:SgClassSymb(int variant, char *name, SgStatement &scope);intnumberOfFields();SgSymbol * field(int i);Chapter 5: Symbols115};Member Functions:SgClassSymb(int variant, char *name, SgStatement &scope)int numberOfFields()Returns the number of members.SgSymbol * eld(int i)Returns the ith member.5.8 SgFieldSymbRepresents C symbols for elds in enums, symbols for elds in structs, and symbols for elds inclasses.Variants: ENUM NAME and FIELD NAME.For base class, see Section 5.1 [SgSymbol], page 105.class SgFieldSymb: public SgSymbol {public:// no check is made to see if the field "identifier"//already exists in the structure.SgFieldSymb(char *identifier, SgType &t, SgSymbol &structureName);intoffset();// position in the structureSgSymbol * structureName(); // parent structureSgSymbol * nextField();intisMethodOfElement();#if 0intisPrivate();intisSequence();voidsetPrivate();voidsetSequence();#endif};SgFieldSymb is used in the following places in the example programs:Chapter 5: Symbols116see [Instrument - isReferenceToMethodOfElement], page 147see [Instrument - isReferenceToClassOfElement], page 148see [Expand Syntax - isReferenceToElementField], page 160Member Functions:SgFieldSymb(char *identier, SgType &t, SgSymbol &structureName)int oset()SgSymbol * structureName()SgSymbol * nextField()int isMethodOfElement()int isPrivate()int isSequence()void setPrivate()void setSequence()5.9 SgMemberFuncSymbRepresents C symbols for members of structs and classes.Variants: MEMBER FUNC, MEMB PRIVATE, MEMB PUBLIC, MEMB PROTECTED andMEMB METHOELEM.For usage, see [SgSymbol Usage], page 108.For base class, see Section 5.4 [SgFunctionSymb], page 112.class SgMemberFuncSymb: public SgFunctionSymb {public:SgMemberFuncSymb(char *identifier, SgType &t, SgStatement &cla,int status);#if 0intstatus();intisVirtual();// 1 if virtual.Chapter 5: Symbols#endifintisMethodOfElement();SgSymbol * className();voidsetClassName(SgSymbol &symb);};SgMemberFuncSymb is used in the following places in the example programs: see [Instrument - isReferenceToMethodOfElement], page 147 see [Instrument - isReferenceToClassOfElement], page 148 see [Instrument - inMethodOfTheElement], page 149 see [Instrument - whichFunctionAmI], page 150Member Functions:SgMemberFuncSymb(char *identier, SgType &t, SgStatement &cla, int status)int status()Returns the protection status of the symbol.int isVirtual()int isMethodOfElement()SgSymbol * className()Returns the symbol table entry for the enclosing class or struct.void setClassName(SgSymbol &symb)5.10 SgLabelVarSymbRepresents Fortran symbols for label variables for assigned goto statements.Variant: LABEL NAMEFor base class, see Section 5.1 [SgSymbol], page 105.class SgLabelVarSymb: public SgSymbol {public:SgLabelVarSymb(char *name, SgStatement &scope);117Chapter 5: Symbols};SgLabelVarSymb is used in the following places in the example programs: see [Dump Info - classifySymbols], page 185Member Functions:SgLabelVarSymb(char *name, SgStatement &scope)5.11 SgExternalSymbRepresents Fortran symbols for external functions.Variant: ROUTINE NAMEFor base class, see Section 5.1 [SgSymbol], page 105.class SgExternalSymb: public SgSymbol {public:SgExternalSymb(char *name, SgStatement &scope);};SgExternalSymb is used in the following places in the example programs: see [Dump Info - classifySymbols], page 185Member Functions:SgExternalSymb(char *name, SgStatement &scope)118Chapter 5: Symbols5.12 SgConstructSymbRepresents Fortran symbols for construct names.Variant: CONSTRUCT NAMEFor base class, see Section 5.1 [SgSymbol], page 105.class SgConstructSymb: public SgSymbol {// for fortran statement with construct namespublic:SgConstructSymb(char *name, SgStatement &scope);};SgConstructSymb is used in the following places in the example programs: see [Dump Info - classifySymbols], page 185Member Functions:SgConstructSymb(char *name, SgStatement &scope)5.13 SgModuleSymbRepresents Fortran symbols for module statements.For base class, see Section 5.1 [SgSymbol], page 105.class SgModuleSymb: public SgSymbol {// A lot of work needs to be done on this class.// for fortran module statement// variant == MODULE_NAMEpublic:SgModuleSymb(char *name);};SgModuleSymb is used in the following places in the example programs: see [Dump Info - classifySymbols], page 185119Chapter 5: SymbolsMember Functions:SgModuleSymb(char *name)5.14 SgInterfaceSymbRepresents Fortran 90 symbols for module interface statements.Variant: (? MODULE NAME or INTERFACE NAME?)For base class, see Section 5.1 [SgSymbol], page 105.class SgInterfaceSymb: public SgSymbol {public:SgInterfaceSymb(char *name, SgStatement &scope);};SgInterfaceSymb is used in the following places in the example programs: see [Dump Info - classifySymbols], page 185Member Functions:SgInterfaceSymb(char *name, SgStatement &scope)120Chapter 6: Types1216 TypesSage's type classes correspond to the type structures of the languages Sage can deal with.

Характеристики

Список файлов учебной работы

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6529
Авторов
на СтудИзбе
301
Средний доход
с одного платного файла
Обучение Подробнее