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 xmlvalue xmllist xmllist xmllist xmlvalue xmlnode replaceall addtolist xmlvalue param name void deletexml property xml name name for int i 0 i length i xml xml get xml from annotation i if xml token type xml cursor token type start xml deletexml property name deletexmlproperty xmlname getxmlfromannotation tokentype xmlcursor tokentype deletexmlproperty param index public void delete int index if index 0 index length xml xml get xml from annotation index xml remove internal remove from list index getxmlfromannotation internalremovefromlist return public object get ids object enum objs if prototype flag enum objs new object 0 else enum objs new object length for int i 0 i enum objs length i enum objs i new integer i return enum objs getids enumobjs prototypeflag enumobjs enumobjs enumobjs enumobjs enumobjs return public object get ids for debug return get ids getidsfordebug getids xml list will remove will delete all items in the list a set delete this differs from the xml list delete operator void remove int n len length for int i n len 1 i 0 i xml xml get xml from annotation i if xml null xml remove internal remove from list i xmllist xmllist nlen nlen getxmlfromannotation internalremovefromlist param index return xml item int index return annos null get xml from annotation index xml create emptyxml lib _annos getxmlfromannotation createemptyxml param name param value private void set attribute xml name xml name object value for int i 0 i length i xml xml get xml from annotation i xml set attribute xml name value setattribute xmlname xmlname getxmlfromannotation setattribute xmlname param to add void add to list object to add if to add instanceof undefined missing argument do nothing return if to add instanceof xml list xml list xml src xml list to add for int i 0 i xml src length i annos add xml xml src item i get annotation else if to add instanceof xml annos add xml to add get annotation else if to add instanceof xml x script annotation annos add xml x script annotation to add toadd addtolist toadd toadd toadd xmllist xmllist xmlsrc xmllist toadd xmlsrc _annos xmlsrc getannotation toadd _annos toadd getannotation toadd xscriptannotation _annos xscriptannotation toadd param to add xml add namespace namespace ns if length 1 return get xml from annotation 0 add namespace ns else throw script runtime type error the add namespace method works only on lists containing one item toadd addnamespace getxmlfromannotation addnamespace scriptruntime typeerror addnamespace param xml return xml append child object xml if length 1 return get xml from annotation 0 append child xml else throw script runtime type error the append child method works only on lists containing one item appendchild getxmlfromannotation appendchild scriptruntime typeerror appendchild param attr return xml list attribute xml name xml name xml list result new xml list lib for int i 0 i length i xml xml get xml from annotation i result add to list xml attribute xml name return result xmllist xmlname xmlname xmllist xmllist getxmlfromannotation addtolist xmlname return xml list attributes xml list result new xml list lib for int i 0 i length i xml xml get xml from annotation i result add to list xml attributes return result xmllist xmllist xmllist getxmlfromannotation addtolist xml list child long index xml list result new xml list lib for int i 0 i length i result add to list get xml from annotation i child index return result xmllist xmllist xmllist addtolist getxmlfromannotation xml list child xml name xml name xml list result new xml list lib for int i 0 i length i result add to list get xml from annotation i child xml name return result xmllist xmlname xmlname xmllist xmllist addtolist getxmlfromannotation xmlname return int child index if length 1 return get xml from annotation 0 child index else throw script runtime type error the child index method works only on lists containing one item childindex getxmlfromannotation childindex scriptruntime typeerror childindex return xml list children vector v new vector for int i 0 i length i xml xml get xml from annotation i if xml null object o xml children if o instanceof xml list xml list child list xml list o int c children child list length for int j 0 j c children j v add element child list item j xml list all children new xml list lib int sz v size for int i 0 i sz i all children add to list v get i return all children xmllist getxmlfromannotation xmllist xmllist childlist xmllist cchildren childlist cchildren addelement childlist xmllist allchildren xmllist allchildren addtolist allchildren return xml list comments xml list result new xml list lib for int i 0 i length i xml xml get xml from annotation i result add to list xml comments return result xmllist xmllist xmllist getxmlfromannotation addtolist param xml return boolean contains object xml boolean result false for int i 0 i length i xml member get xml from annotation i if member equivalent xml xml result true break return result getxmlfromannotation equivalentxml return object copy xml list result new xml list lib for int i 0 i length i xml xml get xml from annotation i result add to list xml copy return result xmllist xmllist getxmlfromannotation addtolist return xml list descendants xml name xml name xml list result new xml list lib for int i 0 i length i xml xml get xml from annotation i result add to list xml descendants xml name return result xmllist xmlname xmlname xmllist xmllist getxmlfromannotation addtolist xmlname return object in scope namespaces if length 1 return get xml from annotation 0 in scope namespaces else throw script runtime type error the in scope namespaces method works only on lists containing one item inscopenamespaces getxmlfromannotation inscopenamespaces scriptruntime typeerror inscopenamespaces param child param xml xml insert child after object child object xml if length 1 return get xml from annotation 0 insert child after child xml else throw script runtime type error the insert child after method works only on lists containing one item insertchildafter getxmlfromannotation insertchildafter scriptruntime typeerror insertchildafter param child param xml xml insert child before object child object xml if length 1 return get xml from annotation 0 insert child after child xml else throw script runtime type error the insert child before method works only on lists containing one item insertchildbefore getxmlfromannotation insertchildafter scriptruntime typeerror insertchildbefore return boolean has own property xml name xml name boolean has property false if prototype flag string property xml name local name has property 0 find prototype id property else has property get property list xml name length 0 return has property hasownproperty xmlname xmlname hasproperty prototypeflag xmlname localname hasproperty findprototypeid hasproperty getpropertylist xmlname hasproperty return boolean has complex content boolean complex content int length length if length 0 complex content false else if length 1 complex content get xml from annotation 0 has complex content else complex content false for int i 0 i length i xml next element get xml from annotation i if next element token type xml cursor token type start complex content true break return complex content hascomplexcontent complexcontent complexcontent complexcontent getxmlfromannotation hascomplexcontent complexcontent nextelement getxmlfromannotation nextelement tokentype xmlcursor tokentype complexcontent complexcontent return boolean has simple content boolean simple content int length length if length 0 simple content true else if length 1 simple content get xml from annotation 0 has simple content else simple content true for int i 0 i length i xml next element get xml from annotation i if next element token type xml cursor token type start simple content false break return simple content hassimplecontent simplecontent simplecontent simplecontent getxmlfromannotation hassimplecontent simplecontent nextelement getxmlfromannotation nextelement tokentype xmlcursor tokentype simplecontent simplecontent return int length int result 0 if annos null result annos length return result _annos _annos return string local name if length 1 return name local name else throw script runtime type error the local name method works only on lists containing one item localname localname scriptruntime typeerror localname return q name name if length 1 return get xml from annotation 0 name else throw script runtime type error the name method works only on lists containing one item qname getxmlfromannotation scriptruntime typeerror param prefix return object namespace string prefix if length 1 return get xml from annotation 0 namespace prefix else throw script runtime type error the namespace method works only on lists containing one item getxmlfromannotation scriptruntime typeerror return object namespace declarations if length 1 return get xml from annotation 0 namespace declarations else throw script runtime type error the namespace declarations method works only on lists containing one item namespacedeclarations getxmlfromannotation namespacedeclarations scriptruntime typeerror namespacedeclarations return object node kind if length 1 return get xml from annotation 0 node kind else throw script runtime type error the node kind method works only on lists containing one item nodekind getxmlfromannotation nodekind scriptruntime typeerror nodekind void normalize for int i 0 i length i get xml from annotation i normalize getxmlfromannotation if list is empty return undefined if elements have different parents return undefined if they all have the same parent return that parent return object parent object same parent undefined instance if length 0 target object null target object instanceof xml same parent target object else for int i 0 i length i object curr parent get xml from annotation i parent if i 0 set the first for the rest to compare to same parent curr parent else if same parent curr parent same parent undefined instance break if everything in the list is the same parent then return that as the parent return same parent sameparent targetobject targetobject sameparent targetobject currparent getxmlfromannotation sameparent currparent sameparent currparent sameparent sameparent sameparent param xml return xml prepend child object xml if length 1 return get xml from annotation 0 prepend child xml else throw script runtime type error the prepend child method works only on lists containing one item prependchild getxmlfromannotation prependchild scriptruntime typeerror prependchild return object processing instructions xml name xml name xml list result new xml list lib for int i 0 i length i xml xml get xml from annotation i result add to list xml processing instructions xml name return result processinginstructions xmlname xmlname xmllist xmllist getxmlfromannotation addtolist processinginstructions xmlname param name return boolean property is enumerable object name long index if name instanceof integer index integer name int value else if name instanceof number double x number name double value index long x if double index x return false if index 0 1 0 x 0 negative 0 return false else string s script runtime to string name index script runtime test uint32 string s return 0 index index length propertyisenumerable intvalue doublevalue scriptruntime tostring scriptruntime testuint32string param ns xml remove namespace namespace ns if length 1 return get xml from annotation 0 remove namespace ns else throw script runtime type error the remove namespace method works only on lists containing one item removenamespace getxmlfromannotation removenamespace scriptruntime typeerror removenamespace xml replace long index object xml if length 1 return get xml from annotation 0 replace index xml else throw script runtime type error the replace method works only on lists containing one item getxmlfromannotation scriptruntime typeerror param property name param xml return xml replace xml name xml name object xml if length 1 return get xml from annotation 0 replace xml name xml else throw script runtime type error the replace method works only on lists containing one item propertyname xmlname xmlname getxmlfromannotation xmlname scriptruntime typeerror param xml xml set children object xml if length 1 return get xml from annotation 0 set children xml else throw script runtime type error the set children method works only on lists containing one item setchildren getxmlfromannotation setchildren scriptruntime typeerror setchildren param name void set local name string local name if length 1 get xml from annotation 0 set local name local name else throw script runtime type error the set local name method works only on lists containing one item setlocalname localname getxmlfromannotation setlocalname localname scriptruntime typeerror setlocalname param name void set name q name qname if length 1 get xml from annotation 0 set name qname else throw script runtime type error the set name method works only on lists containing one item setname qname getxmlfromannotation setname scriptruntime typeerror setname param ns void set namespace namespace ns if length 1 get xml from annotation 0 set namespace ns else throw script runtime type error the set namespace method works only on lists containing one item setnamespace getxmlfromannotation setnamespace scriptruntime typeerror setnamespace return xml list text xml list result new xml list lib for int i 0 i length i result add to list get xml from annotation i text return result xmllist xmllist xmllist addtolist getxmlfromannotation return public string to string if has simple content string buffer sb new string buffer for int i 0 i length i xml next get xml from annotation i sb append next to string return sb to string else return toxml string 0 tostring hassimplecontent stringbuffer stringbuffer getxmlfromannotation tostring tostring toxmlstring string to source int indent xxx indent is ignored return toxml string 0 tosource toxmlstring return string toxml string int indent string buffer sb new string buffer for int i 0 i length i if i 0 sb append n sb append get xml from annotation i toxml string indent return sb to string toxmlstring stringbuffer stringbuffer getxmlfromannotation toxmlstring tostring return object value of return this valueof param target return boolean equivalent xml object target boolean result false zero length list should equate to undefined if target instanceof undefined length 0 result true else if length 1 result get xml from annotation 0 equivalent xml target else if target instanceof xml list xml list other list xml list target if other list length length result true for int i 0 i length i if get xml from annotation i equivalent xml other list get xml from annotation i result false break return result equivalentxml getxmlfromannotation equivalentxml xmllist xmllist otherlist xmllist otherlist getxmlfromannotation equivalentxml otherlist getxmlfromannotation param name param start return private xml list get property list xml name name xml list property list new xml list lib javax xml namespace q name qname null if name is descendants name is attribute name only set the target property if this is a regular child get and not a descendant or attribute get qname new javax xml namespace q name name uri name local name property list set targets this qname for int i 0 i length i property list add to list get xml from annotation i get property list name return property list xmllist getpropertylist xmlname xmllist propertylist xmllist qname isdescendants isattributename targetproperty qname localname propertylist settargets propertylist addtolist getxmlfromannotation getpropertylist propertylist private object apply or call boolean is apply context cx scriptable scope scriptable this obj object args string method name is apply apply call if this obj instanceof xml list xml list this obj target property null throw script runtime type error1 msg isnt function method name return script runtime apply or call is apply cx scope this obj args applyorcall isapply thisobj methodname isapply thisobj xmllist xmllist thisobj targetproperty scriptruntime typeerror1 methodname scriptruntime applyorcall isapply thisobj protected object js constructor context cx boolean in new expr object args if args length 0 return new xml list lib else object arg0 args 0 if in new expr arg0 instanceof xml list xml list xml list returns the same object return arg0 return new xml list lib arg0 jsconstructor innewexpr xmllist innewexpr xmllist xmllist xmllist xmllist org apache xmlbeans xml object get xml object if length 1 return get xml from annotation 0 get xml object else throw script runtime type error get xml object method works only on lists containing one item xmlobject getxmlobject getxmlfromannotation getxmlobject scriptruntime typeerror getxmlobject see ecma 357 11 2 2 1 semantics 3 e public scriptable get extra method source context cx if length 1 return get xml from annotation 0 return null 11_2_2_1 3_e getextramethodsource getxmlfromannotation public object call context cx scriptable scope scriptable this obj object args this xml list is being called as a function let s find the real function object if target property null throw script runtime not function error this string method name target property get local part boolean is apply method name equals apply if is apply method name equals call return apply or call is apply cx scope this obj args callable method script runtime get elem function and this this method name cx call last stored scriptable to clear stored this obj but ignore the result as the method should use the supplied this obj not one from redirected call script runtime last stored scriptable cx return method call cx scope this obj args thisobj xmllist targetproperty scriptruntime notfunctionerror methodname targetproperty getlocalpart isapply methodname isapply methodname applyorcall isapply thisobj scriptruntime getelemfunctionandthis methodname laststoredscriptable thisobj thisobj scriptruntime laststoredscriptable thisobj public scriptable construct context cx scriptable scope object args throw script runtime type error1 msg not ctor xml list scriptruntime typeerror1 xmllist data flow bit set int size its size size its bits new int size 31 5 dataflowbitset itssize itsbits void set int n if 0 n n its size bad index n its bits n 5 1 n 31 itssize badindex itsbits boolean test int n if 0 n n its size bad index n return its bits n 5 1 n 31 0 itssize badindex itsbits void not int bits length its bits length for int i 0 i bits length i its bits i its bits i bitslength itsbits bitslength itsbits itsbits void clear int n if 0 n n its size bad index n its bits n 5 1 n 31 itssize badindex itsbits void clear int bits length its bits length for int i 0 i bits length i its bits i 0 bitslength itsbits bitslength itsbits void or data flow bit set b int bits length its bits length for int i 0 i bits length i its bits i b its bits i dataflowbitset bitslength itsbits bitslength itsbits itsbits public string to string string buffer sb new string buffer sb append data flow bit set size sb append its size sb append n int bits length its bits length for int i 0 i bits length i sb append integer to hex string its bits i sb append return sb to string tostring stringbuffer stringbuffer dataflowbitset itssize bitslength itsbits bitslength tohexstring itsbits tostring boolean df data flow bit set in data flow bit set gen data flow bit set not kill int bits length its bits length boolean changed false for int i 0 i bits length i int old bits its bits i its bits i in its bits i gen its bits i not kill its bits i changed old bits its bits i return changed dataflowbitset dataflowbitset dataflowbitset notkill bitslength itsbits bitslength oldbits itsbits itsbits itsbits itsbits notkill itsbits oldbits itsbits boolean df2 data flow bit set in data flow bit set gen data flow bit set not kill int bits length its bits length boolean changed false for int i 0 i bits length i int old bits its bits i its bits i in its bits i not kill its bits i gen its bits i changed old bits its bits i return changed dataflowbitset dataflowbitset dataflowbitset notkill bitslength itsbits bitslength oldbits itsbits itsbits itsbits notkill itsbits itsbits oldbits itsbits private void bad index int n throw new runtime exception data flow bit set bad index n badindex runtimeexception dataflowbitset public object wrap context cx scriptable scope object obj class static type if obj instanceof string obj instanceof number obj instanceof boolean return obj else if obj instanceof character char a character obj char value return new string a return super wrap cx scope obj static type statictype charvalue statictype the method must not be public or protected static security controller global return global securitycontroller check if global link security controller was already installed see init global security controller controller public static boolean has global return global null securitycontroller initglobal securitycontroller hasglobal initialize global controller that will be used for all security related operations the global controller takes precedence over already installed link context specific controllers and cause any subsequent call to link context set security controller security controller to throw an exception p the method can only be called once see has global public static void init global security controller controller if controller null throw new illegal argument exception if global null throw new security exception cannot overwrite already installed global security controller global controller setsecuritycontroller securitycontroller hasglobal initglobal securitycontroller illegalargumentexception securityexception securitycontroller get class loader like object that can be used to define classes with the given security context param parent loader parent class loader to delegate search for classes not defined by the class loader itself param security domain some object specifying the security context of the code that is defined by the returned class loader public abstract generated class loader create class loader parentloader securitydomain generatedclassloader createclassloader create link generated class loader with restrictions imposed by static domain and all current stack frames the method uses the security controller instance associated with the current link context to construct proper dynamic domain and create corresponding class loader par if no security controller is associated with the current link context the method calls link context create class loader class loader parent param parent parent class loader if null link context get application class loader will be used param static domain static security domain public static generated class loader create loader class loader parent object static domain context cx context get context if parent null parent cx get application class loader security controller sc cx get security controller generated class loader loader if sc null loader cx create class loader parent else object dynamic domain sc get dynamic security domain static domain loader sc create class loader parent dynamic domain return loader generatedclassloader staticdomain securitycontroller securitycontroller createclassloader classloader getapplicationclassloader staticdomain generatedclassloader createloader classloader staticdomain getcontext getapplicationclassloader securitycontroller getsecuritycontroller generatedclassloader createclassloader dynamicdomain getdynamicsecuritydomain staticdomain createclassloader dynamicdomain get dynamic security domain that allows an action only if it is allowed by the current java stack and i security domain i if i security domain i is null return domain representing permissions allowed by the current stack securitydomain securitydomain call link callable call context cx scriptable scope scriptable this obj object args of i callable i under restricted security domain where an action is allowed only if it is allowed according to the java stack on the moment of the i exec with domain i call and i security domain i any call to link get dynamic security domain object during execution of tt callable call cx scope this obj args tt should return a domain incorporate restrictions imposed by i security domain i and java stack on the moment of call with domain invocation p the method should always be overridden it is not declared abstract for compatibility reasons public object call with domain object security domain context cx final callable callable scriptable scope final scriptable this obj final object args return exec with domain cx scope new script public object exec context cx scriptable scope return callable call cx scope this obj args security domain thisobj execwithdomain securitydomain getdynamicsecuritydomain thisobj securitydomain callwithdomain callwithdomain securitydomain thisobj execwithdomain thisobj securitydomain return exec with domain cx scope new script public object exec context cx scriptable scope return callable call cx scope this obj args execwithdomain thisobj deprecated the application should not override this method and instead override link call with domain object security domain context cx callable callable scriptable scope scriptable this obj object args public object exec with domain context cx scriptable scope script script object security domain throw new illegal state exception call with domain should be overridden callwithdomain securitydomain thisobj execwithdomain securitydomain illegalstateexception callwithdomain follows the art of computer programming by donald e knuth public uint map this 4 uintmap public uint map int initial capacity if initial capacity 0 kit code bug table grow when number of stored keys 3 4 of max capacity int minimal capacity initial capacity 4 3 int i for i 2 1 i minimal capacity i power i if check power 2 kit code bug uintmap initialcapacity initialcapacity codebug minimalcapacity initialcapacity minimalcapacity codebug public boolean is empty return key count 0 isempty keycount public int size return key count keycount public boolean has int key if key 0 kit code bug return 0 find index key codebug findindex get object value assigned with key return key object value or null if key is absent public object get object int key if key 0 kit code bug if values null int index find index key if 0 index return values index return null getobject codebug findindex get integer value assigned with key return key integer value or default value if key is absent public int get int int key int default value if key 0 kit code bug int index find index key if 0 index if ivalues shift 0 return keys ivalues shift index return 0 return default value defaultvalue getint defaultvalue codebug findindex ivaluesshift ivaluesshift defaultvalue get integer value assigned with key return key integer value or default value if key does not exist or does not have int value throws runtime exception if key does not exist public int get existing int int key if key 0 kit code bug int index find index key if 0 index if ivalues shift 0 return keys ivalues shift index return 0 key must exist kit code bug return 0 defaultvalue runtimeexception getexistingint codebug findindex ivaluesshift ivaluesshift codebug set object value of the key if key does not exist also set its int value to 0 public void put int key object value if key 0 kit code bug int index ensure index key false if values null values new object 1 power values index value codebug ensureindex set int value of the key if key does not exist also set its object value to null public void put int key int value if key 0 kit code bug int index ensure index key true if ivalues shift 0 int n 1 power keys length can be n 2 after clear which set ivalues shift to 0 if keys length n 2 int tmp new int n 2 system arraycopy keys 0 tmp 0 n keys tmp ivalues shift n keys ivalues shift index value codebug ensureindex ivaluesshift ivaluesshift ivaluesshift ivaluesshift public void remove int key if key 0 kit code bug int index find index key if 0 index keys index deleted key count allow to gc value and make sure that new key with the deleted slot shall get proper default values if values null values index null if ivalues shift 0 keys ivalues shift index 0 codebug findindex keycount ivaluesshift ivaluesshift public void clear int n 1 power if keys null for int i 0 i n i keys i empty if values null for int i 0 i n i values i null ivalues shift 0 key count 0 occupied count 0 ivaluesshift keycount occupiedcount return array of present keys public int get keys int keys this keys int n key count int result new int n for int i 0 n 0 i int entry keys i if entry empty entry deleted result n entry return result getkeys keycount private static int table lookup step int fraction int mask int power int shift 32 2 power if shift 0 return fraction shift mask 1 else return fraction mask shift 1 tablelookupstep private int find index int key int keys this keys if keys null int fraction key a int index fraction 32 power int entry keys index if entry key return index if entry empty search in table after first failed attempt int mask 1 power 1 int step table lookup step fraction mask power int n 0 do if check if n occupied count kit code bug n index index step mask entry keys index if entry key return index while entry empty return 1 findindex tablelookupstep occupiedcount codebug and enough free space private int insert new key int key if check occupied count key count kit code bug if check key count 1 power kit code bug int keys this keys int fraction key a int index fraction 32 power if keys index empty int mask 1 power 1 int step table lookup step fraction mask power int first index index do if check keys index deleted kit code bug index index step mask if check first index index kit code bug while keys index empty keys index key occupied count key count return index insertnewkey occupiedcount keycount codebug keycount codebug tablelookupstep firstindex codebug firstindex codebug occupiedcount keycount private void rehash table boolean ensure int space if keys null check if removing deleted entries would free enough space if key count 2 occupied count need to grow less then half of deleted entries power int n 1 power int old keys int old shift ivalues shift if old shift 0 ensure int space keys new int n else ivalues shift n keys new int n 2 for int i 0 i n i keys i empty object old values values if old values null values new object n int old count key count occupied count 0 if old count 0 key count 0 for int i 0 remaining old count remaining 0 i int key old i if key empty key deleted int index insert new key key if old values null values index old values i if old shift 0 keys ivalues shift index old old shift i remaining rehashtable ensureintspace keycount occupiedcount oldshift ivaluesshift oldshift ensureintspace ivaluesshift oldvalues oldvalues oldcount keycount occupiedcount oldcount keycount oldcount insertnewkey oldvalues oldvalues oldshift ivaluesshift oldshift ensure key index creating one if necessary private int ensure index int key boolean int type int index 1 int first deleted 1 int keys this keys if keys null int fraction key a index fraction 32 power int entry keys index if entry key return index if entry empty if entry deleted first deleted index search in table after first failed attempt int mask 1 power 1 int step table lookup step fraction mask power int n 0 do if check if n occupied count kit code bug n index index step mask entry keys index if entry key return index if entry deleted first deleted 0 first deleted index while entry empty inserting of new key if check keys null keys index empty kit code bug if first deleted 0 index first deleted else need to consume empty entry check occupation level if keys null occupied count 4 1 power 3 too litle unused entries rehash rehash table int type keys this keys return insert new key key occupied count keys index key key count return index ensureindex inttype firstdeleted firstdeleted tablelookupstep occupiedcount codebug firstdeleted firstdeleted codebug firstdeleted firstdeleted occupiedcount rehashtable inttype insertnewkey occupiedcount keycount private void write object object output stream out throws io exception out default write object int count key count if count 0 boolean has int values ivalues shift 0 boolean has object values values null out write boolean has int values out write boolean has object values for int i 0 count 0 i int key keys i if key empty key deleted count out write int key if has int values out write int keys ivalues shift i if has object values out write object values i writeobject objectoutputstream ioexception defaultwriteobject keycount hasintvalues ivaluesshift hasobjectvalues writeboolean hasintvalues writeboolean hasobjectvalues writeint hasintvalues writeint ivaluesshift hasobjectvalues writeobject private void read object object input stream in throws io exception class not found exception in default read object int written key count key count if written key count 0 key count 0 boolean has int values in read boolean boolean has object values in read boolean int n 1 power if has int values keys new int 2 n ivalues shift n else keys new int n for int i 0 i n i keys i empty if has object values values new object n for int i 0 i written key count i int key in read int int index insert new key key if has int values int ivalue in read int keys ivalues shift index ivalue if has object values values index in read object readobject objectinputstream ioexception classnotfoundexception defaultreadobject writtenkeycount keycount writtenkeycount keycount hasintvalues readboolean hasobjectvalues readboolean hasintvalues ivaluesshift hasobjectvalues writtenkeycount readint insertnewkey hasintvalues readint ivaluesshift hasobjectvalues readobject 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 public string ambiguous object arg return object public string ambiguous js object arg return jsobject jsobject scriptable output stream constructor creates a scriptable output stream for use in serializing java script objects calls exclude standard object names param out the output stream to write to param scope the scope containing the object public scriptable output stream output stream out scriptable scope throws io exception super out this scope scope table new hashtable 31 table put scope enable replace object true exclude standard object names scriptableoutputstream scriptableoutputstream javascript excludestandardobjectnames outputstream scriptableoutputstream outputstream ioexception enablereplaceobject excludestandardobjectnames adds a qualified name to the list of object to be excluded from serialization names excluded from serialization are looked up in the new scope and replaced upon deserialization param name a fully qualified name of the form a b c where a must be a property of the top level object the object need not exist in which case the name is ignored throws illegal argument exception if the object is not a link scriptable public void add optional excluded name string name object obj lookup qualified name scope name if obj null obj unique tag not found if obj instanceof scriptable throw new illegal argument exception object for excluded name name is not a scriptable it is obj get class get name table put obj name illegalargumentexception addoptionalexcludedname lookupqualifiedname uniquetag not_found illegalargumentexception getclass getname adds a qualified name to the list of object to be excluded from serialization names excluded from serialization are looked up in the new scope and replaced upon deserialization param name a fully qualified name of the form a b c where a must be a property of the top level object throws illegal argument exception if the object is not found or is not a link scriptable public void add excluded name string name object obj lookup qualified name scope name if obj instanceof scriptable throw new illegal argument exception object for excluded name name not found table put obj name illegalargumentexception addexcludedname lookupqualifiedname illegalargumentexception returns true if the name is excluded from serialization public boolean has excluded name string name return table get name null hasexcludedname removes a name from the list of names to exclude public void remove excluded name string name table remove name removeexcludedname adds the names of the standard objects and their prototypes to the list of excluded names public void exclude standard object names string names object object prototype function function prototype string string prototype math no math prototype array array prototype error error prototype number number prototype date date prototype reg exp reg exp prototype script script prototype continuation continuation prototype for int i 0 i names length i add excluded name names i string optional names xml xml prototype xml list xml list prototype for int i 0 i optional names length i add optional excluded name optional names i excludestandardobjectnames regexp regexp addexcludedname optionalnames xmllist xmllist optionalnames addoptionalexcludedname optionalnames static object lookup qualified name scriptable scope string qualified name string tokenizer st new string tokenizer qualified name object result scope while st has more tokens string s st next token result scriptable object get property scriptable result s if result null result instanceof scriptable break return result lookupqualifiedname qualifiedname stringtokenizer stringtokenizer qualifiedname hasmoretokens nexttoken scriptableobject getproperty static final long serial versionuid 2692990309789917727l pending lookup string name this name name serialversionuid pendinglookup pending lookup string name this name name string get name return name pendinglookup getname protected object replace object object obj throws io exception string name string table get obj if name null return obj return new pending lookup name replaceobject ioexception pendinglookup public static void init scriptable scope boolean sealed continuation obj new continuation obj export asjs class max prototype id scope sealed exportasjsclass max_prototype_id public object get implementation return implementation getimplementation public void init implementation object implementation this implementation implementation initimplementation public string get class name return continuation getclassname public scriptable construct context cx scriptable scope object args throw context report runtime error direct call is not supported reportruntimeerror public object call context cx scriptable scope scriptable this obj object args return interpreter restart continuation this cx scope args thisobj restartcontinuation public static boolean is continuation constructor id function object f if f has tag ftag f method id id constructor return true return false iscontinuationconstructor idfunctionobject hastag methodid id_constructor protected void init prototype id int id string s int arity switch id case id constructor arity 0 s constructor break default throw new illegal argument exception string value of id init prototype method ftag id s arity initprototypeid id_constructor illegalargumentexception valueof initprototypemethod public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag ftag return super exec id call f cx scope this obj args int id f method id switch id case id constructor throw context report runtime error direct call is not supported throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag execidcall thisobj methodid id_constructor reportruntimeerror illegalargumentexception valueof protected int find prototype id string s int id generated last update 2004 09 08 12 02 41 cest l0 id 0 string x null if s length 11 x constructor id id constructor if x null x s x equals s id 0 generated return id findprototypeid id_constructor private int offset public string get line terminator return line terminator getlineterminator lineterminator public string get line terminator return line terminator public void set line terminator string value line terminator value getlineterminator lineterminator setlineterminator lineterminator public void set line terminator string value line terminator value public int get indent step return indent step setlineterminator lineterminator getindentstep indentstep public int get indent step return indent step public void set indent step int char count indent step char count getindentstep indentstep setindentstep char_count indentstep char_count public void set indent step int char count indent step char count public int get indent tab size return indent tab size setindentstep char_count indentstep char_count getindenttabsize indenttabsize public int get indent tab size return indent tab size public void set indent tab size int tab size indent tab size tab size getindenttabsize indenttabsize setindenttabsize tab_size indenttabsize tab_size public void set indent tab size int tab size indent tab size tab size public void clear offset 0 setindenttabsize tab_size indenttabsize tab_size private int ensure area int area size int begin offset int end begin area size if end buffer length int new capacity buffer length 2 if end new capacity new capacity end char tmp new char new capacity system arraycopy buffer 0 tmp 0 begin buffer tmp return begin ensure_area area_size area_size new_capacity new_capacity new_capacity new_capacity private int add area int area size int pos ensure area area size offset pos area size return pos add_area area_size ensure_area area_size area_size public int get offset return offset getoffset public int get last char return offset 0 1 buffer offset 1 getlastchar public void p char c int pos add area 1 buffer pos c add_area public void p string s int l s length int pos add area l s get chars 0 l buffer pos add_area getchars public final void p char array p array 0 array length public void p char array int begin int end int l end begin int pos add area l system arraycopy array begin buffer pos l add_area public void p int i p integer to string i tostring public void qchar int c int pos ensure area 2 literal char max size buffer pos pos put string literal char pos 1 c false buffer pos offset pos 1 ensure_area literal_char_max_size put_string_literal_char public void qstring string s int l s length int pos ensure area 2 literal char max size l buffer pos pos for int i 0 i l i pos put string literal char pos s char at i true buffer pos offset pos 1 ensure_area literal_char_max_size put_string_literal_char charat private int put string literal char int pos int c boolean in string boolean backslash symbol true switch c case b c b break case t c t break case n c n break case f c f break case r c r break case backslash symbol in string break case backslash symbol in string break default backslash symbol false if backslash symbol buffer pos buffer pos 1 char c pos 2 else if c c 126 buffer pos char c pos else buffer pos buffer pos 1 u buffer pos 2 digit to hex letter 0xf c 12 buffer pos 3 digit to hex letter 0xf c 8 buffer pos 4 digit to hex letter 0xf c 4 buffer pos 5 digit to hex letter 0xf c pos 6 return pos put_string_literal_char in_string backslash_symbol backslash_symbol in_string backslash_symbol in_string backslash_symbol backslash_symbol digit_to_hex_letter digit_to_hex_letter digit_to_hex_letter digit_to_hex_letter private static char digit to hex letter int d return char d 10 0 d a 10 d digit_to_hex_letter public void indent int level int visible size indent step level int indent size tab count if indent tab size 0 tab count 0 indent size visible size else tab count visible size indent tab size indent size tab count visible size indent tab size int pos add area indent size int tab end pos tab count int indent end pos indent size for pos tab end pos buffer pos t for pos indent end pos buffer pos visible_size indentstep indent_size tab_count indenttabsize tab_count indent_size visible_size tab_count visible_size indenttabsize indent_size tab_count visible_size indenttabsize add_area indent_size tab_end tab_count indent_end indent_size tab_end indent_end public void nl p n public void line int indent level string s indent indent level p s nl indent_level indent_level public void erase int begin int end system arraycopy buffer end buffer begin offset end offset end begin public string to string return new string buffer 0 offset tostring create a java script function object from a java method p the code member code argument must be either a java lang reflect method or a java lang reflect constructor and must match one of two forms p the first form is a member with zero or more parameters of the following types object string boolean scriptable int or double the long type is not supported because the double representation of a long which is the emca mandated storage type for numbers may lose precision if the member is a method the return value must be void or one of the types allowed for parameters p the runtime will perform appropriate conversions based upon the type of the parameter a parameter type of object specifies that no conversions are to be done a parameter of type string will use context to string to convert arguments similarly parameters of type double boolean and scriptable will cause context to number context to boolean and context to object respectively to be called p if the method is not static the java this value will correspond to the java script this value any attempt to call the function with a this value that is not of the right java type will result in an error p the second form is the variable arguments or varargs form if the function object will be used as a constructor the member must have the following parameters pre context cx object args function ctor obj boolean in new expr pre and if it is a method be static and return an object result p otherwise if the function object will i not i be used to define a constructor the member must be a static method with parameters context cx scriptable this obj object args function fun obj pre pre and an object result p when the function varargs form is called as part of a function call the code args code parameter contains the arguments with code this obj code set to the java script this value code fun obj code is the function object for the invoked function p when the constructor varargs form is called or invoked while evaluating a code new code expression code args code contains the arguments code ctor obj code refers to this function object and code in new expr code is true if and only if a code new code expression caused the call this supports defining a function that has different behavior when called as a constructor than when invoked as a normal function call for example the boolean constructor when called as a function will convert to boolean rather than creating a new object p param name the name of the function param method or constructor a java lang reflect method or a java lang reflect constructor that defines the object param scope enclosing scope of function see org mozilla javascript scriptable public function object string name member method or constructor scriptable scope if method or constructor instanceof constructor member new member box constructor method or constructor is static true well doesn t take a this else member new member box method method or constructor is static member is static string method name member get name this function name name class types member arg types int arity types length if arity 4 types 1 is array types 2 is array either variable args or an error if types 1 is array if is static types 0 script runtime context class types 1 get component type script runtime object class types 2 script runtime function class types 3 boolean type throw context report runtime error1 msg varargs ctor method name parms length varargs ctor else if is static types 0 script runtime context class types 1 script runtime scriptable class types 2 get component type script runtime object class types 3 script runtime function class throw context report runtime error1 msg varargs fun method name parms length varargs method else parms length arity if arity 0 type tags new byte arity for int i 0 i arity i int tag get type tag types i if tag java unsupported type throw context report runtime error2 msg bad parms types i get name method name type tags i byte tag if member is method method method member method class return type method get return type if return type void type has void return true else return type tag get type tag return type else class ctor type member get declaring class if script runtime scriptable class is assignable from ctor type throw context report runtime error1 msg bad ctor return ctor type get name script runtime set function proto and parent this scope javascript tostring tonumber toboolean toobject javascript functionobject ctorobj innewexpr functionobject thisobj funobj thisobj javascript funobj ctorobj functionobject innewexpr methodorconstructor functionobject methodorconstructor methodorconstructor memberbox methodorconstructor isstatic memberbox methodorconstructor isstatic isstatic methodname getname functionname argtypes isarray isarray isarray isstatic scriptruntime contextclass getcomponenttype scriptruntime objectclass scriptruntime functionclass reportruntimeerror1 methodname parmslength varargs_ctor isstatic scriptruntime contextclass scriptruntime scriptableclass getcomponenttype scriptruntime objectclass scriptruntime functionclass reportruntimeerror1 methodname parmslength varargs_method parmslength typetags gettypetag java_unsupported_type reportruntimeerror2 getname methodname typetags ismethod returntype getreturntype returntype hasvoidreturn returntypetag gettypetag returntype ctortype getdeclaringclass scriptruntime scriptableclass isassignablefrom ctortype reportruntimeerror1 ctortype getname scriptruntime setfunctionprotoandparent return one of tt java type tt constants to indicate desired type or link java unsupported type if the convertion is not possible public static int get type tag class type if type script runtime string class return java string type if type script runtime integer class type integer type return java int type if type script runtime boolean class type boolean type return java boolean type if type script runtime double class type double type return java double type if script runtime scriptable class is assignable from type return java scriptable type if type script runtime object class return java object type note that the long type is not supported see the javadoc for the constructor for this class return java unsupported type java_ _type java_unsupported_type gettypetag scriptruntime stringclass java_string_type scriptruntime integerclass java_int_type scriptruntime booleanclass java_boolean_type scriptruntime doubleclass java_double_type scriptruntime scriptableclass isassignablefrom java_scriptable_type scriptruntime objectclass java_object_type java_unsupported_type public static object convert arg context cx scriptable scope object arg int type tag switch type tag case java string type if arg instanceof string return arg return script runtime to string arg case java int type if arg instanceof integer return arg return new integer script runtime to int32 arg case java boolean type if arg instanceof boolean return arg return script runtime to boolean arg boolean true boolean false case java double type if arg instanceof double return arg return new double script runtime to number arg case java scriptable type if arg instanceof scriptable return arg return script runtime to object cx scope arg case java object type return arg default throw new illegal argument exception convertarg typetag typetag java_string_type scriptruntime tostring java_int_type scriptruntime toint32 java_boolean_type scriptruntime toboolean java_double_type scriptruntime tonumber java_scriptable_type scriptruntime toobject java_object_type illegalargumentexception return the value defined by the method used to construct the object number of parameters of the method or 1 if the method is a varargs form public int get arity return parms length 0 1 parms length getarity parmslength parmslength return the same value as link get arity public int get length return get arity getarity getlength getarity public string get function name return function name null function name getfunctionname functionname functionname get java method or constructor this function represent public member get method or constructor if member is method return member method else return member ctor getmethodorconstructor ismethod static method find single method method methods string name method found null for int i 0 n methods length i n i method method methods i if method null name equals method get name if found null throw context report runtime error2 msg no overload name method get declaring class get name found method return found findsinglemethod getname reportruntimeerror2 getdeclaringclass getname returns all public methods declared by the specified class this excludes inherited methods param clazz the class from which to pull public declared methods return the public methods declared in the specified class see class get declared methods static method get method list class clazz method methods null try get declared methods may be rejected by the security manager but get methods is more expensive if saw security exception methods clazz get declared methods catch security exception e if we get an exception once give up on get declared methods saw security exception true if methods null methods clazz get methods int count 0 for int i 0 i methods length i if saw security exception methods i get declaring class clazz modifier is public methods i get modifiers methods i null else count method result new method count int j 0 for int i 0 i methods length i if methods i null result j methods i return result getdeclaredmethods getmethodlist getdeclaredmethods getmethods sawsecurityexception getdeclaredmethods securityexception getdeclaredmethods sawsecurityexception getmethods sawsecurityexception getdeclaringclass ispublic getmodifiers define this function as a java script constructor p sets up the prototype and constructor properties also calls set parent and set prototype with appropriate values then adds the function object as a property of the given scope using code prototype get class name code as the name of the property param scope the scope in which to define the constructor typically the global object param prototype the prototype object see org mozilla javascript scriptable set parent scope see org mozilla javascript scriptable set prototype see org mozilla javascript scriptable get class name public void add as constructor scriptable scope scriptable prototype script runtime set function proto and parent this scope set immune prototype property prototype prototype set parent scope this final int attr scriptable object dontenum scriptable object permanent scriptable object readonly define property prototype constructor this attr string name prototype get class name define property scope name this scriptable object dontenum set parent scope scope javascript setparent setprototype getclassname setparentscope setprototype getclassname addasconstructor scriptruntime setfunctionprotoandparent setimmuneprototypeproperty setparentscope scriptableobject scriptableobject scriptableobject defineproperty getclassname defineproperty scriptableobject setparentscope deprecated use link get type tag class and link convert arg context scriptable object int for type convertion public static object convert arg context cx scriptable scope object arg class desired int tag get type tag desired if tag java unsupported type throw context report runtime error1 msg cant convert desired get name return convert arg cx scope arg tag gettypetag convertarg convertarg gettypetag java_unsupported_type reportruntimeerror1 getname convertarg performs conversions on argument types if needed and invokes the underlying java method or constructor p implements function call see org mozilla javascript function call context scriptable scriptable object public object call context cx scriptable scope scriptable this obj object args object result boolean check method result false if parms length 0 if parms length varargs method object invoke args cx this obj args this result member invoke null invoke args check method result true else boolean in new expr this obj null boolean b in new expr boolean true boolean false object invoke args cx args this b result member is ctor member new instance invoke args member invoke null invoke args else if is static class clazz member get declaring class if clazz is instance this obj boolean compatible false if this obj scope scriptable parent scope get parent scope if scope parent scope call with dynamic scope for standalone function use parent scope as this obj compatible clazz is instance parent scope if compatible this obj parent scope if compatible couldn t find an object to call this on throw script runtime type error1 msg incompat call function name object invoke args if parms length args length do not allocate new argument array if java arguments are the same as the original js ones invoke args args for int i 0 i parms length i object arg args i object converted convert arg cx scope arg type tags i if arg converted if invoke args args invoke args object args clone invoke args i converted else if parms length 0 invoke args script runtime empty args else invoke args new object parms length for int i 0 i parms length i object arg i args length args i undefined instance invoke args i convert arg cx scope arg type tags i if member is method result member invoke this obj invoke args check method result true else result member new instance invoke args if check method result if has void return result undefined instance else if return type tag java unsupported type result cx get wrap factory wrap cx scope result null xxx the code assumes that if return type tag java object type then the java method did a proper job of converting the result to js primitive or scriptable to avoid potentially costly context java tojs call return result thisobj checkmethodresult parmslength parmslength varargs_method invokeargs thisobj invokeargs checkmethodresult innewexpr thisobj innewexpr invokeargs isctor newinstance invokeargs invokeargs isstatic getdeclaringclass isinstance thisobj thisobj parentscope getparentscope parentscope parentscope thisobj isinstance parentscope thisobj parentscope scriptruntime typeerror1 functionname invokeargs parmslength invokeargs parmslength convertarg typetags invokeargs invokeargs invokeargs parmslength invokeargs scriptruntime emptyargs invokeargs parmslength parmslength invokeargs convertarg typetags ismethod thisobj invokeargs checkmethodresult newinstance invokeargs checkmethodresult hasvoidreturn returntypetag java_unsupported_type getwrapfactory returntypetag java_object_type javatojs return new link scriptable instance using the default constructor for the class of the underlying java method return null to indicate that the call method should be used to create new objects public scriptable create object context cx scriptable scope if member is ctor parms length varargs ctor return null scriptable result try result scriptable member get declaring class new instance catch exception ex throw context throw as script runtime ex ex result set prototype get class prototype result set parent scope get parent scope return result createobject isctor parmslength varargs_ctor getdeclaringclass newinstance throwasscriptruntimeex setprototype getclassprototype setparentscope getparentscope boolean is var args method return parms length varargs method isvarargsmethod parmslength varargs_method boolean is var args constructor return parms length varargs ctor isvarargsconstructor parmslength varargs_ctor private void read object object input stream in throws io exception class not found exception in default read object if parms length 0 class types member arg types type tags new byte parms length for int i 0 i parms length i type tags i byte get type tag types i if member is method method method member method class return type method get return type if return type void type has void return true else return type tag get type tag return type readobject objectinputstream ioexception classnotfoundexception defaultreadobject parmslength argtypes typetags parmslength parmslength typetags gettypetag ismethod returntype getreturntype returntype hasvoidreturn returntypetag gettypetag returntype public class run script4 public static void main string args throws exception context cx context enter try scriptable scope cx init standard objects use the counter class to define a counter constructor and prototype in java script scriptable object define class scope counter class create an instance of counter and assign it to the top level variable my counter this is equivalent to the java script code my counter new counter 7 object arg new integer 7 scriptable my counter cx new object scope counter arg scope put my counter scope my counter string s for int i 0 i args length i s args i object result cx evaluate string scope s cmd 1 null system err println cx to string result finally context exit runscript4 initstandardobjects javascript scriptableobject defineclass mycounter javascript mycounter mycounter newobject mycounter mycounter evaluatestring tostring static void init scriptable scope boolean sealed native math obj new native math obj activate prototype map max id obj set prototype get object prototype scope obj set parent scope scope if sealed obj seal object scriptable object define property scope math obj scriptable object dontenum nativemath nativemath activateprototypemap max_id setprototype getobjectprototype setparentscope sealobject scriptableobject defineproperty scriptableobject private native math nativemath public string get class name return math getclassname protected void init prototype id int id if id last method id string name int arity switch id case id tosource arity 0 name to source break case id abs arity 1 name abs break case id acos arity 1 name acos break case id asin arity 1 name asin break case id atan arity 1 name atan break case id atan2 arity 2 name atan2 break case id ceil arity 1 name ceil break case id cos arity 1 name cos break case id exp arity 1 name exp break case id floor arity 1 name floor break case id log arity 1 name log break case id max arity 2 name max break case id min arity 2 name min break case id pow arity 2 name pow break case id random arity 0 name random break case id round arity 1 name round break case id sin arity 1 name sin break case id sqrt arity 1 name sqrt break case id tan arity 1 name tan break default throw new illegal state exception string value of id init prototype method math tag id name arity else string name double x switch id case id e x math e name e break case id pi x math pi name pi break case id ln10 x 2 302585092994046 name ln10 break case id ln2 x 0 6931471805599453 name ln2 break case id log2e x 1 4426950408889634 name log2e break case id log10e x 0 4342944819032518 name log10e break case id sqrt1 2 x 0 7071067811865476 name sqrt1 2 break case id sqrt2 x 1 4142135623730951 name sqrt2 break default throw new illegal state exception string value of id init prototype value id name script runtime wrap number x dontenum readonly permanent initprototypeid last_method_id id_tosource tosource id_abs id_acos id_asin id_atan id_atan2 id_ceil id_cos id_exp id_floor id_log id_max id_min id_pow id_random id_round id_sin id_sqrt id_tan illegalstateexception valueof initprototypemethod math_tag id_e id_pi id_ln10 id_ln2 id_log2e id_log10e id_sqrt1_2 sqrt1_2 id_sqrt2 illegalstateexception valueof initprototypevalue scriptruntime wrapnumber public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag math tag return super exec id call f cx scope this obj args double x int method id f method id switch method id case id tosource return math case id abs x script runtime to number args 0 abs 0 0 should be 0 0 but 0 0 0 0 false x x 0 0 0 0 x 0 0 x x break case id acos case id asin x script runtime to number args 0 if x x 1 0 x x 1 0 x method id id acos math acos x math asin x else x double nan break case id atan x script runtime to number args 0 x math atan x break case id atan2 x script runtime to number args 0 x math atan2 x script runtime to number args 1 break case id ceil x script runtime to number args 0 x math ceil x break case id cos x script runtime to number args 0 x x double positive infinity x double negative infinity double nan math cos x break case id exp x script runtime to number args 0 x x double positive infinity x x double negative infinity 0 0 math exp x break case id floor x script runtime to number args 0 x math floor x break case id log x script runtime to number args 0 java s log 0 infinity we need nan x x 0 double nan math log x break case id max case id min x method id id max double negative infinity double positive infinity for int i 0 i args length i double d script runtime to number args i if d d x d nan break if method id id max if x d x d does not work due to 0 0 0 0 x math max x d else x math min x d break case id pow x script runtime to number args 0 x js pow x script runtime to number args 1 break case id random x math random break case id round x script runtime to number args 0 if x x x double positive infinity x double negative infinity round only finite x long l math round x if l 0 x double l else we must propagate the sign of d into the result if x 0 0 x script runtime negative zero else if x 0 0 x 0 0 break case id sin x script runtime to number args 0 x x double positive infinity x double negative infinity double nan math sin x break case id sqrt x script runtime to number args 0 x math sqrt x break case id tan x script runtime to number args 0 x math tan x break default throw new illegal state exception string value of method id return script runtime wrap number x execidcall idfunctionobject thisobj hastag math_tag execidcall thisobj methodid methodid methodid id_tosource id_abs scriptruntime tonumber id_acos id_asin scriptruntime tonumber methodid id_acos id_atan scriptruntime tonumber id_atan2 scriptruntime tonumber scriptruntime tonumber id_ceil scriptruntime tonumber id_cos scriptruntime tonumber positive_infinity negative_infinity id_exp scriptruntime tonumber positive_infinity negative_infinity id_floor scriptruntime tonumber id_log scriptruntime tonumber id_max id_min methodid id_max negative_infinity positive_infinity scriptruntime tonumber methodid id_max id_pow scriptruntime tonumber js_pow scriptruntime tonumber id_random id_round scriptruntime tonumber positive_infinity negative_infinity scriptruntime negativezero id_sin scriptruntime tonumber positive_infinity negative_infinity id_sqrt scriptruntime tonumber id_tan scriptruntime tonumber illegalstateexception valueof methodid scriptruntime wrapnumber see ecma 15 8 2 13 private double js pow double x double y double result if y y y is nan result is always nan result y else if y 0 java s pow nan 0 nan we need 1 result 1 0 else if x 0 many dirrerences from java s math pow if 1 x 0 result y 0 0 double positive infinity else x is 0 need to check if y is an odd integer long y long long y if y long y y long 0x1 0 result y 0 0 0 double negative infinity else result y 0 0 0 double positive infinity else result math pow x y if result result check for broken java implementations that gives nan when they should return something else if y double positive infinity if x 1 0 1 0 x result double positive infinity else if 1 0 x x 1 0 result 0 else if y double negative infinity if x 1 0 1 0 x result 0 else if 1 0 x x 1 0 result double positive infinity else if x double positive infinity result y 0 double positive infinity 0 0 else if x double negative infinity long y long long y if y long y y long 0x1 0 y is odd integer result y 0 double negative infinity 0 0 else result y 0 double positive infinity 0 0 return result js_pow positive_infinity y_long y_long y_long negative_infinity positive_infinity positive_infinity positive_infinity negative_infinity positive_infinity positive_infinity positive_infinity negative_infinity y_long y_long y_long negative_infinity positive_infinity protected int find prototype id string s int id generated last update 2004 03 17 13 51 32 cet l0 id 0 string x null int c l switch s length case 1 if s char at 0 e id id e break l0 break l case 2 if s char at 0 p s char at 1 i id id pi break l0 break l case 3 switch s char at 0 case l if s char at 2 2 s char at 1 n id id ln2 break l0 break l case a if s char at 2 s s char at 1 b id id abs break l0 break l case c if s char at 2 s s char at 1 o id id cos break l0 break l case e if s char at 2 p s char at 1 x id id exp break l0 break l case l if s char at 2 g s char at 1 o id id log break l0 break l case m c s char at 2 if c n if s char at 1 i id id min break l0 else if c x if s char at 1 a id id max break l0 break l case p if s char at 2 w s char at 1 o id id pow break l0 break l case s if s char at 2 n s char at 1 i id id sin break l0 break l case t if s char at 2 n s char at 1 a id id tan break l0 break l break l case 4 switch s char at 1 case n x ln10 id id ln10 break l case c x acos id id acos break l case e x ceil id id ceil break l case q x sqrt id id sqrt break l case s x asin id id asin break l case t x atan id id atan break l break l case 5 switch s char at 0 case l x log2e id id log2e break l case s x sqrt2 id id sqrt2 break l case a x atan2 id id atan2 break l case f x floor id id floor break l case r x round id id round break l break l case 6 c s char at 0 if c l x log10e id id log10e else if c r x random id id random break l case 7 x sqrt1 2 id id sqrt1 2 break l case 8 x to source id id tosource break l if x null x s x equals s id 0 generated return id findprototypeid charat id_e charat charat id_pi charat charat charat id_ln2 charat charat id_abs charat charat id_cos charat charat id_exp charat charat id_log charat charat id_min charat id_max charat charat id_pow charat charat id_sin charat charat id_tan charat id_ln10 id_acos id_ceil id_sqrt id_asin id_atan charat id_log2e id_sqrt2 id_atan2 id_floor id_round charat id_log10e id_random sqrt1_2 id_sqrt1_2 tosource id_tosource public class call 001 extends live connect test public call 001 super call_001 liveconnecttest call_001 public static void main string args call 001 test new call 001 test start call_001 call_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 call js object object data i executetest getdataarray jsobject jsobject getjsobject jsobject create and return a js object using data in the data array param data object array containing name of js object and assignment expression return the js object public js object getjs object object data string constructor data 0 data 1 js object the this js object global eval constructor return the this jsobject jsobject jsobject jsobject getjsobject jsobject thethis jsobject thethis use js object call to invoke a java script method verify the value and class of the object returned param the this js object whose method will be called will be checked param data object array containing the name of the method arguments to be passed to that method and the expected return value of the method public void call js object the this object data string exception null string method string data 2 object args object data 3 object e value data 4 object a value null class e class null class a class null try a value the this call method object args if a value null e class e value get class a class a value get class catch exception e exception the this call method args 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 the this call method args 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 jsobject javascript thethis jsobject jsobject thethis evalue avalue eclass aclass avalue thethis avalue eclass evalue getclass aclass avalue getclass thethis tostring printstacktrace avalue addtestcase getmember avalue thethis evalue avalue evalue addtestcase avalue getclass aclass getname aclass getname eclass getname aclass getname eclass getname get the data array which is an object array data arrays which are also object arrays ul li identifier for java script object li assignment expression to initialize java script object li method of the java script object li arguments to pass to the method li value returned by the method ul to add test cases to this test modify this method return the data array public object get data array object d0 new string boo 0 identifier new string new boolean 1 assignment expression new string value of 2 method null 3 argument array new boolean false 4 return value object d1 new string date new string new date 0 new string getutc full year null new double 1970 object data array d0 d1 return data array javascript javascript javascript getdataarray valueof getutcfullyear dataarray dataarray interpreter data int language version string source file string encoded source this language version language version this its source file source file this encoded source encoded source init interpreterdata languageversion sourcefile encodedsource languageversion languageversion itssourcefile sourcefile encodedsource encodedsource interpreter data interpreter data parent this parent data parent this language version parent language version this its source file parent its source file this encoded source parent encoded source init interpreterdata interpreterdata parentdata languageversion languageversion itssourcefile itssourcefile encodedsource encodedsource private void init itsi code new byte initial max icode length its string table new string initial stringtable size itsicode initial_max_icode_length itsstringtable initial_stringtable_size boolean eval script flag true if script corresponds to eval code public boolean is top level return top level evalscriptflag istoplevel toplevel public boolean is function return its function type 0 isfunction itsfunctiontype public string get function name return its name getfunctionname itsname public int get param count return arg count getparamcount argcount public int get param and var count return arg names length getparamandvarcount argnames public string get param or var name int index return arg names index getparamorvarname argnames public string get source name return its source file getsourcename itssourcefile public boolean is generated script return script runtime is generated script its source file isgeneratedscript scriptruntime isgeneratedscript itssourcefile public int get line numbers return interpreter get line numbers this getlinenumbers getlinenumbers public int get function count return its nested functions null 0 its nested functions length getfunctioncount itsnestedfunctions itsnestedfunctions public debuggable script get function int index return its nested functions index debuggablescript getfunction itsnestedfunctions public debuggable script get parent return parent data debuggablescript getparent parentdata private static block reduce to array obj to int map map block result null if map is empty result new block map size int i 0 obj to int map iterator iter map new iterator for iter start iter done iter next fat block fb fat block iter get key result i fb real block return result reducetoarray objtointmap isempty objtointmap newiterator fatblock fatblock getkey realblock void add successor fat block b successors put b 0 addsuccessor fatblock void add successor fat block b successors put b 0 void add predecessor fat block b predecessors put b 0 addsuccessor fatblock addpredecessor fatblock void add predecessor fat block b predecessors put b 0 block get successors return reduce to array successors addpredecessor fatblock getsuccessors reducetoarray block get successors return reduce to array successors block get predecessors return reduce to array predecessors getsuccessors reducetoarray getpredecessors reducetoarray block int start node index int end node index its start node index start node index its end node index end node index startnodeindex endnodeindex itsstartnodeindex startnodeindex itsendnodeindex endnodeindex static void run flow analyzes opt function node fn node statement nodes int param count fn fnode get param count int var count fn fnode get param and var count int var types new int var count if the variable is a parameter it could have any type for int i 0 i param count i var types i optimizer any type if the variable is from a var statement its type event will be set when we see the set var node for int i param count i var count i var types i optimizer no type block the blocks build blocks statement nodes if debug debug blockcount system out println fn fnode get function name debug blockcount system out println to string the blocks statement nodes reaching def data flow fn statement nodes the blocks var types type flow fn statement nodes the blocks var types if debug for int i 0 i the blocks length i system out println for block the blocks i its blockid the blocks i print live on entry set fn system out println variable table size var count for int i 0 i var count i system out println i type var types i for int i param count i var count i if var types i optimizer number type fn set is number var i runflowanalyzes optfunctionnode statementnodes paramcount getparamcount varcount getparamandvarcount vartypes varcount paramcount vartypes anytype typeevent setvar paramcount varcount vartypes notype theblocks buildblocks statementnodes debug_blockcount getfunctionname debug_blockcount tostring theblocks statementnodes reachingdefdataflow statementnodes theblocks vartypes typeflow statementnodes theblocks vartypes theblocks theblocks itsblockid theblocks printliveonentryset varcount varcount vartypes paramcount varcount vartypes numbertype setisnumbervar private static block build blocks node statement nodes a mapping from each target node to the block it begins hashtable the target blocks new hashtable obj array the blocks new obj array there s a block that starts at index 0 int begin node index 0 for int i 0 i statement nodes length i switch statement nodes i get type case token target if i begin node index fat block fb new fat block begin node index i 1 if statement nodes begin node index get type token target the target blocks put statement nodes begin node index fb the blocks add fb start the next block at this node begin node index i break case token ifne case token ifeq case token goto fat block fb new fat block begin node index i if statement nodes begin node index get type token target the target blocks put statement nodes begin node index fb the blocks add fb start the next block at the next node begin node index i 1 break if begin node index statement nodes length fat block fb new fat block begin node index statement nodes length 1 if statement nodes begin node index get type token target the target blocks put statement nodes begin node index fb the blocks add fb build successor and predecessor links for int i 0 i the blocks size i fat block fb fat block the blocks get i node block end node statement nodes fb real block its end node index int block end node type block end node get type if block end node type token goto i the blocks size 1 fat block fall thru target fat block the blocks get i 1 fb add successor fall thru target fall thru target add predecessor fb if block end node type token ifne block end node type token ifeq block end node type token goto node target node jump block end node target fat block branch target block fat block the target blocks get target target put prop node targetblock prop branch target block real block fb add successor branch target block branch target block add predecessor fb block result new block the blocks size for int i 0 i the blocks size i fat block fb fat block the blocks get i block b fb real block b its successors fb get successors b its predecessors fb get predecessors b its blockid i result i b return result buildblocks statementnodes thetargetblocks objarray theblocks objarray beginnodeindex statementnodes statementnodes gettype beginnodeindex fatblock newfatblock beginnodeindex statementnodes beginnodeindex gettype thetargetblocks statementnodes beginnodeindex theblocks beginnodeindex fatblock newfatblock beginnodeindex statementnodes beginnodeindex gettype thetargetblocks statementnodes beginnodeindex theblocks beginnodeindex beginnodeindex statementnodes fatblock newfatblock beginnodeindex statementnodes statementnodes beginnodeindex gettype thetargetblocks statementnodes beginnodeindex theblocks theblocks fatblock fatblock theblocks blockendnode statementnodes realblock itsendnodeindex blockendnodetype blockendnode gettype blockendnodetype theblocks fatblock fallthrutarget fatblock theblocks addsuccessor fallthrutarget fallthrutarget addpredecessor blockendnodetype blockendnodetype blockendnodetype blockendnode fatblock branchtargetblock fatblock thetargetblocks putprop targetblock_prop branchtargetblock realblock addsuccessor branchtargetblock branchtargetblock addpredecessor theblocks theblocks fatblock fatblock theblocks realblock itssuccessors getsuccessors itspredecessors getpredecessors itsblockid private static fat block new fat block int start node index int end node index fat block fb new fat block fb real block new block start node index end node index return fb fatblock newfatblock startnodeindex endnodeindex fatblock fatblock realblock startnodeindex endnodeindex private static string to string block block list node statement nodes if debug return null string writer sw new string writer print writer pw new print writer sw pw println block list length blocks for int i 0 i block list length i block b block list i pw println b its blockid pw println from b its start node index statement nodes b its start node index to string pw println thru b its end node index statement nodes b its end node index to string pw print predecessors if b its predecessors null for int j 0 j b its predecessors length j pw print b its predecessors j its blockid pw println else pw println none pw print successors if b its successors null for int j 0 j b its successors length j pw print b its successors j its blockid pw println else pw println none return sw to string tostring blocklist statementnodes stringwriter stringwriter printwriter printwriter blocklist blocklist blocklist itsblockid itsstartnodeindex statementnodes itsstartnodeindex tostring itsendnodeindex statementnodes itsendnodeindex tostring itspredecessors itspredecessors itspredecessors itsblockid itssuccessors itssuccessors itssuccessors itsblockid tostring private static void reaching def data flow opt function node fn node statement nodes block the blocks int var types initialize the live on entry and live on exit sets then discover the variables that are def d by each function and those that are used before being def d hence live on entry for int i 0 i the blocks length i the blocks i init live on entry sets fn statement nodes this visits every block starting at the last re adding the predecessors of any block whose inputs change as a result of the dataflow remind better would be to visit in cfg postorder boolean visit new boolean the blocks length boolean done once new boolean the blocks length int v index the blocks length 1 boolean need rescan false visit v index true while true if visit v index done once v index done once v index true visit v index false if the blocks v index do reached use data flow block pred the blocks v index its predecessors if pred null for int i 0 i pred length i int index pred i its blockid visit index true need rescan index v index if v index 0 if need rescan v index the blocks length 1 need rescan false else break else v index if any variable is live on entry to block 0 we have to mark it as not j regable since it means that someone is trying to access the undefined ness of that variable the blocks 0 mark any type variables var types reachingdefdataflow optfunctionnode statementnodes theblocks vartypes liveonentry liveonexit liveonentry theblocks theblocks initliveonentrysets statementnodes theblocks doneonce theblocks vindex theblocks needrescan vindex vindex doneonce vindex doneonce vindex vindex theblocks vindex doreachedusedataflow theblocks vindex itspredecessors itsblockid needrescan vindex vindex needrescan vindex theblocks needrescan vindex jregable theblocks markanytypevariables vartypes private static void type flow opt function node fn node statement nodes block the blocks int var types boolean visit new boolean the blocks length boolean done once new boolean the blocks length int v index 0 boolean need rescan false visit v index true while true if visit v index done once v index done once v index true visit v index false if the blocks v index do type flow fn statement nodes var types block succ the blocks v index its successors if succ null for int i 0 i succ length i int index succ i its blockid visit index true need rescan index v index if v index the blocks length 1 if need rescan v index 0 need rescan false else break else v index typeflow optfunctionnode statementnodes theblocks vartypes theblocks doneonce theblocks vindex needrescan vindex vindex doneonce vindex doneonce vindex vindex theblocks vindex dotypeflow statementnodes vartypes theblocks vindex itssuccessors itsblockid needrescan vindex vindex theblocks needrescan vindex needrescan vindex private static boolean assign type int var types int index int type return type var types index type assigntype vartypes vartypes private void mark any type variables int var types for int i 0 i var types length i if its live on entry set test i assign type var types i optimizer any type markanytypevariables vartypes vartypes itsliveonentryset assigntype vartypes anytype private void look for variable access opt function node fn node n switch n get type case token dec case token inc node child n get first child if child get type token getvar int var index fn get var index child if its not def set test var index its use before def set set var index its not def set set var index break case token setvar node lhs n get first child node rhs lhs get next look for variable access fn rhs its not def set set fn get var index n break case token getvar int var index fn get var index n if its not def set test var index its use before def set set var index break default node child n get first child while child null look for variable access fn child child child get next break lookforvariableaccess optfunctionnode gettype getfirstchild gettype varindex getvarindex itsnotdefset varindex itsusebeforedefset varindex itsnotdefset varindex getfirstchild getnext lookforvariableaccess itsnotdefset getvarindex varindex getvarindex itsnotdefset varindex itsusebeforedefset varindex getfirstchild lookforvariableaccess getnext private void init live on entry sets opt function node fn node statement nodes int list length fn get var count its use before def set new data flow bit set list length its not def set new data flow bit set list length its live on entry set new data flow bit set list length its live on exit set new data flow bit set list length for int i its start node index i its end node index i node n statement nodes i look for variable access fn n its not def set not truth in advertising initliveonentrysets optfunctionnode statementnodes listlength getvarcount itsusebeforedefset dataflowbitset listlength itsnotdefset dataflowbitset listlength itsliveonentryset dataflowbitset listlength itsliveonexitset dataflowbitset listlength itsstartnodeindex itsendnodeindex statementnodes lookforvariableaccess itsnotdefset private boolean do reached use data flow its live on exit set clear if its successors null for int i 0 i its successors length i its live on exit set or its successors i its live on entry set return its live on entry set df2 its live on exit set its use before def set its not def set doreachedusedataflow itsliveonexitset itssuccessors itssuccessors itsliveonexitset itssuccessors itsliveonentryset itsliveonentryset itsliveonexitset itsusebeforedefset itsnotdefset private static int find expression type opt function node fn node n int var types switch n get type case token number return optimizer number type case token call case token new case token ref call return optimizer any type case token getelem return optimizer any type case token getvar return var types fn get var index n case token inc case token dec case token div case token mod case token bitor case token bitxor case token bitand case token lsh case token rsh case token ursh case token sub return optimizer number type case token add if the lhs rhs are known to be numbers we can be sure that s the result otherwise it could be a string node child n get first child int l type find expression type fn child var types int r type find expression type fn child get next var types return l type r type we re not distinguishng strings yet node child n get first child if child null return optimizer any type else int result optimizer no type while child null result find expression type fn child var types child child get next return result findexpressiontype optfunctionnode vartypes gettype numbertype ref_call anytype anytype vartypes getvarindex numbertype getfirstchild ltype findexpressiontype vartypes rtype findexpressiontype getnext vartypes ltype rtype getfirstchild anytype notype findexpressiontype vartypes getnext private static boolean find def points opt function node fn node n int var types boolean result false node child n get first child switch n get type default while child null result find def points fn child var types child child get next break case token dec case token inc if child get type token getvar the var is a number now int i fn get var index child result assign type var types i optimizer number type break case token setprop case token setprop op if child get type token getvar int i fn get var index child assign type var types i optimizer any type while child null result find def points fn child var types child child get next break case token setvar node r value child get next int the type find expression type fn r value var types int i fn get var index n result assign type var types i the type break return result finddefpoints optfunctionnode vartypes getfirstchild gettype finddefpoints vartypes getnext gettype thevar getvarindex assigntype vartypes numbertype setprop_op gettype getvarindex assigntype vartypes anytype finddefpoints vartypes getnext rvalue getnext thetype findexpressiontype rvalue vartypes getvarindex assigntype vartypes thetype private boolean do type flow opt function node fn node statement nodes int var types boolean changed false for int i its start node index i its end node index i node n statement nodes i if n null changed find def points fn n var types return changed dotypeflow optfunctionnode statementnodes vartypes itsstartnodeindex itsendnodeindex statementnodes finddefpoints vartypes private boolean is live on entry int index return its live on entry set null its live on entry set test index isliveonentry itsliveonentryset itsliveonentryset private void print live on entry set opt function node fn if debug for int i 0 i fn get var count i string name fn fnode get param or var name i if its use before def set test i system out println name is used before def d if its not def set test i system out println name is not def d if its live on entry set test i system out println name is live on entry if its live on exit set test i system out println name is live on exit printliveonentryset optfunctionnode getvarcount getparamorvarname itsusebeforedefset itsnotdefset itsliveonentryset itsliveonexitset static final long serial versionuid 5733330028285400526l native reg exp ctor serialversionuid nativeregexpctor public string get function name return reg exp getfunctionname regexp public object call context cx scriptable scope scriptable this obj object args if args length 0 args 0 instanceof native reg exp args length 1 args 1 undefined instance return args 0 return construct cx scope args thisobj nativeregexp public scriptable construct context cx scriptable scope object args native reg exp re new native reg exp re compile cx scope args script runtime set object proto and parent re scope return re nativeregexp nativeregexp scriptruntime setobjectprotoandparent private static reg exp impl get impl context cx context get current context return reg exp impl script runtime get reg exp proxy cx regexpimpl getimpl getcurrentcontext regexpimpl scriptruntime getregexpproxy max instance id dollar id base 9 protected int get max instance id return super get max instance id max instance id max_instance_id dollar_id_base getmaxinstanceid getmaxinstanceid max_instance_id protected int find instance id info string s int id generated last update 2001 05 24 16 09 31 gmt 02 00 l0 id 0 string x null int c l switch s length case 2 switch s char at 1 case if s char at 0 id id ampersand break l0 break l case if s char at 0 id id quote break l0 break l case if s char at 0 id id star break l0 break l case if s char at 0 id id plus break l0 break l case 1 if s char at 0 id id dollar 1 break l0 break l case 2 if s char at 0 id id dollar 2 break l0 break l case 3 if s char at 0 id id dollar 3 break l0 break l case 4 if s char at 0 id id dollar 4 break l0 break l case 5 if s char at 0 id id dollar 5 break l0 break l case 6 if s char at 0 id id dollar 6 break l0 break l case 7 if s char at 0 id id dollar 7 break l0 break l case 8 if s char at 0 id id dollar 8 break l0 break l case 9 if s char at 0 id id dollar 9 break l0 break l case if s char at 0 id id underscore break l0 break l case if s char at 0 id id back quote break l0 break l break l case 5 x input id id input break l case 9 c s char at 4 if c m x last match id id lastmatch else if c p x last paren id id lastparen else if c i x multiline id id multiline break l case 11 x left context id id leftcontext break l case 12 x right context id id rightcontext break l 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 multiline case id star case id input case id underscore attr permanent break default attr permanent readonly break return instance id info attr super get max instance id id findinstanceidinfo charat charat id_ampersand charat id_quote charat id_star charat id_plus charat id_dollar_1 charat id_dollar_2 charat id_dollar_3 charat id_dollar_4 charat id_dollar_5 charat id_dollar_6 charat id_dollar_7 charat id_dollar_8 charat id_dollar_9 _ charat id_underscore charat id_back_quote id_input charat lastmatch id_lastmatch lastparen id_lastparen id_multiline leftcontext id_leftcontext rightcontext id_rightcontext findinstanceidinfo id_multiline id_star id_input id_underscore instanceidinfo getmaxinstanceid protected string get instance id name int id int shifted id super get max instance id if 1 shifted shifted max instance id switch shifted case id multiline return multiline case id star return case id input return input case id underscore return case id lastmatch return last match case id ampersand return case id lastparen return last paren case id plus return case id leftcontext return left context case id back quote return case id rightcontext return right context case id quote return must be one of 1 9 convert to 0 8 int substring number shifted dollar id base 1 char buf char 1 substring number return new string buf return super get instance id name id getinstanceidname getmaxinstanceid max_instance_id id_multiline id_star id_input id_underscore _ id_lastmatch lastmatch id_ampersand id_lastparen lastparen id_plus id_leftcontext leftcontext id_back_quote id_rightcontext rightcontext id_quote substring_number dollar_id_base substring_number getinstanceidname protected object get instance id value int id int shifted id super get max instance id if 1 shifted shifted max instance id reg exp impl impl get impl object string result switch shifted case id multiline case id star return script runtime wrap boolean impl multiline case id input case id underscore string result impl input break case id lastmatch case id ampersand string result impl last match break case id lastparen case id plus string result impl last paren break case id leftcontext case id back quote string result impl left context break case id rightcontext case id quote string result impl right context break default must be one of 1 9 convert to 0 8 int substring number shifted dollar id base 1 string result impl get paren sub string substring number break return string result null string result to string return super get instance id value id getinstanceidvalue getmaxinstanceid max_instance_id regexpimpl getimpl stringresult id_multiline id_star scriptruntime wrapboolean id_input id_underscore stringresult id_lastmatch id_ampersand stringresult lastmatch id_lastparen id_plus stringresult lastparen id_leftcontext id_back_quote stringresult leftcontext id_rightcontext id_quote stringresult rightcontext substring_number dollar_id_base stringresult getparensubstring substring_number stringresult stringresult tostring getinstanceidvalue protected void set instance id value int id object value int shifted id super get max instance id switch shifted case id multiline case id star get impl multiline script runtime to boolean value return case id input case id underscore get impl input script runtime to string value return super set instance id value id value setinstanceidvalue getmaxinstanceid id_multiline id_star getimpl scriptruntime toboolean id_input id_underscore getimpl scriptruntime tostring setinstanceidvalue deprecated use link wrapped exception wrapped exception throwable to report exceptions in java code public java script exception object value this value 0 wrappedexception wrappedexception javascriptexception create a java script exception wrapping the given java script value param value the java script value thrown public java script exception object value string source name int line number record error origin source name line number null 0 this value value javascript javascript javascript javascriptexception sourcename linenumber recorderrororigin sourcename linenumber public string details if value instanceof scriptable to prevent potential of evaluation and throwing more exceptions return script runtime default object to string scriptable value return script runtime to string value scriptruntime defaultobjecttostring scriptruntime tostring return the value wrapped by this exception public object get value return value getvalue 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 public class datatypes 012 extends live connect test public datatypes 012 super datatypes_012 liveconnecttest datatypes_012 public static void main string args datatypes 012 test new datatypes 012 test start datatypes_012 datatypes_012 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 long array true do array test dt pub static array long true do array test dt get long array true do array test dt pub array long false executetest doarraytest staticgetlongarray doarraytest pub_static_array_long doarraytest getlongarray doarraytest pub_array_long assign a java long 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 long array data type class pub static array long long 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 long 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_long 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 static final long serial versionuid 6460763940409461664l public native java class serialversionuid nativejavaclass public native java class scriptable scope class cl this parent scope this java object cl init members nativejavaclass javaobject initmembers protected void init members class cl class java object members java members lookup class parent cl cl static field and methods members get field and methods objects this cl true initmembers javaobject javamembers lookupclass staticfieldandmethods getfieldandmethodsobjects public string get class name return java class getclassname javaclass public boolean has string name scriptable start return members has name true public object get string name scriptable start when used as a constructor script runtime new object asks for our prototype to create an object of the correct type we don t really care what the object is since we re returning one constructed out of whole cloth so we return null if name equals prototype return null object result scriptable not found if static field and methods null result static field and methods get name if result null return result if members has name true result members get this name java object true else experimental look for nested classes by appending name to current class name class nested class find nested class get class object name if nested class null throw members report member not found name native java class nested value new native java class scriptable object get top level scope this nested class nested value set parent scope this result nested value return result scriptruntime newobject not_found staticfieldandmethods staticfieldandmethods javaobject nestedclass findnestedclass getclassobject nestedclass reportmembernotfound nativejavaclass nestedvalue nativejavaclass scriptableobject gettoplevelscope nestedclass nestedvalue setparentscope nestedvalue public void put string name scriptable start object value members put this name java object value true javaobject public object get ids return members get ids true getids getids public class get class object return class super unwrap getclassobject public object get default value class hint if hint null hint script runtime string class return this 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 call context cx scriptable scope scriptable this obj object args if it looks like a cast of an object to this class type walk the prototype chain to see if there s a wrapper of a object that s an instanceof this class if args length 1 args 0 instanceof scriptable class c get class object scriptable p scriptable args 0 do if p instanceof wrapper object o wrapper p unwrap if c is instance o return p p p get prototype while p null return construct cx scope args thisobj getclassobject isinstance getprototype public scriptable construct context cx scriptable scope object args class class object get class object int modifiers class object get modifiers if modifier is interface modifiers modifier is abstract modifiers member box ctors members ctors int index native java method find function cx ctors args if index 0 string sig native java method script signature args throw context report runtime error2 msg no java ctor class object get name sig found the constructor so try invoking it return construct specific cx scope args ctors index else scriptable top level scriptable object get top level scope this string msg try trying to construct an interface use java adapter to construct a new class on the fly that implements this interface object v top level get java adapter top level if v not found function f function v object adapter args this args 0 return scriptable f construct cx top level adapter args catch exception ex fall through to error string m ex get message if m null msg m throw context report runtime error2 msg cant instantiate msg class object get name classobject getclassobject classobject getmodifiers isinterface isabstract memberbox nativejavamethod findfunction nativejavamethod scriptsignature reportruntimeerror2 classobject getname constructspecific toplevel scriptableobject gettoplevelscope javaadapter toplevel javaadapter toplevel not_found adapterargs toplevel adapterargs getmessage reportruntimeerror2 classobject getname static scriptable construct specific context cx scriptable scope object args member box ctor scriptable top level scriptable object get top level scope scope class class object ctor get declaring class class arg types ctor arg types object orig args args for int i 0 i args length i object arg args i object x context js to java arg arg types i if x arg if args orig args args object orig args clone args i x object instance ctor new instance args we need to force this to be wrapped because construct has to return a scriptable return cx get wrap factory wrap new object cx top level instance constructspecific memberbox toplevel scriptableobject gettoplevelscope classobject getdeclaringclass argtypes argtypes origargs jstojava argtypes origargs origargs newinstance _has_ getwrapfactory wrapnewobject toplevel public string to string return java class get class object get name tostring javaclass getclassobject getname determines if prototype is a wrapped java object and performs a java instanceof exception if value is an instance of native java class it isn t considered an instance of the java class this forestalls any name conflicts between java lang class s methods and the static methods exposed by a java native class public boolean has instance scriptable value if value instanceof wrapper value instanceof native java class object instance wrapper value unwrap return get class object is instance instance value wasn t something we understand return false nativejavaclass javanativeclass hasinstance nativejavaclass getclassobject isinstance private static class find nested class class parent class string name string nested class name parent class get name name class loader loader parent class get class loader if loader null alert if loader is null nested class should be loaded via system class loader which can be different from the loader that brought rhino classes that class for name would use but class loader get system class loader is java 2 only return kit class or null nested class name else return kit class or null loader nested class name findnestedclass parentclass nestedclassname parentclass getname classloader parentclass getclassloader forname classloader getsystemclassloader classornull nestedclassname classornull nestedclassname public class datatypes 014 extends live connect test public datatypes 014 super datatypes_014 liveconnecttest datatypes_014 public static void main string args datatypes 014 test new datatypes 014 test start datatypes_014 datatypes_014 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 float array true do array test dt pub static array float true do array test dt get float array true do array test dt pub array float false executetest doarraytest staticgetfloatarray doarraytest pub_static_array_float doarraytest getfloatarray doarraytest pub_array_float assign a java float 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 float array public void do array test string command boolean should equal float array data type class pub static array float float 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 float 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_float 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 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 expect return object 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 expect return short public class function node extends script or fn node public function node string name super token function function name name functionnode scriptorfnnode functionnode functionname public string get function name return function name getfunctionname functionname public boolean requires activation return its needs activation requiresactivation itsneedsactivation public boolean get ignore dynamic scope return its ignore dynamic scope getignoredynamicscope itsignoredynamicscope public static final int function expression statement 3 public int get function type return its function type function_expression_statement getfunctiontype itsfunctiontype call frame clone frozen if frozen kit code bug call frame copy try copy call frame clone catch clone not supported exception ex throw new illegal state exception clone stack but keep var source to point to values from this frame to share variables copy stack object stack clone copy s dbl double s dbl clone copy frozen false return copy callframe clonefrozen codebug callframe callframe clonenotsupportedexception illegalstateexception varsource sdbl sdbl continuation jump continuation c call frame current this captured frame call frame c get implementation if this captured frame null current null continuation and current execution does not share any frames if there is nothing to capture or if there is no currently executed frames this branch frame null else search for branch frame where parent frame chains starting from captured and current meet call frame chain1 this captured frame call frame chain2 current first work parents of chain1 or chain2 until the same frame depth int diff chain1 frame index chain2 frame index if diff 0 if diff 0 swap to make sure that chain1 frame index chain2 frame index and diff 0 chain1 current chain2 this captured frame diff diff do chain1 chain1 parent frame while diff 0 if chain1 frame index chain2 frame index kit code bug now walk parents in parallel until a shared frame is found or until the root is reached while chain1 chain2 chain1 null chain1 chain1 parent frame chain2 chain2 parent frame this branch frame chain1 if this branch frame null this branch frame frozen kit code bug continuationjump callframe capturedframe callframe getimplementation capturedframe branchframe callframe capturedframe callframe frameindex frameindex frameindex frameindex capturedframe parentframe frameindex frameindex codebug parentframe parentframe branchframe branchframe branchframe codebug private static string bytecode name int bytecode if valid bytecode bytecode throw new illegal argument exception string value of bytecode if token printi code return string value of bytecode if valid token code bytecode return token name bytecode switch bytecode case icode dup return dup case icode dup2 return dup2 case icode swap return swap case icode pop return pop case icode pop result return pop result case icode ifeq pop return ifeq pop case icode var inc dec return var inc dec case icode name inc dec return name inc dec case icode prop inc dec return prop inc dec case icode elem inc dec return elem inc dec case icode ref inc dec return ref inc dec case icode scope load return scope load case icode scope save return scope save case icode typeofname return typeofname case icode name and this return name and this case icode prop and this return prop and this case icode elem and this return elem and this case icode value and this return value and this case icode closure expr return closure expr case icode closure stmt return closure stmt case icode callspecial return callspecial case icode retundef return retundef case icode gosub return gosub case icode startsub return startsub case icode retsub return retsub case icode line return line case icode shortnumber return shortnumber case icode intnumber return intnumber case icode literal new return literal new case icode literal set return literal set case icode spare arraylit return spare arraylit case icode reg ind c0 return reg ind c0 case icode reg ind c1 return reg ind c1 case icode reg ind c2 return reg ind c2 case icode reg ind c3 return reg ind c3 case icode reg ind c4 return reg ind c4 case icode reg ind c5 return reg ind c5 case icode reg ind1 return load ind1 case icode reg ind2 return load ind2 case icode reg ind4 return load ind4 case icode reg str c0 return reg str c0 case icode reg str c1 return reg str c1 case icode reg str c2 return reg str c2 case icode reg str c3 return reg str c3 case icode reg str1 return load str1 case icode reg str2 return load str2 case icode reg str4 return load str4 case icode getvar1 return getvar1 case icode setvar1 return setvar1 case icode undef return undef case icode zero return zero case icode one return one case icode enterdq return enterdq case icode leavedq return leavedq case icode tail call return tail call case icode local clear return local clear icode without name throw new illegal state exception string value of bytecode bytecodename validbytecode illegalargumentexception valueof printicode valueof validtokencode icode_dup icode_dup2 icode_swap icode_pop icode_pop_result pop_result icode_ifeq_pop ifeq_pop icode_var_inc_dec var_inc_dec icode_name_inc_dec name_inc_dec icode_prop_inc_dec prop_inc_dec icode_elem_inc_dec elem_inc_dec icode_ref_inc_dec ref_inc_dec icode_scope_load scope_load icode_scope_save scope_save icode_typeofname icode_name_and_this name_and_this icode_prop_and_this prop_and_this icode_elem_and_this elem_and_this icode_value_and_this value_and_this icode_closure_expr closure_expr icode_closure_stmt closure_stmt icode_callspecial icode_retundef icode_gosub icode_startsub icode_retsub icode_line icode_shortnumber icode_intnumber icode_literal_new literal_new icode_literal_set literal_set icode_spare_arraylit spare_arraylit icode_reg_ind_c0 reg_ind_c0 icode_reg_ind_c1 reg_ind_c1 icode_reg_ind_c2 reg_ind_c2 icode_reg_ind_c3 reg_ind_c3 icode_reg_ind_c4 reg_ind_c4 icode_reg_ind_c5 reg_ind_c5 icode_reg_ind1 load_ind1 icode_reg_ind2 load_ind2 icode_reg_ind4 load_ind4 icode_reg_str_c0 reg_str_c0 icode_reg_str_c1 reg_str_c1 icode_reg_str_c2 reg_str_c2 icode_reg_str_c3 reg_str_c3 icode_reg_str1 load_str1 icode_reg_str2 load_str2 icode_reg_str4 load_str4 icode_getvar1 icode_setvar1 icode_undef icode_zero icode_one icode_enterdq icode_leavedq icode_tail_call tail_call icode_local_clear local_clear illegalstateexception valueof private static boolean valid icode int icode return min icode icode icode 1 validicode min_icode private static boolean valid token code int token return token first bytecode token token token token last bytecode token validtokencode first_bytecode_token last_bytecode_token private static boolean valid bytecode int bytecode return valid icode bytecode valid token code bytecode validbytecode validicode validtokencode public object compile compiler environs compiler env script or fn node tree string encoded source boolean return function this compiler env compiler env new node transformer transform tree if token print trees system out println tree to string tree tree if return function tree tree get function node 0 script or fn tree its data new interpreter data compiler env get language version script or fn get source name encoded source its data top level true if return function generate functioni code else generatei code from tree script or fn return its data compilerenvirons compilerenv scriptorfnnode encodedsource returnfunction compilerenv compilerenv nodetransformer printtrees tostringtree returnfunction getfunctionnode scriptorfn itsdata interpreterdata compilerenv getlanguageversion scriptorfn getsourcename encodedsource itsdata toplevel returnfunction generatefunctionicode generateicodefromtree scriptorfn itsdata public script create script object object bytecode object static security domain interpreter data idata interpreter data bytecode return interpreted function create script its data static security domain createscriptobject staticsecuritydomain interpreterdata interpreterdata interpretedfunction createscript itsdata staticsecuritydomain public function create function object context cx scriptable scope object bytecode object static security domain interpreter data idata interpreter data bytecode return interpreted function create function cx scope its data static security domain createfunctionobject staticsecuritydomain interpreterdata interpreterdata interpretedfunction createfunction itsdata staticsecuritydomain private void generate functioni code its in function flag true function node the function function node script or fn its data its function type the function get function type its data its needs activation the function requires activation its data its name the function get function name if the function get ignore dynamic scope if compiler env is use dynamic scope its data use dynamic scope true generatei code from tree the function get last child generatefunctionicode itsinfunctionflag functionnode thefunction functionnode scriptorfn itsdata itsfunctiontype thefunction getfunctiontype itsdata itsneedsactivation thefunction requiresactivation itsdata itsname thefunction getfunctionname thefunction getignoredynamicscope compilerenv isusedynamicscope itsdata usedynamicscope generateicodefromtree thefunction getlastchild private void generatei code from tree node tree generate nested functions generate reg exp literals visit statement tree fix label gotos add return result only to scripts as function always ends with return if its data its function type 0 add token token return result if its data itsi code length itsi code top make its data itsi code length exactly itsi code top to save memory and catch bugs with jumps beyound icode as early as possible byte tmp new byte itsi code top system arraycopy its data itsi code 0 tmp 0 itsi code top its data itsi code tmp if its strings size 0 its data its string table null else its data its string table new string its strings size obj to int map iterator iter its strings new iterator for iter start iter done iter next string str string iter get key int index iter get value if its data its string table index null kit code bug its data its string table index str if its double table top 0 its data its double table null else if its data its double table length its double table top double tmp new double its double table top system arraycopy its data its double table 0 tmp 0 its double table top its data its double table tmp if its exception table top 0 its data its exception table length its exception table top int tmp new int its exception table top system arraycopy its data its exception table 0 tmp 0 its exception table top its data its exception table tmp its data its max vars script or fn get param and var count its max frame array interpret method needs this amount for its stack and s dbl arrays its data its max frame array its data its max vars its data its max locals its data its max stack its data arg names script or fn get param and var names its data arg count script or fn get param count its data encoded source start script or fn get encoded source start its data encoded source end script or fn get encoded source end if its literal ids size 0 its data literal ids its literal ids to array if token printi code dumpi code its data generateicodefromtree generatenestedfunctions generateregexpliterals visitstatement fixlabelgotos return_result itsdata itsfunctiontype addtoken return_result itsdata itsicode itsicodetop itsdata itsicode itsicodetop itsicodetop itsdata itsicode itsicodetop itsdata itsicode itsstrings itsdata itsstringtable itsdata itsstringtable itsstrings objtointmap itsstrings newiterator getkey getvalue itsdata itsstringtable codebug itsdata itsstringtable itsdoubletabletop itsdata itsdoubletable itsdata itsdoubletable itsdoubletabletop itsdoubletabletop itsdata itsdoubletable itsdoubletabletop itsdata itsdoubletable itsexceptiontabletop itsdata itsexceptiontable itsexceptiontabletop itsexceptiontabletop itsdata itsexceptiontable itsexceptiontabletop itsdata itsexceptiontable itsdata itsmaxvars scriptorfn getparamandvarcount itsmaxframearray sdbl itsdata itsmaxframearray itsdata itsmaxvars itsdata itsmaxlocals itsdata itsmaxstack itsdata argnames scriptorfn getparamandvarnames itsdata argcount scriptorfn getparamcount itsdata encodedsourcestart scriptorfn getencodedsourcestart itsdata encodedsourceend scriptorfn getencodedsourceend itsliteralids itsdata literalids itsliteralids toarray printicode dumpicode itsdata private void generate nested functions int function count script or fn get function count if function count 0 return interpreter data array new interpreter data function count for int i 0 i function count i function node def script or fn get function node i interpreter jsi new interpreter jsi compiler env compiler env jsi script or fn def jsi its data new interpreter data its data jsi generate functioni code array i jsi its data its data its nested functions array generatenestedfunctions functioncount scriptorfn getfunctioncount functioncount interpreterdata interpreterdata functioncount functioncount functionnode scriptorfn getfunctionnode compilerenv compilerenv scriptorfn itsdata interpreterdata itsdata generatefunctionicode itsdata itsdata itsnestedfunctions private void generate reg exp literals int n script or fn get regexp count if n 0 return context cx context get context reg exp proxy rep script runtime check reg exp proxy cx object array new object n for int i 0 i n i string string script or fn get regexp string i string flags script or fn get regexp flags i array i rep compile reg exp cx string flags its data its reg exp literals array generateregexpliterals scriptorfn getregexpcount getcontext regexpproxy scriptruntime checkregexpproxy scriptorfn getregexpstring scriptorfn getregexpflags compileregexp itsdata itsregexpliterals private void update line number node node int lineno node get lineno if lineno its line number lineno 0 if its data first linepc 0 its data first linepc lineno its line number lineno add icode icode line add uint16 lineno 0xffff updatelinenumber getlineno itslinenumber itsdata firstlinepc itsdata firstlinepc itslinenumber addicode icode_line adduint16 private runtime exception bad tree node node throw new runtime exception node to string runtimeexception badtree runtimeexception tostring private void visit statement node node int type node get type node child node get first child switch type case token function int fn index node get existing int prop node function prop int fn type script or fn get function node fn index get function type only function expressions or function expression statements needs closure code creating new function object on stack as function statements are initialized at script function start in addition function expression can not present here at statement level they must only present as expressions if fn type function node function expression statement add index op icode closure stmt fn index else if fn type function node function statement throw kit code bug break case token script case token label case token loop case token block case token empty case token with update line number node while child null visit statement child child child get next break case token enterwith visit expression child 0 add token token enterwith stack change 1 break case token leavewith add token token leavewith break case token local block int local alloc local node put int prop node local prop local update line number node while child null visit statement child child child get next add index op icode local clear local release local local break case token switch update line number node see comments in ir factory create switch for description of switch node node switch node node jump node visit expression child 0 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 bad tree case node node test case node get first child add icode icode dup stack change 1 visit expression test 0 add token token sheq stack change 1 if true icode ifeq pop will jump and remove case value from stack add goto case node target icode ifeq pop stack change 1 add icode icode pop stack change 1 break case token target mark target label node break case token ifeq case token ifne node target node jump node target visit expression child 0 add goto target type stack change 1 break case token goto node target node jump node target add goto target type break case token jsr node target node jump node target add goto target icode gosub break case token finally account for incomming gotosub address stack change 1 int finally register get local block ref node add index op icode startsub finally register stack change 1 while child null visit statement child child child get next add index op icode retsub finally register break case token expr void case token expr result update line number node visit expression child 0 add icode type token expr void icode pop icode pop result stack change 1 break case token try node jump try node node jump node int exception object local get local block ref try node int scope local alloc local add index op icode scope save scope local int try start itsi code top while child null visit statement child child child get next node catch target try node target if catch target null int catch startpc its label table get target label catch target add exception handler try start catch startpc catch startpc false exception object local scope local node finally target try node get finally if finally target null int finally startpc its label table get target label finally target add exception handler try start finally startpc finally startpc true exception object local scope local add index op icode local clear scope local release local scope local break case token catch scope int local index get local block ref node int scope index node get existing int prop node catch scope prop string name child get string child child get next visit expression child 0 load expression object add string prefix name add index prefix local index add token token catch scope add uint8 scope index 0 1 0 stack change 1 break case token throw update line number node visit expression child 0 add token token throw add uint16 its line number 0xffff stack change 1 break case token rethrow update line number node add index op token rethrow get local block ref node break case token return update line number node if child null visit expression child ecf tail add token token return stack change 1 else add icode icode retundef break case token return result update line number node add token token return result break case token enum init keys case token enum init values visit expression child 0 add index op type get local block ref node stack change 1 break default throw bad tree node if its stack depth 0 throw kit code bug visitstatement gettype getfirstchild fnindex getexistingintprop function_prop fntype scriptorfn getfunctionnode fnindex getfunctiontype fntype functionnode function_expression_statement addindexop icode_closure_stmt fnindex fntype functionnode function_statement codebug updatelinenumber visitstatement getnext visitexpression addtoken stackchange addtoken local_block alloclocal putintprop local_prop updatelinenumber visitstatement getnext addindexop icode_local_clear releaselocal updatelinenumber irfactory createswitch switchnode visitexpression casenode getnext casenode casenode casenode getnext casenode gettype badtree casenode casenode getfirstchild addicode icode_dup stackchange visitexpression addtoken stackchange icode_ifeq_pop addgoto casenode icode_ifeq_pop stackchange addicode icode_pop stackchange marktargetlabel visitexpression addgoto stackchange addgoto addgoto icode_gosub stackchange finallyregister getlocalblockref addindexop icode_startsub finallyregister stackchange visitstatement getnext addindexop icode_retsub finallyregister expr_void expr_result updatelinenumber visitexpression addicode expr_void icode_pop icode_pop_result stackchange trynode exceptionobjectlocal getlocalblockref trynode scopelocal alloclocal addindexop icode_scope_save scopelocal trystart itsicodetop visitstatement getnext catchtarget trynode catchtarget catchstartpc itslabeltable gettargetlabel catchtarget addexceptionhandler trystart catchstartpc catchstartpc exceptionobjectlocal scopelocal finallytarget trynode getfinally finallytarget finallystartpc itslabeltable gettargetlabel finallytarget addexceptionhandler trystart finallystartpc finallystartpc exceptionobjectlocal scopelocal addindexop icode_local_clear scopelocal releaselocal scopelocal catch_scope localindex getlocalblockref scopeindex getexistingintprop catch_scope_prop getstring getnext visitexpression addstringprefix addindexprefix localindex addtoken catch_scope adduint8 scopeindex stackchange updatelinenumber visitexpression addtoken adduint16 itslinenumber stackchange updatelinenumber addindexop getlocalblockref updatelinenumber visitexpression ecf_tail addtoken stackchange addicode icode_retundef return_result updatelinenumber addtoken return_result enum_init_keys enum_init_values visitexpression addindexop getlocalblockref stackchange badtree itsstackdepth codebug private void visit expression node node int context flags int type node get type node child node get first child int saved stack depth its stack depth switch type case token function int fn index node get existing int prop node function prop function node fn script or fn get function node fn index see comments in visit statement for token function case if fn get function type function node function expression throw kit code bug add index op icode closure expr fn index stack change 1 break case token local load int local index get local block ref node add index op token local load local index stack change 1 break case token comma node last child node get last child while child last child visit expression child 0 add icode icode pop stack change 1 child child get next preserve tail context flag if any visit expression child context flags ecf tail break case token use stack indicates that stack was modified externally like placed catch object stack change 1 break case token ref call case token call case token new if type token new visit expression child 0 else generate call fun and this child int arg count 0 while child child get next null visit expression child 0 arg count int call type node get int prop node specialcall prop node non specialcall if call type node non specialcall embed line number and source filename add index op icode callspecial arg count add uint8 call type add uint8 type token new 1 0 add uint16 its line number 0xffff else if type token call if context flags ecf tail 0 type icode tail call add index op type arg count adjust stack if type token new new f args result stack change arg count else call f this obj args result ref call f this obj args ref stack change 1 arg count if arg count its data its max callee args its data its max callee args arg count break case token and case token or visit expression child 0 add icode icode dup stack change 1 int after second jump start itsi code top int jump type token and token ifne token ifeq add goto op jump stack change 1 add icode icode pop stack change 1 child child get next preserve tail context flag if any visit expression child context flags ecf tail resolve forward goto after second jump start break case token hook node if then child get next node if else if then get next visit expression child 0 int else jump start itsi code top add goto op token ifne stack change 1 preserve tail context flag if any visit expression if then context flags ecf tail int after else jump start itsi code top add goto op token goto resolve forward goto else jump start its stack depth saved stack depth preserve tail context flag if any visit expression if else context flags ecf tail resolve forward goto after else jump start break case token getprop visit expression child 0 child child get next add string op token getprop child get string break case token getelem case token delprop case token bitand case token bitor case token bitxor case token lsh case token rsh case token ursh case token add case token sub case token mod case token div case token mul case token eq case token ne case token sheq case token shne case token in case token instanceof case token le case token lt case token ge case token gt visit expression child 0 child child get next visit expression child 0 add token type stack change 1 break case token pos case token neg case token not case token bitnot case token typeof case token void visit expression child 0 if type token void add icode icode pop add icode icode undef else add token type break case token get ref case token del ref visit expression child 0 add token type break case token setprop case token setprop op visit expression child 0 child child get next string property child get string child child get next if type token setprop op add icode icode dup stack change 1 add string op token getprop property compensate for the following use stack stack change 1 visit expression child 0 add string op token setprop property stack change 1 break case token setelem case token setelem op visit expression child 0 child child get next visit expression child 0 child child get next if type token setelem op add icode icode dup2 stack change 2 add token token getelem stack change 1 compensate for the following use stack stack change 1 visit expression child 0 add token token setelem stack change 2 break case token set ref case token set ref op visit expression child 0 child child get next if type token set ref op add icode icode dup stack change 1 add token token get ref compensate for the following use stack stack change 1 visit expression child 0 add token token set ref stack change 1 break case token setname string name child get string visit expression child 0 child child get next visit expression child 0 add string op token setname name stack change 1 break case token typeofname string name node get string int index 1 use typeofname if an activation frame exists since the vars all exist there instead of in jregs if its in function flag its data its needs activation index script or fn get param or var index name if index 1 add string op icode typeofname name stack change 1 else add var op token getvar index stack change 1 add token token typeof break case token bindname case token name case token string add string op type node get string stack change 1 break case token inc case token dec visit inc dec node child break case token number double num node get double int inum int num if inum num if inum 0 add icode icode zero check for negative ze visitexpression contextflags gettype getfirstchild savedstackdepth itsstackdepth fnindex getexistingintprop function_prop functionnode scriptorfn getfunctionnode fnindex visitstatement getfunctiontype functionnode function_expression codebug addindexop icode_closure_expr fnindex stackchange local_load localindex getlocalblockref addindexop local_load localindex stackchange lastchild getlastchild lastchild visitexpression addicode icode_pop stackchange getnext visitexpression contextflags ecf_tail use_stack stackchange ref_call visitexpression generatecallfunandthis argcount getnext visitexpression argcount calltype getintprop specialcall_prop non_specialcall calltype non_specialcall addindexop icode_callspecial argcount adduint8 calltype adduint8 adduint16 itslinenumber contextflags ecf_tail icode_tail_call addindexop argcount stackchange argcount thisobj ref_call thisobj stackchange argcount argcount itsdata itsmaxcalleeargs itsdata itsmaxcalleeargs argcount visitexpression addicode icode_dup stackchange aftersecondjumpstart itsicodetop addgotoop stackchange addicode icode_pop stackchange getnext visitexpression contextflags ecf_tail resolveforwardgoto aftersecondjumpstart ifthen getnext ifelse ifthen getnext visitexpression elsejumpstart itsicodetop addgotoop stackchange visitexpression ifthen contextflags ecf_tail afterelsejumpstart itsicodetop addgotoop resolveforwardgoto elsejumpstart itsstackdepth savedstackdepth visitexpression ifelse contextflags ecf_tail resolveforwardgoto afterelsejumpstart visitexpression getnext addstringop getstring visitexpression getnext visitexpression addtoken stackchange visitexpression addicode icode_pop addicode icode_undef addtoken get_ref del_ref visitexpression addtoken setprop_op visitexpression getnext getstring getnext setprop_op addicode icode_dup stackchange addstringop use_stack stackchange visitexpression addstringop stackchange setelem_op visitexpression getnext visitexpression getnext setelem_op addicode icode_dup2 stackchange addtoken stackchange use_stack stackchange visitexpression addtoken stackchange set_ref set_ref_op visitexpression getnext set_ref_op addicode icode_dup stackchange addtoken get_ref use_stack stackchange visitexpression addtoken set_ref stackchange getstring visitexpression getnext visitexpression addstringop stackchange getstring itsinfunctionflag itsdata itsneedsactivation scriptorfn getparamorvarindex addstringop icode_typeofname stackchange addvarop stackchange addtoken addstringop getstring stackchange visitincdec getdouble addicode icode_zero private void generate call fun and this node left generate code to place on stack function and this obj int type left get type switch type case token name string name left get string stack function this obj add string op icode name and this name stack change 2 break case token getprop case token getelem node target left get first child visit expression target 0 node id target get next if type token getprop string property id get string stack target function this obj add string op icode prop and this property stack change 1 else visit expression id 0 stack target id function this obj add icode icode elem and this break default including token getvar visit expression left 0 stack value function this obj add icode icode value and this stack change 1 break generatecallfunandthis thisobj gettype getstring thisobj addstringop icode_name_and_this stackchange getfirstchild visitexpression getnext getstring thisobj addstringop icode_prop_and_this stackchange visitexpression thisobj addicode icode_elem_and_this visitexpression thisobj addicode icode_value_and_this stackchange private void visit inc dec node node node child int incr decr mask node get existing int prop node incrdecr prop int child type child get type switch child type case token getvar if its data its needs activation kit code bug string name child get string int i script or fn get param or var index name add var op icode var inc dec i add uint8 incr decr mask stack change 1 break case token name string name child get string add string op icode name inc dec name add uint8 incr decr mask stack change 1 break case token getprop node object child get first child visit expression object 0 string property object get next get string add string op icode prop inc dec property add uint8 incr decr mask break case token getelem node object child get first child visit expression object 0 node index object get next visit expression index 0 add icode icode elem inc dec add uint8 incr decr mask stack change 1 break case token get ref node ref child get first child visit expression ref 0 add icode icode ref inc dec add uint8 incr decr mask break default throw bad tree node visitincdec incrdecrmask getexistingintprop incrdecr_prop childtype gettype childtype itsdata itsneedsactivation codebug getstring scriptorfn getparamorvarindex addvarop icode_var_inc_dec adduint8 incrdecrmask stackchange getstring addstringop icode_name_inc_dec adduint8 incrdecrmask stackchange getfirstchild visitexpression getnext getstring addstringop icode_prop_inc_dec adduint8 incrdecrmask getfirstchild visitexpression getnext visitexpression addicode icode_elem_inc_dec adduint8 incrdecrmask stackchange get_ref getfirstchild visitexpression addicode icode_ref_inc_dec adduint8 incrdecrmask badtree private void visit literal node node node child int type node get type int count object property ids null if type token arraylit count 0 for node n child n null n n get next count else if type token objectlit property ids object node get prop node object ids prop count property ids length else throw bad tree node add index op icode literal new count stack change 1 while child null visit expression child 0 add icode icode literal set stack change 1 child child get next if type token arraylit int skip indexes int node get prop node skip indexes prop if skip indexes null add token token arraylit else int index its literal ids size its literal ids add skip indexes add index op icode spare arraylit index else int index its literal ids size its literal ids add property ids add index op token objectlit index visitliteral gettype propertyids getnext propertyids getprop object_ids_prop propertyids badtree addindexop icode_literal_new stackchange visitexpression addicode icode_literal_set stackchange getnext skipindexes getprop skip_indexes_prop skipindexes addtoken itsliteralids itsliteralids skipindexes addindexop icode_spare_arraylit itsliteralids itsliteralids propertyids addindexop private int get local block ref node node node local block node node get prop node local block prop return local block get existing int prop node local prop getlocalblockref localblock getprop local_block_prop localblock getexistingintprop local_prop private int get target label node target int label target label id if label 1 return label label its label table top if its label table null label 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 label its label table tmp its label table top label 1 its label table label 1 target label id label return label gettargetlabel labelid itslabeltabletop itslabeltable itslabeltable itslabeltable itslabeltable min_label_table_size itslabeltable itslabeltable itslabeltable itslabeltabletop itslabeltable labelid private void mark target label node target int label get target label target if its label table label 1 can mark label only once kit code bug its label table label itsi code top marktargetlabel gettargetlabel itslabeltable codebug itslabeltable itsicodetop private void add goto node target int goto op int label get target label target if label its label table top kit code bug int targetpc its label table label if targetpc 1 add backward goto goto op targetpc else int gotopc itsi code top add goto op goto op 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 gotopc addgoto gotoop gettargetlabel itslabeltabletop codebug itslabeltable addbackwardgoto gotoop itsicodetop addgotoop gotoop itsfixuptabletop itsfixuptable itsfixuptable itsfixuptable itsfixuptable min_fixup_table_size itsfixuptable itsfixuptable itsfixuptable itsfixuptabletop itsfixuptable private void fix label gotos for int i 0 i its fixup table top i long fixup its fixup table i int label int fixup 32 int jump source int fixup int pc its label table label if pc 1 unlocated label throw kit code bug resolve goto jump source pc its fixup table top 0 fixlabelgotos itsfixuptabletop itsfixuptable jumpsource itslabeltable codebug resolvegoto jumpsource itsfixuptabletop private void add backward goto int goto op int jumppc int frompc itsi code top ensure that this is a jump backward if frompc jumppc throw kit code bug add goto op goto op resolve goto frompc jumppc addbackwardgoto gotoop itsicodetop codebug addgotoop gotoop resolvegoto private void resolve forward goto int frompc ensure that forward jump skips at least self bytecode if itsi code top frompc 3 throw kit code bug resolve goto frompc itsi code top resolveforwardgoto itsicodetop codebug resolvegoto itsicodetop private void resolve goto int frompc int jumppc int offset jumppc frompc ensure that jumps do not overlap if 0 offset offset 2 throw kit code bug int offset site frompc 1 if offset short offset if its data long jumps null its data long jumps new uint map its data long jumps put offset site jumppc offset 0 byte array its data itsi code array offset site byte offset 8 array offset site 1 byte offset resolvegoto codebug offsetsite itsdata longjumps itsdata longjumps uintmap itsdata longjumps offsetsite itsdata itsicode offsetsite offsetsite private void add token int token if valid token code token throw kit code bug add uint8 token addtoken validtokencode codebug adduint8 private void add icode int icode if valid icode icode throw kit code bug write negative icode as uint8 bits add uint8 icode 0xff addicode validicode codebug adduint8 private void add uint8 int value if value 0xff 0 throw kit code bug byte array its data itsi code int top itsi code top if top array length array increasei code capasity 1 array top byte value itsi code top top 1 adduint8 codebug itsdata itsicode itsicodetop increaseicodecapasity itsicodetop private void add uint16 int value if value 0xffff 0 throw kit code bug byte array its data itsi code int top itsi code top if top 2 array length array increasei code capasity 2 array top byte value 8 array top 1 byte value itsi code top top 2 adduint16 codebug itsdata itsicode itsicodetop increaseicodecapasity itsicodetop private void add int int i byte array its data itsi code int top itsi code top if top 4 array length array increasei code capasity 4 array top byte i 24 array top 1 byte i 16 array top 2 byte i 8 array top 3 byte i itsi code top top 4 addint itsdata itsicode itsicodetop increaseicodecapasity itsicodetop private int get double index double num int index its double table top if index 0 its data its double table new double 64 else if its data its double table length index double na new double index 2 system arraycopy its data its double table 0 na 0 index its data its double table na its data its double table index num its double table top index 1 return index getdoubleindex itsdoubletabletop itsdata itsdoubletable itsdata itsdoubletable itsdata itsdoubletable itsdata itsdoubletable itsdata itsdoubletable itsdoubletabletop private void add goto op int goto op byte array its data itsi code int top itsi code top if top 3 array length array increasei code capasity 3 array top byte goto op offset would written later itsi code top top 1 2 addgotoop gotoop itsdata itsicode itsicodetop increaseicodecapasity gotoop itsicodetop private void add var op int op int var index switch op case token getvar case token setvar if var index 128 add icode op token getvar icode getvar1 icode setvar1 add uint8 var index return fallthrough case icode var inc dec add index op op var index return throw kit code bug addvarop varindex varindex addicode icode_getvar1 icode_setvar1 adduint8 varindex icode_var_inc_dec addindexop varindex codebug private void add string op int op string str add string prefix str if valid icode op add icode op else add token op addstringop addstringprefix validicode addicode addtoken private void add index op int op int index add index prefix index if valid icode op add icode op else add token op addindexop addindexprefix validicode addicode addtoken private void add string prefix string str int index its strings get str 1 if index 1 index its strings size its strings put str index if index 4 add icode icode reg str c0 index else if index 0xff add icode icode reg str1 add uint8 index else if index 0xffff add icode icode reg str2 add uint16 index else add icode icode reg str4 add int index addstringprefix itsstrings itsstrings itsstrings addicode icode_reg_str_c0 addicode icode_reg_str1 adduint8 addicode icode_reg_str2 adduint16 addicode icode_reg_str4 addint private void add index prefix int index if index 0 kit code bug if index 6 add icode icode reg ind c0 index else if index 0xff add icode icode reg ind1 add uint8 index else if index 0xffff add icode icode reg ind2 add uint16 index else add icode icode reg ind4 add int index addindexprefix codebug addicode icode_reg_ind_c0 addicode icode_reg_ind1 adduint8 addicode icode_reg_ind2 adduint16 addicode icode_reg_ind4 addint private void add exception handler int icode start int icode end int handler start boolean is finally int exception object local int scope local int top its exception table top int table its data its exception table if table null if top 0 kit code bug table new int exception slot size 2 its data its exception table table else if table length top table new int table length 2 system arraycopy its data its exception table 0 table 0 top its data its exception table table table top exception try start slot icode start table top exception try end slot icode end table top exception handler slot handler start table top exception type slot is finally 1 0 table top exception local slot exception object local table top exception scope slot scope local its exception table top top exception slot size addexceptionhandler icodestart icodeend handlerstart isfinally exceptionobjectlocal scopelocal itsexceptiontabletop itsdata itsexceptiontable codebug exception_slot_size itsdata itsexceptiontable itsdata itsexceptiontable itsdata itsexceptiontable exception_try_start_slot icodestart exception_try_end_slot icodeend exception_handler_slot handlerstart exception_type_slot isfinally exception_local_slot exceptionobjectlocal exception_scope_slot scopelocal itsexceptiontabletop exception_slot_size private byte increasei code capasity int extra size int capacity its data itsi code length int top itsi code top if top extra size capacity throw kit code bug capacity 2 if top extra size capacity capacity top extra size byte array new byte capacity system arraycopy its data itsi code 0 array 0 top its data itsi code array return array increaseicodecapasity extrasize itsdata itsicode itsicodetop extrasize codebug extrasize extrasize itsdata itsicode itsdata itsicode private void stack change int change if change 0 its stack depth change else int new depth its stack depth change if new depth its data its max stack its data its max stack new depth its stack depth new depth stackchange itsstackdepth newdepth itsstackdepth newdepth itsdata itsmaxstack itsdata itsmaxstack newdepth itsstackdepth newdepth private int alloc local int local slot its local top its local top if its local top its data its max locals its data its max locals its local top return local slot alloclocal localslot itslocaltop itslocaltop itslocaltop itsdata itsmaxlocals itsdata itsmaxlocals itslocaltop localslot private void release local int local slot its local top if local slot its local top kit code bug releaselocal localslot itslocaltop localslot itslocaltop codebug private static int get short byte i code int pc return i code pc 8 i code pc 1 0xff getshort icode icode icode private static int get index byte i code int pc return i code pc 0xff 8 i code pc 1 0xff getindex icode icode icode private static int get int byte i code int pc return i code pc 24 i code pc 1 0xff 16 i code pc 2 0xff 8 i code pc 3 0xff getint icode icode icode icode icode private static int get exception handler call frame frame boolean only finally int exception table frame idata its exception table if exception table null no exception handlers return 1 icode switch in the interpreter increments pc immediately and it is necessary to subtract 1 from the saved pc to point it before the start of the next instruction int pc frame pc 1 opt use binary search int best 1 best start 0 best end 0 for int i 0 i exception table length i exception slot size int start exception table i exception try start slot int end exception table i exception try end slot if start pc pc end continue if only finally exception table i exception type slot 1 continue if best 0 since handlers always nest and they never have shared end although they can share start it is sufficient to compare handlers ends if best end end continue check the above assumption if best start start kit code bug should be nested if best end end kit code bug no ens sharing best i best start start best end end return best getexceptionhandler callframe onlyfinally exceptiontable itsexceptiontable exceptiontable beststart bestend exceptiontable exception_slot_size exceptiontable exception_try_start_slot exceptiontable exception_try_end_slot onlyfinally exceptiontable exception_type_slot bestend beststart codebug bestend codebug beststart bestend private static void dumpi code interpreter data idata if token printi code return byte i code idata itsi code int i code length i code length string strings idata its string table print stream out system out out println i code dump for idata its name length i code length out println max stack idata its max stack int index reg 0 for int pc 0 pc i code length out flush out print pc int token i code pc int icode length bytecode span token string tname bytecode name token int old pc pc pc switch token default if icode length 1 kit code bug out println tname break case icode gosub case token goto case token ifeq case token ifne case icode ifeq pop case icode leavedq int newpc pc get short i code pc 1 out println tname newpc pc 2 break case icode var inc dec case icode name inc dec case icode prop inc dec case icode elem inc dec case icode ref inc dec int incr decr type i code pc out println tname incr decr type pc break case icode callspecial int call type i code pc 0xff boolean is new i code pc 1 0 int line get index i code pc 2 out println tname call type is new index reg line pc 4 break case token catch scope boolean after fisrt flag i code pc 0 out println tname after fisrt flag pc break case token regexp out println tname idata its reg exp literals index reg break case token objectlit case icode spare arraylit out println tname idata literal ids index reg break case icode closure expr case icode closure stmt out println tname idata its nested functions index reg break case token call case icode tail call case token ref call case token new out println tname index reg break case token throw int line get index i code pc out println tname line pc 2 break case icode shortnumber int value get short i code pc out println tname value pc 2 break case icode intnumber int value get int i code pc out println tname value pc 4 break case token number double value idata its double table index reg out println tname value pc 2 break case icode line int line get index i code pc out println tname line pc 2 break case icode reg str1 string str strings 0xff i code pc out println tname str pc break case icode reg str2 string str strings get index i code pc out println tname str pc 2 break case icode reg str4 string str strings get int i code pc out println tname str pc 4 break case icode reg ind1 index reg 0xff i code pc out println tname index reg pc break case icode reg ind2 index reg get index i code pc out println tname index reg pc 2 break case icode reg ind4 index reg get int i code pc out println tname index reg pc 4 break case icode getvar1 case icode setvar1 index reg i code pc out println tname index reg pc break if old pc icode length pc kit code bug int table idata its exception table if table null out println exception handlers table length exception slot size for int i 0 i table length i exception slot size int try start table i exception try start slot int try end table i exception try end slot int handler start table i exception handler slot int type table i exception type slot int exception local table i exception local slot int scope local table i exception scope slot out println try start try start try end try end handler start handler start type type 0 catch finally exception local exception local out flush dumpicode interpreterdata printicode icode itsicode icodelength icode itsstringtable printstream icode itsname icodelength maxstack itsmaxstack indexreg icodelength icode icodelength bytecodespan bytecodename old_pc icodelength codebug icode_gosub icode_ifeq_pop icode_leavedq getshort icode icode_var_inc_dec icode_name_inc_dec icode_prop_inc_dec icode_elem_inc_dec icode_ref_inc_dec incrdecrtype icode incrdecrtype icode_callspecial calltype icode isnew icode getindex icode calltype isnew indexreg catch_scope afterfisrtflag icode afterfisrtflag itsregexpliterals indexreg icode_spare_arraylit literalids indexreg icode_closure_expr icode_closure_stmt itsnestedfunctions indexreg icode_tail_call ref_call indexreg getindex icode icode_shortnumber getshort icode icode_intnumber getint icode itsdoubletable indexreg icode_line getindex icode icode_reg_str1 icode icode_reg_str2 getindex icode icode_reg_str4 getint icode icode_reg_ind1 indexreg icode indexreg icode_reg_ind2 indexreg getindex icode indexreg icode_reg_ind4 indexreg getint icode indexreg icode_getvar1 icode_setvar1 indexreg icode indexreg old_pc icodelength codebug itsexceptiontable exception_slot_size exception_slot_size trystart exception_try_start_slot tryend exception_try_end_slot handlerstart exception_handler_slot exception_type_slot exceptionlocal exception_local_slot scopelocal exception_scope_slot trystart trystart tryend tryend handlerstart handlerstart exceptionlocal exceptionlocal private static int bytecode span int bytecode switch bytecode case token throw source line return 1 2 case icode gosub case token goto case token ifeq case token ifne case icode ifeq pop case icode leavedq target pc offset return 1 2 case icode callspecial call type is new line number return 1 1 1 2 case token catch scope scope flag return 1 1 case icode var inc dec case icode name inc dec case icode prop inc dec case icode elem inc dec case icode ref inc dec type of return 1 1 case icode shortnumber short number return 1 2 case icode intnumber int number return 1 4 case icode reg ind1 ubyte index return 1 1 case icode reg ind2 ushort index return 1 2 case icode reg ind4 int index return 1 4 case icode reg str1 ubyte string index return 1 1 case icode reg str2 ushort string index return 1 2 case icode reg str4 int string index return 1 4 case icode getvar1 case icode setvar1 byte var index return 1 1 case icode line line number return 1 2 if valid bytecode bytecode throw kit code bug return 1 bytecodespan icode_gosub icode_ifeq_pop icode_leavedq icode_callspecial catch_scope icode_var_inc_dec icode_name_inc_dec icode_prop_inc_dec icode_elem_inc_dec icode_ref_inc_dec icode_shortnumber icode_intnumber icode_reg_ind1 icode_reg_ind2 icode_reg_ind4 icode_reg_str1 icode_reg_str2 icode_reg_str4 icode_getvar1 icode_setvar1 icode_line validbytecode codebug static int get line numbers interpreter data data uint map present lines new uint map byte i code data itsi code int i code length i code length for int pc 0 pc i code length int bytecode i code pc int span bytecode span bytecode if bytecode icode line if span 3 kit code bug int line get index i code pc 1 present lines put line 0 pc span return present lines get keys getlinenumbers interpreterdata uintmap presentlines uintmap icode itsicode icodelength icode icodelength icode bytecodespan icode_line codebug getindex icode presentlines presentlines getkeys static void capture interpreter stack info rhino exception ex context cx context get current context if cx null cx last interpreter frame null no interpreter invocations ex interpreter stack info null ex interpreter line data null return has interpreter frame on the stack call frame array if cx previous interpreter invocations null cx previous interpreter invocations size 0 array new call frame 1 else int previous count cx previous interpreter invocations size if cx previous interpreter invocations peek cx last interpreter frame it can happen if exception was generated after frame was pushed to cx previous interpreter invocations but before assignment to cx last interpreter frame in this case frames has to be ignored previous count array new call frame previous count 1 cx previous interpreter invocations to array array array array length 1 call frame cx last interpreter frame int interpreter frame count 0 for int i 0 i array length i interpreter frame count 1 array i frame index int linepc new int interpreter frame count fill linepc with pc positions from all interpreter frames start from the most nested frame int linepc index interpreter frame count for int i array length i 0 i call frame frame array i while frame null linepc index linepc linepc index frame pc source line start frame frame parent frame if linepc index 0 kit code bug ex interpreter stack info array ex interpreter line data linepc captureinterpreterstackinfo rhinoexception getcurrentcontext lastinterpreterframe interpreterstackinfo interpreterlinedata callframe previousinterpreterinvocations previousinterpreterinvocations callframe previouscount previousinterpreterinvocations previousinterpreterinvocations lastinterpreterframe previousinterpreterinvocations lastinterpreterframe previouscount callframe previouscount previousinterpreterinvocations toarray callframe lastinterpreterframe interpreterframecount interpreterframecount frameindex interpreterframecount linepcindex interpreterframecount callframe linepcindex linepcindex pcsourcelinestart parentframe linepcindex codebug interpreterstackinfo interpreterlinedata static string get source position from stack context cx int linep call frame frame call frame cx last interpreter frame interpreter data idata frame idata if frame pc source line start 0 linep 0 get index idata itsi code frame pc source line start else linep 0 0 return idata its source file getsourcepositionfromstack callframe callframe lastinterpreterframe interpreterdata pcsourcelinestart getindex itsicode pcsourcelinestart itssourcefile static string get patched stack rhino exception ex string native stack trace string tag org mozilla javascript interpreter interpret loop string buffer sb new string buffer native stack trace length 1000 string line separator system get property line separator call frame array call frame ex interpreter stack info int linepc ex interpreter line data int array index array length int linepc index linepc length int offset 0 while array index 0 array index int pos native stack trace index of tag offset if pos 0 break skip tag length pos tag length skip until the end of line for pos native stack trace length pos char c native stack trace char at pos if c n c r break sb append native stack trace substring offset pos offset pos call frame frame array array index while frame null if linepc index 0 kit code bug linepc index interpreter data idata frame idata sb append line separator sb append tat script if idata its name null idata its name length 0 sb append sb append idata its name sb append sb append idata its source file int pc linepc linepc index if pc 0 include line info only if available sb append sb append get index idata itsi code pc sb append frame frame parent frame sb append native stack trace substring offset return sb to string getpatchedstack rhinoexception nativestacktrace interpretloop stringbuffer stringbuffer nativestacktrace lineseparator getproperty callframe callframe interpreterstackinfo interpreterlinedata arrayindex linepcindex arrayindex arrayindex nativestacktrace indexof nativestacktrace nativestacktrace charat nativestacktrace callframe arrayindex linepcindex codebug linepcindex interpreterdata lineseparator itsname itsname itsname itssourcefile linepcindex getindex itsicode parentframe nativestacktrace tostring static string get encoded source interpreter data idata if idata encoded source null return null return idata encoded source substring idata encoded source start idata encoded source end getencodedsource interpreterdata encodedsource encodedsource encodedsourcestart encodedsourceend private static void init function context cx scriptable scope interpreted function parent int index interpreted function fn fn interpreted function create function cx scope parent index script runtime init function cx scope fn fn idata its function type parent idata eval script flag initfunction interpretedfunction interpretedfunction interpretedfunction createfunction scriptruntime initfunction itsfunctiontype evalscriptflag static object interpret interpreted function ifun context cx scriptable scope scriptable this obj object args if script runtime has top call cx kit code bug if cx interpreter security domain ifun security domain object saved domain cx interpreter security domain cx interpreter security domain ifun security domain try return ifun security controller call with domain ifun security domain cx ifun scope this obj args finally cx interpreter security domain saved domain call frame frame new call frame init frame cx scope this obj args null 0 args length ifun null frame return interpret loop cx frame null interpretedfunction thisobj scriptruntime hastopcall codebug interpretersecuritydomain securitydomain saveddomain interpretersecuritydomain interpretersecuritydomain securitydomain securitycontroller callwithdomain securitydomain thisobj interpretersecuritydomain saveddomain callframe callframe initframe thisobj interpretloop public static object restart continuation continuation c context cx scriptable scope object args if script runtime has top call cx return script runtime do top call c cx scope null args object arg if args length 0 arg undefined instance else arg args 0 call frame captured frame call frame c get implementation if captured frame null no frames to restart return arg continuation jump cjump new continuation jump c null cjump result arg return interpret loop cx null cjump restartcontinuation scriptruntime hastopcall scriptruntime dotopcall callframe capturedframe callframe getimplementation capturedframe continuationjump continuationjump interpretloop private static object interpret loop context cx call frame frame object throwable throwable holds exception object to rethrow or catch it is also used for continuation restart in which case it holds continuation jump final object dbl mrk unique tag double mark final object undefined undefined instance final boolean instruction counting cx instruction threshold 0 arbitrary number to add to instruction count when calling other functions final int invocation cost 100 arbitrary exception cost for instruction counting final int exception cost 100 string string reg null int index reg 1 if cx last interpreter frame null save the top frame from the previous interpreter loop invocation on the stack if cx previous interpreter invocations null cx previous interpreter invocations new obj array cx previous interpreter invocations push cx last interpreter frame when restarting continuation throwable is not null and to jump to the code that rewind continuation state index reg should be set to 1 with the normal call throable null and index reg 1 allows to catch bugs with using inde reg to access array eleemnts before initializing index reg if throwable null assert assumptions if throwable instanceof continuation jump it should be continuation kit code bug object interpreter result null double interpreter result dbl 0 0 state loop for without exceptions try if throwable null recovering from exception index reg contains the index of handler if index reg 0 normal excepton handler transfer control appropriately if frame frozen xxx deal with exceptios frame frame clone frozen int table frame idata its exception table frame pc table index reg exception handler slot if instruction counting frame pc prev branch frame pc frame saved stack top frame empty stack top int scope local frame local shift table index reg exception scope slot int ex local frame local shift table index reg exception local slot frame scope scriptable frame stack scope local frame stack ex local throwable throwable null else continuation restoration continuation jump cjump continuation jump throwable clear throwable to indicate that execptions are ok throwable null if cjump branch frame frame kit code bug check that we have at least one frozen frame in the case of detached continuation restoration unwind code ensure that if cjump captured frame null kit code bug need to rewind branch frame captured frame and all frames in between int rewind count cjump captured frame frame index 1 if cjump branch frame null rewind count cjump branch frame frame index int enter count 0 call frame enter frames null call frame x cjump captured frame for int i 0 i rewind count i if x frozen kit code bug if is frame enter exit required x if enter frames null allocate enough space to store the rest of rewind frames in case all of them would require to enter enter frames new call frame rewind count i enter frames enter count x enter count x x parent frame while enter count 0 execute enter walk enter frames in the reverse order since they were stored starting from the captured frame not branch frame enter count x enter frames enter count enter frame cx x script runtime empty args continuation jump is almost done captured frame points to the call to the function that captured continuation so clone captured frame and emulate return that function with the suplied result frame cjump captured frame clone frozen set call result frame cjump result cjump result dbl restart the execution should be already cleared if throwable null kit code bug else if frame frozen kit code bug use local variables for constant values in frame for faster access object stack frame stack double s dbl frame s dbl object vars frame var source stack double var dbls frame var source s dbl byte i code frame idata itsi code string strings frame idata its string table use local for stack top as well since execption handlers can only exist at statement level where stack is empty it is necessary to save restore stack top only accross function calls and normal returns int stack top frame saved stack top store new frame in cx which is used for error reporting etc cx last interpreter frame frame loop for exception handler assumes that pc is already incremented pass the instruction start when it searches the exception handler int op i code frame pc jumpless run back indent to ease imlementation reading switch op case token throw object value stack stack top if value dbl mrk value script runtime wrap number s dbl stack top stack top int source line get index i code frame pc throwable new java script exception value frame idata its source file source line break without exceptions case token rethrow index reg frame local shift throwable stack index reg break without exceptions case token ge case token le case token gt case token lt stack top object rhs stack stack top 1 object lhs stack stack top boolean val bln object compare number compare double r dbl l dbl if rhs dbl mrk r dbl s dbl stack top 1 l dbl stack double frame stack top else if lhs dbl mrk r dbl script runtime to number rhs l dbl s dbl stack top else break number compare switch op case token ge val bln l dbl r dbl break object compare case token le val bln l dbl r dbl break object compare case token gt val bln l dbl r dbl break object compare case token lt val bln l dbl r dbl break object compare default throw kit code bug switch op case token ge val bln script runtime cmp le rhs lhs break case token le val bln script runtime cmp le lhs rhs break case token gt val bln script runtime cmp lt rhs lhs break case token lt interpretloop callframe continuationjump dbl_mrk uniquetag double_mark instructioncounting instructionthreshold instructioncount invocation_cost exception_cost stringreg indexreg lastinterpreterframe interpreterloop previousinterpreterinvocations previousinterpreterinvocations objarray previousinterpreterinvocations lastinterpreterframe indexreg indexreg indereg indexreg continuationjump codebug interpreterresult interpreterresultdbl stateloop withoutexceptions indexreg indexreg clonefrozen itsexceptiontable indexreg exception_handler_slot instructioncounting pcprevbranch savedstacktop emptystacktop scopelocal localshift indexreg exception_scope_slot exlocal localshift indexreg exception_local_slot scopelocal exlocal continuationjump continuationjump branchframe codebug capturedframe codebug branchframe capturedframe rewindcount capturedframe frameindex branchframe rewindcount branchframe frameindex entercount callframe enterframes callframe capturedframe rewindcount codebug isframeenterexitrequired enterframes enterframes callframe rewindcount enterframes entercount entercount parentframe entercount enterframes capturedframe branchframe entercount enterframes entercount enterframe scriptruntime emptyargs capturedframe capturedframe capturedframe clonefrozen setcallresult resultdbl codebug codebug sdbl sdbl varsource vardbls varsource sdbl icode itsicode itsstringtable stacktop stacktop stacktop savedstacktop lastinterpreterframe icode jumplessrun stacktop dbl_mrk scriptruntime wrapnumber sdbl stacktop stacktop sourceline getindex icode javascriptexception itssourcefile sourceline withoutexceptions indexreg localshift indexreg withoutexceptions stacktop stacktop stacktop valbln object_compare number_compare rdbl ldbl dbl_mrk rdbl sdbl stacktop ldbl stack_double stacktop dbl_mrk rdbl scriptruntime tonumber ldbl sdbl stacktop number_compare valbln ldbl rdbl object_compare valbln ldbl rdbl object_compare valbln ldbl rdbl object_compare valbln ldbl rdbl object_compare codebug valbln scriptruntime cmp_le valbln scriptruntime cmp_le valbln scriptruntime cmp_lt for if ex state ex no js state boolean only finally ex state ex catch state index reg get exception handler frame only finally if index reg 0 we caught an exception restart the loop with exception pending the processing at the loop start continue state loop no allowed execption handlers in this frame unwind to parent and try to look there exit frame cx frame throwable frame frame parent frame if frame null break if cjump null cjump branch frame frame continuation branch point was hit restart the state loop to reenter continuation index reg 1 continue state loop no more frames rethrow the exception or deal with continuation if cjump null if cjump branch frame null the above loop should locate the top frame kit code bug if cjump captured frame null restarting detached continuation index reg 1 continue state loop return continuation result to the caller interpreter result cjump result interpreter result dbl cjump result dbl throwable null break state loop end of state loop for do cleanups restorations before the final return or throw if cx previous interpreter invocations null cx previous interpreter invocations size 0 cx last interpreter frame cx previous interpreter invocations pop else it was the last interpreter frame on the stack cx last interpreter frame null force gc of the value cx previous interpreter invocations cx previous interpreter invocations null if throwable null if throwable instanceof runtime exception throw runtime exception throwable else must be instance of error or code bug throw error throwable return interpreter result dbl mrk interpreter result script runtime wrap number interpreter result dbl exstate ex_no_js_state onlyfinally exstate ex_catch_state indexreg getexceptionhandler onlyfinally indexreg stateloop exitframe parentframe branchframe indexreg stateloop branchframe codebug capturedframe indexreg stateloop interpreterresult interpreterresultdbl resultdbl stateloop stateloop previousinterpreterinvocations previousinterpreterinvocations lastinterpreterframe previousinterpreterinvocations lastinterpreterframe previousinterpreterinvocations previousinterpreterinvocations runtimeexception runtimeexception interpreterresult dbl_mrk interpreterresult scriptruntime wrapnumber interpreterresultdbl private static void init frame context cx scriptable caller scope scriptable this obj object args double args dbl int arg shift int arg count interpreted function fn or script call frame parent frame call frame frame interpreter data idata fn or script idata boolean use activation idata its needs activation debug frame debugger frame null if cx debugger null debugger frame cx debugger get frame cx idata if debugger frame null use activation true if use activation copy args to new array to pass to enter activation function or debugger frame on enter if args dbl null args get args array args args dbl arg shift arg count arg shift 0 args dbl null scriptable scope if idata its function type 0 if idata use dynamic scope scope fn or script get parent scope else scope caller scope if use activation scope script runtime create function activation fn or script scope args else scope caller scope script runtime init script fn or script this obj cx scope fn or script idata eval script flag if idata its nested functions null if idata its function type 0 idata its needs activation kit code bug for int i 0 i idata its nested functions length i interpreter data fdata idata its nested functions i if fdata its function type function node function statement init function cx scope fn or script i scriptable script reg exps null if idata its reg exp literals null wrapped regexps for functions are stored in interpreted function but for script which should not contain references to scope the regexps re wrapped during each script execution if idata its function type 0 script reg exps fn or script function reg exps else script reg exps fn or script create reg exp wraps cx scope initialize args vars locals and stack int empty stack top idata its max vars idata its max locals 1 int max frame array idata its max frame array if max frame array empty stack top idata its max stack 1 kit code bug object stack double s dbl boolean stack reuse if frame stack null max frame array frame stack length reuse stacks from old frame stack reuse true stack frame stack s dbl frame s dbl else stack reuse false stack new object max frame array s dbl new double max frame array int defined args idata arg count if defined args arg count defined args arg count fill the frame structure frame parent frame parent frame frame frame index parent frame null 0 parent frame frame index 1 if frame frame index cx get maximum interpreter stack depth throw context report runtime error exceeded maximum stack depth frame frozen false frame fn or script fn or script frame idata idata frame stack stack frame s dbl s dbl frame var source frame frame local shift idata its max vars frame empty stack top empty stack top frame debugger frame debugger frame frame use activation use activation frame this obj this obj frame script reg exps script reg exps initialize initial values of variables that change during interpretation frame result undefined instance frame pc 0 frame pc prev branch 0 frame pc source line start idata first linepc frame scope scope frame saved stack top empty stack top frame saved call op 0 system arraycopy args arg shift stack 0 defined args if args dbl null system arraycopy args dbl arg shift s dbl 0 defined args for int i defined args i idata its max vars i stack i undefined instance if stack reuse clean the stack part and space beyond stack if any of the old array to allow to gc objects there for int i empty stack top 1 i stack length i stack i null enter frame cx frame args initframe callerscope thisobj argsdbl argshift argcount interpretedfunction fnorscript callframe parentframe callframe interpreterdata fnorscript useactivation itsneedsactivation debugframe debuggerframe debuggerframe getframe debuggerframe useactivation useactivation enteractivationfunction debuggerframe onenter argsdbl getargsarray argsdbl argshift argcount argshift argsdbl itsfunctiontype usedynamicscope fnorscript getparentscope callerscope useactivation scriptruntime createfunctionactivation fnorscript callerscope scriptruntime initscript fnorscript thisobj fnorscript evalscriptflag itsnestedfunctions itsfunctiontype itsneedsactivation codebug itsnestedfunctions interpreterdata itsnestedfunctions itsfunctiontype functionnode function_statement initfunction fnorscript scriptregexps itsregexpliterals interpretedfunction itsfunctiontype scriptregexps fnorscript functionregexps scriptregexps fnorscript createregexpwraps emptystacktop itsmaxvars itsmaxlocals maxframearray itsmaxframearray maxframearray emptystacktop itsmaxstack codebug sdbl stackreuse maxframearray stackreuse sdbl sdbl stackreuse maxframearray sdbl maxframearray definedargs argcount definedargs argcount definedargs argcount parentframe parentframe frameindex parentframe parentframe frameindex frameindex getmaximuminterpreterstackdepth reportruntimeerror fnorscript fnorscript sdbl sdbl varsource localshift itsmaxvars emptystacktop emptystacktop debuggerframe debuggerframe useactivation useactivation thisobj thisobj scriptregexps scriptregexps pcprevbranch pcsourcelinestart firstlinepc savedstacktop emptystacktop savedcallop argshift definedargs argsdbl argsdbl argshift sdbl definedargs definedargs itsmaxvars stackreuse emptystacktop enterframe private static boolean is frame enter exit required call frame frame return frame debugger frame null frame idata its needs activation isframeenterexitrequired callframe debuggerframe itsneedsactivation private static void enter frame context cx call frame frame object args if frame debugger frame null frame debugger frame on enter cx frame scope frame this obj args if frame idata its needs activation enter activation only when its needs activation true not when use activation holds since debugger should not interfere with activation chaining script runtime enter activation function cx frame scope enterframe callframe debuggerframe debuggerframe onenter thisobj itsneedsactivation itsneedsactivation useactivation scriptruntime enteractivationfunction private static void exit frame context cx call frame frame object throwable if frame idata its needs activation script runtime exit activation function cx if frame debugger frame null try if throwable instanceof throwable frame debugger frame on exit cx true throwable else object result continuation jump cjump continuation jump throwable if cjump null result frame result else result cjump result if result unique tag double mark double result dbl if cjump null result dbl frame result dbl else result dbl cjump result dbl result script runtime wrap number result dbl frame debugger frame on exit cx false result catch throwable ex system err println rhino usage warning on exit terminated with exception ex print stack trace system err exitframe callframe itsneedsactivation scriptruntime exitactivationfunction debuggerframe debuggerframe onexit continuationjump continuationjump uniquetag double_mark resultdbl resultdbl resultdbl resultdbl resultdbl scriptruntime wrapnumber resultdbl debuggerframe onexit onexit printstacktrace private static void set call result call frame frame object call result double call result dbl if frame saved call op token call frame stack frame saved stack top call result frame s dbl frame saved stack top call result dbl else if frame saved call op token new if construct returns scriptable then it replaces on stack top saved original instance of the object if call result instanceof scriptable frame stack frame saved stack top call result else kit code bug frame saved call op 0 setcallresult callframe callresult callresultdbl savedcallop savedstacktop callresult sdbl savedstacktop callresultdbl savedcallop callresult savedstacktop callresult codebug savedcallop private static void capture continuation context cx call frame frame int stack top continuation c new continuation script runtime set object proto and parent c script runtime get top call scope cx make sure that all frames upstack frames are frozen call frame x frame parent frame while x null x frozen x frozen true allow to gc unused stack space for int i x saved stack top 1 i x stack length i allow to gc unused stack space x stack i null if x saved call op token call the call will always overwrite the stack top with the result x stack x saved stack top null else if x saved call op token new kit code bug the new operator uses stack top to store the constructed object so it shall not be cleared see comments in set call result x x parent frame c init implementation frame parent frame frame stack stack top c capturecontinuation callframe stacktop scriptruntime setobjectprotoandparent scriptruntime gettopcallscope callframe parentframe savedstacktop savedcallop savedstacktop savedcallop codebug setcallresult parentframe initimplementation parentframe stacktop private static int stack int32 call frame frame int i object x frame stack i double value if x unique tag double mark value frame s dbl i else value script runtime to number x return script runtime to int32 value stack_int32 callframe uniquetag double_mark sdbl scriptruntime tonumber scriptruntime toint32 private static double stack double call frame frame int i object x frame stack i if x unique tag double mark return script runtime to number x else return frame s dbl i stack_double callframe uniquetag double_mark scriptruntime tonumber sdbl private static boolean stack boolean call frame frame int i object x frame stack i if x boolean true return true else if x boolean false return false else if x unique tag double mark double d frame s dbl i return d d d 0 0 else if x null x undefined instance return false else if x instanceof number double d number x double value return d d d 0 0 else if x instanceof boolean return boolean x boolean value else return script runtime to boolean x stack_boolean callframe uniquetag double_mark sdbl doublevalue booleanvalue scriptruntime toboolean private static void do add object stack double s dbl int stack top context cx object rhs stack stack top 1 object lhs stack stack top double d boolean left right order if rhs unique tag double mark d s dbl stack top 1 if lhs unique tag double mark s dbl stack top d return left right order true fallthrough to object number code else if lhs unique tag double mark d s dbl stack top lhs rhs left right order false fallthrough to object number code else if lhs instanceof scriptable rhs instanceof scriptable stack stack top script runtime add lhs rhs cx else if lhs instanceof string string lstr string lhs string rstr script runtime to string rhs stack stack top lstr concat rstr else if rhs instanceof string string lstr script runtime to string lhs string rstr string rhs stack stack top lstr concat rstr else double l dbl lhs instanceof number number lhs double value script runtime to number lhs double r dbl rhs instanceof number number rhs double value script runtime to number rhs stack stack top unique tag double mark s dbl stack top l dbl r dbl return handle object lhs number d code if lhs instanceof scriptable rhs script runtime wrap number d if left right order object tmp lhs lhs rhs rhs tmp stack stack top script runtime add lhs rhs cx else if lhs instanceof string string lstr string lhs string rstr script runtime to string d if left right order stack stack top lstr concat rstr else stack stack top rstr concat lstr else double l dbl lhs instanceof number number lhs double value script runtime to number lhs stack stack top unique tag double mark s dbl stack top l dbl d do_add sdbl stacktop stacktop stacktop leftrightorder uniquetag double_mark sdbl stacktop uniquetag double_mark sdbl stacktop leftrightorder uniquetag double_mark sdbl stacktop leftrightorder stacktop scriptruntime scriptruntime tostring stacktop scriptruntime tostring stacktop ldbl doublevalue scriptruntime tonumber rdbl doublevalue scriptruntime tonumber stacktop uniquetag double_mark sdbl stacktop ldbl rdbl scriptruntime wrapnumber leftrightorder stacktop scriptruntime scriptruntime tostring leftrightorder stacktop stacktop ldbl doublevalue scriptruntime tonumber stacktop uniquetag double_mark sdbl stacktop ldbl private static object get args array object stack double s dbl int shift int count if count 0 return script runtime empty args object args new object count for int i 0 i count i shift object val stack shift if val unique tag double mark val script runtime wrap number s dbl shift args i val return args getargsarray sdbl scriptruntime emptyargs uniquetag double_mark scriptruntime wrapnumber sdbl private static void add instruction count context cx call frame frame int extra cx instruction count frame pc frame pc prev branch extra if cx instruction count cx instruction threshold cx observe instruction count cx instruction count cx instruction count 0 addinstructioncount callframe instructioncount pcprevbranch instructioncount instructionthreshold observeinstructioncount instructioncount instructioncount static void init scriptable scope boolean sealed native boolean obj new native boolean false obj export asjs class max prototype id scope sealed nativeboolean nativeboolean exportasjsclass max_prototype_id private native boolean boolean b boolean value b nativeboolean booleanvalue public string get class name return boolean getclassname public object get default value class type hint this is actually non ecma but will be proposed as a change in round 2 if type hint script runtime boolean class return script runtime wrap boolean boolean value return super get default value type hint getdefaultvalue typehint typehint scriptruntime booleanclass scriptruntime wrapboolean booleanvalue getdefaultvalue typehint 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 case id valueof arity 0 s value of break default throw new illegal argument exception string value of id init prototype method boolean tag id s arity initprototypeid id_constructor id_tostring tostring id_tosource tosource id_valueof valueof illegalargumentexception valueof initprototypemethod boolean_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag boolean tag return super exec id call f cx scope this obj args int id f method id if id id constructor boolean b script runtime to boolean args 0 if this obj null new boolean val creates a new boolean object return new native boolean b boolean val converts val to a boolean return script runtime wrap boolean b the rest of boolean prototype methods require this obj to be boolean if this obj instanceof native boolean throw incompatible call error f boolean value native boolean this obj boolean value switch id case id tostring return value true false case id tosource return value new boolean true new boolean false case id valueof return script runtime wrap boolean value throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag boolean_tag execidcall thisobj methodid id_constructor scriptruntime toboolean thisobj nativeboolean scriptruntime wrapboolean thisobj thisobj nativeboolean incompatiblecallerror nativeboolean thisobj booleanvalue id_tostring id_tosource id_valueof scriptruntime wrapboolean illegalargumentexception valueof protected int find prototype id string s int id generated last update 2004 03 17 13 28 00 cet l0 id 0 string x null int c int s length s length if s length 7 x value of id id valueof else 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 valueof id_valueof s_length charat tosource id_tosource tostring id_tostring s_length id_constructor public class run script public static void main string args creates and enters a context the context stores information about the execution environment of a script context cx context enter try initialize the standard objects object function etc this must be done before scripts can be executed returns a scope object that we use in later calls 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 object result cx evaluate string scope s cmd 1 null convert the result to a string and print it system err println cx to string result finally exit from the context context exit runscript initstandardobjects evaluatestring tostring public string choose file if cwd null string dir system get property user dir if dir null cwd new file dir if cwd null dlg set current directory cwd dlg set dialog title select a file to load int return val dlg show open dialog this if return val j file chooser approve option string result dlg get selected file get path cwd new file dlg get selected file get parent return result return null choosefile getproperty setcurrentdirectory setdialogtitle returnval showopendialog returnval jfilechooser approve_option getselectedfile getpath getselectedfile getparent public static void main string args js console console new js console args jsconsole jsconsole public void create file chooser 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 name f get name int i name last index of if i 0 i name length 1 string ext name 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 createfilechooser jfilechooser filefilter filefilter isdirectory getname lastindexof tolowercase getdescription javascript addchoosablefilefilter new javax swing filechooser file filter public boolean accept file f if f is directory return true string name f get name int i name last index of if i 0 i name length 1 string ext name 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 public js console string args super rhino java script console j menu bar menubar new j menu bar create file chooser string file items load exit string file cmds load exit char file short cuts l x string edit items cut copy paste char edit short cuts t c p string plaf items metal windows motif boolean plaf state true false false 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 for int i 0 i file items length i 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 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 button group group new button group for int i 0 i plaf items length i j radio button menu item item new j radio button menu item plaf items i plaf state i group add item item add action listener this plaf menu add item menubar add file menu menubar add edit menu menubar add plaf menu setj menu bar menubar console text area new console text area args j scroll pane scroller new j scroll pane console text area set content pane scroller console text area set rows 24 console text area set columns 80 add window listener new window adapter public void window closing window event e system exit 0 pack set visible true system set in console text area get in system set out console text area get out system set err console text area get err main set in console text area get in main set out console text area get out main set err console text area get err main main args jsconsole javascript jmenubar jmenubar createfilechooser fileitems filecmds fileshortcuts edititems editshortcuts plafitems plafstate jmenu filemenu jmenu filemenu setmnemonic jmenu editmenu jmenu editmenu setmnemonic jmenu plafmenu jmenu plafmenu setmnemonic fileitems jmenuitem jmenuitem fileitems fileshortcuts setactioncommand filecmds addactionlistener filemenu edititems jmenuitem jmenuitem edititems editshortcuts addactionlistener editmenu buttongroup buttongroup plafitems jradiobuttonmenuitem jradiobuttonmenuitem plafitems plafstate addactionlistener plafmenu filemenu editmenu plafmenu setjmenubar consoletextarea consoletextarea jscrollpane jscrollpane consoletextarea setcontentpane consoletextarea setrows consoletextarea setcolumns addwindowlistener windowadapter windowclosing windowevent setvisible setin consoletextarea getin setout consoletextarea getout seterr consoletextarea geterr setin consoletextarea getin setout consoletextarea getout seterr consoletextarea geterr console text area set columns 80 add window listener new window adapter public void window closing window event e system exit 0 consoletextarea setcolumns addwindowlistener windowadapter windowclosing windowevent public void action performed action event e string cmd e get action command string plaf name null if cmd equals load string f choose file if f null f f replace console text area eval load f else if cmd equals exit system exit 0 else 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 else 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 if plaf name null try ui manager set look and feel plaf name swing utilities update component treeui this console text area post updateui update component treeui seems to mess up the file chooser dialog so just create a new one create file chooser catch exception exc j option pane show message dialog this exc get message platform j option pane error message actionperformed actionevent getactioncommand plaf_name choosefile consoletextarea consoletextarea consoletextarea consoletextarea plaf_name metallookandfeel plaf_name windowslookandfeel plaf_name motiflookandfeel plaf_name uimanager setlookandfeel plaf_name swingutilities updatecomponenttreeui consoletextarea postupdateui updatecomponenttreeui createfilechooser joptionpane showmessagedialog getmessage joptionpane error_message final class ir factory ir factory parser parser this parser parser irfactory irfactory script or fn node create script return new script or fn node token script scriptorfnnode createscript scriptorfnnode script for associating file url names with toplevel scripts void init script script or fn node script node node body node children body get first child if children null script node add children to back children initscript scriptorfnnode scriptnode getfirstchild scriptnode addchildrentoback leaf node create leaf int node type return new node node type createleaf nodetype nodetype node create leaf int node type int node op return new node node type node op createleaf nodetype nodeop nodetype nodeop statement leaf nodes node create switch node expr int lineno the switch will be rewritten from switch expr case test1 statements1 default statements default case testn statementsn to switch expr case test1 goto label1 case testn goto labeln goto label default label1 statements1 label default statements default labeln statementsn break label where inside switch each break without label will be replaced by goto break label if the original switch does not have the default label then the transformed code would contain after the switch instead of goto label default the following goto goto break label node jump switch node new node jump token switch expr lineno node block new node token block switch node return block createswitch statementsdefault labeldefault labeldefault statementsdefault breaklabel breaklabel labeldefault breaklabel switchnode switchnode if case expression argument is null it indicate default label void add switch case node switch block node case expression node statements if switch block get type token block throw kit code bug node jump switch node node jump switch block get first child if switch node get type token switch throw kit code bug node goto target node new target if case expression null node jump case node new node jump token case case expression case node target goto target switch node add child to back case node else switch node set default goto target switch block add child to back goto target switch block add child to back statements caseexpression addswitchcase switchblock caseexpression switchblock gettype codebug switchnode switchblock getfirstchild switchnode gettype codebug gototarget newtarget caseexpression casenode caseexpression casenode gototarget switchnode addchildtoback casenode switchnode setdefault gototarget switchblock addchildtoback gototarget switchblock addchildtoback void close switch node switch block if switch block get type token block throw kit code bug node jump switch node node jump switch block get first child if switch node get type token switch throw kit code bug node switch break target node new target switch node target is only used by node transformer to detect switch end switch node target switch break target node default target switch node get default if default target null default target switch break target switch block add child after make jump token goto default target switch node switch block add child to back switch break target closeswitch switchblock switchblock gettype codebug switchnode switchblock getfirstchild switchnode gettype codebug switchbreaktarget newtarget switchnode nodetransformer switchnode switchbreaktarget defaulttarget switchnode getdefault defaulttarget defaulttarget switchbreaktarget switchblock addchildafter makejump defaulttarget switchnode switchblock addchildtoback switchbreaktarget node create variables int lineno return new node token var lineno createvariables node create expr statement node expr int lineno int type if parser inside function type token expr void else type token expr result return new node type expr lineno createexprstatement insidefunction expr_void expr_result node create expr statement no return node expr int lineno return new node token expr void expr lineno createexprstatementnoreturn expr_void node create default namespace node expr int lineno default xml namespace requires activation set requires activation node n create unary token defaultnamespace expr node result create expr statement n lineno return result createdefaultnamespace setrequiresactivation createunary createexprstatement name node create name string name check activation name name token name return node new string token name name createname checkactivationname newstring string for literals node create string string string return node new string string createstring newstring number for literals node create number double number return node new number number createnumber newnumber catch clause of try catch finally param var name the name of the variable to bind to the exception param catch cond the condition under which to catch the exception may be null if no condition is given param stmts the statements in the catch clause param lineno the starting line number of the catch clause node create catch string var name node catch cond node stmts int lineno if catch cond null catch cond new node token empty return new node token catch create name var name catch cond stmts lineno varname catchcond createcatch varname catchcond catchcond catchcond createname varname catchcond throw node create throw node expr int lineno return new node token throw expr lineno createthrow return node create return node expr int lineno return expr null new node token return lineno new node token return expr lineno createreturn label node create label int lineno return new node jump token label lineno createlabel node get label loop node label return node jump label get loop getlabelloop getloop label node create labeled statement node label arg node statement node jump label node jump label arg make a target and put it after the statement node and in the label node so breaks get the right target node break target node new target node block new node token block label statement break target label target break target return block createlabeledstatement labelarg labelarg _after_ breaktarget newtarget breaktarget breaktarget break possibly labeled node create break node break statement int lineno node jump n new node jump token break lineno node jump jump statement int t break statement get type if t token loop t token label jump statement node jump break statement else if t token block break statement get first child get type token switch jump statement node jump break statement get first child else throw kit code bug n set jump statement jump statement return n createbreak breakstatement jumpstatement breakstatement gettype jumpstatement breakstatement breakstatement getfirstchild gettype jumpstatement breakstatement getfirstchild codebug setjumpstatement jumpstatement continue possibly labeled node create continue node loop int lineno if loop get type token loop kit code bug node jump n new node jump token continue lineno n set jump statement node jump loop return n createcontinue gettype codebug setjumpstatement statement block creates the empty statement block must make subsequent calls to add statements to the node node create block int lineno return new node token block lineno createblock function node create function string name return new function node name functionnode createfunction functionnode node init function function node fn node int function index node statements int function type fn node its function type function type fn node add child to back statements int function count fn node get function count if function count 0 functions containing other functions require activation objects fn node its needs activation true for int i 0 i function count i function node fn fn node get function node i nested function expression statements overrides var if fn get function type function node function expression statement string name fn get function name if name null name length 0 fn node remove param or var name if function type function node function expression string name fn node get function name if name null name length 0 fn node has param or var name a function expression needs to have its name as a variable if it isn t already allocated as a variable see ecma ch 13 we add code to the beginning of the function to initialize a local variable of the function s name to the function value fn node add var name node set fn new node token expr void new node token setname node new string token bindname name new node token thisfn statements add children to front set fn add return to end if needed node last stmt statements get last child if last stmt null last stmt get type token return statements add child to back new node token return node result node new string token function fn node get function name result put int prop node function prop function index return result initfunction functionnode fnnode functionindex functiontype fnnode itsfunctiontype functiontype fnnode addchildtoback functioncount fnnode getfunctioncount functioncount fnnode itsneedsactivation functioncount functionnode fnnode getfunctionnode getfunctiontype functionnode function_expression_statement getfunctionname fnnode removeparamorvar functiontype functionnode function_expression fnnode getfunctionname fnnode hasparamorvar fnnode addvar setfn expr_void newstring addchildrentofront setfn laststmt getlastchild laststmt laststmt gettype addchildtoback newstring fnnode getfunctionname putintprop function_prop functionindex add a child to the back of the given node this function breaks the factory abstraction but it removes a requirement from implementors of node void add child to back node parent node child parent add child to back child addchildtoback addchildtoback create loop node the parser will later call create while create do while create for create for in to finish loop generation node create loop node node loop label int lineno node jump result new node jump token loop lineno if loop label null node jump loop label set loop result return result createwhile createdowhile createfor createforin createloopnode looplabel looplabel looplabel setloop while node create while node loop node cond node body return create loop node jump loop loop while body cond null null createwhile createloop loop_while do while node create do while node loop node body node cond return create loop node jump loop loop do while body cond null null dowhile createdowhile createloop loop_do_while for node create for node loop node init node test node incr node body return create loop node jump loop loop for body test init incr createfor createloop loop_for private node create loop node jump loop int loop type node body node cond node init node incr node body target node new target node cond target node new target if loop type loop for cond get type token empty cond new node token true node jump ifeq new node jump token ifeq cond ifeq target body target node break target node new target loop add child to back body target loop add children to back body if loop type loop while loop type loop for propagate lineno to condition loop add children to back new node token empty loop get lineno loop add child to back cond target loop add child to back ifeq loop add child to back break target loop target break target node continue target cond target if loop type loop while loop type loop for just add a goto to the condition in the do while loop add child to front make jump token goto cond target if loop type loop for if init get type token empty if init get type token var init new node token expr void init loop add child to front init node incr target node new target loop add child after incr target body if incr get type token empty incr new node token expr void incr loop add child after incr incr target continue target incr target loop set continue continue target return loop createloop looptype bodytarget newtarget condtarget newtarget looptype loop_for gettype bodytarget breaktarget newtarget addchildtoback bodytarget addchildrentoback looptype loop_while looptype loop_for addchildrentoback getlineno addchildtoback condtarget addchildtoback addchildtoback breaktarget breaktarget continuetarget condtarget looptype loop_while looptype loop_for addchildtofront makejump condtarget looptype loop_for gettype gettype expr_void addchildtofront incrtarget newtarget addchildafter incrtarget gettype expr_void addchildafter incrtarget continuetarget incrtarget setcontinue continuetarget for in node create for in node loop node lhs node obj node body boolean is for each string name int type lhs get type node lvalue if type token var check that there was only one variable given we can t do this in the parser because then the parser would have to know something about the init node of the for in loop node last child lhs get last child if lhs get first child last child parser report error msg mult index lvalue node new string token name last child get string else lvalue make reference lhs if lvalue null parser report error msg bad for in lhs return obj node local block new node token local block int init type is for each token enum init values token enum init keys node init new node init type obj init put prop node local block prop local block node cond new node token enum next cond put prop node local block prop local block node id new node token enum id id put prop node local block prop local block node new body new node token block node assign simple assignment lvalue id new body add child to back new node token expr void assign new body add child to back body loop create while loop cond new body loop add child to front init if type token var loop add child to front lhs local block add child to back loop return local block createforin isforeach gettype lastchild getlastchild getfirstchild lastchild reporterror newstring lastchild getstring makereference reporterror localblock local_block inittype isforeach enum_init_values enum_init_keys inittype putprop local_block_prop localblock enum_next putprop local_block_prop localblock enum_id putprop local_block_prop localblock newbody simpleassignment newbody addchildtoback expr_void newbody addchildtoback createwhile newbody addchildtofront addchildtofront localblock addchildtoback localblock try catch finally the ir factory tries to express as much as possible in the tree the responsibilities remaining for codegen are to add the java handlers either but not both of target and finally might not be defined a catch handler for javascript exceptions that unwraps the exception onto the stack and got oes to the catch target a finally handler and a goto to goto around these handlers node create try catch finally node try block node catch blocks node finally block int lineno boolean has finally finally block null finally block get type token block finally block has children short circuit if try block get type token block try block has children has finally return try block boolean has catch catch blocks has children short circuit if has finally has catch bc finally might be an empty block return try block node handler block new node token local block node jump pn new node jump token try try block lineno pn put prop node local block prop handler block if has catch jump around catch code node end catch node new target pn add child to back make jump token goto end catch make a target for the catch that the tcf node knows about node catch target node new target pn target catch target mark it pn add child to back catch target given try try block catch e if condition1 something1 catch e if conditionn somethingn catch e something default rewrite as try try block goto after catch catch x with new catch scope e x if condition1 something1 goto after catch with new catch scope e x if conditionn somethingn goto after catch with new catch scope e x something default goto after catch after catch if there is no default catch then the last with block arround something default is replaced by rethrow it is assumed that catch handler generation will store exeception object in handler block register block with local for exception scope objects node catch scope block new node token local block expects catchblocks children to be cond block pairs node cb catch blocks get first child boolean has default false int scope index 0 while cb null int catch line no cb get lineno node name cb get first child node cond name get next node catch statement cond get next cb remove child name cb remove child cond cb remove child catch statement add goto to the catch statement to jump out of catch but prefix it with leavewith since try catch produces with code in order to limit the scope of the exception object catch statement add child to back new node token leavewith catch statement add child to back make jump token goto end catch create condition if when present node cond stmt if cond get type token empty cond stmt catch statement has default true else cond stmt create if cond catch statement null catch line no generate code to create the scope object and store it in catch scope block register node catch scope new node token catch scope name create use local handler block catch scope put prop node local block prop catch scope block catch scope put int prop node catch scope prop scope index catch scope block add child to back catch scope add with statement based on catch scope object catch scope block add child to back create with create use local catch scope block cond stmt catch line no move to next cb cb cb get next scope index pn add child to back catch scope block if has default generate code to rethrow if no catch clause was executed node rethrow new node token rethrow rethrow put prop node local block prop handler block pn add child to back rethrow pn add child to back end catch if has finally node finally target node new target pn set finally finally target add jsr finally to the try block pn add child to back make jump token jsr finally target jump around finally code node finally end node new target pn add child to back make jump token goto finally end pn add child to back finally target node f block new node token finally finally block f block put prop node local block prop handler block pn add child to back f block pn add child to back finally end handler block add child to back pn return handler block irfactory gotoes createtrycatchfinally tryblock catchblocks finallyblock hasfinally finallyblock finallyblock gettype finallyblock haschildren tryblock gettype tryblock haschildren hasfinally tryblock hascatch catchblocks haschildren hasfinally hascatch tryblock handlerblock local_block tryblock putprop local_block_prop handlerblock hascatch endcatch newtarget addchildtoback makejump endcatch catchtarget newtarget catchtarget addchildtoback catchtarget tryblock somethingdefault tryblock after_catch newcatchscope after_catch newcatchscope after_catch newcatchscope somethingdefault after_catch after_catch somethingdefault handlerblock catchscopeblock local_block catchblocks getfirstchild hasdefault scopeindex catchlineno getlineno getfirstchild getnext catchstatement getnext removechild removechild removechild catchstatement catchstatement addchildtoback catchstatement addchildtoback makejump endcatch condstmt gettype condstmt catchstatement hasdefault condstmt createif catchstatement catchlineno catchscopeblock catchscope catch_scope createuselocal handlerblock catchscope putprop local_block_prop catchscopeblock catchscope putintprop catch_scope_prop scopeindex catchscopeblock addchildtoback catchscope catchscopeblock addchildtoback createwith createuselocal catchscopeblock condstmt catchlineno getnext scopeindex addchildtoback catchscopeblock hasdefault putprop local_block_prop handlerblock addchildtoback addchildtoback endcatch hasfinally finallytarget newtarget setfinally finallytarget addchildtoback makejump finallytarget finallyend newtarget addchildtoback makejump finallyend addchildtoback finallytarget fblock finallyblock fblock putprop local_block_prop handlerblock addchildtoback fblock addchildtoback finallyend handlerblock addchildtoback handlerblock with node create with node obj node body int lineno set requires activation node result new node token block lineno result add child to back new node token enterwith obj node body node new node token with body lineno result add children to back body node result add child to back new node token leavewith return result createwith setrequiresactivation addchildtoback bodynode addchildrentoback bodynode addchildtoback dotquery public node create dot query node obj node body int lineno set requires activation node result new node token dotquery obj body lineno return result createdotquery setrequiresactivation node create array literal obj array elems int skip count int length elems size int skip indexes null if skip count 0 skip indexes new int skip count node array new node token arraylit for int i 0 j 0 i length i node elem node elems get i if elem null array add child to back elem else skip indexes j i j if skip count 0 array put prop node skip indexes prop skip indexes return array createarrayliteral objarray skipcount skipindexes skipcount skipindexes skipcount addchildtoback skipindexes skipcount putprop skip_indexes_prop skipindexes object literals br create object literal rewrites its argument as object creation plus object property entries so later compiler stages don t need to know about object literals node create object literal obj array elems int size elems size 2 node object new node token objectlit object properties if size 0 properties script runtime empty args else properties new object size for int i 0 i size i properties i elems get 2 i node value node elems get 2 i 1 object add child to back value object put prop node object ids prop properties return object createobjectliteral createobjectliteral objarray scriptruntime emptyargs addchildtoback putprop object_ids_prop regular expressions node create reg exp int regexp index node n new node token regexp n put int prop node regexp prop regexp index return n createregexp regexpindex putintprop regexp_prop regexpindex if statement node create if node cond node if true node if false int lineno int cond status is always defined boolean cond if cond status always true boolean return if true else if cond status always false boolean if if false null return if false replace if false xxx by empty block return new node token block lineno node result new node token block lineno node if not target node new target node jump ifne new node jump token ifne cond ifne target if not target result add child to back ifne result add children to back if true if if false null node end target node new target result add child to back make jump token goto end target result add child to back if not target result add children to back if false result add child to back end target else result add child to back if not target return result createif iftrue iffalse condstatus isalwaysdefinedboolean condstatus always_true_boolean iftrue condstatus always_false_boolean iffalse iffalse ifnottarget newtarget ifnottarget addchildtoback addchildrentoback iftrue iffalse endtarget newtarget addchildtoback makejump endtarget addchildtoback ifnottarget addchildrentoback iffalse addchildtoback endtarget addchildtoback ifnottarget node create cond expr node cond node if true node if false int cond status is always defined boolean cond if cond status always true boolean return if true else if cond status always false boolean return if false return new node token hook cond if true if false createcondexpr iftrue iffalse condstatus isalwaysdefinedboolean condstatus always_true_boolean iftrue condstatus always_false_boolean iffalse iftrue iffalse unary node create unary int node type node child int child type child get type switch node type case token delprop node n if child type token name transform delete name a to delete bind a string a child set type token bindname node left child node right node new string child get string n new node node type left right else if child type token getprop child type token getelem node left child get first child node right child get last child child remove child left child remove child right n new node node type left right else if child type token get ref node ref child get first child child remove child ref n new node token del ref ref else n new node token true return n case token typeof if child type token name child set type token typeofname return child break case token bitnot if child type token number int value script runtime to int32 child get double child set double value return child break case token neg if child type token number child set double child get double return child break case token not int status is always defined boolean child if status 0 int type if status always true boolean type token false else type token true if child type token true child type token false child set type type return child return new node type break return new node node type child createunary nodetype childtype gettype nodetype childtype settype newstring getstring nodetype childtype childtype getfirstchild getlastchild removechild removechild nodetype childtype get_ref getfirstchild removechild del_ref childtype settype childtype scriptruntime toint32 getdouble setdouble childtype setdouble getdouble isalwaysdefinedboolean always_true_boolean childtype childtype settype nodetype node create call or new int node type node child int type node non specialcall if child get type token name string name child get string if name equals eval type node specialcall eval else if name equals with type node specialcall with else if child get type token getprop string name child get last child get string if name equals eval type node specialcall eval node node new node node type child if type node non specialcall calls to these functions require activation objects set requires activation node put int prop node specialcall prop type return node createcallornew nodetype non_specialcall gettype getstring specialcall_eval specialcall_with gettype getlastchild getstring specialcall_eval nodetype non_specialcall setrequiresactivation putintprop specialcall_prop node create inc dec int node type boolean post node child child make reference child if child null string msg if node type token dec msg msg bad decr else msg msg bad incr parser report error msg return null int child type child get type switch child type case token name case token getprop case token getelem case token get ref node n new node node type child int incr decr mask 0 if node type token dec incr decr mask node decr flag if post incr decr mask node post flag n put int prop node incrdecr prop incr decr mask return n throw kit code bug createincdec nodetype makereference nodetype reporterror childtype gettype childtype get_ref nodetype incrdecrmask nodetype incrdecrmask decr_flag incrdecrmask post_flag putintprop incrdecr_prop incrdecrmask codebug node create property get node target string namespace string name int member type flags if namespace null member type flags 0 if target null return create name name check activation name name token getprop if script runtime is special property name node ref new node token ref special target ref put prop node name prop name return new node token get ref ref return new node token getprop target create string name node elem create string name member type flags node property flag return create member ref get target namespace elem member type flags createpropertyget membertypeflags membertypeflags createname checkactivationname scriptruntime isspecialproperty ref_special putprop name_prop get_ref createstring createstring membertypeflags property_flag creatememberrefget membertypeflags node create element get node target string namespace node elem int member type flags opt could optimize to create property get iff elem is string that can not be number if namespace null member type flags 0 stand alone aaa as primary expression is array literal declaration and should not come here if target null throw kit code bug return new node token getelem target elem return create member ref get target namespace elem member type flags createelementget membertypeflags createpropertyget membertypeflags codebug creatememberrefget membertypeflags private node create member ref get node target string namespace node elem int member type flags node ns node null if namespace null see 11 1 2 in ecma 357 if namespace equals ns node new node token null else ns node create name namespace node ref if target null if namespace null ref new node token ref name elem else ref new node token ref ns name ns node elem else if namespace null ref new node token ref member target elem else ref new node token ref ns member target ns node elem if member type flags 0 ref put int prop node member type prop member type flags return new node token get ref ref creatememberrefget membertypeflags nsnode nsnode nsnode createname ref_name ref_ns_name nsnode ref_member ref_ns_member nsnode membertypeflags putintprop member_type_prop membertypeflags get_ref binary node create binary int node type node left node right switch node type case token add numerical addition and string concatenation if left type token string string s2 if right type token string s2 right get string else if right type token number s2 script runtime number to string right get double 10 else break string s1 left get string left set string s1 concat s2 return left else if left type token number if right type token number left set double left get double right get double return left else if right type token string string s1 s2 s1 script runtime number to string left get double 10 s2 right get string right set string s1 concat s2 return right can t do anything if we don t know both types since 0 object is supposed to call to string on the object and do string concantenation rather than addition break case token sub numerical subtraction if left type token number double ld left get double if right type token number both numbers left set double ld right get double return left else if ld 0 0 first 0 0 x x return new node token neg right else if right type token number if right get double 0 0 second 0 x 0 x can not make simply x because x 0 must be number return new node token pos left break case token mul numerical multiplication if left type token number double ld left get double if right type token number both numbers left set double ld right get double return left else if ld 1 0 first 1 1 x x return new node token pos right else if right type token number if right get double 1 0 second 1 x 1 x can not make simply x because x 0 must be number return new node token pos left can t do x 0 infinity 0 gives nan not 0 break case token div number division if right type token number double rd right get double if left type token number both constants just divide trust java to handle x 0 left set double left get double rd return left else if rd 1 0 second 1 x 1 x not simply x to force number convertion return new node token pos left break case token and since x y gives x not false when boolean x is false and y not boolean y when boolean x is true x y can only be simplified if x is defined see bug 309957 int left status is always defined boolean left if left status always false boolean if the first one is false just return it return left else if left status always true boolean if first is true set to second return right break case token or since x y gives x not true when boolean x is true and y not boolean y when boolean x is false x y can only be simplified if x is defined see bug 309957 int left status is always defined boolean left if left status always true boolean if the first one is true just return it return left else if left status always false boolean if first is false set to second return right break return new node node type left right createbinary nodetype nodetype getstring scriptruntime numbertostring getdouble getstring setstring setdouble getdouble getdouble scriptruntime numbertostring getdouble getstring setstring tostring getdouble setdouble getdouble getdouble getdouble setdouble getdouble getdouble getdouble setdouble getdouble leftstatus isalwaysdefinedboolean leftstatus always_false_boolean leftstatus always_true_boolean leftstatus isalwaysdefinedboolean leftstatus always_true_boolean leftstatus always_false_boolean nodetype private node simple assignment node left node right int node type left get type switch node type case token name left set type token bindname return new node token setname left right case token getprop case token getelem node obj left get first child node id left get last child int type if node type token getprop type token setprop else type token setelem return new node type obj id right case token get ref node ref left get first child check mutable reference ref return new node token set ref ref right throw kit code bug simpleassignment nodetype gettype nodetype settype getfirstchild getlastchild nodetype get_ref getfirstchild checkmutablereference set_ref codebug private void check mutable reference node n int member type flags n get int prop node member type prop 0 if member type flags node descendants flag 0 parser report error msg bad assign left checkmutablereference membertypeflags getintprop member_type_prop membertypeflags descendants_flag reporterror node create assignment int assign type node left node right left make reference left if left null parser report error msg bad assign left return right int assign op switch assign type case token assign return simple assignment left right case token assign bitor assign op token bitor break case token assign bitxor assign op token bitxor break case token assign bitand assign op token bitand break case token assign lsh assign op token lsh break case token assign rsh assign op token rsh break case token assign ursh assign op token ursh break case token assign add assign op token add break case token assign sub assign op token sub break case token assign mul assign op token mul break case token assign div assign op token div break case token assign mod assign op token mod break default throw kit code bug int node type left get type switch node type case token name string s left get string node op left node new string token name s node op new node assign op op left right node lvalue left node new string token bindname s return new node token setname lvalue left op case token getprop case token getelem node obj left get first child node id left get last child int type node type token getprop token setprop op token setelem op node op left new node token use stack node op new node assign op op left right return new node type obj id op case token get ref node ref left get first child check mutable reference ref node op left new node token use stack node op new node assign op op left right return new node token set ref op ref op throw kit code bug createassignment assigntype makereference reporterror assignop assigntype simpleassignment assign_bitor assignop assign_bitxor assignop assign_bitand assignop assign_lsh assignop assign_rsh assignop assign_ursh assignop assign_add assignop assign_sub assignop assign_mul assignop assign_div assignop assign_mod assignop codebug nodetype gettype nodetype getstring opleft newstring assignop opleft lvalueleft newstring lvalueleft getfirstchild getlastchild nodetype setprop_op setelem_op opleft use_stack assignop opleft get_ref getfirstchild checkmutablereference opleft use_stack assignop opleft set_ref_op codebug node create use local node local block if token local block local block get type throw kit code bug node result new node token local load result put prop node local block prop local block return result createuselocal localblock local_block localblock gettype codebug local_load putprop local_block_prop localblock private node jump make jump int type node target node jump n new node jump type n target target return n makejump private node make reference node node int type node get type switch type case token name case token getprop case token getelem case token get ref return node case token call node set type token ref call return new node token get ref node signal caller to report error return null makereference gettype get_ref settype ref_call get_ref check if node always mean true or false in boolean context private static int is always defined boolean node node switch node get type case token false case token null return always false boolean case token true return always true boolean case token number double num node get double if num num num 0 0 return always true boolean else return always false boolean return 0 isalwaysdefinedboolean gettype always_false_boolean always_true_boolean getdouble always_true_boolean always_false_boolean private void check activation name string name int token if parser inside function boolean activation false if arguments equals name parser compiler env activation names null parser compiler env activation names contains key name activation true else if length equals name if token token getprop parser compiler env get language version context version 1 2 use of length in 1 2 requires an activation object activation true if activation set requires activation checkactivationname insidefunction compilerenv activationnames compilerenv activationnames containskey compilerenv getlanguageversion version_1_2 setrequiresactivation private void set requires activation if parser inside function function node parser current script or fn its needs activation true setrequiresactivation insidefunction functionnode currentscriptorfn itsneedsactivation public class slot 003 extends live connect test public slot 003 super slot_003 liveconnecttest slot_003 super public static void main string args slot 003 test new slot 003 test start slot_003 slot_003 public void execute test get base objects object test matrix get data array js object js array createjs array get length js array 0 for int i 0 i test matrix length i set slot js array i object test matrix i get slot js array i object test matrix i get length js array test matrix length executetest getbaseobjects testmatrix getdataarray jsobject jsarray createjsarray getlength jsarray testmatrix setslot jsarray testmatrix getslot jsarray testmatrix getlength jsarray testmatrix get the constructor of all the base java script objects the test will compare the instance constructor to the base object constructor to verify that the java script type of the object is corret public boolean get base objects try js number js object global eval number prototype constructor js string js object global eval string prototype constructor js function js object global eval function prototype constructor js boolean js object global eval boolean prototype constructor js object js object global eval object prototype constructor js math js object global eval math js date js object global eval date prototype constructor js array js object global eval array prototype constructor js reg exp js object global eval reg exp prototype constructor catch exception e system err println failed in get base objects e to string e print stack trace return false return true javascript javascript getbaseobjects jsnumber jsobject jsstring jsobject jsfunction jsobject jsboolean jsobject jsobject jsobject jsmath jsobject jsdate jsobject jsarray jsobject jsregexp jsobject regexp getbaseobjects tostring printstacktrace get the data array which is an array of arrays each of the internal arrays consists of three objects a string whose value will be passed to the java script array constructor a string which is the expected string value of retreiving the js object via get slot and a js object which is the js object s constructor that allows us to verify the type of js object return the data array public object get data array object item0 global eval new string java script string new string java script string js string object item1 global eval new number 12345 new string 12345 js number object item2 global eval new boolean false new string false js boolean object item3 global eval new array 0 1 2 3 4 new string 0 1 2 3 4 js array object item4 global eval new object new string object object js object object data array item0 item1 item2 item3 item4 return data array javascript jsobject getslot jsobject jsobject jsobject getdataarray javascript javascript jsstring jsnumber jsboolean jsarray jsobject dataarray dataarray create an empty java script array named js array return the js object array object public js object createjs array js object js array null string args var js array new array 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 js object js array js object global get member js array passed result exception return js array javascript jsarray jsobject jsobject createjsarray jsobject jsarray jsarray jsarray jsobject getmember jsarray getmember jsarray tostring printstacktrace addtestcase jsarray 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 in this test the expected class of all objects is js object param js array 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 array int slot object data string exception js object constructor null js object result null class e class null class a class null try result js object js array get slot slot if result null e class class for name netscape javascript js object a class result get class constructor js object result get member constructor catch exception e exception js array get slot slot threw e to string file exception exception e print stack trace finally if result null add test case js array get slot slot to string trim returned result data 1 equals result true data 1 to string trim equals result to string exception else check the string value of the result add test case js array get slot slot returned result data 1 to string equals result true data 1 equals result to string exception check the class of the result all should be js objects add test case e class equals a class true e class equals a class exception check the constructor of the result add test case constructor equals data 2 true constructor equals data 2 exception jsobject getslot jsobject jsobject jsarray jsobject jsarray getslot jsobjectconstructor getslot jsobject jsarray jsobject jsobject eclass aclass jsobject jsarray getslot eclass forname jsobject aclass getclass jsobject getmember jsarray getslot tostring printstacktrace addtestcase jsarray getslot tostring tostring tostring addtestcase jsarray getslot tostring tostring jsobjects addtestcase eclass aclass eclass aclass addtestcase 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 data string exception null string result passed try js array set slot slot object data 0 catch exception e result failed exception js array set slot slot data 0 threw e to string file exception exception e print stack trace finally add test case js array set slot slot data 0 passed result exception jsobject setslot setslot jsarray jsobject setslot javavalue setslot jsobject jsarray jsarray setslot jsarray setslot tostring printstacktrace addtestcase jsarray setslot public class slot 004 extends live connect test public slot 004 super slot_004 liveconnecttest slot_004 super public static void main string args slot 004 test new slot 004 test start slot_004 slot_004 public void execute test object test matrix get data array js object js array createjs array get length js array 0 for int i 0 i test matrix length i set slot js array i object test matrix i get slot js array i object test matrix i get length js array test matrix length executetest testmatrix getdataarray jsobject jsarray createjsarray getlength jsarray testmatrix setslot jsarray testmatrix getslot jsarray testmatrix getlength jsarray testmatrix get the data array which is an array of arrays each of the internal arrays consists of three objects a string whose value will be passed to the java script array constructor a string which is the expected string value of retreiving the js object via get slot and a js object which is the js object s constructor that allows us to verify the type of js object return the data array public object get data array object item0 new string java string new string java string java lang string object item1 new integer 12345 new string 12345 java lang integer object item2 new boolean false new string false java lang boolean object item3 new double 12345 0 new string 12345 0 java lang double object data array item0 item1 item2 item3 return data array javascript jsobject getslot jsobject jsobject jsobject getdataarray dataarray dataarray create an empty java script array named js array return the js object array object public js object createjs array js object js array null string args var js array new array 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 js object js array js object global get member js array passed result exception return js array javascript jsarray jsobject jsobject createjsarray jsobject jsarray jsarray jsarray jsobject getmember jsarray getmember jsarray tostring printstacktrace addtestcase jsarray 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 in this test the expected class of all objects is js object param js array 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 array int slot object data string exception object result null class e class null class a class null try result object js array get slot slot if result null e class class for name string data 2 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 result null add test case js array get slot slot to string trim returned result data 1 equals result true data 1 to string trim equals result to string exception else check the string value of the result add test case js array get slot slot returned result data 1 to string equals result true data 1 equals result to string exception check the class of the result all should be js objects add test case e class equals a class true e class equals a class exception jsobject getslot jsobject jsobject jsarray jsobject jsarray getslot jsobjectconstructor getslot jsobject jsarray eclass aclass jsarray getslot eclass forname aclass getclass jsarray getslot tostring printstacktrace addtestcase jsarray getslot tostring tostring tostring addtestcase jsarray getslot tostring tostring jsobjects 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 data string exception null string result passed try js array set slot slot object data 0 catch exception e result failed exception js array set slot slot data 0 threw e to string file exception exception e print stack trace finally add test case js array set slot slot data 0 passed result exception jsobject setslot setslot jsarray jsobject setslot javavalue setslot jsobject jsarray jsarray setslot jsarray setslot tostring printstacktrace addtestcase jsarray setslot token stream parser parser reader source reader string source string int lineno this parser parser this lineno lineno if source reader null if source string null kit code bug this source reader source reader this source buffer new char 512 this source end 0 else if source string null kit code bug this source string source string this source end source string length this source cursor 0 tokenstream sourcereader sourcestring sourcereader sourcestring codebug sourcereader sourcereader sourcebuffer sourceend sourcestring codebug sourcestring sourcestring sourceend sourcestring sourcecursor string token to string int token if token print trees string name token name token switch token case token string case token regexp case token name return name this string case token number return number this number return name return tokentostring printtrees static boolean is keyword string s return token eof string to keyword s iskeyword stringtokeyword private static int string to keyword string name string id map the following assumes that token eof 0 final int id break token break id case token case id continue token continue id default token default id delete token delprop id do token do id else token else id export token export id false token false id for token for id function token function id if token if id in token in id new token new id null token null id return token return id switch token switch id this token this id true token true id typeof token typeof id var token var id void token void id while token while id with token with the following are ifdef reserve java keywords in jsscan c id abstract token reserved id boolean token reserved id byte token reserved id catch token catch id char token reserved id class token reserved id const token reserved id debugger token reserved id double token reserved id enum token reserved id extends token reserved id final token reserved id finally token finally id float token reserved id goto token reserved id implements token reserved id import token import id instanceof token instanceof id int token reserved id interface token reserved id long token reserved id native token reserved id package token reserved id private token reserved id protected token reserved id public token reserved id short token reserved id static token reserved id super token reserved id synchronized token reserved id throw token throw id throws token reserved id transient token reserved id try token try id volatile token reserved int id string s name generated last update 2001 06 01 17 45 01 cest l0 id 0 string x null int c l switch s length case 2 c s char at 1 if c f if s char at 0 i id id if break l0 else if c n if s char at 0 i id id in break l0 else if c o if s char at 0 d id id do break l0 break l case 3 switch s char at 0 case f if s char at 2 r s char at 1 o id id for break l0 break l case i if s char at 2 t s char at 1 n id id int break l0 break l case n if s char at 2 w s char at 1 e id id new break l0 break l case t if s char at 2 y s char at 1 r id id try break l0 break l case v if s char at 2 r s char at 1 a id id var break l0 break l break l case 4 switch s char at 0 case b x byte id id byte break l case c c s char at 3 if c e if s char at 2 s s char at 1 a id id case break l0 else if c r if s char at 2 a s char at 1 h id id char break l0 break l case e c s char at 3 if c e if s char at 2 s s char at 1 l id id else break l0 else if c m if s char at 2 u s char at 1 n id id enum break l0 break l case g x goto id id goto break l case l x long id id long break l case n x null id id null break l case t c s char at 3 if c e if s char at 2 u s char at 1 r id id true break l0 else if c s if s char at 2 i s char at 1 h id id this break l0 break l case v x void id id void break l case w x with id id with break l break l case 5 switch s char at 2 case a x class id id class break l case e x break id id break break l case i x while id id while break l case l x false id id false break l case n c s char at 0 if c c x const id id const else if c f x final id id final break l case o c s char at 0 if c f x float id id float else if c s x short id id short break l case p x super id id super break l case r x throw id id throw break l case t x catch id id catch break l break l case 6 switch s char at 1 case a x native id id native break l case e c s char at 0 if c d x delete id id delete else if c r x return id id return break l case h x throws id id throws break l case m x import id id import break l case o x double id id double break l case t x static id id static break l case u x public id id public break l case w x switch id id switch break l case x x export id id export break l case y x typeof id id typeof break l break l case 7 switch s char at 1 case a x package id id package break l case e x default id id default break l case i x finally id id finally break l case o x boolean id id boolean break l case r x private id id private break l case x x extends id id extends break l break l case 8 switch s char at 0 case a x abstract id id abstract break l case c x continue id id continue break l case d x debugger id id debugger break l case f x function id id function break l case v x volatile id id volatile break l break l case 9 c s char at 0 if c i x interface id id interface else if c p x protected id id protected else if c t x transient id id transient break l case 10 c s char at 1 if c m x implements id id implements else if c n x instanceof id id instanceof break l case 12 x synchronized id id synchronized break l if x null x s x equals s id 0 generated string id map if id 0 return token eof return id 0xff stringtokeyword string_id_map id_break id_case id_continue id_default id_delete id_do id_else id_export id_false id_for id_function id_if id_in id_new id_null id_return id_switch id_this id_true id_typeof id_var id_void id_while id_with reserve_java_keywords id_abstract id_boolean id_byte id_catch id_char id_class id_const id_debugger id_double id_enum id_extends id_final id_finally id_float id_goto id_implements id_import id_instanceof id_int id_interface id_long id_native id_package id_private id_protected id_public id_short id_static id_super id_synchronized id_throw id_throws id_transient id_try id_volatile charat charat id_if charat id_in charat id_do charat charat charat id_for charat charat id_int charat charat id_new charat charat id_try charat charat id_var charat id_byte charat charat charat id_case charat charat id_char charat charat charat id_else charat charat id_enum id_goto id_long id_null charat charat charat id_true charat charat id_this id_void id_with charat id_class id_break id_while id_false charat id_const id_final charat id_float id_short id_super id_throw id_catch charat id_native charat id_delete id_return id_throws id_import id_double id_static id_public id_switch id_export id_typeof charat id_package id_default id_finally id_boolean id_private id_extends charat id_abstract id_continue id_debugger id_function id_volatile charat id_interface id_protected id_transient charat id_implements id_instanceof id_synchronized string_id_map final int get lineno return lineno getlineno final int get lineno return lineno final string get string return string getlineno getstring final string get string return string final double get number return number getstring getnumber final double get number return number final boolean eof return hiteof getnumber final int get token throws io exception int c retry for eat whitespace possibly sensitive to newlines for c get char if c eof char return token eof else if c n dirty line false return token eol else if isjs space c if c dirty line true break if c return token xmlattr identifier keyword instanceof watch out for starting with a backslash boolean identifier start boolean is unicode escape start false if c c get char if c u identifier start true is unicode escape start true string buffer top 0 else identifier start false unget char c c else identifier start character is java identifier start char c if identifier start string buffer top 0 add to string c if identifier start boolean contains escape is unicode escape start for if is unicode escape start strictly speaking we should probably push back all the bad characters if the backslash uxxxx sequence is malformed but since there isn t a correct context is there for a bad unicode escape sequence in an identifier we can report an error here int escape val 0 for int i 0 i 4 i c get char escape val kit x digit to int c escape val next check takes care about c 0 and bad escape if escape val 0 break if escape val 0 parser add error msg invalid escape return token error add to string escape val is unicode escape start false else c get char if c c get char if c u is unicode escape start true contains escape true else parser add error msg illegal character return token error else if c eof char character is java identifier part char c break add to string c unget char c string str get string from buffer if contains escape opt we shouldn t have to make a string object to check if it s a keyword return the corresponding token if it s a keyword int result string to keyword str if result token eof if result token reserved return result else if parser compiler env is reserved keyword as identifier return result else if implementation permits to use future reserved keywords in violation with the ecma script treat it as name but issue warning parser add warning msg reserved keyword str this string string all strings intern str return token name is it a number if is digit c c is digit peek char string buffer top 0 int base 10 if c 0 c get char if c x c x base 16 c get char else if is digit c base 8 else add to string 0 if base 16 while 0 kit x digit to int c 0 add to string c c get char else while 0 c c 9 we permit 08 and 09 as decimal numbers which makes our behavior a superset of the ecma numeric grammar we might not always be so permissive so we warn about it if base 8 c 8 parser add warning msg bad octal literal c 8 8 9 base 10 add to string c c get char boolean is integer true if base 10 c c e c e is integer false if c do add to string c c get char while is digit c if c e c e add to string c c get char if c c add to string c c get char if is digit c parser add error msg missing exponent return token error do add to string c c get char while is digit c unget char c string num string get string from buffer double dval if base 10 is integer try use java conversion to number from string dval double value of num string double value catch number format exception ex parser add error msg caught nfe return token error else dval script runtime string to number num string 0 base this number dval return token number is it a string if c c we attempt to accumulate a string the fast way by building it directly out of the reader but if there are any escaped characters in the string we revert to building it out of a string buffer int quote char c string buffer top 0 c get char str loop while c quote char if c n c eof char unget char c parser add error msg unterminated string lit return token error if c we ve hit an escaped character int escape val c get char switch c case b c b break case f c f break case n c n break case r c r break case t c t break v a late addition to the ecma spec it is not in java so use 0xb case v c 0xb break case u get 4 hex digits if the u escape is not followed by 4 hex digits use u the literal character sequence that follows int escape start string buffer top add to string u escape val 0 for int i 0 i 4 i c g gettoken ioexception getchar eof_char dirtyline isjsspace dirtyline identifierstart isunicodeescapestart getchar identifierstart isunicodeescapestart stringbuffertop identifierstart ungetchar identifierstart isjavaidentifierstart identifierstart stringbuffertop addtostring identifierstart containsescape isunicodeescapestart isunicodeescapestart escapeval getchar escapeval xdigittoint escapeval escapeval escapeval adderror addtostring escapeval isunicodeescapestart getchar getchar isunicodeescapestart containsescape adderror eof_char isjavaidentifierpart addtostring ungetchar getstringfrombuffer containsescape stringtokeyword compilerenv isreservedkeywordasidentifier ecmascript addwarning allstrings isdigit isdigit peekchar stringbuffertop getchar getchar isdigit addtostring xdigittoint addtostring getchar addwarning addtostring getchar isinteger isinteger addtostring getchar isdigit addtostring getchar addtostring getchar isdigit adderror addtostring getchar isdigit ungetchar numstring getstringfrombuffer isinteger valueof numstring doublevalue numberformatexception adderror scriptruntime stringtonumber numstring stringbuffer quotechar stringbuffertop getchar strloop quotechar eof_char ungetchar adderror escapeval getchar escapestart stringbuffertop addtostring escapeval private static boolean is alpha int c use z a if c z return a c else return a c c z isalpha static boolean is digit int c return 0 c c 9 isdigit static boolean isjs space int c if c 127 return c 0x20 c 0x9 c 0xc c 0xb else return c 0xa0 character get type char c character space separator isjsspace gettype space_separator private static boolean isjs format char int c return c 127 character get type char c character format isjsformatchar gettype parser calls the method when it gets or in literal context void read reg exp int start token throws io exception string buffer top 0 if start token token assign div miss scanned add to string else if start token token div kit code bug int c while c get char if c n c eof char unget char c throw parser report error msg unterminated re lit if c add to string c c get char add to string c int re end string buffer top while true if match char g add to string g else if match char i add to string i else if match char m add to string m else break if is alpha peek char throw parser report error msg invalid re flag this string new string string buffer 0 re end this reg exp flags new string string buffer re end string buffer top re end readregexp starttoken ioexception stringbuffertop starttoken assign_div addtostring starttoken codebug getchar eof_char ungetchar reporterror addtostring getchar addtostring reend stringbuffertop matchchar addtostring matchchar addtostring matchchar addtostring isalpha peekchar reporterror stringbuffer reend regexpflags stringbuffer reend stringbuffertop reend boolean isxml attribute return xml is attribute isxmlattribute xmlisattribute int get firstxml token throws io exception xml open tags count 0 xml is attribute false xml is tag content false unget char return get nextxml token getfirstxmltoken ioexception xmlopentagscount xmlisattribute xmlistagcontent ungetchar getnextxmltoken int get nextxml token throws io exception string buffer top 0 remember the xml for int c get char c eof char c get char if xml is tag content switch c case add to string c xml is tag content false xml is attribute false break case add to string c if peek char c get char add to string c xml is tag content false xml open tags count break case unget char c this string get string from buffer return token xml case case add to string c if read quoted string c return token error break case add to string c xml is attribute true break case case t case r case n add to string c break default add to string c xml is attribute false break if xml is tag content xml open tags count 0 this string get string from buffer return token xmlend else switch c case add to string c c peek char switch c case c get char skip add to string c c peek char switch c case c get char skip add to string c c get char if c add to string c if read xml comment return token error else throw away the string in progress string buffer top 0 this string null parser add error msg xml bad form return token error break case c get char skip add to string c if get char c get char d get char a get char t get char a get char add to string c add to string d add to string a add to string t add to string a add to string if readcdata return token error else throw away the string in progress string buffer top 0 this string null parser add error msg xml bad form return token error break default if read entity return token error break break case c get char skip add to string c if readpi return token error break case end tag c get char skip add to string c if xml open tags count 0 throw away the string in progress string buffer top 0 this string null parser add error msg xml bad form return token error xml is tag content true xml open tags count break default start tag xml is tag content true xml open tags count break break case unget char c this string get string from buffer return token xml default add to string c break string buffer top 0 throw away the string in progress this string null parser add error msg xml bad form return token error getnextxmltoken ioexception stringbuffertop getchar eof_char getchar xmlistagcontent addtostring xmlistagcontent xmlisattribute addtostring peekchar getchar addtostring xmlistagcontent xmlopentagscount ungetchar getstringfrombuffer addtostring readquotedstring addtostring xmlisattribute addtostring addtostring xmlisattribute xmlistagcontent xmlopentagscount getstringfrombuffer addtostring peekchar getchar addtostring peekchar getchar addtostring getchar addtostring readxmlcomment stringbuffertop adderror getchar addtostring getchar getchar getchar getchar getchar getchar addtostring addtostring addtostring addtostring addtostring addtostring stringbuffertop adderror readentity getchar addtostring getchar addtostring xmlopentagscount stringbuffertop adderror xmlistagcontent xmlopentagscount xmlistagcontent xmlopentagscount ungetchar getstringfrombuffer addtostring stringbuffertop adderror private boolean read quoted string int quote throws io exception for int c get char c eof char c get char add to string c if c quote return true string buffer top 0 throw away the string in progress this string null parser add error msg xml bad form return false readquotedstring ioexception getchar eof_char getchar addtostring stringbuffertop adderror private boolean read xml comment throws io exception for int c get char c eof char add to string c if c peek char c get char add to string c if peek char c get char skip add to string c return true else continue c get char string buffer top 0 throw away the string in progress this string null parser add error msg xml bad form return false readxmlcomment ioexception getchar eof_char addtostring peekchar getchar addtostring peekchar getchar addtostring getchar stringbuffertop adderror private boolean readcdata throws io exception for int c get char c eof char add to string c if c peek char c get char add to string c if peek char c get char skip add to string c return true else continue c get char string buffer top 0 throw away the string in progress this string null parser add error msg xml bad form return false ioexception getchar eof_char addtostring peekchar getchar addtostring peekchar getchar addtostring getchar stringbuffertop adderror private boolean read entity throws io exception int decl tags 1 for int c get char c eof char c get char add to string c switch c case decl tags break case decl tags if decl tags 0 return true break string buffer top 0 throw away the string in progress this string null parser add error msg xml bad form return false readentity ioexception decltags getchar eof_char getchar addtostring decltags decltags decltags stringbuffertop adderror private boolean readpi throws io exception for int c get char c eof char c get char add to string c if c peek char c get char skip add to string c return true string buffer top 0 throw away the string in progress this string null parser add error msg xml bad form return false ioexception getchar eof_char getchar addtostring peekchar getchar addtostring stringbuffertop adderror private string get string from buffer return new string string buffer 0 string buffer top getstringfrombuffer stringbuffer stringbuffertop private void add to string int c int n string buffer top if n string buffer length char tmp new char string buffer length 2 system arraycopy string buffer 0 tmp 0 n string buffer tmp string buffer n char c string buffer top n 1 addtostring stringbuffertop stringbuffer stringbuffer stringbuffer stringbuffer stringbuffer stringbuffertop private void unget char int c can not unread past across line boundary if unget cursor 0 unget buffer unget cursor 1 n kit code bug unget buffer unget cursor c ungetchar ungetcursor ungetbuffer ungetcursor codebug ungetbuffer ungetcursor private boolean match char int test throws io exception int c get char if c test return true else unget char c return false matchchar ioexception getchar ungetchar private int peek char throws io exception int c get char unget char c return c peekchar ioexception getchar ungetchar private int get char throws io exception if unget cursor 0 return unget buffer unget cursor for int c if source string null if source cursor source end hiteof true return eof char c source string char at source cursor else if source cursor source end if fill source buffer hiteof true return eof char c source buffer source cursor if line end char 0 if line end char r c n line end char n continue line end char 1 line start source cursor 1 lineno if c 127 if c n c r line end char c c n else if isjs format char c continue if script runtime isjs line terminator c line end char c c n return c getchar ioexception ungetcursor ungetbuffer ungetcursor sourcestring sourcecursor sourceend eof_char sourcestring charat sourcecursor sourcecursor sourceend fillsourcebuffer eof_char sourcebuffer sourcecursor lineendchar lineendchar lineendchar lineendchar linestart sourcecursor lineendchar isjsformatchar scriptruntime isjslineterminator lineendchar private void skip line throws io exception skip to end of line int c while c get char eof char c n unget char c skipline ioexception getchar eof_char ungetchar final int get offset int n source cursor line start if line end char 0 n return n getoffset sourcecursor linestart lineendchar final string get line if source string null string case int line end source cursor if line end char 0 line end else for line end source end line end int c source string char at line end if script runtime isjs line terminator c break return source string substring line start line end else reader case int line length source cursor line start if line end char 0 line length else read until the end of line for line length int i line start line length if i source end try if fill source buffer break catch io exception ioe ignore it we re already displaying an error break i recalculuation as fill source buffer can move saved line buffer and change line start i line start line length int c source buffer i if script runtime isjs line terminator c break return new string source buffer line start line length getline sourcestring lineend sourcecursor lineendchar lineend lineend sourceend lineend sourcestring charat lineend scriptruntime isjslineterminator sourcestring linestart lineend linelength sourcecursor linestart lineendchar linelength linelength linestart linelength sourceend fillsourcebuffer ioexception fillsourcebuffer linestart linestart linelength sourcebuffer scriptruntime isjslineterminator sourcebuffer linestart linelength private boolean fill source buffer throws io exception if source string null kit code bug if source end source buffer length if line start 0 system arraycopy source buffer line start source buffer 0 source end line start source end line start source cursor line start line start 0 else char tmp new char source buffer length 2 system arraycopy source buffer 0 tmp 0 source end source buffer tmp int n source reader read source buffer source end source buffer length source end if n 0 return false source end n return true fillsourcebuffer ioexception sourcestring codebug sourceend sourcebuffer linestart sourcebuffer linestart sourcebuffer sourceend linestart sourceend linestart sourcecursor linestart linestart sourcebuffer sourcebuffer sourceend sourcebuffer sourcereader sourcebuffer sourceend sourcebuffer sourceend sourceend static void init scriptable scope boolean sealed base function obj new base function obj is prototype property immune true obj export asjs class max prototype id scope sealed basefunction basefunction isprototypepropertyimmune exportasjsclass max_prototype_id public base function basefunction public base function scriptable scope scriptable prototype super scope prototype basefunction public string get class name return function getclassname implements the instanceof operator for java script function objects p code foo new foo br foo instanceof foo true br code param instance the value that appeared on the lhs of the instanceof operator return true if the prototype property of this appears in value s prototype chain public boolean has instance scriptable instance object proto prop scriptable object get property this prototype if proto prop instanceof scriptable return script runtime js delegates to instance scriptable proto prop throw script runtime type error1 msg instanceof bad prototype get function name javascript hasinstance protoprop scriptableobject getproperty protoprop scriptruntime jsdelegatesto protoprop scriptruntime typeerror1 getfunctionname 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 20 00 12 12 gmt 02 00 l0 id 0 string x null int c l switch s length case 4 x name id id name break l case 5 x arity id id arity break l case 6 x length id id length break l case 9 c s char at 0 if c a x arguments id id arguments else if c p x prototype id id prototype break l 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 length case id arity case id name attr dontenum readonly permanent break case id prototype attr is prototype property immune dontenum readonly permanent dontenum break case id arguments attr dontenum permanent break default throw new illegal state exception return instance id info attr id findinstanceidinfo id_name id_arity id_length charat id_arguments id_prototype string_id_map findinstanceidinfo id_length id_arity id_name id_prototype isprototypepropertyimmune id_arguments illegalstateexception instanceidinfo protected string get instance id name int id switch id case id length return length case id arity return arity case id name return name case id prototype return prototype case id arguments return arguments return super get instance id name id getinstanceidname id_length id_arity id_name id_prototype id_arguments getinstanceidname protected object get instance id value int id switch id case id length return script runtime wrap int get length case id arity return script runtime wrap int get arity case id name return get function name case id prototype return get prototype property case id arguments return get arguments return super get instance id value id getinstanceidvalue id_length scriptruntime wrapint getlength id_arity scriptruntime wrapint getarity id_name getfunctionname id_prototype getprototypeproperty id_arguments getarguments getinstanceidvalue protected void set instance id value int id object value if id id prototype if is prototype property immune prototype property value null value unique tag null value return else if id id arguments if value not found this should not be called since arguments is permanent kit code bug default put arguments value super set instance id value id value setinstanceidvalue id_prototype isprototypepropertyimmune prototypeproperty uniquetag null_value id_arguments not_found codebug defaultput setinstanceidvalue protected void fill constructor properties id function object ctor fix up bootstrapping problem get prototype of the id function object can not return function prototype because function object is not yet defined ctor set prototype this super fill constructor properties ctor fillconstructorproperties idfunctionobject getprototype idfunctionobject setprototype 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 tosource arity 1 s to source break case id apply arity 2 s apply break case id call arity 1 s call break default throw new illegal argument exception string value of id init prototype method function tag id s arity initprototypeid id_constructor id_tostring tostring id_tosource tosource id_apply id_call illegalargumentexception valueof initprototypemethod function_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag function 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 scope args case id tostring base function realf real function this obj f int indent script runtime to int32 args 0 return realf decompile indent 0 case id tosource base function realf real function this obj f int indent 0 int flags decompiler to source flag if args length 0 indent script runtime to int32 args 0 if indent 0 flags 0 else indent 0 return realf decompile indent flags case id apply case id call return script runtime apply or call id id apply cx scope this obj args throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag function_tag execidcall thisobj methodid id_constructor jsconstructor id_tostring basefunction realfunction thisobj scriptruntime toint32 id_tosource basefunction realfunction thisobj to_source_flag scriptruntime toint32 id_apply id_call scriptruntime applyorcall id_apply thisobj illegalargumentexception valueof private base function real function scriptable this obj id function object f object x this obj get default value script runtime function class if x instanceof base function return base function x throw script runtime type error1 msg incompat call f get function name basefunction realfunction thisobj idfunctionobject thisobj getdefaultvalue scriptruntime functionclass basefunction basefunction scriptruntime typeerror1 getfunctionname make value as dont enum dont delete read only prototype property of this function object public void set immune prototype property object value if is prototype property immune throw new illegal state exception prototype property value null value unique tag null value is prototype property immune true dontenum dontdelete readonly setimmuneprototypeproperty isprototypepropertyimmune illegalstateexception prototypeproperty uniquetag null_value isprototypepropertyimmune protected scriptable get class prototype object proto val get prototype property if proto val instanceof scriptable return scriptable proto val return get class prototype this object getclassprototype protoval getprototypeproperty protoval protoval getclassprototype should be overridden public object call context cx scriptable scope scriptable this obj object args return undefined instance thisobj public scriptable construct context cx scriptable scope object args scriptable result create object cx scope if result null object val call cx scope result args if val instanceof scriptable result scriptable val else object val call cx scope null args if val instanceof scriptable it is program error not to return scriptable from the call method if create object returns null throw new illegal state exception bad implementaion of call as constructor name get function name in get class get name result scriptable val if result get prototype null result set prototype get class prototype if result get parent scope null scriptable parent get parent scope if result parent result set parent scope parent return result createobject createobject illegalstateexception getfunctionname getclass getname getprototype setprototype getclassprototype getparentscope getparentscope setparentscope creates new script object the default implementation of link construct uses the method to to get the value for tt this obj tt argument when invoking link call the methos is allowed to return tt null tt to indicate that link call will create a new object itself in this case link construct will set scope and prototype on the result link call unless they are already set public scriptable create object context cx scriptable scope scriptable new instance new native object new instance set prototype get class prototype new instance set parent scope get parent scope return new instance thisobj createobject newinstance nativeobject newinstance setprototype getclassprototype newinstance setparentscope getparentscope newinstance decompile the source information associated with this js function script back into a string param indent how much to indent the decompiled result param flags flags specifying format of decompilation output string decompile int indent int flags string buffer sb new string buffer boolean justbody 0 flags decompiler only body flag if justbody sb append function sb append get function name sb append n t sb append native code arity sb append get arity sb append n if justbody sb append n return sb to string stringbuffer stringbuffer only_body_flag getfunctionname getarity tostring public int get arity return 0 getarity public int get arity return 0 public int get length return 0 getarity getlength public int get length return 0 public string get function name return getlength getfunctionname final object get prototype property object result prototype property if result null synchronized this result prototype property if result null setup default prototype result prototype property else if result unique tag null value result null return result getprototypeproperty prototypeproperty prototypeproperty setupdefaultprototype prototypeproperty uniquetag null_value private void setup default prototype native object obj new native object final int attr scriptable object dontenum obj define property constructor this attr put the prototype property into the object now then in the wacky case of a user defining a function object we don t get an infinite loop trying to find the prototype prototype property obj scriptable proto get object prototype this if proto obj not the one we just made it must remain grounded obj set prototype proto setupdefaultprototype nativeobject nativeobject scriptableobject defineproperty prototypeproperty getobjectprototype setprototype private object get arguments function name arguments is deprecated so we use a slow way of getting it that doesn t add to the invocation cost todo add warning error based on version object value default get arguments if value not found should after changing function name arguments its activation still be available during function call this code assumes it should not default get arguments not found means assigned arguments return value context cx context get context native call activation script runtime find function activation cx this return activation null null activation get arguments activation getarguments defaultget not_found defaultget not_found getcontext nativecall scriptruntime findfunctionactivation private static object js constructor context cx scriptable scope object args int arglen args length string buffer source buf new string buffer source buf append function version 1 2 function constructor behavior print anonymous as the function name if the version under which the function was compiled is less than 1 2 or if it s greater than 1 2 because we need to be closer to ecma if cx get language version context version 1 2 source buf append anonymous source buf append append arguments as coma separated strings for int i 0 i arglen 1 i if i 0 source buf append source buf append script runtime to string args i source buf append if arglen 0 append function body string fun body script runtime to string args arglen 1 source buf append fun body source buf append string source source buf to string int linep new int 1 string filename context get source position from stack linep if filename null filename eval ed string linep 0 1 string sourceuri script runtime make url for generated script false filename linep 0 scriptable global scriptable object get top level scope scope error reporter reporter reporter default error reporter for eval cx get error reporter compile with explicit interpreter instance to force interpreter mode return cx compile function global source new interpreter reporter sourceuri 1 null jsconstructor stringbuffer sourcebuf stringbuffer sourcebuf getlanguageversion version_1_2 sourcebuf sourcebuf sourcebuf sourcebuf scriptruntime tostring sourcebuf funbody scriptruntime tostring sourcebuf funbody sourcebuf sourcebuf tostring getsourcepositionfromstack scriptruntime makeurlforgeneratedscript scriptableobject gettoplevelscope errorreporter defaulterrorreporter foreval geterrorreporter compilefunction protected int find prototype id string s int id string id map generated last update 2004 03 17 13 23 22 cet l0 id 0 string x null int c l switch s length case 4 x call id id call break l case 5 x apply id id apply 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 x constructor id id constructor break l if x null x s x equals s id 0 generated return id findprototypeid string_id_map id_call id_apply charat tosource id_tosource tostring id_tostring id_constructor static final long serial versionuid 5637830967241712746l public class definition exception string detail super detail serialversionuid classdefinitionexception public class script or fn node extends node public script or fn node int node type super node type scriptorfnnode scriptorfnnode nodetype nodetype public final string get source name return source name getsourcename sourcename public final string get source name return source name public final void set source name string source name this source name source name getsourcename sourcename setsourcename sourcename sourcename sourcename public final int get encoded source start return encoded source start getencodedsourcestart encodedsourcestart public final int get encoded source start return encoded source start public final int get encoded source end return encoded source end getencodedsourcestart encodedsourcestart getencodedsourceend encodedsourceend public final int get encoded source end return encoded source end public final void set encoded source bounds int start int end this encoded source start start this encoded source end end getencodedsourceend encodedsourceend setencodedsourcebounds encodedsourcestart encodedsourceend public final int get base lineno return base lineno getbaselineno baselineno public final void set base lineno int lineno one time action if lineno 0 base lineno 0 kit code bug base lineno lineno setbaselineno baselineno codebug baselineno public final int get end lineno return end lineno getendlineno endlineno public final void set end lineno int lineno one time action if lineno 0 end lineno 0 kit code bug end lineno lineno setendlineno endlineno codebug endlineno public final int get function count if functions null return 0 return functions size getfunctioncount public final function node get function node int i return function node functions get i functionnode getfunctionnode functionnode public final int add function function node fn node if fn node null kit code bug if functions null functions new obj array functions add fn node return functions size 1 addfunction functionnode fnnode fnnode codebug objarray fnnode public final int get regexp count if regexps null return 0 return regexps size 2 getregexpcount public final string get regexp string int index return string regexps get index 2 getregexpstring public final string get regexp flags int index return string regexps get index 2 1 getregexpflags public final int add regexp string string string flags if string null kit code bug if regexps null regexps new obj array regexps add string regexps add flags return regexps size 2 1 addregexp codebug objarray public final boolean has param or var string name return its variable names has name hasparamorvar itsvariablenames public final int get param or var index string name return its variable names get name 1 getparamorvarindex itsvariablenames public final string get param or var name int index return string its variables get index getparamorvarname itsvariables public final int get param count return var start getparamcount varstart public final int get param and var count return its variables size getparamandvarcount itsvariables public final string get param and var names int n its variables size if n 0 return script runtime empty strings string array new string n its variables to array array return array getparamandvarnames itsvariables scriptruntime emptystrings itsvariables toarray public final void add param string name check addparam is not called after add local if var start its variables size kit code bug allow non unique parameter names use the last occurrence int index var start its variables add name its variable names put name index addparam addlocal varstart itsvariables codebug varstart itsvariables itsvariablenames public final void add var string name int v index its variable names get name 1 if v index 1 there s already a variable or parameter with this name return int index its variables size its variables add name its variable names put name index addvar vindex itsvariablenames vindex itsvariables itsvariables itsvariablenames public final void remove param or var string name int i its variable names get name 1 if i 1 its variables remove i its variable names remove name obj to int map iterator iter its variable names new iterator for iter start iter done iter next int v iter get value if v i iter set value v 1 removeparamorvar itsvariablenames itsvariables itsvariablenames objtointmap itsvariablenames newiterator getvalue setvalue public final object get compiler data return compiler data getcompilerdata compilerdata public final void set compiler data object data if data null throw new illegal argument exception can only call once if compiler data null throw new illegal state exception compiler data data setcompilerdata illegalargumentexception compilerdata illegalstateexception compilerdata 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 static string static object static object public static string static ambiguous boolean arg return static boolean object static_object static_object staticambiguous static_boolean_object public static string static ambiguous string arg return static string staticambiguous static_string public static string static ambiguous object arg return static object staticambiguous static_object static final long serial versionuid 4174889037736658296l public obj array serialversionuid objarray public obj array public final boolean is sealed return sealed objarray issealed public final void seal sealed true public final boolean is empty return size 0 isempty public final int size return size public final void set size int new size if new size 0 throw new illegal argument exception if sealed throw on seled mutation int n size if new size n for int i new size i n i set impl i null else if new size n if new size fields store size ensure capacity new size size new size setsize newsize newsize illegalargumentexception onseledmutation newsize newsize setimpl newsize newsize fields_store_size ensurecapacity newsize newsize public final object get int index if 0 index index size throw on invalid index index size return get impl index oninvalidindex getimpl public final void set int index object value if 0 index index size throw on invalid index index size if sealed throw on seled mutation set impl index value oninvalidindex onseledmutation setimpl private object get impl int index switch index case 0 return f0 case 1 return f1 case 2 return f2 case 3 return f3 case 4 return f4 return data index fields store size getimpl fields_store_size private void set impl int index object value switch index case 0 f0 value break case 1 f1 value break case 2 f2 value break case 3 f3 value break case 4 f4 value break default data index fields store size value setimpl fields_store_size public int index of object obj int n size for int i 0 i n i object current get impl i if current obj current null current equals obj return i return 1 indexof getimpl public int last index of object obj for int i size i 0 i object current get impl i if current obj current null current equals obj return i return 1 lastindexof getimpl public final object peek int n size if n 0 throw on empty stack top read return get impl n 1 onemptystacktopread getimpl public final object pop if sealed throw on seled mutation int n size n object top switch n case 1 throw on empty stack top read case 0 top f0 f0 null break case 1 top f1 f1 null break case 2 top f2 f2 null break case 3 top f3 f3 null break case 4 top f4 f4 null break default top data n fields store size data n fields store size null size n return top onseledmutation onemptystacktopread fields_store_size fields_store_size public final void push object value add value public final void add object value if sealed throw on seled mutation int n size if n fields store size ensure capacity n 1 size n 1 set impl n value onseledmutation fields_store_size ensurecapacity setimpl public final void add int index object value int n size if 0 index index n throw on invalid index index n 1 if sealed throw on seled mutation object tmp switch index case 0 if n 0 f0 value break tmp f0 f0 value value tmp case 1 if n 1 f1 value break tmp f1 f1 value value tmp case 2 if n 2 f2 value break tmp f2 f2 value value tmp case 3 if n 3 f3 value break tmp f3 f3 value value tmp case 4 if n 4 f4 value break tmp f4 f4 value value tmp index fields store size default ensure capacity n 1 if index n system arraycopy data index fields store size data index fields store size 1 n index data index fields store size value size n 1 oninvalidindex onseledmutation fields_store_size ensurecapacity fields_store_size fields_store_size fields_store_size public final void remove int index int n size if 0 index index n throw on invalid index index n if sealed throw on seled mutation n switch index case 0 if n 0 f0 null break f0 f1 case 1 if n 1 f1 null break f1 f2 case 2 if n 2 f2 null break f2 f3 case 3 if n 3 f3 null break f3 f4 case 4 if n 4 f4 null break f4 data 0 index fields store size default if index n system arraycopy data index fields store size 1 data index fields store size n index data n fields store size null size n oninvalidindex onseledmutation fields_store_size fields_store_size fields_store_size fields_store_size public final void clear if sealed throw on seled mutation int n size for int i 0 i n i set impl i null size 0 onseledmutation setimpl public final object to array object array new object size to array array 0 return array toarray toarray public final void to array object array to array array 0 toarray toarray public final void to array object array int offset int n size switch n default system arraycopy data 0 array offset fields store size n fields store size case 5 array offset 4 f4 case 4 array offset 3 f3 case 3 array offset 2 f2 case 2 array offset 1 f1 case 1 array offset 0 f0 case 0 break toarray fields_store_size fields_store_size private void ensure capacity int minimal capacity int required minimal capacity fields store size if required 0 throw new illegal argument exception if data null int alloc fields store size 2 if alloc required alloc required data new object alloc else int alloc data length if alloc required if alloc fields store size alloc fields store size 2 else alloc 2 if alloc required alloc required object tmp new object alloc if size fields store size system arraycopy data 0 tmp 0 size fields store size data tmp ensurecapacity minimalcapacity minimalcapacity fields_store_size illegalargumentexception fields_store_size fields_store_size fields_store_size fields_store_size fields_store_size private static runtime exception on invalid index int index int upper bound u2209 is not element of string msg index u2209 0 upper bound throw new index out of bounds exception msg runtimeexception oninvalidindex upperbound upperbound indexoutofboundsexception private static runtime exception on empty stack top read throw new runtime exception empty stack runtimeexception onemptystacktopread runtimeexception private static runtime exception on seled mutation throw new illegal state exception attempt to modify sealed array runtimeexception onseledmutation illegalstateexception private void write object object output stream os throws io exception os default write object int n size for int i 0 i n i object obj get impl i os write object obj writeobject objectoutputstream ioexception defaultwriteobject getimpl writeobject private void read object object input stream is throws io exception class not found exception is default read object it reads size int n size if n fields store size data new object n fields store size for int i 0 i n i object obj is read object set impl i obj readobject objectinputstream ioexception classnotfoundexception defaultreadobject fields_store_size fields_store_size readobject setimpl public abstract class rhino exception extends runtime exception rhino exception interpreter capture interpreter stack info this rhinoexception runtimeexception rhinoexception captureinterpreterstackinfo rhino exception string details super details interpreter capture interpreter stack info this rhinoexception captureinterpreterstackinfo public final string get message string details details if source name null line number 0 return details string buffer buf new string buffer details buf append if source name null buf append source name if line number 0 buf append buf append line number buf append return buf to string getmessage sourcename linenumber stringbuffer stringbuffer sourcename sourcename linenumber linenumber tostring public string details return super get message getmessage get the uri of the script source containing the error or null if that information is not available public final string source name return source name sourcename sourcename initialize the uri of the script source containing the error param source name the uri of the script source reponsible for the error it should not be tt null tt throws illegal state exception if the method is called more then once public final void init source name string source name if source name null throw new illegal argument exception if this source name null throw new illegal state exception this source name source name sourcename illegalstateexception initsourcename sourcename sourcename illegalargumentexception sourcename illegalstateexception sourcename sourcename returns the line number of the statement causing the error or zero if not available public final int line number return line number linenumber linenumber initialize the line number of the script statement causing the error param line number the line number in the script source it should be positive number throws illegal state exception if the method is called more then once public final void init line number int line number if line number 0 throw new illegal argument exception string value of line number if this line number 0 throw new illegal state exception this line number line number linenumber illegalstateexception initlinenumber linenumber linenumber illegalargumentexception valueof linenumber linenumber illegalstateexception linenumber linenumber the column number of the location of the error or zero if unknown public final int column number return column number columnnumber columnnumber initialize the column number of the script statement causing the error param column number the column number in the script source it should be positive number throws illegal state exception if the method is called more then once public final void init column number int column number if column number 0 throw new illegal argument exception string value of column number if this column number 0 throw new illegal state exception this column number column number columnnumber illegalstateexception initcolumnnumber columnnumber columnnumber illegalargumentexception valueof columnnumber columnnumber illegalstateexception columnnumber columnnumber the source text of the line causing the error or null if unknown public final string line source return line source linesource linesource initialize the text of the source line containing the error param line source the text of the source line reponsible for the error it should not be tt null tt throws illegal state exception if the method is called more then once public final void init line source string line source if line source null throw new illegal argument exception if this line source null throw new illegal state exception this line source line source linesource illegalstateexception initlinesource linesource linesource illegalargumentexception linesource illegalstateexception linesource linesource final void record error origin string source name int line number string line source int column number xxx for compatibility allow for now 1 to mean 0 if line number 1 line number 0 if source name null init source name source name if line number 0 init line number line number if line source null init line source line source if column number 0 init column number column number recorderrororigin sourcename linenumber linesource columnnumber linenumber linenumber sourcename initsourcename sourcename linenumber initlinenumber linenumber linesource initlinesource linesource columnnumber initcolumnnumber columnnumber private string generate stack trace get stable reference to work properly with concurrent access char array writer writer new char array writer super print stack trace new print writer writer string orig stack trace writer to string return interpreter get patched stack this orig stack trace generatestacktrace chararraywriter chararraywriter printstacktrace printwriter origstacktrace tostring getpatchedstack origstacktrace public void print stack trace print writer s if interpreter stack info null super print stack trace s else s print generate stack trace printstacktrace printwriter interpreterstackinfo printstacktrace generatestacktrace public void print stack trace print stream s if interpreter stack info null super print stack trace s else s print generate stack trace printstacktrace printstream interpreterstackinfo printstacktrace generatestacktrace 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 expect return char see context throw as script runtime ex throwable e public wrapped exception throwable exception super wrapped exception to string this exception exception kit init cause this exception int linep 0 string source name context get source position from stack linep int line number linep 0 if source name null init source name source name if line number 0 init line number line number throwasscriptruntimeex wrappedexception tostring initcause sourcename getsourcepositionfromstack linenumber sourcename initsourcename sourcename linenumber initlinenumber linenumber get the wrapped exception return the exception that was presented as a argument to the constructor when this object was created public throwable get wrapped exception return exception getwrappedexception deprecated use link get wrapped exception instead public object unwrap return get wrapped exception getwrappedexception getwrappedexception public class counter extends scriptable object the zero argument constructor used by rhino runtime to create instances public counter scriptableobject method js constructor defines the java script constructor public void js constructor int a count a jsconstructor javascript jsconstructor the class name is defined by the get class name method public string get class name return counter getclassname getclassname the method jsget count defines the count property public int jsget count return count jsget_count jsget_count methods can be defined using the jsfunction prefix here we define reset count for java script public void jsfunction resetcount count 0 jsfunction_ resetcount javascript jsfunction_resetcount 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 ambiguous long arg return long public string ambiguous float arg return float return float public string expect return float void optimize script or fn node script or fn int opt level its opt level opt level run on one function at a time for now int function count script or fn get function count for int i 0 i function count i opt function node f opt function node get script or fn i optimize function f scriptorfnnode scriptorfn optlevel itsoptlevel optlevel functioncount scriptorfn getfunctioncount functioncount optfunctionnode optfunctionnode scriptorfn optimizefunction private void optimize function opt function node the function if the function fnode requires activation return in direct call function the function is target of direct call this the function the function obj array statements array new obj array buildstatementlist r the function fnode statements array node the statement nodes new node statements array size statements array to array the statement nodes block run flow analyzes the function the statement nodes if the function fnode requires activation now that we know which local vars are in fact always numbers we re write the tree to take advantage of that any arithmetic or assignment op involving just number typed vars is marked so that the codegen will generate non object code parameter used in number context false for int i 0 i the statement nodes length i rewrite for number variables the statement nodes i the function set parameter number context parameter used in number context optimizefunction optfunctionnode thefunction thefunction requiresactivation indirectcallfunction thefunction istargetofdirectcall thefunction thefunction objarray statementsarray objarray buildstatementlist_r thefunction statementsarray thestatementnodes statementsarray statementsarray toarray thestatementnodes runflowanalyzes thefunction thestatementnodes thefunction requiresactivation parameterusedinnumbercontext thestatementnodes rewritefornumbervariables thestatementnodes thefunction setparameternumbercontext parameterusedinnumbercontext private void markdcp number context node n if in direct call function n get type token getvar int var index the function get var index n if the function is parameter var index parameter used in number context true markdcpnumbercontext indirectcallfunction gettype varindex thefunction getvarindex thefunction isparameter varindex parameterusedinnumbercontext private boolean convert parameter node n if in direct call function n get type token getvar int var index the function get var index n if the function is parameter var index n remove prop node isnumber prop return true return false convertparameter indirectcallfunction gettype varindex thefunction getvarindex thefunction isparameter varindex removeprop isnumber_prop private int rewrite for number variables node n switch n get type case token expr void node child n get first child int type rewrite for number variables child if type number type n put int prop node isnumber prop node both return no type case token number n put int prop node isnumber prop node both return number type case token getvar int var index the function get var index n if in direct call function the function is parameter var index n put int prop node isnumber prop node both return number type else if the function is number var var index n put int prop node isnumber prop node both return number type return no type case token inc case token dec node child n get first child will be a getvar or getprop if child get type token getvar int var index the function get var index child if the function is number var var index n put int prop node isnumber prop node both markdcp number context child return number type else return no type else return no type case token setvar node l child n get first child node r child l child get next int r type rewrite for number variables r child int var index the function get var index n if in direct call function the function is parameter var index if r type number type if convert parameter r child n put int prop node isnumber prop node both return number type markdcp number context r child return no type else return r type else if the function is number var var index if r type number type n remove child r child n add child to back new node token to double r child n put int prop node isnumber prop node both markdcp number context r child return number type else if r type number type if convert parameter r child n remove child r child n add child to back new node token to object r child return no type case token le case token lt case token ge case token gt node l child n get first child node r child l child get next int l type rewrite for number variables l child int r type rewrite for number variables r child markdcp number context l child markdcp number context r child if convert parameter l child if convert parameter r child return no type else if r type number type n put int prop node isnumber prop node right else if convert parameter r child if l type number type n put int prop node isnumber prop node left else if l type number type if r type number type n put int prop node isnumber prop node both else n put int prop node isnumber prop node left else if r type number type n put int prop node isnumber prop node right we actually build a boolean value return no type case token add node l child n get first child node r child l child get next int l type rewrite for number variables l child int r type rewrite for number variables r child if convert parameter l child if convert parameter r child return no type else if r type number type n put int prop node isnumber prop node right else if convert parameter r child if l type number type n put int prop node isnumber prop node left else if l type number type if r type number type n put int prop node isnumber prop node both return number type else n put int prop node isnumber prop node left else if r type number type n put int prop node isnumber prop node right return no type case token bitxor case token bitor case token bitand case token rsh case token lsh case token sub case token mul case token div case token mod node l child n get first child node r child l child get next int l type rewrite for number variables l child int r type rewrite for number variables r child markdcp number context l child markdcp number context r child if l type number type if r type number type n put int prop node isnumber prop node both return number type else if convert parameter r child n remove child r child n add child to back new node token to double r child n put int prop node isnumber prop node both return number type else if r type number type if convert parameter l child n remove child l child n add child to front new node token to double l child n put int prop node isnumber prop node both return number type else if convert parameter l child n remove child l child n add child to front new node token to double l child if convert parameter r child n remove child r child n add child to back new node token to double r child n put int prop node isnumber prop node both return number type case token setelem case token setelem op rewritefornumbervariables gettype expr_void getfirstchild rewritefornumbervariables numbertype putintprop isnumber_prop notype putintprop isnumber_prop numbertype varindex thefunction getvarindex indirectcallfunction thefunction isparameter varindex putintprop isnumber_prop numbertype thefunction isnumbervar varindex putintprop isnumber_prop numbertype notype getfirstchild gettype varindex thefunction getvarindex thefunction isnumbervar varindex putintprop isnumber_prop markdcpnumbercontext numbertype notype notype lchild getfirstchild rchild lchild getnext rtype rewritefornumbervariables rchild varindex thefunction getvarindex indirectcallfunction thefunction isparameter varindex rtype numbertype convertparameter rchild putintprop isnumber_prop numbertype markdcpnumbercontext rchild notype rtype thefunction isnumbervar varindex rtype numbertype removechild rchild addchildtoback to_double rchild putintprop isnumber_prop markdcpnumbercontext rchild numbertype rtype numbertype convertparameter rchild removechild rchild addchildtoback to_object rchild notype lchild getfirstchild rchild lchild getnext ltype rewritefornumbervariables lchild rtype rewritefornumbervariables rchild markdcpnumbercontext lchild markdcpnumbercontext rchild convertparameter lchild convertparameter rchild notype rtype numbertype putintprop isnumber_prop convertparameter rchild ltype numbertype putintprop isnumber_prop ltype numbertype rtype numbertype putintprop isnumber_prop putintprop isnumber_prop rtype numbertype putintprop isnumber_prop notype lchild getfirstchild rchild lchild getnext ltype rewritefornumbervariables lchild rtype rewritefornumbervariables rchild convertparameter lchild convertparameter rchild notype rtype numbertype putintprop isnumber_prop convertparameter rchild ltype numbertype putintprop isnumber_prop ltype numbertype rtype numbertype putintprop isnumber_prop numbertype putintprop isnumber_prop rtype numbertype putintprop isnumber_prop notype lchild getfirstchild rchild lchild getnext ltype rewritefornumbervariables lchild rtype rewritefornumbervariables rchild markdcpnumbercontext lchild markdcpnumbercontext rchild ltype numbertype rtype numbertype putintprop isnumber_prop numbertype convertparameter rchild removechild rchild addchildtoback to_double rchild putintprop isnumber_prop numbertype rtype numbertype convertparameter lchild removechild lchild addchildtofront to_double lchild putintprop isnumber_prop numbertype convertparameter lchild removechild lchild addchildtofront to_double lchild convertparameter rchild removechild rchild addchildtoback to_double rchild putintprop isnumber_prop numbertype setelem_op private void rewrite as object children node n node child force optimized children to be objects while child null node next child child get next int type rewrite for number variables child if type number type if convert parameter child n remove child child node nu child new node token to object child if next child null n add child to back nu child else n add child before nu child next child child next child rewriteasobjectchildren nextchild getnext rewritefornumbervariables numbertype convertparameter removechild nuchild to_object nextchild addchildtoback nuchild addchildbefore nuchild nextchild nextchild private static void buildstatementlist r node node obj array statements int type node get type if type token block type token local block type token loop type token function node child node get first child while child null buildstatementlist r child statements child child get next else statements add node buildstatementlist_r objarray gettype local_block getfirstchild buildstatementlist_r getnext construct a new live nav env param file test file whose program will be evaluated in this environment param suite test suite which this test file belongs to param driver test driver that is currently running public live nav env test file file test suite suite live nav drv driver super file suite driver livenavenv testfile testsuite testfile testdriver livenavenv testfile testsuite livenavdrv open the current test file in the window by using live connect to set the window s location href property to a url where the test file can be found xxx need to generate html file on the fly public object execute test file try location js object window get member location driver p file name we need to look for the html file in the test directory the name of the file is the class name html string classname file name substring 0 file name length class length html string s driver http path classname system out println trying to set browser window to s location set member href s evaluated successfully wait for completion catch exception e driver p file name failed with exception e file exception e to string if file name ends with n js this file passed true evaluated successfully true else this file passed false this suite passed false evaluated successfully false return null testfile liveconnect testfile executetestfile jsobject getmember http_path setmember evaluatedsuccessfully waitforcompletion tostring endswith evaluatedsuccessfully evaluatedsuccessfully get a reference to the live connect test applet unfortunately due to reasons i don t understand we can t just get the test file object from the live connect test via live connect attempting to cast the applet to live connect test fails with a java lang class cast exception so we continue to use the temporary file hack in navigator need a reference to the applet so we can properly destroy it before closing the navigator window this is http scopus bugsplat show bug cgi id 300350 and when that s fixed we can ue the get applet class method below to directly access the live connect test s test file file object so we don t have use the temporary file hack public applet get applet object document object window get member document object applets js object document get member applets return applet js object applets get slot 0 liveconnecttest testfile liveconnecttest liveconnect liveconnecttest classcastexception show_bug getappletclass liveconnecttest testfile getapplet getmember jsobject getmember jsobject getslot currently does not work see get applet public void get applet class applet applet try driver p the class of applet is applet get class to string driver p is it a jsobject 001 applet instanceof jsobject 001 driver p is it a live connect test applet instanceof live connect test driver p is it an applet applet instanceof applet driver p try to cast applet to jsobject 001 this throws the class cast exception driver p jsobject 001 applet to string catch exception e driver p parse result threw exception e getapplet getappletclass getclass tostring jsobject_001 jsobject_001 liveconnecttest liveconnecttest jsobject_001 classcastexception jsobject_001 tostring parseresult parse the results file for this test the which contains data in the following format pre classname live connect test class name 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 boolean parse result applet get applet vector label null vector value null try file reader fr new file reader driver output directory get absolute path driver output directory get absolute path ends with file separator file separator live connect test 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 if passed this file passed false this suite passed false this file 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 catch io exception e driver p e to string return false return true liveconnecttest no_passed no_failed liveconnecttest writeresultstotempfile parseresult getapplet filereader filereader output_directory getabsolutepath output_directory getabsolutepath endswith liveconnecttest temp_log_name bufferedreader bufferedreader readline readline booleanvalue readline intvalue no_passed readline intvalue no_failed readline intvalue totalcases casespassed no_passed casespassed no_passed casesfailed no_failed casesfailed no_failed ioexception tostring destroy the test applet close navigator window and delete the reference to the test applet s window public void close applet destroy opener eval window name close opener eval delete window name window_name window_name public string ambiguous string arg return string public string ambiguous object arg return object public static string static ambiguous string arg return static string staticambiguous static_string public static string static ambiguous object arg return static object staticambiguous static_object private static final int dtobasestr buffer size 1078 private static char basedigit int digit return char digit 10 a 10 digit 0 digit dtobasestr_buffer_size private static int lo0bits int y int k int x y if x 7 0 if x 1 0 return 0 if x 2 0 return 1 return 2 k 0 if x 0xffff 0 k 16 x 16 if x 0xff 0 k 8 x 8 if x 0xf 0 k 4 x 4 if x 0x3 0 k 2 x 2 if x 1 0 k x 1 if x 1 0 return 32 return k return the number 0 through 32 of most significant zero bits in x private static int hi0bits int x int k 0 if x 0xffff0000 0 k 16 x 16 if x 0xff000000 0 k 8 x 8 if x 0xf0000000 0 k 4 x 4 if x 0xc0000000 0 k 2 x 2 if x 0x80000000 0 k if x 0x40000000 0 return 32 return k private static void stuff bits byte bits int offset int val bits offset byte val 24 bits offset 1 byte val 16 bits offset 2 byte val 8 bits offset 3 byte val stuffbits bits in b in bits d must be finite and nonzero private static big integer d2b double d int e int bits byte dbl bits int i k y z de long d bits double double to long bits d int d0 int d bits 32 int d1 int d bits z d0 frac mask d0 0x7fffffff clear sign bit which we ignore if de int d0 exp shift 0 z exp msk1 if y d1 0 dbl bits new byte 8 k lo0bits y y k if k 0 stuff bits dbl bits 4 y z 32 k z k else stuff bits dbl bits 4 y stuff bits dbl bits 0 z i z 0 2 1 else js assert z dbl bits new byte 4 k lo0bits z z k stuff bits dbl bits 0 z k 32 i 1 if de 0 e 0 de bias p 1 k bits 0 p k else e 0 de bias p 1 1 k bits 0 32 i hi0bits z return new big integer dbl bits biginteger dbl_bits dbits doubletolongbits dbits dbits frac_mask exp_shift exp_msk1 dbl_bits stuffbits dbl_bits stuffbits dbl_bits stuffbits dbl_bits js_assert dbl_bits stuffbits dbl_bits biginteger dbl_bits static string js dtobasestr int base double d if 2 base base 36 throw new illegal argument exception bad base base check for infinity and nan if double is nan d return nan else if double is infinite d return d 0 0 infinity infinity else if d 0 alert should it distinguish 0 0 from 0 0 return 0 boolean negative if d 0 0 negative false else negative true d d get the integer part of d including sign string int digits double dfloor math floor d long lfloor long dfloor if lfloor dfloor int part fits long int digits long to string negative lfloor lfloor base else big integer should be used long floor bits double double to long bits dfloor int exp int floor bits exp shiftl exp mask shifted long mantissa if exp 0 mantissa floor bits frac maskl 1 else mantissa floor bits frac maskl exp msk1l if negative mantissa mantissa exp 1075 big integer x big integer value of mantissa if exp 0 x x shift left exp else if exp 0 x x shift right exp int digits x to string base if d dfloor no fraction part return int digits else we have a fraction char buffer the output string int p index to current position in the buffer int q int digit double df the fractional part of d big integer b buffer new char dtobasestr buffer size p 0 df d dfloor long d bits double double to long bits d int word0 int d bits 32 int word1 int d bits int e new int 1 int bbits new int 1 b d2b df e bbits js assert e 0 at this point df b 2 e e must be less than zero because 0 df 1 int s2 word0 exp shift1 exp mask exp shift1 if s2 0 s2 1 s2 bias p 1 2 s2 next double d d 2 js assert s2 e big integer mlo big integer value of 1 big integer mhi mlo if word1 0 word0 bndry mask 0 word0 exp mask exp mask 1 0 the special case here we want to be within a quarter of the last input significant digit instead of one half of it when the output string s value is less than d s2 log2p mhi big integer value of 1 log2p b b shift left e 0 s2 big integer s big integer value of 1 s s shift left s2 at this point we have the following s 2 s2 1 df b 2 s2 0 d prev double d 2 mlo 2 s2 next double d d 2 mhi 2 s2 big integer big base big integer value of base boolean done false do b b multiply big base big integer div result b divide and remainder s b div result 1 digit char div result 0 int value if mlo mhi mlo mhi mlo multiply big base else mlo mlo multiply big base mhi mhi multiply big base do we yet have the shortest string that will round to d int j b compare to mlo j is b 2 s2 compared with mlo 2 s2 big integer delta s subtract mhi int j1 delta signum 0 1 b compare to delta j1 is b 2 s2 compared with 1 mhi 2 s2 if j1 0 word1 1 0 if j 0 digit done true else if j 0 j 0 word1 1 0 if j1 0 either dig or dig 1 would work here as the least significant digit use whichever would produce an output value closer to d b b shift left 1 j1 b compare to s if j1 0 the even test j1 0 digit 1 is not here because it messes up odd base output such as 3 5 in base 3 digit done true else if j1 0 digit done true js assert digit uint32 base buffer p basedigit digit while done string buffer sb new string buffer int digits length 1 p sb append int digits sb append sb append buffer 0 p return sb to string js_dtobasestr illegalargumentexception isnan isinfinite intdigits intdigits tostring biginteger floorbits doubletolongbits floorbits exp_shiftl exp_mask_shifted floorbits frac_maskl floorbits frac_maskl exp_msk1l biginteger biginteger valueof shiftleft shiftright intdigits tostring intdigits biginteger dtobasestr_buffer_size dbits doubletolongbits dbits dbits js_assert exp_shift1 exp_mask exp_shift1 nextdouble js_assert biginteger biginteger valueof biginteger bndry_mask exp_mask exp_mask biginteger valueof shiftleft biginteger biginteger valueof shiftleft prevdouble nextdouble biginteger bigbase biginteger valueof bigbase biginteger divresult divideandremainder divresult divresult intvalue bigbase bigbase bigbase compareto biginteger compareto shiftleft compareto js_assert stringbuffer stringbuffer intdigits intdigits tostring static int word0 double d long d bits double double to long bits d return int d bits 32 dbits doubletolongbits dbits static double set word0 double d int i long d bits double double to long bits d d bits long i 32 d bits 0x0ffffffffl return double long bits to double d bits setword0 dbits doubletolongbits dbits dbits longbitstodouble dbits static int word1 double d long d bits double double to long bits d return int d bits dbits doubletolongbits dbits return b 5 k k must be nonnegative xxxx the c version built a cache of these static big integer pow5mult big integer b int k return b multiply big integer value of 5 pow k biginteger biginteger biginteger valueof static boolean round off string buffer buf int i buf length while i 0 i char c buf char at i if c 9 buf set char at i char c 1 buf set length i 1 return false buf set length 0 return true roundoff stringbuffer charat setcharat setlength setlength bufsize should be two greater than the maximum number of output characters expected static int js dtoa double d int mode boolean bias up int ndigits boolean sign string buffer buf arguments ndigits decpt sign are similar to those of ecvt and fcvt trailing zeros are suppressed from the returned string if not null rve is set to point to the end of the return value if d is infinity or nan then decpt is set to 9999 mode 0 shortest string that yields d when read in and rounded to nearest 1 like 0 but with steele white stopping rule e g with ieee p754 arithmetic mode 0 gives 1e23 whereas mode 1 gives 9 999999999999999e22 2 max 1 ndigits significant digits this gives a return value similar to that of ecvt except that trailing zeros are suppressed 3 through ndigits past the decimal point this gives a return value similar to that from fcvt except that trailing zeros are suppressed and ndigits can be negative 4 9 should give the same return values as 2 3 i e 4 mode 9 same return as mode 2 mode 1 these modes are mainly for debugging often they run slower but sometimes faster than modes 2 3 4 5 8 9 left to right digit generation 6 9 don t try fast floating point estimate if applicable values of mode other than 0 9 are treated as mode 0 sufficient space is allocated to the return value to hold the suppressed trailing zeros int b2 b5 i ieps ilim ilim0 ilim1 j j1 k k0 m2 m5 s2 s5 char dig long l long x big integer b b1 delta mlo mhi s int be new int 1 int bbits new int 1 double d2 ds eps boolean spec case denorm k check try quick leftright if word0 d sign bit 0 set sign for everything including 0 s and na ns sign 0 true word0 d sign bit clear sign bit d set word0 d word0 d sign bit else sign 0 false if word0 d exp mask exp mask infinity or nan buf append word1 d 0 word0 d frac mask 0 infinity nan return 9999 if d 0 no digits buf set length 0 buf append 0 copy 0 to buffer return 1 b d2b d be bbits if i int word0 d exp shift1 exp mask exp shift1 0 d2 set word0 d word0 d frac mask1 exp 11 log x log 1 5 x 1 5 1 5 log10 x log x log 10 log 1 5 log 10 x 1 5 1 5 log 10 log10 d i bias log 2 log 10 log10 d2 this suggests computing an approximation k to log10 d by k i bias 0 301029995663981 d2 1 5 0 289529654602168 0 176091259055681 we want k to be too large rather than too small the error in the first order taylor series approximation is in our favor so we just round up the constant enough to compensate for any error in the multiplication of i bias by 0 301029995663981 since i bias 1077 and 1077 0 30103 2 52 7 2e 14 adding 1e 13 to the constant term more than suffices hence we adjust the constant term to 0 1760912590558 we could get a more accurate k by invoking log10 but this is probably not worthwhile i bias denorm false else d is denormalized i bbits 0 be 0 bias p 1 1 x i 32 word0 d 64 i word1 d i 32 word1 d 32 i d2 x word0 d2 31 exp msk1 adjust exponent d2 set word0 x word0 x 31 exp msk1 i bias p 1 1 1 denorm true at this point d f 2 i where 1 f 2 d2 is an approximation of f ds d2 1 5 0 289529654602168 0 1760912590558 i 0 301029995663981 k int ds if ds 0 0 ds k k want k floor ds k check true if k 0 k ten pmax if d tens k k k check false at this point floor log10 d k floor log10 d 1 if k check is zero we re guaranteed that k floor log10 d j bbits 0 i 1 at this point d b 2 j where b is an odd integer if j 0 b2 0 s2 j else b2 j s2 0 if k 0 b5 0 s5 k s2 k else b2 k b5 k s5 0 at this point d 10 k b 2 b2 5 b5 2 s2 5 s5 where b is an odd integer b2 0 b5 0 s2 0 and s5 0 if mode 0 mode 9 mode 0 try quick true if mode 5 mode 4 try quick false leftright true ilim ilim1 0 switch mode case 0 case 1 ilim ilim1 1 i 18 ndigits 0 break case 2 leftright false no break case 4 if ndigits 0 ndigits 1 ilim ilim1 i ndigits break case 3 leftright false no break case 5 i ndigits k 1 ilim i ilim1 i 1 if i 0 i 1 ilim is the maximum number of significant digits we want based on k and ndigits ilim1 is the maximum number of significant digits we want based on k and ndigits when it turns out that k was computed too high by one boolean fast failed false if ilim 0 ilim quick max try quick try to get by with floating point arithmetic i 0 d2 d k0 k ilim0 ilim ieps 2 conservative divide d by 10 k keeping track of the roundoff error and avoiding overflows if k 0 ds tens k 0xf j k 4 if j bletch 0 prevent overflows j bletch 1 d bigtens n bigtens 1 ieps for j 0 j 1 i if j 1 0 ieps ds bigtens i d ds else if j1 k 0 d tens j1 0xf for j j1 4 j 0 j 1 i if j 1 0 ieps d bigtens i check that k was computed correctly if k check d 1 0 ilim 0 if ilim1 0 fast failed true else ilim ilim1 k d 10 ieps eps bounds the cumulative error eps ieps d 7 0 word0 eps p 1 exp msk1 eps ieps d 7 0 eps set word0 eps word0 eps p 1 exp msk1 if ilim 0 s mhi null d 5 0 if d eps buf append 1 k return k 1 if d eps buf set length 0 buf append 0 copy 0 to buffer return 1 fast failed true if fast failed fast failed true if leftright use steele white method of only generating digits needed eps 0 5 tens ilim 1 eps for i 0 l long d d l buf append char 0 l if d eps return k 1 if 1 0 d eps goto bump up char last ch while true last ch buf char at buf length 1 js_dtoa biasup stringbuffer biginteger spec_case k_check try_quick sign_bit nans sign_bit setword0 sign_bit exp_mask exp_mask frac_mask no_digits setlength exp_shift1 exp_mask exp_shift1 setword0 frac_mask1 exp_11 exp_msk1 setword0 exp_msk1 k_check ten_pmax k_check k_check try_quick try_quick fast_failed quick_max try_quick n_bigtens k_check fast_failed exp_msk1 setword0 exp_msk1 setlength fast_failed fast_failed fast_failed bump_up lastch lastch charat private static void strip trailing zeroes string buffer buf while s 0 s int bl buf length while bl 0 buf char at bl 0 buf set length bl 1 striptrailingzeroes stringbuffer charat setlength static void js dtostr string buffer buffer int mode int precision double d int dec pt position of decimal point relative to first digit returned by js dtoa boolean sign new boolean 1 true if the sign bit was set in d int n digits number of significand digits returned by js dtoa js assert buffer size size t mode dtostr standard exponential dtostr standard buffer size dtostr variable buffer size precision if mode dtostr fixed d 1e21 d 1e21 mode dtostr standard change mode here rather than below because the buffer may not be large enough to hold a large integer dec pt js dtoa d dtoa modes mode mode dtostr fixed precision sign buffer n digits buffer length if infinity infinity or nan return the string regardless of the mode if dec pt 9999 boolean exponential notation false int minn digits 0 minimum number of significand digits required by mode and precision int p int q switch mode case dtostr standard if dec pt 5 dec pt 21 exponential notation true else minn digits dec pt break case dtostr fixed if precision 0 minn digits dec pt precision else minn digits dec pt break case dtostr exponential js assert precision 0 minn digits precision fall through case dtostr standard exponential exponential notation true break case dtostr precision js assert precision 0 minn digits precision if dec pt 5 dec pt precision exponential notation true break if the number has fewer than minn digits pad it with zeros at the end if n digits minn digits p minn digits n digits minn digits do buffer append 0 while buffer length p if exponential notation insert a decimal point if more than one significand digit if n digits 1 buffer insert 1 buffer append e if dec pt 1 0 buffer append buffer append dec pt 1 js snprintf num end buffer size num end buffer e d dec pt 1 else if dec pt n digits some kind of a fraction in fixed notation js assert dec pt n digits if dec pt 0 dd dd dd dd buffer insert dec pt else 0 00 00dd dd for int i 0 i 1 dec pt i buffer insert 0 0 buffer insert 1 if negative and neither 0 0 nor nan output a leading if sign 0 word0 d sign bit word1 d 0 word0 d exp mask exp mask word1 d 0 word0 d frac mask 0 buffer insert 0 js_dtostr stringbuffer decpt js_dtoa ndigits js_dtoa js_assert buffersize size_t dtostr_standard_exponential dtostr_standard_buffer_size dtostr_variable_buffer_size dtostr_fixed dtostr_standard decpt js_dtoa dtoamodes dtostr_fixed ndigits decpt exponentialnotation minndigits dtostr_standard decpt decpt exponentialnotation minndigits decpt dtostr_fixed minndigits decpt minndigits decpt dtostr_exponential js_assert minndigits dtostr_standard_exponential exponentialnotation dtostr_precision js_assert minndigits decpt decpt exponentialnotation minndigits ndigits minndigits minndigits ndigits minndigits exponentialnotation ndigits decpt decpt js_snprintf numend buffersize numend decpt decpt ndigits js_assert decpt ndigits decpt decpt decpt sign_bit exp_mask exp_mask frac_mask public id function object id function call idcall object tag int id int arity if arity 0 throw new illegal argument exception this idcall idcall this tag tag this method id id this arity arity if arity 0 throw new illegal argument exception idfunctionobject idfunctioncall illegalargumentexception methodid illegalargumentexception public id function object id function call idcall object tag int id string name int arity scriptable scope super scope null if arity 0 throw new illegal argument exception if name null throw new illegal argument exception this idcall idcall this tag tag this method id id this arity arity this function name name idfunctionobject idfunctioncall illegalargumentexception illegalargumentexception methodid functionname public void init function string name scriptable scope if name null throw new illegal argument exception if scope null throw new illegal argument exception this function name name set parent scope scope initfunction illegalargumentexception illegalargumentexception functionname setparentscope public final boolean has tag object tag return this tag tag hastag public final int method id return method id methodid methodid public final void mark as constructor scriptable prototype property use call as constructor true set immune prototype property prototype property markasconstructor prototypeproperty usecallasconstructor setimmuneprototypeproperty prototypeproperty public final void add as property scriptable target scriptable object define property target function name this scriptable object dontenum addasproperty scriptableobject defineproperty functionname scriptableobject public void export as scope property add as property get parent scope exportasscopeproperty addasproperty getparentscope public scriptable get prototype lazy initialization of prototype for native functions this may not be called at all scriptable proto super get prototype if proto null proto get function prototype get parent scope set prototype proto return proto getprototype getprototype getfunctionprototype getparentscope setprototype public object call context cx scriptable scope scriptable this obj object args return idcall exec id call this cx scope this obj args thisobj execidcall thisobj public scriptable create object context cx scriptable scope if use call as constructor return null throw error if not explicitly coded to be used as constructor to satisfy ecma script standard see bugzilla 202019 to follow current 2003 05 01 spider monkey behavior change it to return super create object cx scope throw script runtime type error1 msg not ctor function name createobject usecallasconstructor ecmascript spidermonkey createobject scriptruntime typeerror1 functionname string decompile int indent int flags string buffer sb new string buffer boolean justbody 0 flags decompiler only body flag if justbody sb append function sb append get function name sb append sb append native code for if idcall instanceof scriptable scriptable sobj scriptable idcall sb append sobj get class name sb append sb append get function name sb append arity sb append get arity sb append justbody n n return sb to string stringbuffer stringbuffer only_body_flag getfunctionname getclassname getfunctionname getarity tostring public int get arity return arity getarity public int get length return get arity getlength getarity public int get length return get arity public string get function name return function name null function name getlength getarity getfunctionname functionname functionname public final runtime exception unknown it is program error to call id like methods for unknown function return new illegal argument exception bad function id method id master idcall runtimeexception illegalargumentexception methodid static void init scriptable scope boolean sealed native object obj new native object obj export asjs class max prototype id scope sealed nativeobject nativeobject exportasjsclass max_prototype_id public string get class name return object getclassname public string to string return script runtime default object to string this tostring scriptruntime defaultobjecttostring 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 tolocalestring arity 0 s to locale string break case id valueof arity 0 s value of break case id hasownproperty arity 1 s has own property break case id propertyisenumerable arity 1 s property is enumerable break case id isprototypeof arity 1 s is prototype of break case id tosource arity 0 s to source break default throw new illegal argument exception string value of id init prototype method object tag id s arity initprototypeid id_constructor id_tostring tostring id_tolocalestring tolocalestring id_valueof valueof id_hasownproperty hasownproperty id_propertyisenumerable propertyisenumerable id_isprototypeof isprototypeof id_tosource tosource illegalargumentexception valueof initprototypemethod object_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag object tag return super exec id call f cx scope this obj args int id f method id switch id case id constructor if this obj null base function construct will set up parent proto return f construct cx scope args if args length 0 args 0 null args 0 undefined instance return new native object return script runtime to object cx scope args 0 case id tolocalestring for now just alias to string case id tostring if cx has feature context feature to string as source string s script runtime default object to source cx scope this obj args int l s length if l 0 s char at 0 s char at l 1 strip that surrounds to source s s substring 1 l 1 return s return script runtime default object to string this obj case id valueof return this obj case id hasownproperty boolean result if args length 0 result false else string s script runtime to string id or index cx args 0 if s null int index script runtime last index result cx result this obj has index this obj else result this obj has s this obj return script runtime wrap boolean result case id propertyisenumerable boolean result if args length 0 result false else string s script runtime to string id or index cx args 0 if s null int index script runtime last index result cx result this obj has index this obj if result this obj instanceof scriptable object scriptable object so scriptable object this obj int attrs so get attributes index result attrs scriptable object dontenum 0 else result this obj has s this obj if result this obj instanceof scriptable object scriptable object so scriptable object this obj int attrs so get attributes s result attrs scriptable object dontenum 0 return script runtime wrap boolean result case id isprototypeof boolean result false if args length 0 args 0 instanceof scriptable scriptable v scriptable args 0 do v v get prototype if v this obj result true break while v null return script runtime wrap boolean result case id tosource return script runtime default object to source cx scope this obj args default throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag object_tag execidcall thisobj methodid id_constructor thisobj basefunction nativeobject scriptruntime toobject id_tolocalestring tostring id_tostring hasfeature feature_to_string_as_source scriptruntime defaultobjecttosource thisobj charat charat tosource scriptruntime defaultobjecttostring thisobj id_valueof thisobj id_hasownproperty scriptruntime tostringidorindex scriptruntime lastindexresult thisobj thisobj thisobj thisobj scriptruntime wrapboolean id_propertyisenumerable scriptruntime tostringidorindex scriptruntime lastindexresult thisobj thisobj thisobj scriptableobject scriptableobject scriptableobject thisobj getattributes scriptableobject thisobj thisobj thisobj scriptableobject scriptableobject scriptableobject thisobj getattributes scriptableobject scriptruntime wrapboolean id_isprototypeof getprototype thisobj scriptruntime wrapboolean id_tosource scriptruntime defaultobjecttosource thisobj illegalargumentexception valueof protected int find prototype id string s int id generated last update 2003 11 11 01 51 40 cet l0 id 0 string x null int c l switch s length case 7 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 x constructor id id constructor break l case 13 x is prototype of id id isprototypeof break l case 14 c s char at 0 if c h x has own property id id hasownproperty else if c t x to locale string id id tolocalestring break l case 20 x property is enumerable id id propertyisenumerable break l if x null x s x equals s id 0 generated return id findprototypeid valueof id_valueof charat tosource id_tosource tostring id_tostring id_constructor isprototypeof id_isprototypeof charat hasownproperty id_hasownproperty tolocalestring id_tolocalestring propertyisenumerable id_propertyisenumerable 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 native java top package class loader loader super true loader nativejavatoppackage classloader public object call context cx scriptable scope scriptable this obj object args return construct cx scope args thisobj public scriptable construct context cx scriptable scope object args class loader loader null if args length 0 object arg args 0 if arg instanceof wrapper arg wrapper arg unwrap if arg instanceof class loader loader class loader arg if loader null context report runtime error0 msg not classloader return null return new native java package true loader classloader classloader classloader reportruntimeerror0 nativejavapackage public static void init context cx scriptable scope boolean sealed class loader loader cx get application class loader final native java top package top new native java top package loader top set prototype get object prototype scope top set parent scope scope string names kit semicolon split common packages for int i 0 i names length i top force package names i scope get class implementation id function object get class new id function object top ftag id getclass get class 1 scope we want to get a real alias and not a distinct java package with the same package name so that we share classes and top that are underneath native java package java alias native java package top get java top it s safe to downcast here since init standard objects takes a scriptable object scriptable object global scriptable object scope if sealed get class seal object get class export as scope property global define property packages top scriptable object dontenum global define property java java alias scriptable object dontenum classloader getapplicationclassloader nativejavatoppackage nativejavatoppackage setprototype getobjectprototype setparentscope semicolonsplit commonpackages forcepackage getclass idfunctionobject getclass idfunctionobject id_getclass getclass javapackage packagename nativejavapackage javaalias nativejavapackage initstandardobjects scriptableobject scriptableobject scriptableobject getclass sealobject getclass exportasscopeproperty defineproperty scriptableobject defineproperty javaalias scriptableobject 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 getclass return js getclass cx scope args throw f unknown execidcall idfunctionobject thisobj hastag methodid id_getclass js_getclass private scriptable js getclass context cx scriptable scope object args if args length 0 args 0 instanceof wrapper scriptable result this class cl wrapper args 0 unwrap get class evaluate the class name by getting successive properties of the string to find the appropriate native java class object string name cl get name int offset 0 for int index name index of offset string prop name index 1 name substring offset name substring offset index object prop result get prop name result if prop instanceof scriptable break fall through to error result scriptable prop if index 1 return result offset index 1 throw context report runtime error0 msg not java obj js_getclass getclass nativejavaclass getname indexof propname propname reportruntimeerror0 public abstract class xml object extends id scriptable object public xml object xmlobject idscriptableobject xmlobject public xml object scriptable scope scriptable prototype super scope prototype xmlobject implementation of ecma script has public abstract boolean ecma has context cx object id ecmascript ecmahas public abstract boolean ecma has context cx object id implementation of ecma script get public abstract object ecma get context cx object id ecmahas ecmascript ecmaget public abstract object ecma get context cx object id implementation of ecma script put public abstract void ecma put context cx object id object value ecmaget ecmascript ecmaput public abstract void ecma put context cx object id object value implementation of ecma script delete public abstract boolean ecma delete context cx object id ecmaput ecmascript ecmadelete return an additional object to look for methods that runtime should consider during method search return null if no such object available generic reference to implement x y x y etc public abstract ref member ref context cx object elem memberref generic reference to implement x ns x ns y x ns y etc public abstract ref member ref context cx object namespace object elem memberref int member type flags wrap this object into native with to implement the with statement public abstract native with enter with scriptable scope membertypeflags nativewith nativewith enterwith public abstract native with enter with scriptable scope wrap this object into native with to implement the query public abstract native with enter dot query scriptable scope nativewith enterwith nativewith nativewith enterdotquery custom tt tt operator should return link scriptable not found if this object does not have custom addition operator for the given value or the result of the addition operation p the default implementation returns link scriptable not found to indicate no custom addition operation param cx the context object associated with the current thread param this is left if true the object should calculate this value if false the object should calculate value this param value the second argument for addition operation public object add values context cx boolean this is left object value return scriptable not found not_found not_found thisisleft addvalues thisisleft not_found public class datatypes 010 extends live connect test public datatypes 010 super datatypes_010 liveconnecttest datatypes_010 public static void main string args datatypes 010 test new datatypes 010 test start datatypes_010 datatypes_010 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 double array true do array test dt pub static array double true do array test dt get double array true do array test dt pub array double false executetest doarraytest staticgetdoublearray doarraytest pub_static_array_double doarraytest getdoublearray doarraytest pub_array_double 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 double array data type class pub static array double double 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 double 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 var 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_double jsarray jsarray_length javascript jsarray jsarray jsarray getmember jsarray javascript jsarray_length jsarray intvalue jsarray javascript jsarray_length jsarray addtestcase jsarray jsarray jsarray printstacktrace tostring jsarray_length jsarray jsarray addtestcase jsarray jsarray getmember jsarray jsarray shouldequal jsarray opt function node function node fnode this fnode fnode fnode set compiler data this optfunctionnode functionnode setcompilerdata static opt function node get script or fn node script or fn int i function node fnode script or fn get function node i return opt function node fnode get compiler data optfunctionnode scriptorfnnode scriptorfn functionnode scriptorfn getfunctionnode optfunctionnode getcompilerdata static opt function node get script or fn node script or fn return opt function node script or fn get compiler data optfunctionnode scriptorfnnode scriptorfn optfunctionnode scriptorfn getcompilerdata boolean is target of direct call return direct target index 0 istargetofdirectcall directtargetindex int get direct target index return direct target index getdirecttargetindex directtargetindex void set direct target index int direct target index one time action if direct target index 0 this direct target index 0 kit code bug this direct target index direct target index setdirecttargetindex directtargetindex directtargetindex directtargetindex codebug directtargetindex directtargetindex void set parameter number context boolean b its parameter number context b setparameternumbercontext itsparameternumbercontext boolean get parameter number context return its parameter number context getparameternumbercontext itsparameternumbercontext int get var count return fnode get param and var count getvarcount getparamandvarcount boolean is parameter int var index return var index fnode get param count isparameter varindex varindex getparamcount boolean is number var int var index var index fnode get param count if var index 0 number var flags null return number var flags var index return false isnumbervar varindex varindex getparamcount varindex numbervarflags numbervarflags varindex void set is number var int var index var index fnode get param count can only be used with non parameters if var index 0 kit code bug if number var flags null int size fnode get param and var count fnode get param count number var flags new boolean size number var flags var index true setisnumbervar varindex varindex getparamcount varindex codebug numbervarflags getparamandvarcount getparamcount numbervarflags numbervarflags varindex int get var index node n int index n get int prop node variable prop 1 if index 1 string name int type n get type if type token getvar name n get string else if type token setvar name n get first child get string else throw kit code bug index fnode get param or var index name if index 0 throw kit code bug n put int prop node variable prop index return index getvarindex getintprop variable_prop gettype getstring getfirstchild getstring codebug getparamorvarindex codebug putintprop variable_prop create a new test suite object param name name of the test suite param file path full path to test suite directory public test suite string name string file path this name name this file path file path this passed true this total cases 0 this cases passed 0 this cases failed 0 testsuite testsuite filepath testsuite testsuite filepath filepath filepath totalcases casespassed casesfailed public int float 512 public int ambiguous float arg return float public int ambiguous double arg return double implement call shrinking optimizer code public static object call0 callable fun scriptable this obj context cx scriptable scope return fun call cx scope this obj script runtime empty args thisobj thisobj scriptruntime emptyargs implement arg call shrinking optimizer code public static object call1 callable fun scriptable this obj object arg0 context cx scriptable scope return fun call cx scope this obj new object arg0 thisobj thisobj implement arg0 arg1 call shrinking optimizer code public static object call2 callable fun scriptable this obj object arg0 object arg1 context cx scriptable scope return fun call cx scope this obj new object arg0 arg1 thisobj thisobj implement arg0 arg1 call shrinking optimizer code public static object calln callable fun scriptable this obj object args context cx scriptable scope return fun call cx scope this obj args thisobj thisobj implement name args call shrinking optimizer code public static object call name object args string name context cx scriptable scope callable f get name function and this name cx scope scriptable this obj last stored scriptable cx return f call cx scope this obj args callname getnamefunctionandthis thisobj laststoredscriptable thisobj implement name call shrinking optimizer code public static object call name0 string name context cx scriptable scope callable f get name function and this name cx scope scriptable this obj last stored scriptable cx return f call cx scope this obj script runtime empty args callname0 getnamefunctionandthis thisobj laststoredscriptable thisobj scriptruntime emptyargs implement x property call shrinking optimizer code public static object call prop0 object value string property context cx scriptable scope callable f get prop function and this value property cx scriptable this obj last stored scriptable cx return f call cx scope this obj script runtime empty args callprop0 getpropfunctionandthis thisobj laststoredscriptable thisobj scriptruntime emptyargs public static object add object val1 double val2 if val1 instanceof scriptable val1 scriptable val1 get default value null if val1 instanceof string return wrap double to number val1 val2 return string val1 concat to string val2 getdefaultvalue wrapdouble tonumber tostring public static object add double val1 object val2 if val2 instanceof scriptable val2 scriptable val2 get default value null if val2 instanceof string return wrap double to number val2 val1 return to string val1 concat string val2 getdefaultvalue wrapdouble tonumber tostring public static object pad start object current args int count object result new object current args length count system arraycopy current args 0 result count current args length return result padstart currentargs currentargs currentargs currentargs public static void init function native function fn int function type scriptable scope context cx script runtime init function cx scope fn function type false initfunction nativefunction functiontype scriptruntime initfunction functiontype public static object call special context cx callable fun scriptable this obj object args scriptable scope scriptable caller this int call type string file name int line number return script runtime call special cx fun this obj args scope caller this call type file name line number callspecial thisobj callerthis calltype filename linenumber scriptruntime callspecial thisobj callerthis calltype filename linenumber public static object new object special context cx object fun object args scriptable scope scriptable caller this int call type return script runtime new special cx fun args scope call type newobjectspecial callerthis calltype scriptruntime newspecial calltype public static double wrap double double num if num 0 0 if 1 num 0 0 0 return zero obj else if num 1 0 return one obj else if num 1 0 return minus one obj else if num num return na nobj return new double num wrapdouble zeroobj oneobj minusoneobj nanobj static string encode int array int array xxx this extremely inefficient for small integers if array null return null int n array length char buffer new char 1 n 2 buffer 0 1 for int i 0 i n i int value array i int shift 1 i 2 buffer shift char value 16 buffer shift 1 char value return new string buffer encodeintarray private static int decode int array string str int array size xxx this extremely inefficient for small integers if array size 0 if str null throw new illegal argument exception return null if str length 1 array size 2 str char at 0 1 throw new illegal argument exception int array new int array size for int i 0 i array size i int shift 1 i 2 array i str char at shift 16 str char at shift 1 return array decodeintarray arraysize arraysize illegalargumentexception arraysize charat illegalargumentexception arraysize arraysize charat charat public static scriptable new array literal object objects string encoded ints int skip count context cx scriptable scope int skip indexces decode int array encoded ints skip count return new array literal objects skip indexces cx scope newarrayliteral encodedints skipcount skipindexces decodeintarray encodedints skipcount newarrayliteral skipindexces public static void main final script script final string args context call new context action public object run context cx scriptable object global get global cx get the command line arguments and define arguments array in the top level object object args copy new object args length system arraycopy args 0 args copy 0 args length scriptable args obj cx new array global args copy global define property arguments args obj scriptable object dontenum script exec cx global return null contextaction scriptableobject getglobal argscopy argscopy argsobj newarray argscopy defineproperty argsobj scriptableobject context call new context action public object run context cx scriptable object global get global cx get the command line arguments and define arguments array in the top level object object args copy new object args length system arraycopy args 0 args copy 0 args length scriptable args obj cx new array global args copy global define property arguments args obj scriptable object dontenum script exec cx global return null contextaction scriptableobject getglobal argscopy argscopy argsobj newarray argscopy defineproperty argsobj scriptableobject public class slot 002 extends live connect test public slot 002 super slot_002 liveconnecttest slot_002 super public static void main string args slot 002 test new slot 002 test start slot_002 slot_002 public void execute test get base objects object test matrix get data array string args get array arguments test matrix js object js array createjs array args get length js array test matrix length for int i 0 i test matrix length i get slot js array i object test matrix i executetest getbaseobjects testmatrix getdataarray getarrayarguments testmatrix jsobject jsarray createjsarray getlength jsarray testmatrix testmatrix getslot jsarray testmatrix public string get array arguments object matrix string buffer buffer new string buffer for int i 0 i matrix length i buffer append object matrix i 0 if i matrix length 1 buffer append return buffer to string getarrayarguments stringbuffer stringbuffer tostring get the constructor of all the base java script objects the test will compare the instance constructor to the base object constructor to verify that the java script type of the object is corret public boolean get base objects try js number js object global eval number prototype constructor js string js object global eval string prototype constructor js function js object global eval function prototype constructor js boolean js object global eval boolean prototype constructor js object js object global eval object prototype constructor js math js object global eval math js date js object global eval date prototype constructor js array js object global eval array prototype constructor js reg exp js object global eval reg exp prototype constructor catch exception e system err println failed in get base objects e to string e print stack trace return false return true javascript javascript getbaseobjects jsnumber jsobject jsstring jsobject jsfunction jsobject jsboolean jsobject jsobject jsobject jsmath jsobject jsdate jsobject jsarray jsobject jsregexp jsobject regexp getbaseobjects tostring printstacktrace get the data array which is an array of arrays each of the internal arrays consists of three objects a string whose value will be passed to the java script array constructor a string which is the expected string value of retreiving the js object via get slot and a js object which is the js object s constructor that allows us to verify the type of js object return the data array public object get data array object item0 new string new string java script string new string java script string js string object item1 new string new number 12345 new string 12345 js number object item2 new string new boolean false new string false js boolean object item3 new string new array 0 1 2 3 4 new string 0 1 2 3 4 js array object item4 new string new object new string object object js object object data array item0 item1 item2 item3 item4 return data array javascript jsobject getslot jsobject jsobject jsobject getdataarray javascript javascript jsstring jsnumber jsboolean jsarray jsobject dataarray dataarray 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 in this test the expected class of all objects is js object param js array 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 array int slot object data string exception js object constructor null js object result null class e class null class a class null try result js object js array get slot slot if result null e class class for name netscape javascript js object a class result get class constructor js object result get member constructor catch exception e exception js array get slot slot threw e to string file exception exception e print stack trace finally if result null add test case js array get slot slot to string trim returned result data 1 equals result true data 1 to string trim equals result to string exception else check the string value of the result add test case js array get slot slot returned result data 1 to string equals result true data 1 equals result exception check the class of the result all should be js objects add test case e class equals a class true e class equals a class exception constructor of the result add test case constructor equals data 2 true constructor equals data 2 exception jsobject getslot jsobject jsobject jsarray jsobject jsarray getslot jsobjectconstructor getslot jsobject jsarray jsobject jsobject eclass aclass jsobject jsarray getslot eclass forname jsobject aclass getclass jsobject getmember jsarray getslot tostring printstacktrace addtestcase jsarray getslot tostring tostring tostring addtestcase jsarray getslot tostring jsobjects addtestcase eclass aclass eclass aclass addtestcase opt transformer hashtable possible direct calls obj array direct call targets this possible direct calls possible direct calls this direct call targets direct call targets opttransformer possibledirectcalls objarray directcalltargets possibledirectcalls possibledirectcalls directcalltargets directcalltargets protected void visit new node node script or fn node tree detect direct call node tree super visit new node tree visitnew scriptorfnnode detectdirectcall visitnew protected void visit call node node script or fn node tree detect direct call node tree super visit call node tree visitcall scriptorfnnode detectdirectcall visitcall private void detect direct call node node script or fn node tree if tree get type token function node left node get first child count the arguments int arg count 0 node arg left get next while arg null arg arg get next arg count if arg count 0 opt function node get tree its contains calls0 true optimize a call site by converting call a b c into function object for a instance variable init d by constructor this is a directcall node fn get prop tmp get base a a if fn function object for a fn call tmp b c else script runtime call fn tmp b c if possible direct calls null string target name null if left get type token name target name left get string else if left get type token getprop target name left get first child get next get string if target name null opt function node ofn ofn opt function node possible direct calls get target name if ofn null arg count ofn fnode get param count ofn fnode requires activation refuse to direct call any function with more than 32 parameters prevent code explosion for wacky test cases if arg count 32 node put prop node directcall prop ofn if ofn is target of direct call int index direct call targets size direct call targets add ofn ofn set direct target index index detectdirectcall scriptorfnnode gettype getfirstchild argcount getnext getnext argcount argcount optfunctionnode itscontainscalls0 functionobjectfor getprop getbase functionobjectfor scriptruntime possibledirectcalls targetname gettype targetname getstring gettype targetname getfirstchild getnext getstring targetname optfunctionnode optfunctionnode possibledirectcalls targetname argcount getparamcount requiresactivation directcall argcount putprop directcall_prop istargetofdirectcall directcalltargets directcalltargets setdirecttargetindex create a new mac ref env public mac ref env test file f test suite s ref drv d this file f this suite s this driver d macrefenv macrefenv testfile testsuite refdrv this implementation does nothing since creating the js shell automatically runs the test on the mac public object execute test file return null executetestfile instantiate a new java script shell which has been built with mac test hack defined public object create context try look for a file called flagfile flg file flag new file flagfile flg if flag exists flag delete task runtime get runtime exec driver executable wait a maximum of five minutes int i 0 while flag exists i 60 thread current thread sleep 5000 catch io exception x system out println io exception in runjs x catch interrupted exception x system out println interrupted exception in runjs x return null javascript mac_test_hack createcontext getruntime currentthread ioexception ioexception interruptedexception interruptedexception public boolean setup mac files boolean result1 get directory name delete results file boolean result3 create testargs file boolean result4 write testargs file if result1 result3 result4 return true else return false setupmacfiles getdirectoryname deleteresultsfile createtestargsfile writetestargsfile public synchronized void run test try if setup mac files file start time driver get current time create context 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 setupmacfiles starttime getcurrenttime createcontext endtime getcurrenttime getexitvalue endswith parseresult endswith geterror geterror getexitvalue nthrew public boolean parse result string line int i j results new file results txt if results exists return false spit out all the lines we find in the result file try file reader fr new file reader results line number reader lnr new line number reader fr do line lnr read line driver p line if line null driver p terror no lines to read return false while line equals size tag if line lnr read line null return false file total cases integer value of line int value if line lnr read line null driver p terror no lines after size tag 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 lnr 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 try lnr close fr close catch io exception x system out println io exception in runjs x return false catch number format exception nfe system out println terror no integer after size tag return false catch io exception e system out println exception reading process output e to string file exception e to string return false return true parseresult filereader filereader linenumberreader linenumberreader readline sizetag readline totalcases valueof intvalue readline sizetag totalcases startswith readline startswith starttag totalcases totalcases ioexception tostring testcase testcase casevector addelement endswith ioexception ioexception numberformatexception sizetag ioexception tostring tostring get the executable s directory which is where we will write testargs txt and from where we will get results txt public boolean get directory name directory name return true getdirectoryname directoryname check to see whether testargs txt exists if so delete it public boolean create testargs file string testargsname testargs txt file testargsfile new file testargsname if testargsfile exists testargsfile delete testargs new test log testargs txt return true createtestargsfile testlog public boolean delete results file string resultsname results txt file resultsfile new file resultsname if resultsfile exists resultsfile delete return true deleteresultsfile write testargs txt to the directory where the executable is public boolean write testargs file string helper get mac file string driver helper string string testfile get mac file string file file path testargs write line f testargs write line helper testargs write line f testargs write line testfile testargs close log return true writetestargsfile getmacfilestring helper_string getmacfilestring filepath writeline writeline writeline writeline closelog public void close return replace slashes in a string with colons public string get mac file string string path string buffer buffer new string buffer int i for i 0 i path length i if path char at i buffer append else buffer append path char at i return buffer to string getmacfilestring stringbuffer stringbuffer charat charat tostring int pretty indent scriptable global scope return global scope prettyindent globalscope globalscope private xml lib impl scriptable global scope this global scope global scope default settings xmllibimpl globalscope globalscope globalscope defaultsettings public static void init context cx scriptable scope boolean sealed to force linkage error if xml object is not available xml object class get name xml lib impl lib new xml lib impl scope xml lib bound lib bind to scope scope if bound lib lib export to scope sealed linkageerror xmlobject xmlobject getname xmllibimpl xmllibimpl xmllib bindtoscope exporttoscope private void export to scope boolean sealed xml prototype xml create emptyxml this xml list prototype new xml list this namespace prototype new namespace this qname prototype new q name this xml prototype export asjs class sealed xml list prototype export asjs class sealed namespace prototype export asjs class sealed qname prototype export asjs class sealed exporttoscope xmlprototype createemptyxml xmllistprototype xmllist namespaceprototype qnameprototype qname xmlprototype exportasjsclass xmllistprototype exportasjsclass namespaceprototype exportasjsclass qnameprototype exportasjsclass void default settings ignore comments true ignore processing instructions true ignore whitespace true pretty printing true pretty indent 2 defaultsettings ignorecomments ignoreprocessinginstructions ignorewhitespace prettyprinting prettyindent xml name to attribute name context cx object name value string uri string local name if name value instanceof string uri local name string name value else if name value instanceof xml name xml name xml name xml name name value if xml name is attribute name xml name set attribute name return xml name else if name value instanceof q name q name qname q name name value uri qname uri local name qname local name else if name value instanceof boolean name value instanceof number name value undefined instance name value null throw badxml name name value else uri local name script runtime to string name value xml name xml name xml name form property uri local name xml name set attribute name return xml name xmlname toattributename namevalue localname namevalue localname namevalue namevalue xmlname xmlname xmlname xmlname namevalue xmlname isattributename xmlname setattributename xmlname namevalue qname qname qname namevalue localname localname namevalue namevalue namevalue namevalue badxmlname namevalue localname scriptruntime tostring namevalue xmlname xmlname xmlname formproperty localname xmlname setattributename xmlname private static runtime exception badxml name object value string msg if value instanceof number msg can not construct xml name from number else if value instanceof boolean msg can not construct xml name from boolean else if value undefined instance value null msg can not construct xml name from else throw new illegal argument exception value to string return script runtime type error msg script runtime to string value runtimeexception badxmlname illegalargumentexception tostring scriptruntime typeerror scriptruntime tostring xml name toxml name context cx object name value xml name result if name value instanceof xml name result xml name name value else if name value instanceof q name q name qname q name name value result xml name form property qname uri qname local name else if name value instanceof string result toxml name from string cx string name value else if name value instanceof boolean name value instanceof number name value undefined instance name value null throw badxml name name value else string name script runtime to string name value result toxml name from string cx name return result xmlname toxmlname namevalue xmlname namevalue xmlname xmlname namevalue namevalue qname qname qname namevalue xmlname formproperty localname namevalue toxmlnamefromstring namevalue namevalue namevalue namevalue namevalue badxmlname namevalue scriptruntime tostring namevalue toxmlnamefromstring if value represents uint32 index make it available through script runtime last uint32 result cx and return null otherwise return the same value as toxml name cx value xml name toxml name or index context cx object value xml name result if value instanceof xml name result xml name value else if value instanceof string string str string value long test script runtime test uint32 string str if test 0 script runtime store uint32 result cx test result null else result toxml name from string cx str else if value instanceof number double d number value double value long l long d if l d 0 l l 0xffffffffl script runtime store uint32 result cx l result null else throw badxml name value else if value instanceof q name q name qname q name value string uri qname uri boolean number false result null if uri null uri length 0 only in this case qname to string can resemble uint32 long test script runtime test uint32 string uri if test 0 script runtime store uint32 result cx test number true if number result xml name form property uri qname local name else if value instanceof boolean value undefined instance value null throw badxml name value else string str script runtime to string value long test script runtime test uint32 string str if test 0 script runtime store uint32 result cx test result null else result toxml name from string cx str return result scriptruntime lastuint32result toxmlname xmlname toxmlnameorindex xmlname xmlname xmlname scriptruntime testuint32string scriptruntime storeuint32result toxmlnamefromstring doublevalue scriptruntime storeuint32result badxmlname qname qname qname tostring scriptruntime testuint32string scriptruntime storeuint32result xmlname formproperty localname badxmlname scriptruntime tostring scriptruntime testuint32string scriptruntime storeuint32result toxmlnamefromstring xml name toxml name from string context cx string name if name null throw new illegal argument exception int l name length if l 0 char first char name char at 0 if first char if l 1 return xml name form star else if first char xml name xml name xml name form property name substring 1 xml name set attribute name return xml name string uri get default namespaceuri cx return xml name form property uri name xmlname toxmlnamefromstring illegalargumentexception firstchar charat firstchar xmlname formstar firstchar xmlname xmlname xmlname formproperty xmlname setattributename xmlname getdefaultnamespaceuri xmlname formproperty namespace construct namespace context cx object uri value string prefix string uri if uri value instanceof namespace namespace ns namespace uri value prefix ns prefix uri ns uri else if uri value instanceof q name q name qname q name uri value uri qname uri if uri null prefix qname prefix else uri qname to string prefix null else uri script runtime to string uri value prefix uri length 0 null return new namespace this prefix uri constructnamespace urivalue urivalue urivalue urivalue qname qname qname urivalue tostring scriptruntime tostring urivalue namespace cast to namespace context cx object namescape obj if namescape obj instanceof namespace return namespace namescape obj return construct namespace cx namescape obj casttonamespace namescapeobj namescapeobj namescapeobj constructnamespace namescapeobj namespace construct namespace context cx return new namespace this constructnamespace public namespace construct namespace context cx object prefix value object uri value string prefix string uri if uri value instanceof q name q name qname q name uri value uri qname uri if uri null uri qname to string else uri script runtime to string uri value if uri length 0 if prefix value undefined instance prefix else prefix script runtime to string prefix value if prefix length 0 throw script runtime type error illegal prefix prefix for no namespace else if prefix value undefined instance prefix else if isxml name cx prefix value prefix else prefix script runtime to string prefix value return new namespace this prefix uri constructnamespace prefixvalue urivalue urivalue qname qname qname urivalue tostring scriptruntime tostring urivalue prefixvalue scriptruntime tostring prefixvalue scriptruntime typeerror prefixvalue isxmlname prefixvalue scriptruntime tostring prefixvalue string get default namespaceuri context cx string uri if cx null cx context get current context if cx null object ns script runtime search default namespace cx if ns null if ns instanceof namespace uri namespace ns uri else should not happen but for now it could due to bad search default namespace implementation return uri getdefaultnamespaceuri getcurrentcontext scriptruntime searchdefaultnamespace searchdefaultnamespace namespace get default namespace context cx if cx null cx context get current context if cx null return namespace prototype namespace result object ns script runtime search default namespace cx if ns null result namespace prototype else if ns instanceof namespace result namespace ns else should not happen but for now it could due to bad search default namespace implementation result namespace prototype return result getdefaultnamespace getcurrentcontext namespaceprototype scriptruntime searchdefaultnamespace namespaceprototype searchdefaultnamespace namespaceprototype q name cast toq name context cx object qname value if qname value instanceof q name return q name qname value return constructq name cx qname value qname casttoqname qnamevalue qnamevalue qname qname qnamevalue constructqname qnamevalue q name constructq name context cx object name value q name result if name value instanceof q name q name qname q name name value result new q name this qname uri qname local name qname prefix else string local name script runtime to string name value result constructq name from string cx local name return result qname constructqname namevalue qname namevalue qname qname qname namevalue qname localname localname scriptruntime tostring namevalue constructqnamefromstring localname optimized version of constructq name for string type q name constructq name from string context cx string local name if local name null throw new illegal argument exception string uri string prefix if equals local name uri null prefix null else namespace ns get default namespace cx uri ns uri prefix ns prefix return new q name this uri local name prefix constructqname qname constructqnamefromstring localname localname illegalargumentexception localname getdefaultnamespace qname localname q name constructq name context cx object namespace value object name value string uri string local name string prefix if name value instanceof q name q name qname q name name value local name qname local name else local name script runtime to string name value namespace ns if namespace value undefined instance if equals local name ns null else ns get default namespace cx else if namespace value null ns null else if namespace value instanceof namespace ns namespace namespace value else ns construct namespace cx namespace value if ns null uri null prefix null else uri ns uri prefix ns prefix return new q name this uri local name prefix qname constructqname namespacevalue namevalue localname namevalue qname qname qname namevalue localname localname localname scriptruntime tostring namevalue namespacevalue localname getdefaultnamespace namespacevalue namespacevalue namespacevalue constructnamespace namespacevalue qname localname object addxml objects context cx xml object obj1 xml object obj2 xml list list to add new xml list this if obj1 instanceof xml list xml list list1 xml list obj1 if list1 length 1 list to add add to list list1 item 0 else might be xml fragment xml fragment xml fragment then the result will be an xml list which we want to be an r value and allow it to be assigned to an lvalue list to add new xml list this obj1 else list to add add to list xml obj1 if obj2 instanceof xml list xml list list2 xml list obj2 for int i 0 i list2 length i list to add add to list list2 item i else if obj2 instanceof xml list to add add to list xml obj2 return list to add addxmlobjects xmlobject xmlobject xmllist listtoadd xmllist xmllist xmllist xmllist listtoadd addtolist xmlfragment xmlfragment xmlfragment xmllist rvalue listtoadd xmllist listtoadd addtolist xmllist xmllist xmllist listtoadd addtolist listtoadd addtolist listtoadd see e4x 13 1 2 1 public boolean isxml name context cx object name obj string name try name script runtime to string name obj catch ecma error ee if type error equals ee get name return false throw ee see http w3 org tr xml names11 nt nc name int length name length if length 0 if isnc name start char name char at 0 for int i 1 i length i if isnc name char name char at i return false return true return false isxmlname nameobj scriptruntime tostring nameobj ecmaerror typeerror getname ncname isncnamestartchar charat isncnamechar charat private static boolean isnc name start char int c if c 0x7f 0 optimize for ascii and use a z a z if c a return c z else if c a if c z return true return c else if c 0x1fff 0 return 0xc0 c c 0xd6 0xd8 c c 0xf6 0xf8 c c 0x2ff 0x370 c c 0x37d 0x37f c return 0x200c c c 0x200d 0x2070 c c 0x218f 0x2c00 c c 0x2fef 0x3001 c c 0xd7ff 0xf900 c c 0xfdcf 0xfdf0 c c 0xfffd 0x10000 c c 0xeffff isncnamestartchar _ _ private static boolean isnc name char int c if c 0x7f 0 optimize for ascii and use 0 9 a z a z if c a return c z else if c a if c z return true return c else if c 0 return c 9 else return c c else if c 0x1fff 0 return isnc name start char c c 0xb7 0x300 c c 0x36f return isnc name start char c 0x203f c c 0x2040 isncnamechar _ _ isncnamestartchar isncnamestartchar xml name to qualified name context cx object namespace value object name value this is duplication of constructq name cx namespace value name value but for xml name string uri string local name if name value instanceof q name q name qname q name name value local name qname local name else local name script runtime to string name value namespace ns if namespace value undefined instance if equals local name ns null else ns get default namespace cx else if namespace value null ns null else if namespace value instanceof namespace ns namespace namespace value else ns construct namespace cx namespace value if ns null uri null else uri ns uri return xml name form property uri local name xmlname toqualifiedname namespacevalue namevalue constructqname namespacevalue namevalue xmlname localname namevalue qname qname qname namevalue localname localname localname scriptruntime tostring namevalue namespacevalue localname getdefaultnamespace namespacevalue namespacevalue namespacevalue constructnamespace namespacevalue xmlname formproperty localname public ref name ref context cx object name scriptable scope int member type flags if member type flags node attribute flag 0 should only be called foir cases like name or expr throw kit code bug xml name xml name to attribute name cx name return xml primary reference cx xml name scope nameref membertypeflags membertypeflags attribute_flag codebug xmlname xmlname toattributename xmlprimaryreference xmlname public ref name ref context cx object namespace object name scriptable scope int member type flags xml name xml name to qualified name cx namespace name if member type flags node attribute flag 0 if xml name is attribute name xml name set attribute name return xml primary reference cx xml name scope nameref membertypeflags xmlname xmlname toqualifiedname membertypeflags attribute_flag xmlname isattributename xmlname setattributename xmlprimaryreference xmlname private ref xml primary reference context cx xml name xml name scriptable scope xml object impl xml obj xml object impl first xml object null for xml object can only present on scope chain as a wrapper of xml with scope if scope instanceof xml with scope xml obj xml object impl scope get prototype if xml obj hasxml property xml name break if first xml object null first xml object xml obj scope scope get parent scope if scope null xml obj first xml object break xml obj null corresponds to undefined as the target of the reference if xml obj null xml name initxml object xml obj return xml name xmlprimaryreference xmlname xmlname xmlobjectimpl xmlobj xmlobjectimpl firstxmlobject xmlwithscope xmlwithscope xmlobj xmlobjectimpl getprototype xmlobj hasxmlproperty xmlname firstxmlobject firstxmlobject xmlobj getparentscope xmlobj firstxmlobject xmlobj xmlobj xmlname initxmlobject xmlobj xmlname escapes the reserved characters in a value of an attribute and surround it by param value unescaped text return the escaped text public string escape attribute value object value string text script runtime to string value if text length 0 return xml object xo xml object factory new instance xml cursor cursor xo new cursor cursor to next token cursor begin element a cursor insert attribute with value a text cursor dispose string element text xo to string int begin element text index of int end element text last index of return element text substring begin end 1 escapeattributevalue scriptruntime tostring xmlobject xmlobject newinstance xmlcursor newcursor tonexttoken beginelement insertattributewithvalue elementtext tostring elementtext indexof elementtext lastindexof elementtext escapes the reserved characters in a value of a text node param value unescaped text return the escaped text public string escape text value object value if value instanceof xml object impl return xml object impl value toxml string 0 string text script runtime to string value if text length 0 return text xml object xo xml object factory new instance xml cursor cursor xo new cursor cursor to next token cursor begin element a cursor insert chars text cursor dispose string element text xo to string int begin element text index of 1 int end element text last index of return begin end element text substring begin end escapetextvalue xmlobjectimpl xmlobjectimpl toxmlstring scriptruntime tostring xmlobject xmlobject newinstance xmlcursor newcursor tonexttoken beginelement insertchars elementtext tostring elementtext indexof elementtext lastindexof elementtext public object to default xml namespace context cx object uri value return construct namespace cx uri value todefaultxmlnamespace urivalue constructnamespace urivalue creates a new main public main string title dim new dim debug gui new swing gui dim title debuggui swinggui returns the debugger window link j frame public j frame get debug frame return debug gui jframe jframe getdebugframe debuggui breaks execution of the script public void do break dim set break dobreak setbreak sets whether execution should break when a script exception is thrown public void set break on exceptions boolean value dim set break on exceptions value debug gui get menubar get break on exceptions set selected value setbreakonexceptions setbreakonexceptions debuggui getmenubar getbreakonexceptions setselected sets whether execution should break when a function is entered public void set break on enter boolean value dim set break on enter value debug gui get menubar get break on enter set selected value setbreakonenter setbreakonenter debuggui getmenubar getbreakonenter setselected sets whether execution should break when a function is left public void set break on return boolean value dim set break on return value debug gui get menubar get break on return set selected value setbreakonreturn setbreakonreturn debuggui getmenubar getbreakonreturn setselected removes all breakpoints public void clear all breakpoints dim clear all breakpoints clearallbreakpoints clearallbreakpoints resumes execution of the script public void go dim go sets the scope to be used for script evaluation public void set scope scriptable scope set scope provider i proxy new scope provider scope setscope setscopeprovider iproxy newscopeprovider sets the link scope provider that provides a scope to be used for script evaluation public void set scope provider scope provider p dim set scope provider p scopeprovider setscopeprovider scopeprovider setscopeprovider assign a runnable object that will be invoked when the user selects exit or closes the debugger main window public void set exit action runnable r debug gui set exit action r setexitaction debuggui setexitaction returns an link input stream for stdin from the debugger s internal console window public input stream get in return debug gui get console get in inputstream inputstream getin debuggui getconsole getin returns a link print stream for stdout to the debugger s internal console window public print stream get out return debug gui get console get out printstream printstream getout debuggui getconsole getout returns a link print stream for stderr in the debugger s internal console window public print stream get err return debug gui get console get err printstream printstream geterr debuggui getconsole geterr packs the debugger gui frame public void pack debug gui pack debuggui sets the debugger gui frame dimensions public void set size int w int h debug gui set size w h setsize debuggui setsize sets the visibility of the debugger gui frame public void set visible boolean flag debug gui set visible flag setvisible debuggui setvisible returns whether the debugger gui frame is visible public boolean is visible return debug gui is visible isvisible debuggui isvisible frees any resources held by the debugger public void dispose clear all breakpoints dim go debug gui dispose dim null clearallbreakpoints debuggui attaches the debugger to the given link context factory public void attach to context factory factory dim attach to factory contextfactory attachto contextfactory attachto detaches from the current link context factory public void detach dim detach contextfactory main entry point creates a debugger attached to a rhino link org mozilla tools shell main shell session public static void main string args main main new main rhino java script debugger main do break main set exit action new i proxy i proxy exit action system set in main get in system set out main get out system set err main get err global global org mozilla javascript tools shell main get global global set in main get in global set out main get out global set err main get err main attach to org mozilla javascript tools shell main shell context factory main set scope global main pack main set size 600 460 main set visible true org mozilla javascript tools shell main exec args javascript dobreak setexitaction iproxy iproxy exit_action setin getin setout getout seterr geterr getglobal setin getin setout getout seterr geterr attachto shellcontextfactory setscope setsize setvisible entry point for embedded applications this method attaches to the global link context factory with a scope of a newly created link global object no i o redirection is performed as with link main string public static void main embedded string title context factory factory context factory get global global global new global global init factory main embedded factory global title contextfactory mainembedded contextfactory contextfactory getglobal mainembedded entry point for embedded applications this method attaches to the given link context factory with the given scope no i o redirection is performed as with link main string public static void main embedded context factory factory scriptable scope string title main embedded impl factory scope title contextfactory mainembedded contextfactory mainembeddedimpl entry point for embedded applications this method attaches to the given link context factory with the given scope no i o redirection is performed as with link main string public static void main embedded context factory factory scope provider scope provider string title main embedded impl factory scope provider title contextfactory mainembedded contextfactory scopeprovider scopeprovider mainembeddedimpl scopeprovider helper method for link main embedded private static void main embedded impl context factory factory object scope provider string title if title null title rhino java script debugger embedded usage main main new main title main do break main set exit action new i proxy i proxy exit action main attach to factory if scope provider instanceof scope provider main set scope provider scope provider scope provider else scriptable scope scriptable scope provider if scope instanceof global global global global scope global set in main get in global set out main get out global set err main get err main set scope scope main pack main set size 600 460 main set visible true mainembedded mainembeddedimpl contextfactory scopeprovider javascript dobreak setexitaction iproxy iproxy exit_action attachto scopeprovider scopeprovider setscopeprovider scopeprovider scopeprovider scopeprovider setin getin setout getout seterr geterr setscope setsize setvisible deprecated use link set size int int instead public void set size java awt dimension dimension debug gui set size dimension width dimension height setsize setsize debuggui setsize deprecated the method does nothing and is only present for compatibility public void set optimization level int level setoptimizationlevel deprecated the method is only present for compatibility and should not be called public void context entered context cx throw new illegal state exception contextentered illegalstateexception deprecated the method is only present for compatibility and should not be called public void context exited context cx throw new illegal state exception contextexited illegalstateexception deprecated the method is only present for compatibility and should not be called public void context created context cx throw new illegal state exception contextcreated illegalstateexception deprecated the method is only present for compatibility and should not be called public void context released context cx throw new illegal state exception contextreleased illegalstateexception creates a new i proxy public i proxy int type this type type iproxy iproxy creates a new i proxy that acts as a link scope provider public static scope provider new scope provider scriptable scope i proxy scope provider new i proxy scope provider scope provider scope scope return scope provider iproxy scopeprovider scopeprovider newscopeprovider iproxy scopeprovider iproxy scope_provider scopeprovider scopeprovider exit action public void run if type exit action kit code bug system exit 0 exit_action codebug returns the scope for script evaluations public scriptable get scope if type scope provider kit code bug if scope null kit code bug return scope getscope scope_provider codebug codebug private interpreted function interpreter data idata object static security domain this idata idata always get context from the current thread to avoid security breaches via passing mangled context instances with bogus security controller context cx context get context security controller sc cx get security controller object dynamic domain if sc null dynamic domain sc get dynamic security domain static security domain else if static security domain null throw new illegal argument exception dynamic domain null this security controller sc this security domain dynamic domain interpretedfunction interpreterdata staticsecuritydomain securitycontroller getcontext securitycontroller getsecuritycontroller dynamicdomain dynamicdomain getdynamicsecuritydomain staticsecuritydomain staticsecuritydomain illegalargumentexception dynamicdomain securitycontroller securitydomain dynamicdomain private interpreted function interpreted function parent int index this idata parent idata its nested functions index this security controller parent security controller this security domain parent security domain interpretedfunction interpretedfunction itsnestedfunctions securitycontroller securitycontroller securitydomain securitydomain create script from compiled bytecode static interpreted function create script interpreter data idata object static security domain interpreted function f f new interpreted function idata static security domain return f interpretedfunction createscript interpreterdata staticsecuritydomain interpretedfunction interpretedfunction staticsecuritydomain create function compiled from function constructor static interpreted function create function context cx scriptable scope interpreter data idata object static security domain interpreted function f f new interpreted function idata static security domain f init interpreted function cx scope return f interpretedfunction createfunction interpreterdata staticsecuritydomain interpretedfunction interpretedfunction staticsecuritydomain initinterpretedfunction create function embedded in script or another function static interpreted function create function context cx scriptable scope interpreted function parent int index interpreted function f new interpreted function parent index f init interpreted function cx scope return f interpretedfunction createfunction interpretedfunction interpretedfunction interpretedfunction initinterpretedfunction scriptable create reg exp wraps context cx scriptable scope if idata its reg exp literals null kit code bug reg exp proxy rep script runtime check reg exp proxy cx int n idata its reg exp literals length scriptable array new scriptable n for int i 0 i n i array i rep wrap reg exp cx scope idata its reg exp literals i return array createregexpwraps itsregexpliterals codebug regexpproxy scriptruntime checkregexpproxy itsregexpliterals wrapregexp itsregexpliterals private void init interpreted function context cx scriptable scope init script function cx scope if idata its reg exp literals null function reg exps create reg exp wraps cx scope initinterpretedfunction initscriptfunction itsregexpliterals functionregexps createregexpwraps public string get function name return idata its name null idata its name getfunctionname itsname itsname calls the function param cx the current context param scope the scope used for the call param the value of this param function arguments must not be null you can use link script runtime empty args to pass empty arguments return the result of the function call public object call context cx scriptable scope scriptable this obj object args if script runtime has top call cx return script runtime do top call this cx scope this obj args return interpreter interpret this cx scope this obj args scriptruntime emptyargs thisobj scriptruntime hastopcall scriptruntime dotopcall thisobj thisobj public object exec context cx scriptable scope if idata its function type 0 can only be applied to scripts throw new illegal state exception if script runtime has top call cx it will go through call path but they are equivalent return script runtime do top call this cx scope scope script runtime empty args return interpreter interpret this cx scope scope script runtime empty args itsfunctiontype illegalstateexception scriptruntime hastopcall scriptruntime dotopcall scriptruntime emptyargs scriptruntime emptyargs public string get encoded source return interpreter get encoded source idata getencodedsource getencodedsource public debuggable script get debuggable view return idata debuggablescript getdebuggableview protected int get language version return idata language version getlanguageversion languageversion protected int get param count return idata arg count getparamcount argcount protected int get param and var count return idata arg names length getparamandvarcount argnames protected string get param or var name int index return idata arg names index getparamorvarname argnames 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 expect return byte public static string name int token if print names return string value of token switch token case error return error case eof return eof case eol return eol case enterwith return enterwith case leavewith return leavewith case return return return case goto return goto case ifeq return ifeq case ifne return ifne case setname return setname case bitor return bitor case bitxor return bitxor case bitand return bitand case eq return eq case ne return ne case lt return lt case le return le case gt return gt case ge return ge case lsh return lsh case rsh return rsh case ursh return ursh case add return add case sub return sub case mul return mul case div return div case mod return mod case not return not case bitnot return bitnot case pos return pos case neg return neg case new return new case delprop return delprop case typeof return typeof case getprop return getprop case setprop return setprop case getelem return getelem case setelem return setelem case call return call case name return name case number return number case string return string case null return null case this return this case false return false case true return true case sheq return sheq case shne return shne case regexp return object case bindname return bindname case throw return throw case rethrow return rethrow case in return in case instanceof return instanceof case local load return local load case getvar return getvar case setvar return setvar case catch scope return catch scope case enum init keys return enum init keys case enum init values return enum init values case enum next return enum next case enum id return enum id case thisfn return thisfn case return result return return result case arraylit return arraylit case objectlit return objectlit case get ref return get ref case set ref return set ref case del ref return del ref case ref call return ref call case ref special return ref special case defaultnamespace return defaultnamespace case escxmltext return escxmltext case escxmlattr return escxmlattr case ref member return ref member case ref ns member return ref ns member case ref name return ref name case ref ns name return ref ns name case try return try case semi return semi case lb return lb case rb return rb case lc return lc case rc return rc case lp return lp case rp return rp case comma return comma case assign return assign case assign bitor return assign bitor case assign bitxor return assign bitxor case assign bitand return assign bitand case assign lsh return assign lsh case assign rsh return assign rsh case assign ursh return assign ursh case assign add return assign add case assign sub return assign sub case assign mul return assign mul case assign div return assign div case assign mod return assign mod case hook return hook case colon return colon case or return or case and return and case inc return inc case dec return dec case dot return dot case function return function case export return export case import return import case if return if case else return else case switch return switch case case return case case default return default case while return while case do return do case for return for case break return break case continue return continue case var return var case with return with case catch return catch case finally return finally case reserved return reserved case empty return empty case block return block case label return label case target return target case loop return loop case expr void return expr void case expr result return expr result case jsr return jsr case script return script case typeofname return typeofname case use stack return use stack case setprop op return setprop op case setelem op return setelem op case local block return local block case set ref op return set ref op case dotdot return dotdot case coloncolon return coloncolon case xml return xml case dotquery return dotquery case xmlattr return xmlattr case xmlend return xmlend case to object return to object case to double return to double token without name throw new illegal state exception string value of token printnames valueof local_load local_load catch_scope catch_scope enum_init_keys enum_init_keys enum_init_values enum_init_values enum_next enum_next enum_id enum_id return_result return_result get_ref get_ref set_ref set_ref del_ref del_ref ref_call ref_call ref_special ref_special ref_member ref_member ref_ns_member ref_ns_member ref_name ref_name ref_ns_name ref_ns_name assign_bitor assign_bitor assign_bitxor assign_bitxor assign_bitand assign_bitand assign_lsh assign_lsh assign_rsh assign_rsh assign_ursh assign_ursh assign_add assign_add assign_sub assign_sub assign_mul assign_mul assign_div assign_div assign_mod assign_mod expr_void expr_void expr_result expr_result use_stack use_stack setprop_op setprop_op setelem_op setelem_op local_block local_block set_ref_op set_ref_op to_object to_object to_double to_double illegalstateexception valueof string suffix public live nav drv super set suffix java livenavdrv setsuffix public static void main string args system out println main live nav drv d new live nav drv d start livenavdrv livenavdrv iterate through suites for each file in each suite create a live nav env in this case a navigator window that can load and evaluate the test result see live nav env parse result 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 live 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 live 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 livenavenv livenavenv parseresult executesuite testsuite privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalfileread privilegemanager enableprivilege universalfilewrite privilegemanager enableprivilege universalpropertyread livenavenv testfile testfile elementat livenavenv runtest writefileresult output_directory writecaseresults output_directory writesuiteresult output_directory writesuitesummary output_directory private hashtable threads with context new hashtable protected object get thread context helper return thread current thread threadswithcontext getthreadcontexthelper currentthread protected context get context object context helper thread t thread context helper return context threads with context get t getcontext contexthelper contexthelper threadswithcontext protected void set context object context helper context cx thread t thread context helper if cx null allow to garbage collect thread reference threads with context remove t else threads with context put t cx setcontext contexthelper contexthelper threadswithcontext threadswithcontext protected class loader get current thread class loader return null classloader getcurrentthreadclassloader protected boolean try to make accessible object accessible object return false trytomakeaccessible accessibleobject the zero parameter constructor when context define class is called with this class it will construct foo prototype using this constructor public foo defineclass the java method defining the java script foo constructor takes an initial value for the counter property note that in the example shell session above we didn t supply a argument to the foo constructor this means that the undefined value is used as the value of the argument and when the argument is converted to an integer undefined becomes 0 public foo int counter start counter counter start javascript counterstart counterstart returns the name of this java script class foo public string get class name return foo javascript getclassname the java method defining the java script reset counter function resets the counter to 0 public void jsfunction resetcounter counter 0 javascript resetcounter jsfunction_resetcounter the java method implementing the getter for the counter property p if set counter had been defined in this class the runtime would call the setter when the property is assigned to public int jsget counter return counter setcounter jsget_counter an example of a variable arguments method all variable arguments methods must have the same number and types of parameters and must be static p param cx the context of the current thread param this obj the java script this value param args the array of arguments for this call param fun obj the function object of the invoked java script function this value is useful to compute a scope using context get top level scope return computes the string values and types of this and of each of the supplied arguments and returns them in a string exception thread association exception if the current thread is not associated with a context see org mozilla javascript scriptable object get top level scope public static object jsfunction varargs context cx scriptable this obj object args function fun obj string buffer buf new string buffer buf append this buf append context to string this obj buf append args for int i 0 i args length i buf append context to string args i if i 1 args length buf append buf append return buf to string thisobj javascript funobj javascript gettoplevelscope threadassociationexception scriptableobject gettoplevelscope jsfunction_varargs thisobj funobj stringbuffer stringbuffer tostring thisobj tostring tostring public namespace xml lib impl lib string uri super lib global scope lib namespace prototype if uri null throw new illegal argument exception this lib lib this prefix uri length 0 null this uri uri xmllibimpl globalscope namespaceprototype illegalargumentexception public namespace xml lib impl lib string prefix string uri super lib global scope lib namespace prototype if uri null throw new illegal argument exception if uri length 0 prefix should be for empty uri if prefix null throw new illegal argument exception if prefix length 0 throw new illegal argument exception this lib lib this prefix prefix this uri uri xmllibimpl globalscope namespaceprototype illegalargumentexception illegalargumentexception illegalargumentexception public 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 uri return uri return public string prefix return prefix return public string to string return uri tostring return public string to locale string return to string tolocalestring tostring public boolean equals object obj if obj instanceof namespace return false return equals namespace obj protected object equivalent values object value if value instanceof namespace return scriptable not found boolean result equals namespace value return result boolean true boolean false equivalentvalues not_found private boolean equals namespace n return uri equals n uri return public string get class name return namespace getclassname param hint return public object get default value class hint return uri getdefaultvalue 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 20 19 50 50 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 6 x prefix id id prefix 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 prefix 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 id_prefix findinstanceidinfo id_prefix id_uri illegalstateexception instanceidinfo getmaxinstanceid protected string get instance id name int id switch id super get max instance id case id prefix return prefix case id uri return uri return super get instance id name id getinstanceidname getmaxinstanceid id_prefix id_uri getinstanceidname protected object get instance id value int id switch id super get max instance id case id prefix if prefix null return undefined instance return prefix case id uri return uri return super get instance id value id getinstanceidvalue getmaxinstanceid id_prefix id_uri getinstanceidvalue protected int find prototype id string s int id generated last update 2004 08 21 12 07 01 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 namespace tag id s arity initprototypeid id_constructor id_tostring tostring id_tosource tosource illegalargumentexception valueof initprototypemethod namespace_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag namespace 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 namespace_tag execidcall thisobj methodid id_constructor jsconstructor thisobj id_tostring realthis thisobj tostring id_tosource realthis thisobj js_tosource illegalargumentexception valueof private namespace real this scriptable this obj id function object f if this obj instanceof namespace throw incompatible call error f return namespace this obj realthis thisobj idfunctionobject thisobj incompatiblecallerror thisobj private object js constructor context cx boolean in new expr object args if in new expr args length 1 return lib cast to namespace cx args 0 if args length 0 return lib construct namespace cx else if args length 1 return lib construct namespace cx args 0 else return lib construct namespace cx args 0 args 1 jsconstructor innewexpr innewexpr casttonamespace constructnamespace constructnamespace constructnamespace private string js tosource string buffer sb new string buffer sb append to source impl prefix uri sb sb append return sb to string js_tosource stringbuffer stringbuffer tosourceimpl tostring static void to source impl string prefix string uri string buffer sb sb append new namespace if uri length 0 if equals prefix throw new illegal argument exception prefix else sb append if prefix null sb append script runtime escape string prefix sb append sb append script runtime escape string uri sb append sb append tosourceimpl stringbuffer illegalargumentexception scriptruntime escapestring scriptruntime escapestring static final long serial versionuid 8221564865490676219l public property exception string detail super detail serialversionuid propertyexception x script annotation xml cursor curs name curs get name xscriptannotation xmlcursor _name getname namespace declarations xml cursor curs prefixidx 0 namespacedecls new string buffer skip non elements curs defaultnsuri curs namespace for prefix if is any default namespace add decl defaultnsuri namespacedeclarations xmlcursor _prefixidx _namespacedecls stringbuffer skipnonelements _defaultnsuri namespaceforprefix isanydefaultnamespace adddecl _defaultnsuri private void add decl string prefix string ns namespacedecls append prefix length 0 declare namespace prefix default element namespace ns n adddecl _namespacedecls string get next prefix string ns string prefix ns prefixidx namespacedecls append declare namespace prefix ns n return prefix getnextprefix _prefixidx _namespacedecls boolean is any default namespace return defaultnsuri null defaultnsuri length 0 false isanydefaultnamespace _defaultnsuri _defaultnsuri string get declarations return namespacedecls to string getdeclarations _namespacedecls tostring param anno private xml xml lib impl lib x script annotation anno super lib lib xml prototype anno anno anno xscriptxml this xmllibimpl xscriptannotation xmlprototype _anno _anno _xscriptxml static xml create emptyxml xml lib impl lib x script annotation anno xml object xo xml object factory new instance xml cursor curs xo new cursor try anno new x script annotation curs curs set bookmark anno finally curs dispose return new xml lib anno createemptyxml xmllibimpl xscriptannotation xmlobject xmlobject newinstance xmlcursor newcursor xscriptannotation setbookmark private static xml createxml xml lib impl lib xml cursor curs if curs current token type is startdoc curs to first content token x script annotation anno find annotation curs return new xml lib anno xmllibimpl xmlcursor currenttokentype isstartdoc tofirstcontenttoken xscriptannotation findannotation special constructor for making an attribute private static xml create attributexml xml lib impl lib xml cursor cursor if cursor is attr throw new illegal argument exception x script annotation anno new x script annotation cursor cursor set bookmark anno return new xml lib anno createattributexml xmllibimpl xmlcursor isattr illegalargumentexception xscriptannotation xscriptannotation setbookmark param qname param value return static xml create text element xml lib impl lib javax xml namespace q name qname string value x script annotation anno xml object xo xml object factory new instance xml cursor cursor xo new cursor try cursor to next token cursor begin element qname get local part qname get namespaceuri if namespace length 0 cursor insert namespace namespace cursor insert chars value cursor to start doc cursor to next token anno new x script annotation cursor cursor set bookmark anno finally cursor dispose return new xml lib anno createtextelement xmllibimpl qname xscriptannotation xmlobject xmlobject newinstance xmlcursor newcursor tonexttoken beginelement getlocalpart getnamespaceuri insertnamespace insertchars tostartdoc tonexttoken xscriptannotation setbookmark static xml create from xml object xml lib impl lib xml object xo x script annotation anno xml cursor curs xo new cursor if curs current token type is startdoc curs to first content token try anno new x script annotation curs curs set bookmark anno finally curs dispose return new xml lib anno createfromxmlobject xmllibimpl xmlobject xscriptannotation xmlcursor newcursor currenttokentype isstartdoc tofirstcontenttoken xscriptannotation setbookmark static xml create fromjs xml lib impl lib object input object xml object xo boolean is text false string frag if input object null input object undefined instance frag else if input object instanceof xml object impl todo faster way for xml objects frag xml object impl input object toxml string 0 else if input object instanceof wrapper object wrapped wrapper input object unwrap if wrapped instanceof xml object return create from xml object lib xml object wrapped frag script runtime to string input object if frag trim starts with throw script runtime type error invalid use of xml object anonymous tags if frag index of 1 must be solo text node wrap in xml fragment is text true frag text fragment frag text fragment xml options options new xml options if lib ignore comments options put xml options load strip comments if lib ignore processing instructions options put xml options load strip procinsts if lib ignore whitespace options put xml options load strip whitespace try xo xml object factory parse frag options apply the default namespace context cx context get current context string defaulturi lib get default namespaceuri cx if defaulturi length 0 xml cursor cursor xo new cursor boolean is root true while cursor to next token is enddoc if cursor is start continue check if this element explicitly sets the default namespace boolean defaultns declared false cursor push while cursor to next token is any attr if cursor is namespace if cursor get name get local part length 0 defaultns declared true break cursor pop if defaultns declared cursor to end token continue check if this element s name is in no namespace javax xml namespace q name qname cursor get name if qname get namespaceuri length 0 change the namespace qname new javax xml namespace q name defaulturi qname get local part cursor set name qname if is root declare the default namespace cursor push cursor to next token cursor insert namespace defaulturi cursor pop is root false cursor dispose catch xml exception xe todo need to handle namespace prefix not found in xml look for namespace type in the scope change string error msg use of undefined namespace prefix string msg xe get error get message if msg starts with error msg string prefix msg substring error msg length string err msg xe get message if err msg equals error unexpected end of file after null create an empty document xo xml object factory new instance else throw script runtime type error xe get message catch throwable e todo tll catch specific exceptions during parse throw script runtime type error not parsable as xml xml cursor curs xo new cursor if curs current token type is startdoc curs to first content token if is text move it to point to the text node curs to first content token x script annotation anno try anno new x script annotation curs curs set bookmark anno finally curs dispose return new xml lib anno createfromjs xmllibimpl inputobject xmlobject istext inputobject inputobject inputobject xmlobjectimpl xmlobjects xmlobjectimpl inputobject toxmlstring inputobject inputobject xmlobject createfromxmlobject xmlobject scriptruntime tostring inputobject startswith scriptruntime typeerror indexof istext textfragment textfragment xmloptions xmloptions ignorecomments xmloptions load_strip_comments ignoreprocessinginstructions xmloptions load_strip_procinsts ignorewhitespace xmloptions load_strip_whitespace xmlobject getcurrentcontext getdefaultnamespaceuri xmlcursor newcursor isroot tonexttoken isenddoc isstart defaultnsdeclared tonexttoken isanyattr isnamespace getname getlocalpart defaultnsdeclared defaultnsdeclared toendtoken qname getname getnamespaceuri qname getlocalpart setname isroot tonexttoken insertnamespace isroot xmlexception errormsg geterror getmessage startswith errormsg errormsg errmsg getmessage errmsg xmlobject newinstance scriptruntime typeerror getmessage scriptruntime typeerror xmlcursor newcursor currenttokentype isstartdoc tofirstcontenttoken istext tofirstcontenttoken xscriptannotation xscriptannotation setbookmark static xml get from annotation xml lib impl lib x script annotation anno if anno xscriptxml null anno xscriptxml new xml lib anno return anno xscriptxml getfromannotation xmllibimpl xscriptannotation _xscriptxml _xscriptxml _xscriptxml param curs return private static token type skip non elements xml cursor curs token type tt curs current token type while tt is comment tt is procinst tt curs to next token return tt tokentype skipnonelements xmlcursor tokentype currenttokentype iscomment isprocinst tonexttoken param curs return protected static x script annotation find annotation xml cursor curs xml bookmark anno curs get bookmark x script annotation class if anno null anno new x script annotation curs curs set bookmark anno return x script annotation anno xscriptannotation findannotation xmlcursor xmlbookmark getbookmark xscriptannotation xscriptannotation setbookmark xscriptannotation return private xml options get options xml options options new xml options if lib ignore comments options put xml options load strip comments if lib ignore processing instructions options put xml options load strip procinsts if lib ignore whitespace options put xml options load strip whitespace if lib pretty printing options put xml options save pretty print null options put xml options save pretty print indent new integer lib pretty indent return options xmloptions getoptions xmloptions xmloptions ignorecomments xmloptions load_strip_comments ignoreprocessinginstructions xmloptions load_strip_procinsts ignorewhitespace xmloptions load_strip_whitespace prettyprinting xmloptions save_pretty_print xmloptions save_pretty_print_indent prettyindent param cursor param opts return private static string dump node xml cursor cursor xml options opts if cursor is text return cursor get chars if cursor is finish return cursor push boolean wan raw text cursor is startdoc cursor to first child cursor pop return wan raw text cursor get text value cursor xml text opts dumpnode xmlcursor xmloptions istext getchars isfinish wanrawtext isstartdoc tofirstchild wanrawtext gettextvalue xmltext return private xml cursor new cursor xml cursor curs if anno null curs anno create cursor if curs null orphaned case xml object doc xml object factory new instance curs doc new cursor if anno name null curs to next token curs insert element anno name curs to prev sibling curs set bookmark anno else xml object doc xml object factory new instance curs doc new cursor return curs xmlcursor newcursor xmlcursor _anno _anno createcursor xmlobject xmlobject newinstance newcursor _anno _name tonexttoken insertelement _anno _name toprevsibling setbookmark _anno xmlobject xmlobject newinstance newcursor private boolean move to child xml cursor curs long index boolean f first child boolean f use start doc if index 0 throw new illegal argument exception long idx child 0 if f use start doc curs current token type is startdoc we always move to the children of the top node todo this assumes that we want have multiple top level nodes which we should be able tohave curs to first content token token type tt curs to first content token if tt is none tt is end while true if index idx child return true tt curs current token type if tt is text curs to next token else if tt is start need to do this we want to be pointing at the text if that after the end token curs to end token curs to next token else if tt is comment tt is procinst continue else break idx child else if f first child index 0 drill into where first child would be curs to first content token return true return false movetochild xmlcursor ffirstchild fusestartdoc illegalargumentexception idxchild fusestartdoc currenttokentype isstartdoc tofirstcontenttoken tokentype tofirstcontenttoken isnone isend idxchild currenttokentype istext tonexttoken isstart toendtoken tonexttoken iscomment isprocinst idxchild ffirstchild tofirstcontenttoken return xml cursor token type token type xml cursor token type result xml cursor curs new cursor if curs is startdoc curs to first content token result curs current token type curs dispose return result xmlcursor tokentype tokentype xmlcursor tokentype xmlcursor newcursor isstartdoc tofirstcontenttoken currenttokentype param src curs param dest curs param f dont move if same return private boolean move src to dest xml cursor src curs xml cursor dest curs boolean f dont move if same boolean f moved something true token type tt do if f dont move if same src curs is in same document dest curs src curs compare position dest curs 0 if the source and destination are pointing at the same place then there s nothing to move f moved something false break todo tll use replace contents when added and eliminate children removes see above todo if dest curs current token type is startdoc dest curs to next token todo tll can eric support notion of copy instead of me copying then moving xml cursor copy curs copy src curs copy curs move xml dest curs copy curs dispose tt src curs current token type while tt is start tt is end tt is enddoc return f moved something srccurs destcurs fdontmoveifsame movesrctodest xmlcursor srccurs xmlcursor destcurs fdontmoveifsame fmovedsomething tokentype fdontmoveifsame srccurs isinsamedocument destcurs srccurs compareposition destcurs fmovedsomething replacecontents destcurs currenttokentype isstartdoc destcurs tonexttoken xmlcursor copycurs srccurs copycurs movexml destcurs copycurs srccurs currenttokentype isstart isend isenddoc fmovedsomething param curs to copy return private xml cursor copy xml cursor curs to copy xml object xo xml object factory new instance xml cursor copy curs null if curs to copy current token type is text try try just as a textnode to do that we need to wrap the text in a special fragment tag that is not visible from the xml cursor copy curs xml object factory parse x fragment xmlns x http www openuri org fragment curs to copy get chars x fragment new cursor if curs to copy to next sibling if curs to copy current token type is text curs to copy to next token it s not an element it s text so skip it catch exception ex throw script runtime type error ex get message else copy curs xo new cursor copy curs to first content token if curs to copy current token type xml cursor token type startdoc curs to copy to next token curs to copy copy xml copy curs if curs to copy to next sibling if element skip element if curs to copy current token type is text curs to copy to next token it s not an element it s text so skip it copy curs to start doc copy curs to first content token return copy curs curstocopy xmlcursor xmlcursor curstocopy xmlobject xmlobject newinstance xmlcursor copycurs curstocopy currenttokentype istext xmlcursor copycurs xmlobject curstocopy getchars newcursor curstocopy tonextsibling curstocopy currenttokentype istext curstocopy tonexttoken scriptruntime typeerror getmessage copycurs newcursor copycurs tofirstcontenttoken curstocopy currenttokentype xmlcursor tokentype curstocopy tonexttoken curstocopy copyxml copycurs curstocopy tonextsibling curstocopy currenttokentype istext curstocopy tonexttoken copycurs tostartdoc copycurs tofirstcontenttoken copycurs param curs param xml to insert private void insert child xml cursor curs object xml to insert if xml to insert null xml to insert instanceof undefined do nothing else if xml to insert instanceof xml cursor move src to dest xml cursor xml to insert curs true else if xml to insert instanceof xml xml xml value xml xml to insert if it s an attribute then change to text node if xml value token type xml cursor token type attr insert child curs xml value to string else xml cursor curs to insert xml xml to insert new cursor move src to dest curs to insert curs true curs to insert dispose else if xml to insert instanceof xml list xml list list xml list xml to insert for int i 0 i list length i insert child curs list item i else convert to string and make xml out of it string xml str script runtime to string xml to insert xml object xo xml object factory new instance create an empty document xml cursor source curs xo new cursor source curs to next token to hold the text source curs insert chars xml str source curs to prev token call us again with the cursor move src to dest source curs curs true xmltoinsert insertchild xmlcursor xmltoinsert xmltoinsert xmltoinsert xmltoinsert xmlcursor movesrctodest xmlcursor xmltoinsert xmltoinsert xmlvalue xmltoinsert xmlvalue tokentype xmlcursor tokentype insertchild xmlvalue tostring xmlcursor curstoinsert xmltoinsert newcursor movesrctodest curstoinsert curstoinsert xmltoinsert xmllist xmllist xmllist xmltoinsert insertchild xmlstr scriptruntime tostring xmltoinsert xmlobject xmlobject newinstance xmlcursor sourcecurs newcursor sourcecurs tonexttoken sourcecurs insertchars xmlstr sourcecurs toprevtoken movesrctodest sourcecurs param child to match param xml to insert param add to type private void insert child xml child to match object xml to insert int add to type xml cursor curs new cursor token type tt curs current token type xml cursor xml child cursor child to match new cursor if tt is startdoc tt curs to first content token if tt is container tt curs to next token while tt is end if tt is start see if this child is the same as the one thep passed in if curs compare position xml child cursor 0 found it if add to type append child move the cursor to just past the end of this element curs to end token curs to next token insert child curs xml to insert break skip over child elements if tt is start tt curs to end token tt curs to next token xml child cursor dispose curs dispose childtomatch xmltoinsert addtotype insertchild childtomatch xmltoinsert addtotype xmlcursor newcursor tokentype currenttokentype xmlcursor xmlchildcursor childtomatch newcursor isstartdoc tofirstcontenttoken iscontainer tonexttoken isend isstart compareposition xmlchildcursor addtotype append_child toendtoken tonexttoken insertchild xmltoinsert isstart toendtoken tonexttoken xmlchildcursor param curs protected void remove token xml cursor curs xml object xo xml object factory new instance don t delete anything move to another document so it gets orphaned nicely xml cursor tmp curs xo new cursor tmp curs to first content token curs move xml tmp curs tmp curs dispose removetoken xmlcursor xmlobject xmlobject newinstance xmlcursor tmpcurs newcursor tmpcurs tofirstcontenttoken movexml tmpcurs tmpcurs param index protected void remove child long index xml cursor curs new cursor if move to child curs index false false remove token curs curs dispose removechild xmlcursor newcursor movetochild removetoken param name return protected static javax xml namespace q name computeq name object name if name instanceof string string ns null string local name null string full name string name local name full name if full name starts with int idx full name index of if idx 1 ns full name substring 1 idx 1 don t include the around the namespace local name full name substring idx 1 if ns null return new javax xml namespace q name local name else return new javax xml namespace q name ns local name return null qname computeqname localname fullname localname fullname fullname startswith fullname indexof fullname localname fullname qname localname qname localname param dest curs param new value private void replace xml cursor dest curs xml new value if dest curs is startdoc can t overwrite a whole document user really wants to overwrite the contents of dest curs to first content token orphan the token don t delete it outright on the xml cursor remove token dest curs xml cursor src curs new value new cursor if src curs current token type is startdoc cann t append a whole document user really wants to append the contents of src curs to first content token move src to dest src curs dest curs false re link a new annotation to this cursor we just deleted the previous annotation on entrance to replace if dest curs to prev sibling dest curs to prev token dest curs set bookmark new x script annotation dest curs todo would be nice if dest curs to next sibling went to where the next token if the cursor was pointing at the last token in the stream dest curs to end token dest curs to next token src curs dispose destcurs newvalue xmlcursor destcurs newvalue destcurs isstartdoc destcurs tofirstcontenttoken xmlcursor removetoken destcurs xmlcursor srccurs newvalue newcursor srccurs currenttokentype isstartdoc srccurs tofirstcontenttoken movesrctodest srccurs destcurs destcurs toprevsibling destcurs toprevtoken destcurs setbookmark xscriptannotation destcurs destcurs tonextsibling destcurs toendtoken destcurs tonexttoken srccurs param currxml node param xml value return private boolean do put xml name name xml currxml node xml object impl xml value boolean result false xml cursor curs currxml node new cursor try replace the node with this new xml value xml xml int to assign len xml value length for int i 0 i to assign len i if xml value instanceof xml list xml xml xml list xml value item i else xml xml xml value if it s an attribute or text node make text node xml cursor token type tt xml token type if tt xml cursor token type attr tt xml cursor token type text xml make xml from string lib name xml to string if i 0 1st assignment is replace child all others are append child replace curs xml else insert child curs xml we re done we ve blown away the node because the rvalue was xml result true catch exception ex ex print stack trace throw script runtime type error ex get message finally curs dispose return result currxmlnode xmlvalue doput xmlname currxmlnode xmlobjectimpl xmlvalue xmlcursor currxmlnode newcursor toassignlen xmlvalue toassignlen xmlvalue xmllist xmllist xmlvalue xmlvalue xmlcursor tokentype tokentype xmlcursor tokentype xmlcursor tokentype makexmlfromstring tostring replacechild appendchild insertchild printstacktrace scriptruntime typeerror getmessage make a text node element with this element name and text value param name param value return private xml make xml from string xml lib impl lib xml name name string value xml result javax xml namespace q name qname try qname new javax xml namespace q name name uri name local name catch exception e throw script runtime type error e get message result create text element lib qname value to string return result makexmlfromstring xmllibimpl xmlname qname qname localname scriptruntime typeerror getmessage createtextelement tostring param name return private xml list match attributes xml name xml name xml list result new xml list lib xml cursor curs new cursor if curs current token type is startdoc curs to first content token if curs is start if curs to first attribute do if qname matches xml name curs get name result add to list create attribute object curs while curs to next attribute curs dispose return result xmllist matchattributes xmlname xmlname xmllist xmllist xmlcursor newcursor currenttokentype isstartdoc tofirstcontenttoken isstart tofirstattribute qnamematches xmlname getname addtolist createattributeobject tonextattribute param attr curs return private xml create attribute object xml cursor attr curs xml result null if attr curs current token type is attr result create attributexml lib attr curs return result attrcurs createattributeobject xmlcursor attrcurs attrcurs currenttokentype isattr createattributexml attrcurs public string get class name return xml getclassname xml 0 should return this all other indexes are undefined param index param start return public object get int index scriptable start log get index index if index 0 return this else return scriptable not found not_found does the named property exist param name param start return boolean hasxml property xml name xml name boolean result false if prototype flag string name xml name local name if get method name not found result true else 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 prototypeflag xmlname localname getmethod not_found xmlname localname getpropertylist xmlname getmethod not_found param index param start return public boolean has int index scriptable start return index 0 return public object get ids object enum objs if prototype flag enum objs new object 0 else enum objs new object 1 enum objs 0 new integer 0 return enum objs getids enumobjs prototypeflag enumobjs enumobjs enumobjs enumobjs return public object get ids for debug return get ids getidsfordebug getids param name param start return object getxml property xml name xml name object result not found if prototype flag string name xml name local name result get method name else result get property list xml name return result getxmlproperty xmlname xmlname not_found prototypeflag xmlname localname getmethod getpropertylist xmlname param name param start param value void putxml property xml name xml name object value log put property name value value get class if prototype flag else special case checks for undefined and null if value null value null else if value instanceof undefined value undefined get the named property if xml name is attribute name set attribute xml name value else if xml name uri null xml name local name equals set children value else convert text into xml if needed xml object impl xml value null if value instanceof xml object impl xml value xml object impl value check for attribute type and convert to text node if xml value instanceof xml if xml xml value token type xml cursor token type attr xml value make xml from string lib xml name xml value to string if xml value instanceof xml list for int i 0 i xml value length i xml xml xml xml list xml value item i if xml token type xml cursor token type attr xml list xml value replace i make xml from string lib xml name xml to string else xml value make xml from string lib xml name script runtime to string value xml list matches xml list get property list xml name if matches length 0 append child xml value else remove all other matches for int i 1 i matches length i remove child matches item i child index replace first match with new value do put xml name xml matches item 0 xml value putxmlproperty xmlname xmlname getclass prototypeflag xmlname isattributename setattribute xmlname xmlname xmlname localname setchildren xmlobjectimpl xmlvalue xmlobjectimpl xmlvalue xmlobjectimpl textnode xmlvalue xmlvalue tokentype xmlcursor tokentype xmlvalue makexmlfromstring xmlname xmlvalue tostring xmlvalue xmllist xmlvalue xmllist xmlvalue tokentype xmlcursor tokentype xmllist xmlvalue makexmlfromstring xmlname tostring xmlvalue makexmlfromstring xmlname scriptruntime tostring xmllist xmllist getpropertylist xmlname appendchild xmlvalue removechild childindex doput xmlname xmlvalue param index param start param value public void put int index scriptable start object value spec says assignment to indexed xml object should return type error throw script runtime type error assignment to indexed xml is not allowed scriptruntime typeerror param name void deletexml property xml name name if name is descendants name is attribute name xml cursor curs new cursor todo cover the case name if name local name equals delete all attributes if curs to first attribute while curs current token type is attr curs remove xml else delete an attribute javax xml namespace q name qname new javax xml namespace q name name uri name local name curs remove attribute qname curs dispose else xml list matches xml list get property list name matches remove deletexmlproperty xmlname isdescendants isattributename xmlcursor newcursor localname tofirstattribute currenttokentype isattr removexml qname qname localname removeattribute xmllist xmllist getpropertylist param index public void delete int index if index 0 remove protected x script annotation get annotation return anno xscriptannotation getannotation _anno protected void changens string olduri string newuri xml cursor curs new cursor while curs to parent goto the top of the document token type tt curs current token type if tt is startdoc tt curs to first content token if tt is start do if tt is start tt is attr tt is namespace javax xml namespace q name currq name curs get name if olduri equals currq name get namespaceuri curs set name new javax xml namespace q name newuri currq name get local part tt curs to next token while tt is enddoc tt is none curs dispose xmlcursor newcursor toparent tokentype currenttokentype isstartdoc tofirstcontenttoken isstart isstart isattr isnamespace qname currqname getname currqname getnamespaceuri setname qname currqname getlocalpart tonexttoken isenddoc isnone void remove xml cursor child curs new cursor if child curs current token type is startdoc remove on the document removes all children token type tt child curs to first content token while tt is end tt is enddoc remove token child curs tt child curs current token type now see where we re pointing after the delete next token else remove token child curs child curs dispose xmlcursor childcurs newcursor childcurs currenttokentype isstartdoc tokentype childcurs tofirstcontenttoken isend isenddoc removetoken childcurs childcurs currenttokentype removetoken childcurs childcurs param value void replace all xml value xml cursor curs new cursor replace curs value anno value anno curs dispose replaceall xmlcursor newcursor _anno _anno param attr name param value void set attribute xml name xml name object value if xml name uri null xml name local name equals throw script runtime type error assignment not supported xml cursor curs new cursor string str value script runtime to string value if curs current token type is startdoc curs to first content token javax xml namespace q name q name try q name new javax xml namespace q name xml name uri xml name local name catch exception e throw script runtime type error e get message if curs set attribute text q name str value if curs current token type is start can only add attributes inside of a start curs to next token curs insert attribute with value q name str value curs dispose attrname setattribute xmlname xmlname xmlname xmlname localname scriptruntime typeerror xmlcursor newcursor strvalue scriptruntime tostring currenttokentype isstartdoc tofirstcontenttoken qname qname qname qname xmlname xmlname localname scriptruntime typeerror getmessage setattributetext qname strvalue currenttokentype isstart tonexttoken insertattributewithvalue qname strvalue param namespace return private xml list all child nodes string namespace xml list result new xml list lib xml cursor curs new cursor token type tt curs current token type javax xml namespace q name target property new javax xml namespace q name namespace if tt is startdoc tt curs to first content token if tt is container tt curs to first content token while tt is end if tt is start not an element result add to list find annotation curs reset target property to null in this case target property null else match namespace as well if specified if namespace null namespace length 0 namespace equals curs get name get namespaceuri equals namespace add it to the list result add to list find annotation curs set target property if target name is otherwise if target property does not match current then set to null if target property null if target property get local part equals target property curs get name else if target property get local part equals curs get name get local part not a match unset target property target property null skip over child elements if tt is start tt curs to end token tt curs to next token curs dispose set the targets for this xml list result set targets this target property return result xmllist allchildnodes xmllist xmllist xmlcursor newcursor tokentype currenttokentype qname targetproperty qname isstartdoc tofirstcontenttoken iscontainer tofirstcontenttoken isend isstart addtolist findannotation targetproperty getname getnamespaceuri addtolist findannotation targetproperty targetproperty getlocalpart targetproperty getname targetproperty getlocalpart getname getlocalpart targetproperty isstart toendtoken tonexttoken xmllist settargets targetproperty return private xml list match descendant attributes xml name xml name xml list result new xml list lib xml cursor curs new cursor token type tt curs current token type set the targets for this xml list result set targets this null if tt is startdoc tt curs to first content token if tt is container int nest level 1 while nest level 0 tt curs to next token only try to match names for attributes if tt is attr if qname matches xml name curs get name result add to list find annotation curs if tt is start nest level else if tt is end nest level else if tt is enddoc shouldn t get here but just in case break curs dispose return result xmllist matchdescendantattributes xmlname xmlname xmllist xmllist xmlcursor newcursor tokentype currenttokentype xmllist settargets isstartdoc tofirstcontenttoken iscontainer nestlevel nestlevel tonexttoken isattr qnamematches xmlname getname addtolist findannotation isstart nestlevel isend nestlevel isenddoc return private xml list match descendant children xml name xml name xml list result new xml list lib xml cursor curs new cursor token type tt curs current token type set the targets for this xml list result set targets this null if tt is startdoc tt curs to first content token if tt is container int nest level 1 while nest level 0 tt curs to next token if tt is attr tt is end tt is enddoc only try to match names for elements or processing instructions if tt is start tt is procinst not an element or procinst only add if qname is all if xml name local name equals result add to list find annotation curs else if qname matches xml name curs get name result add to list find annotation curs if tt is start nest level else if tt is end nest level else if tt is enddoc shouldn t get here but just in case break curs dispose return result xmllist matchdescendantchildren xmlname xmlname xmllist xmllist xmlcursor newcursor tokentype currenttokentype xmllist settargets isstartdoc tofirstcontenttoken iscontainer nestlevel nestlevel tonexttoken isattr isend isenddoc isstart isprocinst xmlname localname addtolist findannotation qnamematches xmlname getname addtolist findannotation isstart nestlevel isend nestlevel isenddoc param token type return private xml list match children xml cursor token type token type return match children token type xml name form star tokentype xmllist matchchildren xmlcursor tokentype tokentype matchchildren tokentype xmlname formstar return private xml list match children xml cursor token type token type xml name name xml list result new xml list lib xml cursor curs new cursor token type tt curs current token type javax xml namespace q name qname new javax xml namespace q name name uri name local name javax xml namespace q name target property qname if tt is startdoc tt curs to first content token if tt is container tt curs to first content token while tt is end if tt token type only try to match names for elements or processing instructions if tt is start tt is procinst not an element or no name specified result add to list find annotation curs reset target property to null in this case target property null else match names as well if qname matches name curs get name add it to the list result add to list find annotation curs set target property if target name is otherwise if target property does not match current then set to null if target property null if target property get local part equals target property curs get name else if target property get local part equals curs get name get local part not a match unset target property target property null skip over child elements if tt is start tt curs to end token tt curs to next token curs dispose if token type xml cursor token type start set the targets for this xml list result set targets this target property return result xmllist matchchildren xmlcursor tokentype tokentype xmlname xmllist xmllist xmlcursor newcursor tokentype currenttokentype qname qname localname qname targetproperty isstartdoc tofirstcontenttoken iscontainer tofirstcontenttoken isend tokentype isstart isprocinst addtolist findannotation targetproperty qnamematches getname addtolist findannotation targetproperty targetproperty getlocalpart targetproperty getname targetproperty getlocalpart getname getlocalpart targetproperty isstart toendtoken tonexttoken tokentype xmlcursor tokentype xmllist settargets targetproperty param template param match return private boolean qname matches xml name template javax xml namespace q name match boolean matches false if template uri null template uri equals match get namespaceuri uri ok test name if template local name equals template local name equals match get local part matches true return matches qnamematches xmlname qname getnamespaceuri localname localname getlocalpart the add namespace method adds a namespace declaration to the in scope namespaces for this xml object and returns this xml object param to add xml add namespace namespace ns when a namespace is used it will be added automatically to the in scope namespaces set there is no need to add namespaces with undefined prefixes string ns prefix ns prefix if ns prefix null return this xml cursor cursor new cursor try if cursor is container return this javax xml namespace q name qname cursor get name don t add a default namespace declarations to containers with q names in no namespace if qname get namespaceuri equals ns prefix equals return this get all declared namespaces that are in scope map prefix touri namespace helper get all namespaces lib cursor string uri string prefix touri get ns prefix if uri null check if the namespace is not already in scope if uri equals ns uri return this cursor push let s see if we have to delete a namespace declaration while cursor to next token is any attr if cursor is namespace qname cursor get name string prefix qname get local part if prefix equals ns prefix delete the current namespace declaration cursor remove xml break cursor pop cursor to next token cursor insert namespace ns prefix ns uri finally cursor dispose return this addnamespace toadd addnamespace inscopenamespaces nsprefix nsprefix xmlcursor newcursor iscontainer qname getname qnames getnamespaceuri nsprefix prefixtouri namespacehelper getallnamespaces prefixtouri nsprefix tonexttoken isanyattr isnamespace getname getlocalpart nsprefix removexml tonexttoken insertnamespace nsprefix param xml return xml append child object xml xml cursor curs new cursor if curs is startdoc curs to first content token move the cursor to the end of this element if curs is start curs to end token insert child curs xml curs dispose return this appendchild xmlcursor newcursor isstartdoc tofirstcontenttoken isstart toendtoken insertchild param name return xml list attribute xml name xml name return match attributes xml name xmllist xmlname xmlname matchattributes xmlname return xml list attributes xml name xml name xml name form star return match attributes xml name xmllist xmlname xmlname xmlname formstar matchattributes xmlname xml list child long index xml list result new xml list lib result set targets this null result add to list get xml child index return result xmllist xmllist xmllist settargets addtolist getxmlchild xml list child xml name xml name if xml name null return new xml list lib xml list result if xml name local name equals result all child nodes xml name uri else result match children xml cursor token type start xml name return result xmllist xmlname xmlname xmlname xmllist xmllist xmlname localname allchildnodes xmlname matchchildren xmlcursor tokentype xmlname param index return xml get xml child long index xml result null xml cursor curs new cursor if move to child curs index false true result createxml lib curs curs dispose return result getxmlchild xmlcursor newcursor movetochild return int child index int index 0 xml cursor curs new cursor token type tt curs current token type while true if tt is text index if curs to prev sibling break else if tt is start tt curs to prev token if tt is end curs to next token if curs to prev sibling break index else hit the parent start tag so get out we re down counting children break else if tt is comment tt is procinst curs to prev token else break tt curs current token type index curs current token type is startdoc 1 index curs dispose return index childindex xmlcursor newcursor tokentype currenttokentype istext toprevsibling isstart toprevtoken isend tonexttoken toprevsibling iscomment isprocinst toprevtoken currenttokentype currenttokentype isstartdoc return xml list children return all child nodes null xmllist allchildnodes return xml list comments return match children xml cursor token type comment xmllist matchchildren xmlcursor tokentype param xml return boolean contains object xml boolean result false if xml instanceof xml result equivalent xml xml return result equivalentxml return object copy xml cursor src curs new cursor if src curs is startdoc src curs to first content token xml xml create emptyxml lib xml cursor dest curs xml new cursor dest curs to first content token src curs copy xml dest curs dest curs dispose src curs dispose return xml xmlcursor srccurs newcursor srccurs isstartdoc srccurs tofirstcontenttoken createemptyxml xmlcursor destcurs newcursor destcurs tofirstcontenttoken srccurs copyxml destcurs destcurs srccurs param name return xml list descendants xml name xml name xml list result if xml name is attribute name result match descendant attributes xml name else result match descendant children xml name return result xmllist xmlname xmlname xmllist xmlname isattributename matchdescendantattributes xmlname matchdescendantchildren xmlname the in scope namespaces method returns an array of namespace objects representing the namespaces in scope for this xml object in the context of its parent return array of all namespaces in scope for this xml object object in scope namespaces xml cursor cursor new cursor object namespaces namespace helper in scope namespaces lib cursor cursor dispose return namespaces inscopenamespaces inscopenamespaces xmlcursor newcursor namespacehelper inscopenamespaces param child param xml xml insert child after object child object xml if child null spec says inserting after nothing is the same as prepending prepend child xml else if child instanceof xml insert child xml child xml append child return this insertchildafter prependchild insertchild append_child param child param xml xml insert child before object child object xml if child null spec says inserting before nothing is the same as appending append child xml else if child instanceof xml insert child xml child xml prepend child return this insertchildbefore appendchild insertchild prepend_child return boolean has own property xml name xml name boolean has property false if prototype flag string property xml name local name has property 0 find prototype id property else has property get property list xml name length 0 return has property hasownproperty xmlname xmlname hasproperty prototypeflag xmlname localname hasproperty findprototypeid hasproperty getpropertylist xmlname hasproperty return boolean has complex content return has simple content hascomplexcontent hassimplecontent return boolean has simple content boolean simple content false xml cursor curs new cursor if curs is attr curs is text return true if curs is startdoc curs to first content token simple content curs to first child curs dispose return simple content hassimplecontent simplecontent xmlcursor newcursor isattr istext isstartdoc tofirstcontenttoken simplecontent tofirstchild simplecontent length of an xml object is always 1 it s a list of xml objects of size 1 return int length return 1 return string local name xml cursor cursor new cursor if cursor is startdoc cursor to first content token string name null if cursor is start cursor is attr cursor is procinst javax xml namespace q name qname cursor get name name qname get local part cursor dispose return name localname xmlcursor newcursor isstartdoc tofirstcontenttoken isstart isattr isprocinst qname getname getlocalpart the name method returns the qualified name associated with this xml object return the qualified name associated with this xml object q name name xml cursor cursor new cursor if cursor is startdoc cursor to first content token q name name null if cursor is start cursor is attr cursor is procinst javax xml namespace q name qname cursor get name if cursor is procinst name new q name lib qname get local part else string uri qname get namespaceuri string prefix qname get prefix name new q name lib uri qname get local part prefix cursor dispose return name qname xmlcursor newcursor isstartdoc tofirstcontenttoken qname isstart isattr isprocinst qname getname isprocinst qname getlocalpart getnamespaceuri getprefix qname getlocalpart param prefix return object namespace string prefix xml cursor cursor new cursor if cursor is startdoc cursor to first content token object result null if prefix null if cursor is start cursor is attr object in scopens namespace helper in scope namespaces lib cursor xxx is it reaaly necessary to create the second cursor xml cursor cursor2 new cursor if cursor2 is startdoc cursor2 to first content token result namespace helper get namespace lib cursor2 in scopens cursor2 dispose else map prefix touri namespace helper get all namespaces lib cursor string uri string prefix touri get prefix result uri null undefined instance new namespace lib prefix uri cursor dispose return result xmlcursor newcursor isstartdoc tofirstcontenttoken isstart isattr inscopens namespacehelper inscopenamespaces xmlcursor newcursor isstartdoc tofirstcontenttoken namespacehelper getnamespace inscopens prefixtouri namespacehelper getallnamespaces prefixtouri return object namespace declarations xml cursor cursor new cursor object namespaces namespace helper namespace declarations lib cursor cursor dispose return namespaces namespacedeclarations xmlcursor newcursor namespacehelper namespacedeclarations return object node kind string result xml cursor token type tt token type if tt xml cursor token type attr result attribute else if tt xml cursor token type text result text else if tt xml cursor token type comment result comment else if tt xml cursor token type procinst result processing instruction else if tt xml cursor token type start result element else a non existant node has the node kind of text result text return result nodekind xmlcursor tokentype tokentype xmlcursor tokentype xmlcursor tokentype xmlcursor tokentype xmlcursor tokentype xmlcursor tokentype nodekind void normalize xml cursor curs new cursor token type tt curs current token type walk through the tokens removing empty text nodes and merging adjacent text nodes if tt is startdoc tt curs to first content token if tt is container int nest level 1 string previous text null while nest level 0 tt curs to next token if tt xml cursor token type text string current text curs get chars trim if current text trim length 0 empty text node remove remove token curs curs to prev token else if previous text null no previous text node reset to trimmed version previous text current text else it appears that this case never happens with x beans previous text node exists concatenate string new text previous text current text curs to prev token remove token curs remove token curs curs insert chars new text else previous text null if tt is start nest level else if tt is end nest level else if tt is enddoc shouldn t get here but just in case break curs dispose xmlcursor newcursor tokentype currenttokentype isstartdoc tofirstcontenttoken iscontainer nestlevel previoustext nestlevel tonexttoken xmlcursor tokentype currenttext getchars currenttext removetoken toprevtoken previoustext previoustext currenttext xbeans newtext previoustext currenttext toprevtoken removetoken removetoken insertchars newtext previoustext isstart nestlevel isend nestlevel isenddoc return object parent object parent xml cursor curs new cursor if curs is startdoc at doc level no parent parent undefined instance else if curs to parent if curs is startdoc was top level no parent parent undefined instance else parent get from annotation lib find annotation curs else no parent parent undefined instance curs dispose return parent xmlcursor newcursor isstartdoc toparent isstartdoc getfromannotation findannotation param xml return xml prepend child object xml xml cursor curs new cursor if curs is startdoc curs to first content token move the cursor to the first content token curs to first content token insert child curs xml curs dispose return this prependchild xmlcursor newcursor isstartdoc tofirstcontenttoken tofirstcontenttoken insertchild return object processing instructions xml name xml name return match children xml cursor token type procinst xml name processinginstructions xmlname xmlname matchchildren xmlcursor tokentype xmlname param name return boolean property is enumerable object name boolean result if name instanceof integer result integer name int value 0 else if name instanceof number double x number name double value check that number is posotive 0 result x 0 0 1 0 x 0 else result script runtime to string name equals 0 return result propertyisenumerable intvalue doublevalue scriptruntime tostring param namespace xml remove namespace namespace ns xml cursor cursor new cursor try if cursor is startdoc cursor to first content token if cursor is start return this string ns prefix ns prefix string nsuri ns uri map prefix touri new hash map int depth 1 while cursor is end depth 0 if cursor is start get the namespaces declared in this element the ones with undefined prefixes are not candidates for removal because they are used prefix touri clear namespace helper get namespaces cursor prefix touri obj array in scopens bag new obj array iterator i prefix touri entry set iterator while i has next map entry entry map entry i next ns new namespace lib string entry get key string entry get value in scopens bag add ns add the uri we are looking for to avoid matching non existing namespaces ns new namespace lib nsuri in scopens bag add ns object in scopens in scopens bag to array check the element name namespace n namespace helper get namespace lib cursor in scopens if nsuri equals n uri ns prefix null ns prefix equals n prefix this namespace is used return this check the attributes cursor push boolean has next cursor to first attribute while has next n namespace helper get namespace lib cursor in scopens if nsuri equals n uri ns prefix null ns prefix equals n prefix this namespace is used return this has next cursor to next attribute cursor pop if ns prefix null remove all namespaces declarations that match nsuri i prefix touri entry set iterator while i has next map entry entry map entry i next if entry get value equals nsuri namespace helper remove namespace cursor string entry get key else if nsuri equals prefix touri get ns prefix remove the namespace declaration that matches ns prefix namespace helper remove namespace cursor string value of ns prefix switch cursor to next token int value case xml cursor token type int start depth break case xml cursor token type int end depth break finally cursor dispose return this removenamespace xmlcursor newcursor isstartdoc tofirstcontenttoken isstart nsprefix prefixtouri hashmap isend isstart prefixtouri namespacehelper getnamespaces prefixtouri objarray inscopensbag objarray prefixtouri entryset hasnext getkey getvalue inscopensbag inscopensbag inscopens inscopensbag toarray namespacehelper getnamespace inscopens nsprefix nsprefix hasnext tofirstattribute hasnext namespacehelper getnamespace inscopens nsprefix nsprefix hasnext tonextattribute nsprefix prefixtouri entryset hasnext getvalue namespacehelper removenamespace getkey prefixtouri nsprefix nsprefix namespacehelper removenamespace valueof nsprefix tonexttoken intvalue xmlcursor tokentype int_start xmlcursor tokentype int_end xml replace long index object xml xml list xl child to replace xml list child index if xl child to replace length 0 one exists an that index xml child to replace xml xl child to replace item 0 insert child after child to replace xml remove child index return this xmllist xlchildtoreplace xmllist xlchildtoreplace childtoreplace xlchildtoreplace insertchildafter childtoreplace removechild param property name param xml return xml replace xml name xml name object xml putxml property xml name xml return this propertyname xmlname xmlname putxmlproperty xmlname param xml xml set children object xml remove all children xml name xml name xml name form star xml list matches xml list get property list xml name matches remove append new children append child xml return this setchildren xmlname xmlname xmlname formstar xmllist xmllist getpropertylist xmlname appendchild param name void set local name string local name xml cursor cursor new cursor try if cursor is startdoc cursor to first content token if cursor is text cursor is comment return javax xml namespace q name qname cursor get name cursor set name new javax xml namespace q name qname get namespaceuri local name qname get prefix finally cursor dispose setlocalname localname xmlcursor newcursor isstartdoc tofirstcontenttoken istext iscomment qname getname setname qname getnamespaceuri localname getprefix param name void set name q name qname xml cursor cursor new cursor try if cursor is startdoc cursor to first content token if cursor is text cursor is comment return if cursor is procinst string local name qname local name cursor set name new javax xml namespace q name local name else string prefix qname prefix if prefix null prefix cursor set name new javax xml namespace q name qname uri qname local name prefix finally cursor dispose setname qname xmlcursor newcursor isstartdoc tofirstcontenttoken istext iscomment isprocinst localname localname setname qname localname setname qname localname param ns void set namespace namespace ns xml cursor cursor new cursor try if cursor is startdoc cursor to first content token if cursor is text cursor is comment cursor is procinst return string prefix ns prefix if prefix null prefix cursor set name new javax xml namespace q name ns uri local name prefix finally cursor dispose setnamespace xmlcursor newcursor isstartdoc tofirstcontenttoken istext iscomment isprocinst setname qname localname return xml list text return match children xml cursor token type text xmllist matchchildren xmlcursor tokentype return public string to string string result xml cursor curs new cursor if curs is startdoc curs to first content token if curs is text result curs get chars else if curs is start has simple content result curs get text value else result toxml string 0 return result tostring xmlcursor newcursor isstartdoc tofirstcontenttoken istext getchars isstart hassimplecontent gettextvalue toxmlstring string to source int indent xxx does toxml string always return valid xml literal return toxml string indent tosource toxmlstring toxmlstring return string toxml string int indent xxx indent is ignored string result xml cursor curs new cursor if curs is startdoc curs to first content token try if curs is text result curs get chars else if curs is attr result curs get text value else if curs is comment curs is procinst result xml dump node curs get options todo x beans dependent hack here if it s a comment or pi take off the xml frament stuff string start xml fragment string end xml fragment if result starts with start result result substring start length if result ends with end result result substring 0 result length end length else result xml dump node curs get options finally curs dispose return result toxmlstring xmlcursor newcursor isstartdoc tofirstcontenttoken istext getchars isattr gettextvalue iscomment isprocinst dumpnode getoptions xbeans startswith endswith dumpnode getoptions return object value of return this valueof param target return boolean equivalent xml object target boolean result false if target instanceof xml xml other xml xml target compare with to string if either side is text node or attribute otherwise compare as xml xml cursor token type thistt token type xml cursor token type othertt other xml token type if thistt xml cursor token type attr othertt xml cursor token type attr thistt xml cursor token type text othertt xml cursor token type text result to string equals other xml to string else xml cursor curs one new cursor xml cursor curs two other xml new cursor result logical equality nodes equal curs one curs two curs one dispose curs two dispose old way of comparing by string boolean org pretty printing prototype pretty printing prototype pretty printing true result toxml string 0 equals other xml toxml string 0 prototype pretty printing org pretty printing else if target instanceof xml list xml list other list xml list target if other list length 1 result equivalent xml other list get xml from annotation 0 else if has simple content string other str script runtime to string target result to string equals other str return result equivalentxml otherxml tostring xmlcursor tokentype tokentype xmlcursor tokentype otherxml tokentype xmlcursor tokentype xmlcursor tokentype xmlcursor tokentype xmlcursor tokentype tostring otherxml tostring xmlcursor cursone newcursor xmlcursor curstwo otherxml newcursor logicalequality nodesequal cursone curstwo cursone curstwo orgprettyprinting prettyprinting prettyprinting toxmlstring otherxml toxmlstring prettyprinting orgprettyprinting xmllist xmllist otherlist xmllist otherlist equivalentxml otherlist getxmlfromannotation hassimplecontent otherstr scriptruntime tostring tostring otherstr param name param start return xml list get property list xml name name xml list result get the named property if name is descendants result descendants name else if name is attribute name result attribute name else result child name return result xmllist getpropertylist xmlname xmllist isdescendants isattributename protected object js constructor context cx boolean in new expr object args if args length 0 return create fromjs lib else object arg0 args 0 if in new expr arg0 instanceof xml xml xml returns the same object return arg0 return create fromjs lib arg0 jsconstructor innewexpr createfromjs innewexpr createfromjs see ecma 357 11 2 2 1 semantics 3 f public scriptable get extra method source context cx if has simple content string src to string return script runtime to object or null cx src return null 11_2_2_1 3_f getextramethodsource hassimplecontent tostring scriptruntime toobjectornull xml object get xml object xml object xo xml cursor cursor new cursor try xo cursor get object finally cursor dispose return xo xmlobject getxmlobject xmlobject xmlcursor newcursor getobject public class datatypes 003 extends live connect test public datatypes 003 super datatypes_003 liveconnecttest datatypes_003 public static void main string args datatypes 003 test new datatypes 003 test start datatypes_003 datatypes_003 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 java objects are unwrapped do getjs var tests packages com netscape javascript qa liveconnect data type class java lang class class com netscape javascript qa liveconnect data type class do getjs var tests new java lang string java string java lang string java string strings numbers and booleans are converted to string double and boolean objects do getjs var tests boolean true java lang boolean true do getjs var tests boolean java lang boolean false do getjs var tests boolean false java lang boolean false do getjs var tests number 12345 java lang double new double 12345 to string do getjs var tests 12345 java lang double new double 12345 to string do getjs var tests string hello java lang string hello do getjs var tests hello java lang string hello do getjs var tests true java lang boolean true do getjs var tests false java lang boolean false other objects are wrapped with a js object do getjs var tests new number 0 netscape javascript js object 0 throws null pointer exception put in its own test do getjs var tests null netscape javascript js object null 4 05 returns a java lang string which i guess we need to maintain for backward compatilibilty do getjs var tests void 0 java lang string undefined do getjs var tests new number 999 netscape javascript js object 999 do getjs var tests math netscape javascript js object object math do getjs var tests new boolean true netscape javascript js object true do getjs var tests new boolean false netscape javascript js object false do getjs var tests new string netscape javascript js object do getjs var tests new string hi netscape javascript js object hi do getjs var tests new array 1 2 3 4 5 netscape javascript js object 1 2 3 4 5 do getjs var tests 5 4 3 2 1 netscape javascript js object 5 4 3 2 1 javascript jsobject jsobject executetest dogetjsvartests datatypeclass datatypeclass dogetjsvartests dogetjsvartests dogetjsvartests dogetjsvartests dogetjsvartests tostring dogetjsvartests tostring dogetjsvartests dogetjsvartests dogetjsvartests dogetjsvartests jsobject dogetjsvartests jsobject nullpointerexception dogetjsvartests jsobject dogetjsvartests dogetjsvartests jsobject dogetjsvartests jsobject dogetjsvartests jsobject dogetjsvartests jsobject dogetjsvartests jsobject dogetjsvartests jsobject dogetjsvartests jsobject dogetjsvartests jsobject pass the same arguments to two different tests param right expr right hand side to a java script assignment expression param class name expected name of the class of the java script object when its value is retrieved from the java script context using js object eval or js object get member param value string representation of the value of the java script object see getjs var with eval see getjs var with get member public void do getjs var tests string right expr string class name string value getjs var with eval right expr class name value getjs var with get member right expr class name value rightexpr javascript classname javascript javascript jsobject jsobject getmember javascript getjsvarwitheval getjsvarwithgetmember dogetjsvartests rightexpr classname getjsvarwitheval rightexpr classname getjsvarwithgetmember rightexpr classname 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 a 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 js object 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 js object global eval var name 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 js object new object compare the class of the js object to the expected class add test case global eval var var name right expr js object global eval var name js object get class get name equals expected class get name js object class is js object get class get name true js object get class get name equals expected class get name exception compare the value of the string value of the js object to the expected string value add test case js object to string equals value to string true js object to string equals value exception jsobject javascript javascript jsobject getmember jsobject getmember rightexpr javascript classname evalue getjsvarwitheval rightexpr classname varname jsvar jsobject expectedclass expectedclass forname classname javascript varname rightexpr varname javascript jsobject varname setjsvarwitheval tostring rightexpr expectedclass getname tostring printstacktrace tostring jsobject jsobject addtestcase varname rightexpr jsobject varname jsobject getclass getname expectedclass getname jsobject jsobject getclass getname jsobject getclass getname expectedclass getname jsobject addtestcase jsobject tostring tostring jsobject tostring 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 add the test cases param right expr right hand side to a 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 get member string right expr string class name string value string var name js var object js object 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 js object global get member var name catch exception e system err println getjs 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 js object new object check the class of the js object object add test case global eval var var name right expr js object global get member var name js object get class get name equals expected class get name js object class is js object get class get name true js object get class get name equals expected class get name exception check the string representation of the js object add test case js object to string equals value to string true js object to string equals value exception jsobject javascript javascript jsobject getmember rightexpr javascript classname evalue getjsvarwithgetmember rightexpr classname varname jsvar jsobject expectedclass expectedclass forname classname javascript varname rightexpr varname javascript jsobject getmember varname getjsvarwithgetmember tostring rightexpr expectedclass getname tostring printstacktrace tostring jsobject jsobject addtestcase varname rightexpr jsobject getmember varname jsobject getclass getname expectedclass getname jsobject jsobject getclass getname jsobject getclass getname expectedclass getname jsobject addtestcase jsobject tostring tostring jsobject tostring 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 public string ambiguous object arg return object private static final object importer tag new object public importer top level importer_tag importertoplevel public importer top level public importer top level context cx this cx false importertoplevel importertoplevel public importer top level context cx boolean sealed init standard objects cx sealed importertoplevel initstandardobjects public string get class name return top scope flag global java importer getclassname topscopeflag javaimporter public static void init context cx scriptable scope boolean sealed importer top level obj new importer top level obj export asjs class max prototype id scope sealed importertoplevel importertoplevel exportasjsclass max_prototype_id public void init standard objects context cx boolean sealed assume that context init standard objects initialize java importer property lazily so the above init call is not yet called cx init standard objects this sealed top scope flag true if seal is true then export asjs class cx seal would seal this obj since this is scope as well it would not allow to add variables id function object ctor export asjs class max prototype id this false if sealed ctor seal object delete constructor defined by export asjs class so constructor name would refer to object constructor and not to java importer prototype constructor delete constructor initstandardobjects initstandardobjects javaimporter initstandardobjects topscopeflag exportasjsclass idfunctionobject exportasjsclass max_prototype_id sealobject exportasjsclass javaimporter public boolean has string name scriptable start return super has name start get package property name start not found getpackageproperty not_found public object get string name scriptable start object result super get name start if result not found return result result get package property name start return result not_found getpackageproperty private object get package property string name scriptable start object result not found object elements synchronized imported packages elements imported packages to array for int i 0 i elements length i native java package p native java package elements i object v p get pkg property name start false if v null v instanceof native java package if result not found result v else throw context report runtime error2 msg ambig import result to string v to string return result getpackageproperty not_found importedpackages importedpackages toarray nativejavapackage nativejavapackage getpkgproperty nativejavapackage not_found reportruntimeerror2 tostring tostring deprecated kept only for compatibility public void import package context cx scriptable this obj object args function fun obj js importpackage args importpackage thisobj funobj js_importpackage private object js construct scriptable scope object args importer top level result new importer top level for int i 0 i args length i object arg args i if arg instanceof native java class result import class native java class arg else if arg instanceof native java package result import package native java package arg else throw context report runtime error1 msg not class not pkg context to string arg set explicitly prototype and scope as otherwise in top scope mode base function construct would keep them set to null it also allow to use java importer without new and still get properly initialized object result set parent scope scope result set prototype this return result js_construct importertoplevel importertoplevel nativejavaclass importclass nativejavaclass nativejavapackage importpackage nativejavapackage reportruntimeerror1 tostring basefunction javaimporter setparentscope setprototype private object js importclass object args for int i 0 i args length i object arg args i if arg instanceof native java class throw context report runtime error1 msg not class context to string arg import class native java class arg return undefined instance js_importclass nativejavaclass reportruntimeerror1 tostring importclass nativejavaclass private object js importpackage object args for int i 0 i args length i object arg args i if arg instanceof native java package throw context report runtime error1 msg not pkg context to string arg import package native java package arg return undefined instance js_importpackage nativejavapackage reportruntimeerror1 tostring importpackage nativejavapackage private void import package native java package pkg synchronized imported packages for int j 0 j imported packages size j if pkg imported packages get j pkg null break if pkg null imported packages add pkg importpackage nativejavapackage importedpackages importedpackages importedpackages importedpackages private void import class native java class cl string s cl get class object get name string n s substring s last index of 1 object val get n this if val not found val cl throw context report runtime error1 msg prop defined n define property n cl dontenum put n this cl importclass nativejavaclass getclassobject getname lastindexof not_found reportruntimeerror1 defineproperty protected void init prototype id int id string s int arity switch id case id constructor arity 0 s constructor break case id importclass arity 1 s import class break case id importpackage arity 1 s import package break default throw new illegal argument exception string value of id init prototype method importer tag id s arity initprototypeid id_constructor id_importclass importclass id_importpackage importpackage illegalargumentexception valueof initprototypemethod importer_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag importer tag return super exec id call f cx scope this obj args int id f method id switch id case id constructor return js construct scope args case id importclass return real this this obj f js importclass args case id importpackage return real this this obj f js importpackage args throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag importer_tag execidcall thisobj methodid id_constructor js_construct id_importclass realthis thisobj js_importclass id_importpackage realthis thisobj js_importpackage illegalargumentexception valueof private importer top level real this scriptable this obj id function object f if top scope flag when used as top scope import package and import class are global function that ignore this obj return this if this obj instanceof importer top level throw incompatible call error f return importer top level this obj importertoplevel realthis thisobj idfunctionobject topscopeflag importpackage importclass thisobj thisobj importertoplevel incompatiblecallerror importertoplevel thisobj protected int find prototype id string s int id generated last update 2004 06 08 02 03 11 cest l0 id 0 string x null int c int s length s length if s length 11 c s char at 0 if c c x constructor id id constructor else if c i x import class id id importclass else if s length 13 x import package id id importpackage if x null x s x equals s id 0 generated return id findprototypeid s_length s_length charat id_constructor importclass id_importclass s_length importpackage id_importpackage public class datatypes 011 extends live connect test public datatypes 011 super datatypes_011 liveconnecttest datatypes_011 public static void main string args datatypes 011 test new datatypes 011 test start datatypes_011 datatypes_011 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 short array true do array test dt pub static array short true do array test dt get short array true do array test dt pub array short false executetest doarraytest staticgetshortarray doarraytest pub_static_array_short doarraytest getshortarray doarraytest pub_array_short assign a java short 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 short array data type class pub static array short short 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 short 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_short 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 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 string float float 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 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 expect return double 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 create a new test log and open associated streams param name name of the log file param terminator string that will be appended to the end of each line public test log string name string terminator this name name this terminator terminator open log testlog testlog openlog write a string to the end test log file public void write line string string if print stream null print stream println string terminator try random access file raf new random access file name rw raf seek raf length raf write output stream to byte array raf close output stream reset catch exception e system out println exception writing to name write line e testlog writeline printstream printstream randomaccessfile randomaccessfile outputstream tobytearray outputstream writeline override if privileges are required to write to file system the default implemenation does nothing public void enable privileges return enableprivileges close print stream associated with the test log file public void close log if print stream null print stream close testlog closelog printstream printstream create streams associated with this test log file public void open log enable privileges this output stream new byte array output stream this print stream new print stream this output stream testlog openlog enableprivileges outputstream bytearrayoutputstream printstream printstream outputstream public string to string return this name tostring public class datatypes 002 extends live connect test public datatypes 002 super datatypes_002 liveconnecttest datatypes_002 public static void main string args datatypes 002 test new datatypes 002 test start datatypes_002 datatypes_002 public void execute test do test one do test two do test three do test four executetest dotestone dotesttwo dotestthree dotestfour string literal gets passed js object eval and this test succeeds public void do test one object before object new value object new string test one new value object after before global eval dt pub static string global eval dt pub static string test one new value after global eval dt pub static string add test case global eval dt public string test one new value after global eval dt pub static string after to string equals new value to string true after to string equals new value to string null jsobject dotestone newvalue pub_static_string pub_static_string pub_static_string addtestcase dt_public_string pub_static_string tostring newvalue tostring tostring newvalue tostring new string value is object to string this succeeds with the extra quoting public void do test two object before object new value object new string test two new value object after before global eval dt pub static string global eval dt pub static string new value to string after global eval dt pub static string add test case object new value object new string test two new value global eval dt public string new value to string after global eval dt pub static string after to string equals new value to string true after to string equals new value to string null tostring dotesttwo newvalue pub_static_string pub_static_string newvalue tostring pub_static_string addtestcase newvalue dt_public_string newvalue tostring pub_static_string tostring newvalue tostring tostring newvalue tostring more extra quoting stuff this succeeds public void do test three object before object new value object new string test three new value object after string eval args dt pub static string new value to string before global eval dt pub static string global eval eval args to string after global eval dt pub static string add test case string eval args eval args to string global eval eval args to string after global eval dt pub static string after to string equals new value to string true after to string equals new value to string null dotestthree newvalue evalargs pub_static_string newvalue tostring pub_static_string evalargs tostring pub_static_string addtestcase evalargs evalargs tostring evalargs tostring pub_static_string tostring newvalue tostring tostring newvalue tostring this throws an exception this does not use the extra quoting public void do test four object before object new value object new string test four new value object after string exception string eval args dt pub static string new value to string string exception js exception thrown try before global eval dt pub static string global eval eval args to string after global eval dt pub static string exception catch exception e if e instanceof js exception after exception else after some random exception thrown file exception e to string add test case string eval args eval args to string global eval eval args to string after global eval dt pub static string after to string equals new value to string exception after to string file exception dotestfour newvalue evalargs pub_static_string newvalue tostring jsexception pub_static_string evalargs tostring pub_static_string jsexception tostring addtestcase evalargs evalargs tostring evalargs tostring pub_static_string tostring newvalue tostring tostring 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 static void define class scriptable object scope try scriptable object define class scope environment class catch exception e throw new error e get message defineclass scriptableobject scriptableobject defineclass getmessage public string get class name return environment getclassname public environment if the prototype instance null the prototype instance this theprototypeinstance theprototypeinstance public environment scriptable object scope set parent scope scope object ctor script runtime get top level prop scope environment if ctor null ctor instanceof scriptable scriptable s scriptable ctor set prototype scriptable s get prototype s scriptableobject setparentscope scriptruntime gettoplevelprop setprototype public boolean has string name scriptable start if this the prototype instance return super has name start return system get property name null theprototypeinstance getproperty public object get string name scriptable start if this the prototype instance return super get name start string result system get property name if result null return script runtime to object get parent scope result else return scriptable not found theprototypeinstance getproperty scriptruntime toobject getparentscope not_found public void put string name scriptable start object value if this the prototype instance super put name start value else system get properties put name script runtime to string value theprototypeinstance getproperties scriptruntime tostring private object collect ids properties props system get properties enumeration names props property names vector keys new vector while names has more elements keys add element names next element object ids new object keys size keys copy into ids return ids collectids getproperties propertynames hasmoreelements addelement nextelement copyinto public object get ids if this the prototype instance return super get ids return collect ids getids theprototypeinstance getids collectids public object get all ids if this the prototype instance return super get all ids return collect ids getallids theprototypeinstance getallids collectids 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 ambiguous long arg return long public string ambiguous float arg return float public string ambiguous double arg return double object double_object public string expect return double object double_object public class datatypes 005 extends live connect test public datatypes 005 super datatypes_005 liveconnecttest datatypes_005 public static void main string args datatypes 005 test new datatypes 005 test start datatypes_005 datatypes_005 public void execute test do field tests dt pub boolean java lang boolean object new boolean data type class pub static final boolean do field tests dt pub byte java lang double object new double data type class pub static final byte do field tests dt pub short java lang double object new double data type class pub static final short do field tests dt pub int java lang double object new double data type class pub static final int do field tests dt pub long java lang double object new double data type class pub static final long do field tests dt pub float java lang double object new double data type class pub static final float do field tests dt pub double java lang double object new double data type class pub static final double do field tests dt pub char java lang double object new double data type class pub static final char do field tests dt pub string java lang string object new string data type class pub static final string executetest dofieldtests pub_boolean datatypeclass pub_static_final_boolean dofieldtests pub_byte datatypeclass pub_static_final_byte dofieldtests pub_short datatypeclass pub_static_final_short dofieldtests pub_int datatypeclass pub_static_final_int dofieldtests pub_long datatypeclass pub_static_final_long dofieldtests pub_float datatypeclass pub_static_final_float dofieldtests pub_double datatypeclass pub_static_final_double dofieldtests pub_char datatypeclass pub_static_final_char dofieldtests pub_string datatypeclass pub_static_final_string call the parent class s setup test environment method use js object eval to define the com netscape javascript qa liveconnect data type class use js object eval to define an instance of the data type class see com netscape javascript qa liveconnect data type class 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 jsobject datatypeclass jsobject datatypeclass datatypeclass setuptestenvironment setuptestenvironment datatypeclass pass the arguments to the different tests all of which take the same arguments param field name of the data type class field param class name name of the class of the data type class field param value value of the data type class field see com netscape javascript qa liveconnect data type class public void do field tests string field string class name object value get public field field class name value if field starts with dt pub final set public final field field class name value else set public field field class name value set java script variable field class name value datatypeclass classname datatypeclass datatypeclass datatypeclass dofieldtests classname getpublicfield classname startswith pub_final setpublicfinalfield classname setpublicfield classname setjavascriptvariable classname use js object eval to create a java script variable whose value is the value of a java object instance use js object get member to get the value of the java script object and verify that the value of the result object is of the expected class and value param field name of the data type class field param class name name of the class of the data type class field param value value of the data type class field see com netscape javascript qa liveconnect data type class public void get public field string field string class name object value string description field string exception null object actual null string expect null check the class try global eval var myobject description actual global get member myobject 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 jsobject javascript jsobject getmember javascript datatypeclass classname datatypeclass datatypeclass datatypeclass getpublicfield classname getmember forname classname getname classnotfoundexception tostring addtestcase getclass getclass getname addtestcase tostring addtestcase tostring tostring tostring tostring use js object eval to create a java script variable whose value is the value of a java object instance use js object eval to reset the value of the java script variable and then use js object eval to get the new value of the java script object verify that the value of the result object is of the expected class and value param field name of the data type class field param class name name of the class of the data type class field param value value of the data type class field see com netscape javascript qa liveconnect data type class 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 jsobject javascript jsobject javascript jsobject javascript datatypeclass classname datatypeclass datatypeclass datatypeclass 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 use js object eval to get the value of a java object field that has been defined as final assign a value to a public final instance field the assignment should fail the value should not change but there should be no error message param field name of the data type class field param class name name of the class of the data type class field param value value of the data type class field see com netscape javascript qa liveconnect data type class public void set public 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 jsobject datatypeclass classname datatypeclass datatypeclass datatypeclass setpublicfinalfield classname newvalue classname classname forname classname getname tostring newvalue tostring addtestcase getclass getclass getname addtestcase tostring addtestcase tostring tostring tostring tostring getmember addtestcase use js object eval to create a java script variable whose value is the value of a java object instance use js object set member to reset the value of the variable and then use js object get member to get the value of the java script object vverify that the value of the result object is of the expected class and value param field name of the data type class field param class name name of the class of the data type class field param value value of the data type class field see com netscape javascript qa liveconnect data type class 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 jsobject javascript jsobject setmember jsobject getmember javascript datatypeclass classname datatypeclass datatypeclass datatypeclass 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 protected boolean has feature context cx int feature index if feature index context feature dynamic scope return use dynamic scope return super has feature cx feature index hasfeature featureindex featureindex feature_dynamic_scope usedynamicscope hasfeature featureindex main entry point set up the shared scope and then spawn new threads that execute relative to that shared scope try to run functions with and without dynamic scope to see the effect the expected output is pre shared scope nested shared scope shared scope nested shared scope shared scope nested shared scope thread0 nested thread0 thread1 nested thread1 thread2 nested thread2 pre the final three lines may be permuted in any order depending on thread scheduling public static void main string args context cx context enter try precompile source only once string source var x shared scope n function f return x n dynamic scope works with nested function too function init closure prefix n return function test return prefix x n n var closure init closure nested n script script cx compile string source shared script 1 null use dynamic scope false run scripts cx script use dynamic scope true run scripts cx script finally cx exit sharedscope sharedscope sharedscope sharedscope sharedscope sharedscope sharedscope initclosure initclosure compilestring sharedscript usedynamicscope runscripts usedynamicscope runscripts static void run scripts context cx script script initialize the standard objects object function etc this must be done before scripts can be executed the call returns a new scope that we will share scriptable object shared scope cx init standard objects null true now we can execute the precompiled script against the scope to define x variable and f function in the shared scope script exec cx shared scope now we spawn some threads that execute a script that calls the function f the scope chain looks like this pre per thread scope prototype shared scope parent scope f s activation pre both the shared scope and the per thread scope have variables x defined in them if f is compiled with dynamic scope enabled the x from the per thread scope will be used otherwise the x from the shared scope will be used the x defined in g which calls f should not be seen by f final int thread count 3 thread t new thread thread count for int i 0 i thread count i string source2 function g var x local return f n java lang system out println g n function g2 var x local return closure n java lang system out println g2 n t i new thread new per thread shared scope source2 thread i for int i 0 i thread count i t i start don t return in this thread until all the spawned threads have completed for int i 0 i thread count i try t i join catch interrupted exception e runscripts scriptableobject sharedscope initstandardobjects sharedscope parentscope threadcount threadcount threadcount perthread sharedscope threadcount threadcount interruptedexception per thread scriptable shared scope string source string x this shared scope shared scope this source source this x x perthread sharedscope sharedscope sharedscope public void run we need a new context for this thread context cx context enter try we can share the scope scriptable thread scope cx new object shared scope thread scope set prototype shared scope we want thread scope to be a new top level scope so set its parent scope to null this means that any variables created by assignments will be properties of thread scope thread scope set parent scope null create a java script property of the thread scope named x and save a value for it thread scope put x thread scope x cx evaluate string thread scope source thread script 1 null finally context exit threadscope newobject sharedscope threadscope setprototype sharedscope threadscope threadscope threadscope setparentscope javascript threadscope threadscope evaluatestring threadscope threadscript construct class compiler that uses the specified compiler environment when generating classes public class compiler compiler environs compiler env if compiler env null throw new illegal argument exception this compiler env compiler env this main method class name codegen default main method class classcompiler classcompiler compilerenvirons compilerenv compilerenv illegalargumentexception compilerenv compilerenv mainmethodclassname default_main_method_class set the class name to use for main method implementation the class must have a method matching tt public static void main script sc string args tt it will be called when tt main string args tt is called in the generated class the class name should be fully qulified name and include the package name like in tt org foo bar tt public void set main method class string class name xxx should this check for a valid class name main method class name class name setmainmethodclass classname mainmethodclassname classname get the name of the class for main method implementation see set main method class string public string get main method class return main method class name setmainmethodclass getmainmethodclass mainmethodclassname get the compiler environment the compiler uses public compiler environs get compiler env return compiler env compilerenvirons getcompilerenv compilerenv get the class that the generated target will extend public class get target extends return target extends gettargetextends targetextends set the class that the generated target will extend param extends class the class it extends public void set target extends class extends class target extends extends class extendsclass settargetextends extendsclass targetextends extendsclass get the interfaces that the generated target will implement public class get target implements return target implements gettargetimplements targetimplements set the interfaces that the generated target will implement param implements classes an array of class objects one for each interface the target will extend public void set target implements class implements classes target implements implements classes implementsclasses settargetimplements implementsclasses targetimplements implementsclasses build class name for a auxiliary class generated by compiler if the compiler needs to generate extra classes beyond the main class it will call this function to build the auxiliary class name the default implementation simply appends aux marker to main class name but this can be overridden protected string make auxiliary class name string main class name string aux marker return main class name aux marker auxmarker mainclassname makeauxiliaryclassname mainclassname auxmarker mainclassname auxmarker compile java script source into one or more java class files the first compiled class will have name main class name if the results of link get target extends or link get target implements are not null then the first compiled class will extend the specified super class and implement specified interfaces return array where elements with even indexes specifies class name and the followinf odd index gives class file body as byte array the initial elemnt of the array always holds main class name and array 1 holds its byte code public object compile to class files string source string source location int lineno string main class name parser p new parser compiler env compiler env get error reporter script or fn node tree p parse source source location lineno string encoded source p get encoded source class super class get target extends class interfaces get target implements string script class name boolean is primary interfaces null super class null if is primary script class name main class name else script class name make auxiliary class name main class name 1 codegen codegen new codegen codegen set main method class main method class name byte script class bytes codegen compile to class file compiler env script class name tree encoded source false if is primary return new object script class name script class bytes int function count tree get function count obj to int map function names new obj to int map function count for int i 0 i function count i function node ofn tree get function node i string name ofn get function name if name null name length 0 function names put name ofn get param count if super class null super class script runtime object class byte main class bytes java adapter create adapter code function names main class name super class interfaces script class name return new object main class name main class bytes script class name script class bytes javascript mainclassname gettargetextends gettargetimplements mainclassname compiletoclassfiles sourcelocation mainclassname compilerenv compilerenv geterrorreporter scriptorfnnode sourcelocation encodedsource getencodedsource superclass gettargetextends gettargetimplements scriptclassname isprimary superclass isprimary scriptclassname mainclassname scriptclassname makeauxiliaryclassname mainclassname setmainmethodclass mainmethodclassname scriptclassbytes compiletoclassfile compilerenv scriptclassname encodedsource isprimary scriptclassname scriptclassbytes functioncount getfunctioncount objtointmap functionnames objtointmap functioncount functioncount functionnode getfunctionnode getfunctionname functionnames getparamcount superclass superclass scriptruntime objectclass mainclassbytes javaadapter createadaptercode functionnames mainclassname superclass scriptclassname mainclassname mainclassbytes scriptclassname scriptclassbytes protected object get thread context helper to make subsequent batch calls to get context set context faster associate permanently one element array with context local so get context set context would need just to read write the first array element note that it is necessary to use object not context to allow garbage collection of rhino classes for details see comments by attila szegedi in https bugzilla mozilla org show bug cgi id 281067 c5 object storage object context local get if storage null storage new object 1 context local set storage return storage getthreadcontexthelper getcontext setcontext contextlocal getcontext setcontext show_bug contextlocal contextlocal protected context get context object context helper object storage object context helper return context storage 0 getcontext contexthelper contexthelper protected void set context object context helper context cx object storage object context helper storage 0 cx setcontext contexthelper contexthelper protected class loader get current thread class loader return thread current thread get context class loader classloader getcurrentthreadclassloader currentthread getcontextclassloader protected boolean try to make accessible object accessible object if accessible object instanceof accessible object return false accessible object accessible accessible object accessible object if accessible is accessible return true try accessible set accessible true catch exception ex return accessible is accessible trytomakeaccessible accessibleobject accessibleobject accessibleobject accessibleobject accessibleobject accessibleobject isaccessible setaccessible isaccessible protected object get interface proxy helper context factory cf class interfaces xxx how to handle interfaces array withclasses from different class loaders using cf get application class loader class loader loader interfaces 0 get class loader class cl proxy get proxy class loader interfaces constructor c try c cl get constructor new class invocation handler class catch no such method exception ex should not happen throw kit init cause new illegal state exception ex return c getinterfaceproxyhelper contextfactory getapplicationclassloader classloader getclassloader getproxyclass getconstructor invocationhandler nosuchmethodexception initcause illegalstateexception protected object new interface proxy object proxy helper final context factory cf final interface adapter adapter final object target final scriptable top scope constructor c constructor proxy helper invocation handler handler new invocation handler public object invoke object proxy method method object args return adapter invoke cf target top scope method args object proxy try proxy c new instance new object handler catch invocation target exception ex throw context throw as script runtime ex ex catch illegal access exception ex shouls not happen throw kit init cause new illegal state exception ex catch instantiation exception ex shouls not happen throw kit init cause new illegal state exception ex return proxy newinterfaceproxy proxyhelper contextfactory interfaceadapter topscope proxyhelper invocationhandler invocationhandler topscope newinstance invocationtargetexception throwasscriptruntimeex illegalaccessexception initcause illegalstateexception instantiationexception initcause illegalstateexception invocation handler handler new invocation handler public object invoke object proxy method method object args return adapter invoke cf target top scope method args invocationhandler invocationhandler topscope public class datatypes 008 extends live connect test public datatypes 008 super datatypes_008 liveconnecttest datatypes_008 public static void main string args datatypes 008 test new datatypes 008 test start datatypes_008 datatypes_008 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 pub static array byte true do array test dt get byte array true do array test dt pub array byte false executetest doarraytest pub_static_array_byte doarraytest getbytearray doarraytest pub_array_byte 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 method call or field reference that returns an array public void do array test string command boolean should equal byte array data type class pub static array byte byte 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 byte 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 var 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_byte jsarray jsarray_length javascript jsarray jsarray jsarray getmember jsarray javascript jsarray_length jsarray intvalue jsarray javascript jsarray_length jsarray addtestcase jsarray jsarray jsarray printstacktrace tostring jsarray_length jsarray jsarray addtestcase jsarray jsarray getmember jsarray jsarray shouldequal jsarray public class tostring 001 extends live connect test public tostring 001 super tostring_001 liveconnecttest tostring_001 public static void main string args tostring 001 test new tostring 001 test start tostring_001 tostring_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 strings js object object data i executetest getdataarray jsobject jsobject getjsobject getstrings jsobject public void get strings js object js object object data string e string string data 2 string result of to string null string result of call null string result of eval null try result of to string js object to string result of call string js object call to string null catch exception e file exception e to string p get strings threw e to string e print stack trace finally add test case js object to string returned js object to string js object to string equals e string true js object to string equals e string file exception add test case calling to string returned result of call js object call to string null equals e string true result of call equals e string file exception getstrings jsobject jsobject estring resultoftostring resultofcall resultofeval resultoftostring jsobject tostring resultofcall jsobject tostring tostring getstrings tostring printstacktrace addtestcase jsobject tostring jsobject tostring jsobject tostring estring jsobject tostring estring addtestcase tostring resultofcall jsobject tostring estring resultofcall estring create and return a js object using data in the data array param data object array containing name of js object and assignment expression return the js object public js object getjs object object data global eval string data 1 js object the this js object global get member string data 0 return the this jsobject jsobject jsobject jsobject getjsobject jsobject thethis jsobject getmember thethis get the data array which is an object array data arrays which are also object arrays the data arrays consist of 8 items ul li identifier for java script object li assignment expression to initialize java script object li expected string value of the object ul to add test cases to this test modify this method return the data array public object get data array object d0 new string o 0 identifier new string var o new object 1 complete expression for instantiation or assignment new string object object object d1 new string num new string num new number 12345 new string 12345 object d2 new string number new string number new number infinity new string infinity object d3 new string string new string string new string java script new string java script object d4 new string array new string array new array 1 2 3 4 5 new string 1 2 3 4 5 object data array d0 d1 d2 d3 d4 return data array javascript javascript getdataarray javascript javascript dataarray dataarray public class run script2 public static void main string args context cx context enter try scriptable scope cx init standard objects add a global variable out that is a java script reflection of system out object js out context java tojs system out scope scriptable object put property scope out js out string s for int i 0 i args length i s args i object result cx evaluate string scope s cmd 1 null system err println cx to string result finally context exit runscript2 initstandardobjects javascript jsout javatojs scriptableobject putproperty jsout evaluatestring tostring no instances should be created protected script runtime scriptruntime public static boolean is rhino runtime type class cl if cl is primitive return cl character type else return cl string class cl boolean class number class is assignable from cl scriptable class is assignable from cl isrhinoruntimetype isprimitive stringclass booleanclass numberclass isassignablefrom scriptableclass isassignablefrom public static scriptable object init standard objects context cx scriptable object scope boolean sealed if scope null scope new native object scope associate value library scope key scope new class cache associate scope base function init scope sealed native object init scope sealed scriptable object proto scriptable object get object prototype scope function prototype proto should be object prototype scriptable function proto scriptable object get function prototype scope function proto set prototype object proto set the prototype of the object passed in if need be if scope get prototype null scope set prototype object proto must precede native global since it s needed therein native error init scope sealed native global init cx scope sealed native array init scope sealed native string init scope sealed native boolean init scope sealed native number init scope sealed native date init scope sealed native math init scope sealed native with init scope sealed native call init scope sealed native script init scope sealed boolean with xml cx has feature context feature e4x for int i 0 i lazily names length i 2 string top property lazily names i string class name lazily names i 1 if with xml class name xml init class continue new lazily loaded ctor scope top property class name sealed continuation init scope sealed return scope scriptableobject initstandardobjects scriptableobject nativeobject associatevalue library_scope_key classcache basefunction nativeobject objectproto scriptableobject getobjectprototype __proto__ functionproto scriptableobject getfunctionprototype functionproto setprototype objectproto getprototype setprototype objectproto nativeglobal nativeerror nativeglobal nativearray nativestring nativeboolean nativenumber nativedate nativemath nativewith nativecall nativescript withxml hasfeature feature_e4x lazilynames topproperty lazilynames classname lazilynames withxml classname xml_init_class lazilyloadedctor topproperty classname public static scriptable object get library scope or null scriptable scope scriptable object lib scope lib scope scriptable object scriptable object get top scope value scope library scope key return lib scope scriptableobject getlibraryscopeornull scriptableobject libscope libscope scriptableobject scriptableobject gettopscopevalue library_scope_key libscope it is public so native reg exp can access it public static boolean isjs line terminator int c optimization for faster check for eol character they do not have 0xdfd0 bits set if c 0xdfd0 0 return false return c n c r c 0x2028 c 0x2029 nativeregexp isjslineterminator public static boolean wrap boolean boolean b return b boolean true boolean false wrapboolean public static integer wrap int int i return new integer i wrapint public static number wrap number double x if x x return script runtime na nobj return new double x wrapnumber scriptruntime nanobj convert the value to a boolean see ecma 9 2 public static boolean to boolean object val for if val instanceof boolean return boolean val boolean value if val null val undefined instance return false if val instanceof string return string val length 0 if val instanceof number double d number val double value return d d d 0 0 if val instanceof scriptable if context get context is versionecma1 pure ecma return true ecma extension val scriptable val get default value boolean class if val instanceof scriptable throw error with class name msg primitive expected val continue warn about nonjs object val return true toboolean booleanvalue doublevalue getcontext isversionecma1 getdefaultvalue booleanclass errorwithclassname warnaboutnonjsobject public static boolean to boolean object args int index return index args length to boolean args index false toboolean toboolean convert the value to a number see ecma 9 3 public static double to number object val for if val instanceof number return number val double value if val null return 0 0 if val undefined instance return nan if val instanceof string return to number string val if val instanceof boolean return boolean val boolean value 1 0 0 if val instanceof scriptable val scriptable val get default value number class if val instanceof scriptable throw error with class name msg primitive expected val continue warn about nonjs object val return nan tonumber doublevalue tonumber booleanvalue getdefaultvalue numberclass errorwithclassname warnaboutnonjsobject public static double to number object args int index return index args length to number args index nan tonumber tonumber static double string to number string s int start int radix char digit max 9 char lower case bound a char upper case bound a int len s length if radix 10 digit max char 0 radix 1 if radix 10 lower case bound char a radix 10 upper case bound char a radix 10 int end double sum 0 0 for end start end len end char c s char at end int new digit if 0 c c digit max new digit c 0 else if a c c lower case bound new digit c a 10 else if a c c upper case bound new digit c a 10 else break sum sum radix new digit if start end return nan if sum 9007199254740992 0 if radix 10 if we re accumulating a decimal number and the number is 2 53 then the result from the repeated multiply add above may be inaccurate call java to get the correct answer try return double value of s substring start end double value catch number format exception nfe return nan else if radix 2 radix 4 radix 8 radix 16 radix 32 the number may also be inaccurate for one of these bases this happens if the addition in value radix digit causes a round down to an even least significant mantissa bit when the first dropped bit is a one if any of the following digits in the number which haven t been added in yet are nonzero then the correct action would have been to round up instead of down an example of this occurs when reading the number 0x1000000000000081 which rounds to 0x1000000000000000 instead of 0x1000000000000100 int bit shift in char 1 int digit 0 final int skip leading zeros 0 final int first exact 53 bits 1 final int after bit 53 2 final int zeros after 54 3 final int mixed after 54 4 int state skip leading zeros int exact bits limit 53 double factor 0 0 boolean bit53 false bit54 is the 54th bit the first dropped from the mantissa boolean bit54 false for if bit shift in char 1 if start end break digit s char at start if 0 digit digit 9 digit 0 else if a digit digit z digit a 10 else digit a 10 bit shift in char radix bit shift in char 1 boolean bit digit bit shift in char 0 switch state case skip leading zeros if bit exact bits limit sum 1 0 state first exact 53 bits break case first exact 53 bits sum 2 0 if bit sum 1 0 exact bits limit if exact bits limit 0 bit53 bit state after bit 53 break case after bit 53 bit54 bit factor 2 0 state zeros after 54 break case zeros after 54 if bit state mixed after 54 fallthrough case mixed after 54 factor 2 break switch state case skip leading zeros sum 0 0 break case first exact 53 bits case after bit 53 do nothing break case zeros after 54 x1 1 x1 1 round up x0 1 x0 round down if bit54 bit53 sum 1 0 sum factor break case mixed after 54 x 100 1 x 1 round up x 0anything x round down if bit54 sum 1 0 sum factor break we don t worry about inaccurate numbers for any other base return sum stringtonumber digitmax lowercasebound uppercasebound digitmax lowercasebound uppercasebound charat newdigit digitmax newdigit lowercasebound newdigit uppercasebound newdigit newdigit valueof doublevalue numberformatexception bitshiftinchar skip_leading_zeros first_exact_53_bits after_bit_53 zeros_after_54 mixed_after_54 skip_leading_zeros exactbitslimit bitshiftinchar charat bitshiftinchar bitshiftinchar bitshiftinchar skip_leading_zeros exactbitslimit first_exact_53_bits first_exact_53_bits exactbitslimit exactbitslimit after_bit_53 after_bit_53 zeros_after_54 zeros_after_54 mixed_after_54 mixed_after_54 skip_leading_zeros first_exact_53_bits after_bit_53 zeros_after_54 mixed_after_54 to number applied to the string type see ecma 9 3 1 public static double to number string s int len s length int start 0 char start char for if start len empty or contains only whitespace return 0 0 start char s char at start if character is whitespace start char break start if start char 0 if start 2 len int c1 s char at start 1 if c1 x c1 x a hexadecimal number return string to number s start 2 16 else if start char start char if start 3 len s char at start 1 0 int c2 s char at start 2 if c2 x c2 x a hexadecimal number with sign double val string to number s start 3 16 return start char val val int end len 1 char end char while character is whitespace end char s char at end end if end char y check for infinity if start char start char start if start 7 end s region matches start infinity 0 8 return start char double negative infinity double positive infinity return nan a non hexadecimal non infinity number just try a normal floating point conversion string sub s substring start end 1 if msjvm bug workarounds the ms jvm will accept non conformant strings rather than throwing a number format exception as it should for int i sub length 1 i 0 i char c sub char at i if 0 c c 9 c c e c e c c continue return nan try return double value of sub double value catch number format exception ex return nan tonumber tonumber startchar startchar charat iswhitespace startchar startchar charat stringtonumber startchar startchar charat charat stringtonumber startchar endchar iswhitespace endchar charat endchar startchar startchar regionmatches startchar negative_infinity positive_infinity msjvm_bug_workarounds numberformatexception charat valueof doublevalue numberformatexception helper function for builtin objects that use the varargs form ecma function formal arguments are undefined if not supplied this function pads the argument array out to the expected length if necessary public static object pad arguments object args int count if count args length return args int i object result new object count for i 0 i args length i result i args i for i count i result i undefined instance return result padarguments private final static boolean msjvm bug workarounds true public static string escape string string s return escape string s msjvm_bug_workarounds escapestring escapestring for escaping strings printed by object and array literals not quite the same as escape public static string escape string string s char escape quote if escape quote escape quote kit code bug string buffer sb null for int i 0 l s length i l i int c s char at i if c c c escape quote c an ordinary print character like c isprint and not or if sb null sb append char c continue if sb null sb new string buffer l 3 sb append s sb set length i int escape 1 switch c case b escape b break case f escape f break case n escape n break case r escape r break case t escape t break case 0xb escape v break java lacks v case escape break case escape break if escape 0 an escaped sort of character sb append sb append char escape else if c escape quote sb append sb append escape quote else int hex size if c 256 2 digit hex sb append x hex size 2 else unicode 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 escapestring escapequote escapequote escapequote codebug stringbuffer charat escapequote stringbuffer setlength escapequote escapequote hexsize hexsize hexsize hexsize tostring static boolean is valid identifier name string s int l s length if l 0 return false if character is java identifier start s char at 0 return false for int i 1 i l i if character is java identifier part s char at i return false return token stream is keyword s isvalididentifiername isjavaidentifierstart charat isjavaidentifierpart charat tokenstream iskeyword convert the value to a string see ecma 9 8 public static string to string object val for if val null return null if val undefined instance return undefined if val instanceof string return string val if val instanceof number xxx should we just teach native number string value about numbers return number to string number val double value 10 if val instanceof scriptable val scriptable val get default value string class if val instanceof scriptable throw error with class name msg primitive expected val continue return val to string tostring nativenumber stringvalue numbertostring doublevalue getdefaultvalue stringclass errorwithclassname tostring static string default object to string scriptable obj return object obj get class name defaultobjecttostring getclassname public static string to string object args int index return index args length to string args index undefined tostring tostring optimized version of to string object for numbers public static string to string double val return number to string val 10 tostring tostring numbertostring public static string number to string double d int base if d d return nan if d double positive infinity return infinity if d double negative infinity return infinity if d 0 0 return 0 if base 2 base 36 throw context report runtime error1 msg bad radix integer to string base if base 10 return d toa js dtobasestr base d else string buffer result new string buffer d toa js dtostr result d toa dtostr standard 0 d return result to string numbertostring positive_infinity negative_infinity reportruntimeerror1 tostring dtoa js_dtobasestr stringbuffer stringbuffer dtoa js_dtostr dtoa dtostr_standard tostring static string uneval context cx scriptable scope object value if value null return null if value undefined instance return undefined if value instanceof string string escaped escape string string value string buffer sb new string buffer escaped length 2 sb append sb append escaped sb append return sb to string if value instanceof number double d number value double value if d 0 1 d 0 return 0 return to string d if value instanceof boolean return to string value if value instanceof scriptable scriptable obj scriptable value object v scriptable object get property obj to source if v instanceof function function f function v return to string f call cx scope obj empty args return to string value warn about nonjs object value return value to string escapestring stringbuffer stringbuffer tostring doublevalue tostring tostring scriptableobject getproperty tosource tostring emptyargs tostring warnaboutnonjsobject tostring static string default object to source context cx scriptable scope scriptable this obj object args boolean toplevel iterating if cx iterating null toplevel true iterating false cx iterating new obj to int map 31 else toplevel false iterating cx iterating has this obj string buffer result new string buffer 128 if toplevel result append result append make sure cx iterating is set to null when done so we don t leak memory try if iterating cx iterating intern this obj stop recursion object ids this obj get ids for int i 0 i ids length i if i 0 result append object id ids i object value if id instanceof integer int int id integer id int value value this obj get int id this obj result append int id else string str id string id value this obj get str id this obj if script runtime is valid identifier name str id result append str id else result append result append script runtime escape string str id result append result append result append script runtime uneval cx scope value finally if toplevel cx iterating null result append if toplevel result append return result to string defaultobjecttosource thisobj objtointmap thisobj stringbuffer stringbuffer thisobj thisobj getids intid intvalue thisobj intid thisobj intid strid thisobj strid thisobj scriptruntime isvalididentifiername strid strid scriptruntime escapestring strid scriptruntime tostring public static scriptable to object scriptable scope object val if val instanceof scriptable return scriptable val return to object context get context scope val toobject toobject getcontext public static scriptable to object or null context cx object obj if obj instanceof scriptable return scriptable obj else if obj null obj undefined instance return to object cx get top call scope cx obj return null toobjectornull toobject gettopcallscope deprecated use link to object scriptable object instead public static scriptable to object scriptable scope object val class static class if val instanceof scriptable return scriptable val return to object context get context scope val toobject toobject staticclass toobject getcontext convert the value to an object see ecma 9 9 public static scriptable to object context cx scriptable scope object val if val instanceof scriptable return scriptable val if val null throw type error0 msg null to object if val undefined instance throw type error0 msg undef to object string class name val instanceof string string val instanceof number number val instanceof boolean boolean null if class name null object args val scope scriptable object get top level scope scope return new object cx scope class name args extension wrap as a live connect object object wrapped cx get wrap factory wrap cx scope val null if wrapped instanceof scriptable return scriptable wrapped throw error with class name msg invalid type val toobject typeerror0 typeerror0 classname classname scriptableobject gettoplevelscope newobject classname liveconnect getwrapfactory errorwithclassname deprecated use link to object context scriptable object instead public static scriptable to object context cx scriptable scope object val class static class return to object cx scope val toobject toobject staticclass toobject deprecated the method is only present for compatibility public static object call context cx object fun object this arg object args scriptable scope if fun instanceof function throw not function error to string fun function function function fun scriptable this obj to object or null cx this arg if this obj null throw undef call error this obj function return function call cx scope this obj args thisarg notfunctionerror tostring thisobj toobjectornull thisarg thisobj undefcallerror thisobj thisobj public static scriptable new object context cx scriptable scope string constructor name object args scope scriptable object get top level scope scope function ctor get existing ctor cx scope constructor name if args null args script runtime empty args return ctor construct cx scope args newobject constructorname scriptableobject gettoplevelscope getexistingctor constructorname scriptruntime emptyargs see ecma 9 4 public static double to integer object val return to integer to number val tointeger tointeger tonumber convenience method public static double to integer double d if it s nan if d d return 0 0 if d 0 0 d double positive infinity d double negative infinity return d if d 0 0 return math floor d else return math ceil d tointeger positive_infinity negative_infinity public static double to integer object args int index return index args length to integer args index 0 0 tointeger tointeger see ecma 9 5 public static int to int32 object val short circuit for common integer values if val instanceof integer return integer val int value return to int32 to number val toint32 intvalue toint32 tonumber public static int to int32 object args int index return index args length to int32 args index 0 toint32 toint32 public static int to int32 double d int id int d if id d this covers 0 0 as well return id if d d d double positive infinity d double negative infinity return 0 d d 0 math floor d math ceil d double two32 4294967296 0 d math iee eremainder d two32 double long d d should hold here long l long d returning int d does not work as d can be outside int range but the result must always be 32 lower bits of l return int l toint32 positive_infinity negative_infinity ieeeremainder see ecma 9 6 return long value representing 32 bits unsigned integer public static long to uint32 double d long l long d if l d this covers 0 0 as well return l 0xffffffffl if d d d double positive infinity d double negative infinity return 0 d d 0 math floor d math ceil d 0x100000000 gives me a numeric overflow double two32 4294967296 0 l long math iee eremainder d two32 return l 0xffffffffl touint32 positive_infinity negative_infinity ieeeremainder public static long to uint32 object val return to uint32 to number val touint32 touint32 tonumber see ecma 9 7 public static char to uint16 object val double d to number val int i int d if i d return char i if d d d double positive infinity d double negative infinity return 0 d d 0 math floor d math ceil d int int16 0x10000 i int math iee eremainder d int16 return char i touint16 tonumber positive_infinity negative_infinity ieeeremainder public static object set default namespace object namespace context cx scriptable scope cx current activation call if scope null scope get top call scope cx xml lib xml lib currentxml lib cx object ns xml lib to default xml namespace cx namespace xxx this should be in separated namesapce from scriptable get put if scope has default ns tag scope xxx this is racy of cause scriptable object define property scope default ns tag ns scriptable object permanent scriptable object dontenum else scope put default ns tag scope ns return undefined instance setdefaultnamespace currentactivationcall gettopcallscope xmllib xmllib currentxmllib xmllib todefaultxmlnamespace default_ns_tag scriptableobject defineproperty default_ns_tag scriptableobject scriptableobject default_ns_tag public static object search default namespace context cx scriptable scope cx current activation call if scope null scope get top call scope cx object ns object for scriptable parent scope get parent scope if parent null ns object scriptable object get property scope default ns tag if ns object scriptable not found return null break ns object scope get default ns tag scope if ns object scriptable not found break scope parent return ns object searchdefaultnamespace currentactivationcall gettopcallscope nsobject getparentscope nsobject scriptableobject getproperty default_ns_tag nsobject not_found nsobject default_ns_tag nsobject not_found nsobject public static object get top level prop scriptable scope string id scope scriptable object get top level scope scope return scriptable object get property scope id gettoplevelprop scriptableobject gettoplevelscope scriptableobject getproperty static function get existing ctor context cx scriptable scope string constructor name object ctor val scriptable object get property scope constructor name if ctor val instanceof function return function ctor val if ctor val scriptable not found throw context report runtime error1 msg ctor not found constructor name else throw context report runtime error1 msg not ctor constructor name getexistingctor constructorname ctorval scriptableobject getproperty constructorname ctorval ctorval ctorval not_found reportruntimeerror1 constructorname reportruntimeerror1 constructorname return 1l if str is not an index or the index value as lower 32 bits of the result private static long index from string string str the length of the decimal string representation of integer max value 2147483647 final int max value length 10 int len str length if len 0 int i 0 boolean negate false int c str char at 0 if c if len 1 c str char at 1 i 1 negate true c 0 if 0 c c 9 len negate max value length 1 max value length use negative numbers to accumulate index to handle integer min value that is greater by 1 in absolute value then integer max value int index c int old index 0 i if index 0 note that 00 01 000 etc are not indexes while i len 0 c str char at i 0 c 9 old index index index 10 index c i make sure all characters were consumed and that it couldn t have overflowed if i len old index integer min value 10 old index integer min value 10 c negate integer min value 10 integer max value 10 return 0xffffffffl negate index index return 1l indexfromstring max_value max_value_length charat charat max_value_length max_value_length min_value max_value oldindex charat oldindex oldindex min_value oldindex min_value min_value max_value if str is a decimal presentation of uint32 value return it as long othewise return 1l public static long test uint32 string string str the length of the decimal string representation of uint32 max value 4294967296 final int max value length 10 int len str length if 1 len len max value length int c str char at 0 c 0 if c 0 note that 00 01 etc are not valid uint32 presentations return len 1 0l 1l if 1 c c 9 long v c for int i 1 i len i c str char at i 0 if 0 c c 9 return 1 v 10 v c check for overflow if v 32 0 return v return 1 testuint32string uint32_max_value max_value_length max_value_length charat charat if s represents index then return index value wrapped as integer and othewise return s static object get index object string s long index test index from string s if index test 0 return new integer int index test return s getindexobject indextest indexfromstring indextest indextest if d is exact int value return its value wrapped as integer and othewise return d converted to string static object get index object double d int i int d if double i d return new integer int i return to string d getindexobject tostring if to string id is a decimal presentation of int32 value then id is index in this case return null and make the index available as script runtime last index result cx otherwise return to string id static string to string id or index context cx object id if id instanceof number double d number id double value int index int d if double index d store index result cx index return null return to string id else string s if id instanceof string s string id else s to string id long index test index from string s if index test 0 store index result cx int index test return null return s tostring scriptruntime lastindexresult tostring tostringidorindex doublevalue storeindexresult tostring tostring indextest indexfromstring indextest storeindexresult indextest call obj get id public static object get object elem object obj object elem context cx scriptable sobj to object or null cx obj if sobj null throw undef read error obj elem return get object elem sobj elem cx getobjectelem toobjectornull undefreaderror getobjectelem public static object get object elem scriptable obj object elem context cx if obj instanceof xml object xml object xml object xml object obj return xml object ecma get cx elem object result string s to string id or index cx elem if s null int index last index result cx result scriptable object get property obj index else result scriptable object get property obj s if result scriptable not found result undefined instance return result getobjectelem xmlobject xmlobject xmlobject xmlobject xmlobject ecmaget tostringidorindex lastindexresult scriptableobject getproperty scriptableobject getproperty not_found version of get object elem when elem is a valid js identifier name public static object get object prop object obj string property context cx scriptable sobj to object or null cx obj if sobj null throw undef read error obj property return get object prop sobj property cx getobjectelem getobjectprop toobjectornull undefreaderror getobjectprop public static object get object prop scriptable obj string property context cx if obj instanceof xml object xml object xml object xml object obj return xml object ecma get cx property object result scriptable object get property obj property if result scriptable not found result undefined instance return result getobjectprop xmlobject xmlobject xmlobject xmlobject xmlobject ecmaget scriptableobject getproperty not_found public static object get object index object obj double dbl index context cx scriptable sobj to object or null cx obj if sobj null throw undef read error obj to string dbl index int index int dbl index if double index dbl index return get object index sobj index cx else string s to string dbl index return get object prop sobj s cx getobjectindex dblindex toobjectornull undefreaderror tostring dblindex dblindex dblindex getobjectindex tostring dblindex getobjectprop public static object get object index scriptable obj int index context cx if obj instanceof xml object xml object xml object xml object obj return xml object ecma get cx new integer index object result scriptable object get property obj index if result scriptable not found result undefined instance return result getobjectindex xmlobject xmlobject xmlobject xmlobject xmlobject ecmaget scriptableobject getproperty not_found public static object set object elem object obj object elem object value context cx scriptable sobj to object or null cx obj if sobj null throw undef write error obj elem value return set object elem sobj elem value cx setobjectelem toobjectornull undefwriteerror setobjectelem public static object set object elem scriptable obj object elem object value context cx if obj instanceof xml object xml object xml object xml object obj xml object ecma put cx elem value return value string s to string id or index cx elem if s null int index last index result cx scriptable object put property obj index value else scriptable object put property obj s value return value setobjectelem xmlobject xmlobject xmlobject xmlobject xmlobject ecmaput tostringidorindex lastindexresult scriptableobject putproperty scriptableobject putproperty version of set object elem when elem is a valid js identifier name public static object set object prop object obj string property object value context cx scriptable sobj to object or null cx obj if sobj null throw undef write error obj property value return set object prop sobj property value cx setobjectelem setobjectprop toobjectornull undefwriteerror setobjectprop public static object set object prop scriptable obj string property object value context cx if obj instanceof xml object xml object xml object xml object obj xml object ecma put cx property value else scriptable object put property obj property value return value setobjectprop xmlobject xmlobject xmlobject xmlobject xmlobject ecmaput scriptableobject putproperty public static object set object index object obj double dbl index object value context cx scriptable sobj to object or null cx obj if sobj null throw undef write error obj string value of dbl index value int index int dbl index if double index dbl index return set object index sobj index value cx else string s to string dbl index return set object prop sobj s value cx setobjectindex dblindex toobjectornull undefwriteerror valueof dblindex dblindex dblindex setobjectindex tostring dblindex setobjectprop public static object set object index scriptable obj int index object value context cx if obj instanceof xml object xml object xml object xml object obj xml object ecma put cx new integer index value else scriptable object put property obj index value return value setobjectindex xmlobject xmlobject xmlobject xmlobject xmlobject ecmaput scriptableobject putproperty public static boolean delete object elem scriptable target object elem context cx boolean result if target instanceof xml object xml object xml object xml object target result xml object ecma delete cx elem else string s to string id or index cx elem if s null int index last index result cx result scriptable object delete property target index else result scriptable object delete property target s return result deleteobjectelem xmlobject xmlobject xmlobject xmlobject xmlobject ecmadelete tostringidorindex lastindexresult scriptableobject deleteproperty scriptableobject deleteproperty public static boolean has object elem scriptable target object elem context cx boolean result if target instanceof xml object xml object xml object xml object target result xml object ecma has cx elem else string s to string id or index cx elem if s null int index last index result cx result scriptable object has property target index else result scriptable object has property target s return result hasobjectelem xmlobject xmlobject xmlobject xmlobject xmlobject ecmahas tostringidorindex lastindexresult scriptableobject hasproperty scriptableobject hasproperty public static object ref get ref ref context cx return ref get cx refget public static object ref set ref ref object value context cx return ref set cx value refset public static object ref del ref ref context cx return wrap boolean ref delete cx refdel wrapboolean static boolean is special property string s return s equals proto s equals parent isspecialproperty __proto__ __parent__ public static ref special ref object obj string special property context cx return special ref create special cx obj special property specialref specialproperty specialref createspecial specialproperty the delete operator see ecma 11 4 1 in ecma 0 19 the description of the delete operator 11 4 1 assumes that the delete method returns a value however the definition of the delete operator 8 6 2 5 does not define a return value here we assume that the delete method doesn t return a value public static object delete object obj object id context cx scriptable sobj to object or null cx obj if sobj null string id str id null null id to string throw type error2 msg undef prop delete to string obj id str boolean result delete object elem sobj id cx return wrap boolean result toobjectornull idstr tostring typeerror2 tostring idstr deleteobjectelem wrapboolean looks up a name in the scope chain and returns its value public static object name context cx scriptable scope string name scriptable parent scope get parent scope if parent null object result top scope name cx scope name if result scriptable not found throw not found error scope name return result return name or function cx scope parent name false getparentscope topscopename not_found notfounderror nameorfunction private static object name or function context cx scriptable scope scriptable parent scope string name boolean as function call object result scriptable this obj scope it is used only if as function call true xml object firstxml object null for if scope instanceof native with scriptable with obj scope get prototype if with obj instanceof xml object xml object xml obj xml object with obj if xml obj ecma has cx name function this should be the target object of with this obj xml obj result xml obj ecma get cx name break if firstxml object null firstxml object xml obj else result scriptable object get property with obj name if result scriptable not found function this should be the target object of with this obj with obj break else if scope instanceof native call native call does not prototype chain and scriptable get can be called directly result scope get name scope if result scriptable not found if as function call ecma 262 requires that this for nested funtions should be top scope this obj scriptable object get top level scope parent scope break else can happen if rhino embedding decided that nested scopes are useful for what ever reasons result scriptable object get property scope name if result scriptable not found this obj scope break scope parent scope parent scope parent scope get parent scope if parent scope null result top scope name cx scope name if result scriptable not found if firstxml object null as function call throw not found error scope name the name was not found but we did find an xml object in the scope chain and we are looking for name not function the result should be an empty xml list in name context result firstxml object ecma get cx name for top scope this obj for functions is always scope itself this obj scope break if as function call if result instanceof callable throw not function error result name store scriptable cx this obj return result nameorfunction parentscope asfunctioncall thisobj asfunctioncall xmlobject firstxmlobject nativewith withobj getprototype withobj xmlobject xmlobject xmlobj xmlobject withobj xmlobj ecmahas thisobj xmlobj xmlobj ecmaget firstxmlobject firstxmlobject xmlobj scriptableobject getproperty withobj not_found thisobj withobj nativecall nativecall not_found asfunctioncall thisobj scriptableobject gettoplevelscope parentscope scriptableobject getproperty not_found thisobj parentscope parentscope parentscope getparentscope parentscope topscopename not_found firstxmlobject asfunctioncall notfounderror xmllist firstxmlobject ecmaget thisobj thisobj asfunctioncall notfunctionerror storescriptable thisobj private static object top scope name context cx scriptable scope string name if cx use dynamic scope scope check dynamic scope cx top call scope scope return scriptable object get property scope name topscopename usedynamicscope checkdynamicscope topcallscope scriptableobject getproperty returns the object in the scope chain that has a given property the order of evaluation of an assignment expression involves evaluating the lhs to a reference evaluating the rhs and then modifying the reference with the rhs value this method is used to bind the given name to an object containing that property so that the side effects of evaluating the rhs do not affect which property is modified typically used in conjunction with set name see ecma 10 1 4 public static scriptable bind context cx scriptable scope string id scriptable firstxml object null scriptable parent scope get parent scope child scopes checks if parent null check for possibly nested with scopes first while scope instanceof native with scriptable with obj scope get prototype if with obj instanceof xml object xml object xml object xml object with obj if xml object ecma has cx id return xml object if firstxml object null firstxml object xml object else if scriptable object has property with obj id return with obj scope parent parent parent get parent scope if parent null break child scopes checks for if scriptable object has property scope id return scope scope parent parent parent get parent scope if parent null break child scopes checks scope here is top scope if cx use dynamic scope scope check dynamic scope cx top call scope scope if scriptable object has property scope id return scope nothing was found but since xml objects always bind return one if found return firstxml object setname firstxmlobject getparentscope childscopeschecks nativewith withobj getprototype withobj xmlobject xmlobject xmlobject xmlobject withobj xmlobject ecmahas xmlobject firstxmlobject firstxmlobject xmlobject scriptableobject hasproperty withobj withobj getparentscope childscopeschecks scriptableobject hasproperty getparentscope childscopeschecks usedynamicscope checkdynamicscope topcallscope scriptableobject hasproperty firstxmlobject public static object set name scriptable bound object value context cx scriptable scope string id if bound null if bound instanceof xml object xml object xml object xml object bound xml object ecma put cx id value else scriptable object put property bound id value else newname 7 where newname has not yet been defined creates a new property in the top scope unless strict mode is specified if cx has feature context feature strict vars throw context report runtime error1 msg assn create strict id find the top scope by walking up the scope chain bound scriptable object get top level scope scope if cx use dynamic scope bound check dynamic scope cx top call scope bound bound put id bound value return value setname xmlobject xmlobject xmlobject xmlobject xmlobject ecmaput scriptableobject putproperty hasfeature feature_strict_vars reportruntimeerror1 scriptableobject gettoplevelscope usedynamicscope checkdynamicscope topcallscope public static object enum init object value context cx boolean enum values id enumeration x new id enumeration x obj to object or null cx value if x obj null null or undefined do not cause errors but rather lead to empty for in loop x enum values enum values enum init should read all initial ids before returning or for a i in a would wrongly enumerate i in a as well enum change object x return x enuminit enumvalues idenumeration idenumeration toobjectornull enumvalues enumvalues enuminit enumchangeobject public static boolean enum next object enum obj opt this could be more efficient boolean result id enumeration x id enumeration enum obj for if x obj null result false break if x index x ids length x obj x obj get prototype enum change object x continue object id x ids x index if x used null x used has id continue if id instanceof string string str id string id if x obj has str id x obj continue must have been deleted x current id str id else int int id number id int value if x obj has int id x obj continue must have been deleted x current id string value of int id result true break return wrap boolean result enumnext enumobj idenumeration idenumeration enumobj getprototype enumchangeobject strid strid currentid strid intid intvalue intid currentid valueof intid wrapboolean public static object enum id object enum obj context cx id enumeration x id enumeration enum obj if x enum values return x current id object result string s to string id or index cx x current id if s null int index last index result cx result x obj get index x obj else result x obj get s x obj return result enumid enumobj idenumeration idenumeration enumobj enumvalues currentid tostringidorindex currentid lastindexresult private static void enum change object id enumeration x object ids null while x obj null ids x obj get ids if ids length 0 break x obj x obj get prototype if x obj null x ids null object previous x ids int l previous length if x used null x used new obj to int map l for int i 0 i l i x used intern previous i x ids ids x index 0 enumchangeobject idenumeration getids getprototype objtointmap prepare for calling name return function corresponding to name and make current top scope available as script runtime last stored scriptable for consumption as this obj the caller must call script runtime last stored scriptable immediately after calling this method public static callable get name function and this string name context cx scriptable scope scriptable parent scope get parent scope if parent null object result top scope name cx scope name if result instanceof callable if result scriptable not found throw not found error scope name else throw not function error result name top scope is not native with or native call this obj scope scriptable this obj scope store scriptable cx this obj return callable result name will call store scriptable cx this obj return callable name or function cx scope parent name true scriptruntime laststoredscriptable thisobj scriptruntime laststoredscriptable getnamefunctionandthis getparentscope topscopename not_found notfounderror notfunctionerror nativewith nativecall thisobj thisobj storescriptable thisobj storescriptable thisobj nameorfunction prepare for calling obj id return function corresponding to obj id and make obj properly converted to scriptable available as script runtime last stored scriptable for consumption as this obj the caller must call script runtime last stored scriptable immediately after calling this method public static callable get elem function and this object obj object elem context cx string s to string id or index cx elem if s null return get prop function and this obj s cx int index last index result cx scriptable this obj to object or null cx obj if this obj null throw undef call error obj string value of index object value for ignore xml lookup as requred by ecma 357 11 2 2 1 value scriptable object get property this obj index if value scriptable not found break if this obj instanceof xml object break xml object xml object xml object this obj scriptable extra xml object get extra method source cx if extra null break this obj extra if value instanceof callable throw not function error value elem store scriptable cx this obj return callable value scriptruntime laststoredscriptable thisobj scriptruntime laststoredscriptable getelemfunctionandthis tostringidorindex getpropfunctionandthis lastindexresult thisobj toobjectornull thisobj undefcallerror valueof scriptableobject getproperty thisobj not_found thisobj xmlobject xmlobject xmlobject xmlobject thisobj xmlobject getextramethodsource thisobj notfunctionerror storescriptable thisobj prepare for calling obj property return function corresponding to obj property and make obj properly converted to scriptable available as script runtime last stored scriptable for consumption as this obj the caller must call script runtime last stored scriptable immediately after calling this method public static callable get prop function and this object obj string property context cx scriptable this obj to object or null cx obj if this obj null throw undef call error obj property object value for ignore xml lookup as requred by ecma 357 11 2 2 1 value scriptable object get property this obj property if value scriptable not found break if this obj instanceof xml object break xml object xml object xml object this obj scriptable extra xml object get extra method source cx if extra null break this obj extra if value instanceof callable throw not function error value property store scriptable cx this obj return callable value scriptruntime laststoredscriptable thisobj scriptruntime laststoredscriptable getpropfunctionandthis thisobj toobjectornull thisobj undefcallerror scriptableobject getproperty thisobj not_found thisobj xmlobject xmlobject xmlobject xmlobject thisobj xmlobject getextramethodsource thisobj notfunctionerror storescriptable thisobj prepare for calling expression return function corresponding to expression and make parent scope of the function available as script runtime last stored scriptable for consumption as this obj the caller must call script runtime last stored scriptable immediately after calling this method public static callable get value function and this object value context cx if value instanceof callable throw not function error value callable f callable value scriptable this obj if f instanceof scriptable this obj scriptable f get parent scope else if cx top call scope null throw new illegal state exception this obj cx top call scope if this obj get parent scope null if this obj instanceof native with functions defined inside with should have with target as their this obj else if this obj instanceof native call nested functions should have top scope as their this obj this obj scriptable object get top level scope this obj store scriptable cx this obj return f scriptruntime laststoredscriptable thisobj scriptruntime laststoredscriptable getvaluefunctionandthis notfunctionerror thisobj thisobj getparentscope topcallscope illegalstateexception thisobj topcallscope thisobj getparentscope thisobj nativewith thisobj thisobj nativecall thisobj thisobj scriptableobject gettoplevelscope thisobj storescriptable thisobj perform function call in reference context should always return value that can be passed to link ref get object or link ref set object object arbitrary number of times the args array reference should not be stored in any object that is can be gc reachable after this method returns if this is necessary store args clone not args array itself public static ref call ref callable function scriptable this obj object args context cx if function instanceof ref callable ref callable rfunction ref callable function ref ref rfunction ref call cx this obj args if ref null throw new illegal state exception rfunction get class get name ref call returned null return ref no runtime support for now string msg get message1 msg no ref from function to string function throw construct error reference error msg refget refset callref thisobj refcallable refcallable refcallable refcall thisobj illegalstateexception getclass getname refcall getmessage1 tostring constructerror referenceerror operator new see ecma 11 2 2 public static scriptable new object object fun context cx scriptable scope object args if fun instanceof function throw not function error fun function function function fun return function construct cx scope args newobject notfunctionerror public static object call special context cx callable fun scriptable this obj object args scriptable scope scriptable caller this int call type string filename int line number if call type node specialcall eval if native global is eval function fun return eval special cx scope caller this args filename line number else if call type node specialcall with if native with is with function fun throw context report runtime error1 msg only from new with else throw kit code bug return fun call cx scope this obj args callspecial thisobj callerthis calltype linenumber calltype specialcall_eval nativeglobal isevalfunction evalspecial callerthis linenumber calltype specialcall_with nativewith iswithfunction reportruntimeerror1 codebug thisobj public static object new special context cx object fun object args scriptable scope int call type if call type node specialcall eval if native global is eval function fun throw type error1 msg not ctor eval else if call type node specialcall with if native with is with function fun return native with new with special cx scope args else throw kit code bug return new object fun cx scope args newspecial calltype calltype specialcall_eval nativeglobal isevalfunction typeerror1 calltype specialcall_with nativewith iswithfunction nativewith newwithspecial codebug newobject function prototype apply and function prototype call see ecma 15 3 4 34 public static object apply or call boolean is apply context cx scriptable scope scriptable this obj object args int l args length callable function if this obj instanceof callable function callable this obj else object value this obj get default value script runtime function class if value instanceof callable throw script runtime not function error value this obj function callable value scriptable call this null if l 0 call this to object or null cx args 0 if call this null this covers the case of args 0 null undefined as well call this get top call scope cx object call args if is apply follow ecma 15 3 4 3 if l 1 call args script runtime empty args else object arg1 args 1 if arg1 null arg1 undefined instance call args script runtime empty args else if arg1 instanceof native array arg1 instanceof arguments call args cx get elements scriptable arg1 else throw script runtime type error0 msg arg isnt array else follow ecma 15 3 4 4 if l 1 call args script runtime empty args else call args new object l 1 system arraycopy args 1 call args 0 l 1 return function call cx scope call this call args applyorcall isapply thisobj thisobj thisobj thisobj getdefaultvalue scriptruntime functionclass scriptruntime notfunctionerror thisobj callthis callthis toobjectornull callthis callthis gettopcallscope callargs isapply callargs scriptruntime emptyargs callargs scriptruntime emptyargs nativearray callargs getelements scriptruntime typeerror0 callargs scriptruntime emptyargs callargs callargs callthis callargs the eval function property of the global object see ecma 15 1 2 1 public static object eval special context cx scriptable scope object this arg object args string filename int line number if args length 1 return undefined instance object x args 0 if x instanceof string if cx has feature context feature strict eval throw context report runtime error0 msg eval nonstring strict string message script runtime get message0 msg eval nonstring context report warning message return x if filename null int linep new int 1 filename context get source position from stack linep if filename null line number linep 0 else filename string source name script runtime make url for generated script true filename line number error reporter reporter reporter default error reporter for eval cx get error reporter compile with explicit interpreter instance to force interpreter mode script script cx compile string string x new interpreter reporter source name 1 null interpreted function script idata eval script flag true callable c callable script return c call cx scope scriptable this arg script runtime empty args evalspecial thisarg linenumber hasfeature feature_strict_eval reportruntimeerror0 scriptruntime getmessage0 reportwarning getsourcepositionfromstack linenumber sourcename scriptruntime makeurlforgeneratedscript linenumber errorreporter defaulterrorreporter foreval geterrorreporter compilestring sourcename interpretedfunction evalscriptflag thisarg scriptruntime emptyargs the typeof operator public static string typeof object value if value null return object if value undefined instance return undefined if value instanceof scriptable if value instanceof xml object return xml return value instanceof callable function object if value instanceof string return string if value instanceof number return number if value instanceof boolean return boolean throw error with class name msg invalid type value xmlobject errorwithclassname the typeof operator that correctly handles the undefined case public static string typeof name scriptable scope string id context cx context get context scriptable val bind cx scope id if val null return undefined return typeof get object prop val id cx typeofname getcontext getobjectprop public static object add object val1 object val2 context cx if val1 instanceof number val2 instanceof number return wrap number number val1 double value number val2 double value if val1 instanceof xml object object test xml object val1 add values cx true val2 if test scriptable not found return test if val2 instanceof xml object object test xml object val2 add values cx false val1 if test scriptable not found return test if val1 instanceof scriptable val1 scriptable val1 get default value null if val2 instanceof scriptable val2 scriptable val2 get default value null if val1 instanceof string val2 instanceof string if val1 instanceof number val2 instanceof number return wrap number number val1 double value number val2 double value else return wrap number to number val1 to number val2 return to string val1 concat to string val2 wrapnumber doublevalue doublevalue xmlobject xmlobject addvalues not_found xmlobject xmlobject addvalues not_found getdefaultvalue getdefaultvalue wrapnumber doublevalue doublevalue wrapnumber tonumber tonumber tostring tostring public static object name incr decr scriptable scope chain string id int incr decr mask scriptable target object value search do target scope chain do value target get id scope chain if value scriptable not found break search target target get prototype while target null scope chain scope chain get parent scope while scope chain null throw not found error scope chain id return do scriptable incr decr target id scope chain value incr decr mask nameincrdecr scopechain incrdecrmask scopechain scopechain not_found getprototype scopechain scopechain getparentscope scopechain notfounderror scopechain doscriptableincrdecr scopechain incrdecrmask public static object prop incr decr object obj string id context cx int incr decr mask scriptable start to object or null cx obj if start null throw undef read error obj id scriptable target start object value search do value target get id start if value scriptable not found break search target target get prototype while target null start put id start na nobj return na nobj return do scriptable incr decr target id start value incr decr mask propincrdecr incrdecrmask toobjectornull undefreaderror not_found getprototype nanobj nanobj doscriptableincrdecr incrdecrmask private static object do scriptable incr decr scriptable target string id scriptable proto chain start object value int incr decr mask boolean post incr decr mask node post flag 0 double number if value instanceof number number number value double value else number to number value if post convert result to number value wrap number number if incr decr mask node decr flag 0 number else number number result wrap number number target put id proto chain start result if post return value else return result doscriptableincrdecr protochainstart incrdecrmask incrdecrmask post_flag doublevalue tonumber wrapnumber incrdecrmask decr_flag wrapnumber protochainstart public static object elem incr decr object obj object index context cx int incr decr mask object value get object elem obj index cx boolean post incr decr mask node post flag 0 double number if value instanceof number number number value double value else number to number value if post convert result to number value wrap number number if incr decr mask node decr flag 0 number else number number result wrap number number set object elem obj index result cx if post return value else return result elemincrdecr incrdecrmask getobjectelem incrdecrmask post_flag doublevalue tonumber wrapnumber incrdecrmask decr_flag wrapnumber setobjectelem public static object ref incr decr ref ref context cx int incr decr mask object value ref get cx boolean post incr decr mask node post flag 0 double number if value instanceof number number number value double value else number to number value if post convert result to number value wrap number number if incr decr mask node decr flag 0 number else number number result wrap number number ref set cx result if post return value else return result refincrdecr incrdecrmask incrdecrmask post_flag doublevalue tonumber wrapnumber incrdecrmask decr_flag wrapnumber private static object to primitive object val if val instanceof scriptable return val scriptable s scriptable val object result s get default value null if result instanceof scriptable throw type error0 msg bad default value return result toprimitive getdefaultvalue typeerror0 equality see ecma 11 9 public static boolean eq object x object y if x null x undefined instance if y null y undefined instance return true if y instanceof scriptable object object test scriptable object y equivalent values x if test scriptable not found return boolean test boolean value return false else if x instanceof number return eq number number x double value y else if x instanceof string return eq string string x y else if x instanceof boolean boolean b boolean x boolean value if y instanceof boolean return b boolean y boolean value if y instanceof scriptable object object test scriptable object y equivalent values x if test scriptable not found return boolean test boolean value return eq number b 1 0 0 0 y else if x instanceof scriptable if y instanceof scriptable if x y return true if x instanceof scriptable object object test scriptable object x equivalent values y if test scriptable not found return boolean test boolean value if y instanceof scriptable object object test scriptable object y equivalent values x if test scriptable not found return boolean test boolean value if x instanceof wrapper y instanceof wrapper return wrapper x unwrap wrapper y unwrap return false else if y instanceof boolean if x instanceof scriptable object object test scriptable object x equivalent values y if test scriptable not found return boolean test boolean value double d boolean y boolean value 1 0 0 0 return eq number d x else if y instanceof number return eq number number y double value x else if y instanceof string return eq string string y x covers the case when y undefined instance as well return false else warn about nonjs object x return x y scriptableobject scriptableobject equivalentvalues not_found booleanvalue eqnumber doublevalue eqstring booleanvalue booleanvalue scriptableobject scriptableobject equivalentvalues not_found booleanvalue eqnumber scriptableobject scriptableobject equivalentvalues not_found booleanvalue scriptableobject scriptableobject equivalentvalues not_found booleanvalue scriptableobject scriptableobject equivalentvalues not_found booleanvalue booleanvalue eqnumber eqnumber doublevalue eqstring warnaboutnonjsobject static boolean eq number double x object y for if y null y undefined instance return false else if y instanceof number return x number y double value else if y instanceof string return x to number y else if y instanceof boolean return x boolean y boolean value 1 0 0 0 else if y instanceof scriptable if y instanceof scriptable object object xval wrap number x object test scriptable object y equivalent values xval if test scriptable not found return boolean test boolean value y to primitive y else warn about nonjs object y return false eqnumber doublevalue tonumber booleanvalue scriptableobject wrapnumber scriptableobject equivalentvalues not_found booleanvalue toprimitive warnaboutnonjsobject private static boolean eq string string x object y for if y null y undefined instance return false else if y instanceof string return x equals y else if y instanceof number return to number x number y double value else if y instanceof boolean return to number x boolean y boolean value 1 0 0 0 else if y instanceof scriptable if y instanceof scriptable object object test scriptable object y equivalent values x if test scriptable not found return boolean test boolean value y to primitive y continue else warn about nonjs object y return false eqstring tonumber doublevalue tonumber booleanvalue scriptableobject scriptableobject equivalentvalues not_found booleanvalue toprimitive warnaboutnonjsobject public static boolean shallow eq object x object y if x y if x instanceof number return true nan check double d number x double value return d d if x null x undefined instance return false else if x instanceof number if y instanceof number return number x double value number y double value else if x instanceof string if y instanceof string return x equals y else if x instanceof boolean if y instanceof boolean return x equals y else if x instanceof scriptable if x instanceof wrapper y instanceof wrapper return wrapper x unwrap wrapper y unwrap else warn about nonjs object x return x y return false shalloweq doublevalue doublevalue doublevalue warnaboutnonjsobject the instanceof operator return a instanceof b public static boolean instance of object a object b context cx check rhs is an object if b instanceof scriptable throw type error0 msg instanceof not object for primitive values on lhs return false xxx we may want to change this so that 5 instanceof number true if a instanceof scriptable return false return scriptable b has instance scriptable a instanceof typeerror0 hasinstance delegates to return true iff rhs appears in lhs proto chain protected static boolean js delegates to scriptable lhs scriptable rhs scriptable proto lhs get prototype while proto null if proto equals rhs return true proto proto get prototype return false jsdelegatesto getprototype getprototype the in operator this is a new js 1 3 language feature the in operator mirrors the operation of the for in construct and tests whether the rhs has the property given by the lhs it is different from the for in construct in that br it doesn t perform to object on the right hand side br it returns true for dont enum properties param a the left hand operand param b the right hand operand return true if property name or element number a is a property of b public static boolean in object a object b context cx if b instanceof scriptable throw type error0 msg instanceof not object return has object elem scriptable b a cx toobject dontenum typeerror0 hasobjectelem public static boolean cmp lt object val1 object val2 double d1 d2 if val1 instanceof number val2 instanceof number d1 number val1 double value d2 number val2 double value else if val1 instanceof scriptable val1 scriptable val1 get default value number class if val2 instanceof scriptable val2 scriptable val2 get default value number class if val1 instanceof string val2 instanceof string return string val1 compare to string val2 0 d1 to number val1 d2 to number val2 return d1 d2 cmp_lt doublevalue doublevalue getdefaultvalue numberclass getdefaultvalue numberclass compareto tonumber tonumber public static boolean cmp le object val1 object val2 double d1 d2 if val1 instanceof number val2 instanceof number d1 number val1 double value d2 number val2 double value else if val1 instanceof scriptable val1 scriptable val1 get default value number class if val2 instanceof scriptable val2 scriptable val2 get default value number class if val1 instanceof string val2 instanceof string return string val1 compare to string val2 0 d1 to number val1 d2 to number val2 return d1 d2 cmp_le doublevalue doublevalue getdefaultvalue numberclass getdefaultvalue numberclass compareto tonumber tonumber public static scriptable object get global context cx final string global class org mozilla javascript tools shell global class global class kit class or null global class if global class null try class parm script runtime context class constructor global class ctor global class get constructor parm object arg cx return scriptable object global class ctor new instance arg catch exception e fall through return new importer top level cx scriptableobject getglobal global_class globalclass classornull global_class globalclass scriptruntime contextclass globalclassctor globalclass getconstructor scriptableobject globalclassctor newinstance importertoplevel public static boolean has top call context cx return cx top call scope null hastopcall topcallscope public static scriptable get top call scope context cx scriptable scope cx top call scope if scope null throw new illegal state exception return scope gettopcallscope topcallscope illegalstateexception public static object do top call callable callable context cx scriptable scope scriptable this obj object args if scope null throw new illegal argument exception if cx top call scope null throw new illegal state exception object result cx top call scope scriptable object get top level scope scope cx use dynamic scope cx has feature context feature dynamic scope context factory f cx get factory try result f do top call callable cx scope this obj args finally cx top call scope null cleanup cached references cx cachedxml lib null if cx current activation call null function should always call exit activation function if it creates activation record throw new illegal state exception return result dotopcall thisobj illegalargumentexception topcallscope illegalstateexception topcallscope scriptableobject gettoplevelscope usedynamicscope hasfeature feature_dynamic_scope contextfactory getfactory dotopcall thisobj topcallscope cachedxmllib currentactivationcall exitactivationfunction illegalstateexception return tt possible dynamic scope tt if tt static top scope tt is present on its prototype chain and return tt static top scope tt otherwise should only be called when tt static top scope tt is top scope static scriptable check dynamic scope scriptable possible dynamic scope scriptable static top scope return cx top call scope if scope if possible dynamic scope static top scope return possible dynamic scope scriptable proto possible dynamic scope for proto proto get prototype if proto static top scope return possible dynamic scope if proto null return static top scope possibledynamicscope statictopscope statictopscope statictopscope checkdynamicscope possibledynamicscope statictopscope topcallscope possibledynamicscope statictopscope possibledynamicscope possibledynamicscope getprototype statictopscope possibledynamicscope statictopscope public static void init script native function fun obj scriptable this obj context cx scriptable scope boolean eval script if cx top call scope null throw new illegal state exception int var count fun obj get param and var count if var count 0 scriptable var scope scope never define any variables from var statements inside with object see bug 38590 while var scope instanceof native with var scope var scope get parent scope for int i var count i 0 string name fun obj get param or var name i don t overwrite existing def if already defined in object or prototypes of object if scriptable object has property scope name if eval script global var definitions are supposed to be dontdelete scriptable object define property var scope name undefined instance scriptable object permanent else var scope put name var scope undefined instance initscript nativefunction funobj thisobj evalscript topcallscope illegalstateexception varcount funobj getparamandvarcount varcount varscope varscope nativewith varscope varscope getparentscope varcount funobj getparamorvarname scriptableobject hasproperty evalscript scriptableobject defineproperty varscope scriptableobject varscope varscope public static scriptable create function activation native function fun obj scriptable scope object args return new native call fun obj scope args createfunctionactivation nativefunction funobj nativecall funobj public static void enter activation function context cx scriptable activation if cx top call scope null throw new illegal state exception native call call native call activation call parent activation call cx current activation call cx current activation call call enteractivationfunction topcallscope illegalstateexception nativecall nativecall parentactivationcall currentactivationcall currentactivationcall public static void exit activation function context cx native call call cx current activation call cx current activation call call parent activation call call parent activation call null exitactivationfunction nativecall currentactivationcall currentactivationcall parentactivationcall parentactivationcall static native call find function activation context cx function f native call call cx current activation call while call null if call function f return call call call parent activation call return null nativecall findfunctionactivation nativecall currentactivationcall parentactivationcall public static scriptable new catch scope throwable t scriptable last catch scope string exception name context cx scriptable scope object obj boolean cache obj get obj if t instanceof java script exception cache obj false obj java script exception t get value else cache obj true create wrapper object unless it was associated with the previous scope object if last catch scope null native object last native object last catch scope obj last get associated value t if obj null kit code bug break get obj rhino exception re string error name string error msg throwable java exception null if t instanceof ecma error ecma error ee ecma error t re ee error name ee get name error msg ee get error message else if t instanceof wrapped exception wrapped exception we wrapped exception t re we java exception we get wrapped exception error name java exception error msg java exception get class get name java exception get message else if t instanceof evaluator exception pure evaluator exception nor wrapped exception instance evaluator exception ee evaluator exception t re ee error name internal error error msg ee get message else script can catch only instances of java script exception ecma error and evaluator exception throw kit code bug string source uri re source name if source uri null source uri int line re line number object args if line 0 args new object error msg source uri new integer line else args new object error msg source uri scriptable error object cx new object scope error name args scriptable object put property error object name error name if java exception null object wrap cx get wrap factory wrap cx scope java exception null scriptable object define property error object java exception wrap scriptable object permanent scriptable object readonly if re null object wrap cx get wrap factory wrap cx scope re null scriptable object define property error object rhino exception wrap scriptable object permanent scriptable object readonly obj error object native object catch scope object new native object see ecma 12 4 catch scope object define property exception name obj scriptable object permanent if cache obj catch scope object associate value t obj return catch scope object newcatchscope lastcatchscope exceptionname cacheobj getobj javascriptexception cacheobj javascriptexception getvalue cacheobj lastcatchscope nativeobject nativeobject lastcatchscope getassociatedvalue codebug getobj rhinoexception errorname errormsg javaexception ecmaerror ecmaerror ecmaerror errorname getname errormsg geterrormessage wrappedexception wrappedexception wrappedexception javaexception getwrappedexception errorname javaexception errormsg javaexception getclass getname javaexception getmessage evaluatorexception wrappedexception evaluatorexception evaluatorexception errorname internalerror errormsg getmessage javascriptexception ecmaerror evaluatorexception codebug sourceuri sourcename sourceuri sourceuri linenumber errormsg sourceuri errormsg sourceuri errorobject newobject errorname scriptableobject putproperty errorobject errorname javaexception getwrapfactory javaexception scriptableobject defineproperty errorobject javaexception scriptableobject scriptableobject getwrapfactory scriptableobject defineproperty errorobject rhinoexception scriptableobject scriptableobject errorobject nativeobject catchscopeobject nativeobject catchscopeobject defineproperty exceptionname scriptableobject cacheobj catchscopeobject associatevalue catchscopeobject public static scriptable enter with object obj context cx scriptable scope scriptable sobj to object or null cx obj if sobj null throw type error1 msg undef with to string obj if sobj instanceof xml object xml object xml object xml object sobj return xml object enter with scope return new native with scope sobj enterwith toobjectornull typeerror1 tostring xmlobject xmlobject xmlobject xmlobject xmlobject enterwith nativewith public static scriptable leave with scriptable scope native with nw native with scope return nw get parent scope leavewith nativewith nativewith getparentscope public static scriptable enter dot query object value scriptable scope if value instanceof xml object throw not xml error value xml object object xml object value return object enter dot query scope enterdotquery xmlobject notxmlerror xmlobject xmlobject enterdotquery public static object update dot query boolean value scriptable scope return null to continue looping native with nw native with scope return nw update dot query value updatedotquery nativewith nativewith updatedotquery public static scriptable leave dot query scriptable scope native with nw native with scope return nw get parent scope leavedotquery nativewith nativewith getparentscope public static void set function proto and parent base function fn scriptable scope fn set parent scope scope fn set prototype scriptable object get function prototype scope setfunctionprotoandparent basefunction setparentscope setprototype scriptableobject getfunctionprototype public static void set object proto and parent scriptable object object scriptable scope compared with function it always sets the scope to top scope scope scriptable object get top level scope scope object set parent scope scope scriptable proto scriptable object get class prototype scope object get class name object set prototype proto setobjectprotoandparent scriptableobject scriptableobject gettoplevelscope setparentscope scriptableobject getclassprototype getclassname setprototype public static void init function context cx scriptable scope native function function int type boolean from eval code if type function node function statement string name function get function name if name null name length 0 if from eval code ecma specifies that functions defined in global and function scope outside eval should have dontdelete set scriptable object define property scope name function scriptable object permanent else scope put name scope function else if type function node function expression statement string name function get function name if name null name length 0 always put function expression statements into initial activation object ignoring the with statement to follow spider monkey while scope instanceof native with scope scope get parent scope scope put name scope function else throw kit code bug initfunction nativefunction fromevalcode functionnode function_statement getfunctionname fromevalcode scriptableobject defineproperty scriptableobject functionnode function_expression_statement getfunctionname spidermonkey nativewith getparentscope codebug public static scriptable new array literal object objects int skip indexces context cx scriptable scope int count objects length int skip count 0 if skip indexces null skip count skip indexces length int length count skip count integer length obj new integer length scriptable array obj if the version is 120 then new array 4 means create a new array with 4 as the first element in this case we have to set length property manually if cx get language version context version 1 2 array obj cx new object scope array script runtime empty args scriptable object put property array obj length length obj else array obj cx new object scope array new object length obj int skip 0 for int i 0 j 0 i length i if skip skip count skip indexces skip i skip continue scriptable object put property array obj i objects j j return array obj newarrayliteral skipindexces skipcount skipindexces skipcount skipindexces skipcount lengthobj arrayobj getlanguageversion version_1_2 arrayobj newobject scriptruntime emptyargs scriptableobject putproperty arrayobj lengthobj arrayobj newobject lengthobj skipcount skipindexces scriptableobject putproperty arrayobj arrayobj public static scriptable new object literal object property ids object property values context cx scriptable scope scriptable object cx new object scope for int i 0 end property ids length i end i object id property ids i object value property values i if id instanceof string scriptable object put property object string id value else int index integer id int value scriptable object put property object index value return object newobjectliteral propertyids propertyvalues newobject propertyids propertyids propertyvalues scriptableobject putproperty intvalue scriptableobject putproperty public static boolean is array object object obj return obj instanceof native array obj instanceof arguments isarrayobject nativearray public static object get array elements scriptable object context cx context get context long long len native array get length property cx object if long len integer max value arrays beyond max int is not in java in any case throw new illegal argument exception int len int long len if len 0 return script runtime empty args else object result new object len for int i 0 i len i object elem scriptable object get property object i result i elem scriptable not found undefined instance elem return result getarrayelements getcontext longlen nativearray getlengthproperty longlen max_value max_int illegalargumentexception longlen scriptruntime emptyargs scriptableobject getproperty not_found static void check deprecated context cx string name int version cx get language version if version context version 1 4 version context version default string msg get message1 msg deprec ctor name if version context version default context report warning msg else throw context report runtime error msg checkdeprecated getlanguageversion version_1_4 version_default getmessage1 version_default reportwarning reportruntimeerror public static string get message0 string message id return get message message id null getmessage0 messageid getmessage messageid public static string get message1 string message id object arg1 object arguments arg1 return get message message id arguments getmessage1 messageid getmessage messageid public static string get message2 string message id object arg1 object arg2 object arguments arg1 arg2 return get message message id arguments getmessage2 messageid getmessage messageid public static string get message3 string message id object arg1 object arg2 object arg3 object arguments arg1 arg2 arg3 return get message message id arguments getmessage3 messageid getmessage messageid public static string get message4 string message id object arg1 object arg2 object arg3 object arg4 object arguments arg1 arg2 arg3 arg4 return get message message id arguments getmessage4 messageid getmessage messageid public static string get message string message id object arguments final string default resource org mozilla javascript resources messages context cx context get current context locale locale cx null cx get locale locale get default resource bundle does cacheing resource bundle rb resource bundle get bundle default resource 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 it s ok to format the string even if arguments is null we need to format it anyway to make double s collapse to single s todo message format is not available on p java message format formatter new message format format string return formatter format arguments getmessage messageid defaultresource getcurrentcontext getlocale getdefault resourcebundle resourcebundle resourcebundle getbundle defaultresource formatstring formatstring getstring messageid missingresourceexception runtimeexception messageid messageformat pjava messageformat messageformat formatstring public static ecma error construct error string error string message int linep new int 1 string filename context get source position from stack linep return construct error error message filename linep 0 null 0 ecmaerror constructerror getsourcepositionfromstack constructerror public static ecma error construct error string error string message string source name int line number string line source int column number return new ecma error error message source name line number line source column number ecmaerror constructerror sourcename linenumber linesource columnnumber ecmaerror sourcename linenumber linesource columnnumber public static ecma error type error string message return construct error type error message ecmaerror typeerror constructerror typeerror public static ecma error type error0 string message id string msg get message0 message id return type error msg ecmaerror typeerror0 messageid getmessage0 messageid typeerror public static ecma error type error1 string message id string arg1 string msg get message1 message id arg1 return type error msg ecmaerror typeerror1 messageid getmessage1 messageid typeerror public static ecma error type error2 string message id string arg1 string arg2 string msg get message2 message id arg1 arg2 return type error msg ecmaerror typeerror2 messageid getmessage2 messageid typeerror public static ecma error type error3 string message id string arg1 string arg2 string arg3 string msg get message3 message id arg1 arg2 arg3 return type error msg ecmaerror typeerror3 messageid getmessage3 messageid typeerror public static runtime exception undef read error object object object id string id str id null null id to string return type error2 msg undef prop read to string object id str runtimeexception undefreaderror idstr tostring typeerror2 tostring idstr public static runtime exception undef call error object object object id string id str id null null id to string return type error2 msg undef method call to string object id str runtimeexception undefcallerror idstr tostring typeerror2 tostring idstr public static runtime exception undef write error object object object id object value string id str id null null id to string string value str value instanceof scriptable value to string to string value return type error3 msg undef prop write to string object id str value str runtimeexception undefwriteerror idstr tostring valuestr tostring tostring typeerror3 tostring idstr valuestr public static runtime exception not found error scriptable object string property xxx use object to improve the error message string msg get message1 msg is not defined property throw construct error reference error msg runtimeexception notfounderror getmessage1 constructerror referenceerror public static runtime exception not function error object value return not function error value value runtimeexception notfunctionerror notfunctionerror public static runtime exception not function error object value object message helper xxx use value for better error reporting string msg message helper null null message helper to string if value scriptable not found return type error1 msg function not found msg return type error2 msg isnt function msg value null null value get class get name runtimeexception notfunctionerror messagehelper messagehelper messagehelper tostring not_found typeerror1 typeerror2 getclass getname private static runtime exception not xml error object value throw type error1 msg isnt xml object script runtime to string value runtimeexception notxmlerror typeerror1 scriptruntime tostring private static void warn about nonjs object object nonjs object string message rhino usage warning missed context java tojs conversion n rhino runtime detected object nonjs object of class nonjs object get class get name where it expected string number boolean or scriptable instance please check your code for missing context java tojs call context report warning message just to be sure that it would be noticed system err println message warnaboutnonjsobject nonjsobject javatojs nonjsobject nonjsobject getclass getname javatojs reportwarning public static reg exp proxy get reg exp proxy context cx return cx get reg exp proxy regexpproxy getregexpproxy getregexpproxy public static void set reg exp proxy context cx reg exp proxy proxy if proxy null throw new illegal argument exception cx reg exp proxy proxy setregexpproxy regexpproxy illegalargumentexception regexpproxy public static reg exp proxy check reg exp proxy context cx reg exp proxy result get reg exp proxy cx if result null throw context report runtime error0 msg no regexp return result regexpproxy checkregexpproxy regexpproxy getregexpproxy reportruntimeerror0 private static xml lib currentxml lib context cx scripts should be running to access this if cx top call scope null throw new illegal state exception xml lib xml lib cx cachedxml lib if xml lib null xml lib xml lib extract from scope cx top call scope if xml lib null throw new illegal state exception cx cachedxml lib xml lib return xml lib xmllib currentxmllib topcallscope illegalstateexception xmllib xmllib cachedxmllib xmllib xmllib xmllib extractfromscope topcallscope xmllib illegalstateexception cachedxmllib xmllib xmllib escapes the reserved characters in a value of an attribute param value unescaped text return the escaped text public static string escape attribute value object value context cx xml lib xml lib currentxml lib cx return xml lib escape attribute value value escapeattributevalue xmllib xmllib currentxmllib xmllib escapeattributevalue escapes the reserved characters in a value of a text node param value unescaped text return the escaped text public static string escape text value object value context cx xml lib xml lib currentxml lib cx return xml lib escape text value value escapetextvalue xmllib xmllib currentxmllib xmllib escapetextvalue public static ref member ref object obj object elem context cx int member type flags if obj instanceof xml object throw not xml error obj xml object xml object xml object obj return xml object member ref cx elem member type flags memberref membertypeflags xmlobject notxmlerror xmlobject xmlobject xmlobject xmlobject memberref membertypeflags public static ref member ref object obj object namespace object elem context cx int member type flags if obj instanceof xml object throw not xml error obj xml object xml object xml object obj return xml object member ref cx namespace elem member type flags memberref membertypeflags xmlobject notxmlerror xmlobject xmlobject xmlobject xmlobject memberref membertypeflags public static ref name ref object name context cx scriptable scope int member type flags xml lib xml lib currentxml lib cx return xml lib name ref cx name scope member type flags nameref membertypeflags xmllib xmllib currentxmllib xmllib nameref membertypeflags public static ref name ref object namespace object name context cx scriptable scope int member type flags xml lib xml lib currentxml lib cx return xml lib name ref cx namespace name scope member type flags nameref membertypeflags xmllib xmllib currentxmllib xmllib nameref membertypeflags private static void store index result context cx int index cx scratch index index storeindexresult scratchindex static int last index result context cx return cx scratch index lastindexresult scratchindex public static void store uint32 result context cx long value if value 32 0 throw new illegal argument exception cx scratch uint32 value storeuint32result illegalargumentexception scratchuint32 public static long last uint32 result context cx long value cx scratch uint32 if value 32 0 throw new illegal state exception return value lastuint32result scratchuint32 illegalstateexception private static void store scriptable context cx scriptable value the previosly stored scratch scriptable should be consumed if cx scratch scriptable null throw new illegal state exception cx scratch scriptable value storescriptable scratchscriptable scratchscriptable illegalstateexception scratchscriptable public static scriptable last stored scriptable context cx scriptable result cx scratch scriptable cx scratch scriptable null return result laststoredscriptable scratchscriptable scratchscriptable static string make url for generated script boolean is eval string master script url int master script line if is eval return master script url master script line eval else return master script url master script line function makeurlforgeneratedscript iseval masterscripturl masterscriptline iseval masterscripturl masterscriptline masterscripturl masterscriptline static boolean is generated script string source url alert this may clash with a valid url containing eval or function return source url index of eval 0 source url index of function 0 isgeneratedscript sourceurl sourceurl indexof sourceurl indexof private static runtime exception error with class name string msg object val return context report runtime error1 msg val get class get name runtimeexception errorwithclassname reportruntimeerror1 getclass getname implements generated class loader public defining class loader this parent loader get class get class loader generatedclassloader definingclassloader parentloader getclass getclassloader public defining class loader class loader parent loader this parent loader parent loader definingclassloader classloader parentloader parentloader parentloader public class define class string name byte data return super define class name data 0 data length defineclass defineclass public void link class class cl resolve class cl linkclass resolveclass public class load class string name boolean resolve throws class not found exception class cl find loaded class name if cl null if parent loader null cl parent loader load class name else cl find system class name if resolve resolve class cl return cl loadclass classnotfoundexception findloadedclass parentloader parentloader loadclass findsystemclass resolveclass 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 class datatypes 018 extends live connect test public datatypes 018 super datatypes_018 liveconnecttest datatypes_018 public static void main string args datatypes 018 test new datatypes 018 test start datatypes_018 datatypes_018 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 301981 p bugnumber file bugnumber setuptestenvironment setuptestenvironment datatypeclass public void execute test p executing test string expected field value field string expected method value method string actual field value string actual method value string ambiguous reference amia field ora method try from java script call the setter actual field value string global eval dt ambiguous reference actual method value string global eval dt ambiguous reference catch exception e e print stack trace file exception e to string actual field value actual method value add test case dt ambiguous reference expected field value actual field value file exception add test case dt ambiguous reference expected method value actual method value file exception executetest expectedfieldvalue expectedmethodvalue actualfieldvalue actualmethodvalue ambiguousreference amiafieldoramethod javascript actualfieldvalue ambiguousreference actualmethodvalue ambiguousreference printstacktrace tostring actualfieldvalue actualmethodvalue addtestcase ambiguousreference expectedfieldvalue actualfieldvalue addtestcase ambiguousreference expectedmethodvalue actualmethodvalue public class data type class constructor stuff public data type class pub int constructor arg constructor arg none datatypeclass datatypeclass pub_int_constructor_arg constructor_arg_none instance setters public data type class boolean b pub int constructor arg constructor arg boolean datatypeclass pub_int_constructor_arg constructor_arg_boolean pub int constructor arg constructor arg boolean public data type class boolean b pub int constructor arg constructor arg boolean object pub_int_constructor_arg constructor_arg_boolean datatypeclass pub_int_constructor_arg constructor_arg_boolean_object pub int constructor arg constructor arg boolean object public data type class byte b pub int constructor arg constructor arg byte pub_int_constructor_arg constructor_arg_boolean_object datatypeclass pub_int_constructor_arg constructor_arg_byte pub int constructor arg constructor arg byte public data type class byte b pub int constructor arg constructor arg byte object pub_int_constructor_arg constructor_arg_byte datatypeclass pub_int_constructor_arg constructor_arg_byte_object pub int constructor arg constructor arg byte object public data type class integer i pub int constructor arg constructor arg integer object pub_int_constructor_arg constructor_arg_byte_object datatypeclass pub_int_constructor_arg constructor_arg_integer_object pub int constructor arg constructor arg integer object public data type class int i pub int constructor arg constructor arg int pub_int_constructor_arg constructor_arg_integer_object datatypeclass pub_int_constructor_arg constructor_arg_int pub int constructor arg constructor arg int public data type class double d pub int constructor arg constructor arg double object pub_int_constructor_arg constructor_arg_int datatypeclass pub_int_constructor_arg constructor_arg_double_object pub int constructor arg constructor arg double object public data type class double d pub int constructor arg constructor arg double pub_int_constructor_arg constructor_arg_double_object datatypeclass pub_int_constructor_arg constructor_arg_double pub int constructor arg constructor arg double public data type class float f pub int constructor arg constructor arg float object pub_int_constructor_arg constructor_arg_double datatypeclass pub_int_constructor_arg constructor_arg_float_object pub int constructor arg constructor arg float object public data type class float f pub int constructor arg constructor arg float pub_int_constructor_arg constructor_arg_float_object datatypeclass pub_int_constructor_arg constructor_arg_float pub int constructor arg constructor arg float public data type class long l pub int constructor arg constructor arg long object pub_int_constructor_arg constructor_arg_float datatypeclass pub_int_constructor_arg constructor_arg_long_object pub int constructor arg constructor arg long object public data type class long l pub int constructor arg constructor arg long pub_int_constructor_arg constructor_arg_long_object datatypeclass pub_int_constructor_arg constructor_arg_long pub int constructor arg constructor arg long public data type class short s pub int constructor arg constructor arg short object pub_int_constructor_arg constructor_arg_long datatypeclass pub_int_constructor_arg constructor_arg_short_object pub int constructor arg constructor arg short object public data type class short s pub int constructor arg constructor arg short pub_int_constructor_arg constructor_arg_short_object datatypeclass pub_int_constructor_arg constructor_arg_short pub int constructor arg constructor arg short public data type class string s pub int constructor arg constructor arg string pub_int_constructor_arg constructor_arg_short datatypeclass pub_int_constructor_arg constructor_arg_string pub int constructor arg constructor arg string public data type class object o pub int constructor arg constructor arg object pub_int_constructor_arg constructor_arg_string datatypeclass pub_int_constructor_arg constructor_arg_object pub int constructor arg constructor arg object public data type class char c pub int constructor arg constructor arg char pub_int_constructor_arg constructor_arg_object datatypeclass pub_int_constructor_arg constructor_arg_char pub int constructor arg constructor arg char public data type class character c pub int constructor arg constructor arg char object pub_int_constructor_arg constructor_arg_char datatypeclass pub_int_constructor_arg constructor_arg_char_object pub int constructor arg constructor arg char object public data type class byte b pub int constructor arg constructor arg byte array pub_int_constructor_arg constructor_arg_char_object datatypeclass pub_int_constructor_arg constructor_arg_byte_array 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 public boolean boolean value return pub boolean representation booleanvalue pub_boolean_representation override to string public string to string return pub string representation tostring tostring pub_string_representation have a method that has the same name as a field public string amia field ora method return method amiafieldoramethod public string amia field ora method field public static boolean static get boolean return pub static boolean amiafieldoramethod staticgetboolean pub_static_boolean return pub static boolean public static boolean static get boolean object return pub static boolean object pub_static_boolean staticgetbooleanobject pub_static_boolean_object public static byte static get byte return pub static byte staticgetbyte pub_static_byte return pub static byte public static byte static get byte object return pub static byte object pub_static_byte staticgetbyteobject pub_static_byte_object public static integer static get integer object return pub static integer object staticgetintegerobject pub_static_integer_object return pub static integer object public static int static get integer return new integer pub static int int value pub_static_integer_object staticgetinteger pub_static_int intvalue public static double static get double object return pub static double object staticgetdoubleobject pub_static_double_object public static double static get double return new double pub static double double value staticgetdouble pub_static_double doublevalue public static float static get float object return pub static float object staticgetfloatobject pub_static_float_object public static float static get float return new float pub static float float value staticgetfloat pub_static_float floatvalue public static long static get long object return pub static long object staticgetlongobject pub_static_long_object public static long static get long return new long pub static long long value staticgetlong pub_static_long longvalue public static short static get short object return pub static short object staticgetshortobject pub_static_short_object public static short static get short return new short pub static short short value staticgetshort pub_static_short shortvalue public static string static get string object return pub static string staticgetstringobject pub_static_string public static char static get char return pub static char staticgetchar pub_static_char public static character static get character return pub static char object staticgetcharacter pub_static_char_object instance getters public boolean get boolean return pub boolean getboolean pub_boolean return pub boolean public boolean get boolean object return pub boolean object pub_boolean getbooleanobject pub_boolean_object public byte get byte return pub byte getbyte pub_byte return pub byte public byte get byte object return pub byte object pub_byte getbyteobject pub_byte_object public integer get integer object return pub integer object getintegerobject pub_integer_object return pub integer object public int get integer return new integer pub int int value pub_integer_object getinteger pub_int intvalue public double get double object return pub double object getdoubleobject pub_double_object public double get double return new double pub double double value getdouble pub_double doublevalue public float get float object return pub float object getfloatobject pub_float_object public float get float return new float pub float float value getfloat pub_float floatvalue public long get long object return pub long object getlongobject pub_long_object public long get long return new long pub long long value getlong pub_long longvalue public string get string object return pub string getstringobject pub_string public object get object return pub object getobject pub_object public short get short object return pub short object getshortobject pub_short_object public short get short return new short pub short short value getshort pub_short shortvalue public char get char return pub char getchar pub_char public character get character return pub char object getcharacter pub_char_object setters public static void static set boolean boolean b pub static boolean b staticsetboolean pub_static_boolean pub static boolean b public static void static set boolean object boolean b pub static boolean object b pub_static_boolean staticsetbooleanobject pub_static_boolean_object public static void static set byte byte b pub static byte b staticsetbyte pub_static_byte pub static byte b public static void static set byte object byte b pub static byte object b pub_static_byte staticsetbyteobject pub_static_byte_object public static void static set integer object integer i pub static integer object i staticsetintegerobject pub_static_integer_object pub static integer object i public static void static set integer int i pub static int i pub_static_integer_object staticsetinteger pub_static_int public static void static set double object double d pub static double object d staticsetdoubleobject pub_static_double_object public static void static set double double d pub static double d staticsetdouble pub_static_double public static void static set float object float f pub static float object f staticsetfloatobject pub_static_float_object public static void static set float float f pub static float f staticsetfloat pub_static_float public static void static set long object long l pub static long object l staticsetlongobject pub_static_long_object public static void static set long long l pub static long l staticsetlong pub_static_long public static void static set short object short s pub static short object s staticsetshortobject pub_static_short_object public static void static set short short s pub static short s staticsetshort pub_static_short public static void static set string object string s pub static string s staticsetstringobject pub_static_string public static void static set char char c pub static char c staticsetchar pub_static_char public static void static set character character c pub static char object c staticsetcharacter pub_static_char_object instance setters public void set boolean boolean b pub boolean b setboolean pub_boolean pub boolean b public void set boolean object boolean b pub boolean object b pub_boolean setbooleanobject pub_boolean_object public void set byte byte b pub byte b setbyte pub_byte pub byte b public void set byte object byte b pub byte object b pub_byte setbyteobject pub_byte_object public void set integer object integer i pub integer object i setintegerobject pub_integer_object pub integer object i public void set integer int i pub int i pub_integer_object setinteger pub_int public void set double object double d pub double object d setdoubleobject pub_double_object public void set double double d pub double d setdouble pub_double public void set float object float f pub float object f setfloatobject pub_float_object public void set float float f pub float f setfloat pub_float public void set long object long l pub long object l setlongobject pub_long_object public void set long long l pub long l setlong pub_long public void set short object short s pub short object s setshortobject pub_short_object public void set short short s pub short s setshort pub_short public void set string object string s pub string s setstringobject pub_string public void set object object o pub object o setobject pub_object public void set char char c pub char c setchar pub_char public void set character character c pub char object c setcharacter pub_char_object public class pub class pub static final class public class instance get class return pub class pub_class pub_static_final_class instancegetclass pub_class return pub class public void set class class c pub class c pub_class setclass pub_class pub class c public class static get class return pub static class pub_class staticgetclass pub_static_class return pub static class public void static set class class c pub static class c pub_static_class staticsetclass pub_static_class static arrays public static byte static get byte array return pub static array byte staticgetbytearray pub_static_array_byte return pub static array byte public static char static get char array return pub static array char pub_static_array_byte staticgetchararray pub_static_array_char return pub static array char public static double static get double array return pub static array double pub_static_array_char staticgetdoublearray pub_static_array_double return pub static array double public static short static get short array return pub static array short pub_static_array_double staticgetshortarray pub_static_array_short return pub static array short public static long static get long array return pub static array long pub_static_array_short staticgetlongarray pub_static_array_long return pub static array long public static int static get int array return pub static array int pub_static_array_long staticgetintarray pub_static_array_int return pub static array int public static float static get float array return pub static array float pub_static_array_int staticgetfloatarray pub_static_array_float return pub static array float public static object static get object array return pub static array object pub_static_array_float staticgetobjectarray pub_static_array_object instance arrays public byte get byte array return pub static array byte getbytearray pub_static_array_byte return pub static array byte public char get char array return pub static array char pub_static_array_byte getchararray pub_static_array_char return pub static array char public double get double array return pub static array double pub_static_array_char getdoublearray pub_static_array_double return pub static array double public short get short array return pub static array short pub_static_array_double getshortarray pub_static_array_short return pub static array short public long get long array return pub static array long pub_static_array_short getlongarray pub_static_array_long return pub static array long public int get int array return pub static array int pub_static_array_long getintarray pub_static_array_int return pub static array int public float get float array return pub static array float pub_static_array_int getfloatarray pub_static_array_float return pub static array float public object get object array return pub static array object pub_static_array_float getobjectarray pub_static_array_object instance array setters public void set byte array byte b pub static array byte b setbytearray pub_static_array_byte pub static array byte b public void set char array char c pub static array char c pub_static_array_byte setchararray pub_static_array_char pub static array char c public void set double array double d pub static array double d pub_static_array_char setdoublearray pub_static_array_double pub static array double d public void set short array short s pub static array short s pub_static_array_double setshortarray pub_static_array_short pub static array short s public void set long array long l pub static array long l pub_static_array_short setlongarray pub_static_array_long pub static array long l public void set int array int i pub static array int i pub_static_array_long setintarray pub_static_array_int pub static array int i public void set float array float f pub static array float f pub_static_array_int setfloatarray pub_static_array_float pub static array float f public void set object array object o pub static array object o pub_static_array_float setobjectarray pub_static_array_object constructor a new nav env public nav env test file f test suite s nav drv d this file f this suite s this driver d this opener js object js object get window d this window null this window name js get random window name navenv navenv testfile testsuite navdrv jsobject jsobject getwindow window_name getrandomwindowname called by nav drv to run the current test file public synchronized void run test int i 0 system out println file name try create context file start time driver get current time system out println i execute test file system out println i if evaluated successfully system out println i parse result system out println i file end time driver get current time catch exception e suite passed false file passed false file exception file failed with exception e navdrv testfile runtest createcontext starttime getcurrenttime executetestfile evaluatedsuccessfully parseresult endtime getcurrenttime creates a new java script context in this case a navigator window and returns the js object associated with that window public object create context system out println opening window opener eval window name window open window name window js object opener get member window name return window javascript jsobject createcontext window_name window_name jsobject getmember window_name open the current test file in the window by using live connect to set the window s location href property to a url where the test file can be found public object execute test file system out println execute test file try location js object window get member location system out println file name string s driver http path suite name file name location set member href driver http path suite name file name evaluated successfully wait for completion catch exception e system err println file name failed with exception e file exception e to string if file name ends with n js this file passed true evaluated successfully true else this file passed false this suite passed false evaluated successfully false return null testfile liveconnect testfile executetestfile executetestfile jsobject getmember http_path setmember http_path evaluatedsuccessfully waitforcompletion tostring endswith evaluatedsuccessfully evaluatedsuccessfully checks the value of the variable completed which is set by the stop test function in each test if the stop test function is not called in 20 seconds the test fails negative tests will still succeed since the onerror handler should call the stop test function public boolean wait for completion int counter 0 if window get member completed to string equals true while window get member completed to string equals true try if counter 20 file passed false file exception test failed to complete system out println test failed to complete return false system out println driver sleep 1000 counter catch exception e system out println sleep failed e return false return true stoptest stoptest stoptest waitforcompletion getmember tostring getmember tostring use live connect to get the navigator window s testcases property which is defined in all tests parse the testcases array and create a new test case object for each test case object it finds public synchronized boolean parse result try js object testcases js object window get member testcases file total cases number js object testcases get member length int value system out println testcases length is file total cases for int i 0 i file total cases i js object tc js object js object testcases get slot i test case nc new test case tc get member passed null null tc get member passed to string tc get member name null null tc get member name to string tc get member description null null tc get member description to string tc get member expect null null tc get member expect to string tc get member actual null null tc get member actual to string tc get member reason null null tc get member reason to string file case vector add element nc if nc passed equals false if file name ends with n js this file passed true else this file passed false this suite passed false catch exception e system out println e file exception e to string if file name ends with n html file passed true else file passed false suite passed false if the file failed try to get the file s bugnumber if this file passed false try this file bugnumber window get member bugnumber to string catch exception e do nothing return true liveconnect testcase testcase parseresult jsobject jsobject getmember totalcases jsobject getmember intvalue totalcases totalcases jsobject jsobject jsobject getslot testcase testcase getmember getmember tostring getmember getmember tostring getmember getmember tostring getmember getmember tostring getmember getmember tostring getmember getmember tostring casevector addelement endswith tostring endswith getmember tostring close navigator window public void close opener eval window name close opener eval delete window name window_name window_name generate a random window name so that each test is associated with a unique window public string get random window name return integer to string new double math random 100000 int value getrandomwindowname tostring intvalue create a delegator prototype this constructor should only be used for creating prototype objects of delegator see org mozilla javascript delegator construct public delegator create a new delegator that forwards requests to a delegee scriptable object param obj the delegee see org mozilla javascript scriptable public delegator scriptable obj this obj obj crete new delegator instance the default implementation calls this get class new instance see construct context cx scriptable scope object args protected delegator new instance try return delegator this get class new instance catch exception ex throw context throw as script runtime ex ex getclass newinstance newinstance getclass newinstance throwasscriptruntimeex retrieve the delegee return the delegee public scriptable get delegee return obj getdelegee set the delegee param obj the delegee see org mozilla javascript scriptable public void set delegee scriptable obj this obj obj setdelegee see org mozilla javascript scriptable get class name public string get class name return obj get class name getclassname getclassname getclassname see org mozilla javascript scriptable get public object get string name scriptable start return obj get name start see org mozilla javascript scriptable get public object get int index scriptable start return obj get index start see org mozilla javascript scriptable has public boolean has string name scriptable start return obj has name start see org mozilla javascript scriptable has public boolean has int index scriptable start return obj has index start see org mozilla javascript scriptable put public void put string name scriptable start object value obj put name start value see org mozilla javascript scriptable put public void put int index scriptable start object value obj put index start value see org mozilla javascript scriptable delete public void delete string name obj delete name see org mozilla javascript scriptable delete public void delete int index obj delete index see org mozilla javascript scriptable get prototype public scriptable get prototype return obj get prototype getprototype getprototype getprototype see org mozilla javascript scriptable set prototype public void set prototype scriptable prototype obj set prototype prototype setprototype setprototype setprototype see org mozilla javascript scriptable get parent scope public scriptable get parent scope return obj get parent scope getparentscope getparentscope getparentscope see org mozilla javascript scriptable set parent scope public void set parent scope scriptable parent obj set parent scope parent setparentscope setparentscope setparentscope see org mozilla javascript scriptable get ids public object get ids return obj get ids getids getids getids note that this method does not get forwarded to the delegee if the code hint code parameter is null code script runtime scriptable class code or code script runtime function class code instead the object itself is returned param hint the type hint return the default value see org mozilla javascript scriptable get default value public object get default value class hint return hint null hint script runtime scriptable class hint script runtime function class this obj get default value hint scriptruntime scriptableclass scriptruntime functionclass getdefaultvalue getdefaultvalue scriptruntime scriptableclass scriptruntime functionclass getdefaultvalue see org mozilla javascript scriptable has instance public boolean has instance scriptable instance return obj has instance instance hasinstance hasinstance hasinstance see org mozilla javascript function call public object call context cx scriptable scope scriptable this obj object args return function obj call cx scope this obj args thisobj thisobj note that if the code delegee code is code null code this method creates a new instance of the delegator itself rathert than forwarding the call to the code delegee code this permits the use of delegator prototypes param cx the current context for this thread param scope an enclosing scope of the caller except when the function is called from a closure param args the array of arguments return the allocated object see function construct context scriptable object public scriptable construct context cx scriptable scope object args if obj null this little trick allows us to declare prototype objects for delegators delegator n new instance scriptable delegee if args length 0 delegee new native object else delegee script runtime to object cx scope args 0 n set delegee delegee return n else return function obj construct cx scope args newinstance nativeobject scriptruntime toobject setdelegee public static class iterator iterator obj to int map master this master master objtointmap final void init object keys int values int key count this keys keys this values values this cursor 1 this remaining key count keycount keycount public void start master init iterator this next inititerator public boolean done return remaining 0 public void next if remaining 1 kit code bug if remaining 0 remaining 1 cursor 1 else for cursor cursor object key keys cursor if key null key deleted remaining break codebug public object get key object key keys cursor if key unique tag null value key null return key getkey uniquetag null_value public int get value return values cursor getvalue public void set value int value values cursor value setvalue public obj to int map this 4 objtointmap public obj to int map int key count hint if key count hint 0 kit code bug table grow when number of stored keys 3 4 of max capacity int minimal capacity key count hint 4 3 int i for i 2 1 i minimal capacity i power i if check power 2 kit code bug objtointmap keycounthint keycounthint codebug minimalcapacity keycounthint minimalcapacity codebug public boolean is empty return key count 0 isempty keycount public int size return key count keycount public boolean has object key if key null key unique tag null value return 0 find index key uniquetag null_value findindex get integer value assigned with key return key integer value or default value if key is absent public int get object key int default value if key null key unique tag null value int index find index key if 0 index return values index return default value defaultvalue defaultvalue uniquetag null_value findindex defaultvalue get integer value assigned with key return key integer value throws runtime exception if key does not exist public int get existing object key if key null key unique tag null value int index find index key if 0 index return values index key must exist kit code bug return 0 runtimeexception getexisting uniquetag null_value findindex codebug public void put object key int value if key null key unique tag null value int index ensure index key values index value uniquetag null_value ensureindex if table already contains a key that equals to key arg return that key while setting its value to zero otherwise add key arg with 0 value to the table and return it public object intern object key arg boolean null key false if key arg null null key true key arg unique tag null value int index ensure index key arg values index 0 return null key null keys index keyarg keyarg keyarg nullkey keyarg nullkey keyarg uniquetag null_value ensureindex keyarg nullkey public void remove object key if key null key unique tag null value int index find index key if 0 index keys index deleted key count uniquetag null_value findindex keycount public void clear int i keys length while i 0 keys i null key count 0 occupied count 0 keycount occupiedcount public iterator new iterator return new iterator this newiterator from the iterator inner class to workaround jdk 1 1 compiler bug which generates code triggering verifier error on recent jv ms final void init iterator iterator i i init keys values key count verifiererror jvms inititerator keycount return array of present keys public object get keys object array new object key count get keys array 0 return array getkeys keycount getkeys public void get keys object array int offset int count key count for int i 0 count 0 i object key keys i if key null key deleted if key unique tag null value key null array offset key offset count getkeys keycount uniquetag null_value private static int table lookup step int fraction int mask int power int shift 32 2 power if shift 0 return fraction shift mask 1 else return fraction mask shift 1 tablelookupstep private int find index object key if keys null int hash key hash code int fraction hash a int index fraction 32 power object test keys index if test null int n 1 power if test key values n index hash test equals key return index search in table after first failed attempt int mask n 1 int step table lookup step fraction mask power int n 0 for if check if n occupied count kit code bug n index index step mask test keys index if test null break if test key values n index hash test equals key return index return 1 findindex hashcode tablelookupstep occupiedcount codebug and enough free space private int insert new key object key int hash if check occupied count key count kit code bug if check key count 1 power kit code bug int fraction hash a int index fraction 32 power int n 1 power if keys index null int mask n 1 int step table lookup step fraction mask power int first index index do if check keys index deleted kit code bug index index step mask if check first index index kit code bug while keys index null keys index key values n index hash occupied count key count return index insertnewkey occupiedcount keycount codebug keycount codebug tablelookupstep firstindex codebug firstindex codebug occupiedcount keycount private void rehash table if keys null if check key count 0 kit code bug if check occupied count 0 kit code bug int n 1 power keys new object n values new int 2 n else check if removing deleted entries would free enough space if key count 2 occupied count need to grow less then half of deleted entries power int n 1 power object old keys keys int old values values int oldn old keys length keys new object n values new int 2 n int remaining key count occupied count key count 0 for int i 0 remaining 0 i object key old keys i if key null key deleted int key hash old values oldn i int index insert new key key key hash values index old values i remaining rehashtable keycount codebug occupiedcount codebug keycount occupiedcount oldkeys oldvalues oldkeys keycount occupiedcount keycount oldkeys keyhash oldvalues insertnewkey keyhash oldvalues ensure key index creating one if necessary private int ensure index object key int hash key hash code int index 1 int first deleted 1 if keys null int fraction hash a index fraction 32 power object test keys index if test null int n 1 power if test key values n index hash test equals key return index if test deleted first deleted index search in table after first failed attempt int mask n 1 int step table lookup step fraction mask power int n 0 for if check if n occupied count kit code bug n index index step mask test keys index if test null break if test key values n index hash test equals key return index if test deleted first deleted 0 first deleted index inserting of new key if check keys null keys index null kit code bug if first deleted 0 index first deleted else need to consume empty entry check occupation level if keys null occupied count 4 1 power 3 too litle unused entries rehash rehash table return insert new key key hash occupied count keys index key values 1 power index hash key count return index ensureindex hashcode firstdeleted firstdeleted tablelookupstep occupiedcount codebug firstdeleted firstdeleted codebug firstdeleted firstdeleted occupiedcount rehashtable insertnewkey occupiedcount keycount private void write object object output stream out throws io exception out default write object int count key count for int i 0 count 0 i object key keys i if key null key deleted count out write object key out write int values i writeobject objectoutputstream ioexception defaultwriteobject keycount writeobject writeint private void read object object input stream in throws io exception class not found exception in default read object int written key count key count if written key count 0 key count 0 int n 1 power keys new object n values new int 2 n for int i 0 i written key count i object key in read object int hash key hash code int index insert new key key hash values index in read int readobject objectinputstream ioexception classnotfoundexception defaultreadobject writtenkeycount keycount writtenkeycount keycount writtenkeycount readobject hashcode insertnewkey readint public class live connect test extends applet implements runnable create a new live connect test public live connect test liveconnecttest liveconnecttest liveconnecttest main method used when running as an application public static void main string args live connect test test new live connect test liveconnecttest liveconnecttest public void start run public void stop main method when run as an applet public void run system out println running the test setup test environment file start time test driver get current time execute test file end time test driver get current time get results cleanup test environment stop setuptestenvironment starttime testdriver getcurrenttime executetest endtime testdriver getcurrenttime getresults cleanuptestenvironment initialize variables open log files public void setup test environment global js object get window this get environment if environment browser privilege manager enable privilege universal file access privilege manager enable privilege universal property read output get output directory if logging test driver open log files output templog get temp log output testdir get test directory file new test file this get class get name testdir to string this get class to string file bugnumber this bugnumber file description this get class to string setuptestenvironment jsobject getwindow getenvironment privilegemanager enableprivilege universalfileaccess privilegemanager enableprivilege universalpropertyread getoutputdirectory testdriver openlogfiles gettemplog gettestdirectory testfile getclass getname tostring getclass tostring getclass tostring public void get environment this environment global get member version equals undefined browser shell return getenvironment getmember create a test log object which will be used to write the testclass results to a temporary log file if there is an existing log delete it public test log get temp log file output string templog try temp log name string global get member output file equals undefined temp log name string global get member output file templog output get absolute path temp log name catch exception e this exception e to string p exception deleting existing templog e to string return new test log templog testlog testlog gettemplog temp_log_name getmember output_file temp_log_name getmember output_file getabsolutepath temp_log_name tostring tostring testlog get the output file if defined which is where the temp log is written if the file is not defined assume we are running in the shell and do not write any output xxx change this to match description above see com netscape javascript drivers live connect drv public file get output directory string o if this environment browser string output param this get parameter output return new file get parameter output else try o string global get member output directory if o equals undefined logging true catch exception e system err println output directory threw e e print stack trace system exit 1 system out println output file is o to string return new file o to string output_file liveconnectdrv getoutputdirectory outputparam getparameter getparameter getmember output_directory output_directory printstacktrace tostring tostring get the test directory variable which must be defined in the java script helper file see com netscape javascript drivers live connect drv public file get test directory try string o string global get member test directory o o ends with file separator o o file separator return new file o to string catch exception e system err println test directory is not defined e return new file test_directory javascript liveconnectdrv gettestdirectory getmember test_directory endswith tostring test_directory execute the test subclasses must implement this method the default implemenation does nothing this method should instantiate test cases and add them to the testcase vector public void execute test return testcases executetest add a test case to the testcase vector param description a description of the test case param expect a string representation of the expected result param actual a string representation of the actual result param exception the message in any java script runtime error or java exception that was thrown public void add test case string description string expect string actual string exception string result expect actual true false test case tc new test case result this get class get name to string description expect actual exception file case vector add element tc file total cases if result false file passed false file cases failed else file cases passed return testcase javascript addtestcase testcase testcase getclass getname tostring casevector addelement totalcases casesfailed casespassed close all logs public void close logs test driver get log output test driver summary log name close log test driver get log output test driver suite log name close log test driver get log output test driver file log name close log test driver get log output test driver case log name close log templog close log templog null closelogs testdriver getlog testdriver summary_log_name closelog testdriver getlog testdriver suite_log_name closelog testdriver getlog testdriver file_log_name closelog testdriver getlog testdriver case_log_name closelog closelog iterate through the testcase vector populate the properties of the test file object public void get results display results if logging write results to case log write results to file log write results to temp log testfile getresults displayresults writeresultstocaselog writeresultstofilelog writeresultstotemplog write a summary of the test case to standard out public void display results for int i 0 i file case vector size i test case tc test case file case vector element at i p tc description tc actual tc expect tc actual failed expected tc expect passed get failed cases testcase displayresults casevector testcase testcase casevector elementat getfailedcases if any test cases did not pass write a summary of the failed cases to the case log using static test driver methods see com netscape javascript qa drivers test driver write case results public void write results to case log if file passed test driver write case results file file description output case_log testdriver testdriver writecaseresults writeresultstocaselog testdriver writecaseresults if the test failed write a summary of this test to the file log use static test driver methods to write to the file log see com netscape javascript qa drivers test driver write file result public void write results to file log if file passed test driver write file result file null output file_log testdriver file_log testdriver writefileresult writeresultstofilelog testdriver writefileresult write to a file containing the results of this test file the content of this file is parsed by the parse result method of live connect env which maintains information about all files and suites executed the format of the temp log is a list of name value pairs one per line the temp log is overwritten each time the live connect drv executes a test changes to the format of the templog file will require changes to live connect drv parse result 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 xxx may also want to write bugnumber time completed etc probably what this should do is enumerate all the properties of a test file object that the driver can parse and treat as though it had a normal test file object see com netscape javascript qa drivers live connect drv parse result public void write results to temp log system out println writing results to templog to string templog write line file description templog write line file passed templog write line file case vector size templog write line file cases passed templog write line file cases failed templog write line file bugnumber p file name p passed passed p total cases file case vector size p cases passed file cases passed p cases failed file cases failed p bugnumber file bugnumber return testfile parseresult liveconnectenv liveconnectdrv liveconnectdrv parseresult liveconnecttest no_passed no_failed testfile testfile liveconnectdrv parseresult writeresultstotemplog tostring writeline writeline writeline casevector writeline casespassed writeline casesfailed writeline casevector casespassed casesfailed close logs and set the value of the completed variable in the java script environment so that the driver knows the test has finished public void cleanup test environment try if logging templog close log global eval var completed true catch exception e p exception in cleanup test environment e to string e print stack trace javascript cleanuptestenvironment closelog cleanuptestenvironment tostring printstacktrace public void p string s system out println s this dandy little hack from nix that is used to test things that should fail it runs a method on a java script object catching any exceptions it returns the detail message from the exception or no exception if it succeeds this is from nix public static string catch exception js object self string method object args object rval string msg try rval self call method args msg no exception catch throwable e msg e get message return msg javascript no_exception catchexception jsobject no_exception getmessage public void get failed cases if file passed return p failed test cases for int i 0 i file case vector size i test case tc test case file case vector element at i if tc passed true p tc description tc actual tc expect tc actual failed expected tc expect passed tc reason length 0 tc reason getfailedcases casevector testcase testcase casevector elementat prototype values id scriptable object obj int max id if obj null throw new illegal argument exception if max id 1 throw new illegal argument exception this obj obj this max id max id prototypevalues idscriptableobject maxid illegalargumentexception maxid illegalargumentexception maxid maxid final int get max id return max id getmaxid maxid final void init value int id string name object value int attributes if 1 id id max id throw new illegal argument exception if name null throw new illegal argument exception if value not found throw new illegal argument exception scriptable object check valid attributes attributes if obj find prototype id name id throw new illegal argument exception name if id constructor id if value instanceof id function object throw new illegal argument exception consructor should be initialized with id function object constructor id function object value constructor attrs short attributes return init slot id name value attributes initvalue maxid illegalargumentexception illegalargumentexception not_found illegalargumentexception scriptableobject checkvalidattributes findprototypeid illegalargumentexception constructorid idfunctionobject illegalargumentexception idfunctionobject idfunctionobject constructorattrs initslot private void init slot int id string name object value int attributes object array value array if array null throw new illegal state exception if value null value unique tag null value int index id 1 slot span synchronized this object value2 array index value slot if value2 null array index value slot value array index name slot name attribute array id 1 short attributes else if name equals array index name slot throw new illegal state exception initslot valuearray illegalstateexception uniquetag null_value slot_span value_slot value_slot name_slot attributearray name_slot illegalstateexception final id function object create precached constructor if constructor id 0 throw new illegal state exception constructor id obj find prototype id constructor if constructor id 0 throw new illegal state exception no id for constructor property obj init prototype id constructor id if constructor null throw new illegal state exception obj get class get name init prototype id did not initialize id constructor id constructor init function obj get class name scriptable object get top level scope obj constructor mark as constructor obj return constructor idfunctionobject createprecachedconstructor constructorid illegalstateexception constructorid findprototypeid constructorid illegalstateexception initprototypeid constructorid illegalstateexception getclass getname initprototypeid constructorid initfunction getclassname scriptableobject gettoplevelscope markasconstructor final int find id string name object array value array if array null return obj find prototype id name int id last found id if name array id 1 slot span name slot return id id obj find prototype id name if id 0 int name slot id 1 slot span name slot make cache to work array name slot name last found id id return id findid valuearray findprototypeid lastfoundid slot_span name_slot findprototypeid nameslot slot_span name_slot nameslot lastfoundid final boolean has int id object array value array if array null not yet initialized assume all exists return true int value slot id 1 slot span value slot object value array value slot if value null the particular entry has not been yet initialized return true return value not found valuearray valueslot slot_span value_slot valueslot not_found final object get int id object value ensure id id if value unique tag null value value null return value ensureid uniquetag null_value final void set int id scriptable start object value if value not found throw new illegal argument exception ensure id id int attr attribute array id 1 if attr readonly 0 if start obj if value null value unique tag null value int value slot id 1 slot span value slot synchronized this value array value slot value else int name slot id 1 slot span name slot string name string value array name slot start put name start value not_found illegalargumentexception ensureid attributearray uniquetag null_value valueslot slot_span value_slot valuearray valueslot nameslot slot_span name_slot valuearray nameslot final void delete int id ensure id id int attr attribute array id 1 if attr permanent 0 int value slot id 1 slot span value slot synchronized this value array value slot not found attribute array id 1 empty ensureid attributearray valueslot slot_span value_slot valuearray valueslot not_found attributearray final int get attributes int id ensure id id return attribute array id 1 getattributes ensureid attributearray final void set attributes int id int attributes scriptable object check valid attributes attributes ensure id id synchronized this attribute array id 1 short attributes setattributes scriptableobject checkvalidattributes ensureid attributearray final object get names boolean get all object extra entries object names null int count 0 for int id 1 id max id id object value ensure id id if get all attribute array id 1 dontenum 0 if value not found int name slot id 1 slot span name slot string name string value array name slot if names null names new object max id names count name if count 0 return extra entries else if extra entries null extra entries length 0 if count names length object tmp new object count system arraycopy names 0 tmp 0 count names tmp return names else int extra extra entries length object tmp new object extra count system arraycopy extra entries 0 tmp 0 extra system arraycopy names 0 tmp extra count return tmp getnames getall extraentries maxid ensureid getall attributearray not_found nameslot slot_span name_slot valuearray nameslot maxid extraentries extraentries extraentries extraentries extraentries private object ensure id int id object array value array if array null synchronized this array value array if array null array new object max id slot span value array array attribute array new short max id int value slot id 1 slot span value slot object value array value slot if value null if id constructor id init slot constructor id constructor constructor constructor attrs constructor null no need to refer it any longer else obj init prototype id id value array value slot if value null throw new illegal state exception obj get class get name init prototype id int id did not initialize id id return value ensureid valuearray valuearray maxid slot_span valuearray attributearray maxid valueslot slot_span value_slot valueslot constructorid initslot constructorid constructorattrs initprototypeid valueslot illegalstateexception getclass getname initprototypeid public id scriptable object idscriptableobject public id scriptable object scriptable scope scriptable prototype super scope prototype idscriptableobject protected final object default get string name return super get name this defaultget protected final void default put string name object value super put name this value defaultput public boolean has string name scriptable start int info find instance id info name if info 0 int attr info 16 if attr permanent 0 return true int id info 0xffff return not found get instance id value id if prototype values null int id prototype values find id name if id 0 return prototype values has id return super has name start findinstanceidinfo not_found getinstanceidvalue prototypevalues prototypevalues findid prototypevalues public object get string name scriptable start int info find instance id info name if info 0 int id info 0xffff return get instance id value id if prototype values null int id prototype values find id name if id 0 return prototype values get id return super get name start findinstanceidinfo getinstanceidvalue prototypevalues prototypevalues findid prototypevalues public void put string name scriptable start object value int info find instance id info name if info 0 if start this is sealed throw context report runtime error1 msg modify sealed name int attr info 16 if attr readonly 0 if start this int id info 0xffff set instance id value id value else start put name start value return if prototype values null int id prototype values find id name if id 0 if start this is sealed throw context report runtime error1 msg modify sealed name prototype values set id start value return super put name start value findinstanceidinfo issealed reportruntimeerror1 setinstanceidvalue prototypevalues prototypevalues findid issealed reportruntimeerror1 prototypevalues public void delete string name int info find instance id info name if info 0 let the super class to throw exceptions for sealed objects if is sealed int attr info 16 if attr permanent 0 int id info 0xffff set instance id value id not found return if prototype values null int id prototype values find id name if id 0 if is sealed prototype values delete id return super delete name findinstanceidinfo issealed setinstanceidvalue not_found prototypevalues prototypevalues findid issealed prototypevalues public int get attributes string name int info find instance id info name if info 0 int attr info 16 return attr if prototype values null int id prototype values find id name if id 0 return prototype values get attributes id return super get attributes name getattributes findinstanceidinfo prototypevalues prototypevalues findid prototypevalues getattributes getattributes public void set attributes string name int attributes scriptable object check valid attributes attributes int info find instance id info name if info 0 int current attributes info 16 if attributes current attributes throw new runtime exception change of attributes for this id is not supported return if prototype values null int id prototype values find id name if id 0 prototype values set attributes id attributes return super set attributes name attributes setattributes scriptableobject checkvalidattributes findinstanceidinfo currentattributes currentattributes runtimeexception prototypevalues prototypevalues findid prototypevalues setattributes setattributes object get ids boolean get all object result super get ids get all if prototype values null result prototype values get names get all result int max instance id get max instance id if max instance id 0 object ids null int count 0 for int id max instance id id 0 id string name get instance id name id int info find instance id info name if info 0 int attr info 16 if attr permanent 0 if not found get instance id value id continue if get all attr dontenum 0 if count 0 need extra room for no more then 1 id names ids new object id ids count name if count 0 if result length 0 ids length count result ids else object tmp new object result length count system arraycopy result 0 tmp 0 result length system arraycopy ids 0 tmp result length count result tmp return result getids getall getids getall prototypevalues prototypevalues getnames getall maxinstanceid getmaxinstanceid maxinstanceid maxinstanceid getinstanceidname findinstanceidinfo not_found getinstanceidvalue getall get maximum id find instance id info can generate protected int get max instance id return 0 findinstanceidinfo getmaxinstanceid protected static int instance id info int attributes int id return attributes 16 id instanceidinfo map name to id of instance property should return 0 if not found or the result of link instance id info int int protected int find instance id info string name return 0 instanceidinfo findinstanceidinfo map id back to property name it defines protected string get instance id name int id throw new illegal argument exception string value of id getinstanceidname illegalargumentexception valueof get id value if id value is constant descendant can call cache id value to store value in the permanent cache default implementation creates id function object instance for given id and cache its value protected object get instance id value int id throw new illegal state exception string value of id cacheidvalue idfunctionobject getinstanceidvalue illegalstateexception valueof set or delete id value if value not found the implementation should make sure that the following get instance id value return not found protected void set instance id value int id object value throw new illegal state exception string value of id not_found getinstanceidvalue not_found setinstanceidvalue illegalstateexception valueof this obj will be null if invoked as constructor in which case instance of scriptable should be returned public object exec id call id function object f context cx scriptable scope scriptable this obj object args throw f unknown thisobj execidcall idfunctionobject thisobj public final id function object export asjs class int max prototype id scriptable scope boolean sealed set scope and prototype unless this is top level scope itself if scope this scope null set parent scope scope set prototype get object prototype scope activate prototype map max prototype id id function object ctor prototype values create precached constructor if sealed seal object fill constructor properties ctor if sealed ctor seal object ctor export as scope property return ctor idfunctionobject exportasjsclass maxprototypeid setparentscope setprototype getobjectprototype activateprototypemap maxprototypeid idfunctionobject prototypevalues createprecachedconstructor sealobject fillconstructorproperties sealobject exportasscopeproperty public final boolean has prototype map return prototype values null hasprototypemap prototypevalues public final void activate prototype map int max prototype id prototype values values new prototype values this max prototype id synchronized this if prototype values null throw new illegal state exception prototype values values activateprototypemap maxprototypeid prototypevalues prototypevalues maxprototypeid prototypevalues illegalstateexception prototypevalues public final void init prototype method object tag int id string name int arity scriptable scope scriptable object get top level scope this id function object f new id function tag id name arity scope prototype values init value id name f dontenum initprototypemethod scriptableobject gettoplevelscope idfunctionobject newidfunction prototypevalues initvalue public final void init prototype constructor id function object f int id prototype values constructor id if id 0 throw new illegal state exception if f method id id throw new illegal argument exception if is sealed f seal object prototype values init value id constructor f dontenum initprototypeconstructor idfunctionobject prototypevalues constructorid illegalstateexception methodid illegalargumentexception issealed sealobject prototypevalues initvalue public final void init prototype value int id string name object value int attributes prototype values init value id name value attributes initprototypevalue prototypevalues initvalue protected void init prototype id int id throw new illegal state exception string value of id initprototypeid illegalstateexception valueof protected int find prototype id string name throw new illegal state exception name findprototypeid illegalstateexception protected void fill constructor properties id function object ctor fillconstructorproperties idfunctionobject protected void add id function property scriptable obj object tag int id string name int arity scriptable scope scriptable object get top level scope obj id function object f new id function tag id name arity scope f add as property obj addidfunctionproperty scriptableobject gettoplevelscope idfunctionobject newidfunction addasproperty utility method to construct type error to indicate incompatible call when converting script this obj to a particular type is not possible possible usage would be to have a private function like real this pre private static native something real this scriptable this obj id function object f if this obj instanceof native something throw incompatible call error f return native something this obj pre note that although such function can be implemented universally via java lang class is instance it would be much more slower param read only specify if the function f does not change state of object return scriptable object suitable for a check by the instanceof operator throws runtime exception if no more instanceof target can be found protected static ecma error incompatible call error id function object f throw script runtime type error1 msg incompat call f get function name thisobj realthis nativesomething realthis thisobj idfunctionobject thisobj nativesomething incompatiblecallerror nativesomething thisobj isinstance readonly runtimeexception ecmaerror incompatiblecallerror idfunctionobject scriptruntime typeerror1 getfunctionname private id function object new id function object tag int id string name int arity scriptable scope id function object f new id function object this tag id name arity scope if is sealed f seal object return f idfunctionobject newidfunction idfunctionobject idfunctionobject issealed sealobject private void read object object input stream stream throws io exception class not found exception stream default read object int max prototype id stream read int if max prototype id 0 activate prototype map max prototype id readobject objectinputstream ioexception classnotfoundexception defaultreadobject maxprototypeid readint maxprototypeid activateprototypemap maxprototypeid private void write object object output stream stream throws io exception stream default write object int max prototype id 0 if prototype values null max prototype id prototype values get max id stream write int max prototype id writeobject objectoutputstream ioexception defaultwriteobject maxprototypeid prototypevalues maxprototypeid prototypevalues getmaxid writeint maxprototypeid 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 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 class shell extends scriptable object public string get class name return global scriptableobject getclassname 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 associate a new context with this thread context cx context enter try initialize the standard objects object function etc this must be done before scripts can be executed shell shell new shell cx init standard objects shell define some global functions particular to the shell note that these functions are not part of ecma string names print quit version load help shell define function properties names shell class scriptable object dontenum args process options cx args set up arguments in the global scope to contain the command line arguments after the name of the script to execute object array args if args length 0 int length args length 1 array new object length system arraycopy args 1 array 0 length scriptable args obj cx new array shell array shell define property arguments args obj scriptable object dontenum shell process source cx args length 0 null args 0 finally context exit initstandardobjects definefunctionproperties scriptableobject processoptions argsobj newarray defineproperty argsobj scriptableobject processsource parse arguments public static string process options context cx string args for int i 0 i args length i string arg args i if arg starts with string result new string args length i for int j i j args length j result j i args j return result if arg equals version if i args length usage arg double d cx to number args i if d d usage arg cx set language version int d continue usage arg return new string 0 processoptions startswith tonumber setlanguageversion print a usage message private static void usage string s p didn t understand s p valid arguments are p version 100 110 120 130 140 150 system exit 1 print a help message this method is defined as a java script function public void help p p command description p p help display usage and help messages p define class class name define an extension using the java class p named with the string argument p uses scriptable object define class p load foo js load java script source files named by p string arguments p load class class name load a class named by a string argument p the class must be a script compiled to a p class file p print expr evaluate and print expressions p quit quit the shell p version number get or set the java script version number p javascript defineclass classname scriptableobject defineclass javascript loadclass classname javascript 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 void print context cx scriptable this obj object args function fun obj for int i 0 i args length i if i 0 system out print convert the arbitrary java script value into a string form string s context to string args i system out print s system out println javascript javascript thisobj funobj javascript tostring quit the shell this only affects the interactive mode this method is defined as a java script function public void quit quitting true javascript 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 cx 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 shell shell shell get top level scope this obj for int i 0 i args length i shell process source cx cx to string args i javascript javascript thisobj funobj gettoplevelscope thisobj processsource tostring evaluate java script source param cx the current context param filename the name of the file to compile or null for interactive mode private void process source context cx string filename if filename null buffered reader in new buffered reader new input stream reader system in string source name stdin int lineno 1 boolean hiteof false do int startline lineno system err print js system err flush try string source collect lines of source to compile while true string newline newline in read line if newline null hiteof true break source source newline n lineno continue collecting as long as more lines are needed to complete the current statement string is compilable unit is also true if the source statement will result in any error other than one that might be resolved by appending more source if cx string is compilable unit source break object result cx evaluate string this source source name startline null if result cx get undefined value system err println cx to string result catch wrapped exception we some form of exception was caught by java script and propagated up system err println we get wrapped exception to string we print stack trace catch evaluator exception ee some form of java script error system err println js ee get message catch java script exception jse some form of java script error system err println js jse get message catch io exception ioe system err println ioe to string if quitting the user executed the quit function break while hiteof system err println else file reader in null try in new file reader filename catch file not found exception ex context report error couldn t open file filename return try here we evalute the entire contents of the file as a script text is printed only if the print function is called cx evaluate reader this in filename 1 null catch wrapped exception we system err println we get wrapped exception to string we print stack trace catch evaluator exception ee system err println js ee get message catch java script exception jse system err println js jse get message catch io exception ioe system err println ioe to string finally try in close catch io exception ioe system err println ioe to string system gc javascript processsource bufferedreader bufferedreader inputstreamreader sourcename readline stringiscompilableunit stringiscompilableunit evaluatestring sourcename getundefinedvalue tostring wrappedexception javascript getwrappedexception tostring printstacktrace evaluatorexception javascript getmessage javascriptexception javascript getmessage ioexception tostring filereader filereader filenotfoundexception reporterror evaluatereader wrappedexception getwrappedexception tostring printstacktrace evaluatorexception getmessage javascriptexception getmessage ioexception tostring ioexception tostring private static void p string s system out println s static final long serial versionuid 6948590651130498591l public native java object serialversionuid nativejavaobject public native java object scriptable scope object java object class static type this parent scope this java object java object this static type static type init members nativejavaobject javaobject statictype javaobject javaobject statictype statictype initmembers protected void init members class dynamic type if java object null dynamic type java object get class else dynamic type static type members java members lookup class parent dynamic type static type field and methods members get field and methods objects this java object false initmembers dynamictype javaobject dynamictype javaobject getclass dynamictype statictype javamembers lookupclass dynamictype statictype fieldandmethods getfieldandmethodsobjects javaobject public boolean has string name scriptable start return members has name false public boolean has int index scriptable start return false public object get string name scriptable start if field and methods null object result field and methods get name if result null return result todo passing this as the scope is bogus since it has no parent scope return members get this name java object false fieldandmethods fieldandmethods javaobject public object get int index scriptable start throw members report member not found integer to string index reportmembernotfound tostring public void put string name scriptable start object value we could be asked to modify the value of a property in the prototype since we can t add a property to a java object we modify it in the prototype rather than copy it down if prototype null members has name false members put this name java object value false else prototype put name prototype value javaobject public void put int index scriptable start object value throw members report member not found integer to string index reportmembernotfound tostring public boolean has instance scriptable value this is an instance of a java class so always return false return false hasinstance public void delete string name public void delete int index public scriptable get prototype if prototype null java object instanceof string return scriptable object get class prototype parent string return prototype getprototype javaobject scriptableobject getclassprototype sets the prototype of the object public void set prototype scriptable m prototype m setprototype returns the parent enclosing scope of the object public scriptable get parent scope return parent getparentscope sets the parent enclosing scope of the object public void set parent scope scriptable m parent m setparentscope public object get ids return members get ids false getids getids deprecated use link context get wrap factory together with calling link wrap factory wrap context cx scriptable scope object obj class public static object wrap scriptable scope object obj class static type context cx context get context return cx get wrap factory wrap cx scope obj static type getwrapfactory wrapfactory statictype getcontext getwrapfactory statictype public object unwrap return java object javaobject public string get class name return java object getclassname javaobject public object get default value class hint object value if hint null if java object instanceof boolean hint script runtime boolean class if hint null hint script runtime string class value java object to string else string converter name if hint script runtime boolean class converter name boolean value else if hint script runtime number class converter name double value else throw context report runtime error0 msg default value object converter object get converter name this if converter object instanceof function function f function converter object value f call context get context f get parent scope this script runtime empty args else if hint script runtime number class java object instanceof boolean boolean b boolean java object boolean value value script runtime wrap number b 1 0 0 0 else value java object to string return value getdefaultvalue javaobject scriptruntime booleanclass scriptruntime stringclass javaobject tostring convertername scriptruntime booleanclass convertername booleanvalue scriptruntime numberclass convertername doublevalue reportruntimeerror0 converterobject convertername converterobject converterobject getcontext getparentscope scriptruntime emptyargs scriptruntime numberclass javaobject javaobject booleanvalue scriptruntime wrapnumber javaobject tostring determine whether we can should convert between the given type and the desired one this should be superceded by a conversion cost calculation function but for now i ll hide behind precedent public static boolean can convert object from obj class to int weight get conversion weight from obj to return weight conversion none canconvert fromobj getconversionweight fromobj conversion_none derive a ranking based on how natural the conversion is the special value conversion none means no conversion is possible and conversion nontrivial signals that more type conformance testing is required based on a href http www mozilla org js liveconnect lc3 method overloading html preferred method conversions from live connect 3 a static int get conversion weight object from obj class to int from code getjs type code from obj switch from code case jstype undefined if to script runtime string class to script runtime object class return 1 break case jstype null if to is primitive return 1 break case jstype boolean boolean is 1 if to boolean type return 1 else if to script runtime boolean class return 2 else if to script runtime object class return 3 else if to script runtime string class return 4 break case jstype number if to is primitive if to double type return 1 else if to boolean type return 1 get size rank to else if to script runtime string class native numbers are 1 8 return 9 else if to script runtime object class return 10 else if script runtime number class is assignable from to double is 1 return 2 break case jstype string if to script runtime string class return 1 else if to is instance from obj return 2 else if to is primitive if to character type return 3 else if to boolean type return 4 break case jstype java class if to script runtime class class return 1 else if to script runtime object class return 3 else if to script runtime string class return 4 break case jstype java object case jstype java array object java obj from obj if java obj instanceof wrapper java obj wrapper java obj unwrap if to is instance java obj return conversion nontrivial if to script runtime string class return 2 else if to is primitive to boolean type return from code jstype java array conversion nontrivial 2 get size rank to break case jstype object other objects takes 1 3 spots if to from obj get class no conversion required return 1 if to is array if from obj instanceof native array this is a native array conversion to a java array array conversions are all equal and preferable to object and string conversion per lc3 return 1 else if to script runtime object class return 2 else if to script runtime string class return 3 else if to script runtime date class if from obj instanceof native date this is a native date to java date conversion return 1 else if to is interface if from obj instanceof function see comments in coerce type if to get methods length 1 return 1 return 11 else if to is primitive to boolean type return 3 get size rank to break return conversion none conversion_none conversion_nontrivial lc3_method_overloading getconversionweight fromobj fromcode getjstypecode fromobj fromcode jstype_undefined scriptruntime stringclass scriptruntime objectclass jstype_null isprimitive jstype_boolean scriptruntime booleanclass scriptruntime objectclass scriptruntime stringclass jstype_number isprimitive getsizerank scriptruntime stringclass scriptruntime objectclass scriptruntime numberclass isassignablefrom jstype_string scriptruntime stringclass isinstance fromobj isprimitive jstype_java_class scriptruntime classclass scriptruntime objectclass scriptruntime stringclass jstype_java_object jstype_java_array javaobj fromobj javaobj javaobj javaobj isinstance javaobj conversion_nontrivial scriptruntime stringclass isprimitive fromcode jstype_java_array conversion_nontrivial getsizerank jstype_object fromobj getclass isarray fromobj nativearray scriptruntime objectclass scriptruntime stringclass scriptruntime dateclass fromobj nativedate isinterface fromobj coercetype getmethods isprimitive getsizerank conversion_none static int get size rank class a type if a type double type return 1 else if a type float type return 2 else if a type long type return 3 else if a type integer type return 4 else if a type short type return 5 else if a type character type return 6 else if a type byte type return 7 else if a type boolean type return conversion none else return 8 getsizerank atype atype atype atype atype atype atype atype atype conversion_none private static int getjs type code object value if value null return jstype null else if value undefined instance return jstype undefined else if value instanceof string return jstype string else if value instanceof number return jstype number else if value instanceof boolean return jstype boolean else if value instanceof scriptable if value instanceof native java class return jstype java class else if value instanceof native java array return jstype java array else if value instanceof wrapper return jstype java object else return jstype object else if value instanceof class return jstype java class else class value class value get class if value class is array return jstype java array else return jstype java object getjstypecode jstype_null jstype_undefined jstype_string jstype_number jstype_boolean nativejavaclass jstype_java_class nativejavaarray jstype_java_array jstype_java_object jstype_object jstype_java_class valueclass getclass valueclass isarray jstype_java_array jstype_java_object not intended for public use callers should use the public api context to type see org mozilla javascript context js to java object class deprecated as of 1 5 release 4 public static object coerce type class type object value return coerce type impl type value totype jstojava coercetype coercetypeimpl type munging for field setting and method invocation conforms to lc3 specification static object coerce type impl class type object value if value null value get class type return value switch getjs type code value case jstype null raise error if type is primitive if type is primitive report conversion error value type return null case jstype undefined if type script runtime string class type script runtime object class return undefined else report conversion error undefined type break case jstype boolean under lc3 only js booleans can be coerced into a boolean value if type boolean type type script runtime boolean class type script runtime object class return value else if type script runtime string class return value to string else report conversion error value type break case jstype number if type script runtime string class return script runtime to string value else if type script runtime object class return coerce to number double type value else if type is primitive type boolean type script runtime number class is assignable from type return coerce to number type value else report conversion error value type break case jstype string if type script runtime string class type is instance value return value else if type character type type script runtime character class special case for converting a single char string to a character placed here because it applies only to js strings not other js objects converted to strings if string value length 1 return new character string value char at 0 else return coerce to number type value else if type is primitive type boolean type script runtime number class is assignable from type return coerce to number type value else report conversion error value type break case jstype java class if value instanceof wrapper value wrapper value unwrap if type script runtime class class type script runtime object class return value else if type script runtime string class return value to string else report conversion error value type break case jstype java object case jstype java array if type is primitive if type boolean type report conversion error value type return coerce to number type value else if value instanceof wrapper value wrapper value unwrap if type script runtime string class return value to string else if type is instance value return value else report conversion error value type break case jstype object if type script runtime string class return script runtime to string value else if type is primitive if type boolean type report conversion error value type return coerce to number type value else if type is instance value return value else if type script runtime date class value instanceof native date double time native date value getjs time value xxx this will replace nan by 0 return new date long time else if type is array value instanceof native array make a new java array and coerce the js array components to the target component type native array array native array value long length array get length class array type type get component type object result array new instance array type int length for int i 0 i length i try array set result i coerce type array type array get i array catch evaluator exception ee report conversion error value type return result else if value instanceof wrapper value wrapper value unwrap if type is instance value return value report conversion error value type else if type is interface value instanceof callable try to use function as implementation of java interface xxx curently only instances of scriptable object are supported since the resulting interface proxies should be reused next time conversion is made and generic callable has no storage for it weak references can address it but for now use this restriction if value instanceof scriptable object scriptable object so scriptable object value object key kit make hash key from pair coerced interface key type object old so get associated value key if old null function was already wrapped return old context cx context get context object glue interface adapter create cx type callable value store for later retrival glue so associate value key glue return glue report conversion error value type else report conversion error value type break return value coercetypeimpl getclass getjstypecode jstype_null isprimitive isprimitive reportconversionerror jstype_undefined scriptruntime stringclass scriptruntime objectclass reportconversionerror jstype_boolean scriptruntime booleanclass scriptruntime objectclass scriptruntime stringclass tostring reportconversionerror jstype_number scriptruntime stringclass scriptruntime tostring scriptruntime objectclass coercetonumber isprimitive scriptruntime numberclass isassignablefrom coercetonumber reportconversionerror jstype_string scriptruntime stringclass isinstance scriptruntime characterclass charat coercetonumber isprimitive scriptruntime numberclass isassignablefrom coercetonumber reportconversionerror jstype_java_class scriptruntime classclass scriptruntime objectclass scriptruntime stringclass tostring reportconversionerror jstype_java_object jstype_java_array isprimitive reportconversionerror coercetonumber scriptruntime stringclass tostring isinstance reportconversionerror jstype_object scriptruntime stringclass scriptruntime tostring isprimitive reportconversionerror coercetonumber isinstance scriptruntime dateclass nativedate nativedate getjstimevalue isarray nativearray nativearray nativearray getlength arraytype getcomponenttype newinstance arraytype coercetype arraytype evaluatorexception reportconversionerror isinstance reportconversionerror isinterface scriptableobject scriptableobject scriptableobject scriptableobject makehashkeyfrompair coerced_interface_key getassociatedvalue getcontext interfaceadapter associatevalue reportconversionerror reportconversionerror private static object coerce to number class type object value class value class value get class character if type character type type script runtime character class if value class script runtime character class return value return new character char to integer value script runtime character class double character min value double character max value double float if type script runtime object class type script runtime double class type double type return value class script runtime double class value new double to double value if type script runtime float class type float type if value class script runtime float class return value else double number to double value if double is infinite number double is nan number number 0 0 return new float float number else double abs number math abs number if abs number double float min value return new float number 0 0 0 0 0 0 else if abs number double float max value return new float number 0 0 float positive infinity float negative infinity else return new float float number integer long short byte if type script runtime integer class type integer type if value class script runtime integer class return value else return new integer int to integer value script runtime integer class double integer min value double integer max value if type script runtime long class type long type if value class script runtime long class return value else long values cannot be expressed exactly in doubles we thus use the largest and smallest double value that has a value expressible as a long value we build these numerical values from their hexidecimal representations to avoid any problems caused by attempting to parse a decimal representation final double max double long bits to double 0x43dfffffffffffffl final double min double long bits to double 0xc3e0000000000000l return new long to integer value script runtime long class min max if type script runtime short class type short type if value class script runtime short class return value else return new short short to integer value script runtime short class double short min value double short max value if type script runtime byte class type byte type if value class script runtime byte class return value else return new byte byte to integer value script runtime byte class double byte min value double byte max value return new double to double value coercetonumber valueclass getclass scriptruntime characterclass valueclass scriptruntime characterclass tointeger scriptruntime characterclass min_value max_value scriptruntime objectclass scriptruntime doubleclass valueclass scriptruntime doubleclass todouble scriptruntime floatclass valueclass scriptruntime floatclass todouble isinfinite isnan absnumber absnumber min_value absnumber max_value positive_infinity negative_infinity scriptruntime integerclass valueclass scriptruntime integerclass tointeger scriptruntime integerclass min_value max_value scriptruntime longclass valueclass scriptruntime longclass longbitstodouble longbitstodouble tointeger scriptruntime longclass scriptruntime shortclass valueclass scriptruntime shortclass tointeger scriptruntime shortclass min_value max_value scriptruntime byteclass valueclass scriptruntime byteclass tointeger scriptruntime byteclass min_value max_value todouble private static double to double object value if value instanceof number return number value double value else if value instanceof string return script runtime to number string value else if value instanceof scriptable if value instanceof wrapper xxx optimize tail recursion return to double wrapper value unwrap else return script runtime to number value else method meth try meth value get class get method double value null catch no such method exception e meth null catch security exception e meth null if meth null try return number meth invoke value null double value catch illegal access exception e xxx ignore or error message report conversion error value double type catch invocation target exception e xxx ignore or error message report conversion error value double type return script runtime to number value to string todouble doublevalue scriptruntime tonumber todouble scriptruntime tonumber getclass getmethod doublevalue nosuchmethodexception securityexception doublevalue illegalaccessexception reportconversionerror invocationtargetexception reportconversionerror scriptruntime tonumber tostring private static long to integer object value class type double min double max double d to double value if double is infinite d double is nan d convert to string first for more readable message report conversion error script runtime to string value type if d 0 0 d math floor d else d math ceil d if d min d max convert to string first for more readable message report conversion error script runtime to string value type return long d tointeger todouble isinfinite isnan reportconversionerror scriptruntime tostring reportconversionerror scriptruntime tostring static void report conversion error object value class type it uses string value of value not value to string since value can be null bug 282447 throw context report runtime error2 msg conversion not allowed string value of value java members java signature type reportconversionerror valueof tostring reportruntimeerror2 valueof javamembers javasignature private void write object object output stream out throws io exception out default write object if java object null class jo class java object get class if jo class get name starts with adapter out write boolean true if adapter writeadapterobject null throw new io exception object args java object out try adapter writeadapterobject invoke null args catch exception ex throw new io exception else out write boolean false out write object java object else out write boolean false out write object java object if static type null out write object static type get class get name else out write object null writeobject objectoutputstream ioexception defaultwriteobject javaobject joclass javaobject getclass joclass getname startswith writeboolean adapter_writeadapterobject ioexception javaobject adapter_writeadapterobject ioexception writeboolean writeobject javaobject writeboolean writeobject javaobject statictype writeobject statictype getclass getname writeobject private void read object object input stream in throws io exception class not found exception in default read object if in read boolean if adapter readadapterobject null throw new class not found exception object args this in try java object adapter readadapterobject invoke null args catch exception ex throw new io exception else java object in read object string class name string in read object if class name null static type class for name class name else static type null init members readobject objectinputstream ioexception classnotfoundexception defaultreadobject readboolean adapter_readadapterobject classnotfoundexception javaobject adapter_readadapterobject ioexception javaobject readobject classname readobject classname statictype forname classname statictype initmembers public object observer public observed task string cl object observer this command line cl this observer observer observedtask commandline public string buffer get input return input stringbuffer getinput public string buffer get error return error stringbuffer geterror int get exit value return exit value getexitvalue exitvalue execute the process and return when the process is complete public void exec throws io exception runtime rt runtime get runtime try process proc rt exec command line output stream os rt get localized output stream proc get output stream if this observer instanceof ref env os write quit n get bytes os flush os close input stream reader is is new input stream reader proc get error stream new thread new stream reader error is start is new input stream reader proc get input stream new thread new stream reader input is start proc wait for exit value proc exit value unfortunately the following pause seems to need to be here otherwise we get a crash on aix process wait for doesn t seem to wait for the process to complete before continuing bad need to find a workaround if system get property os name starts with aix system get property os name starts with hp pause 20000 else pause 10000 catch exception e java lang system out println e e print stack trace ioexception getruntime commandline outputstream getlocalizedoutputstream getoutputstream refenv getbytes inputstreamreader inputstreamreader geterrorstream streamreader inputstreamreader getinputstream streamreader waitfor exitvalue exitvalue waitfor getproperty startswith getproperty startswith printstacktrace simple print method used for debugging public void print system out println input stream of process system out println input system out println error stream of process system out println error system out println exit value of process exit value exitvalue simple pause method used for debugging static void pause int length try thread current thread sleep length catch interrupted exception ex system err println ex currentthread interruptedexception main used for debugging static public void main string args if args length 1 system err println usage java run it command line system exit 1 try observed task task new observed task args 0 null task exec task print pause 10000 catch exception e system err println error exception thrown e system exit 2 runit observedtask observedtask input stream reader input stream reader stream reader string buffer b input stream reader i buffer b input stream reader i inputstreamreader inputstreamreader streamreader stringbuffer inputstreamreader inputstreamreader public void run try int ch while ch input stream reader read 1 buffer append char ch catch io exception ex system err println error io exception thrown ex ex print stack trace inputstreamreader ioexception ioexception printstacktrace public class member 002 extends live connect test public member 002 super member_002 liveconnecttest member_002 public static void main string args member 002 test new member 002 test start member_002 member_002 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 set member object data i get member js object object data i remove member js object object data i executetest getdataarray jsobject jsobject getjsobject setmember getmember jsobject removemember jsobject create and return a js object using data in the data array param data object array containing name of js object and assignment expression return the js object public js object getjs object object data string constructor data 0 data 1 js object the this js object global eval constructor return the this jsobject jsobject jsobject jsobject getjsobject jsobject thethis jsobject thethis use js object eval to assign a java script value to a property of a java script object verify that the expression returns the value of the assignment expression param data object array that has items corresponding to the name of a js object a property of that object and a java script assignment expression for that property public void set member object data object result null string eval string string data 0 string data 2 string data 3 try result global eval eval string catch exception e exception eval string threw e to string file exception exception e print stack trace finally add test case eval string returned result result equals data 5 true result equals data 5 exception jsobject javascript javascript jsobject javascript setmember evalstring evalstring evalstring tostring printstacktrace addtestcase evalstring get the value of a java script property check its type and value param the this js object whose property will be checked param data object array containing the name of the js object property and the expected value of that property public void get member js object the this object data string exception null string property string data 2 object e value data 6 object a value null class e class null class a class null string e type string data 7 string a type 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 a type string global eval typeof string data 0 string data 2 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 the this 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 check the js type of the property value add test case typeof a value returned a type a type equals e type true a type equals e type exception javascript thethis jsobject jsobject getmember jsobject thethis evalue avalue eclass aclass etype atype avalue thethis getmember avalue eclass evalue getclass aclass avalue getclass atype thethis getmember tostring printstacktrace avalue addtestcase getmember avalue thethis getmember evalue avalue evalue addtestcase avalue getclass aclass getname aclass getname eclass getname aclass getname eclass getname addtestcase avalue atype atype etype atype etype delete a js object using js object remove member after removing the member check the member s java script value and type public void remove member js object the this object data string exception null string property string data 2 object e value data 8 object a value null class e class null class a class null string e type string data 9 string a type null try the this remove member property a value the this get member property if a value null e class e value get class a class a value get class a type string global eval typeof string data 0 string data 2 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 after removing get member returned a value the this get member property equals e value true a value equals e value exception check the class of the property add test case after removing 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 check the js type of the property value add test case after removing typeof a value returned a type a type equals e type true a type equals e type exception jsobject jsobject removemember javascript removemember jsobject thethis evalue avalue eclass aclass etype atype thethis removemember avalue thethis getmember avalue eclass evalue getclass aclass avalue getclass atype thethis getmember tostring printstacktrace avalue addtestcase getmember avalue thethis getmember evalue avalue evalue addtestcase avalue getclass aclass getname aclass getname eclass getname aclass getname eclass getname addtestcase avalue atype atype etype atype etype get the data array which is an object array data arrays which are also object arrays the data arrays consist of 8 items ul li identifier for java script object li assignment expression to initialize java script object li property of java script object to set get li value to assign to property li initial value of property li value of property before calling set member li value returned by set member li value of property after calling set 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 boo 0 identifier new string new boolean 1 assignment expression new string foo 2 property new string bar 3 java script value to assign new string undefined 4 value before assignment new string bar 5 value returned by setter new string bar 6 value after assignment new string string 7 js typeof value new string undefined 8 value after removing new string undefined 9 typeof after removing object d1 new string num new string new number 12345 new string some property new string 02134 new string undefined new double 0 02134 new double 0 02134 new string number new string undefined 8 value after removing new string undefined 9 typeof after removing object d2 new string number new string number new string positive infinity new string 0 new double double positive infinity new double 0 new double double positive infinity new string number new double double positive infinity new string number object data array d0 d1 d2 return data array javascript javascript javascript setmember setmember setmember javascript getdataarray javascript someproperty positive_infinity positive_infinity positive_infinity positive_infinity dataarray dataarray static void init scriptable scope boolean sealed native array obj new native array obj export asjs class max prototype id scope sealed nativearray nativearray exportasjsclass max_prototype_id zero parameter constructor just used to create array prototype private native array dense null this length 0 nativearray public native array long length int int length int length if int length length int length 0 if int length maximum dense length int length maximum dense length dense new object int length for int i 0 i int length i dense i not found this length length nativearray intlength intlength intlength intlength maximumdenselength intlength maximumdenselength intlength intlength not_found public native array object array dense array this length array length nativearray public string get class name return array getclassname max instance id 1 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 if s equals length return instance id info dontenum permanent id length return super find instance id info s findinstanceidinfo instanceidinfo id_length findinstanceidinfo protected string get instance id name int id if id id length return length return super get instance id name id getinstanceidname id_length getinstanceidname protected object get instance id value int id if id id length return script runtime wrap number length return super get instance id value id getinstanceidvalue id_length scriptruntime wrapnumber getinstanceidvalue protected void set instance id value int id object value if id id length set length value return super set instance id value id value setinstanceidvalue id_length setlength setinstanceidvalue 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 tolocalestring arity 1 s to locale string break case id tosource arity 0 s to source break case id join arity 1 s join break case id reverse arity 0 s reverse break case id sort arity 1 s sort break case id push arity 1 s push break case id pop arity 1 s pop break case id shift arity 1 s shift break case id unshift arity 1 s unshift break case id splice arity 1 s splice break case id concat arity 1 s concat break case id slice arity 1 s slice break case id indexof arity 1 s index of break case id lastindexof arity 1 s last index of break case id every arity 1 s every break case id filter arity 1 s filter break case id foreach arity 1 s for each break case id map arity 1 s map break case id some arity 1 s some break default throw new illegal argument exception string value of id init prototype method array tag id s arity initprototypeid id_constructor id_tostring tostring id_tolocalestring tolocalestring id_tosource tosource id_join id_reverse id_sort id_push id_pop id_shift id_unshift id_splice id_concat id_slice id_indexof indexof id_lastindexof lastindexof id_every id_filter id_foreach foreach id_map id_some illegalargumentexception valueof initprototypemethod array_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag array tag return super exec id call f cx scope this obj args int id f method id switch id case id constructor boolean in new expr this obj null if in new expr id function object construct will set up parent proto return f construct cx scope args return js constructor cx scope args case id tostring return to string helper cx scope this obj cx has feature context feature to string as source false case id tolocalestring return to string helper cx scope this obj false true case id tosource return to string helper cx scope this obj true false case id join return js join cx this obj args case id reverse return js reverse cx this obj args case id sort return js sort cx scope this obj args case id push return js push cx this obj args case id pop return js pop cx this obj args case id shift return js shift cx this obj args case id unshift return js unshift cx this obj args case id splice return js splice cx scope this obj args case id concat return js concat cx scope this obj args case id slice return js slice cx this obj args case id indexof return index of helper cx this obj args false case id lastindexof return index of helper cx this obj args true case id every case id filter case id foreach case id map case id some return iterative method cx id scope this obj args throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag array_tag execidcall thisobj methodid id_constructor innewexpr thisobj innewexpr idfunctionobject jsconstructor id_tostring tostringhelper thisobj hasfeature feature_to_string_as_source id_tolocalestring tostringhelper thisobj id_tosource tostringhelper thisobj id_join js_join thisobj id_reverse js_reverse thisobj id_sort js_sort thisobj id_push js_push thisobj id_pop js_pop thisobj id_shift js_shift thisobj id_unshift js_unshift thisobj id_splice js_splice thisobj id_concat js_concat thisobj id_slice js_slice thisobj id_indexof indexofhelper thisobj id_lastindexof indexofhelper thisobj id_every id_filter id_foreach id_map id_some iterativemethod thisobj illegalargumentexception valueof public object get int index scriptable start if dense null 0 index index dense length return dense index return super get index start public boolean has int index scriptable start if dense null 0 index index dense length return dense index not found return super has index start not_found otherwise return 1l private static long to array index string id double d script runtime to number id if d d long index script runtime to uint32 d if index d index 4294967295l assume that script runtime to string index is the same as java lang long to string index for long if long to string index equals id return index return 1 toarrayindex scriptruntime tonumber scriptruntime touint32 scriptruntime tostring tostring tostring public void put string id scriptable start object value super put id start value if start this if the object is sealed super will throw exception long index to array index id if index length length index 1 toarrayindex public void put int index scriptable start object value if start this is sealed dense null 0 index index dense length if start this sealed super will throw exception dense index value else super put index start value if start this only set the array length if given an array index ecma 15 4 0 if this length index avoid overflowing index this length long index 1 issealed public void delete int index if is sealed dense null 0 index index dense length dense index not found else super delete index issealed not_found public object get ids object super ids super get ids if dense null return super ids int n dense length long current length length if n current length n int current length if n 0 return super ids int super length super ids length object ids new object n super length make a copy of dense to be immune to removing of array elems from other thread when calculating present count system arraycopy dense 0 ids 0 n int present count 0 for int i 0 i n i replace existing elements by their indexes if ids i not found ids present count new integer i present count if present count n dense contains deleted elems need to shrink the result object tmp new object present count super length system arraycopy ids 0 tmp 0 present count ids tmp system arraycopy super ids 0 ids present count super length return ids getids superids getids superids currentlength currentlength currentlength superids superlength superids superlength presentcount presentcount not_found presentcount presentcount presentcount presentcount superlength presentcount superids presentcount superlength public object get default value class hint if hint script runtime number class context cx context get context if cx get language version context version 1 2 return new long length return super get default value hint getdefaultvalue scriptruntime numberclass getcontext getlanguageversion version_1_2 getdefaultvalue see ecma 15 4 1 2 private static object js constructor context cx scriptable scope object args if args length 0 return new native array only use 1 arg as first element for version 1 2 for any other version including 1 3 follow ecma and use it as a length if cx get language version context version 1 2 return new native array args else object arg0 args 0 if args length 1 arg0 instanceof number return new native array args else long len script runtime to uint32 arg0 if len number arg0 double value throw context report runtime error0 msg arraylength bad return new native array len jsconstructor nativearray getlanguageversion version_1_2 nativearray nativearray scriptruntime touint32 doublevalue reportruntimeerror0 nativearray public long get length return length getlength deprecated use link get length instead public long jsget length return get length getlength jsget_length getlength private void set length object val xxx do we satisfy this 15 4 5 1 put p v 1 call the can put method of a with name p 2 if result 1 is false return double d script runtime to number val long long val script runtime to uint32 d if long val d throw context report runtime error0 msg arraylength bad if long val length remove all properties between long val and length if length long val 0x1000 assume that the representation is sparse object e get ids will only find in object itself for int i 0 i e length i object id e i if id instanceof string maxint will appear as string string str id string id long index to array index str id if index long val delete str id else int index integer id int value if index long val delete index else assume a dense representation for long i long val i length i delete elem this i length long val setlength canput scriptruntime tonumber longval scriptruntime touint32 longval reportruntimeerror0 longval longval longval getids strid toarrayindex strid longval strid intvalue longval longval deleteelem longval static long get length property context cx scriptable obj these will both give numeric lengths within uint32 range if obj instanceof native string return native string obj get length else if obj instanceof native array return native array obj get length else if obj instanceof scriptable return 0 return script runtime to uint32 script runtime get object prop obj length cx getlengthproperty nativestring nativestring getlength nativearray nativearray getlength scriptruntime touint32 scriptruntime getobjectprop private static object set length property context cx scriptable target long length return script runtime set object prop target length script runtime wrap number length cx setlengthproperty scriptruntime setobjectprop scriptruntime wrapnumber private static void delete elem scriptable target long index int i int index if i index target delete i else target delete long to string index deleteelem tostring private static object get elem context cx scriptable target long index if index integer max value string id long to string index return script runtime get object prop target id cx else return script runtime get object index target int index cx getelem max_value tostring scriptruntime getobjectprop scriptruntime getobjectindex private static void set elem context cx scriptable target long index object value if index integer max value string id long to string index script runtime set object prop target id value cx else script runtime set object index target int index value cx setelem max_value tostring scriptruntime setobjectprop scriptruntime setobjectindex private static string to string helper context cx scriptable scope scriptable this obj boolean to source boolean to locale it s probably redundant to handle long lengths in this function string buffers are limited to 2 31 in java long length get length property cx this obj string buffer result new string buffer 256 whether to return 4 unquoted 5 or 4 quoted 5 string separator if to source result append separator else separator boolean haslast false long i 0 boolean toplevel iterating if cx iterating null toplevel true iterating false cx iterating new obj to int map 31 else toplevel false iterating cx iterating has this obj make sure cx iterating is set to null when done so we don t leak memory try if iterating cx iterating put this obj 0 stop recursion for i 0 i length i if i 0 result append separator object elem get elem cx this obj i if elem null elem undefined instance haslast false continue haslast true if to source result append script runtime uneval cx scope elem else if elem instanceof string string s string elem if to source result append result append script runtime escape string s result append else result append s else if to locale elem undefined instance elem null callable fun scriptable fun this fun script runtime get prop function and this elem to locale string cx fun this script runtime last stored scriptable cx elem fun call cx scope fun this script runtime empty args result append script runtime to string elem finally if toplevel cx iterating null if to source for length behavior we want to string to be symmetric if haslast i 0 result append else result append return result to string tostringhelper thisobj tosource tolocale stringbuffers getlengthproperty thisobj stringbuffer stringbuffer tosource objtointmap thisobj thisobj getelem thisobj tosource scriptruntime tosource scriptruntime escapestring tolocale funthis scriptruntime getpropfunctionandthis tolocalestring funthis scriptruntime laststoredscriptable funthis scriptruntime emptyargs scriptruntime tostring tosource tostring tostring see ecma 15 4 4 3 private static string js join context cx scriptable this obj object args string separator long llength get length property cx this obj int length int llength if llength length throw context report runtime error1 msg arraylength too big string value of llength if no args use as separator if args length 1 args 0 undefined instance separator else separator script runtime to string args 0 if length 0 return string buf new string length int total size 0 for int i 0 i length i object temp get elem cx this obj i if temp null temp undefined instance string str script runtime to string temp total size str length buf i str total size length 1 separator length string buffer sb new string buffer total size for int i 0 i length i if i 0 sb append separator string str buf i if str null str null for undefined or null sb append str return sb to string js_join thisobj getlengthproperty thisobj reportruntimeerror1 valueof scriptruntime tostring total_size getelem thisobj scriptruntime tostring total_size total_size stringbuffer stringbuffer total_size tostring see ecma 15 4 4 4 private static scriptable js reverse context cx scriptable this obj object args long len get length property cx this obj long half len 2 for long i 0 i half i long j len i 1 object temp1 get elem cx this obj i object temp2 get elem cx this obj j set elem cx this obj i temp2 set elem cx this obj j temp1 return this obj js_reverse thisobj getlengthproperty thisobj getelem thisobj getelem thisobj setelem thisobj setelem thisobj thisobj see ecma 15 4 4 5 private static scriptable js sort context cx scriptable scope scriptable this obj object args long length get length property cx this obj if length 1 return this obj object compare object cmp buf if args length 0 undefined instance args 0 sort with given compare function compare args 0 cmp buf new object 2 buffer for cmp arguments else sort with default compare compare null cmp buf null should we use the extended sort function or the faster one if length integer max value heapsort extended cx scope this obj length compare cmp buf else int ilength int length copy the js array into a working array so it can be sorted cheaply object working new object ilength for int i 0 i ilength i working i get elem cx this obj i heapsort cx scope working ilength compare cmp buf copy the working array back into this obj for int i 0 i ilength i set elem cx this obj i working i return this obj js_sort thisobj getlengthproperty thisobj thisobj cmpbuf cmpbuf cmpbuf max_value heapsort_extended thisobj cmpbuf getelem thisobj cmpbuf thisobj setelem thisobj thisobj return true only if x y private static boolean is bigger context cx scriptable scope object x object y object cmp object cmp buf if cmp null if cmp buf null kit code bug else if cmp buf null cmp buf length 2 kit code bug object undef undefined instance sort undefined to end if undef y return false x can not be bigger then undef else if undef x return true y undef here so x y if cmp null if no cmp function supplied sort lexicographically string a script runtime to string x string b script runtime to string y return a compare to b 0 else assemble args and call supplied js cmp function cmp buf 0 x cmp buf 1 y callable fun script runtime get value function and this cmp cx scriptable fun this script runtime last stored scriptable cx object ret fun call cx scope fun this cmp buf double d script runtime to number ret xxx what to do when cmp function returns nan ecma states that it s then not a consistent compararison function but then what do we do back out and start over with the generic cmp function when we see a nan throw an error for now just ignore it return d 0 isbigger cmpbuf cmpbuf codebug cmpbuf cmpbuf codebug scriptruntime tostring scriptruntime tostring compareto cmpbuf cmpbuf scriptruntime getvaluefunctionandthis funthis scriptruntime laststoredscriptable funthis cmpbuf scriptruntime tonumber heapsort implementation see introduction to algorithms by cormen leiserson rivest for details adjusted for zero based indexes private static void heapsort context cx scriptable scope object array int length object cmp object cmp buf if length 1 kit code bug build heap for int i length 2 i 0 i object pivot array i heapify cx scope pivot array i length cmp cmp buf sort heap for int i length i 1 i object pivot array i array i array 0 heapify cx scope pivot array 0 i cmp cmp buf cmpbuf codebug cmpbuf cmpbuf pivot and child heaps of i should be made into heap starting at i original array i is never used to have less array access during sorting private static void heapify context cx scriptable scope object pivot object array int i int end object cmp object cmp buf for int child i 2 1 if child end break object child val array child if child 1 end object next val array child 1 if is bigger cx scope next val child val cmp cmp buf child child val next val if is bigger cx scope child val pivot cmp cmp buf break array i child val i child array i pivot cmpbuf childval nextval isbigger nextval childval cmpbuf childval nextval isbigger childval cmpbuf childval version of heapsort that call get elem set elem on target to query assign array elements instead of java array access private static void heapsort extended context cx scriptable scope scriptable target long length object cmp object cmp buf if length 1 kit code bug build heap for long i length 2 i 0 i object pivot get elem cx target i heapify extended cx scope pivot target i length cmp cmp buf sort heap for long i length i 1 i object pivot get elem cx target i set elem cx target i get elem cx target 0 heapify extended cx scope pivot target 0 i cmp cmp buf getelem setelem heapsort_extended cmpbuf codebug getelem heapify_extended cmpbuf getelem setelem getelem heapify_extended cmpbuf private static void heapify extended context cx scriptable scope object pivot scriptable target long i long end object cmp object cmp buf for long child i 2 1 if child end break object child val get elem cx target child if child 1 end object next val get elem cx target child 1 if is bigger cx scope next val child val cmp cmp buf child child val next val if is bigger cx scope child val pivot cmp cmp buf break set elem cx target i child val i child set elem cx target i pivot heapify_extended cmpbuf childval getelem nextval getelem isbigger nextval childval cmpbuf childval nextval isbigger childval cmpbuf setelem childval setelem non ecma methods private static object js push context cx scriptable this obj object args long length get length property cx this obj for int i 0 i args length i set elem cx this obj length i args i length args length object length obj set length property cx this obj length if js1 2 follow perl4 by returning the last thing pushed otherwise return the new array length if cx get language version context version 1 2 if js1 2 no arguments return undefined return args length 0 undefined instance args args length 1 else return length obj js_push thisobj getlengthproperty thisobj setelem thisobj lengthobj setlengthproperty thisobj getlanguageversion version_1_2 lengthobj private static object js pop context cx scriptable this obj object args object result long length get length property cx this obj if length 0 length get the to be deleted property s value result get elem cx this obj length we don t need to delete the last property because set length does that for us else result undefined instance necessary to match js even when length 0 js pop will give a length property to any target it is called on set length property cx this obj length return result js_pop thisobj getlengthproperty thisobj getelem thisobj setlength setlengthproperty thisobj private static object js shift context cx scriptable this obj object args object result long length get length property cx this obj if length 0 long i 0 length get the to be deleted property s value result get elem cx this obj i slide down the array above the first element leave i set to point to the last element if length 0 for i 1 i length i object temp get elem cx this obj i set elem cx this obj i 1 temp we don t need to delete the last property because set length does that for us else result undefined instance set length property cx this obj length return result js_shift thisobj getlengthproperty thisobj getelem thisobj getelem thisobj setelem thisobj setlength setlengthproperty thisobj private static object js unshift context cx scriptable this obj object args object result long length get length property cx this obj int argc args length if args length 0 slide up the array to make room for args at the bottom if length 0 for long last length 1 last 0 last object temp get elem cx this obj last set elem cx this obj last argc temp copy from argv to the bottom of the array for int i 0 i args length i set elem cx this obj i args i follow perl by returning the new array length length args length return set length property cx this obj length return script runtime wrap number length js_unshift thisobj getlengthproperty thisobj getelem thisobj setelem thisobj setelem thisobj setlengthproperty thisobj scriptruntime wrapnumber private static object js splice context cx scriptable scope scriptable this obj object args create an empty array to return scope get top level scope scope object result script runtime new object cx scope array null int argc args length if argc 0 return result long length get length property cx this obj convert the first argument into a starting index long begin to slice index script runtime to integer args 0 length argc convert the second argument into count long count if args length 1 count length begin else double dcount script runtime to integer args 1 if dcount 0 count 0 else if dcount length begin count length begin else count long dcount argc long end begin count if there are elements to remove put them into the return value if count 0 if count 1 cx get language version context version 1 2 js lacks list context whereby in perl one turns the single scalar that s spliced out into an array just by assigning it to single instead of single or by using it as perl push s first argument for instance js1 2 emulated perl too closely and returned a non array for the single splice out case requiring callers to test and wrap in if necessary so js1 3 default and other versions all return an array of length 1 for uniformity result get elem cx this obj begin else for long last begin last end last scriptable result array scriptable result object temp get elem cx this obj last set elem cx result array last begin temp else if count 0 cx get language version context version 1 2 emulate c js1 2 if no elements are removed return undefined result undefined instance find the direction up or down to copy and make way for argv long delta argc count if delta 0 for long last length 1 last end last object temp get elem cx this obj last set elem cx this obj last delta temp else if delta 0 for long last end last length last object temp get elem cx this obj last set elem cx this obj last delta temp copy from argv into the hole to complete the splice int argoffset args length argc for int i 0 i argc i set elem cx this obj begin i args i argoffset update length in case we deleted elements from the end set length property cx this obj length delta return result js_splice thisobj gettoplevelscope scriptruntime newobject getlengthproperty thisobj tosliceindex scriptruntime tointeger scriptruntime tointeger getlanguageversion version_1_2 getelem thisobj resultarray getelem thisobj setelem resultarray getlanguageversion version_1_2 getelem thisobj setelem thisobj getelem thisobj setelem thisobj setelem thisobj setlengthproperty thisobj private static scriptable js concat context cx scriptable scope scriptable this obj object args create an empty array to return scope get top level scope scope function ctor script runtime get existing ctor cx scope array scriptable result ctor construct cx scope script runtime empty args long length long slot 0 put the target in the result array only add it as an array if it looks like one if script runtime instance of this obj ctor cx length get length property cx this obj copy from the target object into the result for slot 0 slot length slot object temp get elem cx this obj slot set elem cx result slot temp else set elem cx result slot this obj copy from the arguments into the result if any argument has a numeric length property treat it as an array and add elements separately otherwise just copy the argument for int i 0 i args length i if script runtime instance of args i ctor cx script runtime instance of instanceof scriptable scriptable arg scriptable args i length get length property cx arg for long j 0 j length j slot object temp get elem cx arg j set elem cx result slot temp else set elem cx result slot args i return result js_concat thisobj gettoplevelscope scriptruntime getexistingctor scriptruntime emptyargs scriptruntime instanceof thisobj getlengthproperty thisobj getelem thisobj setelem setelem thisobj scriptruntime instanceof scriptruntime instanceof getlengthproperty getelem setelem setelem private scriptable js slice context cx scriptable this obj object args scriptable scope get top level scope this scriptable result script runtime new object cx scope array null long length get length property cx this obj long begin end if args length 0 begin 0 end length else begin to slice index script runtime to integer args 0 length if args length 1 end length else end to slice index script runtime to integer args 1 length for long slot begin slot end slot object temp get elem cx this obj slot set elem cx result slot begin temp return result js_slice thisobj gettoplevelscope scriptruntime newobject getlengthproperty thisobj tosliceindex scriptruntime tointeger tosliceindex scriptruntime tointeger getelem thisobj setelem private static long to slice index double value long length long result if value 0 0 if value length 0 0 result 0 else result long value length else if value length result length else result long value return result tosliceindex implements the methods index of and last index of private object index of helper context cx scriptable this obj object args boolean is last object compare to args length 0 args 0 undefined instance long length get length property cx this obj long start args length 1 script runtime to int32 script runtime to number args 1 is last length 0 if start 0 start length if start 0 start 0 if is last for long i start i 0 i if script runtime shallow eq get elem cx this obj i compare to return new long i else for long i start i length i if script runtime shallow eq get elem cx this obj i compare to return new long i return negative one indexof lastindexof indexofhelper thisobj islast compareto getlengthproperty thisobj scriptruntime toint32 scriptruntime tonumber islast islast scriptruntime shalloweq getelem thisobj compareto scriptruntime shalloweq getelem thisobj compareto negative_one implements the methods every filter for each map and some private object iterative method context cx int id scriptable scope scriptable this obj object args object callback arg args length 0 args 0 undefined instance if callback arg null callback arg instanceof function throw script runtime not function error script runtime to string callback arg function f function callback arg scriptable parent scriptable object get top level scope f scriptable this arg args length 1 args 1 instanceof scriptable scriptable args 1 parent long length get length property cx this obj scriptable array null if id id filter array script runtime new object cx scope array null else if id id map allocate dense array for efficiency object ctor args new long length array script runtime new object cx scope array ctor args object inner args new object 3 long j 0 for long i 0 i length i inner args 0 get elem cx this obj i inner args 1 new long i inner args 2 this obj object result f call cx parent this arg inner args switch id case id every if script runtime to boolean result return boolean false break case id filter if script runtime to boolean result set elem cx array j inner args 0 break case id foreach break case id map set elem cx array j result break case id some if script runtime to boolean result return boolean true break switch id case id every return boolean true case id filter case id map return array case id some return boolean false case id foreach default return undefined instance foreach iterativemethod thisobj callbackarg callbackarg callbackarg scriptruntime notfunctionerror scriptruntime tostring callbackarg callbackarg scriptableobject gettoplevelscope thisarg getlengthproperty thisobj id_filter scriptruntime newobject id_map ctorargs scriptruntime newobject ctorargs innerargs innerargs getelem thisobj innerargs innerargs thisobj thisarg innerargs id_every scriptruntime toboolean id_filter scriptruntime toboolean setelem innerargs id_foreach id_map setelem id_some scriptruntime toboolean id_every id_filter id_map id_some id_foreach protected int find prototype id string s int id generated last update 2005 09 26 15 47 42 edt l0 id 0 string x null int c l switch s length case 3 c s char at 0 if c m if s char at 2 p s char at 1 a id id map break l0 else if c p if s char at 2 p s char at 1 o id id pop break l0 break l case 4 switch s char at 2 case i x join id id join break l case m x some id id some break l case r x sort id id sort break l case s x push id id push break l break l case 5 c s char at 1 if c h x shift id id shift else if c l x slice id id slice else if c v x every id id every break l case 6 c s char at 0 if c c x concat id id concat else if c f x filter id id filter else if c s x splice id id splice break l case 7 switch s char at 0 case f x for each id id foreach break l case i x index of id id indexof break l case r x reverse id id reverse break l case u x unshift id id unshift break l 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 l x last index of id id lastindexof 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 charat charat id_map charat charat id_pop charat id_join id_some id_sort id_push charat id_shift id_slice id_every charat id_concat id_filter id_splice charat foreach id_foreach indexof id_indexof id_reverse id_unshift charat tosource id_tosource tostring id_tostring charat id_constructor lastindexof id_lastindexof tolocalestring id_tolocalestring create a new synchronized function from an existing one param obj the existing function public synchronizer scriptable obj super obj see org mozilla javascript function call public object call context cx scriptable scope scriptable this obj object args synchronized this obj return function obj call cx scope this obj args thisobj thisobj thisobj xml ctor xml xml object tag int id int arity super xml tag id arity this lib xml lib activate prototype map max function id xmlctor activateprototypemap max_function_id private void write setting scriptable target for int i 1 i max instance id i int id super get max instance id i string name get instance id name id object value get instance id value id scriptable object put property target name value writesetting max_instance_id getmaxinstanceid getinstanceidname getinstanceidvalue scriptableobject putproperty private void read settings scriptable source for int i 1 i max instance id i int id super get max instance id i string name get instance id name id object value scriptable object get property source name if value scriptable object not found continue switch i case id ignorecomments case id ignoreprocessinginstructions case id ignorewhitespace case id prettyprinting if value instanceof boolean continue break case id prettyindent if value instanceof number continue break default throw new illegal state exception set instance id value id value readsettings max_instance_id getmaxinstanceid getinstanceidname scriptableobject getproperty scriptableobject not_found id_ignorecomments id_ignoreprocessinginstructions id_ignorewhitespace id_prettyprinting id_prettyindent illegalstateexception setinstanceidvalue max instance id 5 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 19 13 03 52 cest l0 id 0 string x null int c l switch s length case 12 x pretty indent id id prettyindent break l case 14 c s char at 0 if c i x ignore comments id id ignorecomments else if c p x pretty printing id id prettyprinting break l case 16 x ignore whitespace id id ignorewhitespace break l case 28 x ignore processing instructions id id ignoreprocessinginstructions break l 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 ignorecomments case id ignoreprocessinginstructions case id ignorewhitespace case id prettyindent case id prettyprinting attr permanent dontenum break default throw new illegal state exception return instance id info attr super get max instance id id findinstanceidinfo prettyindent id_prettyindent charat ignorecomments id_ignorecomments prettyprinting id_prettyprinting ignorewhitespace id_ignorewhitespace ignoreprocessinginstructions id_ignoreprocessinginstructions findinstanceidinfo id_ignorecomments id_ignoreprocessinginstructions id_ignorewhitespace id_prettyindent id_prettyprinting illegalstateexception instanceidinfo getmaxinstanceid protected string get instance id name int id switch id super get max instance id case id ignorecomments return ignore comments case id ignoreprocessinginstructions return ignore processing instructions case id ignorewhitespace return ignore whitespace case id prettyindent return pretty indent case id prettyprinting return pretty printing return super get instance id name id getinstanceidname getmaxinstanceid id_ignorecomments ignorecomments id_ignoreprocessinginstructions ignoreprocessinginstructions id_ignorewhitespace ignorewhitespace id_prettyindent prettyindent id_prettyprinting prettyprinting getinstanceidname protected object get instance id value int id switch id super get max instance id case id ignorecomments return script runtime wrap boolean lib ignore comments case id ignoreprocessinginstructions return script runtime wrap boolean lib ignore processing instructions case id ignorewhitespace return script runtime wrap boolean lib ignore whitespace case id prettyindent return script runtime wrap int lib pretty indent case id prettyprinting return script runtime wrap boolean lib pretty printing return super get instance id value id getinstanceidvalue getmaxinstanceid id_ignorecomments scriptruntime wrapboolean ignorecomments id_ignoreprocessinginstructions scriptruntime wrapboolean ignoreprocessinginstructions id_ignorewhitespace scriptruntime wrapboolean ignorewhitespace id_prettyindent scriptruntime wrapint prettyindent id_prettyprinting scriptruntime wrapboolean prettyprinting getinstanceidvalue protected void set instance id value int id object value switch id super get max instance id case id ignorecomments lib ignore comments script runtime to boolean value return case id ignoreprocessinginstructions lib ignore processing instructions script runtime to boolean value return case id ignorewhitespace lib ignore whitespace script runtime to boolean value return case id prettyindent lib pretty indent script runtime to int32 value return case id prettyprinting lib pretty printing script runtime to boolean value return super set instance id value id value setinstanceidvalue getmaxinstanceid id_ignorecomments ignorecomments scriptruntime toboolean id_ignoreprocessinginstructions ignoreprocessinginstructions scriptruntime toboolean id_ignorewhitespace ignorewhitespace scriptruntime toboolean id_prettyindent prettyindent scriptruntime toint32 id_prettyprinting prettyprinting scriptruntime toboolean setinstanceidvalue protected int find prototype id string s int id generated last update 2004 07 19 13 03 52 cest l0 id 0 string x null int s length s length if s length 8 x settings id id settings else if s length 11 x set settings id id setsettings else if s length 15 x default settings id id defaultsettings if x null x s x equals s id 0 generated return id findprototypeid s_length s_length id_settings s_length setsettings id_setsettings s_length defaultsettings id_defaultsettings protected void init prototype id int id string s int arity switch id case id defaultsettings arity 0 s default settings break case id settings arity 0 s settings break case id setsettings arity 1 s set settings break default throw new illegal argument exception string value of id init prototype method xmlctor tag id s arity initprototypeid id_defaultsettings defaultsettings id_settings id_setsettings setsettings illegalargumentexception valueof initprototypemethod xmlctor_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag xmlctor tag return super exec id call f cx scope this obj args int id f method id switch id case id defaultsettings lib default settings scriptable obj cx new object scope write setting obj return obj case id settings scriptable obj cx new object scope write setting obj return obj case id setsettings scriptable obj null if args length 0 args 0 null args 0 undefined instance lib default settings else if args 0 instanceof scriptable read settings scriptable args 0 return undefined instance throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag xmlctor_tag execidcall thisobj methodid id_defaultsettings defaultsettings newobject writesetting id_settings newobject writesetting id_setsettings defaultsettings readsettings illegalargumentexception valueof static void init scriptable scope boolean sealed native string obj new native string obj export asjs class max prototype id scope sealed nativestring nativestring exportasjsclass max_prototype_id private native string string s string s nativestring public string get class name return string getclassname max instance id 1 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 if s equals length return instance id info dontenum readonly permanent id length return super find instance id info s findinstanceidinfo instanceidinfo id_length findinstanceidinfo protected string get instance id name int id if id id length return length return super get instance id name id getinstanceidname id_length getinstanceidname protected object get instance id value int id if id id length return script runtime wrap int string length return super get instance id value id getinstanceidvalue id_length scriptruntime wrapint getinstanceidvalue protected void fill constructor properties id function object ctor add id function property ctor string tag constructorid fromcharcode from char code 1 super fill constructor properties ctor fillconstructorproperties idfunctionobject addidfunctionproperty string_tag constructorid_fromcharcode fromcharcode 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 tosource arity 0 s to source break case id valueof arity 0 s value of break case id charat arity 1 s char at break case id charcodeat arity 1 s char code at break case id indexof arity 1 s index of break case id lastindexof arity 1 s last index of break case id split arity 2 s split break case id substring arity 2 s substring break case id tolowercase arity 0 s to lower case break case id touppercase arity 0 s to upper case break case id substr arity 2 s substr break case id concat arity 1 s concat break case id slice arity 2 s slice break case id bold arity 0 s bold break case id italics arity 0 s italics break case id fixed arity 0 s fixed break case id strike arity 0 s strike break case id small arity 0 s small break case id big arity 0 s big break case id blink arity 0 s blink break case id sup arity 0 s sup break case id sub arity 0 s sub break case id fontsize arity 0 s fontsize break case id fontcolor arity 0 s fontcolor break case id link arity 0 s link break case id anchor arity 0 s anchor break case id equals arity 1 s equals break case id equalsignorecase arity 1 s equals ignore case break case id match arity 1 s match break case id search arity 1 s search break case id replace arity 1 s replace break default throw new illegal argument exception string value of id init prototype method string tag id s arity initprototypeid id_constructor id_tostring tostring id_tosource tosource id_valueof valueof id_charat charat id_charcodeat charcodeat id_indexof indexof id_lastindexof lastindexof id_split id_substring id_tolowercase tolowercase id_touppercase touppercase id_substr id_concat id_slice id_bold id_italics id_fixed id_strike id_small id_big id_blink id_sup id_sub id_fontsize id_fontcolor id_link id_anchor id_equals id_equalsignorecase equalsignorecase id_match id_search id_replace illegalargumentexception valueof initprototypemethod string_tag public object exec id call id function object f context cx scriptable scope scriptable this obj object args if f has tag string tag return super exec id call f cx scope this obj args int id f method id switch id case constructorid fromcharcode int n args length if n 1 return string buffer sb new string buffer n for int i 0 i n i sb append script runtime to uint16 args i return sb to string case id constructor string s args length 1 script runtime to string args 0 if this obj null new string val creates a new string object return new native string s string val converts val to a string value return s case id tostring case id valueof ecma 15 5 4 2 the to string function is not generic return real this this obj f string case id tosource string s real this this obj f string return new string script runtime escape string s case id charat case id charcodeat see ecma 15 5 4 4 5 string target script runtime to string this obj double pos script runtime to integer args 0 if pos 0 pos target length if id id charat return else return script runtime na nobj char c target char at int pos if id id charat return string value of c else return script runtime wrap int c case id indexof return script runtime wrap int js indexof script runtime to string this obj args case id lastindexof return script runtime wrap int js lastindexof script runtime to string this obj args case id split return js split cx scope script runtime to string this obj args case id substring return js substring cx script runtime to string this obj args case id tolowercase see ecma 15 5 4 11 return script runtime to string this obj to lower case case id touppercase see ecma 15 5 4 12 return script runtime to string this obj to upper case case id substr return js substr script runtime to string this obj args case id concat return js concat script runtime to string this obj args case id slice return js slice script runtime to string this obj args case id bold return tagify this obj b null null case id italics return tagify this obj i null null case id fixed return tagify this obj tt null null case id strike return tagify this obj strike null null case id small return tagify this obj small null null case id big return tagify this obj big null null case id blink return tagify this obj blink null null case id sup return tagify this obj sup null null case id sub return tagify this obj sub null null case id fontsize return tagify this obj font size args case id fontcolor return tagify this obj font color args case id link return tagify this obj a href args case id anchor return tagify this obj a name args case id equals case id equalsignorecase string s1 script runtime to string this obj string s2 script runtime to string args 0 return script runtime wrap boolean id id equals s1 equals s2 s1 equals ignore case s2 case id match case id search case id replace int action type if id id match action type reg exp proxy ra match else if id id search action type reg exp proxy ra search else action type reg exp proxy ra replace return script runtime check reg exp proxy cx action cx scope this obj args action type throw new illegal argument exception string value of id execidcall idfunctionobject thisobj hastag string_tag execidcall thisobj methodid constructorid_fromcharcode stringbuffer stringbuffer scriptruntime touint16 tostring id_constructor scriptruntime tostring thisobj nativestring id_tostring id_valueof tostring realthis thisobj id_tosource realthis thisobj scriptruntime escapestring id_charat id_charcodeat scriptruntime tostring thisobj scriptruntime tointeger id_charat scriptruntime nanobj charat id_charat valueof scriptruntime wrapint id_indexof scriptruntime wrapint js_indexof scriptruntime tostring thisobj id_lastindexof scriptruntime wrapint js_lastindexof scriptruntime tostring thisobj id_split js_split scriptruntime tostring thisobj id_substring js_substring scriptruntime tostring thisobj id_tolowercase scriptruntime tostring thisobj tolowercase id_touppercase scriptruntime tostring thisobj touppercase id_substr js_substr scriptruntime tostring thisobj id_concat js_concat scriptruntime tostring thisobj id_slice js_slice scriptruntime tostring thisobj id_bold thisobj id_italics thisobj id_fixed thisobj id_strike thisobj id_small thisobj id_big thisobj id_blink thisobj id_sup thisobj id_sub thisobj id_fontsize thisobj id_fontcolor thisobj id_link thisobj id_anchor thisobj id_equals id_equalsignorecase scriptruntime tostring thisobj scriptruntime tostring scriptruntime wrapboolean id_equals equalsignorecase id_match id_search id_replace actiontype id_match actiontype regexpproxy ra_match id_search actiontype regexpproxy ra_search actiontype regexpproxy ra_replace scriptruntime checkregexpproxy thisobj actiontype illegalargumentexception valueof private static native string real this scriptable this obj id function object f if this obj instanceof native string throw incompatible call error f return native string this obj nativestring realthis thisobj idfunctionobject thisobj nativestring incompatiblecallerror nativestring thisobj private static string tagify object this obj string tag string attribute object args string str script runtime to string this obj string buffer result new string buffer result append result append tag if attribute null result append result append attribute result append result append script runtime to string args 0 result append result append result append str result append result append tag result append return result to string thisobj scriptruntime tostring thisobj stringbuffer stringbuffer scriptruntime tostring tostring public string to string return string tostring public object get int index scriptable start if 0 index index string length return string substring index index 1 return super get index start public void put int index scriptable start object value if 0 index index string length return super put index start value private static int js indexof string target object args string search script runtime to string args 0 double begin script runtime to integer args 1 if begin target length return 1 else if begin 0 begin 0 return target index of search int begin js_indexof scriptruntime tostring scriptruntime tointeger indexof private static int js lastindexof string target object args string search script runtime to string args 0 double end script runtime to number args 1 if end end end target length end target length else if end 0 end 0 return target last index of search int end js_lastindexof scriptruntime tostring scriptruntime tonumber lastindexof private static int find split context cx scriptable scope string target string separator int version reg exp proxy re proxy scriptable re int ip int matchlen boolean matched string parensp int i ip 0 int length target length perl4 special case for str split only if the user has selected java script1 2 explicitly split on whitespace and skip leading w s strange but true apparently modeled after awk if version context version 1 2 re null separator length 1 separator char at 0 skip leading whitespace if at front of str if i 0 while i length character is whitespace target char at i i ip 0 i don t delimit whitespace at end of string if i length return 1 skip over the non whitespace chars while i length character is whitespace target char at i i now skip the next run of whitespace int j i while j length character is whitespace target char at j j update matchlen to count delimiter chars matchlen 0 j i return i stop if past end of string if at end of string we will return target length so that ab split new array ab and the resulting array converts back to the string ab for symmetry nb this differs from perl which drops the trailing empty substring if the limit argument is omitted if i length return 1 match a regular expression against the separator at or above index i return 1 at end of string instead of trying for a match so we don t get stuck in a loop if re null return re proxy find split cx scope target separator re ip matchlen matched parensp deviate from ecma by never splitting an empty string by any separator string into a non empty array an array of length 1 that contains the empty string if version context version default version context version 1 3 length 0 return 1 special case if sep is the empty string split str into one character substrings let our caller worry about whether to split once at end of string into an empty substring for 1 2 compatibility at the end of the string we return the length as the result and set the separator length to 1 this allows the caller to include an additional null string at the end of the substring list if separator length 0 if version context version 1 2 if i length matchlen 0 1 return i return i 1 return i length 1 i 1 punt to j l s index of return target length if separator is not found if ip 0 length return length i target index of separator ip 0 return i 1 i length find_split regexpproxy reproxy javascript1 version_1_2 charat iswhitespace charat iswhitespace charat iswhitespace charat reproxy find_split version_default version_1_3 version_1_2 indexof indexof private static object js split context cx scriptable scope string target object args create an empty array to return scriptable top get top level scope scope scriptable result script runtime new object cx top array null return an array consisting of the target if no separator given don t check against undefined because we want fooundefinedbar split void 0 to split to foo bar if args length 1 result put 0 result target return result use the second argument as the split limit if given boolean limited args length 1 args 1 undefined instance long limit 0 initialize to avoid warning if limited clamp limit between 0 and 1 string length limit script runtime to uint32 args 1 if limit target length limit 1 target length string separator null int matchlen new int 1 scriptable re null reg exp proxy re proxy null if args 0 instanceof scriptable re proxy script runtime get reg exp proxy cx if re proxy null scriptable test scriptable args 0 if re proxy is reg exp test re test if re null separator script runtime to string args 0 matchlen 0 separator length split target with separator or re int ip 0 int match int len 0 boolean matched false string parens null int version cx get language version while match find split cx scope target separator version re proxy re ip matchlen matched parens 0 if limited len limit match target length break string substr if target length 0 substr target else substr target substring ip 0 match result put len result substr len imitate perl s feature of including parenthesized substrings that matched part of the delimiter in the new array after the split substring that was delimited if re null matched 0 true int size parens 0 length for int num 0 num size num if limited len limit break result put len result parens 0 num len matched 0 false ip 0 match matchlen 0 if version context version 1 3 version context version default deviate from ecma to imitate perl which omits a final split unless a limit argument is given and big enough if limited ip 0 target length break return result js_split gettoplevelscope scriptruntime newobject scriptruntime touint32 regexpproxy reproxy reproxy scriptruntime getregexpproxy reproxy reproxy isregexp scriptruntime tostring getlanguageversion find_split reproxy version_1_3 version_default private static string js substring context cx string target object args int length target length double start script runtime to integer args 0 double end if start 0 start 0 else if start length start length if args length 1 args 1 undefined instance end length else end script runtime to integer args 1 if end 0 end 0 else if end length end length swap if end start if end start if cx get language version context version 1 2 double temp start start end end temp else emulate old jdk1 0 java lang string substring end start return target substring int start int end js_substring scriptruntime tointeger scriptruntime tointeger getlanguageversion version_1_2 int get length return string length getlength private static string js substr string target object args if args length 1 return target double begin script runtime to integer args 0 double end int length target length if begin 0 begin length if begin 0 begin 0 else if begin length begin length if args length 1 end length else end script runtime to integer args 1 if end 0 end 0 end begin if end length end length return target substring int begin int end js_substr scriptruntime tointeger scriptruntime tointeger private static string js concat string target object args int n args length if n 0 return target else if n 1 string arg script runtime to string args 0 return target concat arg find total capacity for the final string to avoid unnecessary re allocations in string buffer int size target length string args as strings new string n for int i 0 i n i string s script runtime to string args i args as strings i s size s length string buffer result new string buffer size result append target for int i 0 i n i result append args as strings i return result to string js_concat scriptruntime tostring stringbuffer argsasstrings scriptruntime tostring argsasstrings stringbuffer stringbuffer argsasstrings tostring private static string js slice string target object args if args length 0 double begin script runtime to integer args 0 double end int length target length if begin 0 begin length if begin 0 begin 0 else if begin length begin length if args length 1 end length else end script runtime to integer args 1 if end 0 end length if end 0 end 0 else if end length end length if end begin end begin return target substring int begin int end return target js_slice scriptruntime tointeger scriptruntime tointeger protected int find prototype id string s int id generated last update 2004 03 17 13 44 29 cet l0 id 0 string x null int c l switch s length case 3 c s char at 2 if c b if s char at 0 s s char at 1 u id id sub break l0 else if c g if s char at 0 b s char at 1 i id id big break l0 else if c p if s char at 0 s s char at 1 u id id sup break l0 break l case 4 c s char at 0 if c b x bold id id bold else if c l x link id id link break l case 5 switch s char at 4 case d x fixed id id fixed break l case e x slice id id slice break l case h x match id id match break l case k x blink id id blink break l case l x small id id small break l case t x split id id split break l break l case 6 switch s char at 1 case e x search id id search break l case h x char at id id charat break l case n x anchor id id anchor break l case o x concat id id concat break l case q x equals id id equals break l case t x strike id id strike break l case u x substr id id substr break l break l case 7 switch s char at 1 case a x value of id id valueof break l case e x replace id id replace break l case n x index of id id indexof break l case t x italics id id italics break l break l case 8 c s char at 4 if c r x to string id id tostring else if c s x fontsize id id fontsize else if c u x to source id id tosource break l case 9 c s char at 0 if c f x fontcolor id id fontcolor else if c s x substring id id substring break l case 10 x char code at id id charcodeat break l case 11 switch s char at 2 case l x to lower case id id tolowercase break l case u x to upper case id id touppercase break l case n x constructor id id constructor break l case s x last index of id id lastindexof break l break l case 16 x equals ignore case id id equalsignorecase break l if x null x s x equals s id 0 generated return id findprototypeid charat charat charat id_sub charat charat id_big charat charat id_sup charat id_bold id_link charat id_fixed id_slice id_match id_blink id_small id_split charat id_search charat id_charat id_anchor id_concat id_equals id_strike id_substr charat valueof id_valueof id_replace indexof id_indexof id_italics charat tostring id_tostring id_fontsize tosource id_tosource charat id_fontcolor id_substring charcodeat id_charcodeat charat tolowercase id_tolowercase touppercase id_touppercase id_constructor lastindexof id_lastindexof equalsignorecase id_equalsignorecase class sub string public sub string substring substring public sub string string str index 0 char array str to char array length str length substring chararray tochararray public sub string char source int start int len there must be a better way of doing this index 0 length len char array new char len for int j 0 j len j char array j source start j substring chararray chararray public string to string return char array null new string char array index length tostring chararray chararray public class slot 005 extends live connect test public slot 005 super slot_005 liveconnecttest slot_005 super public static void main string args slot 005 test new slot 005 test start slot_005 slot_005 public void execute test get base objects object test matrix get data array for int i 0 i test matrix length i js object js object createjs object object test matrix i set slot js object i object test matrix i get slot js object i object test matrix i executetest getbaseobjects testmatrix getdataarray testmatrix jsobject jsobject createjsobject testmatrix setslot jsobject testmatrix getslot jsobject testmatrix public js object createjs object object data return js object data 0 jsobject createjsobject jsobject get the constructor of all the base java script objects the test will compare the instance constructor to the base object constructor to verify that the java script type of the object is corret public boolean get base objects try js number js object global eval number prototype constructor js string js object global eval string prototype constructor js function js object global eval function prototype constructor js boolean js object global eval boolean prototype constructor js object js object global eval object prototype constructor js math js object global eval math js date js object global eval date prototype constructor js array js object global eval array prototype constructor js reg exp js object global eval reg exp prototype constructor catch exception e system err println failed in get base objects e to string e print stack trace return false return true javascript javascript getbaseobjects jsnumber jsobject jsstring jsobject jsfunction jsobject jsboolean jsobject jsobject jsobject jsmath jsobject jsdate jsobject jsarray jsobject jsregexp jsobject regexp getbaseobjects tostring printstacktrace get the data array which is an array of arrays each of the internal arrays consists of three objects a string whose value will be passed to the java script array constructor a string which is the expected string value of retreiving the js object via get slot and a js object which is the js object s constructor that allows us to verify the type of js object return the data array public object get data array object item0 global eval new string passed global eval new string passed new string passed js string object item1 global eval new number 12345 global eval new number 98765 new string 98765 js number object item2 global eval new boolean false global eval new boolean true new string true js boolean object item3 global eval new array 0 1 2 3 4 global eval new array h i new string h i js array object item4 global eval new object global eval new object new string object object js object object data array item0 item1 item2 item3 item4 return data array javascript jsobject getslot jsobject jsobject jsobject getdataarray jsstring jsnumber jsboolean jsarray jsobject dataarray dataarray create an empty java script array named js array return the js object array object public js object createjs array js object js array null string args var js array new array 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 js object js array js object global get member js array passed result exception return js array javascript jsarray jsobject jsobject createjsarray jsobject jsarray jsarray jsarray jsobject getmember jsarray getmember jsarray tostring printstacktrace addtestcase jsarray 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 in this test the expected class of all objects is js object param js array 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 array int slot object data string exception js object constructor null js object result null class e class null class a class null try result js object js array get slot slot if result null e class class for name netscape javascript js object a class result get class constructor js object result get member constructor catch exception e exception js array get slot slot threw e to string file exception exception e print stack trace finally if result null add test case js array get slot slot to string trim returned result data 1 equals result true data 1 to string trim equals result to string exception else check the string value of the result add test case js array get slot slot returned result data 2 to string equals result true data 2 equals result to string exception check the class of the result all should be js objects add test case e class equals a class true e class equals a class exception check the constructor of the result add test case constructor equals data 3 true constructor equals data 3 exception jsobject getslot jsobject jsobject jsarray jsobject jsarray getslot jsobjectconstructor getslot jsobject jsarray jsobject jsobject eclass aclass jsobject jsarray getslot eclass forname jsobject aclass getclass jsobject getmember jsarray getslot tostring printstacktrace addtestcase jsarray getslot tostring tostring tostring addtestcase jsarray getslot tostring tostring jsobjects addtestcase eclass aclass eclass aclass addtestcase 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 data string exception null string result passed try js array set slot slot object data 1 catch exception e result failed exception js array set slot slot data 1 threw e to string file exception exception e print stack trace finally add test case js array set slot slot data 1 passed result exception jsobject setslot setslot jsarray jsobject setslot javavalue setslot jsobject jsarray jsarray setslot jsarray setslot tostring printstacktrace addtestcase jsarray setslot 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 create a scriptable input stream param in the input stream to read from param scope the top level scope to create the object in public scriptable input stream input stream in scriptable scope throws io exception super in this scope scope enable resolve object true context cx context get current context if cx null this class loader cx get application class loader scriptableinputstream inputstream scriptableinputstream inputstream ioexception enableresolveobject getcurrentcontext classloader getapplicationclassloader protected class resolve class object stream class desc throws io exception class not found exception string name desc get name if class loader null try return class loader load class name catch class not found exception ex fall through to default loading return super resolve class desc resolveclass objectstreamclass ioexception classnotfoundexception getname classloader classloader loadclass classnotfoundexception resolveclass protected object resolve object object obj throws io exception if obj instanceof scriptable output stream pending lookup string name scriptable output stream pending lookup obj get name obj scriptable output stream lookup qualified name scope name if obj scriptable not found throw new io exception object name not found upon deserialization else if obj instanceof unique tag obj unique tag obj read resolve else if obj instanceof undefined obj undefined obj read resolve return obj resolveobject ioexception scriptableoutputstream pendinglookup scriptableoutputstream pendinglookup getname scriptableoutputstream lookupqualifiedname not_found ioexception uniquetag uniquetag readresolve readresolve sets the gui callback object to use public void set gui callback gui callback callback this callback callback guicallback setguicallback guicallback tells the debugger to break at the next opportunity public void set break this break flag true setbreak breakflag sets the scope provider to be used public void set scope provider scope provider scope provider this scope provider scope provider scopeprovider setscopeprovider scopeprovider scopeprovider scopeprovider scopeprovider switches context to the stack frame with the given index public void context switch int frame index this frame index frame index contextswitch frameindex frameindex frameindex sets whether the debugger should break on exceptions public void set break on exceptions boolean break on exceptions this break on exceptions break on exceptions setbreakonexceptions breakonexceptions breakonexceptions breakonexceptions sets whether the debugger should break on function entering public void set break on enter boolean break on enter this break on enter break on enter setbreakonenter breakonenter breakonenter breakonenter sets whether the debugger should break on function return public void set break on return boolean break on return this break on return break on return setbreakonreturn breakonreturn breakonreturn breakonreturn attaches the debugger to the given context factory public void attach to context factory factory detach this context factory factory this listener new dimi proxy this iproxy listen factory add listener this listener contextfactory attachto contextfactory contextfactory dimiproxy iproxy_listen addlistener detaches the debugger from the current context factory public void detach if listener null context factory remove listener listener context factory null listener null contextfactory contextfactory removelistener contextfactory releases resources associated with this debugger public void dispose detach returns the function source object for the given script or function private function source get function source debuggable script fn or script function source fsource function source fn or script if fsource null string url get normalized url fn or script source info si source info url if si null if fn or script is generated script not eval or function try to load it from url string source load source url if source null debuggable script top fn or script for debuggable script parent top get parent if parent null break top parent register top script top source fsource function source fn or script return fsource functionsource functionsource getfunctionsource debuggablescript fnorscript functionsource functionsource fnorscript getnormalizedurl fnorscript sourceinfo sourceinfo fnorscript isgeneratedscript loadsource debuggablescript fnorscript debuggablescript getparent registertopscript functionsource fnorscript loads the script at the given url private string load source string source url string source null int hash source url index of if hash 0 source url source url substring 0 hash try input stream is open stream if source url index of 0 can be a file name try if source url starts with string home system get property user home if home null string path from home source url substring 2 file f new file new file home path from home if f exists is new file input stream f break open stream file f new file source url if f exists is new file input stream f break open stream catch security exception ex no existing file assume missed http if source url starts with source url http source url else if source url starts with source url http 127 0 0 1 source url else source url http source url is new url source url open stream try source kit read reader new input stream reader is finally is close catch io exception ex system err println failed to load source from source url ex return source loadsource sourceurl sourceurl indexof sourceurl sourceurl inputstream openstream sourceurl indexof sourceurl startswith getproperty pathfromhome sourceurl pathfromhome fileinputstream openstream sourceurl fileinputstream openstream securityexception sourceurl startswith sourceurl sourceurl sourceurl startswith sourceurl sourceurl sourceurl sourceurl sourceurl openstream readreader inputstreamreader ioexception sourceurl registers the given script as a top level script in the debugger private void register top script debuggable script top script string source if top script is top level throw new illegal argument exception string url get normalized url top script debuggable script functions get all functions top script final source info source info new source info source functions url synchronized url to source info source info old source info url to source info get url if old null source info copy breakpoints from old url to source info put url source info for int i 0 i source info function sources top i function source fsource source info function source i string name fsource name if name length 0 function names put name fsource synchronized function to source for int i 0 i functions length i function source fsource source info function source i function to source put functions i fsource callback update source text source info registertopscript debuggablescript topscript topscript istoplevel illegalargumentexception getnormalizedurl topscript debuggablescript getallfunctions topscript sourceinfo sourceinfo sourceinfo urltosourceinfo sourceinfo sourceinfo urltosourceinfo sourceinfo copybreakpointsfrom urltosourceinfo sourceinfo sourceinfo functionsourcestop functionsource sourceinfo functionsource functionnames functiontosource functionsource sourceinfo functionsource functiontosource updatesourcetext sourceinfo returns the function source object for the given function or script private function source function source debuggable script fn or script return function source function to source get fn or script functionsource functionsource functionsource debuggablescript fnorscript functionsource functiontosource fnorscript returns an array of all function names public string function names string a synchronized url to source info enumeration e function names keys a new string function names size int i 0 while e has more elements a i string e next element return a functionnames urltosourceinfo functionnames functionnames hasmoreelements nextelement returns the function source object for the function with the given name public function source function source by name string function name return function source function names get function name functionsource functionsource functionsourcebyname functionname functionsource functionnames functionname returns the source info object for the given url public source info source info string url return source info url to source info get url sourceinfo sourceinfo sourceinfo sourceinfo urltosourceinfo returns the source url for the given script or function private string get normalized url debuggable script fn or script string url fn or script get source name if url null url stdin else not to produce window for eval from different lines strip line numbers i e replace all 0 9 eval by eval option similar teatment for function char eval separator string buffer sb null int url length url length int cursor 0 for int search start url index of eval separator cursor if search start 0 break string replace null int i search start 1 boolean has digits false while i url length int c url char at i if 0 c c 9 break i if i search start 1 i points after 0 9 if eval region matches 0 url i 6 cursor i 6 replace eval if replace null break if sb null sb new string buffer sb append url substring 0 search start sb append replace if sb null if cursor url length sb append url substring cursor url sb to string return url getnormalizedurl debuggablescript fnorscript fnorscript getsourcename evalseparator stringbuffer urllength searchstart indexof evalseparator searchstart searchstart hasdigits urllength charat searchstart regionmatches stringbuffer searchstart urllength tostring returns an array of all functions in the given script private static debuggable script get all functions debuggable script function obj array functions new obj array collectfunctions r function functions debuggable script result new debuggable script functions size functions to array result return result debuggablescript getallfunctions debuggablescript objarray objarray collectfunctions_r debuggablescript debuggablescript toarray helper function for link get all functions debuggable script private static void collectfunctions r debuggable script function obj array array array add function for int i 0 i function get function count i collectfunctions r function get function i array getallfunctions debuggablescript collectfunctions_r debuggablescript objarray getfunctioncount collectfunctions_r getfunction clears all breakpoints public void clear all breakpoints enumeration e url to source info elements while e has more elements source info si source info e next element si remove all breakpoints clearallbreakpoints urltosourceinfo hasmoreelements sourceinfo sourceinfo nextelement removeallbreakpoints called when a breakpoint has been hit private void handle breakpoint hit stack frame frame context cx break flag false interrupted cx frame null handlebreakpointhit stackframe breakflag called when a script exception has been thrown private void handle exception thrown context cx throwable ex stack frame frame if break on exceptions context data cd frame context data if cd last processed exception ex interrupted cx frame ex cd last processed exception ex handleexceptionthrown stackframe breakonexceptions contextdata contextdata lastprocessedexception lastprocessedexception returns the current context data object public context data current context data return interrupted context data contextdata contextdata currentcontextdata interruptedcontextdata sets the action to perform to end interruption public void set return value int return value synchronized monitor this return value return value monitor notify setreturnvalue returnvalue returnvalue returnvalue resumes execution of script public void go synchronized monitor this return value go monitor notify all returnvalue notifyall evaluates the given script public string eval string expr string result undefined if expr null return result context data context data current context data if context data null frame index context data frame count return result stack frame frame context data get frame frame index if context data event thread flag context cx context get current context result do eval cx frame expr else synchronized monitor if inside interrupt loop eval request expr eval frame frame monitor notify do try monitor wait catch interrupted exception exc thread current thread interrupt break while eval request null result eval result return result contextdata contextdata currentcontextdata contextdata frameindex contextdata framecount stackframe contextdata getframe frameindex contextdata eventthreadflag getcurrentcontext do_eval insideinterruptloop evalrequest evalframe interruptedexception currentthread evalrequest evalresult compiles the given script public void compile script string url string text dimi proxy action new dimi proxy this iproxy compile script action url url action text text action with context compilescript dimiproxy dimiproxy iproxy_compile_script withcontext evaluates the given script public void eval script final string url final string text dimi proxy action new dimi proxy this iproxy eval script action url url action text text action with context evalscript dimiproxy dimiproxy iproxy_eval_script withcontext converts the given script object to a string public string object to string object object dimi proxy action new dimi proxy this iproxy object to string action object object action with context return action string result objecttostring dimiproxy dimiproxy iproxy_object_to_string withcontext stringresult returns whether the given string is syntactically valid script public boolean string is compilable unit string str dimi proxy action new dimi proxy this iproxy string is compilable action text str action with context return action boolean result stringiscompilableunit dimiproxy dimiproxy iproxy_string_is_compilable withcontext booleanresult returns the value of a property on the given script object public object get object property object object object id dimi proxy action new dimi proxy this iproxy object property action object object action id id action with context return action object result getobjectproperty dimiproxy dimiproxy iproxy_object_property withcontext objectresult returns an array of the property names on the given script object public object get object ids object object dimi proxy action new dimi proxy this iproxy object ids action object object action with context return action object array result getobjectids dimiproxy dimiproxy iproxy_object_ids withcontext objectarrayresult returns the value of a property on the given script object private object get object property impl context cx object object object id scriptable scriptable scriptable object object result if id instanceof string string name string id if name equals this result scriptable else if name equals proto result scriptable get prototype else if name equals parent result scriptable get parent scope else result scriptable object get property scriptable name if result scriptable object not found result undefined instance else int index integer id int value result scriptable object get property scriptable index if result scriptable object not found result undefined instance return result getobjectpropertyimpl __proto__ getprototype __parent__ getparentscope scriptableobject getproperty scriptableobject not_found intvalue scriptableobject getproperty scriptableobject not_found returns an array of the property names on the given script object private object get object ids impl context cx object object if object instanceof scriptable object undefined instance return context empty args object ids scriptable scriptable scriptable object if scriptable instanceof debuggable object ids debuggable object scriptable get all ids else ids scriptable get ids scriptable proto scriptable get prototype scriptable parent scriptable get parent scope int extra 0 if proto null extra if parent null extra if extra 0 object tmp new object extra ids length system arraycopy ids 0 tmp extra ids length ids tmp extra 0 if proto null ids extra proto if parent null ids extra parent return ids getobjectidsimpl emptyargs debuggableobject debuggableobject getallids getids getprototype getparentscope __proto__ __parent__ interrupts script execution private void interrupted context cx final stack frame frame throwable script exception context data context data frame context data int line frame get line number string url frame get url boolean event thread flag callback is gui event thread context data event thread flag event thread flag boolean recursive event thread call false interrupted check synchronized event thread monitor if event thread flag if interrupted context data null recursive event thread call true break interrupted check else while interrupted context data null try event thread monitor wait catch interrupted exception exc return interrupted context data context data if recursive event thread call xxx for now the following is commented out as on linux too deep recursion of dispatch next gui event causes gui lockout note it can make gui unresponsive if long running script will be called on gui thread while processing another interrupt if false run event dispatch until gui sets a flag to exit the initial call to interrupted while this return value 1 try callback dispatch next gui event catch interrupted exception exc return if interrupted context data null kit code bug try do int frame count context data frame count this frame index frame count 1 final string thread title thread current thread to string final string alert message if script exception null alert message null else alert message script exception to string int return value 1 if event thread flag synchronized monitor if inside interrupt loop kit code bug this inside interrupt loop true this eval request null this return value 1 callback enter interrupt frame thread title alert message try for try monitor wait catch interrupted exception exc thread current thread interrupt break if eval request null this eval result null try eval result do eval cx eval frame eval request finally eval request null eval frame null monitor notify continue if this return value 1 return value this return value break finally inside interrupt loop false else this return value 1 callback enter interrupt frame thread title alert message while this return value 1 try callback dispatch next gui event catch interrupted exception exc return value this return value switch return value case step over context data break next line true context data stop at frame depth context data frame count break case step into context data break next line true context data stop at frame depth 1 break case step out if context data frame count 1 context data break next line true context data stop at frame depth context data frame count 1 break while false finally synchronized event thread monitor interrupted context data null event thread monitor notify all stackframe scriptexception contextdata contextdata contextdata getlinenumber geturl eventthreadflag isguieventthread contextdata eventthreadflag eventthreadflag recursiveeventthreadcall interruptedcheck eventthreadmonitor eventthreadflag interruptedcontextdata recursiveeventthreadcall interruptedcheck interruptedcontextdata eventthreadmonitor interruptedexception interruptedcontextdata contextdata recursiveeventthreadcall dispatchnextguievent returnvalue dispatchnextguievent interruptedexception interruptedcontextdata codebug framecount contextdata framecount frameindex framecount threadtitle currentthread tostring alertmessage scriptexception alertmessage alertmessage scriptexception tostring returnvalue eventthreadflag insideinterruptloop codebug insideinterruptloop evalrequest returnvalue enterinterrupt threadtitle alertmessage interruptedexception currentthread evalrequest evalresult evalresult do_eval evalframe evalrequest evalrequest evalframe returnvalue returnvalue returnvalue insideinterruptloop returnvalue enterinterrupt threadtitle alertmessage returnvalue dispatchnextguievent interruptedexception returnvalue returnvalue returnvalue step_over contextdata breaknextline contextdata stopatframedepth contextdata framecount step_into contextdata breaknextline contextdata stopatframedepth step_out contextdata framecount contextdata breaknextline contextdata stopatframedepth contextdata framecount eventthreadmonitor interruptedcontextdata eventthreadmonitor notifyall evaluates script in the given stack frame private static string do eval context cx stack frame frame string expr string result string debugger saved debugger cx get debugger object saved data cx get debugger context data int saved level cx get optimization level cx set debugger null null cx set optimization level 1 cx set generating debug false try callable script callable cx compile string expr 0 null object result script call cx frame scope frame this obj script runtime empty args if result undefined instance result string else result string script runtime to string result catch exception exc result string exc get message finally cx set generating debug true cx set optimization level saved level cx set debugger saved debugger saved data if result string null result string null return result string do_eval stackframe resultstring saved_debugger getdebugger saved_data getdebuggercontextdata saved_level getoptimizationlevel setdebugger setoptimizationlevel setgeneratingdebug compilestring thisobj scriptruntime emptyargs resultstring resultstring scriptruntime tostring resultstring getmessage setgeneratingdebug setoptimizationlevel saved_level setdebugger saved_debugger saved_data resultstring resultstring resultstring creates a new dimi proxy private dimi proxy dim dim int type this dim dim this type type dimiproxy dimiproxy performs the action given by link type public object run context cx switch type case iproxy compile script cx compile string text url 1 null break case iproxy eval script scriptable scope null if dim scope provider null scope dim scope provider get scope if scope null scope new importer top level cx cx evaluate string scope text url 1 null break case iproxy string is compilable boolean result cx string is compilable unit text break case iproxy object to string if object undefined instance string result undefined else if object null string result null else if object instanceof native call string result object call else string result context to string object break case iproxy object property object result dim get object property impl cx object id break case iproxy object ids object array result dim get object ids impl cx object break default throw kit code bug return null iproxy_compile_script compilestring iproxy_eval_script scopeprovider scopeprovider getscope importertoplevel evaluatestring iproxy_string_is_compilable booleanresult stringiscompilableunit iproxy_object_to_string stringresult stringresult nativecall stringresult stringresult tostring iproxy_object_property objectresult getobjectpropertyimpl iproxy_object_ids objectarrayresult getobjectidsimpl codebug performs the action given by link type with the attached link context factory private void with context dim context factory call this contextfactory withcontext contextfactory called when a context is created public void context created context cx if type iproxy listen kit code bug context data context data new context data debugger debugger new dimi proxy dim iproxy debug cx set debugger debugger context data cx set generating debug true cx set optimization level 1 contextcreated iproxy_listen codebug contextdata contextdata contextdata dimiproxy iproxy_debug setdebugger contextdata setgeneratingdebug setoptimizationlevel called when a context is destroyed public void context released context cx if type iproxy listen kit code bug contextreleased iproxy_listen codebug returns a stack frame for the given function or script public debug frame get frame context cx debuggable script fn or script if type iproxy debug kit code bug function source item dim get function source fn or script if item null can not debug if source is not available return null return new stack frame cx dim item stackframe debugframe getframe debuggablescript fnorscript iproxy_debug codebug functionsource getfunctionsource fnorscript stackframe called when compilation is finished public void handle compilation done context cx debuggable script fn or script string source if type iproxy debug kit code bug if fn or script is top level return dim register top script fn or script source handlecompilationdone debuggablescript fnorscript iproxy_debug codebug fnorscript istoplevel registertopscript fnorscript returns the context data for the given context public static context data get context cx return context data cx get debugger context data contextdata contextdata contextdata getdebuggercontextdata returns the number of stack frames public int frame count return frame stack size framecount framestack returns the stack frame with the given index public stack frame get frame int frame number int num frame stack size frame number 1 return stack frame frame stack get num stackframe getframe framenumber framestack framenumber stackframe framestack pushes a stack frame on to the stack private void push frame stack frame frame frame stack push frame pushframe stackframe framestack pops a stack frame from the stack private void pop frame frame stack pop popframe framestack creates a new stack frame private stack frame context cx dim dim function source fsource this dim dim this context data context data get cx this fsource fsource this breakpoints fsource source info breakpoints this line number fsource first line stackframe stackframe functionsource contextdata contextdata sourceinfo linenumber firstline called when the stack frame is entered public void on enter context cx scriptable scope scriptable this obj object args context data push frame this this scope scope this this obj this obj if dim break on enter dim handle breakpoint hit this cx onenter thisobj contextdata pushframe thisobj thisobj breakonenter handlebreakpointhit called when the current position has changed public void on line change context cx int lineno this line number lineno if breakpoints lineno dim break flag boolean line break context data break next line if line break context data stop at frame depth 0 line break context data frame count context data stop at frame depth if line break return context data stop at frame depth 1 context data break next line false dim handle breakpoint hit this cx onlinechange linenumber breakflag linebreak contextdata breaknextline linebreak contextdata stopatframedepth linebreak contextdata framecount contextdata stopatframedepth linebreak contextdata stopatframedepth contextdata breaknextline handlebreakpointhit called when an exception has been thrown public void on exception thrown context cx throwable exception dim handle exception thrown cx exception this onexceptionthrown handleexceptionthrown called when the stack frame has been left public void on exit context cx boolean by throw object result or exception if dim break on return by throw dim handle breakpoint hit this cx context data pop frame onexit bythrow resultorexception breakonreturn bythrow handlebreakpointhit contextdata popframe returns the source info object for the function public source info source info return fsource source info sourceinfo sourceinfo sourceinfo sourceinfo returns the context data object for the context public context data context data return context data contextdata contextdata contextdata contextdata returns the scope object for this frame public object scope return scope returns the this object for this frame public object this obj return this obj thisobj thisobj returns the source url public string get url return fsource source info url geturl sourceinfo returns the current line number public int get line number return line number getlinenumber linenumber creates a new function source private function source source info source info int first line string name if name null throw new illegal argument exception this source info source info this first line first line this name name functionsource functionsource sourceinfo sourceinfo firstline illegalargumentexception sourceinfo sourceinfo firstline firstline returns the source info object that describes the source of the function public source info source info return source info sourceinfo sourceinfo sourceinfo sourceinfo returns the line number of the first line of the function public int first line return first line firstline firstline returns the name of the function public string name return name creates a new source info object private source info string source debuggable script functions string normilized url this source source this url normilized url int n functions length int line arrays new int n for int i 0 i n i line arrays i functions i get line numbers int min all 0 max all 1 int first lines new int n for int i 0 i n i int lines line arrays i if lines null lines length 0 first lines i 1 else int min max min max lines 0 for int j 1 j lines length j int line lines j if line min min line else if line max max line first lines i min if min all max all min all min max all max else if min min all min all min if max max all max all max if min all max all no line information this min line 1 this breakable lines empty boolean array this breakpoints empty boolean array else if min all 0 line numbers can not be negative throw new illegal state exception string value of min all this min line min all int lines top max all 1 this breakable lines new boolean lines top this breakpoints new boolean lines top for int i 0 i n i int lines line arrays i if lines null lines length 0 for int j 0 j lines length j int line lines j this breakable lines line true this function sources new function source n for int i 0 i n i string name functions i get function name if name null name this function sources i new function source this first lines i name sourceinfo sourceinfo debuggablescript normilizedurl normilizedurl linearrays linearrays getlinenumbers minall maxall firstlines linearrays firstlines firstlines minall maxall minall maxall minall minall maxall maxall minall maxall minline breakablelines empty_boolean_array empty_boolean_array minall illegalstateexception valueof minall minline minall linestop maxall breakablelines linestop linestop linearrays breakablelines functionsources functionsource getfunctionname functionsources functionsource firstlines returns the source text public string source return this source returns the script s origin url public string url return this url returns the number of function source objects stored in this object public int function sources top return function sources length functionsource functionsourcestop functionsources returns the function source object with the given index public function source function source int i return function sources i functionsource functionsource functionsource functionsources copies the breakpoints from the given source info object into this one private void copy breakpoints from source info old int end old breakpoints length if end this breakpoints length end this breakpoints length for int line 0 line end line if old breakpoints line this breakpoints line true sourceinfo copybreakpointsfrom sourceinfo returns whether the given line number can have a breakpoint set on it public boolean breakable line int line return line this breakable lines length this breakable lines line breakableline breakablelines breakablelines returns whether there is a breakpoint set on the given line public boolean breakpoint int line if breakable line line throw new illegal argument exception string value of line return line this breakpoints length this breakpoints line breakableline illegalargumentexception valueof sets or clears the breakpoint flag for the given line public boolean breakpoint int line boolean value if breakable line line throw new illegal argument exception string value of line boolean changed synchronized breakpoints if breakpoints line value breakpoints line value changed true else changed false return changed breakableline illegalargumentexception valueof removes all breakpoints from the script public void remove all breakpoints synchronized breakpoints for int line 0 line breakpoints length line breakpoints line false removeallbreakpoints the zero parameter constructor when context define class is called with this class it will construct file prototype using this constructor public file defineclass the java method defining the java script file constructor if the constructor has one or more arguments and the first argument is not undefined the argument is converted to a string as used as the filename p otherwise system in or system out is assumed as appropriate to the use public static scriptable js constructor context cx object args function ctor obj boolean in new expr file result new file if args length 0 args 0 context get undefined value result name result file null else result name context to string args 0 result file new java io file result name return result javascript jsconstructor ctorobj innewexpr getundefinedvalue tostring returns the name of this java script class file public string get class name return file javascript getclassname get the name of the file used to define the name property public string jsget name return name jsget_name read the remaining lines in the file and return them in an array implements a java script function p this is a good example of creating a new array and setting elements in that array exception io exception if an error occurred while accessing the file associated with this object public object jsfunction readlines throws io exception vector v new vector string s while s jsfunction readline null v add element s object lines new object v size v copy into lines scriptable scope scriptable object get top level scope this context cx context get current context return cx new object scope array lines javascript ioexception jsfunction_readlines ioexception jsfunction_readline addelement copyinto scriptableobject gettoplevelscope getcurrentcontext newobject read a line implements a java script function exception io exception if an error occurred while accessing the file associated with this object or eof exception if the object reached the end of the file public string jsfunction readline throws io exception return get reader read line javascript ioexception eofexception jsfunction_readline ioexception getreader readline read a character exception io exception if an error occurred while accessing the file associated with this object or eof exception if the object reached the end of the file public string jsfunction readchar throws io exception int i get reader read if i 1 return null char char array char i return new string char array ioexception eofexception jsfunction_readchar ioexception getreader chararray chararray write strings implements a java script function p this function takes a variable number of arguments converts each argument to a string and writes that string to the file exception io exception if an error occurred while accessing the file associated with this object public static void jsfunction write context cx scriptable this obj object args function fun obj throws io exception write0 this obj args false javascript ioexception jsfunction_write thisobj funobj ioexception thisobj write strings and a newline implements a java script function exception io exception if an error occurred while accessing the file associated with this object public static void jsfunction writeline context cx scriptable this obj object args function fun obj throws io exception write0 this obj args true javascript ioexception jsfunction_writeline thisobj funobj ioexception thisobj public int jsget linenumber throws file not found exception return get reader get line number jsget_linenumber filenotfoundexception getreader getlinenumber close the file it may be reopened implements a java script function exception io exception if an error occurred while accessing the file associated with this object public void jsfunction close throws io exception if reader null reader close reader null else if writer null writer close writer null javascript ioexception jsfunction_close ioexception finalizer close the file when this object is collected public void finalize try jsfunction close catch io exception e jsfunction_close ioexception get the java reader public object jsfunction getreader if reader null return null here we use to object to wrap the buffered reader object in a scriptable object so that it can be manipulated by java script scriptable parent scriptable object get top level scope this return context java tojs reader parent jsfunction_getreader toobject bufferedreader javascript scriptableobject gettoplevelscope javatojs get the java writer see file jsfunction getreader public object jsfunction getwriter if writer null return null scriptable parent scriptable object get top level scope this return context java tojs writer parent jsfunction_getreader jsfunction_getwriter scriptableobject gettoplevelscope javatojs get the reader checking that we re not already writing this file private line number reader get reader throws file not found exception if writer null throw context report runtime error already writing file name if reader null reader new line number reader file null new input stream reader system in new file reader file return reader linenumberreader getreader filenotfoundexception reportruntimeerror linenumberreader inputstreamreader filereader perform the guts of write and write line since the two functions differ only in whether they write a newline character move the code into a common subroutine private static void write0 scriptable this obj object args boolean eol throws io exception file this file check instance this obj if this file reader null throw context report runtime error already writing file this file name if this file writer null this file writer new buffered writer this file file null new output stream writer system out new file writer this file file for int i 0 i args length i string s context to string args i this file writer write s 0 s length if eol this file writer new line writeline thisobj ioexception thisfile checkinstance thisobj thisfile reportruntimeerror thisfile thisfile thisfile bufferedwriter thisfile outputstreamwriter filewriter thisfile tostring thisfile thisfile newline perform the instanceof check and return the downcasted file object this is necessary since methods may reside in the file prototype object and scripts can dynamically alter prototype chains for example pre js define class file js o object object js o proto file prototype object file js o write hi js called on incompatible object pre the runtime will take care of such checks when non static java methods are defined as java script functions private static file check instance scriptable obj if obj null obj instanceof file throw context report runtime error called on incompatible object return file obj defineclass __proto__ javascript checkinstance reportruntimeerror static void init scriptable scope boolean sealed native with obj new native with obj set parent scope scope obj set prototype scriptable object get object prototype scope id function object ctor new id function object obj ftag id constructor with 0 scope ctor mark as constructor obj if sealed ctor seal object ctor export as scope property nativewith nativewith setparentscope setprototype scriptableobject getobjectprototype idfunctionobject idfunctionobject id_constructor markasconstructor sealobject exportasscopeproperty private native with nativewith protected native with scriptable parent scriptable prototype this parent parent this prototype prototype nativewith public string get class name return with getclassname public boolean has string id scriptable start return prototype has id prototype public boolean has int index scriptable start return prototype has index prototype public object get string id scriptable start if start this start prototype return prototype get id start public object get int index scriptable start if start this start prototype return prototype get index start public void put string id scriptable start object value if start this start prototype prototype put id start value public void put int index scriptable start object value if start this start prototype prototype put index start value public void delete string id prototype delete id public void delete int index prototype delete index public scriptable get prototype return prototype getprototype public void set prototype scriptable prototype this prototype prototype setprototype public scriptable get parent scope return parent getparentscope public void set parent scope scriptable parent this parent parent setparentscope public object get ids return prototype get ids getids getids public object get default value class type hint return prototype get default value type hint getdefaultvalue typehint getdefaultvalue typehint public boolean has instance scriptable value return prototype has instance value hasinstance hasinstance must return null to continue looping or the final collection result protected object update dot query boolean value native with itself does not support it throw new illegal state exception updatedotquery nativewith illegalstateexception 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 constructor throw context report runtime error1 msg cant call indirect with throw f unknown execidcall idfunctionobject thisobj hastag methodid id_constructor reportruntimeerror1 static boolean is with function object function obj if function obj instanceof id function object id function object f id function object function obj return f has tag ftag f method id id constructor return false iswithfunction functionobj functionobj idfunctionobject idfunctionobject idfunctionobject functionobj hastag methodid id_constructor static object new with special context cx scriptable scope object args script runtime check deprecated cx with scope scriptable object get top level scope scope native with this obj new native with this obj set prototype args length 0 scriptable object get class prototype scope object script runtime to object cx scope args 0 this obj set parent scope scope return this obj newwithspecial scriptruntime checkdeprecated scriptableobject gettoplevelscope nativewith thisobj nativewith thisobj setprototype scriptableobject getclassprototype scriptruntime toobject thisobj setparentscope thisobj public final void init script function context cx scriptable scope script runtime set function proto and parent this scope initscriptfunction scriptruntime setfunctionprotoandparent param indent how much to indent the decompiled result param flags flags specifying format of decompilation output final string decompile int indent int flags string encoded source get encoded source if encoded source null return super decompile indent flags else uint map properties new uint map 1 properties put decompiler initial indent prop indent return decompiler decompile encoded source flags properties encodedsource getencodedsource encodedsource uintmap uintmap initial_indent_prop encodedsource public int get length int param count get param count if get language version context version 1 2 return param count context cx context get context native call activation script runtime find function activation cx this if activation null return param count return activation original args length getlength paramcount getparamcount getlanguageversion version_1_2 paramcount getcontext nativecall scriptruntime findfunctionactivation paramcount originalargs public int get arity return get param count getarity getparamcount deprecated use link base function get function name instead for backwards compatibility keep an old method name used by batik and possibly others public string jsget name return get function name basefunction getfunctionname jsget_name getfunctionname get encoded source string public string get encoded source return null getencodedsource public debuggable script get debuggable view return null debuggablescript getdebuggableview protected abstract int get language version getlanguageversion protected abstract int get language version get number of declared parameters it should be 0 for scripts protected abstract int get param count getlanguageversion getparamcount get number of declared parameters and variables defined through var statements get parameter or variable name if tt index link get param count tt then return the name of the corresponding parameter otherwise returm the name of variable getparamcount public int float 512 public int ambiguous double arg return double public int ambiguous float arg return float private final int tag id private unique tag int tag id this tag id tag id tagid uniquetag tagid tagid tagid public object read resolve switch tag id case id not found return not found case id null value return null value case id double mark return double mark throw new illegal state exception string value of tag id readresolve tagid id_not_found not_found id_null_value null_value id_double_mark double_mark illegalstateexception valueof tagid overridden for better debug printouts public string to string string name switch tag id case id not found name not found break case id null value name null value break case id double mark name double mark break default throw kit code bug return super to string name tostring tagid id_not_found not_found id_null_value null_value id_double_mark double_mark codebug tostring param f rhino file that will be executed in this rhino env param s the rhino file s test suite param d the rhino drv applet that created this rhino env public rhino env test file f test suite s test driver d this file f this suite s this driver d rhinofile rhinoenv rhinofile rhinodrv rhinoenv rhinoenv testfile testsuite testdriver creates the java script context which evaluates the contents of a rhino file and returns a result the rhino env parses the test result and sets values of the rhino file test result properties see com netscape javascript context set optimization level see com netscape javascript context set debug level public synchronized void run test this driver p file name try cx create context context cx set optimization level driver opt level context cx set debug level driver debug level object load fn execute test file driver helper functions get absolute path file start time driver get current time result execute test file file file path file end time driver get current time parse result catch exception e suite passed false file passed false file exception file failed with exception e javascript rhinofile rhinoenv rhinofile setoptimizationlevel setdebuglevel runtest createcontext setoptimizationlevel opt_level setdebuglevel debug_level loadfn executetestfile helper_functions getabsolutepath starttime getcurrenttime executetestfile filepath endtime getcurrenttime parseresult create a new com netscape javascript context return the newly instantiated context public object create context this is stolen from main java cx new context context cx enter global new global context cx init standard objects global string names print quit version load help load class try global define function properties names main class scriptable object dontenum catch property exception e throw new error e get message return cx createcontext initstandardobjects loadclass definefunctionproperties scriptableobject propertyexception getmessage return cx public object execute test file return null executetestfile given a filename evaluate the file s contents as a java script program return the value of the program if the test throws a java exception or java script runtime or compilation error return the string value of the error message param s full path to the file that will be exectued return test result object if the test is positive result should be an instance of scriptable if the test is negative the result should be a string whose value is the message in the java script error or java exception public object execute test file string s this bit is stolen from main java file reader in null try in new file reader s catch file not found exception ex driver p couldn t open file s object result null try here we evalute the entire contents of the file as as script text is printed only if the print function is called cx evaluate reader scriptable global in args i 1 null result scriptable context cx evaluate reader scriptable global reader in s 1 null catch wrapped exception we driver p wrapped exception we get wrapped exception to string result we get wrapped exception to string catch exception jse driver p java script exception jse get message result jse get message return result javascript javascript javascript executetestfile filereader filereader filenotfoundexception evaluatereader evaluatereader wrappedexception getwrappedexception tostring getwrappedexception tostring javascriptexception getmessage getmessage evaluates the rhino file result if the result is an instance of javax javascript scriptable assume it is a java script array of test case objects as described in rhino drv java for each test case in the array add an element to the rhino file s test case vector if all test cases passed set the rhino file s passed value to true else set its passed value to false p if the result is not a scriptable object the test failed set the the rhino file s exception property to the string value of the result however negative tests which should have a n js extension are expected to fail public boolean parse result flattened object fo null if result instanceof scriptable fo new flattened object scriptable result try file total cases number fo get property length int value for int i 0 i file total cases i scriptable tc scriptable scriptable result get i scriptable result test case rt new test case get string tc get passed tc get string tc get name tc get string tc get description tc get string tc get expect tc get string tc get actual tc get string tc get reason tc file bugnumber get string tc get bugnumber tc starts with com netscape javascript file bugnumber get string tc get bugnumber tc file case vector add element rt if rt passed equals false 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 catch exception e this file exception got a scriptable result but failed parsing its arguments exception e to string flattened object is fo to string this file passed false this suite passed false return false else if it s not a scriptable object test failed set the file s exception to the string value of whatever result we did get this file exception result to string if the file s name ends in n the test expected an error if file name ends with n js this file passed true else this file passed false this suite passed false return false return true rhinofile javascript testcase rhinodrv rhinofile rhinofile rhinofile parseresult flattenedobject flattenedobject totalcases getproperty intvalue totalcases testcase testcase getstring getstring getstring getstring getstring getstring getstring startswith getstring casevector addelement totalcases endswith tostring tostring tostring endswith close the context public void close try context cx exit catch exception e suite passed false file passed false file exception file failed with exception e get the java script string associated with a java script object param object a java identifier for a java script object return the java script string representation of the object public string get string object object return context cx to string object javascript javascript javascript javascript getstring tostring 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 ambiguous long arg return long public string expect return long private int tag value end private static boolean is value type int id if id string tag return true return false tag_value_end is_value_type string_tag private static string tag name int id switch id case switch tag return switch tag str case switch tag return switch tag str case generated tag return generated tag str case generated tag return generated tag str return tag_name switch_tag switch_tag_str switch_tag switch_tag_str generated_tag generated_tag_str generated_tag generated_tag_str void process file string file path throws io exception source file file path body new file body input stream is if file path equals is system in else is new file input stream file path try reader r new input stream reader is ascii body read data r finally is close process file if body was modified output stream os if file path equals os system out else os new file output stream file path try writer w new output stream writer os body write data w w flush finally os close process_file file_path ioexception source_file file_path filebody inputstream file_path fileinputstream file_path inputstreamreader readdata process_file wasmodified outputstream file_path fileoutputstream file_path outputstreamwriter writedata private void process file throws io exception int cur state 0 char buffer body get buffer int generated begin 1 generated end 1 int time stamp begin 1 time stamp end 1 body start line loop l while body next line int begin body get line begin int end body get line end int tag id extract line tag id buffer begin end boolean bad tag false switch cur state case 0 if tag id switch tag cur state switch tag all pairs remove all elements generated begin 1 else if tag id switch tag bad tag true break case switch tag if tag id 0 look for id definitions buffer begin end false else if tag id string tag look for id definitions buffer begin end true else if tag id generated tag if generated begin 0 bad tag true else cur state generated tag time stamp begin tag definition end time stamp end end else if tag id switch tag cur state 0 if generated begin 0 all pairs is empty generate java code string code p to string boolean different body set replacement generated begin generated end code if different string stamp get time stamp body set replacement time stamp begin time stamp end stamp break else bad tag true break case generated tag if tag id 0 if generated begin 0 generated begin begin else if tag id generated tag if generated begin 0 generated begin begin cur state switch tag generated end begin else bad tag true break if bad tag string text tool error reporter get message msg idswitch bad tag order tag name tag id throw r runtime error text source file body get line number null 0 if cur state 0 string text tool error reporter get message msg idswitch file end in switch tag name cur state throw r runtime error text source file body get line number null 0 process_file ioexception cur_state getbuffer generated_begin generated_end time_stamp_begin time_stamp_end startlineloop nextline getlinebegin getlineend tag_id extract_line_tag_id bad_tag cur_state tag_id switch_tag cur_state switch_tag all_pairs removeallelements generated_begin tag_id switch_tag bad_tag switch_tag tag_id look_for_id_definitions tag_id string_tag look_for_id_definitions tag_id generated_tag generated_begin bad_tag cur_state generated_tag time_stamp_begin tag_definition_end time_stamp_end tag_id switch_tag cur_state generated_begin all_pairs isempty generate_java_code tostring setreplacement generated_begin generated_end get_time_stamp setreplacement time_stamp_begin time_stamp_end bad_tag generated_tag tag_id generated_begin generated_begin tag_id generated_tag generated_begin generated_begin cur_state switch_tag generated_end bad_tag bad_tag toolerrorreporter getmessage bad_tag_order tag_name tag_id runtimeerror source_file getlinenumber cur_state toolerrorreporter getmessage file_end_in_switch tag_name cur_state runtimeerror source_file getlinenumber private string get time stamp simple date format f new simple date format last update yyyy mm dd hh mm ss z string date string f format new date return f format new date get_time_stamp simpledateformat simpledateformat datestring private void generate java code p clear id value pair pairs new id value pair all pairs size all pairs copy into pairs switch generator g new switch generator g char tail test threshold 2 g set reporter r g set code printer p g generate switch pairs 0 generate_java_code idvaluepair idvaluepair all_pairs all_pairs copyinto switchgenerator switchgenerator char_tail_test_threshold setreporter setcodeprinter generateswitch private int extract line tag id char array int cursor int end int id 0 cursor skip white space array cursor end int after leading white space cursor cursor look for slash slash array cursor end if cursor end boolean at line start after leading white space 2 cursor cursor skip white space array cursor end if cursor end array cursor cursor boolean end tag false if cursor end array cursor cursor end tag true int tag start cursor for cursor end cursor int c array cursor if c c is white space c break if cursor end int tag end cursor cursor skip white space array cursor end if cursor end int c array cursor if c c id get tag id array tag start tag end at line start if id 0 string bad null if c if end tag id id if is value type id bad msg idswitch no end usage tag definition end cursor 1 else if end tag bad msg idswitch no end with value else if is value type id bad msg idswitch no value allowed id extract tag value array cursor 1 end id if bad null string s tool error reporter get message bad tag name id throw r runtime error s source file body get line number null 0 return id extract_line_tag_id skip_white_space after_leading_white_space look_for_slash_slash at_line_start after_leading_white_space skip_white_space end_tag end_tag tag_start is_white_space tag_end skip_white_space get_tag_id tag_start tag_end at_line_start end_tag is_value_type no_end_usage tag_definition_end end_tag no_end_with_value is_value_type no_value_allowed extract_tag_value toolerrorreporter getmessage tag_name runtimeerror source_file getlinenumber return position after first of or end if not found private int look for slash slash char array int cursor int end while cursor 2 end int c array cursor if c c array cursor if c return cursor return end look_for_slash_slash private int extract tag value char array int cursor int end int id cursor points after alert implement support for quoted strings boolean found false cursor skip white space array cursor end if cursor end int value start cursor int value end cursor while cursor end int c array cursor if is white space c int after space skip white space array cursor 1 end if after space end array after space value end cursor cursor after space break cursor after space 1 else if c value end cursor break else cursor if cursor end array cursor is here found true tag value start value start tag value end value end tag definition end cursor 1 return found id 0 extract_tag_value skip_white_space value_start value_end is_white_space after_space skip_white_space after_space after_space value_end after_space after_space value_end tag_value_start value_start tag_value_end value_end tag_definition_end private int get tag id char array int begin int end boolean at line start if at line start if equals switch tag str array begin end return switch tag if equals generated tag str array begin end return generated tag if equals string tag str array begin end return string tag return 0 get_tag_id at_line_start at_line_start switch_tag_str switch_tag generated_tag_str generated_tag string_tag_str string_tag private void look for id definitions char array int begin int end boolean use tag value as string look for the pattern t id a za z0 9 t where 1 gives field or method name int cursor begin skip tab and spaces at the beginning cursor skip white space array cursor end int id start cursor int name start skip matched prefix id array cursor end if name start 0 found id prefix cursor name start cursor skip name char array cursor end int name end cursor if name start name end cursor skip white space array cursor end if cursor end if array cursor int id end name end if use tag value as string name start tag value start name end tag value end got the match add id array id start id end name start name end look_for_id_definitions use_tag_value_as_string id_ 9_ skip_white_space id_start name_start skip_matched_prefix id_ name_start id_ name_start skip_name_char name_end name_start name_end skip_white_space id_end name_end use_tag_value_as_string name_start tag_value_start name_end tag_value_end add_id id_start id_end name_start name_end private void add id char array int id start int id end int name start int name end string name new string array name start name end name start string value new string array id start id end id start id value pair pair new id value pair name value pair set line number body get line number all pairs add element pair add_id id_start id_end name_start name_end name_start name_end name_start id_start id_end id_start idvaluepair idvaluepair setlinenumber getlinenumber all_pairs addelement private static boolean is white space int c return c c t is_white_space private static int skip white space char array int begin int end int cursor begin for cursor end cursor int c array cursor if is white space c break return cursor skip_white_space is_white_space private static int skip matched prefix string prefix char array int begin int end int cursor 1 int prefix length prefix length if prefix length end begin cursor begin for int i 0 i prefix length i cursor if prefix char at i array cursor cursor 1 break return cursor skip_matched_prefix prefix_length prefix_length prefix_length charat 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 static int skip name char char array int begin int end int cursor begin for cursor end cursor int c array cursor if a c c z a c c z if 0 c c 9 if c break return cursor skip_name_char _ public static void main string args main self new main int status self exec args system exit status private int exec string args r new tool error reporter true system err int arg count process options args if arg count 0 option error tool error reporter get message msg idswitch no file argument return 1 if arg count 1 option error tool error reporter get message msg idswitch too many arguments return 1 p new code printer p set indent step 4 p set indent tab size 0 try process file args 0 catch io exception ex print error tool error reporter get message msg idswitch io error ex to string return 1 catch evaluator exception ex return 1 return 0 toolerrorreporter arg_count process_options arg_count option_error toolerrorreporter getmessage no_file_argument arg_count option_error toolerrorreporter getmessage too_many_arguments codeprinter setindentstep setindenttabsize process_file ioexception print_error toolerrorreporter getmessage io_error tostring evaluatorexception private int process options string args int status 1 boolean show usage false boolean show version false int n args length l for int i 0 i n i string arg args i int arg length arg length if arg length 2 if arg char at 0 if arg char at 1 if arg length 2 args i null break if arg equals help show usage true else if arg equals version show version true else option error tool error reporter get message msg idswitch bad option arg status 1 break l else for int j 1 j arg length j char c arg char at j switch c case h show usage true break default option error tool error reporter get message msg idswitch bad option char string value of c status 1 break l args i null if status 1 if show usage show usage status 0 if show version show version status 0 if status 1 system exit status return remove nulls args process_options show_usage show_version arg_length arg_length charat charat arg_length show_usage show_version option_error toolerrorreporter getmessage bad_option arg_length charat show_usage option_error toolerrorreporter getmessage bad_option_char valueof show_usage show_usage show_version show_version remove_nulls private void show usage system out println tool error reporter get message msg idswitch usage system out println show_usage toolerrorreporter getmessage private void show version system out println tool error reporter get message msg idswitch version show_version toolerrorreporter getmessage private void option error string str print error tool error reporter get message msg idswitch bad invocation str option_error print_error toolerrorreporter getmessage bad_invocation private void print error string text system err println text print_error private int remove nulls string array int n array length int cursor 0 for cursor n cursor if array cursor null break int destination cursor if cursor n cursor for cursor n cursor string elem array cursor if elem null array destination elem destination return destination remove_nulls native java method member box methods this function name methods 0 get name this methods methods nativejavamethod memberbox functionname getname native java method member box method string name this function name name this methods new member box method nativejavamethod memberbox functionname memberbox public native java method method method string name this new member box method name nativejavamethod memberbox public string get function name return function name getfunctionname functionname static string script signature object values string buffer sig new string buffer for int i 0 i values length i object value values i string s if value null s null else if value instanceof boolean s boolean else if value instanceof string s string else if value instanceof number s number else if value instanceof scriptable if value instanceof undefined s undefined else if value instanceof wrapper object wrapped wrapper value unwrap s wrapped get class get name else if value instanceof function s function else s object else s java members java signature value get class if i 0 sig append sig append s return sig to string scriptsignature stringbuffer stringbuffer getclass getname javamembers javasignature getclass tostring string decompile int indent int flags string buffer sb new string buffer boolean justbody 0 flags decompiler only body flag if justbody sb append function sb append get function name sb append sb append n sb append to string sb append justbody n n return sb to string stringbuffer stringbuffer only_body_flag getfunctionname tostring tostring public string to string string buffer sb new string buffer for int i 0 n methods length i n i method method methods i method sb append java members java signature method get return type sb append sb append method get name sb append java members live connect signature methods i arg types sb append n return sb to string tostring stringbuffer stringbuffer javamembers javasignature getreturntype getname javamembers liveconnectsignature argtypes tostring public object call context cx scriptable scope scriptable this obj object args find a method that matches the types given if methods length 0 throw new runtime exception no methods defined for call int index find function cx methods args if index 0 class c methods 0 method get declaring class string sig c get name get function name script signature args throw context report runtime error1 msg java no such method sig member box meth methods index class arg types meth arg types first we marshall the args object orig args args for int i 0 i args length i object arg args i object coerced context js to java arg arg types i if coerced arg if orig args args args object args clone args i coerced object java object if meth is static java object null don t need an object else scriptable o this obj class c meth get declaring class for if o null throw context report runtime error3 msg nonjava method get function name script runtime to string this obj c get name if o instanceof wrapper java object wrapper o unwrap if c is instance java object break o o get prototype if debug print debug calling meth args object retval meth invoke java object args class static type meth method get return type if debug class actual type retval null null retval get class system err println returned retval actual actual type expect static type object wrapped cx get wrap factory wrap cx scope retval static type if debug class actual type wrapped null null wrapped get class system err println wrapped as wrapped class actual type if wrapped null static type void type wrapped undefined instance return wrapped thisobj runtimeexception findfunction getdeclaringclass getname getfunctionname scriptsignature reportruntimeerror1 no_such_method memberbox argtypes argtypes origargs jstojava argtypes origargs javaobject isstatic javaobject thisobj getdeclaringclass reportruntimeerror3 getfunctionname scriptruntime tostring thisobj getname javaobject isinstance javaobject getprototype printdebug javaobject statictype getreturntype actualtype getclass actualtype statictype getwrapfactory statictype actualtype getclass actualtype statictype find the index of the correct function to call given the set of methods or constructors and the arguments if no function can be found to call return 1 static int find function context cx member box methods or ctors object args if methods or ctors length 0 return 1 else if methods or ctors length 1 member box member methods or ctors 0 class arg types member arg types int alength arg types length if alength args length return 1 for int j 0 j alength j if native java object can convert args j arg types j if debug print debug rejecting args can t convert member args return 1 if debug print debug found member args return 0 int first best fit 1 int extra best fits null int extra best fits count 0 search for int i 0 i methods or ctors length i member box member methods or ctors i class arg types member arg types if arg types length args length continue search for int j 0 j arg types length j if native java object can convert args j arg types j if debug print debug rejecting args can t convert member args continue search if first best fit 0 if debug print debug found first applicable member args first best fit i else compare with all currently fit methods the loop starts from 1 denoting first best fit and proceed until extra best fits count to avoid extra best fits allocation in the most common case of no ambiguity int better count 0 number of times member was prefered over best fits int worse count 0 number of times best fits were prefered over member for int j 1 j extra best fits count j int best fit index if j 1 best fit index first best fit else best fit index extra best fits j member box best fit methods or ctors best fit index int preference prefer signature args arg types best fit arg types if preference preference ambiguous break else if preference preference first arg better count else if preference preference second arg worse count else if preference preference equal kit code bug this should not happen in theory but on some jv ms class get methods will return all static methods of the class heirarchy even if a derived class s parameters match exactly we want to call the dervied class s method if best fit is static best fit get declaring class is assignable from member get declaring class on some jv ms class get methods will return all static methods of the class heirarchy even if a derived class s parameters match exactly we want to call the dervied class s method if debug print debug substituting overridden static member args if j 1 first best fit i else extra best fits j i else if debug print debug ignoring same signature member member args continue search if better count 1 extra best fits count member was prefered over all best fits if debug print debug new first applicable member args first best fit i extra best fits count 0 else if worse count 1 extra best fits count all best fits were prefered over member ignore it if debug print debug rejecting all current bests better member args else some ambiguity was present add member to best fit set if debug print debug added to best fit set member args if extra best fits null allocate maximum possible array extra best fits new int methods or ctors length 1 extra best fits extra best fits count i extra best fits count if first best fit 0 nothing was found return 1 else if extra best fits count 0 single best fit return first best fit report remaining ambiguity string buffer buf new string buffer for int j 1 j extra best fits count j int best fit index if j 1 best fit index first best fit else best fit index extra best fits j buf append n buf append methods or ctors best fit index to java declaration member box first fit member methods or ctors first best fit string member name first fit member get name string member class first fit member get declaring class get name if methods or ctors 0 is method throw context report runtime error3 msg constructor ambiguous member name script signature args buf to string else throw context report runtime error4 msg method ambiguous member class member name script signature args buf to string findfunction memberbox methodsorctors methodsorctors methodsorctors memberbox methodsorctors argtypes argtypes argtypes nativejavaobject canconvert argtypes printdebug printdebug firstbestfit extrabestfits extrabestfitscount methodsorctors memberbox methodsorctors argtypes argtypes argtypes argtypes nativejavaobject canconvert argtypes printdebug firstbestfit printdebug firstbestfit firstbestfit extrabestfitscount extrabestfits bettercount worsecount extrabestfitscount bestfitindex bestfitindex firstbestfit bestfitindex extrabestfits memberbox bestfit methodsorctors bestfitindex prefersignature argtypes bestfit argtypes preference_ambiguous preference_first_arg bettercount preference_second_arg worsecount preference_equal codebug jvms getmethods bestfit isstatic bestfit getdeclaringclass isassignablefrom getdeclaringclass jvms getmethods printdebug firstbestfit extrabestfits printdebug bettercount extrabestfitscount printdebug firstbestfit extrabestfitscount worsecount extrabestfitscount printdebug printdebug extrabestfits extrabestfits methodsorctors extrabestfits extrabestfitscount extrabestfitscount firstbestfit extrabestfitscount firstbestfit stringbuffer stringbuffer extrabestfitscount bestfitindex bestfitindex firstbestfit bestfitindex extrabestfits methodsorctors bestfitindex tojavadeclaration memberbox firstfitmember methodsorctors firstbestfit membername firstfitmember getname memberclass firstfitmember getdeclaringclass getname methodsorctors ismethod reportruntimeerror3 membername scriptsignature tostring reportruntimeerror4 memberclass membername scriptsignature tostring determine which of two signatures is the closer fit returns one of preference equal preference first arg preference second arg or preference ambiguous private static int prefer signature object args class sig1 class sig2 int total preference 0 for int j 0 j args length j class type1 sig1 j class type2 sig2 j if type1 type2 continue object arg args j determine which of type1 type2 is easier to convert from arg int rank1 native java object get conversion weight arg type1 int rank2 native java object get conversion weight arg type2 int preference if rank1 rank2 preference preference first arg else if rank1 rank2 preference preference second arg else equal ranks if rank1 native java object conversion nontrivial if type1 is assignable from type2 preference preference second arg else if type2 is assignable from type1 preference preference first arg else preference preference ambiguous else preference preference ambiguous total preference preference if total preference preference ambiguous break return total preference preference_equal preference_first_arg preference_second_arg preference_ambiguous prefersignature totalpreference nativejavaobject getconversionweight nativejavaobject getconversionweight preference_first_arg preference_second_arg nativejavaobject conversion_nontrivial isassignablefrom preference_second_arg isassignablefrom preference_first_arg preference_ambiguous preference_ambiguous totalpreference totalpreference preference_ambiguous totalpreference private static void print debug string msg member box member object args if debug string buffer sb new string buffer sb append sb append msg sb append member get declaring class get name sb append if member is method sb append member get name sb append java members live connect signature member arg types sb append for arguments sb append script signature args sb append system out println sb printdebug memberbox stringbuffer stringbuffer getdeclaringclass getname ismethod getname javamembers liveconnectsignature argtypes scriptsignature public interface quit action public void quit context cx int exit code quitaction exitcode public interface scope provider returns the scope object to be used for script evaluation scriptable get scope scopeprovider getscope public interface gui callback called when the source text of some script has been changed void update source text dim source info source info guicallback updatesourcetext sourceinfo sourceinfo called when the interrupt loop has been entered void enter interrupt dim stack frame last frame string thread title enterinterrupt stackframe lastframe threadtitle returns whether the current thread is the gui s event thread this information is required to avoid blocking the event thread from the debugger processes the next gui event this manual pumping of gui events is necessary when the gui event thread itself has been stopped returns an array of ids for the properties of the object p all properties even those with attribute dont enum are listed this allows the debugger to display all properties of the object 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 dontenum called when execution is ready to start bytecode interpretation for entered a particular function or script param cx current context for this thread param activation the activation scope for the function or script param this obj value of the java script code this code object param args the array of arguments public void on enter context cx scriptable activation thisobj javascript onenter scriptable this obj object args called when executed code reaches new line in the source param cx current context for this thread param line number current line number in the script source thisobj linenumber called when thrown exception is handled by the function or script param cx current context for this thread param ex exception object called when the function or script for this frame is about to return param cx current context for this thread param by throw if true function will leave by throwing exception otherwise it will execute normal return param result or exception function result in case of normal return or exception object if about to throw exception bythrow resultorexception called when compilation of a particular function or script into internal bytecode is done param cx current context for this thread param fn or script object describing the function or script param source the function or script source void handle compilation done context cx debuggable script fn or script fnorscript handlecompilationdone debuggablescript fnorscript called when execution entered a particular function or script return implementation of debug frame which receives debug information during the function or script execution or null otherwise debugframe public interface debuggable script public boolean is top level debuggablescript istoplevel public boolean is top level returns true if this is a function false if it is a script public boolean is function istoplevel isfunction get name of the function described by this script return null or an empty string if this script is not function get number of declared parameters in function return 0 if this script is not function see get param and var count see get param or var name int index getparamandvarcount getparamorvarname get number of declared parameters and local variables return number of declared global variables if this script is not function see get param count see get param or var name int index getparamcount getparamorvarname get name of a declared parameter or local variable tt index tt should be less then link get param and var count if tt index nbsp lt nbsp link get param count tt return the name of the corresponding parameter otherwise return the name of variable if this script is not function return the name of the declared global variable getparamandvarcount getparamcount get the name of the source usually filename or url of the script returns true if this script or function were runtime generated from java script using tt eval tt function or tt function tt or tt script tt constructors javascript get array containing the line numbers that that can be passed to code debug frame on line change code note that line order in the resulting array is arbitrary debugframe onlinechange public int get line numbers public int get function count getlinenumbers getfunctioncount public int get function count public debuggable script get function int index getfunctioncount debuggablescript getfunction public debuggable script get function int index public debuggable script get parent debuggablescript getfunction debuggablescript getparent perform the call param cx the current context for this thread param scope the scope to use to resolve properties param this obj the java script code this code object param args the array of arguments return the result of the call public object call context cx scriptable scope scriptable this obj thisobj javascript thisobj deprecated rhino runtime never calls the method public void context entered context cx contextentered public void context entered context cx deprecated rhino runtime never calls the method public void context exited context cx contextentered contextexited call the function note that the array of arguments is not guaranteed to have length greater than 0 param cx the current context for this thread param scope the scope to execute the function relative to this is set to the value returned by get parent scope except when the function is called from a closure param this obj the java script code this code object param args the array of arguments return the result of the call public object call context cx scriptable scope scriptable this obj getparentscope thisobj javascript thisobj call the function as a constructor this method is invoked by the runtime in order to satisfy a use of the java script code new code operator this method is expected to create a new object and return it param cx the current context for this thread param scope an enclosing scope of the caller except when the function is called from a closure param args the array of arguments return the allocated object javascript unwrap the object by returning the wrapped value return a wrapped value return true iff the java class with the given name should be exposed to scripts p an embedding may filter which java classes are exposed through live connect to java script scripts p due to the fact that there is no package reflection in java this method will also be called with package names there is no way for rhino to tell if packages a b is a package name or a class that doesn t exist what rhino does is attempt to load each segment of packages a b c it first attempts to load class a then attempts to load class a b then finally attempts to load class a b c on a rhino installation without any class shutter set and without any of the above classes the expression packages a b c will result in a java package a b c and not an error p with class shutter supplied rhino will first call visible to scripts before attempting to look up the class name if visible to scripts returns false the class name lookup is not performed and subsequent rhino execution assumes the class is not present so for java lang system out println the lookup of java lang system is skipped and thus rhino assumes that java lang system doesn t exist so then for java lang system out rhino attempts to load the class java lang system out because it assumes that java lang system is a package name p param full class name the full name of the class including the package name with as a delimiter for example the standard string class is java lang string return whether or not to reveal this class to scripts liveconnect javascript classshutter javapackage classshutter visibletoscripts visibletoscripts fullclassname this obj will be null if invoked as constructor in which case instance of scriptable should be returned public object exec id call id function object f context cx scriptable scope thisobj execidcall idfunctionobject get the name of the set of objects implemented by this java class this corresponds to the class operation in ecma and is used by object prototype to string in ecma p see ecma 8 6 2 and 15 2 4 2 tostring get a named property from the object looks property up in this object and returns the associated value if found returns not found if not found note that this method is not expected to traverse the prototype chain this is different from the ecma get operation depending on the property selector the runtime will call this method or the form of code get code that takes an integer table tr th java script code th th java code th tr tr td a b td td a get b a td tr tr td a foo td td a get foo a td tr tr td a 3 td td a get 3 a td tr tr td a 3 td td a get 3 a td tr tr td a 3 0 td td a get 3 a td tr tr td a 3 0 td td a get 3 0 a td tr tr td a 1 1 td td a get 1 1 a td tr tr td a 4 td td a get 4 a td tr table p the values that may be returned are limited to the following ul li java lang boolean objects li li java lang string objects li li java lang number objects li li org mozilla javascript scriptable objects li li null li li the value returned by context get undefined value li li not found li ul 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 see org mozilla javascript context get undefined value not_found javascript getundefinedvalue not_found not_found getundefinedvalue get a property from the object selected by an integral index identical to code get string scriptable code except that an integral index is used to select the property 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 see org mozilla javascript scriptable get string scriptable not_found indicates whether or not a named property is defined in an object does not traverse the prototype chain p the property is specified by a string name as defined for the code get code method p param name the name of the property param start the object in which the lookup began return true if and only if the named property is found in the object see org mozilla javascript scriptable get see org mozilla javascript scriptable object get property scriptableobject getproperty indicates whether or not an indexed property is defined in an object does not traverse the prototype chain p the property is specified by an integral index as defined for the code get code method p param index the numeric index for the property param start the object in which the lookup began return true if and only if the indexed property is found in the object see org mozilla javascript scriptable get see org mozilla javascript scriptable object get property scriptableobject getproperty sets a named property in this object p the property is specified by a string name as defined for code get code p the possible values that may be passed in are as defined for code get code a class that implements this method may choose to ignore calls to set certain properties in which case those properties are effectively read only p for properties defined in a prototype chain use code put property code in scriptable object p note that if a property i a i is defined in the prototype i p i of an object i o i then evaluating code o a 23 code will cause code set code to be called on the prototype i p i with i o i as the i start i parameter to preserve java script semantics it is the scriptable object s responsibility to modify i o i p this design allows properties to be defined in prototypes and implemented in terms of getters and setters of java values without consuming slots in each instance p p the values that may be set are limited to the following ul li java lang boolean objects li li java lang string objects li li java lang number objects li li org mozilla javascript scriptable objects li li null li li the value returned by context get undefined value li ul p arbitrary java objects may be wrapped in a scriptable by first calling code context to object code this allows the property of a java script object to contain an arbitrary java object as a value p note that code has code will be called by the runtime first before code set code is called to determine in which object the property is defined note that this method is not expected to traverse the prototype chain which is different from the ecma put operation param name the name of the property param start the object whose property is being set param value value to set the property to see org mozilla javascript scriptable has see org mozilla javascript scriptable get see org mozilla javascript scriptable object put property see org mozilla javascript context to object putproperty scriptableobject javascript getundefinedvalue toobject javascript scriptableobject putproperty toobject sets an indexed property in this object p the property is specified by an integral index as defined for code get code p identical to code put string scriptable object code except that an integral index is used to select the property 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 see org mozilla javascript scriptable has see org mozilla javascript scriptable get see org mozilla javascript scriptable put string scriptable object see org mozilla javascript scriptable object put property scriptableobject putproperty removes a property from this object this operation corresponds to the ecma delete except that the no result is returned the runtime will guarantee that this method is called only if the property exists after this method is called the runtime will call scriptable has to see if the property has been removed in order to determine the boolean result of the delete operator as defined by ecma 11 4 1 p a property can be made permanent by ignoring calls to remove it p the property is specified by a string name as defined for code get code p to delete properties defined in a prototype chain see delete property in scriptable object param name the identifier for the property see org mozilla javascript scriptable get see org mozilla javascript scriptable object delete property deleteproperty scriptableobject scriptableobject deleteproperty removes a property from this object the property is specified by an integral index as defined for code get code p to delete properties defined in a prototype chain see delete property in scriptable object identical to code delete string code except that an integral index is used to select the property param index the numeric index for the property see org mozilla javascript scriptable get see org mozilla javascript scriptable object delete property deleteproperty scriptableobject scriptableobject deleteproperty get the prototype of the object return the prototype set the prototype of the object param prototype the prototype to set get the parent scope of the object return the parent scope set the parent scope of the object param parent the parent scope to set get an array of property ids not all property ids need be returned those properties whose ids are not returned are considered non enumerable return an array of objects each entry in the array is either a java lang string or a java lang number get the default value of the object with a given hint the hints are string class for type string number class for type number scriptable class for type object and boolean class for type boolean p a code hint code of null means no hint see ecma 8 6 2 6 param hint the type hint return the default value the instanceof operator p the java script code lhs instanceof rhs causes rhs has instance lhs to be called p the return value is implementation dependent so that embedded host objects can return an appropriate value see the js 1 3 language documentation for more detail p this operator corresponds to the proposed emca has instance operator param instance the value that appeared on the lhs of the instanceof operator return an implementation dependent value javascript hasinstance hasinstance execute action using the supplied context instance when rhino runtime calls the method tt cx tt will be associated with the current thread as active context see context call context action see context factory call context action contextaction contextfactory contextaction public static final int ra search 3 public boolean is reg exp scriptable obj ra_search isregexp public boolean is reg exp scriptable obj public object compile reg exp context cx string source string flags isregexp compileregexp public object compile reg exp context cx string source string flags public scriptable wrap reg exp context cx scriptable scope object compiled compileregexp wrapregexp object compiled public object action context cx scriptable scope scriptable this obj object args int action type thisobj actiontype int action type public int find split context cx scriptable scope string target string separator scriptable re int ip int matchlen boolean matched string parensp actiontype find_split perform function call in reference context the args array reference should not be stored in any object that is can be gc reachable after this method returns if this is necessary for example to implement link ref methods then store args clone not args array itself param cx the current context for this thread param this obj the java script code this code object param args the array of arguments thisobj javascript execute the script p the script is executed in a particular runtime context which must be associated with the current thread the script is executed relative to a scope definitions and uses of global top level variables and functions will access properties of the scope object for compliant ecma programs the scope must be an object that has been initialized as a global object using code context init standard objects code p param cx the context associated with the current thread param scope the scope to execute relative to return the result of executing the script see org mozilla javascript context init standard objects initstandardobjects initstandardobjects define a new java class classes created via this method should have the same class loader param name fully qualified class name param data class byte code return new class object link the given class param cl class instance returned from the previous call to link define class string byte see java lang class loader resolve class class defineclass classloader resolveclass report a warning the implementing class may choose to ignore the warning if it desires param message a string describing the warning param source name a string describing the java script source where the warning occured typically a filename or url param line the line number associated with the warning param line source the text of the line may be null param line offset the offset into line source where problem was detected void warning string message string source name int line sourcename javascript linesource lineoffset linesource sourcename report an error the implementing class is free to throw an exception if it desires if execution has not yet begun the java script engine is free to find additional errors rather than terminating the translation it will not execute a script that had errors however param message a string describing the error param source name a string describing the java script source where the error occured typically a filename or url param line the line number associated with the error param line source the text of the line may be null param line offset the offset into line source where problem was detected void error string message string source name int line javascript sourcename javascript linesource lineoffset linesource sourcename public interface test environment pass the java script program to the java script environment testenvironment javascript javascript create a new java script context in which to evaluate a java script program return the java script context javascript javascript javascript given a filename evaluate the file s contents as a java script program return the return value of the java script program if the test throws a java exception or java script runtime or compilation error return the string value of the error message javascript javascript javascript evaluate the result of the java script program attempt to get the java script array of test case objects for each test case object found create a com netscape javascript qa drivers test case object and populate its fields return true if the the result could be parsed successfully false otherwise javascript javascript testcase testcase testcase public boolean parse result close the context destroy the java script environment public void close parseresult javascript