www.pudn.com > TurboPadSource.tar.gz > syntax.cpp
/**
* \file Syntax Implementation
*
* Implementation of Syntax functions.
*/
#include "syntax.h"
Syntax::Syntax()
{
preprocessor = false;
keyWords.resize(9);
}
void Syntax::Clear()
{
languageName = "";
blockComment = "";
streamStart = "";
streamEnd = "";
preprocessor = false;
for (int i = 0; (unsigned int) i < keyWords.size(); i++)
keyWords[i] = "";
}
bool Syntax::HasComment()
{
return HasBlockComment() || HasStreamComment();
}
bool Syntax::HasIndentationWord(const wxString &line)
{
if (line == "" || line == " ") return false;
wxStringTokenizer stringTok(indentWords, " ");
wxString token;
int tokenLoc;
while (stringTok.HasMoreTokens())
{
token = stringTok.GetNextToken();
if ((tokenLoc = line.Find(token)) != -1)
{
if (line.Contains((blockComment.BeforeLast(' ')))
|| line.Contains(streamStart)
|| line.Contains(streamEnd)
|| line.AfterLast(')').Contains(statementEnd) // \todo Don't assume ( and ) groups statements
|| (preprocessor && line.Contains("#")))
return false; // \todo Make sure the word is not in a string
else
return true;
}
}
return false;
}
bool Syntax::HasStreamComment()
{
return streamStart != "" && streamEnd != "";
}
// \todo These things should be loaded from external files
void Syntax::Initialize(int lang)
{
Clear();
switch (lang)
{
case Ada:
languageName = "Ada";
keyWords[0] =
"abort abstract accept access aliased all array at begin body "
"case constant declare delay delta digits do else elsif end entry exception exit for "
"function generic goto if in is limited loop new null of others out package pragma "
"private procedure protected raise range record renames requeue return reverse "
"select separate subtype tagged task terminate then type until use when while with ";
indentWords = "begin declare else elsif exception for if is loop while";
blockComment = "-- ";
streamStart = "";
streamEnd = "";
statementEnd = ";";
preprocessor = false;
break;
case CPP:
languageName = "C++";
keyWords[0] =
"asm auto bool break case catch char class const const_cast continue "
"default delete do double dynamic_cast else enum explicit export extern false float for "
"friend goto if inline int long mutable namespace new operator private protected public "
"register reinterpret_cast return short signed sizeof static static_cast struct switch "
"template this throw true try typedef typeid typename union unsigned using "
"virtual void volatile wchar_t while";
keyWords[2] =
"a addindex addtogroup anchor arg attention author "
"b brief bug c class code copydoc date def defgroup "
"deprecated dontinclude dotfile e else elseif em "
"endcode endhtmlonly endif endlatexonly endlink endverbatim "
"enum example exception f$ f[ f] file fn hideinitializer "
"htmlinclude htmlonly if ifnot image include ingroup "
"internal invariant interface latexonly li line link "
"mainpage n name namespace nosubgrouping note overload "
"p package page par param post pre ref relates "
"remarks return retval sa section showinitializer "
"since skip skipline struct subsection subsubsection test "
"throw todo typedef union until var verbatim verbinclude "
"version warning weakgroup $ @ & ~ < > # ";
indentWords =
"case catch class default do else for if "
"private protected public struct try union while";
blockComment = "// ";
streamStart = "/*";
streamEnd = "*/";
statementEnd = ";";
preprocessor = true;
break;
case DosBatch:
languageName = "Dos Batch";
keyWords[0] =
"rem set if exist errorlevel for in do "
"break call chcp cd chdir choice cls country ctty date del erase dir echo "
"exit goto loadfix loadhigh mkdir md move path pause prompt rename ren "
"rmdir rd shift time type ver verify vol "
"com con lpt nul";
indentWords = "";
blockComment = "rem ";
streamStart = "";
streamEnd = "";
statementEnd = "";
preprocessor = false;
break;
case Eiffel:
languageName = "Eiffel";
keyWords[0] =
"alias all and any as bit boolean "
"check class character clone create creation current "
"debug deferred div do double "
"else elseif end ensure equal expanded export external "
"false feature forget from frozen general "
"if implies indexing infix inherit inspect integer invariant is "
"language like local loop mod name nochange none not "
"obsolete old once or platform pointer prefix precursor "
"real redefine rename require rescue result retry "
"select separate string strip then true undefine unique until "
"variant void when xor";
indentWords = "do else elsif rescue if is loop";
blockComment = "--";
streamStart = "";
streamEnd = "";
statementEnd = ";";
preprocessor = false;
break;
case Fortran:
languageName = "Fortran";
keyWords[0] =
"allocatable allocate assignment backspace block "
"blockdata call case character close common complex contains continue "
"cycle data deallocate default dimension direct do double doubleprecision "
"elemental else elseif elsewhere end endblock endblockdata enddo endfile "
"endforall endfunction endif endinterface endmodule endprogram endselect "
"endsubroutine endtype endwhere entry equivalence err exist exit external forall "
"format formatted function go goto if implicit in inout include "
"inquire integer intent interface intrinsic iolength iostat kind "
"len logical module namelist none null nullify only open operator optional "
"parameter pointer position precision print private procedure program public pure "
"out read readwrite real rec recursive result return rewind save select selectcase "
"sequence sequential stat status "
"stop subroutine target then to type unformatted unit use where while write ";
indentWords =
"associate block blockdata case do enum forall "
"function interface module program subroutine then type where";
blockComment = "! ";
streamStart = "";
streamEnd = "";
statementEnd = "end";
preprocessor = false;
break;
case HTML:
languageName = "HTML";
keyWords[0] =
"a abbr acronym address applet area b base basefont "
"bdo big blockquote body br button caption center "
"cite code col colgroup dd del dfn dir div dl dt em "
"fieldset font form frame frameset h1 h2 h3 h4 h5 h6 "
"head hr html i iframe img input ins isindex kbd label "
"legend li link map menu meta noframes noscript "
"object ol optgroup option p param pre q s samp "
"script select small span strike strong style sub sup "
"table tbody td textarea tfoot th thead title tr tt u ul "
"var xml xmlns "
// Attributes
"abbr accept-charset accept accesskey action align alink "
"alt archive axis background bgcolor border "
"cellpadding cellspacing char charoff charset checked cite "
"class classid clear codebase codetype color cols colspan "
"compact content coords "
"data datafld dataformatas datapagesize datasrc datetime "
"declare defer dir disabled enctype event "
"face for frame frameborder "
"headers height href hreflang hspace http-equiv "
"id ismap label lang language leftmargin link longdesc "
"marginwidth marginheight maxlength media method multiple "
"name nohref noresize noshade nowrap "
"object onblur onchange onclick ondblclick onfocus "
"onkeydown onkeypress onkeyup onload onmousedown "
"onmousemove onmouseover onmouseout onmouseup "
"onreset onselect onsubmit onunload "
"profile prompt readonly rel rev rows rowspan rules "
"scheme scope selected shape size span src standby start style "
"summary tabindex target text title topmargin type usemap "
"valign value valuetype version vlink vspace width "
"text password checkbox radio submit reset "
"file hidden image "
// Other Keywords
"public !doctype";
keyWords[4] =
"and argv as argc break case cfunction class continue declare default do "
"die echo else elseif empty enddeclare endfor endforeach endif endswitch "
"endwhile e_all e_parse e_error e_warning eval exit extends false for "
"foreach function global http_cookie_vars http_get_vars http_post_vars "
"http_post_files http_env_vars http_server_vars if include include_once "
"list new not null old_function or parent php_os php_self php_version "
"print require require_once return static switch stdclass this true var "
"xor virtual while __file__ __line__ __sleep __wakeup";
indentWords = "";
blockComment = "";
streamStart = "";
statementEnd = "";
preprocessor = false;
break;
case Java:
languageName = "Java";
keyWords[0] =
"abstract assert boolean break byte case catch char class "
"const continue default do double else extends final finally float for future "
"generic goto if implements import inner instanceof int interface long "
"native new null outer package private protected public rest "
"return short static super switch synchronized this throw throws "
"transient try var void volatile while";
indentWords =
"case catch class default do else for if "
"private protected public struct try union while";
blockComment = "// ";
streamStart = "/*";
streamEnd = "*/";
statementEnd = ";";
preprocessor = false; // ??
break;
case Javascript:
languageName = "Javascript";
keyWords[0] =
"abstract boolean break byte case catch char class "
"const continue debugger default delete do double else enum export extends "
"final finally float for function goto if implements import in instanceof "
"int interface long native new package private protected public "
"return short static super switch synchronized this throw throws "
"transient try typeof var void volatile while with";
indentWords =
"case catch class default do else for if "
"private protected public struct try union while";
blockComment = "// ";
streamStart = "/*";
streamEnd = "*/";
statementEnd = ";";
preprocessor = false; // ??
break;
case Pascal:
languageName = "Pascal";
keyWords[0] =
"program const type var begin end array set packed record string if then else "
"while for to downto do with repeat until case of goto exit label procedure "
"function nil file and or not xor div mod unit uses implementation interface "
"external asm inline object constructor destructor virtual far assembler near "
"inherited stdcall cdecl library export exports end. "
"class ansistring raise try except on index name finally "
"resourcestring false true initialization finalization override";
indentWords =
"case catch class default do else for then "
"private protected public struct try union while type";
blockComment = "// ";
streamStart = "{";
streamEnd = "}";
statementEnd = ";";
preprocessor = false;
break;
case Perl:
languageName = "Perl";
keyWords[0] =
"NULL __FILE__ __LINE__ __PACKAGE__ __DATA__ __END__ AUTOLOAD "
"BEGIN CORE DESTROY END EQ GE GT INIT LE LT NE CHECK abs accept "
"alarm and atan2 bind binmode bless caller chdir chmod chomp chop "
"chown chr chroot close closedir cmp connect continue cos crypt "
"dbmclose dbmopen defined delete die do dump each else elsif endgrent "
"endhostent endnetent endprotoent endpwent endservent eof eq eval "
"exec exists exit exp fcntl fileno flock for foreach fork format "
"formline ge getc getgrent getgrgid getgrnam gethostbyaddr gethostbyname "
"gethostent getlogin getnetbyaddr getnetbyname getnetent getpeername "
"getpgrp getppid getpriority getprotobyname getprotobynumber getprotoent "
"getpwent getpwnam getpwuid getservbyname getservbyport getservent "
"getsockname getsockopt glob gmtime goto grep gt hex if index "
"int ioctl join keys kill last lc lcfirst le length link listen "
"local localtime lock log lstat lt m map mkdir msgctl msgget msgrcv "
"msgsnd my ne next no not oct open opendir or ord our pack package "
"pipe pop pos print printf prototype push q qq qr quotemeta qu "
"qw qx rand read readdir readline readlink readpipe recv redo "
"ref rename require reset return reverse rewinddir rindex rmdir "
"s scalar seek seekdir select semctl semget semop send setgrent "
"sethostent setnetent setpgrp setpriority setprotoent setpwent "
"setservent setsockopt shift shmctl shmget shmread shmwrite shutdown "
"sin sleep socket socketpair sort splice split sprintf sqrt srand "
"stat study sub substr symlink syscall sysopen sysread sysseek "
"system syswrite tell telldir tie tied time times tr truncate "
"uc ucfirst umask undef unless unlink unpack unshift untie until "
"use utime values vec wait waitpid wantarray warn while write x xor y";
indentWords = "";
blockComment = "# ";
streamStart = "";
streamEnd = "";
statementEnd = "";
preprocessor = false;
break;
case PHP:
languageName = "PHP";
keyWords[0] =
"and argv as argc break case cfunction class continue declare default do "
"die echo else elseif empty enddeclare endfor endforeach endif endswitch "
"endwhile e_all e_parse e_error e_warning eval exit extends false for "
"foreach function global http_cookie_vars http_get_vars http_post_vars "
"http_post_files http_env_vars http_server_vars if include include_once "
"list new not null old_function or parent php_os php_self php_version "
"print require require_once return static switch stdclass this true var "
"xor virtual while __file__ __line__ __sleep __wakeup";
indentWords = "";
blockComment = "// ";
streamStart = "/*";
streamEnd = "*/";
statementEnd = "";
preprocessor = false;
break;
case Python:
languageName = "Python";
keyWords[0] =
"and assert break class continue def del elif "
"else except exec finally for from global if import in is lambda None "
"not or pass print raise return try while yield";
indentWords = ":";
blockComment = "# ";
streamStart = "";
streamEnd = "";
statementEnd = "";
preprocessor = false;
break;
case Ruby:
languageName = "Ruby";
keyWords[0] =
"__FILE__ and def end in or self unless __LINE__ begin "
"defined? ensure module redo super until BEGIN break do false next rescue "
"then when END case else for nil require retry true while alias class elsif if "
"not return undef yield";
indentWords = "";
blockComment = "# ";
streamStart = "";
streamEnd = "";
statementEnd = "";
preprocessor = false;
break;
case SQL:
languageName = "SQL";
keyWords[0] =
"ABSOLUTE ACTION ADD ADMIN AFTER AGGREGATE "
"ALIAS ALL ALLOCATE ALTER AND ANY ARE ARRAY AS ASC "
"ASSERTION AT AUTHORIZATION BEFORE BEGIN "
"BINARY BIT BLOB BOOLEAN BOTH BREADTH BY "
"CALL CASCADE CASCADED CASE CAST CATALOG CHAR CHARACTER "
"CHECK CLASS CLOB CLOSE COLLATE COLLATION COLUMN COMMIT "
"COMPLETION CONNECT CONNECTION CONSTRAINT CONSTRAINTS "
"CONSTRUCTOR CONTINUE CORRESPONDING CREATE CROSS CUBE CURRENT "
"CURRENT_DATE CURRENT_PATH CURRENT_ROLE CURRENT_TIME CURRENT_TIMESTAMP "
"CURRENT_USER CURSOR CYCLE DATA DATE DAY "
"DEALLOCATE DEC DECIMAL DECLARE DEFAULT "
"DEFERRABLE DEFERRED DELETE DEPTH DEREF DESC DESCRIBE DESCRIPTOR "
"DESTROY DESTRUCTOR DETERMINISTIC DICTIONARY DIAGNOSTICS DISCONNECT DISTINCT "
"DOMAIN DOUBLE DROP DYNAMIC EACH ELSE END END-EXEC "
"EQUALS ESCAPE EVERY EXCEPT EXCEPTION EXEC EXECUTE EXTERNAL "
"FALSE FETCH FIRST FLOAT FOR FOREIGN FOUND FROM FREE FULL FUNCTION "
"GENERAL GET GLOBAL GO GOTO GRANT GROUP GROUPING HAVING HOST HOUR "
"IDENTITY IGNORE IMMEDIATE IN INDICATOR INITIALIZE INITIALLY "
"INNER INOUT INPUT INSERT INT INTEGER INTERSECT INTERVAL "
"INTO IS ISOLATION ITERATE JOIN KEY "
"LANGUAGE LARGE LAST LATERAL LEADING LEFT LESS LEVEL LIKE "
"LIMIT LOCAL LOCALTIME LOCALTIMESTAMP LOCATOR "
"MAP MATCH MINUTE MODIFIES MODIFY MODULE MONTH "
"NAMES NATIONAL NATURAL NCHAR NCLOB NEW NEXT NO NONE "
"NOT NULL NUMERIC OBJECT OF OFF OLD ON ONLY OPEN OPERATION OPTION "
"OR ORDER ORDINALITY OUT OUTER OUTPUT "
"PAD PARAMETER PARAMETERS PARTIAL PATH POSTFIX PRECISION PREFIX "
"PREORDER PREPARE PRESERVE PRIMARY "
"PRIOR PRIVILEGES PROCEDURE PUBLIC "
"READ READS REAL RECURSIVE REF REFERENCES REFERENCING RELATIVE "
"RESTRICT RESULT RETURN RETURNS REVOKE RIGHT "
"ROLE ROLLBACK ROLLUP ROUTINE ROW ROWS "
"SAVEPOINT SCHEMA SCROLL SCOPE SEARCH SECOND SECTION SELECT "
"SEQUENCE SESSION SESSION_USER SET SETS SIZE SMALLINT SOME| SPACE "
"SPECIFIC SPECIFICTYPE SQL SQLEXCEPTION SQLSTATE SQLWARNING START "
"STATE STATEMENT STATIC STRUCTURE SYSTEM_USER "
"TABLE TEMPORARY TERMINATE THAN THEN TIME TIMESTAMP "
"TIMEZONE_HOUR TIMEZONE_MINUTE TO TRAILING TRANSACTION TRANSLATION "
"TREAT TRIGGER TRUE UNDER UNION UNIQUE UNKNOWN "
"UNNEST UPDATE USAGE USER USING "
"VALUE VALUES VARCHAR VARIABLE VARYING VIEW "
"WHEN WHENEVER WHERE WITH WITHOUT WORK WRITE YEAR ZONE";
indentWords = "";
blockComment = "";
streamStart = "/*";
streamEnd = "*/";
statementEnd = "";
preprocessor = false;
break;
case TclTk:
languageName = "Tcl/Tk";
keyWords[0] =
"after append array auto_execok auto_import auto_load "
"auto_load_index auto_qualify beep binary break case catch cd clock "
"close concat continue dde default echo else elseif encoding eof "
"error eval exec exit expr fblocked fconfigure fcopy file "
"fileevent flush for foreach format gets glob global history if "
"incr info interp join lappend lindex linsert list llength load "
"lrange lreplace lsearch lsort namespace open package pid "
"pkg_mkIndex proc puts pwd read regexp regsub rename resource "
"return scan seek set socket source split string subst switch "
"tclLog tclMacPkgSearch tclPkgSetup tclPkgUnknown tell time "
"trace unknown unset update uplevel upvar variable vwait while "
"bell bind bindtags button canvas checkbutton console "
"destroy entry event focus font frame grab grid image label listbox menu "
"menubutton message pack place radiobutton raise scale scrollbar "
"text tk tkwait toplevel winfo wm "
"tkButtonDown tkButtonEnter tkButtonInvoke "
"tkButtonLeave tkButtonUp tkCancelRepeat tkCheckRadioInvoke tkDarken "
"tkEntryAutoScan tkEntryBackspace tkEntryButton1 tkEntryClosestGap "
"tkEntryInsert tkEntryKeySelect tkEntryMouseSelect tkEntryNextWord "
"tkEntryPaste tkEntryPreviousWord tkEntrySeeInsert tkEntrySetCursor "
"tkEntryTranspose tkEventMotifBindings tkFDGetFileTypes tkFirstMenu "
"tkFocusGroup_Destroy tkFocusGroup_In tkFocusGroup_Out tkFocusOK "
"tkListboxAutoScan tkListboxBeginExtend tkListboxBeginSelect "
"tkListboxBeginToggle tkListboxCancel tkListboxDataExtend "
"tkListboxExtendUpDown tkListboxMotion tkListboxSelectAll "
"tkListboxUpDown tkMbButtonUp tkMbEnter tkMbLeave tkMbMotion "
"tkMbPost tkMenuButtonDown tkMenuDownArrow tkMenuDup tkMenuEscape "
"tkMenuFind tkMenuFindName tkMenuFirstEntry tkMenuInvoke tkMenuLeave "
"tkMenuLeftArrow tkMenuMotion tkMenuNextEntry tkMenuNextMenu "
"tkMenuRightArrow tkMenuUnpost tkMenuUpArrow tkMessageBox "
"tkPostOverPoint tkRecolorTree tkRestoreOldGrab tkSaveGrabInfo "
"tkScaleActivate tkScaleButton2Down tkScaleButtonDown "
"tkScaleControlPress tkScaleDrag tkScaleEndDrag tkScaleIncrement "
"tkScreenChanged tkScrollButton2Down tkScrollButtonDown "
"tkScrollButtonUp tkScrollByPages tkScrollByUnits tkScrollDrag "
"tkScrollEndDrag tkScrollSelect tkScrollStartDrag tkScrollToPos "
"tkScrollTopBottom tkTabToWindow tkTearOffMenu tkTextAutoScan "
"tkTextButton1 tkTextClosestGap tkTextInsert tkTextKeyExtend "
"tkTextKeySelect tkTextNextPara tkTextNextPos tkTextNextWord "
"tkTextPaste tkTextPrevPara tkTextPrevPos tkTextResetAnchor "
"tkTextScrollPages tkTextSelectTo tkTextSetCursor tkTextTranspose "
"tkTextUpDownLine tkTraverseToMenu tkTraverseWithinMenu tk_bisque "
"tk_chooseColor tk_dialog tk_focusFollowsMouse tk_focusNext "
"tk_focusPrev tk_getOpenFile tk_getSaveFile tk_messageBox "
"tk_optionMenu tk_popup tk_setPalette tk_textCopy tk_textCut "
"tk_textPaste";
indentWords = "switch catch class default do else for if";
blockComment = "# ";
streamStart = "";
streamEnd = "";
statementEnd = ";";
preprocessor = false;
break;
case Text:
languageName = "Text";
keyWords[0] = "";
indentWords = "";
blockComment = "";
streamStart = "";
streamEnd = "";
statementEnd = ";";
preprocessor = false;
break;
case VisualBasic:
languageName = "Visual Basic";
keyWords[0] =
"and begin case call continue do each else elseif end erase "
"error event exit false for function get gosub goto if implement in load loop lset "
"me mid new next not nothing on or property raiseevent rem resume return rset "
"select set stop sub then to true unload until wend while with withevents "
"attribute alias as boolean byref byte byval const compare currency date declare dim double "
"enum explicit friend global integer let lib long module object option optional "
"preserve private property public redim single static string type variant ";
indentWords = "";
blockComment = "' ";
streamStart = "";
streamEnd = "";
statementEnd = ";";
preprocessor = false;
break;
case x86:
languageName = "x86 Assembly";
keyWords[0] =
"aaa aad aam aas adc add and call cbw "
"clc cld cli cmc cmp cmps cmpsb cmpsw cwd daa das dec div esc hlt "
"idiv imul in inc int into iret ja jae jb jbe jc jcxz je jg jge jl "
"jle jmp jna jnae jnb jnbe jnc jne jng jnge jnl jnle jno jnp jns "
"jnz jo jp jpe jpo js jz lahf lds lea les lods lodsb lodsw loop "
"loope loopew loopne loopnew loopnz loopnzw loopw loopz loopzw "
"mov movs movsb movsw mul neg nop not or out pop popf push pushf "
"rcl rcr ret retf retn rol ror sahf sal sar sbb scas scasb scasw "
"shl shr stc std sti stos stosb stosw sub test wait xchg xlat xlatb xor "
"bound enter ins insb insw leave outs outsb outsw popa pusha pushw "
"arpl lar lsl sgdt sidt sldt smsw str verr verw clts lgdt lidt lldt lmsw ltr "
"bsf bsr bt btc btr bts cdq cmpsd cwde insd iretd iretdf iretf "
"jecxz lfs lgs lodsd loopd looped loopned loopnzd loopzd lss "
"movsd movsx movzx outsd popad popfd pushad pushd pushfd scasd seta "
"setae setb setbe setc sete setg setge setl setle setna setnae setnb "
"setnbe setnc setne setng setnge setnl setnle setno setnp setns "
"setnz seto setp setpe setpo sets setz shld shrd stosd "
"bswap cmpxchg invd invlpg wbinvd xadd "
"lock rep repe repne repnz repz";
indentWords = ".if";
blockComment = "; ";
streamStart = "";
streamEnd = "";
statementEnd = ".endif";
preprocessor = true;
break;
case XML:
languageName = "XML";
keyWords[0] = "";
indentWords = "";
blockComment = "";
streamStart = "";
statementEnd = "";
preprocessor = false;
break;
}
}