creates a new swing gui public swing gui dim dim string title super title this dim dim init dim set gui callback this swinggui swinggui setguicallback returns the menubar of this debugger frame public menubar get menubar return menubar getmenubar sets the link runnable that will be run when the exit menu item is chosen public void set exit action runnable r exit action r setexitaction exitaction returns the debugger console component public js internal console get console return console jsinternalconsole getconsole sets the visibility of the debugger gui public void set visible boolean b super set visible b if b this needs to be done after the window is visible console console text area request focus context split set divider location 0 5 try console set maximum true console set selected true console show console console text area request focus catch exception exc setvisible setvisible consoletextarea requestfocus setdividerlocation setmaximum setselected consoletextarea requestfocus records a new internal frame void add top level string key j frame frame if frame this toplevels put key frame addtoplevel jframe constructs the debugger gui private void init menubar new menubar this setj menu bar menubar tool bar new j tool bar j button button j button break button go button step into button step over button step out button string tool tips break pause go f5 step into f11 step over f7 step out f8 int count 0 button break button new j button break j button focus button button button set tool tip text break button set action command break button add action listener menubar button set enabled true button set tool tip text tool tips count button go button new j button go button set tool tip text go button set action command go button add action listener menubar button set enabled false button set tool tip text tool tips count button step into button new j button step into button set tool tip text step into button set action command step into button add action listener menubar button set enabled false button set tool tip text tool tips count button step over button new j button step over button set tool tip text step over button set action command step over button set enabled false button add action listener menubar button set tool tip text tool tips count button step out button new j button step out button set tool tip text step out button set action command step out button set enabled false button add action listener menubar button set tool tip text tool tips count dimension dim step over button get preferred size break button set preferred size dim break button set minimum size dim break button set maximum size dim break button set size dim go button set preferred size dim go button set minimum size dim go button set maximum size dim step into button set preferred size dim step into button set minimum size dim step into button set maximum size dim step over button set preferred size dim step over button set minimum size dim step over button set maximum size dim step out button set preferred size dim step out button set minimum size dim step out button set maximum size dim tool bar add break button tool bar add go button tool bar add step into button tool bar add step over button tool bar add step out button j panel content pane new j panel content pane set layout new border layout get content pane add tool bar border layout north get content pane add content pane border layout center desk new j desktop pane desk set preferred size new dimension 600 300 desk set minimum size new dimension 150 50 desk add console new js internal console java script console context new context window this context set preferred size new dimension 600 120 context set minimum size new dimension 50 50 split1 new j split pane j split pane vertical split desk context split1 set one touch expandable true swing gui set resize weight split1 0 66 content pane add split1 border layout center status bar new j label status bar set text thread content pane add status bar border layout south dlg new j file chooser javax swing filechooser file filter filter new javax swing filechooser file filter public boolean accept file f if f is directory return true string n f get name int i n last index of if i 0 i n length 1 string ext n substring i 1 to lower case if ext equals js return true return false public string get description return java script files js dlg add choosable file filter filter add window listener new window adapter public void window closing window event e exit setjmenubar toolbar jtoolbar jbutton jbutton breakbutton gobutton stepintobutton stepoverbutton stepoutbutton tooltips breakbutton jbutton jbutton focusbutton settooltiptext setactioncommand addactionlistener setenabled settooltiptext tooltips gobutton jbutton settooltiptext setactioncommand addactionlistener setenabled settooltiptext tooltips stepintobutton jbutton settooltiptext setactioncommand addactionlistener setenabled settooltiptext tooltips stepoverbutton jbutton settooltiptext setactioncommand setenabled addactionlistener settooltiptext tooltips stepoutbutton jbutton settooltiptext setactioncommand setenabled addactionlistener settooltiptext tooltips stepoverbutton getpreferredsize breakbutton setpreferredsize breakbutton setminimumsize breakbutton setmaximumsize breakbutton setsize gobutton setpreferredsize gobutton setminimumsize gobutton setmaximumsize stepintobutton setpreferredsize stepintobutton setminimumsize stepintobutton setmaximumsize stepoverbutton setpreferredsize stepoverbutton setminimumsize stepoverbutton setmaximumsize stepoutbutton setpreferredsize stepoutbutton setminimumsize stepoutbutton setmaximumsize toolbar breakbutton toolbar gobutton toolbar stepintobutton toolbar stepoverbutton toolbar stepoutbutton jpanel contentpane jpanel contentpane setlayout borderlayout getcontentpane toolbar borderlayout getcontentpane contentpane borderlayout jdesktoppane setpreferredsize setminimumsize jsinternalconsole javascript contextwindow setpreferredsize setminimumsize jsplitpane jsplitpane vertical_split setonetouchexpandable swinggui setresizeweight contentpane borderlayout statusbar jlabel statusbar settext contentpane statusbar borderlayout jfilechooser filefilter filefilter isdirectory getname lastindexof tolowercase getdescription javascript addchoosablefilefilter addwindowlistener windowadapter windowclosing windowevent new javax swing filechooser file filter public boolean accept file f if f is directory return true string n f get name int i n last index of if i 0 i n length 1 string ext n substring i 1 to lower case if ext equals js return true return false filefilter isdirectory getname lastindexof tolowercase public string get description return java script files js getdescription javascript dlg add choosable file filter filter add window listener new window adapter public void window closing window event e exit addchoosablefilefilter addwindowlistener windowadapter windowclosing windowevent runs the link exit action private void exit if exit action null swing utilities invoke later exit action dim set return value dim exit exitaction exitaction swingutilities invokelater exitaction setreturnvalue returns the link file window for the given url file window get file window string url if url null url equals stdin return null return file window file windows get url filewindow filewindow getfilewindow filewindow filewindows returns a short version of the given url static string get short name string url int last slash url last index of if last slash 0 last slash url last index of string short name url if last slash 0 last slash 1 url length short name url substring last slash 1 return short name getshortname lastslash lastindexof lastslash lastslash lastindexof shortname lastslash lastslash shortname lastslash shortname closes the given link file window void remove window file window w file windows remove w get url j menu window menu get window menu int count window menu get item count j menu item last item window menu get item count 1 string name get short name w get url for int i 5 i count i j menu item item window menu get item i if item null continue separator string text item get text 1 d foo js 2 d bar js int pos text index of if text substring pos 1 equals name window menu remove item cascade 0 tile 1 2 console 3 4 if count 6 remove the final separator window menu remove 4 else int j i 4 for i count 1 i j menu item this item window menu get item i if this item null 1 d foo js 2 d bar js text this item get text if text equals more windows break else pos text index of this item set text char 0 j text substring pos 1 this item set mnemonic 0 j j if count 6 0 last item item if last item get text equals more windows window menu remove last item break window menu revalidate filewindow removewindow filewindow filewindows geturl jmenu windowmenu getwindowmenu windowmenu getitemcount jmenuitem lastitem windowmenu getitem getshortname geturl jmenuitem windowmenu getitem gettext indexof windowmenu windowmenu jmenuitem thisitem windowmenu getitem thisitem thisitem gettext indexof thisitem settext thisitem setmnemonic lastitem lastitem gettext windowmenu lastitem windowmenu shows the line at which execution in the given stack frame just stopped void show stop line dim stack frame frame string source name frame get url if source name null source name equals stdin if console is visible console show else int line number frame get line number file window w get file window source name if w null set file position w line number else dim source info si frame source info create file window si line number showstopline stackframe sourcename geturl sourcename sourcename isvisible linenumber getlinenumber filewindow getfilewindow sourcename setfileposition linenumber sourceinfo sourceinfo createfilewindow linenumber creates and shows a new link file window for the given source void create file window dim source info source info int line boolean activate true string url source info url file window w new file window this source info file windows put url w if line 1 if current window null current window set position 1 try w set position w text area get line start offset line 1 catch bad location exception exc try w set position w text area get line start offset 0 catch bad location exception ee w set position 1 desk add w if line 1 current window w menubar add file url w set visible true if activate try w set maximum true w set selected true w move to front catch exception exc filewindow createfilewindow sourceinfo sourceinfo sourceinfo filewindow filewindow sourceinfo filewindows currentwindow currentwindow setposition setposition textarea getlinestartoffset badlocationexception setposition textarea getlinestartoffset badlocationexception setposition currentwindow addfile setvisible setmaximum setselected movetofront moves the current position in the given link file window to the given line private void set file position file window w int line boolean activate true j text area ta w text area try if line 1 w set position 1 if current window w current window null else int loc ta get line start offset line 1 if current window null current window w current window set position 1 w set position loc current window w catch bad location exception exc fix me if activate if w is icon desk get desktop manager deiconify frame w desk get desktop manager activate frame w try w show w to front required for correct frame layering jdk 1 4 1 w set selected true catch exception exc filewindow setfileposition filewindow jtextarea textarea setposition currentwindow currentwindow getlinestartoffset currentwindow currentwindow currentwindow setposition setposition currentwindow badlocationexception isicon getdesktopmanager deiconifyframe getdesktopmanager activateframe tofront setselected handles script interruption void enter interrupt impl dim stack frame last frame string thread title string alert message status bar set text thread thread title show stop line last frame if alert message null message dialog wrapper show message dialog this alert message exception in script j option pane error message update enabled true dim context data context data last frame context data j combo box ctx context context vector tool tips context tool tips context disable update int frame count context data frame count ctx remove all items workaround for jdk 1 4 bug that caches selected value even after remove all items is called ctx set selected item null tool tips remove all elements for int i 0 i frame count i dim stack frame frame context data get frame i string url frame get url int line number frame get line number string short name url if url length 20 short name url substring url length 17 string location short name line line number ctx insert item at location i location url line line number tool tips add element location context enable update ctx set selected index 0 ctx set minimum size new dimension 50 ctx get minimum size height enterinterruptimpl stackframe lastframe threadtitle alertmessage statusbar settext threadtitle showstopline lastframe alertmessage messagedialogwrapper showmessagedialog alertmessage joptionpane error_message updateenabled contextdata contextdata lastframe contextdata jcombobox tooltips tooltips disableupdate framecount contextdata framecount removeallitems removeallitems setselecteditem tooltips removeallelements framecount stackframe contextdata getframe geturl linenumber getlinenumber shortname shortname shortname linenumber insertitemat linenumber tooltips addelement enableupdate setselectedindex setminimumsize getminimumsize returns the window menu private j menu get window menu return menubar get menu 3 jmenu getwindowmenu getmenu displays a link j file chooser and returns the selected filename private string choose file string title dlg set dialog title title file cwd null string dir system get property user dir if dir null cwd new file dir if cwd null dlg set current directory cwd int return val dlg show open dialog this if return val j file chooser approve option try string result dlg get selected file get canonical path cwd dlg get selected file get parent file properties props system get properties props put user dir cwd get path system set properties props return result catch io exception ignored catch security exception ignored return null jfilechooser choosefile setdialogtitle getproperty setcurrentdirectory returnval showopendialog returnval jfilechooser approve_option getselectedfile getcanonicalpath getselectedfile getparentfile getproperties getpath setproperties ioexception securityexception returns the current selected internal frame private j internal frame get selected frame j internal frame frames desk get all frames for int i 0 i frames length i if frames i is showing return frames i return frames frames length 1 jinternalframe getselectedframe jinternalframe getallframes isshowing enables or disables the menu and tool bars with respect to the state of script execution private void update enabled boolean interrupted menubar getj menu bar update enabled interrupted for int ci 0 cc tool bar get component count ci cc ci boolean enable button if ci 0 break enable button interrupted else enable button interrupted tool bar get component ci set enabled enable button if interrupted tool bar set enabled true raise the debugger window int state get extended state if state frame iconified set extended state frame normal to front context enable else if current window null current window set position 1 context disable updateenabled getjmenubar updateenabled toolbar getcomponentcount enablebutton enablebutton enablebutton toolbar getcomponent setenabled enablebutton toolbar setenabled getextendedstate setextendedstate tofront currentwindow currentwindow setposition calls link j split pane set resize weight via reflection for compatibility since jdk lt 1 3 does not have this method static void set resize weight j split pane pane double weight try method m j split pane class get method set resize weight new class double class m invoke pane new object new double weight catch no such method exception exc catch illegal access exception exc catch java lang reflect invocation target exception exc jsplitpane setresizeweight setresizeweight jsplitpane jsplitpane getmethod setresizeweight nosuchmethodexception illegalaccessexception invocationtargetexception reads the file with the given name and returns its contents as a string private string read file string file name string text try reader r new file reader file name try text kit read reader r finally r close catch io exception ex message dialog wrapper show message dialog this ex get message error reading file name j option pane error message text null return text readfile filename filereader filename readreader ioexception messagedialogwrapper showmessagedialog getmessage filename joptionpane error_message called when the source text for a script has been updated public void update source text dim source info source info run proxy proxy new run proxy this run proxy update source text proxy source info source info swing utilities invoke later proxy updatesourcetext sourceinfo sourceinfo runproxy runproxy runproxy update_source_text sourceinfo sourceinfo swingutilities invokelater called when the interrupt loop has been entered public void enter interrupt dim stack frame last frame string thread title string alert message if swing utilities is event dispatch thread enter interrupt impl last frame thread title alert message else run proxy proxy new run proxy this run proxy enter interrupt proxy last frame last frame proxy thread title thread title proxy alert message alert message swing utilities invoke later proxy enterinterrupt stackframe lastframe threadtitle alertmessage swingutilities iseventdispatchthread enterinterruptimpl lastframe threadtitle alertmessage runproxy runproxy runproxy enter_interrupt lastframe lastframe threadtitle threadtitle alertmessage alertmessage swingutilities invokelater returns whether the current thread is the gui event thread public boolean is gui event thread return swing utilities is event dispatch thread isguieventthread swingutilities iseventdispatchthread processes the next gui event public void dispatch next gui event throws interrupted exception event queue queue awt event queue if queue null queue toolkit get default toolkit get system event queue awt event queue queue awt event event queue get next event if event instanceof active event active event event dispatch else object source event get source if source instanceof component component comp component source comp dispatch event event else if source instanceof menu component menu component source dispatch event event dispatchnextguievent interruptedexception eventqueue awteventqueue getdefaulttoolkit getsystemeventqueue awteventqueue awtevent getnextevent activeevent activeevent getsource dispatchevent menucomponent menucomponent dispatchevent performs an action from the menu or toolbar public void action performed action event e string cmd e get action command int return value 1 if cmd equals cut cmd equals copy cmd equals paste j internal frame f get selected frame if f null f instanceof action listener action listener f action performed e else if cmd equals step over return value dim step over else if cmd equals step into return value dim step into else if cmd equals step out return value dim step out else if cmd equals go return value dim go else if cmd equals break dim set break else if cmd equals exit exit else if cmd equals open string file name choose file select a file to compile if file name null string text read file file name if text null run proxy proxy new run proxy this run proxy open file proxy file name file name proxy text text new thread proxy start else if cmd equals load string file name choose file select a file to execute if file name null string text read file file name if text null run proxy proxy new run proxy this run proxy load file proxy file name file name proxy text text new thread proxy start else if cmd equals more windows more windows dlg new more windows this file windows window files dlg show dialog this else if cmd equals console if console is icon desk get desktop manager deiconify frame console console show desk get desktop manager activate frame console console console text area request focus else if cmd equals cut else if cmd equals copy else if cmd equals paste else if cmd equals go to function find function dlg new find function this go to function function dlg show dialog this else if cmd equals tile j internal frame frames desk get all frames int count frames length int rows cols rows cols int math sqrt count if rows cols count cols if rows cols count rows dimension size desk get size int w size width cols int h size height rows int x 0 int y 0 for int i 0 i rows i for int j 0 j cols j int index i cols j if index frames length break j internal frame f frames index try f set icon false f set maximum false catch exception exc desk get desktop manager set bounds for frame f x y w h x w y h x 0 else if cmd equals cascade j internal frame frames desk get all frames int count frames length int x y w h x y 0 h desk get height int d h count if d 30 d 30 for int i count 1 i 0 i x d y d j internal frame f frames i try f set icon false f set maximum false catch exception exc dimension dimen f get preferred size w dimen width h dimen height desk get desktop manager set bounds for frame f x y w h else object obj get file window cmd if obj null file window w file window obj try if w is icon w set icon false w set visible true w move to front w set selected true catch exception exc if return value 1 update enabled false dim set return value return value actionperformed actionevent getactioncommand returnvalue jinternalframe getselectedframe actionlistener actionlistener actionperformed returnvalue step_over returnvalue step_into returnvalue step_out returnvalue setbreak filename choosefile filename readfile filename runproxy runproxy runproxy open_file filename filename filename choosefile filename readfile filename runproxy runproxy runproxy load_file filename filename morewindows morewindows filewindows showdialog isicon getdesktopmanager deiconifyframe getdesktopmanager activateframe consoletextarea requestfocus findfunction findfunction showdialog jinternalframe getallframes getsize jinternalframe seticon setmaximum getdesktopmanager setboundsforframe jinternalframe getallframes getheight jinternalframe seticon setmaximum getpreferredsize getdesktopmanager setboundsforframe getfilewindow filewindow filewindow isicon seticon setvisible movetofront setselected returnvalue updateenabled setreturnvalue returnvalue shows a message dialog wrapping the code msg code at 60 columns public static void show message dialog component parent string msg string title int flags if msg length 60 string buffer buf new string buffer int len msg length int j 0 int i for i 0 i len i j char c msg char at i buf append c if character is whitespace c int remainder len i int k for k i 1 k len k if character is whitespace msg char at k break if k len int next word len k i if j next word len 60 buf append n j 0 msg buf to string j option pane show message dialog parent msg title flags showmessagedialog stringbuffer stringbuffer charat iswhitespace iswhitespace charat nextwordlen nextwordlen tostring joptionpane showmessagedialog creates a new eval text area public eval text area swing gui debug gui this debug gui debug gui history new java util vector document doc get document doc add document listener this add key listener this set line wrap true set font new font monospaced 0 12 append output mark doc get length evaltextarea evaltextarea swinggui debuggui debuggui debuggui getdocument adddocumentlistener addkeylistener setlinewrap setfont outputmark getlength selects a subrange of the text public void select int start int end request focus super select start end requestfocus called when enter is pressed private synchronized void return pressed document doc get document int len doc get length segment segment new segment try doc get text output mark len output mark segment catch javax swing text bad location exception ignored ignored print stack trace string text segment to string if debug gui dim string is compilable unit text if text trim length 0 history add element text history index history size append n string result debug gui dim eval text if result length 0 append result append n append output mark doc get length else append n returnpressed getdocument getlength gettext outputmark outputmark badlocationexception printstacktrace tostring debuggui stringiscompilableunit addelement historyindex debuggui outputmark getlength writes output into the text area public synchronized void write string str insert str output mark int len str length output mark len select output mark output mark outputmark outputmark outputmark outputmark called when a key is pressed public void key pressed key event e int code e get key code if code key event vk back space code key event vk left if output mark get caret position e consume else if code key event vk home int caret pos get caret position if caret pos output mark e consume else if caret pos output mark if e is control down if e is shift down move caret position output mark else set caret position output mark e consume else if code key event vk enter return pressed e consume else if code key event vk up history index if history index 0 if history index history size history index history size 1 if history index 0 string str string history element at history index int len get document get length replace range str output mark len int caret pos output mark str length select caret pos caret pos else history index else history index e consume else if code key event vk down int caret pos output mark if history size 0 history index if history index 0 history index 0 int len get document get length if history index history size string str string history element at history index replace range str output mark len caret pos output mark str length else history index history size replace range output mark len select caret pos caret pos e consume keypressed keyevent getkeycode keyevent vk_back_space keyevent vk_left outputmark getcaretposition keyevent vk_home caretpos getcaretposition caretpos outputmark caretpos outputmark iscontroldown isshiftdown movecaretposition outputmark setcaretposition outputmark keyevent vk_enter returnpressed keyevent vk_up historyindex historyindex historyindex historyindex historyindex elementat historyindex getdocument getlength replacerange outputmark caretpos outputmark caretpos caretpos historyindex historyindex keyevent vk_down caretpos outputmark historyindex historyindex historyindex getdocument getlength historyindex elementat historyindex replacerange outputmark caretpos outputmark historyindex replacerange outputmark caretpos caretpos called when a key is typed public void key typed key event e int key char e get key char if key char 0x8 key event vk back space if output mark get caret position e consume else if get caret position output mark set caret position output mark keytyped keyevent keychar getkeychar keychar keyevent vk_back_space outputmark getcaretposition getcaretposition outputmark setcaretposition outputmark called when a key is released public synchronized void key released key event e keyreleased keyevent called when text was inserted into the text area public synchronized void insert update document event e int len e get length int off e get offset if output mark off output mark len insertupdate documentevent getlength getoffset outputmark outputmark called when text was removed from the text area public synchronized void remove update document event e int len e get length int off e get offset if output mark off if output mark off len output mark len else output mark off removeupdate documentevent getlength getoffset outputmark outputmark outputmark outputmark attempts to clean up the damange done by link update component treeui public synchronized void post updateui request focus set caret get caret select output mark output mark updatecomponenttreeui postupdateui requestfocus setcaret getcaret outputmark outputmark called when text has changed in the text area public synchronized void changed update document event e changedupdate documentevent creates a new eval window public eval window string name swing gui debug gui super name true false true true eval text area new eval text area debug gui eval text area set rows 24 eval text area set columns 80 j scroll pane scroller new j scroll pane eval text area set content pane scroller scroller set preferred size new dimension 600 400 pack set visible true evalwindow evalwindow swinggui debuggui evaltextarea evaltextarea debuggui evaltextarea setrows evaltextarea setcolumns jscrollpane jscrollpane evaltextarea setcontentpane setpreferredsize setvisible sets whether the text area is enabled public void set enabled boolean b super set enabled b eval text area set enabled b setenabled setenabled evaltextarea setenabled performs an action on the text area public void action performed action event e string cmd e get action command if cmd equals cut eval text area cut else if cmd equals copy eval text area copy else if cmd equals paste eval text area paste actionperformed actionevent getactioncommand evaltextarea evaltextarea evaltextarea creates a new js internal console public js internal console string name super name true false true true console text area new console text area null console text area set rows 24 console text area set columns 80 j scroll pane scroller new j scroll pane console text area set content pane scroller pack add internal frame listener new internal frame adapter public void internal frame activated internal frame event e hack if console text area has focus console text area get caret set visible false console text area get caret set visible true jsinternalconsole jsinternalconsole consoletextarea consoletextarea consoletextarea setrows consoletextarea setcolumns jscrollpane jscrollpane consoletextarea setcontentpane addinternalframelistener internalframeadapter internalframeactivated internalframeevent consoletextarea hasfocus consoletextarea getcaret setvisible consoletextarea getcaret setvisible add internal frame listener new internal frame adapter public void internal frame activated internal frame event e hack if console text area has focus console text area get caret set visible false console text area get caret set visible true addinternalframelistener internalframeadapter internalframeactivated internalframeevent consoletextarea hasfocus consoletextarea getcaret setvisible consoletextarea getcaret setvisible returns the input stream of the console text area public input stream get in return console text area get in inputstream getin consoletextarea getin returns the output stream of the console text area public print stream get out return console text area get out printstream getout consoletextarea getout returns the error stream of the console text area public print stream get err return console text area get err printstream geterr consoletextarea geterr performs an action on the text area public void action performed action event e string cmd e get action command if cmd equals cut console text area cut else if cmd equals copy console text area copy else if cmd equals paste console text area paste actionperformed actionevent getactioncommand consoletextarea consoletextarea consoletextarea creates a new file popup menu public file popup menu file text area w this w w j menu item item add item new j menu item set breakpoint item add action listener w add item new j menu item clear breakpoint item add action listener w add item new j menu item run item add action listener w filepopupmenu filepopupmenu filetextarea jmenuitem jmenuitem addactionlistener jmenuitem addactionlistener jmenuitem addactionlistener displays the menu at the given coordinates public void show j component comp int x int y this x x this y y super show comp x y jcomponent creates a new file text area public file text area file window w this w w popup new file popup menu this popup add popup menu listener this add mouse listener this add key listener this set font new font monospaced 0 12 filetextarea filetextarea filewindow filepopupmenu addpopupmenulistener addmouselistener addkeylistener setfont moves the selection to the given offset public void select int pos if pos 0 try int line get line of offset pos rectangle rect model to view pos if rect null select pos pos else try rectangle nrect model to view get line start offset line 1 if nrect null rect nrect catch exception exc j viewport vp j viewport get parent rectangle view rect vp get view rect if view rect y view rect height rect y need to scroll up select pos pos else need to scroll down rect y view rect height rect height 2 scroll rect to visible rect select pos pos catch bad location exception exc select pos pos exc print stack trace getlineofoffset modeltoview modeltoview getlinestartoffset jviewport jviewport getparent viewrect getviewrect viewrect viewrect viewrect scrollrecttovisible badlocationexception printstacktrace checks if the popup menu should be shown private void check popup mouse event e if e is popup trigger popup show this e getx e gety checkpopup mouseevent ispopuptrigger called when a mouse button is pressed public void mouse pressed mouse event e check popup e mousepressed mouseevent checkpopup called when the mouse is clicked public void mouse clicked mouse event e check popup e request focus get caret set visible true mouseclicked mouseevent checkpopup requestfocus getcaret setvisible called when the mouse enters the component public void mouse entered mouse event e mouseentered mouseevent called when the mouse exits the component public void mouse exited mouse event e mouseexited mouseevent called when a mouse button is released public void mouse released mouse event e check popup e mousereleased mouseevent checkpopup called before the popup menu will become visible public void popup menu will become visible popup menu event e popupmenuwillbecomevisible popupmenuevent called before the popup menu will become invisible public void popup menu will become invisible popup menu event e popupmenuwillbecomeinvisible popupmenuevent called when the popup menu is cancelled public void popup menu canceled popup menu event e popupmenucanceled popupmenuevent performs an action public void action performed action event e int pos view to model new point popup x popup y popup set visible false string cmd e get action command int line 1 try line get line of offset pos catch exception exc if cmd equals set breakpoint w set break point line 1 else if cmd equals clear breakpoint w clear break point line 1 else if cmd equals run w load actionperformed actionevent viewtomodel setvisible getactioncommand getlineofoffset setbreakpoint clearbreakpoint called when a key is pressed public void key pressed key event e switch e get key code case key event vk back space case key event vk enter case key event vk delete e consume break keypressed keyevent getkeycode keyevent vk_back_space keyevent vk_enter keyevent vk_delete called when a key is typed public void key typed key event e e consume keytyped keyevent called when a key is released public void key released key event e e consume keyreleased keyevent creates a new more windows more windows j frame frame hashtable file windows string title string label text super frame title true this file windows file windows buttons cancel button new j button cancel set button new j button select cancel button add action listener this set button add action listener this get root pane set default button set button dim part of the dialog list new j list new default list model default list model model default list model list get model model clear model fire interval removed model 0 size enumeration e file windows keys while e has more elements string data e next element to string model add element data list set selected index 0 model fire interval added model 0 data length set button set enabled true list set selection mode list selection model single interval selection list add mouse listener new mouse handler j scroll pane list scroller new j scroll pane list list scroller set preferred size new dimension 320 240 xxx must do the following too or else the scroller thinks xxx it s taller than it is list scroller set minimum size new dimension 250 80 list scroller set alignmentx left alignment create a container so that we can add a title around the scroll pane can t add a title directly to the scroll pane because its background would be white lay out the label and scroll pane from top to button j panel list pane new j panel list pane set layout new box layout list pane box layout y axis j label label new j label label text label set label for list list pane add label list pane add box create rigid area new dimension 0 5 list pane add list scroller list pane set border border factory create empty border 10 10 10 10 lay out the buttons from left to right j panel button pane new j panel button pane set layout new box layout button pane box layout x axis button pane set border border factory create empty border 0 10 10 10 button pane add box create horizontal glue button pane add cancel button button pane add box create rigid area new dimension 10 0 button pane add set button put everything together using the content pane s border layout container content pane get content pane content pane add list pane border layout center content pane add button pane border layout south pack add key listener new key adapter public void key pressed key event ke int code ke get key code if code key event vk escape ke consume value null set visible false morewindows morewindows jframe filewindows labeltext filewindows filewindows cancelbutton jbutton setbutton jbutton cancelbutton addactionlistener setbutton addactionlistener getrootpane setdefaultbutton setbutton jlist defaultlistmodel defaultlistmodel defaultlistmodel getmodel fireintervalremoved filewindows hasmoreelements nextelement tostring addelement setselectedindex fireintervaladded setbutton setenabled setselectionmode listselectionmodel single_interval_selection addmouselistener mousehandler jscrollpane listscroller jscrollpane listscroller setpreferredsize listscroller setminimumsize listscroller setalignmentx left_alignment jpanel listpane jpanel listpane setlayout boxlayout listpane boxlayout y_axis jlabel jlabel labeltext setlabelfor listpane listpane createrigidarea listpane listscroller listpane setborder borderfactory createemptyborder jpanel buttonpane jpanel buttonpane setlayout boxlayout buttonpane boxlayout x_axis buttonpane setborder borderfactory createemptyborder buttonpane createhorizontalglue buttonpane cancelbutton buttonpane createrigidarea buttonpane setbutton borderlayout contentpane getcontentpane contentpane listpane borderlayout contentpane buttonpane borderlayout addkeylistener keyadapter keypressed keyevent getkeycode keyevent vk_escape setvisible add key listener new key adapter public void key pressed key event ke int code ke get key code if code key event vk escape ke consume value null set visible false addkeylistener keyadapter keypressed keyevent getkeycode keyevent vk_escape setvisible shows the dialog public string show dialog component comp value null set location relative to comp set visible true return value showdialog setlocationrelativeto setvisible sets the selected value private void set value string new value value new value list set selected value value true setvalue newvalue newvalue setselectedvalue performs an action public void action performed action event e string cmd e get action command if cmd equals cancel set visible false value null else if cmd equals select value string list get selected value set visible false j internal frame w j internal frame file windows get value if w null try w show w set selected true catch exception exc actionperformed actionevent getactioncommand setvisible getselectedvalue setvisible jinternalframe jinternalframe filewindows setselected private class mouse handler extends mouse adapter public void mouse clicked mouse event e if e get click count 2 set button do click mousehandler mouseadapter mouseclicked mouseevent getclickcount setbutton doclick creates a new find function public find function swing gui debug gui string title string label text super debug gui title true this debug gui debug gui cancel button new j button cancel set button new j button select cancel button add action listener this set button add action listener this get root pane set default button set button list new j list new default list model default list model model default list model list get model model clear string a debug gui dim function names java util arrays sort a for int i 0 i a length i model add element a i list set selected index 0 set button set enabled a length 0 list set selection mode list selection model single interval selection list add mouse listener new mouse handler j scroll pane list scroller new j scroll pane list list scroller set preferred size new dimension 320 240 list scroller set minimum size new dimension 250 80 list scroller set alignmentx left alignment create a container so that we can add a title around the scroll pane can t add a title directly to the scroll pane because its background would be white lay out the label and scroll pane from top to button j panel list pane new j panel list pane set layout new box layout list pane box layout y axis j label label new j label label text label set label for list list pane add label list pane add box create rigid area new dimension 0 5 list pane add list scroller list pane set border border factory create empty border 10 10 10 10 lay out the buttons from left to right j panel button pane new j panel button pane set layout new box layout button pane box layout x axis button pane set border border factory create empty border 0 10 10 10 button pane add box create horizontal glue button pane add cancel button button pane add box create rigid area new dimension 10 0 button pane add set button put everything together using the content pane s border layout container content pane get content pane content pane add list pane border layout center content pane add button pane border layout south pack add key listener new key adapter public void key pressed key event ke int code ke get key code if code key event vk escape ke consume value null set visible false findfunction findfunction swinggui debuggui labeltext debuggui debuggui debuggui cancelbutton jbutton setbutton jbutton cancelbutton addactionlistener setbutton addactionlistener getrootpane setdefaultbutton setbutton jlist defaultlistmodel defaultlistmodel defaultlistmodel getmodel debuggui functionnames addelement setselectedindex setbutton setenabled setselectionmode listselectionmodel single_interval_selection addmouselistener mousehandler jscrollpane listscroller jscrollpane listscroller setpreferredsize listscroller setminimumsize listscroller setalignmentx left_alignment jpanel listpane jpanel listpane setlayout boxlayout listpane boxlayout y_axis jlabel jlabel labeltext setlabelfor listpane listpane createrigidarea listpane listscroller listpane setborder borderfactory createemptyborder jpanel buttonpane jpanel buttonpane setlayout boxlayout buttonpane boxlayout x_axis buttonpane setborder borderfactory createemptyborder buttonpane createhorizontalglue buttonpane cancelbutton buttonpane createrigidarea buttonpane setbutton borderlayout contentpane getcontentpane contentpane listpane borderlayout contentpane buttonpane borderlayout addkeylistener keyadapter keypressed keyevent getkeycode keyevent vk_escape setvisible add key listener new key adapter public void key pressed key event ke int code ke get key code if code key event vk escape ke consume value null set visible false addkeylistener keyadapter keypressed keyevent getkeycode keyevent vk_escape setvisible shows the dialog public string show dialog component comp value null set location relative to comp set visible true return value showdialog setlocationrelativeto setvisible sets the last function selected private void set value string new value value new value list set selected value value true setvalue newvalue newvalue setselectedvalue performs an action public void action performed action event e string cmd e get action command if cmd equals cancel set visible false value null else if cmd equals select if list get selected index 0 return try value string list get selected value catch array index out of bounds exception exc return set visible false dim function source item debug gui dim function source by name value if item null dim source info si item source info string url si url int line number item first line file window w debug gui get file window url if w null debug gui create file window si line number w debug gui get file window url w set position 1 int start w get position line number 1 int end w get position line number 1 w text area select start w text area set caret position start w text area move caret position end try w show debug gui request focus w request focus w text area request focus catch exception exc actionperformed actionevent getactioncommand setvisible getselectedindex getselectedvalue arrayindexoutofboundsexception setvisible functionsource debuggui functionsourcebyname sourceinfo sourceinfo linenumber firstline filewindow debuggui getfilewindow debuggui createfilewindow linenumber debuggui getfilewindow setposition getposition linenumber getposition linenumber textarea textarea setcaretposition textarea movecaretposition debuggui requestfocus requestfocus textarea requestfocus class mouse handler extends mouse adapter public void mouse clicked mouse event e if e get click count 2 set button do click mousehandler mouseadapter mouseclicked mouseevent getclickcount setbutton doclick creates a new file header public file header file window file window this file window file window add mouse listener this update fileheader fileheader filewindow filewindow filewindow filewindow addmouselistener updates the gutter public void update file text area text area file window text area font font text area get font set font font font metrics metrics get font metrics font int h metrics get height int line count text area get line count 1 string dummy integer to string line count if dummy length 2 dummy 99 dimension d new dimension d width metrics string width dummy 16 d height line count h 100 set preferred size d set size d filetextarea textarea filewindow textarea textarea getfont setfont fontmetrics getfontmetrics getheight linecount textarea getlinecount tostring linecount stringwidth linecount setpreferredsize setsize paints the component public void paint graphics g super paint g file text area text area file window text area font font text area get font g set font font font metrics metrics get font metrics font rectangle clip g get clip bounds g set color get background g fill rect clip x clip y clip width clip height int left getx int ascent metrics get max ascent int h metrics get height int line count text area get line count 1 string dummy integer to string line count if dummy length 2 dummy 99 int max width metrics string width dummy int start line clip y h int end line clip y clip height h 1 int width get width if end line line count end line line count for int i start line i end line i string text int pos 2 try pos text area get line start offset i catch bad location exception ignored boolean is break point file window is break point i 1 text integer to string i 1 int w metrics string width text int y i h g set color color blue g draw string text 0 y ascent int x width ascent if is break point g set color new color 0x80 0x00 0x00 int dy y ascent 9 g fill oval x dy 9 9 g draw oval x dy 8 8 g draw oval x dy 9 9 if pos file window current pos polygon arrow new polygon int dx x y ascent 10 int dy y arrow add point dx dy 3 arrow add point dx 5 dy 3 for x dx 5 x dx 10 x y arrow add point x y for x dx 9 x dx 5 x y arrow add point x y arrow add point dx 5 dy 7 arrow add point dx dy 7 g set color color yellow g fill polygon arrow g set color color black g draw polygon arrow filetextarea textarea filewindow textarea textarea getfont setfont fontmetrics getfontmetrics getclipbounds setcolor getbackground fillrect getmaxascent getheight linecount textarea getlinecount tostring linecount maxwidth stringwidth startline endline getwidth endline linecount endline linecount startline endline textarea getlinestartoffset badlocationexception isbreakpoint filewindow isbreakpoint tostring stringwidth setcolor drawstring isbreakpoint setcolor filloval drawoval drawoval filewindow currentpos addpoint addpoint addpoint addpoint addpoint addpoint setcolor fillpolygon setcolor drawpolygon called when the mouse enters the component public void mouse entered mouse event e mouseentered mouseevent called when a mouse button is pressed public void mouse pressed mouse event e font font file window text area get font font metrics metrics get font metrics font int h metrics get height press line e gety h mousepressed mouseevent filewindow textarea getfont fontmetrics getfontmetrics getheight pressline called when the mouse is clicked public void mouse clicked mouse event e mouseclicked mouseevent called when the mouse exits the component public void mouse exited mouse event e mouseexited mouseevent called when a mouse button is released public void mouse released mouse event e if e get component this e get modifiers mouse event button1 mask 0 int x e getx int y e gety font font file window text area get font font metrics metrics get font metrics font int h metrics get height int line y h if line press line file window toggle break point line 1 else press line 1 mousereleased mouseevent getcomponent getmodifiers mouseevent button1_mask filewindow textarea getfont fontmetrics getfontmetrics getheight pressline filewindow togglebreakpoint pressline loads the file void load string url get url if url null run proxy proxy new run proxy debug gui run proxy load file proxy file name url proxy text source info source new thread proxy start geturl runproxy runproxy debuggui runproxy load_file filename sourceinfo returns the offset position for the given line public int get position int line int result 1 try result text area get line start offset line catch javax swing text bad location exception exc return result getposition textarea getlinestartoffset badlocationexception returns whether the given line has a breakpoint public boolean is break point int line return source info breakable line line source info breakpoint line isbreakpoint sourceinfo breakableline sourceinfo toggles the breakpoint on the given line public void toggle break point int line if is break point line set break point line else clear break point line togglebreakpoint isbreakpoint setbreakpoint clearbreakpoint sets a breakpoint on the given line public void set break point int line if source info breakable line line boolean changed source info breakpoint line true if changed file header repaint setbreakpoint sourceinfo breakableline sourceinfo fileheader clears a breakpoint from the given line public void clear break point int line if source info breakable line line boolean changed source info breakpoint line false if changed file header repaint clearbreakpoint sourceinfo breakableline sourceinfo fileheader creates a new file window public file window swing gui debug gui dim source info source info super swing gui get short name source info url true true true true this debug gui debug gui this source info source info update tool tip current pos 1 text area new file text area this text area set rows 24 text area set columns 80 p new j scroll pane file header new file header this p set viewport view text area p set row header view file header set content pane p pack update text source info text area select 0 filewindow filewindow swinggui debuggui sourceinfo sourceinfo swinggui getshortname sourceinfo debuggui debuggui sourceinfo sourceinfo updatetooltip currentpos textarea filetextarea textarea setrows textarea setcolumns jscrollpane fileheader fileheader setviewportview textarea setrowheaderview fileheader setcontentpane updatetext sourceinfo textarea updates the tool tip contents private void update tool tip in case file name is very long try to set tool tip on frame component c get component 1 this will work at least for metal l f if c null c instanceof j component j component c set tool tip text get url updatetooltip filename getcomponent jcomponent jcomponent settooltiptext geturl returns the url of the source public string get url return source info url geturl sourceinfo called when the text of the script has changed public void update text dim source info source info this source info source info string new text source info source if text area get text equals new text text area set text new text int pos 0 if current pos 1 pos current pos text area select pos file header update file header repaint updatetext sourceinfo sourceinfo sourceinfo sourceinfo newtext sourceinfo textarea gettext newtext textarea settext newtext currentpos currentpos textarea fileheader fileheader sets the cursor position public void set position int pos text area select pos current pos pos file header repaint setposition textarea currentpos fileheader selects a range of characters public void select int start int end int doc end text area get document get length text area select doc end doc end text area select start end docend textarea getdocument getlength textarea docend docend textarea disposes this file window public void dispose debug gui remove window this super dispose filewindow debuggui removewindow performs an action public void action performed action event e string cmd e get action command if cmd equals cut text area cut else if cmd equals copy text area copy else if cmd equals paste text area paste actionperformed actionevent getactioncommand textarea textarea textarea creates a new my table model public my table model swing gui debug gui this debug gui debug gui expressions new vector values new vector expressions add element values add element mytablemodel mytablemodel swinggui debuggui debuggui debuggui addelement addelement returns the number of columns in the table 2 public int get column count return 2 getcolumncount returns the number of rows in the table public int get row count return expressions size getrowcount returns the name of the given column public string get column name int column switch column case 0 return expression case 1 return value return null getcolumnname returns whether the given cell is editable public boolean is cell editable int row int column return true iscelleditable returns the value in the given cell public object get value at int row int column switch column case 0 return expressions element at row case 1 return values element at row return getvalueat elementat elementat sets the value in the given cell public void set value at object value int row int column switch column case 0 string expr value to string expressions set element at expr row string result if expr length 0 result debug gui dim eval expr if result null result values set element at result row update model if row 1 expressions size expressions add element values add element fire table rows inserted row 1 row 1 break case 1 just reset column 2 ignore edits fire table data changed setvalueat tostring setelementat debuggui setelementat updatemodel addelement addelement firetablerowsinserted firetabledatachanged re evaluates the expressions in the table void update model for int i 0 i expressions size i object value expressions element at i string expr value to string string result if expr length 0 result debug gui dim eval expr if result null result else result result result replace n values set element at result i fire table data changed updatemodel elementat tostring debuggui setelementat firetabledatachanged creates a new evaluator public evaluator swing gui debug gui super new my table model debug gui table model my table model get model swinggui debuggui mytablemodel debuggui tablemodel mytablemodel getmodel creates a new variable model public variable model variablemodel variablemodel creates a new variable model public variable model dim debugger object scope this debugger debugger this root new variable node scope this variablemodel variablemodel variablenode returns the root node of the tree public object get root if debugger null return null return root getroot returns the number of children of the given node public int get child count object node obj if debugger null return 0 variable node node variable node node obj return children node length getchildcount nodeobj variablenode variablenode nodeobj returns a child of the given node public object get child object node obj int i if debugger null return null variable node node variable node node obj return children node i getchild nodeobj variablenode variablenode nodeobj returns whether the given node is a leaf node public boolean is leaf object node obj if debugger null return true variable node node variable node node obj return children node length 0 isleaf nodeobj variablenode variablenode nodeobj returns the index of a node under its parent public int get index of child object parent obj object child obj if debugger null return 1 variable node parent variable node parent obj variable node child variable node child obj variable node children children parent for int i 0 i children length i if children i child return i return 1 getindexofchild parentobj childobj variablenode variablenode parentobj variablenode variablenode childobj variablenode returns whether the given cell is editable public boolean is cell editable object node int column return column 0 iscelleditable sets the value at the given cell public void set value at object value object node int column setvalueat public void set value at object value object node int column adds a tree model listener to this tree public void add tree model listener tree model listener l setvalueat treemodellistener addtreemodellistener treemodellistener public void add tree model listener tree model listener l removes a tree model listener from this tree public void remove tree model listener tree model listener l addtreemodellistener treemodellistener treemodellistener removetreemodellistener treemodellistener public void remove tree model listener tree model listener l public void value for path changed tree path path object new value removetreemodellistener treemodellistener valueforpathchanged treepath newvalue returns the number of columns public int get column count return c names length getcolumncount cnames returns the name of the given column public string get column name int column return c names column getcolumnname cnames returns the type of value stored in the given column public class get column class int column return c types column getcolumnclass ctypes returns the value at the given cell public object get value at object node obj int column if debugger null return null variable node node variable node node obj switch column case 0 name return node to string case 1 value string result try result debugger object to string get value node catch runtime exception exc result exc get message string buffer buf new string buffer int len result length for int i 0 i len i char ch result char at i if character isiso control ch ch buf append ch return buf to string return null getvalueat nodeobj variablenode variablenode nodeobj tostring objecttostring getvalue runtimeexception getmessage stringbuffer stringbuffer charat isisocontrol tostring returns an array of the children of the given node private variable node children variable node node if node children null return node children variable node children object value get value node object ids debugger get object ids value if ids length 0 children childless else arrays sort ids new comparator public int compare object l object r if l instanceof string if r instanceof integer return 1 return string l compare to ignore case string r else if r instanceof string return 1 int lint integer l int value int rint integer r int value return lint rint children new variable node ids length for int i 0 i ids length i children i new variable node value ids i node children children return children variablenode variablenode variablenode getvalue getobjectids comparetoignorecase intvalue intvalue variablenode variablenode arrays sort ids new comparator public int compare object l object r if l instanceof string if r instanceof integer return 1 return string l compare to ignore case string r else if r instanceof string return 1 int lint integer l int value int rint integer r int value return lint rint comparetoignorecase intvalue intvalue returns the value of the given node public object get value variable node node try return debugger get object property node object node id catch exception exc return undefined getvalue variablenode getobjectproperty creates a new variable node public variable node object object object id this object object this id id variablenode variablenode returns a string representation of this node public string to string return id instanceof string string id integer id int value tostring intvalue creates a new my tree table public my tree table variable model model super model mytreetable mytreetable variablemodel initializes a tree for this tree table public j tree reset tree tree table model tree table model tree new tree table cell renderer tree table model install a table model representing the visible rows in the tree super set model new tree table model adapter tree table model tree force the j table and j tree to share their row selection models list to tree selection model wrapper selection wrapper new list to tree selection model wrapper tree set selection model selection wrapper set selection model selection wrapper get list selection model make the tree and table row heights the same if tree get row height 1 metal looks better like this set row height 18 install the tree editor renderer and editor set default renderer tree table model class tree set default editor tree table model class new tree table cell editor set show grid true set intercell spacing new dimension 1 1 tree set root visible false tree set shows root handles true default tree cell renderer r default tree cell renderer tree get cell renderer r set open icon null r set closed icon null r set leaf icon null return tree jtree resettree treetablemodel treetablemodel treetablecellrenderer treetablemodel tablemodel setmodel treetablemodeladapter treetablemodel jtable jtree listtotreeselectionmodelwrapper selectionwrapper listtotreeselectionmodelwrapper setselectionmodel selectionwrapper setselectionmodel selectionwrapper getlistselectionmodel getrowheight setrowheight setdefaultrenderer treetablemodel setdefaulteditor treetablemodel treetablecelleditor setshowgrid setintercellspacing setrootvisible setshowsroothandles defaulttreecellrenderer defaulttreecellrenderer getcellrenderer setopenicon setclosedicon setleaficon returns whether the cell under the coordinates of the mouse in the link event object is editable public boolean is cell editable event object e if e instanceof mouse event mouse event me mouse event e if the modifiers are not 0 or the left mouse button tree may try and toggle the selection and table will then try and toggle resulting in the selection remaining the same to avoid this we only dispatch when the modifiers are 0 or the left mouse button if me get modifiers 0 me get modifiers input event button1 mask 1024 0 me get modifiers input event shift mask input event ctrl mask input event alt mask input event button2 mask input event button3 mask 64 shift down mask 128 ctrl down mask 512 alt down mask 2048 button2 down mask 4096 button3 down mask 0 int row row at point me get point for int counter get column count 1 counter 0 counter if tree table model class get column class counter mouse event newme new mouse event my tree table this tree me getid me get when me get modifiers me getx get cell rect row counter true x me gety me get click count me is popup trigger my tree table this tree dispatch event newme break if me get click count 3 return true return false if e null return true return false eventobject iscelleditable eventobject mouseevent mouseevent mouseevent getmodifiers getmodifiers inputevent button1_mask getmodifiers inputevent shift_mask inputevent ctrl_mask inputevent alt_mask inputevent button2_mask inputevent button3_mask shift_down_mask ctrl_down_mask alt_down_mask button2_down_mask button3_down_mask rowatpoint getpoint getcolumncount treetablemodel getcolumnclass mouseevent mouseevent mytreetable getwhen getmodifiers getcellrect getclickcount ispopuptrigger mytreetable dispatchevent getclickcount creates a new context window public context window final swing gui debug gui this debug gui debug gui enabled false j panel left new j panel j tool bar t1 new j tool bar t1 set name variables t1 set layout new grid layout t1 add left j panel p1 new j panel p1 set layout new grid layout j panel p2 new j panel p2 set layout new grid layout p1 add t1 j label label new j label context context new j combo box context set light weight popup enabled false tool tips new java util vector label set border context get border context add action listener this context set action command context switch grid bag layout layout new grid bag layout left set layout layout grid bag constraints lc new grid bag constraints lc insets left 5 lc anchor grid bag constraints west lc ipadx 5 layout set constraints label lc left add label grid bag constraints c new grid bag constraints c gridwidth grid bag constraints remainder c fill grid bag constraints horizontal c anchor grid bag constraints west layout set constraints context c left add context tabs new j tabbed pane swing constants bottom tabs set preferred size new dimension 500 300 this table new my tree table new variable model j scroll pane jsp new j scroll pane this table jsp get viewport set view size new dimension 5 2 tabs add this jsp locals table new my tree table new variable model locals table set auto resize mode j table auto resize all columns locals table set preferred size null jsp new j scroll pane locals table tabs add locals jsp c weightx c weighty 1 c gridheight grid bag constraints remainder c fill grid bag constraints both c anchor grid bag constraints west layout set constraints tabs c left add tabs evaluator new evaluator debug gui cmd line new eval text area debug gui cmd line request focus table model evaluator table model jsp new j scroll pane evaluator j tool bar t2 new j tool bar t2 set name evaluate tabs2 new j tabbed pane swing constants bottom tabs2 add watch jsp tabs2 add evaluate new j scroll pane cmd line tabs2 set preferred size new dimension 500 300 t2 set layout new grid layout t2 add tabs2 p2 add t2 evaluator set auto resize mode j table auto resize all columns split new j split pane j split pane horizontal split p1 p2 split set one touch expandable true swing gui set resize weight split 0 5 set layout new border layout add split border layout center final j tool bar finalt1 t1 final j tool bar finalt2 t2 final j panel finalp1 p1 final j panel finalp2 p2 final j split pane final split split final j panel final this this component listener clistener new component listener boolean t1 docked true boolean t2 docked true void check component comp component this parent final this get parent if this parent null return component parent finalt1 get parent boolean left docked true boolean right docked true boolean adjust vertical split false if parent null if parent finalp1 while parent instanceof j frame parent parent get parent j frame frame j frame parent debug gui add top level variables frame we need the following hacks because we want an undocked toolbar to be resizable we are using j toolbar as a container of a j combo box without this j combo box s popup can get left floating when the toolbar is re docked we make the frame resizable and then remove j toolbar s window listener and insert one of our own that first ensures the j combo box s popup window is closed and then calls j toolbar s window listener if frame is resizable frame set resizable true frame set default close operation window constants do nothing on close final event listener l frame get listeners window listener class frame remove window listener window listener l 0 frame add window listener new window adapter public void window closing window event e context hide popup window listener l 0 window closing e adjust vertical split true left docked false else left docked true parent finalt2 get parent if parent null if parent finalp2 while parent instanceof j frame parent parent get parent j frame frame j frame parent debug gui add top level evaluate frame frame set resizable true right docked false else right docked true if left docked t2 docked right docked t2 docked no change return t1 docked left docked t2 docked right docked j split pane split j split pane this parent if left docked if right docked final split set divider location 0 5 else final split set divider location 1 0 if adjust vertical split split set divider location 0 66 else if right docked final split set divider location 0 0 split set divider location 0 66 else both undocked split set divider location 1 0 public void component hidden component event e check e get component public void component moved component event e check e get component public void component resized component event e check e get component public void component shown component event e check e get component p1 add container listener new container listener public void component added container event e component this parent final this get parent j split pane split j split pane this parent if e get child finalt1 if finalt2 get parent finalp2 both docked final split set divider location 0 5 else left docked only final split set divider location 1 0 split set divider location 0 66 public void component removed container event e component this parent final this get parent j split pane split j split pane this parent if e get child finalt1 if finalt2 get parent finalp2 right docked only final split set divider location 0 0 split set divider location 0 66 else both undocked split set divider location 1 0 t1 add component listener clistener t2 add component listener clistener disable contextwindow contextwindow swinggui debuggui debuggui debuggui jpanel jpanel jtoolbar jtoolbar setname setlayout gridlayout jpanel jpanel setlayout gridlayout jpanel jpanel setlayout gridlayout jlabel jlabel jcombobox setlightweightpopupenabled tooltips setborder getborder addactionlistener setactioncommand contextswitch gridbaglayout gridbaglayout setlayout gridbagconstraints gridbagconstraints gridbagconstraints setconstraints gridbagconstraints gridbagconstraints gridbagconstraints gridbagconstraints gridbagconstraints setconstraints jtabbedpane swingconstants setpreferredsize thistable mytreetable variablemodel jscrollpane jscrollpane thistable getviewport setviewsize localstable mytreetable variablemodel localstable setautoresizemode jtable auto_resize_all_columns localstable setpreferredsize jscrollpane localstable gridbagconstraints gridbagconstraints gridbagconstraints setconstraints debuggui cmdline evaltextarea debuggui cmdline requestfocus tablemodel tablemodel jscrollpane jtoolbar jtoolbar setname jtabbedpane swingconstants jscrollpane cmdline setpreferredsize setlayout gridlayout setautoresizemode jtable auto_resize_all_columns jsplitpane jsplitpane horizontal_split setonetouchexpandable swinggui setresizeweight setlayout borderlayout borderlayout jtoolbar jtoolbar jpanel jpanel jsplitpane finalsplit jpanel finalthis componentlistener componentlistener t1docked t2docked thisparent finalthis getparent thisparent getparent leftdocked rightdocked adjustverticalsplit jframe getparent jframe jframe debuggui addtoplevel jtoolbar jcombobox jcombobox jtoolbar jcombobox jtoolbar isresizable setresizable setdefaultcloseoperation windowconstants do_nothing_on_close eventlistener getlisteners windowlistener removewindowlistener windowlistener addwindowlistener windowadapter windowclosing windowevent hidepopup windowlistener windowclosing adjustverticalsplit leftdocked leftdocked getparent jframe getparent jframe jframe debuggui addtoplevel setresizable rightdocked rightdocked leftdocked t2docked rightdocked t2docked t1docked leftdocked t2docked rightdocked jsplitpane jsplitpane thisparent leftdocked rightdocked finalsplit setdividerlocation finalsplit setdividerlocation adjustverticalsplit setdividerlocation rightdocked finalsplit setdividerlocation setdividerlocation setdividerlocation componenthidden componentevent getcomponent componentmoved componentevent getcomponent componentresized componentevent getcomponent componentshown componentevent getcomponent addcontainerlistener containerlistener componentadded containerevent thisparent finalthis getparent jsplitpane jsplitpane thisparent getchild getparent finalsplit setdividerlocation finalsplit setdividerlocation setdividerlocation componentremoved containerevent thisparent finalthis getparent jsplitpane jsplitpane thisparent getchild getparent finalsplit setdividerlocation setdividerlocation setdividerlocation addcomponentlistener addcomponentlistener boolean t2 docked true void check component comp component this parent final this get parent if this parent null return component parent finalt1 get parent boolean left docked true boolean right docked true boolean adjust vertical split false if parent null if parent finalp1 while parent instanceof j frame parent parent get parent j frame frame j frame parent debug gui add top level variables frame we need the following hacks because we want an undocked toolbar to be resizable we are using j toolbar as a container of a j combo box without this j combo box s popup can get left floating when the toolbar is re docked we make the frame resizable and then remove j toolbar s window listener and insert one of our own that first ensures the j combo box s popup window is closed and then calls j toolbar s window listener if frame is resizable frame set resizable true frame set default close operation window constants do nothing on close final event listener l frame get listeners window listener class frame remove window listener window listener l 0 frame add window listener new window adapter public void window closing window event e context hide popup window listener l 0 window closing e adjust vertical split true left docked false else left docked true parent finalt2 get parent if parent null if parent finalp2 while parent instanceof j frame parent parent get parent j frame frame j frame parent debug gui add top level evaluate frame frame set resizable true right docked false else right docked true if left docked t2 docked right docked t2 docked no change return t1 docked left docked t2 docked right docked j split pane split j split pane this parent if left docked if right docked final split set divider location 0 5 else final split set divider location 1 0 if adjust vertical split split set divider location 0 66 else if right docked final split set divider location 0 0 split set divider location 0 66 else both undocked split set divider location 1 0 t2docked thisparent finalthis getparent thisparent getparent leftdocked rightdocked adjustverticalsplit jframe getparent jframe jframe debuggui addtoplevel jtoolbar jcombobox jcombobox jtoolbar jcombobox jtoolbar isresizable setresizable setdefaultcloseoperation windowconstants do_nothing_on_close eventlistener getlisteners windowlistener removewindowlistener windowlistener addwindowlistener windowadapter windowclosing windowevent hidepopup windowlistener windowclosing adjustverticalsplit leftdocked leftdocked getparent jframe getparent jframe jframe debuggui addtoplevel setresizable rightdocked rightdocked leftdocked t2docked rightdocked t2docked t1docked leftdocked t2docked rightdocked jsplitpane jsplitpane thisparent leftdocked rightdocked finalsplit setdividerlocation finalsplit setdividerlocation adjustverticalsplit setdividerlocation rightdocked finalsplit setdividerlocation setdividerlocation setdividerlocation frame remove window listener window listener l 0 frame add window listener new window adapter public void window closing window event e context hide popup window listener l 0 window closing e removewindowlistener windowlistener addwindowlistener windowadapter windowclosing windowevent hidepopup windowlistener windowclosing public void component hidden component event e check e get component componenthidden componentevent getcomponent check e get component public void component moved component event e check e get component getcomponent componentmoved componentevent getcomponent check e get component public void component resized component event e check e get component getcomponent componentresized componentevent getcomponent check e get component public void component shown component event e check e get component getcomponent componentshown componentevent getcomponent p1 add container listener new container listener public void component added container event e component this parent final this get parent j split pane split j split pane this parent if e get child finalt1 if finalt2 get parent finalp2 both docked final split set divider location 0 5 else left docked only final split set divider location 1 0 split set divider location 0 66 addcontainerlistener containerlistener componentadded containerevent thisparent finalthis getparent jsplitpane jsplitpane thisparent getchild getparent finalsplit setdividerlocation finalsplit setdividerlocation setdividerlocation public void component removed container event e component this parent final this get parent j split pane split j split pane this parent if e get child finalt1 if finalt2 get parent finalp2 right docked only final split set divider location 0 0 split set divider location 0 66 else both undocked split set divider location 1 0 componentremoved containerevent thisparent finalthis getparent jsplitpane jsplitpane thisparent getchild getparent finalsplit setdividerlocation setdividerlocation setdividerlocation disables the component public void disable context set enabled false this table set enabled false locals table set enabled false evaluator set enabled false cmd line set enabled false setenabled thistable setenabled localstable setenabled setenabled cmdline setenabled enables the component public void enable context set enabled true this table set enabled true locals table set enabled true evaluator set enabled true cmd line set enabled true setenabled thistable setenabled localstable setenabled setenabled cmdline setenabled disables updating of the component public void disable update enabled false disableupdate enables updating of the component public void enable update enabled true enableupdate performs an action public void action performed action event e if enabled return if e get action command equals context switch dim context data context data debug gui dim current context data if context data null return int frame index context get selected index context set tool tip text tool tips element at frame index to string int frame count context data frame count if frame index frame count return dim stack frame frame context data get frame frame index object scope frame scope object this obj frame this obj this table reset tree new variable model debug gui dim this obj variable model scope model if scope this obj scope model new variable model debug gui dim scope else scope model new variable model locals table reset tree scope model debug gui dim context switch frame index debug gui show stop line frame table model update model actionperformed actionevent getactioncommand contextswitch contextdata contextdata debuggui currentcontextdata contextdata frameindex getselectedindex settooltiptext tooltips elementat frameindex tostring framecount contextdata framecount frameindex framecount stackframe contextdata getframe frameindex thisobj thisobj thistable resettree variablemodel debuggui thisobj variablemodel scopemodel thisobj scopemodel variablemodel debuggui scopemodel variablemodel localstable resettree scopemodel debuggui contextswitch frameindex debuggui showstopline tablemodel updatemodel creates a new menubar menubar swing gui debug gui super this debug gui debug gui string file items open run exit string file cmds open load exit char file short cuts 0 n 0 x int file accelerators key event vk o key event vk n 0 key event vk q string edit items cut copy paste go to function char edit short cuts t c p f string debug items break go step into step over step out char debug short cuts b g i o t string plaf items metal windows motif char plaf short cuts m w f int debug accelerators key event vk pause key event vk f5 key event vk f11 key event vk f7 key event vk f8 0 0 j menu file menu new j menu file file menu set mnemonic f j menu edit menu new j menu edit edit menu set mnemonic e j menu plaf menu new j menu platform plaf menu set mnemonic p j menu debug menu new j menu debug debug menu set mnemonic d window menu new j menu window window menu set mnemonic w for int i 0 i file items length i if file items i length 0 file menu add separator else j menu item item new j menu item file items i file short cuts i item set action command file cmds i item add action listener this file menu add item if file accelerators i 0 key stroke k key stroke get key stroke file accelerators i event ctrl mask item set accelerator k for int i 0 i edit items length i j menu item item new j menu item edit items i edit short cuts i item add action listener this edit menu add item for int i 0 i plaf items length i j menu item item new j menu item plaf items i plaf short cuts i item add action listener this plaf menu add item for int i 0 i debug items length i j menu item item new j menu item debug items i debug short cuts i item add action listener this if debug accelerators i 0 key stroke k key stroke get key stroke debug accelerators i 0 item set accelerator k if i 0 interrupt only items add item else run only items add item debug menu add item break on exceptions new j check box menu item break on exceptions break on exceptions set mnemonic x break on exceptions add action listener this break on exceptions set selected false debug menu add break on exceptions break on enter new j check box menu item break on function enter break on enter set mnemonic e break on enter add action listener this break on enter set selected false debug menu add break on enter break on return new j check box menu item break on function return break on return set mnemonic r break on return add action listener this break on return set selected false debug menu add break on return add file menu add edit menu add plaf menu add debug menu j menu item item window menu add item new j menu item cascade a item add action listener this window menu add item new j menu item tile t item add action listener this window menu add separator window menu add item new j menu item console c item add action listener this add window menu update enabled false swinggui debuggui debuggui debuggui fileitems filecmds fileshortcuts fileaccelerators keyevent vk_o keyevent vk_n keyevent vk_q edititems editshortcuts debugitems debugshortcuts plafitems plafshortcuts debugaccelerators keyevent vk_pause keyevent vk_f5 keyevent vk_f11 keyevent vk_f7 keyevent vk_f8 jmenu filemenu jmenu filemenu setmnemonic jmenu editmenu jmenu editmenu setmnemonic jmenu plafmenu jmenu plafmenu setmnemonic jmenu debugmenu jmenu debugmenu setmnemonic windowmenu jmenu windowmenu setmnemonic fileitems fileitems filemenu addseparator jmenuitem jmenuitem fileitems fileshortcuts setactioncommand filecmds addactionlistener filemenu fileaccelerators keystroke keystroke getkeystroke fileaccelerators ctrl_mask setaccelerator edititems jmenuitem jmenuitem edititems editshortcuts addactionlistener editmenu plafitems jmenuitem jmenuitem plafitems plafshortcuts addactionlistener plafmenu debugitems jmenuitem jmenuitem debugitems debugshortcuts addactionlistener debugaccelerators keystroke keystroke getkeystroke debugaccelerators setaccelerator interruptonlyitems runonlyitems debugmenu breakonexceptions jcheckboxmenuitem breakonexceptions setmnemonic breakonexceptions addactionlistener breakonexceptions setselected debugmenu breakonexceptions breakonenter jcheckboxmenuitem breakonenter setmnemonic breakonenter addactionlistener breakonenter setselected debugmenu breakonenter breakonreturn jcheckboxmenuitem breakonreturn setmnemonic breakonreturn addactionlistener breakonreturn setselected debugmenu breakonreturn filemenu editmenu plafmenu debugmenu jmenuitem windowmenu jmenuitem addactionlistener windowmenu jmenuitem addactionlistener windowmenu addseparator windowmenu jmenuitem addactionlistener windowmenu updateenabled returns the break on exceptions menu item public j check box menu item get break on exceptions return break on exceptions jcheckboxmenuitem getbreakonexceptions breakonexceptions returns the break on enter menu item public j check box menu item get break on enter return break on enter jcheckboxmenuitem getbreakonenter breakonenter returns the break on return menu item public j check box menu item get break on return return break on return jcheckboxmenuitem getbreakonreturn breakonreturn returns the debug menu public j menu get debug menu return get menu 2 jmenu getdebugmenu getmenu performs an action public void action performed action event e string cmd e get action command string plaf name null if cmd equals metal plaf name javax swing plaf metal metal look and feel else if cmd equals windows plaf name com sun java swing plaf windows windows look and feel else if cmd equals motif plaf name com sun java swing plaf motif motif look and feel else object source e get source if source break on exceptions debug gui dim set break on exceptions break on exceptions is selected else if source break on enter debug gui dim set break on enter break on enter is selected else if source break on return debug gui dim set break on return break on return is selected else debug gui action performed e return try ui manager set look and feel plaf name swing utilities update component treeui debug gui swing utilities update component treeui debug gui dlg catch exception ignored ignored print stack trace actionperformed actionevent getactioncommand plaf_name plaf_name metallookandfeel plaf_name windowslookandfeel plaf_name motiflookandfeel getsource breakonexceptions debuggui setbreakonexceptions breakonexceptions isselected breakonenter debuggui setbreakonenter breakonenter isselected breakonreturn debuggui setbreakonreturn breakonreturn isselected debuggui actionperformed uimanager setlookandfeel plaf_name swingutilities updatecomponenttreeui debuggui swingutilities updatecomponenttreeui debuggui printstacktrace adds a file to the window menu public void add file string url int count window menu get item count j menu item item if count 4 window menu add separator count j menu item last item window menu get item count 1 boolean has more win false int max win 5 if last item null last item get text equals more windows has more win true max win if has more win count 4 5 window menu add item new j menu item more windows m item set action command more windows item add action listener this return else if count 4 max win if has more win count window menu remove last item string short name swing gui get short name url window menu add item new j menu item char 0 count 4 short name 0 count 4 if has more win window menu add last item else return item set action command url item add action listener this addfile windowmenu getitemcount jmenuitem windowmenu addseparator jmenuitem lastitem windowmenu getitem hasmorewin maxwin lastitem lastitem gettext hasmorewin maxwin hasmorewin windowmenu jmenuitem setactioncommand addactionlistener maxwin hasmorewin windowmenu lastitem shortname swinggui getshortname windowmenu jmenuitem shortname hasmorewin windowmenu lastitem setactioncommand addactionlistener updates the enabledness of menu items public void update enabled boolean interrupted for int i 0 i interrupt only items size i j menu item item j menu item interrupt only items element at i item set enabled interrupted for int i 0 i run only items size i j menu item item j menu item run only items element at i item set enabled interrupted updateenabled interruptonlyitems jmenuitem jmenuitem interruptonlyitems elementat setenabled runonlyitems jmenuitem jmenuitem runonlyitems elementat setenabled creates a new run proxy public run proxy swing gui debug gui int type this debug gui debug gui this type type runproxy runproxy swinggui debuggui debuggui debuggui runs this runnable public void run switch type case open file try debug gui dim compile script file name text catch runtime exception ex message dialog wrapper show message dialog debug gui ex get message error compiling file name j option pane error message break case load file try debug gui dim eval script file name text catch runtime exception ex message dialog wrapper show message dialog debug gui ex get message run error for file name j option pane error message break case update source text string file name source info url file window w debug gui get file window file name if w null w update text source info w show else if file name equals stdin debug gui create file window source info 1 break case enter interrupt debug gui enter interrupt impl last frame thread title alert message break default throw new illegal argument exception string value of type open_file debuggui compilescript filename runtimeexception messagedialogwrapper showmessagedialog debuggui getmessage filename joptionpane error_message load_file debuggui evalscript filename runtimeexception messagedialogwrapper showmessagedialog debuggui getmessage filename joptionpane error_message update_source_text filename sourceinfo filewindow debuggui getfilewindow filename updatetext sourceinfo filename debuggui createfilewindow sourceinfo enter_interrupt debuggui enterinterruptimpl lastframe threadtitle alertmessage illegalargumentexception valueof create a new test case object param passed true if the test case passed otherwise false param name label associated with the test case param description string showing what got tested usually java script code param expect string representation of the expected result param actual string representation of the actual result param reason reason for test failure see com netscape javascript qa drivers test driver see com netscape javascript qa drivers test environment public test case string passed string name string description string expect string actual string reason this passed passed this name name this description description this expect expect this actual actual this reason reason testcase javascript testdriver testenvironment testcase public string float float public string ambiguous boolean arg return boolean object boolean_object public string ambiguous boolean arg return boolean public string ambiguous object arg return object public string ambiguous string arg return string public string ambiguous byte arg return byte public string ambiguous char arg return char public string ambiguous short arg return short public string ambiguous int arg return int public string expect return int the zero parameter constructor when scriptable object define class is called with this class it will construct matrix prototype using this constructor public matrix scriptableobject defineclass the java constructor also used to define the java script constructor public matrix int dimension if dimension 0 throw context report runtime error dimension of matrix must be greater than zero dim dimension v new vector javascript reportruntimeerror returns the name of this java script class matrix public string get class name return matrix javascript getclassname defines the dim property by returning true if name is equal to dim p defines no other properties i e returns false for all other names param name the name of the property param start the object where lookup began public boolean has string name scriptable start return name equals dim defines all numeric properties by returning true param index the index of the property param start the object where lookup began public boolean has int index scriptable start return true get the named property p handles the dim property and returns not found for all other names param name the property name param start the object where the lookup began public object get string name scriptable start if name equals dim return new integer dim return not found not_found not_found get the indexed property p look up the element in the associated vector and return it if it exists if it doesn t exist create it p param index the index of the integral property param start the object where the lookup began public object get int index scriptable start if index v size v set size index 1 object result v element at index if result null return result if dim 2 matrix m new matrix dim 1 m set parent scope get parent scope m set prototype get prototype result m else context cx context get current context scriptable scope scriptable object get top level scope start result cx new array scope 0 v set element at result index return result setsize elementat setparentscope getparentscope setprototype getprototype getcurrentcontext scriptableobject gettoplevelscope newarray setelementat set a named property we do nothing here so all properties are effectively read only public void put string name scriptable start object value set an indexed property we do nothing here so all properties are effectively read only public void put int index scriptable start object value remove a named property this method shouldn t even be called since we define all properties as permanent public void delete string id remove an indexed property this method shouldn t even be called since we define all properties as permanent public void delete int index get prototype public scriptable get prototype return prototype getprototype set prototype public void set prototype scriptable prototype this prototype prototype setprototype get parent public scriptable get parent scope return parent getparentscope set parent public void set parent scope scriptable parent this parent parent setparentscope get properties we return an empty array since we define all properties to be dontenum public object get ids return new object 0 getids default value use the convenience method from context that takes care of calling to string etc public object get default value class type hint return object matrix tostring getdefaultvalue typehint instanceof operator we mimick the normal java script instanceof semantics returning true if code this code appears in code value code s prototype chain public boolean has instance scriptable value scriptable proto value get prototype while proto null if proto equals this return true proto proto get prototype return false javascript hasinstance getprototype getprototype public string jsobject jsobject public string ambiguous boolean arg return boolean object boolean_object public string ambiguous boolean arg return boolean public string ambiguous byte arg return byte public string ambiguous char arg return char public string ambiguous short arg return short public string ambiguous int arg return int public string ambiguous long arg return long member box ctor public native java constructor member box ctor this ctor ctor memberbox nativejavaconstructor memberbox public object call context cx scriptable scope scriptable this obj object args return native java class construct specific cx scope args ctor thisobj nativejavaclass constructspecific public string get function name string sig java members live connect signature ctor arg types return init concat sig getfunctionname javamembers liveconnectsignature argtypes public string to string return java constructor ctor get name tostring javaconstructor getname static void init scriptable scope boolean sealed native call obj new native call obj export asjs class max prototype id scope sealed nativecall nativecall exportasjsclass max_prototype_id native call nativecall native call native function function scriptable scope object args this function function set parent scope scope leave prototype null this original args args null script runtime empty args args initialize values of arguments int param and var count function get param and var count int param count function get param count if param and var count 0 for int i 0 i param count i string name function get param or var name i object val i args length args i undefined instance define property name val permanent initialize arguments property but only if it was not overriden by the parameter with the same name if super has arguments this define property arguments new arguments this permanent if param and var count 0 for int i param count i param and var count i string name function get param or var name i if super has name this define property name undefined instance permanent nativecall nativefunction setparentscope originalargs scriptruntime emptyargs paramandvarcount getparamandvarcount paramcount getparamcount paramandvarcount paramcount getparamorvarname defineproperty defineproperty paramandvarcount paramcount paramandvarcount getparamorvarname defineproperty public string get class name return call getclassname protected int find prototype id string s return s equals constructor id constructor 0 findprototypeid id_constructor protected void init prototype id int id string s int arity if id id constructor arity 1 s constructor else throw new illegal argument exception string value of id init prototype method call tag id s arity initprototypeid id_constructor illegalargumentexception valueof initprototypemethod call_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag call tag return super exec id call f cx scope this obj args int id f method id if id id constructor if this obj null throw context report runtime error1 msg only from new call script runtime check deprecated cx call native call result new native call result set prototype get object prototype scope return result throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag call_tag execidcall thisobj methodid id_constructor thisobj reportruntimeerror1 scriptruntime checkdeprecated nativecall nativecall setprototype getobjectprototype illegalargumentexception valueof public string float float public string ambiguous boolean arg return boolean public string ambiguous boolean arg return boolean object boolean_object public string ambiguous double arg return double object double_object public string expect return boolean public abstract class security proxy extends security controller protected abstract void call process file secure context cx scriptable scope string filename securityproxy securitycontroller callprocessfilesecure public lazily loaded ctor scriptable object scope string ctor name string class name boolean sealed this class name class name this ctor name ctor name this sealed sealed if getter null method methods function object get method list get class getter function object find single method methods get property setter function object find single method methods set property scope define property ctor name this getter setter scriptable object dontenum lazilyloadedctor scriptableobject ctorname classname classname classname ctorname ctorname functionobject getmethodlist getclass functionobject findsinglemethod getproperty functionobject findsinglemethod setproperty defineproperty ctorname scriptableobject public object get property scriptable object obj synchronized obj if is replaced boolean remove on error false class cl kit class or null class name if cl null remove on error true else try scriptable object define class obj cl sealed is replaced true catch invocation target exception ex throwable target ex get target exception if target instanceof runtime exception throw runtime exception target remove on error true catch rhino exception ex remove on error true catch instantiation exception ex remove on error true catch illegal access exception ex remove on error true catch security exception ex treat security exceptions as absence of object they can be due to the following reasons java lang runtime permission create class loader remove on error true catch linkage error ex no dependant classes remove on error true if remove on error obj delete ctor name return scriptable not found get just added object return obj get ctor name obj getproperty scriptableobject isreplaced removeonerror classornull classname removeonerror scriptableobject defineclass isreplaced invocationtargetexception gettargetexception runtimeexception runtimeexception removeonerror rhinoexception removeonerror instantiationexception removeonerror illegalaccessexception removeonerror securityexception runtimepermission createclassloader removeonerror linkageerror removeonerror removeonerror ctorname not_found ctorname public object set property scriptable object obj object val synchronized obj is replaced true return val setproperty scriptableobject isreplaced public string jsobject jsobject public string ambiguous boolean arg return boolean object boolean_object public string ambiguous boolean arg return boolean public string ambiguous byte arg return byte public string ambiguous char arg return char public string ambiguous short arg return short public string ambiguous int arg return int public string ambiguous long arg return long public string ambiguous float arg return float public string ambiguous double arg return double public string ambiguous string arg return string xml with scope xml lib impl lib scriptable parent xml object prototype super parent prototype this lib lib xmlwithscope xmllibimpl xmlobject void init as dot query xml object prototype xml object get prototype xml with scope also handles the xxx dot query for xml basically dot query is a for in with statement and in the following 3 statements we setup to signal it s dot query the index and the object being looped over the xws set prototype is the scope of the object which is is a element of the lhs xml list currindex 0 dqprototype prototype if prototype instanceof xml list xml list xl xml list prototype if xl length 0 set prototype scriptable xl get 0 null always return the outer most type of xml l value of xml to left of dot query xmllist new xml list lib initasdotquery xmlobject xmlobject getprototype xmlwithscope dotquery dotquery dotquery setprototype xmllist _currindex _dqprototype xmllist xmllist xmllist setprototype lvalue dotquery _xmllist xmllist protected object update dot query boolean value return null to continue looping xml object seed dqprototype xml list xmll xmllist object result if seed instanceof xml list we re a list so keep testing each element of the list if the result on the top of stack is true then that element is added to our result list if false we try the next element xml list org xmll xml list seed int idx currindex if value xmll add to list org xmll get idx null more elements to test if idx org xmll length yes set our new index get the next element and reset the expression to run with this object as the with selector currindex idx set prototype scriptable org xmll get idx null continue looping return null else if we re not a xml list then there s no looping just return dq prototype if the result is true if value xmll add to list seed return xmll updatedotquery xmlobject _dqprototype xmllist _xmllist xmllist xmllist orgxmll xmllist _currindex addtolist orgxmll orgxmll _currindex setprototype orgxmll xmllist dqprototype addtolist public static xml lib extract from scope or null scriptable scope scriptable object so script runtime get library scope or null scope if so null if librray is not yet initialized return null return null ensure lazily initialization of real xml library instance which is done on first access to xml property scriptable object get property so xml return xml lib so get associated value xml lib key xmllib extractfromscopeornull scriptableobject scriptruntime getlibraryscopeornull scriptableobject getproperty xmllib getassociatedvalue xml_lib_key public static xml lib extract from scope scriptable scope xml lib lib extract from scope or null scope if lib null return lib string msg script runtime get message0 msg xml not available throw context report runtime error msg xmllib extractfromscope xmllib extractfromscopeornull scriptruntime getmessage0 reportruntimeerror protected final xml lib bind to scope scriptable scope scriptable object so script runtime get library scope or null scope if so null standard library should be initialized at this point throw new illegal state exception return xml lib so associate value xml lib key this xmllib bindtoscope scriptableobject scriptruntime getlibraryscopeornull illegalstateexception xmllib associatevalue xml_lib_key public abstract boolean isxml name context cx object name isxmlname public abstract boolean isxml name context cx object name public abstract ref name ref context cx object name scriptable scope int member type flags isxmlname nameref membertypeflags scriptable scope int member type flags public abstract ref name ref context cx object namespace object name scriptable scope int member type flags membertypeflags nameref membertypeflags escapes the reserved characters in a value of an attribute and surround it by param value unescaped text return the escaped text escapes the reserved characters in a value of a text node param value unescaped text return the escaped text construct namespace for default xml statement public abstract object to default xml namespace context cx object uri value todefaultxmlnamespace urivalue public string jsobject jsobject public string ambiguous boolean arg return boolean object boolean_object public string ambiguous boolean arg return boolean public string ambiguous byte arg return byte public string ambiguous char arg return char public string ambiguous short arg return short public string ambiguous int arg return int public string ambiguous long arg return long public string ambiguous float arg return float static final long serial versionuid 8743165779676009808l public evaluator exception string detail super detail serialversionuid evaluatorexception create an exception with the specified detail message errors internal to the java script engine will simply throw a runtime exception param detail the error message param source name the name of the source reponsible for the error param line number the line number of the source public evaluator exception string detail string source name int line number this detail source name line number null 0 javascript runtimeexception sourcename linenumber evaluatorexception sourcename linenumber sourcename linenumber create an exception with the specified detail message errors internal to the java script engine will simply throw a runtime exception param detail the error message param source name the name of the source reponsible for the error param line number the line number of the source param column number the column number of the source may be zero if unknown param line source the source of the line containing the error may be null if unknown public evaluator exception string detail string source name int line number string line source int column number super detail record error origin source name line number line source column number javascript runtimeexception sourcename linenumber columnnumber columnnumber linesource evaluatorexception sourcename linenumber linesource columnnumber recorderrororigin sourcename linenumber linesource columnnumber deprecated use link rhino exception source name from the super class public string get source name return source name rhinoexception sourcename getsourcename sourcename deprecated use link rhino exception line number from the super class public int get line number return line number rhinoexception linenumber getlinenumber linenumber deprecated use link rhino exception column number from the super class public int get column number return column number rhinoexception columnnumber getcolumnnumber columnnumber deprecated use link rhino exception line source from the super class public string get line source return line source rhinoexception linesource getlinesource linesource public string float float public string ambiguous boolean arg return boolean public string ambiguous byte arg return byte public string ambiguous short arg return short public string ambiguous int arg return int public string ambiguous long arg return long public string ambiguous float arg return float public string ambiguous double arg return double object double_object public string ambiguous double arg return double public string ambiguous char arg return char public string ambiguous object arg return object public string ambiguous string arg return string public string expect return string public static void init context cx scriptable scope boolean sealed native reg exp proto new native reg exp proto re re compiled compilere null false proto activate prototype map max prototype id proto set parent scope scope proto set prototype get object prototype scope native reg exp ctor ctor new native reg exp ctor bug 324006 ecma 262 15 10 6 1 says the initial value of reg exp prototype constructor is the builtin reg exp constructor proto put constructor proto ctor script runtime set function proto and parent ctor scope ctor set immune prototype property proto if sealed proto seal object ctor seal object define property scope reg exp ctor scriptable object dontenum nativeregexp nativeregexp recompiled activateprototypemap max_prototype_id setparentscope setprototype getobjectprototype nativeregexpctor nativeregexpctor regexp regexp scriptruntime setfunctionprotoandparent setimmuneprototypeproperty sealobject sealobject defineproperty regexp scriptableobject native reg exp scriptable scope object regexp compiled this re re compiled regexp compiled this last index 0 script runtime set object proto and parent this scope nativeregexp regexpcompiled recompiled regexpcompiled lastindex scriptruntime setobjectprotoandparent public string get class name return reg exp getclassname regexp public object call context cx scriptable scope scriptable this obj object args return exec sub cx scope args match thisobj execsub public scriptable construct context cx scriptable scope object args return scriptable exec sub cx scope args match execsub scriptable compile context cx scriptable scope object args if args length 0 args 0 instanceof native reg exp if args length 1 args 1 undefined instance report error throw script runtime type error0 msg bad regexp compile native reg exp that obj native reg exp args 0 this re that obj re this last index that obj last index return this string s args length 0 script runtime to string args 0 string global args length 1 args 1 undefined instance script runtime to string args 1 null this re re compiled compilere s global false this last index 0 return this nativeregexp scriptruntime typeerror0 nativeregexp thatobj nativeregexp thatobj lastindex thatobj lastindex scriptruntime tostring scriptruntime tostring recompiled lastindex public string to string string buffer buf new string buffer buf append if re source length 0 buf append re source else see bugzilla 226045 buf append buf append if re flags jsreg glob 0 buf append g if re flags jsreg fold 0 buf append i if re flags jsreg multiline 0 buf append m return buf to string tostring stringbuffer stringbuffer jsreg_glob jsreg_fold jsreg_multiline tostring native reg exp nativeregexp native reg exp private static reg exp impl get impl context cx return reg exp impl script runtime get reg exp proxy cx nativeregexp regexpimpl getimpl regexpimpl scriptruntime getregexpproxy private object exec sub context cx scriptable scope obj object args int match type reg exp impl re impl get impl cx string str if args length 0 str re impl input if str null report error msg no re input for to string else str script runtime to string args 0 double d re flags jsreg glob 0 last index 0 object rval if d 0 str length d last index 0 rval null else int indexp int d rval execute reg exp cx scope obj re impl str indexp match type if re flags jsreg glob 0 last index rval null rval undefined instance 0 indexp 0 return rval execsub scopeobj matchtype regexpimpl reimpl getimpl reimpl reporterror tostring scriptruntime tostring jsreg_glob lastindex lastindex executeregexp scopeobj reimpl matchtype jsreg_glob lastindex static object compilere string str string global boolean flat re compiled regexp new re compiled regexp source str to char array int length str length int flags 0 if global null for int i 0 i global length i char c global char at i if c g flags jsreg glob else if c i flags jsreg fold else if c m flags jsreg multiline else report error msg invalid re flag string value of c regexp flags flags compiler state state new compiler state regexp source length flags if flat length 0 if debug system out println flat str state result new re node reop flat state result chr state cpbegin 0 state result length length state result flat index 0 state prog length 5 else if parse disjunction state return null regexp program new byte state prog length 1 if state class count 0 regexp class list new re char set state class count regexp class count state class count int endpc emitre bytecode state regexp 0 state result regexp program endpc reop end if debug system out println prog length endpc for int i 0 i endpc i system out print regexp program i if i endpc 1 system out print system out println regexp paren count state paren count if re starts with literal init anchor ch accordingly switch regexp program 0 case reop ucflat1 case reop ucflat1i regexp anchor ch char get index regexp program 1 break case reop flat1 case reop flat1i regexp anchor ch char regexp program 1 0xff break case reop flat case reop flati int k get index regexp program 1 regexp anchor ch regexp source k break if debug if regexp anchor ch 0 system out println anchor ch char regexp anchor ch return regexp recompiled recompiled tochararray charat jsreg_glob jsreg_fold jsreg_multiline reporterror valueof compilerstate compilerstate renode reop_flat flatindex proglength parsedisjunction proglength classcount classlist recharset classcount classcount classcount emitrebytecode reop_end parencount parencount anchorch reop_ucflat1 reop_ucflat1i anchorch getindex reop_flat1 reop_flat1i anchorch reop_flat reop_flati getindex anchorch anchorch anchorch static boolean is digit char c return 0 c c 9 isdigit private static boolean is word char c return character is letter c is digit c c isword isletter isdigit _ private static boolean is line term char c return script runtime isjs line terminator c islineterm scriptruntime isjslineterminator private static boolean isre white space int c return c u0020 c u0009 c n c r c 0x2028 c 0x2029 c u000c c u000b c u00a0 character get type char c character space separator isrewhitespace gettype space_separator private static char upcase char ch if ch 128 if a ch ch z return char ch a a return ch char cu character to upper case ch if ch 128 cu 128 return ch return cu touppercase private static char downcase char ch if ch 128 if a ch ch z return char ch a a return ch char cl character to lower case ch if ch 128 cl 128 return ch return cl tolowercase private static int toascii hex digit int c if c 0 return 1 if c 9 return c 0 c 0x20 if a c c f return c a 10 return 1 toasciihexdigit private static boolean parse disjunction compiler state state if parse alternative state return false char source state cpbegin int index state cp if index source length source index re node alt result state cp alt result new re node reop alt alt result kid state result if parse disjunction state return false alt result kid2 state result state result alt result alt next jump end jump end state prog length 9 return true parsedisjunction compilerstate parsealternative renode altresult altresult renode reop_alt altresult parsedisjunction altresult altresult proglength private static boolean parse alternative compiler state state re node head term null re node tail term null char source state cpbegin while true if state cp state cpend source state cp state paren nesting 0 source state cp if head term null state result new re node reop empty else state result head term return true if parse term state return false if head term null head term state result else if tail term null head term next state result tail term state result while tail term next null tail term tail term next else tail term next state result tail term tail term next while tail term next null tail term tail term next parsealternative compilerstate renode headterm renode tailterm parennesting headterm renode reop_empty headterm parseterm headterm headterm tailterm headterm tailterm tailterm tailterm tailterm tailterm tailterm tailterm tailterm tailterm tailterm calculate the total size of the bitmap required for a class expression private static boolean calculate bitmap size compiler state state re node target char src int index int end char range start 0 char c int n int digit int n digits int i int max 0 boolean in range false target bmsize 0 if index end return true if src index index while index end int local max 0 n digits 2 switch src index case index c src index switch c case b local max 0x8 break case f local max 0xc break case n local max 0xa break case r local max 0xd break case t local max 0x9 break case v local max 0xb break case c if index 1 end character is letter src index 1 local max char src index 0x1f else local max break case u n digits 2 fall thru case x n 0 for i 0 i n digits index end i c src index n kit x digit to int c n if n 0 back off to accepting the original as a literal index i 1 n break local max n break case d if in range report error msg bad range return false local max 9 break case d case s case s case w case w if in range report error msg bad range return false target bmsize 65535 return true case 0 case 1 case 2 case 3 case 4 case 5 case 6 case 7 this is a non ecma extension decimal escapes in this case octal are supposed to be an error inside class ranges but supported here for backwards compatibility n c 0 c src index if 0 c c 7 index n 8 n c 0 c src index if 0 c c 7 index i 8 n c 0 if i 0377 n i else index local max n break default local max c break break default local max src index break if in range if range start local max report error msg bad range return false in range false else if index end 1 if src index index in range true range start char local max continue if state flags jsreg fold 0 char cu upcase char local max char cd downcase char local max local max cu cd cu cd if local max max max local max target bmsize max return true calculatebitmapsize compilerstate renode rangestart ndigits inrange localmax ndigits localmax localmax localmax localmax localmax localmax isletter localmax localmax ndigits ndigits xdigittoint localmax inrange reporterror localmax inrange reporterror localmax localmax localmax inrange rangestart localmax reporterror inrange inrange rangestart localmax jsreg_fold localmax localmax localmax localmax localmax private static void do flat compiler state state char c state result new re node reop flat state result chr c state result length 1 state result flat index 1 state prog length 3 doflat compilerstate renode reop_flat flatindex proglength private static int get decimal value char c compiler state state int max value string overflow message id boolean overflow false int start state cp char src state cpbegin int value c 0 for state cp state cpend state cp c src state cp if is digit c break if overflow int digit c 0 if value max value digit 10 value value 10 digit else overflow true value max value if overflow report error overflow message id string value of src start state cp start return value getdecimalvalue compilerstate maxvalue overflowmessageid isdigit maxvalue maxvalue reporterror overflowmessageid valueof private static boolean parse term compiler state state char src state cpbegin char c src state cp int n digits 2 int paren base count state paren count int num tmp re node term int term start int ocp state cp switch c assertions and atoms case state result new re node reop bol state prog length return true case state result new re node reop eol state prog length return true case if state cp state cpend c src state cp switch c assertion escapes case b state result new re node reop wbdry state prog length return true case b state result new re node reop wnonbdry state prog length return true decimal escape case 0 under strict ecma 3 we interpret 0 as nul and don t accept octal however xxx and since rhino doesn t have a strict mode we ll just behave the old way for compatibility reasons see http bugzilla mozilla org show bug cgi id 141078 octal escape num 0 while state cp state cpend c src state cp if c 0 c 7 state cp tmp 8 num c 0 if tmp 0377 break num tmp else break c char num do flat state c break case 1 case 2 case 3 case 4 case 5 case 6 case 7 case 8 case 9 term start state cp 1 num get decimal value c state 0xffff msg overlarge backref n 9 and count of parentheses then treat as octal instead if num 9 num state paren count state cp term start num 0 while state cp state cpend c src state cp if c 0 c 7 state cp tmp 8 num c 0 if tmp 0377 break num tmp else break c char num do flat state c break otherwise it s a back reference state result new re node reop backref state result paren index num 1 state prog length 3 break control escape case f c 0xc do flat state c break case n c 0xa do flat state c break case r c 0xd do flat state c break case t c 0x9 do flat state c break case v c 0xb do flat state c break control letter case c if state cp 1 state cpend character is letter src state cp 1 c char src state cp 0x1f else back off to accepting the original as a literal state cp c do flat state c break unicode escape sequence case u n digits 2 fall thru hex escape sequence case x int n 0 int i for i 0 i n digits state cp state cpend i int digit c src state cp n kit x digit to int c n if n 0 back off to accepting the original u or x as a literal state cp i 2 n src state cp break c char n do flat state c break character class escapes case d state result new re node reop digit state prog length break case d state result new re node reop nondigit state prog length break case s state result new re node reop space state prog length break case s state result new re node reop nonspace state prog length break case w state result new re node reop alnum state prog length break case w state result new re node reop nonalnum state prog length break identity escape default state result new re node reop flat state result chr c state result length 1 state result flat index state cp 1 state prog length 3 break break else a trailing is an error report error msg trail backslash return false case re node result null term start state cp if state cp 1 state cpend src state cp c src state cp 1 c c state cp 2 if c result new re node reop assert assert next asserttest state prog length 4 else if c result new re node reop assert not assertnot next assertnottest state prog length 4 else result new re node reop lparen lparen index rparen index state prog length 6 result paren index state paren count state paren nesting if parse disjunction state return false if state cp state cpend src state cp report error msg unterm paren return false state cp state paren nesting if result null result kid state result state result result break case report error msg re unmatched right paren return false case state result new re node reop class term start state cp state result start index term start while true if state cp state cpend report error msg unterm class return false if src state cp state cp else if src state cp state result kidlen state cp term start break state cp state result index state class count call calculate bitmap size now as we want any errors it finds to be reported during the parse phase not at execution if calculate bitmap size state state result src term start state cp return false state prog length 3 clas parseterm compilerstate ndigits parenbasecount parencount renode termstart renode reop_bol proglength renode reop_eol proglength renode reop_wbdry proglength renode reop_wnonbdry proglength show_bug doflat termstart getdecimalvalue parencount termstart doflat renode reop_backref parenindex proglength doflat doflat doflat doflat doflat isletter doflat unicodeescapesequence ndigits hexescapesequence ndigits xdigittoint doflat renode reop_digit proglength renode reop_nondigit proglength renode reop_space proglength renode reop_nonspace proglength renode reop_alnum proglength renode reop_nonalnum proglength identityescape renode reop_flat flatindex proglength reporterror renode termstart renode reop_assert proglength renode reop_assert_not proglength renode reop_lparen proglength parenindex parencount parennesting parsedisjunction reporterror parennesting reporterror renode reop_class termstart startindex termstart reporterror termstart classcount calculatebitmapsize calculatebitmapsize termstart proglength private static void resolve forward jump byte array int from int pc if from pc throw kit code bug add index array from pc from resolveforwardjump codebug addindex private static int get offset byte array int pc return get index array pc getoffset getindex private static int add index byte array int pc int index if index 0 throw kit code bug if index 0xffff throw context report runtime error too complex regexp array pc byte index 8 array pc 1 byte index return pc 2 addindex codebug reportruntimeerror private static int get index byte array int pc return array pc 0xff 8 array pc 1 0xff getindex private static int emitre bytecode compiler state state re compiled re int pc re node t re node next alt int next alt fixup next term fixup byte program re program while t null program pc t op switch t op case reop empty pc break case reop alt next alt t kid2 next alt fixup pc address of next alternate pc offset len pc emitre bytecode state re pc t kid program pc reop jump next term fixup pc address of following term pc offset len resolve forward jump program next alt fixup pc pc emitre bytecode state re pc next alt program pc reop jump next alt fixup pc pc offset len resolve forward jump program next term fixup pc resolve forward jump program next alt fixup pc break case reop flat consecutize flat s if possible if t flat index 1 while t next null t next op reop flat t flat index t length t next flat index t length t next length t next t next next if t flat index 1 t length 1 if state flags jsreg fold 0 program pc 1 reop flati else program pc 1 reop flat pc add index program pc t flat index pc add index program pc t length else if t chr 256 if state flags jsreg fold 0 program pc 1 reop flat1i else program pc 1 reop flat1 program pc byte t chr else if state flags jsreg fold 0 program pc 1 reop ucflat1i else program pc 1 reop ucflat1 pc add index program pc t chr break case reop lparen pc add index program pc t paren index pc emitre bytecode state re pc t kid program pc reop rparen pc add index program pc t paren index break case reop backref pc add index program pc t paren index break case reop assert next term fixup pc pc offset len pc emitre bytecode state re pc t kid program pc reop asserttest resolve forward jump program next term fixup pc break case reop assert not next term fixup pc pc offset len pc emitre bytecode state re pc t kid program pc reop assertnottest resolve forward jump program next term fixup pc break case reop quant if t min 0 t max 1 program pc 1 t greedy reop star reop minimalstar else if t min 0 t max 1 program pc 1 t greedy reop opt reop minimalopt else if t min 1 t max 1 program pc 1 t greedy reop plus reop minimalplus else if t greedy program pc 1 reop minimalquant pc add index program pc t min max can be 1 which add index does not accept pc add index program pc t max 1 pc add index program pc t paren count pc add index program pc t paren index next term fixup pc pc offset len pc emitre bytecode state re pc t kid program pc reop endchild resolve forward jump program next term fixup pc break case reop class pc add index program pc t index re class list t index new re char set t bmsize t start index t kidlen break default break t t next return pc emitrebytecode compilerstate recompiled renode renode nextalt nextaltfixup nexttermfixup reop_empty reop_alt nextalt nextaltfixup offset_len emitrebytecode reop_jump nexttermfixup offset_len resolveforwardjump nextaltfixup emitrebytecode nextalt reop_jump nextaltfixup offset_len resolveforwardjump nexttermfixup resolveforwardjump nextaltfixup reop_flat flatindex reop_flat flatindex flatindex flatindex jsreg_fold reop_flati reop_flat addindex flatindex addindex jsreg_fold reop_flat1i reop_flat1 jsreg_fold reop_ucflat1i reop_ucflat1 addindex reop_lparen addindex parenindex emitrebytecode reop_rparen addindex parenindex reop_backref addindex parenindex reop_assert nexttermfixup offset_len emitrebytecode reop_asserttest resolveforwardjump nexttermfixup reop_assert_not nexttermfixup offset_len emitrebytecode reop_assertnottest resolveforwardjump nexttermfixup reop_quant reop_star reop_minimalstar reop_opt reop_minimalopt reop_plus reop_minimalplus reop_minimalquant addindex addindex addindex addindex parencount addindex parenindex nexttermfixup offset_len emitrebytecode reop_endchild resolveforwardjump nexttermfixup reop_class addindex classlist recharset startindex private static void push prog state re global data g data int min int max re back track data back track last to save int continuation pc int continuation op g data state stack top new re prog state g data state stack top min max g data cp back track last to save continuation pc continuation op pushprogstate reglobaldata gdata rebacktrackdata backtracklasttosave continuation_pc continuation_op gdata statestacktop reprogstate gdata statestacktop gdata backtracklasttosave continuation_pc continuation_op private static re prog state pop prog state re global data g data re prog state state g data state stack top g data state stack top state previous return state reprogstate popprogstate reglobaldata gdata reprogstate gdata statestacktop gdata statestacktop private static void push back track state re global data g data byte op int target g data back track stack top new re back track data g data op target pushbacktrackstate reglobaldata gdata gdata backtrackstacktop rebacktrackdata gdata private static boolean flatn matcher re global data g data int match chars int length char chars int end if g data cp length end return false for int i 0 i length i if g data regexp source match chars i chars g data cp i return false g data cp length return true flatnmatcher reglobaldata gdata matchchars gdata gdata matchchars gdata gdata private static boolean flatni matcher re global data g data int match chars int length char chars int end if g data cp length end return false for int i 0 i length i if upcase g data regexp source match chars i upcase chars g data cp i return false g data cp length return true flatnimatcher reglobaldata gdata matchchars gdata gdata matchchars gdata gdata private static boolean backref matcher re global data g data int paren index char chars int end int len int i int paren content g data parens index paren index if paren content 1 return true len g data parens length paren index if g data cp len end return false if g data regexp flags jsreg fold 0 for i 0 i len i if upcase chars paren content i upcase chars g data cp i return false else for i 0 i len i if chars paren content i chars g data cp i return false g data cp len return true backrefmatcher reglobaldata gdata parenindex parencontent gdata parens_index parenindex parencontent gdata parens_length parenindex gdata gdata jsreg_fold parencontent gdata parencontent gdata gdata add a single character to the re char set private static void add character to char set re char set cs char c int byte index int c 8 if c cs length throw new runtime exception cs bits byte index 1 c 0x7 recharset addcharactertocharset recharset byteindex runtimeexception byteindex add a character range c1 to c2 inclusive to the re char set private static void add character range to char set re char set cs char c1 char c2 int i int byte index1 int c1 8 int byte index2 int c2 8 if c2 cs length c1 c2 throw new runtime exception c1 0x7 c2 0x7 if byte index1 byte index2 cs bits byte index1 int 0xff 7 c2 c1 c1 else cs bits byte index1 0xff c1 for i byte index1 1 i byte index2 i cs bits i byte 0xff cs bits byte index2 int 0xff 7 c2 recharset addcharacterrangetocharset recharset byteindex1 byteindex2 runtimeexception byteindex1 byteindex2 byteindex1 byteindex1 byteindex1 byteindex2 byteindex2 compile the source of the class into a re char set private static void process char set re global data g data re char set char set synchronized char set if char set converted process char set impl g data char set char set converted true recharset processcharset reglobaldata gdata recharset charset charset charset processcharsetimpl gdata charset charset private static void process char set impl re global data g data re char set char set int src char set start index int end src char set strlength char range start 0 this ch int byte length char c int n int n digits int i boolean in range false char set sense true byte length char set length 8 1 char set bits new byte byte length if src end return if g data regexp source src char set sense false src while src end n digits 2 switch g data regexp source src case src c g data regexp source src switch c case b this ch 0x8 break case f this ch 0xc break case n this ch 0xa break case r this ch 0xd break case t this ch 0x9 break case v this ch 0xb break case c if src 1 end is word g data regexp source src 1 this ch char g data regexp source src 0x1f else src this ch break case u n digits 2 fall thru case x n 0 for i 0 i n digits src end i c g data regexp source src int digit toascii hex digit c if digit 0 back off to accepting the original as a literal src i 1 n break n n 4 digit this ch char n break case 0 case 1 case 2 case 3 case 4 case 5 case 6 case 7 this is a non ecma extension decimal escapes in this case octal are supposed to be an error inside class ranges but supported here for backwards compatibility n c 0 c g data regexp source src if 0 c c 7 src n 8 n c 0 c g data regexp source src if 0 c c 7 src i 8 n c 0 if i 0377 n i else src this ch char n break case d add character range to char set char set 0 9 continue don t need range processing case d add character range to char set char set char 0 char 0 1 add character range to char set char set char 9 1 char char set length continue case s for i int char set length i 0 i if isre white space i add character to char set char set char i continue case s for i int char set length i 0 i if isre white space i add character to char set char set char i continue case w for i int char set length i 0 i if is word char i add character to char set char set char i continue case w for i int char set length i 0 i if is word char i add character to char set char set char i continue default this ch c break break default this ch g data regexp source src break if in range if g data regexp flags jsreg fold 0 add character range to char set char set upcase range start upcase this ch add character range to char set char set downcase range start downcase this ch else add character range to char set char set range start this ch in range false else if g data regexp flags jsreg fold 0 add character to char set char set upcase this ch add character to char set char set downcase this ch else add character to char set char set this ch if src end 1 if g data regexp source src src in range true range start this ch processcharsetimpl reglobaldata gdata recharset charset charset startindex charset rangestart thisch bytelength ndigits inrange charset bytelength charset charset bytelength gdata charset ndigits gdata gdata thisch thisch thisch thisch thisch thisch isword gdata thisch gdata thisch ndigits ndigits gdata toasciihexdigit thisch gdata gdata thisch addcharacterrangetocharset charset addcharacterrangetocharset charset addcharacterrangetocharset charset charset charset isrewhitespace addcharactertocharset charset charset isrewhitespace addcharactertocharset charset charset isword addcharactertocharset charset charset isword addcharactertocharset charset thisch thisch gdata inrange gdata jsreg_fold addcharacterrangetocharset charset rangestart thisch addcharacterrangetocharset charset rangestart thisch addcharacterrangetocharset charset rangestart thisch inrange gdata jsreg_fold addcharactertocharset charset thisch addcharactertocharset charset thisch addcharactertocharset charset thisch gdata inrange rangestart thisch private static boolean class matcher re global data g data re char set char set char ch if char set converted process char set g data char set int byte index ch 8 if char set sense if char set length 0 ch char set length char set bits byte index 1 ch 0x7 0 return false else if char set length 0 ch char set length char set bits byte index 1 ch 0x7 0 return false return true classmatcher reglobaldata gdata recharset charset charset processcharset gdata charset byteindex charset charset charset charset byteindex charset charset charset byteindex private static boolean executere bytecode re global data g data char chars int end int pc 0 byte program g data regexp program int currentcontinuation op int currentcontinuation pc boolean result false currentcontinuation pc 0 currentcontinuation op reop end if debug system out println input new string chars start at g data cp int op program pc for if debug system out println testing at g data cp op op switch op case reop empty result true break case reop bol if g data cp 0 if g data multiline g data regexp flags jsreg multiline 0 if is line term chars g data cp 1 result false break else result false break result true break case reop eol if g data cp end if g data multiline g data regexp flags jsreg multiline 0 if is line term chars g data cp result false break else result false break result true break case reop wbdry result g data cp 0 is word chars g data cp 1 g data cp end is word chars g data cp break case reop wnonbdry result g data cp 0 is word chars g data cp 1 g data cp end is word chars g data cp break case reop dot result g data cp end is line term chars g data cp if result g data cp break case reop digit result g data cp end is digit chars g data cp if result g data cp break case reop nondigit result g data cp end is digit chars g data cp if result g data cp break case reop space result g data cp end isre white space chars g data cp if result g data cp break case reop nonspace result g data cp end isre white space chars g data cp if result g data cp break case reop alnum result g data cp end is word chars g data cp if result g data cp break case reop nonalnum result g data cp end is word chars g data cp if result g data cp break case reop flat int offset get index program pc pc index len int length get index program pc pc index len result flatn matcher g data offset length chars end break case reop flati int offset get index program pc pc index len int length get index program pc pc index len result flatni matcher g data offset length chars end break case reop flat1 char match ch char program pc 0xff result g data cp end chars g data cp match ch if result g data cp break case reop flat1i char match ch char program pc 0xff result g data cp end upcase chars g data cp upcase match ch if result g data cp break case reop ucflat1 char match ch char get index program pc pc index len result g data cp end chars g data cp match ch if result g data cp break case reop ucflat1i char match ch char get index program pc pc index len result g data cp end upcase chars g data cp upcase match ch if result g data cp break case reop alt int nextpc byte nextop push prog state g data 0 0 null currentcontinuation pc currentcontinuation op nextpc pc get offset program pc nextop program nextpc push back track state g data nextop nextpc pc index len op program pc continue case reop jump int offset re prog state state pop prog state g data currentcontinuation pc state continuation pc currentcontinuation op state continuation op offset get offset program pc pc offset op program pc continue case reop lparen int paren index get index program pc pc index len g data set parens paren index g data cp 0 op program pc continue case reop rparen int cap index int paren index get index program pc pc index len cap index g data parens index paren index g data set parens paren index cap index g data cp cap index if paren index g data last paren g data last paren paren index op program pc continue case reop backref int paren index get index program pc pc index len result backref matcher g data paren index chars end break case reop class int index get index program pc pc index len if g data cp end if class matcher g data g data regexp class list index chars g data cp g data cp result true break result false break case reop assert case reop assert not byte test op push prog state g data 0 0 g data back track stack top currentcontinuation pc currentcontinuation op if op reop assert test op reop asserttest else test op reop assertnottest push back track state g data test op pc get offset program pc pc index len op program pc continue case reop asserttest case reop assertnottest re prog state state pop prog state g data g data cp state index g data back track stack top state back track currentcontinuation pc state continuation pc currentcontinuation op state continuation op if result if op reop asserttest result true else result false else if o executerebytecode reglobaldata gdata gdata currentcontinuation_op currentcontinuation_pc currentcontinuation_pc currentcontinuation_op reop_end gdata gdata reop_empty reop_bol gdata gdata gdata jsreg_multiline islineterm gdata reop_eol gdata gdata gdata jsreg_multiline islineterm gdata reop_wbdry gdata isword gdata gdata isword gdata reop_wnonbdry gdata isword gdata gdata isword gdata reop_dot gdata islineterm gdata gdata reop_digit gdata isdigit gdata gdata reop_nondigit gdata isdigit gdata gdata reop_space gdata isrewhitespace gdata gdata reop_nonspace gdata isrewhitespace gdata gdata reop_alnum gdata isword gdata gdata reop_nonalnum gdata isword gdata gdata reop_flat getindex index_len getindex index_len flatnmatcher gdata reop_flati getindex index_len getindex index_len flatnimatcher gdata reop_flat1 matchch gdata gdata matchch gdata reop_flat1i matchch gdata gdata matchch gdata reop_ucflat1 matchch getindex index_len gdata gdata matchch gdata reop_ucflat1i matchch getindex index_len gdata gdata matchch gdata reop_alt pushprogstate gdata currentcontinuation_pc currentcontinuation_op getoffset pushbacktrackstate gdata index_len reop_jump reprogstate popprogstate gdata currentcontinuation_pc continuation_pc currentcontinuation_op continuation_op getoffset reop_lparen parenindex getindex index_len gdata set_parens parenindex gdata reop_rparen cap_index parenindex getindex index_len cap_index gdata parens_index parenindex gdata set_parens parenindex cap_index gdata cap_index parenindex gdata lastparen gdata lastparen parenindex reop_backref parenindex getindex index_len backrefmatcher gdata parenindex reop_class getindex index_len gdata classmatcher gdata gdata classlist gdata gdata reop_assert reop_assert_not testop pushprogstate gdata gdata backtrackstacktop currentcontinuation_pc currentcontinuation_op reop_assert testop reop_asserttest testop reop_assertnottest pushbacktrackstate gdata testop getoffset index_len reop_asserttest reop_assertnottest reprogstate popprogstate gdata gdata gdata backtrackstacktop backtrack currentcontinuation_pc continuation_pc currentcontinuation_op continuation_op reop_asserttest private static boolean match reg exp re global data g data re compiled re char chars int start int end boolean multiline if re paren count 0 g data parens new long re paren count else g data parens null g data back track stack top null g data state stack top null g data multiline multiline g data regexp re g data last paren 0 int anchor ch g data regexp anchor ch have to include the position beyond the last character in order to detect end of input line condition for int i start i end i if the first node is a literal match step the index into the string until that match is made or fail if it can t be found at all if anchor ch 0 for if i end return false char match ch chars i if match ch anchor ch g data regexp flags jsreg fold 0 upcase match ch upcase char anchor ch break i g data cp i for int j 0 j re paren count j g data set parens j 1 0 boolean result executere bytecode g data chars end g data back track stack top null g data state stack top null if result g data skipped i start return true return false matchregexp reglobaldata gdata recompiled parencount gdata parencount gdata gdata backtrackstacktop gdata statestacktop gdata gdata gdata lastparen anchorch gdata anchorch anchorch matchch matchch anchorch gdata jsreg_fold matchch anchorch gdata parencount gdata set_parens executerebytecode gdata gdata backtrackstacktop gdata statestacktop gdata object execute reg exp context cx scriptable scope obj reg exp impl res string str int indexp int match type re global data g data new re global data int start indexp 0 char char array str to char array int end char array length if start end start end call the recursive matcher to do the real work boolean matches match reg exp g data re char array start end res multiline if matches if match type prefix return null return undefined instance int index g data cp int i index indexp 0 i int matchlen i start g data skipped int ep index index matchlen object result scriptable obj if match type test testing for a match and updating cx reg exp impl don t allocate an array object do return true result boolean true obj null else the array returned on match has element 0 bound to the matched string elements 1 through re paren count bound to the paren matches an index property telling the length of the left context and an input property referring to the input string scriptable scope get top level scope scope obj result script runtime new object cx scope array null obj scriptable result string matchstr new string char array index matchlen obj put 0 obj matchstr if re paren count 0 res parens null res last paren sub string empty sub string else sub string parsub null int num res parens new sub string re paren count for num 0 num re paren count num int cap index g data parens index num string parstr if cap index 1 int cap length g data parens length num parsub new sub string char array cap index cap length res parens num parsub if match type test continue parstr parsub to string obj put num 1 obj parstr else if match type test obj put num 1 obj undefined instance res last paren parsub if match type test define the index and input properties last for better for in loop order so they come after the elements obj put index obj new integer start g data skipped obj put input obj str if res last match null res last match new sub string res left context new sub string res right context new sub string res last match char array char array res last match index index res last match length matchlen res left context char array char array if cx get language version context version 1 2 js1 2 emulated perl4 0 1 8 patch level 36 for global regexps used in scalar contexts and unintentionally for the string match list psuedo context on hi there bye the following would result language while g print s g perl4 036 hi there hihitherehi therebye perl5 hi hi there hihitherehi therebye js1 2 hi there hihitheretherebye insofar as js1 2 always defined as left context from the last match for global regexps it was more consistent than perl4 res left context index start res left context length g data skipped else for js1 3 and ecm av2 emulate perl5 exactly js1 3 hi hi there hihitherehi therebye res left context index 0 res left context length start g data skipped res right context char array char array res right context index ep res right context length end ep return result executeregexp scopeobj regexpimpl matchtype reglobaldata gdata reglobaldata chararray tochararray chararray matchregexp gdata chararray matchtype gdata gdata matchtype regexpimpl parencount gettoplevelscope scopeobj scriptruntime newobject chararray parencount lastparen substring emptysubstring substring substring parencount parencount cap_index gdata parens_index cap_index cap_length gdata parens_length substring chararray cap_index cap_length matchtype tostring matchtype lastparen matchtype gdata lastmatch lastmatch substring leftcontext substring rightcontext substring lastmatch chararray chararray lastmatch lastmatch leftcontext chararray chararray getlanguageversion version_1_2 leftcontext leftcontext gdata ecmav2 leftcontext leftcontext gdata rightcontext chararray chararray rightcontext rightcontext int get flags return re flags getflags private static void report error string message id string arg string msg script runtime get message1 message id arg throw script runtime construct error syntax error msg reporterror messageid scriptruntime getmessage1 messageid scriptruntime constructerror syntaxerror max instance id 5 protected int get max instance id return max instance id max_instance_id getmaxinstanceid max_instance_id protected int find instance id info string s int id generated last update 2001 05 24 12 01 22 gmt 02 00 l0 id 0 string x null int c int s length s length if s length 6 c s char at 0 if c g x global id id global else if c s x source id id source else if s length 9 c s char at 0 if c l x last index id id lastindex else if c m x multiline id id multiline else if s length 10 x ignore case id id ignorecase if x null x s x equals s id 0 generated string id map if id 0 return super find instance id info s int attr switch id case id lastindex attr permanent dontenum break case id source case id global case id ignorecase case id multiline attr permanent readonly dontenum break default throw new illegal state exception return instance id info attr id findinstanceidinfo s_length s_length charat id_global id_source s_length charat lastindex id_lastindex id_multiline s_length ignorecase id_ignorecase string_id_map findinstanceidinfo id_lastindex id_source id_global id_ignorecase id_multiline illegalstateexception instanceidinfo protected string get instance id name int id switch id case id lastindex return last index case id source return source case id global return global case id ignorecase return ignore case case id multiline return multiline return super get instance id name id getinstanceidname id_lastindex lastindex id_source id_global id_ignorecase ignorecase id_multiline getinstanceidname protected object get instance id value int id switch id case id lastindex return script runtime wrap number last index case id source return new string re source case id global return script runtime wrap boolean re flags jsreg glob 0 case id ignorecase return script runtime wrap boolean re flags jsreg fold 0 case id multiline return script runtime wrap boolean re flags jsreg multiline 0 return super get instance id value id getinstanceidvalue id_lastindex scriptruntime wrapnumber lastindex id_source id_global scriptruntime wrapboolean jsreg_glob id_ignorecase scriptruntime wrapboolean jsreg_fold id_multiline scriptruntime wrapboolean jsreg_multiline getinstanceidvalue protected void set instance id value int id object value if id id lastindex last index script runtime to number value return super set instance id value id value setinstanceidvalue id_lastindex lastindex scriptruntime tonumber setinstanceidvalue protected void init prototype id int id string s int arity switch id case id compile arity 1 s compile break case id tostring arity 0 s to string break case id tosource arity 0 s to source break case id exec arity 1 s exec break case id test arity 1 s test break case id prefix arity 1 s prefix break default throw new illegal argument exception string value of id init prototype method regexp tag id s arity initprototypeid id_compile id_tostring tostring id_tosource tosource id_exec id_test id_prefix illegalargumentexception valueof initprototypemethod regexp_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag regexp tag return super exec id call f cx scope this obj args int id f method id switch id case id compile return real this this obj f compile cx scope args case id tostring case id tosource return real this this obj f to string case id exec return real this this obj f exec sub cx scope args match case id test object x real this this obj f exec sub cx scope args test return boolean true equals x boolean true boolean false case id prefix return real this this obj f exec sub cx scope args prefix throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag regexp_tag execidcall thisobj methodid id_compile realthis thisobj id_tostring id_tosource realthis thisobj tostring id_exec realthis thisobj execsub id_test realthis thisobj execsub id_prefix realthis thisobj execsub illegalargumentexception valueof private static native reg exp real this scriptable this obj id function object f if this obj instanceof native reg exp throw incompatible call error f return native reg exp this obj nativeregexp realthis thisobj idfunctionobject thisobj nativeregexp incompatiblecallerror nativeregexp thisobj string id map protected int find prototype id string s int id generated last update 2004 03 17 13 54 21 cet l0 id 0 string x null int c l switch s length case 4 c s char at 0 if c e x exec id id exec else if c t x test id id test break l case 6 x prefix id id prefix break l case 7 x compile id id compile break l case 8 c s char at 3 if c o x to source id id tosource else if c t x to string id id tostring break l if x null x s x equals s id 0 generated return id string_id_map findprototypeid charat id_exec id_test id_prefix id_compile charat tosource id_tosource tostring id_tostring class re node re node byte op this op op renode renode compiler state char source int length int flags this cpbegin source this cp 0 this cpend length this flags flags this paren count 0 this class count 0 this prog length 0 compilerstate parencount classcount proglength re prog state re prog state previous int min int max int index re back track data back track int continuation pc int continuation op this previous previous this min min this max max this index index this continuation op continuation op this continuation pc continuation pc this back track back track reprogstate reprogstate rebacktrackdata backtrack continuation_pc continuation_op continuation_op continuation_op continuation_pc continuation_pc backtrack backtrack re back track data re global data g data int op int pc previous g data back track stack top continuation op op continuation pc pc last paren g data last paren if g data parens null parens long g data parens clone cp g data cp state stack top g data state stack top rebacktrackdata reglobaldata gdata gdata backtrackstacktop continuation_op continuation_pc lastparen gdata lastparen gdata gdata gdata statestacktop gdata statestacktop get start of parenthesis capture contents 1 for empty int parens index int i return int parens i parens_index get length of parenthesis capture contents int parens length int i return int parens i 32 parens_length void set parens int i int index int length parens i long index 0xffffffffl long length 32 set_parens re char set int length int start index int strlength this length length this start index start index this strlength strlength recharset startindex startindex startindex private quit action quit action public global quitaction quitaction public global context cx init cx set the action to call from quit public void init quit action quit action quit action if quit action null throw new illegal argument exception quit action is null if this quit action null throw new illegal argument exception the method is once call this quit action quit action initquitaction quitaction quitaction quitaction illegalargumentexception quitaction quitaction illegalargumentexception quitaction quitaction public void init context factory factory factory call new context action public object run context cx init cx return null contextfactory contextaction factory call new context action public object run context cx init cx return null contextaction public void init context cx define some global functions particular to the shell note that these functions are not part of ecma init standard objects cx sealed std lib string names define class deserialize help load load class print quit read file read url run command seal serialize spawn sync toint32 version define function properties names global class scriptable object dontenum set up environment in the global scope to provide access to the system environment variables environment define class this environment environment new environment this define property environment environment scriptable object dontenum history native array cx new array this 0 define property history history scriptable object dontenum initialized true initstandardobjects sealedstdlib defineclass loadclass readfile readurl runcommand definefunctionproperties scriptableobject defineclass defineproperty scriptableobject nativearray newarray defineproperty scriptableobject print a help message this method is defined as a java script function public static void help context cx scriptable this obj object args function fun obj print stream out get instance fun obj get out out println tool error reporter get message msg help javascript thisobj funobj printstream getinstance funobj getout toolerrorreporter getmessage print the string values of its arguments this method is defined as a java script function note that its arguments are of the varargs form which allows it to handle an arbitrary number of arguments supplied to the java script function public static object print context cx scriptable this obj object args function fun obj print stream out get instance fun obj get out for int i 0 i args length i if i 0 out print convert the arbitrary java script value into a string form string s context to string args i out print s out println return context get undefined value javascript javascript thisobj funobj printstream getinstance funobj getout javascript tostring getundefinedvalue call embedding specific quit action passing its argument as int32 exit code this method is defined as a java script function public static void quit context cx scriptable this obj object args function fun obj global global get instance fun obj if global quit action null int exit code args length 0 0 script runtime to int32 args 0 global quit action quit cx exit code javascript thisobj funobj getinstance funobj quitaction exitcode scriptruntime toint32 quitaction exitcode get and set the language version this method is defined as a java script function public static double version context cx scriptable this obj object args function fun obj double result double cx get language version if args length 0 double d context to number args 0 cx set language version int d return result javascript thisobj funobj getlanguageversion tonumber setlanguageversion load and execute a set of java script source files this method is defined as a java script function public static void load context cx scriptable this obj object args function fun obj for int i 0 i args length i main process file cx this obj context to string args i javascript javascript thisobj funobj processfile thisobj tostring load a java class that defines a java script object using the conventions outlined in scriptable object define class p this method is defined as a java script function exception illegal access exception if access is not available to a reflected class member exception instantiation exception if unable to instantiate the named class exception invocation target exception if an exception is thrown during execution of methods of the named class exception class definition exception if the format of the class causes this exception in scriptable object define class see org mozilla javascript scriptable object define class public static void define class context cx scriptable this obj object args function fun obj throws illegal access exception instantiation exception invocation target exception class clazz get class args scriptable object define class this obj clazz javascript scriptableobject defineclass javascript illegalaccessexception instantiationexception invocationtargetexception classdefinitionexception scriptableobject defineclass scriptableobject defineclass defineclass thisobj funobj illegalaccessexception instantiationexception invocationtargetexception getclass scriptableobject defineclass thisobj load and execute a script compiled to a class file p this method is defined as a java script function when called as a java script function a single argument is expected this argument should be the name of a class that implements the script interface as will any script compiled by jsc exception illegal access exception if access is not available to the class exception instantiation exception if unable to instantiate the named class exception invocation target exception if an exception is thrown during execution of methods of the named class see org mozilla javascript scriptable object define class public static void load class context cx scriptable this obj object args function fun obj throws illegal access exception instantiation exception invocation target exception class clazz get class args if script class is assignable from clazz throw report runtime error msg must implement script script script script clazz new instance script exec cx this obj javascript javascript illegalaccessexception instantiationexception invocationtargetexception scriptableobject defineclass loadclass thisobj funobj illegalaccessexception instantiationexception invocationtargetexception getclass isassignablefrom reportruntimeerror newinstance thisobj private static class get class object args throws illegal access exception instantiation exception invocation target exception if args length 0 throw report runtime error msg expected string arg object arg0 args 0 if arg0 instanceof wrapper object wrapped wrapper arg0 unwrap if wrapped instanceof class return class wrapped string class name context to string args 0 try return class for name class name catch class not found exception cnfe throw report runtime error msg class not found class name getclass illegalaccessexception instantiationexception invocationtargetexception reportruntimeerror classname tostring forname classname classnotfoundexception reportruntimeerror classname public static void serialize context cx scriptable this obj object args function fun obj throws io exception if args length 2 throw context report runtime error expected an object to serialize and a filename to write the serialization to object obj args 0 string filename context to string args 1 file output stream fos new file output stream filename scriptable scope scriptable object get top level scope this obj scriptable output stream out new scriptable output stream fos scope out write object obj out close thisobj funobj ioexception reportruntimeerror tostring fileoutputstream fileoutputstream scriptableobject gettoplevelscope thisobj scriptableoutputstream scriptableoutputstream writeobject public static object deserialize context cx scriptable this obj object args function fun obj throws io exception class not found exception if args length 1 throw context report runtime error expected a filename to read the serialization from string filename context to string args 0 file input stream fis new file input stream filename scriptable scope scriptable object get top level scope this obj object input stream in new scriptable input stream fis scope object deserialized in read object in close return context to object deserialized scope thisobj funobj ioexception classnotfoundexception reportruntimeerror tostring fileinputstream fileinputstream scriptableobject gettoplevelscope thisobj objectinputstream scriptableinputstream readobject toobject the spawn function runs a given function or script in a different thread js function g a 7 js a 3 3 js spawn g thread thread 1 5 main js a 3 public static object spawn context cx scriptable this obj object args function fun obj scriptable scope fun obj get parent scope runner runner if args length 0 args 0 instanceof function object new args null if args length 1 args 1 instanceof scriptable new args cx get elements scriptable args 1 if new args null new args script runtime empty args runner new runner scope function args 0 new args else if args length 0 args 0 instanceof script runner new runner scope script args 0 else throw report runtime error msg spawn args runner factory cx get factory thread thread new thread runner thread start return thread thisobj funobj funobj getparentscope newargs newargs getelements newargs newargs scriptruntime emptyargs newargs reportruntimeerror getfactory the sync function creates a synchronized function in the sense of a java synchronized method from an existing function the new function synchronizes on the code this code object of its invocation js var o f sync function x print entry packages java lang thread sleep x 1000 print exit js spawn function o f 5 thread thread 0 5 main entry js spawn function o f 5 thread thread 1 5 main js exit entry exit public static object sync context cx scriptable this obj object args function fun obj if args length 1 args 0 instanceof function return new synchronizer function args 0 else throw report runtime error msg sync args thisobj funobj reportruntimeerror execute the specified command with the given argument and options as a separate process and return the exit status of the process p usage pre run command command run command command arg1 argn run command command arg1 argn options pre all except the last arguments to run command are converted to strings and denote command name and its arguments if the last argument is a java script object it is an option object otherwise it is converted to string denoting the last argument and options objects assumed to be empty te following properties of the option object are processed ul li tt args tt provides an array of additional command arguments li tt env tt explicit environment object all its enumeratable properties define the corresponding environment variable names li tt input tt the process input if it is not java io input stream it is converted to string and sent to the process as its input if not specified no input is provided to the process li tt output tt the process output instead of java lang system out if it is not instance of java io output stream the process output is read converted to a string appended to the output property value converted to string and put as the new value of the output property li tt err tt the process error output instead of java lang system err if it is not instance of java io output stream the process error output is read converted to a string appended to the err property value converted to string and put as the new value of the err property ul public static object run command context cx scriptable this obj object args function fun obj throws io exception int l args length if l 0 l 1 args 0 instanceof scriptable throw report runtime error msg run command bad args input stream in null output stream out null err null byte array output stream out bytes null err bytes null object out obj null err obj null string environment null scriptable params null object add args null if args l 1 instanceof scriptable params scriptable args l 1 l object env obj scriptable object get property params env if env obj scriptable not found if env obj null environment new string 0 else if env obj instanceof scriptable throw report runtime error msg run command bad env scriptable env hash scriptable env obj object ids scriptable object get property ids env hash environment new string ids length for int i 0 i ids length i object key obj ids i val string key if key obj instanceof string key string key obj val scriptable object get property env hash key else int ikey number key obj int value key integer to string ikey val scriptable object get property env hash ikey if val scriptable object not found val undefined instance environment i key script runtime to string val object in obj scriptable object get property params input if in obj scriptable not found in to input stream in obj out obj scriptable object get property params output if out obj scriptable not found out to output stream out obj if out null out bytes new byte array output stream out out bytes err obj scriptable object get property params err if err obj scriptable not found err to output stream err obj if err null err bytes new byte array output stream err err bytes object add args obj scriptable object get property params args if add args obj scriptable not found scriptable s context to object add args obj get top level scope this obj add args cx get elements s global global get instance fun obj if out null out global null global get out system out if err null err global null global get err system err if no explicit input stream do not send any input to process in particular do not use system in to avoid deadlocks when waiting for user input to send to process which is already terminated as it is not always possible to interrupt read method string cmd new string add args null l l add args length for int i 0 i l i cmd i script runtime to string args i if add args null for int i 0 i add args length i cmd l i script runtime to string add args i int exit code run process cmd environment in out err if out bytes null string s script runtime to string out obj out bytes to string scriptable object put property params output s if err bytes null string s script runtime to string err obj err bytes to string scriptable object put property params err s return new integer exit code runcommand runcommand runcommand runcommand javascript inputstream outputstream outputstream runcommand thisobj funobj ioexception reportruntimeerror runcommand inputstream outputstream bytearrayoutputstream outbytes errbytes outobj errobj addargs envobj scriptableobject getproperty envobj not_found envobj envobj reportruntimeerror runcommand envhash envobj scriptableobject getpropertyids envhash keyobj keyobj keyobj scriptableobject getproperty envhash keyobj intvalue tostring scriptableobject getproperty envhash scriptableobject not_found scriptruntime tostring inobj scriptableobject getproperty inobj not_found toinputstream inobj outobj scriptableobject getproperty outobj not_found tooutputstream outobj outbytes bytearrayoutputstream outbytes errobj scriptableobject getproperty errobj not_found tooutputstream errobj errbytes bytearrayoutputstream errbytes addargsobj scriptableobject getproperty addargsobj not_found toobject addargsobj gettoplevelscope thisobj addargs getelements getinstance funobj getout geterr addargs addargs scriptruntime tostring addargs addargs scriptruntime tostring addargs exitcode runprocess outbytes scriptruntime tostring outobj outbytes tostring scriptableobject putproperty errbytes scriptruntime tostring errobj errbytes tostring scriptableobject putproperty exitcode the seal function seals all supplied arguments public static void seal context cx scriptable this obj object args function fun obj for int i 0 i args length i object arg args i if arg instanceof scriptable object arg undefined instance if arg instanceof scriptable arg undefined instance throw report runtime error msg shell seal not object else throw report runtime error msg shell seal not scriptable for int i 0 i args length i object arg args i scriptable object arg seal object thisobj funobj scriptableobject reportruntimeerror reportruntimeerror scriptableobject sealobject the read file reads the given file context and convert it to a string using the specified character coding or default character coding if explicit coding argument is not given p usage pre read file file path read file file path char coding pre the first form converts file s context to string using the default character coding public static object read file context cx scriptable this obj object args function fun obj throws io exception if args length 0 throw report runtime error msg shell read file bad args string path script runtime to string args 0 string char coding null if args length 2 char coding script runtime to string args 1 return read url path char coding true readfile readfile filepath readfile filepath charcoding readfile thisobj funobj ioexception reportruntimeerror readfile scriptruntime tostring charcoding charcoding scriptruntime tostring readurl charcoding the read url opens connection to the given url read all its data and converts them to a string using the specified character coding or default character coding if explicit coding argument is not given p usage pre read url url read url url char coding pre the first form converts file s context to string using the default char coding public static object read url context cx scriptable this obj object args function fun obj throws io exception if args length 0 throw report runtime error msg shell read url bad args string url script runtime to string args 0 string char coding null if args length 2 char coding script runtime to string args 1 return read url url char coding false readurl readurl readurl charcoding charcoding readurl thisobj funobj ioexception reportruntimeerror readurl scriptruntime tostring charcoding charcoding scriptruntime tostring readurl charcoding convert the argumnet to int32 number public static object toint32 context cx scriptable this obj object args function fun obj object arg args length 0 args 0 undefined instance if arg instanceof integer return arg return script runtime wrap int script runtime to int32 arg thisobj funobj scriptruntime wrapint scriptruntime toint32 public input stream get in return in stream null system in in stream inputstream getin instream instream public void set in input stream in in stream in setin inputstream instream public print stream get out return out stream null system out out stream printstream getout outstream outstream public void set out print stream out out stream out setout printstream outstream public print stream get err return err stream null system err err stream printstream geterr errstream errstream public void set err print stream err err stream err seterr printstream errstream public void set sealed std lib boolean value sealed std lib value setsealedstdlib sealedstdlib private static global get instance function function scriptable scope function get parent scope if scope instanceof global throw report runtime error msg bad shell function scope string value of scope return global scope getinstance getparentscope reportruntimeerror valueof if any of in out err is null the corresponding process stream will be closed immediately otherwise it will be closed as soon as all data will be read from written to process private static int run process string cmd string environment input stream in output stream out output stream err throws io exception process p if environment null p runtime get runtime exec cmd else p runtime get runtime exec cmd environment pipe thread in thread null err thread null try input stream err process null try if err null err process p get error stream else p get error stream close input stream out process null try if out null out process p get input stream else p get input stream close output stream in process null try if in null in process p get output stream else p get output stream close if out null read process output on this thread if err null err thread new pipe thread true err process err err thread start if in null in thread new pipe thread false in in process in thread start pipe true out process out else if in null no output read process input on this thread if err null err thread new pipe thread true err process err err thread start pipe false in in process in close else if err null no output or input read process err on this thread pipe true err process err err process close err process null wait for process completion for try p wait for break catch interrupted exception ex return p exit value finally pipe will close stream as well but for reliability duplicate it in any case if in process null in process close finally if out process null out process close finally if err process null err process close finally p destroy if in thread null for try in thread join break catch interrupted exception ex if err thread null for try err thread join break catch interrupted exception ex runprocess inputstream outputstream outputstream ioexception getruntime getruntime pipethread inthread errthread inputstream errprocess errprocess geterrorstream geterrorstream inputstream outprocess outprocess getinputstream getinputstream outputstream inprocess inprocess getoutputstream getoutputstream errthread pipethread errprocess errthread inthread pipethread inprocess inthread outprocess errthread pipethread errprocess errthread inprocess errprocess errprocess errprocess waitfor interruptedexception exitvalue inprocess inprocess outprocess outprocess errprocess errprocess inthread inthread interruptedexception errthread errthread interruptedexception static void pipe boolean from process input stream from output stream to throws io exception try final int size 4096 byte buffer new byte size for int n if from process n from read buffer 0 size else try n from read buffer 0 size catch io exception ex ignore exception as it can be cause by closed pipe break if n 0 break if from process to write buffer 0 n to flush else try to write buffer 0 n to flush catch io exception ex ignore exception as it can be cause by closed pipe break finally try if from process from close else to close catch io exception ex ignore errors on close on windows jvm may throw invalid refrence exception if process terminates too fast fromprocess inputstream outputstream ioexception fromprocess ioexception fromprocess ioexception fromprocess ioexception private static input stream to input stream object value throws io exception input stream is null string s null if value instanceof wrapper object unwrapped wrapper value unwrap if unwrapped instanceof input stream is input stream unwrapped else if unwrapped instanceof byte is new byte array input stream byte unwrapped else if unwrapped instanceof reader s read reader reader unwrapped else if unwrapped instanceof char s new string char unwrapped if is null if s null s script runtime to string value is new byte array input stream s get bytes return is inputstream toinputstream ioexception inputstream inputstream inputstream bytearrayinputstream readreader scriptruntime tostring bytearrayinputstream getbytes private static output stream to output stream object value output stream os null if value instanceof wrapper object unwrapped wrapper value unwrap if unwrapped instanceof output stream os output stream unwrapped return os outputstream tooutputstream outputstream outputstream outputstream private static string read url string file path string char coding boolean url is file throws io exception int chunk length input stream is null try if url is file url url obj new url file path url connection uc url obj open connection is uc get input stream chunk length uc get content length if chunk length 0 chunk length 1024 if char coding null string type uc get content type if type null char coding get char coding from type type else file f new file file path long length f length chunk length int length if chunk length length throw new io exception too big file size length if chunk length 0 return is new file input stream f reader r if char coding null r new input stream reader is else r new input stream reader is char coding return read reader r chunk length finally if is null is close readurl filepath charcoding urlisfile ioexception chunklength inputstream urlisfile urlobj filepath urlconnection urlobj openconnection getinputstream chunklength getcontentlength chunklength chunklength charcoding getcontenttype charcoding getcharcodingfromtype filepath chunklength chunklength ioexception chunklength fileinputstream charcoding inputstreamreader inputstreamreader charcoding readreader chunklength private static string get char coding from type string type int i type index of if i 0 int end type length i while i end type char at i i string charset charset if charset region matches true 0 type i charset length i charset length while i end type char at i i if i end type char at i i while i end type char at i i if i end i is at the start of non empty char coding spec while type char at end 1 end return type substring i end return null getcharcodingfromtype indexof charat regionmatches charat charat charat charcoding charat private static string read reader reader reader throws io exception return read reader reader 4096 readreader ioexception readreader private static string read reader reader reader int initial buffer size throws io exception char buffer new char initial buffer size int offset 0 for int n reader read buffer offset buffer length offset if n 0 break offset n if offset buffer length char tmp new char buffer length 2 system arraycopy buffer 0 tmp 0 offset buffer tmp return new string buffer 0 offset readreader initialbuffersize ioexception initialbuffersize static runtime exception report runtime error string msg id string message tool error reporter get message msg id return context report runtime error message runtimeexception reportruntimeerror msgid toolerrorreporter getmessage msgid reportruntimeerror static runtime exception report runtime error string msg id string msg arg string message tool error reporter get message msg id msg arg return context report runtime error message runtimeexception reportruntimeerror msgid msgarg toolerrorreporter getmessage msgid msgarg reportruntimeerror runner scriptable scope function func object args this scope scope f func this args args runner scriptable scope script script this scope scope s script public void run factory call this public object run context cx if f null return f call cx scope scope args else return s exec cx scope pipe thread boolean from process input stream from output stream to set daemon true this from process from process this from from this to to pipethread fromprocess inputstream outputstream setdaemon fromprocess fromprocess public void run try global pipe from process from to catch io exception ex throw context throw as script runtime ex ex fromprocess ioexception throwasscriptruntimeex static final long serial versionuid 924022554283675333l public string get class name return java array serialversionuid getclassname javaarray public static native java array wrap scriptable scope object array return new native java array scope array nativejavaarray nativejavaarray public object unwrap return array public native java array scriptable scope object array super scope null script runtime object class class cl array get class if cl is array throw new runtime exception array expected this array array this length array get length array this cls cl get component type nativejavaarray scriptruntime objectclass getclass isarray runtimeexception getlength getcomponenttype public boolean has string id scriptable start return id equals length super has id start public boolean has int index scriptable start return 0 index index length public object get string id scriptable start if id equals length return new integer length object result super get id start if result not found scriptable object has property get prototype id throw context report runtime error2 msg java member not found array get class get name id return result not_found scriptableobject hasproperty getprototype reportruntimeerror2 getclass getname public object get int index scriptable start if 0 index index length context cx context get context object obj array get array index return cx get wrap factory wrap cx this obj cls return undefined instance getcontext getwrapfactory public void put string id scriptable start object value ignore assignments to length it s readonly if id equals length super put id start value public void put int index scriptable start object value if 0 index index length array set array index context js to java value cls return super put index start value jstojava public object get default value class hint if hint null hint script runtime string class return array to string if hint script runtime boolean class return boolean true if hint script runtime number class return script runtime na nobj return this getdefaultvalue scriptruntime stringclass tostring scriptruntime booleanclass scriptruntime numberclass scriptruntime nanobj public object get ids object result new object length int i length while i 0 result i new integer i return result getids public boolean has instance scriptable value if value instanceof wrapper return false object instance wrapper value unwrap return cls is instance instance hasinstance isinstance public scriptable get prototype if prototype null prototype scriptable object get class prototype this get parent scope array return prototype getprototype scriptableobject getclassprototype getparentscope public class slot 006 extends live connect test public slot 006 super slot_006 liveconnecttest slot_006 super public static void main string args slot 006 test new slot 006 test start slot_006 slot_006 public void execute test object test matrix get data array for int i 0 i test matrix length i js object js object getjs string object test matrix i for int j 0 j string object test matrix i 1 length j get slot js object j object test matrix i executetest testmatrix getdataarray testmatrix jsobject jsobject getjsstring testmatrix testmatrix getslot jsobject testmatrix public js object getjs string object data return js object data 0 jsobject getjsstring jsobject data in this test contains of java script string object java object with the same string value return the data array public object get data array object item0 global eval new string passed new string passed object data array item0 return data array javascript getdataarray dataarray dataarray use js object get slot to get an indexed member of a js object in this test the expected class of all objects is js object xxx propbably need to add a bunch of unicode characters here param jss tring the js object with indexed members param slot the index property to retrieve param data object array containing the string representation of the expected result of js array get slot slot and the js objectconstructor of the expected result which allows us to verify the value and type of the result object public void get slot js object js string int slot object data string exception js object constructor null class e class null class a class null string result null string e result null try e result new character string data 1 char at slot to string result string js string get slot slot if result null e class class for name java lang string a class result get class catch exception e exception js string get slot slot threw e to string file exception exception e print stack trace finally if result null add test case js string get slot slot to string returned result e result equals result true e result equals result exception else check the string value of the result add test case js string get slot slot returned result e result to string equals result true e result equals result to string exception check the class of the result all should be java lang strings add test case e class equals a class true e class equals a class exception jsobject getslot jsobject jsobject jsstring jsobject jsarray getslot jsobjectconstructor getslot jsobject jsstring jsobject eclass aclass eresult eresult charat tostring jsstring getslot eclass forname aclass getclass jsstring getslot tostring printstacktrace addtestcase jsstring getslot tostring eresult eresult addtestcase jsstring getslot eresult tostring eresult tostring addtestcase eclass aclass eclass aclass search for class cache object in the given scope the method first calls link scriptable object get top level scope scriptable scope to get the top most scope and then tries to locate associated class cache object in the prototype chain of the top scope param scope scope to search for class cache object return previously associated class cache object or a new instance of class cache if no class cache object was found see associate scriptable object top scope public static class cache get scriptable scope class cache cache cache class cache scriptable object get top scope value scope akey if cache null xxx warn somehow about wrong cache usage cache new class cache return cache classcache scriptableobject gettoplevelscope classcache classcache classcache classcache classcache scriptableobject topscope classcache classcache classcache scriptableobject gettopscopevalue classcache associate class cache object with the given top level scope the class cache object can only be associated with the given scope once param top scope scope to associate this class cache object with return true if no prevous class cache objects were embedded into the scope and this class cache were successfully associated or false otherwise see get scriptable scope public boolean associate scriptable object top scope if top scope get parent scope null can only associate cache with top level scope throw new illegal argument exception if this top scope associate value akey this scope top scope return true return false classcache classcache topscope classcache classcache classcache scriptableobject topscope topscope getparentscope illegalargumentexception topscope associatevalue topscope empty caches of generated java classes and java reflection information public synchronized void clear caches class table new hashtable java adapter generated classes new hashtable interface adapter cache null clearcaches classtable javaadaptergeneratedclasses interfaceadaptercache check if generated java classes and java reflection information is cached public final boolean is caching enabled return caching is enabled iscachingenabled cachingisenabled set whether to cache some values p by default the engine will cache the results of tt class get methods tt and similar calls this can speed execution dramatically but increases the memory footprint also with caching enabled references may be held to objects past the lifetime of any real usage p if caching is enabled and this method is called with a code false code argument the caches will be emptied p caching is enabled by default param enabled if true caching is enabled see clear caches public synchronized void set caching enabled boolean enabled if enabled caching is enabled return if enabled clear caches caching is enabled enabled getmethods clearcaches setcachingenabled cachingisenabled clearcaches cachingisenabled deprecated the method always returns false see set invoker optimization enabled boolean enabled public boolean is invoker optimization enabled return false setinvokeroptimizationenabled isinvokeroptimizationenabled deprecated the method does nothing invoker optimization is no longer used by rhino on modern jdk like 1 4 or 1 5 the disadvatages of the optimization like incresed memory usage or longer initialization time overweight small speed increase that can be gained using generated proxy class to replace reflection public synchronized void set invoker optimization enabled boolean enabled setinvokeroptimizationenabled internal engine method to return serial number for generated classes to ensure name uniqueness public final synchronized int new class serial number return generated class serial newclassserialnumber generatedclassserial object get interface adapter class cl object result hashtable cache interface adapter cache if cache null result null else result cache get cl return result getinterfaceadapter interfaceadaptercache synchronized void cache interface adapter class cl object iadapter if caching is enabled if interface adapter cache null interface adapter cache new hashtable interface adapter cache put cl iadapter cacheinterfaceadapter cachingisenabled interfaceadaptercache interfaceadaptercache interfaceadaptercache create a new ref drv param args the arguments passed to the main method public ref drv string args super args set suffix js refdrv refdrv setsuffix ref drv expects the following options pre e full path to the java script executable d directory in which tests are installed h path to helper functions file jsref js o directory in which log files will be written s list of suites that should be executed pre public static void main string args ref drv d new ref drv args d start refdrv javascript refdrv refdrv process command line options see com netscape javascript qa drivers rhino drv process options public boolean process options int length args length if args 0 starts with xxx need to verify that we at least get valid d and h options for int i 0 i args length i if args i equals d p d this test directory args i ends with file separator new file args i new file args i file separator p d this test directory if this test directory is directory p error this test directory get absolute path is not a test directory return false else continue if args i equals s p s files new string 20 for int j i k 0 j args length j if args j starts with break files k args j if args i equals h p h this helper string new string args i this helper functions new file helper string if this helper functions is file p error this helper functions get absolute path file not found return false p h this helper functions if args i equals c p c this code coverage new boolean args i boolean value if args i equals o p o output directory new file args i file separator if output directory exists output directory is directory p error output directory get absolute path is not a directory return false if args i equals p this opt level integer parse int args i if args i equals db this debug level integer parse int args i this opt level 0 if args i equals e this executable args i if args i equals t string tinderbox args i if tinderbox equals true tinderbox equals 1 this tinderbox true else this tinderbox false return true else switch args length case 0 p error specify location of java script tests return false case 1 p error specify location of java script helper functions file return false case 2 this test directory args 0 ends with file separator new file args 0 new file args 0 file separator this helper functions new file args 1 if this test directory is directory p error this test directory get absolute path is not a directory return false if this helper functions is file p error this helper functions get absolute path file not found return false return true default p could not understand arguments return false rhinodrv processoptions processoptions startswith test_directory endswith test_directory test_directory isdirectory test_directory getabsolutepath test_directory startswith helper_string helper_functions helper_string helper_functions isfile helper_functions getabsolutepath helper_functions code_coverage booleanvalue output_directory output_directory output_directory isdirectory output_directory getabsolutepath opt_level parseint debug_level parseint opt_level __tinderbox __tinderbox __tinderbox javascript javascript helper_functions test_directory endswith helper_functions test_directory isdirectory test_directory getabsolutepath helper_functions isfile helper_functions getabsolutepath for each test file in each test suite create a new ref env run the test parse its results and close the ref env public synchronized void execute suite test suite suite test environment context test file file p executing suite try for int i 0 i suite size i synchronized suite file test file suite element at i if get system information 0 starts with mac context new mac ref env file suite this mac ref env context run test else context new ref env file suite this ref env context run test write file result file suite output directory write case results file suite output directory context close context null if file passed suite passed false catch exception e e print stack trace write suite result suite output directory write suite summary suite output directory testfile testsuite refenv refenv executesuite testsuite testenvironment testfile testfile elementat getsysteminformation startswith macrefenv macrefenv runtest refenv refenv runtest writefileresult output_directory writecaseresults output_directory printstacktrace writesuiteresult output_directory writesuitesummary output_directory public int float 512 public int ambiguous float arg return float public int ambiguous double arg return double public int ambiguous byte arg return byte public class datatypes 016 extends live connect test public datatypes 016 super datatypes_016 liveconnecttest datatypes_016 public static void main string args datatypes 016 test new datatypes 016 test start datatypes_016 datatypes_016 public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class global eval var dt new dt setuptestenvironment setuptestenvironment datatypeclass public boolean check byte string v double max new double byte max value double value double min new double byte min value double value double value new double v double value if value min value max return true return false checkbyte max_value doublevalue min_value doublevalue doublevalue public boolean check integer string v double max new double integer max value double value double min new double integer min value double value double value new double v double value if value min value max return true return false checkinteger max_value doublevalue min_value doublevalue doublevalue public boolean check short string v double max new double short max value double value double min new double short min value double value double value new double v double value if value min value max return true return false checkshort max_value doublevalue min_value doublevalue doublevalue public boolean check float string v double max new double float max value double value double min new double float min value double value double value new double v double value if value min value max return true return false checkfloat max_value doublevalue min_value doublevalue doublevalue public boolean check long string v double max new double long max value double value double min new double long min value double value double value new double v double value if value min value max return true return false checklong max_value doublevalue min_value doublevalue doublevalue public boolean check double string v double max new double double max value double value double min new double double min value double value double value new double v double value if value min value max return true return false checkdouble max_value doublevalue min_value doublevalue doublevalue public void execute test for int i 0 i js vals length i do setter test dt static set double js vals i dt static get double dt pub static double number new double js vals i number new double data type class pub static double true do setter test dt static set byte js vals i dt static get byte dt pub static byte number new byte new double js vals i byte value number new byte data type class pub static byte check byte js vals i do setter test dt static set short js vals i dt static get short dt pub static short number new short new double js vals i short value number new short data type class pub static short check short js vals i do setter test dt static set integer js vals i dt static get integer dt pub static int number new integer new double js vals i int value number new integer data type class pub static int check integer js vals i do setter test dt static set float js vals i dt static get float dt pub static float number new float new double js vals i float value number new float data type class pub static float true do setter test dt static set long js vals i dt static get long dt pub static long number new long new double js vals i long value number new long data type class pub static long check long js vals i executetest jsvals dosettertest staticsetdouble jsvals staticgetdouble pub_static_double jsvals datatypeclass pub_static_double dosettertest staticsetbyte jsvals staticgetbyte pub_static_byte jsvals bytevalue datatypeclass pub_static_byte checkbyte jsvals dosettertest staticsetshort jsvals staticgetshort pub_static_short jsvals shortvalue datatypeclass pub_static_short checkshort jsvals dosettertest staticsetinteger jsvals staticgetinteger pub_static_int jsvals intvalue datatypeclass pub_static_int checkinteger jsvals dosettertest staticsetfloat jsvals staticgetfloat pub_static_float jsvals floatvalue datatypeclass pub_static_float dosettertest staticsetlong jsvals staticgetlong pub_static_long jsvals longvalue datatypeclass pub_static_long checklong jsvals this tests calls a java setter method from java script it verifies that the setter was called properly in two ways by checking the return value of the getter method and by checking the value of the public field that was set param setter java method that takes an argument and sets a value param js value java script value that is passed to the setter param getter java method that returns the value set by setter param field java field that setter changed param e result expected result which should be of some number type param in range whether or not the value is in range for the particular type if not expect a js excedeption public void do setter test string setter string js value string getter string field number e result number field value boolean in range string set method setter js value string get method getter double expected result in range new double e result double value new double field value double value double getter result null object field result null string set result no exception string expected set result set result try expected set result in range no exception class for name netscape javascript js exception get name from java script call the setter will throw exception if in range global eval set method catch exception e set result e get class get name file exception e to string finally add test case set method expected set result set result file exception try from java script call the getter getter result double global eval get method from java sript access the field field result double global eval field catch exception e e print stack trace file exception e to string field result e get class get name finally add test case value getter result expected expected result set method expected result equals getter result true expected result equals getter result file exception add test case value field result expected expected result set method expected result equals field result true expected result equals field result file exception javascript jsvalue javascript eresult inrange jsexcedeption dosettertest jsvalue eresult fieldvalue inrange setmethod jsvalue getmethod expectedresult inrange eresult doublevalue fieldvalue doublevalue getterresult fieldresult setresult expectedsetresult setresult expectedsetresult inrange forname jsexception getname javascript inrange setmethod setresult getclass getname tostring addtestcase setmethod expectedsetresult setresult javascript getterresult getmethod javasript fieldresult printstacktrace tostring fieldresult getclass getname addtestcase getterresult expectedresult setmethod expectedresult getterresult expectedresult getterresult addtestcase fieldresult expectedresult setmethod expectedresult fieldresult expectedresult fieldresult native java package boolean internal usage string package name class loader class loader this package name package name this class loader class loader nativejavapackage internalusage packagename classloader classloader packagename packagename classloader classloader deprecated native java package is an internal class do not use it directly public native java package string package name class loader class loader this false package name class loader nativejavapackage nativejavapackage packagename classloader classloader packagename classloader deprecated native java package is an internal class do not use it directly public native java package string package name this false package name context get current context get application class loader nativejavapackage nativejavapackage packagename packagename getcurrentcontext getapplicationclassloader public string get class name return java package getclassname javapackage public boolean has string id scriptable start return true public boolean has int index scriptable start return false public void put string id scriptable start object value can t add properties to java packages sorry public void put int index scriptable start object value throw context report runtime error0 msg pkg int reportruntimeerror0 public object get string id scriptable start return get pkg property id start true getpkgproperty public object get int index scriptable start return not found not_found need to look for a class by that name void force package string name scriptable scope native java package pkg int end name index of if end 1 end name length string id name substring 0 end object cached super get id this if cached null cached instanceof native java package pkg native java package cached else string new package package name length 0 id package name id pkg new native java package true new package class loader script runtime set object proto and parent pkg scope super put id this pkg if end name length pkg force package name substring end 1 scope forcepackage nativejavapackage indexof nativejavapackage nativejavapackage newpackage packagename packagename nativejavapackage newpackage classloader scriptruntime setobjectprotoandparent forcepackage synchronized object get pkg property string name scriptable start boolean create pkg object cached super get name start if cached not found return cached string class name package name length 0 name package name name context cx context get context class shutter shutter cx get class shutter scriptable new value null if shutter null shutter visible to scripts class name class cl null if class loader null cl kit class or null class loader class name else cl kit class or null class name if cl null new value new native java class get top level scope this cl new value set prototype get prototype if new value null create pkg native java package pkg pkg new native java package true class name class loader script runtime set object proto and parent pkg get parent scope new value pkg if new value null make it available for fast lookup and sharing of lazily reflected constructors and static members super put name start new value return new value getpkgproperty createpkg not_found classname packagename packagename getcontext classshutter getclassshutter newvalue visibletoscripts classname classloader classornull classloader classname classornull classname newvalue nativejavaclass gettoplevelscope newvalue setprototype getprototype newvalue createpkg nativejavapackage nativejavapackage classname classloader scriptruntime setobjectprotoandparent getparentscope newvalue newvalue newvalue newvalue public object get default value class ignored return to string getdefaultvalue tostring public string to string return java package package name tostring javapackage packagename public class live connect drv extends test driver public live connect drv string args super args set suffix class liveconnectdrv testdriver liveconnectdrv setsuffix set suffix class public static void main string args live connect drv d new live connect drv args d start setsuffix liveconnectdrv liveconnectdrv public boolean process options int length args length if args 0 starts with xxx need to verify that we at least get valid d and h options for int i 0 i args length i if args i equals d this test directory args i ends with file separator new file args i new file args i file separator if this test directory is directory p error this test directory get absolute path is not a directory return false else continue if args i equals s files new string 20 for int j i k 0 j args length j if args j starts with break files k args j if args i equals h this helper functions new file args i if this helper functions is file p error this helper functions get absolute path file not found return false if args i equals o string odir args i output directory new file odir ends with file separator odir odir file separator output directory mkdirs if output directory exists output directory is directory p error output directory get absolute path could not create directory return false if args i equals p opt level integer parse int args i if args i equals db debug level integer parse int args i opt level 0 if args i equals e executable args i return true else switch args length case 0 p error specify location of java script tests return false case 1 p error specify location of java script helper functions file return false case 2 this test directory args 0 ends with file separator new file args 0 new file args 0 file separator this helper functions new file args 1 if this test directory is directory p error this test directory get absolute path is not a directory return false if this helper functions is file p error this helper functions get absolute path file not found return false return true default p could not understand arguments return false processoptions startswith test_directory endswith test_directory isdirectory test_directory getabsolutepath startswith helper_functions helper_functions isfile helper_functions getabsolutepath output_directory endswith output_directory output_directory output_directory isdirectory output_directory getabsolutepath opt_level parseint debug_level parseint opt_level javascript javascript helper_functions test_directory endswith helper_functions test_directory isdirectory test_directory getabsolutepath helper_functions isfile helper_functions getabsolutepath public synchronized void execute suite test suite suite p live connect drv execute suite suite name test environment context test file file if executable null generate helper file for int i 0 i suite size i synchronized suite file test file suite element at i p file name if executable null context new live connect env file suite this else context new live rhino env file suite this synchronized context context run test the following two lines are used by the other test drivers but are not used by live connect drv since each live connec test writes its results to these log files write file result file suite output directory write case results file suite output directory context close context null if file passed suite passed false write suite result suite output directory write suite summary suite output directory executesuite testsuite liveconnectdrv executesuite testenvironment testfile generatehelperfile testfile elementat liveconnectenv liverhinoenv runtest liveconnectdrv liveconnectest writefileresult output_directory writecaseresults output_directory writesuiteresult output_directory writesuitesummary output_directory public void generate helper file try this helper functions new file output directory helper js p helper functions file is helper functions file output stream fos new file output stream helper functions fos write var output directory output directory get bytes fos write var output file arguments 1 get bytes fos write var test class name arguments 0 get bytes fos write var test class eval test class name get bytes fos write var testclass new test class get bytes fos write testclass run get bytes fos write quit get bytes fos close catch exception e p generate helper file threw e to string e print stack trace generatehelperfile helper_functions output_directory helper_functions fileoutputstream fileoutputstream helper_functions output_directory output_directory getbytes output_file getbytes testclassname getbytes testclass testclassname getbytes testclass getbytes getbytes getbytes generatehelperfile tostring printstacktrace for each class file in the suite directory create a test file object for live connect the test class name needs to be the name of the class and the file path needs to be the full package name prepended with the java script keyword packages and without the class suffix public void get cases test suite suite enable privileges file dir new file suite file path string files dir list xxx hardcoded package name need to fix this string filename packages com netscape javascript qa liveconnect suite name for int i 0 i files length i if files i ends with get suffix test file item new test file files i filename files i substring 0 files i length get suffix length p item file path suite add element item testfile liveconnect javascript getcases testsuite enableprivileges filepath endswith getsuffix testfile testfile getsuffix filepath addelement public arguments native call activation this activation activation scriptable parent activation get parent scope set parent scope parent set prototype scriptable object get object prototype parent args activation original args length obj new integer args length native function f activation function callee obj f int version f get language version if version context version 1 3 version context version default caller obj null else caller obj not found nativecall getparentscope setparentscope setprototype scriptableobject getobjectprototype originalargs lengthobj nativefunction calleeobj getlanguageversion version_1_3 version_default callerobj callerobj not_found public string get class name return arguments getclassname public boolean has int index scriptable start if 0 index index args length if args index not found return true return super has index start not_found public object get int index scriptable start if 0 index index args length object value args index if value not found if shared with activation index native function f activation function string arg name f get param or var name index value activation get arg name activation if value not found kit code bug return value return super get index start not_found sharedwithactivation nativefunction argname getparamorvarname argname not_found codebug private boolean shared with activation int index native function f activation function int defined count f get param count if index defined count check if argument is not hidden by later argument with the same name as hidden arguments are not shared with activation if index defined count 1 string arg name f get param or var name index for int i index 1 i defined count i if arg name equals f get param or var name i return false return true return false sharedwithactivation nativefunction definedcount getparamcount definedcount definedcount argname getparamorvarname definedcount argname getparamorvarname public void put int index scriptable start object value if 0 index index args length if args index not found if shared with activation index string arg name arg name activation function get param or var name index activation put arg name activation value return synchronized this if args index not found if args activation original args args object args clone args index value return super put index start value not_found sharedwithactivation argname argname getparamorvarname argname not_found originalargs public void delete int index if 0 index index args length synchronized this if args index not found if args activation original args args object args clone args index not found return super delete index not_found originalargs not_found max instance id 3 protected int get max instance id return max instance id max_instance_id getmaxinstanceid max_instance_id protected int find instance id info string s int id generated last update 2002 04 09 20 46 33 cest l0 id 0 string x null int c if s length 6 c s char at 5 if c e x callee id id callee else if c h x length id id length else if c r x caller id id caller if x null x s x equals s id 0 generated if id 0 return super find instance id info s int attr switch id case id callee case id caller case id length attr dontenum break default throw new illegal state exception return instance id info attr id findinstanceidinfo charat id_callee id_length id_caller findinstanceidinfo id_callee id_caller id_length illegalstateexception instanceidinfo protected string get instance id name int id switch id case id callee return callee case id length return length case id caller return caller return null getinstanceidname id_callee id_length id_caller protected object get instance id value int id switch id case id callee return callee obj case id length return length obj case id caller object value caller obj if value unique tag null value value null else if value null native call caller activation parent activation call if caller null value caller get arguments caller else value null return value return super get instance id value id getinstanceidvalue id_callee calleeobj id_length lengthobj id_caller callerobj uniquetag null_value nativecall parentactivationcall getinstanceidvalue protected void set instance id value int id object value switch id case id callee callee obj value return case id length length obj value return case id caller caller obj value null value unique tag null value return super set instance id value id value setinstanceidvalue id_callee calleeobj id_length lengthobj id_caller callerobj uniquetag null_value setinstanceidvalue object get ids boolean get all object ids super get ids get all if get all args length 0 boolean present null int extra count args length for int i 0 i ids length i object id ids i if id instanceof integer int index integer id int value if 0 index index args length if present null present new boolean args length if present index present index true extra count if extra count 0 object tmp new object extra count ids length system arraycopy ids 0 tmp extra count ids length ids tmp int offset 0 for int i 0 i args length i if present null present i ids offset new integer i offset if offset extra count kit code bug return ids getids getall getids getall getall extracount intvalue extracount extracount extracount extracount extracount codebug public class js object eval given a js object and some java script code have the object evaluate the java script code public static object eval js object obj string code obj eval code return null jsobjecteval jsobject javascript javascript jsobject public int float 512 public int ambiguous float arg return float public int ambiguous double arg return double public int ambiguous byte arg return byte public int ambiguous char arg return char public int ambiguous short arg return short public int ambiguous int arg return int public int ambiguous long arg return long public int ambiguous string arg return string public int ambiguous object arg return object public int ambiguous boolean arg return boolean object boolean_object return boolean object public int expect return boolean object boolean_object boolean_object public static void main string args throws exception context cx context enter try scriptable scope cx init standard objects scriptable object define class scope counter class scriptable test counter cx new object scope counter object count scriptable object get property test counter count system out println count count count scriptable object get property test counter count system out println count count scriptable object call method test counter reset count new object 0 system out println reset count count scriptable object get property test counter count system out println count count finally context exit initstandardobjects scriptableobject defineclass testcounter newobject scriptableobject getproperty testcounter scriptableobject getproperty testcounter scriptableobject callmethod testcounter resetcount resetcount scriptableobject getproperty testcounter construct a class file writer for a class param class name the name of the class to write including full package qualification param super class name the name of the superclass of the class to write including full package qualification param source file name the name of the source file to use for producing debug information or null if debug information is not desired public class file writer string class name string super class name string source file name generated class name class name its constant pool new constant pool this its this class index its constant pool add class class name its super class index its constant pool add class super class name if source file name null its source file name index its constant pool add utf8 source file name its flags acc public classfilewriter classname superclassname sourcefilename classfilewriter classname superclassname sourcefilename generatedclassname classname itsconstantpool constantpool itsthisclassindex itsconstantpool addclass classname itssuperclassindex itsconstantpool addclass superclassname sourcefilename itssourcefilenameindex itsconstantpool addutf8 sourcefilename itsflags acc_public public final string get class name return generated class name getclassname generatedclassname add an interface implemented by this class this method may be called multiple times for classes that implement multiple interfaces param interface name a name of an interface implemented by the class being written including full package qualification public void add interface string interface name short interface index its constant pool add class interface name its interfaces add new short interface index interfacename addinterface interfacename interfaceindex itsconstantpool addclass interfacename itsinterfaces interfaceindex set the class s flags flags must be a set of the following flags bitwise or d together acc public acc private acc protected acc final acc abstract todo check that this is the appropriate set param flags the set of class flags to set public void set flags short flags its flags flags acc_public acc_private acc_protected acc_final acc_abstract setflags itsflags static string get slashed form string name return name replace getslashedform convert java class name in dot notation into lname with dots replaced by slashes form suitable for use as jvm type signatures public static string class name to signature string name int name length name length int colon pos 1 name length char buf new char colon pos 1 buf 0 l buf colon pos name get chars 0 name length buf 1 for int i 1 i colon pos i if buf i buf i return new string buf 0 colon pos 1 classnametosignature namelength colonpos namelength colonpos colonpos getchars namelength colonpos colonpos add a field to the class param field name the name of the field param type the type of the field using param flags the attributes of the field such as acc public etc bitwise or d together public void add field string field name string type short flags short field name index its constant pool add utf8 field name short type index its constant pool add utf8 type its fields add new class file field field name index type index flags fieldname acc_public addfield fieldname fieldnameindex itsconstantpool addutf8 fieldname typeindex itsconstantpool addutf8 itsfields classfilefield fieldnameindex typeindex add a field to the class param field name the name of the field param type the type of the field using param flags the attributes of the field such as acc public etc bitwise or d together param value an initial integral value public void add field string field name string type short flags int value short field name index its constant pool add utf8 field name short type index its constant pool add utf8 type class file field field new class file field field name index type index flags field set attributes its constant pool add utf8 constant value short 0 short 0 its constant pool add constant value its fields add field fieldname acc_public addfield fieldname fieldnameindex itsconstantpool addutf8 fieldname typeindex itsconstantpool addutf8 classfilefield classfilefield fieldnameindex typeindex setattributes itsconstantpool addutf8 constantvalue itsconstantpool addconstant itsfields add a field to the class param field name the name of the field param type the type of the field using param flags the attributes of the field such as acc public etc bitwise or d together param value an initial long value public void add field string field name string type short flags long value short field name index its constant pool add utf8 field name short type index its constant pool add utf8 type class file field field new class file field field name index type index flags field set attributes its constant pool add utf8 constant value short 0 short 2 its constant pool add constant value its fields add field fieldname acc_public addfield fieldname fieldnameindex itsconstantpool addutf8 fieldname typeindex itsconstantpool addutf8 classfilefield classfilefield fieldnameindex typeindex setattributes itsconstantpool addutf8 constantvalue itsconstantpool addconstant itsfields add a field to the class param field name the name of the field param type the type of the field using param flags the attributes of the field such as acc public etc bitwise or d together param value an initial double value public void add field string field name string type short flags double value short field name index its constant pool add utf8 field name short type index its constant pool add utf8 type class file field field new class file field field name index type index flags field set attributes its constant pool add utf8 constant value short 0 short 2 its constant pool add constant value its fields add field fieldname acc_public addfield fieldname fieldnameindex itsconstantpool addutf8 fieldname typeindex itsconstantpool addutf8 classfilefield classfilefield fieldnameindex typeindex setattributes itsconstantpool addutf8 constantvalue itsconstantpool addconstant itsfields add information about java variable to use when generating the local variable table param name variable name param type variable type as bytecode descriptor string param startpc the starting bytecode pc where this variable is live or 1 if it does not have a java register param register the java register number of variable or 1 if it does not have a java register public void add variable descriptor string name string type int startpc int register int name index its constant pool add utf8 name int descriptor index its constant pool add utf8 type int chunk name index descriptor index startpc register if its var descriptors null its var descriptors new obj array its var descriptors add chunk addvariabledescriptor nameindex itsconstantpool addutf8 descriptorindex itsconstantpool addutf8 nameindex descriptorindex itsvardescriptors itsvardescriptors objarray itsvardescriptors add a method and begin adding code this method must be called before other methods for adding code exception tables etc can be invoked param method name the name of the method param type a string representing the type param flags the attributes of the field such as acc public etc bitwise or d together public void start method string method name string type short flags short method name index its constant pool add utf8 method name short type index its constant pool add utf8 type its current method new class file method method name index type index flags its methods add its current method methodname acc_public startmethod methodname methodnameindex itsconstantpool addutf8 methodname typeindex itsconstantpool addutf8 itscurrentmethod classfilemethod methodnameindex typeindex itsmethods itscurrentmethod complete generation of the method after this method is called no more code can be added to the method begun with code start method code param max locals the maximum number of local variable slots a k a java registers used by the method param vars the array of the variables for the method or null if none public void stop method short max locals if its current method null throw new illegal state exception no method to stop fix label gotos its max locals max locals int line number table length 0 if its line number table null 6 bytes for the attribute header 2 bytes for the line number count 4 bytes for each entry line number table length 6 2 its line number table top 4 int variable table length 0 if its var descriptors null 6 bytes for the attribute header 2 bytes for the variable count 10 bytes for each entry variable table length 6 2 its var descriptors size 10 int attr length 2 attribute name index 4 attribute length 2 max stack 2 max locals 4 code length its code buffer top 2 exception table length its exception table top 8 2 attributes count line number table length variable table length byte code attribute new byte attr length int index 0 int code attr index its constant pool add utf8 code index put int16 code attr index code attribute index attr length 6 discount the attribute header index put int32 attr length code attribute index index put int16 its max stack code attribute index index put int16 its max locals code attribute index index put int32 its code buffer top code attribute index system arraycopy its code buffer 0 code attribute index its code buffer top index its code buffer top if its exception table top 0 index put int16 its exception table top code attribute index for int i 0 i its exception table top i exception table entry ete its exception table i short startpc short get labelpc ete its start label short endpc short get labelpc ete its end label short handlerpc short get labelpc ete its handler label short catch type ete its catch type if startpc 1 throw new illegal state exception start label not defined if endpc 1 throw new illegal state exception end label not defined if handlerpc 1 throw new illegal state exception handler label not defined index put int16 startpc code attribute index index put int16 endpc code attribute index index put int16 handlerpc code attribute index index put int16 catch type code attribute index else write 0 as exception table length index put int16 0 code attribute index int attribute count 0 if its line number table null attribute count if its var descriptors null attribute count index put int16 attribute count code attribute index if its line number table null int line number table attr index its constant pool add utf8 line number table index put int16 line number table attr index code attribute index int table attr length 2 its line number table top 4 index put int32 table attr length code attribute index index put int16 its line number table top code attribute index for int i 0 i its line number table top i index put int32 its line number table i code attribute index if its var descriptors null int variable table attr index its constant pool add utf8 local variable table index put int16 variable table attr index code attribute index int var count its var descriptors size int table attr length 2 var count 10 index put int32 table attr length code attribute index index put int16 var count code attribute index for int i 0 i var count i int chunk int its var descriptors get i int name index chunk 0 int descriptor index chunk 1 int startpc chunk 2 int register chunk 3 int length its code buffer top startpc index put int16 startpc code attribute index index put int16 length code attribute index index put int16 name index code attribute index index put int16 descriptor index code attribute index index put int16 register code attribute index its current method set code attribute code attribute its exception table null its exception table top 0 its line number table top 0 its code buffer top 0 its current method null its max stack 0 its stack top 0 its label table top 0 its fixup table top 0 its var descriptors null startmethod maxlocals stopmethod maxlocals itscurrentmethod illegalstateexception fixlabelgotos itsmaxlocals maxlocals linenumbertablelength itslinenumbertable linenumbertablelength itslinenumbertabletop variabletablelength itsvardescriptors variabletablelength itsvardescriptors attrlength attribute_name_index attribute_length max_stack max_locals code_length itscodebuffertop exception_table_length itsexceptiontabletop attributes_count linenumbertablelength variabletablelength codeattribute attrlength codeattrindex itsconstantpool addutf8 putint16 codeattrindex codeattribute attrlength putint32 attrlength codeattribute putint16 itsmaxstack codeattribute putint16 itsmaxlocals codeattribute putint32 itscodebuffertop codeattribute itscodebuffer codeattribute itscodebuffertop itscodebuffertop itsexceptiontabletop putint16 itsexceptiontabletop codeattribute itsexceptiontabletop exceptiontableentry itsexceptiontable getlabelpc itsstartlabel getlabelpc itsendlabel getlabelpc itshandlerlabel catchtype itscatchtype illegalstateexception illegalstateexception illegalstateexception putint16 codeattribute putint16 codeattribute putint16 codeattribute putint16 catchtype codeattribute putint16 codeattribute attributecount itslinenumbertable attributecount itsvardescriptors attributecount putint16 attributecount codeattribute itslinenumbertable linenumbertableattrindex itsconstantpool addutf8 linenumbertable putint16 linenumbertableattrindex codeattribute tableattrlength itslinenumbertabletop putint32 tableattrlength codeattribute putint16 itslinenumbertabletop codeattribute itslinenumbertabletop putint32 itslinenumbertable codeattribute itsvardescriptors variabletableattrindex itsconstantpool addutf8 localvariabletable putint16 variabletableattrindex codeattribute varcount itsvardescriptors tableattrlength varcount putint32 tableattrlength codeattribute putint16 varcount codeattribute varcount itsvardescriptors nameindex descriptorindex itscodebuffertop putint16 codeattribute putint16 codeattribute putint16 nameindex codeattribute putint16 descriptorindex codeattribute putint16 codeattribute itscurrentmethod setcodeattribute codeattribute itsexceptiontable itsexceptiontabletop itslinenumbertabletop itscodebuffertop itscurrentmethod itsmaxstack itsstacktop itslabeltabletop itsfixuptabletop itsvardescriptors add the single byte opcode to the current method param the op code the opcode of the bytecode public void add int the op code if opcode count the op code 0 throw new illegal argument exception unexpected operands int new stack its stack top stack change the op code if new stack 0 short max value new stack bad stack new stack if debugcode system out println add bytecode str the op code add to code buffer the op code its stack top short new stack if new stack its max stack its max stack short new stack if debugstack system out println after bytecode str the op code stack its stack top theopcode theopcode opcodecount theopcode illegalargumentexception newstack itsstacktop stackchange theopcode newstack max_value newstack badstack newstack bytecodestr theopcode addtocodebuffer theopcode itsstacktop newstack newstack itsmaxstack itsmaxstack newstack bytecodestr theopcode itsstacktop add a single operand opcode to the current method param the op code the opcode of the bytecode param the operand the operand of the bytecode public void add int the op code int the operand if debugcode system out println add bytecode str the op code integer to hex string the operand int new stack its stack top stack change the op code if new stack 0 short max value new stack bad stack new stack switch the op code case byte code goto fallthru case byte code ifeq case byte code ifne case byte code iflt case byte code ifge case byte code ifgt case byte code ifle case byte code if icmpeq case byte code if icmpne case byte code if icmplt case byte code if icmpge case byte code if icmpgt case byte code if icmple case byte code if acmpeq case byte code if acmpne case byte code jsr case byte code ifnull case byte code ifnonnull if the operand 0x80000000 0x80000000 if the operand 0 the operand 65535 throw new illegal argument exception bad label for branch int branchpc its code buffer top add to code buffer the op code if the operand 0x80000000 0x80000000 hard displacement add to code int16 the operand else a label int targetpc get labelpc the operand if debuglabels int the label the operand 0x7fffffff system out println fixing branch to the label at targetpc from branchpc if targetpc 1 int offset targetpc branchpc add to code int16 offset else add label fixup the operand branchpc 1 add to code int16 0 break case byte code bipush if byte the operand the operand throw new illegal argument exception out of range byte add to code buffer the op code add to code buffer byte the operand break case byte code sipush if short the operand the operand throw new illegal argument exception out of range short add to code buffer the op code add to code int16 the operand break case byte code newarray if 0 the operand the operand 256 throw new illegal argument exception out of range index add to code buffer the op code add to code buffer the operand break case byte code getfield case byte code putfield if 0 the operand the operand 65536 throw new illegal argument exception out of range field add to code buffer the op code add to code int16 the operand break case byte code ldc case byte code ldc w case byte code ldc2 w if 0 the operand the operand 65536 throw new illegal argument exception out of range index if the operand 256 the op code byte code ldc w the op code byte code ldc2 w if the op code byte code ldc add to code buffer byte code ldc w else add to code buffer the op code add to code int16 the operand else add to code buffer the op code add to code buffer the operand break case byte code ret case byte code iload case byte code lload case byte code fload case byte code dload case byte code aload case byte code istore case byte code lstore case byte code fstore case byte code dstore case byte code astore if 0 the operand the operand 65536 throw new illegal argument exception out of range variable if the operand 256 add to code buffer byte code wide add to code buffer the op code add to code int16 the operand else add to code buffer the op code add to code buffer the operand break default throw new illegal argument exception unexpected opcode for 1 operand its stack top short new stack if new stack its max stack its max stack short new stack if debugstack system out println after bytecode str the op code stack its stack top theopcode theoperand theopcode theoperand bytecodestr theopcode tohexstring theoperand newstack itsstacktop stackchange theopcode newstack max_value newstack badstack newstack theopcode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode if_icmpeq bytecode if_icmpne bytecode if_icmplt bytecode if_icmpge bytecode if_icmpgt bytecode if_icmple bytecode if_acmpeq bytecode if_acmpne bytecode bytecode bytecode theoperand theoperand theoperand illegalargumentexception itscodebuffertop addtocodebuffer theopcode theoperand addtocodeint16 theoperand getlabelpc theoperand thelabel theoperand thelabel addtocodeint16 addlabelfixup theoperand addtocodeint16 bytecode theoperand theoperand illegalargumentexception addtocodebuffer theopcode addtocodebuffer theoperand bytecode theoperand theoperand illegalargumentexception addtocodebuffer theopcode addtocodeint16 theoperand bytecode theoperand theoperand illegalargumentexception addtocodebuffer theopcode addtocodebuffer theoperand bytecode bytecode theoperand theoperand illegalargumentexception addtocodebuffer theopcode addtocodeint16 theoperand bytecode bytecode ldc_w bytecode ldc2_w theoperand theoperand illegalargumentexception theoperand theopcode bytecode ldc_w theopcode bytecode ldc2_w theopcode bytecode addtocodebuffer bytecode ldc_w addtocodebuffer theopcode addtocodeint16 theoperand addtocodebuffer theopcode addtocodebuffer theoperand bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode theoperand theoperand illegalargumentexception theoperand addtocodebuffer bytecode addtocodebuffer theopcode addtocodeint16 theoperand addtocodebuffer theopcode addtocodebuffer theoperand illegalargumentexception itsstacktop newstack newstack itsmaxstack itsmaxstack newstack bytecodestr theopcode itsstacktop generate the load constant bytecode for the given integer param k the constant public void add load constant int k add byte code ldc its constant pool add constant k addloadconstant bytecode itsconstantpool addconstant generate the load constant bytecode for the given long param k the constant public void add load constant long k add byte code ldc2 w its constant pool add constant k addloadconstant bytecode ldc2_w itsconstantpool addconstant generate the load constant bytecode for the given float param k the constant public void add load constant float k add byte code ldc its constant pool add constant k addloadconstant bytecode itsconstantpool addconstant generate the load constant bytecode for the given double param k the constant public void add load constant double k add byte code ldc2 w its constant pool add constant k addloadconstant bytecode ldc2_w itsconstantpool addconstant generate the load constant bytecode for the given string param k the constant public void add load constant string k add byte code ldc its constant pool add constant k addloadconstant bytecode itsconstantpool addconstant add the given two operand bytecode to the current method param the op code the opcode of the bytecode param the operand1 the first operand of the bytecode param the operand2 the second operand of the bytecode public void add int the op code int the operand1 int the operand2 if debugcode system out println add bytecode str the op code integer to hex string the operand1 integer to hex string the operand2 int new stack its stack top stack change the op code if new stack 0 short max value new stack bad stack new stack if the op code byte code iinc if 0 the operand1 the operand1 65536 throw new illegal argument exception out of range variable if 0 the operand2 the operand2 65536 throw new illegal argument exception out of range increment if the operand1 255 the operand2 128 the operand2 127 add to code buffer byte code wide add to code buffer byte code iinc add to code int16 the operand1 add to code int16 the operand2 else add to code buffer byte code wide add to code buffer byte code iinc add to code buffer the operand1 add to code buffer the operand2 else if the op code byte code multianewarray if 0 the operand1 the operand1 65536 throw new illegal argument exception out of range index if 0 the operand2 the operand2 256 throw new illegal argument exception out of range dimensions add to code buffer byte code multianewarray add to code int16 the operand1 add to code buffer the operand2 else throw new illegal argument exception unexpected opcode for 2 operands its stack top short new stack if new stack its max stack its max stack short new stack if debugstack system out println after bytecode str the op code stack its stack top theopcode theoperand1 theoperand2 theopcode theoperand1 theoperand2 bytecodestr theopcode tohexstring theoperand1 tohexstring theoperand2 newstack itsstacktop stackchange theopcode newstack max_value newstack badstack newstack theopcode bytecode theoperand1 theoperand1 illegalargumentexception theoperand2 theoperand2 illegalargumentexception theoperand1 theoperand2 theoperand2 addtocodebuffer bytecode addtocodebuffer bytecode addtocodeint16 theoperand1 addtocodeint16 theoperand2 addtocodebuffer bytecode addtocodebuffer bytecode addtocodebuffer theoperand1 addtocodebuffer theoperand2 theopcode bytecode theoperand1 theoperand1 illegalargumentexception theoperand2 theoperand2 illegalargumentexception addtocodebuffer bytecode addtocodeint16 theoperand1 addtocodebuffer theoperand2 illegalargumentexception itsstacktop newstack newstack itsmaxstack itsmaxstack newstack bytecodestr theopcode itsstacktop public void add int the op code string class name if debugcode system out println add bytecode str the op code class name int new stack its stack top stack change the op code if new stack 0 short max value new stack bad stack new stack switch the op code case byte code new case byte code anewarray case byte code checkcast case byte code instanceof short class index its constant pool add class class name add to code buffer the op code add to code int16 class index break default throw new illegal argument exception bad opcode for class reference its stack top short new stack if new stack its max stack its max stack short new stack if debugstack system out println after bytecode str the op code stack its stack top theopcode classname bytecodestr theopcode classname newstack itsstacktop stackchange theopcode newstack max_value newstack badstack newstack theopcode bytecode bytecode bytecode bytecode classindex itsconstantpool addclass classname addtocodebuffer theopcode addtocodeint16 classindex illegalargumentexception itsstacktop newstack newstack itsmaxstack itsmaxstack newstack bytecodestr theopcode itsstacktop public void add int the op code string class name string field name string field type if debugcode system out println add bytecode str the op code class name field name field type int new stack its stack top stack change the op code char field type char field type char at 0 int field size field type char j field type char d 2 1 switch the op code case byte code getfield case byte code getstatic new stack field size break case byte code putstatic case byte code putfield new stack field size break default throw new illegal argument exception bad opcode for field reference if new stack 0 short max value new stack bad stack new stack short field ref index its constant pool add field ref class name field name field type add to code buffer the op code add to code int16 field ref index its stack top short new stack if new stack its max stack its max stack short new stack if debugstack system out println after bytecode str the op code stack its stack top theopcode classname fieldname fieldtype bytecodestr theopcode classname fieldname fieldtype newstack itsstacktop stackchange theopcode fieldtypechar fieldtype charat fieldsize fieldtypechar fieldtypechar theopcode bytecode bytecode newstack fieldsize bytecode bytecode newstack fieldsize illegalargumentexception newstack max_value newstack badstack newstack fieldrefindex itsconstantpool addfieldref classname fieldname fieldtype addtocodebuffer theopcode addtocodeint16 fieldrefindex itsstacktop newstack newstack itsmaxstack itsmaxstack newstack bytecodestr theopcode itsstacktop public void add invoke int the op code string class name string method name string method type if debugcode system out println add bytecode str the op code class name method name method type int parameter info size of parameters method type int parameter count parameter info 16 int stack diff short parameter info int new stack its stack top stack diff new stack stack change the op code adjusts for this if new stack 0 short max value new stack bad stack new stack switch the op code case byte code invokevirtual case byte code invokespecial case byte code invokestatic case byte code invokeinterface add to code buffer the op code if the op code byte code invokeinterface short if method ref index its constant pool add interface method ref class name method name method type add to code int16 if method ref index add to code buffer parameter count 1 add to code buffer 0 else short method ref index its constant pool add method ref class name method name method type add to code int16 method ref index break default throw new illegal argument exception bad opcode for method reference its stack top short new stack if new stack its max stack its max stack short new stack if debugstack system out println after bytecode str the op code stack its stack top addinvoke theopcode classname methodname methodtype bytecodestr theopcode classname methodname methodtype parameterinfo sizeofparameters methodtype parametercount parameterinfo stackdiff parameterinfo newstack itsstacktop stackdiff newstack stackchange theopcode newstack max_value newstack badstack newstack theopcode bytecode bytecode bytecode bytecode addtocodebuffer theopcode theopcode bytecode ifmethodrefindex itsconstantpool addinterfacemethodref classname methodname methodtype addtocodeint16 ifmethodrefindex addtocodebuffer parametercount addtocodebuffer methodrefindex itsconstantpool addmethodref classname methodname methodtype addtocodeint16 methodrefindex illegalargumentexception itsstacktop newstack newstack itsmaxstack itsmaxstack newstack bytecodestr theopcode itsstacktop generate code to load the given integer on stack param k the constant public void add push int k if byte k k if k 1 add byte code iconst m1 else if 0 k k 5 add byte byte code iconst 0 k else add byte code bipush byte k else if short k k add byte code sipush short k else add load constant k addpush bytecode iconst_m1 bytecode iconst_0 bytecode bytecode addloadconstant public void add push boolean k add k byte code iconst 1 byte code iconst 0 addpush bytecode iconst_1 bytecode iconst_0 generate code to load the given long on stack param k the constant public void add push long k int ik int k if ik k add push ik add byte code i2l else add load constant k addpush addpush bytecode addloadconstant generate code to load the given double on stack param k the constant public void add push double k if k 0 0 zero add byte code dconst 0 if 1 0 k 0 negative zero add byte code dneg else if k 1 0 k 1 0 add byte code dconst 1 if k 0 add byte code dneg else add load constant k addpush bytecode dconst_0 bytecode bytecode dconst_1 bytecode addloadconstant generate the code to leave on stack the given string even if the string encoding exeeds the class file limit for single string constant param k the constant public void add push string k int length k length int limit its constant pool get utf encoding limit k 0 length if limit length add load constant k return split string into picies fitting the utf limit and generate code for string buffer sb new string buffer length sb append load constant piece 1 sb append load constant piece n sb to string final string sb java lang string buffer add byte code new sb add byte code dup add push length add invoke byte code invokespecial sb init i v int cursor 0 for add byte code dup string s k substring cursor limit add load constant s add invoke byte code invokevirtual sb append ljava lang string ljava lang string buffer add byte code pop if limit length break cursor limit limit its constant pool get utf encoding limit k limit length add invoke byte code invokevirtual sb to string ljava lang string addpush itsconstantpool getutfencodinglimit addloadconstant stringbuffer stringbuffer loadconstant piece_1 loadconstant piece_n tostring stringbuffer bytecode bytecode addpush addinvoke bytecode bytecode addloadconstant addinvoke bytecode stringbuffer bytecode itsconstantpool getutfencodinglimit addinvoke bytecode tostring check if k fits limit on string constant size imposed by class file format param k the string constant public boolean is under string size limit string k return its constant pool is under utf encoding limit k isunderstringsizelimit itsconstantpool isunderutfencodinglimit store integer from stack top into the given local param local number of local register public void addi store int local xop byte code istore 0 byte code istore local addistore bytecode istore_0 bytecode store long from stack top into the given local param local number of local register public void addl store int local xop byte code lstore 0 byte code lstore local addlstore bytecode lstore_0 bytecode store float from stack top into the given local param local number of local register public void addf store int local xop byte code fstore 0 byte code fstore local addfstore bytecode fstore_0 bytecode store double from stack top into the given local param local number of local register public void addd store int local xop byte code dstore 0 byte code dstore local adddstore bytecode dstore_0 bytecode store object from stack top into the given local param local number of local register public void adda store int local xop byte code astore 0 byte code astore local addastore bytecode astore_0 bytecode load integer from the given local into stack param local number of local register public void addi load int local xop byte code iload 0 byte code iload local addiload bytecode iload_0 bytecode load long from the given local into stack param local number of local register public void addl load int local xop byte code lload 0 byte code lload local addlload bytecode lload_0 bytecode load float from the given local into stack param local number of local register public void addf load int local xop byte code fload 0 byte code fload local addfload bytecode fload_0 bytecode load double from the given local into stack param local number of local register public void addd load int local xop byte code dload 0 byte code dload local adddload bytecode dload_0 bytecode load object from the given local into stack param local number of local register public void adda load int local xop byte code aload 0 byte code aload local addaload bytecode aload_0 bytecode load this into stack public void add load this add byte code aload 0 addloadthis bytecode aload_0 private void xop int short op int op int local switch local case 0 add short op break case 1 add short op 1 break case 2 add short op 2 break case 3 add short op 3 break default add op local shortop shortop shortop shortop shortop public int add table switch int low int high if debugcode system out println add bytecode str byte code tableswitch low high if low high throw new illegal argument exception bad bounds low high int new stack its stack top stack change byte code tableswitch if new stack 0 short max value new stack bad stack new stack int entry count high low 1 int pad size 3 its code buffer top 3 its code buffer top 4 int n add reserved code space 1 pad size 4 1 2 entry count int switch start n its code buffer n byte byte code tableswitch while pad size 0 its code buffer n 0 pad size n 4 skip default offset n put int32 low its code buffer n put int32 high its code buffer n its stack top short new stack if new stack its max stack its max stack short new stack if debugstack system out println after bytecode str byte code tableswitch stack its stack top return switch start addtableswitch bytecodestr bytecode illegalargumentexception newstack itsstacktop stackchange bytecode newstack max_value newstack badstack newstack entrycount padsize itscodebuffertop itscodebuffertop addreservedcodespace padsize entrycount switchstart itscodebuffer bytecode padsize itscodebuffer padsize putint32 itscodebuffer putint32 itscodebuffer itsstacktop newstack newstack itsmaxstack itsmaxstack newstack bytecodestr bytecode itsstacktop switchstart public final void mark table switch default int switch start set table switch jump switch start 1 its code buffer top marktableswitchdefault switchstart settableswitchjump switchstart itscodebuffertop public final void mark table switch case int switch start int case index set table switch jump switch start case index its code buffer top marktableswitchcase switchstart caseindex settableswitchjump switchstart caseindex itscodebuffertop public final void mark table switch case int switch start int case index int stack top if 0 stack top stack top its max stack throw new illegal argument exception bad stack index stack top its stack top short stack top set table switch jump switch start case index its code buffer top marktableswitchcase switchstart caseindex stacktop stacktop stacktop itsmaxstack illegalargumentexception stacktop itsstacktop stacktop settableswitchjump switchstart caseindex itscodebuffertop public void set table switch jump int switch start int case index int jump target if 0 jump target jump target its code buffer top throw new illegal argument exception bad jump target jump target if case index 1 throw new illegal argument exception bad case index case index int pad size 3 switch start 3 switch start 4 int case offset if case index 0 default label case offset switch start 1 pad size else case offset switch start 1 pad size 4 3 case index if 0 switch start switch start its code buffer top 4 4 pad size 1 throw new illegal argument exception switch start is outside a possible range of tableswitch in already generated code if 0xff its code buffer switch start byte code tableswitch throw new illegal argument exception switch start is not offset of tableswitch statement if 0 case offset case offset 4 its code buffer top case index 1 does not guarantee that case offset 0 due to a possible overflow throw new illegal argument exception too big case index case index alert perhaps check against case bounds put int32 jump target switch start its code buffer case offset settableswitchjump switchstart caseindex jumptarget jumptarget jumptarget itscodebuffertop illegalargumentexception jumptarget caseindex illegalargumentexception caseindex padsize switchstart switchstart caseoffset caseindex caseoffset switchstart padsize caseoffset switchstart padsize caseindex switchstart switchstart itscodebuffertop padsize illegalargumentexception switchstart itscodebuffer switchstart bytecode illegalargumentexception switchstart caseoffset caseoffset itscodebuffertop caseindex caseoffset illegalargumentexception caseindex putint32 jumptarget switchstart itscodebuffer caseoffset public int acquire label int top its label table top if its label table null top its label table length if its label table null its label table new int min label table size else int tmp new int its label table length 2 system arraycopy its label table 0 tmp 0 top its label table tmp its label table top top 1 its label table top 1 return top 0x80000000 acquirelabel itslabeltabletop itslabeltable itslabeltable itslabeltable itslabeltable min_label_table_size itslabeltable itslabeltable itslabeltable itslabeltabletop itslabeltable public void mark label int label if label 0 throw new illegal argument exception bad label no biscuit label 0x7fffffff if label its label table top throw new illegal argument exception bad label if its label table label 1 throw new illegal state exception can only mark label once its label table label its code buffer top marklabel illegalargumentexception itslabeltabletop illegalargumentexception itslabeltable illegalstateexception itslabeltable itscodebuffertop public void mark label int label short stack top mark label label its stack top stack top marklabel stacktop marklabel itsstacktop stacktop public void mark handler int the label its stack top 1 mark label the label markhandler thelabel itsstacktop marklabel thelabel private int get labelpc int label if label 0 throw new illegal argument exception bad label no biscuit label 0x7fffffff if label its label table top throw new illegal argument exception bad label return its label table label getlabelpc illegalargumentexception itslabeltabletop illegalargumentexception itslabeltable private void add label fixup int label int fixup site if label 0 throw new illegal argument exception bad label no biscuit label 0x7fffffff if label its label table top throw new illegal argument exception bad label int top its fixup table top if its fixup table null top its fixup table length if its fixup table null its fixup table new long min fixup table size else long tmp new long its fixup table length 2 system arraycopy its fixup table 0 tmp 0 top its fixup table tmp its fixup table top top 1 its fixup table top long label 32 fixup site addlabelfixup fixupsite illegalargumentexception itslabeltabletop illegalargumentexception itsfixuptabletop itsfixuptable itsfixuptable itsfixuptable itsfixuptable min_fixup_table_size itsfixuptable itsfixuptable itsfixuptable itsfixuptabletop itsfixuptable fixupsite private void fix label gotos byte code buffer its code buffer for int i 0 i its fixup table top i long fixup its fixup table i int label int fixup 32 int fixup site int fixup int pc its label table label if pc 1 unlocated label throw new runtime exception 1 to get delta from instruction start int offset pc fixup site 1 if short offset offset throw new runtime exception program too complex too big jump offset code buffer fixup site byte offset 8 code buffer fixup site 1 byte offset its fixup table top 0 fixlabelgotos codebuffer itscodebuffer itsfixuptabletop itsfixuptable fixupsite itslabeltable runtimeexception fixupsite runtimeexception codebuffer fixupsite codebuffer fixupsite itsfixuptabletop get the current offset into the code of the current method return an integer representing the offset public int get current code offset return its code buffer top getcurrentcodeoffset itscodebuffertop public short get stack top return its stack top getstacktop itsstacktop public void adjust stack top int delta int new stack its stack top delta if new stack 0 short max value new stack bad stack new stack its stack top short new stack if new stack its max stack its max stack short new stack if debugstack system out println after adjust stack top delta stack its stack top adjuststacktop newstack itsstacktop newstack max_value newstack badstack newstack itsstacktop newstack newstack itsmaxstack itsmaxstack newstack adjuststacktop itsstacktop private void add to code buffer int b int n add reserved code space 1 its code buffer n byte b addtocodebuffer addreservedcodespace itscodebuffer private void add to code int16 int value int n add reserved code space 2 put int16 value its code buffer n addtocodeint16 addreservedcodespace putint16 itscodebuffer private int add reserved code space int size if its current method null throw new illegal argument exception no method to add to int old top its code buffer top int new top old top size if new top its code buffer length int new size its code buffer length 2 if new top new size new size new top byte tmp new byte new size system arraycopy its code buffer 0 tmp 0 old top its code buffer tmp its code buffer top new top return old top addreservedcodespace itscurrentmethod illegalargumentexception oldtop itscodebuffertop newtop oldtop newtop itscodebuffer newsize itscodebuffer newtop newsize newsize newtop newsize itscodebuffer oldtop itscodebuffer itscodebuffertop newtop oldtop public void add exception handler int start label int end label int handler label string catch class name if start label 0x80000000 0x80000000 throw new illegal argument exception bad start label if end label 0x80000000 0x80000000 throw new illegal argument exception bad end label if handler label 0x80000000 0x80000000 throw new illegal argument exception bad handler label if catch class name is null use 0 for the catch type index which means catch everything even when the verifier has let you throw something other than a throwable short catch type index catch class name null 0 its constant pool add class catch class name exception table entry new entry new exception table entry start label end label handler label catch type index int n its exception table top if n 0 its exception table new exception table entry exception table size else if n its exception table length exception table entry tmp new exception table entry n 2 system arraycopy its exception table 0 tmp 0 n its exception table tmp its exception table n new entry its exception table top n 1 addexceptionhandler startlabel endlabel handlerlabel catchclassname startlabel illegalargumentexception startlabel endlabel illegalargumentexception endlabel handlerlabel illegalargumentexception handlerlabel catchclassname catch_type_index catch_type_index catchclassname itsconstantpool addclass catchclassname exceptiontableentry newentry exceptiontableentry startlabel endlabel handlerlabel catch_type_index itsexceptiontabletop itsexceptiontable exceptiontableentry exceptiontablesize itsexceptiontable exceptiontableentry exceptiontableentry itsexceptiontable itsexceptiontable itsexceptiontable newentry itsexceptiontabletop public void add line number entry short line number if its current method null throw new illegal argument exception no method to stop int n its line number table top if n 0 its line number table new int line number table size else if n its line number table length int tmp new int n 2 system arraycopy its line number table 0 tmp 0 n its line number table tmp its line number table n its code buffer top 16 line number its line number table top n 1 addlinenumberentry linenumber itscurrentmethod illegalargumentexception itslinenumbertabletop itslinenumbertable linenumbertablesize itslinenumbertable itslinenumbertable itslinenumbertable itslinenumbertable itscodebuffertop linenumber itslinenumbertabletop write the class file to the output stream param o stream the stream to write to throws io exception if writing to the stream produces an exception public void write output stream o stream throws io exception byte array to byte array o stream write array outputstream ostream ioexception outputstream ostream ioexception tobytearray ostream private int get write size int size 0 if its source file name index 0 its constant pool add utf8 source file size 8 write long file header constant size its constant pool get write size size 2 write short its flags size 2 write short its this class index size 2 write short its super class index size 2 write short its interfaces size size 2 its interfaces size size 2 write short its fields size for int i 0 i its fields size i size class file field its fields get i get write size size 2 write short its methods size for int i 0 i its methods size i size class file method its methods get i get write size if its source file name index 0 size 2 write short 1 attributes count size 2 write short source file attribute name index size 4 write int 2 size 2 write short its source file name index else size 2 out write short 0 no attributes return size getwritesize itssourcefilenameindex itsconstantpool addutf8 sourcefile writelong fileheaderconstant itsconstantpool getwritesize writeshort itsflags writeshort itsthisclassindex writeshort itssuperclassindex writeshort itsinterfaces itsinterfaces writeshort itsfields itsfields classfilefield itsfields getwritesize writeshort itsmethods itsmethods classfilemethod itsmethods getwritesize itssourcefilenameindex writeshort writeshort sourcefileattributenameindex writeint writeshort itssourcefilenameindex writeshort get the class file as array of bytesto the output stream public byte to byte array int data size get write size byte data new byte data size int offset 0 short source file attribute name index 0 if its source file name index 0 source file attribute name index its constant pool add utf8 source file offset put int64 file header constant data offset offset its constant pool write data offset offset put int16 its flags data offset offset put int16 its this class index data offset offset put int16 its super class index data offset offset put int16 its interfaces size data offset for int i 0 i its interfaces size i int interface index short its interfaces get i short value offset put int16 interface index data offset offset put int16 its fields size data offset for int i 0 i its fields size i class file field field class file field its fields get i offset field write data offset offset put int16 its methods size data offset for int i 0 i its methods size i class file method method class file method its methods get i offset method write data offset if its source file name index 0 offset put int16 1 data offset attributes count offset put int16 source file attribute name index data offset offset put int32 2 data offset offset put int16 its source file name index data offset else offset put int16 0 data offset no attributes if offset data size check get write size is consistent with write throw new runtime exception return data outputstream tobytearray datasize getwritesize datasize sourcefileattributenameindex itssourcefilenameindex sourcefileattributenameindex itsconstantpool addutf8 sourcefile putint64 fileheaderconstant itsconstantpool putint16 itsflags putint16 itsthisclassindex putint16 itssuperclassindex putint16 itsinterfaces itsinterfaces interfaceindex itsinterfaces shortvalue putint16 interfaceindex putint16 itsfields itsfields classfilefield classfilefield itsfields putint16 itsmethods itsmethods classfilemethod classfilemethod itsmethods itssourcefilenameindex putint16 putint16 sourcefileattributenameindex putint32 putint16 itssourcefilenameindex putint16 datasize getwritesize runtimeexception static int put int64 long value byte array int offset offset put int32 int value 32 array offset return put int32 int value array offset putint64 putint32 putint32 private static void bad stack int value string s if value 0 s stack underflow value else s too big stack value throw new illegal state exception s badstack illegalstateexception private static int size of parameters string p string int length p string length int right parenthesis p string last index of if 3 length minimal signature takes at least 3 chars v p string char at 0 1 right parenthesis right parenthesis 1 length boolean ok true int index 1 int stack diff 0 int count 0 string loop while index right parenthesis switch p string char at index default ok false break string loop case j case d stack diff fall thru case b case s case c case i case z case f stack diff count index continue case index int c p string char at index while c index c p string char at index switch c default ok false break string loop case j case d case b case s case c case i case z case f stack diff count index continue case l fall thru fall thru case l stack diff count index int semicolon p string index of index if index 1 semicolon semicolon right parenthesis ok false break string loop index semicolon 1 continue if ok switch p string char at right parenthesis 1 default ok false break case j case d stack diff fall thru case b case s case c case i case z case f case l case stack diff fall thru case v break if ok return count 16 0xffff stack diff throw new illegal argument exception bad parameter signature p string sizeofparameters pstring pstring rightparenthesis pstring lastindexof pstring charat rightparenthesis rightparenthesis stackdiff stringloop rightparenthesis pstring charat stringloop stackdiff stackdiff pstring charat pstring charat stringloop stackdiff stackdiff pstring indexof rightparenthesis stringloop pstring charat rightparenthesis stackdiff stackdiff stackdiff illegalargumentexception pstring static int put int16 int value byte array int offset array offset 0 byte value 8 array offset 1 byte value return offset 2 putint16 static int put int32 int value byte array int offset array offset 0 byte value 24 array offset 1 byte value 16 array offset 2 byte value 8 array offset 3 byte value return offset 4 putint32 number of operands accompanying the opcode static int opcode count int opcode switch opcode case byte code aaload case byte code aastore case byte code aconst null case byte code aload 0 case byte code aload 1 case byte code aload 2 case byte code aload 3 case byte code areturn case byte code arraylength case byte code astore 0 case byte code astore 1 case byte code astore 2 case byte code astore 3 case byte code athrow case byte code baload case byte code bastore case byte code breakpoint case byte code caload case byte code castore case byte code d2f case byte code d2i case byte code d2l case byte code dadd case byte code daload case byte code dastore case byte code dcmpg case byte code dcmpl case byte code dconst 0 case byte code dconst 1 case byte code ddiv case byte code dload 0 case byte code dload 1 case byte code dload 2 case byte code dload 3 case byte code dmul case byte code dneg case byte code drem case byte code dreturn case byte code dstore 0 case byte code dstore 1 case byte code dstore 2 case byte code dstore 3 case byte code dsub case byte code dup case byte code dup2 case byte code dup2 x1 case byte code dup2 x2 case byte code dup x1 case byte code dup x2 case byte code f2d case byte code f2i case byte code f2l case byte code fadd case byte code faload case byte code fastore case byte code fcmpg case byte code fcmpl case byte code fconst 0 case byte code fconst 1 case byte code fconst 2 case byte code fdiv case byte code fload 0 case byte code fload 1 case byte code fload 2 case byte code fload 3 case byte code fmul case byte code fneg case byte code frem case byte code freturn case byte code fstore 0 case byte code fstore 1 case byte code fstore 2 case byte code fstore 3 case byte code fsub case byte code i2b case byte code i2c case byte code i2d case byte code i2f case byte code i2l case byte code i2s case byte code iadd case byte code iaload case byte code iand case byte code iastore case byte code iconst 0 case byte code iconst 1 case byte code iconst 2 case byte code iconst 3 case byte code iconst 4 case byte code iconst 5 case byte code iconst m1 case byte code idiv case byte code iload 0 case byte code iload 1 case byte code iload 2 case byte code iload 3 case byte code impdep1 case byte code impdep2 case byte code imul case byte code ineg case byte code ior case byte code irem case byte code ireturn case byte code ishl case byte code ishr case byte code istore 0 case byte code istore 1 case byte code istore 2 case byte code istore 3 case byte code isub case byte code iushr case byte code ixor case byte code l2d case byte code l2f case byte code l2i case byte code ladd case byte code laload case byte code land case byte code lastore case byte code lcmp case byte code lconst 0 case byte code lconst 1 case byte code ldiv case byte code lload 0 case byte code lload 1 case byte code lload 2 case byte code lload 3 case byte code lmul case byte code lneg case byte code lor case byte code lrem case byte code lreturn case byte code lshl case byte code lshr case byte code lstore 0 case byte code lstore 1 case byte code lstore 2 case byte code lstore 3 case byte code lsub case byte code lushr case byte code lxor case byte code monitorenter case byte code monitorexit case byte code nop case byte code pop case byte code pop2 case byte code return case byte code saload case byte code sastore case byte code swap case byte code wide return 0 case byte code aload case byte code anewarray case byte code astore case byte code bipush case byte code checkcast case byte code dload case byte code dstore case byte code fload case byte code fstore case byte code getfield case byte code getstatic case byte code goto case byte code goto w case byte code ifeq case byte code ifge case byte code ifgt case byte code ifle case byte code iflt case byte code ifne case byte code ifnonnull case byte code ifnull case byte code if acmpeq case byte code if acmpne case byte code if icmpeq case byte code if icmpge case byte code if icmpgt case byte code if icmple case byte code if icmplt case byte code if icmpne case byte code iload case byte code instanceof case byte code invokeinterface case byte code invokespecial case byte code invokestatic case byte code invokevirtual case byte code istore case byte code jsr case byte code jsr w case byte code ldc case byte code ldc2 w case byte code ldc w case byte code lload case byte code lstore case byte code new case byte code newarray case byte code putfield case byte code putstatic case byte code ret case byte code sipush return 1 case byte code iinc case byte code multianewarray return 2 case byte code lookupswitch case byte code tableswitch return 1 throw new illegal argument exception bad opcode opcode opcodecount bytecode bytecode bytecode aconst_null bytecode aload_0 bytecode aload_1 bytecode aload_2 bytecode aload_3 bytecode bytecode bytecode astore_0 bytecode astore_1 bytecode astore_2 bytecode astore_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode dconst_0 bytecode dconst_1 bytecode bytecode dload_0 bytecode dload_1 bytecode dload_2 bytecode dload_3 bytecode bytecode bytecode bytecode bytecode dstore_0 bytecode dstore_1 bytecode dstore_2 bytecode dstore_3 bytecode bytecode bytecode bytecode dup2_x1 bytecode dup2_x2 bytecode dup_x1 bytecode dup_x2 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode fconst_0 bytecode fconst_1 bytecode fconst_2 bytecode bytecode fload_0 bytecode fload_1 bytecode fload_2 bytecode fload_3 bytecode bytecode bytecode bytecode bytecode fstore_0 bytecode fstore_1 bytecode fstore_2 bytecode fstore_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode iconst_0 bytecode iconst_1 bytecode iconst_2 bytecode iconst_3 bytecode iconst_4 bytecode iconst_5 bytecode iconst_m1 bytecode bytecode iload_0 bytecode iload_1 bytecode iload_2 bytecode iload_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode istore_0 bytecode istore_1 bytecode istore_2 bytecode istore_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode lconst_0 bytecode lconst_1 bytecode bytecode lload_0 bytecode lload_1 bytecode lload_2 bytecode lload_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode lstore_0 bytecode lstore_1 bytecode lstore_2 bytecode lstore_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode goto_w bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode if_acmpeq bytecode if_acmpne bytecode if_icmpeq bytecode if_icmpge bytecode if_icmpgt bytecode if_icmple bytecode if_icmplt bytecode if_icmpne bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode jsr_w bytecode bytecode ldc2_w bytecode ldc_w bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode illegalargumentexception the effect on the operand stack of a given opcode static int stack change int opcode for invoke accounts only for popping this unless static ignoring parameters and return type switch opcode case byte code dastore case byte code lastore return 4 case byte code aastore case byte code bastore case byte code castore case byte code dcmpg case byte code dcmpl case byte code fastore case byte code iastore case byte code lcmp case byte code sastore return 3 case byte code dadd case byte code ddiv case byte code dmul case byte code drem case byte code dreturn case byte code dstore case byte code dstore 0 case byte code dstore 1 case byte code dstore 2 case byte code dstore 3 case byte code dsub case byte code if acmpeq case byte code if acmpne case byte code if icmpeq case byte code if icmpge case byte code if icmpgt case byte code if icmple case byte code if icmplt case byte code if icmpne case byte code ladd case byte code land case byte code ldiv case byte code lmul case byte code lor case byte code lrem case byte code lreturn case byte code lstore case byte code lstore 0 case byte code lstore 1 case byte code lstore 2 case byte code lstore 3 case byte code lsub case byte code lxor case byte code pop2 return 2 case byte code aaload case byte code areturn case byte code astore case byte code astore 0 case byte code astore 1 case byte code astore 2 case byte code astore 3 case byte code athrow case byte code baload case byte code caload case byte code d2f case byte code d2i case byte code fadd case byte code faload case byte code fcmpg case byte code fcmpl case byte code fdiv case byte code fmul case byte code frem case byte code freturn case byte code fstore case byte code fstore 0 case byte code fstore 1 case byte code fstore 2 case byte code fstore 3 case byte code fsub case byte code getfield case byte code iadd case byte code iaload case byte code iand case byte code idiv case byte code ifeq case byte code ifge case byte code ifgt case byte code ifle case byte code iflt case byte code ifne case byte code ifnonnull case byte code ifnull case byte code imul case byte code invokeinterface case byte code invokespecial but needs to account for case byte code invokevirtual pops this unless static case byte code ior case byte code irem case byte code ireturn case byte code ishl case byte code ishr case byte code istore case byte code istore 0 case byte code istore 1 case byte code istore 2 case byte code istore 3 case byte code isub case byte code iushr case byte code ixor case byte code l2f case byte code l2i case byte code lookupswitch case byte code lshl case byte code lshr case byte code lushr case byte code monitorenter case byte code monitorexit case byte code pop case byte code putfield case byte code saload case byte code tableswitch return 1 case byte code anewarray case byte code arraylength case byte code breakpoint case byte code checkcast case byte code d2l case byte code daload case byte code dneg case byte code f2i case byte code fneg case byte code getstatic case byte code goto case byte code goto w case byte code i2b case byte code i2c case byte code i2f case byte code i2s case byte code iinc case byte code impdep1 case byte code impdep2 case byte code ineg case byte code instanceof case byte code invokestatic case byte code l2d case byte code laload case byte code lneg case byte code newarray case byte code nop case byte code putstatic case byte code ret case byte code return case byte code swap case byte code wide return 0 case byte code aconst null case byte code aload case byte code aload 0 case byte code aload 1 case byte code aload 2 case byte code aload 3 case byte code bipush case byte code dup case byte code dup x1 case byte code dup x2 case byte code f2d case byte code f2l case byte code fconst 0 case byte code fconst 1 case byte code fconst 2 case byte code fload case byte code fload 0 case byte code fload 1 case byte code fload 2 case byte code fload 3 case byte code i2d case byte code i2l case byte code iconst 0 case byte code iconst 1 case byte code iconst 2 case byte code iconst 3 case byte code iconst 4 case byte code iconst 5 case byte code iconst m1 case byte code iload case byte code iload 0 case byte code iload 1 case byte code iload 2 case byte code iload 3 case byte code jsr case byte code jsr w case byte code ldc case byte code ldc w case byte code multianewarray case byte code new case byte code sipush return 1 case byte code dconst 0 case byte code dconst 1 case byte code dload case byte code dload 0 case byte code dload 1 case byte code dload 2 case byte code dload 3 case byte code dup2 case byte code dup2 x1 case byte code dup2 x2 case byte code lconst 0 case byte code lconst 1 case byte code ldc2 w case byte code lload case byte code lload 0 case byte code lload 1 case byte code lload 2 case byte code lload 3 return 2 throw new illegal argument exception bad opcode opcode stackchange bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode dstore_0 bytecode dstore_1 bytecode dstore_2 bytecode dstore_3 bytecode bytecode if_acmpeq bytecode if_acmpne bytecode if_icmpeq bytecode if_icmpge bytecode if_icmpgt bytecode if_icmple bytecode if_icmplt bytecode if_icmpne bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode lstore_0 bytecode lstore_1 bytecode lstore_2 bytecode lstore_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode astore_0 bytecode astore_1 bytecode astore_2 bytecode astore_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode fstore_0 bytecode fstore_1 bytecode fstore_2 bytecode fstore_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode istore_0 bytecode istore_1 bytecode istore_2 bytecode istore_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode goto_w bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode aconst_null bytecode bytecode aload_0 bytecode aload_1 bytecode aload_2 bytecode aload_3 bytecode bytecode bytecode dup_x1 bytecode dup_x2 bytecode bytecode bytecode fconst_0 bytecode fconst_1 bytecode fconst_2 bytecode bytecode fload_0 bytecode fload_1 bytecode fload_2 bytecode fload_3 bytecode bytecode bytecode iconst_0 bytecode iconst_1 bytecode iconst_2 bytecode iconst_3 bytecode iconst_4 bytecode iconst_5 bytecode iconst_m1 bytecode bytecode iload_0 bytecode iload_1 bytecode iload_2 bytecode iload_3 bytecode bytecode jsr_w bytecode bytecode ldc_w bytecode bytecode bytecode bytecode dconst_0 bytecode dconst_1 bytecode bytecode dload_0 bytecode dload_1 bytecode dload_2 bytecode dload_3 bytecode bytecode dup2_x1 bytecode dup2_x2 bytecode lconst_0 bytecode lconst_1 bytecode ldc2_w bytecode bytecode lload_0 bytecode lload_1 bytecode lload_2 bytecode lload_3 illegalargumentexception private static string bytecode str int code if debugstack debugcode switch code case byte code nop return nop case byte code aconst null return aconst null case byte code iconst m1 return iconst m1 case byte code iconst 0 return iconst 0 case byte code iconst 1 return iconst 1 case byte code iconst 2 return iconst 2 case byte code iconst 3 return iconst 3 case byte code iconst 4 return iconst 4 case byte code iconst 5 return iconst 5 case byte code lconst 0 return lconst 0 case byte code lconst 1 return lconst 1 case byte code fconst 0 return fconst 0 case byte code fconst 1 return fconst 1 case byte code fconst 2 return fconst 2 case byte code dconst 0 return dconst 0 case byte code dconst 1 return dconst 1 case byte code bipush return bipush case byte code sipush return sipush case byte code ldc return ldc case byte code ldc w return ldc w case byte code ldc2 w return ldc2 w case byte code iload return iload case byte code lload return lload case byte code fload return fload case byte code dload return dload case byte code aload return aload case byte code iload 0 return iload 0 case byte code iload 1 return iload 1 case byte code iload 2 return iload 2 case byte code iload 3 return iload 3 case byte code lload 0 return lload 0 case byte code lload 1 return lload 1 case byte code lload 2 return lload 2 case byte code lload 3 return lload 3 case byte code fload 0 return fload 0 case byte code fload 1 return fload 1 case byte code fload 2 return fload 2 case byte code fload 3 return fload 3 case byte code dload 0 return dload 0 case byte code dload 1 return dload 1 case byte code dload 2 return dload 2 case byte code dload 3 return dload 3 case byte code aload 0 return aload 0 case byte code aload 1 return aload 1 case byte code aload 2 return aload 2 case byte code aload 3 return aload 3 case byte code iaload return iaload case byte code laload return laload case byte code faload return faload case byte code daload return daload case byte code aaload return aaload case byte code baload return baload case byte code caload return caload case byte code saload return saload case byte code istore return istore case byte code lstore return lstore case byte code fstore return fstore case byte code dstore return dstore case byte code astore return astore case byte code istore 0 return istore 0 case byte code istore 1 return istore 1 case byte code istore 2 return istore 2 case byte code istore 3 return istore 3 case byte code lstore 0 return lstore 0 case byte code lstore 1 return lstore 1 case byte code lstore 2 return lstore 2 case byte code lstore 3 return lstore 3 case byte code fstore 0 return fstore 0 case byte code fstore 1 return fstore 1 case byte code fstore 2 return fstore 2 case byte code fstore 3 return fstore 3 case byte code dstore 0 return dstore 0 case byte code dstore 1 return dstore 1 case byte code dstore 2 return dstore 2 case byte code dstore 3 return dstore 3 case byte code astore 0 return astore 0 case byte code astore 1 return astore 1 case byte code astore 2 return astore 2 case byte code astore 3 return astore 3 case byte code iastore return iastore case byte code lastore return lastore case byte code fastore return fastore case byte code dastore return dastore case byte code aastore return aastore case byte code bastore return bastore case byte code castore return castore case byte code sastore return sastore case byte code pop return pop case byte code pop2 return pop2 case byte code dup return dup case byte code dup x1 return dup x1 case byte code dup x2 return dup x2 case byte code dup2 return dup2 case byte code dup2 x1 return dup2 x1 case byte code dup2 x2 return dup2 x2 case byte code swap return swap case byte code iadd return iadd case byte code ladd return ladd case byte code fadd return fadd case byte code dadd return dadd case byte code isub return isub case byte code lsub return lsub case byte code fsub return fsub case byte code dsub return dsub case byte code imul return imul case byte code lmul return lmul case byte code fmul return fmul case byte code dmul return dmul case byte code idiv return idiv case byte code ldiv return ldiv case byte code fdiv return fdiv case byte code ddiv return ddiv case byte code irem return irem case byte code lrem return lrem case byte code frem return frem case byte code drem return drem case byte code ineg return ineg case byte code lneg return lneg case byte code fneg return fneg case byte code dneg return dneg case byte code ishl return ishl case byte code lshl return lshl case byte code ishr return ishr case byte code lshr return lshr case byte code iushr return iushr case byte code lushr return lushr case byte code iand return iand case byte code land return land case byte code ior return ior case byte code lor return lor case byte code ixor return ixor case byte code lxor return lxor case byte code iinc return iinc case byte code i2l return i2l case byte code i2f return i2f case byte code i2d return i2d case byte code l2i return l2i case byte code l2f return l2f case byte code l2d return l2d case byte code f2i return f2i case byte code f2l return f2l case byte code f2d return f2d case byte code d2i return d2i case byte code d2l return d2l case byte code d2f return d2f case byte code i2b return i2b case byte code i2c return i2c case byte code i2s return i2s case byte code lcmp return lcmp case byte code fcmpl return fcmpl case byte code fcmpg return fcmpg case byte code dcmpl return dcmpl case byte code dcmpg bytecodestr bytecode bytecode aconst_null aconst_null bytecode iconst_m1 iconst_m1 bytecode iconst_0 iconst_0 bytecode iconst_1 iconst_1 bytecode iconst_2 iconst_2 bytecode iconst_3 iconst_3 bytecode iconst_4 iconst_4 bytecode iconst_5 iconst_5 bytecode lconst_0 lconst_0 bytecode lconst_1 lconst_1 bytecode fconst_0 fconst_0 bytecode fconst_1 fconst_1 bytecode fconst_2 fconst_2 bytecode dconst_0 dconst_0 bytecode dconst_1 dconst_1 bytecode bytecode bytecode bytecode ldc_w ldc_w bytecode ldc2_w ldc2_w bytecode bytecode bytecode bytecode bytecode bytecode iload_0 iload_0 bytecode iload_1 iload_1 bytecode iload_2 iload_2 bytecode iload_3 iload_3 bytecode lload_0 lload_0 bytecode lload_1 lload_1 bytecode lload_2 lload_2 bytecode lload_3 lload_3 bytecode fload_0 fload_0 bytecode fload_1 fload_1 bytecode fload_2 fload_2 bytecode fload_3 fload_3 bytecode dload_0 dload_0 bytecode dload_1 dload_1 bytecode dload_2 dload_2 bytecode dload_3 dload_3 bytecode aload_0 aload_0 bytecode aload_1 aload_1 bytecode aload_2 aload_2 bytecode aload_3 aload_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode istore_0 istore_0 bytecode istore_1 istore_1 bytecode istore_2 istore_2 bytecode istore_3 istore_3 bytecode lstore_0 lstore_0 bytecode lstore_1 lstore_1 bytecode lstore_2 lstore_2 bytecode lstore_3 lstore_3 bytecode fstore_0 fstore_0 bytecode fstore_1 fstore_1 bytecode fstore_2 fstore_2 bytecode fstore_3 fstore_3 bytecode dstore_0 dstore_0 bytecode dstore_1 dstore_1 bytecode dstore_2 dstore_2 bytecode dstore_3 dstore_3 bytecode astore_0 astore_0 bytecode astore_1 astore_1 bytecode astore_2 astore_2 bytecode astore_3 astore_3 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode dup_x1 dup_x1 bytecode dup_x2 dup_x2 bytecode bytecode dup2_x1 dup2_x1 bytecode dup2_x2 dup2_x2 bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode final char get char buffer int minimal size if minimal size tmp char buffer length int new size tmp char buffer length 2 if minimal size new size new size minimal size tmp char buffer new char new size return tmp char buffer getcharbuffer minimalsize minimalsize tmpcharbuffer newsize tmpcharbuffer minimalsize newsize newsize minimalsize tmpcharbuffer newsize tmpcharbuffer exception table entry int start label int end label int handler label short catch type its start label start label its end label end label its handler label handler label its catch type catch type exceptiontableentry startlabel endlabel handlerlabel catchtype itsstartlabel startlabel itsendlabel endlabel itshandlerlabel handlerlabel itscatchtype catchtype class file field short name index short type index short flags its name index name index its type index type index its flags flags its has attributes false classfilefield nameindex typeindex itsnameindex nameindex itstypeindex typeindex itsflags itshasattributes void set attributes short attr1 short attr2 short attr3 int index its has attributes true its attr1 attr1 its attr2 attr2 its attr3 attr3 its index index setattributes itshasattributes itsattr1 itsattr2 itsattr3 itsindex int write byte data int offset offset class file writer put int16 its flags data offset offset class file writer put int16 its name index data offset offset class file writer put int16 its type index data offset if its has attributes write 0 attributes offset class file writer put int16 0 data offset else offset class file writer put int16 1 data offset offset class file writer put int16 its attr1 data offset offset class file writer put int16 its attr2 data offset offset class file writer put int16 its attr3 data offset offset class file writer put int16 its index data offset return offset classfilewriter putint16 itsflags classfilewriter putint16 itsnameindex classfilewriter putint16 itstypeindex itshasattributes classfilewriter putint16 classfilewriter putint16 classfilewriter putint16 itsattr1 classfilewriter putint16 itsattr2 classfilewriter putint16 itsattr3 classfilewriter putint16 itsindex int get write size int size 2 3 if its has attributes size 2 else size 2 2 4 return size getwritesize itshasattributes class file method short name index short type index short flags its name index name index its type index type index its flags flags classfilemethod nameindex typeindex itsnameindex nameindex itstypeindex typeindex itsflags void set code attribute byte code attribute its code attribute code attribute setcodeattribute codeattribute itscodeattribute codeattribute int write byte data int offset offset class file writer put int16 its flags data offset offset class file writer put int16 its name index data offset offset class file writer put int16 its type index data offset code attribute only offset class file writer put int16 1 data offset system arraycopy its code attribute 0 data offset its code attribute length offset its code attribute length return offset classfilewriter putint16 itsflags classfilewriter putint16 itsnameindex classfilewriter putint16 itstypeindex classfilewriter putint16 itscodeattribute itscodeattribute itscodeattribute int get write size return 2 4 its code attribute length getwritesize itscodeattribute constant pool class file writer cfw this cfw cfw its top index 1 the zero th entry is reserved its pool new byte constant pool size its top 0 constantpool classfilewriter itstopindex itspool constantpoolsize itstop int write byte data int offset offset class file writer put int16 short its top index data offset system arraycopy its pool 0 data offset its top offset its top return offset classfilewriter putint16 itstopindex itspool itstop itstop int get write size return 2 its top getwritesize itstop int add constant int k ensure 5 its pool its top constant integer its top class file writer put int32 k its pool its top return short its top index addconstant itspool itstop constant_integer itstop classfilewriter putint32 itspool itstop itstopindex int add constant long k ensure 9 its pool its top constant long its top class file writer put int64 k its pool its top int index its top index its top index 2 return index addconstant itspool itstop constant_long itstop classfilewriter putint64 itspool itstop itstopindex itstopindex int add constant float k ensure 5 its pool its top constant float int bits float float to int bits k its top class file writer put int32 bits its pool its top return its top index addconstant itspool itstop constant_float floattointbits itstop classfilewriter putint32 itspool itstop itstopindex int add constant double k ensure 9 its pool its top constant double long bits double double to long bits k its top class file writer put int64 bits its pool its top int index its top index its top index 2 return index addconstant itspool itstop constant_double doubletolongbits itstop classfilewriter putint64 itspool itstop itstopindex itstopindex int add constant string k int utf8 index 0xffff add utf8 k int the index its string const hash get int utf8 index 1 if the index 1 the index its top index ensure 3 its pool its top constant string its top class file writer put int16 utf8 index its pool its top its string const hash put utf8 index the index return the index addconstant utf8index addutf8 theindex itsstringconsthash getint utf8index theindex theindex itstopindex itspool itstop constant_string itstop classfilewriter putint16 utf8index itspool itstop itsstringconsthash utf8index theindex theindex boolean is under utf encoding limit string s int str len s length if str len 3 max utf encoding size return true else if str len max utf encoding size return false return str len get utf encoding limit s 0 str len isunderutfencodinglimit strlen strlen max_utf_encoding_size strlen max_utf_encoding_size strlen getutfencodinglimit strlen get maximum i such that tt start i end tt and tt s substring start i tt fits jvm utf string encoding limit int get utf encoding limit string s int start int end if end start 3 max utf encoding size return end int limit max utf encoding size for int i start i end i int c s char at i if 0 c c 0x7f limit else if c 0x7ff limit 2 else limit 3 if limit 0 return i return end getutfencodinglimit max_utf_encoding_size max_utf_encoding_size charat short add utf8 string k int the index its utf8 hash get k 1 if the index 1 int str len k length boolean too big string if str len max utf encoding size too big string true else too big string false ask for worst case scenario buffer when each char takes 3 bytes ensure 1 2 str len 3 int top its top its pool top constant utf8 top 2 skip length char chars cfw get char buffer str len k get chars 0 str len chars 0 for int i 0 i str len i int c chars i if c 0 c 0x7f its pool top byte c else if c 0x7ff its pool top byte 0xe0 c 12 its pool top byte 0x80 c 6 0x3f its pool top byte 0x80 c 0x3f else its pool top byte 0xc0 c 6 its pool top byte 0x80 c 0x3f int utf len top its top 1 2 if utf len max utf encoding size too big string true else write back length its pool its top 1 byte utf len 8 its pool its top 2 byte utf len its top top the index its top index its utf8 hash put k the index if too big string throw new illegal argument exception too big string return short the index addutf8 theindex itsutf8hash theindex strlen toobigstring strlen max_utf_encoding_size toobigstring toobigstring strlen itstop itspool constant_utf8 getcharbuffer strlen getchars strlen strlen itspool itspool itspool itspool itspool itspool utflen itstop utflen max_utf_encoding_size toobigstring itspool itstop utflen itspool itstop utflen itstop theindex itstopindex itsutf8hash theindex toobigstring illegalargumentexception theindex private short add name and type string name string type short name index add utf8 name short type index add utf8 type ensure 5 its pool its top constant nameandtype its top class file writer put int16 name index its pool its top its top class file writer put int16 type index its pool its top return short its top index addnameandtype nameindex addutf8 typeindex addutf8 itspool itstop constant_nameandtype itstop classfilewriter putint16 nameindex itspool itstop itstop classfilewriter putint16 typeindex itspool itstop itstopindex short add class string class name int the index its class hash get class name 1 if the index 1 string slashed class name if class name index of 0 slashed class file writer get slashed form class name the index its class hash get slashed 1 if the index 1 its class hash put class name the index if the index 1 int utf8 index add utf8 slashed ensure 3 its pool its top constant class its top class file writer put int16 utf8 index its pool its top the index its top index its class hash put slashed the index if class name slashed its class hash put class name the index return short the index addclass classname theindex itsclasshash classname theindex classname classname indexof classfilewriter getslashedform classname theindex itsclasshash theindex itsclasshash classname theindex theindex utf8index addutf8 itspool itstop constant_class itstop classfilewriter putint16 utf8index itspool itstop theindex itstopindex itsclasshash theindex classname itsclasshash classname theindex theindex short add field ref string class name string field name string field type field or method ref ref new field or method ref class name field name field type int the index its field ref hash get ref 1 if the index 1 short nt index add name and type field name field type short class index add class class name ensure 5 its pool its top constant fieldref its top class file writer put int16 class index its pool its top its top class file writer put int16 nt index its pool its top the index its top index its field ref hash put ref the index return short the index addfieldref classname fieldname fieldtype fieldormethodref fieldormethodref classname fieldname fieldtype theindex itsfieldrefhash theindex ntindex addnameandtype fieldname fieldtype classindex addclass classname itspool itstop constant_fieldref itstop classfilewriter putint16 classindex itspool itstop itstop classfilewriter putint16 ntindex itspool itstop theindex itstopindex itsfieldrefhash theindex theindex short add method ref string class name string method name string method type field or method ref ref new field or method ref class name method name method type int the index its method ref hash get ref 1 if the index 1 short nt index add name and type method name method type short class index add class class name ensure 5 its pool its top constant methodref its top class file writer put int16 class index its pool its top its top class file writer put int16 nt index its pool its top the index its top index its method ref hash put ref the index return short the index addmethodref classname methodname methodtype fieldormethodref fieldormethodref classname methodname methodtype theindex itsmethodrefhash theindex ntindex addnameandtype methodname methodtype classindex addclass classname itspool itstop constant_methodref itstop classfilewriter putint16 classindex itspool itstop itstop classfilewriter putint16 ntindex itspool itstop theindex itstopindex itsmethodrefhash theindex theindex short add interface method ref string class name string method name string method type short nt index add name and type method name method type short class index add class class name ensure 5 its pool its top constant interfacemethodref its top class file writer put int16 class index its pool its top its top class file writer put int16 nt index its pool its top return short its top index addinterfacemethodref classname methodname methodtype ntindex addnameandtype methodname methodtype classindex addclass classname itspool itstop constant_interfacemethodref itstop classfilewriter putint16 classindex itspool itstop itstop classfilewriter putint16 ntindex itspool itstop itstopindex void ensure int how much if its top how much its pool length int new capacity its pool length 2 if its top how much new capacity new capacity its top how much byte tmp new byte new capacity system arraycopy its pool 0 tmp 0 its top its pool tmp howmuch itstop howmuch itspool newcapacity itspool itstop howmuch newcapacity newcapacity itstop howmuch newcapacity itspool itstop itspool field or method ref string class name string name string type this class name class name this name name this type type fieldormethodref classname classname classname public boolean equals object obj if obj instanceof field or method ref return false field or method ref x field or method ref obj return class name equals x class name name equals x name type equals x type fieldormethodref fieldormethodref fieldormethodref classname classname public int hash code if hash code 1 int h1 class name hash code int h2 name hash code int h3 type hash code hash code h1 h2 h3 return hash code hashcode hashcode classname hashcode hashcode hashcode hashcode hashcode static void init scriptable scope boolean sealed native script obj new native script null obj export asjs class max prototype id scope sealed nativescript nativescript exportasjsclass max_prototype_id private native script script script this script script nativescript returns the name of this java script class script public string get class name return script javascript getclassname public object call context cx scriptable scope scriptable this obj object args if script null return script exec cx scope return undefined instance thisobj public scriptable construct context cx scriptable scope object args throw context report runtime error0 msg script is not constructor reportruntimeerror0 public int get length return 0 getlength public int get arity return 0 getarity string decompile int indent int flags if script instanceof native function return native function script decompile indent flags return super decompile indent flags nativefunction nativefunction protected void init prototype id int id string s int arity switch id case id constructor arity 1 s constructor break case id tostring arity 0 s to string break case id exec arity 0 s exec break case id compile arity 1 s compile break default throw new illegal argument exception string value of id init prototype method script tag id s arity initprototypeid id_constructor id_tostring tostring id_exec id_compile illegalargumentexception valueof initprototypemethod script_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag script tag return super exec id call f cx scope this obj args int id f method id switch id case id constructor string source args length 0 script runtime to string args 0 script script compile cx source native script nscript new native script script script runtime set object proto and parent nscript scope return nscript case id tostring native script real real this this obj f script real script real script if real script null return return cx decompile script real script 0 case id exec throw context report runtime error1 msg cant call indirect exec case id compile native script real real this this obj f string source script runtime to string args 0 real script compile cx source return real throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag script_tag execidcall thisobj methodid id_constructor scriptruntime tostring nativescript nativescript scriptruntime setobjectprotoandparent id_tostring nativescript realthis thisobj realscript realscript decompilescript realscript id_exec reportruntimeerror1 id_compile nativescript realthis thisobj scriptruntime tostring illegalargumentexception valueof private static native script real this scriptable this obj id function object f if this obj instanceof native script throw incompatible call error f return native script this obj nativescript realthis thisobj idfunctionobject thisobj nativescript incompatiblecallerror nativescript thisobj private static script compile context cx string source int linep 0 string filename context get source position from stack linep if filename null filename script object linep 0 1 error reporter reporter reporter default error reporter for eval cx get error reporter return cx compile string source null reporter filename linep 0 null getsourcepositionfromstack errorreporter defaulterrorreporter foreval geterrorreporter compilestring protected int find prototype id string s int id generated last update 2001 05 23 13 25 01 gmt 02 00 l0 id 0 string x null l switch s length case 4 x exec id id exec break l case 7 x compile id id compile break l case 8 x to string id id tostring break l case 11 x constructor id id constructor break l if x null x s x equals s id 0 generated return id findprototypeid id_exec id_compile tostring id_tostring id_constructor wrap the object p the value returned must be one of ul li java lang boolean li li java lang string li li java lang number li li org mozilla javascript scriptable objects li li the value returned by context get undefined value li li null li ul param cx the current context for this thread param scope the scope of the executing script param obj the object to be wrapped note it can be null param static type type hint if security restrictions prevent to wrap object based on its class static type will be used instead return the wrapped value public object wrap context cx scriptable scope object obj class static type if obj null obj undefined instance obj instanceof scriptable return obj if static type null static type is primitive if static type void type return undefined instance if static type character type return new integer int character obj char value return obj if is java primitive wrap if obj instanceof string obj instanceof number obj instanceof boolean return obj else if obj instanceof character return string value of character obj char value class cls obj get class if cls is array return native java array wrap scope obj return wrap as java object cx scope obj static type getundefinedvalue statictype statictype statictype statictype statictype isprimitive statictype statictype charvalue isjavaprimitivewrap valueof charvalue getclass isarray nativejavaarray wrapasjavaobject statictype wrap an object newly created by a constructor call param cx the current context for this thread param scope the scope of the executing script param obj the object to be wrapped return the wrapped value public scriptable wrap new object context cx scriptable scope object obj if obj instanceof scriptable return scriptable obj class cls obj get class if cls is array return native java array wrap scope obj return wrap as java object cx scope obj null wrapnewobject getclass isarray nativejavaarray wrapasjavaobject wrap java object as scriptable instance to allow full access to its methods and fields from java script p link wrap context scriptable object class and link wrap new object context scriptable object call this method when they can not convert tt java object tt to java script primitive value or java script array p subclasses can override the method to provide custom wrappers for java objects param cx the current context for this thread param scope the scope of the executing script param java object the object to be wrapped param static type type hint if security restrictions prevent to wrap object based on its class static type will be used instead return the wrapped value which shall not be null public scriptable wrap as java object context cx scriptable scope object java object class static type scriptable wrap wrap new native java object scope java object static type return wrap javascript wrapnewobject javaobject javascript javascript javaobject statictype statictype wrapasjavaobject javaobject statictype nativejavaobject javaobject statictype return code false code if result of java method which is instance of code string code code number code code boolean code and code character code should be used directly as java script primitive type by default the method returns true to indicate that instances of code string code code number code code boolean code and code character code should be wrapped as any other java object and scripts can access any java method available in these objects use link set java primitive wrap boolean to change this public final boolean is java primitive wrap return java primitive wrap javascript setjavaprimitivewrap isjavaprimitivewrap javaprimitivewrap see is java primitive wrap public final void set java primitive wrap boolean value context cx context get current context if cx null cx is sealed context on sealed mutation java primitive wrap value isjavaprimitivewrap setjavaprimitivewrap getcurrentcontext issealed onsealedmutation javaprimitivewrap public static final object instance new undefined private undefined public object read resolve return instance readresolve static final long serial versionuid 6461524852170711724l public nota function exception serialversionuid notafunctionexception public node transformer nodetransformer public final void transform script or fn node tree transform compilation unit tree for int i 0 i tree get function count i function node fn tree get function node i transform fn scriptorfnnode transformcompilationunit getfunctioncount functionnode getfunctionnode private void transform compilation unit script or fn node tree loops new obj array loop ends new obj array to save against upchecks if no finally blocks are used has finally false transformcompilationunit r tree tree transformcompilationunit scriptorfnnode objarray loopends objarray hasfinally transformcompilationunit_r private void transformcompilationunit r final script or fn node tree final node parent node node null sibling loop for node previous null if node null node parent get first child else previous node node node get next if node null break int type node get type switch type case token label case token switch case token loop loops push node loop ends push node jump node target break case token with loops push node node leave node get next if leave get type token leavewith kit code bug loop ends push leave break case token try node jump jump node jump node node finallytarget jump get finally if finallytarget null has finally true loops push node loop ends push finallytarget break case token target case token leavewith if loop ends is empty loop ends peek node loop ends pop loops pop break case token return if we didn t support try finally it wouldn t be necessary to put leavewith nodes here but as we do need a series of jsr finally nodes before each return we need to ensure that each finally block gets the correct scope which could mean that some leavewith nodes are necessary if has finally break skip the whole mess node unwind block null for int i loops size 1 i 0 i node n node loops get i int elemtype n get type if elemtype token try elemtype token with node unwind if elemtype token try node jump jsrnode new node jump token jsr node jsrtarget node jump n get finally jsrnode target jsrtarget unwind jsrnode else unwind new node token leavewith if unwind block null unwind block new node token block node get lineno unwind block add child to back unwind if unwind block null node return node node node return expr return node get first child node replace current parent previous node unwind block if return expr null unwind block add child to back return node else node store new node token expr result return expr unwind block add child to front store return node new node token return result unwind block add child to back return node transform return expression transformcompilationunit r tree store skip transformcompilationunit r to avoid infinite loop continue sibling loop break case token break case token continue node jump jump node jump node node jump jump statement jump get jump statement if jump statement null kit code bug for int i loops size if i 0 parser ir factory ensure that break continue always has a jump statement associated with it which should be found throw kit code bug i node n node loops get i if n jump statement break int elemtype n get type if elemtype token with node leave new node token leavewith previous add before current parent previous node leave else if elemtype token try node jump try node node jump n node jump jsr finally new node jump token jsr jsr finally target try node get finally previous add before current parent previous node jsr finally if type token break jump target jump statement target else jump target jump statement get continue jump set type token goto break case token call visit call node tree break case token new visit new node tree break case token var node result new node token block for node cursor node get first child cursor null move cursor to next before create assignment get chance to change n next node n cursor if n get type token name kit code bug cursor cursor get next if n has children continue node init n get first child n remove child init n set type token bindname n new node token setname n init node pop new node token expr void n node get lineno result add child to back pop node replace current parent previous node result break case token name case token setname case token delprop turn name to var for faster access if possible if tree get type token function function node tree requires activation break node name source if type token name name source node else name source node get first child if name source get type token bindname if type token delprop break throw kit code bug string name name source get string if tree has param or var name if type token name node set type token getvar else if type token setname node set type token setvar name source set type token string else if type token delprop local variables are by definition permanent node n new node token false node replace current parent previous node n else throw kit code bug break transformcompilationunit r tree node transformcompilationunit_r scriptorfnnode siblingloop getfirstchild getnext gettype loopends getnext gettype codebug loopends getfinally hasfinally loopends loopends isempty loopends loopends hasfinally unwindblock gettype getfinally unwindblock unwindblock getlineno unwindblock addchildtoback unwindblock returnnode returnexpr returnnode getfirstchild replacecurrent unwindblock returnexpr unwindblock addchildtoback returnnode expr_result returnexpr unwindblock addchildtofront returnnode return_result unwindblock addchildtoback returnnode transformcompilationunit_r transformcompilationunit_r siblingloop jumpstatement getjumpstatement jumpstatement codebug irfactory codebug jumpstatement gettype addbeforecurrent trynode jsrfinally jsrfinally trynode getfinally addbeforecurrent jsrfinally jumpstatement jumpstatement getcontinue settype visitcall visitnew getfirstchild createassignment gettype codebug getnext haschildren getfirstchild removechild settype expr_void getlineno addchildtoback replacecurrent gettype functionnode requiresactivation namesource namesource namesource getfirstchild namesource gettype codebug namesource getstring hasparamorvar settype settype namesource settype replacecurrent codebug transformcompilationunit_r protected void visit new node node script or fn node tree visitnew scriptorfnnode protected void visit call node node script or fn node tree visitcall scriptorfnnode private static node add before current node parent node previous node current node to add if previous null if current parent get first child kit code bug parent add child to front to add else if current previous get next kit code bug parent add child after to add previous return to add addbeforecurrent toadd getfirstchild codebug addchildtofront toadd getnext codebug addchildafter toadd toadd private static node replace current node parent node previous node current node replacement if previous null if current parent get first child kit code bug parent replace child current replacement else if previous next current check cached prev next current is necessary due to possible tree mutations parent replace child after previous replacement else parent replace child current replacement return replacement replacecurrent getfirstchild codebug replacechild cachedprev replacechildafter replacechild public static double pub double representation 0 2134 public double double value return pub double representation pub_double_representation doublevalue pub_double_representation public int to number return pub number representation tonumber pub_number_representation override boolean value public boolean boolean value return pub boolean representation booleanvalue booleanvalue pub_boolean_representation override to string public string to string return pub string representation tostring tostring pub_string_representation data type class instance public static js object static getjs object return pub static jsobject datatypeclass jsobject staticgetjsobject pub_static_jsobject public js object getjs object return pub jsobject jsobject getjsobject pub_jsobject return pub jsobject public static void static setjs object js object jso pub static jsobject jso pub_jsobject staticsetjsobject jsobject pub_static_jsobject pub static jsobject jso public void setjs object js object jso pub jsobject jso pub_static_jsobject setjsobject jsobject pub_jsobject public js object createjs object array int length pub jsobject array new js object length return pub jsobject array jsobject createjsobjectarray pub_jsobject_array jsobject pub_jsobject_array public static js object static createjs object array int length pub static jsobject array new js object length return pub static jsobject array jsobject staticcreatejsobjectarray pub_static_jsobject_array jsobject pub_static_jsobject_array private protection domain domain loader class loader parent protection domain domain super parent null parent get system class loader this domain domain protectiondomain classloader protectiondomain getsystemclassloader public class define class string name byte data return super define class name data 0 data length domain defineclass defineclass public void link class class cl resolve class cl linkclass resolveclass the moment of constructor invocation context permissions protection domain static domain context access controller get context if static domain null statispermissions static domain get permissions set read only contextpermissions protectiondomain staticdomain _context accesscontroller getcontext staticdomain _statispermissions staticdomain getpermissions setreadonly public void add permission permission throw new runtime exception not implemented runtimeexception public boolean implies permission permission if statispermissions null if statispermissions implies permission return false try context check permission permission return true catch access control exception ex return false _statispermissions _statispermissions _context checkpermission accesscontrolexception public enumeration elements return new enumeration public boolean has more elements return false public object next element return null hasmoreelements nextelement return new enumeration public boolean has more elements return false hasmoreelements return new enumeration public boolean has more elements return false public object next element return null hasmoreelements nextelement public string to string string buffer sb new string buffer sb append get class get name sb append sb append integer to hex string system identity hash code this sb append context sb append context sb append static permitions sb append statispermissions sb append return sb to string tostring stringbuffer stringbuffer getclass getname tohexstring identityhashcode _context static_permitions _statispermissions tostring public java policy security to trigger error on jdk 1 1 with lazy load new code source null java security cert certificate null javapolicysecurity codesource protected void call process file secure final context cx final scriptable scope final string filename access controller do privileged new privileged action public object run url url get url obj filename protection domain static domain get url domain url main process file secure cx scope url to external form static domain return null callprocessfilesecure accesscontroller doprivileged privilegedaction geturlobj protectiondomain staticdomain geturldomain processfilesecure toexternalform staticdomain access controller do privileged new privileged action public object run url url get url obj filename protection domain static domain get url domain url main process file secure cx scope url to external form static domain return null accesscontroller doprivileged privilegedaction geturlobj protectiondomain staticdomain geturldomain processfilesecure toexternalform staticdomain private url get url obj string url url url obj try url obj new url url catch malformedurl exception ex assume as main process file secure it is file need to build its url string cur dir system get property user dir cur dir cur dir replace if cur dir ends with cur dir cur dir try url cur dirurl new url file cur dir url obj new url cur dirurl url catch malformedurl exception ex2 throw new runtime exception can not construct file url for url ex2 get message return url obj geturlobj urlobj urlobj malformedurlexception processfilesecure curdir getproperty curdir curdir curdir endswith curdir curdir curdirurl curdir urlobj curdirurl malformedurlexception runtimeexception getmessage urlobj private protection domain get url domain url url code source cs cs new code source url java security cert certificate null permission collection pc policy get policy get permissions cs return new protection domain cs pc protectiondomain geturldomain codesource codesource permissioncollection getpolicy getpermissions protectiondomain public generated class loader create class loader class loader parent loader object security domain protection domain domain protection domain security domain return new loader parent loader domain generatedclassloader createclassloader classloader parentloader securitydomain protectiondomain protectiondomain securitydomain parentloader public object get dynamic security domain object security domain protection domain static domain protection domain security domain return get dynamic domain static domain getdynamicsecuritydomain securitydomain protectiondomain staticdomain protectiondomain securitydomain getdynamicdomain staticdomain private protection domain get dynamic domain protection domain static domain context permissions p new context permissions static domain protection domain context domain new protection domain null p return context domain protectiondomain getdynamicdomain protectiondomain staticdomain contextpermissions contextpermissions staticdomain protectiondomain contextdomain protectiondomain contextdomain public object call with domain object security domain final context cx final callable callable final scriptable scope final scriptable this obj final object args protection domain static domain protection domain security domain there is no direct way in java to intersect permitions according stack context with additional domain the following implementation first constructs protection domain that allows actions only allowed by both static domain and current stack context and then constructs access controller for this dynamic domain if this is too slow alternative solution would be to generate class per domain with a proxy method to call to infect java stack another optimization in case of scripts coming from world domain that is having minimal default privileges is to construct one access control context based on protection domain with least possible privileges and simply call access controller do privileged with this untrusted context protection domain dynamic domain get dynamic domain static domain protection domain tmp dynamic domain access control context restricted new access control context tmp privileged action action new privileged action public object run return callable call cx scope this obj args return access controller do privileged action restricted callwithdomain securitydomain thisobj protectiondomain staticdomain protectiondomain securitydomain protectiondomain staticdomain accesscontroller accesscontrolcontext protectiondomain accesscontroller doprivileged protectiondomain dynamicdomain getdynamicdomain staticdomain protectiondomain dynamicdomain accesscontrolcontext accesscontrolcontext privilegedaction privilegedaction thisobj accesscontroller doprivileged privileged action action new privileged action public object run return callable call cx scope this obj args privilegedaction privilegedaction thisobj static void init scriptable scope boolean sealed native error obj new native error scriptable object put property obj name error scriptable object put property obj message scriptable object put property obj file name scriptable object put property obj line number new integer 0 obj export asjs class max prototype id scope sealed nativeerror nativeerror scriptableobject putproperty scriptableobject putproperty scriptableobject putproperty filename scriptableobject putproperty linenumber exportasjsclass max_prototype_id static native error make context cx scriptable scope id function object ctor obj object args scriptable proto scriptable ctor obj get prototype ctor obj native error obj new native error obj set prototype proto obj set parent scope scope if args length 1 scriptable object put property obj message script runtime to string args 0 if args length 2 scriptable object put property obj file name args 1 if args length 3 int line script runtime to int32 args 2 scriptable object put property obj line number new integer line return obj nativeerror idfunctionobject ctorobj ctorobj ctorobj nativeerror nativeerror setprototype setparentscope scriptableobject putproperty scriptruntime tostring scriptableobject putproperty filename scriptruntime toint32 scriptableobject putproperty linenumber public string get class name return error getclassname public string to string return js tostring this tostring js_tostring protected void init prototype id int id string s int arity switch id case id constructor arity 1 s constructor break case id tostring arity 0 s to string break case id tosource arity 0 s to source break default throw new illegal argument exception string value of id init prototype method error tag id s arity initprototypeid id_constructor id_tostring tostring id_tosource tosource illegalargumentexception valueof initprototypemethod error_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag error tag return super exec id call f cx scope this obj args int id f method id switch id case id constructor return make cx scope f args case id tostring return js tostring this obj case id tosource return js tosource cx scope this obj throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag error_tag execidcall thisobj methodid id_constructor id_tostring js_tostring thisobj id_tosource js_tosource thisobj illegalargumentexception valueof private static string js tostring scriptable this obj return get string this obj name get string this obj message js_tostring thisobj getstring thisobj getstring thisobj private static string js tosource context cx scriptable scope scriptable this obj emulation of spider monkey behavior object name scriptable object get property this obj name object message scriptable object get property this obj message object file name scriptable object get property this obj file name object line number scriptable object get property this obj line number string buffer sb new string buffer sb append new if name not found name undefined instance sb append script runtime to string name sb append if message not found file name not found line number not found if message not found message sb append script runtime uneval cx scope message if file name not found line number not found sb append if file name not found file name sb append script runtime uneval cx scope file name if line number not found int line script runtime to int32 line number if line 0 sb append sb append script runtime to string line sb append return sb to string js_tosource thisobj spidermonkey scriptableobject getproperty thisobj scriptableobject getproperty thisobj filename scriptableobject getproperty thisobj filename linenumber scriptableobject getproperty thisobj linenumber stringbuffer stringbuffer not_found scriptruntime tostring not_found filename not_found linenumber not_found not_found scriptruntime filename not_found linenumber not_found filename not_found filename scriptruntime filename linenumber not_found scriptruntime toint32 linenumber scriptruntime tostring tostring private static string get string scriptable obj string id object value scriptable object get property obj id if value not found return return script runtime to string value getstring scriptableobject getproperty not_found scriptruntime tostring protected int find prototype id string s int id string id map generated last update 2004 03 17 13 35 15 cet l0 id 0 string x null int c int s length s length if s length 8 c s char at 3 if c o x to source id id tosource else if c t x to string id id tostring else if s length 11 x constructor id id constructor if x null x s x equals s id 0 generated return id findprototypeid string_id_map s_length s_length charat tosource id_tosource tostring id_tostring s_length id_constructor private error reporter chained reporter private default error reporter errorreporter chainedreporter defaulterrorreporter static error reporter for eval error reporter reporter default error reporter r new default error reporter r for eval true r chained reporter reporter return r errorreporter foreval errorreporter defaulterrorreporter defaulterrorreporter foreval chainedreporter public void warning string message string sourceuri int line string line text int line offset if chained reporter null chained reporter warning message sourceuri line line text line offset else do nothing linetext lineoffset chainedreporter chainedreporter linetext lineoffset public void error string message string sourceuri int line string line text int line offset if for eval throw script runtime construct error syntax error message sourceuri line line text line offset if chained reporter null chained reporter error message sourceuri line line text line offset else throw runtime error message sourceuri line line text line offset linetext lineoffset foreval scriptruntime constructerror syntaxerror linetext lineoffset chainedreporter chainedreporter linetext lineoffset runtimeerror linetext lineoffset public evaluator exception runtime error string message string sourceuri int line string line text int line offset if chained reporter null return chained reporter runtime error message sourceuri line line text line offset else return new evaluator exception message sourceuri line line text line offset evaluatorexception runtimeerror linetext lineoffset chainedreporter chainedreporter runtimeerror linetext lineoffset evaluatorexception linetext lineoffset public class datatypes 004 extends live connect test public datatypes 004 super datatypes_004 liveconnecttest datatypes_004 public static void main string args datatypes 004 test new datatypes 004 test start datatypes_004 datatypes_004 public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class setuptestenvironment setuptestenvironment datatypeclass values passed from java script to java are converted as follows ul li li objects that are wrappers around java objects are unwrapped li other objects are wrapped with a js object li strings numbers and booleans are converted to string float and boolean objects respectively see netscape javascript js object public void execute test getjs var with eval null netscape javascript js object null getjs var with get member null netscape javascript js object null javascript jsobject jsobject executetest getjsvarwitheval jsobject getjsvarwithgetmember jsobject use js object eval to create a java script variable of a java script type get the value of the variable using js object get member and js object eval the type and value of the object returned by get member and eval should be the same add the testcase param right expr right hand side to the java script assignment expression param class name string representation of expected type of the result param e value expected value of the result public void getjs var with eval string right expr string class name string value string var name js var object result class expected class null try expected class class for name class name create the variable in the java script context global eval var var name right expr get the value of var name from the java script context result global eval var name system out println result is result catch exception e system err println setjs var with eval threw e to string with arguments right expr expected class get name value to string e print stack trace exception e to string result new object try add test case global eval var var name right expr result global eval var name result null true result null exception catch exception e file exception e to string jsobject javascript javascript jsobject getmember jsobject getmember rightexpr javascript classname evalue getjsvarwitheval rightexpr classname varname jsvar expectedclass expectedclass forname classname javascript varname rightexpr varname javascript varname setjsvarwitheval tostring rightexpr expectedclass getname tostring printstacktrace tostring addtestcase varname rightexpr varname tostring public void getjs var with get member string right expr string class name string value string var name js var object result class expected class null try expected class class for name class name create the variable in the java script context global eval var var name right expr get the value of var name from the java script context result global get member var name catch exception e system err println setjs var with get member threw e to string with arguments right expr expected class get name value to string e print stack trace exception e to string result new object try add test case global eval var var name right expr result global get member var name result null true result null exception catch exception e file exception e to string getjsvarwithgetmember rightexpr classname varname jsvar expectedclass expectedclass forname classname javascript varname rightexpr varname javascript getmember varname setjsvarwithgetmember tostring rightexpr expectedclass getname tostring printstacktrace tostring addtestcase varname rightexpr getmember varname tostring public rhino drv string args super args set suffix js rhinodrv setsuffix public static void main string args rhino drv d new rhino drv args d start rhinodrv rhinodrv public boolean process options int length args length if args 0 starts with xxx need to verify that we at least get valid d and h options for int i 0 i args length i if args i equals t string tinderbox args i if tinderbox equals true tinderbox equals 1 test driver tinderbox true else test driver tinderbox false if args i equals d p d this test directory args i ends with file separator new file args i new file args i file separator p d this test directory if this test directory is directory system err println error this test directory get absolute path is not a test directory return false else continue if args i equals s p s files new string 20 for int j i k 0 j args length j if args j starts with break files k args j if args i equals h p h this helper functions new file args i if this helper functions is file system err println error this helper functions get absolute path file not found return false if args i equals o p o output directory new file args i file separator if output directory exists output directory is directory system err println error output directory get absolute path is not a directory return false if args i equals p opt level integer parse int args i if args i equals db debug level integer parse int args i opt level 0 if args i equals e executable args i return true else switch args length case 0 system err println error specify location of java script tests return false case 1 system err println error specify location of java script helper functions file return false case 2 this test directory args 0 ends with file separator new file args 0 new file args 0 file separator this helper functions new file args 1 if this test directory is directory system err println error this test directory get absolute path is not a directory return false if this helper functions is file system err println error this helper functions get absolute path file not found return false return true default system err println could not understand arguments return false processoptions startswith __tinderbox __tinderbox __tinderbox testdriver testdriver test_directory endswith test_directory test_directory isdirectory test_directory getabsolutepath test_directory startswith helper_functions helper_functions isfile helper_functions getabsolutepath output_directory output_directory output_directory isdirectory output_directory getabsolutepath opt_level parseint debug_level parseint opt_level javascript javascript helper_functions test_directory endswith helper_functions test_directory isdirectory test_directory getabsolutepath helper_functions isfile helper_functions getabsolutepath for each file in each suite create a new rhino env public synchronized void execute suite test suite suite rhino env context test file file for int i 0 i suite size i synchronized suite file test file suite element at i context new rhino env file suite this context run test write file result file suite output directory write case results file suite output directory context close context null if file passed suite passed false write suite result suite output directory write suite summary suite output directory rhinoenv executesuite testsuite rhinoenv testfile testfile elementat rhinoenv runtest writefileresult output_directory writecaseresults output_directory writesuiteresult output_directory writesuitesummary output_directory create an exception with the specified detail message errors internal to the java script engine will simply throw a runtime exception param source name the name of the source reponsible for the error param line number the line number of the source param column number the column number of the source may be zero if unknown param line source the source of the line containing the error may be null if unknown ecma error string error name string error message string source name int line number string line source int column number record error origin source name line number line source column number this error name error name this error message error message javascript runtimeexception sourcename linenumber columnnumber columnnumber linesource ecmaerror errorname errormessage sourcename linenumber linesource columnnumber recorderrororigin sourcename linenumber linesource columnnumber errorname errorname errormessage errormessage deprecated ecma error error instances should not be constructed explicitly since they are generated by the engine public ecma error scriptable native error string source name int line number int column number string line source this internal error script runtime to string native error source name line number line source column number ecmaerror ecmaerror nativeerror sourcename linenumber columnnumber linesource internalerror scriptruntime tostring nativeerror sourcename linenumber linesource columnnumber public string details return error name error message errorname errormessage gets the name of the error ecma edition 3 defines the following errors eval error range error reference error syntax error type error and uri error additional error names may be added in the future see ecma edition 3 15 11 7 9 return the name of the error public string get name return error name evalerror rangeerror referenceerror syntaxerror typeerror urierror getname errorname gets the message corresponding to the error see ecma edition 3 15 11 7 10 return an implemenation defined string describing the error public string get error message return error message geterrormessage errormessage deprecated use link rhino exception source name from the super class public string get source name return source name rhinoexception sourcename getsourcename sourcename deprecated use link rhino exception line number from the super class public int get line number return line number rhinoexception linenumber getlinenumber linenumber deprecated use link rhino exception column number from the super class public int get column number return column number rhinoexception columnnumber getcolumnnumber columnnumber deprecated use link rhino exception line source from the super class public string get line source return line source rhinoexception linesource getlinesource linesource deprecated always returns b null b public scriptable get error object return null geterrorobject public abstract class ref implements serializable public boolean has context cx return true public abstract object get context cx public abstract object get context cx public abstract object set context cx object value public abstract object set context cx object value public boolean delete context cx return false create a new live connect env public live connect env test file f test suite s live connect drv d this file f this suite s this driver d this temp log name js get random file name tmp liveconnectenv liveconnectenv testfile testsuite liveconnectdrv temp_log_name getrandomfilename called by the driver to execute the test program public synchronized void run test try create context file start time driver get current time execute test file file end time driver get current time if task get exit value 0 system out println abmormal program termination exit value task get exit value if file name ends with n js file passed true else file exception process exit value task get exit value suite passed false file passed false parse result catch exception e suite passed false file passed false e print stack trace runtest createcontext starttime getcurrenttime executetestfile endtime getcurrenttime getexitvalue getexitvalue endswith getexitvalue parseresult printstacktrace instantiate a new java script shell passing the helper file and the name of the test class as arguments public object create context task new observed task driver executable driver helper functions get absolute path file file path temp log name this return object task javascript createcontext observedtask helper_functions getabsolutepath filepath temp_log_name start the shell process public object execute test file try task exec catch io exception e system err println e file exception e to string return null executetestfile ioexception tostring parse the results file for this test the which contains data in the following format pre classname live connect test passed true false length number of testcases in this test no passed number of testcases that passed no failed number of testcases that failed pre see com netscape javascript qa liveconnect live connect test write results to temp file public synchronized boolean parse result string line buffered reader buf new buffered reader new string reader new string task get input try do line buf read line system out println line while line null catch io exception e system err println exception reading process output e to string file exception e to string return false vector label null vector value null string t null try file reader fr new file reader driver output directory get absolute path temp log name buffered reader br new buffered reader fr string classname br read line boolean passed new boolean br read line boolean value int length new double br read line int value int no passed new double br read line int value int no failed new double br read line int value string bugnumber br read line if passed this file passed false this suite passed false this file total cases length this suite total cases length this file cases passed no passed this suite cases passed no passed this file cases failed no failed this suite cases failed no failed this file bugnumber bugnumber catch io exception e system err println e e print stack trace return true liveconnecttest no_passed no_failed liveconnecttest writeresultstotempfile parseresult bufferedreader bufferedreader stringreader getinput readline ioexception tostring tostring filereader filereader output_directory getabsolutepath temp_log_name bufferedreader bufferedreader readline readline booleanvalue readline intvalue no_passed readline intvalue no_failed readline intvalue readline totalcases totalcases casespassed no_passed casespassed no_passed casesfailed no_failed casesfailed no_failed ioexception printstacktrace public string get random file name return integer to string new double math random 100000 int value getrandomfilename tostring intvalue delete the temp log associated with this context public void close string templog driver output directory temp log name try file f new file templog if f exists f delete catch exception e e print stack trace return output_directory temp_log_name printstacktrace void p string s system out println s public static void init context cx scriptable scope boolean sealed native global obj new native global for int id 1 id last scope function id id string name int arity 1 switch id case id decodeuri name decodeuri break case id decodeuricomponent name decodeuri component break case id encodeuri name encodeuri break case id encodeuricomponent name encodeuri component break case id escape name escape break case id eval name eval break case id isfinite name is finite break case id isnan name is nan break case id isxmlname name isxml name break case id parsefloat name parse float break case id parseint name parse int arity 2 break case id unescape name unescape break case id uneval name uneval break default throw kit code bug id function object f new id function object obj ftag id name arity scope if sealed f seal object f export as scope property scriptable object define property scope nan script runtime na nobj scriptable object dontenum scriptable object define property scope infinity script runtime wrap number double positive infinity scriptable object dontenum scriptable object define property scope undefined undefined instance scriptable object dontenum string error methods kit semicolon split conversion error eval error range error reference error syntax error type error uri error internal error java exception each error constructor gets its own error object as a prototype with the name property set to the name of the error for int i 0 i error methods length i string name error methods i scriptable error proto script runtime new object cx scope error script runtime empty args error proto put name error proto name if sealed if error proto instanceof scriptable object scriptable object error proto seal object id function object ctor new id function object obj ftag id new commonerror name 1 scope ctor mark as constructor error proto if sealed ctor seal object ctor export as scope property nativeglobal nativeglobal last_scope_function_id id_decodeuri id_decodeuricomponent decodeuricomponent id_encodeuri id_encodeuricomponent encodeuricomponent id_escape id_eval id_isfinite isfinite id_isnan isnan id_isxmlname isxmlname id_parsefloat parsefloat id_parseint parseint id_unescape id_uneval codebug idfunctionobject idfunctionobject sealobject exportasscopeproperty scriptableobject defineproperty scriptruntime nanobj scriptableobject scriptableobject defineproperty scriptruntime wrapnumber positive_infinity scriptableobject scriptableobject defineproperty scriptableobject errormethods semicolonsplit conversionerror evalerror rangeerror referenceerror syntaxerror typeerror urierror internalerror javaexception errormethods errormethods errorproto scriptruntime newobject scriptruntime emptyargs errorproto errorproto errorproto scriptableobject scriptableobject errorproto sealobject idfunctionobject idfunctionobject id_new_commonerror markasconstructor errorproto sealobject exportasscopeproperty public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag ftag int method id f method id switch method id case id decodeuri case id decodeuricomponent string str script runtime to string args 0 return decode str method id id decodeuri case id encodeuri case id encodeuricomponent string str script runtime to string args 0 return encode str method id id encodeuri case id escape return js escape args case id eval return js eval cx scope args case id isfinite boolean result if args length 1 result false else double d script runtime to number args 0 result d d d double positive infinity d double negative infinity return script runtime wrap boolean result case id isnan the global method is nan as per ecma 262 15 1 2 6 boolean result if args length 1 result true else double d script runtime to number args 0 result d d return script runtime wrap boolean result case id isxmlname object name args length 0 undefined instance args 0 xml lib xml lib xml lib extract from scope scope return script runtime wrap boolean xml lib isxml name cx name case id parsefloat return js parsefloat args case id parseint return js parseint args case id unescape return js unescape args case id uneval object value args length 0 args 0 undefined instance return script runtime uneval cx scope value case id new commonerror the implementation of all the ecma error constructors syntax error type error etc return native error make cx scope f args throw f unknown execidcall idfunctionobject thisobj hastag methodid methodid methodid id_decodeuri id_decodeuricomponent scriptruntime tostring methodid id_decodeuri id_encodeuri id_encodeuricomponent scriptruntime tostring methodid id_encodeuri id_escape js_escape id_eval js_eval id_isfinite scriptruntime tonumber positive_infinity negative_infinity scriptruntime wrapboolean id_isnan isnan scriptruntime tonumber scriptruntime wrapboolean id_isxmlname xmllib xmllib xmllib extractfromscope scriptruntime wrapboolean xmllib isxmlname id_parsefloat js_parsefloat id_parseint js_parseint id_unescape js_unescape id_uneval scriptruntime id_new_commonerror syntaxerror typeerror nativeerror the global method parse int as per ecma 262 15 1 2 2 private object js parseint object args string s script runtime to string args 0 int radix script runtime to int32 args 1 int len s length if len 0 return script runtime na nobj boolean negative false int start 0 char c do c s char at start if character is whitespace c break start while start len if c negative c start final int no radix 1 if radix 0 radix no radix else if radix 2 radix 36 return script runtime na nobj else if radix 16 len start 1 s char at start 0 c s char at start 1 if c x c x start 2 if radix no radix radix 10 if len start 1 s char at start 0 c s char at start 1 if c x c x radix 16 start 2 else if 0 c c 9 radix 8 start double d script runtime string to number s start radix return script runtime wrap number negative d d parseint js_parseint scriptruntime tostring scriptruntime toint32 scriptruntime nanobj charat iswhitespace no_radix no_radix scriptruntime nanobj charat charat no_radix charat charat scriptruntime stringtonumber scriptruntime wrapnumber the global method parse float as per ecma 262 15 1 2 3 param cx unused param this obj unused param args the arguments to parse float ignoring args 1 param fun obj unused private object js parsefloat object args if args length 1 return script runtime na nobj string s script runtime to string args 0 int len s length int start 0 scan forward to skip whitespace char c for if start len return script runtime na nobj c s char at start if token stream isjs space c break start int i start if c c i if i len return script runtime na nobj c s char at i if c i check for infinity if i 8 len s region matches i infinity 0 8 double d if s char at start d double negative infinity else d double positive infinity return script runtime wrap number d return script runtime na nobj find the end of the legal bit int decimal 1 int exponent 1 for i len i switch s char at i case if decimal 1 only allow a single decimal point break decimal i continue case e case e if exponent 1 break exponent i continue case case only allow or after e or e if exponent i 1 break continue case 0 case 1 case 2 case 3 case 4 case 5 case 6 case 7 case 8 case 9 continue default break break s s substring start i try return double value of s catch number format exception ex return script runtime na nobj parsefloat thisobj parsefloat funobj js_parsefloat scriptruntime nanobj scriptruntime tostring scriptruntime nanobj charat tokenstream isjsspace scriptruntime nanobj charat regionmatches charat negative_infinity positive_infinity scriptruntime wrapnumber scriptruntime nanobj charat valueof numberformatexception scriptruntime nanobj the global method escape as per ecma 262 15 1 2 4 includes code for the mask argument supported by the c escape method which used to be part of the browser imbedding blame for the strange constant names should be directed there private object js escape object args final int url xalphas 1 url xpalphas 2 url path 4 string s script runtime to string args 0 int mask url xalphas url xpalphas url path if args length 1 the mask argument non ecma double d script runtime to number args 1 if d d mask int d d 0 mask url xalphas url xpalphas url path throw context report runtime error0 msg bad esc mask string buffer sb null for int k 0 l s length k l k int c s char at k if mask 0 c 0 c 9 c a c z c a c z c c c c c 0 mask url path c c if sb null sb append char c else if sb null sb new string buffer l 3 sb append s sb set length k int hex size if c 256 if c mask url xpalphas sb append continue sb append hex size 2 else sb append sb append u hex size 4 append hexadecimal form of c left padded with 0 for int shift hex size 1 4 shift 0 shift 4 int digit 0xf c shift int hc digit 10 0 digit a 10 digit sb append char hc return sb null s sb to string js_escape url_xalphas url_xpalphas url_path scriptruntime tostring url_xalphas url_xpalphas url_path scriptruntime tonumber url_xalphas url_xpalphas url_path reportruntimeerror0 stringbuffer charat _ url_path stringbuffer setlength hexsize url_xpalphas hexsize hexsize hexsize tostring the global unescape method as per ecma 262 15 1 2 5 private object js unescape object args string s script runtime to string args 0 int first escape pos s index of if first escape pos 0 int l s length char buf s to char array int destination first escape pos for int k first escape pos k l char c buf k k if c k l int end start if buf k u start k 1 end k 5 else start k end k 2 if end l int x 0 for int i start i end i x kit x digit to int buf i x if x 0 c char x k end buf destination c destination s new string buf 0 destination return s js_unescape scriptruntime tostring firstescapepos indexof firstescapepos tochararray firstescapepos firstescapepos xdigittoint private object js eval context cx scriptable scope object args string m script runtime get message1 msg cant call indirect eval throw native global construct error cx eval error m scope js_eval scriptruntime getmessage1 nativeglobal constructerror evalerror static boolean is eval function object function obj if function obj instanceof id function object id function object function id function object function obj if function has tag ftag function method id id eval return true return false isevalfunction functionobj functionobj idfunctionobject idfunctionobject idfunctionobject functionobj hastag methodid id_eval deprecated use link script runtime construct error string string instead public static ecma error construct error context cx string error string message scriptable scope return script runtime construct error error message scriptruntime constructerror ecmaerror constructerror scriptruntime constructerror deprecated use link script runtime construct error string string string int int string instead public static ecma error construct error context cx string error string message scriptable scope string source name int line number int column number string line source return script runtime construct error error message source name line number line source column number scriptruntime constructerror ecmaerror constructerror sourcename linenumber columnnumber linesource scriptruntime constructerror sourcename linenumber linesource columnnumber private static string encode string str boolean full uri byte utf8buf null string buffer sb null for int k 0 length str length k length k char c str char at k if encode unescaped c full uri if sb null sb append c else if sb null sb new string buffer length 3 sb append str sb set length k utf8buf new byte 6 if 0xdc00 c c 0xdfff throw context report runtime error0 msg bad uri int v if c 0xd800 0xdbff c v c else k if k length throw context report runtime error0 msg bad uri char c2 str char at k if 0xdc00 c2 c2 0xdfff throw context report runtime error0 msg bad uri v c 0xd800 10 c2 0xdc00 0x10000 int l one ucs4 to utf8 char utf8buf v for int j 0 j l j int d 0xff utf8buf j sb append sb append to hex char d 4 sb append to hex char d 0xf return sb null str sb to string fulluri stringbuffer charat encodeunescaped fulluri stringbuffer setlength reportruntimeerror0 reportruntimeerror0 charat reportruntimeerror0 oneucs4toutf8char tohexchar tohexchar tostring private static char to hex char int i if i 4 0 kit code bug return char i 10 i 0 i 10 a tohexchar codebug private static int un hex char c if a c c f return c a 10 else if a c c f return c a 10 else if 0 c c 9 return c 0 else return 1 unhex private static int un hex char c1 char c2 int i1 un hex c1 int i2 un hex c2 if i1 0 i2 0 return i1 4 i2 return 1 unhex unhex unhex private static string decode string str boolean full uri char buf null int buf top 0 for int k 0 length str length k length char c str char at k if c if buf null buf buf top c k else if buf null decode always compress so result can not be bigger then str length buf new char length str get chars 0 k buf 0 buf top k int start k if k 3 length throw context report runtime error0 msg bad uri int b un hex str char at k 1 str char at k 2 if b 0 throw context report runtime error0 msg bad uri k 3 if b 0x80 0 c char b else decode utf 8 sequence into ucs4 char and encode it into utf 16 int utf8 tail ucs4 char min ucs4 char if b 0xc0 0x80 first utf 8 should be ouside 0x80 0xbf throw context report runtime error0 msg bad uri else if b 0x20 0 utf8 tail 1 ucs4 char b 0x1f min ucs4 char 0x80 else if b 0x10 0 utf8 tail 2 ucs4 char b 0x0f min ucs4 char 0x800 else if b 0x08 0 utf8 tail 3 ucs4 char b 0x07 min ucs4 char 0x10000 else if b 0x04 0 utf8 tail 4 ucs4 char b 0x03 min ucs4 char 0x200000 else if b 0x02 0 utf8 tail 5 ucs4 char b 0x01 min ucs4 char 0x4000000 else first utf 8 can not be 0xff or 0xfe throw context report runtime error0 msg bad uri if k 3 utf8 tail length throw context report runtime error0 msg bad uri for int j 0 j utf8 tail j if str char at k throw context report runtime error0 msg bad uri b un hex str char at k 1 str char at k 2 if b 0 b 0xc0 0x80 throw context report runtime error0 msg bad uri ucs4 char ucs4 char 6 b 0x3f k 3 check for overlongs and other should not present codes if ucs4 char min ucs4 char ucs4 char 0xfffe ucs4 char 0xffff ucs4 char 0xfffd if ucs4 char 0x10000 ucs4 char 0x10000 if ucs4 char 0xfffff throw context report runtime error0 msg bad uri char h char ucs4 char 10 0xd800 c char ucs4 char 0x3ff 0xdc00 buf buf top h else c char ucs4 char if full uri uri decode reserved index of c 0 for int x start x k x buf buf top str char at x else buf buf top c return buf null str new string buf 0 buf top fulluri buftop charat buftop getchars buftop reportruntimeerror0 unhex charat charat reportruntimeerror0 ucs4char utf8tail ucs4char minucs4char reportruntimeerror0 utf8tail ucs4char minucs4char utf8tail ucs4char minucs4char utf8tail ucs4char minucs4char utf8tail ucs4char minucs4char utf8tail ucs4char minucs4char reportruntimeerror0 utf8tail reportruntimeerror0 utf8tail charat reportruntimeerror0 unhex charat charat reportruntimeerror0 ucs4char ucs4char ucs4char minucs4char ucs4char ucs4char ucs4char ucs4char ucs4char ucs4char reportruntimeerror0 ucs4char ucs4char buftop ucs4char fulluri uri_decode_reserved indexof buftop charat buftop buftop private static boolean encode unescaped char c boolean full uri if a c c z a c c z 0 c c 9 return true if index of c 0 return true if full uri return uri decode reserved index of c 0 return false encodeunescaped fulluri _ indexof fulluri uri_decode_reserved indexof private static int one ucs4 to utf8 char byte utf8 buffer int ucs4 char int utf8 length 1 js assert ucs4 char 0x7fffffff if ucs4 char 0x7f 0 utf8 buffer 0 byte ucs4 char else int i int a ucs4 char 11 utf8 length 2 while a 0 a 5 utf8 length i utf8 length while i 0 utf8 buffer i byte ucs4 char 0x3f 0x80 ucs4 char 6 utf8 buffer 0 byte 0x100 1 8 utf8 length ucs4 char return utf8 length oneucs4toutf8char utf8buffer ucs4char utf8length js_assert ucs4char ucs4char utf8buffer ucs4char ucs4char utf8length utf8length utf8length utf8buffer ucs4char ucs4char utf8buffer utf8length ucs4char utf8length public interface listener notify about newly created link context object public void context created context cx contextcreated notify that the specified link context instance is no longer associated with the current thread get global context factory see has explicit global see init global context factory public static context factory get global return global contextfactory hasexplicitglobal initglobal contextfactory contextfactory getglobal check if global factory was set return true to indicate that link init global context factory was already called and false to indicate that the global factory was not explicitly set see get global see init global context factory public static boolean has explicit global return has custom global initglobal contextfactory getglobal initglobal contextfactory hasexplicitglobal hascustomglobal set global context factory the method can only be called once see get global see has explicit global public static void init global context factory factory if factory null throw new illegal argument exception if has custom global throw new illegal state exception has custom global true global factory contextfactory getglobal hasexplicitglobal initglobal contextfactory illegalargumentexception hascustomglobal illegalstateexception hascustomglobal create new link context instance to be associated with the current thread this is a callback method used by rhino to create link context instance when it is necessary to associate one with the current execution thread tt make context tt is allowed to call link context seal object on the result to prevent link context changes by hostile scripts or applets protected context make context return new context makecontext makecontext implementation of link context has feature int feature index this can be used to customize link context without introducing additional subclasses protected boolean has feature context cx int feature index int version switch feature index case context feature non ecma get year during the great date rewrite of 1 3 we tried to track the evolving ecma standard which then had a definition of get year which always subtracted 1900 which we implemented not realizing that it was incompatible with the old behavior now rather than thrash the behavior yet again we ve decided to leave it with the 1900 behavior and point people to the get full year method but we try to protect existing scripts that have specified a version version cx get language version return version context version 1 0 version context version 1 1 version context version 1 2 case context feature member expr as function name return false case context feature reserved keyword as identifier return false case context feature to string as source version cx get language version return version context version 1 2 case context feature parent proto proprties return true case context feature e4x version cx get language version return version context version default version context version 1 6 case context feature dynamic scope return false case context feature strict vars return false case context feature strict eval return false it is a bug to call the method with unknown feature index throw new illegal argument exception string value of feature index hasfeature featureindex hasfeature featureindex featureindex feature_non_ecma_get_year getyear getfullyear getlanguageversion version_1_0 version_1_1 version_1_2 feature_member_expr_as_function_name feature_reserved_keyword_as_identifier feature_to_string_as_source getlanguageversion version_1_2 feature_parent_proto_proprties feature_e4x getlanguageversion version_default version_1_6 feature_dynamic_scope feature_strict_vars feature_strict_eval featureindex illegalargumentexception valueof featureindex create class loader for generated classes this method creates an instance of the default implementation of link generated class loader rhino uses this interface to load generated jvm classes when no link security controller is installed application can override the method to provide custom class loading protected generated class loader create class loader class loader parent return new defining class loader parent generatedclassloader securitycontroller generatedclassloader createclassloader classloader definingclassloader get class loader to use when searching for java classes unless it was explicitly initialized with link init application class loader class loader the method returns null to indicate that thread get context class loader should be used public final class loader get application class loader return application class loader classloader initapplicationclassloader classloader getcontextclassloader classloader getapplicationclassloader applicationclassloader set explicit class loader to use when searching for java classes see get application class loader public final void init application class loader class loader loader if loader null throw new illegal argument exception loader is null if kit test if can load rhino classes loader throw new illegal argument exception loader can not resolve rhino classes if this application class loader null throw new illegal state exception application class loader can only be set once check not sealed this application class loader loader getapplicationclassloader initapplicationclassloader classloader illegalargumentexception testifcanloadrhinoclasses illegalargumentexception applicationclassloader illegalstateexception applicationclassloader checknotsealed applicationclassloader execute top call to script or function when the runtime is about to execute a script or function that will create the first stack frame with scriptable code it calls this method to perform the real call in this way execution of any script happens inside this function protected object do top call callable callable context cx scriptable scope scriptable this obj object args return callable call cx scope this obj args dotopcall thisobj thisobj implementation of link context observe instruction count int instruction count this can be used to customize link context without introducing additional subclasses protected void observe instruction count context cx int instruction count observeinstructioncount instructioncount observeinstructioncount instructioncount protected void on context created context cx object listeners this listeners for int i 0 i listener l listener kit get listener listeners i if l null break l context created cx oncontextcreated getlistener contextcreated protected void on context released context cx object listeners this listeners for int i 0 i listener l listener kit get listener listeners i if l null break l context released cx oncontextreleased getlistener contextreleased public final void add listener listener listener check not sealed synchronized listeners lock if disabled listening throw new illegal state exception listeners kit add listener listeners listener addlistener checknotsealed listenerslock disabledlistening illegalstateexception addlistener public final void remove listener listener listener check not sealed synchronized listeners lock if disabled listening throw new illegal state exception listeners kit remove listener listeners listener removelistener checknotsealed listenerslock disabledlistening illegalstateexception removelistener the method is used only to imlement context disable static context listening final void disable context listening check not sealed synchronized listeners lock disabled listening true listeners null disablestaticcontextlistening disablecontextlistening checknotsealed listenerslock disabledlistening checks if this is a sealed context factory see seal public final boolean is sealed return sealed contextfactory issealed seal this context factory so any attempt to modify it like to add or remove its listeners will throw an exception see is sealed public final void seal check not sealed sealed true contextfactory issealed checknotsealed protected final void check not sealed if sealed throw new illegal state exception checknotsealed illegalstateexception call link context action run context cx using the link context instance associated with the current thread if no context is associated with the thread then link make context will be called to construct new context instance the instance will be temporary associated with the thread during call to link context action run context see context factory call context action see context call context factory factory callable callable scriptable scope scriptable this obj object args public final object call context action action return context call this action contextaction makecontext contextaction contextfactory contextaction contextfactory thisobj contextaction same as link context enter with the difference that if a new context needs to be created then this context factory is used to create it instead of the global context factory return a context associated with the current thread public final context enter return enter null same as link context enter context with the difference that if a new context needs to be created then this context factory is used to create it instead of the global context factory return a context associated with the current thread public final context enter context cx return context enter cx this same as link context exit although if you used link enter or link enter context methods on this object you should use this exit method instead of the static one in link context public final void exit context exit this create a new ref env public ref env test file f test suite s ref drv d this file f this suite s this driver d refenv refenv testfile testsuite refdrv called by the driver to execute the test program public void run test driver p file name try file start time driver get current time create context execute test file file end time driver get current time if task get exit value 0 if file name ends with n js file passed true else suite passed false file passed false if parse result if file name ends with n js file passed true else suite passed false file passed false file exception new string task get error catch exception e suite passed false file passed false file exception unknown process exception file exception new string task get error exit value task get exit value n threw exception e runtest starttime getcurrenttime createcontext executetestfile endtime getcurrenttime getexitvalue endswith parseresult endswith geterror geterror getexitvalue nthrew instantiate a new java script shell passing the test file as an argument public object create context if driver code coverage string command coverage save merge data save merge text data driver executable f driver helper functions get absolute path f file file path system out println command is command task new observed task command this else task new observed task driver executable f driver helper functions get absolute path f file file path this return object task javascript testfile createcontext code_coverage savemergedata savemergetextdata helper_functions getabsolutepath filepath observedtask observedtask helper_functions getabsolutepath filepath start the shell process public object execute test file try task exec catch io exception e driver p e to string file exception e to string e print stack trace return null executetestfile ioexception tostring tostring printstacktrace parse the standard output of the process and try to create new test case objects public boolean parse result string line int i j buffered reader br new buffered reader new string reader new string task get input try do line br read line driver p line if line null driver p terror no lines to read return false while line equals size tag if line br read line null return false file total cases integer value of line int value if line br read line null driver p terror no lines after size tag return false catch number format exception nfe driver p terror no integer after size tag return false catch io exception e driver p exception reading process output e to string file exception e to string return false for i 0 i file total cases i string values new string tags length try for j 0 j tags length j values j null if line starts with tags j driver p line didn t start with tags j line return false while line br read line null line starts with start tag values j values j null line values j n line if values j null values j if line null i file total cases 1 driver p line null and i file total cases 1 return false catch io exception e driver p exception reading process output e file exception e to string return false test case rt new test case values 0 values 1 values 4 values 2 values 3 values 5 file bugnumber values 6 file case vector add element rt if rt passed equals false if file name ends with n js this file passed true else this file passed false this suite passed false if file total cases 0 if file name ends with n js this file passed true else this file reason file contains no testcases this file reason this file passed false this suite passed false return true testcase parseresult bufferedreader bufferedreader stringreader getinput readline sizetag readline totalcases valueof intvalue readline sizetag numberformatexception sizetag ioexception tostring tostring totalcases startswith readline startswith starttag totalcases totalcases ioexception tostring testcase testcase casevector addelement endswith totalcases endswith method required by test environment this implemenation does nothing public void close return testenvironment private xml name string uri string local name this uri uri this local name local name xmlname localname localname localname static xml name form star return new xml name null xmlname formstar xmlname static xml name form property string uri string local name return new xml name uri local name xmlname formproperty localname xmlname localname void initxml object xml object impl xml object if xml object null throw new illegal argument exception if this xml object null throw new illegal state exception this xml object xml object initxmlobject xmlobjectimpl xmlobject xmlobject illegalargumentexception xmlobject illegalstateexception xmlobject xmlobject string uri return uri string local name return local name localname localname boolean is attribute name return is attribute name isattributename isattributename void set attribute name if is attribute name throw new illegal state exception is attribute name true setattributename isattributename illegalstateexception isattributename boolean is descendants return is descendants isdescendants isdescendants void set is descendants if is descendants throw new illegal state exception is descendants true setisdescendants isdescendants illegalstateexception isdescendants public boolean has context cx if xml object null return false return xml object hasxml property this xmlobject xmlobject hasxmlproperty public object get context cx if xml object null throw script runtime undef read error undefined instance to string return xml object getxml property this xmlobject scriptruntime undefreaderror tostring xmlobject getxmlproperty public object set context cx object value if xml object null throw script runtime undef write error undefined instance to string value assignment to descendants causes parse error on bad reference and this should not be called if is descendants throw kit code bug xml object putxml property this value return value xmlobject scriptruntime undefwriteerror tostring isdescendants codebug xmlobject putxmlproperty public boolean delete context cx if xml object null return true xml object deletexml property this return xml object hasxml property this xmlobject xmlobject deletexmlproperty xmlobject hasxmlproperty public string to string return qname local name string buffer buff new string buffer if is descendants buff append if is attribute name buff append if uri null buff append if local name equals return buff to string else buff append append uri append buff append append local name return buff to string tostring localname stringbuffer stringbuffer isdescendants isattributename localname tostring localname tostring public class datatypes 001 extends live connect test public datatypes 001 super datatypes_001 liveconnecttest datatypes_001 public static void main string args datatypes 001 test new datatypes 001 test start datatypes_001 datatypes_001 public void execute test do static field tests dt pub static boolean java lang boolean object new boolean data type class pub static final boolean do static field tests dt pub static final boolean java lang boolean object new boolean data type class pub static final boolean do static field tests dt pub static byte java lang double object new double data type class pub static final byte do static field tests dt pub static final byte java lang double object new double data type class pub static final byte do static field tests dt pub static short java lang double object new double data type class pub static final short do static field tests dt pub static final short java lang double object new double data type class pub static final short do static field tests dt pub static int java lang double object new double data type class pub static final int do static field tests dt pub static final int java lang double object new double data type class pub static final int do static field tests dt pub static long java lang double object new double data type class pub static final long do static field tests dt pub static final long java lang double object new double data type class pub static final long do static field tests dt pub static float java lang double object new double data type class pub static final float do static field tests dt pub static final float java lang double object new double data type class pub static final float do static field tests dt pub static double java lang double object new double data type class pub static final double do static field tests dt pub static final double java lang double object new double data type class pub static final double do static field tests dt pub static final char java lang double object new double data type class pub static final char do static field tests dt pub static char java lang double object new double data type class pub static final char do static field tests dt pub static string java lang string object new string data type class pub static final string do static field tests dt pub static final string java lang string object new string data type class pub static final string executetest dostaticfieldtests pub_static_boolean datatypeclass pub_static_final_boolean dostaticfieldtests pub_static_final_boolean datatypeclass pub_static_final_boolean dostaticfieldtests pub_static_byte datatypeclass pub_static_final_byte dostaticfieldtests pub_static_final_byte datatypeclass pub_static_final_byte dostaticfieldtests pub_static_short datatypeclass pub_static_final_short dostaticfieldtests pub_static_final_short datatypeclass pub_static_final_short dostaticfieldtests pub_static_int datatypeclass pub_static_final_int dostaticfieldtests pub_static_final_int datatypeclass pub_static_final_int dostaticfieldtests pub_static_long datatypeclass pub_static_final_long dostaticfieldtests pub_static_final_long datatypeclass pub_static_final_long dostaticfieldtests pub_static_float datatypeclass pub_static_final_float dostaticfieldtests pub_static_final_float datatypeclass pub_static_final_float dostaticfieldtests pub_static_double datatypeclass pub_static_final_double dostaticfieldtests pub_static_final_double datatypeclass pub_static_final_double dostaticfieldtests pub_static_final_char datatypeclass pub_static_final_char dostaticfieldtests pub_static_char datatypeclass pub_static_final_char dostaticfieldtests pub_static_string datatypeclass pub_static_final_string dostaticfieldtests pub_static_final_string datatypeclass pub_static_final_string public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class file bugnumber 301113 setuptestenvironment setuptestenvironment datatypeclass public void do static field tests string field string class name object value get public static field field class name value if field starts with dt pub static final set public static final field field class name value else set public static field field class name value set java script variable field class name value dostaticfieldtests classname getpublicstaticfield classname startswith pub_static_final setpublicstaticfinalfield classname setpublicstaticfield classname setjavascriptvariable classname set the value of a java script variable to a java value get the value of that variable public void get public static field string field string class name object value string description field string exception null object actual null string expect null string typeof null string expected type null check the class try global eval var myobject description actual global get member myobject typeof string global eval typeof myobject expect class for name class name get name if value instanceof number expected type number else if value instanceof boolean expected type boolean else expected type object catch class not found exception e catch exception e exception e to string might want to do all the interesting stuff here in a try catch block add test case global eval var myobject description global eval typeof myobject equals expected type true typeof equals expected type exception add test case description get class expect actual get class get name exception add test case description value to string true actual equals value exception add test case actual to string equals value to string true actual to string equals value to string exception javascript getpublicstaticfield classname expectedtype getmember forname classname getname expectedtype expectedtype expectedtype classnotfoundexception tostring addtestcase expectedtype expectedtype addtestcase getclass getclass getname addtestcase tostring addtestcase tostring tostring tostring tostring try to set the value of a public static field using js object set member which should succeed public void set public static field string field string class name object value string description field string exception null object before null object after null string expect null object new value class name equals java lang double new double 0 class name equals java lang boolean new boolean false object new string new value try before global eval description need to quote strings if class name equals java lang string global eval description new value to string else global eval description new value after global eval description expect class for name class name get name catch exception e exception e to string add test case global eval description new value to string after global eval description after get class get name expect after get class get name exception add test case after to string equals new value to string true after equals new value exception add test case after to string equals new value to string true after to string equals new value to string exception jsobject setmember setpublicstaticfield classname newvalue classname classname classname newvalue tostring newvalue forname classname getname tostring addtestcase newvalue tostring getclass getname getclass getname addtestcase tostring newvalue tostring newvalue addtestcase tostring newvalue tostring tostring newvalue tostring assign a value to a public static final java field the assignment should fail the value should not change but there should be no error message public void set public static final field string field string class name object value string description field string exception null object before null object after null string expect null object new value class name equals java lang double new double 0 class name equals java lang boolean new boolean false object new string new value try expect class for name class name get name catch exception e exception e to string before global eval description global eval description new value to string after global eval description check the class of the result which should be the same as expect add test case description get class expect after get class get name exception the value of the actual result should be the original value add test case description value to string true after equals value exception the string representation of the actual result should be the same as the string representation of the expected value add test case after to string equals value to string true after to string equals value to string exception get member field should return the same value before and after the assignment add test case before equals after true before equals after exception setpublicstaticfinalfield classname newvalue classname classname forname classname getname tostring newvalue tostring addtestcase getclass getclass getname addtestcase tostring addtestcase tostring tostring tostring tostring getmember addtestcase public void set java script variable string field string class name object value string description field string exception null object actual null string expect null object new value class name equals java lang double new double 0 class name equals java lang boolean new boolean false object new string new value try global eval var myobject description global set member myobject new value actual global get member myobject expect class for name class name get name catch exception e exception e to string add test case global eval var myobject description global set member myobject new value to string actual global get member myobject actual get class get name expect actual get class get name exception add test case description new value to string true actual equals new value exception add test case actual to string equals new value to string true actual to string equals new value to string exception setjavascriptvariable classname newvalue classname classname setmember newvalue getmember forname classname getname tostring addtestcase setmember newvalue tostring getmember getclass getname getclass getname addtestcase newvalue tostring newvalue addtestcase tostring newvalue tostring tostring newvalue tostring number node double number super token number this number number numbernode private static class string node extends node string node int type string str super type this str str stringnode stringnode public static class jump extends node public jump int type super type jump int type int lineno super type lineno jump int type node child super type child jump int type node child int lineno super type child lineno public final jump get jump statement if type token break type token continue kit code bug return jump node getjumpstatement codebug jumpnode public final void set jump statement jump jump statement if type token break type token continue kit code bug if jump statement null kit code bug if this jump node null kit code bug only once this jump node jump statement setjumpstatement jumpstatement codebug jumpstatement codebug jumpnode codebug jumpnode jumpstatement public final node get default if type token switch kit code bug return target2 getdefault codebug public final void set default node default target if type token switch kit code bug if default target type token target kit code bug if target2 null kit code bug only once target2 default target setdefault defaulttarget codebug defaulttarget codebug codebug defaulttarget public final node get finally if type token try kit code bug return target2 getfinally codebug public final void set finally node finally target if type token try kit code bug if finally target type token target kit code bug if target2 null kit code bug only once target2 finally target setfinally finallytarget codebug finallytarget codebug codebug finallytarget public final jump get loop if type token label kit code bug return jump node getloop codebug jumpnode public final void set loop jump loop if type token label kit code bug if loop null kit code bug if jump node null kit code bug only once jump node loop setloop codebug codebug jumpnode codebug jumpnode public final node get continue if type token loop kit code bug return target2 getcontinue codebug public final void set continue node continue target if type token loop kit code bug if continue target type token target kit code bug if target2 null kit code bug only once target2 continue target setcontinue continuetarget codebug continuetarget codebug codebug continuetarget public node int node type type node type nodetype nodetype public node int node type node child type node type first last child child next null nodetype nodetype public node int node type node left node right type node type first left last right left next right right next null nodetype nodetype public node int node type node left node mid node right type node type first left last right left next mid mid next right right next null nodetype nodetype public node int node type int line type node type lineno line nodetype nodetype public node int node type node child int line this node type child lineno line nodetype nodetype public node int node type node left node right int line this node type left right lineno line nodetype nodetype public node int node type node left node mid node right int line this node type left mid right lineno line nodetype nodetype public static node new number double number return new number node number newnumber numbernode public static node new string string str return new string node token string str newstring stringnode public static node new string int type string str return new string node type str newstring stringnode public int get type return type gettype public void set type int type this type type settype public boolean has children return first null haschildren public node get first child return first getfirstchild public node get last child return last getlastchild public node get next return next getnext public node get child before node child if child first return null node n first while n next child n n next if n null throw new runtime exception node is not a child return n getchildbefore runtimeexception public node get last sibling node n this while n next null n n next return n getlastsibling public void add child to front node child child next first first child if last null last child addchildtofront public void add child to back node child child next null if last null first last child return last next child last child addchildtoback public void add children to front node children node last sib children get last sibling last sib next first first children if last null last last sib addchildrentofront lastsib getlastsibling lastsib lastsib public void add children to back node children if last null last next children last children get last sibling if first null first children addchildrentoback getlastsibling add child before node public void add child before node new child node node if new child next null throw new runtime exception new child had siblings in add child before if first node new child next first first new child return node prev get child before node add child after new child prev addchildbefore newchild newchild runtimeexception newchild addchildbefore newchild newchild getchildbefore addchildafter newchild add child after node public void add child after node new child node node if new child next null throw new runtime exception new child had siblings in add child after new child next node next node next new child if last node last new child addchildafter newchild newchild runtimeexception newchild addchildafter newchild newchild newchild public void remove child node child node prev get child before child if prev null first first next else prev next child next if child last last prev child next null removechild getchildbefore public void replace child node child node new child new child next child next if child first first new child else node prev get child before child prev next new child if child last last new child child next null replacechild newchild newchild newchild getchildbefore newchild newchild public void replace child after node prev child node new child node child prev child next new child next child next prev child next new child if child last last new child child next null replacechildafter prevchild newchild prevchild newchild prevchild newchild newchild private static final string prop to string int prop type if token print trees if context print trees is false the compiler can remove all these strings switch prop type case function prop return function case local prop return local case local block prop return local block case regexp prop return regexp case casearray prop return casearray case targetblock prop return targetblock case variable prop return variable case isnumber prop return isnumber case directcall prop return directcall case specialcall prop return specialcall case skip indexes prop return skip indexes case object ids prop return object ids prop case incrdecr prop return incrdecr prop case catch scope prop return catch scope prop case label id prop return label id prop case member type prop return member type prop case name prop return name prop default kit code bug return null proptostring proptype printtrees printtrees proptype function_prop local_prop local_block_prop local_block regexp_prop casearray_prop targetblock_prop variable_prop isnumber_prop directcall_prop specialcall_prop skip_indexes_prop skip_indexes object_ids_prop object_ids_prop incrdecr_prop incrdecr_prop catch_scope_prop catch_scope_prop label_id_prop label_id_prop member_type_prop member_type_prop name_prop name_prop codebug private prop list item lookup property int prop type prop list item x prop list head while x null prop type x type x x next return x proplistitem lookupproperty proptype proplistitem proplisthead proptype private prop list item ensure property int prop type prop list item item lookup property prop type if item null item new prop list item item type prop type item next prop list head prop list head item return item proplistitem ensureproperty proptype proplistitem lookupproperty proptype proplistitem proptype proplisthead proplisthead public void remove prop int prop type prop list item x prop list head if x null prop list item prev null while x type prop type prev x x x next if x null return if prev null prop list head x next else prev next x next removeprop proptype proplistitem proplisthead proplistitem proptype proplisthead public object get prop int prop type prop list item item lookup property prop type if item null return null return item object value getprop proptype proplistitem lookupproperty proptype objectvalue public int get int prop int prop type int default value prop list item item lookup property prop type if item null return default value return item int value getintprop proptype defaultvalue proplistitem lookupproperty proptype defaultvalue intvalue public int get existing int prop int prop type prop list item item lookup property prop type if item null kit code bug return item int value getexistingintprop proptype proplistitem lookupproperty proptype codebug intvalue public void put prop int prop type object prop if prop null remove prop prop type else prop list item item ensure property prop type item object value prop putprop proptype removeprop proptype proplistitem ensureproperty proptype objectvalue public void put int prop int prop type int prop prop list item item ensure property prop type item int value prop putintprop proptype proplistitem ensureproperty proptype intvalue public int get lineno return lineno getlineno can only be called when tt get type token number tt public final double get double return number node this number gettype getdouble numbernode public final void set double double number number node this number number setdouble numbernode can only be called when node has string context public final string get string return string node this str getstring stringnode can only be called when node has string context public final void set string string s if s null kit code bug string node this str s setstring codebug stringnode public static node new target return new node token target newtarget public final int label id if type token target kit code bug return get int prop label id prop 1 labelid codebug getintprop label_id_prop public void label id int label id if type token target kit code bug put int prop label id prop label id labelid labelid codebug putintprop label_id_prop labelid public string to string if token print trees string buffer sb new string buffer to string new obj to int map sb return sb to string return string value of type tostring printtrees stringbuffer stringbuffer tostring objtointmap tostring valueof private void to string obj to int map print ids string buffer sb if token print trees sb append token name type if this instanceof string node sb append sb append get string else if this instanceof script or fn node script or fn node sof script or fn node this if this instanceof function node function node fn function node this sb append sb append fn get function name sb append source name sb append sof get source name sb append encoded source length sb append sof get encoded source end sof get encoded source start sb append base line sb append sof get base lineno sb append end line sb append sof get end lineno sb append else if this instanceof jump jump jump jump this if type token break type token continue sb append label append print id jump get jump statement print ids sb sb append else if type token try node catch node jump target node finally target jump get finally if catch node null sb append catch append print id catch node print ids sb sb append if finally target null sb append finally append print id finally target print ids sb sb append else if type token label type token loop type token switch sb append break append print id jump target print ids sb sb append if type token loop sb append continue append print id jump get continue print ids sb sb append else sb append target append print id jump target print ids sb sb append else if type token number sb append sb append get double else if type token target sb append append print id this print ids sb if lineno 1 sb append sb append lineno for prop list item x prop list head x null x x next int type x type sb append sb append prop to string type sb append string value switch type case targetblock prop can t add this as it recurses value target block property break case local block prop can t add this as it is dull value last local block break case isnumber prop switch x int value case both value both break case right value right break case left value left break default throw kit code bug break case specialcall prop switch x int value case specialcall eval value eval break case specialcall with value with break default non specialcall should not be stored throw kit code bug break default object obj x object value if obj null value obj to string else value string value of x int value break sb append value sb append tostring objtointmap printids stringbuffer printtrees stringnode getstring scriptorfnnode scriptorfnnode scriptorfnnode functionnode functionnode functionnode getfunctionname getsourcename getencodedsourceend getencodedsourcestart getbaselineno getendlineno appendprintid getjumpstatement printids catchnode finallytarget getfinally catchnode appendprintid catchnode printids finallytarget appendprintid finallytarget printids appendprintid printids appendprintid getcontinue printids appendprintid printids getdouble appendprintid printids proplistitem proplisthead proptostring targetblock_prop local_block_prop isnumber_prop intvalue codebug specialcall_prop intvalue specialcall_eval specialcall_with non_specialcall codebug objectvalue tostring valueof intvalue public string to string tree script or fn node tree top if token print trees string buffer sb new string buffer to string tree helper tree top this null 0 sb return sb to string return null tostringtree scriptorfnnode treetop printtrees stringbuffer stringbuffer tostringtreehelper treetop tostring private static void to string tree helper script or fn node tree top node n obj to int map print ids int level string buffer sb if token print trees if print ids null print ids new obj to int map generate print ids tree top print ids for int i 0 i level i sb append n to string print ids sb sb append n for node cursor n get first child cursor null cursor cursor get next if cursor get type token function int fn index cursor get existing int prop node function prop function node fn tree top get function node fn index to string tree helper fn fn null level 1 sb else to string tree helper tree top cursor print ids level 1 sb tostringtreehelper scriptorfnnode treetop objtointmap printids stringbuffer printtrees printids printids objtointmap generateprintids treetop printids tostring printids getfirstchild getnext gettype fnindex getexistingintprop function_prop functionnode treetop getfunctionnode fnindex tostringtreehelper tostringtreehelper treetop printids private static void generate print ids node n obj to int map map if token print trees map put n map size for node cursor n get first child cursor null cursor cursor get next generate print ids cursor map generateprintids objtointmap printtrees getfirstchild getnext generateprintids private static void append print id node n obj to int map print ids string buffer sb if token print trees if n null int id print ids get n 1 sb append if id 1 sb append id 1 else sb append not available appendprintid objtointmap printids stringbuffer printtrees printids not_available private string str public console write console text area text area string str this text area text area this str str consolewrite consoletextarea textarea textarea textarea public void run text area write str textarea private string buffer buffer public console writer console text area text area this text area text area buffer new string buffer stringbuffer consolewriter consoletextarea textarea textarea textarea stringbuffer public synchronized void write int ch buffer append char ch if ch n flush buffer flushbuffer public synchronized void write char data int off int len for int i off i len i buffer append data i if data i n flush buffer flushbuffer public synchronized void flush if buffer length 0 flush buffer flushbuffer public void close flush private void flush buffer string str buffer to string buffer set length 0 swing utilities invoke later new console write text area str flushbuffer tostring setlength swingutilities invokelater consolewrite textarea private int output mark 0 public void select int start int end request focus super select start end outputmark requestfocus public console text area string argv super history new java util vector console1 new console writer this console2 new console writer this out new print stream console1 err new print stream console2 piped output stream out pipe new piped output stream in pipe new print writer out pipe in new piped input stream try out pipe connect in catch io exception exc exc print stack trace get document add document listener this add key listener this set line wrap true set font new font monospaced 0 12 consoletextarea consolewriter consolewriter printstream printstream pipedoutputstream outpipe pipedoutputstream inpipe printwriter outpipe pipedinputstream outpipe ioexception printstacktrace getdocument adddocumentlistener addkeylistener setlinewrap setfont synchronized void return pressed document doc get document int len doc get length segment segment new segment try doc get text output mark len output mark segment catch javax swing text bad location exception ignored ignored print stack trace if segment count 0 history add element segment to string history index history size in pipe write segment array segment offset segment count append n output mark doc get length in pipe write n in pipe flush console1 flush returnpressed getdocument getlength gettext outputmark outputmark badlocationexception printstacktrace addelement tostring historyindex inpipe outputmark getlength inpipe inpipe public void eval string str in pipe write str in pipe write n in pipe flush console1 flush inpipe inpipe inpipe public void key pressed key event e int code e get key code if code key event vk back space code key event vk left if output mark get caret position e consume else if code key event vk home int caret pos get caret position if caret pos output mark e consume else if caret pos output mark if e is control down if e is shift down move caret position output mark else set caret position output mark e consume else if code key event vk enter return pressed e consume else if code key event vk up history index if history index 0 if history index history size history index history size 1 if history index 0 string str string history element at history index int len get document get length replace range str output mark len int caret pos output mark str length select caret pos caret pos else history index else history index e consume else if code key event vk down int caret pos output mark if history size 0 history index if history index 0 history index 0 int len get document get length if history index history size string str string history element at history index replace range str output mark len caret pos output mark str length else history index history size replace range output mark len select caret pos caret pos e consume keypressed keyevent getkeycode keyevent vk_back_space keyevent vk_left outputmark getcaretposition keyevent vk_home caretpos getcaretposition caretpos outputmark caretpos outputmark iscontroldown isshiftdown movecaretposition outputmark setcaretposition outputmark keyevent vk_enter returnpressed keyevent vk_up historyindex historyindex historyindex historyindex historyindex elementat historyindex getdocument getlength replacerange outputmark caretpos outputmark caretpos caretpos historyindex historyindex keyevent vk_down caretpos outputmark historyindex historyindex historyindex getdocument getlength historyindex elementat historyindex replacerange outputmark caretpos outputmark historyindex replacerange outputmark caretpos caretpos public void key typed key event e int key char e get key char if key char 0x8 key event vk back space if output mark get caret position e consume else if get caret position output mark set caret position output mark keytyped keyevent keychar getkeychar keychar keyevent vk_back_space outputmark getcaretposition getcaretposition outputmark setcaretposition outputmark public synchronized void key released key event e keyreleased keyevent public synchronized void write string str insert str output mark int len str length output mark len select output mark output mark outputmark outputmark outputmark outputmark public synchronized void insert update document event e int len e get length int off e get offset if output mark off output mark len insertupdate documentevent getlength getoffset outputmark outputmark public synchronized void remove update document event e int len e get length int off e get offset if output mark off if output mark off len output mark len else output mark off removeupdate documentevent getlength getoffset outputmark outputmark outputmark outputmark public synchronized void post updateui this attempts to cleanup the damage done by update component treeui request focus set caret get caret select output mark output mark postupdateui updatecomponenttreeui requestfocus setcaret getcaret outputmark outputmark public synchronized void changed update document event e changedupdate documentevent public input stream get in return in inputstream getin public print stream get out return out printstream getout public print stream get err return err printstream geterr public compiler environs error reporter default error reporter instance language version context version default generate debug info true use dynamic scope false reserved keyword as identifier false allow member expr as function name false xml available true optimization level 0 generating source true compilerenvirons errorreporter defaulterrorreporter languageversion version_default generatedebuginfo usedynamicscope reservedkeywordasidentifier allowmemberexprasfunctionname xmlavailable optimizationlevel generatingsource public void init from context context cx set error reporter cx get error reporter this language version cx get language version use dynamic scope cx compile functions with dynamic scope flag generate debug info cx is generating debug changed cx is generating debug reserved keyword as identifier cx has feature context feature reserved keyword as identifier allow member expr as function name cx has feature context feature member expr as function name xml available cx has feature context feature e4x optimization level cx get optimization level generating source cx is generating source activation names cx activation names initfromcontext seterrorreporter geterrorreporter languageversion getlanguageversion usedynamicscope compilefunctionswithdynamicscopeflag generatedebuginfo isgeneratingdebugchanged isgeneratingdebug reservedkeywordasidentifier hasfeature feature_reserved_keyword_as_identifier allowmemberexprasfunctionname hasfeature feature_member_expr_as_function_name xmlavailable hasfeature feature_e4x optimizationlevel getoptimizationlevel generatingsource isgeneratingsource activationnames activationnames public final error reporter get error reporter return error reporter errorreporter geterrorreporter errorreporter public void set error reporter error reporter error reporter if error reporter null throw new illegal argument exception this error reporter error reporter seterrorreporter errorreporter errorreporter errorreporter illegalargumentexception errorreporter errorreporter public final int get language version return language version getlanguageversion languageversion public void set language version int language version context check language version language version this language version language version setlanguageversion languageversion checklanguageversion languageversion languageversion languageversion public final boolean is generate debug info return generate debug info isgeneratedebuginfo generatedebuginfo public void set generate debug info boolean flag this generate debug info flag setgeneratedebuginfo generatedebuginfo public final boolean is use dynamic scope return use dynamic scope isusedynamicscope usedynamicscope public final boolean is reserved keyword as identifier return reserved keyword as identifier isreservedkeywordasidentifier reservedkeywordasidentifier public void set reserved keyword as identifier boolean flag reserved keyword as identifier flag setreservedkeywordasidentifier reservedkeywordasidentifier public final boolean is allow member expr as function name return allow member expr as function name isallowmemberexprasfunctionname allowmemberexprasfunctionname public void set allow member expr as function name boolean flag allow member expr as function name flag setallowmemberexprasfunctionname allowmemberexprasfunctionname public final boolean is xml available return xml available isxmlavailable xmlavailable public void set xml available boolean flag xml available flag setxmlavailable xmlavailable public final int get optimization level return optimization level getoptimizationlevel optimizationlevel public void set optimization level int level context check optimization level level this optimization level level setoptimizationlevel checkoptimizationlevel optimizationlevel public final boolean is generating source return generating source isgeneratingsource generatingsource specify whether or not source information should be generated p without source information evaluating the to string method on java script functions produces only native code for the body of the function note that code generated without source is not fully ecma conformant public void set generating source boolean generating source this generating source generating source tostring javascript setgeneratingsource generatingsource generatingsource generatingsource public class datatypes 015 extends live connect test public datatypes 015 super datatypes_015 liveconnecttest datatypes_015 public static void main string args datatypes 015 test new datatypes 015 test start datatypes_015 datatypes_015 public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class global eval var dt new dt setuptestenvironment setuptestenvironment datatypeclass public void execute test do array test dt static get object array true do array test dt pub static array object true do array test dt get object array true do array test dt pub array object false executetest doarraytest staticgetobjectarray doarraytest pub_static_array_object doarraytest getobjectarray doarraytest pub_array_object assign a java object array to a java script variable in the following ways ul li call a static method li get the value of a static field li call an instance method li get the value of an instance field param command the command to eval to get the object array public void do array test string command boolean should equal object array data type class pub static array object object js array int jsarray length try assign the array to a java script variable global eval var js array command get the js array object which should be the java array js array object global get member js array get the length of the array from java script jsarray length double global eval js array length int value iterate through js array in java script verify that the type and value of each object in the array is correct for int i 0 i jsarray length i verify that the array item is the same object as in the original array object item object global eval js array i add test case js array command global eval js array i equals array i should equal item equals array i catch exception e e print stack trace file exception e to string jsarray length 0 js array null verify that js array is the same as the original array add test case js array command js array global get member js array js array array should equal js array array exception javascript doarraytest shouldequal datatypeclass pub_static_array_object jsarray jsarray_length javascript jsarray jsarray jsarray getmember jsarray javascript jsarray_length jsarray intvalue jsarray javascript jsarray_length jsarray addtestcase jsarray jsarray shouldequal printstacktrace tostring jsarray_length jsarray jsarray addtestcase jsarray jsarray getmember jsarray jsarray shouldequal jsarray private special ref scriptable target int type string name this target target this type type this name name specialref static ref create special context cx object object string name scriptable target script runtime to object or null cx object if target null throw script runtime undef read error object name int type if name equals proto type special proto else if name equals parent type special parent else throw new illegal argument exception name if cx has feature context feature parent proto proprties clear special after checking for valid name type special none return new special ref target type name createspecial scriptruntime toobjectornull scriptruntime undefreaderror __proto__ special_proto __parent__ special_parent illegalargumentexception hasfeature feature_parent_proto_proprties special_none specialref public object get context cx switch type case special none return script runtime get object prop target name cx case special proto return target get prototype case special parent return target get parent scope default throw kit code bug special_none scriptruntime getobjectprop special_proto getprototype special_parent getparentscope codebug public object set context cx object value switch type case special none return script runtime set object prop target name value cx case special proto case special parent scriptable obj script runtime to object or null cx value if obj null check that obj does not contain on its prototype scope chain to prevent cycles scriptable search obj do if search target throw context report runtime error1 msg cyclic value name if type special proto search search get prototype else search search get parent scope while search null if type special proto target set prototype obj else target set parent scope obj return obj default throw kit code bug special_none scriptruntime setobjectprop special_proto special_parent scriptruntime toobjectornull reportruntimeerror1 special_proto getprototype getparentscope special_proto setprototype setparentscope codebug public boolean has context cx if type special none return script runtime has object elem target name cx return true special_none scriptruntime hasobjectelem public boolean delete context cx if type special none return script runtime delete object elem target name cx return false special_none scriptruntime deleteobjectelem private static final int function end token last token 1 string get encoded source return source to string 0 function_end last_token getencodedsource sourcetostring int get current offset return source top getcurrentoffset sourcetop int mark function start int function type int saved offset get current offset add token token function append char function type return saved offset markfunctionstart functiontype savedoffset getcurrentoffset addtoken functiontype savedoffset int mark function end int function start int offset get current offset append char function end return offset markfunctionend functionstart getcurrentoffset function_end void add token int token if 0 token token token last token throw new illegal argument exception append char token addtoken last_token illegalargumentexception void addeol int token if 0 token token token last token throw new illegal argument exception append char token append char token eol last_token illegalargumentexception void add name string str add token token name append string str addname addtoken appendstring void add string string str add token token string append string str addstring addtoken appendstring void add regexp string regexp string flags add token token regexp append string regexp flags addregexp addtoken appendstring void add number double n add token token number encode the number in the source stream save as number type char char char char char where type is d double s short j long we need to retain float vs integer type info to keep the behavior of liveconnect type guessing the same after decompilation liveconnect tries to present 1 0 to java as a float double opt this is no longer true we could compress the format this may not be the most space efficient encoding the chars created below may take up to 3 bytes in constant pool utf 8 encoding so a double could take up to 12 bytes long lbits long n if lbits n if it s floating point save as a double bit pattern 12 15 97 our scanner only returns double for f p lbits double double to long bits n append d append char lbits 48 append char lbits 32 append char lbits 16 append char lbits else we can ignore negative values bc they re already prefixed by neg if lbits 0 kit code bug will it fit in a char this gives a short encoding for integer values up to 2 16 if lbits character max value append s append char lbits else integral but won t fit in a char store as a long append j append char lbits 48 append char lbits 32 append char lbits 16 append char lbits addnumber addtoken doubletolongbits codebug max_value private void append string string str int l str length int length encoding size 1 if l 0x8000 length encoding size 2 int next top source top length encoding size l if next top source buffer length increase source capacity next top if l 0x8000 use 2 chars to encode strings exceeding 32k were the highest bit in the first char indicates presence of the next byte source buffer source top char 0x8000 l 16 source top source buffer source top char l source top str get chars 0 l source buffer source top source top next top appendstring lengthencodingsize lengthencodingsize nexttop sourcetop lengthencodingsize nexttop sourcebuffer increasesourcecapacity nexttop sourcebuffer sourcetop sourcetop sourcebuffer sourcetop sourcetop getchars sourcebuffer sourcetop sourcetop nexttop private void append char c if source top source buffer length increase source capacity source top 1 source buffer source top c source top sourcetop sourcebuffer increasesourcecapacity sourcetop sourcebuffer sourcetop sourcetop private void increase source capacity int minimal capacity call this only when capacity increase is must if minimal capacity source buffer length kit code bug int new capacity source buffer length 2 if new capacity minimal capacity new capacity minimal capacity char tmp new char new capacity system arraycopy source buffer 0 tmp 0 source top source buffer tmp increasesourcecapacity minimalcapacity minimalcapacity sourcebuffer codebug newcapacity sourcebuffer newcapacity minimalcapacity newcapacity minimalcapacity newcapacity sourcebuffer sourcetop sourcebuffer private string source to string int offset if offset 0 source top offset kit code bug return new string source buffer offset source top offset sourcetostring sourcetop codebug sourcebuffer sourcetop decompile the source information associated with this js function script back into a string for the most part this just means translating tokens back to their string representations there s a little bit of lookahead logic to decide the proper spacing indentation most of the work in mapping the original source to the prettyprinted decompiled version is done by the parser param source encoded source tree presentation param flags flags to select output format param properties indentation properties public static string decompile string source int flags uint map properties int length source length if length 0 return int indent properties get int initial indent prop 0 if indent 0 throw new illegal argument exception int indent gap properties get int indent gap prop 4 if indent gap 0 throw new illegal argument exception int case gap properties get int case gap prop 2 if case gap 0 throw new illegal argument exception string buffer result new string buffer boolean just function body 0 flags decompiler only body flag boolean to source 0 flags decompiler to source flag spew tokens in source for debugging as type number char if print source system err println length length for int i 0 i length i note that token to name will fail unless context print trees is true string tokenname null if token print names tokenname token name source char at i if tokenname null tokenname string pad tokenname length 7 t t t system err println tokenname pad int source char at i t script runtime escape string source substring i i 1 system err println int brace nesting 0 boolean after firsteol false int i 0 int top function type if source char at i token script i top function type 1 else top function type source char at i 1 if to source add an initial newline to exactly match js result append n for int j 0 j indent j result append else if top function type function node function expression result append while i length switch source char at i case token name case token regexp re wrapped in s in parser i print source string source i 1 false result continue case token string i print source string source i 1 true result continue case token number i print source number source i 1 result continue case token true result append true break case token false result append false break case token null result append null break case token this result append this break case token function i skip function type result append function break case function end do nothing break case token comma result append break case token lc brace nesting if token eol get next source length i indent indent gap result append break case token rc brace nesting don t print the closing rc if it closes the toplevel function and we re called from decompile function body if just function body brace nesting 0 break result append switch get next source length i case token eol case function end indent indent gap break case token while case token else indent indent gap result append break break case token lp result append break case token rp result append if token lc get next source length i result append break case token lb result append break case token rb result append break case token eol if to source break boolean new line true if after firsteol after firsteol true if just function body throw away just added function name and restore the original indent result set length 0 indent indent gap new line false if new line result append n add indent if any tokens remain less setback if next token is a label case or default if i 1 length int less 0 int next token source char at i 1 if next token token case next token token default less indent gap case gap else if next token token rc less indent gap elaborate check against label skip past a following inlined name and look for a colon else if next token token name int after name get source string end source i 2 if source char at after name token colon less indent gap for less indent less result append break case token dot result append break case token new result append new break case token delprop result append delete break case token if result append if break case token else result append else break case token for result append for break case token in result append in break case token with result append with break case token while result append while break case token do result append do break case token try result append try break case token catch result append catch break case token finally result append finally break case token throw result append throw break case token switch result append switch break case token break result append break if token name get next source length i result append break case token continue result append continue if token name get next source length i result append break case token case result append case break case token default result append default break case token return result append return if token semi get next source length i result append break case token var result append var break case token semi result append if token eol get next source length i separators in for uintmap getint initial_indent_prop illegalargumentexception indentgap getint indent_gap_prop indentgap illegalargumentexception casegap getint case_gap_prop casegap illegalargumentexception stringbuffer stringbuffer justfunctionbody only_body_flag tosource to_source_flag printsource tokentoname printtrees printnames charat charat scriptruntime escapestring bracenesting afterfirsteol topfunctiontype charat topfunctiontype topfunctiontype charat tosource topfunctiontype functionnode function_expression charat printsourcestring printsourcestring printsourcenumber function_end bracenesting getnext indentgap bracenesting decompilefunctionbody justfunctionbody bracenesting getnext function_end indentgap indentgap getnext tosource newline afterfirsteol afterfirsteol justfunctionbody setlength indentgap newline newline nexttoken charat nexttoken nexttoken indentgap casegap nexttoken indentgap nexttoken aftername getsourcestringend charat aftername indentgap getnext getnext getnext getnext private static int get next string source int length int i return i 1 length source char at i 1 token eof getnext charat private static int get source string end string source int offset return print source string source offset false null getsourcestringend printsourcestring private static int print source string string source int offset boolean as quoted string string buffer sb int length source char at offset offset if 0x8000 length 0 length 0x7fff length 16 source char at offset offset if sb null string str source substring offset offset length if as quoted string sb append str else sb append sb append script runtime escape string str sb append return offset length printsourcestring asquotedstring stringbuffer charat charat asquotedstring scriptruntime escapestring private static int print source number string source int offset string buffer sb double number 0 0 char type source char at offset offset if type s if sb null int ival source char at offset number ival offset else if type j type d if sb null long lbits lbits long source char at offset 48 lbits long source char at offset 1 32 lbits long source char at offset 2 16 lbits long source char at offset 3 if type j number lbits else number double long bits to double lbits offset 4 else bad source throw new runtime exception if sb null sb append script runtime number to string number 10 return offset printsourcenumber stringbuffer charat charat charat charat charat charat longbitstodouble runtimeexception scriptruntime numbertostring public static class class or null string class name try return class for name class name catch class not found exception ex catch security exception ex catch linkage error ex catch illegal argument exception e can be thrown if name has characters that a class name can not contain return null classornull classname forname classname classnotfoundexception securityexception linkageerror illegalargumentexception public static class class or null class loader loader string class name try return loader load class class name catch class not found exception ex catch security exception ex catch linkage error ex catch illegal argument exception e can be thrown if name has characters that a class name can not contain return null classornull classloader classname loadclass classname classnotfoundexception securityexception linkageerror illegalargumentexception static object new instance or null class cl try return cl new instance catch security exception x catch linkage error ex catch instantiation exception x catch illegal access exception x return null newinstanceornull newinstance securityexception linkageerror instantiationexception illegalaccessexception check that test class is accesible from the given loader static boolean test if can load rhino classes class loader loader class test class script runtime context factory class class x kit class or null loader test class get name if x test class the check covers the case when x null loader does not know about test class or the case when x null x test class loader loads a class unrelated to test class return false return true testclass testifcanloadrhinoclasses classloader testclass scriptruntime contextfactoryclass classornull testclass getname testclass testclass testclass testclass if init cause methods exists in throwable call tt ex init cause cause tt or otherwise do nothing return the tt ex tt argument public static runtime exception init cause runtime exception ex throwable cause if throwable initcause null object args cause try throwable initcause invoke ex args catch exception e ignore any exceptions return ex initcause initcause runtimeexception initcause runtimeexception throwable_initcause throwable_initcause split string into array of strings using semicolon as string terminator after the last string is required public static string semicolon split string s string array null for loop 2 times first to count semicolons and then to fill array int count 0 int cursor 0 for int next s index of cursor if next 0 break if array null array count s substring cursor next count cursor next 1 after the last semicolon if array null array size counting state check for required terminating if cursor s length throw new illegal argument exception array new string count else array filling state stop the loop break return array semicolonsplit indexof illegalargumentexception if character tt c tt is a hexadecimal digit return tt accumulator tt 16 plus corresponding number otherise return 1 public static int x digit to int int c int accumulator check use 0 9 a z a z if c 9 c 0 if 0 c break check else if c f if a c c a 10 break check else if c f if a c c a 10 break check return 1 return accumulator 4 c xdigittoint add i listener i to i bag i of listeners the function does not modify i bag i and return a new collection containing i listener i and all listeners from i bag i bag without listeners always represented as the null value p usage example pre private volatile object change listeners public void add my listener property change listener l synchronized this change listeners kit add listener change listeners l public void remove text listener property change listener l synchronized this change listeners kit remove listener change listeners l public void fire change event object old value object new value get immune local copy object listeners change listeners if listeners null property change event e new property change event this some property old value new value for int i 0 i object l kit get listener listeners i if l null break property change listener l property change e pre param listener listener to add to i bag i param bag current collection of listeners return a new bag containing all listeners from i bag i and i listener i see remove listener object bag object listener see get listener object bag int index public static object add listener object bag object listener if listener null throw new illegal argument exception if listener instanceof object throw new illegal argument exception if bag null bag listener else if bag instanceof object bag new object bag listener else object array object bag int l array length bag has at least 2 elements if it is array if l 2 throw new illegal argument exception object tmp new object l 1 system arraycopy array 0 tmp 0 l tmp l listener bag tmp return bag changelisteners addmylistener propertychangelistener changelisteners addlistener changelisteners removetextlistener propertychangelistener changelisteners removelistener changelisteners firechangeevent oldvalue newvalue changelisteners propertychangeevent propertychangeevent someproperty oldvalue newvalue getlistener propertychangelistener propertychange removelistener getlistener addlistener illegalargumentexception illegalargumentexception illegalargumentexception remove i listener i from i bag i of listeners the function does not modify i bag i and return a new collection containing all listeners from i bag i except i listener i if i bag i does not contain i listener i the function returns i bag i p for usage example see link add listener object bag object listener param listener listener to remove from i bag i param bag current collection of listeners return a new bag containing all listeners from i bag i except i listener i see add listener object bag object listener see get listener object bag int index public static object remove listener object bag object listener if listener null throw new illegal argument exception if listener instanceof object throw new illegal argument exception if bag listener bag null else if bag instanceof object object array object bag int l array length bag has at least 2 elements if it is array if l 2 throw new illegal argument exception if l 2 if array 1 listener bag array 0 else if array 0 listener bag array 1 else int i l do i if array i listener object tmp new object l 1 system arraycopy array 0 tmp 0 i system arraycopy array i 1 tmp i l i 1 bag tmp break while i 0 return bag addlistener addlistener getlistener removelistener illegalargumentexception illegalargumentexception illegalargumentexception get listener at i index i position in i bag i or null if i index i equals to number of listeners in i bag i p for usage example see link add listener object bag object listener param bag current collection of listeners param index index of the listener to access return listener at the given index or null see add listener object bag object listener see remove listener object bag object listener public static object get listener object bag int index if index 0 if bag null return null if bag instanceof object return bag object array object bag bag has at least 2 elements if it is array if array length 2 throw new illegal argument exception return array 0 else if index 1 if bag instanceof object if bag null throw new illegal argument exception return null object array object bag the array access will check for index on its own return array 1 else bag has to array object array object bag int l array length if l 2 throw new illegal argument exception if index l return null return array index addlistener addlistener removelistener getlistener illegalargumentexception illegalargumentexception illegalargumentexception static object init hash hashtable h object key object initial value synchronized h object current h get key if current null h put key initial value else initial value current return initial value inithash initialvalue initialvalue initialvalue initialvalue complex key object key1 object key2 this key1 key1 this key2 key2 complexkey public boolean equals object another obj if another obj instanceof complex key return false complex key another complex key another obj return key1 equals another key1 key2 equals another key2 anotherobj anotherobj complexkey complexkey complexkey anotherobj public int hash code if hash 0 hash key1 hash code key2 hash code return hash hashcode hashcode hashcode public static object make hash key from pair object key1 object key2 if key1 null throw new illegal argument exception if key2 null throw new illegal argument exception return new complex key key1 key2 makehashkeyfrompair illegalargumentexception illegalargumentexception complexkey public static string read reader reader r throws io exception char buffer new char 512 int cursor 0 for int n r read buffer cursor buffer length cursor if n 0 break cursor n if cursor buffer length char tmp new char buffer length 2 system arraycopy buffer 0 tmp 0 cursor buffer tmp return new string buffer 0 cursor readreader ioexception public static byte read stream input stream is int initial buffer capacity throws io exception if initial buffer capacity 0 throw new illegal argument exception bad initial buffer capacity initial buffer capacity byte buffer new byte initial buffer capacity int cursor 0 for int n is read buffer cursor buffer length cursor if n 0 break cursor n if cursor buffer length byte tmp new byte buffer length 2 system arraycopy buffer 0 tmp 0 cursor buffer tmp if cursor buffer length byte tmp new byte cursor system arraycopy buffer 0 tmp 0 cursor buffer tmp return buffer readstream inputstream initialbuffercapacity ioexception initialbuffercapacity illegalargumentexception initialbuffercapacity initialbuffercapacity initialbuffercapacity throws runtime exception to indicate failed assertion the function never returns and its return type is runtime exception only to be able to write tt throw kit code bug tt if plain tt kit code bug tt triggers unreachable code error public static runtime exception code bug throws runtime exception runtime exception ex new illegal state exception failed assertion print stack trace asap ex print stack trace system err throw ex runtimeexception runtimeexception codebug codebug runtimeexception codebug runtimeexception runtimeexception illegalstateexception printstacktrace public string jsobject jsobject public string ambiguous boolean arg return boolean object boolean_object public string ambiguous boolean arg return boolean public string ambiguous byte arg return byte public string ambiguous char arg return char public string ambiguous short arg return short public string ambiguous int arg return int public class datatypes 013 extends live connect test public datatypes 013 super datatypes_013 liveconnecttest datatypes_013 public static void main string args datatypes 013 test new datatypes 013 test start datatypes_013 datatypes_013 public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class global eval var dt new dt setuptestenvironment setuptestenvironment datatypeclass public void execute test do array test dt static get int array true do array test dt pub static array int true do array test dt get int array true do array test dt pub array int false executetest doarraytest staticgetintarray doarraytest pub_static_array_int doarraytest getintarray doarraytest pub_array_int assign a java byte array to a java script variable in the following ways ul li call a static method li get the value of a static field li call an instance method li get the value of an instance field param command the command to eval to get the byte array public void do array test string command boolean should equal int array data type class pub static array int int js array int jsarray length try assign the array to a java script variable global eval var js array command get the js array object which should be the java object js array int global get member js array get the length of the array from java script jsarray length double global eval js array length int value iterate through js array in java script verify that the type and value of each object in the array is correct for int i 0 i jsarray length i verify that the array item is the same object as in the original array double item double global eval js array i add test case js array command global eval js array i equals array i true item equals new double array i catch exception e e print stack trace file exception e to string jsarray length 0 js array null verify that js array is the same as the original array add test case js array command js array global get member js array js array array should equal true false js array array javascript doarraytest shouldequal datatypeclass pub_static_array_int jsarray jsarray_length javascript jsarray jsarray jsarray getmember jsarray javascript jsarray_length jsarray intvalue jsarray javascript jsarray_length jsarray addtestcase jsarray jsarray printstacktrace tostring jsarray_length jsarray jsarray addtestcase jsarray jsarray getmember jsarray jsarray shouldequal jsarray private static vm bridge make instance for int i 0 i 3 i string class name if i 0 class name org mozilla javascript vmbridge custom else if i 1 class name org mozilla javascript jdk13 vmbridge jdk13 else class name org mozilla javascript jdk11 vmbridge jdk11 class cl kit class or null class name if cl null vm bridge bridge vm bridge kit new instance or null cl if bridge null return bridge throw new illegal state exception failed to create vm bridge instance vmbridge makeinstance classname classname vmbridge_custom classname vmbridge_jdk13 classname vmbridge_jdk11 classornull classname vmbridge vmbridge newinstanceornull illegalstateexception vmbridge return a helper object to optimize link context access p the runtime will pass the resulting helper object to the subsequent calls to link get context object context helper and link set context object context helper context cx methods in this way the implementation can use the helper to cache information about current thread to make link context access faster getcontext contexthelper setcontext contexthelper get link context instance associated with the current thread or null if none param context helper the result of link get thread context helper called from the current thread contexthelper getthreadcontexthelper associate link context instance with the current thread or remove the current association if tt cx tt is null param context helper the result of link get thread context helper called from the current thread contexthelper getthreadcontexthelper protected abstract void set context object context helper context cx return the class loader instance associated with the current thread protected abstract class loader get current thread class loader setcontext contexthelper classloader classloader getcurrentthreadclassloader in many jvm ss public methods in private classes are not accessible by default sun bug 4071593 vm bridge instance should try to workaround that via for example calling method set accessible true when it is available the implementation is responsible to catch all possible exceptions like security exception if the workaround is not available return true if it was possible to make method accessible or false otherwise jvmss vmbridge setaccessible securityexception create helper object to create later proxies implementing the specified interfaces later under jdk 1 3 the implementation can look like pre return java lang reflect proxy get proxy class interfaces get constructor new class java lang reflect invocation handler class pre param interfaces array with one or more interface class objects protected object get interface proxy helper context factory cf class interfaces throw context report runtime error vm bridge get interface proxy helper is not supported getproxyclass getconstructor invocationhandler getinterfaceproxyhelper contextfactory reportruntimeerror vmbridge getinterfaceproxyhelper create proxy object for link interface adapter the proxy should call link interface adapter invoke context factory cf object target scriptable top scope method method object args as implementation of interface methods associated with tt proxy helper tt param proxy helper the result of the previous call to link get interface proxy helper context factory class protected object new interface proxy object proxy helper context factory cf interface adapter adapter object target scriptable top scope throw context report runtime error vm bridge new interface proxy is not supported interfaceadapter interfaceadapter contextfactory topscope proxyhelper proxyhelper getinterfaceproxyhelper contextfactory newinterfaceproxy proxyhelper contextfactory interfaceadapter topscope reportruntimeerror vmbridge newinterfaceproxy public class member 001 extends live connect test public member 001 super member_001 liveconnecttest member_001 public static void main string args member 001 test new member 001 test start member_001 member_001 public void setup test environment super setup test environment setuptestenvironment setuptestenvironment public void execute test object data get data array for int i 0 i data length i js object js object getjs object object data i get the initial value of the property get member js object object data i object data i 4 set the value of the property set member js object object data i verify the value of the property get member js object object data i object data i 5 executetest getdataarray jsobject jsobject getjsobject getmember jsobject setmember jsobject getmember jsobject public js object getjs object object data return js object global eval data 0 data 1 jsobject getjsobject jsobject get the data array which is an object array data arrays which are also object arrays the data arrays consist of 3 items ul li string passed to global eval to create the this object for set member li string property of the js object to get or set li object new value of the property pass to set member and expect li object value of the property before setting it expected result from get member li string representation of the property as retrieved by get member li string class name of the property as retrieved by get member li string typeof as determined by java script ul to add test cases to this test modify this method return the data array public object get data array object d0 new string d0 0 identifier new string new boolean 1 assignment expression new string foo 2 property new string bar 3 value to assign new string undefined 4 initial value new string bar 5 value after assignment java lang string 6 class of property new string object 7 js typeof value object d1 new string d1 0 identifier new string new string java script 1 assignment expression new string foo 2 property new boolean true 3 value to assign new string undefined 4 initial value new boolean true 5 value after assignment java lang boolean 6 class of property new string object 7 js typeof value object d2 new string d2 0 identifier new string new number 12345 1 assignment expression new string foo 2 property new double 0 2134 3 value to assign new string undefined 4 initial value new double 0 2134 5 value after assignment java lang double 6 class of property new string object 7 js typeof value object d3 new string d3 0 identifier new string new number 12345 1 assignment expression new string foo 2 property new integer 987654 3 value to assign new string undefined 4 initial value new integer 987654 5 value after assignment java lang integer 6 class of property new string object 7 js typeof value object d4 new string d4 new string new object new string property global new string undefined global netscape javascript js object new string object object data array d0 d1 d3 d4 return data array setmember jsobject setmember getmember getmember getmember javascript getdataarray javascript jsobject dataarray dataarray get the value of a java script property check its class public void get member js object the this object data object value string exception string property string data 2 object e value value object a value null class e class null class a class null try a value the this get member property if a value null e class e value get class a class a value get class catch exception e exception the this get member property threw e to string file exception exception e print stack trace finally if a value null else check the value of the property add test case get member returned a value data 0 get member property equals e value true a value equals e value exception check the class of the property add test case a value get class returned a class get name a class get name equals e class get name true a class get name equals e class get name exception javascript getmember jsobject thethis evalue avalue eclass aclass avalue thethis getmember avalue eclass evalue getclass aclass avalue getclass thethis getmember tostring printstacktrace avalue addtestcase getmember avalue getmember evalue avalue evalue addtestcase avalue getclass aclass getname aclass getname eclass getname aclass getname eclass getname set the value of a java script property public void set member js object the this object data string exception string result passed string property string data 2 object value data 3 try the this set member property value catch exception e result failed exception the this set member property value threw e to string file exception exception e print stack trace finally add test case the this set member property value passed result exception javascript setmember jsobject thethis thethis setmember thethis setmember tostring printstacktrace addtestcase thethis setmember static final long serial versionuid 6358550398665688245l member box method method init method serialversionuid memberbox member box constructor constructor init constructor memberbox private void init method method this member object method this arg types method get parameter types memberobject argtypes getparametertypes private void init constructor constructor this member object constructor this arg types constructor get parameter types memberobject argtypes getparametertypes method method return method member object memberobject constructor ctor return constructor member object memberobject boolean is method return member object instanceof method ismethod memberobject boolean is ctor return member object instanceof constructor isctor memberobject boolean is static return modifier is static member object get modifiers isstatic isstatic memberobject getmodifiers string get name return member object get name getname memberobject getname class get declaring class return member object get declaring class getdeclaringclass memberobject getdeclaringclass string to java declaration string buffer sb new string buffer if is method method method method sb append method get return type sb append sb append method get name else constructor ctor ctor string name ctor get declaring class get name int last dot name last index of if last dot 0 name name substring last dot 1 sb append name sb append java members live connect signature arg types return sb to string tojavadeclaration stringbuffer stringbuffer ismethod getreturntype getname getdeclaringclass getname lastdot lastindexof lastdot lastdot javamembers liveconnectsignature argtypes tostring public string to string return member object to string tostring memberobject tostring object invoke object target object args method method method try try return method invoke target args catch illegal access exception ex method accessible search accessible method method arg types if accessible null member object accessible method accessible else if vm bridge instance try to make accessible method throw context throw as script runtime ex ex retry after recovery return method invoke target args catch exception ex throw context throw as script runtime ex ex illegalaccessexception searchaccessiblemethod argtypes memberobject vmbridge trytomakeaccessible throwasscriptruntimeex throwasscriptruntimeex object new instance object args constructor ctor ctor try try return ctor new instance args catch illegal access exception ex if vm bridge instance try to make accessible ctor throw context throw as script runtime ex ex return ctor new instance args catch exception ex throw context throw as script runtime ex ex newinstance newinstance illegalaccessexception vmbridge trytomakeaccessible throwasscriptruntimeex newinstance throwasscriptruntimeex private static method search accessible method method method class params int modifiers method get modifiers if modifier is public modifiers modifier is static modifiers class c method get declaring class if modifier is public c get modifiers string name method get name class intfs c get interfaces for int i 0 n intfs length i n i class intf intfs i if modifier is public intf get modifiers try return intf get method name params catch no such method exception ex catch security exception ex for c c get superclass if c null break if modifier is public c get modifiers try method m c get method name params int m modifiers m get modifiers if modifier is public m modifiers modifier is static m modifiers return m catch no such method exception ex catch security exception ex return null searchaccessiblemethod getmodifiers ispublic isstatic getdeclaringclass ispublic getmodifiers getname getinterfaces ispublic getmodifiers getmethod nosuchmethodexception securityexception getsuperclass ispublic getmodifiers getmethod mmodifiers getmodifiers ispublic mmodifiers isstatic mmodifiers nosuchmethodexception securityexception private void read object object input stream in throws io exception class not found exception in default read object member member read member in if member instanceof method init method member else init constructor member readobject objectinputstream ioexception classnotfoundexception defaultreadobject readmember private void write object object output stream out throws io exception out default write object write member out member object writeobject objectoutputstream ioexception defaultwriteobject writemember memberobject writes a constructor or method object methods and constructors are not serializable so we must serialize information about the class the name and the parameters and recreate upon deserialization private static void write member object output stream out member member throws io exception if member null out write boolean false return out write boolean true if member instanceof method member instanceof constructor throw new illegal argument exception not method or constructor out write boolean member instanceof method out write object member get name out write object member get declaring class if member instanceof method write parameters out method member get parameter types else write parameters out constructor member get parameter types writemember objectoutputstream ioexception writeboolean writeboolean illegalargumentexception writeboolean writeobject getname writeobject getdeclaringclass writeparameters getparametertypes writeparameters getparametertypes reads a method or a constructor from the stream private static member read member object input stream in throws io exception class not found exception if in read boolean return null boolean is method in read boolean string name string in read object class declaring class in read object class parms read parameters in try if is method return declaring get method name parms else return declaring get constructor parms catch no such method exception e throw new io exception cannot find member e readmember objectinputstream ioexception classnotfoundexception readboolean ismethod readboolean readobject readobject readparameters ismethod getmethod getconstructor nosuchmethodexception ioexception writes an array of parameter types to the stream requires special handling because primitive types cannot be found upon deserialization by the default java implementation private static void write parameters object output stream out class parms throws io exception out write short parms length outer for int i 0 i parms length i class parm parms i out write boolean parm is primitive if parm is primitive out write object parm continue for int j 0 j primitives length j if parm equals primitives j out write byte j continue outer throw new illegal argument exception primitive parm not found writeparameters objectoutputstream ioexception writeshort writeboolean isprimitive isprimitive writeobject writebyte illegalargumentexception reads an array of parameter types from the stream private static class read parameters object input stream in throws io exception class not found exception class result new class in read short for int i 0 i result length i if in read boolean result i class in read object continue result i primitives in read byte return result readparameters objectinputstream ioexception classnotfoundexception readshort readboolean readobject readbyte static void check valid attributes int attributes final int mask readonly dontenum permanent if attributes mask 0 throw new illegal argument exception string value of attributes checkvalidattributes illegalargumentexception valueof public scriptable object scriptableobject public scriptable object scriptable scope scriptable prototype if scope null throw new illegal argument exception parent scope object scope prototype object prototype scriptableobject illegalargumentexception parentscopeobject prototypeobject return the name of the class this is typically the same name as the constructor classes extending scriptable object must implement this abstract method scriptableobject returns true if the named property is defined param name the name of the property param start the object in which the lookup began return true if and only if the property was found in the object public boolean has string name scriptable start return null get named slot name getnamedslot returns true if the property index is defined param index the numeric index for the property param start the object in which the lookup began return true if and only if the property was found in the object public boolean has int index scriptable start return null get slot null index getslot returns the value of the named property or not found if the property was created using define property the appropriate getter method is called param name the name of the property param start the object in which the lookup began return the value of the property may be null or not found public object get string name scriptable start slot slot get named slot name if slot null return scriptable not found if slot instanceof getter slot getter slot gslot getter slot slot if gslot getter null return get by getter gslot start return slot value not_found defineproperty not_found getnamedslot not_found getterslot getterslot getterslot getbygetter returns the value of the indexed property or not found param index the numeric index for the property param start the object in which the lookup began return the value of the property may be null or not found public object get int index scriptable start slot slot get slot null index if slot null return scriptable not found return slot value not_found not_found getslot not_found sets the value of the named property creating it if need be if the property was created using define property the appropriate setter method is called p if the property s attributes include readonly no action is taken this method will actually set the property in the start object param name the name of the property param start the object whose property is being set param value value to set the property to public void put string name scriptable start object value slot slot last access get local copy if name slot string key slot was deleted 0 int hash name hash code slot get slot name hash if slot null if start this start put name start value return slot add slot name hash null note cache is not updated in put if start this is sealed throw context report runtime error1 msg modify sealed name if slot attributes scriptable object readonly 0 return if slot instanceof getter slot getter slot gslot getter slot slot if gslot setter null set by setter gslot start value return if this start slot value value else start put name start value defineproperty lastaccess stringkey wasdeleted hashcode getslot addslot issealed reportruntimeerror1 scriptableobject getterslot getterslot getterslot setbysetter sets the value of the indexed property creating it if need be param index the numeric index for the property param start the object whose property is being set param value value to set the property to public void put int index scriptable start object value slot slot get slot null index if slot null if start this start put index start value return slot add slot null index null if start this is sealed throw context report runtime error1 msg modify sealed integer to string index if slot attributes scriptable object readonly 0 return if this start slot value value else start put index start value getslot addslot issealed reportruntimeerror1 tostring scriptableobject removes a named property from the object if the property is not found or it has the permanent attribute no action is taken param name the name of the property public void delete string name remove slot name name hash code removeslot hashcode removes the indexed property from the object if the property is not found or it has the permanent attribute no action is taken param index the numeric index for the property public void delete int index remove slot null index removeslot deprecated use link get attributes string name the engine always ignored the start argument public final int get attributes string name scriptable start return get attributes name getattributes getattributes getattributes deprecated use link get attributes int index the engine always ignored the start argument public final int get attributes int index scriptable start return get attributes index getattributes getattributes getattributes deprecated use link set attributes string name int attributes the engine always ignored the start argument public final void set attributes string name scriptable start int attributes set attributes name attributes setattributes setattributes setattributes deprecated use link set attributes int index int attributes the engine always ignored the start argument public void set attributes int index scriptable start int attributes set attributes index attributes setattributes setattributes setattributes get the attributes of a named property the property is specified by code name code as defined for code has code p param name the identifier for the property return the bitset of attributes exception evaluator exception if the named property is not found see org mozilla javascript scriptable object has see org mozilla javascript scriptable object readonly see org mozilla javascript scriptable object dontenum see org mozilla javascript scriptable object permanent see org mozilla javascript scriptable object empty public int get attributes string name slot slot get named slot name if slot null throw context report runtime error1 msg prop not found name return slot attributes evaluatorexception scriptableobject scriptableobject scriptableobject scriptableobject scriptableobject getattributes getnamedslot reportruntimeerror1 get the attributes of an indexed property param index the numeric index for the property exception evaluator exception if the named property is not found is not found return the bitset of attributes see org mozilla javascript scriptable object has see org mozilla javascript scriptable object readonly see org mozilla javascript scriptable object dontenum see org mozilla javascript scriptable object permanent see org mozilla javascript scriptable object empty public int get attributes int index slot slot get slot null index if slot null throw context report runtime error1 msg prop not found string value of index return slot attributes evaluatorexception scriptableobject scriptableobject scriptableobject scriptableobject scriptableobject getattributes getslot reportruntimeerror1 valueof set the attributes of a named property the property is specified by code name code as defined for code has code p the possible attributes are readonly dontenum and permanent combinations of attributes are expressed by the bitwise or of attributes empty is the state of no attributes set any unused bits are reserved for future use param name the name of the property param attributes the bitset of attributes exception evaluator exception if the named property is not found see org mozilla javascript scriptable has see org mozilla javascript scriptable object readonly see org mozilla javascript scriptable object dontenum see org mozilla javascript scriptable object permanent see org mozilla javascript scriptable object empty public void set attributes string name int attributes check valid attributes attributes slot slot get named slot name if slot null throw context report runtime error1 msg prop not found name slot attributes short attributes evaluatorexception scriptableobject scriptableobject scriptableobject scriptableobject setattributes checkvalidattributes getnamedslot reportruntimeerror1 set the attributes of an indexed property param index the numeric index for the property param attributes the bitset of attributes exception evaluator exception if the named property is not found see org mozilla javascript scriptable has see org mozilla javascript scriptable object readonly see org mozilla javascript scriptable object dontenum see org mozilla javascript scriptable object permanent see org mozilla javascript scriptable object empty public void set attributes int index int attributes check valid attributes attributes slot slot get slot null index if slot null throw context report runtime error1 msg prop not found string value of index slot attributes short attributes evaluatorexception scriptableobject scriptableobject scriptableobject scriptableobject setattributes checkvalidattributes getslot reportruntimeerror1 valueof returns the prototype of the object public scriptable get prototype return prototype object getprototype prototypeobject sets the prototype of the object public void set prototype scriptable m prototype object m setprototype prototypeobject returns the parent enclosing scope of the object public scriptable get parent scope return parent scope object getparentscope parentscopeobject sets the parent enclosing scope of the object public void set parent scope scriptable m parent scope object m setparentscope parentscopeobject returns an array of ids for the properties of the object p any properties with the attribute dontenum are not listed p return an array of java lang objects with an entry for every listed property properties accessed via an integer index will have a corresponding integer entry in the returned array properties accessed by a string will have a string entry in the returned array public object get ids return get ids false getids getids returns an array of ids for the properties of the object p all properties even those with attribute dontenum are listed p return an array of java lang objects with an entry for every listed property properties accessed via an integer index will have a corresponding integer entry in the returned array properties accessed by a string will have a string entry in the returned array public object get all ids return get ids true getallids getids implements the default value internal method p note that the to primitive conversion is a no op for every type other than object for which default value is called see ecma 9 1 p a code hint code of null means no hint param type hint the type hint return the default value for the object see ecma 8 6 2 6 public object get default value class type hint context cx null for int i 0 i 2 i boolean try to string if type hint script runtime string class try to string i 0 else try to string i 1 string method name object args if try to string method name to string args script runtime empty args else method name value of args new object 1 string hint if type hint null hint undefined else if type hint script runtime string class hint string else if type hint script runtime scriptable class hint object else if type hint script runtime function class hint function else if type hint script runtime boolean class type hint boolean type hint boolean else if type hint script runtime number class type hint script runtime byte class type hint byte type type hint script runtime short class type hint short type type hint script runtime integer class type hint integer type type hint script runtime float class type hint float type type hint script runtime double class type hint double type hint number else throw context report runtime error1 msg invalid type type hint to string args 0 hint object v get property this method name if v instanceof function continue function fun function v if cx null cx context get context v fun call cx fun get parent scope this args if v null if v instanceof scriptable return v if type hint script runtime scriptable class type hint script runtime function class return v if try to string v instanceof wrapper let a wrapped java lang string pass for a primitive string object u wrapper v unwrap if u instanceof string return u fall through to error string arg type hint null undefined type hint get name throw script runtime type error1 msg default value arg defaultvalue toprimitive defaultvalue typehint getdefaultvalue typehint trytostring typehint scriptruntime stringclass trytostring trytostring methodname trytostring methodname tostring scriptruntime emptyargs methodname valueof typehint typehint scriptruntime stringclass typehint scriptruntime scriptableclass typehint scriptruntime functionclass typehint scriptruntime booleanclass typehint typehint scriptruntime numberclass typehint scriptruntime byteclass typehint typehint scriptruntime shortclass typehint typehint scriptruntime integerclass typehint typehint scriptruntime floatclass typehint typehint scriptruntime doubleclass typehint reportruntimeerror1 typehint tostring getproperty methodname getcontext getparentscope typehint scriptruntime scriptableclass typehint scriptruntime functionclass trytostring typehint typehint getname scriptruntime typeerror1 implements the instanceof operator p this operator has been proposed to ecma param instance the value that appeared on the lhs of the instanceof operator return true if this appears in value s prototype chain public boolean has instance scriptable instance default for js objects other than function is to do prototype chasing this will be overridden in native function and non js objects return script runtime js delegates to instance this hasinstance nativefunction scriptruntime jsdelegatesto custom tt tt operator must return link scriptable not found if this object does not have custom equality operator for the given value tt boolean true tt if this object is equivalent to tt value tt tt boolean false tt if this object is not equivalent to tt value tt p the default implementation returns boolean true if tt this value tt or link scriptable not found otherwise it indicates that by default custom equality is available only if tt value tt is tt this tt in which case true is returned protected object equivalent values object value return this value boolean true scriptable not found not_found not_found equivalentvalues not_found defines java script objects from a java class that implements scriptable if the given class has a method pre static void init context cx scriptable scope boolean sealed pre or its compatibility form pre static void init scriptable scope pre then it is invoked and no further initialization is done p however if no such a method is found then the class s constructors and methods are used to initialize a class in the following manner p first the zero parameter constructor of the class is called to create the prototype if no such constructor exists a link evaluator exception is thrown p next all methods are scanned for special prefixes that indicate that they have special meaning for defining java script objects these special prefixes are ul li code jsfunction code for a java script function li code jsstaticfunction code for a java script function that is a property of the constructor li code jsget code for a getter of a java script property li code jsset code for a setter of a java script property li code js constructor code for a java script function that is the constructor ul p if the method s name begins with jsfunction a java script function is created with a name formed from the rest of the java method name following jsfunction so a java method named jsfunction foo will define a java script method foo calling this java script function will cause the java method to be called the parameters of the method must be of number and types as defined by the function object class the java script function is then added as a property of the prototype p if the method s name begins with jsstaticfunction it is handled similarly except that the resulting java script function is added as a property of the constructor object the java method must be static if the method s name begins with jsget or jsset the method is considered to define a property accesses to the defined property will result in calls to these getter and setter methods if no setter is defined the property is defined as readonly p if the method s name is js constructor the method is considered to define the body of the constructor only one method of this name may be defined if no method is found that can serve as constructor a java constructor will be selected to serve as the java script constructor in the following manner if the class has only one java constructor that constructor is used to define the java script constructor if the the class has two constructors one must be the zero argument constructor otherwise an link evaluator exception would have already been thrown when the prototype was to be created in this case the java constructor with one or more parameters will be used to define the java script constructor if the class has three or more constructors an link evaluator exception will be thrown p finally if there is a method pre static void finish init scriptable scope function object constructor scriptable prototype pre it will be called to finish any initialization the code scope code argument will be passed along with the newly created constructor and the newly created prototype p param scope the scope in which to define the constructor param clazz the java class to use to define the java script objects and properties exception illegal access exception if access is not available to a reflected class member exception instantiation exception if unable to instantiate the named class exception invocation target exception if an exception is thrown during execution of methods of the named class see org mozilla javascript function see org mozilla javascript function object see org mozilla javascript scriptable object readonly see org mozilla javascript scriptable object define property public static void define class scriptable scope class clazz throws illegal access exception instantiation exception invocation target exception define class scope clazz false false javascript evaluatorexception javascript jsfunction_ javascript jsstaticfunction_ javascript jsget_ javascript jsset_ javascript jsconstructor javascript jsfunction_ javascript jsfunction_ jsfunction_foo javascript javascript functionobject javascript jsstaticfunction_ javascript jsget_ jsset_ jsconstructor javascript javascript evaluatorexception javascript evaluatorexception finishinit functionobject javascript illegalaccessexception instantiationexception invocationtargetexception functionobject scriptableobject scriptableobject defineproperty defineclass illegalaccessexception instantiationexception invocationtargetexception defineclass defines java script objects from a java class optionally allowing sealing similar to code define class scriptable scope class clazz code except that sealing is allowed an object that is sealed cannot have properties added or removed note that sealing is not allowed in the current ecma iso language specification but is likely for the next version param scope the scope in which to define the constructor param clazz the java class to use to define the java script objects and properties the class must implement scriptable param sealed whether or not to create sealed standard objects that cannot be modified exception illegal access exception if access is not available to a reflected class member exception instantiation exception if unable to instantiate the named class exception invocation target exception if an exception is thrown during execution of methods of the named class since 1 4r3 public static void define class scriptable scope class clazz boolean sealed throws illegal access exception instantiation exception invocation target exception define class scope clazz sealed false javascript defineclass javascript illegalaccessexception instantiationexception invocationtargetexception defineclass illegalaccessexception instantiationexception invocationtargetexception defineclass defines java script objects from a java class optionally allowing sealing and mapping of java inheritance to java script prototype based inheritance similar to code define class scriptable scope class clazz code except that sealing and inheritance mapping are allowed an object that is sealed cannot have properties added or removed note that sealing is not allowed in the current ecma iso language specification but is likely for the next version param scope the scope in which to define the constructor param clazz the java class to use to define the java script objects and properties the class must implement scriptable param sealed whether or not to create sealed standard objects that cannot be modified param map inheritance whether or not to map java inheritance to java script prototype based inheritance return the class name for the prototype of the specified class exception illegal access exception if access is not available to a reflected class member exception instantiation exception if unable to instantiate the named class exception invocation target exception if an exception is thrown during execution of methods of the named class since 1 6r2 public static string define class scriptable scope class clazz boolean sealed boolean map inheritance throws illegal access exception instantiation exception invocation target exception method methods function object get method list clazz for int i 0 i methods length i method method methods i if method get name equals init continue class parm types method get parameter types if parm types length 3 parm types 0 script runtime context class parm types 1 script runtime scriptable class parm types 2 boolean type modifier is static method get modifiers object args context get context scope sealed boolean true boolean false method invoke null args return null if parm types length 1 parm types 0 script runtime scriptable class modifier is static method get modifiers object args scope method invoke null args return null if we got here there isn t an init method with the right parameter types constructor ctors clazz get constructors constructor proto ctor null for int i 0 i ctors length i if ctors i get parameter types length 0 proto ctor ctors i break if proto ctor null throw context report runtime error1 msg zero arg ctor clazz get name scriptable proto scriptable proto ctor new instance script runtime empty args string class name proto get class name set the prototype s prototype trying to map java inheritance to js prototype based inheritance if requested to do so scriptable super proto null if map inheritance class super class clazz get superclass if script runtime scriptable class is assignable from super class string name scriptable object define class scope super class sealed map inheritance if name null super proto scriptable object get class prototype scope name if super proto null super proto scriptable object get object prototype scope proto set prototype super proto find out whether there are any methods that begin with js if so then only methods that begin with special prefixes will be defined as java script entities final string function prefix jsfunction final string static function prefix jsstaticfunction final string getter prefix jsget final string setter prefix jsset final string ctor name js constructor member ctor member function object find single method methods ctor name if ctor member null if ctors length 1 ctor member ctors 0 else if ctors length 2 if ctors 0 get parameter types length 0 ctor member ctors 1 else if ctors 1 get parameter types length 0 ctor member ctors 0 if ctor member null throw context report runtime error1 msg ctor multiple parms clazz get name function object ctor new function object class name ctor member scope if ctor is var args method throw context report runtime error1 msg varargs ctor ctor member get name ctor add as constructor scope proto method finish init null for int i 0 i methods length i if methods i ctor member continue string name methods i get name if name equals finish init class parm types methods i get parameter types if parm types length 3 parm types 0 script runtime scriptable class parm types 1 function object class parm types 2 script runtime scriptable class modifier is static methods i get modifiers finish init methods i continue ignore any compiler generated methods if name index of 1 continue if name equals ctor name continue string prefix null if name starts with function prefix prefix function prefix else if name starts with static function prefix prefix static function prefix if modifier is static methods i get modifiers throw context report runtime error js static function must be used with static method else if name starts with getter prefix prefix getter prefix else if name starts with setter prefix prefix setter prefix else continue name name substring prefix length if prefix setter prefix continue deal with set when we see get if prefix getter prefix if proto instanceof scriptable object throw context report runtime error2 msg extend scriptable proto get class to string name method setter function object find single method methods setter prefix name int attr scriptable object permanent scriptable object dontenum setter null 0 scriptable object readonly scriptable object proto define property name null methods i setter attr continue function object f new function object name methods i proto if f is var args constructor throw context report runtime error1 msg varargs fun ctor member get name scriptable dest prefix static function prefix ctor proto define property dest name f dontenum if sealed f seal object call user code to complete initialization if necessary if finish init null object finish args scope ctor proto finish init invoke null finish args seal the object if necessary if sealed ctor seal object if proto instanceof scriptable object scriptable object proto seal object return class name javascript javascript defineclass javascript mapinheritance javascript illegalaccessexception instantiationexception invocationtargetexception defineclass mapinheritance illegalaccessexception instantiationexception invocationtargetexception functionobject getmethodlist getname parmtypes getparametertypes parmtypes parmtypes scriptruntime contextclass parmtypes scriptruntime scriptableclass parmtypes isstatic getmodifiers getcontext parmtypes parmtypes scriptruntime scriptableclass isstatic getmodifiers getconstructors protoctor getparametertypes protoctor protoctor reportruntimeerror1 getname protoctor newinstance scriptruntime emptyargs classname getclassname superproto mapinheritance superclass getsuperclass scriptruntime scriptableclass isassignablefrom superclass scriptableobject defineclass superclass mapinheritance superproto scriptableobject getclassprototype superproto superproto scriptableobject getobjectprototype setprototype superproto javascript functionprefix jsfunction_ staticfunctionprefix jsstaticfunction_ getterprefix jsget_ setterprefix jsset_ ctorname jsconstructor ctormember functionobject findsinglemethod ctorname ctormember ctormember getparametertypes ctormember getparametertypes ctormember ctormember reportruntimeerror1 getname functionobject functionobject classname ctormember isvarargsmethod reportruntimeerror1 ctormember getname addasconstructor finishinit ctormember getname finishinit parmtypes getparametertypes parmtypes parmtypes scriptruntime scriptableclass parmtypes functionobject parmtypes scriptruntime scriptableclass isstatic getmodifiers finishinit indexof ctorname startswith functionprefix functionprefix startswith staticfunctionprefix staticfunctionprefix isstatic getmodifiers reportruntimeerror jsstaticfunction startswith getterprefix getterprefix startswith setterprefix setterprefix setterprefix getterprefix scriptableobject reportruntimeerror2 getclass tostring functionobject findsinglemethod setterprefix scriptableobject scriptableobject scriptableobject scriptableobject defineproperty functionobject functionobject isvarargsconstructor reportruntimeerror1 ctormember getname staticfunctionprefix defineproperty sealobject finishinit finishargs finishinit finishargs sealobject scriptableobject scriptableobject sealobject classname define a java script property creates the property with an initial value and sets its attributes param property name the name of the property to define param value the initial value of the property param attributes the attributes of the java script property see org mozilla javascript scriptable put public void define property string property name object value int attributes put property name this value set attributes property name attributes javascript propertyname javascript defineproperty propertyname propertyname setattributes propertyname utility method to add properties to arbitrary scriptable object if destination is instance of scriptable object calls define property there otherwise calls put in destination ignoring attributes public static void define property scriptable destination string property name object value int attributes if destination instanceof scriptable object destination put property name destination value return scriptable object so scriptable object destination so define property property name value attributes scriptableobject defineproperty defineproperty propertyname scriptableobject propertyname scriptableobject scriptableobject defineproperty propertyname define a java script property with getter and setter side effects if the setter is not found the attribute readonly is added to the given attributes p the getter must be a method with zero parameters and the setter if found must be a method with one parameter p param property name the name of the property to define this name also affects the name of the setter and getter to search for if the property id is foo then code clazz code will be searched for get foo and set foo methods param clazz the java class to search for the getter and setter param attributes the attributes of the java script property see org mozilla javascript scriptable put public void define property string property name class clazz int attributes int length property name length if length 0 throw new illegal argument exception char buf new char 3 length property name get chars 0 length buf 3 buf 3 character to upper case buf 3 buf 0 g buf 1 e buf 2 t string getter name new string buf buf 0 s string setter name new string buf method methods function object get method list clazz method getter function object find single method methods getter name method setter function object find single method methods setter name if setter null attributes scriptable object readonly define property property name null getter setter null null setter attributes javascript propertyname propertyid getfoo setfoo javascript defineproperty propertyname propertyname illegalargumentexception propertyname getchars touppercase gettername settername functionobject getmethodlist functionobject findsinglemethod gettername functionobject findsinglemethod settername scriptableobject defineproperty propertyname define a java script property use this method only if you wish to define getters and setters for a given property in a scriptable object to create a property without special getter or setter side effects use code define property string int code if code setter code is null the attribute readonly is added to the given attributes p several forms of getters or setters are allowed in all cases the type of the value parameter can be any one of the following types object string boolean scriptable byte short int long float or double the runtime will perform appropriate conversions based upon the type of the parameter see description in function object the first forms are nonstatic methods of the class referred to by this pre object get foo void set foo some type value pre next are static methods that may be of any class the object whose property is being accessed is passed in as an extra argument pre static object get foo scriptable object obj static void set foo scriptable object obj some type value pre finally it is possible to delegate to another object entirely using the code delegate to code parameter in this case the methods are nonstatic methods of the class delegated to and the object whose property is being accessed is passed in as an extra argument pre object get foo scriptable object obj void set foo scriptable object obj some type value pre param property name the name of the property to define param delegate to an object to call the getter and setter methods on or null depending on the form used above param getter the method to invoke to get the value of the property param setter the method to invoke to set the value of the property param attributes the attributes of the java script property public void define property string property name object delegate to method getter method setter int attributes if delegate to null modifier is static getter get modifiers delegate to has static accessors class parm types getter get parameter types if parm types length 0 if parm types length 1 parm types 0 script runtime scriptable object class throw context report runtime error1 msg bad getter parms getter to string else if delegate to null throw context report runtime error1 msg obj getter parms getter to string if setter null if delegate to has static accessors modifier is static setter get modifiers throw context report runtime error0 msg getter static parm types setter get parameter types if parm types length 2 if parm types 0 script runtime scriptable object class throw context report runtime error0 msg setter2 parms if delegate to null throw context report runtime error1 msg setter1 parms setter to string else if parm types length 1 if delegate to null throw context report runtime error1 msg setter2 expected setter to string else throw context report runtime error0 msg setter parms class setter type parm types parm types length 1 int setter type tag function object get type tag setter type if setter type tag function object java unsupported type throw context report runtime error2 msg setter2 expected setter type get name setter to string getter slot gslot new getter slot gslot delegate to delegate to gslot getter new member box getter if setter null gslot setter new member box setter gslot attributes short attributes slot inserted add slot property name property name hash code gslot if inserted gslot throw new runtime exception property already exists javascript scriptableobject defineproperty functionobject getfoo setfoo sometype getfoo scriptableobject setfoo scriptableobject sometype delegateto getfoo scriptableobject setfoo scriptableobject sometype propertyname delegateto javascript defineproperty propertyname delegateto delegateto isstatic getmodifiers delegateto has_static_accessors parmtypes getparametertypes parmtypes parmtypes parmtypes scriptruntime scriptableobjectclass reportruntimeerror1 tostring delegateto reportruntimeerror1 tostring delegateto has_static_accessors isstatic getmodifiers reportruntimeerror0 parmtypes getparametertypes parmtypes parmtypes scriptruntime scriptableobjectclass reportruntimeerror0 delegateto reportruntimeerror1 tostring parmtypes delegateto reportruntimeerror1 tostring reportruntimeerror0 settertype parmtypes parmtypes settertypetag functionobject gettypetag settertype settertypetag functionobject java_unsupported_type reportruntimeerror2 settertype getname tostring getterslot getterslot delegateto delegateto memberbox memberbox addslot propertyname propertyname hashcode runtimeexception search for names in a class adding the resulting methods as properties p uses reflection to find the methods of the given names then function objects are constructed from the methods found and are added to this object as properties with the given names param names the names of the methods to add as function properties param clazz the class to search for the methods param attributes the attributes of the new properties see org mozilla javascript function object public void define function properties string names class clazz int attributes method methods function object get method list clazz for int i 0 i names length i string name names i method m function object find single method methods name if m null throw context report runtime error2 msg method not found name clazz get name function object f new function object name m this define property name f attributes functionobjects functionobject definefunctionproperties functionobject getmethodlist functionobject findsinglemethod reportruntimeerror2 getname functionobject functionobject defineproperty get the object prototype property see ecma 15 2 4 public static scriptable get object prototype scriptable scope return get class prototype scope object getobjectprototype getclassprototype get the function prototype property see ecma 15 3 4 public static scriptable get function prototype scriptable scope return get class prototype scope function getfunctionprototype getclassprototype get the prototype for the named class for example code get class prototype s date code will first walk up the parent chain to find the outermost scope then will search that scope for the date constructor and then will return date prototype if any of the lookups fail or the prototype is not a java script object then null will be returned param scope an object in the scope chain param class name the name of the constructor return the prototype for the named class or null if it cannot be found public static scriptable get class prototype scriptable scope string class name scope get top level scope scope object ctor get property scope class name object proto if ctor instanceof base function proto base function ctor get prototype property else if ctor instanceof scriptable scriptable ctor obj scriptable ctor proto ctor obj get prototype ctor obj else return null if proto instanceof scriptable return scriptable proto return null getclassprototype javascript classname getclassprototype classname gettoplevelscope getproperty classname basefunction basefunction getprototypeproperty ctorobj ctorobj ctorobj get the global scope p walks the parent scope chain to find an object with a null parent scope the global object param obj a java script object return the corresponding global scope public static scriptable get top level scope scriptable obj for scriptable parent obj get parent scope if parent null return obj obj parent javascript gettoplevelscope getparentscope seal this object a sealed object may not have properties added or removed once an object is sealed it may not be unsealed since 1 4r3 public synchronized void seal object if count 0 count 1 count sealobject return true if this object is sealed it is an error to attempt to add or remove properties to a sealed object return true if sealed false otherwise since 1 4r3 public final boolean is sealed return count 0 issealed gets a named property from an object or any object in its prototype chain p searches the prototype chain for a property named code name code p param obj a java script object param name a property name return the value of a property with name code name code found in code obj code or any object in its prototype chain or code scriptable not found code if not found since 1 5r2 public static object get property scriptable obj string name scriptable start obj object result do result obj get name start if result scriptable not found break obj obj get prototype while obj null return result javascript not_found getproperty not_found getprototype gets an indexed property from an object or any object in its prototype chain p searches the prototype chain for a property with integral index code index code note that if you wish to look for properties with numerical but non integral indicies you should use get property scriptable string with the string value of the index p param obj a java script object param index an integral index return the value of a property with index code index code found in code obj code or any object in its prototype chain or code scriptable not found code if not found since 1 5r2 public static object get property scriptable obj int index scriptable start obj object result do result obj get index start if result scriptable not found break obj obj get prototype while obj null return result getproperty javascript not_found getproperty not_found getprototype returns whether a named property is defined in an object or any object in its prototype chain p searches the prototype chain for a property named code name code p param obj a java script object param name a property name return the true if property was found since 1 5r2 public static boolean has property scriptable obj string name return null get base obj name javascript hasproperty getbase returns whether an indexed property is defined in an object or any object in its prototype chain p searches the prototype chain for a property with index code index code p param obj a java script object param index a property index return the true if property was found since 1 5r2 public static boolean has property scriptable obj int index return null get base obj index javascript hasproperty getbase puts a named property in an object or in an object in its prototype chain p seaches for the named property in the prototype chain if it is found the value of the property in code obj code is changed through a call to link scriptable put string scriptable object on the prototype passing code obj code as the code start code argument this allows the prototype to veto the property setting in case the prototype defines the property with read only attribute if the property is not found it is added in code obj code param obj a java script object param name a property name param value any java script value accepted by scriptable put since 1 5r2 public static void put property scriptable obj string name object value scriptable base get base obj name if base null base obj base put name obj value readonly javascript javascript putproperty getbase puts an indexed property in an object or in an object in its prototype chain p seaches for the indexed property in the prototype chain if it is found the value of the property in code obj code is changed through a call to link scriptable put int scriptable object on the prototype passing code obj code as the code start code argument this allows the prototype to veto the property setting in case the prototype defines the property with read only attribute if the property is not found it is added in code obj code param obj a java script object param index a property index param value any java script value accepted by scriptable put since 1 5r2 public static void put property scriptable obj int index object value scriptable base get base obj index if base null base obj base put index obj value readonly javascript javascript putproperty getbase removes the property from an object or its prototype chain p searches for a property with code name code in obj or its prototype chain if it is found the object s delete method is called param obj a java script object param name a property name return true if the property doesn t exist or was successfully removed since 1 5r2 public static boolean delete property scriptable obj string name scriptable base get base obj name if base null return true base delete name return base has name obj javascript deleteproperty getbase removes the property from an object or its prototype chain p searches for a property with code index code in obj or its prototype chain if it is found the object s delete method is called param obj a java script object param index a property index return true if the property doesn t exist or was successfully removed since 1 5r2 public static boolean delete property scriptable obj int index scriptable base get base obj index if base null return true base delete index return base has index obj javascript deleteproperty getbase returns an array of all ids from an object and its prototypes p param obj a java script object return an array of all ids from all object in the prototype chain if a given id occurs multiple times in the prototype chain it will occur only once in this list since 1 5r2 public static object get property ids scriptable obj if obj null return script runtime empty args object result obj get ids obj to int map map null for obj obj get prototype if obj null break object ids obj get ids if ids length 0 continue if map null if result length 0 result ids continue map new obj to int map result length ids length for int i 0 i result length i map intern result i result null allow to gc the result for int i 0 i ids length i map intern ids i if map null result map get keys return result javascript getpropertyids scriptruntime emptyargs getids objtointmap getprototype getids objtointmap getkeys call a method of an object param obj the java script object param method name the name of the function property param args the arguments for the call see context get current context public static object call method scriptable obj string method name object args return call method null obj method name args javascript methodname getcurrentcontext callmethod methodname callmethod methodname call a method of an object param cx the context object associated with the current thread param obj the java script object param method name the name of the function property param args the arguments for the call public static object call method context cx scriptable obj string method name object args object fun obj get property obj method name if fun obj instanceof function throw script runtime not function error obj method name function fun function fun obj xxx what should be the scope when calling fun obj the following favor scope stored in the object on the assumption that is more useful especially under dynamic scope setup an alternative is to check for dynamic scope flag and use scriptable object get top level scope fun if the flag is not set but that require access to context and messy code so for now it is not checked scriptable scope scriptable object get top level scope obj if cx null return fun call cx scope obj args else return context call null fun scope obj args javascript methodname callmethod methodname funobj getproperty methodname funobj scriptruntime notfunctionerror methodname funobj funobj scriptableobject gettoplevelscope scriptableobject gettoplevelscope private static scriptable get base scriptable obj string name do if obj has name obj break obj obj get prototype while obj null return obj getbase getprototype private static scriptable get base scriptable obj int index do if obj has index obj break obj obj get prototype while obj null return obj getbase getprototype get arbitrary application specific value associated with this object param key key object to select particular value see associate value object key object value public final object get associated value object key hashtable h associated values if h null return null return h get key associatevalue getassociatedvalue associatedvalues get arbitrary application specific value associated with the top scope of the given scope the method first calls link get top level scope scriptable scope and then searches the prototype chain of the top scope for the first object containing the associated value with the given key param scope the starting scope param key key object to select particular value see get associated value object key public static object get top scope value scriptable scope object key scope scriptable object get top level scope scope for if scope instanceof scriptable object scriptable object so scriptable object scope object value so get associated value key if value null return value scope scope get prototype if scope null return null gettoplevelscope getassociatedvalue gettopscopevalue scriptableobject gettoplevelscope scriptableobject scriptableobject scriptableobject getassociatedvalue getprototype associate arbitrary application specific value with this object value can only be associated with the given object and key only once the method ignores any subsequent attempts to change the already associated value p the associated values are not serilized param key key object to select particular value param value the value to associate return the passed value if the method is called first time for the given key or old value for any subsequent calls see get associated value object key public final object associate value object key object value if value null throw new illegal argument exception hashtable h associated values if h null synchronized this h associated values if h null h new hashtable associated values h return kit init hash h key value getassociatedvalue associatevalue illegalargumentexception associatedvalues associatedvalues associatedvalues inithash private object get by getter getter slot slot scriptable start object getter this object args if slot delegate to null if start this walk the prototype chain to find an appropriate object to invoke the getter on class clazz slot getter get declaring class while clazz is instance start start start get prototype if start this break if start null start this break getter this start args script runtime empty args else getter this slot delegate to args new object this return slot getter invoke getter this args getbygetter getterslot getterthis delegateto getdeclaringclass isinstance getprototype getterthis scriptruntime emptyargs getterthis delegateto getterthis private void set by setter getter slot slot scriptable start object value if start this if slot delegate to null slot setter get declaring class is instance start start put slot string key start value return object setter this object args object setter result context cx context get context class p types slot setter arg types class desired p types p types length 1 alert cache tag since it is already calculated in define property int tag function object get type tag desired object actual arg function object convert arg cx start value tag if slot delegate to null setter this start args new object actual arg else if start this kit code bug setter this slot delegate to args new object this actual arg check start is sealed start is always instance of scriptable object due to logic in if start this above if scriptable object start is sealed throw context report runtime error1 msg modify sealed slot string key setter result slot setter invoke setter this args if slot setter method get return type void type replace getter slot by a simple one slot replacement new slot replacement int key slot int key replacement string key slot string key replacement attributes slot attributes replacement value setter result synchronized this int i get slot position slots slot string key slot int key check slot was not deleted replaced before synchronization if i 0 slots i slot slots i replacement it is important to make sure that last access slot to prevent accessing the old slot via last access and then invoking setter one more time last access replacement setbysetter getterslot delegateto getdeclaringclass isinstance stringkey setterthis setterresult getcontext ptypes argtypes ptypes ptypes defineproperty functionobject gettypetag actualarg functionobject convertarg delegateto setterthis actualarg codebug setterthis delegateto actualarg scriptableobject scriptableobject issealed reportruntimeerror1 stringkey setterresult setterthis getreturntype intkey intkey stringkey stringkey setterresult getslotposition stringkey intkey lastaccess lastaccess lastaccess private slot get named slot string name query last access cache and check that it was not deleted slot slot last access if name slot string key slot was deleted 0 return slot int hash name hash code slot slots this slots get stable local reference int i get slot position slots name hash if i 0 return null slot slots i update cache here string key equals name holds but it can be that slot string key name to make last name cache work need to change the key slot string key name last access slot return slot getnamedslot lastaccess stringkey wasdeleted hashcode getslotposition stringkey stringkey stringkey lastaccess private slot get slot string id int index slot slots this slots get local copy int i get slot position slots id index return i 0 null slots i getslot getslotposition private static int get slot position slot slots string id int index if slots null int start index 0x7fffffff slots length int i start do slot slot slots i if slot null break if slot removed slot int key index slot string key id id null id equals slot string key return i if i slots length i 0 while i start return 1 getslotposition intkey stringkey stringkey add a new slot to the hash table this method must be synchronized since it is altering the hash table itself note that we search again for the slot to set since another thread could have added the given property or caused the table to grow while this thread was searching private synchronized slot add slot string id int index slot new slot if is sealed string str id null id integer to string index throw context report runtime error1 msg add sealed str if slots null slots new slot 5 return add slot impl id index new slot addslot newslot issealed tostring reportruntimeerror1 addslotimpl newslot must be inside synchronized this private slot add slot impl string id int index slot new slot int start index 0x7fffffff slots length int i start for slot slot slots i if slot null slot removed if 4 count 1 3 slots length grow return add slot impl id index new slot slot new slot null new slot new slot slot string key id slot int key index slots i slot count return slot if slot int key index slot string key id id null id equals slot string key return slot if i slots length i 0 if i start slots should never be full or bug in grow code throw new illegal state exception addslotimpl newslot addslotimpl newslot newslot newslot stringkey intkey intkey stringkey stringkey illegalstateexception remove a slot from the hash table this method must be synchronized since it is altering the hash table itself we might be able to optimize this more but deletes are not common private synchronized void remove slot string name int index if is sealed string str name null name integer to string index throw context report runtime error1 msg remove sealed str int i get slot position slots name index if i 0 slot slot slots i if slot attributes permanent 0 mark the slot as removed to handle a case when another thread manages to put just removed slot into last access cache slot was deleted byte 1 if slot last access last access removed count if count 0 slots i removed else with no slots it is ok to mark with null slots i null removeslot issealed tostring reportruntimeerror1 getslotposition lastaccess wasdeleted lastaccess lastaccess must be inside synchronized this private void grow slot new slots new slot slots length 2 1 for int j slots length 1 j 0 j slot slot slots j if slot null slot removed continue int k slot int key 0x7fffffff new slots length while new slots k null if k new slots length k 0 the end of the synchronized statement will cause the memory writes to be propagated on a multiprocessor machine we want to make sure that the new table is prepared to be read xxx causes the this pointer to be null in calling stack frames on the ms jvm synchronized slot new slots k slot slots new slots newslots intkey newslots newslots newslots newslots newslots object get ids boolean get all slot s slots object a script runtime empty args if s null return a int c 0 for int i 0 i s length i slot slot s i if slot null slot removed continue if get all slot attributes dontenum 0 if c 0 a new object s length i a c slot string key null object slot string key new integer slot int key if c a length return a object result new object c system arraycopy a 0 result 0 c return result getids getall scriptruntime emptyargs getall stringkey stringkey intkey private synchronized void write object object output stream out throws io exception out default write object int n count if n 0 n 1 count slot s slots if s null if n 0 kit code bug out write int 0 else out write int s length for int i 0 n 0 i slot slot s i if slot null slot removed n out write object slot writeobject objectoutputstream ioexception defaultwriteobject codebug writeint writeint writeobject private void read object object input stream in throws io exception class not found exception in default read object last access removed int capacity in read int if capacity 0 slots new slot capacity int n count boolean was sealed false if n 0 n 1 n was sealed true count 0 for int i 0 i n i slot s slot in read object add slot impl s string key s int key s if was sealed count 1 count readobject objectinputstream ioexception classnotfoundexception defaultreadobject lastaccess readint wassealed wassealed readobject addslotimpl stringkey intkey wassealed private void read object object input stream in throws io exception class not found exception in default read object if string key null int key string key hash code readobject objectinputstream ioexception classnotfoundexception defaultreadobject stringkey intkey stringkey hashcode static void init scriptable scope boolean sealed native number obj new native number 0 0 obj export asjs class max prototype id scope sealed nativenumber nativenumber exportasjsclass max_prototype_id private native number double number double value number nativenumber doublevalue public string get class name return number getclassname protected void fill constructor properties id function object ctor final int attr scriptable object dontenum scriptable object permanent scriptable object readonly ctor define property nan script runtime na nobj attr ctor define property positive infinity script runtime wrap number double positive infinity attr ctor define property negative infinity script runtime wrap number double negative infinity attr ctor define property max value script runtime wrap number double max value attr ctor define property min value script runtime wrap number double min value attr super fill constructor properties ctor fillconstructorproperties idfunctionobject scriptableobject scriptableobject scriptableobject defineproperty scriptruntime nanobj defineproperty positive_infinity scriptruntime wrapnumber positive_infinity defineproperty negative_infinity scriptruntime wrapnumber negative_infinity defineproperty max_value scriptruntime wrapnumber max_value defineproperty min_value scriptruntime wrapnumber min_value fillconstructorproperties protected void init prototype id int id string s int arity switch id case id constructor arity 1 s constructor break case id tostring arity 1 s to string break case id tolocalestring arity 1 s to locale string break case id tosource arity 0 s to source break case id valueof arity 0 s value of break case id tofixed arity 1 s to fixed break case id toexponential arity 1 s to exponential break case id toprecision arity 1 s to precision break default throw new illegal argument exception string value of id init prototype method number tag id s arity initprototypeid id_constructor id_tostring tostring id_tolocalestring tolocalestring id_tosource tosource id_valueof valueof id_tofixed tofixed id_toexponential toexponential id_toprecision toprecision illegalargumentexception valueof initprototypemethod number_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag number tag return super exec id call f cx scope this obj args int id f method id if id id constructor double val args length 1 script runtime to number args 0 0 0 if this obj null new number val creates a new number object return new native number val number val converts val to a number value return script runtime wrap number val the rest of number prototype methods require this obj to be number if this obj instanceof native number throw incompatible call error f double value native number this obj double value switch id case id tostring case id tolocalestring to locale string is just an alias for to string for now int base args length 0 10 script runtime to int32 args 0 return script runtime number to string value base case id tosource return new number script runtime to string value case id valueof return script runtime wrap number value case id tofixed return num to value args d toa dtostr fixed d toa dtostr fixed 20 0 case id toexponential return num to value args d toa dtostr standard exponential d toa dtostr exponential 0 1 case id toprecision return num to value args d toa dtostr standard d toa dtostr precision 1 0 default throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag number_tag execidcall thisobj methodid id_constructor scriptruntime tonumber thisobj nativenumber scriptruntime wrapnumber thisobj thisobj nativenumber incompatiblecallerror nativenumber thisobj doublevalue id_tostring id_tolocalestring tolocalestring tostring scriptruntime toint32 scriptruntime numbertostring id_tosource scriptruntime tostring id_valueof scriptruntime wrapnumber id_tofixed num_to dtoa dtostr_fixed dtoa dtostr_fixed id_toexponential num_to dtoa dtostr_standard_exponential dtoa dtostr_exponential id_toprecision num_to dtoa dtostr_standard dtoa dtostr_precision illegalargumentexception valueof public string to string return script runtime number to string double value 10 tostring scriptruntime numbertostring doublevalue private static string num to double val object args int zero arg mode int one arg mode int precision min int precision offset int precision if args length 0 precision 0 one arg mode zero arg mode else we allow a larger range of precision than ecma requires this is permitted by ecma precision script runtime to int32 args 0 if precision precision min precision max precision string msg script runtime get message1 msg bad precision script runtime to string args 0 throw script runtime construct error range error msg string buffer sb new string buffer d toa js dtostr sb one arg mode precision precision offset val return sb to string num_to zeroargmode oneargmode precisionmin precisionoffset oneargmode zeroargmode scriptruntime toint32 precisionmin max_precision scriptruntime getmessage1 scriptruntime tostring scriptruntime constructerror rangeerror stringbuffer stringbuffer dtoa js_dtostr oneargmode precisionoffset tostring protected int find prototype id string s int id generated last update 2004 03 17 13 41 35 cet l0 id 0 string x null int c l switch s length case 7 c s char at 0 if c t x to fixed id id tofixed else if c v x value of id id valueof break l case 8 c s char at 3 if c o x to source id id tosource else if c t x to string id id tostring break l case 11 c s char at 0 if c c x constructor id id constructor else if c t x to precision id id toprecision break l case 13 x to exponential id id toexponential break l case 14 x to locale string id id tolocalestring break l if x null x s x equals s id 0 generated return id findprototypeid charat tofixed id_tofixed valueof id_valueof charat tosource id_tosource tostring id_tostring charat id_constructor toprecision id_toprecision toexponential id_toexponential tolocalestring id_tolocalestring public class datatypes 009 extends live connect test public datatypes 009 super datatypes_009 liveconnecttest datatypes_009 public static void main string args datatypes 009 test new datatypes 009 test start datatypes_009 datatypes_009 public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class global eval var dt new dt setuptestenvironment setuptestenvironment datatypeclass public void execute test do array test dt static get char array true do array test dt pub static array char true do array test dt get char array true do array test dt pub array char false executetest doarraytest staticgetchararray doarraytest pub_static_array_char doarraytest getchararray doarraytest pub_array_char assign a java array to a java script variable in the following ways ul li call a static method li get the value of a static field li call an instance method li get the value of an instance field param command the command to eval to get the array public void do array test string command boolean should equal char array data type class pub static array char char js array int jsarray length try assign the array to a java script variable global eval var js array command get the js array object which should be the java object js array char global get member js array get the length of the array from java script jsarray length double global eval js array length int value iterate through js array in java script verify that the type and value of each object in the array is correct for int i 0 i jsarray length i verify that the array item is the same object as in the original array double item double global eval js array i add test case js array command global eval js array i equals array i true item equals new double array i catch exception e e print stack trace file exception e to string jsarray length 0 js array null verify that js array is the same as the original array add test case js array command js array global get member js array js array array should equal true false js array array javascript doarraytest shouldequal datatypeclass pub_static_array_char jsarray jsarray_length javascript jsarray jsarray jsarray getmember jsarray javascript jsarray_length jsarray intvalue jsarray javascript jsarray_length jsarray addtestcase jsarray jsarray printstacktrace tostring jsarray_length jsarray jsarray addtestcase jsarray jsarray getmember jsarray jsarray shouldequal jsarray create a new context note that the context must be associated with a thread before it can be used to execute a script see enter see call context action public context set language version version default optimization level codegen class null 0 1 maximum interpreter stack depth integer max value contextaction setlanguageversion version_default optimizationlevel codegenclass maximuminterpreterstackdepth max_value get the current context the current context is per thread this method looks up the context associated with the current thread p return the context associated with the current thread or null if no context is associated with the current thread see org mozilla javascript context enter see org mozilla javascript context exit public static context get current context object helper vm bridge instance get thread context helper return vm bridge instance get context helper getcurrentcontext vmbridge getthreadcontexthelper vmbridge getcontext get a context associated with the current thread creating one if need be the context stores the execution state of the java script engine so it is required that the context be entered before execution may begin once a thread has entered a context then get current context may be called to find the context that is associated with the current thread p calling code enter code will return either the context currently associated with the thread or will create a new context and associate it with the current thread each call to code enter code must have a matching call to code exit code for example pre context cx context enter try cx evaluate string finally context exit pre instead of using tt enter tt tt exit tt pair consider using link call context action which guarantees proper association of context instances with the current thread and is faster with this method the above example becomes pre context call new context action public object run context cx cx evaluate string return null pre return a context associated with the current thread see get current context see exit see call context action public static context enter return enter null javascript getcurrentcontext evaluatestring contextaction contextaction evaluatestring getcurrentcontext contextaction get a context associated with the current thread using the given context if need be p the same as code enter code except that code cx code is associated with the current thread and returned if the current thread has no associated context and code cx code is not associated with any other thread param cx a context to associate with the thread if possible return a context associated with the current thread see enter see call context action see context factory call context action public static context enter context cx return enter cx context factory get global contextaction contextfactory contextaction contextfactory getglobal static final context enter context cx context factory factory object helper vm bridge instance get thread context helper context old vm bridge instance get context helper if old null if cx null cx old cx enter count 0 the suplied context must be the context for the current thread if it is already entered throw new illegal argument exception cannot enter context active on another thread if old factory null context with associated factory will be released automatically and does not need to change enter count return old if old sealed on sealed mutation cx old else if cx null cx factory make context else if cx sealed on sealed mutation if cx enter count 0 cx factory null throw new illegal state exception if cx creation event was sent cx creation event was sent true factory on context created cx if old null vm bridge instance set context helper cx cx enter count return cx contextfactory vmbridge getthreadcontexthelper vmbridge getcontext entercount illegalargumentexception entercount onsealedmutation makecontext onsealedmutation entercount illegalstateexception creationeventwassent creationeventwassent oncontextcreated vmbridge setcontext entercount exit a block of code requiring a context calling code exit code will remove the association between the current thread and a context if the prior call to code enter code on this thread newly associated a context with this thread once the current thread no longer has an associated context it cannot be used to execute java script until it is again associated with a context see org mozilla javascript context enter see call context action see context factory call context action public static void exit exit context factory get global javascript contextaction contextfactory contextaction contextfactory getglobal static void exit context factory factory object helper vm bridge instance get thread context helper context cx vm bridge instance get context helper if cx null throw new illegal state exception calling context exit without previous context enter if cx factory null context with associated factory will be released automatically and does not need to change enter count return if cx enter count 1 kit code bug if cx sealed on sealed mutation cx enter count if cx enter count 0 vm bridge instance set context helper null factory on context released cx contextfactory vmbridge getthreadcontexthelper vmbridge getcontext illegalstateexception entercount entercount codebug onsealedmutation entercount entercount vmbridge setcontext oncontextreleased call link context action run context cx using the context instance associated with the current thread if no context is associated with the thread then tt context factory get global make context tt will be called to construct new context instance the instance will be temporary associated with the thread during call to link context action run context return the result of link context action run context public static object call context action action return call context factory get global action contextaction contextfactory getglobal makecontext contextaction contextaction contextaction contextfactory getglobal call link callable call context cx scriptable scope scriptable this obj object args using the context instance associated with the current thread if no context is associated with the thread then link context factory make context will be called to construct new context instance the instance will be temporary associated with the thread during call to link context action run context p it is allowed to use null for tt factory tt argument in which case the factory associated with the scope will be used to create new context instances see context factory call context action public static object call context factory factory callable callable scriptable scope scriptable this obj object args if factory null factory context factory get global object helper vm bridge instance get thread context helper context cx vm bridge instance get context helper if cx null object result if cx factory null result callable call cx scope this obj args else context was associated with the thread via context enter set factory to make context enter exit to be no op during call cx factory factory try result callable call cx scope this obj args finally cx factory null return result cx prepare new context factory helper try return callable call cx scope this obj args finally release context helper cx thisobj contextfactory makecontext contextaction contextfactory contextaction contextfactory thisobj contextfactory getglobal vmbridge getthreadcontexthelper vmbridge getcontext thisobj thisobj preparenewcontext thisobj releasecontext the method implements links context factory call context action logic static object call context factory factory context action action object helper vm bridge instance get thread context helper context cx vm bridge instance get context helper if cx null if cx factory null return action run cx else cx factory factory try return action run cx finally cx factory null cx prepare new context factory helper try return action run cx finally release context helper cx contextfactory contextaction contextfactory contextaction vmbridge getthreadcontexthelper vmbridge getcontext preparenewcontext releasecontext private static context prepare new context context factory factory object context helper context cx factory make context if cx factory null cx enter count 0 throw new illegal state exception factory make context returned context instance already associated with some thread cx factory factory factory on context created cx if factory is sealed cx is sealed cx seal null vm bridge instance set context context helper cx return cx preparenewcontext contextfactory contexthelper makecontext entercount illegalstateexception makecontext oncontextcreated issealed issealed vmbridge setcontext contexthelper private static void release context object context helper context cx vm bridge instance set context context helper null try cx factory on context released cx finally cx factory null releasecontext contexthelper vmbridge setcontext contexthelper oncontextreleased deprecated see context factory add listener context factory listener see context factory get global public static void add context listener context listener listener special workaround for the debugger string dbg org mozilla javascript tools debugger main if dbg equals listener get class get name class cl listener get class class factory class kit class or null org mozilla javascript context factory class sig factory class object args context factory get global try method m cl get method attach to sig m invoke listener args catch exception ex runtime exception rex new runtime exception kit init cause rex ex throw rex return context factory get global add listener listener contextfactory addlistener contextfactory contextfactory getglobal addcontextlistener contextlistener getclass getname getclass factoryclass classornull contextfactory factoryclass contextfactory getglobal getmethod attachto runtimeexception runtimeexception initcause contextfactory getglobal addlistener deprecated see context factory remove listener context factory listener see context factory get global public static void remove context listener context listener listener context factory get global add listener listener contextfactory removelistener contextfactory contextfactory getglobal removecontextlistener contextlistener contextfactory getglobal addlistener return link context factory instance used to create this context or the result of link context factory get global if no factory was used for context creation public final context factory get factory context factory result factory if result null result context factory get global return result contextfactory contextfactory getglobal contextfactory getfactory contextfactory contextfactory getglobal checks if this is a sealed context a sealed context instance does not allow to modify any of its properties and will throw an exception on any such attempt see seal object seal key public final boolean is sealed return sealed sealkey issealed seal this context object so any attempt to modify any of its properties including calling link enter and link exit methods will throw an exception p if tt seal key tt is not null calling link unseal object seal key with the same key unseals the object if tt seal key tt is null unsealing is no longer possible see is sealed see unseal object public final void seal object seal key if sealed on sealed mutation sealed true this seal key seal key sealkey sealkey sealkey issealed sealkey onsealedmutation sealkey sealkey unseal previously sealed context object the tt seal key tt argument should not be null and should match tt seal key tt suplied with the last call to link seal object or an exception will be thrown see is sealed see seal object seal key public final void unseal object seal key if seal key null throw new illegal argument exception if this seal key seal key throw new illegal argument exception if sealed throw new illegal state exception sealed false this seal key null sealkey sealkey issealed sealkey sealkey sealkey illegalargumentexception sealkey sealkey illegalargumentexception illegalstateexception sealkey static void on sealed mutation throw new illegal state exception onsealedmutation illegalstateexception get the current language version p the language version number affects java script semantics as detailed in the overview documentation return an integer that is one of version 1 0 version 1 1 etc public final int get language version return version javascript version_1_0 version_1_1 getlanguageversion set the language version p setting the language version will affect functions and scripts compiled subsequently see the overview documentation for version specific behavior param version the version as specified by version 1 0 version 1 1 etc public void set language version int version if sealed on sealed mutation check language version version object listeners property listeners if listeners null version this version fire property change impl listeners language version property new integer this version new integer version this version version version_1_0 version_1_1 setlanguageversion onsealedmutation checklanguageversion propertylisteners firepropertychangeimpl languageversionproperty public static boolean is valid language version int version switch version case version default case version 1 0 case version 1 1 case version 1 2 case version 1 3 case version 1 4 case version 1 5 case version 1 6 return true return false isvalidlanguageversion version_default version_1_0 version_1_1 version_1_2 version_1_3 version_1_4 version_1_5 version_1_6 public static void check language version int version if is valid language version version return throw new illegal argument exception bad language version version checklanguageversion isvalidlanguageversion illegalargumentexception get the implementation version p the implementation version is of the form pre i name lang ver i code release code i rel num date i pre where i name i is the name of the product i lang ver i is the language version i rel num i is the release number and i date i is the release date for that specific release in the form yyyy mm dd return a string that encodes the product language version release number and date public final string get implementation version xxx probably it would be better to embed this directly into source with special build preprocessing but that would require some ant tweaking and then replacing token in resource files was simpler if implementation version null implementation version script runtime get message0 implementation version return implementation version langver relnum langver relnum getimplementationversion implementationversion implementationversion scriptruntime getmessage0 implementationversion get the current error reporter see org mozilla javascript error reporter public final error reporter get error reporter if error reporter null return default error reporter instance return error reporter errorreporter errorreporter geterrorreporter errorreporter defaulterrorreporter errorreporter change the current error reporter return the previous error reporter see org mozilla javascript error reporter public final error reporter set error reporter error reporter reporter if sealed on sealed mutation if reporter null throw new illegal argument exception error reporter old get error reporter if reporter old return old object listeners property listeners if listeners null fire property change impl listeners error reporter property old reporter this error reporter reporter return old errorreporter errorreporter seterrorreporter errorreporter onsealedmutation illegalargumentexception errorreporter geterrorreporter propertylisteners firepropertychangeimpl errorreporterproperty errorreporter get the current locale returns the default locale if none has been set see java util locale public final locale get locale if locale null locale locale get default return locale getlocale getdefault set the current locale see java util locale public final locale set locale locale loc if sealed on sealed mutation locale result locale locale loc return result setlocale onsealedmutation register an object to receive notifications when a bound property has changed see java beans property change event see remove property change listener java beans property change listener param l the listener public final void add property change listener property change listener l if sealed on sealed mutation property listeners kit add listener property listeners l propertychangeevent removepropertychangelistener propertychangelistener addpropertychangelistener propertychangelistener onsealedmutation propertylisteners addlistener propertylisteners remove an object from the list of objects registered to receive notification of changes to a bounded property see java beans property change event see add property change listener java beans property change listener param l the listener public final void remove property change listener property change listener l if sealed on sealed mutation property listeners kit remove listener property listeners l propertychangeevent addpropertychangelistener propertychangelistener removepropertychangelistener propertychangelistener onsealedmutation propertylisteners removelistener propertylisteners notify any registered listeners that a bounded property has changed see add property change listener java beans property change listener see remove property change listener java beans property change listener see java beans property change listener see java beans property change event param property the bound property param old value the old value param new vale the new value final void fire property change string property object old value object new value object listeners property listeners if listeners null fire property change impl listeners property old value new value addpropertychangelistener propertychangelistener removepropertychangelistener propertychangelistener propertychangelistener propertychangeevent oldvalue newvale firepropertychange oldvalue newvalue propertylisteners firepropertychangeimpl oldvalue newvalue private void fire property change impl object listeners string property object old value object new value for int i 0 i object l kit get listener listeners i if l null break if l instanceof property change listener property change listener pcl property change listener l pcl property change new property change event this property old value new value firepropertychangeimpl oldvalue newvalue getlistener propertychangelistener propertychangelistener propertychangelistener propertychange propertychangeevent oldvalue newvalue report a warning using the error reporter for the current thread param message the warning message to report param source name a string describing the source such as a filename param lineno the starting line number param line source the text of the line may be null param line offset the offset into line source where problem was detected see org mozilla javascript error reporter public static void report warning string message string source name int lineno string line source int line offset context cx context get context cx get error reporter warning message source name lineno line source line offset sourcename linesource lineoffset linesource errorreporter reportwarning sourcename linesource lineoffset getcontext geterrorreporter sourcename linesource lineoffset report a warning using the error reporter for the current thread param message the warning message to report see org mozilla javascript error reporter public static void report warning string message int linep 0 string filename get source position from stack linep context report warning message filename linep 0 null 0 errorreporter reportwarning getsourcepositionfromstack reportwarning report an error using the error reporter for the current thread param message the error message to report param source name a string describing the source such as a filename param lineno the starting line number param line source the text of the line may be null param line offset the offset into line source where problem was detected see org mozilla javascript error reporter public static void report error string message string source name int lineno string line source int line offset context cx get current context if cx null cx get error reporter error message source name lineno line source line offset else throw new evaluator exception message source name lineno line source line offset sourcename linesource lineoffset linesource errorreporter reporterror sourcename linesource lineoffset getcurrentcontext geterrorreporter sourcename linesource lineoffset evaluatorexception sourcename linesource lineoffset report an error using the error reporter for the current thread param message the error message to report see org mozilla javascript error reporter public static void report error string message int linep 0 string filename get source position from stack linep context report error message filename linep 0 null 0 errorreporter reporterror getsourcepositionfromstack reporterror report a runtime error using the error reporter for the current thread param message the error message to report param source name a string describing the source such as a filename param lineno the starting line number param line source the text of the line may be null param line offset the offset into line source where problem was detected return a runtime exception that will be thrown to terminate the execution of the script see org mozilla javascript error reporter public static evaluator exception report runtime error string message string source name int lineno string line source int line offset context cx get current context if cx null return cx get error reporter runtime error message source name lineno line source line offset else throw new evaluator exception message source name lineno line source line offset sourcename linesource lineoffset linesource errorreporter evaluatorexception reportruntimeerror sourcename linesource lineoffset getcurrentcontext geterrorreporter runtimeerror sourcename linesource lineoffset evaluatorexception sourcename linesource lineoffset static evaluator exception report runtime error0 string message id string msg script runtime get message0 message id return report runtime error msg evaluatorexception reportruntimeerror0 messageid scriptruntime getmessage0 messageid reportruntimeerror static evaluator exception report runtime error1 string message id object arg1 string msg script runtime get message1 message id arg1 return report runtime error msg evaluatorexception reportruntimeerror1 messageid scriptruntime getmessage1 messageid reportruntimeerror static evaluator exception report runtime error2 string message id object arg1 object arg2 string msg script runtime get message2 message id arg1 arg2 return report runtime error msg evaluatorexception reportruntimeerror2 messageid scriptruntime getmessage2 messageid reportruntimeerror static evaluator exception report runtime error3 string message id object arg1 object arg2 object arg3 string msg script runtime get message3 message id arg1 arg2 arg3 return report runtime error msg evaluatorexception reportruntimeerror3 messageid scriptruntime getmessage3 messageid reportruntimeerror static evaluator exception report runtime error4 string message id object arg1 object arg2 object arg3 object arg4 string msg script runtime get message4 message id arg1 arg2 arg3 arg4 return report runtime error msg evaluatorexception reportruntimeerror4 messageid scriptruntime getmessage4 messageid reportruntimeerror report a runtime error using the error reporter for the current thread param message the error message to report see org mozilla javascript error reporter public static evaluator exception report runtime error string message int linep 0 string filename get source position from stack linep return context report runtime error message filename linep 0 null 0 errorreporter evaluatorexception reportruntimeerror getsourcepositionfromstack reportruntimeerror initialize the standard objects creates instances of the standard objects and their constructors object string number date etc setting up scope to act as a global object as in ecma 15 1 p this method must be called to initialize a scope before scripts can be evaluated in that scope p this method does not affect the context it is called upon return the initialized scope public final scriptable object init standard objects return init standard objects null false scriptableobject initstandardobjects initstandardobjects initialize the standard objects creates instances of the standard objects and their constructors object string number date etc setting up scope to act as a global object as in ecma 15 1 p this method must be called to initialize a scope before scripts can be evaluated in that scope p this method does not affect the context it is called upon param scope the scope to initialize or null in which case a new object will be created to serve as the scope return the initialized scope the method returns the value of the scope argument if it is not null or newly allocated scope object which is an instance link scriptable object public final scriptable init standard objects scriptable object scope return init standard objects scope false scriptableobject initstandardobjects scriptableobject initstandardobjects initialize the standard objects creates instances of the standard objects and their constructors object string number date etc setting up scope to act as a global object as in ecma 15 1 p this method must be called to initialize a scope before scripts can be evaluated in that scope p this method does not affect the context it is called upon p this form of the method also allows for creating sealed standard objects an object that is sealed cannot have properties added changed or removed this is useful to create a superglobal that can be shared among several top level objects note that sealing is not allowed in the current ecma iso language specification but is likely for the next version param scope the scope to initialize or null in which case a new object will be created to serve as the scope param sealed whether or not to create sealed standard objects that cannot be modified return the initialized scope the method returns the value of the scope argument if it is not null or newly allocated scope object since 1 4r3 public scriptable object init standard objects scriptable object scope boolean sealed return script runtime init standard objects this scope sealed scriptableobject initstandardobjects scriptableobject scriptruntime initstandardobjects get the singleton object that represents the java script undefined value public static object get undefined value return undefined instance javascript getundefinedvalue evaluate a java script source string the provided source name and line number are used for error messages and for producing debug information param scope the scope to execute in param source the java script source param source name a string describing the source such as a filename param lineno the starting line number param security domain an arbitrary object that specifies security information about the origin or owner of the script for implementations that don t care about security this value may be null return the result of evaluating the string see org mozilla javascript security controller public final object evaluate string scriptable scope string source string source name int lineno object security domain script script compile string source source name lineno security domain if script null return script exec this scope else return null javascript javascript sourcename securitydomain securitycontroller evaluatestring sourcename securitydomain compilestring sourcename securitydomain evaluate a reader as java script source all characters of the reader are consumed param scope the scope to execute in param in the reader to get java script source from param source name a string describing the source such as a filename param lineno the starting line number param security domain an arbitrary object that specifies security information about the origin or owner of the script for implementations that don t care about security this value may be null return the result of evaluating the source exception io exception if an io exception was generated by the reader public final object evaluate reader scriptable scope reader in string source name int lineno object security domain throws io exception script script compile reader scope in source name lineno security domain if script null return script exec this scope else return null javascript javascript sourcename securitydomain ioexception ioexception evaluatereader sourcename securitydomain ioexception compilereader sourcename securitydomain check whether a string is ready to be compiled p string is compilable unit is intended to support interactive compilation of javascript if compiling the string would result in an error that might be fixed by appending more source this method returns false in every other case it returns true p interactive shells may accumulate source lines using this method after each new line is appended to check whether the statement being entered is complete param source the source buffer to check return whether the source is ready for compilation since 1 4 release 2 public final boolean string is compilable unit string source boolean errorseen false compiler environs compiler env new compiler environs compiler env init from context this no source name or source text manager because we re just going to throw away the result compiler env set generating source false parser p new parser compiler env default error reporter instance try p parse source null 1 catch evaluator exception ee errorseen true return false only if an error occurred as a result of reading past the end of the file i e if the source could be fixed by appending more source if errorseen p eof return false else return true stringiscompilableunit stringiscompilableunit compilerenvirons compilerenv compilerenvirons compilerenv initfromcontext compilerenv setgeneratingsource compilerenv defaulterrorreporter evaluatorexception deprecated see compile reader reader in string source name int lineno object security domain public final script compile reader scriptable scope reader in string source name int lineno object security domain throws io exception return compile reader in source name lineno security domain compilereader sourcename securitydomain compilereader sourcename securitydomain ioexception compilereader sourcename securitydomain compiles the source in the given reader p returns a script that may later be executed will consume all the source in the reader param in the input reader param source name a string describing the source such as a filename param lineno the starting line number for reporting errors param security domain an arbitrary object that specifies security information about the origin or owner of the script for implementations that don t care about security this value may be null return a script that may later be executed exception io exception if an io exception was generated by the reader see org mozilla javascript script public final script compile reader reader in string source name int lineno object security domain throws io exception if lineno 0 for compatibility illegal argument exception can not be thrown here lineno 0 return script compile impl null in null source name lineno security domain false null null sourcename securitydomain ioexception ioexception compilereader sourcename securitydomain ioexception illegalargumentexception compileimpl sourcename securitydomain compiles the source in the given string p returns a script that may later be executed param source the source string param source name a string describing the source such as a filename param lineno the starting line number for reporting errors param security domain an arbitrary object that specifies security information about the origin or owner of the script for implementations that don t care about security this value may be null return a script that may later be executed see org mozilla javascript script public final script compile string string source string source name int lineno object security domain if lineno 0 for compatibility illegal argument exception can not be thrown here lineno 0 return compile string source null null source name lineno security domain sourcename securitydomain compilestring sourcename securitydomain illegalargumentexception compilestring sourcename securitydomain final script compile string string source interpreter compiler error reporter compilation error reporter string source name int lineno object security domain try return script compile impl null null source source name lineno security domain false compiler compilation error reporter catch io exception ex should not happen when dealing with source as string throw new runtime exception compilestring errorreporter compilationerrorreporter sourcename securitydomain compileimpl sourcename securitydomain compilationerrorreporter ioexception runtimeexception compile a java script function p the function source must be a function definition as defined by ecma e g function f a return a param scope the scope to compile relative to param source the function definition source param source name a string describing the source such as a filename param lineno the starting line number param security domain an arbitrary object that specifies security information about the origin or owner of the script for implementations that don t care about security this value may be null return a function that may later be called see org mozilla javascript function public final function compile function scriptable scope string source string source name int lineno object security domain return compile function scope source null null source name lineno security domain javascript sourcename securitydomain compilefunction sourcename securitydomain compilefunction sourcename securitydomain final function compile function scriptable scope string source interpreter compiler error reporter compilation error reporter string source name int lineno object security domain try return function compile impl scope null source source name lineno security domain true compiler compilation error reporter catch io exception ioe should never happen because we just made the reader from a string throw new runtime exception compilefunction errorreporter compilationerrorreporter sourcename securitydomain compileimpl sourcename securitydomain compilationerrorreporter ioexception runtimeexception decompile the script p the canonical source of the script is returned param script the script to decompile param indent the number of spaces to indent the result return a string representing the script source public final string decompile script script script int indent native function script impl native function script return script impl decompile indent 0 decompilescript nativefunction scriptimpl nativefunction scriptimpl decompile a java script function p decompiles a previously compiled java script function object to canonical source p returns function body of native code if no decompilation information is available param fun the java script function to decompile param indent the number of spaces to indent the result return a string representing the function source public final string decompile function function fun int indent if fun instanceof base function return base function fun decompile indent 0 else return function fun get class name n t native code n n javascript javascript javascript decompilefunction basefunction basefunction getclassname decompile the body of a java script function p decompiles the body a previously compiled java script function object to canonical source omitting the function header and trailing brace returns native code if no decompilation information is available param fun the java script function to decompile param indent the number of spaces to indent the result return a string representing the function body source public final string decompile function body function fun int indent if fun instanceof base function base function bf base function fun return bf decompile indent decompiler only body flag alert not sure what the right response here is return native code n javascript javascript javascript decompilefunctionbody basefunction basefunction basefunction only_body_flag create a new java script object equivalent to evaluating new object param scope the scope to search for the constructor and to evaluate against return the new object public final scriptable new object scriptable scope return new object scope object script runtime empty args javascript newobject newobject scriptruntime emptyargs create a new java script object by executing the named constructor the call code new object scope foo code is equivalent to evaluating new foo param scope the scope to search for the constructor and to evaluate against param constructor name the name of the constructor to call return the new object public final scriptable new object scriptable scope string constructor name return new object scope constructor name script runtime empty args javascript newobject constructorname newobject constructorname newobject constructorname scriptruntime emptyargs creates a new java script object by executing the named constructor searches code scope code for the named constructor calls it with the given arguments and returns the result p the code pre object args a b new object scope foo args pre is equivalent to evaluating new foo a b assuming that the foo constructor has been defined in code scope code param scope the scope to search for the constructor and to evaluate against param constructor name the name of the constructor to call param args the array of arguments for the constructor return the new object public final scriptable new object scriptable scope string constructor name object args scope scriptable object get top level scope scope function ctor script runtime get existing ctor this scope constructor name if args null args script runtime empty args return ctor construct this scope args javascript newobject constructorname newobject constructorname scriptableobject gettoplevelscope scriptruntime getexistingctor constructorname scriptruntime emptyargs create an array with a specified initial length p param scope the scope to create the object in param length the initial length java script arrays may have additional properties added dynamically return the new array object public final scriptable new array scriptable scope int length native array result new native array length script runtime set object proto and parent result scope return result javascript newarray nativearray nativearray scriptruntime setobjectprotoandparent create an array with a set of initial elements param scope the scope to create the object in param elements the initial elements each object in this array must be an acceptable java script type and type of array should be exactly object not some object subclass return the new array object public final scriptable new array scriptable scope object elements if elements get class get component type script runtime object class throw new illegal argument exception native array result new native array elements script runtime set object proto and parent result scope return result javascript someobjectsubclass newarray getclass getcomponenttype scriptruntime objectclass illegalargumentexception nativearray nativearray scriptruntime setobjectprotoandparent get the elements of a java script array p if the object defines a length property convertible to double number then the number is converted uint32 value as defined in ecma 9 6 and java array of that size is allocated the array is initialized with the values obtained by calling get on object for each value of i in 0 length 1 if there is not a defined value for a property the undefined value is used to initialize the corresponding element in the array the java array is then returned if the object doesn t define a length property or it is not a number empty array is returned param object the java script array or array like object return a java array of objects since 1 4 release 2 public final object get elements scriptable object return script runtime get array elements object javascript javascript getelements scriptruntime getarrayelements convert the value to a java script boolean value p see ecma 9 2 param value a java script value return the corresponding boolean value converted using the ecma rules public static boolean to boolean object value return script runtime to boolean value javascript javascript toboolean scriptruntime toboolean convert the value to a java script number value p returns a java double for the java script number p see ecma 9 3 param value a java script value return the corresponding double value converted using the ecma rules public static double to number object value return script runtime to number value javascript javascript javascript tonumber scriptruntime tonumber convert the value to a java script string value p see ecma 9 8 p param value a java script value return the corresponding string value converted using the ecma rules public static string to string object value return script runtime to string value javascript javascript tostring scriptruntime tostring convert the value to an java script object value p note that a scope must be provided to look up the constructors for number boolean and string p see ecma 9 9 p additionally arbitrary java objects and classes will be wrapped in a scriptable object with its java fields and methods reflected as java script properties of the object param value any java object param scope global scope containing constructors for number boolean and string return new java script object public static scriptable to object object value scriptable scope return script runtime to object scope value javascript javascript javascript toobject scriptruntime toobject deprecated see to object object scriptable public static scriptable to object object value scriptable scope class static type return script runtime to object scope value toobject toobject statictype scriptruntime toobject convenient method to convert java value to its closest representation in java script p if value is an instance of string number boolean function or scriptable it is returned as it and will be treated as the corresponding java script type of string number boolean function and object p note that for number instances during any arithmetic operation in java script the engine will always use the result of tt number double value tt resulting in a precision loss if the number can not fit into double p if value is an instance of character it will be converted to string of length 1 and its java script type will be string p the rest of values will be wrapped as live connect objects by calling link wrap factory wrap context cx scriptable scope object obj class static type as in pre context cx context get current context return cx get wrap factory wrap cx scope value null pre param value any java object param scope top scope object return value suitable to pass to any api that takes java script values public static object java tojs object value scriptable scope if value instanceof string value instanceof number value instanceof boolean value instanceof scriptable return value else if value instanceof character return string value of character value char value else context cx context get context return cx get wrap factory wrap cx scope value null javascript javascript javascript doublevalue javascript liveconnect wrapfactory statictype getcurrentcontext getwrapfactory javascript javatojs valueof charvalue getcontext getwrapfactory convert a java script value into the desired type uses the semantics defined with live connect3 and throws an illegal argument exception if the conversion cannot be performed param value the java script value to convert param desired type the java type to convert to primitive java types are represented using the type fields in the corresponding wrapper class in java lang return the converted value throws evaluator exception if the conversion cannot be performed public static object js to java object value class desired type throws evaluator exception return native java object coerce type impl desired type value javascript liveconnect3 javascript desiredtype evaluatorexception jstojava desiredtype evaluatorexception nativejavaobject coercetypeimpl desiredtype deprecated see js to java object class throws illegal argument exception if the conversion cannot be performed note that link js to java object class throws link evaluator exception instead public static object to type object value class desired type throws illegal argument exception try return js to java value desired type catch evaluator exception ex illegal argument exception ex2 new illegal argument exception ex get message kit init cause ex2 ex throw ex2 jstojava illegalargumentexception jstojava evaluatorexception totype desiredtype illegalargumentexception jstojava desiredtype evaluatorexception illegalargumentexception illegalargumentexception getmessage initcause rethrow the exception wrapping it as the script runtime exception unless the exception is instance of link ecma error or link evaluator exception it will be wrapped as link wrapped exception a subclass of link evaluator exception the resulting exception object always contains source name and line number of script that triggered exception p this method always throws an exception its return value is provided only for convenience to allow a usage like pre throw context throw as script runtime ex ex pre to indicate that code after the method is unreachable throws evaluator exception throws ecma error public static runtime exception throw as script runtime ex throwable e while e instanceof invocation target exception e invocation target exception e get target exception special handling of error so scripts would not catch them if e instanceof error throw error e if e instanceof rhino exception throw rhino exception e throw new wrapped exception e ecmaerror evaluatorexception wrappedexception evaluatorexception throwasscriptruntimeex evaluatorexception ecmaerror runtimeexception throwasscriptruntimeex invocationtargetexception invocationtargetexception gettargetexception rhinoexception rhinoexception wrappedexception tell whether debug information is being generated since 1 3 public final boolean is generating debug return generating debug isgeneratingdebug generatingdebug specify whether or not debug information should be generated p setting the generation of debug information on will set the optimization level to zero since 1 3 public final void set generating debug boolean generating debug if sealed on sealed mutation generating debug changed true if generating debug get optimization level 0 set optimization level 0 this generating debug generating debug setgeneratingdebug generatingdebug onsealedmutation generatingdebugchanged generatingdebug getoptimizationlevel setoptimizationlevel generatingdebug generatingdebug tell whether source information is being generated since 1 3 public final boolean is generating source return generating source isgeneratingsource generatingsource specify whether or not source information should be generated p without source information evaluating the to string method on java script functions produces only native code for the body of the function note that code generated without source is not fully ecma conformant since 1 3 public final void set generating source boolean generating source if sealed on sealed mutation this generating source generating source tostring javascript setgeneratingsource generatingsource onsealedmutation generatingsource generatingsource get the current optimization level p the optimization level is expressed as an integer between 1 and 9 since 1 3 public final int get optimization level return optimization level getoptimizationlevel optimizationlevel set the current optimization level p the optimization level is expected to be an integer between 1 and 9 any negative values will be interpreted as 1 and any values greater than 9 will be interpreted as 9 an optimization level of 1 indicates that interpretive mode will always be used levels 0 through 9 indicate that class files may be generated higher optimization levels trade off compile time performance for runtime performance the optimizer level can t be set greater than 1 if the optimizer package doesn t exist at run time param optimization level an integer indicating the level of optimization to perform since 1 3 public final void set optimization level int optimization level if sealed on sealed mutation if optimization level 2 to be compatible with cocoon fork optimization level 1 check optimization level optimization level if codegen class null optimization level 1 this optimization level optimization level optimizationlevel setoptimizationlevel optimizationlevel onsealedmutation optimizationlevel optimizationlevel checkoptimizationlevel optimizationlevel codegenclass optimizationlevel optimizationlevel optimizationlevel public static boolean is valid optimization level int optimization level return 1 optimization level optimization level 9 isvalidoptimizationlevel optimizationlevel optimizationlevel optimizationlevel public static void check optimization level int optimization level if is valid optimization level optimization level return throw new illegal argument exception optimization level outside 1 9 optimization level checkoptimizationlevel optimizationlevel isvalidoptimizationlevel optimizationlevel illegalargumentexception optimizationlevel returns the maximum stack depth in terms of number of call frames allowed in a single invocation of interpreter if the set depth would be exceeded the interpreter will throw an evaluator exception in the script defaults to integer max value the setting only has effect for interpreted functions those compiled with optimization level set to 1 as the interpreter doesn t use the java stack but rather manages its own stack in the heap memory a runaway recursion in interpreted code would eventually consume all available memory and cause out of memory error instead of a stack overflow error limited to only a single thread this setting helps prevent such situations return the current maximum interpreter stack depth public final int get maximum interpreter stack depth return maximum interpreter stack depth evaluatorexception max_value outofmemoryerror stackoverflowerror getmaximuminterpreterstackdepth maximuminterpreterstackdepth sets the maximum stack depth in terms of number of call frames allowed in a single invocation of interpreter if the set depth would be exceeded the interpreter will throw an evaluator exception in the script defaults to integer max value the setting only has effect for interpreted functions those compiled with optimization level set to 1 as the interpreter doesn t use the java stack but rather manages its own stack in the heap memory a runaway recursion in interpreted code would eventually consume all available memory and cause out of memory error instead of a stack overflow error limited to only a single thread this setting helps prevent such situations param max the new maximum interpreter stack depth throws illegal state exception if this context s optimization level is not 1 throws illegal argument exception if the new depth is not at least 1 public final void set maximum interpreter stack depth int max if sealed on sealed mutation if optimization level 1 throw new illegal state exception cannot set maximum interpreter stack depth when optimization level 1 if max 1 throw new illegal argument exception cannot set maximum interpreter stack depth to less than 1 maximum interpreter stack depth max evaluatorexception max_value outofmemoryerror stackoverflowerror illegalstateexception illegalargumentexception setmaximuminterpreterstackdepth onsealedmutation optimizationlevel illegalstateexception maximuminterpreterstackdepth optimizationlevel illegalargumentexception maximuminterpreterstackdepth maximuminterpreterstackdepth set the security controller for this context p security controller may only be set if it is currently null and link security controller has global is tt false tt otherwise a security exception is thrown param controller a security controller object throws security exception if there is already a security controller object for this context or globally installed see security controller init global security controller controller see security controller has global public final void set security controller security controller controller if sealed on sealed mutation if controller null throw new illegal argument exception if security controller null throw new security exception can not overwrite existing security controller object if security controller has global throw new security exception can not overwrite existing global security controller object security controller controller securitycontroller securitycontroller hasglobal securityexception securitycontroller securityexception securitycontroller securitycontroller initglobal securitycontroller securitycontroller hasglobal setsecuritycontroller securitycontroller onsealedmutation illegalargumentexception securitycontroller securityexception securitycontroller securitycontroller hasglobal securityexception securitycontroller securitycontroller set the live connect access filter for this context p link class shutter may only be set if it is currently null otherwise a security exception is thrown param shutter a class shutter object throws security exception if there is already a class shutter object for this context public final void set class shutter class shutter shutter if sealed on sealed mutation if shutter null throw new illegal argument exception if class shutter null throw new security exception cannot overwrite existing class shutter object class shutter shutter liveconnect classshutter securityexception classshutter securityexception classshutter setclassshutter classshutter onsealedmutation illegalargumentexception classshutter securityexception classshutter classshutter final class shutter get class shutter return class shutter classshutter getclassshutter classshutter get a value corresponding to a key p since the context is associated with a thread it can be used to maintain values that can be later retrieved using the current thread p note that the values are maintained with the context so if the context is disassociated from the thread the values cannot be retreived also if private data is to be maintained in this manner the key should be a java lang object whose reference is not divulged to untrusted code param key the key used to lookup the value return a value previously stored using put thread local public final object get thread local object key if hashtable null return null return hashtable get key putthreadlocal getthreadlocal put a value that can later be retrieved using a given key p param key the key used to index the value param value the value to save public final void put thread local object key object value if sealed on sealed mutation if hashtable null hashtable new hashtable hashtable put key value putthreadlocal onsealedmutation remove values from thread local storage param key the key for the entry to remove since 1 5 release 2 public final void remove thread local object key if sealed on sealed mutation if hashtable null return hashtable remove key removethreadlocal onsealedmutation deprecated see feature dynamic scope see has feature int public final boolean has compile functions with dynamic scope return compile functions with dynamic scope flag feature_dynamic_scope hasfeature hascompilefunctionswithdynamicscope compilefunctionswithdynamicscopeflag deprecated see feature dynamic scope see has feature int public final void set compile functions with dynamic scope boolean flag if sealed on sealed mutation compile functions with dynamic scope flag flag feature_dynamic_scope hasfeature setcompilefunctionswithdynamicscope onsealedmutation compilefunctionswithdynamicscopeflag deprecated see class cache get scriptable see class cache set caching enabled boolean public static void set caching enabled boolean caching enabled classcache classcache setcachingenabled setcachingenabled cachingenabled set a wrap factory for this context p the wrap factory allows custom object wrapping behavior for java object manipulated with java script see wrap factory since 1 5 release 4 public final void set wrap factory wrap factory wrap factory if sealed on sealed mutation if wrap factory null throw new illegal argument exception this wrap factory wrap factory wrapfactory wrapfactory javascript wrapfactory setwrapfactory wrapfactory wrapfactory onsealedmutation wrapfactory illegalargumentexception wrapfactory wrapfactory return the current wrap factory or null if none is defined see wrap factory since 1 5 release 4 public final wrap factory get wrap factory if wrap factory null wrap factory new wrap factory return wrap factory wrapfactory wrapfactory wrapfactory getwrapfactory wrapfactory wrapfactory wrapfactory wrapfactory return the current debugger return the debugger or null if none is attached public final debugger get debugger return debugger getdebugger return the debugger context data associated with current context return the debugger data or null if debugger is not attached public final object get debugger context data return debugger data getdebuggercontextdata debuggerdata set the associated debugger param debugger the debugger to be used on callbacks from the engine param context data arbitrary object that debugger can use to store per context data public final void set debugger debugger debugger object context data if sealed on sealed mutation this debugger debugger debugger data context data contextdata setdebugger contextdata onsealedmutation debuggerdata contextdata return debuggable script instance if any associated with the script if callable supports debuggable script implementation the method returns it otherwise null is returned public static debuggable script get debuggable view script script if script instanceof native function return native function script get debuggable view return null debuggablescript debuggablescript debuggablescript getdebuggableview nativefunction nativefunction getdebuggableview controls certain aspects of script semantics should be overwritten to alter default behavior p the default implementation calls link context factory has feature context cx int feature index that allows to customize context behavior without introducing context subclasses link context factory documentation gives an example of has feature implementation param feature index feature index to check return true if the code feature index code feature is turned on see feature non ecma get year see feature member expr as function name see feature reserved keyword as identifier see feature to string as source see feature parent proto proprties see feature e4x see feature dynamic scope see feature strict vars see feature strict eval public boolean has feature int feature index context factory f get factory return f has feature this feature index contextfactory hasfeature featureindex contextfactory hasfeature featureindex featureindex feature_non_ecma_get_year feature_member_expr_as_function_name feature_reserved_keyword_as_identifier feature_to_string_as_source feature_parent_proto_proprties feature_e4x feature_dynamic_scope feature_strict_vars feature_strict_eval hasfeature featureindex contextfactory getfactory hasfeature featureindex get set threshold of executed instructions counter that triggers call to code observe instruction count code when the threshold is zero instruction counting is disabled otherwise each time the run time executes at least the threshold value of script instructions code observe instruction count code will be called public final int get instruction observer threshold return instruction threshold observeinstructioncount observeinstructioncount getinstructionobserverthreshold instructionthreshold public final void set instruction observer threshold int threshold if sealed on sealed mutation if threshold 0 throw new illegal argument exception instruction threshold threshold setinstructionobserverthreshold onsealedmutation illegalargumentexception instructionthreshold allow application to monitor counter of executed script instructions in context subclasses run time calls this when instruction counting is enabled and the counter reaches limit set by code set instruction observer threshold code the method is useful to observe long running scripts and if necessary to terminate them p the instruction counting support is available only for interpreted scripts generated when the optimization level is set to 1 p the default implementation calls link context factory observe instruction count context cx int instruction count that allows to customize context behavior without introducing context subclasses param instruction count amount of script instruction executed since last call to code observe instruction count code throws error to terminate the script see set optimization level int protected void observe instruction count int instruction count context factory f get factory f observe instruction count this instruction count setinstructionobserverthreshold contextfactory observeinstructioncount instructioncount instructioncount observeinstructioncount setoptimizationlevel observeinstructioncount instructioncount contextfactory getfactory observeinstructioncount instructioncount create class loader for generated classes the method calls link context factory create class loader class loader using the result of link get factory public generated class loader create class loader class loader parent context factory f get factory return f create class loader parent contextfactory createclassloader classloader getfactory generatedclassloader createclassloader classloader contextfactory getfactory createclassloader public final class loader get application class loader if application class loader null context factory f get factory class loader loader f get application class loader if loader null class loader thread loader vm bridge instance get current thread class loader if thread loader null kit test if can load rhino classes thread loader thread get context class loader is not cached since its caching prevents it from gc which may lead to a memory leak and hides updates to thread get context class loader return thread loader thread get context class loader can not load rhino classes try to use the loader of context factory or context subclasses class f class f get class if f class script runtime context factory class loader f class get class loader else loader get class get class loader application class loader loader return application class loader classloader getapplicationclassloader applicationclassloader contextfactory getfactory classloader getapplicationclassloader classloader threadloader vmbridge getcurrentthreadclassloader threadloader testifcanloadrhinoclasses threadloader getcontextclassloader getcontextclassloader threadloader getcontextclassloader contextfactory fclass getclass fclass scriptruntime contextfactoryclass fclass getclassloader getclass getclassloader applicationclassloader applicationclassloader public final void set application class loader class loader loader if sealed on sealed mutation if loader null restore default behaviour application class loader null return if kit test if can load rhino classes loader throw new illegal argument exception loader can not resolve rhino classes application class loader loader setapplicationclassloader classloader onsealedmutation applicationclassloader testifcanloadrhinoclasses illegalargumentexception applicationclassloader internal method that reports an error for missing calls to enter static context get context context cx get current context if cx null throw new runtime exception no context associated with current thread return cx getcontext getcurrentcontext runtimeexception private object compile impl scriptable scope reader source reader string source string string source name int lineno object security domain boolean return function interpreter compiler error reporter compilation error reporter throws io exception if security domain null security controller null throw new illegal argument exception security domain should be null if set security controller was never called one of source reader or source string has to be null if source reader null source string null kit code bug scope should be given if and only if compiling function if scope null return function kit code bug compiler environs compiler env new compiler environs compiler env init from context this if compilation error reporter null compilation error reporter compiler env get error reporter if debugger null if source reader null source string kit read reader source reader source reader null parser p new parser compiler env compilation error reporter if return function p called by compile function true script or fn node tree if source string null tree p parse source string source name lineno else tree p parse source reader source name lineno if return function if tree get function count 1 tree get first child null tree get first child get type token function xxx the check just look for the first child and allows for more nodes after it for compatibility with sources like function throw new illegal argument exception compile function only accepts source with single js function source string if compiler null compiler create compiler string encoded source p get encoded source object bytecode compiler compile compiler env tree encoded source return function if debugger null if source string null kit code bug if bytecode instanceof debuggable script debuggable script dscript debuggable script bytecode notifydebugger r this dscript source string else throw new runtime exception not supported object result if return function result compiler create function object this scope bytecode security domain else result compiler create script object bytecode security domain return result compileimpl sourcereader sourcestring sourcename securitydomain returnfunction errorreporter compilationerrorreporter ioexception securitydomain securitycontroller illegalargumentexception securitydomain setsecuritycontroller sourcereader sourcestring sourcereader sourcestring codebug returnfunction codebug compilerenvirons compilerenv compilerenvirons compilerenv initfromcontext compilationerrorreporter compilationerrorreporter compilerenv geterrorreporter sourcereader sourcestring readreader sourcereader sourcereader compilerenv compilationerrorreporter returnfunction calledbycompilefunction scriptorfnnode sourcestring sourcestring sourcename sourcereader sourcename returnfunction getfunctioncount getfirstchild getfirstchild gettype illegalargumentexception compilefunction sourcestring createcompiler encodedsource getencodedsource compilerenv encodedsource returnfunction sourcestring codebug debuggablescript debuggablescript debuggablescript notifydebugger_r sourcestring runtimeexception returnfunction createfunctionobject securitydomain createscriptobject securitydomain private static void notifydebugger r context cx debuggable script dscript string debug source cx debugger handle compilation done cx dscript debug source for int i 0 i dscript get function count i notifydebugger r cx dscript get function i debug source notifydebugger_r debuggablescript debugsource handlecompilationdone debugsource getfunctioncount notifydebugger_r getfunction debugsource private interpreter create compiler interpreter result null if optimization level 0 codegen class null result interpreter kit new instance or null codegen class if result null result new interpreter return result createcompiler optimizationlevel codegenclass newinstanceornull codegenclass static string get source position from stack int linep context cx get current context if cx null return null if cx last interpreter frame null return interpreter get source position from stack cx linep a bit of a hack but the only way to get filename and line number from an enclosing frame char array writer writer new char array writer runtime exception re new runtime exception re print stack trace new print writer writer string s writer to string int open 1 int close 1 int colon 1 for int i 0 i s length i char c s char at i if c colon i else if c open i else if c close i else if c n open 1 close 1 colon 1 open colon colon close string file str s substring open 1 colon if file str ends with java string line str s substring colon 1 close try linep 0 integer parse int line str if linep 0 0 linep 0 0 return file str catch number format exception e fall through open close colon 1 return null getsourcepositionfromstack getcurrentcontext lastinterpreterframe getsourcepositionfromstack chararraywriter chararraywriter runtimeexception runtimeexception printstacktrace printwriter tostring charat filestr filestr endswith linestr parseint linestr filestr numberformatexception reg exp proxy get reg exp proxy if reg exp proxy null class cl kit class or null org mozilla javascript regexp reg exp impl if cl null reg exp proxy reg exp proxy kit new instance or null cl return reg exp proxy regexpproxy getregexpproxy regexpproxy classornull regexpimpl regexpproxy regexpproxy newinstanceornull regexpproxy final boolean is versionecma1 return version version default version version 1 3 isversionecma1 version_default version_1_3 the method must not be public or protected security controller get security controller security controller global security controller global if global null return global return security controller securitycontroller getsecuritycontroller securitycontroller securitycontroller securitycontroller public final boolean is generating debug changed return generating debug changed isgeneratingdebugchanged generatingdebugchanged add a name to the list of names forcing the creation of real activation objects for functions param name the name of the object to add to the list public void add activation name string name if sealed on sealed mutation if activation names null activation names new hashtable 5 activation names put name name addactivationname onsealedmutation activationnames activationnames activationnames check whether the name is in the list of names of objects forcing the creation of activation objects param name the name of the object to test return true if an function activation object is needed public final boolean is activation needed string name return activation names null activation names contains key name isactivationneeded activationnames activationnames containskey remove a name from the list of names forcing the creation of real activation objects for functions param name the name of the object to remove from the list public void remove activation name string name if sealed on sealed mutation if activation names null activation names remove name removeactivationname onsealedmutation activationnames activationnames public int float 512 public int ambiguous float arg return float public int ambiguous double arg return double public int ambiguous byte arg return byte public int ambiguous char arg return char public int ambiguous short arg return short public int ambiguous int arg return int public int ambiguous long arg return long private string source file public code printer get code printer return p source_file codeprinter getcodeprinter public code printer get code printer return p public void set code printer code printer value p value codeprinter getcodeprinter setcodeprinter codeprinter public void set code printer code printer value p value public tool error reporter get reporter return r setcodeprinter codeprinter toolerrorreporter getreporter public tool error reporter get reporter return r public void set reporter tool error reporter value r value toolerrorreporter getreporter setreporter toolerrorreporter public void set reporter tool error reporter value r value public string get source file name return source file setreporter toolerrorreporter getsourcefilename source_file public string get source file name return source file public void set source file name string value source file value getsourcefilename source_file setsourcefilename source_file public void generate switch string pairs string default value int n pairs length 2 id value pair id pairs new id value pair n for int i 0 i n i id pairs i new id value pair pairs 2 i pairs 2 i 1 generate switch id pairs default value generateswitch default_value idvaluepair id_pairs idvaluepair id_pairs idvaluepair generateswitch id_pairs default_value public void generate switch id value pair pairs string default value int begin 0 int end pairs length if begin end return this pairs pairs this default value default value generate body begin end 2 generateswitch idvaluepair default_value default_value default_value generate_body private void generate body int begin int end int indent level p indent indent level p p v switch label p p p p v id p p p p default value p p string p p v guess p p null c was defined false int c def begin p get offset p p int p p v c p p int c def end p get offset p nl generate length switch begin end indent level 1 if c was defined p erase c def begin c def end p indent indent level 1 p p if p p v guess p p null p p v guess p p p p v s p p p p v guess p p equals p p v s p p p p v id p p p p default value p p p nl p line indent level generate_body indent_level indent_level v_switch_label v_id default_value v_guess c_was_defined c_def_begin getoffset v_c c_def_end getoffset generate_length_switch indent_level c_was_defined c_def_begin c_def_end indent_level v_guess v_guess v_s v_guess v_s v_id default_value indent_level private void generate length switch int begin int end int indent level sort pairs begin end 1 check all is different begin end int lengths count count different lengths begin end columns new int pairs end 1 id length boolean use if if lengths count use if threshold use if true if lengths count 1 p indent indent level p p int p p v s p p v length suffix p p p p v s p p length p nl else use if false p indent indent level p p v label p p switch p p v s p p length p nl int same length begin begin int cur l pairs begin id length l 0 for int i begin i if i end l pairs i id length cur l int next indent if use if p indent indent level if same length begin begin p p else p p if if lengths count 1 p p v s p p length else p p v s p p v length suffix p p p p cur l p p next indent indent level 1 else p indent indent level p p case p p cur l p p next indent indent level 1 generate letter switch same length begin i next indent use if use if if use if p p p nl else p p break p p v label p p p nl if i end break same length begin i cur l l if use if p indent indent level p p p nl generate_length_switch indent_level sort_pairs check_all_is_different lengths_count count_different_lengths idlength use_if lengths_count use_if_threshold use_if lengths_count indent_level v_s v_length_suffix v_s use_if indent_level v_label v_s same_length_begin cur_l idlength idlength cur_l next_indent use_if indent_level same_length_begin lengths_count v_s v_s v_length_suffix cur_l next_indent indent_level indent_level cur_l next_indent indent_level generate_letter_switch same_length_begin next_indent use_if use_if use_if v_label same_length_begin cur_l use_if indent_level private void generate letter switch int begin int end int indent level boolean label was defined boolean inside if int l pairs begin id length for int i 0 i l i columns i i generate letter switch r begin end l indent level label was defined inside if generate_letter_switch indent_level label_was_defined inside_if idlength generate_letter_switch_r indent_level label_was_defined inside_if private boolean generate letter switch r int begin int end int l int indent level boolean label was defined boolean inside if boolean next is unreachable false if begin 1 end p p id value pair pair pairs begin if l char tail test threshold p p v guess p p p qstring pair id p p p p v id p p p p pair value p p else if l 0 next is unreachable true p p v id p p p p pair value p p break p p v switch label p p else p p if int column columns 0 p p v s p p char at p p column p p p qchar pair id char at column for int i 1 i l i p p column columns i p p v s p p char at p p column p p p qchar pair id char at column p p p p v id p p p p pair value p p break p p v switch label p p p p return next is unreachable int max column index find max different column begin end l int max column columns max column index int count count different chars begin end max column columns max column index columns l 1 if inside if p nl p indent indent level else p p boolean use if if count use if threshold use if true c was defined true p p v c p p p p v s p p char at p p max column p p else use if false if label was defined label was defined true p p v label p p p p switch p p v s p p char at p p max column p p int same char begin begin int cur ch pairs begin id char at max column ch 0 for int i begin i if i end ch pairs i id char at max column cur ch int next indent if use if p nl p indent indent level if same char begin begin p p else p p if p p v c p p p qchar cur ch p p next indent indent level 1 else p nl p indent indent level p p case p qchar cur ch p p next indent indent level 1 boolean after unreachable generate letter switch r same char begin i l 1 next indent label was defined use if if use if p p else if after unreachable p p break p p v label p p if i end break same char begin i cur ch ch if use if p nl if inside if p indent indent level 1 else p indent indent level else p nl p indent indent level p p if inside if p nl p indent indent level 1 else p p columns max column index max column return next is unreachable generate_letter_switch_r indent_level label_was_defined inside_if next_is_unreachable idvaluepair char_tail_test_threshold v_guess v_id next_is_unreachable v_id v_switch_label v_s charat charat v_s charat charat v_id v_switch_label next_is_unreachable max_column_index find_max_different_column max_column max_column_index count_different_chars max_column max_column_index inside_if indent_level use_if use_if_threshold use_if c_was_defined v_c v_s charat max_column use_if label_was_defined label_was_defined v_label v_s charat max_column same_char_begin cur_ch charat max_column charat max_column cur_ch next_indent use_if indent_level same_char_begin v_c cur_ch next_indent indent_level indent_level cur_ch next_indent indent_level after_unreachable generate_letter_switch_r same_char_begin next_indent label_was_defined use_if use_if after_unreachable v_label same_char_begin cur_ch use_if inside_if indent_level indent_level indent_level inside_if indent_level max_column_index max_column next_is_unreachable private int count different lengths int begin int end int lengths count 0 int cur l 1 for begin end begin int l pairs begin id length if cur l l lengths count cur l l return lengths count count_different_lengths lengths_count cur_l idlength cur_l lengths_count cur_l lengths_count private int find max different column int begin int end int l int max count 0 int max index 0 for int i 0 i l i int column columns i sort pairs begin end column int count count different chars begin end column if count end begin return i if max count count max count count max index i if max index l 1 sort pairs begin end columns max index return max index find_max_different_column max_count max_index sort_pairs count_different_chars max_count max_count max_index max_index sort_pairs max_index max_index private int count different chars int begin int end int column int chars count 0 int cur ch 1 for begin end begin int ch pairs begin id char at column if ch cur ch chars count cur ch ch return chars count count_different_chars chars_count cur_ch charat cur_ch chars_count cur_ch chars_count private void check all is different int begin int end if begin end id value pair prev pairs begin while begin end id value pair current pairs begin if prev id equals current id throw on same pair fail prev current prev current check_all_is_different idvaluepair idvaluepair on_same_pair_fail private evaluator exception on same pair fail id value pair a id value pair b string buffer sb new string buffer int line1 a get line number line2 b get line number if line2 line1 int tmp line1 line1 line2 line2 tmp string error text tool error reporter get message msg idswitch same string a id new integer line2 return r runtime error error text source file line1 null 0 evaluatorexception on_same_pair_fail idvaluepair idvaluepair stringbuffer stringbuffer getlinenumber getlinenumber error_text toolerrorreporter getmessage same_string runtimeerror error_text source_file private void sort pairs int begin int end int comparator heap4 sort pairs begin end begin comparator sort_pairs heap4sort private static boolean bigger id value pair a id value pair b int comparator if comparator 0 for length selection switch it is enough to compare just length but to detect same strings full comparison is essential return a id length b id length int diff a id length b id length if diff 0 return diff 0 return a id compare to b id 0 else return a id char at comparator b id char at comparator idvaluepair idvaluepair idlength idlength idlength idlength compareto charat charat private static void heap4 sort id value pair array int offset int size int comparator if size 1 return make heap4 array offset size comparator while size 1 size id value pair v1 array offset size id value pair v2 array offset 0 array offset size v2 array offset 0 v1 heapify4 array offset size 0 comparator heap4sort idvaluepair makeheap4 idvaluepair idvaluepair private static void make heap4 id value pair array int offset int size int comparator for int i size 2 2 i 0 i heapify4 array offset size i comparator makeheap4 idvaluepair private static void heapify4 id value pair array int offset int size int i int comparator int new i1 new i2 new i3 id value pair i val array offset i for int base i 2 new i1 base 1 new i2 base 2 new i3 base 3 int new i4 base 4 if new i4 size break id value pair val1 array offset new i1 id value pair val2 array offset new i2 id value pair val3 array offset new i3 id value pair val4 array offset new i4 if bigger val2 val1 comparator val1 val2 new i1 new i2 if bigger val4 val3 comparator val3 val4 new i3 new i4 if bigger val3 val1 comparator val1 val3 new i1 new i3 if bigger i val val1 comparator return array offset i val1 array offset new i1 i val i new i1 if new i1 size id value pair val1 array offset new i1 if new i2 size id value pair val2 array offset new i2 if bigger val2 val1 comparator val1 val2 new i1 new i2 if new i3 size id value pair val3 array offset new i3 if bigger val3 val1 comparator val1 val3 new i1 new i3 if bigger val1 i val comparator array offset i val1 array offset new i1 i val idvaluepair new_i1 new_i2 new_i3 idvaluepair i_val new_i1 new_i2 new_i3 new_i4 new_i4 idvaluepair new_i1 idvaluepair new_i2 idvaluepair new_i3 idvaluepair new_i4 new_i1 new_i2 new_i3 new_i4 new_i1 new_i3 i_val new_i1 i_val new_i1 new_i1 idvaluepair new_i1 new_i2 idvaluepair new_i2 new_i1 new_i2 new_i3 idvaluepair new_i3 new_i1 new_i3 i_val new_i1 i_val public class datatypes 007 extends live connect test public datatypes 007 super datatypes_007 liveconnecttest datatypes_007 public static void main string args datatypes 007 test new datatypes 007 test start datatypes_007 datatypes_007 public void execute test do static method tests dt static get boolean object java lang boolean object new boolean data type class pub static final boolean do static method tests dt static get boolean java lang boolean object new boolean data type class pub static final boolean do static method tests dt static get byte java lang double object new double data type class pub static final byte do static method tests dt static get byte object java lang byte object new byte data type class pub static final byte do static method tests dt static get char java lang double object new double data type class pub static final char do static method tests dt static get character java lang character object new character data type class pub static final char do static method tests dt static get short java lang double object new double data type class pub static final short do static method tests dt static get short object java lang short object new short data type class pub static final short do static method tests dt static get integer java lang double object new double data type class pub static final int do static method tests dt static get integer object java lang integer object new integer data type class pub static final int do static method tests dt static get integer java lang double object new double data type class pub static final int do static method tests dt static get long java lang double object new double data type class pub static final long do static method tests dt static get long object java lang long object new long data type class pub static final long do static method tests dt static get float java lang double object new double data type class pub static final float do static method tests dt static get float object java lang float object new float data type class pub static final float do static method tests dt static get double java lang double object new double data type class pub static final double do static method tests dt static get double object java lang double object new double data type class pub static final double do static method tests dt static get char java lang double object new double data type class pub static final char do static method tests dt static get string object java lang string object new string data type class pub static final string executetest dostaticmethodtests staticgetbooleanobject datatypeclass pub_static_final_boolean dostaticmethodtests staticgetboolean datatypeclass pub_static_final_boolean dostaticmethodtests staticgetbyte datatypeclass pub_static_final_byte dostaticmethodtests staticgetbyteobject datatypeclass pub_static_final_byte dostaticmethodtests staticgetchar datatypeclass pub_static_final_char dostaticmethodtests staticgetcharacter datatypeclass pub_static_final_char dostaticmethodtests staticgetshort datatypeclass pub_static_final_short dostaticmethodtests staticgetshortobject datatypeclass pub_static_final_short dostaticmethodtests staticgetinteger datatypeclass pub_static_final_int dostaticmethodtests staticgetintegerobject datatypeclass pub_static_final_int dostaticmethodtests staticgetinteger datatypeclass pub_static_final_int dostaticmethodtests staticgetlong datatypeclass pub_static_final_long dostaticmethodtests staticgetlongobject datatypeclass pub_static_final_long dostaticmethodtests staticgetfloat datatypeclass pub_static_final_float dostaticmethodtests staticgetfloatobject datatypeclass pub_static_final_float dostaticmethodtests staticgetdouble datatypeclass pub_static_final_double dostaticmethodtests staticgetdoubleobject datatypeclass pub_static_final_double dostaticmethodtests staticgetchar datatypeclass pub_static_final_char dostaticmethodtests staticgetstringobject datatypeclass pub_static_final_string public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class setuptestenvironment setuptestenvironment datatypeclass public void do static method tests string method string class name object value get public static method method class name value get java script value method class name value dostaticmethodtests classname getpublicstaticmethod classname getjavascriptvalue classname set the value of a java script variable to a java value get the value of that variable public void get public static method string method string class name object value string description method string exception null object actual null string expect null check the class try actual global eval method expect class for name class name get name catch class not found exception e catch exception e exception e to string might want to do all the interesting stuff here in a try catch block add test case description get class expect actual get class get name exception add test case description value to string true actual equals value exception add test case actual to string equals value to string true actual to string equals value to string exception javascript getpublicstaticmethod classname forname classname getname classnotfoundexception tostring addtestcase getclass getclass getname addtestcase tostring addtestcase tostring tostring tostring tostring try to set the value of a public static field using js object set member which should succeed public void set public static field string field string class name object value string description field string exception null object before null object after null string expect null object new value class name equals java lang double new double 0 class name equals java lang boolean new boolean false object new string new value try before global eval description need to quote strings if class name equals java lang string global eval description new value to string else global eval description new value after global eval description expect class for name class name get name catch exception e exception e to string add test case global eval description new value to string after global eval description after get class get name expect after get class get name exception add test case after to string equals new value to string true after equals new value exception add test case after to string equals new value to string true after to string equals new value to string exception jsobject setmember setpublicstaticfield classname newvalue classname classname classname newvalue tostring newvalue forname classname getname tostring addtestcase newvalue tostring getclass getname getclass getname addtestcase tostring newvalue tostring newvalue addtestcase tostring newvalue tostring tostring newvalue tostring assign a value to a public static final java field the assignment should fail the value should not change but there should be no error message public void set public static final field string field string class name object value string description field string exception null object before null object after null string expect null object new value class name equals java lang double new double 0 class name equals java lang boolean new boolean false object new string new value try expect class for name class name get name catch exception e exception e to string before global eval description global eval description new value to string after global eval description check the class of the result which should be the same as expect add test case description get class expect after get class get name exception the value of the actual result should be the original value add test case description value to string true after equals value exception the string representation of the actual result should be the same as the string representation of the expected value add test case after to string equals value to string true after to string equals value to string exception get member field should return the same value before and after the assignment add test case before equals after true before equals after exception setpublicstaticfinalfield classname newvalue classname classname forname classname getname tostring newvalue tostring addtestcase getclass getclass getname addtestcase tostring addtestcase tostring tostring tostring tostring getmember addtestcase public void get java script value string field string class name object value string description field string exception null object actual null string expect null try global eval var myobject description actual global get member myobject expect class for name class name get name catch exception e exception e to string add test case global eval var myobject description actual global get member myobject actual get class get name expect actual get class get name exception add test case actual value to string true actual equals value exception add test case actual to string equals value to string true actual to string equals value to string exception getjavascriptvalue classname getmember forname classname getname tostring addtestcase getmember getclass getname getclass getname addtestcase tostring addtestcase tostring tostring tostring tostring public class slot 001 extends live connect test public slot 001 super slot_001 liveconnecttest slot_001 super public static void main string args slot 001 test new slot 001 test start slot_001 slot_001 public void execute test for int i 0 i test matrix length i string args string object test matrix i 0 js object js array createjs array args get the length of the array using js object get member int java length object test matrix i length 1 get length js array java length for int j 0 j java length j get slot js array j object test matrix i j 1 executetest testmatrix testmatrix jsobject jsarray createjsarray jsobject getmember javalength testmatrix getlength jsarray javalength javalength getslot jsarray testmatrix create a java script array named js array param new array arguments string containing a list of arguments for the java script array constructor return the js object array object public js object createjs array string new array arguments js object js array null string args var js array new array new array arguments string result passed try system out println args global eval args js array js object global get member js array catch exception e result failed exception global get member js array threw e to string file exception exception e print stack trace finally add test case global eval var js array new array new array arguments js object js array js object global get member js array passed result exception return js array javascript jsarray newarrayarguments javascript jsobject jsobject createjsarray newarrayarguments jsobject jsarray jsarray newarrayarguments jsarray jsobject getmember jsarray getmember jsarray tostring printstacktrace addtestcase jsarray newarrayarguments jsobject jsarray jsobject getmember jsarray jsarray use js object get member to get the length property of a js object param js array a js object with a property named length param java length the expected length of the js object public void get length js object js array int java length string exception int js length 0 try js length double js array get member length int value catch exception e exception js array get member length threw e to string file exception exception e print stack trace finally add test case length is js length js array get member length int value java length true js length java length exception jsobject getmember jsobject jsarray jsobject javalength jsobject getlength jsobject jsarray javalength jslength jslength jsarray getmember intvalue jsarray getmember tostring printstacktrace addtestcase jslength jsarray getmember intvalue javalength jslength javalength use js object get slot to get an indexed member of a js object param js array the js object with indexed members param slot the index property to retrieve param java value a java object whose type and value are what we expect js array get slot slot to return public void get slot js object js array int slot object java value string exception object result null class e class null class a class null try result js array get slot slot if java value null e class java value get class a class result get class catch exception e exception js array get slot slot threw e to string file exception exception e print stack trace finally if java value null add test case js array get slot slot returned result java value result true java value result exception else add test case js array get slot slot returned result java value equals result true java value equals result exception add test case e class equals a class true e class equals a class exception jsobject getslot jsobject jsarray jsobject javavalue jsarray getslot getslot jsobject jsarray javavalue eclass aclass jsarray getslot javavalue eclass javavalue getclass aclass getclass jsarray getslot tostring printstacktrace javavalue addtestcase jsarray getslot javavalue javavalue addtestcase jsarray getslot javavalue javavalue addtestcase eclass aclass eclass aclass js object set slot returns undefined this just verifies that we can call set slot without throwing an exception param js array the js object on which set slot will be called param slot the indexed member that will be set param java value the value to set the indexed member public void set slot js object js array int slot object java value string exception null string result passed try js array set slot slot java value catch exception e result failed exception js array set slot slot java value threw e to string file exception exception e print stack trace finally add test case js array set slot slot java value passed result exception jsobject setslot setslot jsarray jsobject setslot javavalue setslot jsobject jsarray javavalue jsarray setslot javavalue jsarray setslot javavalue tostring printstacktrace addtestcase jsarray setslot javavalue public static boolean nodes equal xml cursor xml one xml cursor xml two boolean result false if xml one is startdoc xml one to first content token if xml two is startdoc xml two to first content token if xml one current token type xml two current token type if xml one is enddoc both empty result true else if xml one is attr result attributes equal xml one xml two else if xml one is text result text nodes equal xml one xml two else if xml one is comment result comments equal xml one xml two else if xml one is procinst result processing instructions equal xml one xml two else if xml one is start compare root elements result elements equal xml one xml two return result nodesequal xmlcursor xmlone xmlcursor xmltwo xmlone isstartdoc xmlone tofirstcontenttoken xmltwo isstartdoc xmltwo tofirstcontenttoken xmlone currenttokentype xmltwo currenttokentype xmlone isenddoc xmlone isattr attributesequal xmlone xmltwo xmlone istext textnodesequal xmlone xmltwo xmlone iscomment commentsequal xmlone xmltwo xmlone isprocinst processinginstructionsequal xmlone xmltwo xmlone isstart elementsequal xmlone xmltwo private static boolean elements equal xml cursor xml one xml cursor xml two boolean result true if qnames equal xml one get name xml two get name result false else these filter out empty text nodes next token xml one next token xml two do if xml one current token type xml two current token type not same token result false break else if xml one is end done with this element step over end break else if xml one is enddoc shouldn t get here break else if xml one is attr this one will move us to the first non attr token result attribute lists equal xml one xml two else if xml one is text result text nodes equal xml one xml two else if xml one is comment result comments equal xml one xml two else if xml one is procinst result processing instructions equal xml one xml two else if xml one is start result elements equal xml one xml two else xml log unknown token type xml one current token type these filter out empty text nodes next token xml one next token xml two while result return result elementsequal xmlcursor xmlone xmlcursor xmltwo qnamesequal xmlone getname xmltwo getname nexttoken xmlone nexttoken xmltwo xmlone currenttokentype xmltwo currenttokentype xmlone isend xmlone isenddoc xmlone isattr attributelistsequal xmlone xmltwo xmlone istext textnodesequal xmlone xmltwo xmlone iscomment commentsequal xmlone xmltwo xmlone isprocinst processinginstructionsequal xmlone xmltwo xmlone isstart elementsequal xmlone xmltwo xmlone currenttokentype nexttoken xmlone nexttoken xmltwo param xml one param xml two return private static boolean attribute lists equal xml cursor xml one xml cursor xml two boolean result true tree map map one load attribute map xml one tree map map two load attribute map xml two if map one size map two size result false else set keys one map one key set set keys two map two key set iterator it one keys one iterator iterator it two keys two iterator while result it one has next string value one string it one next string value two string it two next if value one equals value two result false else javax xml namespace q name qname one javax xml namespace q name map one get value one javax xml namespace q name qname two javax xml namespace q name map two get value two if qnames equal qname one qname two result false return result xmlone xmltwo attributelistsequal xmlcursor xmlone xmlcursor xmltwo treemap mapone loadattributemap xmlone treemap maptwo loadattributemap xmltwo mapone maptwo keysone mapone keyset keystwo maptwo keyset itone keysone ittwo keystwo itone hasnext valueone itone valuetwo ittwo valueone valuetwo qname qnameone qname mapone valueone qname qnametwo qname maptwo valuetwo qnamesequal qnameone qnametwo param xml return private static tree map load attribute map xml cursor xml tree map result new tree map while xml is attr result put xml get text value xml get name next token xml return result treemap loadattributemap xmlcursor treemap treemap isattr gettextvalue getname nexttoken param xml one param xml two return private static boolean attributes equal xml cursor xml one xml cursor xml two boolean result false if xml one is attr xml two is attr if qnames equal xml one get name xml two get name if xml one get text value equals xml two get text value result true return result xmlone xmltwo attributesequal xmlcursor xmlone xmlcursor xmltwo xmlone isattr xmltwo isattr qnamesequal xmlone getname xmltwo getname xmlone gettextvalue xmltwo gettextvalue param xml one param xml two return private static boolean text nodes equal xml cursor xml one xml cursor xml two boolean result false if xml one is text xml two is text if xml one get chars equals xml two get chars result true return result xmlone xmltwo textnodesequal xmlcursor xmlone xmlcursor xmltwo xmlone istext xmltwo istext xmlone getchars xmltwo getchars param xml one param xml two return private static boolean comments equal xml cursor xml one xml cursor xml two boolean result false if xml one is comment xml two is comment if xml one get text value equals xml two get text value result true return result xmlone xmltwo commentsequal xmlcursor xmlone xmlcursor xmltwo xmlone iscomment xmltwo iscomment xmlone gettextvalue xmltwo gettextvalue param xml one param xml two return private static boolean processing instructions equal xml cursor xml one xml cursor xml two boolean result false if xml one is procinst xml two is procinst if qnames equal xml one get name xml two get name if xml one get text value equals xml two get text value result true return result xmlone xmltwo processinginstructionsequal xmlcursor xmlone xmlcursor xmltwo xmlone isprocinst xmltwo isprocinst qnamesequal xmlone getname xmltwo getname xmlone gettextvalue xmltwo gettextvalue param qname one param qname two return private static boolean qnames equal javax xml namespace q name qname one javax xml namespace q name qname two boolean result false if qname one get namespaceuri equals qname two get namespaceuri if qname one get local part equals qname two get local part return true return result qnameone qnametwo qnamesequal qname qnameone qname qnametwo qnameone getnamespaceuri qnametwo getnamespaceuri qnameone getlocalpart qnametwo getlocalpart filter out empty text nodes here param xml private static void next token xml cursor xml do xml to next token if xml is text not a text node break else if xml get chars trim length 0 text node is not empty break while true textnodes nexttoken xmlcursor tonexttoken istext getchars public int float 512 public int ambiguous float arg return float public int ambiguous double arg return double public int ambiguous byte arg return byte public int ambiguous char arg return char public int ambiguous short arg return short public int ambiguous int arg return int public int ambiguous long arg return long public int ambiguous string arg return string public int ambiguous object arg return object return object public int expect return object protected xml object impl xml lib impl lib xml object prototype super lib global scope prototype this lib lib xmlobjectimpl xmllibimpl xmlobject globalscope ecma has cx id calls this after resolving when id to xml name and checking it is not uint32 index ecmahas xmlname ecma get cx id calls this after resolving when id to xml name and checking it is not uint32 index ecmaget xmlname ecma put cx id value calls this after resolving when id to xml name and checking it is not uint32 index ecmaput xmlname ecma delete cx id calls this after resolving when id to xml name and checking it is not uint32 index ecmadelete xmlname abstract void deletexml property xml name name test xml equality with target the target abstract boolean equivalent xml object target deletexmlproperty xmlname equivalentxml methods from section 12 4 4 in the spec abstract xml add namespace namespace ns addnamespace methods from section 12 4 4 in the spec abstract xml add namespace namespace ns abstract xml append child object xml addnamespace appendchild abstract xml add namespace namespace ns abstract xml append child object xml abstract xml list attribute xml name xml name addnamespace appendchild xmllist xmlname xmlname abstract xml append child object xml abstract xml list attribute xml name xml name abstract xml list attributes appendchild xmllist xmlname xmlname xmllist abstract xml list attribute xml name xml name abstract xml list attributes abstract xml list child long index xmllist xmlname xmlname xmllist xmllist abstract xml list attributes abstract xml list child long index abstract xml list child xml name xml name xmllist xmllist xmllist xmlname xmlname abstract xml list child long index abstract xml list child xml name xml name abstract int child index xmllist xmllist xmlname xmlname childindex abstract xml list child xml name xml name abstract int child index abstract xml list children xmllist xmlname xmlname childindex xmllist abstract int child index abstract xml list children abstract xml list comments childindex xmllist xmllist abstract xml list children abstract xml list comments abstract boolean contains object xml xmllist xmllist abstract xml list comments abstract boolean contains object xml abstract object copy xmllist abstract boolean contains object xml abstract object copy abstract xml list descendants xml name xml name xmllist xmlname xmlname abstract object copy abstract xml list descendants xml name xml name abstract object in scope namespaces xmllist xmlname xmlname inscopenamespaces abstract xml list descendants xml name xml name abstract object in scope namespaces abstract xml insert child after object child object xml xmllist xmlname xmlname inscopenamespaces insertchildafter abstract object in scope namespaces abstract xml insert child after object child object xml abstract xml insert child before object child object xml inscopenamespaces insertchildafter insertchildbefore abstract xml insert child after object child object xml abstract xml insert child before object child object xml abstract boolean has own property xml name xml name insertchildafter insertchildbefore hasownproperty xmlname xmlname abstract xml insert child before object child object xml abstract boolean has own property xml name xml name abstract boolean has complex content insertchildbefore hasownproperty xmlname xmlname hascomplexcontent abstract boolean has own property xml name xml name abstract boolean has complex content abstract boolean has simple content hasownproperty xmlname xmlname hascomplexcontent hassimplecontent abstract boolean has complex content abstract boolean has simple content abstract int length hascomplexcontent hassimplecontent abstract boolean has simple content abstract int length abstract string local name hassimplecontent localname abstract int length abstract string local name abstract q name name localname qname abstract string local name abstract q name name abstract object namespace string prefix localname qname abstract q name name abstract object namespace string prefix abstract object namespace declarations qname namespacedeclarations abstract object namespace string prefix abstract object namespace declarations abstract object node kind namespacedeclarations nodekind abstract object namespace declarations abstract object node kind abstract void normalize namespacedeclarations nodekind abstract object node kind abstract void normalize abstract object parent nodekind abstract void normalize abstract object parent abstract xml prepend child object xml prependchild abstract object parent abstract xml prepend child object xml abstract object processing instructions xml name xml name prependchild processinginstructions xmlname xmlname abstract xml prepend child object xml abstract object processing instructions xml name xml name abstract boolean property is enumerable object member prependchild processinginstructions xmlname xmlname propertyisenumerable abstract object processing instructions xml name xml name abstract boolean property is enumerable object member abstract xml remove namespace namespace ns processinginstructions xmlname xmlname propertyisenumerable removenamespace abstract boolean property is enumerable object member abstract xml remove namespace namespace ns abstract xml replace long index object xml propertyisenumerable removenamespace abstract xml remove namespace namespace ns abstract xml replace long index object xml abstract xml replace xml name name object xml removenamespace xmlname abstract xml replace long index object xml abstract xml replace xml name name object xml abstract xml set children object xml xmlname setchildren abstract xml replace xml name name object xml abstract xml set children object xml abstract void set local name string name xmlname setchildren setlocalname abstract xml set children object xml abstract void set local name string name abstract void set name q name xml name setchildren setlocalname setname qname xmlname abstract void set local name string name abstract void set name q name xml name abstract void set namespace namespace ns setlocalname setname qname xmlname setnamespace abstract void set name q name xml name abstract void set namespace namespace ns abstract xml list text setname qname xmlname setnamespace xmllist abstract void set namespace namespace ns abstract xml list text public abstract string to string setnamespace xmllist tostring abstract xml list text public abstract string to string abstract string to source int indent xmllist tostring tosource public abstract string to string abstract string to source int indent abstract string toxml string int indent tostring tosource toxmlstring abstract string to source int indent abstract string toxml string int indent abstract object value of tosource toxmlstring valueof abstract object value of extension to access native implementation from scripts abstract org apache xmlbeans xml object get xml object valueof xmlobject getxmlobject abstract org apache xmlbeans xml object get xml object protected abstract object js constructor context cx boolean in new expr object args xmlobject getxmlobject jsconstructor innewexpr final object get method string id return super get id this getmethod public final object get default value class hint return to string getdefaultvalue tostring public void delete string name throw new illegal argument exception string name illegalargumentexception xml object always compare with any value and equivalent values never returns link scriptable not found for them but rather calls equivalent xml value and wrap the result as boolean protected final object equivalent values object value boolean result equivalent xml value return result boolean true boolean false xmlobject equivalentvalues not_found equivalentxml equivalentvalues equivalentxml public final xml lib lib return lib xmllib implementation of ecma script has public final boolean ecma has context cx object id if cx null cx context get current context xml name xml name lib toxml name or index cx id if xml name null long index script runtime last uint32 result cx xxx fix this cast return has int index this return hasxml property xml name ecmascript ecmahas getcurrentcontext xmlname xmlname toxmlnameorindex xmlname scriptruntime lastuint32result hasxmlproperty xmlname implementation of ecma script get public final object ecma get context cx object id if cx null cx context get current context xml name xml name lib toxml name or index cx id if xml name null long index script runtime last uint32 result cx xxx fix this cast object result get int index this if result scriptable not found result undefined instance return result return getxml property xml name ecmascript ecmaget getcurrentcontext xmlname xmlname toxmlnameorindex xmlname scriptruntime lastuint32result not_found getxmlproperty xmlname implementation of ecma script put public final void ecma put context cx object id object value if cx null cx context get current context xml name xml name lib toxml name or index cx id if xml name null long index script runtime last uint32 result cx xxx fix this cast put int index this value return putxml property xml name value ecmascript ecmaput getcurrentcontext xmlname xmlname toxmlnameorindex xmlname scriptruntime lastuint32result putxmlproperty xmlname implementation of ecma script delete public final boolean ecma delete context cx object id if cx null cx context get current context xml name xml name lib toxml name or index cx id if xml name null long index script runtime last uint32 result cx xxx fix this delete int index return true deletexml property xml name return true ecmascript ecmadelete getcurrentcontext xmlname xmlname toxmlnameorindex xmlname scriptruntime lastuint32result deletexmlproperty xmlname public ref member ref context cx object elem int member type flags xml name xml name if member type flags node attribute flag 0 xml name lib to attribute name cx elem else if member type flags node descendants flag 0 code generation would use ecma get has delete set for normal name idenrifiers so one attribute flag or descendants flag has to be set throw kit code bug xml name lib toxml name cx elem if member type flags node descendants flag 0 xml name set is descendants xml name initxml object this return xml name memberref membertypeflags xmlname xmlname membertypeflags attribute_flag xmlname toattributename membertypeflags descendants_flag attribute_flag descendants_flag codebug xmlname toxmlname membertypeflags descendants_flag xmlname setisdescendants xmlname initxmlobject xmlname generic reference to implement x ns x ns y x ns y etc public ref member ref context cx object namespace object elem int member type flags xml name xml name lib to qualified name cx namespace elem if member type flags node attribute flag 0 if xml name is attribute name xml name set attribute name if member type flags node descendants flag 0 xml name set is descendants xml name initxml object this return xml name memberref membertypeflags xmlname xmlname toqualifiedname membertypeflags attribute_flag xmlname isattributename xmlname setattributename membertypeflags descendants_flag xmlname setisdescendants xmlname initxmlobject xmlname public native with enter with scriptable scope return new xml with scope lib scope this nativewith enterwith xmlwithscope public native with enter dot query scriptable scope xml with scope xws new xml with scope lib scope this xws init as dot query return xws nativewith enterdotquery xmlwithscope xmlwithscope initasdotquery public final object add values context cx boolean this is left object value if value instanceof xml object xml object v1 v2 if this is left v1 this v2 xml object value else v1 xml object value v2 this return lib addxml objects cx v1 v2 if value undefined instance both xml undefined and undefined xml gives string xml return script runtime to string this return super add values cx this is left value addvalues thisisleft xmlobject xmlobject thisisleft xmlobject xmlobject addxmlobjects scriptruntime tostring addvalues thisisleft final void export asjs class boolean sealed prototype flag true export asjs class max prototype id lib global scope sealed exportasjsclass prototypeflag exportasjsclass max_prototype_id globalscope protected int find prototype id string s int id generated last update 2004 11 10 15 38 11 cet l0 id 0 string x null int c l switch s length case 4 c s char at 0 if c c x copy id id copy else if c n x name id id name else if c t x text id id text break l case 5 x child id id child break l case 6 c s char at 0 if c l x length id id length else if c p x parent id id parent break l case 7 c s char at 0 if c r x replace id id replace else if c s x set name id id setname else if c v x value of id id valueof break l case 8 switch s char at 4 case k x node kind id id nodekind break l case a x contains id id contains break l case d x children id id children break l case e x comments id id comments break l case r x to string id id tostring break l case u x to source id id tosource break l break l case 9 switch s char at 2 case c x local name id id localname break l case m x namespace id id namespace break l case r x normalize id id normalize break l case t x attribute id id attribute break l break l case 10 c s char at 0 if c a x attributes id id attributes else if c c x child index id id childindex break l case 11 switch s char at 0 case a x append child id id appendchild break l case c x constructor id id constructor break l case d x descendants id id descendants break l case s x set children id id setchildren break l case t x toxml string id id toxmlstring break l break l case 12 switch s char at 0 case a x add namespace id id addnamespace break l case g x get xml object id id getxmlobject break l case p x prepend child id id prependchild break l case s c s char at 3 if c l x set local name id id setlocalname else if c n x set namespace id id setnamespace break l break l case 14 x has own property id id hasownproperty break l case 15 x remove namespace id id removenamespace break l case 16 c s char at 0 if c h x has simple content id id hassimplecontent else if c i x insert child after id id insertchildafter break l case 17 c s char at 3 if c c x has complex content id id hascomplexcontent else if c c x in scope namespaces id id inscopenamespaces else if c e x insert child before id id insertchildbefore break l case 20 x property is enumerable id id propertyisenumerable break l case 21 x namespace declarations id id namespacedeclarations break l case 22 x processing instructions id id processinginstructions break l if x null x s x equals s id 0 generated return id findprototypeid charat id_copy id_name id_text id_child charat id_length id_parent charat id_replace setname id_setname valueof id_valueof charat nodekind id_nodekind id_contains id_children id_comments tostring id_tostring tosource id_tosource charat localname id_localname id_namespace id_normalize id_attribute charat id_attributes childindex id_childindex charat appendchild id_appendchild id_constructor id_descendants setchildren id_setchildren toxmlstring id_toxmlstring charat addnamespace id_addnamespace getxmlobject id_getxmlobject prependchild id_prependchild charat setlocalname id_setlocalname setnamespace id_setnamespace hasownproperty id_hasownproperty removenamespace id_removenamespace charat hassimplecontent id_hassimplecontent insertchildafter id_insertchildafter charat hascomplexcontent id_hascomplexcontent inscopenamespaces id_inscopenamespaces insertchildbefore id_insertchildbefore propertyisenumerable id_propertyisenumerable namespacedeclarations id_namespacedeclarations processinginstructions id_processinginstructions protected void init prototype id int id string s int arity switch id case id constructor id function object ctor if this instanceof xml ctor new xml ctor xml this xmlobject tag id 1 else ctor new id function object this xmlobject tag id 1 init prototype constructor ctor return case id addnamespace arity 1 s add namespace break case id appendchild arity 1 s append child break case id attribute arity 1 s attribute break case id attributes arity 0 s attributes break case id child arity 1 s child break case id childindex arity 0 s child index break case id children arity 0 s children break case id comments arity 0 s comments break case id contains arity 1 s contains break case id copy arity 0 s copy break case id descendants arity 1 s descendants break case id hascomplexcontent arity 0 s has complex content break case id hasownproperty arity 1 s has own property break case id hassimplecontent arity 0 s has simple content break case id inscopenamespaces arity 0 s in scope namespaces break case id insertchildafter arity 2 s insert child after break case id insertchildbefore arity 2 s insert child before break case id length arity 0 s length break case id localname arity 0 s local name break case id name arity 0 s name break case id namespace arity 1 s namespace break case id namespacedeclarations arity 0 s namespace declarations break case id nodekind arity 0 s node kind break case id normalize arity 0 s normalize break case id parent arity 0 s parent break case id prependchild arity 1 s prepend child break case id processinginstructions arity 1 s processing instructions break case id propertyisenumerable arity 1 s property is enumerable break case id removenamespace arity 1 s remove namespace break case id replace arity 2 s replace break case id setchildren arity 1 s set children break case id setlocalname arity 1 s set local name break case id setname arity 1 s set name break case id setnamespace arity 1 s set namespace break case id text arity 0 s text break case id tostring arity 0 s to string break case id tosource arity 1 s to source break case id toxmlstring arity 1 s toxml string break case id valueof arity 0 s value of break case id getxmlobject arity 0 s get xml object break default throw new illegal argument exception string value of id init prototype method xmlobject tag id s arity initprototypeid id_constructor idfunctionobject xmlctor xmlobject_tag idfunctionobject xmlobject_tag initprototypeconstructor id_addnamespace addnamespace id_appendchild appendchild id_attribute id_attributes id_child id_childindex childindex id_children id_comments id_contains id_copy id_descendants id_hascomplexcontent hascomplexcontent id_hasownproperty hasownproperty id_hassimplecontent hassimplecontent id_inscopenamespaces inscopenamespaces id_insertchildafter insertchildafter id_insertchildbefore insertchildbefore id_length id_localname localname id_name id_namespace id_namespacedeclarations namespacedeclarations id_nodekind nodekind id_normalize id_parent id_prependchild prependchild id_processinginstructions processinginstructions id_propertyisenumerable propertyisenumerable id_removenamespace removenamespace id_replace id_setchildren setchildren id_setlocalname setlocalname id_setname setname id_setnamespace setnamespace id_text id_tostring tostring id_tosource tosource id_toxmlstring toxmlstring id_valueof valueof id_getxmlobject getxmlobject illegalargumentexception valueof initprototypemethod xmlobject_tag param f param cx param scope param this obj param args return public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag xmlobject tag return super exec id call f cx scope this obj args int id f method id if id id constructor return js constructor cx this obj null args all xml xml list prototype methods require this obj to be xml if this obj instanceof xml object impl throw incompatible call error f xml object impl real this xml object impl this obj switch id case id addnamespace namespace ns lib cast to namespace cx arg args 0 return real this add namespace ns case id appendchild return real this append child arg args 0 case id attribute xml name xml name lib to attribute name cx arg args 0 return real this attribute xml name case id attributes return real this attributes case id child xml name xml name lib toxml name or index cx arg args 0 if xml name null long index script runtime last uint32 result cx return real this child index else return real this child xml name case id childindex return script runtime wrap int real this child index case id children return real this children case id comments return real this comments case id contains return script runtime wrap boolean real this contains arg args 0 case id copy return real this copy case id descendants xml name xml name args length 0 xml name form star lib toxml name cx args 0 return real this descendants xml name case id inscopenamespaces object array real this in scope namespaces return cx new array scope array case id insertchildafter return real this insert child after arg args 0 arg args 1 case id insertchildbefore return real this insert child before arg args 0 arg args 1 case id hasownproperty xml name xml name lib toxml name cx arg args 0 return script runtime wrap boolean real this has own property xml name case id hascomplexcontent return script runtime wrap boolean real this has complex content case id hassimplecontent return script runtime wrap boolean real this has simple content case id length return script runtime wrap int real this length case id localname return real this local name case id name return real this name case id namespace string prefix args length 0 script runtime to string args 0 null return real this namespace prefix case id namespacedeclarations object array real this namespace declarations return cx new array scope array case id nodekind return real this node kind case id normalize real this normalize return undefined instance case id parent return real this parent case id prependchild return real this prepend child arg args 0 case id processinginstructions xml name xml name args length 0 lib toxml name cx args 0 xml name form star return real this processing instructions xml name case id propertyisenumerable return script runtime wrap boolean real this property is enumerable arg args 0 case id removenamespace namespace ns lib cast to namespace cx arg args 0 return real this remove namespace ns case id replace xml name xml name lib toxml name or index cx arg args 0 object arg1 arg args 1 if xml name null long index script runtime last uint32 result cx return real this replace index arg1 else return real this replace xml name arg1 case id setchildren return real this set children arg args 0 case id setlocalname string local name object arg arg args 0 if arg instanceof q name local name q name arg local name else local name script runtime to string arg real this set local name local name return undefined instance case id setname object arg args length 0 args 0 undefined instance q name qname if arg instanceof q name qname q name arg if qname uri null qname lib constructq name from string cx qname local name else e4x 13 4 4 35 requires to always construct q name qname lib constructq name cx qname else qname lib constructq name cx arg real this set name qname return undefined instance case id setnamespace namespace ns lib cast to namespace cx arg args 0 real this set namespace ns return undefined instance case id text return real this text case id tostring return real this to string case id tosource int indent script runtime to int32 args 0 return real this to source indent case id toxmlstring int indent script runtime to int32 args 0 return real this toxml string indent case id valueof return real this value of case id getxmlobject org apache xmlbeans xml object xml object real this get xml object return context java tojs xml object scope throw new illegal argument exception string value of id thisobj execidcall idfunctionobject thisobj hastag xmlobject_tag execidcall thisobj methodid id_constructor jsconstructor thisobj xmllist thisobj thisobj xmlobjectimpl incompatiblecallerror xmlobjectimpl realthis xmlobjectimpl thisobj id_addnamespace casttonamespace realthis addnamespace id_appendchild realthis appendchild id_attribute xmlname xmlname toattributename realthis xmlname id_attributes realthis id_child xmlname xmlname toxmlnameorindex xmlname scriptruntime lastuint32result realthis realthis xmlname id_childindex scriptruntime wrapint realthis childindex id_children realthis id_comments realthis id_contains scriptruntime wrapboolean realthis id_copy realthis id_descendants xmlname xmlname xmlname formstar toxmlname realthis xmlname id_inscopenamespaces realthis inscopenamespaces newarray id_insertchildafter realthis insertchildafter id_insertchildbefore realthis insertchildbefore id_hasownproperty xmlname xmlname toxmlname scriptruntime wrapboolean realthis hasownproperty xmlname id_hascomplexcontent scriptruntime wrapboolean realthis hascomplexcontent id_hassimplecontent scriptruntime wrapboolean realthis hassimplecontent id_length scriptruntime wrapint realthis id_localname realthis localname id_name realthis id_namespace scriptruntime tostring realthis id_namespacedeclarations realthis namespacedeclarations newarray id_nodekind realthis nodekind id_normalize realthis id_parent realthis id_prependchild realthis prependchild id_processinginstructions xmlname xmlname toxmlname xmlname formstar realthis processinginstructions xmlname id_propertyisenumerable scriptruntime wrapboolean realthis propertyisenumerable id_removenamespace casttonamespace realthis removenamespace id_replace xmlname xmlname toxmlnameorindex xmlname scriptruntime lastuint32result realthis realthis xmlname id_setchildren realthis setchildren id_setlocalname localname qname localname qname localname localname scriptruntime tostring realthis setlocalname localname id_setname qname qname qname constructqnamefromstring localname qname constructqname constructqname realthis setname id_setnamespace casttonamespace realthis setnamespace id_text realthis id_tostring realthis tostring id_tosource scriptruntime toint32 realthis tosource id_toxmlstring scriptruntime toint32 realthis toxmlstring id_valueof realthis valueof id_getxmlobject xmlobject xmlobject realthis getxmlobject javatojs xmlobject illegalargumentexception valueof private static object arg object args int i return i args length args i undefined instance public class reg exp impl implements reg exp proxy public boolean is reg exp scriptable obj return obj instanceof native reg exp regexpimpl regexpproxy isregexp nativeregexp public object compile reg exp context cx string source string flags return native reg exp compilere source flags false compileregexp nativeregexp public scriptable wrap reg exp context cx scriptable scope object compiled return new native reg exp scope compiled wrapregexp nativeregexp public object action context cx scriptable scope scriptable this obj object args int action type glob data data new glob data data mode action type switch action type case ra match object rval data optarg 1 rval match or replace cx scope this obj args this data false return data arrayobj null rval data arrayobj case ra search data optarg 1 return match or replace cx scope this obj args this data false case ra replace object arg1 args length 2 undefined instance args 1 string repstr null function lambda null if arg1 instanceof function lambda function arg1 else repstr script runtime to string arg1 data optarg 2 data lambda lambda data repstr repstr data dollar repstr null 1 repstr index of data char buf null data left index 0 object val match or replace cx scope this obj args this data true sub string rc this right context if data char buf null if data global val null val equals boolean true didn t match even once return data str sub string lc this left context replace glob data cx scope this lc index lc length data char buf append rc char array rc index rc length return data char buf to string default throw kit code bug thisobj actiontype globdata globdata actiontype actiontype ra_match matchorreplace thisobj ra_search matchorreplace thisobj ra_replace scriptruntime tostring indexof charbuf leftindex matchorreplace thisobj substring rightcontext charbuf substring leftcontext replace_glob charbuf chararray charbuf tostring codebug analog of c match or replace private static object match or replace context cx scriptable scope scriptable this obj object args reg exp impl re impl glob data data boolean force flat native reg exp re string str script runtime to string this obj data str str scriptable top scope scriptable object get top level scope scope if args length 0 object compiled native reg exp compilere false re new native reg exp top scope compiled else if args 0 instanceof native reg exp re native reg exp args 0 else string src script runtime to string args 0 string opt if data optarg args length args 0 src opt script runtime to string args data optarg else opt null object compiled native reg exp compilere src opt force flat re new native reg exp top scope compiled data regexp re data global re get flags native reg exp jsreg glob 0 int indexp 0 object result null if data mode ra search result re execute reg exp cx scope re impl str indexp native reg exp test if result null result equals boolean true result new integer re impl left context length else result new integer 1 else if data global re last index 0 for int count 0 indexp 0 str length count result re execute reg exp cx scope re impl str indexp native reg exp test if result null result equals boolean true break if data mode ra match match glob data cx scope count re impl else if data mode ra replace kit code bug sub string last match re impl last match int left index data left index int leftlen last match index left index data left index last match index last match length replace glob data cx scope re impl left index leftlen if re impl last match length 0 if indexp 0 str length break indexp 0 else result re execute reg exp cx scope re impl str indexp data mode ra replace native reg exp test native reg exp match return result match_or_replace matchorreplace thisobj regexpimpl reimpl globdata forceflat nativeregexp scriptruntime tostring thisobj topscope scriptableobject gettoplevelscope nativeregexp nativeregexp topscope nativeregexp nativeregexp scriptruntime tostring scriptruntime tostring nativeregexp forceflat nativeregexp topscope getflags nativeregexp jsreg_glob ra_search executeregexp reimpl nativeregexp reimpl leftcontext lastindex executeregexp reimpl nativeregexp ra_match match_glob reimpl ra_replace codebug substring lastmatch reimpl lastmatch leftindex leftindex lastmatch leftindex leftindex lastmatch lastmatch replace_glob reimpl leftindex reimpl lastmatch executeregexp reimpl ra_replace nativeregexp nativeregexp public int find split context cx scriptable scope string target string separator scriptable re obj int ip int matchlen boolean matched string parensp int i ip 0 int length target length int result int version cx get language version native reg exp re native reg exp re obj again while true imitating c label js1 2 deviated from perl by never matching at end of string int ipsave ip 0 reuse ip to save object creation ip 0 i object ret re execute reg exp cx scope this target ip native reg exp test if ret boolean true mismatch ensure our caller advances i past end of string ip 0 ipsave matchlen 0 1 matched 0 false return length i ip 0 ip 0 ipsave matched 0 true sub string sep this last match matchlen 0 sep length if matchlen 0 0 empty string match never split on an empty match at the start of a find split cycle same rule as for an empty global match in match or replace if i ip 0 bump along to avoid sticking at an empty match but don t bump past end of string our caller must do that by adding sep length to our return value if i length if version context version 1 2 matchlen 0 1 result i else result 1 break i continue again imitating c goto pr assert size t i sep length result i matchlen 0 break int size parens null 0 parens length parensp 0 new string size for int num 0 num size num sub string parsub get paren sub string num parensp 0 num parsub to string return result find_split reobj getlanguageversion nativeregexp nativeregexp reobj executeregexp nativeregexp substring lastmatch find_split match_or_replace version_1_2 pr_assert size_t substring getparensubstring tostring analog of regexp paren substring in c jsregexp h assumes zero based i e for 3 i 2 sub string get paren sub string int i if parens null i parens length sub string parsub parens i if parsub null return parsub return sub string empty sub string regexp_paren_substring substring getparensubstring substring substring emptysubstring private static void match glob glob data mdata context cx scriptable scope int count reg exp impl re impl if mdata arrayobj null scriptable s scriptable object get top level scope scope mdata arrayobj script runtime new object cx s array null sub string matchsub re impl last match string matchstr matchsub to string mdata arrayobj put count mdata arrayobj matchstr match_glob globdata regexpimpl reimpl scriptableobject gettoplevelscope scriptruntime newobject substring reimpl lastmatch tostring private static void replace glob glob data rdata context cx scriptable scope reg exp impl re impl int left index int leftlen int replen string lambda str if rdata lambda null invoke lambda function with args last match 1 2 n left context length whole string sub string parens re impl parens int paren count parens null 0 parens length object args new object paren count 3 args 0 re impl last match to string for int i 0 i paren count i sub string sub parens i if sub null args i 1 sub to string else args i 1 undefined instance args paren count 1 new integer re impl left context length args paren count 2 rdata str this is a hack to prevent expose of re impl data to js function which can run new regexps modifing regexp that are used later by the engine todo redesign is necessary if re impl script runtime get reg exp proxy cx kit code bug reg exp impl re2 new reg exp impl re2 multiline re impl multiline re2 input re impl input script runtime set reg exp proxy cx re2 try scriptable parent scriptable object get top level scope scope object result rdata lambda call cx parent parent args lambda str script runtime to string result finally script runtime set reg exp proxy cx re impl replen lambda str length else lambda str null replen rdata repstr length if rdata dollar 0 int skip new int 1 int dp rdata dollar do sub string sub interpret dollar cx re impl rdata repstr dp skip if sub null replen sub length skip 0 dp skip 0 else dp dp rdata repstr index of dp while dp 0 int growth leftlen replen re impl right context length string buffer char buf rdata char buf if char buf null char buf new string buffer growth rdata char buf char buf else char buf ensure capacity rdata char buf length growth char buf append re impl left context char array left index leftlen if rdata lambda null char buf append lambda str else do replace rdata cx re impl replace_glob globdata regexpimpl reimpl leftindex lambdastr lastmatch leftcontext substring reimpl parencount parencount reimpl lastmatch tostring parencount substring tostring parencount reimpl leftcontext parencount reimpl reimpl scriptruntime getregexpproxy codebug regexpimpl regexpimpl reimpl reimpl scriptruntime setregexpproxy scriptableobject gettoplevelscope lambdastr scriptruntime tostring scriptruntime setregexpproxy reimpl lambdastr lambdastr substring interpretdollar reimpl indexof reimpl rightcontext stringbuffer charbuf charbuf charbuf charbuf stringbuffer charbuf charbuf charbuf ensurecapacity charbuf charbuf reimpl leftcontext chararray leftindex charbuf lambdastr do_replace reimpl private static sub string interpret dollar context cx reg exp impl res string da int dp int skip char dc int num tmp if da char at dp kit code bug allow a real backslash literal to escape 1 etc int version cx get language version if version context version default version context version 1 4 if dp 0 da char at dp 1 return null int dal da length if dp 1 dal return null interpret all perl match induced dollar variables dc da char at dp 1 if native reg exp is digit dc int cp if version context version default version context version 1 4 if dc 0 return null check for overflow to avoid gobbling arbitrary decimal digits num 0 cp dp while cp dal native reg exp is digit dc da char at cp tmp 10 num dc 0 if tmp num break num tmp else ecma 3 1 9 or 01 99 int paren count res parens null 0 res parens length num dc 0 if num paren count return null cp dp 2 if dp 2 dal dc da char at dp 2 if native reg exp is digit dc tmp 10 num dc 0 if tmp paren count cp num tmp if num 0 return null 0 or 00 is not valid adjust num from 1 n origin to 0 array index origin num skip 0 cp dp return res get paren sub string num skip 0 2 switch dc case return new sub string case return res last match case return res last paren case if version context version 1 2 js1 2 imitated the perl4 bug where left context at each step in an iterative use of a global regexp started from last match not from the start of the target string but perl4 does start at the beginning of the target string when it is used in a substitution so we emulate that special case here res left context index 0 res left context length res last match index return res left context case return res right context return null substring interpretdollar regexpimpl charat codebug getlanguageversion version_default version_1_4 charat charat nativeregexp isdigit version_default version_1_4 nativeregexp isdigit charat parencount parencount charat nativeregexp isdigit parencount getparensubstring substring lastmatch lastparen version_1_2 leftcontext leftcontext lastmatch leftcontext rightcontext analog of do replace in jsstr c private static void do replace glob data rdata context cx reg exp impl reg exp impl string buffer char buf rdata char buf int cp 0 string da rdata repstr int dp rdata dollar if dp 1 int skip new int 1 do int len dp cp char buf append da substring cp dp cp dp sub string sub interpret dollar cx reg exp impl da dp skip if sub null len sub length if len 0 char buf append sub char array sub index len cp skip 0 dp skip 0 else dp dp da index of dp while dp 0 int dal da length if dal cp char buf append da substring cp dal do_replace do_replace globdata regexpimpl regexpimpl stringbuffer charbuf charbuf charbuf substring interpretdollar regexpimpl charbuf chararray indexof charbuf public parser compiler environs compiler env error reporter error reporter this compiler env compiler env this error reporter error reporter compilerenvirons compilerenv errorreporter errorreporter compilerenv compilerenv errorreporter errorreporter protected decompiler create decompiler compiler environs compiler env return new decompiler createdecompiler compilerenvirons compilerenv void add warning string message id string message arg string message script runtime get message1 message id message arg error reporter warning message sourceuri ts get lineno ts get line ts get offset addwarning messageid messagearg scriptruntime getmessage1 messageid messagearg errorreporter getlineno getline getoffset void add error string message id syntax error count string message script runtime get message0 message id error reporter error message sourceuri ts get lineno ts get line ts get offset adderror messageid syntaxerrorcount scriptruntime getmessage0 messageid errorreporter getlineno getline getoffset runtime exception report error string message id add error message id throw a parser exception exception to unwind the recursive descent parse throw new parser exception runtimeexception reporterror messageid adderror messageid parserexception parserexception private int peek token throws io exception int tt current flagged token if tt token eof tt ts get token if tt token eol do tt ts get token while tt token eol tt ti after eol current flagged token tt return tt clear ti mask peektoken ioexception currentflaggedtoken gettoken gettoken ti_after_eol currentflaggedtoken clear_ti_mask private int peek flagged token throws io exception peek token return current flagged token peekflaggedtoken ioexception peektoken currentflaggedtoken private void consume token current flagged token token eof consumetoken currentflaggedtoken private int next token throws io exception int tt peek token consume token return tt nexttoken ioexception peektoken consumetoken private int next flagged token throws io exception peek token int tt flagged current flagged token consume token return tt flagged nextflaggedtoken ioexception peektoken ttflagged currentflaggedtoken consumetoken ttflagged private boolean match token int to match throws io exception int tt peek token if tt to match return false consume token return true matchtoken tomatch ioexception peektoken tomatch consumetoken private int peek token oreol throws io exception int tt peek token check for last peeked token flags if current flagged token ti after eol 0 tt token eol return tt peektokenoreol ioexception peektoken currentflaggedtoken ti_after_eol private void set check for label if current flagged token clear ti mask token name throw kit code bug current flagged token ti check label setcheckforlabel currentflaggedtoken clear_ti_mask codebug currentflaggedtoken ti_check_label private void must match token int to match string message id throws io exception parser exception if match token to match report error message id mustmatchtoken tomatch messageid ioexception parserexception matchtoken tomatch reporterror messageid private void must havexml if compiler env is xml available report error msg xml not available musthavexml compilerenv isxmlavailable reporterror public string get encoded source return encoded source getencodedsource encodedsource public boolean eof return ts eof boolean inside function return nesting of function 0 insidefunction nestingoffunction private node enter loop node loop label node loop nf create loop node loop label ts get lineno if loop set null loop set new obj array if loop and switch set null loop and switch set new obj array loop set push loop loop and switch set push loop return loop enterloop looplabel createloopnode looplabel getlineno loopset loopset objarray loopandswitchset loopandswitchset objarray loopset loopandswitchset private void exit loop loop set pop loop and switch set pop exitloop loopset loopandswitchset private node enter switch node switch selector int lineno node switch label node switch node nf create switch switch selector lineno if loop and switch set null loop and switch set new obj array loop and switch set push switch node return switch node enterswitch switchselector switchlabel switchnode createswitch switchselector loopandswitchset loopandswitchset objarray loopandswitchset switchnode switchnode private void exit switch loop and switch set pop exitswitch loopandswitchset public script or fn node parse string source string string sourceuri int lineno this sourceuri sourceuri this ts new token stream this null source string lineno try return parse catch io exception ex should never happen throw new illegal state exception scriptorfnnode sourcestring tokenstream sourcestring ioexception illegalstateexception public script or fn node parse reader source reader string sourceuri int lineno throws io exception this sourceuri sourceuri this ts new token stream this source reader null lineno return parse scriptorfnnode sourcereader ioexception tokenstream sourcereader private script or fn node parse throws io exception this decompiler create decompiler compiler env this nf new ir factory this current script or fn nf create script int source start offset decompiler get current offset this encoded source null decompiler add token token script this current flagged token token eof this syntax error count 0 int base lineno ts get lineno line number where source starts so we have something to add nodes to until we ve collected all the source node pn nf create leaf token block try for int tt peek token if tt token eof break node n if tt token function consume token try n function called by compile function function node function expression function node function statement catch parser exception e break else n statement nf add child to back pn n catch stack overflow error ex string msg script runtime get message0 mag too deep parser recursion throw context report runtime error msg sourceuri ts get lineno null 0 if this syntax error count 0 string msg string value of this syntax error count msg script runtime get message1 msg got syntax errors msg throw error reporter runtime error msg sourceuri base lineno null 0 current script or fn set source name sourceuri current script or fn set base lineno base lineno current script or fn set end lineno ts get lineno int source end offset decompiler get current offset current script or fn set encoded source bounds source start offset source end offset nf init script current script or fn pn if compiler env is generating source encoded source decompiler get encoded source this decompiler null it helps gc return current script or fn scriptorfnnode ioexception createdecompiler compilerenv irfactory currentscriptorfn createscript sourcestartoffset getcurrentoffset encodedsource addtoken currentflaggedtoken syntaxerrorcount baselineno getlineno createleaf peektoken consumetoken calledbycompilefunction functionnode function_expression functionnode function_statement parserexception addchildtoback stackoverflowerror scriptruntime getmessage0 reportruntimeerror getlineno syntaxerrorcount valueof syntaxerrorcount scriptruntime getmessage1 errorreporter runtimeerror baselineno currentscriptorfn setsourcename currentscriptorfn setbaselineno baselineno currentscriptorfn setendlineno getlineno sourceendoffset getcurrentoffset currentscriptorfn setencodedsourcebounds sourcestartoffset sourceendoffset initscript currentscriptorfn compilerenv isgeneratingsource encodedsource getencodedsource currentscriptorfn private node parse function body throws io exception nesting of function node pn nf create block ts get lineno try body loop for node n int tt peek token switch tt case token error case token eof case token rc break body loop case token function consume token n function function node function statement break default n statement break nf add child to back pn n catch parser exception e ignore it finally nesting of function return pn parsefunctionbody ioexception nestingoffunction createblock getlineno bodyloop peektoken bodyloop consumetoken functionnode function_statement addchildtoback parserexception nestingoffunction private node function int function type throws io exception parser exception int synthetic type function type int base lineno ts get lineno line number where source starts int function source start decompiler mark function start function type string name node member expr node null if match token token name name ts get string decompiler add name name if match token token lp if compiler env is allow member expr as function name extension to ecma if function name does not follow by assume name starts member expr node member expr head nf create name name name member expr node member expr tail false member expr head must match token token lp msg no paren parms else if match token token lp anonymous function name else name if compiler env is allow member expr as function name note that member expr can not start with like in function 1 2 to string because function already processed as anonymous function member expr node member expr false must match token token lp msg no paren parms if member expr node null synthetic type function node function expression boolean nested inside function function node fn node nf create function name if nested nesting of with 0 1 nested functions are not affected by the dynamic scope flag as dynamic scope is already a parent of their scope 2 functions defined under the with statement also immune to this setup in which case dynamic scope is ignored in favor of with object fn node its ignore dynamic scope true int function index current script or fn add function fn node int function source end script or fn node saved script or fn current script or fn current script or fn fn node int saved nesting of with nesting of with nesting of with 0 hashtable saved label set label set label set null obj array saved loop set loop set loop set null obj array saved loop and switch set loop and switch set loop and switch set null node body string source try decompiler add token token lp if match token token rp boolean first true do if first decompiler add token token comma first false must match token token name msg no parm string s ts get string if fn node has param or var s add warning msg dup parms s fn node add param s decompiler add name s while match token token comma must match token token rp msg no paren after parms decompiler add token token rp must match token token lc msg no brace body decompiler addeol token lc body parse function body must match token token rc msg no brace after body decompiler add token token rc function source end decompiler mark function end function source start if function type function node function expression if compiler env get language version context version 1 2 function f function g is not allowed in 1 2 or later but for compatibility with old scripts the check is done only if language is explicitly set xxx warning needed if version version default int tt peek token oreol if tt token function report error msg no semi stmt add eol only if function is not part of expression since it gets semi eol from statement in that case decompiler add token token eol finally loop and switch set saved loop and switch set loop set saved loop set label set saved label set nesting of with saved nesting of with current script or fn saved script or fn fn node set encoded source bounds function source start function source end fn node set source name sourceuri fn node set base lineno base lineno fn node set end lineno ts get lineno node pn nf init function fn node function index body synthetic type if member expr node null pn nf create assignment token assign member expr node pn if function type function node function expression xxx check j script behavior should it be create expr statement pn nf create expr statement no return pn base lineno return pn functiontype ioexception parserexception synthetictype functiontype baselineno getlineno functionsourcestart markfunctionstart functiontype memberexprnode matchtoken getstring addname matchtoken compilerenv isallowmemberexprasfunctionname memberexpr memberexprhead createname memberexprnode memberexprtail memberexprhead mustmatchtoken matchtoken compilerenv isallowmemberexprasfunctionname memberexpr tostring memberexprnode memberexpr mustmatchtoken memberexprnode synthetictype functionnode function_expression insidefunction functionnode fnnode createfunction nestingofwith fnnode itsignoredynamicscope functionindex currentscriptorfn addfunction fnnode functionsourceend scriptorfnnode savedscriptorfn currentscriptorfn currentscriptorfn fnnode savednestingofwith nestingofwith nestingofwith savedlabelset labelset labelset objarray savedloopset loopset loopset objarray savedloopandswitchset loopandswitchset loopandswitchset addtoken matchtoken addtoken mustmatchtoken getstring fnnode hasparamorvar addwarning fnnode addparam addname matchtoken mustmatchtoken addtoken mustmatchtoken parsefunctionbody mustmatchtoken addtoken functionsourceend markfunctionend functionsourcestart functiontype functionnode function_expression compilerenv getlanguageversion version_1_2 version_default peektokenoreol reporterror addtoken loopandswitchset savedloopandswitchset loopset savedloopset labelset savedlabelset nestingofwith savednestingofwith currentscriptorfn savedscriptorfn fnnode setencodedsourcebounds functionsourcestart functionsourceend fnnode setsourcename fnnode setbaselineno baselineno fnnode setendlineno getlineno initfunction fnnode functionindex synthetictype memberexprnode createassignment memberexprnode functiontype functionnode function_expression jscript createexprstatement createexprstatementnoreturn baselineno private node statements throws io exception node pn nf create block ts get lineno int tt while tt peek token token eof tt token rc nf add child to back pn statement return pn ioexception createblock getlineno peektoken addchildtoback private node condition throws io exception parser exception node pn must match token token lp msg no paren cond decompiler add token token lp pn expr false must match token token rp msg no paren after cond decompiler add token token rp there s a check here in jsparse c that corrects to return pn ioexception parserexception mustmatchtoken addtoken mustmatchtoken addtoken match a name return null if no match private node match jump label name throws io exception parser exception node label null int tt peek token oreol if tt token name consume token string name ts get string decompiler add name name if label set null label node label set get name if label null report error msg undef label return label matchjumplabelname ioexception parserexception peektokenoreol consumetoken getstring addname labelset labelset reporterror private node statement throws io exception try node pn statement helper null if pn null return pn catch parser exception e skip to end of statement int lineno ts get lineno guessing statement end for int tt peek token oreol consume token switch tt case token error case token eof case token eol case token semi break guessing statement end return nf create expr statement nf create name error lineno ioexception statementhelper parserexception getlineno guessingstatementend peektokenoreol consumetoken guessingstatementend createexprstatement createname whether the catch e e instanceof exception syntax is implemented private node statement helper node statement label throws io exception parser exception node pn null int tt tt peek token switch tt case token if consume token decompiler add token token if int lineno ts get lineno node cond condition decompiler addeol token lc node if true statement node if false null if match token token else decompiler add token token rc decompiler add token token else decompiler addeol token lc if false statement decompiler addeol token rc pn nf create if cond if true if false lineno return pn case token switch consume token decompiler add token token switch int lineno ts get lineno must match token token lp msg no paren switch decompiler add token token lp pn enter switch expr false lineno statement label try must match token token rp msg no paren after switch decompiler add token token rp must match token token lc msg no brace switch decompiler addeol token lc boolean has default false switch loop for tt next token node case expression switch tt case token rc break switch loop case token case decompiler add token token case case expression expr false must match token token colon msg no colon case decompiler addeol token colon break case token default if has default report error msg double switch default decompiler add token token default has default true case expression null must match token token colon msg no colon case decompiler addeol token colon break default report error msg bad switch break switch loop node block nf create leaf token block while tt peek token token rc tt token case tt token default tt token eof nf add child to back block statement case expression null add default lable nf add switch case pn case expression block decompiler addeol token rc nf close switch pn finally exit switch return pn case token while consume token decompiler add token token while node loop enter loop statement label try node cond condition decompiler addeol token lc node body statement decompiler addeol token rc pn nf create while loop cond body finally exit loop return pn case token do consume token decompiler add token token do decompiler addeol token lc node loop enter loop statement label try node body statement decompiler add token token rc must match token token while msg no while do decompiler add token token while node cond condition pn nf create do while loop body cond finally exit loop always auto insert semicon to follow spider monkey it is required by ema script but is ignored by the rest of world see bug 238945 match token token semi decompiler addeol token semi return pn case token for consume token boolean is for each false decompiler add token token for node loop enter loop statement label try node init node init is also foo in foo in object node cond node cond is also object in foo in object node incr null to kill warning node body see if this is a for each instead of just a for if match token token name decompiler add name ts get string if ts get string equals each is for each true else report error msg no paren for must match token token lp msg no paren for decompiler add token token lp tt peek token if tt token semi init nf create leaf token empty else if tt token var set init to a var list or initial consume token consume the var token init variables true else init expr true if match token token in decompiler add token token in cond is the object over which we re iterating cond expr false else ordinary for loop must match token token semi msg no semi for decompiler add token token semi if peek token token semi no loop condition cond nf create leaf token empty else cond expr false must match token token semi msg no semi for cond decompiler add token token semi if peek token token rp incr nf create leaf token empty else incr expr false must match token token rp msg no paren for ctrl decompiler add token token rp decompiler addeol token lc body statement decompiler addeol token rc if incr null cond could be null if in obj got eaten by the init node pn nf create for in loop init cond body is for each else pn nf create for loop init cond incr body finally exit loop return pn case token try consume token int lineno ts get lineno node tryblock node catchblocks null node finallyblock null decompiler add token token try decompiler addeol token lc tryblock statement decompiler addeol token rc catchblocks nf create leaf token block boolean saw default catch false int peek peek token if peek token catch while match token token catch if saw default catch report error msg catch unreachable decompiler add token token catch must match token token lp msg no paren catch decompiler add token token lp must match token token name msg bad catchcond string var name ts get string decompiler add name var name node catch cond null if match token token if decompiler add token token if catch cond expr false else saw default catch true must match token token rp msg bad catchcond decompiler add token token rp must match token token lc msg no brace catchblock decompiler addeol token lc nf add child to back catchblocks nf create catch var name catch cond statements ts get lineno must match token token rc msg no brace after body decompiler addeol token rc else if peek token finally must match token token finally statementhelper statementlabel ioexception parserexception peektoken consumetoken addtoken getlineno iftrue iffalse matchtoken addtoken addtoken iffalse createif iftrue iffalse consumetoken addtoken getlineno mustmatchtoken addtoken enterswitch statementlabel mustmatchtoken addtoken mustmatchtoken hasdefault switchloop nexttoken caseexpression switchloop addtoken caseexpression mustmatchtoken hasdefault reporterror addtoken hasdefault caseexpression mustmatchtoken reporterror switchloop createleaf peektoken addchildtoback caseexpression addswitchcase caseexpression closeswitch exitswitch consumetoken addtoken enterloop statementlabel createwhile exitloop consumetoken addtoken enterloop statementlabel addtoken mustmatchtoken addtoken createdowhile exitloop spidermonkey emascript matchtoken consumetoken isforeach addtoken enterloop statementlabel matchtoken addname getstring getstring isforeach reporterror mustmatchtoken addtoken peektoken createleaf consumetoken matchtoken addtoken mustmatchtoken addtoken peektoken createleaf mustmatchtoken addtoken peektoken createleaf mustmatchtoken addtoken createforin isforeach createfor exitloop consumetoken getlineno addtoken createleaf sawdefaultcatch peektoken matchtoken sawdefaultcatch reporterror addtoken mustmatchtoken addtoken mustmatchtoken varname getstring addname varname catchcond matchtoken addtoken catchcond sawdefaultcatch mustmatchtoken addtoken mustmatchtoken addchildtoback createcatch varname catchcond getlineno mustmatchtoken mustmatchtoken private node variables boolean in for init throws io exception parser exception node pn nf create variables ts get lineno boolean first true decompiler add token token var for node name node init must match token token name msg bad var string s ts get string if first decompiler add token token comma first false decompiler add name s current script or fn add var s name nf create name s omitted check for argument hiding if match token token assign decompiler add token token assign init assign expr in for init nf add child to back name init nf add child to back pn name if match token token comma break return pn inforinit ioexception parserexception createvariables getlineno addtoken mustmatchtoken getstring addtoken addname currentscriptorfn addvar createname matchtoken addtoken assignexpr inforinit addchildtoback addchildtoback matchtoken private node expr boolean in for init throws io exception parser exception node pn assign expr in for init while match token token comma decompiler add token token comma pn nf create binary token comma pn assign expr in for init return pn inforinit ioexception parserexception assignexpr inforinit matchtoken addtoken createbinary assignexpr inforinit private node assign expr boolean in for init throws io exception parser exception node pn cond expr in for init int tt peek token if token first assign tt tt token last assign consume token decompiler add token tt pn nf create assignment tt pn assign expr in for init return pn assignexpr inforinit ioexception parserexception condexpr inforinit peektoken first_assign last_assign consumetoken addtoken createassignment assignexpr inforinit private node cond expr boolean in for init throws io exception parser exception node if true node if false node pn or expr in for init if match token token hook decompiler add token token hook if true assign expr false must match token token colon msg no colon cond decompiler add token token colon if false assign expr in for init return nf create cond expr pn if true if false return pn condexpr inforinit ioexception parserexception iftrue iffalse orexpr inforinit matchtoken addtoken iftrue assignexpr mustmatchtoken addtoken iffalse assignexpr inforinit createcondexpr iftrue iffalse private node or expr boolean in for init throws io exception parser exception node pn and expr in for init if match token token or decompiler add token token or pn nf create binary token or pn or expr in for init return pn orexpr inforinit ioexception parserexception andexpr inforinit matchtoken addtoken createbinary orexpr inforinit private node and expr boolean in for init throws io exception parser exception node pn bit or expr in for init if match token token and decompiler add token token and pn nf create binary token and pn and expr in for init return pn andexpr inforinit ioexception parserexception bitorexpr inforinit matchtoken addtoken createbinary andexpr inforinit private node bit or expr boolean in for init throws io exception parser exception node pn bit xor expr in for init while match token token bitor decompiler add token token bitor pn nf create binary token bitor pn bit xor expr in for init return pn bitorexpr inforinit ioexception parserexception bitxorexpr inforinit matchtoken addtoken createbinary bitxorexpr inforinit private node bit xor expr boolean in for init throws io exception parser exception node pn bit and expr in for init while match token token bitxor decompiler add token token bitxor pn nf create binary token bitxor pn bit and expr in for init return pn bitxorexpr inforinit ioexception parserexception bitandexpr inforinit matchtoken addtoken createbinary bitandexpr inforinit private node bit and expr boolean in for init throws io exception parser exception node pn eq expr in for init while match token token bitand decompiler add token token bitand pn nf create binary token bitand pn eq expr in for init return pn bitandexpr inforinit ioexception parserexception eqexpr inforinit matchtoken addtoken createbinary eqexpr inforinit private node eq expr boolean in for init throws io exception parser exception node pn rel expr in for init for int tt peek token switch tt case token eq case token ne case token sheq case token shne consume token int decompiler token tt int parse token tt if compiler env get language version context version 1 2 java script 1 2 uses shallow equality for and in addition convert and for decompiler into and since the decompiler is supposed to show canonical source and in 1 2 are allowed only as an alias to switch tt case token eq parse token token sheq break case token ne parse token token shne break case token sheq decompiler token token eq break case token shne decompiler token token ne break decompiler add token decompiler token pn nf create binary parse token pn rel expr in for init continue break return pn eqexpr inforinit ioexception parserexception relexpr inforinit peektoken consumetoken decompilertoken parsetoken compilerenv getlanguageversion version_1_2 javascript parsetoken parsetoken decompilertoken decompilertoken addtoken decompilertoken createbinary parsetoken relexpr inforinit private node rel expr boolean in for init throws io exception parser exception node pn shift expr for int tt peek token switch tt case token in if in for init break fall through case token instanceof case token le case token lt case token ge case token gt consume token decompiler add token tt pn nf create binary tt pn shift expr continue break return pn relexpr inforinit ioexception parserexception shiftexpr peektoken inforinit consumetoken addtoken createbinary shiftexpr private node shift expr throws io exception parser exception node pn add expr for int tt peek token switch tt case token lsh case token ursh case token rsh consume token decompiler add token tt pn nf create binary tt pn add expr continue break return pn shiftexpr ioexception parserexception addexpr peektoken consumetoken addtoken createbinary addexpr private node add expr throws io exception parser exception node pn mul expr for int tt peek token if tt token add tt token sub consume token decompiler add token tt flush new lines pn nf create binary tt pn mul expr continue break return pn addexpr ioexception parserexception mulexpr peektoken consumetoken addtoken flushnewlines createbinary mulexpr private node mul expr throws io exception parser exception node pn unary expr for int tt peek token switch tt case token mul case token div case token mod consume token decompiler add token tt pn nf create binary tt pn unary expr continue break return pn mulexpr ioexception parserexception unaryexpr peektoken consumetoken addtoken createbinary unaryexpr private node unary expr throws io exception parser exception int tt tt peek token switch tt case token void case token not case token bitnot case token typeof consume token decompiler add token tt return nf create unary tt unary expr case token add consume token convert to special pos token in decompiler and parse tree decompiler add token token pos return nf create unary token pos unary expr case token sub consume token convert to special neg token in decompiler and parse tree decompiler add token token neg return nf create unary token neg unary expr case token inc case token dec consume token decompiler add token tt return nf create inc dec tt false member expr true case token delprop consume token decompiler add token token delprop return nf create unary token delprop unary expr case token error consume token break xml stream encountered in expression case token lt if compiler env is xml available consume token node pn xml initializer return member expr tail true pn fall thru to the default handling of relop default node pn member expr true don t look across a newline boundary for a postfix incop tt peek token oreol if tt token inc tt token dec consume token decompiler add token tt return nf create inc dec tt true pn return pn return nf create name err only reached on error try to continue unaryexpr ioexception parserexception peektoken consumetoken addtoken createunary unaryexpr consumetoken addtoken createunary unaryexpr consumetoken addtoken createunary unaryexpr consumetoken addtoken createincdec memberexpr consumetoken addtoken createunary unaryexpr consumetoken compilerenv isxmlavailable consumetoken xmlinitializer memberexprtail memberexpr peektokenoreol consumetoken addtoken createincdec createname private node xml initializer throws io exception int tt ts get firstxml token if tt token xml tt token xmlend report error msg syntax return null make a new node to append to node pnxml nf create leaf token new string xml ts get string boolean f anonymous xml trim starts with node pn nf create name f anonymous xml list xml nf add child to back pnxml pn pn null node expr for tt ts get nextxml token switch tt case token xml xml ts get string decompiler add name xml must match token token lc msg syntax decompiler add token token lc expr peek token token rc nf create string expr false must match token token rc msg syntax decompiler add token token rc if pn null pn nf create string xml else pn nf create binary token add pn nf create string xml int node type if ts isxml attribute node type token escxmlattr else node type token escxmltext expr nf create unary node type expr pn nf create binary token add pn expr break case token xmlend xml ts get string decompiler add name xml if pn null pn nf create string xml else pn nf create binary token add pn nf create string xml nf add child to back pnxml pn return pnxml default report error msg syntax return null xmlinitializer ioexception getfirstxmltoken reporterror createleaf getstring fanonymous startswith createname fanonymous xmllist addchildtoback getnextxmltoken getstring addname mustmatchtoken addtoken peektoken createstring mustmatchtoken addtoken createstring createbinary createstring nodetype isxmlattribute nodetype nodetype createunary nodetype createbinary getstring addname createstring createbinary createstring addchildtoback reporterror private void argument list node list node throws io exception parser exception boolean matched matched match token token rp if matched boolean first true do if first decompiler add token token comma first false nf add child to back list node assign expr false while match token token comma must match token token rp msg no paren arg decompiler add token token rp argumentlist listnode ioexception parserexception matchtoken addtoken addchildtoback listnode assignexpr matchtoken mustmatchtoken addtoken private node member expr boolean allow call syntax throws io exception parser exception int tt node pn check for new expressions tt peek token if tt token new eat the new token consume token decompiler add token token new make a new node to append to pn nf create call or new token new member expr false if match token token lp decompiler add token token lp add the arguments to pn if any are supplied argument list pn xxx there s a check in the c source against too many constructor arguments how many do we claim to support experimental syntax allow an object literal to follow a new expression which will mean a kind of anonymous class built with the java adapter the object literal will be passed as an additional argument to the constructor tt peek token if tt token lc nf add child to back pn primary expr else pn primary expr return member expr tail allow call syntax pn memberexpr allowcallsyntax ioexception parserexception peektoken consumetoken addtoken createcallornew memberexpr matchtoken addtoken argumentlist javaadapter peektoken addchildtoback primaryexpr primaryexpr memberexprtail allowcallsyntax private node member expr tail boolean allow call syntax node pn throws io exception parser exception tail loop for int tt peek token switch tt case token dot case token dotdot int member type flags string s consume token decompiler add token tt member type flags 0 if tt token dotdot must havexml member type flags node descendants flag if compiler env is xml available must match token token name msg no name after dot s ts get string decompiler add name s pn nf create property get pn null s member type flags break tt next token switch tt handles name ns name ns ns expr case token name s ts get string decompiler add name s pn property name pn s member type flags break handles name expr case token mul decompiler add name pn property name pn member type flags break handles attr ns attr ns ns attr attr case token xmlattr decompiler add token token xmlattr pn attribute access pn member type flags break default report error msg no name after dot break case token dotquery consume token must havexml decompiler add token token dotquery pn nf create dot query pn expr false ts get lineno must match token token rp msg no paren decompiler add token token rp break case token lb consume token decompiler add token token lb pn nf create element get pn null expr false 0 must match token token rb msg no bracket index decompiler add token token rb break case token lp if allow call syntax break tail loop consume token decompiler add token token lp pn nf create call or new token call pn add the arguments to pn if any are supplied argument list pn break default break tail loop return pn memberexprtail allowcallsyntax ioexception parserexception tailloop peektoken membertypeflags consumetoken addtoken membertypeflags musthavexml membertypeflags descendants_flag compilerenv isxmlavailable mustmatchtoken getstring addname createpropertyget membertypeflags nexttoken getstring addname propertyname membertypeflags addname propertyname membertypeflags addtoken attributeaccess membertypeflags reporterror consumetoken musthavexml addtoken createdotquery getlineno mustmatchtoken addtoken consumetoken addtoken createelementget mustmatchtoken addtoken allowcallsyntax tailloop consumetoken addtoken createcallornew argumentlist tailloop private node attribute access node pn int member type flags throws io exception member type flags node attribute flag int tt next token switch tt handles name ns name ns ns expr case token name string s ts get string decompiler add name s pn property name pn s member type flags break handles name expr case token mul decompiler add name pn property name pn member type flags break handles expr case token lb decompiler add token token lb pn nf create element get pn null expr false member type flags must match token token rb msg no bracket index decompiler add token token rb break default report error msg no name after xml attr pn nf create property get pn null member type flags break return pn attributeaccess membertypeflags ioexception membertypeflags attribute_flag nexttoken getstring addname propertyname membertypeflags addname propertyname membertypeflags addtoken createelementget membertypeflags mustmatchtoken addtoken reporterror xmlattr createpropertyget membertypeflags check if follows name in which case it becomes qualified name private node property name node pn string name int member type flags throws io exception parser exception string namespace null if match token token coloncolon decompiler add token token coloncolon namespace name int tt next token switch tt handles name name case token name name ts get string decompiler add name name break handles name case token mul decompiler add name name break handles name expr case token lb decompiler add token token lb pn nf create element get pn namespace expr false member type flags must match token token rb msg no bracket index decompiler add token token rb return pn default report error msg no name after coloncolon name pn nf create property get pn namespace name member type flags return pn propertyname membertypeflags ioexception parserexception matchtoken addtoken nexttoken getstring addname addname addtoken createelementget membertypeflags mustmatchtoken addtoken reporterror createpropertyget membertypeflags private node primary expr throws io exception parser exception node pn int tt flagged next flagged token int tt tt flagged clear ti mask switch tt case token function return function function node function expression case token lb obj array elems new obj array int skip count 0 decompiler add token token lb boolean after lb or comma true for tt peek token if tt token comma consume token decompiler add token token comma if after lb or comma after lb or comma true else elems add null skip count else if tt token rb consume token decompiler add token token rb break else if after lb or comma report error msg no bracket arg elems add assign expr false after lb or comma false return nf create array literal elems skip count case token lc obj array elems new obj array decompiler add token token lc if match token token rc boolean first true commaloop do object property if first decompiler add token token comma else first false tt peek token switch tt case token name case token string consume token map nam es to strin gs in object literal context but tell the decompiler the proper type string s ts get string if tt token name decompiler add name s else decompiler add string s property script runtime get index object s break case token number consume token double n ts get number decompiler add number n property script runtime get index object n break case token rc trailing comma is ok break commaloop default report error msg bad prop break commaloop must match token token colon msg no colon prop objlit is used as in object literal for decompilation to solve spacing ambiguity decompiler add token token objectlit elems add property elems add assign expr false while match token token comma must match token token rc msg no brace prop decompiler add token token rc return nf create object literal elems case token lp brendan s ir jsparse c makes a new node tagged with tok lp here i m not sure i understand why isn t the grouping already implicit in the structure of the parse tree also tok lp is already overloaded i think in the c ir as function call decompiler add token token lp pn expr false decompiler add token token rp must match token token rp msg no paren return pn case token xmlattr must havexml decompiler add token token xmlattr pn attribute access null 0 return pn case token name string name ts get string if tt flagged ti check label 0 if peek token token colon do not consume colon it is used as unwind indicator to return to statement helper xxx better way return nf create label ts get lineno decompiler add name name if compiler env is xml available pn property name null name 0 else pn nf create name name return pn case token number double n ts get number decompiler add number n return nf create number n case token string string s ts get string decompiler add string s return nf create string s case token div case token assign div got or which should be treated as regexp in fact ts read reg exp tt string flags ts reg exp flags ts reg exp flags null string re ts get string decompiler add regexp re flags int index current script or fn add regexp re flags return nf create reg exp index case token null case token this case token false case token true decompiler add token tt return nf create leaf tt case token reserved report error msg reserved id break case token error the scanner or one of its subroutines reported the error break case token eof report error msg unexpected eof break default report error msg syntax break return null should never reach here primaryexpr ioexception parserexception ttflagged nextflaggedtoken ttflagged clear_ti_mask functionnode function_expression objarray objarray skipcount addtoken after_lb_or_comma peektoken consumetoken addtoken after_lb_or_comma after_lb_or_comma skipcount consumetoken addtoken after_lb_or_comma reporterror assignexpr after_lb_or_comma createarrayliteral skipcount objarray objarray addtoken matchtoken addtoken peektoken consumetoken names strings getstring addname addstring scriptruntime getindexobject consumetoken getnumber addnumber scriptruntime getindexobject reporterror mustmatchtoken addtoken assignexpr matchtoken mustmatchtoken addtoken createobjectliteral tok_lp tok_lp addtoken addtoken mustmatchtoken musthavexml addtoken attributeaccess getstring ttflagged ti_check_label peektoken statementhelper createlabel getlineno addname compilerenv isxmlavailable propertyname createname getnumber addnumber createnumber getstring addstring createstring assign_div readregexp regexpflags regexpflags getstring addregexp currentscriptorfn addregexp createregexp addtoken createleaf reporterror reporterror reporterror public int float 512 public int ambiguous float arg return float public int ambiguous double arg return double public int ambiguous byte arg return byte public int ambiguous char arg return char public int ambiguous short arg return short public int ambiguous int arg return int public int ambiguous long arg return long public int ambiguous string arg return string return string public int expect return string public class datatypes 019 extends live connect test public datatypes 019 super datatypes_019 liveconnecttest datatypes_019 public static void main string args datatypes 019 test new datatypes 019 test start datatypes_019 datatypes_019 public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class global eval var dt new dt file bugnumber 302019 setuptestenvironment setuptestenvironment datatypeclass public void execute test string expected string value data type class pub string representation int expected number value data type class pub number representation double expected double value data type class pub double representation string actual string value double actual number value 0 double actual double value 0 string js string double js number 0 try actual string value string global eval dt to string actual number value double global eval dt to number double value actual double value double global eval dt double value double value js string string global eval var js string string dt js string js number double global eval var js number number dt js number double value catch exception e e print stack trace file exception e to string add test case dt to string expected string value actual string value file exception add test case actual number value expected number value dt to number expected number value actual number value true expected number value actual number value file exception add test case actual double value expected double value dt double value expected double value actual double value true expected double value actual double value file exception add test case global eval var js string string dt js string js string equals expected string value true js string equals expected string value file exception add test case js number js number global eval var js number number dt js number js number expected double value true js number expected double value file exception executetest expectedstringvalue datatypeclass pub_string_representation expectednumbervalue datatypeclass pub_number_representation expecteddoublevalue datatypeclass pub_double_representation actualstringvalue actualnumbervalue actualdoublevalue jsstring jsnumber actualstringvalue tostring actualnumbervalue tonumber doublevalue actualdoublevalue doublevalue doublevalue jsstring jsstring jsstring jsnumber jsnumber jsnumber doublevalue printstacktrace tostring addtestcase tostring expectedstringvalue actualstringvalue addtestcase actualnumbervalue expectednumbervalue tonumber expectednumbervalue actualnumbervalue expectednumbervalue actualnumbervalue addtestcase actualdoublevalue expecteddoublevalue doublevalue expecteddoublevalue actualdoublevalue expecteddoublevalue actualdoublevalue addtestcase jsstring jsstring jsstring expectedstringvalue jsstring expectedstringvalue addtestcase jsnumber jsnumber jsnumber jsnumber jsnumber expecteddoublevalue jsnumber expecteddoublevalue public class datatypes 017 extends live connect test public datatypes 017 super datatypes_017 liveconnecttest datatypes_017 public static void main string args datatypes 017 test new datatypes 017 test start datatypes_017 datatypes_017 public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class global eval var dt new dt setuptestenvironment setuptestenvironment datatypeclass call the setter test with 5 values ul li string value to call setters getters with li method to set the value li method to get the value li field that returns the value li expected result of getter field li whether or not an exception gets thrown ul the rules for conversion ul li if the setter sets the value out of the range return an exception li if the value is in range transform value to math floor value li nan returns 0 ul public void execute test for int i 0 i js vals length i do setter test js vals i dt set double dt get double dt pub double new double js vals i double value double max value object exception new double js vals i double value double min value object exception new double js vals i do setter test dt set byte js vals i dt get byte dt pub byte number new byte new float js vals i byte value new float byte max value new float byte min value do setter test dt set short js vals i dt get short dt pub short number new short new double js vals i short value new float short max value new float short min value do setter test dt set integer js vals i dt get integer dt pub int number new integer new double js vals i int value new float integer max value new float integer min value do setter test dt set float js vals i dt get float dt pub float number new float new double js vals i float value new float float max value new float float min value do setter test dt set long js vals i dt get long dt pub long number new long new double js vals i long value new float long max value new float long min value executetest jsvals dosettertest jsvals setdouble getdouble pub_double jsvals doublevalue max_value jsvals doublevalue min_value jsvals dosettertest setbyte jsvals getbyte pub_byte jsvals bytevalue max_value min_value dosettertest setshort jsvals getshort pub_short jsvals shortvalue max_value min_value dosettertest setinteger jsvals getinteger pub_int jsvals intvalue max_value min_value dosettertest setfloat jsvals getfloat pub_float jsvals floatvalue max_value min_value dosettertest setlong jsvals getlong pub_long jsvals longvalue max_value min_value this tests calls a java setter method from java script it verifies that the setter was called properly in two ways by checking the return value of the getter method and by checking the value of the public field that was set param setter java method that takes an argument and sets a value param js value java script value that is passed to the setter param getter java method that returns the value set by setter param field java field that setter changed param e result expected result which should be of some number type public void do setter test string js value string setter string getter string field object e result string set method setter js value string get method getter string setter result no exception thrown double getter result null double field result null object expected result null boolean eq false try eq e result get class equals class for name java lang string catch class not found exception e add test case set method driver error very bad file exception if eq try global eval set method catch exception e setter result exception file exception e to string e print stack trace finally add test case set method should throw a js exception exception setter result file exception else try from java script call the setter global eval set method from java script call the getter getter result double global eval get method from java sript access the field field result double global eval field catch exception e e print stack trace file exception e to string finally add test case value getter result expected expected result set method get method expected result equals getter result true expected result equals getter result file exception add test case value field result expected expected result set method field expected result equals field result true expected result equals field result file exception javascript jsvalue javascript eresult dosettertest jsvalue eresult setmethod jsvalue getmethod setterresult getterresult fieldresult expectedresult eresult getclass forname classnotfoundexception addtestcase setmethod setmethod setterresult tostring printstacktrace addtestcase setmethod jsexception setterresult javascript setmethod javascript getterresult getmethod javasript fieldresult printstacktrace tostring addtestcase getterresult expectedresult setmethod getmethod expectedresult getterresult expectedresult getterresult addtestcase fieldresult expectedresult setmethod expectedresult fieldresult expectedresult fieldresult q name xml lib impl lib string uri string local name string prefix super lib global scope lib qname prototype if local name null throw new illegal argument exception this lib lib this uri uri this prefix prefix this local name local name qname xmllibimpl localname globalscope qnameprototype localname illegalargumentexception localname localname void export asjs class boolean sealed export asjs class max prototype id lib global scope sealed exportasjsclass exportasjsclass max_prototype_id globalscope return public string to string string result if uri null result concat local name else if uri length 0 result local name else result uri local name return result tostring localname localname localname public string local name return local name localname localname string prefix return prefix null prefix string uri return uri public boolean equals object obj if obj instanceof q name return false return equals q name obj qname qname protected object equivalent values object value if value instanceof q name return scriptable not found boolean result equals q name value return result boolean true boolean false equivalentvalues qname not_found qname private boolean equals q name q boolean result if uri null result q uri null local name equals q local name else result uri equals q uri local name equals q local name return result qname localname localname localname localname return public string get class name return q name getclassname qname param hint return public object get default value class hint return to string getdefaultvalue tostring max instance id 2 protected int get max instance id return super get max instance id max instance id max_instance_id getmaxinstanceid getmaxinstanceid max_instance_id protected int find instance id info string s int id generated last update 2004 07 18 12 32 51 cest l0 id 0 string x null int s length s length if s length 3 x uri id id uri else if s length 9 x local name id id localname if x null x s x equals s id 0 generated if id 0 return super find instance id info s int attr switch id case id localname case id uri attr permanent readonly break default throw new illegal state exception return instance id info attr super get max instance id id findinstanceidinfo s_length s_length id_uri s_length localname id_localname findinstanceidinfo id_localname id_uri illegalstateexception instanceidinfo getmaxinstanceid protected string get instance id name int id switch id super get max instance id case id localname return local name case id uri return uri return super get instance id name id getinstanceidname getmaxinstanceid id_localname localname id_uri getinstanceidname protected object get instance id value int id switch id super get max instance id case id localname return local name case id uri return uri return super get instance id value id getinstanceidvalue getmaxinstanceid id_localname localname id_uri getinstanceidvalue protected int find prototype id string s int id generated last update 2004 08 21 12 45 13 cest l0 id 0 string x null int c int s length s length if s length 8 c s char at 3 if c o x to source id id tosource else if c t x to string id id tostring else if s length 11 x constructor id id constructor if x null x s x equals s id 0 generated return id findprototypeid s_length s_length charat tosource id_tosource tostring id_tostring s_length id_constructor protected void init prototype id int id string s int arity switch id case id constructor arity 2 s constructor break case id tostring arity 0 s to string break case id tosource arity 0 s to source break default throw new illegal argument exception string value of id init prototype method qname tag id s arity initprototypeid id_constructor id_tostring tostring id_tosource tosource illegalargumentexception valueof initprototypemethod qname_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag qname tag return super exec id call f cx scope this obj args int id f method id switch id case id constructor return js constructor cx this obj null args case id tostring return real this this obj f to string case id tosource return real this this obj f js tosource throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag qname_tag execidcall thisobj methodid id_constructor jsconstructor thisobj id_tostring realthis thisobj tostring id_tosource realthis thisobj js_tosource illegalargumentexception valueof private q name real this scriptable this obj id function object f if this obj instanceof q name throw incompatible call error f return q name this obj qname realthis thisobj idfunctionobject thisobj qname incompatiblecallerror qname thisobj private object js constructor context cx boolean in new expr object args if in new expr args length 1 return lib cast toq name cx args 0 if args length 0 return lib constructq name cx undefined instance else if args length 1 return lib constructq name cx args 0 else return lib constructq name cx args 0 args 1 jsconstructor innewexpr innewexpr casttoqname constructqname constructqname constructqname private string js tosource string buffer sb new string buffer sb append to source impl uri local name prefix sb sb append return sb to string js_tosource stringbuffer stringbuffer tosourceimpl localname tostring private static void to source impl string uri string local name string prefix string buffer sb sb append new q name if uri null prefix null if equals local name sb append null else namespace to source impl prefix uri sb sb append sb append sb append script runtime escape string local name sb append tosourceimpl localname stringbuffer qname localname tosourceimpl scriptruntime escapestring localname public id value pair string id string value this id length id length this id id this value value idvaluepair idlength public int get line number return line number getlinenumber linenumber public int get line number return line number public void set line number int value line number value getlinenumber linenumber setlinenumber linenumber public string float float public string ambiguous boolean arg return boolean object boolean_object public string ambiguous boolean arg return boolean public string ambiguous object arg return object public string ambiguous string arg return string public string ambiguous byte arg return byte public string ambiguous char arg return char public string expect return char java adapter signature class super class class interfaces obj to int map names this super class super class this interfaces interfaces this names names javaadaptersignature superclass objtointmap superclass superclass public boolean equals object obj if obj instanceof java adapter signature return false java adapter signature sig java adapter signature obj if super class sig super class return false if interfaces sig interfaces if interfaces length sig interfaces length return false for int i 0 i interfaces length i if interfaces i sig interfaces i return false if names size sig names size return false obj to int map iterator iter new obj to int map iterator names for iter start iter done iter next string name string iter get key int arity iter get value if arity names get name arity 1 return false return true javaadaptersignature javaadaptersignature javaadaptersignature superclass superclass objtointmap objtointmap getkey getvalue public int hash code return super class hash code 0x9e3779b9 names size interfaces length 16 hashcode superclass hashcode public static void init context cx scriptable scope boolean sealed java adapter obj new java adapter id function object ctor new id function object obj ftag id javaadapter java adapter 1 scope ctor mark as constructor null if sealed ctor seal object ctor export as scope property javaadapter javaadapter idfunctionobject idfunctionobject id_javaadapter javaadapter markasconstructor sealobject exportasscopeproperty public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag ftag if f method id id javaadapter return js createadpter cx scope args throw f unknown execidcall idfunctionobject thisobj hastag methodid id_javaadapter js_createadpter public static object convert result object result class c if result undefined instance c script runtime object class c script runtime string class avoid an error for an undefined value return null instead return null return context js to java result c convertresult scriptruntime objectclass scriptruntime stringclass jstojava public static scriptable create adapter wrapper scriptable obj object adapter scriptable scope scriptable object get top level scope obj native java object res new native java object scope adapter null res set prototype obj return res createadapterwrapper scriptableobject gettoplevelscope nativejavaobject nativejavaobject setprototype public static object get adapter self class adapter class object adapter throws no such field exception illegal access exception field self adapter class get declared field self return self get adapter getadapterself adapterclass nosuchfieldexception illegalaccessexception adapterclass getdeclaredfield static object js createadpter context cx scriptable scope object args int n args length if n 0 throw script runtime type error0 msg adapter zero args class super class null class intfs new class n 1 int interface count 0 for int i 0 i n 1 i object arg args i if arg instanceof native java class throw script runtime type error2 msg not java class arg string value of i script runtime to string arg class c native java class arg get class object if c is interface if super class null throw script runtime type error2 msg only one super super class get name c get name super class c else intfs interface count c if super class null super class script runtime object class class interfaces new class interface count system arraycopy intfs 0 interfaces 0 interface count scriptable obj script runtime to object cx scope args n 1 class adapter class get adapter class scope super class interfaces obj class ctor parms script runtime context factory class script runtime scriptable class object ctor args cx get factory obj try object adapter adapter class get constructor ctor parms new instance ctor args return get adapter self adapter class adapter catch exception ex throw context throw as script runtime ex ex js_createadpter scriptruntime typeerror0 superclass interfacecount nativejavaclass scriptruntime typeerror2 valueof scriptruntime tostring nativejavaclass getclassobject isinterface superclass scriptruntime typeerror2 superclass getname getname superclass interfacecount superclass superclass scriptruntime objectclass interfacecount interfacecount scriptruntime toobject adapterclass getadapterclass superclass ctorparms scriptruntime contextfactoryclass scriptruntime scriptableclass ctorargs getfactory adapterclass getconstructor ctorparms newinstance ctorargs getadapterself adapterclass throwasscriptruntimeex needed by native java object serializer public static void write adapter object object java object object output stream out throws io exception class cl java object get class out write object cl get superclass get name class interfaces cl get interfaces string interface names new string interfaces length for int i 0 i interfaces length i interface names i interfaces i get name out write object interface names try object delegee cl get field delegee get java object out write object delegee return catch illegal access exception e catch no such field exception e throw new io exception nativejavaobject writeadapterobject javaobject objectoutputstream ioexception javaobject getclass writeobject getsuperclass getname getinterfaces interfacenames interfacenames getname writeobject interfacenames getfield javaobject writeobject illegalaccessexception nosuchfieldexception ioexception needed by native java object de serializer public static object read adapter object scriptable self object input stream in throws io exception class not found exception context factory factory context cx context get current context if cx null factory cx get factory else factory null class super class class for name string in read object string interface names string in read object class interfaces new class interface names length for int i 0 i interface names length i interfaces i class for name interface names i scriptable delegee scriptable in read object class adapter class get adapter class self super class interfaces delegee class ctor parms script runtime context factory class script runtime scriptable class script runtime scriptable class object ctor args factory delegee self try return adapter class get constructor ctor parms new instance ctor args catch instantiation exception e catch illegal access exception e catch invocation target exception e catch no such method exception e throw new class not found exception adapter nativejavaobject readadapterobject objectinputstream ioexception classnotfoundexception contextfactory getcurrentcontext getfactory superclass forname readobject interfacenames readobject interfacenames interfacenames forname interfacenames readobject adapterclass getadapterclass superclass ctorparms scriptruntime contextfactoryclass scriptruntime scriptableclass scriptruntime scriptableclass ctorargs adapterclass getconstructor ctorparms newinstance ctorargs instantiationexception illegalaccessexception invocationtargetexception nosuchmethodexception classnotfoundexception private static obj to int map get object function names scriptable obj object ids scriptable object get property ids obj obj to int map map new obj to int map ids length for int i 0 i ids length i if ids i instanceof string continue string id string ids i object value scriptable object get property obj id if value instanceof function function f function value int length script runtime to int32 scriptable object get property f length if length 0 length 0 map put id length return map objtointmap getobjectfunctionnames scriptableobject getpropertyids objtointmap objtointmap scriptableobject getproperty scriptruntime toint32 scriptableobject getproperty private static class get adapter class scriptable scope class super class class interfaces scriptable obj class cache cache class cache get scope hashtable generated cache java adapter generated classes obj to int map names get object function names obj java adapter signature sig sig new java adapter signature super class interfaces names class adapter class class generated get sig if adapter class null string adapter name adapter cache new class serial number byte code create adapter code names adapter name super class interfaces null adapter class load adapter class adapter name code if cache is caching enabled generated put sig adapter class return adapter class getadapterclass superclass classcache classcache javaadaptergeneratedclasses objtointmap getobjectfunctionnames javaadaptersignature javaadaptersignature superclass adapterclass adapterclass adaptername newclassserialnumber createadaptercode adaptername superclass adapterclass loadadapterclass adaptername iscachingenabled adapterclass adapterclass public static byte create adapter code obj to int map function names string adapter name class super class class interfaces string script class name class file writer cfw new class file writer adapter name super class get name adapter cfw add field factory lorg mozilla javascript context factory short class file writer acc public class file writer acc final cfw add field delegee lorg mozilla javascript scriptable short class file writer acc public class file writer acc final cfw add field self lorg mozilla javascript scriptable short class file writer acc public class file writer acc final int interfaces count interfaces null 0 interfaces length for int i 0 i interfaces count i if interfaces i null cfw add interface interfaces i get name string super name super class get name replace generate ctor cfw adapter name super name generate serial ctor cfw adapter name super name if script class name null generate empty ctor cfw adapter name super name script class name obj to int map generated overrides new obj to int map obj to int map generated methods new obj to int map generate methods to satisfy all specified interfaces for int i 0 i interfaces count i method methods interfaces i get methods for int j 0 j methods length j method method methods j int mods method get modifiers if modifier is static mods modifier is final mods continue string method name method get name class arg types method get parameter types if function names has method name try super class get method method name arg types the class we re extending implements this method and the java script object doesn t have an override see bug 61226 continue catch no such method exception e not implemented by superclass fall through make sure to generate only one instance of a particular method signature string method signature get method signature method arg types string method key method name method signature if generated overrides has method key generate method cfw adapter name method name arg types method get return type generated overrides put method key 0 generated methods put method name 0 now go through the superclasses methods checking for abstract methods or additional methods to override generate any additional overrides that the object might contain method methods super class get methods for int j 0 j methods length j method method methods j int mods method get modifiers if modifier is static mods modifier is final mods continue if a method is marked abstract must implement it or the resulting class won t be instantiable otherwise if the object has a property of the same name then an override is intended boolean is abstract method modifier is abstract mods string method name method get name if is abstract method function names has method name make sure to generate only one instance of a particular method signature class arg types method get parameter types string method signature get method signature method arg types string method key method name method signature if generated overrides has method key generate method cfw adapter name method name arg types method get return type generated overrides put method key 0 generated methods put method name 0 if a method was overridden generate a super method which lets the delegate call the superclass version if is abstract method generate super cfw adapter name super name method name method signature arg types method get return type generate java methods for remaining properties that are not overrides obj to int map iterator iter new obj to int map iterator function names for iter start iter done iter next string function name string iter get key if generated methods has function name continue int length iter get value class parms new class length for int k 0 k length k parms k script runtime object class generate method cfw adapter name function name parms script runtime object class return cfw to byte array createadaptercode objtointmap functionnames adaptername superclass scriptclassname classfilewriter classfilewriter adaptername superclass getname addfield contextfactory classfilewriter acc_public classfilewriter acc_final addfield classfilewriter acc_public classfilewriter acc_final addfield classfilewriter acc_public classfilewriter acc_final interfacescount interfacescount addinterface getname supername superclass getname generatector adaptername supername generateserialctor adaptername supername scriptclassname generateemptyctor adaptername supername scriptclassname objtointmap generatedoverrides objtointmap objtointmap generatedmethods objtointmap interfacescount getmethods getmodifiers isstatic isfinal methodname getname argtypes getparametertypes functionnames methodname superclass getmethod methodname argtypes javascript nosuchmethodexception methodsignature getmethodsignature argtypes methodkey methodname methodsignature generatedoverrides methodkey generatemethod adaptername methodname argtypes getreturntype generatedoverrides methodkey generatedmethods methodname superclass getmethods getmodifiers isstatic isfinal isabstractmethod isabstract methodname getname isabstractmethod functionnames methodname argtypes getparametertypes methodsignature getmethodsignature argtypes methodkey methodname methodsignature generatedoverrides methodkey generatemethod adaptername methodname argtypes getreturntype generatedoverrides methodkey generatedmethods methodname isabstractmethod generatesuper adaptername supername methodname methodsignature argtypes getreturntype objtointmap objtointmap functionnames functionname getkey generatedmethods functionname getvalue scriptruntime objectclass generatemethod adaptername functionname scriptruntime objectclass tobytearray static class load adapter class string class name byte class bytes generated class loader loader security controller create loader null null class result loader define class class name class bytes loader link class result return result loadadapterclass classname classbytes generatedclassloader securitycontroller createloader defineclass classname classbytes linkclass public static function get function scriptable obj string function name object x scriptable object get property obj function name if x scriptable not found this method used to swallow the exception from calling an undefined method people have come to depend on this somewhat dubious behavior it allows people to avoid implementing listener methods that they don t care about for instance return null if x instanceof function throw script runtime not function error x function name return function x getfunction functionname scriptableobject getproperty functionname not_found scriptruntime notfunctionerror functionname utility method which dynamically binds a context to the current thread if none already exists public static object call method context factory factory final scriptable this obj final function f final object args final long args to wrap if f null see comments in get function return undefined instance if factory null factory context factory get global final scriptable scope f get parent scope if args to wrap 0 return context call factory f scope this obj args context cx context get current context if cx null return do call cx scope this obj f args args to wrap else return factory call new context action public object run context cx return do call cx scope this obj f args args to wrap callmethod contextfactory thisobj argstowrap getfunction contextfactory getglobal getparentscope argstowrap thisobj getcurrentcontext docall thisobj argstowrap contextaction docall thisobj argstowrap else return factory call new context action public object run context cx return do call cx scope this obj f args args to wrap contextaction docall thisobj argstowrap private static object do call context cx scriptable scope scriptable this obj function f object args long args to wrap wrap the rest of objects for int i 0 i args length i if 0 args to wrap 1 i object arg args i if arg instanceof scriptable args i cx get wrap factory wrap cx scope arg null return f call cx scope this obj args docall thisobj argstowrap argstowrap getwrapfactory thisobj public static scriptable run script final script script return scriptable context call new context action public object run context cx scriptable object global script runtime get global cx script exec cx global return global runscript contextaction scriptableobject scriptruntime getglobal return scriptable context call new context action public object run context cx scriptable object global script runtime get global cx script exec cx global return global contextaction scriptableobject scriptruntime getglobal private static void generate ctor class file writer cfw string adapter name string super name cfw start method init lorg mozilla javascript context factory lorg mozilla javascript scriptable v class file writer acc public invoke base class constructor cfw add byte code aload 0 this cfw add invoke byte code invokespecial super name init v save parameter in instance variable factory cfw add byte code aload 0 this cfw add byte code aload 1 first arg context factory instance cfw add byte code putfield adapter name factory lorg mozilla javascript context factory save parameter in instance variable delegee cfw add byte code aload 0 this cfw add byte code aload 2 second arg scriptable delegee cfw add byte code putfield adapter name delegee lorg mozilla javascript scriptable cfw add byte code aload 0 this for the following putfield for self create a wrapper object to be used as this in method calls cfw add byte code aload 2 the scriptable delegee cfw add byte code aload 0 this cfw add invoke byte code invokestatic org mozilla javascript java adapter create adapter wrapper lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript scriptable cfw add byte code putfield adapter name self lorg mozilla javascript scriptable cfw add byte code return cfw stop method short 3 3 this factory delegee generatector classfilewriter adaptername supername startmethod contextfactory classfilewriter acc_public bytecode aload_0 addinvoke bytecode supername bytecode aload_0 bytecode aload_1 contextfactory bytecode adaptername contextfactory bytecode aload_0 bytecode aload_2 bytecode adaptername bytecode aload_0 bytecode aload_2 bytecode aload_0 addinvoke bytecode javaadapter createadapterwrapper bytecode adaptername bytecode stopmethod private static void generate serial ctor class file writer cfw string adapter name string super name cfw start method init lorg mozilla javascript context factory lorg mozilla javascript scriptable lorg mozilla javascript scriptable v class file writer acc public invoke base class constructor cfw add byte code aload 0 this cfw add invoke byte code invokespecial super name init v save parameter in instance variable factory cfw add byte code aload 0 this cfw add byte code aload 1 first arg context factory instance cfw add byte code putfield adapter name factory lorg mozilla javascript context factory save parameter in instance variable delegee cfw add byte code aload 0 this cfw add byte code aload 2 second arg scriptable delegee cfw add byte code putfield adapter name delegee lorg mozilla javascript scriptable save self cfw add byte code aload 0 this cfw add byte code aload 3 second arg scriptable self cfw add byte code putfield adapter name self lorg mozilla javascript scriptable cfw add byte code return cfw stop method short 4 4 this factory delegee self generateserialctor classfilewriter adaptername supername startmethod contextfactory classfilewriter acc_public bytecode aload_0 addinvoke bytecode supername bytecode aload_0 bytecode aload_1 contextfactory bytecode adaptername contextfactory bytecode aload_0 bytecode aload_2 bytecode adaptername bytecode aload_0 bytecode aload_3 bytecode adaptername bytecode stopmethod private static void generate empty ctor class file writer cfw string adapter name string super name string script class name cfw start method init v class file writer acc public invoke base class constructor cfw add byte code aload 0 this cfw add invoke byte code invokespecial super name init v set factory to null to use current global when necessary cfw add byte code aload 0 cfw add byte code aconst null cfw add byte code putfield adapter name factory lorg mozilla javascript context factory load script class cfw add byte code new script class name cfw add byte code dup cfw add invoke byte code invokespecial script class name init v run script and save resulting scope cfw add invoke byte code invokestatic org mozilla javascript java adapter run script lorg mozilla javascript script lorg mozilla javascript scriptable cfw add byte code astore 1 save the scriptable in instance variable delegee cfw add byte code aload 0 this cfw add byte code aload 1 the scriptable cfw add byte code putfield adapter name delegee lorg mozilla javascript scriptable cfw add byte code aload 0 this for the following putfield for self create a wrapper object to be used as this in method calls cfw add byte code aload 1 the scriptable cfw add byte code aload 0 this cfw add invoke byte code invokestatic org mozilla javascript java adapter create adapter wrapper lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript scriptable cfw add byte code putfield adapter name self lorg mozilla javascript scriptable cfw add byte code return cfw stop method short 2 this delegee generateemptyctor classfilewriter adaptername supername scriptclassname startmethod classfilewriter acc_public bytecode aload_0 addinvoke bytecode supername bytecode aload_0 bytecode aconst_null bytecode adaptername contextfactory bytecode scriptclassname bytecode addinvoke bytecode scriptclassname addinvoke bytecode javaadapter runscript bytecode astore_1 bytecode aload_0 bytecode aload_1 bytecode adaptername bytecode aload_0 bytecode aload_1 bytecode aload_0 addinvoke bytecode javaadapter createadapterwrapper bytecode adaptername bytecode stopmethod generates code to wrap java arguments into object non primitive java types are left as is pending convertion in the helper method leaves the array object on the top of the stack static void generate push wrapped args class file writer cfw class arg types int array length push arguments cfw add push array length cfw add byte code anewarray java lang object int param offset 1 for int i 0 i arg types length i cfw add byte code dup duplicate array reference cfw add push i param offset generate wrap arg cfw param offset arg types i cfw add byte code aastore generatepushwrappedargs classfilewriter argtypes arraylength addpush arraylength bytecode paramoffset argtypes bytecode addpush paramoffset generatewraparg paramoffset argtypes bytecode generates code to wrap java argument into object non primitive java types are left unconverted pending convertion in the helper method leaves the wrapper object on the top of the stack private static int generate wrap arg class file writer cfw int param offset class arg type int size 1 if arg type is primitive cfw add byte code aload param offset else if arg type boolean type wrap boolean values with java lang boolean cfw add byte code new java lang boolean cfw add byte code dup cfw add byte code iload param offset cfw add invoke byte code invokespecial java lang boolean init z v else if arg type character type create a string of length 1 using the character parameter cfw add byte code iload param offset cfw add invoke byte code invokestatic java lang string value of c ljava lang string else convert all numeric values to java lang double cfw add byte code new java lang double cfw add byte code dup string type name arg type get name switch type name char at 0 case b case s case i load an int value convert to double cfw add byte code iload param offset cfw add byte code i2d break case l load a long convert to double cfw add byte code lload param offset cfw add byte code l2d size 2 break case f load a float convert to double cfw add byte code fload param offset cfw add byte code f2d break case d cfw add byte code dload param offset size 2 break cfw add invoke byte code invokespecial java lang double init d v return size generatewraparg classfilewriter paramoffset argtype argtype isprimitive bytecode paramoffset argtype bytecode bytecode bytecode paramoffset addinvoke bytecode argtype bytecode paramoffset addinvoke bytecode valueof bytecode bytecode typename argtype getname typename charat bytecode paramoffset bytecode bytecode paramoffset bytecode bytecode paramoffset bytecode bytecode paramoffset addinvoke bytecode generates code to convert a wrapped value type to a primitive type handles unwrapping java lang boolean and java lang number types generates the appropriate return bytecode static void generate return result class file writer cfw class ret type boolean call convert result wrap boolean values with java lang boolean convert all other primitive values to java lang double if ret type void type cfw add byte code pop cfw add byte code return else if ret type boolean type cfw add invoke byte code invokestatic org mozilla javascript context to boolean ljava lang object z cfw add byte code ireturn else if ret type character type characters are represented as strings in java script return the first character first convert the value to a string if possible cfw add invoke byte code invokestatic org mozilla javascript context to string ljava lang object ljava lang string cfw add byte code iconst 0 cfw add invoke byte code invokevirtual java lang string char at i c cfw add byte code ireturn else if ret type is primitive cfw add invoke byte code invokestatic org mozilla javascript context to number ljava lang object d string type name ret type get name switch type name char at 0 case b case s case i cfw add byte code d2i cfw add byte code ireturn break case l cfw add byte code d2l cfw add byte code lreturn break case f cfw add byte code d2f cfw add byte code freturn break case d cfw add byte code dreturn break default throw new runtime exception unexpected return type ret type to string else string ret type str ret type get name if call convert result cfw add load constant ret type str cfw add invoke byte code invokestatic java lang class for name ljava lang string ljava lang class cfw add invoke byte code invokestatic org mozilla javascript java adapter convert result ljava lang object ljava lang class ljava lang object now cast to return type cfw add byte code checkcast ret type str cfw add byte code areturn generatereturnresult classfilewriter rettype callconvertresult rettype bytecode bytecode rettype addinvoke bytecode toboolean bytecode rettype javascript addinvoke bytecode tostring bytecode iconst_0 addinvoke bytecode charat bytecode rettype isprimitive addinvoke bytecode tonumber typename rettype getname typename charat bytecode bytecode bytecode bytecode bytecode bytecode bytecode runtimeexception rettype tostring rettypestr rettype getname callconvertresult addloadconstant rettypestr addinvoke bytecode forname addinvoke bytecode javaadapter convertresult bytecode rettypestr bytecode private static void generate method class file writer cfw string gen name string method name class parms class return type string buffer sb new string buffer int params end append method signature parms return type sb string method signature sb to string cfw start method method name method signature class file writer acc public prepare stack to call cal method push factory cfw add byte code aload 0 cfw add byte code getfield gen name factory lorg mozilla javascript context factory push self cfw add byte code aload 0 cfw add byte code getfield gen name self lorg mozilla javascript scriptable push function cfw add byte code aload 0 cfw add byte code getfield gen name delegee lorg mozilla javascript scriptable cfw add push method name cfw add invoke byte code invokestatic org mozilla javascript java adapter get function lorg mozilla javascript scriptable ljava lang string lorg mozilla javascript function push arguments generate push wrapped args cfw parms parms length push bits to indicate which parameters should be wrapped if parms length 64 if it will be an issue then passing a static boolean array can be an option but for now using simple bitmask throw context report runtime error0 java adapter can not subclass methods with more then 64 arguments long convertion mask 0 for int i 0 i parms length i if parms i is primitive convertion mask 1 i cfw add push convertion mask go through utility method which creates a context to run the method in cfw add invoke byte code invokestatic org mozilla javascript java adapter call method lorg mozilla javascript context factory lorg mozilla javascript scriptable lorg mozilla javascript function ljava lang object j ljava lang object generate return result cfw return type true cfw stop method short params end generatemethod classfilewriter genname methodname returntype stringbuffer stringbuffer paramsend appendmethodsignature returntype methodsignature tostring startmethod methodname methodsignature classfilewriter acc_public calmethod bytecode aload_0 bytecode genname contextfactory bytecode aload_0 bytecode genname bytecode aload_0 bytecode genname addpush methodname addinvoke bytecode javaadapter getfunction generatepushwrappedargs reportruntimeerror0 javaadapter convertionmask isprimitive convertionmask addpush convertionmask addinvoke bytecode javaadapter callmethod contextfactory generatereturnresult returntype stopmethod paramsend generates code to push typed parameters onto the operand stack prior to a direct java method call private static int generate push param class file writer cfw int param offset class param type if param type is primitive cfw adda load param offset return 1 string type name param type get name switch type name char at 0 case z case b case c case s case i load an int value convert to double cfw addi load param offset return 1 case l load a long convert to double cfw addl load param offset return 2 case f load a float convert to double cfw addf load param offset return 1 case d cfw addd load param offset return 2 throw kit code bug generatepushparam classfilewriter paramoffset paramtype paramtype isprimitive addaload paramoffset typename paramtype getname typename charat addiload paramoffset addlload paramoffset addfload paramoffset adddload paramoffset codebug generates code to return a java type after calling a java method that returns the same type generates the appropriate return bytecode private static void generate pop result class file writer cfw class ret type if ret type is primitive string type name ret type get name switch type name char at 0 case b case c case s case i case z cfw add byte code ireturn break case l cfw add byte code lreturn break case f cfw add byte code freturn break case d cfw add byte code dreturn break else cfw add byte code areturn generatepopresult classfilewriter rettype rettype isprimitive typename rettype getname typename charat bytecode bytecode bytecode bytecode bytecode generates a method called super method name which can be called from java script that is equivalent to calling super method name from java eventually this may be supported directly in java script private static void generate super class file writer cfw string gen name string super name string method name string method signature class parms class return type cfw start method super method name method signature class file writer acc public push this cfw add byte code aload 0 push the rest of the parameters int param offset 1 for int i 0 i parms length i param offset generate push param cfw param offset parms i call the superclass implementation of the method cfw add invoke byte code invokespecial super name method name method signature now handle the return type appropriately class ret type return type if ret type equals void type generate pop result cfw ret type else cfw add byte code return cfw stop method short param offset 1 methodname javascript methodname javascript generatesuper classfilewriter genname supername methodname methodsignature returntype startmethod methodname methodsignature classfilewriter acc_public bytecode paramoffset paramoffset generatepushparam paramoffset addinvoke bytecode supername methodname methodsignature rettype returntype rettype generatepopresult rettype bytecode stopmethod paramoffset returns a fully qualified method name concatenated with its signature private static string get method signature method method class arg types string buffer sb new string buffer append method signature arg types method get return type sb return sb to string getmethodsignature argtypes stringbuffer stringbuffer appendmethodsignature argtypes getreturntype tostring static int append method signature class arg types class return type string buffer sb sb append int first local 1 arg types length includes this for int i 0 i arg types length i class type arg types i append type string sb type if type long type type double type adjust for duble slot first local sb append append type string sb return type return first local appendmethodsignature argtypes returntype stringbuffer firstlocal argtypes argtypes argtypes appendtypestring firstlocal appendtypestring returntype firstlocal private static string buffer append type string string buffer sb class type while type is array sb append type type get component type if type is primitive char type letter if type boolean type type letter z else if type long type type letter j else string type name type get name type letter character to upper case type name char at 0 sb append type letter else sb append l sb append type get name replace sb append return sb stringbuffer appendtypestring stringbuffer isarray getcomponenttype isprimitive typeletter typeletter typeletter typename getname typeletter touppercase typename charat typeletter getname static int get args to convert class arg types int count 0 for int i 0 i arg types length i if arg types i is primitive count if count 0 return null int array new int count count 0 for int i 0 i arg types length i if arg types i is primitive array count i return array getargstoconvert argtypes argtypes argtypes isprimitive argtypes argtypes isprimitive make glue object implementing interface cl that will call the supplied js function when called only interfaces were all methods have the same signature is supported return the glue object or null if tt cl tt is not interface or has methods with different signatures static object create context cx class cl callable function if cl is interface throw new illegal argument exception scriptable top scope script runtime get top call scope cx class cache cache class cache get top scope interface adapter adapter adapter interface adapter cache get interface adapter cl context factory cf cx get factory if adapter null method methods cl get methods if methods length 0 throw context report runtime error2 msg no empty interface conversion string value of function cl get class get name boolean can call function false can call function checks class arg types methods 0 get parameter types check that the rest of methods has the same signature for int i 1 i methods length i class types2 methods i get parameter types if types2 length arg types length break can call function checks for int j 0 j arg types length j if types2 j arg types j break can call function checks can call function true if can call function throw context report runtime error2 msg no function interface conversion string value of function cl get class get name adapter new interface adapter cf cl cache cache interface adapter cl adapter return vm bridge instance new interface proxy adapter proxy helper cf adapter function top scope isinterface illegalargumentexception topscope scriptruntime gettopcallscope classcache classcache topscope interfaceadapter interfaceadapter getinterfaceadapter contextfactory getfactory getmethods reportruntimeerror2 valueof getclass getname cancallfunction cancallfunctionchecks argtypes getparametertypes getparametertypes argtypes cancallfunctionchecks argtypes argtypes cancallfunctionchecks cancallfunction cancallfunction reportruntimeerror2 valueof getclass getname interfaceadapter cacheinterfaceadapter vmbridge newinterfaceproxy proxyhelper topscope private interface adapter context factory cf class cl this proxy helper vm bridge instance get interface proxy helper cf new class cl interfaceadapter contextfactory proxyhelper vmbridge getinterfaceproxyhelper public object invoke context factory cf final object target final scriptable top scope final method method final object args context action action new context action public object run context cx return invoke impl cx target top scope method args return cf call action contextfactory topscope contextaction contextaction invokeimpl topscope context action action new context action public object run context cx return invoke impl cx target top scope method args contextaction contextaction invokeimpl topscope object invoke impl context cx object target scriptable top scope method method object args int n args null 0 args length string method name method get name callable function callable target scriptable this obj top scope object jsargs new object n 1 jsargs n method get name if n 0 wrap factory wf cx get wrap factory for int i 0 i n i jsargs i wf wrap cx top scope args i null object result function call cx top scope this obj jsargs class java result type method get return type if java result type void type result null else result context js to java result java result type return result invokeimpl topscope methodname getname thisobj topscope getname wrapfactory getwrapfactory topscope topscope thisobj javaresulttype getreturntype javaresulttype jstojava javaresulttype create a new test file param name name of this test file param file path full path to this file public test file string name string file path super file path this name name this file path file path this passed true this completed false this start time 00 00 00 this end time 00 00 00 this reason this program this total cases 0 this cases passed 0 this cases failed 0 this case vector new vector this exception this bugnumber testfile filepath testfile filepath filepath filepath filepath starttime endtime totalcases casespassed casesfailed casevector public string float float public string ambiguous boolean arg return boolean object boolean_object public string ambiguous boolean arg return boolean public string ambiguous object arg return object public string ambiguous string arg return string public string expect return string public test driver string args this args args if thread null thread new thread this thread start testdriver public void run public void start this files null this output directory null this opt level 0 this debug level 0 this runtime runtime get runtime this free memory runtime free memory this total memory runtime total memory if process options open log files output directory null test directory output directory write date to logs hr output directory write log headers output directory if files null files test directory list if test driver tinderbox write tinderbox header executable suites get suites files for int i 0 i suites size i get cases test suite suites element at i for int i 0 i suites size i if test driver tinderbox write tinderbox suite name test suite suites element at i execute suite test suite suites element at i if test driver tinderbox write tinderbox suite result test suite suites element at i runtime gc stop output_directory opt_level debug_level getruntime free_memory freememory total_memory totalmemory processoptions openlogfiles output_directory test_directory output_directory writedatetologs output_directory writelogheaders output_directory test_directory testdriver writetinderboxheader getsuites getcases testsuite elementat testdriver writetinderboxsuitename testsuite elementat executesuite testsuite elementat testdriver writetinderboxsuiteresult testsuite elementat close all logs public void stop close logs runtime gc long new free memory runtime free memory long new total memory runtime total memory string string tt free memory new free memory n br total memory new total memory n br free leaked free memory new free memory n br total leaked total memory new total memory n br tt p string p done if thread null thread stop thread null closelogs new_free_memory freememory new_total_memory totalmemory new_free_memory new_total_memory free_memory new_free_memory total_memory new_total_memory public void close logs write date to logs output directory get log output directory summary log name close log get log output directory suite log name close log get log output directory file log name close log get log output directory case log name close log if debug get log output directory debug log name close log closelogs writedatetologs output_directory getlog output_directory summary_log_name closelog getlog output_directory suite_log_name closelog getlog output_directory file_log_name closelog getlog output_directory case_log_name closelog getlog output_directory debug_log_name closelog get information about the operating system public static string get system information string system system get property os name system get property os arch system get property os version return system getsysteminformation getproperty getproperty getproperty return a file object with the specified in the output directory public static test log get log file output string filename enable privileges test log log null string system get system information string platform system 0 length 4 system 0 system 0 substring 0 4 string platform system 0 try file logdir new file output get absolute path output get absolute path ends with file separator file separator platform system 1 system 2 get current date logdir mkdirs log new test log logdir get absolute path file separator filename terminator catch exception e p test driver get log threw e to string p platform platform p output output to string p filename filename to string p file separator file separator to string p system 0 system 0 p system 1 system 1 p system 2 system 2 p date get current date e print stack trace return log testlog getlog enableprivileges testlog getsysteminformation getabsolutepath getabsolutepath endswith getcurrentdate _ testlog getabsolutepath testdriver getlog tostring tostring tostring tostring getcurrentdate _ printstacktrace create and write headers to log files param output directory in which output files are written public static void open log files file output enable privileges test log summary log get log output summary log name test log file log get log output file log name test log suite log get log output suite log name test log case log get log output case log name if debug test log debug log get log output debug log name return openlogfiles enableprivileges testlog summary_log getlog summary_log_name testlog file_log getlog file_log_name testlog suite_log getlog suite_log_name testlog case_log getlog case_log_name testlog debug_log getlog debug_log_name public void write log headers file output string header table tr th test driver td this get class to string tr tr th output directory td output directory tr executable null tr th opt level td opt level tr tr th debug level td debug level tr tr th executable td executable tr tr th java version td system get property java vendor system get property java version tr tr th test file directory td test directory tr tr th helper functions td helper functions tr tr th free memory td free memory tr tr th total jvm memory td total memory tr table get log output directory suite log name write line header get log output directory case log name write line header get log output directory file log name write line header get log output directory summary log name write line header get log output directory summary log name write line table width 100 tr bg color ffffcc th rowspan 2 width 15 suite th rowspan 2 width 20 files th rowspan 2 width 10 cases th colspan 2 width 20 passed th colspan 2 width 20 failed th rowspan 2 width 15 result tr tr th width 10 th width 10 th width 10 th width 10 tr table return writelogheaders getclass tostring output_directory optlevel opt_level debuglevel debug_level getproperty getproperty test_directory helper_functions free_memory total_memory getlog output_directory suite_log_name writeline getlog output_directory case_log_name writeline getlog output_directory file_log_name writeline getlog output_directory summary_log_name writeline getlog output_directory summary_log_name writeline bgcolor for each subdirectory of the main test directory create a new test suite object public vector get suites string files vector suites new vector for int i 0 i files length i string filename strip double slashes test directory file separator files i file fileobject new file filename if fileobject is directory test suite s new test suite fileobject get name filename suites add element s return suites testsuite getsuites stripdoubleslashes test_directory isdirectory testsuite testsuite getname addelement if two slashes in a row are found one slash is stripped out mac client has trouble if we don t do this xxx this doesn t work and needs to be fixed public static string strip double slashes string string string buffer buffer new string buffer for int letter 0 letter string length letter char current char string char at letter if current char file separator char buffer append current char else while string char at letter file separator char only add one slash buffer append file separator char letter if new character string char at letter to string equals if new character string char at letter 1 to string equals only got one leave it alone buffer append string char at letter else buffer append string char at letter return buffer to string stripdoubleslashes stringbuffer stringbuffer current_char charat current_char separatorchar current_char charat separatorchar separatorchar charat tostring charat tostring charat charat tostring for each test file in the suite directory create a test file object public void get cases test suite suite enable privileges file dir new file suite file path string files dir list for int i 0 i files length i test file item new test file files i suite file path file separator files i if item is file item get name to lower case ends with get suffix item is directory suite add element item p item testfile getcases testsuite enableprivileges filepath testfile testfile filepath isfile getname tolowercase endswith getsuffix isdirectory addelement subclasses should override this method to iterate through all test files in the test suite create a new test environment run the test and close the test environment for examples see com netscape javascript qa drivers rhino drv and see com netscape javascript qa drivers ref drv public synchronized void execute suite test suite suite testfiles testsuite testenvironment testenvironment rhinodrv refdrv executesuite testsuite if the environment uses a security manager and requires privileges to access system properties override this method to enable privileges the default method does nothing public static void enable privileges enableprivileges write the suite result to the tinderbox log xxx need machine branch start time end time public void write tinderbox header string executable string dotted line string product executable null ns js rhino ns js ref string os info system get property os name system get property os arch system get property os version string java info system get property java vendor system get property java version create the log string system out println dotted line system out println product product system out println machine machine system out println operating system os info system out println java version java info system out println free memory free memory system out println total jvm memory total memory system out println test driver this get class get name system out println output directory output directory system out println path to executable executable if product equals ns js rhino system out println optimization level opt level system out println debug level debug level system out println test directory test directory system out println dotted line starttime endtime writetinderboxheader dottedline osinfo getproperty getproperty getproperty javainfo getproperty getproperty dottedline osinfo javainfo free_memory total_memory getclass getname output_directory opt_level debug_level test_directory dottedline public void write tinderbox suite name test suite suite system out println suite suite name writetinderboxsuitename testsuite public void write tinderbox suite result test suite suite string dotted line system out println result suite passed passed failed if suite passed system out println failed files for int i 0 i suite size i test file file test file suite element at i if file passed system out println file name file bugnumber equals http scopus mcom com bugsplat show bug cgi id file bugnumber system out println dotted line writetinderboxsuiteresult testsuite dottedline testfile testfile elementat show_bug dottedline write an html formatted string to suite log public static void write suite result test suite suite file output if suite size 0 return string buffer buffer tt suite passed font color 00dd00 passed font font color dd0000 failed font nbsp a href suite name suite name a b if suite passed for int i 0 i suite size i test file file test file suite element at i if file passed buffer nbsp a href case html suite name file name file name a if file bugnumber equals buffer nbsp a href http scopus mcom com bugsplat show bug cgi id file bugnumber file bugnumber a buffer tt br get log output suite log name write line buffer to string suite_log writesuiteresult testsuite testfile testfile elementat show_bug getlog suite_log_name writeline tostring write an html formatted string to the summary log that looks like this pre suite number of number of passed failed result name files cases pre public static void write suite summary test suite suite file output if suite size 0 return string buffer p total suite total cases p passed suite cases passed p failed suite cases failed double percent passed math round double suite cases passed double suite total cases 10000 100 double percent failed math round double suite cases failed double suite total cases 10000 100 buffer table width 100 buffer th bgcolor ffffcc width 15 suite name buffer th width 15 bgcolor ffffcc suite size th width 10 bgcolor ffffcc suite total cases th width 10 bgcolor ffffcc suite cases passed th width 10 bgcolor ffffcc percent passed th width 10 bgcolor ffffcc suite cases failed th width 10 bgcolor ffffcc percent failed th width 15 bgcolor ffffcc suite passed true font color 006600 passed font font color 990000 failed font tr table for int i 0 i suite size i test file file test file suite element at i double p passed 0 double p failed 0 if file total cases 0 p passed math round double file cases passed double file total cases 10000 100 p failed math round double file cases failed double file total cases 10000 100 buffer table width 100 tr td width 15 td width 15 a href case html suite name file name file name a td width 10 file total cases td width 10 bg color ccffcc file cases passed td width 10 bg color ccffcc p passed td width 10 bg color ffcccc file cases failed td width 10 bg color ffcccc p failed td width 15 file passed true font color 006600 passed font font color 990000 failed font file reason equals file reason file exception equals br file exception tr table get log output summary log name write line buffer to string summary_log writesuitesummary testsuite totalcases casespassed casesfailed percentpassed casespassed totalcases percentfailed casesfailed totalcases totalcases casespassed percentpassed casesfailed percentfailed testfile testfile elementat ppassed pfailed totalcases ppassed casespassed totalcases pfailed casesfailed totalcases totalcases bgcolor casespassed bgcolor ppassed bgcolor casesfailed bgcolor pfailed getlog summary_log_name writeline tostring write the result of the current file to the file log if the file threw an exception print the exception public static void write file result test file file test suite suite file output string suitename suite null suite name if file passed string buffer buffer tt font color file passed 00dd00 passed font nbsp dd0000 failed font nbsp a href case html suitename file name suitename file name a file exception n if file bugnumber equals buffer nbsp a href http scopus mcom com bugsplat show bug cgi id file bugnumber file bugnumber a get log output file log name write line buffer to string file_log writefileresult testfile testsuite show_bug getlog file_log_name writeline tostring read the contents of a file into a string public static string read file string file path file js file new file file path int length new long js file length int value byte b new byte length string buffer contents new string buffer try file input stream fis new file input stream js file int read fis read b contents append new string b catch exception e p e to string return contents to string readfile filepath jsfile filepath jsfile intvalue stringbuffer stringbuffer fileinputstream fileinputstream jsfile tostring tostring test case management system tcms requires the following information machineid pass or fail test file name beaker test file name date run in mm dd yy start time hh mm ss end time hh mm ss expected results string quite often null actual result string reason for failure tests can provide this information we expected it to be in an object called test case with the following structure pre function test case passed name expect actual reason this passed passed this name description of the test case this expect the expected result this actual the actual result this reason reason for failure pre we will generate machineid pass fail date run start time end time if tcms false omit unnecessary log id public static void write case results test file file test suite suite file output suite total cases file total cases string system get system information string buffer for int i 0 i file case vector size i test case tcase test case file case vector element at i format and write test case results to case log if tcase passed equals true if file passed buffer a name suite name file name buffer tt buffer system 0 if tcase passed equals true if file passed buffer pass suite cases passed 1 file cases passed 1 else if file passed buffer fail suite cases failed 1 file cases failed 1 if tcms buffer tcase name tcase description beaker tcase name tcase description get current date file start time file end time tcase expect tcase actual tcase reason n else buffer tcase name tcase description tcase expect tcase actual tcase reason n if tcase passed equals true buffer tt br n get log output case log name write line buffer to string else buffer testfilename testfilename expectedresults testcase testcase theexpectedresult theactualresult reasonforfailure writecaseresults testfile testsuite totalcases totalcases getsysteminformation casevector testcase testcase casevector elementat case_log casespassed casespassed casesfailed casesfailed getcurrentdate starttime endtime getlog case_log_name writeline tostring short version of writing test case results to the case log used by live connec test subclasses param cases vector of testcases whose results should be written to the case log live connect test sends a vector of failed test case objects param classname name of the live connect test class param output directory in which output is written see com netscape javascript qa liveconnect live connect test write results to case log public static void write case results test file file string classname file output string system get system information string buffer for int i 0 i file case vector size i test case tcase test case file case vector element at i if tcase passed equals true buffer pass else buffer tt buffer system 0 buffer fail buffer tcase name tcase description tcase expect tcase actual tcase reason n buffer tt br n get log output case log name write line buffer to string case_log liveconnectest case_log liveconnecttest testcase liveconnecttest liveconnecttest writeresultstocaselog writecaseresults testfile getsysteminformation casevector testcase testcase casevector elementat getlog case_log_name writeline tostring write system information and current date to the summary log file log and suite log xxx need to fix this to output all test information public static void write date to logs string separator file output date today new date string system get system information long new free memory runtime free memory long new total memory runtime total memory string string tt free memory new free memory n br total memory new total memory n br free leaked free memory new free memory n br total leaked total memory new total memory n br tt separator system 0 system 1 system 2 today to string get log output summary log name write line string get log output file log name write line string get log output suite log name write line string if tcms get log output case log name write line string summary_log file_log suite_log writedatetologs getsysteminformation new_free_memory freememory new_total_memory totalmemory new_free_memory new_total_memory free_memory new_free_memory total_memory new_total_memory tostring getlog summary_log_name writeline getlog file_log_name writeline getlog suite_log_name writeline getlog case_log_name writeline convenience methods public static void p string s if test driver tinderbox system out println s testdriver public static void debug string s if debug test driver tinderbox system err println s testdriver from the current date return a string in the format dd mm yy where is specified by the separator argument public static string get current date string separator date today new date string date today get date 10 0 string value of today get date string value of today get date string month today get month 1 10 0 string value of today get month 1 string value of today get month 1 string year string value of today get year return month separator date separator year getcurrentdate getdate valueof getdate valueof getdate getmonth valueof getmonth valueof getmonth valueof getyear from the current time return a string in the format hh mm ss public static string get current time date now new date string hours now get hours 10 0 string value of now get hours string value of now get hours string minutes now get minutes 10 0 string value of now get minutes string value of now get minutes string seconds now get seconds 10 0 string value of now get seconds string value of now get seconds string time hours minutes seconds return time getcurrenttime gethours valueof gethours valueof gethours getminutes valueof getminutes valueof getminutes getseconds valueof getseconds valueof getseconds return time public string get suffix return suffix getsuffix return suffix public void set suffix string s suffix s setsuffix temporary stop this thread for 5 seconds public boolean sleep int ms try thread sleep 5000 catch exception e p sleep failed e return false return true process options should parse the args object return true if the driver should continue return false if the driver should not continue public boolean process options return false processoptions return false public static void main string args test driver d new test driver args d start testdriver testdriver public class jsobject 001 extends live connect test public jsobject 001 super jsobject_001 liveconnecttest jsobject_001 public static void main string args jsobject 001 test new jsobject 001 test start jsobject_001 jsobject_001 public void execute test get double nan get double infinity getjs object parse int getjs object parse float getjs object eval getjs object escape getjs object unescape getjs object is nan getjs object is finite getjs object object getjs object function getjs object array getjs object string getjs object boolean getjs object number getjs object date getjs object math executetest getdouble getdouble getjsobject parseint getjsobject parsefloat getjsobject getjsobject getjsobject getjsobject isnan getjsobject isfinite getjsobject getjsobject getjsobject getjsobject getjsobject getjsobject getjsobject getjsobject try to get a property of the java script global object the type of this property should be a java lang double if it is not the test will fail with a java lang class cast exception param property name of the java script property to get public void get double string property object jsobject null string exception null string identifier this get class to string string description object jsobject global get member property jsobject instanceof java lang double try jsobject global get member property catch exception e exception exception getting property e to string system err println exception string expect true string actual jsobject instanceof java lang double add test case description expect actual exception javascript classcastexception javascript getdouble getclass tostring getmember getmember tostring addtestcase try to get a property of the java script global object the type of this property should be a netscape javascript js object if it is not the test will fail with a java lang class cast exception param property name of the java script property to get public void getjs object string property object jsobject null string exception null string identifier this get class to string string description object jsobject global get member property jsobject instanceof js object try jsobject global get member property catch exception e exception exception getting property e to string system err println exception string expect true string actual jsobject instanceof js object add test case description expect actual exception javascript jsobject classcastexception javascript getjsobject getclass tostring getmember jsobject getmember tostring jsobject addtestcase public class tool error reporter implements error reporter public tool error reporter boolean report warnings this report warnings system err toolerrorreporter errorreporter toolerrorreporter reportwarnings reportwarnings public tool error reporter boolean report warnings print stream err this report warnings report warnings this err err toolerrorreporter reportwarnings printstream reportwarnings reportwarnings look up the message corresponding to message id in the org mozilla javascript tools shell resources messages property file for internationalization support public static string get message string message id return get message message id object null messageid getmessage messageid getmessage messageid public static string get message string message id string argument object args argument return get message message id args getmessage messageid getmessage messageid public static string get message string message id object arg1 object arg2 object args arg1 arg2 return get message message id args getmessage messageid getmessage messageid public static string get message string message id object args context cx context get current context locale locale cx null locale get default cx get locale resource bundle does cacheing resource bundle rb resource bundle get bundle org mozilla javascript tools resources messages locale string format string try format string rb get string message id catch java util missing resource exception mre throw new runtime exception no message resource found for message property message id if args null return format string else message format formatter new message format format string return formatter format args getmessage messageid getcurrentcontext getdefault getlocale resourcebundle resourcebundle resourcebundle getbundle formatstring formatstring getstring messageid missingresourceexception runtimeexception messageid formatstring messageformat messageformat formatstring private static string get exception message rhino exception ex string msg if ex instanceof java script exception msg get message msg uncaughtjs exception ex details else if ex instanceof ecma error msg get message msg uncaught ecma error ex details else msg ex to string return msg getexceptionmessage rhinoexception javascriptexception getmessage uncaughtjsexception ecmaerror getmessage uncaughtecmaerror tostring public void warning string message string source name int line string line source int line offset if report warnings return report error message message source name line line source line offset true sourcename linesource lineoffset reportwarnings reporterrormessage sourcename linesource lineoffset public void error string message string source name int line string line source int line offset has reported error flag true report error message message source name line line source line offset false sourcename linesource lineoffset hasreportederrorflag reporterrormessage sourcename linesource lineoffset public evaluator exception runtime error string message string source name int line string line source int line offset error message source name line line source line offset return new evaluator exception message source name line line source line offset evaluatorexception runtimeerror sourcename linesource lineoffset sourcename linesource lineoffset evaluatorexception sourcename linesource lineoffset public boolean has reported error return has reported error flag hasreportederror hasreportederrorflag public boolean is reporting warnings return this report warnings isreportingwarnings reportwarnings public void set is reporting warnings boolean report warnings this report warnings report warnings setisreportingwarnings reportwarnings reportwarnings reportwarnings public static void report exception error reporter er rhino exception ex if er instanceof tool error reporter tool error reporter er report exception ex else string msg get exception message ex er error msg ex source name ex line number ex line source ex column number reportexception errorreporter rhinoexception toolerrorreporter toolerrorreporter reportexception getexceptionmessage sourcename linenumber linesource columnnumber public void report exception rhino exception ex if ex instanceof wrapped exception wrapped exception we wrapped exception ex we print stack trace err else string msg get exception message ex report error message msg ex source name ex line number ex line source ex column number false reportexception rhinoexception wrappedexception wrappedexception wrappedexception printstacktrace getexceptionmessage reporterrormessage sourcename linenumber linesource columnnumber private void report error message string message string source name int line string line source int line offset boolean just warning if line 0 string line str string value of line if source name null object args source name line str message message get message msg format3 args else object args line str message message get message msg format2 args else object args message message get message msg format1 args if just warning message get message msg warning message err println message prefix message if null line source err println message prefix line source err println message prefix build indicator line offset reporterrormessage sourcename linesource lineoffset justwarning linestr valueof sourcename sourcename linestr getmessage linestr getmessage getmessage justwarning getmessage messageprefix linesource messageprefix linesource messageprefix buildindicator lineoffset private string build indicator int offset string buffer sb new string buffer for int i 0 i offset 1 i sb append sb append return sb to string buildindicator stringbuffer stringbuffer tostring public nav drv super null system out println constructor set suffix html navdrv setsuffix public static void main string args privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read system out println main nav drv d new nav drv d start privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread navdrv navdrv public boolean process options system out println nav drv process options privilege manager enable privilege universal file access privilege manager enable privilege universal property read window js object js object get window this get parameters string d get parameter directory string o get parameter output http path get parameter http path test directory new file d output directory new file o system out println http path http path system out println directory test directory system out println output output directory if test directory is directory system err println error test directory get absolute path is not a directory return false if output directory is directory system err println error output directory get absolute path is not a directory return false return true processoptions navdrv processoptions privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalpropertyread jsobject jsobject getwindow getparameter getparameter http_path getparameter http_path test_directory output_directory http_path http_path test_directory output_directory test_directory isdirectory test_directory getabsolutepath output_directory isdirectory output_directory getabsolutepath public static void open log files file o privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read test driver open log files o openlogfiles privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread testdriver openlogfiles public vector get suites string files privilege manager enable privilege universal file access privilege manager enable privilege universal property read privilege manager enable privilege universal file read privilege manager enable privilege universal file write return super get suites files getsuites privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalpropertyread privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite getsuites public void get cases test suite suite privilege manager enable privilege universal file access privilege manager enable privilege universal property read privilege manager enable privilege universal file read privilege manager enable privilege universal file write super get cases suite getcases testsuite privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalpropertyread privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite getcases public static test log get log file output string filename privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read return test driver get log output filename testlog getlog privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread testdriver getlog public void write log headers file output privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read super write log headers output writelogheaders privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread writelogheaders public static void write suite result test suite suite file output privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read test driver write suite result suite output writesuiteresult testsuite privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread testdriver writesuiteresult public static void write suite summary test suite suite file output privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read test driver write suite summary suite output writesuitesummary testsuite privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread testdriver writesuitesummary public static void write file result test file file test suite suite file output privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read test driver write file result file suite output writefileresult testfile testsuite privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread testdriver writefileresult public static void write case results test file file test suite suite file output privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read test driver write case results file suite output writecaseresults testfile testsuite privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread testdriver writecaseresults public static void write date to logs string separator file output privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read test driver write date to logs separator output writedatetologs privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread testdriver writedatetologs public synchronized void execute suite test suite suite privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read nav env context test file file for int i 0 i suite size i synchronized suite file test file suite element at i context new nav env file suite this context run test write file result file suite output directory write case results file suite output directory context close context null if file passed suite passed false write suite result suite output directory write suite summary suite output directory executesuite testsuite privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread navenv testfile testfile elementat navenv runtest writefileresult output_directory writecaseresults output_directory writesuiteresult output_directory writesuitesummary output_directory public void stop privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read super stop privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread public void start privilege manager enable privilege universal file access privilege manager enable privilege universal file read privilege manager enable privilege universal file write privilege manager enable privilege universal property read super start privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread public class run script3 public static void main string args context cx context enter try scriptable scope cx init standard objects collect the arguments into a single string string s for int i 0 i args length i s args i now evaluate the string we ve colected we ll ignore the result cx evaluate string scope s cmd 1 null print the value of variable x object x scope get x scope if x scriptable not found system out println x is not defined else system out println x context to string x call function f my arg and print its result object f obj scope get f scope if f obj instanceof function system out println f is undefined or not a function else object function args my arg function f function f obj object result f call cx scope scope function args string report f my args context to string result system out println report finally context exit runscript3 initstandardobjects evaluatestring not_found tostring fobj fobj functionargs fobj functionargs tostring java members scriptable scope class cl this members new hashtable 23 this static members new hashtable 7 this cl cl reflect scope javamembers staticmembers boolean has string name boolean is static hashtable ht is static static members members object obj ht get name if obj null return true else return null find explicit function name is static isstatic isstatic staticmembers findexplicitfunction isstatic object get scriptable scope string name object java object boolean is static hashtable ht is static static members members object member ht get name if is static member null try to get static member from instance lc3 member static members get name if member null member this get explicit function scope name java object is static if member null return scriptable not found if member instanceof scriptable return member context cx context get context object rval class type try if member instanceof bean property bean property bp bean property member if bp getter null return scriptable not found rval bp getter invoke java object context empty args type bp getter method get return type else field field field member rval field get is static null java object type field get type catch exception ex throw context throw as script runtime ex ex need to wrap the object before we return it scope scriptable object get top level scope scope return cx get wrap factory wrap cx scope rval type javaobject isstatic isstatic staticmembers isstatic staticmembers getexplicitfunction javaobject isstatic not_found getcontext beanproperty beanproperty beanproperty not_found javaobject emptyargs getreturntype isstatic javaobject gettype throwasscriptruntimeex scriptableobject gettoplevelscope getwrapfactory void put scriptable scope string name object java object object value boolean is static hashtable ht is static static members members object member ht get name if is static member null try to get static member from instance lc3 member static members get name if member null throw report member not found name if member instanceof field and methods field and methods fam field and methods ht get name member fam field is this a bean property set if member instanceof bean property bean property bp bean property member if bp setter null throw report member not found name if there s only one setter or if the value is null use the main setter otherwise let the native java method decide which setter to use if bp setters null value null class set type bp setter arg types 0 object args context js to java value set type try bp setter invoke java object args catch exception ex throw context throw as script runtime ex ex else object args value bp setters call context get context scriptable object get top level scope scope scope args else if member instanceof field string str member null msg java internal private msg java method assign throw context report runtime error1 str name field field field member object java value context js to java value field get type try field set java object java value catch illegal access exception access ex throw new runtime exception unexpected illegal access exception accessing java field catch illegal argument exception arg ex throw context report runtime error3 msg java internal field type value get class get name field java object get class get name javaobject isstatic isstatic staticmembers isstatic staticmembers reportmembernotfound fieldandmethods fieldandmethods fieldandmethods beanproperty beanproperty beanproperty reportmembernotfound nativejavamethod settype argtypes jstojava settype javaobject throwasscriptruntimeex getcontext scriptableobject gettoplevelscope reportruntimeerror1 javavalue jstojava gettype javaobject javavalue illegalaccessexception accessex runtimeexception illegalaccessexception illegalargumentexception argex reportruntimeerror3 getclass getname javaobject getclass getname object get ids boolean is static hashtable ht is static static members members int len ht size object result new object len enumeration keys ht keys for int i 0 i len i result i keys next element return result getids isstatic isstatic staticmembers nextelement static string java signature class type if type is array return type get name else int array dimension 0 do array dimension type type get component type while type is array string name type get name string suffix if array dimension 1 return name concat suffix else int length name length array dimension suffix length string buffer sb new string buffer length sb append name while array dimension 0 array dimension sb append suffix return sb to string javasignature isarray getname arraydimension arraydimension getcomponenttype isarray getname arraydimension arraydimension stringbuffer stringbuffer arraydimension arraydimension tostring static string live connect signature class arg types int n arg types length if n 0 return string buffer sb new string buffer sb append for int i 0 i n i if i 0 sb append sb append java signature arg types i sb append return sb to string liveconnectsignature argtypes argtypes stringbuffer stringbuffer javasignature argtypes tostring private member box find explicit function string name boolean is static int sig start name index of if sig start 0 return null hashtable ht is static static members members member box methods or ctors null boolean is ctor is static sig start 0 if is ctor explicit request for an overloaded constructor methods or ctors ctors else explicit request for an overloaded method string true name name substring 0 sig start object obj ht get true name if is static obj null try to get static member from instance lc3 obj static members get true name if obj instanceof native java method native java method njm native java method obj methods or ctors njm methods if methods or ctors null for int i 0 i methods or ctors length i class type methods or ctors i arg types string sig live connect signature type if sig start sig length name length name region matches sig start sig 0 sig length return methods or ctors i return null memberbox findexplicitfunction isstatic sigstart indexof sigstart isstatic staticmembers memberbox methodsorctors isctor isstatic sigstart isctor methodsorctors truename sigstart truename isstatic staticmembers truename nativejavamethod nativejavamethod nativejavamethod methodsorctors methodsorctors methodsorctors methodsorctors argtypes liveconnectsignature sigstart regionmatches sigstart methodsorctors private object get explicit function scriptable scope string name object java object boolean is static hashtable ht is static static members members object member null member box method or ctor find explicit function name is static if method or ctor null scriptable prototype scriptable object get function prototype scope if method or ctor is ctor native java constructor fun new native java constructor method or ctor fun set prototype prototype member fun ht put name fun else string true name method or ctor get name member ht get true name if member instanceof native java method native java method member methods length 1 native java method fun new native java method method or ctor name fun set prototype prototype ht put name fun member fun return member getexplicitfunction javaobject isstatic isstatic staticmembers memberbox methodorctor findexplicitfunction isstatic methodorctor scriptableobject getfunctionprototype methodorctor isctor nativejavaconstructor nativejavaconstructor methodorctor setprototype truename methodorctor getname truename nativejavamethod nativejavamethod nativejavamethod nativejavamethod methodorctor setprototype private void reflect scriptable scope we reflect methods first because we want overloaded field method names to be allocated to the native java method before the field gets in the way method methods cl get methods for int i 0 i methods length i method method methods i int mods method get modifiers if modifier is public mods continue boolean is static modifier is static mods hashtable ht is static static members members string name method get name object value ht get name if value null ht put name method else obj array overloaded methods if value instanceof obj array overloaded methods obj array value else if value instanceof method kit code bug value should be instance of method as at this stage static members and members can only contain methods overloaded methods new obj array overloaded methods add value ht put name overloaded methods overloaded methods add method replace method instances by wrapped native java method objects first in static members and then in members for int table cursor 0 table cursor 2 table cursor boolean is static table cursor 0 hashtable ht is static static members members enumeration e ht keys while e has more elements string name string e next element member box method boxes object value ht get name if value instanceof method method boxes new member box 1 method boxes 0 new member box method value else obj array overloaded methods obj array value int n overloaded methods size if n 2 kit code bug method boxes new member box n for int i 0 i n i method method method overloaded methods get i method boxes i new member box method native java method fun new native java method method boxes if scope null script runtime set function proto and parent fun scope ht put name fun reflect fields field fields cl get fields for int i 0 i fields length i field field fields i int mods field get modifiers if modifier is public mods continue boolean is static modifier is static mods hashtable ht is static static members members string name field get name object member ht get name if member null ht put name field else if member instanceof native java method native java method method native java method member field and methods fam new field and methods scope method methods field hashtable fmht is static static field and methods field and methods if fmht null fmht new hashtable 4 if is static static field and methods fmht else field and methods fmht fmht put name fam ht put name fam else if member instanceof field field old field field member if this newly reflected field shadows an inherited field then replace it otherwise since access to the field would be ambiguous from java no field should be reflected for now the first field found wins unless another field explicitly shadows it if old field get declaring class is assignable from field get declaring class ht put name field else unknown member type kit code bug create bean propeties from corresponding get set methods first for static members and then for instance members for int table cursor 0 table cursor 2 table cursor boolean is static table cursor 0 hashtable ht is static static members members hashtable to add new hashtable now for each member make bean properties for enumeration e ht keys e has more elements is this a getter string name string e next element boolean member is get method name starts with get boolean member is set method name starts with set boolean member is is method name starts with is if member is get method member is is method member is set method double check name component string name component name substring member is is method 2 3 if name component length 0 continue make the bean property name string bean property name name component char ch0 name component char at 0 if character is upper case ch0 if name component length 1 bean property name name component to lower case else char ch1 name component char at 1 if character is upper case ch1 bean property name character to lower case ch0 name component substring 1 if we already have a member by this name don t do this property if ht contains key bean property name to add contains key bean property name continue find the getter method or if there is none the is method member box getter null string getter name get concat name component string is name is concat name component getter find getter is static ht getter name if there was no valid getter check for an is method if getter null getter find getter is static ht is name setter member box setter null native java method setters null string setter name set concat name component if ht contains key setter name is this value a method object member ht get setter name if member instanceof native java method native java method njm set native java method member if getter null we have a getter now do we have a matching setter class type getter method get return type setter extract set method type njm set methods is static else no getter find any set method setter extract set method njm set methods is static if njm set methods length 1 setters njm set make the property bean property bp new bean property getter setter setters to add put bean property name bp add the new bean properties for enumeration e to add keys e has more elements object key e next element object value to add get key ht put key value reflect constructors constructor constructors cl get constructors ctors new member box constructors length for int i 0 i constructors length i ctors i new member box constructors i nativejavamethod getmethods getmodifiers ispublic isstatic isstatic isstatic staticmembers getname objarray overloadedmethods objarray overloadedmethods objarray codebug staticmembers overloadedmethods objarray overloadedmethods overloadedmethods overloadedmethods nativejavamethod staticmembers tablecursor tablecursor tablecursor isstatic tablecursor isstatic staticmembers hasmoreelements nextelement memberbox methodboxes methodboxes memberbox methodboxes memberbox objarray overloadedmethods objarray overloadedmethods codebug methodboxes memberbox overloadedmethods methodboxes memberbox nativejavamethod nativejavamethod methodboxes scriptruntime setfunctionprotoandparent getfields getmodifiers ispublic isstatic isstatic isstatic staticmembers getname nativejavamethod nativejavamethod nativejavamethod fieldandmethods fieldandmethods isstatic staticfieldandmethods fieldandmethods isstatic staticfieldandmethods fieldandmethods oldfield oldfield getdeclaringclass isassignablefrom getdeclaringclass codebug tablecursor tablecursor tablecursor isstatic tablecursor isstatic staticmembers toadd hasmoreelements nextelement memberisgetmethod startswith memberissetmethod startswith memberisismethod startswith memberisgetmethod memberisismethod memberissetmethod namecomponent memberisismethod namecomponent beanpropertyname namecomponent namecomponent charat isuppercase namecomponent beanpropertyname namecomponent tolowercase namecomponent charat isuppercase beanpropertyname tolowercase namecomponent containskey beanpropertyname toadd containskey beanpropertyname memberbox gettername namecomponent isname namecomponent findgetter isstatic gettername findgetter isstatic isname memberbox nativejavamethod settername namecomponent containskey settername settername nativejavamethod nativejavamethod njmset nativejavamethod getreturntype extractsetmethod njmset isstatic extractsetmethod njmset isstatic njmset njmset beanproperty beanproperty toadd beanpropertyname toadd hasmoreelements nextelement toadd getconstructors memberbox memberbox private member box find getter boolean is static hashtable ht string getter name if ht contains key getter name check that the getter is a method object member ht get getter name if member instanceof native java method native java method njm get native java method member return extract get method njm get methods is static return null memberbox findgetter isstatic gettername containskey gettername gettername nativejavamethod nativejavamethod njmget nativejavamethod extractgetmethod njmget isstatic private static member box extract get method member box methods boolean is static inspect the list of all member box for the only one having no parameters for int method idx 0 method idx methods length method idx member box method methods method idx does getter method have an empty parameter list with a return value eg a get something or is something if method arg types length 0 is static method is static class type method method get return type if type void type return method break return null memberbox extractgetmethod memberbox isstatic memberbox methodidx methodidx methodidx memberbox methodidx getsomething issomething argtypes isstatic isstatic getreturntype private static member box extract set method class type member box methods boolean is static note it may be preferable to allow native java method find function to find the appropriate setter unfortunately it requires an instance of the target arg to determine that make two passes one to find a method with direct type assignment and one to find a widening conversion for int pass 1 pass 2 pass for int i 0 i methods length i member box method methods i if is static method is static if method method get return type void type class params method arg types if params length 1 if pass 1 if params 0 type return method else if pass 2 kit code bug if params 0 is assignable from type return method return null memberbox extractsetmethod memberbox isstatic nativejavamethod findfunction memberbox isstatic isstatic getreturntype argtypes codebug isassignablefrom private static member box extract set method member box methods boolean is static for int i 0 i methods length i member box method methods i if is static method is static if method method get return type void type if method arg types length 1 return method return null memberbox extractsetmethod memberbox isstatic memberbox isstatic isstatic getreturntype argtypes hashtable get field and methods objects scriptable scope object java object boolean is static hashtable ht is static static field and methods field and methods if ht null return null int len ht size hashtable result new hashtable len enumeration e ht elements while len 0 field and methods fam field and methods e next element field and methods fam new new field and methods scope fam methods fam field fam new java object java object result put fam field get name fam new return result getfieldandmethodsobjects javaobject isstatic isstatic staticfieldandmethods fieldandmethods fieldandmethods fieldandmethods nextelement fieldandmethods famnew fieldandmethods famnew javaobject javaobject getname famnew static java members lookup class scriptable scope class dynamic type class static type java members members class cache cache class cache get scope hashtable ct cache class table class cl dynamic type for members java members ct get cl if members null return members try members new java members cache scope cl break catch security exception e reflection may fail for objects that are in a restricted access package e g sun if we get a security exception try again with the static type if it is interface otherwise try superclass if static type null static type is interface cl static type static type null try static type only once else class parent cl get superclass if parent null if cl is interface last resort after failed static type interface parent script runtime object class else throw e cl parent if cache is caching enabled ct put cl members return members javamembers lookupclass dynamictype statictype javamembers classcache classcache classtable dynamictype javamembers javamembers securityexception statictype statictype isinterface statictype statictype statictype getsuperclass isinterface statictype scriptruntime objectclass iscachingenabled runtime exception report member not found string member name return context report runtime error2 msg java member not found cl get name member name runtimeexception reportmembernotfound membername reportruntimeerror2 getname membername bean property member box getter member box setter native java method setters this getter getter this setter setter this setters setters beanproperty memberbox memberbox nativejavamethod field and methods scriptable scope member box methods field field super methods this field field set parent scope scope set prototype scriptable object get function prototype scope fieldandmethods memberbox setparentscope setprototype scriptableobject getfunctionprototype public object get default value class hint if hint script runtime function class return this object rval class type try rval field get java object type field get type catch illegal access exception acc ex throw context report runtime error1 msg java internal private field get name context cx context get context rval cx get wrap factory wrap cx this rval type if rval instanceof scriptable rval scriptable rval get default value hint return rval getdefaultvalue scriptruntime functionclass javaobject gettype illegalaccessexception accex reportruntimeerror1 getname getcontext getwrapfactory getdefaultvalue protected boolean has feature context cx int feature index switch feature index case context feature strict vars case context feature strict eval return strict mode return super has feature cx feature index hasfeature featureindex featureindex feature_strict_vars feature_strict_eval strictmode hasfeature featureindex protected void on context created context cx cx set language version language version cx set optimization level optimization level if error reporter null cx set error reporter error reporter super on context created cx oncontextcreated setlanguageversion languageversion setoptimizationlevel optimizationlevel errorreporter seterrorreporter errorreporter oncontextcreated public void set strict mode boolean flag check not sealed this strict mode flag setstrictmode checknotsealed strictmode public void set language version int version context check language version version check not sealed this language version version setlanguageversion checklanguageversion checknotsealed languageversion public void set optimization level int optimization level context check optimization level optimization level check not sealed this optimization level optimization level setoptimizationlevel optimizationlevel checkoptimizationlevel optimizationlevel checknotsealed optimizationlevel optimizationlevel public void set error reporter error reporter error reporter if error reporter null throw new illegal argument exception this error reporter error reporter seterrorreporter errorreporter errorreporter errorreporter illegalargumentexception errorreporter errorreporter replace item int begin int end string text this begin begin this end end this replacement text replaceitem public char get buffer return buffer getbuffer public void read data reader r throws io exception int capacity buffer length int offset 0 for int n read r read buffer offset capacity offset if n read 0 break offset n read if capacity offset capacity 2 char tmp new char capacity system arraycopy buffer 0 tmp 0 offset buffer tmp buffer end offset readdata ioexception n_read n_read n_read bufferend public void write initial data writer w throws io exception w write buffer 0 buffer end writeinitialdata ioexception bufferend public void write data writer w throws io exception int offset 0 for replace item x first replace x null x x next int before replace x begin offset if before replace 0 w write buffer offset before replace w write x replacement offset x end int tail buffer end offset if tail 0 w write buffer offset tail writedata ioexception replaceitem firstreplace before_replace before_replace before_replace bufferend public boolean was modified return first replace null wasmodified firstreplace public boolean set replacement int begin int end string text if equals text buffer begin end return false replace item item new replace item begin end text if first replace null first replace last replace item else if begin first replace begin item next first replace first replace item else replace item cursor first replace replace item next cursor next while next null if begin next begin item next next cursor next item break cursor next next next next if next null last replace next item return true setreplacement replaceitem replaceitem firstreplace firstreplace lastreplace firstreplace firstreplace firstreplace replaceitem firstreplace replaceitem lastreplace public int get line number return line number getlinenumber linenumber public int get line number return line number public int get line begin return line begin getlinenumber linenumber getlinebegin linebegin public int get line begin return line begin public int get line end return line end getlinebegin linebegin getlineend lineend public int get line end return line end public void start line loop line number 0 line begin line end next line start 0 getlineend lineend startlineloop linenumber linebegin lineend nextlinestart public boolean next line if next line start buffer end line number 0 return false int i int c 0 for i next line start i buffer end i c buffer i if c n c r break line begin next line start line end i if i buffer end next line start i else if c r i 1 buffer end buffer i 1 n next line start i 2 else next line start i 1 line number return true nextline nextlinestart bufferend linenumber nextlinestart bufferend linebegin nextlinestart lineend bufferend nextlinestart bufferend nextlinestart nextlinestart linenumber private static boolean equals string str char array int begin int end if str length end begin for int i begin j 0 i end i j if array i str char at j return false return true return false charat private namespace helper xml lib impl lib this lib lib insert the default namespace prefix touri put set prefixes new hash set prefixes add uri to prefix put prefixes namespacehelper xmllibimpl prefixtouri hashset uritoprefix declared a new namespace param prefix param uri param declarations private void declare namespace string prefix string uri obj array declarations set prefixes set uri to prefix get uri if prefixes null prefixes new hash set uri to prefix put uri prefixes if prefixes contains prefix string olduri string prefix touri get prefix add the new mapping prefixes add prefix prefix touri put prefix uri if declarations null declarations add new namespace lib prefix uri if olduri null update the existing mapping prefixes set uri to prefix get olduri prefixes remove prefix declarenamespace objarray uritoprefix hashset uritoprefix prefixtouri prefixtouri uritoprefix updates the internal state of this namespace helper to reflect the existance of the xml token pointed to by the cursor private void process name xml cursor cursor obj array declarations javax xml namespace q name qname cursor get name string uri qname get namespaceuri set prefixes set uri to prefix get uri if prefixes null prefixes size 0 undeclared add uri if declarations null declarations add new namespace lib uri namespacehelper processname xmlcursor objarray qname getname getnamespaceuri uritoprefix updates the internal state of this namespace helper with the namespace information of the element pointed to by the cursor private void update xml cursor cursor obj array declarations process the namespace declarations cursor push while cursor to next token is any attr if cursor is namespace javax xml namespace q name name cursor get name string prefix name get local part string uri name get namespaceuri declare namespace prefix uri declarations cursor pop process the element process name cursor declarations process the attributes cursor push boolean has next cursor to first attribute while has next process name cursor declarations has next cursor to next attribute cursor pop namespacehelper xmlcursor objarray tonexttoken isanyattr isnamespace qname getname getlocalpart getnamespaceuri declarenamespace processname hasnext tofirstattribute hasnext processname hasnext tonextattribute return object array of namespace objects in scope at the cursor public static object in scope namespaces xml lib impl lib xml cursor cursor obj array namespaces new obj array namespace helper helper new namespace helper lib cursor push int depth 0 while cursor has prev token if cursor is container cursor push depth cursor to parent for int i 0 i depth i cursor pop helper update cursor null iterator i helper prefix touri entry set iterator while i has next map entry entry map entry i next namespace ns new namespace lib string entry get key string entry get value namespaces add ns i helper undeclared iterator while i has next namespace ns new namespace lib string i next namespaces add ns cursor pop return namespaces to array inscopenamespaces xmllibimpl xmlcursor objarray objarray namespacehelper namespacehelper hasprevtoken iscontainer toparent prefixtouri entryset hasnext getkey getvalue hasnext toarray static namespace get namespace xml lib impl lib xml cursor cursor object in scope namespaces string uri string prefix if cursor is procinst uri prefix else javax xml namespace q name qname cursor get name uri qname get namespaceuri prefix qname get prefix if in scope namespaces null return new namespace lib prefix uri namespace result null for int i 0 i in scope namespaces length i namespace ns namespace in scope namespaces i if ns null continue string nsuri ns uri if nsuri equals uri if prefix equals ns prefix result ns break if result null result prefix null ns prefix null result ns if result null result new namespace lib prefix uri return result getnamespace xmllibimpl xmlcursor inscopenamespaces isprocinst qname getname getnamespaceuri getprefix inscopenamespaces inscopenamespaces inscopenamespaces return list of namespace objects that are declared in the container pointed to by the cursor public static object namespace declarations xml lib impl lib xml cursor cursor obj array declarations new obj array namespace helper helper new namespace helper lib cursor push int depth 0 while cursor has prev token if cursor is container cursor push depth cursor to parent for int i 0 i depth 1 i cursor pop helper update cursor null if depth 0 cursor pop helper update cursor declarations cursor pop return declarations to array namespacedeclarations xmllibimpl xmlcursor objarray objarray namespacehelper namespacehelper hasprevtoken iscontainer toparent toarray return prefix to uri map of all namespaces in scope at the cursor public static map get all namespaces xml lib impl lib xml cursor cursor namespace helper helper new namespace helper lib cursor push int depth 0 while cursor has prev token if cursor is container cursor push depth cursor to parent for int i 0 i depth i cursor pop helper update cursor null cursor pop return helper prefix touri getallnamespaces xmllibimpl xmlcursor namespacehelper namespacehelper hasprevtoken iscontainer toparent prefixtouri public static void get namespaces xml cursor cursor map prefix touri cursor push while cursor to next token is any attr if cursor is namespace javax xml namespace q name name cursor get name string prefix name get local part string uri name get namespaceuri prefix touri put prefix uri cursor pop getnamespaces xmlcursor prefixtouri tonexttoken isanyattr isnamespace qname getname getlocalpart getnamespaceuri prefixtouri public static void remove namespace xml cursor cursor string prefix cursor push while cursor to next token is any attr if cursor is namespace javax xml namespace q name name cursor get name if name get local part equals prefix cursor remove xml break cursor pop removenamespace xmlcursor tonexttoken isanyattr isnamespace qname getname getlocalpart removexml main entry point process arguments as would a normal java program then set up the execution environment and begin to compile scripts public static void main string args main main new main args main process options args if args null if main print help system out println tool error reporter get message msg jsc usage main class get name system exit 0 system exit 1 if main reporter has reported error main process source args processoptions printhelp toolerrorreporter getmessage getname hasreportederror processsource public main reporter new tool error reporter true compiler env new compiler environs compiler env set error reporter reporter compiler new class compiler compiler env toolerrorreporter compilerenv compilerenvirons compilerenv seterrorreporter classcompiler compilerenv parse arguments public string process options string args target package default to no package compiler env set generate debug info false default to no symbols for int i 0 i args length i string arg args i if arg starts with int tail args length i if target name null tail 1 add error msg multiple js to file target name return null string result new string tail for int j 0 j tail j result j args i j return result if arg equals help arg equals h arg equals help print help true return null try if arg equals version i args length int version integer parse int args i compiler env set language version version continue if arg equals opt arg equals o i args length int opt level integer parse int args i compiler env set optimization level opt level continue catch number format exception e bad usage args i return null if arg equals nosource compiler env set generating source false continue if arg equals debug arg equals g compiler env set generate debug info true continue if arg equals main method class i args length compiler set main method class args i continue if arg equals o i args length string name args i int end name length if end 0 character is java identifier start name char at 0 add error msg invalid classfile name name continue for int j 1 j end j char c name char at j if character is java identifier part c if c check if it is the dot in class if j end 6 name ends with class name name substring 0 j break add error msg invalid classfile name name break target name name continue if arg equals package i args length string pkg args i int end pkg length for int j 0 j end j char c pkg char at j if character is java identifier start c for j j end j c pkg char at j if character is java identifier part c break if j end break if c j end 1 continue add error msg package name target package return null target package pkg continue if arg equals extends i args length string target extends args i class super class try super class class for name target extends catch class not found exception e throw new error e to string todo better error compiler set target extends super class continue if arg equals implements i args length todo allow for multiple comma separated interfaces string target implements args i string tokenizer st new string tokenizer target implements vector v new vector while st has more tokens string class name st next token try v add element class for name class name catch class not found exception e throw new error e to string todo better error class implements classes new class v size v copy into implements classes compiler set target implements implements classes continue if arg equals d i args length destination dir args i continue bad usage arg return null no file name p tool error reporter get message msg no file return null processoptions targetpackage compilerenv setgeneratedebuginfo startswith targetname adderror targetname printhelp parseint compilerenv setlanguageversion optlevel parseint compilerenv setoptimizationlevel optlevel numberformatexception badusage compilerenv setgeneratingsource compilerenv setgeneratedebuginfo setmainmethodclass isjavaidentifierstart charat adderror charat isjavaidentifierpart endswith adderror targetname charat isjavaidentifierstart charat isjavaidentifierpart adderror targetpackage targetpackage targetextends superclass superclass forname targetextends classnotfoundexception tostring settargetextends superclass targetimplements stringtokenizer stringtokenizer targetimplements hasmoretokens classname nexttoken addelement forname classname classnotfoundexception tostring implementsclasses copyinto implementsclasses settargetimplements implementsclasses destinationdir badusage toolerrorreporter getmessage print a usage message private static void bad usage string s system err println tool error reporter get message msg jsc bad usage main class get name s badusage toolerrorreporter getmessage getname compile java script source public void process source string filenames for int i 0 i filenames length i string filename filenames i if filename ends with js add error msg extension not js filename return file f new file filename string source read source f if source null return string main class name target name if main class name null string name f get name string nojs name substring 0 name length 3 main class name get class name nojs if target package length 0 main class name target package main class name object compiled compiler compile to class files source filename 1 main class name if compiled null compiled length 0 return file target top dir null if destination dir null target top dir new file destination dir else string parent f get parent if parent null target top dir new file parent for int j 0 j compiled length j 2 string class name string compiled j byte bytes byte compiled j 1 file outfile get output file target top dir class name try file output stream os new file output stream outfile try os write bytes finally os close catch io exception ioe add formated error ioe to string javascript processsource endswith adderror readsource mainclassname targetname mainclassname getname mainclassname getclassname targetpackage mainclassname targetpackage mainclassname compiletoclassfiles mainclassname targettopdir destinationdir targettopdir destinationdir getparent targettopdir classname getoutputfile targettopdir classname fileoutputstream fileoutputstream ioexception addformatederror tostring private string read source file f if f exists add error msg jsfile not found f get absolute path return null try reader in new file reader f try return kit read reader in finally in close catch file not found exception ex add error msg couldnt open f get absolute path catch io exception ioe add formated error ioe to string return null readsource adderror getabsolutepath filereader readreader filenotfoundexception adderror getabsolutepath ioexception addformatederror tostring private file get output file file parent dir string class name string path class name replace file separator char path path concat class file f new file parent dir path string dir path f get parent if dir path null file dir new file dir path if dir exists dir mkdirs return f getoutputfile parentdir classname classname separatorchar parentdir dirpath getparent dirpath dirpath verify that class file names are legal java identifiers substitute illegal characters with underscores and prepend the name with an underscore if the file name does not begin with a java letter string get class name string name char s new char name length 1 char c int j 0 if character is java identifier start name char at 0 s j for int i 0 i name length i j c name char at i if character is java identifier part c s j c else s j return new string s trim javaletter getclassname isjavaidentifierstart charat _ charat isjavaidentifierpart _ private static void p string s system out println s private void add error string message id string arg string msg if arg null msg tool error reporter get message message id else msg tool error reporter get message message id arg add formated error msg adderror messageid toolerrorreporter getmessage messageid toolerrorreporter getmessage messageid addformatederror private void add formated error string message reporter error message null 1 null 1 addformatederror public string float float public string ambiguous boolean arg return boolean public string ambiguous byte arg return byte public string ambiguous short arg return short public string ambiguous int arg return int public string ambiguous long arg return long public string ambiguous float arg return float public string ambiguous double arg return double object double_object public string ambiguous double arg return double public string ambiguous char arg return char public string ambiguous object arg return object public string expect return object public string float float public string ambiguous boolean arg return boolean public string ambiguous byte arg return byte public string ambiguous short arg return short public string ambiguous int arg return int public string ambiguous long arg return long public string ambiguous float arg return float public string ambiguous double arg return double object double_object public string ambiguous double arg return double public string float float public string ambiguous float arg return float public string ambiguous double arg return double public string ambiguous byte arg return byte public string ambiguous char arg return char public string ambiguous short arg return short public string ambiguous int arg return int public string ambiguous long arg return long public string ambiguous string arg return string public string ambiguous object arg return object public string ambiguous boolean arg return boolean object boolean_object public string ambiguous boolean arg return boolean return boolean public string expect return boolean public object compile compiler environs compiler env script or fn node tree string encoded source boolean return function int serial synchronized global lock serial global serial class counter string main class name org mozilla javascript gen c serial byte main class bytes compile to class file compiler env main class name tree encoded source return function return new object main class name main class bytes compilerenvirons compilerenv scriptorfnnode encodedsource returnfunction globallock globalserialclasscounter mainclassname mainclassbytes compiletoclassfile compilerenv mainclassname encodedsource returnfunction mainclassname mainclassbytes public script create script object object bytecode object static security domain class cl define class bytecode static security domain script script try script script cl new instance catch exception ex throw new runtime exception unable to instantiate compiled class ex to string return script createscriptobject staticsecuritydomain defineclass staticsecuritydomain newinstance runtimeexception tostring public function create function object context cx scriptable scope object bytecode object static security domain class cl define class bytecode static security domain native function f try constructor ctor cl get constructors 0 object init args scope cx new integer 0 f native function ctor new instance init args catch exception ex throw new runtime exception unable to instantiate compiled class ex to string return f createfunctionobject staticsecuritydomain defineclass staticsecuritydomain nativefunction getconstructors initargs nativefunction newinstance initargs runtimeexception tostring private class define class object bytecode object static security domain object name bytes pair object bytecode string class name string name bytes pair 0 byte class bytes byte name bytes pair 1 the generated classes in this case refer only to rhino classes which must be accessible through this class loader class loader rhino loader get class get class loader generated class loader loader loader security controller create loader rhino loader static security domain exception e try class cl loader define class class name class bytes loader link class cl return cl catch security exception x e x catch illegal argument exception x e x throw new runtime exception malformed optimizer package e defineclass staticsecuritydomain namebytespair classname namebytespair classbytes namebytespair classloader rhinoloader getclass getclassloader generatedclassloader securitycontroller createloader rhinoloader staticsecuritydomain defineclass classname classbytes linkclass securityexception illegalargumentexception runtimeexception byte compile to class file compiler environs compiler env string main class name script or fn node script or fn string encoded source boolean return function this compiler env compiler env transform script or fn if token print trees system out println script or fn to string tree script or fn if return function script or fn script or fn get function node 0 init script or fn nodes data script or fn this main class name main class name main class signature class file writer class name to signature main class name return generate code encoded source compiletoclassfile compilerenvirons compilerenv mainclassname scriptorfnnode scriptorfn encodedsource returnfunction compilerenv compilerenv scriptorfn printtrees scriptorfn tostringtree scriptorfn returnfunction scriptorfn scriptorfn getfunctionnode initscriptorfnnodesdata scriptorfn mainclassname mainclassname mainclasssignature classfilewriter classnametosignature mainclassname generatecode encodedsource private void transform script or fn node tree initoptfunctions r tree int opt level compiler env get optimization level hashtable possible direct calls null if opt level 0 collect all of the contained functions into a hashtable so that the call optimizer can access the class name parameter count for any call it encounters if tree get type token script int function count tree get function count for int i 0 i function count i opt function node ofn opt function node get tree i if ofn fnode get function type function node function statement string name ofn fnode get function name if name length 0 if possible direct calls null possible direct calls new hashtable possible direct calls put name ofn if possible direct calls null direct call targets new obj array opt transformer ot new opt transformer possible direct calls direct call targets ot transform tree if opt level 0 new optimizer optimize tree opt level scriptorfnnode initoptfunctions_r optlevel compilerenv getoptimizationlevel possibledirectcalls optlevel gettype functioncount getfunctioncount functioncount optfunctionnode optfunctionnode getfunctiontype functionnode function_statement getfunctionname possibledirectcalls possibledirectcalls possibledirectcalls possibledirectcalls directcalltargets objarray opttransformer opttransformer possibledirectcalls directcalltargets optlevel optlevel private static void initoptfunctions r script or fn node script or fn for int i 0 n script or fn get function count i n i function node fn script or fn get function node i new opt function node fn initoptfunctions r fn initoptfunctions_r scriptorfnnode scriptorfn scriptorfn getfunctioncount functionnode scriptorfn getfunctionnode optfunctionnode initoptfunctions_r private void init script or fn nodes data script or fn node script or fn obj array x new obj array collectscriptorfnnodes r script or fn x int count x size script or fn nodes new script or fn node count x to array script or fn nodes script or fn indexes new obj to int map count for int i 0 i count i script or fn indexes put script or fn nodes i i initscriptorfnnodesdata scriptorfnnode scriptorfn objarray objarray collectscriptorfnnodes_r scriptorfn scriptorfnnodes scriptorfnnode toarray scriptorfnnodes scriptorfnindexes objtointmap scriptorfnindexes scriptorfnnodes private static void collectscriptorfnnodes r script or fn node n obj array x x add n int nested count n get function count for int i 0 i nested count i collectscriptorfnnodes r n get function node i x collectscriptorfnnodes_r scriptorfnnode objarray nestedcount getfunctioncount nestedcount collectscriptorfnnodes_r getfunctionnode private byte generate code string encoded source boolean has script script or fn nodes 0 get type token script boolean has functions script or fn nodes length 1 has script string source file null if compiler env is generate debug info source file script or fn nodes 0 get source name class file writer cfw new class file writer main class name super class name source file cfw add field id field name i class file writer acc private cfw add field direct call parent field main class signature class file writer acc private cfw add field regexp array field name regexp array field type class file writer acc private if has functions generate function constructor cfw if has script script or fn node script script or fn nodes 0 cfw add interface org mozilla javascript script generate script ctor cfw script generate main cfw generate execute cfw script generate call method cfw generate native function overrides cfw encoded source int count script or fn nodes length for int i 0 i count i script or fn node n script or fn nodes i body codegen bodygen new body codegen bodygen cfw cfw bodygen codegen this bodygen compiler env compiler env bodygen script or fn n bodygen generate body code if n get type token function opt function node ofn opt function node get n generate function init cfw ofn if ofn is target of direct call emit direct constructor cfw ofn if direct call targets null int n direct call targets size for int j 0 j n j cfw add field get direct target field name j main class signature class file writer acc private emit reg exp init cfw emit constant dude initializers cfw return cfw to byte array generatecode encodedsource hasscript scriptorfnnodes gettype hasfunctions scriptorfnnodes hasscript sourcefile compilerenv isgeneratedebuginfo sourcefile scriptorfnnodes getsourcename classfilewriter classfilewriter mainclassname super_class_name sourcefile addfield id_field_name classfilewriter acc_private addfield direct_call_parent_field mainclasssignature classfilewriter acc_private addfield regexp_array_field_name regexp_array_field_type classfilewriter acc_private hasfunctions generatefunctionconstructor hasscript scriptorfnnode scriptorfnnodes addinterface generatescriptctor generatemain generateexecute generatecallmethod generatenativefunctionoverrides encodedsource scriptorfnnodes scriptorfnnode scriptorfnnodes bodycodegen bodycodegen compilerenv compilerenv scriptorfn generatebodycode gettype optfunctionnode optfunctionnode generatefunctioninit istargetofdirectcall emitdirectconstructor directcalltargets directcalltargets addfield getdirecttargetfieldname mainclasssignature classfilewriter acc_private emitregexpinit emitconstantdudeinitializers tobytearray private void emit direct constructor class file writer cfw opt function node ofn we generate scriptable direct construct direct call args scriptable new instance create object cx scope object val body name cx scope new instance direct call args if val instanceof scriptable return scriptable val return new instance cfw start method get direct ctor name ofn fnode get body method signature ofn fnode short class file writer acc static class file writer acc private int arg count ofn fnode get param count int first local 4 arg count 3 1 cfw adda load 0 this cfw adda load 1 cx cfw adda load 2 scope cfw add invoke byte code invokevirtual org mozilla javascript base function create object lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable cfw adda store first local cfw adda load 0 cfw adda load 1 cfw adda load 2 cfw adda load first local for int i 0 i arg count i cfw adda load 4 i 3 cfw addd load 5 i 3 cfw adda load 4 arg count 3 cfw add invoke byte code invokestatic main class name get body method name ofn fnode get body method signature ofn fnode int exit label cfw acquire label cfw add byte code dup make a copy of direct call result cfw add byte code instanceof org mozilla javascript scriptable cfw add byte code ifeq exit label cast direct call result cfw add byte code checkcast org mozilla javascript scriptable cfw add byte code areturn cfw mark label exit label cfw adda load first local cfw add byte code areturn cfw stop method short first local 1 emitdirectconstructor classfilewriter optfunctionnode directconstruct directcallargs newinstance createobject newinstance directcallargs newinstance startmethod getdirectctorname getbodymethodsignature classfilewriter acc_static classfilewriter acc_private argcount getparamcount firstlocal argcount addaload addaload addaload addinvoke bytecode basefunction createobject addastore firstlocal addaload addaload addaload addaload firstlocal argcount addaload adddload addaload argcount addinvoke bytecode mainclassname getbodymethodname getbodymethodsignature exitlabel acquirelabel bytecode bytecode bytecode exitlabel bytecode bytecode marklabel exitlabel addaload firstlocal bytecode stopmethod firstlocal private void generate call method class file writer cfw cfw start method call lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable ljava lang object ljava lang object short class file writer acc public class file writer acc final generate code for if script runtime has top call cx return script runtime do top call this cx scope this obj args int non top call label cfw acquire label cfw adda load 1 cx cfw add invoke byte code invokestatic org mozilla javascript script runtime has top call lorg mozilla javascript context z cfw add byte code ifne non top call label cfw adda load 0 cfw adda load 1 cfw adda load 2 cfw adda load 3 cfw adda load 4 cfw add invoke byte code invokestatic org mozilla javascript script runtime do top call lorg mozilla javascript callable lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable ljava lang object ljava lang object cfw add byte code areturn cfw mark label non top call label no generate switch to call the real methods cfw adda load 0 cfw adda load 1 cfw adda load 2 cfw adda load 3 cfw adda load 4 int end script or fn nodes length boolean generate switch 2 end int switch start 0 int switch stack top 0 if generate switch cfw add load this cfw add byte code getfield cfw get class name id field name i do switch from 1 end 1 mapping 0 to the default case switch start cfw add table switch 1 end 1 for int i 0 i end i script or fn node n script or fn nodes i if generate switch if i 0 cfw mark table switch default switch start switch stack top cfw get stack top else cfw mark table switch case switch start i 1 switch stack top if n get type token function opt function node ofn opt function node get n if ofn is target of direct call int pcount ofn fnode get param count if pcount 0 loop invariant stack top arguments array from adda load4 for int p 0 p pcount p cfw add byte code arraylength cfw add push p int undef arg cfw acquire label int beyond cfw acquire label cfw add byte code if icmple undef arg get array p cfw adda load 4 cfw add push p cfw add byte code aaload cfw add byte code goto beyond cfw mark label undef arg push undefined cfw cfw mark label beyond only one push cfw adjust stack top 1 cfw add push 0 0 restore invariant cfw adda load 4 cfw add invoke byte code invokestatic main class name get body method name n get body method signature n cfw add byte code areturn cfw stop method short 5 5 this cx scope js this args generatecallmethod classfilewriter startmethod classfilewriter acc_public classfilewriter acc_final scriptruntime hastopcall scriptruntime dotopcall thisobj nontopcalllabel acquirelabel addaload addinvoke bytecode scriptruntime hastopcall bytecode nontopcalllabel addaload addaload addaload addaload addaload addinvoke bytecode scriptruntime dotopcall bytecode marklabel nontopcalllabel addaload addaload addaload addaload addaload scriptorfnnodes generateswitch switchstart switchstacktop generateswitch addloadthis bytecode getclassname id_field_name switchstart addtableswitch scriptorfnnode scriptorfnnodes generateswitch marktableswitchdefault switchstart switchstacktop getstacktop marktableswitchcase switchstart switchstacktop gettype optfunctionnode optfunctionnode istargetofdirectcall getparamcount addaload4 bytecode addpush undefarg acquirelabel acquirelabel bytecode if_icmple undefarg addaload addpush bytecode bytecode marklabel undefarg pushundefined marklabel adjuststacktop addpush addaload addinvoke bytecode mainclassname getbodymethodname getbodymethodsignature bytecode stopmethod private void generate main class file writer cfw cfw start method main ljava lang string v short class file writer acc public class file writer acc static load new script impl cfw add byte code new cfw get class name cfw add byte code dup cfw add invoke byte code invokespecial cfw get class name init v load args cfw add byte code aload 0 call main method class main script script string args cfw add invoke byte code invokestatic main method class main lorg mozilla javascript script ljava lang string v cfw add byte code return 1 string args cfw stop method short 1 generatemain classfilewriter startmethod classfilewriter acc_public classfilewriter acc_static scriptimpl bytecode getclassname bytecode addinvoke bytecode getclassname bytecode aload_0 mainmethodclass addinvoke bytecode mainmethodclass bytecode stopmethod private void generate execute class file writer cfw script or fn node script cfw start method exec lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object short class file writer acc public class file writer acc final final int context arg 1 final int scope arg 2 cfw add load this cfw adda load context arg cfw adda load scope arg cfw add byte code dup cfw add byte code aconst null cfw add invoke byte code invokevirtual cfw get class name call lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable ljava lang object ljava lang object cfw add byte code areturn 3 this context scope cfw stop method short 3 generateexecute classfilewriter scriptorfnnode startmethod classfilewriter acc_public classfilewriter acc_final context_arg scope_arg addloadthis addaload context_arg addaload scope_arg bytecode bytecode aconst_null addinvoke bytecode getclassname bytecode stopmethod private void generate script ctor class file writer cfw script or fn node script cfw start method init v class file writer acc public cfw add load this cfw add invoke byte code invokespecial super class name init v set id to 0 cfw add load this cfw add push 0 cfw add byte code putfield cfw get class name id field name i cfw add byte code return 1 parameter this cfw stop method short 1 generatescriptctor classfilewriter scriptorfnnode startmethod classfilewriter acc_public addloadthis addinvoke bytecode super_class_name addloadthis addpush bytecode getclassname id_field_name bytecode stopmethod private void generate function constructor class file writer cfw final int scope arg 1 final int context arg 2 final int id arg 3 cfw start method init function constructor signature class file writer acc public cfw adda load 0 cfw add invoke byte code invokespecial super class name init v cfw add load this cfw addi load id arg cfw add byte code putfield cfw get class name id field name i cfw add load this cfw adda load context arg cfw adda load scope arg int start script or fn nodes 0 get type token script 1 0 int end script or fn nodes length if start end throw bad tree boolean generate switch 2 end start int switch start 0 int switch stack top 0 if generate switch cfw addi load id arg do switch from start 1 end 1 mapping start to the default case switch start cfw add table switch start 1 end 1 for int i start i end i if generate switch if i start cfw mark table switch default switch start switch stack top cfw get stack top else cfw mark table switch case switch start i 1 start switch stack top opt function node ofn opt function node get script or fn nodes i cfw add invoke byte code invokevirtual main class name get function init method name ofn function init signature cfw add byte code return 4 this scope context id cfw stop method short 4 generatefunctionconstructor classfilewriter scope_arg context_arg id_arg startmethod function_constructor_signature classfilewriter acc_public addaload addinvoke bytecode super_class_name addloadthis addiload id_arg bytecode getclassname id_field_name addloadthis addaload context_arg addaload scope_arg scriptorfnnodes gettype scriptorfnnodes badtree generateswitch switchstart switchstacktop generateswitch addiload id_arg switchstart addtableswitch generateswitch marktableswitchdefault switchstart switchstacktop getstacktop marktableswitchcase switchstart switchstacktop optfunctionnode optfunctionnode scriptorfnnodes addinvoke bytecode mainclassname getfunctioninitmethodname function_init_signature bytecode stopmethod private void generate function init class file writer cfw opt function node ofn final int context arg 1 final int scope arg 2 cfw start method get function init method name ofn function init signature short class file writer acc private class file writer acc final call native function init script function cfw add load this cfw adda load context arg cfw adda load scope arg cfw add invoke byte code invokevirtual org mozilla javascript native function init script function lorg mozilla javascript context lorg mozilla javascript scriptable v precompile all regexp literals int regexp count ofn fnode get regexp count if regexp count 0 cfw add load this push reg exp array cfw ofn fnode context arg scope arg cfw add byte code putfield main class name regexp array field name regexp array field type cfw add byte code return 3 script this function ref scope context cfw stop method short 3 generatefunctioninit classfilewriter optfunctionnode context_arg scope_arg startmethod getfunctioninitmethodname function_init_signature classfilewriter acc_private classfilewriter acc_final nativefunction initscriptfunction addloadthis addaload context_arg addaload scope_arg addinvoke bytecode nativefunction initscriptfunction regexpcount getregexpcount regexpcount addloadthis pushregexparray context_arg scope_arg bytecode mainclassname regexp_array_field_name regexp_array_field_type bytecode scriptthis functionref stopmethod private void generate native function overrides class file writer cfw string encoded source override native function get language version with public int get language version return version constant cfw start method get language version i class file writer acc public cfw add push compiler env get language version cfw add byte code ireturn 1 this and no argument or locals cfw stop method short 1 the rest of native function overrides require specific code for each script function id final int do getfunctionname 0 final int do getparamcount 1 final int do getparamandvarcount 2 final int do getparamorvarname 3 final int do getencodedsource 4 final int switch count 5 for int method index 0 method index switch count method index if method index do getencodedsource encoded source null continue generate prologue switch over function id to implement function specific action epilogue short metod locals switch method index case do getfunctionname metod locals 1 only this cfw start method get function name ljava lang string class file writer acc public break case do getparamcount metod locals 1 only this cfw start method get param count i class file writer acc public break case do getparamandvarcount metod locals 1 only this cfw start method get param and var count i class file writer acc public break case do getparamorvarname metod locals 1 1 this param or var index cfw start method get param or var name i ljava lang string class file writer acc public break case do getencodedsource metod locals 1 only this cfw start method get encoded source ljava lang string class file writer acc public cfw add push encoded source break default throw kit code bug int count script or fn nodes length int switch start 0 int switch stack top 0 if count 1 generate switch but only if there is more then one script function cfw add load this cfw add byte code getfield cfw get class name id field name i do switch from 1 count 1 mapping 0 to the default case switch start cfw add table switch 1 count 1 for int i 0 i count i script or fn node n script or fn nodes i if i 0 if count 1 cfw mark table switch default switch start switch stack top cfw get stack top else cfw mark table switch case switch start i 1 switch stack top impelemnet method specific switch code switch method index case do getfunctionname push function name if n get type token script cfw add push else string name function node n get function name cfw add push name cfw add byte code areturn break case do getparamcount push number of defined parameters cfw add push n get param count cfw add byte code ireturn break case do getparamandvarcount push number of defined parameters and declared variables cfw add push n get param and var count cfw add byte code ireturn break case do getparamorvarname push name of parameter using another switch over param and var count int param and var count n get param and var count if param and var count 0 the runtime should never call the method in this case but to make bytecode verifier happy return null as throwing execption takes more code cfw add byte code aconst null cfw add byte code areturn else if param and var count 1 as above do not check for valid index but always return the name of the first param cfw add push n get param or var name 0 cfw add byte code areturn else do switch over get param or var name cfw addi load 1 param or var index do switch from 1 param and var count 1 mapping 0 to the default case int param switch start cfw add table switch 1 param and var count 1 for int j 0 j param and var count j if cfw get stack top 0 kit code bug string s n get param or var name j if j 0 cfw mark table switch default param switch start else cfw mark table switch case param switch start j 1 0 cfw add push s cfw add byte code areturn break case do getencodedsource push number encoded source start and end to prepare for encoded source substring start end cfw add push n get encoded source start cfw add push n get encoded source end cfw add invoke byte code invokevirtual java lang string substring ii ljava lang string cfw add byte code areturn break default throw kit code bug cfw stop method metod locals generatenativefunctionoverrides classfilewriter encodedsource nativefunction getlanguageversion getlanguageversion startmethod getlanguageversion classfilewriter acc_public addpush compilerenv getlanguageversion bytecode stopmethod nativefunction do_getfunctionname do_getparamcount do_getparamandvarcount do_getparamorvarname do_getencodedsource switch_count methodindex methodindex switch_count methodindex methodindex do_getencodedsource encodedsource metodlocals methodindex do_getfunctionname metodlocals startmethod getfunctionname classfilewriter acc_public do_getparamcount metodlocals startmethod getparamcount classfilewriter acc_public do_getparamandvarcount metodlocals startmethod getparamandvarcount classfilewriter acc_public do_getparamorvarname metodlocals paramorvarindex startmethod getparamorvarname classfilewriter acc_public do_getencodedsource metodlocals startmethod getencodedsource classfilewriter acc_public addpush encodedsource codebug scriptorfnnodes switchstart switchstacktop addloadthis bytecode getclassname id_field_name switchstart addtableswitch scriptorfnnode scriptorfnnodes marktableswitchdefault switchstart switchstacktop getstacktop marktableswitchcase switchstart switchstacktop methodindex do_getfunctionname gettype addpush functionnode getfunctionname addpush bytecode do_getparamcount addpush getparamcount bytecode do_getparamandvarcount addpush getparamandvarcount bytecode do_getparamorvarname paramandvarcount paramandvarcount getparamandvarcount paramandvarcount bytecode aconst_null bytecode paramandvarcount addpush getparamorvarname bytecode getparamorvarname addiload paramandvarcount paramswitchstart addtableswitch paramandvarcount paramandvarcount getstacktop codebug getparamorvarname marktableswitchdefault paramswitchstart marktableswitchcase paramswitchstart addpush bytecode do_getencodedsource encodedsource addpush getencodedsourcestart addpush getencodedsourceend addinvoke bytecode bytecode codebug stopmethod metodlocals private void emit reg exp init class file writer cfw precompile all regexp literals int total reg count 0 for int i 0 i script or fn nodes length i total reg count script or fn nodes i get regexp count if total reg count 0 return cfw start method regexp init method name regexp init method signature short class file writer acc static class file writer acc private class file writer acc synchronized cfw add field reinitdone z short class file writer acc static class file writer acc private cfw add byte code getstatic main class name reinitdone z int do init cfw acquire label cfw add byte code ifeq do init cfw add byte code return cfw mark label do init for int i 0 i script or fn nodes length i script or fn node n script or fn nodes i int reg count n get regexp count for int j 0 j reg count j string re field name get compiled regexp name n j string re field type ljava lang object string re string n get regexp string j string re flags n get regexp flags j cfw add field re field name re field type short class file writer acc static class file writer acc private cfw adda load 0 proxy cfw adda load 1 context cfw add push re string if re flags null cfw add byte code aconst null else cfw add push re flags cfw add invoke byte code invokeinterface org mozilla javascript reg exp proxy compile reg exp lorg mozilla javascript context ljava lang string ljava lang string ljava lang object cfw add byte code putstatic main class name re field name re field type cfw add push 1 cfw add byte code putstatic main class name reinitdone z cfw add byte code return cfw stop method short 2 emitregexpinit classfilewriter totalregcount scriptorfnnodes totalregcount scriptorfnnodes getregexpcount totalregcount startmethod regexp_init_method_name regexp_init_method_signature classfilewriter acc_static classfilewriter acc_private classfilewriter acc_synchronized addfield _reinitdone classfilewriter acc_static classfilewriter acc_private bytecode mainclassname _reinitdone doinit acquirelabel bytecode doinit bytecode marklabel doinit scriptorfnnodes scriptorfnnode scriptorfnnodes regcount getregexpcount regcount refieldname getcompiledregexpname refieldtype restring getregexpstring reflags getregexpflags addfield refieldname refieldtype classfilewriter acc_static classfilewriter acc_private addaload addaload addpush restring reflags bytecode aconst_null addpush reflags addinvoke bytecode regexpproxy compileregexp bytecode mainclassname refieldname refieldtype addpush bytecode mainclassname _reinitdone bytecode stopmethod private void emit constant dude initializers class file writer cfw int n its constant list size if n 0 return cfw start method clinit v short class file writer acc static class file writer acc final double array its constant list for int i 0 i n i double num array i string constant name k i string constant type get static constant wrapper type num cfw add field constant name constant type short class file writer acc static class file writer acc private int inum int num if inum num cfw add byte code new java lang integer cfw add byte code dup cfw add push inum cfw add invoke byte code invokespecial java lang integer init i v else cfw add push num add double wrap cfw cfw add byte code putstatic main class name constant name constant type cfw add byte code return cfw stop method short 0 emitconstantdudeinitializers classfilewriter itsconstantlistsize startmethod classfilewriter acc_static classfilewriter acc_final itsconstantlist constantname _k constanttype getstaticconstantwrappertype addfield constantname constanttype classfilewriter acc_static classfilewriter acc_private bytecode bytecode addpush addinvoke bytecode addpush adddoublewrap bytecode mainclassname constantname constanttype bytecode stopmethod void push reg exp array class file writer cfw script or fn node n int context arg int scope arg int regexp count n get regexp count if regexp count 0 throw bad tree cfw add push regexp count cfw add byte code anewarray java lang object cfw adda load context arg cfw add invoke byte code invokestatic org mozilla javascript script runtime check reg exp proxy lorg mozilla javascript context lorg mozilla javascript reg exp proxy stack proxy array cfw add byte code dup cfw adda load context arg cfw add invoke byte code invokestatic main class name regexp init method name regexp init method signature for int i 0 i regexp count i stack proxy array cfw add byte code dup2 cfw adda load context arg cfw adda load scope arg cfw add byte code getstatic main class name get compiled regexp name n i ljava lang object stack compiled reg exp scope cx proxy array proxy array cfw add invoke byte code invokeinterface org mozilla javascript reg exp proxy wrap reg exp lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript scriptable stack wrapped reg exp array proxy array cfw add push i cfw add byte code swap cfw add byte code aastore stack proxy array remove proxy cfw add byte code pop pushregexparray classfilewriter scriptorfnnode contextarg scopearg regexpcount getregexpcount regexpcount badtree addpush regexpcount bytecode addaload contextarg addinvoke bytecode scriptruntime checkregexpproxy regexpproxy bytecode addaload contextarg addinvoke bytecode mainclassname regexp_init_method_name regexp_init_method_signature regexpcount bytecode addaload contextarg addaload scopearg bytecode mainclassname getcompiledregexpname compiledregexp addinvoke bytecode regexpproxy wrapregexp wrappedregexp addpush bytecode bytecode bytecode void push number as object class file writer cfw double num if num 0 0 if 1 num 0 0 0 cfw add byte code getstatic org mozilla javascript optimizer opt runtime zero obj ljava lang double else cfw add push num add double wrap cfw else if num 1 0 cfw add byte code getstatic org mozilla javascript optimizer opt runtime one obj ljava lang double return else if num 1 0 cfw add byte code getstatic org mozilla javascript optimizer opt runtime minus one obj ljava lang double else if num num cfw add byte code getstatic org mozilla javascript script runtime na nobj ljava lang double else if its constant list size 2000 there appears to be a limit in the jvm on either the number of static fields in a class or the size of the class initializer either way we can t have any more than 2000 statically init d constants cfw add push num add double wrap cfw else int n its constant list size int index 0 if n 0 its constant list new double 64 else double array its constant list while index n array index num index if n array length array new double n 2 system arraycopy its constant list 0 array 0 n its constant list array if index n its constant list n num its constant list size n 1 string constant name k index string constant type get static constant wrapper type num cfw add byte code getstatic main class name constant name constant type pushnumberasobject classfilewriter bytecode optruntime zeroobj addpush adddoublewrap bytecode optruntime oneobj bytecode optruntime minusoneobj bytecode scriptruntime nanobj itsconstantlistsize addpush adddoublewrap itsconstantlistsize itsconstantlist itsconstantlist itsconstantlist itsconstantlist itsconstantlist itsconstantlistsize constantname _k constanttype getstaticconstantwrappertype bytecode mainclassname constantname constanttype private static void add double wrap class file writer cfw cfw add invoke byte code invokestatic org mozilla javascript optimizer opt runtime wrap double d ljava lang double adddoublewrap classfilewriter addinvoke bytecode optruntime wrapdouble private static string get static constant wrapper type double num string constant type int inum int num if inum num return ljava lang integer else return ljava lang double getstaticconstantwrappertype constanttype static void push undefined class file writer cfw cfw add byte code getstatic org mozilla javascript undefined instance ljava lang object pushundefined classfilewriter bytecode int get index script or fn node n return script or fn indexes get existing n getindex scriptorfnnode scriptorfnindexes getexisting static string get direct target field name int i return dt i getdirecttargetfieldname _dt string get direct ctor name script or fn node n return n get index n getdirectctorname scriptorfnnode _n getindex string get body method name script or fn node n return c get index n getbodymethodname scriptorfnnode _c getindex string get body method signature script or fn node n string buffer sb new string buffer sb append sb append main class signature sb append lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable if n get type token function opt function node ofn opt function node get n if ofn is target of direct call int p count ofn fnode get param count for int i 0 i p count i sb append ljava lang object d sb append ljava lang object ljava lang object return sb to string getbodymethodsignature scriptorfnnode stringbuffer stringbuffer mainclasssignature gettype optfunctionnode optfunctionnode istargetofdirectcall pcount getparamcount pcount tostring string get function init method name opt function node ofn return i get index ofn fnode getfunctioninitmethodname optfunctionnode _i getindex string get compiled regexp name script or fn node n int regexp index return re get index n regexp index getcompiledregexpname scriptorfnnode regexpindex _re getindex _ regexpindex static runtime exception bad tree throw new runtime exception bad tree in codegen runtimeexception badtree runtimeexception void set main method class string class name main method class class name setmainmethodclass classname mainmethodclass classname void generate body code init body generation cfw start method codegen get body method name script or fn codegen get body method signature script or fn short class file writer acc static class file writer acc private generate prologue node tree top if fn current null tree top script or fn get last child else tree top script or fn generate statement tree top null generate epilogue cfw stop method short locals max 1 generatebodycode initbodygeneration startmethod getbodymethodname scriptorfn getbodymethodsignature scriptorfn classfilewriter acc_static classfilewriter acc_private generateprologue treetop fncurrent treetop scriptorfn getlastchild treetop scriptorfn generatestatement treetop generateepilogue stopmethod localsmax private void init body generation is top level script or fn codegen script or fn nodes 0 var registers null if script or fn get type token function fn current opt function node get script or fn has vars in regs fn current fnode requires activation if has vars in regs int n fn current fnode get param and var count if n 0 var registers new short n in direct call function fn current is target of direct call if in direct call function has vars in regs codegen bad tree else fn current null has vars in regs false in direct call function false locals new boolean max locals fun obj local 0 context local 1 variable object local 2 this obj local 3 locals max short 4 number of parms this first free local 4 popv local 1 args local 1 its zero arg array 1 its one arg array 1 script regexp local 1 epilogue label 1 enter area start label 1 initbodygeneration istoplevel scriptorfn scriptorfnnodes varregisters scriptorfn gettype fncurrent optfunctionnode scriptorfn hasvarsinregs fncurrent requiresactivation hasvarsinregs fncurrent getparamandvarcount varregisters indirectcallfunction fncurrent istargetofdirectcall indirectcallfunction hasvarsinregs badtree fncurrent hasvarsinregs indirectcallfunction max_locals funobjlocal contextlocal variableobjectlocal thisobjlocal localsmax firstfreelocal popvlocal argslocal itszeroargarray itsoneargarray scriptregexplocal epiloguelabel enterareastartlabel generate the prologue for a function or script private void generate prologue if in direct call function int direct parameter count script or fn get param count 0 is reserved for function object this 1 is reserved for context 2 is reserved for parent scope 3 is reserved for script this if first free local 4 kit code bug for int i 0 i direct parameter count i var registers i first free local 3 is 1 for object parm and 2 for double parm first free local 3 if fn current get parameter number context make sure that all parameters are objects its forced object parameters true for int i 0 i direct parameter count i short reg var registers i cfw adda load reg cfw add byte code getstatic java lang void type ljava lang class int is object label cfw acquire label cfw add byte code if acmpne is object label cfw addd load reg 1 add double wrap cfw adda store reg cfw mark label is object label if fn current null in direct call function compiler env is use dynamic scope fn current fnode get ignore dynamic scope unless we re either in a direct call or using dynamic scope use the enclosing scope of the function as our variable object cfw adda load fun obj local cfw add invoke byte code invokeinterface org mozilla javascript scriptable get parent scope lorg mozilla javascript scriptable cfw adda store variable object local reserve args args local first free local locals max first free local if fn current null see comments in case token regexp if script or fn get regexp count 0 script regexp local get new word local codegen push reg exp array cfw script or fn context local variable object local cfw adda store script regexp local if has vars in regs no need to create activation pad arguments if need be int parm count script or fn get param count if parm count 0 in direct call function set up args array check length of arguments pad if need be cfw adda load args local cfw add byte code arraylength cfw add push parm count int label cfw acquire label cfw add byte code if icmpge label cfw adda load args local cfw add push parm count add script runtime invoke pad arguments ljava lang object i ljava lang object cfw adda store args local cfw mark label label int param count fn current fnode get param count int var count fn current fnode get param and var count remind only need to initialize the vars that don t get a value before the next call and are used in the function short first undef var 1 for int i 0 i var count i short reg 1 if i param count if in direct call function reg get new word local cfw adda load args local cfw add push i cfw add byte code aaload cfw adda store reg else if fn current is number var i reg get new word pair local cfw add push 0 0 cfw addd store reg else reg get new word local if first undef var 1 codegen push undefined cfw first undef var reg else cfw adda load first undef var cfw adda store reg if reg 0 var registers i reg add debug table enry if we re generating debug info if compiler env is generate debug info string name fn current fnode get param or var name i string type fn current is number var i d ljava lang object int startpc cfw get current code offset if reg 0 reg var registers i cfw add variable descriptor name type startpc reg skip creating activation object return string debug variable name if fn current null debug variable name activation cfw adda load fun obj local cfw adda load variable object local cfw adda load args local add script runtime invoke create function activation lorg mozilla javascript native function lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript scriptable cfw adda store variable object local cfw adda load context local cfw adda load variable object local add script runtime invoke enter activation function lorg mozilla javascript context lorg mozilla javascript scriptable v else debug variable name global cfw adda load fun obj local cfw adda load this obj local cfw adda load context local cfw adda load variable object local cfw add push 0 false to indicate it is not eval script add script runtime invoke init script lorg mozilla javascript native function lorg mozilla javascript scriptable lorg mozilla javascript context lorg mozilla javascript scriptable z v enter area start label cfw acquire label epilogue label cfw acquire label cfw mark label enter area start label int function count script or fn get function count for int i 0 i function count i opt function node ofn opt function node get script or fn i if ofn fnode get function type function node function statement visit function ofn function node function statement default is to generate debug info if compiler env is generate debug info cfw add variable descriptor debug variable name lorg mozilla javascript scriptable cfw get current code offset variable object local if fn current null opt use dataflow to prove that this assignment is dead popv local get new word local codegen push undefined cfw cfw adda store popv local int linenum script or fn get end lineno if linenum 1 cfw add line number entry short linenum else if fn current its contains calls0 its zero arg array get new word local cfw add byte code getstatic org mozilla javascript script runtime empty args ljava lang object cfw adda store its zero arg array if fn current its contains calls1 its one arg array get new word local cfw add push 1 cfw add byte code anewarray java lang object cfw adda store its one arg array generateprologue indirectcallfunction directparametercount scriptorfn getparamcount parentscope firstfreelocal codebug directparametercount varregisters firstfreelocal firstfreelocal fncurrent getparameternumbercontext itsforcedobjectparameters directparametercount varregisters addaload bytecode isobjectlabel acquirelabel bytecode if_acmpne isobjectlabel adddload adddoublewrap addastore marklabel isobjectlabel fncurrent indirectcallfunction compilerenv isusedynamicscope fncurrent getignoredynamicscope addaload funobjlocal addinvoke bytecode getparentscope addastore variableobjectlocal argslocal firstfreelocal localsmax firstfreelocal fncurrent scriptorfn getregexpcount scriptregexplocal getnewwordlocal pushregexparray scriptorfn contextlocal variableobjectlocal addastore scriptregexplocal hasvarsinregs parmcount scriptorfn getparamcount parmcount indirectcallfunction addaload argslocal bytecode addpush parmcount acquirelabel bytecode if_icmpge addaload argslocal addpush parmcount addscriptruntimeinvoke padarguments addastore argslocal marklabel paramcount fncurrent getparamcount varcount fncurrent getparamandvarcount firstundefvar varcount paramcount indirectcallfunction getnewwordlocal addaload argslocal addpush bytecode addastore fncurrent isnumbervar getnewwordpairlocal addpush adddstore getnewwordlocal firstundefvar pushundefined firstundefvar addaload firstundefvar addastore varregisters compilerenv isgeneratedebuginfo fncurrent getparamorvarname fncurrent isnumbervar getcurrentcodeoffset varregisters addvariabledescriptor debugvariablename fncurrent debugvariablename addaload funobjlocal addaload variableobjectlocal addaload argslocal addscriptruntimeinvoke createfunctionactivation nativefunction addastore variableobjectlocal addaload contextlocal addaload variableobjectlocal addscriptruntimeinvoke enteractivationfunction debugvariablename addaload funobjlocal addaload thisobjlocal addaload contextlocal addaload variableobjectlocal addpush addscriptruntimeinvoke initscript nativefunction enterareastartlabel acquirelabel epiloguelabel acquirelabel marklabel enterareastartlabel functioncount scriptorfn getfunctioncount functioncount optfunctionnode optfunctionnode scriptorfn getfunctiontype functionnode function_statement visitfunction functionnode function_statement compilerenv isgeneratedebuginfo addvariabledescriptor debugvariablename getcurrentcodeoffset variableobjectlocal fncurrent popvlocal getnewwordlocal pushundefined addastore popvlocal scriptorfn getendlineno addlinenumberentry fncurrent itscontainscalls0 itszeroargarray getnewwordlocal bytecode scriptruntime emptyargs addastore itszeroargarray fncurrent itscontainscalls1 itsoneargarray getnewwordlocal addpush bytecode addastore itsoneargarray private void generate epilogue if has vars in regs if epilogue label 1 cfw mark label epilogue label cfw add byte code areturn return cfw mark label epilogue label if fn current null cfw adda load popv local cfw add byte code areturn else generate activation exit cfw add byte code areturn generate catch block to catch all and rethrow to call exit code under exception propagation as well int finally handler cfw acquire label cfw mark handler finally handler short exception object get new word local cfw adda store exception object duplicate generate activation exit in the catch block since it takes less space then full fetured byte code jsr byte code ret generate activation exit cfw adda load exception object release word local exception object rethrow cfw add byte code athrow mark the handler cfw add exception handler enter area start label epilogue label finally handler null catch any generateepilogue hasvarsinregs epiloguelabel marklabel epiloguelabel bytecode marklabel epiloguelabel fncurrent addaload popvlocal bytecode generateactivationexit bytecode finallyhandler acquirelabel markhandler finallyhandler exceptionobject getnewwordlocal addastore exceptionobject generateactivationexit bytecode bytecode generateactivationexit addaload exceptionobject releasewordlocal exceptionobject bytecode addexceptionhandler enterareastartlabel epiloguelabel finallyhandler private void generate activation exit if fn current null has vars in regs throw kit code bug cfw adda load context local add script runtime invoke exit activation function lorg mozilla javascript context v generateactivationexit fncurrent hasvarsinregs codebug addaload contextlocal addscriptruntimeinvoke exitactivationfunction private void generate statement node node node parent system out println gen code for node to string update line number node int type node get type node child node get first child switch type case token loop case token label case token with case token script case token block case token empty no ops while child null generate statement child node child child get next break case token local block int local get new word local node put int prop node local prop local while child null generate statement child node child child get next release word local short local node remove prop node local prop break case token function int fn index node get existing int prop node function prop opt function node ofn opt function node get script or fn fn index int t ofn fnode get function type if t function node function expression statement visit function ofn t else if t function node function statement throw codegen bad tree break case token try visit try catch finally node jump node child break case token catch scope int local get local block register node int scope index node get existing int prop node catch scope prop string name child get string name of exception child child get next generate expression child node load expression object if scope index 0 cfw add byte code aconst null else load previous catch scope object cfw adda load local cfw add push name cfw adda load context local cfw adda load variable object local add script runtime invoke new catch scope ljava lang throwable lorg mozilla javascript scriptable ljava lang string lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable cfw adda store local break case token throw generate expression child node cfw add byte code new org mozilla javascript java script exception cfw add byte code dup x1 cfw add byte code swap cfw add push script or fn get source name cfw add push its line number cfw add invoke byte code invokespecial org mozilla javascript java script exception init ljava lang object ljava lang string i v cfw add byte code athrow break case token rethrow cfw adda load get local block register node cfw add byte code athrow break case token return result case token return if child null generate expression child node else if type token return codegen push undefined cfw else if popv local 0 throw codegen bad tree cfw adda load popv local if epilogue label 1 if has vars in regs throw codegen bad tree epilogue label cfw acquire label cfw add byte code goto epilogue label break case token switch visit switch node jump node child break case token enterwith generate expression child node cfw adda load context local cfw adda load variable object local add script runtime invoke enter with ljava lang object lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable cfw adda store variable object local break case token leavewith cfw adda load variable object local add script runtime invoke leave with lorg mozilla javascript scriptable lorg mozilla javascript scriptable cfw adda store variable object local break case token enum init keys case token enum init values generate expression child node cfw adda load context local cfw add push type token enum init values add script runtime invoke enum init ljava lang object lorg mozilla javascript context z ljava lang object cfw adda store get local block register node break case token expr void if child get type token setvar special case this so as to avoid unnecessary load s pop s visit set var child child get first child false else generate expression child node if node get int prop node isnumber prop 1 1 cfw add byte code pop2 else cfw add byte code pop break case token expr result generate expression child node if popv local 0 popv local get new word local cfw adda store popv local break case token target int label get target label node cfw mark label label break case token jsr case token goto case token ifeq case token ifne visitgoto node jump node type child break case token finally save return address in a new local where int finally register get new word local cfw adda store finally register while child null generate statement child node child child get next cfw add byte code ret finally register release word local short finally register break default throw codegen bad tree generatestatement tostring updatelinenumber gettype getfirstchild generatestatement getnext local_block getnewwordlocal putintprop local_prop generatestatement getnext releasewordlocal removeprop local_prop fnindex getexistingintprop function_prop optfunctionnode optfunctionnode scriptorfn fnindex getfunctiontype functionnode function_expression_statement visitfunction functionnode function_statement badtree visittrycatchfinally catch_scope getlocalblockregister scopeindex getexistingintprop catch_scope_prop getstring getnext generateexpression scopeindex bytecode aconst_null addaload addpush addaload contextlocal addaload variableobjectlocal addscriptruntimeinvoke newcatchscope addastore generateexpression bytecode javascriptexception bytecode dup_x1 bytecode addpush scriptorfn getsourcename addpush itslinenumber addinvoke bytecode javascriptexception bytecode addaload getlocalblockregister bytecode return_result generateexpression pushundefined popvlocal badtree addaload popvlocal epiloguelabel hasvarsinregs badtree epiloguelabel acquirelabel bytecode epiloguelabel visitswitch generateexpression addaload contextlocal addaload variableobjectlocal addscriptruntimeinvoke enterwith addastore variableobjectlocal addaload variableobjectlocal addscriptruntimeinvoke leavewith addastore variableobjectlocal enum_init_keys enum_init_values generateexpression addaload contextlocal addpush enum_init_values addscriptruntimeinvoke enuminit addastore getlocalblockregister expr_void gettype visitsetvar getfirstchild generateexpression getintprop isnumber_prop bytecode bytecode expr_result generateexpression popvlocal popvlocal getnewwordlocal addastore popvlocal gettargetlabel marklabel finallyregister getnewwordlocal addastore finallyregister generatestatement getnext bytecode finallyregister releasewordlocal finallyregister badtree private void generate expression node node node parent int type node get type node child node get first child switch type case token use stack break case token function if fn current null parent get type token script int fn index node get existing int prop node function prop opt function node ofn opt function node get script or fn fn index int t ofn fnode get function type if t function node function expression throw codegen bad tree visit function ofn t break case token name cfw adda load context local cfw adda load variable object local cfw add push node get string add script runtime invoke name lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang string ljava lang object break case token call case token new int special type node get int prop node specialcall prop node non specialcall if special type node non specialcall opt function node target target opt function node node get prop node directcall prop if target null visit optimized call node target type child else if type token call visit standard call node child else visit standard new node child else visit special call node type special type child break case token ref call generate function and this obj child node stack function obj this obj child child get next generate call arg array node child false cfw adda load context local add script runtime invoke call ref lorg mozilla javascript callable lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript context lorg mozilla javascript ref break case token number double num node get double if node get int prop node isnumber prop 1 1 cfw add push num else codegen push number as object cfw num break case token string cfw add push node get string break case token this cfw adda load this obj local break case token thisfn cfw add byte code aload 0 break case token null cfw add byte code aconst null break case token true cfw add byte code getstatic java lang boolean true ljava lang boolean break case token false cfw add byte code getstatic java lang boolean false ljava lang boolean break case token regexp int i node get existing int prop node regexp prop scripts can not use regexp array field name since it it will make script exec non reentrant so they store regexp array in a local variable while functions always access precomputed regexp array field name not to consume locals if fn current null cfw adda load script regexp local else cfw adda load fun obj local cfw add byte code getfield codegen main class name codegen regexp array field name codegen regexp array field type cfw add push i cfw add byte code aaload break case token comma node next child get next while next null generate expression child node cfw add byte code pop child next next next get next generate expression child node break case token enum next case token enum id int local get local block register node cfw adda load local if type token enum next add script runtime invoke enum next ljava lang object ljava lang boolean else cfw adda load context local add script runtime invoke enum id ljava lang object lorg mozilla javascript context ljava lang object break case token arraylit visit array literal node child break case token objectlit visit object literal node child break case token not int true target cfw acquire label int false target cfw acquire label int beyond cfw acquire label generate if jump child node true target false target cfw mark label true target cfw add byte code getstatic java lang boolean false ljava lang boolean cfw add byte code goto beyond cfw mark label false target cfw add byte code getstatic java lang boolean true ljava lang boolean cfw mark label beyond cfw adjust stack top 1 break case token bitnot generate expression child node add script runtime invoke to int32 ljava lang object i cfw add push 1 implement a as a 1 cfw add byte code ixor cfw add byte code i2d add double wrap break case token void generate expression child node cfw add byte code pop codegen push undefined cfw break case token typeof generate expression child node add script runtime invoke typeof ljava lang object ljava lang string break case token typeofname visit typeofname node break case token inc case token dec visit inc dec node false break case token or case token and generate expression child node cfw add byte code dup add script runtime invoke to boolean ljava lang object z int false target cfw acquire label if type token and cfw add byte code ifeq false target else cfw add byte code ifne false target cfw add byte code pop generate expression child get next node cfw mark label false target break case token hook node if then child get next node if else if then get next generate expression child node add script runtime invoke to boolean ljava lang object z int else target cfw acquire label cfw add byte code ifeq else target short stack cfw get stack top generate expression if then node int after hook cfw acquire label cfw add byte code goto after hook cfw mark label else target stack generate expression if else node cfw mark label after hook break case token add generate expression child node generateexpression gettype getfirstchild use_stack fncurrent gettype fnindex getexistingintprop function_prop optfunctionnode optfunctionnode scriptorfn fnindex getfunctiontype functionnode function_expression badtree visitfunction addaload contextlocal addaload variableobjectlocal addpush getstring addscriptruntimeinvoke specialtype getintprop specialcall_prop non_specialcall specialtype non_specialcall optfunctionnode optfunctionnode getprop directcall_prop visitoptimizedcall visitstandardcall visitstandardnew visitspecialcall specialtype ref_call generatefunctionandthisobj functionobj thisobj getnext generatecallargarray addaload contextlocal addscriptruntimeinvoke callref getdouble getintprop isnumber_prop addpush pushnumberasobject addpush getstring addaload thisobjlocal bytecode aload_0 bytecode aconst_null bytecode bytecode getexistingintprop regexp_prop regexp_array_field_name regexp_array_field_name fncurrent addaload scriptregexplocal addaload funobjlocal bytecode mainclassname regexp_array_field_name regexp_array_field_type addpush bytecode getnext generateexpression bytecode getnext generateexpression enum_next enum_id getlocalblockregister addaload enum_next addscriptruntimeinvoke enumnext addaload contextlocal addscriptruntimeinvoke enumid visitarrayliteral visitobjectliteral truetarget acquirelabel falsetarget acquirelabel acquirelabel generateifjump truetarget falsetarget marklabel truetarget bytecode bytecode marklabel falsetarget bytecode marklabel adjuststacktop generateexpression addscriptruntimeinvoke toint32 addpush bytecode bytecode adddoublewrap generateexpression bytecode pushundefined generateexpression addscriptruntimeinvoke visittypeofname visitincdec generateexpression bytecode addscriptruntimeinvoke toboolean falsetarget acquirelabel bytecode falsetarget bytecode falsetarget bytecode generateexpression getnext marklabel falsetarget ifthen getnext ifelse ifthen getnext generateexpression addscriptruntimeinvoke toboolean elsetarget acquirelabel bytecode elsetarget getstacktop generateexpression ifthen afterhook acquirelabel bytecode afterhook marklabel elsetarget generateexpression ifelse marklabel afterhook generateexpression private void generate if jump node node node parent int true label int false label system out println gen code for node to string int type node get type node child node get first child switch type case token not generate if jump child node false label true label break case token or case token and int inter label cfw acquire label if type token and generate if jump child node inter label false label else generate if jump child node true label inter label cfw mark label inter label child child get next generate if jump child node true label false label break case token in case token instanceof case token le case token lt case token ge case token gt visit if jump rel op node child true label false label break case token eq case token ne case token sheq case token shne visit if jump eq op node child true label false label break default generate generic code for non optimized jump generate expression node parent add script runtime invoke to boolean ljava lang object z cfw add byte code ifne true label cfw add byte code goto false label generateifjump truelabel falselabel tostring gettype getfirstchild generateifjump falselabel truelabel interlabel acquirelabel generateifjump interlabel falselabel generateifjump truelabel interlabel marklabel interlabel getnext generateifjump truelabel falselabel visitifjumprelop truelabel falselabel visitifjumpeqop truelabel falselabel generateexpression addscriptruntimeinvoke toboolean bytecode truelabel bytecode falselabel private void visit function opt function node ofn int function type int fn index codegen get index ofn fnode cfw add byte code new codegen main class name call function constructor cfw add byte code dup cfw adda load variable object local cfw adda load context local load cx cfw add push fn index cfw add invoke byte code invokespecial codegen main class name init codegen function constructor signature init main script field cfw add byte code dup if is top level cfw add byte code aload 0 else cfw add byte code aload 0 cfw add byte code getfield codegen main class name codegen direct call parent field codegen main class signature cfw add byte code putfield codegen main class name codegen direct call parent field codegen main class signature int direct target index ofn get direct target index if direct target index 0 cfw add byte code dup if is top level cfw add byte code aload 0 else cfw add byte code aload 0 cfw add byte code getfield codegen main class name codegen direct call parent field codegen main class signature cfw add byte code swap cfw add byte code putfield codegen main class name codegen get direct target field name direct target index codegen main class signature if function type function node function expression leave closure object on stack and do not pass it to init function which suppose to connect statements to scope return cfw add push function type cfw adda load variable object local cfw adda load context local load cx add opt runtime invoke init function lorg mozilla javascript native function i lorg mozilla javascript scriptable lorg mozilla javascript context v visitfunction optfunctionnode functiontype fnindex getindex bytecode mainclassname bytecode addaload variableobjectlocal addaload contextlocal addpush fnindex addinvoke bytecode mainclassname function_constructor_signature mainscript bytecode istoplevel bytecode aload_0 bytecode aload_0 bytecode mainclassname direct_call_parent_field mainclasssignature bytecode mainclassname direct_call_parent_field mainclasssignature directtargetindex getdirecttargetindex directtargetindex bytecode istoplevel bytecode aload_0 bytecode aload_0 bytecode mainclassname direct_call_parent_field mainclasssignature bytecode bytecode mainclassname getdirecttargetfieldname directtargetindex mainclasssignature functiontype functionnode function_expression initfunction addpush functiontype addaload variableobjectlocal addaload contextlocal addoptruntimeinvoke initfunction nativefunction private int get target label node target int label id target label id if label id 1 label id cfw acquire label target label id label id return label id gettargetlabel labelid labelid labelid labelid acquirelabel labelid labelid labelid private void visitgoto node jump node int type node child node target node target if type token ifeq type token ifne if child null throw codegen bad tree int target label get target label target int fall thru label cfw acquire label if type token ifeq generate if jump child node target label fall thru label else generate if jump child node fall thru label target label cfw mark label fall thru label else if type token jsr add goto target byte code jsr else add goto target byte code goto badtree targetlabel gettargetlabel fallthrulabel acquirelabel generateifjump targetlabel fallthrulabel generateifjump fallthrulabel targetlabel marklabel fallthrulabel addgoto bytecode addgoto bytecode private void visit array literal node node node child int count 0 for node cursor child cursor null cursor cursor get next count load array to store array literal objects add new object array count for int i 0 i count i cfw add byte code dup cfw add push i generate expression child node cfw add byte code aastore child child get next int skip indexes int node get prop node skip indexes prop if skip indexes null cfw add byte code aconst null cfw add byte code iconst 0 else cfw add push opt runtime encode int array skip indexes cfw add push skip indexes length cfw adda load context local cfw adda load variable object local add opt runtime invoke new array literal ljava lang object ljava lang string i lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable visitarrayliteral getnext addnewobjectarray bytecode addpush generateexpression bytecode getnext skipindexes getprop skip_indexes_prop skipindexes bytecode aconst_null bytecode iconst_0 addpush optruntime encodeintarray skipindexes addpush skipindexes addaload contextlocal addaload variableobjectlocal addoptruntimeinvoke newarrayliteral private void visit object literal node node node child object properties object node get prop node object ids prop int count properties length load array with property ids add new object array count for int i 0 i count i cfw add byte code dup cfw add push i object id properties i if id instanceof string cfw add push string id else cfw add push integer id int value add script runtime invoke wrap int i ljava lang integer cfw add byte code aastore load array with property values add new object array count for int i 0 i count i cfw add byte code dup cfw add push i generate expression child node cfw add byte code aastore child child get next cfw adda load context local cfw adda load variable object local add script runtime invoke new object literal ljava lang object ljava lang object lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable visitobjectliteral getprop object_ids_prop addnewobjectarray bytecode addpush addpush addpush intvalue addscriptruntimeinvoke wrapint bytecode addnewobjectarray bytecode addpush generateexpression bytecode getnext addaload contextlocal addaload variableobjectlocal addscriptruntimeinvoke newobjectliteral private void visit special call node node int type int special type node child cfw adda load context local if type token new generate expression child node stack cx function obj else generate function and this obj child node stack cx function obj this obj child child get next generate call arg array node child false string method name string call signature if type token new method name new object special call signature lorg mozilla javascript context ljava lang object ljava lang object lorg mozilla javascript scriptable lorg mozilla javascript scriptable i call type ljava lang object cfw adda load variable object local cfw adda load this obj local cfw add push special type else method name call special call signature lorg mozilla javascript context lorg mozilla javascript callable lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript scriptable lorg mozilla javascript scriptable i call type ljava lang string i filename linenumber ljava lang object cfw adda load variable object local cfw adda load this obj local cfw add push special type string source name script or fn get source name cfw add push source name null source name cfw add push its line number add opt runtime invoke method name call signature visitspecialcall specialtype addaload contextlocal generateexpression functionobj generatefunctionandthisobj functionobj thisobj getnext generatecallargarray methodname callsignature methodname newobjectspecial callsignature addaload variableobjectlocal addaload thisobjlocal addpush specialtype methodname callspecial callsignature addaload variableobjectlocal addaload thisobjlocal addpush specialtype sourcename scriptorfn getsourcename addpush sourcename sourcename addpush itslinenumber addoptruntimeinvoke methodname callsignature private void visit standard call node node node child if node get type token call throw codegen bad tree node first arg child child get next int child type child get type string method name string signature if first arg child null if child type token name name call string name child get string cfw add push name method name call name0 signature ljava lang string lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object else if child type token getprop x name call node prop target child get first child generate expression prop target node node id prop target get next string property id get string cfw add push property method name call prop0 signature ljava lang object ljava lang string lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object else generate function and this obj child node method name call0 signature lorg mozilla javascript callable lorg mozilla javascript scriptable lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object else if child type token name xxx this optimization is only possible if name resolution is not affected by arguments evaluation and currently there are no checks for it string name child get string generate call arg array node first arg child false cfw add push name method name call name signature ljava lang object ljava lang string lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object else int arg count 0 for node arg first arg child arg null arg arg get next arg count generate function and this obj child node stack function obj this obj if arg count 1 generate expression first arg child node method name call1 signature lorg mozilla javascript callable lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object else if arg count 2 generate expression first arg child node generate expression first arg child get next node method name call2 signature lorg mozilla javascript callable lorg mozilla javascript scriptable ljava lang object ljava lang object lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object else generate call arg array node first arg child false method name calln signature lorg mozilla javascript callable lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object cfw adda load context local cfw adda load variable object local add opt runtime invoke method name signature visitstandardcall gettype badtree firstargchild getnext childtype gettype methodname firstargchild childtype getstring addpush methodname callname0 childtype proptarget getfirstchild generateexpression proptarget proptarget getnext getstring addpush methodname callprop0 generatefunctionandthisobj methodname childtype getstring generatecallargarray firstargchild addpush methodname callname argcount firstargchild getnext argcount generatefunctionandthisobj functionobj thisobj argcount generateexpression firstargchild methodname argcount generateexpression firstargchild generateexpression firstargchild getnext methodname generatecallargarray firstargchild methodname addaload contextlocal addaload variableobjectlocal addoptruntimeinvoke methodname private void visit standard new node node node child if node get type token new throw codegen bad tree node first arg child child get next generate expression child node stack function obj cfw adda load context local cfw adda load variable object local stack function obj cx scope generate call arg array node first arg child false add script runtime invoke new object ljava lang object lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript scriptable visitstandardnew gettype badtree firstargchild getnext generateexpression functionobj addaload contextlocal addaload variableobjectlocal functionobj generatecallargarray firstargchild addscriptruntimeinvoke newobject private void visit optimized call node node opt function node target int type node child node first arg child child get next short this obj local 0 if type token new generate expression child node else generate function and this obj child node this obj local get new word local cfw adda store this obj local stack function obj int beyond cfw acquire label int direct target index target get direct target index if is top level cfw add byte code aload 0 else cfw add byte code aload 0 cfw add byte code getfield codegen main class name codegen direct call parent field codegen main class signature cfw add byte code getfield codegen main class name codegen get direct target field name direct target index codegen main class signature cfw add byte code dup2 stack function obj direct funct function obj direct funct int regular call cfw acquire label cfw add byte code if acmpne regular call stack function obj direct funct short stack height cfw get stack top cfw add byte code swap cfw add byte code pop stack direct funct if compiler env is use dynamic scope cfw adda load context local cfw adda load variable object local else cfw add byte code dup stack direct funct direct funct cfw add invoke byte code invokeinterface org mozilla javascript scriptable get parent scope lorg mozilla javascript scriptable stack direct funct scope cfw adda load context local stack direct funct scope cx cfw add byte code swap stack direct func cx scope if type token new cfw add byte code aconst null else cfw adda load this obj local stack direct func cx scope this obj remember that direct call parameters are paired in 1 a reg and 1 d reg if the argument is an incoming arg just pass the orginal pair thru else if the argument is known to be typed number pass void type in the a reg and the number is the d reg else pass the js object in the a reg and 0 0 in the d reg node arg child first arg child while arg child null int dcp register node is direct call parameter arg child if dcp register 0 cfw adda load dcp register cfw addd load dcp register 1 else if arg child get int prop node isnumber prop 1 node both cfw add byte code getstatic java lang void type ljava lang class generate expression arg child node else generate expression arg child node cfw add push 0 0 arg child arg child get next cfw add byte code getstatic org mozilla javascript script runtime empty args ljava lang object cfw add invoke byte code invokestatic codegen main class name type token new codegen get direct ctor name target fnode codegen get body method name target fnode codegen get body method signature target fnode cfw add byte code goto beyond cfw mark label regular call stack height stack function obj direct funct cfw add byte code pop cfw adda load context local cfw adda load variable object local stack function obj cx scope if type token new cfw adda load this obj local release word local this obj local stack function obj cx scope this obj xxx this will generate code for the child array the second time so expression code generation better not to alter tree structure generate call arg array node first arg child true if type token new add script runtime invoke new object ljava lang object lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript scriptable else cfw add invoke byte code invokeinterface org mozilla javascript callable call lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript scriptable ljava lang object ljava lang object cfw mark label beyond visitoptimizedcall optfunctionnode firstargchild getnext thisobjlocal generateexpression generatefunctionandthisobj thisobjlocal getnewwordlocal addastore thisobjlocal functionobj acquirelabel directtargetindex getdirecttargetindex istoplevel bytecode aload_0 bytecode aload_0 bytecode mainclassname direct_call_parent_field mainclasssignature bytecode mainclassname getdirecttargetfieldname directtargetindex mainclasssignature bytecode functionobj directfunct functionobj directfunct regularcall acquirelabel bytecode if_acmpne regularcall functionobj directfunct stackheight getstacktop bytecode bytecode directfunct compilerenv isusedynamicscope addaload contextlocal addaload variableobjectlocal bytecode directfunct directfunct addinvoke bytecode getparentscope directfunct addaload contextlocal directfunct bytecode directfunc bytecode aconst_null addaload thisobjlocal directfunc thisobj directcall areg dreg areg dreg areg dreg argchild firstargchild argchild dcp_register nodeisdirectcallparameter argchild dcp_register addaload dcp_register adddload dcp_register argchild getintprop isnumber_prop bytecode generateexpression argchild generateexpression argchild addpush argchild argchild getnext bytecode scriptruntime emptyargs addinvoke bytecode mainclassname getdirectctorname getbodymethodname getbodymethodsignature bytecode marklabel regularcall stackheight functionobj directfunct bytecode addaload contextlocal addaload variableobjectlocal functionobj addaload thisobjlocal releasewordlocal thisobjlocal functionobj thisobj generatecallargarray firstargchild addscriptruntimeinvoke newobject addinvoke bytecode marklabel private void generate call arg array node node node arg child boolean direct call int arg count 0 for node child arg child child null child child get next arg count load array object to set arguments if arg count 1 its one arg array 0 cfw adda load its one arg array else add new object array arg count copy arguments into it for int i 0 i arg count i cfw add byte code dup cfw add push i if direct call generate expression arg child node else if this has also been a direct call sequence the number flag will have remained set for any parameter so that the values could be copied directly into the outgoing args here we want to force it to be treated as not in a number context so we set the flag off int dcp register node is direct call parameter arg child if dcp register 0 dcp load as object dcp register else generate expression arg child node int child number flag arg child get int prop node isnumber prop 1 if child number flag node both add double wrap cfw add byte code aastore arg child arg child get next generatecallargarray argchild directcall argcount argchild getnext argcount argcount itsoneargarray addaload itsoneargarray addnewobjectarray argcount argcount bytecode addpush directcall generateexpression argchild directcall dcp_register nodeisdirectcallparameter argchild dcp_register dcploadasobject dcp_register generateexpression argchild childnumberflag argchild getintprop isnumber_prop childnumberflag adddoublewrap bytecode argchild argchild getnext private void generate function and this obj node node node parent place on stack function object function this pair int type node get type switch node get type case token getprop case token getelem node target node get first child generate expression target node node id target get next if type token getprop string property id get string cfw add push property cfw adda load context local add script runtime invoke get prop function and this ljava lang object ljava lang string lorg mozilla javascript context lorg mozilla javascript callable else optimizer do not optimize this case for now if node get int prop node isnumber prop 1 1 throw codegen bad tree generate expression id node id cfw adda load context local add script runtime invoke get elem function and this ljava lang object ljava lang object lorg mozilla javascript context lorg mozilla javascript callable break case token name string name node get string cfw add push name cfw adda load context local cfw adda load variable object local add script runtime invoke get name function and this ljava lang string lorg mozilla javascript context lorg mozilla javascript scriptable lorg mozilla javascript callable break default including getvar generate expression node parent cfw adda load context local add script runtime invoke get value function and this ljava lang object lorg mozilla javascript context lorg mozilla javascript callable break get this obj prepared by get name prop elem value function and this cfw adda load context local add script runtime invoke last stored scriptable lorg mozilla javascript context lorg mozilla javascript scriptable generatefunctionandthisobj gettype gettype getfirstchild generateexpression getnext getstring addpush addaload contextlocal addscriptruntimeinvoke getpropfunctionandthis getintprop isnumber_prop badtree generateexpression addaload contextlocal addscriptruntimeinvoke getelemfunctionandthis getstring addpush addaload contextlocal addaload variableobjectlocal addscriptruntimeinvoke getnamefunctionandthis generateexpression addaload contextlocal addscriptruntimeinvoke getvaluefunctionandthis thisobj functionandthis addaload contextlocal addscriptruntimeinvoke laststoredscriptable private void update line number node node its line number node get lineno if its line number 1 return cfw add line number entry short its line number updatelinenumber itslinenumber getlineno itslinenumber addlinenumberentry itslinenumber private void visit try catch finally node jump node node child save the variable object in case there are with statements enclosed by the try block and we catch some exception we ll restore it for the catch block so that catch block statements get the right scope opt we only need to do this if there are enclosed with statements could statically check and omit this if there aren t any xxx opt maybe instead do syntactic transforms to associate each with with a try finally block that does the exitwith short saved variable object get new word local cfw adda load variable object local cfw adda store saved variable object generate the code for the tree most of the work is done in ir factory and node transformer codegen just adds the java handlers for the javascript catch and finally clauses need to set the stack top to 1 to account for the incoming exception int start label cfw acquire label cfw mark label start label short 1 while child null generate statement child node child child get next node catch target node target node finally target node get finally control flow skips the handlers int real end cfw acquire label cfw add byte code goto real end int exception local get local block register node javascript handler unwrap exception and goto to javascript catch area if catch target null get the label to goto int catch label catch target label id generate catch block javascript exception saved variable object catch label start label exception local catch wrapped exceptions see if they are wrapped java script exceptions otherwise rethrow generate catch block evaluator exception saved variable object catch label start label exception local we also need to catch ecma errors and feed the associated error object to the handler generate catch block ecmaerror exception saved variable object catch label start label exception local finally handler catch all exceptions store to a local jsr to the finally then re throw if finally target null int finally handler cfw acquire label cfw mark handler finally handler cfw adda store exception local reset the variable object local cfw adda load saved variable object cfw adda store variable object local get the label to jsr to int finally label finally target label id cfw add byte code jsr finally label rethrow cfw adda load exception local cfw add byte code athrow mark the handler cfw add exception handler start label finally label finally handler null catch any release word local saved variable object cfw mark label real end visittrycatchfinally savedvariableobject getnewwordlocal addaload variableobjectlocal addastore savedvariableobject irfactory nodetransformer startlabel acquirelabel marklabel startlabel generatestatement getnext catchtarget finallytarget getfinally realend acquirelabel bytecode realend exceptionlocal getlocalblockregister catchtarget catchlabel catchtarget labelid generatecatchblock javascript_exception savedvariableobject catchlabel startlabel exceptionlocal wrappedexceptions javascriptexceptions generatecatchblock evaluator_exception savedvariableobject catchlabel startlabel exceptionlocal ecmaerrors generatecatchblock ecmaerror_exception savedvariableobject catchlabel startlabel exceptionlocal finallytarget finallyhandler acquirelabel markhandler finallyhandler addastore exceptionlocal addaload savedvariableobject addastore variableobjectlocal finallylabel finallytarget labelid bytecode finallylabel addaload exceptionlocal bytecode addexceptionhandler startlabel finallylabel finallyhandler releasewordlocal savedvariableobject marklabel realend private void generate catch block int exception type short saved variable object int catch label int start label int exception local int handler cfw acquire label cfw mark handler handler ms jvm gets cranky if the exception object is left on the stack cfw adda store exception local reset the variable object local cfw adda load saved variable object cfw adda store variable object local string exception name if exception type javascript exception exception name org mozilla javascript java script exception else if exception type evaluator exception exception name org mozilla javascript evaluator exception else if exception type ecmaerror exception kit code bug exception name org mozilla javascript ecma error mark the handler cfw add exception handler start label catch label handler exception name cfw add byte code goto catch label generatecatchblock exceptiontype savedvariableobject catchlabel startlabel exceptionlocal acquirelabel markhandler addastore exceptionlocal addaload savedvariableobject addastore variableobjectlocal exceptionname exceptiontype javascript_exception exceptionname javascriptexception exceptiontype evaluator_exception exceptionname evaluatorexception exceptiontype ecmaerror_exception codebug exceptionname ecmaerror addexceptionhandler startlabel catchlabel exceptionname bytecode catchlabel private void visit switch node jump switch node node child see comments in ir factory create switch for description of switch node generate expression child switch node save selector value short selector get new word local cfw adda store selector for node jump case node node jump child get next case node null case node node jump case node get next if case node get type token case throw codegen bad tree node test case node get first child generate expression test case node cfw adda load selector add script runtime invoke shallow eq ljava lang object ljava lang object z add goto case node target byte code ifne release word local selector visitswitch switchnode irfactory createswitch generateexpression switchnode getnewwordlocal addastore casenode getnext casenode casenode casenode getnext casenode gettype badtree casenode getfirstchild generateexpression casenode addaload addscriptruntimeinvoke shalloweq addgoto casenode bytecode releasewordlocal private void visit typeofname node node string name node get string if has vars in regs int var index fn current fnode get param or var index name if var index 0 if fn current is number var var index cfw add push number else if var is direct call parameter var index int dcp register var registers var index cfw adda load dcp register cfw add byte code getstatic java lang void type ljava lang class int is number label cfw acquire label cfw add byte code if acmpeq is number label short stack cfw get stack top cfw adda load dcp register add script runtime invoke typeof ljava lang object ljava lang string int beyond cfw acquire label cfw add byte code goto beyond cfw mark label is number label stack cfw add push number cfw mark label beyond else cfw adda load var registers var index add script runtime invoke typeof ljava lang object ljava lang string return cfw adda load variable object local cfw add push name add script runtime invoke typeof name lorg mozilla javascript scriptable ljava lang string ljava lang string visittypeofname getstring hasvarsinregs varindex fncurrent getparamorvarindex varindex fncurrent isnumbervar varindex addpush varisdirectcallparameter varindex dcp_register varregisters varindex addaload dcp_register bytecode isnumberlabel acquirelabel bytecode if_acmpeq isnumberlabel getstacktop addaload dcp_register addscriptruntimeinvoke acquirelabel bytecode marklabel isnumberlabel addpush marklabel addaload varregisters varindex addscriptruntimeinvoke addaload variableobjectlocal addpush addscriptruntimeinvoke typeofname private void visit inc dec node node boolean is inc int incr decr mask node get existing int prop node incrdecr prop node child node get first child switch child get type case token getvar if has vars in regs kit code bug if node get int prop node isnumber prop 1 1 boolean post incr decr mask node post flag 0 int var index fn current get var index child short reg var registers var index cfw addd load reg if post cfw add byte code dup2 cfw add push 1 0 if incr decr mask node decr flag 0 cfw add byte code dadd else cfw add byte code dsub if post cfw add byte code dup2 cfw addd store reg else boolean post incr decr mask node post flag 0 int var index fn current get var index child short reg var registers var index cfw adda load reg if post cfw add byte code dup add object to double cfw add push 1 0 if incr decr mask node decr flag 0 cfw add byte code dadd else cfw add byte code dsub add double wrap if post cfw add byte code dup cfw adda store reg break break case token name cfw adda load variable object local cfw add push child get string push name cfw add push incr decr mask add script runtime invoke name incr decr lorg mozilla javascript scriptable ljava lang string i ljava lang object break case token getprop node get prop child child get first child generate expression get prop child node generate expression get prop child get next node cfw adda load context local cfw add push incr decr mask add script runtime invoke prop incr decr ljava lang object ljava lang string lorg mozilla javascript context i ljava lang object break case token getelem node elem child child get first child generate expression elem child node generate expression elem child get next node cfw adda load context local cfw add push incr decr mask add script runtime invoke elem incr decr ljava lang object ljava lang object lorg mozilla javascript context i ljava lang object break case token get ref node ref child child get first child generate expression ref child node cfw adda load context local cfw add push incr decr mask add script runtime invoke ref incr decr lorg mozilla javascript ref lorg mozilla javascript context i ljava lang object break default codegen bad tree visitincdec isinc incrdecrmask getexistingintprop incrdecr_prop getfirstchild gettype hasvarsinregs codebug getintprop isnumber_prop incrdecrmask post_flag varindex fncurrent getvarindex varregisters varindex adddload bytecode addpush incrdecrmask decr_flag bytecode bytecode bytecode adddstore incrdecrmask post_flag varindex fncurrent getvarindex varregisters varindex addaload bytecode addobjecttodouble addpush incrdecrmask decr_flag bytecode bytecode adddoublewrap bytecode addastore addaload variableobjectlocal addpush getstring addpush incrdecrmask addscriptruntimeinvoke nameincrdecr getpropchild getfirstchild generateexpression getpropchild generateexpression getpropchild getnext addaload contextlocal addpush incrdecrmask addscriptruntimeinvoke propincrdecr elemchild getfirstchild generateexpression elemchild generateexpression elemchild getnext addaload contextlocal addpush incrdecrmask addscriptruntimeinvoke elemincrdecr get_ref refchild getfirstchild generateexpression refchild addaload contextlocal addpush incrdecrmask addscriptruntimeinvoke refincrdecr badtree private static boolean is arithmetic node node node int type node get type return type token sub type token mod type token div type token mul isarithmeticnode gettype private void visit arithmetic node node int op code node child node parent int child number flag node get int prop node isnumber prop 1 if child number flag 1 generate expression child node generate expression child get next node cfw add op code else boolean child of arithmetic is arithmetic node parent generate expression child node if is arithmetic node child add object to double generate expression child get next node if is arithmetic node child get next add object to double cfw add op code if child of arithmetic add double wrap visitarithmetic opcode childnumberflag getintprop isnumber_prop childnumberflag generateexpression generateexpression getnext opcode childofarithmetic isarithmeticnode generateexpression isarithmeticnode addobjecttodouble generateexpression getnext isarithmeticnode getnext addobjecttodouble opcode childofarithmetic adddoublewrap private void visit bit op node node int type node child int child number flag node get int prop node isnumber prop 1 generate expression child node special case ursh work with the target arg as a long so that we can return a 32 bit unsigned value and call to uint32 instead of to int32 if type token ursh add script runtime invoke to uint32 ljava lang object j generate expression child get next node add script runtime invoke to int32 ljava lang object i looks like we need to explicitly mask the shift to 5 bits lushr takes 6 bits cfw add push 31 cfw add byte code iand cfw add byte code lushr cfw add byte code l2d add double wrap return if child number flag 1 add script runtime invoke to int32 ljava lang object i generate expression child get next node add script runtime invoke to int32 ljava lang object i else add script runtime invoke to int32 d i generate expression child get next node add script runtime invoke to int32 d i switch type case token bitor cfw add byte code ior break case token bitxor cfw add byte code ixor break case token bitand cfw add byte code iand break case token rsh cfw add byte code ishr break case token lsh cfw add byte code ishl break default throw codegen bad tree cfw add byte code i2d if child number flag 1 add double wrap visitbitop childnumberflag getintprop isnumber_prop generateexpression touint32 toint32 addscriptruntimeinvoke touint32 generateexpression getnext addscriptruntimeinvoke toint32 addpush bytecode bytecode bytecode adddoublewrap childnumberflag addscriptruntimeinvoke toint32 generateexpression getnext addscriptruntimeinvoke toint32 addscriptruntimeinvoke toint32 generateexpression getnext addscriptruntimeinvoke toint32 bytecode bytecode bytecode bytecode bytecode badtree bytecode childnumberflag adddoublewrap private int node is direct call parameter node node if node get type token getvar in direct call function its forced object parameters int var index fn current get var index node if fn current is parameter var index return var registers var index return 1 nodeisdirectcallparameter gettype indirectcallfunction itsforcedobjectparameters varindex fncurrent getvarindex fncurrent isparameter varindex varregisters varindex private boolean var is direct call parameter int var index return fn current is parameter var index in direct call function its forced object parameters varisdirectcallparameter varindex fncurrent isparameter varindex indirectcallfunction itsforcedobjectparameters private void gen simple compare int type int truegoto int falsegoto if truegoto 1 throw codegen bad tree switch type case token le cfw add byte code dcmpg cfw add byte code ifle truegoto break case token ge cfw add byte code dcmpl cfw add byte code ifge truegoto break case token lt cfw add byte code dcmpg cfw add byte code iflt truegoto break case token gt cfw add byte code dcmpl cfw add byte code ifgt truegoto break default throw codegen bad tree if falsegoto 1 cfw add byte code goto falsegoto gensimplecompare badtree bytecode bytecode bytecode bytecode bytecode bytecode bytecode bytecode badtree bytecode private void visit if jump rel op node node node child int truegoto int falsegoto if truegoto 1 falsegoto 1 throw codegen bad tree int type node get type node r child child get next if type token instanceof type token in generate expression child node generate expression r child node cfw adda load context local add script runtime invoke type token instanceof instance of in ljava lang object ljava lang object lorg mozilla javascript context z cfw add byte code ifne truegoto cfw add byte code goto falsegoto return int child number flag node get int prop node isnumber prop 1 int left dcp register node is direct call parameter child int right dcp register node is direct call parameter r child if child number flag 1 force numeric context on both parameters and optimize direct call case as optimizer currently does not handle it if child number flag node right left already has number content generate expression child node else if left dcp register 1 dcp load as number left dcp register else generate expression child node add object to double if child number flag node left right already has number content generate expression r child node else if right dcp register 1 dcp load as number right dcp register else generate expression r child node add object to double gen simple compare type truegoto falsegoto else if left dcp register 1 right dcp register 1 generate code to dynamically check for number content if both operands are dcp short stack cfw get stack top int left is not number cfw acquire label cfw adda load left dcp register cfw add byte code getstatic java lang void type ljava lang class cfw add byte code if acmpne left is not number cfw addd load left dcp register 1 dcp load as number right dcp register gen simple compare type truegoto falsegoto if stack cfw get stack top throw codegen bad tree cfw mark label left is not number int right is not number cfw acquire label cfw adda load right dcp register cfw add byte code getstatic java lang void type ljava lang class cfw add byte code if acmpne right is not number cfw adda load left dcp register add object to double cfw addd load right dcp register 1 gen simple compare type truegoto falsegoto if stack cfw get stack top throw codegen bad tree cfw mark label right is not number load both register as objects to call generic cmp cfw adda load left dcp register cfw adda load right dcp register else generate expression child node generate expression r child node if type token ge type token gt cfw add byte code swap string routine type token lt type token gt cmp lt cmp le add script runtime invoke routine ljava lang object ljava lang object z cfw add byte code ifne truegoto cfw add byte code goto falsegoto visitifjumprelop badtree gettype rchild getnext generateexpression generateexpression rchild addaload contextlocal addscriptruntimeinvoke instanceof bytecode bytecode childnumberflag getintprop isnumber_prop left_dcp_register nodeisdirectcallparameter right_dcp_register nodeisdirectcallparameter rchild childnumberflag childnumberflag generateexpression left_dcp_register dcploadasnumber left_dcp_register generateexpression addobjecttodouble childnumberflag generateexpression rchild right_dcp_register dcploadasnumber right_dcp_register generateexpression rchild addobjecttodouble gensimplecompare left_dcp_register right_dcp_register getstacktop leftisnotnumber acquirelabel addaload left_dcp_register bytecode bytecode if_acmpne leftisnotnumber adddload left_dcp_register dcploadasnumber right_dcp_register gensimplecompare getstacktop badtree marklabel leftisnotnumber rightisnotnumber acquirelabel addaload right_dcp_register bytecode bytecode if_acmpne rightisnotnumber addaload left_dcp_register addobjecttodouble adddload right_dcp_register gensimplecompare getstacktop badtree marklabel rightisnotnumber cmp_ addaload left_dcp_register addaload right_dcp_register generateexpression generateexpression rchild bytecode cmp_lt cmp_le addscriptruntimeinvoke bytecode bytecode private void visit if jump eq op node node node child int truegoto int falsegoto if truegoto 1 falsegoto 1 throw codegen bad tree short stack initial cfw get stack top int type node get type node r child child get next optimize if one of operands is null if child get type token null r child get type token null eq is symmetric in this case if child get type token null child r child generate expression child node if type token sheq type token shne int test code type token sheq byte code ifnull byte code ifnonnull cfw add test code truegoto else if type token eq swap false true targets for if type token ne throw codegen bad tree int tmp truegoto truegoto falsegoto falsegoto tmp cfw add byte code dup int undef check label cfw acquire label cfw add byte code ifnonnull undef check label short stack cfw get stack top cfw add byte code pop cfw add byte code goto truegoto cfw mark label undef check label stack codegen push undefined cfw cfw add byte code if acmpeq truegoto cfw add byte code goto falsegoto else int child dcp register node is direct call parameter child if child dcp register 1 r child get type token to object node convert child r child get first child if convert child get type token number cfw adda load child dcp register cfw add byte code getstatic java lang void type ljava lang class int not numbers label cfw acquire label cfw add byte code if acmpne not numbers label cfw addd load child dcp register 1 cfw add push convert child get double cfw add byte code dcmpl if type token eq cfw add byte code ifeq truegoto else cfw add byte code ifne truegoto cfw add byte code goto falsegoto cfw mark label not numbers label fall thru into generic handling generate expression child node generate expression r child node string name int test code switch type case token eq name eq test code byte code ifne break case token ne name eq test code byte code ifeq break case token sheq name shallow eq test code byte code ifne break case token shne name shallow eq test code byte code ifeq break default throw codegen bad tree add script runtime invoke name ljava lang object ljava lang object z cfw add test code truegoto cfw add byte code goto falsegoto if stack initial cfw get stack top throw codegen bad tree visitifjumpeqop badtree stackinitial getstacktop gettype rchild getnext gettype rchild gettype gettype rchild generateexpression testcode bytecode bytecode testcode badtree bytecode undefchecklabel acquirelabel bytecode undefchecklabel getstacktop bytecode bytecode marklabel undefchecklabel pushundefined bytecode if_acmpeq bytecode child_dcp_register nodeisdirectcallparameter child_dcp_register rchild gettype to_object convertchild rchild getfirstchild convertchild gettype addaload child_dcp_register bytecode notnumberslabel acquirelabel bytecode if_acmpne notnumberslabel adddload child_dcp_register addpush convertchild getdouble bytecode bytecode bytecode bytecode marklabel notnumberslabel generateexpression generateexpression rchild testcode testcode bytecode testcode bytecode shalloweq testcode bytecode shalloweq testcode bytecode badtree addscriptruntimeinvoke testcode bytecode stackinitial getstacktop badtree private void visit set name node node node child string name node get first child get string while child null generate expression child node child child get next cfw adda load context local cfw adda load variable object local cfw add push name add script runtime invoke set name lorg mozilla javascript scriptable ljava lang object lorg mozilla javascript context lorg mozilla javascript scriptable ljava lang string ljava lang object visitsetname getfirstchild getstring generateexpression getnext addaload contextlocal addaload variableobjectlocal addpush addscriptruntimeinvoke setname private void visit get var node node if has vars in regs kit code bug int var index fn current get var index node short reg var registers var index if var is direct call parameter var index remember that here the is number flag means that we want to use the incoming parameter in a number context so test the object type and convert the value as necessary if node get int prop node isnumber prop 1 1 dcp load as number reg else dcp load as object reg else if fn current is number var var index cfw addd load reg else cfw adda load reg visitgetvar hasvarsinregs codebug varindex fncurrent getvarindex varregisters varindex varisdirectcallparameter varindex isnumber getintprop isnumber_prop dcploadasnumber dcploadasobject fncurrent isnumbervar varindex adddload addaload private void visit set var node node node child boolean need value if has vars in regs kit code bug int var index fn current get var index node generate expression child get next node boolean is number node get int prop node isnumber prop 1 1 short reg var registers var index if var is direct call parameter var index if is number if need value cfw add byte code dup2 cfw adda load reg cfw add byte code getstatic java lang void type ljava lang class int is number label cfw acquire label int beyond cfw acquire label cfw add byte code if acmpeq is number label short stack cfw get stack top add double wrap cfw adda store reg cfw add byte code goto beyond cfw mark label is number label stack cfw addd store reg 1 cfw mark label beyond else if need value cfw add byte code dup cfw adda store reg else if is number cfw addd store reg if need value cfw addd load reg else cfw adda store reg if need value cfw adda load reg visitsetvar needvalue hasvarsinregs codebug varindex fncurrent getvarindex generateexpression getnext isnumber getintprop isnumber_prop varregisters varindex varisdirectcallparameter varindex isnumber needvalue bytecode addaload bytecode isnumberlabel acquirelabel acquirelabel bytecode if_acmpeq isnumberlabel getstacktop adddoublewrap addastore bytecode marklabel isnumberlabel adddstore marklabel needvalue bytecode addastore isnumber adddstore needvalue adddload addastore needvalue addaload private void visit get prop node node node child generate expression child node object node name child child get next generate expression name child node the name for this foo we call get object prop scriptable which can skip some casting overhead int child type child get type if child type token this name child get type token string cfw adda load context local add script runtime invoke get object prop lorg mozilla javascript scriptable ljava lang string lorg mozilla javascript context ljava lang object else cfw adda load context local add script runtime invoke get object prop ljava lang object ljava lang string lorg mozilla javascript context ljava lang object visitgetprop generateexpression namechild getnext generateexpression namechild getobjectprop childtype gettype childtype namechild gettype addaload contextlocal addscriptruntimeinvoke getobjectprop addaload contextlocal addscriptruntimeinvoke getobjectprop private void visit set prop int type node node node child node object child child generate expression child node child child get next if type token setprop op cfw add byte code dup node name child child generate expression child node child child get next if type token setprop op stack object object name object name object name cfw add byte code dup x1 for this foo we call this get which can skip some casting overhead if object child get type token this name child get type token string cfw adda load context local add script runtime invoke get object prop lorg mozilla javascript scriptable ljava lang string lorg mozilla javascript context ljava lang object else cfw adda load context local add script runtime invoke get object prop ljava lang object ljava lang string lorg mozilla javascript context ljava lang object generate expression child node cfw adda load context local add script runtime invoke set object prop ljava lang object ljava lang string ljava lang object lorg mozilla javascript context ljava lang object visitsetprop objectchild generateexpression getnext setprop_op bytecode namechild generateexpression getnext setprop_op bytecode dup_x1 thisget objectchild gettype namechild gettype addaload contextlocal addscriptruntimeinvoke getobjectprop addaload contextlocal addscriptruntimeinvoke getobjectprop generateexpression addaload contextlocal addscriptruntimeinvoke setobjectprop private void visit set elem int type node node node child generate expression child node child child get next if type token setelem op cfw add byte code dup generate expression child node child child get next boolean index is number node get int prop node isnumber prop 1 1 if type token setelem op if index is number stack object object number object number object number cfw add byte code dup2 x1 cfw adda load context local add opt runtime invoke get object index ljava lang object d lorg mozilla javascript context ljava lang object else stack object object index object object index object object index object cfw add byte code dup x1 cfw adda load context local add script runtime invoke get object elem ljava lang object ljava lang object lorg mozilla javascript context ljava lang object generate expression child node cfw adda load context local if index is number add script runtime invoke set object index ljava lang object d ljava lang object lorg mozilla javascript context ljava lang object else add script runtime invoke set object elem ljava lang object ljava lang object ljava lang object lorg mozilla javascript context ljava lang object visitsetelem generateexpression getnext setelem_op bytecode generateexpression getnext indexisnumber getintprop isnumber_prop setelem_op indexisnumber bytecode dup2_x1 addaload contextlocal addoptruntimeinvoke getobjectindex indexobject indexobject indexobject bytecode dup_x1 addaload contextlocal addscriptruntimeinvoke getobjectelem generateexpression addaload contextlocal indexisnumber addscriptruntimeinvoke setobjectindex addscriptruntimeinvoke setobjectelem private void visit dot query node node node child update line number node generate expression child node cfw adda load variable object local add script runtime invoke enter dot query ljava lang object lorg mozilla javascript scriptable lorg mozilla javascript scriptable cfw adda store variable object local add push null pop with label in between to simplify code for loop continue when it is necessary to pop the null result from update dot query cfw add byte code aconst null int query loop start cfw acquire label cfw mark label query loop start loop continue jumps here cfw add byte code pop generate expression child get next node add script runtime invoke to boolean ljava lang object z cfw adda load variable object local add script runtime invoke update dot query z lorg mozilla javascript scriptable ljava lang object cfw add byte code dup cfw add byte code ifnull query loop start stack non null result of updatedotquery cfw adda load variable object local add script runtime invoke leave dot query lorg mozilla javascript scriptable lorg mozilla javascript scriptable cfw adda store variable object local visitdotquery updatelinenumber generateexpression addaload variableobjectlocal addscriptruntimeinvoke enterdotquery addastore variableobjectlocal updatedotquery bytecode aconst_null queryloopstart acquirelabel marklabel queryloopstart bytecode generateexpression getnext addscriptruntimeinvoke toboolean addaload variableobjectlocal addscriptruntimeinvoke updatedotquery bytecode bytecode queryloopstart non_null_result_of_updatedotquery addaload variableobjectlocal addscriptruntimeinvoke leavedotquery addastore variableobjectlocal private int get local block register node node node local block node node get prop node local block prop int local slot local block get existing int prop node local prop return local slot getlocalblockregister localblock getprop local_block_prop localslot localblock getexistingintprop local_prop localslot private void dcp load as number int dcp register cfw adda load dcp register cfw add byte code getstatic java lang void type ljava lang class int is number label cfw acquire label cfw add byte code if acmpeq is number label short stack cfw get stack top cfw adda load dcp register add object to double int beyond cfw acquire label cfw add byte code goto beyond cfw mark label is number label stack cfw addd load dcp register 1 cfw mark label beyond dcploadasnumber dcp_register addaload dcp_register bytecode isnumberlabel acquirelabel bytecode if_acmpeq isnumberlabel getstacktop addaload dcp_register addobjecttodouble acquirelabel bytecode marklabel isnumberlabel adddload dcp_register marklabel private void dcp load as object int dcp register cfw adda load dcp register cfw add byte code getstatic java lang void type ljava lang class int is number label cfw acquire label cfw add byte code if acmpeq is number label short stack cfw get stack top cfw adda load dcp register int beyond cfw acquire label cfw add byte code goto beyond cfw mark label is number label stack cfw addd load dcp register 1 add double wrap cfw mark label beyond dcploadasobject dcp_register addaload dcp_register bytecode isnumberlabel acquirelabel bytecode if_acmpeq isnumberlabel getstacktop addaload dcp_register acquirelabel bytecode marklabel isnumberlabel adddload dcp_register adddoublewrap marklabel private void add goto node target int jumpcode int target label get target label target cfw add jumpcode target label addgoto targetlabel gettargetlabel targetlabel private void add object to double add script runtime invoke to number ljava lang object d addobjecttodouble addscriptruntimeinvoke tonumber private void add new object array int size if size 0 if its zero arg array 0 cfw adda load its zero arg array else cfw add byte code getstatic org mozilla javascript script runtime empty args ljava lang object else cfw add push size cfw add byte code anewarray java lang object addnewobjectarray itszeroargarray addaload itszeroargarray bytecode scriptruntime emptyargs addpush bytecode private void add script runtime invoke string method name string method signature cfw add invoke byte code invokestatic org mozilla javascript script runtime method name method signature addscriptruntimeinvoke methodname methodsignature addinvoke bytecode scriptruntime methodname methodsignature private void add opt runtime invoke string method name string method signature cfw add invoke byte code invokestatic org mozilla javascript optimizer opt runtime method name method signature addoptruntimeinvoke methodname methodsignature addinvoke bytecode optruntime methodname methodsignature private void add jumped boolean wrap int true label int false label cfw mark label false label int skip cfw acquire label cfw add byte code getstatic java lang boolean false ljava lang boolean cfw add byte code goto skip cfw mark label true label cfw add byte code getstatic java lang boolean true ljava lang boolean cfw mark label skip cfw adjust stack top 1 only have 1 of true false addjumpedbooleanwrap truelabel falselabel marklabel falselabel acquirelabel bytecode bytecode marklabel truelabel bytecode marklabel adjuststacktop private void add double wrap add opt runtime invoke wrap double d ljava lang double adddoublewrap addoptruntimeinvoke wrapdouble private short get new word pair local short result first free local while true if result max locals 1 break if locals result locals result 1 break result if result max locals 1 locals result true locals result 1 true if result first free local for int i first free local 2 i max locals i if locals i first free local short i if locals max first free local locals max first free local return result else return result throw context report runtime error program too complex out of locals getnewwordpairlocal firstfreelocal max_locals max_locals firstfreelocal firstfreelocal max_locals firstfreelocal localsmax firstfreelocal localsmax firstfreelocal reportruntimeerror private short get new word local short result first free local locals result true for int i first free local 1 i max locals i if locals i first free local short i if locals max first free local locals max first free local return result throw context report runtime error program too complex out of locals getnewwordlocal firstfreelocal firstfreelocal max_locals firstfreelocal localsmax firstfreelocal localsmax firstfreelocal reportruntimeerror private void release wordpair local short local if local first free local first free local local locals local false locals local 1 false releasewordpairlocal firstfreelocal firstfreelocal private void release word local short local if local first free local first free local local locals local false releasewordlocal firstfreelocal firstfreelocal static void init scriptable scope boolean sealed native date obj new native date set the value of the prototype date to nan invalid date obj date script runtime nan obj export asjs class max prototype id scope sealed nativedate nativedate scriptruntime exportasjsclass max_prototype_id private native date if this time zone null j u time zone is synchronized so setting class statics from it should be ok this time zone java util time zone get default localtza this time zone get raw offset nativedate thistimezone timezone thistimezone timezone getdefault thistimezone getrawoffset public string get class name return date getclassname public object get default value class type hint if type hint null type hint script runtime string class return super get default value type hint getdefaultvalue typehint typehint typehint scriptruntime stringclass getdefaultvalue typehint double getjs time value return date getjstimevalue protected void fill constructor properties id function object ctor add id function property ctor date tag constructorid now now 0 add id function property ctor date tag constructorid parse parse 1 add id function property ctor date tag constructorid utc utc 1 super fill constructor properties ctor fillconstructorproperties idfunctionobject addidfunctionproperty date_tag constructorid_now addidfunctionproperty date_tag constructorid_parse addidfunctionproperty date_tag constructorid_utc fillconstructorproperties protected void init prototype id int id string s int arity switch id case id constructor arity 1 s constructor break case id tostring arity 0 s to string break case id totimestring arity 0 s to time string break case id todatestring arity 0 s to date string break case id tolocalestring arity 0 s to locale string break case id tolocaletimestring arity 0 s to locale time string break case id tolocaledatestring arity 0 s to locale date string break case id toutcstring arity 0 s toutc string break case id tosource arity 0 s to source break case id valueof arity 0 s value of break case id gettime arity 0 s get time break case id getyear arity 0 s get year break case id getfullyear arity 0 s get full year break case id getutcfullyear arity 0 s getutc full year break case id getmonth arity 0 s get month break case id getutcmonth arity 0 s getutc month break case id getdate arity 0 s get date break case id getutcdate arity 0 s getutc date break case id getday arity 0 s get day break case id getutcday arity 0 s getutc day break case id gethours arity 0 s get hours break case id getutchours arity 0 s getutc hours break case id getminutes arity 0 s get minutes break case id getutcminutes arity 0 s getutc minutes break case id getseconds arity 0 s get seconds break case id getutcseconds arity 0 s getutc seconds break case id getmilliseconds arity 0 s get milliseconds break case id getutcmilliseconds arity 0 s getutc milliseconds break case id gettimezoneoffset arity 0 s get timezone offset break case id settime arity 1 s set time break case id setmilliseconds arity 1 s set milliseconds break case id setutcmilliseconds arity 1 s setutc milliseconds break case id setseconds arity 2 s set seconds break case id setutcseconds arity 2 s setutc seconds break case id setminutes arity 3 s set minutes break case id setutcminutes arity 3 s setutc minutes break case id sethours arity 4 s set hours break case id setutchours arity 4 s setutc hours break case id setdate arity 1 s set date break case id setutcdate arity 1 s setutc date break case id setmonth arity 2 s set month break case id setutcmonth arity 2 s setutc month break case id setfullyear arity 3 s set full year break case id setutcfullyear arity 3 s setutc full year break case id setyear arity 1 s set year break default throw new illegal argument exception string value of id init prototype method date tag id s arity initprototypeid id_constructor id_tostring tostring id_totimestring totimestring id_todatestring todatestring id_tolocalestring tolocalestring id_tolocaletimestring tolocaletimestring id_tolocaledatestring tolocaledatestring id_toutcstring toutcstring id_tosource tosource id_valueof valueof id_gettime gettime id_getyear getyear id_getfullyear getfullyear id_getutcfullyear getutcfullyear id_getmonth getmonth id_getutcmonth getutcmonth id_getdate getdate id_getutcdate getutcdate id_getday getday id_getutcday getutcday id_gethours gethours id_getutchours getutchours id_getminutes getminutes id_getutcminutes getutcminutes id_getseconds getseconds id_getutcseconds getutcseconds id_getmilliseconds getmilliseconds id_getutcmilliseconds getutcmilliseconds id_gettimezoneoffset gettimezoneoffset id_settime settime id_setmilliseconds setmilliseconds id_setutcmilliseconds setutcmilliseconds id_setseconds setseconds id_setutcseconds setutcseconds id_setminutes setminutes id_setutcminutes setutcminutes id_sethours sethours id_setutchours setutchours id_setdate setdate id_setutcdate setutcdate id_setmonth setmonth id_setutcmonth setutcmonth id_setfullyear setfullyear id_setutcfullyear setutcfullyear id_setyear setyear illegalargumentexception valueof initprototypemethod date_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag date tag return super exec id call f cx scope this obj args int id f method id switch id case constructorid now return script runtime wrap number now case constructorid parse string data str script runtime to string args 0 return script runtime wrap number date parsestring data str case constructorid utc return script runtime wrap number jsstaticfunction utc args case id constructor if called as a function just return a string representing the current time if this obj null return date format now id tostring return js constructor args the rest of date prototype methods require this obj to be date if this obj instanceof native date throw incompatible call error f native date real this native date this obj double t real this date switch id case id tostring case id totimestring case id todatestring if t t return date format t id return js nan date str case id tolocalestring case id tolocaletimestring case id tolocaledatestring if t t return tolocale helper t id return js nan date str case id toutcstring if t t return js toutcstring t return js nan date str case id tosource return new date script runtime to string t case id valueof case id gettime return script runtime wrap number t case id getyear case id getfullyear case id getutcfullyear if t t if id id getutcfullyear t local time t t year from time t if id id getyear if cx has feature context feature non ecma get year if 1900 t t 2000 t 1900 else t 1900 return script runtime wrap number t case id getmonth case id getutcmonth if t t if id id getmonth t local time t t month from time t return script runtime wrap number t case id getdate case id getutcdate if t t if id id getdate t local time t t date from time t return script runtime wrap number t case id getday case id getutcday if t t if id id getday t local time t t week day t return script runtime wrap number t case id gethours case id getutchours if t t if id id gethours t local time t t hour from time t return script runtime wrap number t case id getminutes case id getutcminutes if t t if id id getminutes t local time t t min from time t return script runtime wrap number t case id getseconds case id getutcseconds if t t if id id getseconds t local time t t sec from time t return script runtime wrap number t case id getmilliseconds case id getutcmilliseconds if t t if id id getmilliseconds t local time t t ms from time t return script runtime wrap number t case id gettimezoneoffset if t t t t local time t ms per minute return script runtime wrap number t case id settime t time clip script runtime to number args 0 real this date t return script runtime wrap number t case id setmilliseconds case id setutcmilliseconds case id setseconds case id setutcseconds case id setminutes case id setutcminutes case id sethours case id setutchours t make time t args id real this date t return script runtime wrap number t case id setdate case id setutcdate case id setmonth case id setutcmonth case id setfullyear case id setutcfullyear t make date t args id real this date t return script runtime wrap number t case id setyear double year script runtime to number args 0 if year year double is infinite year t script runtime nan else if t t t 0 else t local time t if year 0 year 99 year 1900 double day make day year month from time t date from time t t make date day time within day t t internalutc t t time clip t real this date t return script runtime wrap number t default throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag date_tag execidcall thisobj methodid constructorid_now scriptruntime wrapnumber constructorid_parse datastr scriptruntime tostring scriptruntime wrapnumber date_parsestring datastr constructorid_utc scriptruntime wrapnumber jsstaticfunction_utc id_constructor thisobj date_format id_tostring jsconstructor thisobj thisobj nativedate incompatiblecallerror nativedate realthis nativedate thisobj realthis id_tostring id_totimestring id_todatestring date_format js_nan_date_str id_tolocalestring id_tolocaletimestring id_tolocaledatestring tolocale_helper js_nan_date_str id_toutcstring js_toutcstring js_nan_date_str id_tosource scriptruntime tostring id_valueof id_gettime scriptruntime wrapnumber id_getyear id_getfullyear id_getutcfullyear id_getutcfullyear localtime yearfromtime id_getyear hasfeature feature_non_ecma_get_year scriptruntime wrapnumber id_getmonth id_getutcmonth id_getmonth localtime monthfromtime scriptruntime wrapnumber id_getdate id_getutcdate id_getdate localtime datefromtime scriptruntime wrapnumber id_getday id_getutcday id_getday localtime weekday scriptruntime wrapnumber id_gethours id_getutchours id_gethours localtime hourfromtime scriptruntime wrapnumber id_getminutes id_getutcminutes id_getminutes localtime minfromtime scriptruntime wrapnumber id_getseconds id_getutcseconds id_getseconds localtime secfromtime scriptruntime wrapnumber id_getmilliseconds id_getutcmilliseconds id_getmilliseconds localtime msfromtime scriptruntime wrapnumber id_gettimezoneoffset localtime msperminute scriptruntime wrapnumber id_settime timeclip scriptruntime tonumber realthis scriptruntime wrapnumber id_setmilliseconds id_setutcmilliseconds id_setseconds id_setutcseconds id_setminutes id_setutcminutes id_sethours id_setutchours maketime realthis scriptruntime wrapnumber id_setdate id_setutcdate id_setmonth id_setutcmonth id_setfullyear id_setutcfullyear makedate realthis scriptruntime wrapnumber id_setyear scriptruntime tonumber isinfinite scriptruntime localtime makeday monthfromtime datefromtime makedate timewithinday timeclip realthis scriptruntime wrapnumber illegalargumentexception valueof private static final double ms per minute seconds per minute ms per second private static double day double t return math floor t ms per day msperminute secondsperminute mspersecond msperday private static double time within day double t double result result t ms per day if result 0 result ms per day return result timewithinday msperday msperday private static boolean is leap year int year return year 4 0 year 100 0 year 400 0 isleapyear private static double day from year double y return 365 y 1970 math floor y 1969 4 0 math floor y 1901 100 0 math floor y 1601 400 0 dayfromyear private static double time from year double y return day from year y ms per day timefromyear dayfromyear msperday private static int year from time double t int lo int math floor t ms per day 366 1970 int hi int math floor t ms per day 365 1970 int mid above doesn t work for negative dates if hi lo int temp lo lo hi hi temp use a simple binary search algorithm to find the right year this seems like brute force but the computation of hi and lo years above lands within one year of the correct answer for years within a thousand years of 1970 the loop below only requires six iterations for year 270000 while hi lo mid hi lo 2 if time from year mid t hi mid 1 else lo mid 1 if time from year lo t return mid return lo yearfromtime msperday msperday timefromyear timefromyear private static boolean in leap year double t return is leap year year from time t inleapyear isleapyear yearfromtime private static double day from month int m int year int day m 30 if m 7 day m 2 1 else if m 2 day m 1 2 1 else day m if m 2 is leap year year day return day dayfrommonth isleapyear private static int month from time double t int year year from time t int d int day t day from year year d 31 28 if d 0 return d 28 0 1 if is leap year year if d 0 return 1 29 february d d date count from 1 march int estimate d 30 approx number of month since march int mstart switch estimate case 0 return 2 case 1 mstart 31 break case 2 mstart 31 30 break case 3 mstart 31 30 31 break case 4 mstart 31 30 31 30 break case 5 mstart 31 30 31 30 31 break case 6 mstart 31 30 31 30 31 31 break case 7 mstart 31 30 31 30 31 31 30 break case 8 mstart 31 30 31 30 31 31 30 31 break case 9 mstart 31 30 31 30 31 31 30 31 30 break case 10 return 11 late december default throw kit code bug if d mstart then real month since march estimate 1 return d mstart estimate 2 estimate 1 monthfromtime yearfromtime dayfromyear isleapyear codebug private static int date from time double t int year year from time t int d int day t day from year year d 31 28 if d 0 return d 28 d 31 28 1 d 28 1 if is leap year year if d 0 return 29 29 february d d date count from 1 march int mdays mstart switch d 30 approx number of month since march case 0 return d 1 case 1 mdays 31 mstart 31 break case 2 mdays 30 mstart 31 30 break case 3 mdays 31 mstart 31 30 31 break case 4 mdays 30 mstart 31 30 31 30 break case 5 mdays 31 mstart 31 30 31 30 31 break case 6 mdays 31 mstart 31 30 31 30 31 31 break case 7 mdays 30 mstart 31 30 31 30 31 31 30 break case 8 mdays 31 mstart 31 30 31 30 31 31 30 31 break case 9 mdays 30 mstart 31 30 31 30 31 31 30 31 30 break case 10 return d 31 30 31 30 31 31 30 31 30 1 late december default throw kit code bug d mstart if d 0 wrong estimate sfhift to previous month d mdays return d 1 datefromtime yearfromtime dayfromyear isleapyear codebug private static int week day double t double result result day t 4 result result 7 if result 0 result 7 return int result weekday private static double now return double system current time millis currenttimemillis private final static boolean tzo workaround false private static double daylight savingta double t another workaround the jre doesn t seem to know about dst before year 1 ad so we map to equivalent dates for the purposes of finding dst to be safe we do this for years outside 1970 2038 if t 0 0 t 2145916800000 0 int year equivalent year year from time t double day make day year month from time t date from time t t make date day time within day t if tzo workaround date date new date long t if this time zone in daylight time date return ms per hour else return 0 else use get offset if in daylight time is broken because it seems to work acceptably we don t switch over to it entirely because it requires expensive exploded date arguments and the api makes it impossible to handle dst changeovers cleanly hardcode the assumption that the changeover always happens at 2 00 am t localtza hour from time t 2 ms per hour 0 int year year from time t double offset this time zone get offset year 0 1 0 year month from time t date from time t week day t int time within day t if offset localtza 0 return ms per hour else return 0 return offset localtza tzo_workaround daylightsavingta equivalentyear yearfromtime makeday monthfromtime datefromtime makedate timewithinday tzo_workaround thistimezone indaylighttime msperhour getoffset indaylighttime hourfromtime msperhour yearfromtime thistimezone getoffset monthfromtime datefromtime weekday timewithinday msperhour private static int equivalent year int year int day int day from year year 4 day day 7 if day 0 day 7 years and leap years on which jan 1 is a sunday monday etc if is leap year year switch day case 0 return 1984 case 1 return 1996 case 2 return 1980 case 3 return 1992 case 4 return 1976 case 5 return 1988 case 6 return 1972 else switch day case 0 return 1978 case 1 return 1973 case 2 return 1974 case 3 return 1975 case 4 return 1981 case 5 return 1971 case 6 return 1977 unreachable throw kit code bug equivalentyear dayfromyear isleapyear codebug private static double local time double t return t localtza daylight savingta t localtime daylightsavingta private static double internalutc double t return t localtza daylight savingta t localtza daylightsavingta private static int hour from time double t double result result math floor t ms per hour hours per day if result 0 result hours per day return int result hourfromtime msperhour hoursperday hoursperday private static int min from time double t double result result math floor t ms per minute minutes per hour if result 0 result minutes per hour return int result minfromtime msperminute minutesperhour minutesperhour private static int sec from time double t double result result math floor t ms per second seconds per minute if result 0 result seconds per minute return int result secfromtime mspersecond secondsperminute secondsperminute private static int ms from time double t double result result t ms per second if result 0 result ms per second return int result msfromtime mspersecond mspersecond private static double make time double hour double min double sec double ms return hour minutes per hour min seconds per minute sec ms per second ms maketime minutesperhour secondsperminute mspersecond private static double make day double year double month double date year math floor month 12 month month 12 if month 0 month 12 double yearday math floor time from year year ms per day double monthday day from month int month int year return yearday monthday date 1 makeday timefromyear msperday dayfrommonth private static double make date double day double time return day ms per day time makedate msperday private static double time clip double d if d d d double positive infinity d double negative infinity math abs d half time domain return script runtime nan if d 0 0 return math floor d 0 else return math ceil d 0 timeclip positive_infinity negative_infinity halftimedomain scriptruntime find utc time from given date no 1900 correction private static double date msecfromdate double year double mon double mday double hour double min double sec double msec double day double time double result day make day year mon mday time make time hour min sec msec result make date day time return result date_msecfromdate makeday maketime makedate private static final int maxargs 7 private static double jsstaticfunction utc object args double array new double maxargs int loop double d for loop 0 loop maxargs loop if loop args length d script runtime to number args loop if d d double is infinite d return script runtime nan array loop script runtime to integer args loop else array loop 0 adjust 2 digit years into the 20th century if array 0 0 array 0 99 array 0 1900 if we got a 0 for date which is out of range pretend it s a 1 so date utc 1972 5 works if array 2 1 array 2 1 d date msecfromdate array 0 array 1 array 2 array 3 array 4 array 5 array 6 d time clip d return d jsstaticfunction_utc scriptruntime tonumber isinfinite scriptruntime scriptruntime tointeger date_msecfromdate timeclip private static double date parsestring string s int year 1 int mon 1 int mday 1 int hour 1 int min 1 int sec 1 char c 0 char si 0 int i 0 int n 1 double tzoffset 1 char prevc 0 int limit 0 boolean seenplusminus false limit s length while i limit c s char at i i if c c c if i limit si s char at i if c 0 si si 9 prevc c continue if c comments int depth 1 while i limit c s char at i i if c depth else if c if depth 0 break continue if 0 c c 9 n c 0 while i limit 0 c s char at i c 9 n n 10 c 0 i allow tza before the year so wed nov 05 21 49 11 gmt 0800 1997 works uses of seenplusminus allow in tza so java no timezone style of gmt 4 30 works if prevc prevc year 0 make case below change tzoffset seenplusminus true offset if n 24 n n 60 eg gmt 3 else n n 100 n 100 60 eg gmt 0430 if prevc plus means east of gmt n n if tzoffset 0 tzoffset 1 return script runtime nan tzoffset n else if n 70 prevc mon 0 mday 0 year 0 if year 0 return script runtime nan else if c c c i limit year n 100 n 1900 n else return script runtime nan else if c if hour 0 hour byte n else if min 0 min byte n else return script runtime nan else if c if mon 0 mon byte n 1 else if mday 0 mday byte n else return script runtime nan else if i limit c c c return script runtime nan else if seenplusminus n 60 handle gmt 3 30 if tzoffset 0 tzoffset n else tzoffset n else if hour 0 min 0 min byte n else if min 0 sec 0 sec byte n else if mday 0 mday byte n else return script runtime nan prevc 0 else if c c c c prevc c else int st i 1 while i limit c s char at i if a c c z a c c z break i int letter count i st if letter count 2 return script runtime nan use ported code from jsdate c rather than the locale specific date parsing code from java to keep js and rhino consistent is this the right strategy string wtb am pm monday tuesday wednesday thursday friday saturday sunday january february march april may june july august september october november december gmt ut utc est edt cst cdt mst mdt pst pdt int index 0 for int wtb offset 0 int wtb next wtb index of wtb offset if wtb next 0 return script runtime nan if wtb region matches true wtb offset s st letter count break wtb offset wtb next 1 index if index 2 am pm count 12 30 am as 00 30 12 30 pm as 12 30 instead of blindly adding 12 if pm if hour 12 hour 0 return script runtime nan else if index 0 am if hour 12 hour 0 else pm if hour 12 hour 12 else if index 2 7 ignore week days else if index 7 12 month if mon 0 mon index else return script runtime nan else index 12 timezones switch index case 0 gmt tzoffset 0 break case 1 ut tzoffset 0 break case 2 utc tzoffset 0 break case 3 est tzoffset 5 60 break case 4 edt tzoffset 4 60 break case 5 cst tzoffset 6 60 break case 6 cdt tzoffset 5 60 break case 7 mst tzoffset 7 60 break case 8 mdt tzoffset 6 60 break case 9 pst tzoffset 8 60 break case 10 pdt tzoffset 7 60 break default kit code bug if year 0 mon 0 mday 0 return script runtime nan if sec 0 sec 0 if min 0 min 0 if hour 0 hour 0 double msec date msecfromdate year mon mday hour min sec 0 if tzoffset 1 no time zone specified have to use local return internalutc msec else return msec tzoffset ms per minute date_parsestring charat charat charat charat scriptruntime scriptruntime scriptruntime scriptruntime scriptruntime scriptruntime scriptruntime charat lettercount lettercount scriptruntime wtboffset wtbnext indexof wtboffset wtbnext scriptruntime regionmatches wtboffset lettercount wtboffset wtbnext scriptruntime scriptruntime codebug scriptruntime date_msecfromdate msperminute private static string date format double t int method id string buffer result new string buffer 60 double local local time t tue oct 31 09 41 40 gmt 0800 pst 2000 tue oct 31 2000 09 41 40 gmt 0800 pst if method id id totimestring append week day name result week day local result append append month name result month from time local result append append0 padded uint result date from time local 2 result append int year year from time local if year 0 result append year year append0 padded uint result year 4 if method id id todatestring result append if method id id todatestring append0 padded uint result hour from time local 2 result append append0 padded uint result min from time local 2 result append append0 padded uint result sec from time local 2 offset from gmt in minutes the offset includes daylight savings if it applies int minutes int math floor localtza daylight savingta t ms per minute map 510 minutes to 0830 hours int offset minutes 60 100 minutes 60 if offset 0 result append gmt else result append gmt offset offset append0 padded uint result offset 4 if time zone formatter null time zone formatter new java text simple date format zzz find an equivalent year before getting the timezone comment see daylight savingta if t 0 0 t 2145916800000 0 int equiv equivalent year year from time local double day make day equiv month from time t date from time t t make date day time within day t result append java util date date new date long t result append time zone formatter format date result append return result to string date_format methodid stringbuffer stringbuffer localtime methodid id_totimestring appendweekdayname weekday appendmonthname monthfromtime append0paddeduint datefromtime yearfromtime append0paddeduint methodid id_todatestring methodid id_todatestring append0paddeduint hourfromtime append0paddeduint minfromtime append0paddeduint secfromtime daylightsavingta msperminute append0paddeduint timezoneformatter timezoneformatter simpledateformat daylightsavingta equivalentyear yearfromtime makeday monthfromtime datefromtime makedate timewithinday timezoneformatter tostring the javascript constructor private static object js constructor object args native date obj new native date if called as a constructor with no args return a new date with the current time if args length 0 obj date now return obj if called with just one arg if args length 1 object arg0 args 0 if arg0 instanceof scriptable arg0 scriptable arg0 get default value null double date if arg0 instanceof string it s a string parse it date date parsestring string arg0 else if it s not a string use it as a millisecond date date script runtime to number arg0 obj date time clip date return obj multiple arguments year month day etc double array new double maxargs int loop double d for loop 0 loop maxargs loop if loop args length d script runtime to number args loop if d d double is infinite d obj date script runtime nan return obj array loop script runtime to integer args loop else array loop 0 adjust 2 digit years into the 20th century if array 0 0 array 0 99 array 0 1900 if we got a 0 for date which is out of range pretend it s a 1 if array 2 1 array 2 1 double day make day array 0 array 1 array 2 double time make time array 3 array 4 array 5 array 6 time make date day time time internalutc time obj date time clip time return obj jsconstructor nativedate nativedate getdefaultvalue date_parsestring scriptruntime tonumber timeclip scriptruntime tonumber isinfinite scriptruntime scriptruntime tointeger makeday maketime makedate timeclip private static string tolocale helper double t int method id java text date format formatter switch method id case id tolocalestring if locale date time formatter null locale date time formatter date format get date time instance date format long date format long formatter locale date time formatter break case id tolocaletimestring if locale time formatter null locale time formatter date format get time instance date format long formatter locale time formatter break case id tolocaledatestring if locale date formatter null locale date formatter date format get date instance date format long formatter locale date formatter break default formatter null unreachable return formatter format new date long t tolocale_helper methodid dateformat methodid id_tolocalestring localedatetimeformatter localedatetimeformatter dateformat getdatetimeinstance dateformat dateformat localedatetimeformatter id_tolocaletimestring localetimeformatter localetimeformatter dateformat gettimeinstance dateformat localetimeformatter id_tolocaledatestring localedateformatter localedateformatter dateformat getdateinstance dateformat localedateformatter private static string js toutcstring double date string buffer result new string buffer 60 append week day name result week day date result append append0 padded uint result date from time date 2 result append append month name result month from time date result append int year year from time date if year 0 result append year year append0 padded uint result year 4 result append append0 padded uint result hour from time date 2 result append append0 padded uint result min from time date 2 result append append0 padded uint result sec from time date 2 result append gmt return result to string js_toutcstring stringbuffer stringbuffer appendweekdayname weekday append0paddeduint datefromtime appendmonthname monthfromtime yearfromtime append0paddeduint append0paddeduint hourfromtime append0paddeduint minfromtime append0paddeduint secfromtime tostring private static void append0 padded uint string buffer sb int i int min width if i 0 kit code bug int scale 1 min width if i 10 if i 1000 1000 1000 for int new scale scale 10 if i new scale break min width scale new scale else separated case not to check against 10 10 9 overflow min width 9 scale 1000 1000 1000 while min width 0 sb append 0 min width while scale 1 sb append char 0 i scale i scale scale 10 sb append char 0 i append0paddeduint stringbuffer minwidth codebug minwidth newscale newscale minwidth newscale minwidth minwidth minwidth private static void append month name string buffer sb int index take advantage of the fact that all month abbreviations have the same length to minimize amount of strings runtime has to keep in memory string months jan feb mar apr may jun jul aug sep oct nov dec index 3 for int i 0 i 3 i sb append months char at index i appendmonthname stringbuffer charat private static void append week day name string buffer sb int index string days sun mon tue wed thu fri sat index 3 for int i 0 i 3 i sb append days char at index i appendweekdayname stringbuffer charat private static double make time double date object args int method id int maxargs boolean local true switch method id case id setutcmilliseconds local false fallthrough case id setmilliseconds maxargs 1 break case id setutcseconds local false fallthrough case id setseconds maxargs 2 break case id setutcminutes local false fallthrough case id setminutes maxargs 3 break case id setutchours local false fallthrough case id sethours maxargs 4 break default kit code bug maxargs 0 int i double conv new double 4 double hour min sec msec double lorutime local or utc version of date double time double result just return nan if the date is already nan if date date return date satisfy the ecma rule that if a function is called with fewer arguments than the specified formal arguments the remaining arguments are set to undefined seems like all the date set whatever functions in ecma are only varargs beyond the first argument this should be set to undefined if it s not given this means that d new date d set milliseconds returns nan blech if args length 0 args script runtime pad arguments args 1 for i 0 i args length i maxargs i conv i script runtime to number args i limit checks that happen in make time in ecma if conv i conv i double is infinite conv i return script runtime nan conv i script runtime to integer conv i if local lorutime local time date else lorutime date i 0 int stop args length if maxargs 4 i stop hour conv i else hour hour from time lorutime if maxargs 3 i stop min conv i else min min from time lorutime if maxargs 2 i stop sec conv i else sec sec from time lorutime if maxargs 1 i stop msec conv i else msec ms from time lorutime time make time hour min sec msec result make date day lorutime time if local result internalutc result date time clip result return date maketime methodid methodid id_setutcmilliseconds id_setmilliseconds id_setutcseconds id_setseconds id_setutcminutes id_setminutes id_setutchours id_sethours codebug setwhatever setmilliseconds scriptruntime padarguments scriptruntime tonumber maketime isinfinite scriptruntime scriptruntime tointeger localtime hourfromtime minfromtime secfromtime msfromtime maketime makedate timeclip private static double make date double date object args int method id int maxargs boolean local true switch method id case id setutcdate local false fallthrough case id setdate maxargs 1 break case id setutcmonth local false fallthrough case id setmonth maxargs 2 break case id setutcfullyear local false fallthrough case id setfullyear maxargs 3 break default kit code bug maxargs 0 int i double conv new double 3 double year month day double lorutime local or utc version of date double result see arg padding comment in make time if args length 0 args script runtime pad arguments args 1 for i 0 i args length i maxargs i conv i script runtime to number args i limit checks that happen in make date in ecma if conv i conv i double is infinite conv i return script runtime nan conv i script runtime to integer conv i return nan if date is nan and we re not setting the year if we are use 0 as the time if date date if args length 3 return script runtime nan else lorutime 0 else if local lorutime local time date else lorutime date i 0 int stop args length if maxargs 3 i stop year conv i else year year from time lorutime if maxargs 2 i stop month conv i else month month from time lorutime if maxargs 1 i stop day conv i else day date from time lorutime day make day year month day day within year result make date day time within day lorutime if local result internalutc result date time clip result return date makedate methodid methodid id_setutcdate id_setdate id_setutcmonth id_setmonth id_setutcfullyear id_setfullyear codebug maketime scriptruntime padarguments scriptruntime tonumber makedate isinfinite scriptruntime scriptruntime tointeger scriptruntime localtime yearfromtime monthfromtime datefromtime makeday makedate timewithinday timeclip protected int find prototype id string s int id generated last update 2004 03 17 13 33 23 cet l0 id 0 string x null int c l switch s length case 6 x get day id id getday break l case 7 switch s char at 3 case d c s char at 0 if c g x get date id id getdate else if c s x set date id id setdate break l case t c s char at 0 if c g x get time id id gettime else if c s x set time id id settime break l case y c s char at 0 if c g x get year id id getyear else if c s x set year id id setyear break l case u x value of id id valueof break l break l case 8 switch s char at 3 case h c s char at 0 if c g x get hours id id gethours else if c s x set hours id id sethours break l case m c s char at 0 if c g x get month id id getmonth else if c s x set month id id setmonth break l case o x to source id id tosource break l case t x to string id id tostring break l break l case 9 x getutc day id id getutcday break l case 10 c s char at 3 if c m c s char at 0 if c g x get minutes id id getminutes else if c s x set minutes id id setminutes else if c s c s char at 0 if c g x get seconds id id getseconds else if c s x set seconds id id setseconds else if c u c s char at 0 if c g x getutc date id id getutcdate else if c s x setutc date id id setutcdate break l case 11 switch s char at 3 case f c s char at 0 if c g x get full year id id getfullyear else if c s x set full year id id setfullyear break l case m x togmt string id id togmtstring break l case t x toutc string id id toutcstring break l case u c s char at 0 if c g c s char at 9 if c r x getutc hours id id getutchours else if c t x getutc month id id getutcmonth else if c s c s char at 9 if c r x setutc hours id id setutchours else if c t x setutc month id id setutcmonth break l case s x constructor id id constructor break l break l case 12 c s char at 2 if c d x to date string id id todatestring else if c t x to time string id id totimestring break l case 13 c s char at 0 if c g c s char at 6 if c m x getutc minutes id id getutcminutes else if c s x getutc seconds id id getutcseconds else if c s c s char at 6 if c m x setutc minutes id id setutcminutes else if c s x setutc seconds id id setutcseconds break l case 14 c s char at 0 if c g x getutc full year id id getutcfullyear else if c s x setutc full year id id setutcfullyear else if c t x to locale string id id tolocalestring break l case 15 c s char at 0 if c g x get milliseconds id id getmilliseconds else if c s x set milliseconds id id setmilliseconds break l case 17 x get timezone offset id id gettimezoneoffset break l case 18 c s char at 0 if c g x getutc milliseconds id id getutcmilliseconds else if c s x setutc milliseconds id id setutcmilliseconds else if c t c s char at 8 if c d x to locale date string id id tolocaledatestring else if c t x to locale time string id id tolocaletimestring break l if x null x s x equals s id 0 generated return id findprototypeid getday id_getday charat charat getdate id_getdate setdate id_setdate charat gettime id_gettime settime id_settime charat getyear id_getyear setyear id_setyear valueof id_valueof charat charat gethours id_gethours sethours id_sethours charat getmonth id_getmonth setmonth id_setmonth tosource id_tosource tostring id_tostring getutcday id_getutcday charat charat getminutes id_getminutes setminutes id_setminutes charat getseconds id_getseconds setseconds id_setseconds charat getutcdate id_getutcdate setutcdate id_setutcdate charat charat getfullyear id_getfullyear setfullyear id_setfullyear togmtstring id_togmtstring toutcstring id_toutcstring charat charat getutchours id_getutchours getutcmonth id_getutcmonth charat setutchours id_setutchours setutcmonth id_setutcmonth id_constructor charat todatestring id_todatestring totimestring id_totimestring charat charat getutcminutes id_getutcminutes getutcseconds id_getutcseconds charat setutcminutes id_setutcminutes setutcseconds id_setutcseconds charat getutcfullyear id_getutcfullyear setutcfullyear id_setutcfullyear tolocalestring id_tolocalestring charat getmilliseconds id_getmilliseconds setmilliseconds id_setmilliseconds gettimezoneoffset id_gettimezoneoffset charat getutcmilliseconds id_getutcmilliseconds setutcmilliseconds id_setutcmilliseconds charat tolocaledatestring id_tolocaledatestring tolocaletimestring id_tolocaletimestring main entry point process arguments as would a normal java program also create a new context and associate it with the current thread then set up the execution environment and begin to execute scripts public static void main string args context cx context enter try set version to java script1 2 so that we get object literal style printing instead of object object cx set language version context version 1 2 initialize the standard objects object function etc this must be done before scripts can be executed scriptable scope cx init standard objects now we can evaluate a script let s create a new object using the object literal notation object result cx evaluate string scope obj a 1 b x y my source 1 null scriptable obj scriptable scope get obj scope should print obj result since the result of an assignment expression is the value that was assigned system out println obj obj result result should print obj a 1 system out println obj a obj get a obj scriptable b scriptable obj get b obj should print obj b 0 x system out println obj b 0 b get 0 b should print obj b 1 y system out println obj b 1 b get 1 b should print a 1 b x y function fn function scriptable object get property obj to string system out println fn call cx scope obj new object 0 finally context exit javascript1 setlanguageversion version_1_2 initstandardobjects evaluatestring mysource scriptableobject getproperty tostring string script text i proxy int type this type type scripttext iproxy public object run context cx if type process files process files cx args else if type eval inline script script script load script from source cx script text command 1 null if script null evaluate script script cx get global else throw kit code bug return null process_files processfiles eval_inline_script loadscriptfromsource scripttext evaluatescript getglobal codebug public void quit context cx int exit code if type system exit system exit exit code return throw kit code bug exitcode system_exit exitcode codebug main entry point process arguments as would a normal java program also create a new context and associate it with the current thread then set up the execution environment and begin to execute scripts public static void main string args try if boolean get boolean rhino use java policy security init java policy security support catch security exception ex ex print stack trace system err int result exec args if result 0 system exit result getboolean use_java_policy_security initjavapolicysecuritysupport securityexception printstacktrace execute the given arguments but don t system exit at the end public static int exec string orig args error reporter new tool error reporter false global get err shell context factory set error reporter error reporter string args process options orig args if process stdin file list add element null if global initialized global init shell context factory i proxy iproxy new i proxy i proxy process files iproxy args args shell context factory call iproxy return exit code origargs errorreporter toolerrorreporter geterr shellcontextfactory seterrorreporter errorreporter processoptions origargs processstdin filelist addelement shellcontextfactory iproxy iproxy iproxy process_files shellcontextfactory exitcode static void process files context cx string args define arguments array in the top level object need to allocate new array since new array requires instances of exactly object not object subclass object array new object args length system arraycopy args 0 array 0 args length scriptable args obj cx new array global array global define property arguments args obj scriptable object dontenum for int i 0 i file list size i process source cx string file list element at i processfiles newarray objectsubclass argsobj newarray defineproperty argsobj scriptableobject filelist processsource filelist elementat public static global get global return global getglobal parse arguments public static string process options string args string usage error good usage for int i 0 i if i args length return new string 0 string arg args i if arg starts with process stdin false file list add element arg string result new string args length i 1 system arraycopy args i 1 result 0 args length i 1 return result if arg equals version if i args length usage error arg break good usage int version try version integer parse int args i catch number format exception ex usage error args i break good usage if context is valid language version version usage error args i break good usage shell context factory set language version version continue if arg equals opt arg equals o if i args length usage error arg break good usage int opt try opt integer parse int args i catch number format exception ex usage error args i break good usage if opt 2 compatibility with cocoon rhino fork opt 1 else if context is valid optimization level opt usage error args i break good usage shell context factory set optimization level opt continue if arg equals strict shell context factory set strict mode true continue if arg equals e process stdin false if i args length usage error arg break good usage if global initialized global init shell context factory i proxy iproxy new i proxy i proxy eval inline script iproxy script text args i shell context factory call iproxy continue if arg equals w error reporter set is reporting warnings true continue if arg equals f process stdin false if i args length usage error arg break good usage file list add element args i equals null args i continue if arg equals sealedlib global set sealed std lib true continue usage error arg break good usage print usage message global get out println tool error reporter get message msg shell usage usage error system exit 1 return null processoptions usageerror goodusage startswith processstdin filelist addelement usageerror goodusage parseint numberformatexception usageerror goodusage isvalidlanguageversion usageerror goodusage shellcontextfactory setlanguageversion usageerror goodusage parseint numberformatexception usageerror goodusage isvalidoptimizationlevel usageerror goodusage shellcontextfactory setoptimizationlevel shellcontextfactory setstrictmode processstdin usageerror goodusage shellcontextfactory iproxy iproxy iproxy eval_inline_script scripttext shellcontextfactory errorreporter setisreportingwarnings processstdin usageerror goodusage filelist addelement setsealedstdlib usageerror goodusage getout toolerrorreporter getmessage usageerror private static void init java policy security support throwable ex obj try class cl class for name org mozilla javascript tools shell java policy security security impl security proxy cl new instance security controller init global security impl return catch class not found exception ex ex obj ex catch illegal access exception ex ex obj ex catch instantiation exception ex ex obj ex catch linkage error ex ex obj ex throw kit init cause new illegal state exception can not load security support ex obj ex obj initjavapolicysecuritysupport exobj forname javapolicysecurity securityimpl securityproxy newinstance securitycontroller initglobal securityimpl classnotfoundexception exobj illegalaccessexception exobj instantiationexception exobj linkageerror exobj initcause illegalstateexception exobj exobj evaluate java script source param cx the current context param filename the name of the file to compile or null for interactive mode public static void process source context cx string filename if filename null filename equals print stream ps global get err if filename null print implementation version ps println cx get implementation version use the interpreter for interactive input cx set optimization level 1 buffered reader in new buffered reader new input stream reader global get in int lineno 1 boolean hiteof false while hiteof int startline lineno if filename null ps print js ps flush string source collect lines of source to compile while true string newline try newline in read line catch io exception ioe ps println ioe to string break if newline null hiteof true break source source newline n lineno if cx string is compilable unit source break script script load script from source cx source stdin lineno null if script null object result evaluate script script cx global if result context get undefined value try ps println context to string result catch rhino exception rex tool error reporter report exception cx get error reporter rex native array h global history h put int h get length h source ps println else process file cx global filename system gc javascript processsource printstream geterr getimplementationversion setoptimizationlevel bufferedreader bufferedreader inputstreamreader getin readline ioexception tostring stringiscompilableunit loadscriptfromsource evaluatescript getundefinedvalue tostring rhinoexception toolerrorreporter reportexception geterrorreporter nativearray getlength processfile public static void process file context cx scriptable scope string filename if security impl null process file secure cx scope filename null else security impl call process file secure cx scope filename processfile securityimpl processfilesecure securityimpl callprocessfilesecure static void process file secure context cx scriptable scope string path object security domain script script if path ends with class script load compiled script cx path security domain else string source string read file or url path true if source null exit code exitcode file not found return support the executable script syntax if the first line begins with a treat the whole line as a comment if source length 0 source char at 0 for int i 1 i source length i int c source char at i if c n c r source source substring i break script load script from source cx source path 1 security domain if script null evaluate script script cx scope processfilesecure securitydomain endswith loadcompiledscript securitydomain readfileorurl exitcode exitcode_file_not_found charat charat loadscriptfromsource securitydomain evaluatescript public static script load script from source context cx string script source string path int lineno object security domain try return cx compile string script source path lineno security domain catch evaluator exception ee already printed message exit code exitcode runtime error catch rhino exception rex tool error reporter report exception cx get error reporter rex exit code exitcode runtime error catch virtual machine error ex treat stack overflow and out of memory as runtime errors ex print stack trace string msg tool error reporter get message msg uncaughtjs exception ex to string exit code exitcode runtime error context report error msg return null loadscriptfromsource scriptsource securitydomain compilestring scriptsource securitydomain evaluatorexception exitcode exitcode_runtime_error rhinoexception toolerrorreporter reportexception geterrorreporter exitcode exitcode_runtime_error virtualmachineerror stackoverflow outofmemory printstacktrace toolerrorreporter getmessage uncaughtjsexception tostring exitcode exitcode_runtime_error reporterror private static script load compiled script context cx string path object security domain byte data byte read file or url path false if data null exit code exitcode file not found return null xxx for now extract class name of compiled script from path instead of parsing class bytes int name start path last index of if name start 0 name start 0 else name start int name end path last index of if name end name start does not exist in path name end 0 or it comes before name start name end path length string name path substring name start name end try generated class loader loader security controller create loader cx get application class loader security domain class clazz loader define class name data loader link class clazz if script class is assignable from clazz throw context report runtime error msg must implement script return script clazz new instance catch rhino exception rex tool error reporter report exception cx get error reporter rex exit code exitcode runtime error catch illegal access exception iaex exit code exitcode runtime error context report error iaex to string catch instantiation exception inex exit code exitcode runtime error context report error inex to string return null loadcompiledscript securitydomain readfileorurl exitcode exitcode_file_not_found namestart lastindexof namestart namestart namestart nameend lastindexof nameend namestart nameend namestart nameend namestart nameend generatedclassloader securitycontroller createloader getapplicationclassloader securitydomain defineclass linkclass isassignablefrom reportruntimeerror newinstance rhinoexception toolerrorreporter reportexception geterrorreporter exitcode exitcode_runtime_error illegalaccessexception exitcode exitcode_runtime_error reporterror tostring instantiationexception exitcode exitcode_runtime_error reporterror tostring public static object evaluate script script script context cx scriptable scope try return script exec cx scope catch rhino exception rex tool error reporter report exception cx get error reporter rex exit code exitcode runtime error catch virtual machine error ex treat stack overflow and out of memory as runtime errors ex print stack trace string msg tool error reporter get message msg uncaughtjs exception ex to string exit code exitcode runtime error context report error msg return context get undefined value evaluatescript rhinoexception toolerrorreporter reportexception geterrorreporter exitcode exitcode_runtime_error virtualmachineerror stackoverflow outofmemory printstacktrace toolerrorreporter getmessage uncaughtjsexception tostring exitcode exitcode_runtime_error reporterror getundefinedvalue public static input stream get in return get global get in inputstream getin getglobal getin public static void set in input stream in get global set in in setin inputstream getglobal setin public static print stream get out return get global get out printstream getout getglobal getout public static void set out print stream out get global set out out setout printstream getglobal setout public static print stream get err return get global get err printstream geterr getglobal geterr public static void set err print stream err get global set err err seterr printstream getglobal seterr read file or url specified by tt path tt return file or url content as tt byte tt or as tt string tt if tt convert to string tt is true private static object read file or url string path boolean convert to string url url null assume path is url if it contains dot and there are at least 2 characters in the protocol part the later allows under windows to interpret paths with driver letter as file not url if path index of 2 try url new url path catch malformedurl exception ex input stream is null int capacity hint 0 if url null file file new file path capacity hint int file length try is new file input stream file catch io exception ex context report error tool error reporter get message msg couldnt open path return null else try url connection uc url open connection is uc get input stream capacity hint uc get content length ignore insane values for content length if capacity hint 1 20 capacity hint 1 catch io exception ex context report error tool error reporter get message msg couldnt open url url to string ex to string return null if capacity hint 0 capacity hint 4096 byte data try try data kit read stream is capacity hint finally is close catch io exception ex context report error ex to string return null object result if convert to string result data else convert to string using the default encoding xxx use charset argument of content type if url result new string data return result converttostring readfileorurl converttostring indexof malformedurlexception inputstream capacityhint capacityhint fileinputstream ioexception reporterror toolerrorreporter getmessage urlconnection openconnection getinputstream capacityhint getcontentlength capacityhint capacityhint ioexception reporterror toolerrorreporter getmessage tostring tostring capacityhint capacityhint readstream capacityhint ioexception reporterror tostring converttostring public class exception 001 extends live connect test public exception 001 super exception_001 liveconnecttest exception_001 public static void main string args exception 001 test new exception 001 test start exception_001 exception_001 public void execute test string result no exception thrown try the following statement should throw a java script exception since foo is not defined global eval foo bar 999 catch exception e if e instanceof js exception result js exception thrown else result some random exception thrown file exception e to string e print stack trace finally add test case global eval foo bar 999 should throw a java script exception js exception thrown result file exception executetest javascript jsexception jsexception tostring printstacktrace addtestcase javascript jsexception public class datatypes 006 extends live connect test public datatypes 006 super datatypes_006 liveconnecttest datatypes_006 public static void main string args datatypes 006 test new datatypes 006 test start datatypes_006 datatypes_006 public void execute test do method tests dt get boolean object java lang boolean object new boolean data type class pub static final boolean do method tests dt get boolean java lang boolean object new boolean data type class pub static final boolean do method tests dt get byte java lang double object new double data type class pub static final byte do method tests dt get byte object java lang byte object new byte data type class pub static final byte do method tests dt get short java lang double object new double data type class pub static final short do method tests dt get short object java lang short object new short data type class pub static final short do method tests dt get integer java lang double object new double data type class pub static final int do method tests dt get integer object java lang integer object new integer data type class pub static final int do method tests dt get long java lang double object new double data type class pub static final long do method tests dt get long object java lang long object new long data type class pub static final long do method tests dt get float java lang double object new double data type class pub static final float do method tests dt get float object java lang float object new float data type class pub static final float do method tests dt get double java lang double object new double data type class pub static final double do method tests dt get double object java lang double object new double data type class pub static final double do method tests dt get char java lang double object new double data type class pub static final char do method tests dt get character java lang character object new character data type class pub static final char do method tests dt get string object java lang string object new string data type class pub static final string executetest domethodtests getbooleanobject datatypeclass pub_static_final_boolean domethodtests getboolean datatypeclass pub_static_final_boolean domethodtests getbyte datatypeclass pub_static_final_byte domethodtests getbyteobject datatypeclass pub_static_final_byte domethodtests getshort datatypeclass pub_static_final_short domethodtests getshortobject datatypeclass pub_static_final_short domethodtests getinteger datatypeclass pub_static_final_int domethodtests getintegerobject datatypeclass pub_static_final_int domethodtests getlong datatypeclass pub_static_final_long domethodtests getlongobject datatypeclass pub_static_final_long domethodtests getfloat datatypeclass pub_static_final_float domethodtests getfloatobject datatypeclass pub_static_final_float domethodtests getdouble datatypeclass pub_static_final_double domethodtests getdoubleobject datatypeclass pub_static_final_double domethodtests getchar datatypeclass pub_static_final_char domethodtests getcharacter datatypeclass pub_static_final_char domethodtests getstringobject datatypeclass pub_static_final_string public void setup test environment super setup test environment global eval var dt packages com netscape javascript qa liveconnect data type class global eval var dt new dt setuptestenvironment setuptestenvironment datatypeclass public void do method tests string method string class name object value get public method method class name value domethodtests classname getpublicmethod classname set the value of a java script variable to a java value get the value of that variable public void get public method string method string class name object value string description method string exception null object actual null string expect null check the class try actual global eval method expect class for name class name get name catch class not found exception e catch exception e exception e to string might want to do all the interesting stuff here in a try catch block add test case description get class expect actual get class get name exception add test case description value to string true actual equals value exception add test case actual to string equals value to string true actual to string equals value to string exception javascript getpublicmethod classname forname classname getname classnotfoundexception tostring addtestcase getclass getclass getname addtestcase tostring addtestcase tostring tostring tostring tostring try to set the value of a public static field using js object set member which should succeed public void set public field string field string class name object value string description field string exception null object before null object after null string expect null object new value class name equals java lang double new double 0 class name equals java lang boolean new boolean false object new string new value try before global eval description need to quote strings if class name equals java lang string global eval description new value to string else global eval description new value after global eval description expect class for name class name get name catch exception e exception e to string add test case global eval description new value to string after global eval description after get class get name expect after get class get name exception add test case after to string equals new value to string true after equals new value exception add test case after to string equals new value to string true after to string equals new value to string exception assign a value to a public static final java field the assignment should fail the value should not change but there should be no error message public void set public field string field string class name object value string description field string exception null object before null object after null string expect null object new value class name equals java lang double new double 0 class name equals java lang boolean new boolean false object new string new value try expect class for name class name get name catch exception e exception e to string before global eval description global eval description new value to string after global eval description check the class of the result which should be the same as expect add test case description get class expect after get class get name exception the value of the actual result should be the original value add test case description value to string true after equals value exception the string representation of the actual result should be the same as the string representation of the expected value add test case after to string equals value to string true after to string equals value to string exception get member field should return the same value before and after the assignment add test case before equals after true before equals after exception jsobject setmember setpublicfield classname newvalue classname classname classname newvalue tostring newvalue forname classname getname tostring addtestcase newvalue tostring getclass getname getclass getname addtestcase tostring newvalue tostring newvalue addtestcase tostring newvalue tostring tostring newvalue tostring setpublicfield classname newvalue classname classname forname classname getname tostring newvalue tostring addtestcase getclass getclass getname addtestcase tostring addtestcase tostring tostring tostring tostring getmember addtestcase annotation list v new vector annotationlist void add xml x script annotation n v add n xscriptannotation xml x script annotation item int index return xml x script annotation v get index xscriptannotation xscriptannotation void remove int index v remove index int length return v size xml list xml lib impl lib super lib lib xml list prototype annos new annotation list xmllist xmllibimpl xmllistprototype _annos annotationlist param input object xml list xml lib impl lib object input object super lib lib xml list prototype string frag if input object null input object instanceof undefined frag else if input object instanceof xml xml xml xml input object annos new annotation list annos add xml get annotation else if input object instanceof xml list xml list xmll xml list input object annos new annotation list for int i 0 i xmll annos length i annos add xmll annos item i else frag script runtime to string input object trim if frag starts with frag frag frag fragment frag substring 2 if frag ends with throw script runtime type error xml with anonymous tag missing end anonymous tag frag frag substring 0 frag length 3 fragment xml orgxml xml create fromjs lib frag now orphan the children and add them to our xml list xml list children xml list orgxml children annos new annotation list for int i 0 i children annos length i copy here is so that they ll be orphaned parent will be undefined annos add xml children item i copy get annotation inputobject xmllist xmllibimpl inputobject xmllistprototype inputobject inputobject inputobject inputobject _annos annotationlist _annos getannotation inputobject xmllist xmllist xmllist inputobject _annos annotationlist _annos _annos _annos scriptruntime tostring inputobject startswith endswith scriptruntime typeerror createfromjs xmllist xmllist xmllist _annos annotationlist _annos _annos getannotation param object param property void set targets xml object impl object javax xml namespace q name property target object object target property property settargets xmlobjectimpl qname targetobject targetproperty param index return xml get xml from annotation int index xml ret val if index 0 index length xml x script annotation anno annos item index ret val xml get from annotation lib anno else ret val null return ret val getxmlfromannotation retval xscriptannotation _annos retval getfromannotation retval retval param index private void internal remove from list int index annos remove index internalremovefromlist _annos param index param xml void replace int index xml xml if index length annotation list new anno list new annotation list copy upto item to replace for int i 0 i index i new anno list add annos item i new anno list add xml get annotation skip over old item we re going to replace we ve already add new item on above line for int i index 1 i length i new anno list add annos item i annos new anno list annotationlist newannolist annotationlist newannolist _annos newannolist getannotation newannolist _annos _annos newannolist param index param xml private void insert int index xml xml if index length annotation list new anno list new annotation list copy upto item to insert for int i 0 i index i new anno list add annos item i new anno list add xml get annotation for int i index i length i new anno list add annos item i annos new anno list annotationlist newannolist annotationlist newannolist _annos newannolist getannotation newannolist _annos _annos newannolist public string get class name return xml list getclassname xmllist param index param start return public object get int index scriptable start log get index index if index 0 index length return get xml from annotation index else return scriptable not found getxmlfromannotation not_found param name param start return boolean hasxml property xml name xml name boolean result false has now should return true if the property would have results 0 or if it s a method name string name xml name local name if get property list xml name length 0 get method name not found result true return result hasxmlproperty xmlname xmlname xmlname localname getpropertylist xmlname getmethod not_found param index param start return public boolean has int index scriptable start return 0 index index length param name param value void putxml property xml name xml name object value log put property name special case checks for undefined and null if value null value null else if value instanceof undefined value undefined if length 1 throw script runtime type error assignment to lists with more that one item is not supported else if length 0 secret sauce for super expandos we set an element here and then add ourselves to our target if target object null target property null target property get local part equals add an empty element with our target property name and then set it xml xml value xml create text element lib target property add to list xml value if xml name is attribute name set attribute xml name value else xml xml xml item 0 xml putxml property xml name value update the list with the new item at location 0 replace 0 xml item 0 now add us to our parent xml name name2 xml name form property target property get namespaceuri target property get local part target object putxml property name2 this else throw script runtime type error assignment to empty xml list without targets not supported else if xml name is attribute name set attribute xml name value else xml xml xml item 0 xml putxml property xml name value update the list with the new item at location 0 replace 0 xml item 0 putxmlproperty xmlname xmlname scriptruntime typeerror targetobject targetproperty targetproperty getlocalpart targetproperty xmlvalue createtextelement targetproperty addtolist xmlvalue xmlname isattributename setattribute xmlname putxmlproperty xmlname xmlname xmlname formproperty targetproperty getnamespaceuri targetproperty getlocalpart targetobject putxmlproperty scriptruntime typeerror xmllist xmlname isattributename setattribute xmlname putxmlproperty xmlname param name return object getxml property xml name name return get property list name getxmlproperty xmlname getpropertylist param index param value public void put int index scriptable start object value object parent undefined instance convert text into xml if needed xml object xml value special case checks for undefined and null if value null value null else if value instanceof undefined value undefined if value instanceof xml object xml value xml object value else if target property null xml value xml create fromjs lib value to string else xml value xml create text element lib target property value to string find the parent if index length parent item index parent else appending parent parent if parent instanceof xml found parent alter doc xml xml parent xml parent if index length we re replacing the the node xml xml node get xml from annotation index if xml value instanceof xml xml node replace all xml xml value replace index xml node else if xml value instanceof xml list replace the first one and add the rest on the list xml list list xml list xml value if list length 0 int last index added xml node child index xml node replace all xml list item 0 replace index xml list item 0 for int i 1 i list length i xml parent insert child after xml parent get xml child last index added list item i last index added insert index i xml list item i else appending xml parent append child xml value add to list xml parent get xml child index else don t all have same parent no underlying doc to alter if index length xml xml node xml get from annotation lib annos item index if xml value instanceof xml xml node replace all xml xml value replace index xml node else if xml value instanceof xml list replace the first one and add the rest on the list xml list list xml list xml value if list length 0 xml node replace all xml list item 0 replace index xml list item 0 for int i 1 i list length i insert index i xml list item i else add to list xml value xmlobject xmlvalue xmlobject xmlvalue xmlobject targetproperty xmlvalue createfromjs tostring xmlvalue createtextelement targetproperty tostring xmlparent xmlnode getxmlfromannotation xmlvalue xmlnode replaceall xmlvalue xmlnode xmlvalue xmllist xmllist xmllist xmlvalue lastindexadded xmlnode childindex xmlnode replaceall xmlparent insertchildafter xmlparent getxmlchild lastindexadded lastindexadded xmlparent appendchild xmlvalue addtolist xmlparent getxmlchild xmlnode getfromannotation _annos xmlvalue xmlnode replaceall xmlvalue xmlnode xm