function_name
stringlengths
1
80
function
stringlengths
14
10.6k
comment
stringlengths
12
8.02k
normalized_comment
stringlengths
6
6.55k
sqlite3SelectDelete
void sqlite3SelectDelete(Select *p){ if( p ){ clearSelect(p); sqliteFree(p); } }
/* ** Delete the given Select structure and all of its substructures. */
Delete the given Select structure and all of its substructures.
columnIndex
static int columnIndex(Table *pTab, const char *zCol){ int i; for(i=0; i<pTab->nCol; i++){ if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i; } return -1; }
/* ** Return the index of a column in a table. Return -1 if the column ** is not contained in the table. */
Return the index of a column in a table. Return -1 if the column is not contained in the table.
setToken
static void setToken(Token *p, const char *z){ p->z = (u8*)z; p->n = z ? strlen(z) : 0; p->dyn = 0; }
/* ** Set the value of a token to a '\000'-terminated string. */
Set the value of a token to a '\000'-terminated string.
createIdExpr
static Expr *createIdExpr(const char *zName){ Token dummy; setToken(&dummy, zName); return sqlite3Expr(TK_ID, 0, 0, &dummy); }
/* ** Create an expression node for an identifier with the name of zName */
Create an expression node for an identifier with the name of zName
setJoinExpr
static void setJoinExpr(Expr *p, int iTable){ while( p ){ ExprSetProperty(p, EP_FromJoin); p->iRightJoinTable = iTable; setJoinExpr(p->pLeft, iTable); p = p->pRight; } }
/* ** Set the EP_FromJoin property on all terms of the given expression. ** And set the Expr.iRightJoinTable to iTable for every term in the ** expression. ** ** The EP_FromJoin property is used on terms of an expression to tell ** the LEFT OUTER JOIN processing logic that this term is part of the ** join restriction specified in the ON or USING clause and not a part ** of the more general WHERE clause. These terms are moved over to the ** WHERE clause during join processing but we need to remember that they ** originated in the ON or USING clause. ** ** The Expr.iRightJoinTable tells the WHERE clause processing that the ** expression depends on table iRightJoinTable even if that table is not ** explicitly mentioned in the expression. That information is needed ** for cases like this: ** ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 ** ** The where clause needs to defer the handling of the t1.x=5 ** term until after the t2 loop of the join. In that way, a ** NULL t2 row will be inserted whenever t1.x!=5. If we do not ** defer the handling of t1.x=5, it will be processed immediately ** after the t1 loop and rows with t1.x!=5 will never appear in ** the output, which is incorrect. */
Set the EP_FromJoin property on all terms of the given expression. And set the Expr.iRightJoinTable to iTable for every term in the expression. The EP_FromJoin property is used on terms of an expression to tell the LEFT OUTER JOIN processing logic that this term is part of the join restriction specified in the ON or USING clause and not a part of the more general WHERE clause. These terms are moved over to the WHERE clause during join processing but we need to remember that they originated in the ON or USING clause. The Expr.iRightJoinTable tells the WHERE clause processing that the expression depends on table iRightJoinTable even if that table is not explicitly mentioned in the expression. That information is needed for cases like this: SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5 The where clause needs to defer the handling of the t1.x=5 term until after the t2 loop of the join. In that way, a NULL t2 row will be inserted whenever t1.x!=5. If we do not defer the handling of t1.x=5, it will be processed immediately after the t1 loop and rows with t1.x!=5 will never appear in the output, which is incorrect.
selectOpName
static const char *selectOpName(int id){ char *z; switch( id ){ case TK_ALL: z = "UNION ALL"; break; case TK_INTERSECT: z = "INTERSECT"; break; case TK_EXCEPT: z = "EXCEPT"; break; default: z = "UNION"; break; } return z; }
/* ** Name of the connection operator, used for error messages. */
Name of the connection operator, used for error messages.
printf_realloc
static void *printf_realloc(void *old, int size){ return sqliteRealloc(old,size); }
/* ** Realloc that is a real function, not a macro. */
Realloc that is a real function, not a macro.
sqlite3VMPrintf
char *sqlite3VMPrintf(const char *zFormat, va_list ap){ char zBase[SQLITE_PRINT_BUF_SIZE]; return base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap); }
/* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */
Print into memory obtained from sqliteMalloc(). Use the internal %-conversion extensions.
sqlite3MPrintf
char *sqlite3MPrintf(const char *zFormat, ...){ va_list ap; char *z; char zBase[SQLITE_PRINT_BUF_SIZE]; va_start(ap, zFormat); z = base_vprintf(printf_realloc, 1, zBase, sizeof(zBase), zFormat, ap); va_end(ap); return z; }
/* ** Print into memory obtained from sqliteMalloc(). Use the internal ** %-conversion extensions. */
Print into memory obtained from sqliteMalloc(). Use the internal %-conversion extensions.
sqlite3_mprintf
char *sqlite3_mprintf(const char *zFormat, ...){ va_list ap; char *z; char zBuf[200]; va_start(ap,zFormat); z = base_vprintf((void*(*)(void*,int))realloc, 0, zBuf, sizeof(zBuf), zFormat, ap); va_end(ap); return z; }
/* ** Print into memory obtained from malloc(). Do not use the internal ** %-conversion extensions. This routine is for use by external users. */
Print into memory obtained from malloc(). Do not use the internal %-conversion extensions. This routine is for use by external users.
sqlite3_vmprintf
char *sqlite3_vmprintf(const char *zFormat, va_list ap){ char zBuf[200]; return base_vprintf((void*(*)(void*,int))realloc, 0, zBuf, sizeof(zBuf), zFormat, ap); }
/* This is the varargs version of sqlite3_mprintf. */
This is the varargs version of sqlite3_mprintf.
sqlite3_snprintf
char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){ char *z; va_list ap; va_start(ap,zFormat); z = base_vprintf(0, 0, zBuf, n, zFormat, ap); va_end(ap); return z; }
/* ** sqlite3_snprintf() works like snprintf() except that it ignores the ** current locale settings. This is important for SQLite because we ** are not able to use a "," as the decimal point in place of "." as ** specified by some locales. */
sqlite3_snprintf() works like snprintf() except that it ignores the current locale settings. This is important for SQLite because we are not able to use a "," as the decimal point in place of "." as specified by some locales.
sqlite3DebugPrintf
void sqlite3DebugPrintf(const char *zFormat, ...){ extern int getpid(void); va_list ap; char zBuf[500]; va_start(ap, zFormat); base_vprintf(0, 0, zBuf, sizeof(zBuf), zFormat, ap); va_end(ap); fprintf(stdout,"%d: %s", getpid(), zBuf); fflush(stdout); }
/* ** A version of printf() that understands %lld. Used for debugging. ** The printf() built into some versions of windows does not understand %lld ** and segfaults if you give it a long long int. */
A version of printf() that understands %lld. Used for debugging. The printf() built into some versions of windows does not understand %lld and segfaults if you give it a long long int.
sqlite3OsClose
int sqlite3OsClose(OsFile **pId){ OsFile *id; if( pId!=0 && (id = *pId)!=0 ){ return id->pMethod->xClose(pId); }else{ return SQLITE_OK; } }
/* ** The following routines are convenience wrappers around methods ** of the OsFile object. This is mostly just syntactic sugar. All ** of this would be completely automatic if SQLite were coded using ** C++ instead of plain old C. */
The following routines are convenience wrappers around methods of the OsFile object. This is mostly just syntactic sugar. All of this would be completely automatic if SQLite were coded using C++ instead of plain old C.
sqlite3OsFileHandle
int sqlite3OsFileHandle(OsFile *id){ return id->pMethod->xFileHandle(id); }
/* This method is currently only used while interactively debugging the ** pager. More specificly, it can only be used when sqlite3DebugPrintf() is ** included in the build. */
This method is currently only used while interactively debugging the pager. More specificly, it can only be used when sqlite3DebugPrintf() is included in the build.
sqlite3_os_switch
struct sqlite3OsVtbl *sqlite3_os_switch(void){ return &sqlite3Os; }
/* ** A function to return a pointer to the virtual function table. ** This routine really does not accomplish very much since the ** virtual function table is a global variable and anybody who ** can call this function can just as easily access the variable ** for themselves. Nevertheless, we include this routine for ** backwards compatibility with an earlier redefinable I/O ** interface design. */
A function to return a pointer to the virtual function table. This routine really does not accomplish very much since the virtual function table is a global variable and anybody who can call this function can just as easily access the variable for themselves. Nevertheless, we include this routine for backwards compatibility with an earlier redefinable I/O interface design.
sqlite3BeginParse
void sqlite3BeginParse(Parse *pParse, int explainFlag){ pParse->explain = explainFlag; //pParse->nVar = 0; }
/* ** This routine is called when a new SQL statement is beginning to ** be parsed. Initialize the pParse structure as needed. */
This routine is called when a new SQL statement is beginning to be parsed. Initialize the pParse structure as needed.
sqlite3TableLock
void sqlite3TableLock( Parse *pParse, /* Parsing context */ int iDb, /* Index of the database containing the table to lock */ int iTab, /* Root page number of the table to be locked */ u8 isWriteLock, /* True for a write lock */ const char *zName /* Name of the table to be locked */ ){ /* int i; */ /* int nBytes; */ /* TableLock *p; */ /* if( 0==sqlite3ThreadDataReadOnly()->useSharedData || iDb<0 ){ */ /* return; */ /* } */ /* for(i=0; i<pParse->nTableLock; i++){ */ /* p = &pParse->aTableLock[i]; */ /* if( p->iDb==iDb && p->iTab==iTab ){ */ /* p->isWriteLock = (p->isWriteLock || isWriteLock); */ /* return; */ /* } */ /* } */ /* nBytes = sizeof(TableLock) * (pParse->nTableLock+1); */ /* sqliteReallocOrFree((void **)&pParse->aTableLock, nBytes); */ /* if( pParse->aTableLock ){ */ /* p = &pParse->aTableLock[pParse->nTableLock++]; */ /* p->iDb = iDb; */ /* p->iTab = iTab; */ /* p->isWriteLock = isWriteLock; */ /* p->zName = zName; */ /* } */ }
/* ** Record the fact that we want to lock a table at run-time. ** ** The table to be locked has root page iTab and is found in database iDb. ** A read or a write lock can be taken depending on isWritelock. ** ** This routine just records the fact that the lock is desired. The ** code to make the lock occur is generated by a later call to ** codeTableLocks() which occurs during sqlite3FinishCoding(). */
Record the fact that we want to lock a table at run-time. The table to be locked has root page iTab and is found in database iDb. A read or a write lock can be taken depending on isWritelock. This routine just records the fact that the lock is desired. The code to make the lock occur is generated by a later call to codeTableLocks() which occurs during sqlite3FinishCoding().
sqlite3DeleteTable
void sqlite3DeleteTable(sqlite3 *db, Table *pTable){ /* Index *pIndex, *pNext; */ /* FKey *pFKey, *pNextFKey; */ /* db = 0; */ /* if( pTable==0 ) return; */ /* /1* Do not delete the table until the reference count reaches zero. *1/ */ /* pTable->nRef--; */ /* if( pTable->nRef>0 ){ */ /* return; */ /* } */ /* assert( pTable->nRef==0 ); */ /* /1* Delete all indices associated with this table */ /* *1/ */ /* for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){ */ /* pNext = pIndex->pNext; */ /* assert( pIndex->pSchema==pTable->pSchema ); */ /* sqliteDeleteIndex(pIndex); */ /* } */ /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ /* /1* Delete all foreign keys associated with this table. The keys */ /* ** should have already been unlinked from the db->aFKey hash table */ /* *1/ */ /* for(pFKey=pTable->pFKey; pFKey; pFKey=pNextFKey){ */ /* pNextFKey = pFKey->pNextFrom; */ /* assert( sqlite3HashFind(&pTable->pSchema->aFKey, */ /* pFKey->zTo, strlen(pFKey->zTo)+1)!=pFKey ); */ /* sqliteFree(pFKey); */ /* } */ /* #endif */ /* /1* Delete the Table structure itself. */ /* *1/ */ /* sqliteResetColumnNames(pTable); */ /* sqliteFree(pTable->zName); */ /* sqliteFree(pTable->zColAff); */ /* sqlite3SelectDelete(pTable->pSelect); */ /* #ifndef SQLITE_OMIT_CHECK */ /* sqlite3ExprDelete(pTable->pCheck); */ /* #endif */ /* sqliteFree(pTable); */ }
/* ** Remove the memory data structures associated with the given ** Table. No changes are made to disk by this routine. ** ** This routine just deletes the data structure. It does not unlink ** the table data structure from the hash table. Nor does it remove ** foreign keys from the sqlite.aFKey hash table. But it does destroy ** memory structures of the indices and foreign keys associated with ** the table. ** ** Indices associated with the table are unlinked from the "db" ** data structure if db!=NULL. If db==NULL, indices attached to ** the table are deleted, but it is assumed they have already been ** unlinked. */
Remove the memory data structures associated with the given Table. No changes are made to disk by this routine. This routine just deletes the data structure. It does not unlink the table data structure from the hash table. Nor does it remove foreign keys from the sqlite.aFKey hash table. But it does destroy memory structures of the indices and foreign keys associated with the table. Indices associated with the table are unlinked from the "db" data structure if db!=NULL. If db==NULL, indices attached to the table are deleted, but it is assumed they have already been unlinked.
sqlite3NameFromToken
char *sqlite3NameFromToken(Token *pName){ char *zName; if( pName ){ zName = sqliteStrNDup((char*)pName->z, pName->n); sqlite3Dequote(zName); }else{ zName = 0; } return zName; }
/* ** Given a token, return a string that consists of the text of that ** token with any quotations removed. Space to hold the returned string ** is obtained from sqliteMalloc() and must be freed by the calling ** function. ** ** Tokens are often just pointers into the original SQL text and so ** are not \000 terminated and are not persistent. The returned string ** is \000 terminated and is persistent. */
Given a token, return a string that consists of the text of that token with any quotations removed. Space to hold the returned string is obtained from sqliteMalloc() and must be freed by the calling function. Tokens are often just pointers into the original SQL text and so are not \000 terminated and are not persistent. The returned string is \000 terminated and is persistent.
sqlite3StartTable
void sqlite3StartTable( Parse *pParse, /* Parser context */ Token *pName1, /* First part of the name of the table or view */ Token *pName2, /* Second part of the name of the table or view */ int isTemp, /* True if this is a TEMP table */ int isView, /* True if this is a VIEW */ int noErr /* Do nothing if table already exists */ ){ ParsedResultItem item; item.sqltype = SQLTYPE_CREATE_TABLE; sqlite3ParsedResultArrayAppend(&pParse->parsed, &item); /* Table *pTable; */ /* char *zName = 0; /1* The name of the new table *1/ */ /* sqlite3 *db = pParse->db; */ /* Vdbe *v; */ /* int iDb; /1* Database number to create the table in *1/ */ /* Token *pName; /1* Unqualified name of the table to create *1/ */ /* /1* The table or view name to create is passed to this routine via tokens */ /* ** pName1 and pName2. If the table name was fully qualified, for example: */ /* ** */ /* ** CREATE TABLE xxx.yyy (...); */ /* ** */ /* ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if */ /* ** the table name is not fully qualified, i.e.: */ /* ** */ /* ** CREATE TABLE yyy(...); */ /* ** */ /* ** Then pName1 is set to "yyy" and pName2 is "". */ /* ** */ /* ** The call below sets the pName pointer to point at the token (pName1 or */ /* ** pName2) that stores the unqualified table name. The variable iDb is */ /* ** set to the index of the database that the table or view is to be */ /* ** created in. */ /* *1/ */ /* iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName); */ /* if( iDb<0 ) return; */ /* if( !OMIT_TEMPDB && isTemp && iDb>1 ){ */ /* /1* If creating a temp table, the name may not be qualified *1/ */ /* sqlite3ErrorMsg(pParse, "temporary table name must be unqualified"); */ /* return; */ /* } */ /* if( !OMIT_TEMPDB && isTemp ) iDb = 1; */ /* pParse->sNameToken = *pName; */ /* zName = sqlite3NameFromToken(pName); */ /* if( zName==0 ) return; */ /* if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ */ /* goto begin_table_error; */ /* } */ /* if( db->init.iDb==1 ) isTemp = 1; */ /* #ifndef SQLITE_OMIT_AUTHORIZATION */ /* assert( (isTemp & 1)==isTemp ); */ /* { */ /* int code; */ /* char *zDb = db->aDb[iDb].zName; */ /* if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){ */ /* goto begin_table_error; */ /* } */ /* if( isView ){ */ /* if( !OMIT_TEMPDB && isTemp ){ */ /* code = SQLITE_CREATE_TEMP_VIEW; */ /* }else{ */ /* code = SQLITE_CREATE_VIEW; */ /* } */ /* }else{ */ /* if( !OMIT_TEMPDB && isTemp ){ */ /* code = SQLITE_CREATE_TEMP_TABLE; */ /* }else{ */ /* code = SQLITE_CREATE_TABLE; */ /* } */ /* } */ /* if( sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){ */ /* goto begin_table_error; */ /* } */ /* } */ /* #endif */ /* /1* Make sure the new table name does not collide with an existing */ /* ** index or table name in the same database. Issue an error message if */ /* ** it does. */ /* *1/ */ /* if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ */ /* goto begin_table_error; */ /* } */ /* pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName); */ /* if( pTable ){ */ /* if( !noErr ){ */ /* sqlite3ErrorMsg(pParse, "table %T already exists", pName); */ /* } */ /* goto begin_table_error; */ /* } */ /* if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){ */ /* sqlite3ErrorMsg(pParse, "there is already an index named %s", zName); */ /* goto begin_table_error; */ /* } */ /* pTable = sqliteMalloc( sizeof(Table) ); */ /* if( pTable==0 ){ */ /* pParse->rc = SQLITE_NOMEM; */ /* pParse->nErr++; */ /* goto begin_table_error; */ /* } */ /* pTable->zName = zName; */ /* pTable->nCol = 0; */ /* pTable->aCol = 0; */ /* pTable->iPKey = -1; */ /* pTable->pIndex = 0; */ /* pTable->pSchema = db->aDb[iDb].pSchema; */ /* pTable->nRef = 1; */ /* if( pParse->pNewTable ) sqlite3DeleteTable(db, pParse->pNewTable); */ /* pParse->pNewTable = pTable; */ /* /1* If this is the magic sqlite_sequence table used by autoincrement, */ /* ** then record a pointer to this table in the main database structure */ /* ** so that INSERT can find the table easily. */ /* *1/ */ /* #ifndef SQLITE_OMIT_AUTOINCREMENT */ /* if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){ */ /* pTable->pSchema->pSeqTab = pTable; */ /* } */ /* #endif */ /* /1* Begin generating the code that will insert the table record into */ /* ** the SQLITE_MASTER table. Note in particular that we must go ahead */ /* ** and allocate the record number for the table entry now. Before any */ /* ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause */ /* ** indices to be created and the table record must come before the */ /* ** indices. Hence, the record number for the table must be allocated */ /* ** now. */ /* *1/ */ /* if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){ */ /* int lbl; */ /* int fileFormat; */ /* sqlite3BeginWriteOperation(pParse, 0, iDb); */ /* /1* If the file format and encoding in the database have not been set, */ /* ** set them now. */ /* *1/ */ /* sqlite3VdbeAddOp(v, OP_ReadCookie, iDb, 1); /1* file_format *1/ */ /* lbl = sqlite3VdbeMakeLabel(v); */ /* sqlite3VdbeAddOp(v, OP_If, 0, lbl); */ /* fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ? */ /* 1 : SQLITE_DEFAULT_FILE_FORMAT; */ /* sqlite3VdbeAddOp(v, OP_Integer, fileFormat, 0); */ /* sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 1); */ /* sqlite3VdbeAddOp(v, OP_Integer, ENC(db), 0); */ /* sqlite3VdbeAddOp(v, OP_SetCookie, iDb, 4); */ /* sqlite3VdbeResolveLabel(v, lbl); */ /* /1* This just creates a place-holder record in the sqlite_master table. */ /* ** The record created does not contain anything yet. It will be replaced */ /* ** by the real entry in code generated at sqlite3EndTable(). */ /* ** */ /* ** The rowid for the new entry is left on the top of the stack. */ /* ** The rowid value is needed by the code that sqlite3EndTable will */ /* ** generate. */ /* *1/ */ /* #ifndef SQLITE_OMIT_VIEW */ /* if( isView ){ */ /* sqlite3VdbeAddOp(v, OP_Integer, 0, 0); */ /* }else */ /* #endif */ /* { */ /* sqlite3VdbeAddOp(v, OP_CreateTable, iDb, 0); */ /* } */ /* sqlite3OpenMasterTable(pParse, iDb); */ /* sqlite3VdbeAddOp(v, OP_NewRowid, 0, 0); */ /* sqlite3VdbeAddOp(v, OP_Dup, 0, 0); */ /* sqlite3VdbeAddOp(v, OP_Null, 0, 0); */ /* sqlite3VdbeAddOp(v, OP_Insert, 0, 0); */ /* sqlite3VdbeAddOp(v, OP_Close, 0, 0); */ /* sqlite3VdbeAddOp(v, OP_Pull, 1, 0); */ /* } */ /* /1* Normal (non-error) return. *1/ */ /* return; */ /* /1* If an error occurs, we jump here *1/ */ /* begin_table_error: */ /* sqliteFree(zName); */ /* return; */ }
/* ** Begin constructing a new table representation in memory. This is ** the first of several action routines that get called in response ** to a CREATE TABLE statement. In particular, this routine is called ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp ** flag is true if the table should be stored in the auxiliary database ** file instead of in the main database file. This is normally the case ** when the "TEMP" or "TEMPORARY" keyword occurs in between ** CREATE and TABLE. ** ** The new table record is initialized and put in pParse->pNewTable. ** As more of the CREATE TABLE statement is parsed, additional action ** routines will be called to add more information to this record. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine ** is called to complete the construction of the new table record. */
Begin constructing a new table representation in memory. This is the first of several action routines that get called in response to a CREATE TABLE statement. In particular, this routine is called after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp flag is true if the table should be stored in the auxiliary database file instead of in the main database file. This is normally the case when the "TEMP" or "TEMPORARY" keyword occurs in between CREATE and TABLE. The new table record is initialized and put in pParse->pNewTable. As more of the CREATE TABLE statement is parsed, additional action routines will be called to add more information to this record. At the end of the CREATE TABLE statement, the sqlite3EndTable() routine is called to complete the construction of the new table record.
sqlite3AddColumn
void sqlite3AddColumn(Parse *pParse, Token *pName){ /* Table *p; */ /* int i; */ /* char *z; */ /* Column *pCol; */ /* if( (p = pParse->pNewTable)==0 ) return; */ /* z = sqlite3NameFromToken(pName); */ /* if( z==0 ) return; */ /* for(i=0; i<p->nCol; i++){ */ /* if( STRICMP(z, p->aCol[i].zName) ){ */ /* sqlite3ErrorMsg(pParse, "duplicate column name: %s", z); */ /* sqliteFree(z); */ /* return; */ /* } */ /* } */ /* if( (p->nCol & 0x7)==0 ){ */ /* Column *aNew; */ /* aNew = sqliteRealloc( p->aCol, (p->nCol+8)*sizeof(p->aCol[0])); */ /* if( aNew==0 ){ */ /* sqliteFree(z); */ /* return; */ /* } */ /* p->aCol = aNew; */ /* } */ /* pCol = &p->aCol[p->nCol]; */ /* memset(pCol, 0, sizeof(p->aCol[0])); */ /* pCol->zName = z; */ /* /1* If there is no type specified, columns have the default affinity */ /* ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will */ /* ** be called next to set pCol->affinity correctly. */ /* *1/ */ /* pCol->affinity = SQLITE_AFF_NONE; */ /* p->nCol++; */ }
/* ** Add a new column to the table currently being constructed. ** ** The parser calls this routine once for each column declaration ** in a CREATE TABLE statement. sqlite3StartTable() gets called ** first to get things going. Then this routine is called for each ** column. */
Add a new column to the table currently being constructed. The parser calls this routine once for each column declaration in a CREATE TABLE statement. sqlite3StartTable() gets called first to get things going. Then this routine is called for each column.
sqlite3AddNotNull
void sqlite3AddNotNull(Parse *pParse, int onError){ /* Table *p; */ /* int i; */ /* if( (p = pParse->pNewTable)==0 ) return; */ /* i = p->nCol-1; */ /* if( i>=0 ) p->aCol[i].notNull = onError; */ }
/* ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has ** been seen on a column. This routine sets the notNull flag on ** the column currently under construction. */
This routine is called by the parser while in the middle of parsing a CREATE TABLE statement. A "NOT NULL" constraint has been seen on a column. This routine sets the notNull flag on the column currently under construction.
sqlite3AddColumnType
void sqlite3AddColumnType(Parse *pParse, Token *pType){ /* Table *p; */ /* int i; */ /* Column *pCol; */ /* if( (p = pParse->pNewTable)==0 ) return; */ /* i = p->nCol-1; */ /* if( i<0 ) return; */ /* pCol = &p->aCol[i]; */ /* sqliteFree(pCol->zType); */ /* pCol->zType = sqlite3NameFromToken(pType); */ /* pCol->affinity = sqlite3AffinityType(pType); */ }
/* ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. The pFirst token is the first ** token in the sequence of tokens that describe the type of the ** column currently under construction. pLast is the last token ** in the sequence. Use this information to construct a string ** that contains the typename of the column and store that string ** in zType. */
This routine is called by the parser while in the middle of parsing a CREATE TABLE statement. The pFirst token is the first token in the sequence of tokens that describe the type of the column currently under construction. pLast is the last token in the sequence. Use this information to construct a string that contains the typename of the column and store that string in zType.
sqlite3AddDefaultValue
void sqlite3AddDefaultValue(Parse *pParse, Expr *pExpr){ /* Table *p; */ /* Column *pCol; */ /* if( (p = pParse->pNewTable)!=0 ){ */ /* pCol = &(p->aCol[p->nCol-1]); */ /* if( !sqlite3ExprIsConstantOrFunction(pExpr) ){ */ /* sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant", */ /* pCol->zName); */ /* }else{ */ /* sqlite3ExprDelete(pCol->pDflt); */ /* pCol->pDflt = sqlite3ExprDup(pExpr); */ /* } */ /* } */ /* sqlite3ExprDelete(pExpr); */ }
/* ** The expression is the default value for the most recently added column ** of the table currently under construction. ** ** Default value expressions must be constant. Raise an exception if this ** is not the case. ** ** This routine is called by the parser while in the middle of ** parsing a CREATE TABLE statement. */
The expression is the default value for the most recently added column of the table currently under construction. Default value expressions must be constant. Raise an exception if this is not the case. This routine is called by the parser while in the middle of parsing a CREATE TABLE statement.
sqlite3AddPrimaryKey
void sqlite3AddPrimaryKey( Parse *pParse, /* Parsing context */ ExprList *pList, /* List of field names to be indexed */ int onError, /* What to do with a uniqueness conflict */ int autoInc, /* True if the AUTOINCREMENT keyword is present */ int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */ ){ /* Table *pTab = pParse->pNewTable; */ /* char *zType = 0; */ /* int iCol = -1, i; */ /* if( pTab==0 ) goto primary_key_exit; */ /* if( pTab->hasPrimKey ){ */ /* sqlite3ErrorMsg(pParse, */ /* "table \"%s\" has more than one primary key", pTab->zName); */ /* goto primary_key_exit; */ /* } */ /* pTab->hasPrimKey = 1; */ /* if( pList==0 ){ */ /* iCol = pTab->nCol - 1; */ /* pTab->aCol[iCol].isPrimKey = 1; */ /* }else{ */ /* for(i=0; i<pList->nExpr; i++){ */ /* for(iCol=0; iCol<pTab->nCol; iCol++){ */ /* if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){ */ /* break; */ /* } */ /* } */ /* if( iCol<pTab->nCol ){ */ /* pTab->aCol[iCol].isPrimKey = 1; */ /* } */ /* } */ /* if( pList->nExpr>1 ) iCol = -1; */ /* } */ /* if( iCol>=0 && iCol<pTab->nCol ){ */ /* zType = pTab->aCol[iCol].zType; */ /* } */ /* if( zType && sqlite3StrICmp(zType, "INTEGER")==0 */ /* && sortOrder==SQLITE_SO_ASC ){ */ /* pTab->iPKey = iCol; */ /* pTab->keyConf = onError; */ /* pTab->autoInc = autoInc; */ /* }else if( autoInc ){ */ /* #ifndef SQLITE_OMIT_AUTOINCREMENT */ /* sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " */ /* "INTEGER PRIMARY KEY"); */ /* #endif */ /* }else{ */ /* sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0); */ /* pList = 0; */ /* } */ /* primary_key_exit: */ /* sqlite3ExprListDelete(pList); */ /* return; */ }
/* ** Designate the PRIMARY KEY for the table. pList is a list of names ** of columns that form the primary key. If pList is NULL, then the ** most recently added column of the table is the primary key. ** ** A table can have at most one primary key. If the table already has ** a primary key (and this is the second primary key) then create an ** error. ** ** If the PRIMARY KEY is on a single column whose datatype is INTEGER, ** then we will try to use that column as the rowid. Set the Table.iPKey ** field of the table under construction to be the index of the ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is ** no INTEGER PRIMARY KEY. ** ** If the key is not an INTEGER PRIMARY KEY, then create a unique ** index for the key. No index is created for INTEGER PRIMARY KEYs. */
Designate the PRIMARY KEY for the table. pList is a list of names of columns that form the primary key. If pList is NULL, then the most recently added column of the table is the primary key. A table can have at most one primary key. If the table already has a primary key (and this is the second primary key) then create an error. If the PRIMARY KEY is on a single column whose datatype is INTEGER, then we will try to use that column as the rowid. Set the Table.iPKey field of the table under construction to be the index of the INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is no INTEGER PRIMARY KEY. If the key is not an INTEGER PRIMARY KEY, then create a unique index for the key. No index is created for INTEGER PRIMARY KEYs.
sqlite3AddCheckConstraint
void sqlite3AddCheckConstraint( Parse *pParse, /* Parsing context */ Expr *pCheckExpr /* The check expression */ ){ /* #ifndef SQLITE_OMIT_CHECK */ /* Table *pTab = pParse->pNewTable; */ /* if( pTab ){ */ /* /1* The CHECK expression must be duplicated so that tokens refer */ /* ** to malloced space and not the (ephemeral) text of the CREATE TABLE */ /* ** statement *1/ */ /* pTab->pCheck = sqlite3ExprAnd(pTab->pCheck, sqlite3ExprDup(pCheckExpr)); */ /* } */ /* #endif */ /* sqlite3ExprDelete(pCheckExpr); */ }
/* ** Add a new CHECK constraint to the table currently under construction. */
Add a new CHECK constraint to the table currently under construction.
sqlite3AddCollateType
void sqlite3AddCollateType(Parse *pParse, const char *zType, int nType){ /* Table *p; */ /* int i; */ /* if( (p = pParse->pNewTable)==0 ) return; */ /* i = p->nCol-1; */ /* if( sqlite3LocateCollSeq(pParse, zType, nType) ){ */ /* Index *pIdx; */ /* p->aCol[i].zColl = sqliteStrNDup(zType, nType); */ /* /1* If the column is declared as "<name> PRIMARY KEY COLLATE <type>", */ /* ** then an index may have been created on this column before the */ /* ** collation type was added. Correct this if it is the case. */ /* *1/ */ /* for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){ */ /* assert( pIdx->nColumn==1 ); */ /* if( pIdx->aiColumn[0]==i ){ */ /* pIdx->azColl[0] = p->aCol[i].zColl; */ /* } */ /* } */ /* } */ }
/* ** Set the collation function of the most recently parsed table column ** to the CollSeq given. */
Set the collation function of the most recently parsed table column to the CollSeq given.
sqlite3LocateCollSeq
CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName, int nName){ /* sqlite3 *db = pParse->db; */ /* u8 enc = ENC(db); */ /* u8 initbusy = db->init.busy; */ /* CollSeq *pColl; */ /* pColl = sqlite3FindCollSeq(db, enc, zName, nName, initbusy); */ /* if( !initbusy && (!pColl || !pColl->xCmp) ){ */ /* pColl = sqlite3GetCollSeq(db, pColl, zName, nName); */ /* if( !pColl ){ */ /* if( nName<0 ){ */ /* nName = strlen(zName); */ /* } */ /* sqlite3ErrorMsg(pParse, "no such collation sequence: %.*s", nName, zName); */ /* pColl = 0; */ /* } */ /* } */ /* return pColl; */ }
/* ** This function returns the collation sequence for database native text ** encoding identified by the string zName, length nName. ** ** If the requested collation sequence is not available, or not available ** in the database native encoding, the collation factory is invoked to ** request it. If the collation factory does not supply such a sequence, ** and the sequence is available in another text encoding, then that is ** returned instead. ** ** If no versions of the requested collations sequence are available, or ** another error occurs, NULL is returned and an error message written into ** pParse. */
This function returns the collation sequence for database native text encoding identified by the string zName, length nName. If the requested collation sequence is not available, or not available in the database native encoding, the collation factory is invoked to request it. If the collation factory does not supply such a sequence, and the sequence is available in another text encoding, then that is returned instead. If no versions of the requested collations sequence are available, or another error occurs, NULL is returned and an error message written into pParse.
identLength
static int identLength(const char *z){ int n; for(n=0; *z; n++, z++){ if( *z=='"' ){ n++; } } return n + 2; }
/* ** Measure the number of characters needed to output the given ** identifier. The number returned includes any quotes used ** but does not include the null terminator. ** ** The estimate is conservative. It might be larger that what is ** really needed. */
Measure the number of characters needed to output the given identifier. The number returned includes any quotes used but does not include the null terminator. The estimate is conservative. It might be larger that what is really needed.
sqlite3EndTable
void sqlite3EndTable( Parse *pParse, /* Parse context */ Token *pCons, /* The ',' token after the last column defn. */ Token *pEnd, /* The final ')' token in the CREATE TABLE */ Select *pSelect /* Select from a "CREATE ... AS SELECT" */ ){ /* Table *p; */ /* sqlite3 *db = pParse->db; */ /* int iDb; */ /* if( (pEnd==0 && pSelect==0) || pParse->nErr || sqlite3MallocFailed() ) { */ /* return; */ /* } */ /* p = pParse->pNewTable; */ /* if( p==0 ) return; */ /* assert( !db->init.busy || !pSelect ); */ /* iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); */ /* #ifndef SQLITE_OMIT_CHECK */ /* /1* Resolve names in all CHECK constraint expressions. */ /* *1/ */ /* if( p->pCheck ){ */ /* SrcList sSrc; /1* Fake SrcList for pParse->pNewTable *1/ */ /* NameContext sNC; /1* Name context for pParse->pNewTable *1/ */ /* memset(&sNC, 0, sizeof(sNC)); */ /* memset(&sSrc, 0, sizeof(sSrc)); */ /* sSrc.nSrc = 1; */ /* sSrc.a[0].zName = p->zName; */ /* sSrc.a[0].pTab = p; */ /* sSrc.a[0].iCursor = -1; */ /* sNC.pParse = pParse; */ /* sNC.pSrcList = &sSrc; */ /* sNC.isCheck = 1; */ /* if( sqlite3ExprResolveNames(&sNC, p->pCheck) ){ */ /* return; */ /* } */ /* } */ /* #endif /1* !defined(SQLITE_OMIT_CHECK) *1/ */ /* /1* If the db->init.busy is 1 it means we are reading the SQL off the */ /* ** "sqlite_master" or "sqlite_temp_master" table on the disk. */ /* ** So do not write to the disk again. Extract the root page number */ /* ** for the table from the db->init.newTnum field. (The page number */ /* ** should have been put there by the sqliteOpenCb routine.) */ /* *1/ */ /* if( db->init.busy ){ */ /* p->tnum = db->init.newTnum; */ /* } */ /* /1* If not initializing, then create a record for the new table */ /* ** in the SQLITE_MASTER table of the database. The record number */ /* ** for the new table entry should already be on the stack. */ /* ** */ /* ** If this is a TEMPORARY table, write the entry into the auxiliary */ /* ** file instead of into the main database file. */ /* *1/ */ /* if( !db->init.busy ){ */ /* int n; */ /* Vdbe *v; */ /* char *zType; /1* "view" or "table" *1/ */ /* char *zType2; /1* "VIEW" or "TABLE" *1/ */ /* char *zStmt; /1* Text of the CREATE TABLE or CREATE VIEW statement *1/ */ /* v = sqlite3GetVdbe(pParse); */ /* if( v==0 ) return; */ /* sqlite3VdbeAddOp(v, OP_Close, 0, 0); */ /* /1* Create the rootpage for the new table and push it onto the stack. */ /* ** A view has no rootpage, so just push a zero onto the stack for */ /* ** views. Initialize zType at the same time. */ /* *1/ */ /* if( p->pSelect==0 ){ */ /* /1* A regular table *1/ */ /* zType = "table"; */ /* zType2 = "TABLE"; */ /* #ifndef SQLITE_OMIT_VIEW */ /* }else{ */ /* /1* A view *1/ */ /* zType = "view"; */ /* zType2 = "VIEW"; */ /* #endif */ /* } */ /* /1* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT */ /* ** statement to populate the new table. The root-page number for the */ /* ** new table is on the top of the vdbe stack. */ /* ** */ /* ** Once the SELECT has been coded by sqlite3Select(), it is in a */ /* ** suitable state to query for the column names and types to be used */ /* ** by the new table. */ /* ** */ /* ** A shared-cache write-lock is not required to write to the new table, */ /* ** as a schema-lock must have already been obtained to create it. Since */ /* ** a schema-lock excludes all other database users, the write-lock would */ /* ** be redundant. */ /* *1/ */ /* if( pSelect ){ */ /* Table *pSelTab; */ /* sqlite3VdbeAddOp(v, OP_Dup, 0, 0); */ /* sqlite3VdbeAddOp(v, OP_Integer, iDb, 0); */ /* sqlite3VdbeAddOp(v, OP_OpenWrite, 1, 0); */ /* pParse->nTab = 2; */ /* sqlite3Select(pParse, pSelect, SRT_Table, 1, 0, 0, 0, 0); */ /* sqlite3VdbeAddOp(v, OP_Close, 1, 0); */ /* if( pParse->nErr==0 ){ */ /* pSelTab = sqlite3ResultSetOfSelect(pParse, 0, pSelect); */ /* if( pSelTab==0 ) return; */ /* assert( p->aCol==0 ); */ /* p->nCol = pSelTab->nCol; */ /* p->aCol = pSelTab->aCol; */ /* pSelTab->nCol = 0; */ /* pSelTab->aCol = 0; */ /* sqlite3DeleteTable(0, pSelTab); */ /* } */ /* } */ /* /1* Compute the complete text of the CREATE statement *1/ */ /* if( pSelect ){ */ /* zStmt = createTableStmt(p, p->pSchema==pParse->db->aDb[1].pSchema); */ /* }else{ */ /* n = pEnd->z - pParse->sNameToken.z + 1; */ /* zStmt = sqlite3MPrintf("CREATE %s %.*s", zType2, n, pParse->sNameToken.z); */ /* } */ /* /1* A slot for the record has already been allocated in the */ /* ** SQLITE_MASTER table. We just need to update that slot with all */ /* ** the information we've collected. The rowid for the preallocated */ /* ** slot is the 2nd item on the stack. The top of the stack is the */ /* ** root page for the new table (or a 0 if this is a view). */ /* *1/ */ /* sqlite3NestedParse(pParse, */ /* "UPDATE %Q.%s " */ /* "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#0, sql=%Q " */ /* "WHERE rowid=#1", */ /* db->aDb[iDb].zName, SCHEMA_TABLE(iDb), */ /* zType, */ /* p->zName, */ /* p->zName, */ /* zStmt */ /* ); */ /* sqliteFree(zStmt); */ /* sqlite3ChangeCookie(db, v, iDb); */ /* #ifndef SQLITE_OMIT_AUTOINCREMENT */ /* /1* Check to see if we need to create an sqlite_sequence table for */ /* ** keeping track of autoincrement keys. */ /* *1/ */ /* if( p->autoInc ){ */ /* Db *pDb = &db->aDb[iDb]; */ /* if( pDb->pSchema->pSeqTab==0 ){ */ /* sqlite3NestedParse(pParse, */ /* "CREATE TABLE %Q.sqlite_sequence(name,seq)", */ /* pDb->zName */ /* ); */ /* } */ /* } */ /* #endif */ /* /1* Reparse everything to update our internal data structures *1/ */ /* sqlite3VdbeOp3(v, OP_ParseSchema, iDb, 0, */ /* sqlite3MPrintf("tbl_name='%q'",p->zName), P3_DYNAMIC); */ /* } */ /* /1* Add the table to the in-memory representation of the database. */ /* *1/ */ /* if( db->init.busy && pParse->nErr==0 ){ */ /* Table *pOld; */ /* FKey *pFKey; */ /* Schema *pSchema = p->pSchema; */ /* pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, strlen(p->zName)+1,p); */ /* if( pOld ){ */ /* assert( p==pOld ); /1* Malloc must have failed inside HashInsert() *1/ */ /* return; */ /* } */ /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ /* for(pFKey=p->pFKey; pFKey; pFKey=pFKey->pNextFrom){ */ /* int nTo = strlen(pFKey->zTo) + 1; */ /* pFKey->pNextTo = sqlite3HashFind(&pSchema->aFKey, pFKey->zTo, nTo); */ /* sqlite3HashInsert(&pSchema->aFKey, pFKey->zTo, nTo, pFKey); */ /* } */ /* #endif */ /* pParse->pNewTable = 0; */ /* db->nTable++; */ /* db->flags |= SQLITE_InternChanges; */ /* #ifndef SQLITE_OMIT_ALTERTABLE */ /* if( !p->pSelect ){ */ /* const char *zName = (const char *)pParse->sNameToken.z; */ /* int nName; */ /* assert( !pSelect && pCons && pEnd ); */ /* if( pCons->z==0 ){ */ /* pCons = pEnd; */ /* } */ /* nName = (const char *)pCons->z - zName; */ /* p->addColOffset = 13 + sqlite3utf8CharLen(zName, nName); */ /* } */ /* #endif */ /* } */ }
/* ** This routine is called to report the final ")" that terminates ** a CREATE TABLE statement. ** ** The table structure that other action routines have been building ** is added to the internal hash tables, assuming no errors have ** occurred. ** ** An entry for the table is made in the master table on disk, unless ** this is a temporary table or db->init.busy==1. When db->init.busy==1 ** it means we are reading the sqlite_master table because we just ** connected to the database or because the sqlite_master table has ** recently changed, so the entry for this table already exists in ** the sqlite_master table. We do not want to create it again. ** ** If the pSelect argument is not NULL, it means that this routine ** was called to create a table generated from a ** "CREATE TABLE ... AS SELECT ..." statement. The column names of ** the new table will match the result set of the SELECT. */
This routine is called to report the final ")" that terminates a CREATE TABLE statement. The table structure that other action routines have been building is added to the internal hash tables, assuming no errors have occurred. An entry for the table is made in the master table on disk, unless this is a temporary table or db->init.busy==1. When db->init.busy==1 it means we are reading the sqlite_master table because we just connected to the database or because the sqlite_master table has recently changed, so the entry for this table already exists in the sqlite_master table. We do not want to create it again. If the pSelect argument is not NULL, it means that this routine was called to create a table generated from a "CREATE TABLE ... AS SELECT ..." statement. The column names of the new table will match the result set of the SELECT.
sqlite3CreateView
void sqlite3CreateView( Parse *pParse, /* The parsing context */ Token *pBegin, /* The CREATE token that begins the statement */ Token *pName1, /* The token that holds the name of the view */ Token *pName2, /* The token that holds the name of the view */ Select *pSelect, /* A SELECT statement that will become the new view */ int isTemp /* TRUE for a TEMPORARY view */ ){ /* Table *p; */ /* int n; */ /* const unsigned char *z; */ /* Token sEnd; */ /* DbFixer sFix; */ /* Token *pName; */ /* int iDb; */ /* if( pParse->nVar>0 ){ */ /* sqlite3ErrorMsg(pParse, "parameters are not allowed in views"); */ /* sqlite3SelectDelete(pSelect); */ /* return; */ /* } */ /* sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0); */ /* p = pParse->pNewTable; */ /* if( p==0 || pParse->nErr ){ */ /* sqlite3SelectDelete(pSelect); */ /* return; */ /* } */ /* sqlite3TwoPartName(pParse, pName1, pName2, &pName); */ /* iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema); */ /* if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName) */ /* && sqlite3FixSelect(&sFix, pSelect) */ /* ){ */ /* sqlite3SelectDelete(pSelect); */ /* return; */ /* } */ /* /1* Make a copy of the entire SELECT statement that defines the view. */ /* ** This will force all the Expr.token.z values to be dynamically */ /* ** allocated rather than point to the input string - which means that */ /* ** they will persist after the current sqlite3_exec() call returns. */ /* *1/ */ /* p->pSelect = sqlite3SelectDup(pSelect); */ /* sqlite3SelectDelete(pSelect); */ /* if( sqlite3MallocFailed() ){ */ /* return; */ /* } */ /* if( !pParse->db->init.busy ){ */ /* sqlite3ViewGetColumnNames(pParse, p); */ /* } */ /* /1* Locate the end of the CREATE VIEW statement. Make sEnd point to */ /* ** the end. */ /* *1/ */ /* sEnd = pParse->sLastToken; */ /* if( sEnd.z[0]!=0 && sEnd.z[0]!=';' ){ */ /* sEnd.z += sEnd.n; */ /* } */ /* sEnd.n = 0; */ /* n = sEnd.z - pBegin->z; */ /* z = (const unsigned char*)pBegin->z; */ /* while( n>0 && (z[n-1]==';' || isspace(z[n-1])) ){ n--; } */ /* sEnd.z = &z[n-1]; */ /* sEnd.n = 1; */ /* /1* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table *1/ */ /* sqlite3EndTable(pParse, 0, &sEnd, 0); */ /* return; */ }
/* ** The parser calls this routine in order to create a new VIEW */
The parser calls this routine in order to create a new VIEW
sqlite3DropTable
void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){ ParsedResultItem item; item.sqltype = SQLTYPE_DROP_TABLE; sqlite3ParsedResultArrayAppend(&pParse->parsed, &item); sqlite3SrcListDelete(pName); }
/* ** This routine is called to do the work of a DROP TABLE statement. ** pName is the name of the table to be dropped. */
This routine is called to do the work of a DROP TABLE statement. pName is the name of the table to be dropped.
sqlite3CreateForeignKey
void sqlite3CreateForeignKey( Parse *pParse, /* Parsing context */ ExprList *pFromCol, /* Columns in this table that point to other table */ Token *pTo, /* Name of the other table */ ExprList *pToCol, /* Columns in the other table */ int flags /* Conflict resolution algorithms. */ ){ /* #ifndef SQLITE_OMIT_FOREIGN_KEY */ /* FKey *pFKey = 0; */ /* Table *p = pParse->pNewTable; */ /* int nByte; */ /* int i; */ /* int nCol; */ /* char *z; */ /* assert( pTo!=0 ); */ /* if( p==0 || pParse->nErr ) goto fk_end; */ /* if( pFromCol==0 ){ */ /* int iCol = p->nCol-1; */ /* if( iCol<0 ) goto fk_end; */ /* if( pToCol && pToCol->nExpr!=1 ){ */ /* sqlite3ErrorMsg(pParse, "foreign key on %s" */ /* " should reference only one column of table %T", */ /* p->aCol[iCol].zName, pTo); */ /* goto fk_end; */ /* } */ /* nCol = 1; */ /* }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){ */ /* sqlite3ErrorMsg(pParse, */ /* "number of columns in foreign key does not match the number of " */ /* "columns in the referenced table"); */ /* goto fk_end; */ /* }else{ */ /* nCol = pFromCol->nExpr; */ /* } */ /* nByte = sizeof(*pFKey) + nCol*sizeof(pFKey->aCol[0]) + pTo->n + 1; */ /* if( pToCol ){ */ /* for(i=0; i<pToCol->nExpr; i++){ */ /* nByte += strlen(pToCol->a[i].zName) + 1; */ /* } */ /* } */ /* pFKey = sqliteMalloc( nByte ); */ /* if( pFKey==0 ) goto fk_end; */ /* pFKey->pFrom = p; */ /* pFKey->pNextFrom = p->pFKey; */ /* z = (char*)&pFKey[1]; */ /* pFKey->aCol = (struct sColMap*)z; */ /* z += sizeof(struct sColMap)*nCol; */ /* pFKey->zTo = z; */ /* memcpy(z, pTo->z, pTo->n); */ /* z[pTo->n] = 0; */ /* z += pTo->n+1; */ /* pFKey->pNextTo = 0; */ /* pFKey->nCol = nCol; */ /* if( pFromCol==0 ){ */ /* pFKey->aCol[0].iFrom = p->nCol-1; */ /* }else{ */ /* for(i=0; i<nCol; i++){ */ /* int j; */ /* for(j=0; j<p->nCol; j++){ */ /* if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){ */ /* pFKey->aCol[i].iFrom = j; */ /* break; */ /* } */ /* } */ /* if( j>=p->nCol ){ */ /* sqlite3ErrorMsg(pParse, */ /* "unknown column \"%s\" in foreign key definition", */ /* pFromCol->a[i].zName); */ /* goto fk_end; */ /* } */ /* } */ /* } */ /* if( pToCol ){ */ /* for(i=0; i<nCol; i++){ */ /* int n = strlen(pToCol->a[i].zName); */ /* pFKey->aCol[i].zCol = z; */ /* memcpy(z, pToCol->a[i].zName, n); */ /* z[n] = 0; */ /* z += n+1; */ /* } */ /* } */ /* pFKey->isDeferred = 0; */ /* pFKey->deleteConf = flags & 0xff; */ /* pFKey->updateConf = (flags >> 8 ) & 0xff; */ /* pFKey->insertConf = (flags >> 16 ) & 0xff; */ /* /1* Link the foreign key to the table as the last step. */ /* *1/ */ /* p->pFKey = pFKey; */ /* pFKey = 0; */ /* fk_end: */ /* sqliteFree(pFKey); */ /* #endif /1* !defined(SQLITE_OMIT_FOREIGN_KEY) *1/ */ /* sqlite3ExprListDelete(pFromCol); */ /* sqlite3ExprListDelete(pToCol); */ }
/* ** This routine is called to create a new foreign key on the table ** currently under construction. pFromCol determines which columns ** in the current table point to the foreign key. If pFromCol==0 then ** connect the key to the last column inserted. pTo is the name of ** the table referred to. pToCol is a list of tables in the other ** pTo table that the foreign key points to. flags contains all ** information about the conflict resolution algorithms specified ** in the ON DELETE, ON UPDATE and ON INSERT clauses. ** ** An FKey structure is created and added to the table currently ** under construction in the pParse->pNewTable field. The new FKey ** is not linked into db->aFKey at this point - that does not happen ** until sqlite3EndTable(). ** ** The foreign key is set for IMMEDIATE processing. A subsequent call ** to sqlite3DeferForeignKey() might change this to DEFERRED. */
This routine is called to create a new foreign key on the table currently under construction. pFromCol determines which columns in the current table point to the foreign key. If pFromCol==0 then connect the key to the last column inserted. pTo is the name of the table referred to. pToCol is a list of tables in the other pTo table that the foreign key points to. flags contains all information about the conflict resolution algorithms specified in the ON DELETE, ON UPDATE and ON INSERT clauses. An FKey structure is created and added to the table currently under construction in the pParse->pNewTable field. The new FKey is not linked into db->aFKey at this point - that does not happen until sqlite3EndTable(). The foreign key is set for IMMEDIATE processing. A subsequent call to sqlite3DeferForeignKey() might change this to DEFERRED.
sqlite3CreateIndex
void sqlite3CreateIndex( Parse *pParse, /* All information about this parse */ Token *pName1, /* First part of index name. May be NULL */ Token *pName2, /* Second part of index name. May be NULL */ SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */ ExprList *pList, /* A list of columns to be indexed */ int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */ Token *pStart, /* The CREATE token that begins a CREATE TABLE statement */ Token *pEnd, /* The ")" that closes the CREATE INDEX statement */ int sortOrder, /* Sort order of primary key when pList==NULL */ int ifNotExist /* Omit error if index already exists */ ){ sqlite3SrcListDelete(pTblName); sqlite3ExprListDelete(pList); }
/* ** Create a new index for an SQL table. pName1.pName2 is the name of the index ** and pTblList is the name of the table that is to be indexed. Both will ** be NULL for a primary key or an index that is created to satisfy a ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable ** as the table to be indexed. pParse->pNewTable is a table that is ** currently being constructed by a CREATE TABLE statement. ** ** pList is a list of columns to be indexed. pList will be NULL if this ** is a primary key or unique-constraint on the most recent column added ** to the table currently under construction. */
Create a new index for an SQL table. pName1.pName2 is the name of the index and pTblList is the name of the table that is to be indexed. Both will be NULL for a primary key or an index that is created to satisfy a UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable as the table to be indexed. pParse->pNewTable is a table that is currently being constructed by a CREATE TABLE statement. pList is a list of columns to be indexed. pList will be NULL if this is a primary key or unique-constraint on the most recent column added to the table currently under construction.
sqlite3DefaultRowEst
void sqlite3DefaultRowEst(Index *pIdx){ unsigned *a = pIdx->aiRowEst; int i; assert( a!=0 ); a[0] = 1000000; for(i=pIdx->nColumn; i>=1; i--){ a[i] = 10; } if( pIdx->onError!=OE_None ){ a[pIdx->nColumn] = 1; } }
/* ** Fill the Index.aiRowEst[] array with default information - information ** to be used when we have not run the ANALYZE command. ** ** aiRowEst[0] is suppose to contain the number of elements in the index. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the ** number of rows in the table that match any particular value of the ** first column of the index. aiRowEst[2] is an estimate of the number ** of rows that match any particular combiniation of the first 2 columns ** of the index. And so forth. It must always be the case that * ** aiRowEst[N]<=aiRowEst[N-1] ** aiRowEst[N]>=1 ** ** Apart from that, we have little to go on besides intuition as to ** how aiRowEst[] should be initialized. The numbers generated here ** are based on typical values found in actual indices. */
Fill the Index.aiRowEst[] array with default information - information to be used when we have not run the ANALYZE command. aiRowEst[0] is suppose to contain the number of elements in the index. Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the number of rows in the table that match any particular value of the first column of the index. aiRowEst[2] is an estimate of the number of rows that match any particular combiniation of the first 2 columns of the index. And so forth. It must always be the case that aiRowEst[N]<=aiRowEst[N-1] aiRowEst[N]>=1 Apart from that, we have little to go on besides intuition as to how aiRowEst[] should be initialized. The numbers generated here are based on typical values found in actual indices.
sqlite3DropIndex
void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){ /* Index *pIndex; */ /* Vdbe *v; */ /* sqlite3 *db = pParse->db; */ /* int iDb; */ /* if( pParse->nErr || sqlite3MallocFailed() ){ */ /* goto exit_drop_index; */ /* } */ /* assert( pName->nSrc==1 ); */ /* if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){ */ /* goto exit_drop_index; */ /* } */ /* pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase); */ /* if( pIndex==0 ){ */ /* if( !ifExists ){ */ /* sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0); */ /* } */ /* pParse->checkSchema = 1; */ /* goto exit_drop_index; */ /* } */ /* if( pIndex->autoIndex ){ */ /* sqlite3ErrorMsg(pParse, "index associated with UNIQUE " */ /* "or PRIMARY KEY constraint cannot be dropped", 0); */ /* goto exit_drop_index; */ /* } */ /* iDb = sqlite3SchemaToIndex(db, pIndex->pSchema); */ /* #ifndef SQLITE_OMIT_AUTHORIZATION */ /* { */ /* int code = SQLITE_DROP_INDEX; */ /* Table *pTab = pIndex->pTable; */ /* const char *zDb = db->aDb[iDb].zName; */ /* const char *zTab = SCHEMA_TABLE(iDb); */ /* if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){ */ /* goto exit_drop_index; */ /* } */ /* if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX; */ /* if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){ */ /* goto exit_drop_index; */ /* } */ /* } */ /* #endif */ /* /1* Generate code to remove the index and from the master table *1/ */ /* v = sqlite3GetVdbe(pParse); */ /* if( v ){ */ /* sqlite3NestedParse(pParse, */ /* "DELETE FROM %Q.%s WHERE name=%Q", */ /* db->aDb[iDb].zName, SCHEMA_TABLE(iDb), */ /* pIndex->zName */ /* ); */ /* sqlite3ChangeCookie(db, v, iDb); */ /* destroyRootPage(pParse, pIndex->tnum, iDb); */ /* sqlite3VdbeOp3(v, OP_DropIndex, iDb, 0, pIndex->zName, 0); */ /* } */ /* exit_drop_index: */ /* sqlite3SrcListDelete(pName); */ }
/* ** This routine will drop an existing named index. This routine ** implements the DROP INDEX statement. */
This routine will drop an existing named index. This routine implements the DROP INDEX statement.
sqlite3ArrayAllocate
int sqlite3ArrayAllocate(void **ppArray, int szEntry, int initSize){ char *p; int *an = (int*)&ppArray[1]; if( an[0]>=an[1] ){ void *pNew; int newSize; newSize = an[1]*2 + initSize; pNew = sqliteRealloc(*ppArray, newSize*szEntry); if( pNew==0 ){ return -1; } an[1] = newSize; *ppArray = pNew; } p = *ppArray; memset(&p[an[0]*szEntry], 0, szEntry); return an[0]++; }
/* ** ppArray points into a structure where there is an array pointer ** followed by two integers. The first integer is the ** number of elements in the structure array. The second integer ** is the number of allocated slots in the array. ** ** In other words, the structure looks something like this: ** ** struct Example1 { ** struct subElem *aEntry; ** int nEntry; ** int nAlloc; ** } ** ** The pnEntry parameter points to the equivalent of Example1.nEntry. ** ** This routine allocates a new slot in the array, zeros it out, ** and returns its index. If malloc fails a negative number is returned. ** ** szEntry is the sizeof of a single array entry. initSize is the ** number of array entries allocated on the initial allocation. */
ppArray points into a structure where there is an array pointer followed by two integers. The first integer is the number of elements in the structure array. The second integer is the number of allocated slots in the array. In other words, the structure looks something like this: struct Example1 { struct subElem *aEntry; int nEntry; int nAlloc; } The pnEntry parameter points to the equivalent of Example1.nEntry. This routine allocates a new slot in the array, zeros it out, and returns its index. If malloc fails a negative number is returned. szEntry is the sizeof of a single array entry. initSize is the number of array entries allocated on the initial allocation.
sqlite3IdListAppend
IdList *sqlite3IdListAppend(IdList *pList, Token *pToken){ int i; if( pList==0 ){ pList = sqliteMalloc( sizeof(IdList) ); if( pList==0 ) return 0; pList->nAlloc = 0; } i = sqlite3ArrayAllocate((void**)&pList->a, sizeof(pList->a[0]), 5); if( i<0 ){ sqlite3IdListDelete(pList); return 0; } pList->a[i].zName = sqlite3NameFromToken(pToken); return pList; }
/* ** Append a new element to the given IdList. Create a new IdList if ** need be. ** ** A new IdList is returned, or NULL if malloc() fails. */
Append a new element to the given IdList. Create a new IdList if need be. A new IdList is returned, or NULL if malloc() fails.
sqlite3IdListDelete
void sqlite3IdListDelete(IdList *pList){ int i; if( pList==0 ) return; for(i=0; i<pList->nId; i++){ sqliteFree(pList->a[i].zName); } sqliteFree(pList->a); sqliteFree(pList); }
/* ** Delete an IdList. */
Delete an IdList.
sqlite3IdListIndex
int sqlite3IdListIndex(IdList *pList, const char *zName){ int i; if( pList==0 ) return -1; for(i=0; i<pList->nId; i++){ if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i; } return -1; }
/* ** Return the index in pList of the identifier named zId. Return -1 ** if not found. */
Return the index in pList of the identifier named zId. Return -1 if not found.
sqlite3SrcListAssignCursors
void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){ int i; struct SrcList_item *pItem; assert(pList || sqlite3MallocFailed() ); if( pList ){ for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){ if( pItem->iCursor>=0 ) break; pItem->iCursor = pParse->nTab++; if( pItem->pSelect ){ sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc); } } } }
/* ** Assign cursors to all tables in a SrcList */
Assign cursors to all tables in a SrcList
sqlite3SrcListAddAlias
void sqlite3SrcListAddAlias(SrcList *pList, Token *pToken){ if( pList && pList->nSrc>0 ){ pList->a[pList->nSrc-1].zAlias = sqlite3NameFromToken(pToken); } }
/* ** Add an alias to the last identifier on the given identifier list. */
Add an alias to the last identifier on the given identifier list.
sqlite3SrcListDelete
void sqlite3SrcListDelete(SrcList *pList){ int i; struct SrcList_item *pItem; if( pList==0 ) return; for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){ sqliteFree(pItem->zDatabase); sqliteFree(pItem->zName); sqliteFree(pItem->zAlias); //sqlite3DeleteTable(0, pItem->pTab); sqlite3SelectDelete(pItem->pSelect); sqlite3ExprDelete(pItem->pOn); sqlite3IdListDelete(pItem->pUsing); } sqliteFree(pList); }
/* ** Delete an entire SrcList including all its substructure. */
Delete an entire SrcList including all its substructure.
sqlite3BeginTransaction
void sqlite3BeginTransaction(Parse *pParse, int type){ ParsedResultItem item; item.sqltype = type; sqlite3ParsedResultArrayAppend(&pParse->parsed, &item); }
/* ** Begin a transaction */
Begin a transaction
sqlite3CommitTransaction
void sqlite3CommitTransaction(Parse *pParse){ ParsedResultItem item; item.sqltype = SQLTYPE_TRANSACTION_COMMIT; sqlite3ParsedResultArrayAppend(&pParse->parsed, &item); }
/* ** Commit a transaction */
Commit a transaction
sqlite3RollbackTransaction
void sqlite3RollbackTransaction(Parse *pParse){ ParsedResultItem item; item.sqltype = SQLTYPE_TRANSACTION_ROLLBACK; sqlite3ParsedResultArrayAppend(&pParse->parsed, &item); }
/* ** Rollback a transaction */
Rollback a transaction
ParseTokenName
const char *ParseTokenName(int tokenType){ #ifndef NDEBUG if( tokenType>0 && tokenType<(sizeof(yyTokenName)/sizeof(yyTokenName[0])) ){ return yyTokenName[tokenType]; }else{ return "Unknown"; } #else return ""; #endif }
/* ** This function returns the symbolic name associated with a token ** value. */
This function returns the symbolic name associated with a token value.
ParseAlloc
void *ParseAlloc(void *(*mallocProc)(size_t)){ yyParser *pParser; pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) ); if( pParser ){ pParser->yyidx = -1; } return pParser; }
/* ** This function allocates a new parser. ** The only argument is a pointer to a function which works like ** malloc. ** ** Inputs: ** A pointer to the function used to allocate memory. ** ** Outputs: ** A pointer to a parser. This pointer is used in subsequent calls ** to Parse and ParseFree. */
This function allocates a new parser. The only argument is a pointer to a function which works like malloc. Inputs: A pointer to the function used to allocate memory. Outputs: A pointer to a parser. This pointer is used in subsequent calls to Parse and ParseFree.
yy_destructor
static void yy_destructor(YYCODETYPE yymajor, YYMINORTYPE *yypminor){ switch( yymajor ){ /* Here is inserted the actions which take place when a ** terminal or non-terminal is destroyed. This can happen ** when the symbol is popped from the stack during a ** reduce or during error processing or when a parser is ** being destroyed before it is finished parsing. ** ** Note: during a reduce, the only symbols destroyed are those ** which appear on the RHS of the rule, but which are not used ** inside the C code. */ %% default: break; /* If no destructor action specified: do nothing */ } }
/* The following function deletes the value associated with a ** symbol. The symbol can be either a terminal or nonterminal. ** "yymajor" is the symbol code, and "yypminor" is a pointer to ** the value. */
The following function deletes the value associated with a symbol. The symbol can be either a terminal or nonterminal. "yymajor" is the symbol code, and "yypminor" is a pointer to the value.
ParseFree
void ParseFree( void *p, /* The parser to be deleted */ void (*freeProc)(void*) /* Function used to reclaim memory */ ){ yyParser *pParser = (yyParser*)p; if( pParser==0 ) return; while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser); (*freeProc)((void*)pParser); }
/* ** Deallocate and destroy a parser. Destructors are all called for ** all stack elements before shutting the parser down. ** ** Inputs: ** <ul> ** <li> A pointer to the parser. This should be a pointer ** obtained from ParseAlloc. ** <li> A pointer to a function used to reclaim memory obtained ** from malloc. ** </ul> */
Deallocate and destroy a parser. Destructors are all called for all stack elements before shutting the parser down. Inputs: <ul> <li> A pointer to the parser. This should be a pointer obtained from ParseAlloc. <li> A pointer to a function used to reclaim memory obtained from malloc. </ul>
yy_parse_failed
static void yy_parse_failed( yyParser *yypParser /* The parser */ ){ ParseARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser fails */ %% ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ }
/* ** The following code executes when the parse fails */
The following code executes when the parse fails
yy_syntax_error
static void yy_syntax_error( yyParser *yypParser, /* The parser */ int yymajor, /* The major type of the error token */ YYMINORTYPE yyminor /* The minor type of the error token */ ){ ParseARG_FETCH; #define TOKEN (yyminor.yy0) %% ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ }
/* ** The following code executes when a syntax error first occurs. */
The following code executes when a syntax error first occurs.
yy_accept
static void yy_accept( yyParser *yypParser /* The parser */ ){ ParseARG_FETCH; #ifndef NDEBUG if( yyTraceFILE ){ fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt); } #endif while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser); /* Here code is inserted which will be executed whenever the ** parser accepts */ %% ParseARG_STORE; /* Suppress warning about unused %extra_argument variable */ }
/* ** The following is executed when the parser accepts */
The following is executed when the parser accepts
keywordCompare1
static int keywordCompare1(const void *a, const void *b){ const Keyword *pA = (Keyword*)a; const Keyword *pB = (Keyword*)b; int n = pA->len - pB->len; if( n==0 ){ n = strcmp(pA->zName, pB->zName); } return n; }
/* ** Comparision function for two Keyword records */
Comparision function for two Keyword records
findById
static Keyword *findById(int id){ int i; for(i=0; i<NKEYWORD; i++){ if( aKeywordTable[i].id==id ) break; } return &aKeywordTable[i]; }
/* ** Return a KeywordTable entry with the given id */
Return a KeywordTable entry with the given id
Action_new
struct action *Action_new(){ static struct action *freelist = 0; struct action *new; if( freelist==0 ){ int i; int amt = 100; freelist = (struct action *)malloc( sizeof(struct action)*amt ); if( freelist==0 ){ fprintf(stderr,"Unable to allocate memory for a new parser action."); exit(1); } for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1]; freelist[amt-1].next = 0; } new = freelist; freelist = freelist->next; return new; }
/* Allocate a new parser action */
Allocate a new parser action
Action_sort
struct action *Action_sort(ap) struct action *ap; { ap = (struct action *)msort((char *)ap,(char **)&ap->next,actioncmp); return ap; }
/* Sort parser actions */
Sort parser actions
acttab_free
void acttab_free(acttab *p){ free( p->aAction ); free( p->aLookahead ); free( p ); }
/* Free all memory associated with the given acttab */
Free all memory associated with the given acttab
acttab_alloc
acttab *acttab_alloc(void){ acttab *p = malloc( sizeof(*p) ); if( p==0 ){ fprintf(stderr,"Unable to allocate memory for a new acttab."); exit(1); } memset(p, 0, sizeof(*p)); return p; }
/* Allocate a new acttab structure */
Allocate a new acttab structure
myassert
void myassert(file,line) char *file; int line; { fprintf(stderr,"Assertion failed on line %d of file \"%s\"\n",line,file); exit(1); }
/* ** A more efficient way of handling assertions. */
A more efficient way of handling assertions.
same_symbol
int same_symbol(a,b) struct symbol *a; struct symbol *b; { int i; if( a==b ) return 1; if( a->type!=MULTITERMINAL ) return 0; if( b->type!=MULTITERMINAL ) return 0; if( a->nsubsym!=b->nsubsym ) return 0; for(i=0; i<a->nsubsym; i++){ if( a->subsym[i]!=b->subsym[i] ) return 0; } return 1; }
/* ** Return true if two symbols are the same. */
Return true if two symbols are the same.
newconfig
PRIVATE struct config *newconfig(){ struct config *new; if( freelist==0 ){ int i; int amt = 3; freelist = (struct config *)malloc( sizeof(struct config)*amt ); if( freelist==0 ){ fprintf(stderr,"Unable to allocate memory for a new configuration."); exit(1); } for(i=0; i<amt-1; i++) freelist[i].next = &freelist[i+1]; freelist[amt-1].next = 0; } new = freelist; freelist = freelist->next; return new; }
/* Return a pointer to a new configuration */
Return a pointer to a new configuration
deleteconfig
PRIVATE void deleteconfig(old) struct config *old; { old->next = freelist; freelist = old; }
/* The configuration "old" is no longer used */
The configuration "old" is no longer used
Configlist_init
void Configlist_init(){ current = 0; currentend = &current; basis = 0; basisend = &basis; Configtable_init(); return; }
/* Initialized the configuration list builder */
Initialized the configuration list builder
Configlist_reset
void Configlist_reset(){ current = 0; currentend = &current; basis = 0; basisend = &basis; Configtable_clear(0); return; }
/* Initialized the configuration list builder */
Initialized the configuration list builder
Configlist_add
struct config *Configlist_add(rp,dot) struct rule *rp; /* The rule */ int dot; /* Index into the RHS of the rule where the dot goes */ { struct config *cfp, model; assert( currentend!=0 ); model.rp = rp; model.dot = dot; cfp = Configtable_find(&model); if( cfp==0 ){ cfp = newconfig(); cfp->rp = rp; cfp->dot = dot; cfp->fws = SetNew(); cfp->stp = 0; cfp->fplp = cfp->bplp = 0; cfp->next = 0; cfp->bp = 0; *currentend = cfp; currentend = &cfp->next; Configtable_insert(cfp); } return cfp; }
/* Add another configuration to the configuration list */
Add another configuration to the configuration list
Configlist_sort
void Configlist_sort(){ current = (struct config *)msort((char *)current,(char **)&(current->next),Configcmp); currentend = 0; return; }
/* Sort the configuration list */
Sort the configuration list
Configlist_sortbasis
void Configlist_sortbasis(){ basis = (struct config *)msort((char *)current,(char **)&(current->bp),Configcmp); basisend = 0; return; }
/* Sort the basis configuration list */
Sort the basis configuration list
Configlist_return
struct config *Configlist_return(){ struct config *old; old = current; current = 0; currentend = 0; return old; }
/* Return a pointer to the head of the configuration list and ** reset the list */
Return a pointer to the head of the configuration list and reset the list
Configlist_basis
struct config *Configlist_basis(){ struct config *old; old = basis; basis = 0; basisend = 0; return old; }
/* Return a pointer to the head of the configuration list and ** reset the list */
Return a pointer to the head of the configuration list and reset the list
Configlist_eat
void Configlist_eat(cfp) struct config *cfp; { struct config *nextcfp; for(; cfp; cfp=nextcfp){ nextcfp = cfp->next; assert( cfp->fplp==0 ); assert( cfp->bplp==0 ); if( cfp->fws ) SetFree(cfp->fws); deleteconfig(cfp); } return; }
/* Free all elements of the given configuration list */
Free all elements of the given configuration list
findbreak
static int findbreak(msg,min,max) char *msg; int min; int max; { int i,spot; char c; for(i=spot=min; i<=max; i++){ c = msg[i]; if( c=='\t' ) msg[i] = ' '; if( c=='\n' ){ msg[i] = ' '; spot = i; break; } if( c==0 ){ spot = i; break; } if( c=='-' && i<max-1 ) spot = i+1; if( c==' ' ) spot = i; } return spot; }
/* Find a good place to break "msg" so that its length is at least "min" ** but no more than "max". Make the point as close to max as possible. */
Find a good place to break "msg" so that its length is at least "min" but no more than "max". Make the point as close to max as possible.
memory_error
void memory_error(){ fprintf(stderr,"Out of memory. Aborting...\n"); exit(1); }
/* Report an out-of-memory condition and abort. This function ** is used mostly by the "MemoryCheck" macro in struct.h */
Report an out-of-memory condition and abort. This function is used mostly by the "MemoryCheck" macro in struct.h
handle_D_option
static void handle_D_option(char *z){ char **paz; nDefine++; azDefine = realloc(azDefine, sizeof(azDefine[0])*nDefine); if( azDefine==0 ){ fprintf(stderr,"out of memory\n"); exit(1); } paz = &azDefine[nDefine-1]; *paz = malloc( strlen(z)+1 ); if( *paz==0 ){ fprintf(stderr,"out of memory\n"); exit(1); } strcpy(*paz, z); for(z=*paz; *z && *z!='='; z++){} *z = 0; }
/* This routine is called with the argument to each -D command-line option. ** Add the macro defined to the azDefine array. */
This routine is called with the argument to each -D command-line option. Add the macro defined to the azDefine array.
argindex
static int argindex(n) int n; { int i; int dashdash = 0; if( argv!=0 && *argv!=0 ){ for(i=1; argv[i]; i++){ if( dashdash || !ISOPT(argv[i]) ){ if( n==0 ) return i; n--; } if( strcmp(argv[i],"--")==0 ) dashdash = 1; } } return -1; }
/* ** Return the index of the N-th non-switch argument. Return -1 ** if N is out of range. */
Return the index of the N-th non-switch argument. Return -1 if N is out of range.
Plink_new
struct plink *Plink_new(){ struct plink *new; if( plink_freelist==0 ){ int i; int amt = 100; plink_freelist = (struct plink *)malloc( sizeof(struct plink)*amt ); if( plink_freelist==0 ){ fprintf(stderr, "Unable to allocate memory for a new follow-set propagation link.\n"); exit(1); } for(i=0; i<amt-1; i++) plink_freelist[i].next = &plink_freelist[i+1]; plink_freelist[amt-1].next = 0; } new = plink_freelist; plink_freelist = plink_freelist->next; return new; }
/* Allocate a new plink */
Allocate a new plink
Plink_add
void Plink_add(plpp,cfp) struct plink **plpp; struct config *cfp; { struct plink *new; new = Plink_new(); new->next = *plpp; *plpp = new; new->cfp = cfp; }
/* Add a plink to a plink list */
Add a plink to a plink list
Plink_copy
void Plink_copy(to,from) struct plink **to; struct plink *from; { struct plink *nextpl; while( from ){ nextpl = from->next; from->next = *to; *to = from; from = nextpl; } }
/* Transfer every plink on the list "from" to the list "to" */
Transfer every plink on the list "from" to the list "to"
Plink_delete
void Plink_delete(plp) struct plink *plp; { struct plink *nextpl; while( plp ){ nextpl = plp->next; plp->next = plink_freelist; plink_freelist = plp; plp = nextpl; } }
/* Delete every plink on the list */
Delete every plink on the list
file_makename
PRIVATE char *file_makename(lemp,suffix) struct lemon *lemp; char *suffix; { char *name; char *cp; name = malloc( strlen(lemp->filename) + strlen(suffix) + 5 ); if( name==0 ){ fprintf(stderr,"Can't allocate space for a filename.\n"); exit(1); } strcpy(name,lemp->filename); cp = strrchr(name,'.'); if( cp ) *cp = 0; strcat(name,suffix); return name; }
/* Generate a filename with the given suffix. Space to hold the ** name comes from malloc() and must be freed by the calling ** function. */
Generate a filename with the given suffix. Space to hold the name comes from malloc() and must be freed by the calling function.
tplt_linedir
PRIVATE void tplt_linedir(out,lineno,filename) FILE *out; int lineno; char *filename; { fprintf(out,"#line %d \"",lineno); while( *filename ){ if( *filename == '\\' ) putc('\\',out); putc(*filename,out); filename++; } fprintf(out,"\"\n"); }
/* Print a #line directive line to the output file. */
Print a #line directive line to the output file.
has_destructor
int has_destructor(sp, lemp) struct symbol *sp; struct lemon *lemp; { int ret; if( sp->type==TERMINAL ){ ret = lemp->tokendest!=0; }else{ ret = lemp->vardest!=0 || sp->destructor!=0; } return ret; }
/* ** Return TRUE (non-zero) if the given symbol has a destructor. */
Return TRUE (non-zero) if the given symbol has a destructor.
emit_code
PRIVATE void emit_code(out,rp,lemp,lineno) FILE *out; struct rule *rp; struct lemon *lemp; int *lineno; { char *cp; int linecnt = 0; /* Generate code to do the reduce action */ if( rp->code ){ tplt_linedir(out,rp->line,lemp->filename); fprintf(out,"{%s",rp->code); for(cp=rp->code; *cp; cp++){ if( *cp=='\n' ) linecnt++; } /* End loop */ (*lineno) += 3 + linecnt; fprintf(out,"}\n"); tplt_linedir(out,*lineno,lemp->outname); } /* End if( rp->code ) */ return; }
/* ** Generate code which executes when the rule "rp" is reduced. Write ** the code to "out". Make sure lineno stays up-to-date. */
Generate code which executes when the rule "rp" is reduced. Write the code to "out". Make sure lineno stays up-to-date.
minimum_size_type
static const char *minimum_size_type(int lwr, int upr){ if( lwr>=0 ){ if( upr<=255 ){ return "unsigned char"; }else if( upr<65535 ){ return "unsigned short int"; }else{ return "unsigned int"; } }else if( lwr>=-127 && upr<=127 ){ return "signed char"; }else if( lwr>=-32767 && upr<32767 ){ return "short"; }else{ return "int"; } }
/* ** Return the name of a C datatype able to represent values between ** lwr and upr, inclusive. */
Return the name of a C datatype able to represent values between lwr and upr, inclusive.
axset_compare
static int axset_compare(const void *a, const void *b){ struct axset *p1 = (struct axset*)a; struct axset *p2 = (struct axset*)b; return p2->nAction - p1->nAction; }
/* ** Compare to axset structures for sorting purposes */
Compare to axset structures for sorting purposes
stateResortCompare
static int stateResortCompare(const void *a, const void *b){ const struct state *pA = *(const struct state**)a; const struct state *pB = *(const struct state**)b; int n; n = pB->nNtAct - pA->nNtAct; if( n==0 ){ n = pB->nTknAct - pA->nTknAct; } return n; }
/* ** Compare two states for sorting purposes. The smaller state is the ** one with the most non-terminal actions. If they have the same number ** of non-terminal actions, then the smaller is the one with the most ** token actions. */
Compare two states for sorting purposes. The smaller state is the one with the most non-terminal actions. If they have the same number of non-terminal actions, then the smaller is the one with the most token actions.
SetSize
void SetSize(n) int n; { size = n+1; }
/* Set the set size */
Set the set size
SetNew
char *SetNew(){ char *s; int i; s = (char*)malloc( size ); if( s==0 ){ extern void memory_error(); memory_error(); } for(i=0; i<size; i++) s[i] = 0; return s; }
/* Allocate a new set */
Allocate a new set
SetFree
void SetFree(s) char *s; { free(s); }
/* Deallocate a set */
Deallocate a set
SetAdd
int SetAdd(s,e) char *s; int e; { int rv; rv = s[e]; s[e] = 1; return !rv; }
/* Add a new element to the set. Return TRUE if the element was added ** and FALSE if it was already there. */
Add a new element to the set. Return TRUE if the element was added and FALSE if it was already there.
SetUnion
int SetUnion(s1,s2) char *s1; char *s2; { int i, progress; progress = 0; for(i=0; i<size; i++){ if( s2[i]==0 ) continue; if( s1[i]==0 ){ progress = 1; s1[i] = 1; } } return progress; }
/* Add every element of s2 to s1. Return TRUE if s1 changes. */
Add every element of s2 to s1. Return TRUE if s1 changes.
strhash
PRIVATE int strhash(x) char *x; { int h = 0; while( *x) h = h*13 + *(x++); return h; }
/* ** Code for processing tables in the LEMON parser generator. */
Code for processing tables in the LEMON parser generator.
Strsafe
char *Strsafe(y) char *y; { char *z; z = Strsafe_find(y); if( z==0 && (z=malloc( strlen(y)+1 ))!=0 ){ strcpy(z,y); Strsafe_insert(z); } MemoryCheck(z); return z; }
/* Works like strdup, sort of. Save a string in malloced memory, but ** keep strings in a table so that the same string is not in more ** than one place. */
Works like strdup, sort of. Save a string in malloced memory, but keep strings in a table so that the same string is not in more than one place.
Strsafe_init
void Strsafe_init(){ if( x1a ) return; x1a = (struct s_x1*)malloc( sizeof(struct s_x1) ); if( x1a ){ x1a->size = 1024; x1a->count = 0; x1a->tbl = (x1node*)malloc( (sizeof(x1node) + sizeof(x1node*))*1024 ); if( x1a->tbl==0 ){ free(x1a); x1a = 0; }else{ int i; x1a->ht = (x1node**)&(x1a->tbl[1024]); for(i=0; i<1024; i++) x1a->ht[i] = 0; } } }
/* Allocate a new associative array */
Allocate a new associative array
Strsafe_find
char *Strsafe_find(key) char *key; { int h; x1node *np; if( x1a==0 ) return 0; h = strhash(key) & (x1a->size-1); np = x1a->ht[h]; while( np ){ if( strcmp(np->data,key)==0 ) break; np = np->next; } return np ? np->data : 0; }
/* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */
Return a pointer to data assigned to the given key. Return NULL if no such key.
Symbol_init
void Symbol_init(){ if( x2a ) return; x2a = (struct s_x2*)malloc( sizeof(struct s_x2) ); if( x2a ){ x2a->size = 128; x2a->count = 0; x2a->tbl = (x2node*)malloc( (sizeof(x2node) + sizeof(x2node*))*128 ); if( x2a->tbl==0 ){ free(x2a); x2a = 0; }else{ int i; x2a->ht = (x2node**)&(x2a->tbl[128]); for(i=0; i<128; i++) x2a->ht[i] = 0; } } }
/* Allocate a new associative array */
Allocate a new associative array
Symbol_find
struct symbol *Symbol_find(key) char *key; { int h; x2node *np; if( x2a==0 ) return 0; h = strhash(key) & (x2a->size-1); np = x2a->ht[h]; while( np ){ if( strcmp(np->key,key)==0 ) break; np = np->next; } return np ? np->data : 0; }
/* Return a pointer to data assigned to the given key. Return NULL ** if no such key. */
Return a pointer to data assigned to the given key. Return NULL if no such key.
Symbol_Nth
struct symbol *Symbol_Nth(n) int n; { struct symbol *data; if( x2a && n>0 && n<=x2a->count ){ data = x2a->tbl[n-1].data; }else{ data = 0; } return data; }
/* Return the n-th data. Return NULL if n is out of range. */
Return the n-th data. Return NULL if n is out of range.
Symbol_count
int Symbol_count() { return x2a ? x2a->count : 0; }
/* Return the size of the array */
Return the size of the array