diff options
Diffstat (limited to 'tests')
179 files changed, 29570 insertions, 446 deletions
diff --git a/tests/examplefiles/99_bottles_of_beer.chpl b/tests/examplefiles/99_bottles_of_beer.chpl new file mode 100644 index 00000000..f73be7b1 --- /dev/null +++ b/tests/examplefiles/99_bottles_of_beer.chpl @@ -0,0 +1,118 @@ +/*********************************************************************** + * Chapel implementation of "99 bottles of beer" + * + * by Brad Chamberlain and Steve Deitz + * 07/13/2006 in Knoxville airport while waiting for flight home from + * HPLS workshop + * compiles and runs with chpl compiler version 1.7.0 + * for more information, contact: chapel_info@cray.com + * + * + * Notes: + * o as in all good parallel computations, boundary conditions + * constitute the vast bulk of complexity in this code (invite Brad to + * tell you about his zany boundary condition simplification scheme) + * o uses type inference for variables, arguments + * o relies on integer->string coercions + * o uses named argument passing (for documentation purposes only) + ***********************************************************************/ + +// allow executable command-line specification of number of bottles +// (e.g., ./a.out -snumBottles=999999) +config const numBottles = 99; +const numVerses = numBottles+1; + +// a domain to describe the space of lyrics +var LyricsSpace: domain(1) = {1..numVerses}; + +// array of lyrics +var Lyrics: [LyricsSpace] string; + +// parallel computation of lyrics array +[verse in LyricsSpace] Lyrics(verse) = computeLyric(verse); + +// as in any good parallel language, I/O to stdout is serialized. +// (Note that I/O to a file could be parallelized using a parallel +// prefix computation on the verse strings' lengths with file seeking) +writeln(Lyrics); + + +// HELPER FUNCTIONS: + +proc computeLyric(verseNum) { + var bottleNum = numBottles - (verseNum - 1); + var nextBottle = (bottleNum + numVerses - 1)%numVerses; + return "\n" // disguise space used to separate elements in array I/O + + describeBottles(bottleNum, startOfVerse=true) + " on the wall, " + + describeBottles(bottleNum) + ".\n" + + computeAction(bottleNum) + + describeBottles(nextBottle) + " on the wall.\n"; +} + + +proc describeBottles(bottleNum, startOfVerse:bool = false) { + // NOTE: bool should not be necessary here (^^^^); working around bug + var bottleDescription = if (bottleNum) then bottleNum:string + else (if startOfVerse then "N" + else "n") + + "o more"; + return bottleDescription + + " bottle" + (if (bottleNum == 1) then "" else "s") + + " of beer"; +} + + +proc computeAction(bottleNum) { + return if (bottleNum == 0) then "Go to the store and buy some more, " + else "Take one down and pass it around, "; +} + + +// Modules... +module M1 { + var x = 10; +} + +module M2 { + use M1; + proc main() { + writeln("M2 -> M1 -> x " + x); + } +} + + +// Classes, records, unions... +const PI: real = 3.14159; + +record Point { + var x, y: real; +} +var p: Point; +writeln("Distance from origin: " + sqrt(p.x ** 2 + p.y ** 2)); +p = new Point(1.0, 2.0); +writeln("Distance from origin: " + sqrt(p.x ** 2 + p.y ** 2)); + +class Circle { + var p: Point; + var r: real; +} +var c = new Circle(r=2.0); +proc Circle.area() + return PI * r ** 2; +writeln("Area of circle: " + c.area()); + +class Oval: Circle { + var r2: real; +} +proc Oval.area() + return PI * r * r2; + +delete c; +c = nil; +c = new Oval(r=1.0, r2=2.0); +writeln("Area of oval: " + c.area()); + +union U { + var i: int; + var r: real; +} diff --git a/tests/examplefiles/AcidStateAdvanced.hs b/tests/examplefiles/AcidStateAdvanced.hs new file mode 100644 index 00000000..9e3e7718 --- /dev/null +++ b/tests/examplefiles/AcidStateAdvanced.hs @@ -0,0 +1,209 @@ +{-# LANGUAGE DeriveDataTypeable, FlexibleContexts, GeneralizedNewtypeDeriving + , MultiParamTypeClasses, OverloadedStrings, ScopedTypeVariables, TemplateHaskell + , TypeFamilies, FlexibleInstances #-} +module Main where +import Control.Applicative (Applicative, Alternative, (<$>)) +import Control.Exception.Lifted (bracket) +import Control.Monad.Trans.Control (MonadBaseControl) +import Control.Monad (MonadPlus, mplus) +import Control.Monad.Reader (MonadReader, ReaderT(..), ask) +import Control.Monad.Trans (MonadIO(..)) +import Data.Acid ( AcidState(..), EventState(..), EventResult(..) + , Query(..), QueryEvent(..), Update(..), UpdateEvent(..) + , IsAcidic(..), makeAcidic, openLocalState + ) +import Data.Acid.Local ( createCheckpointAndClose + , openLocalStateFrom + ) +import Data.Acid.Advanced (query', update') +import Data.Maybe (fromMaybe) +import Data.SafeCopy (SafeCopy, base, deriveSafeCopy) +import Data.Data (Data, Typeable) +import Data.Lens ((%=), (!=)) +import Data.Lens.Template (makeLens) +import Data.Text.Lazy (Text) +import Happstack.Server ( Happstack, HasRqData, Method(GET, POST), Request(rqMethod) + , Response + , ServerPartT(..), WebMonad, FilterMonad, ServerMonad + , askRq, decodeBody, dir, defaultBodyPolicy, lookText + , mapServerPartT, nullConf, nullDir, ok, simpleHTTP + , toResponse + ) +import Prelude hiding (head, id) +import System.FilePath ((</>)) +import Text.Blaze ((!)) +import Text.Blaze.Html4.Strict (body, head, html, input, form, label, p, title, toHtml) +import Text.Blaze.Html4.Strict.Attributes (action, enctype, for, id, method, name, type_, value) +class HasAcidState m st where + getAcidState :: m (AcidState st) +query :: forall event m. + ( Functor m + , MonadIO m + , QueryEvent event + , HasAcidState m (EventState event) + ) => + event + -> m (EventResult event) +query event = + do as <- getAcidState + query' (as :: AcidState (EventState event)) event +update :: forall event m. + ( Functor m + , MonadIO m + , UpdateEvent event + , HasAcidState m (EventState event) + ) => + event + -> m (EventResult event) +update event = + do as <- getAcidState + update' (as :: AcidState (EventState event)) event +-- | bracket the opening and close of the `AcidState` handle. + +-- automatically creates a checkpoint on close +withLocalState :: (MonadBaseControl IO m, MonadIO m, IsAcidic st, Typeable st) => + Maybe FilePath -- ^ path to state directory + -> st -- ^ initial state value + -> (AcidState st -> m a) -- ^ function which uses the `AcidState` handle + -> m a +withLocalState mPath initialState = + bracket (liftIO $ (maybe openLocalState openLocalStateFrom mPath) initialState) + (liftIO . createCheckpointAndClose) +-- State that stores a hit count + +data CountState = CountState { _count :: Integer } + deriving (Eq, Ord, Data, Typeable, Show) + +$(deriveSafeCopy 0 'base ''CountState) +$(makeLens ''CountState) + +initialCountState :: CountState +initialCountState = CountState { _count = 0 } + +incCount :: Update CountState Integer +incCount = count %= succ + +$(makeAcidic ''CountState ['incCount]) +-- State that stores a greeting +data GreetingState = GreetingState { _greeting :: Text } + deriving (Eq, Ord, Data, Typeable, Show) + +$(deriveSafeCopy 0 'base ''GreetingState) +$(makeLens ''GreetingState) + +initialGreetingState :: GreetingState +initialGreetingState = GreetingState { _greeting = "Hello" } + +getGreeting :: Query GreetingState Text +getGreeting = _greeting <$> ask + +setGreeting :: Text -> Update GreetingState Text +setGreeting txt = greeting != txt + +$(makeAcidic ''GreetingState ['getGreeting, 'setGreeting]) +data Acid = Acid { acidCountState :: AcidState CountState + , acidGreetingState :: AcidState GreetingState + } + +withAcid :: Maybe FilePath -> (Acid -> IO a) -> IO a +withAcid mBasePath action = + let basePath = fromMaybe "_state" mBasePath + in withLocalState (Just $ basePath </> "count") initialCountState $ \c -> + withLocalState (Just $ basePath </> "greeting") initialGreetingState $ \g -> + action (Acid c g) +newtype App a = App { unApp :: ServerPartT (ReaderT Acid IO) a } + deriving ( Functor, Alternative, Applicative, Monad, MonadPlus, MonadIO + , HasRqData, ServerMonad ,WebMonad Response, FilterMonad Response + , Happstack, MonadReader Acid) + +runApp :: Acid -> App a -> ServerPartT IO a +runApp acid (App sp) = mapServerPartT (flip runReaderT acid) sp +instance HasAcidState App CountState where + getAcidState = acidCountState <$> ask + +instance HasAcidState App GreetingState where + getAcidState = acidGreetingState <$> ask +page :: App Response +page = + do nullDir + g <- greet + c <- update IncCount -- ^ a CountState event + ok $ toResponse $ + html $ do + head $ do + title "acid-state demo" + body $ do + form ! action "/" ! method "POST" ! enctype "multipart/form-data" $ do + label "new message: " ! for "msg" + input ! type_ "text" ! id "msg" ! name "greeting" + input ! type_ "submit" ! value "update message" + p $ toHtml g + p $ do "This page has been loaded " + toHtml c + " time(s)." + where + greet = + do m <- rqMethod <$> askRq + case m of + POST -> + do decodeBody (defaultBodyPolicy "/tmp/" 0 1000 1000) + newGreeting <- lookText "greeting" + update (SetGreeting newGreeting) -- ^ a GreetingState event + return newGreeting + GET -> + do query GetGreeting -- ^ a GreetingState event +main :: IO () +main = + withAcid Nothing $ \acid -> + simpleHTTP nullConf $ runApp acid page +newtype FooState = FooState { foo :: Text } + deriving (Eq, Ord, Data, Typeable, SafeCopy) + +initialFooState :: FooState +initialFooState = FooState { foo = "foo" } + +askFoo :: Query FooState Text +askFoo = foo <$> ask + +$(makeAcidic ''FooState ['askFoo]) +fooPlugin :: (Happstack m, HasAcidState m FooState) => m Response +fooPlugin = + dir "foo" $ do + txt <- query AskFoo + ok $ toResponse txt +data Acid' = Acid' { acidCountState' :: AcidState CountState + , acidGreetingState' :: AcidState GreetingState + , acidFooState' :: AcidState FooState + } +withAcid' :: Maybe FilePath -> (Acid' -> IO a) -> IO a +withAcid' mBasePath action = + let basePath = fromMaybe "_state" mBasePath + in withLocalState (Just $ basePath </> "count") initialCountState $ \c -> + withLocalState (Just $ basePath </> "greeting") initialGreetingState $ \g -> + withLocalState (Just $ basePath </> "foo") initialFooState $ \f -> + action (Acid' c g f) +newtype App' a = App' { unApp' :: ServerPartT (ReaderT Acid' IO) a } + deriving ( Functor, Alternative, Applicative, Monad, MonadPlus, MonadIO + , HasRqData, ServerMonad ,WebMonad Response, FilterMonad Response + , Happstack, MonadReader Acid') + +instance HasAcidState App' FooState where + getAcidState = acidFooState' <$> ask +fooAppPlugin :: App' Response +fooAppPlugin = fooPlugin +fooReaderPlugin :: ReaderT (AcidState FooState) (ServerPartT IO) Response +fooReaderPlugin = fooPlugin +instance HasAcidState (ReaderT (AcidState FooState) (ServerPartT IO)) FooState where + getAcidState = ask +withFooPlugin :: (MonadIO m, MonadBaseControl IO m) => + FilePath -- ^ path to state directory + -> (ServerPartT IO Response -> m a) -- ^ function that uses fooPlugin + -> m a +withFooPlugin basePath f = + do withLocalState (Just $ basePath </> "foo") initialFooState $ \fooState -> + f $ runReaderT fooReaderPlugin fooState +main' :: IO () +main' = + withFooPlugin "_state" $ \fooPlugin' -> + withAcid Nothing $ \acid -> + simpleHTTP nullConf $ fooPlugin' `mplus` runApp acid page diff --git a/tests/examplefiles/BOM.js b/tests/examplefiles/BOM.js new file mode 100644 index 00000000..930599c1 --- /dev/null +++ b/tests/examplefiles/BOM.js @@ -0,0 +1 @@ +/* There is a BOM at the beginning of this file. */
\ No newline at end of file diff --git a/tests/examplefiles/Config.in.cache b/tests/examplefiles/Config.in.cache new file mode 100644 index 00000000..e2f6ad5d --- /dev/null +++ b/tests/examplefiles/Config.in.cache @@ -0,0 +1,1973 @@ +# INCLUDE_BEGIN Config.in +mainmenu "Freetz Configuration" + +config FREETZ_HAVE_DOT_CONFIG + bool + default y + +comment "General --------------------------------" + +config FREETZ_AVM_VERSION_04_30 + bool +config FREETZ_AVM_VERSION_04_33 + bool +config FREETZ_AVM_VERSION_04_40 + bool +config FREETZ_AVM_VERSION_04_49 + bool +config FREETZ_AVM_VERSION_04_57 + bool +config FREETZ_AVM_VERSION_04_67 + bool +config FREETZ_AVM_VERSION_04_70 + bool +config FREETZ_AVM_VERSION_04_76 + bool +config FREETZ_AVM_VERSION_04_80 + bool +config FREETZ_AVM_VERSION_04_87 + bool +config FREETZ_AVM_VERSION_7270_04_86 + bool +config FREETZ_AVM_VERSION_7270_05_05 + bool +config FREETZ_AVM_VERSION_7320_04_86 + bool +config FREETZ_AVM_VERSION_7390_04_90 + bool +config FREETZ_AVM_VERSION_7390_05_05 + bool +config FREETZ_AVM_VERSION_r7203 + bool + +choice + prompt "Hardware type" + default FREETZ_TYPE_FON_WLAN_7270_V2 + help + Select your box type here. + + config FREETZ_TYPE_300IP_AS_FON + select FREETZ_AVM_VERSION_04_49 + bool "300IP as Fon" + + config FREETZ_TYPE_2170 + select FREETZ_AVM_VERSION_04_57 + bool "2170" + + config FREETZ_TYPE_FON + select FREETZ_AVM_VERSION_04_33 if FREETZ_TYPE_LANG_DE + select FREETZ_AVM_VERSION_04_49 if ! FREETZ_TYPE_LANG_DE + bool "Fon" + + config FREETZ_TYPE_FON_5010 + select FREETZ_AVM_VERSION_04_40 + bool "Fon 5010" + + config FREETZ_TYPE_FON_5050 + select FREETZ_AVM_VERSION_04_30 + bool "Fon 5050" + + config FREETZ_TYPE_FON_5124 + select FREETZ_AVM_VERSION_04_76 + bool "Fon 5124" + + config FREETZ_TYPE_FON_5140 + select FREETZ_AVM_VERSION_04_67 + bool "Fon 5140" + + config FREETZ_TYPE_FON_WLAN + select FREETZ_AVM_VERSION_04_33 if FREETZ_TYPE_LANG_DE + select FREETZ_AVM_VERSION_04_49 if ! FREETZ_TYPE_LANG_DE + bool "Fon WLAN" + + config FREETZ_TYPE_FON_WLAN_7050 + select FREETZ_AVM_VERSION_04_33 + bool "Fon WLAN 7050" + + config FREETZ_TYPE_FON_WLAN_7112 + select FREETZ_AVM_VERSION_04_87 + bool "Fon WLAN 7112" + + config FREETZ_TYPE_FON_WLAN_7113 + select FREETZ_AVM_VERSION_04_80 if FREETZ_TYPE_LANG_EN + select FREETZ_AVM_VERSION_04_67 if FREETZ_TYPE_LANG_DE + bool "Fon WLAN 7113" + + config FREETZ_TYPE_FON_WLAN_7140 + select FREETZ_AVM_VERSION_04_33 if FREETZ_TYPE_LANG_DE + select FREETZ_AVM_VERSION_04_76 if FREETZ_TYPE_LANG_A_CH + select FREETZ_AVM_VERSION_04_67 if FREETZ_TYPE_LANG_EN + bool "Fon WLAN 7140" + + config FREETZ_TYPE_FON_WLAN_7141 + select FREETZ_AVM_VERSION_04_76 + bool "Fon WLAN 7141" + + config FREETZ_TYPE_FON_7150 + select FREETZ_AVM_VERSION_04_70 + bool "Fon 7150" + + config FREETZ_TYPE_FON_WLAN_7170 + select FREETZ_AVM_VERSION_04_76 if FREETZ_TYPE_LANG_A_CH + select FREETZ_AVM_VERSION_04_80 if FREETZ_TYPE_LANG_EN + select FREETZ_AVM_VERSION_04_87 if FREETZ_TYPE_LANG_DE + bool "Fon WLAN 7170" + + config FREETZ_TYPE_FON_WLAN_7240 + select FREETZ_AVM_VERSION_7270_05_05 + bool "Fon WLAN 7240" + + config FREETZ_TYPE_FON_WLAN_7270_V1 + select FREETZ_TYPE_FON_WLAN_7270 + bool "Fon WLAN 7270 v1" + + config FREETZ_TYPE_FON_WLAN_7270_V2 + select FREETZ_TYPE_FON_WLAN_7270 + bool "Fon WLAN 7270 v2" + + config FREETZ_TYPE_FON_WLAN_7270_V3 + select FREETZ_TYPE_FON_WLAN_7270 + bool "Fon WLAN 7270 v3" + + config FREETZ_TYPE_FON_WLAN_7320 + select FREETZ_AVM_VERSION_7320_04_86 + bool "Fon WLAN 7320" + + config FREETZ_TYPE_FON_WLAN_7330 + select FREETZ_AVM_VERSION_7320_04_86 + bool "Fon WLAN 7330" + + config FREETZ_TYPE_FON_WLAN_7340 + select FREETZ_AVM_VERSION_7390_05_05 + bool "Fon WLAN 7340" + + config FREETZ_TYPE_FON_WLAN_7390 + select FREETZ_AVM_VERSION_7390_05_05 + bool "Fon WLAN 7390" + + config FREETZ_TYPE_FON_WLAN_7570 + select FREETZ_AVM_VERSION_7270_04_86 + bool "Fon WLAN 7570 VDSL" + + config FREETZ_TYPE_FON_WLAN_7570_IAD + bool "build firmware for Alice IAD 7570" + depends on FREETZ_TYPE_FON_WLAN_7570 + comment "Hint: Use replace kernel to get max filesystem size" + depends on FREETZ_TYPE_FON_WLAN_7570_IAD + + config FREETZ_TYPE_WLAN_3020 + select FREETZ_AVM_VERSION_04_33 + bool "WLAN 3020" + + config FREETZ_TYPE_WLAN_3030 + select FREETZ_AVM_VERSION_04_33 + bool "WLAN 3030" + + config FREETZ_TYPE_WLAN_3130 + select FREETZ_AVM_VERSION_04_33 + bool "WLAN 3130" + + config FREETZ_TYPE_WLAN_3131 + select FREETZ_AVM_VERSION_04_57 + bool "WLAN 3131" + + config FREETZ_TYPE_WLAN_3170 + select FREETZ_AVM_VERSION_04_57 + bool "WLAN 3170" + + config FREETZ_TYPE_WLAN_3270 + select FREETZ_AVM_VERSION_7270_05_05 + bool "WLAN 3270 (v1 and v2 only)" + + config FREETZ_TYPE_WLAN_3270_V3 + select FREETZ_AVM_VERSION_7270_05_05 + bool "WLAN 3270 (v3 only)" + + config FREETZ_TYPE_SPEEDPORT_W501V + select FREETZ_AVM_VERSION_r7203 + bool "Speedport W501V" + + config FREETZ_TYPE_CUSTOM + bool "Custom" + depends on FREETZ_SHOW_ADVANCED + select FREETZ_DL_OVERRIDE + +endchoice # "Hardware type" # + +config FREETZ_TYPE_FON_WLAN_7270 + depends on \ + FREETZ_TYPE_FON_WLAN_7270_V1 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 + select FREETZ_AVM_VERSION_7270_04_86 if \ + FREETZ_TYPE_FON_WLAN_7270_V1 + select FREETZ_AVM_VERSION_7270_05_05 if \ + (FREETZ_TYPE_FON_WLAN_7270_V2 || FREETZ_TYPE_FON_WLAN_7270_V3) + bool + +choice + prompt "Firmware language" + default FREETZ_TYPE_LANG_DE + + config FREETZ_TYPE_LANG_DE + bool "de - deutsch" + depends on \ + ! FREETZ_TYPE_FON_5010 && \ + ! FREETZ_TYPE_FON_5124 && \ + ! FREETZ_TYPE_FON_WLAN_7340 && \ + ! FREETZ_TYPE_FON_WLAN_7570 + + config FREETZ_TYPE_LANG_A_CH + bool "a-ch - deutsch" + depends on \ + FREETZ_TYPE_FON_5010 || \ + FREETZ_TYPE_FON_WLAN_7140 || \ + FREETZ_TYPE_FON_WLAN_7170 \ + + config FREETZ_TYPE_LANG_EN + bool "en - international" + depends on \ + FREETZ_TYPE_FON || \ + FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON_5124 || \ + FREETZ_TYPE_FON_WLAN || \ + FREETZ_TYPE_FON_WLAN_7113 || \ + FREETZ_TYPE_FON_WLAN_7140 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 \ + +endchoice # "Firmware language" # + +config FREETZ_TYPE_LANGUAGE + string + default "de" if FREETZ_TYPE_LANG_DE + default "a-ch" if FREETZ_TYPE_LANG_A_CH + default "en" if FREETZ_TYPE_LANG_EN + +config FREETZ_TYPE_LABOR + bool "Beta/Labor" + depends on \ + FREETZ_TYPE_LANG_DE && \ + ( \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 \ + ) + default n + help + Enable this to compile the mod based on an AVM "beta/labor" firmware. + +choice + prompt "Labor version" + depends on FREETZ_TYPE_LABOR + default FREETZ_TYPE_LABOR_PREVIEW + +# config FREETZ_TYPE_LABOR_DSL +# bool "DSL" +# help +# FRITZ!Lab DSL: This release optimizes the DSL (Digital Subscriber +# Line) software and adds related graphs. + + config FREETZ_TYPE_LABOR_PREVIEW + bool "Preview" + depends on \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 + help + Labor Preview + +endchoice # "Labor version" # + +config FREETZ_TYPE_ALIEN_HARDWARE + bool "Compile image for \"alien\" hardware" + depends on \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7570 + default n + help + Enable this to compile the mod image for another hardware type + +choice + prompt "Alien hardware type" + depends on FREETZ_TYPE_ALIEN_HARDWARE +# default FREETZ_TYPE_SINUS_W500V_7150 if FREETZ_TYPE_FON_7150 + default FREETZ_TYPE_SPEEDPORT_W701V_7170 if FREETZ_TYPE_FON_WLAN_7170 + default FREETZ_TYPE_7240_7270 if FREETZ_TYPE_FON_WLAN_7270_V2 + default FREETZ_TYPE_72702_72701 if FREETZ_TYPE_FON_WLAN_7270_V1 + +# config FREETZ_TYPE_SINUS_W500V_7150 +# bool "Sinus W500V" +# depends on FREETZ_TYPE_FON_7150 +# select FREETZ_MODULE_jffs2 +# help +# Enable this to compile a mod image for T-Com Sinus W500V based +# on a 7150 image. + + config FREETZ_TYPE_SPEEDPORT_W701V_7170 + bool "W701V" + depends on FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE + select FREETZ_REMOVE_FTPD + select FREETZ_REMOVE_MEDIASRV + select FREETZ_REMOVE_PRINTSERV + select FREETZ_REMOVE_PRINTSERV_MODULE if ! FREETZ_MODULE_usblp + select FREETZ_REMOVE_SMBD + help + Enable this to compile a mod image for T-Com Speedport W701V based + on a 7170 image. + + config FREETZ_TYPE_SPEEDPORT_W900V_7170 + bool "W900V" + depends on FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE + help + Enable this to compile a mod image for T-Com Speedport W900V based + on a 7170 image. + + config FREETZ_TYPE_SPEEDPORT_W920V_7570 + bool "W920V" + depends on FREETZ_TYPE_FON_WLAN_7570 + help + Enable this to compile a mod image for T-Com Speedport W920V based + on a 7570 image. + + config FREETZ_TYPE_3170_7170 + bool "3170" + depends on FREETZ_TYPE_FON_WLAN_7170 + select FREETZ_REMOVE_VOIPD + select FREETZ_REMOVE_VOIP_ISDN + select FREETZ_REMOVE_CAPIOVERTCP + help + Enable this to compile a mod image for FritzBox FON WLAN 3170 based + on a 7170 image. + + config FREETZ_TYPE_7112_7170 + bool "7112" + depends on FREETZ_TYPE_FON_WLAN_7170 + select FREETZ_REMOVE_FTPD + select FREETZ_REMOVE_MEDIASRV + select FREETZ_REMOVE_PRINTSERV + select FREETZ_REMOVE_PRINTSERV_MODULE if ! FREETZ_MODULE_usblp + select FREETZ_REMOVE_SMBD + help + Enable this to compile a mod image for FritzBox Fon WLAN 7112 based + on a 7170 image. + + config FREETZ_TYPE_7113_7170 + bool "7113" + depends on FREETZ_TYPE_FON_WLAN_7170 + select FREETZ_REMOVE_FTPD + select FREETZ_REMOVE_MEDIASRV + select FREETZ_REMOVE_PRINTSERV + select FREETZ_REMOVE_PRINTSERV_MODULE if ! FREETZ_MODULE_usblp + select FREETZ_REMOVE_SMBD + help + Enable this to compile a mod image for FritzBox Fon WLAN 7113 based + on a 7170 image. + + config FREETZ_TYPE_7140_7170 + bool "7140" + depends on FREETZ_TYPE_FON_WLAN_7170 + help + Enable this to compile a mod image for FritzBox FON WLAN 7140 based + on a 7170 image. + + config FREETZ_TYPE_7141_7170 + bool "7141" + depends on FREETZ_TYPE_FON_WLAN_7170 + help + Enable this to compile a mod image for FritzBox FON WLAN 7141 based + on a 7170 image. + + config FREETZ_TYPE_7240_7270 + bool "7240" + depends on FREETZ_TYPE_FON_WLAN_7270_V2 || FREETZ_TYPE_FON_WLAN_7270_V3 + help + Enable this to compile a mod image for FritzBox FON WLAN 7240 based + on a 7270 image. + + config FREETZ_TYPE_7270_7270 + bool "7270 v1" + depends on FREETZ_TYPE_FON_WLAN_7270_V2 && FREETZ_REPLACE_KERNEL_AVAILABLE + select FREETZ_REPLACE_KERNEL +# select FREETZ_REMOVE_AVM_VPN +# select FREETZ_REMOVE_CAPIOVERTCP +# select FREETZ_REMOVE_NTFS +# select FREETZ_REMOVE_SMBD +# select FREETZ_REMOVE_UMTSD +# select FREETZ_REMOVE_VOIPD +# select FREETZ_REMOVE_VOIP_ISDN +# select FREETZ_REMOVE_WEBDAV + help + Enable this to compile a mod image for FritzBox FON WLAN 7270 v1 based + on a 7270 v2 image. + + Caution: To fit into 8MB ROM some AVM components (e.g. telephony) have + to be removed. Please use usbroot for a full featured image. + + config FREETZ_TYPE_72702_72701 + bool "7270 v2" + depends on FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_REPLACE_KERNEL_AVAILABLE + help + Enable this to compile a mod image for FritzBox FON WLAN 7270 v2 based + on a 7270 v1 image. + + config FREETZ_TYPE_IAD_3331_7170 + bool "Alice IAD 3331" + depends on FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE + select FREETZ_REMOVE_PIGLET_V1 if FREETZ_SHOW_ADVANCED + select FREETZ_ENFORCE_URLADER_SETTINGS + help + Enable this to compile a mod image for Alice IAD 3331 based + on a 7170 image. + The firmware_version has to be enforced, because this variable is unset + in the 7170_HN bootloader. + Initial flashing might only be possible via ./tools/push_firmware + +endchoice # "Alien hardware type" # + +config FREETZ_AVM_VERSION_STRING + string + default "04.30" if FREETZ_AVM_VERSION_04_30 + default "04.33" if FREETZ_AVM_VERSION_04_33 + default "04.40" if FREETZ_AVM_VERSION_04_40 + default "04.49" if FREETZ_AVM_VERSION_04_49 + default "04.57" if FREETZ_AVM_VERSION_04_57 + default "04.67" if FREETZ_AVM_VERSION_04_67 + default "04.70" if FREETZ_AVM_VERSION_04_70 + default "04.76" if FREETZ_AVM_VERSION_04_76 + default "04.80" if FREETZ_AVM_VERSION_04_80 + default "04.87" if FREETZ_AVM_VERSION_04_87 + default "7270_04.86" if FREETZ_AVM_VERSION_7270_04_86 + default "7270_05.05" if FREETZ_AVM_VERSION_7270_05_05 + default "7320_04.86" if FREETZ_AVM_VERSION_7320_04_86 + default "7390_04.90" if FREETZ_AVM_VERSION_7390_04_90 + default "7390_05.05" if FREETZ_AVM_VERSION_7390_05_05 + default "r7203" if FREETZ_AVM_VERSION_r7203 + + +choice + prompt "Annex" + depends on FREETZ_TYPE_LANG_EN && \ + ! FREETZ_TYPE_FON_WLAN_7113 && \ + ! FREETZ_TYPE_FON_WLAN_7270 && \ + ! FREETZ_TYPE_FON_WLAN_7340 && \ + ! FREETZ_TYPE_FON_WLAN_7390 && \ + ! FREETZ_TYPE_FON_WLAN_7570 + default FREETZ_TYPE_ANNEX_B + + config FREETZ_TYPE_ANNEX_A + bool "A" + + config FREETZ_TYPE_ANNEX_B + bool "B" + +endchoice # prompt "Annex" # + +config FREETZ_TYPE_PREFIX + string + default "300ip_as_fon" if FREETZ_TYPE_300IP_AS_FON + default "2170" if FREETZ_TYPE_2170 + default "3020" if FREETZ_TYPE_WLAN_3020 + default "3030" if FREETZ_TYPE_WLAN_3030 + default "3130" if FREETZ_TYPE_WLAN_3130 + default "3131" if FREETZ_TYPE_WLAN_3131 + default "3170" if FREETZ_TYPE_WLAN_3170 + default "3270" if FREETZ_TYPE_WLAN_3270 + default "3270_v3" if FREETZ_TYPE_WLAN_3270_V3 + default "fon" if FREETZ_TYPE_FON + default "5010" if FREETZ_TYPE_FON_5010 + default "5050" if FREETZ_TYPE_FON_5050 + default "5124" if FREETZ_TYPE_FON_5124 + default "5140" if FREETZ_TYPE_FON_5140 + default "fon_wlan" if FREETZ_TYPE_FON_WLAN + default "7050" if FREETZ_TYPE_FON_WLAN_7050 + default "7112" if FREETZ_TYPE_FON_WLAN_7112 + default "7113" if FREETZ_TYPE_FON_WLAN_7113 + default "7140" if FREETZ_TYPE_FON_WLAN_7140 + default "7141" if FREETZ_TYPE_FON_WLAN_7141 + default "7150" if FREETZ_TYPE_FON_7150 + default "7170" if FREETZ_TYPE_FON_WLAN_7170 + default "7240" if FREETZ_TYPE_FON_WLAN_7240 && ! FREETZ_TYPE_LABOR +# default "7240_preview" if FREETZ_TYPE_FON_WLAN_7240 && FREETZ_TYPE_LABOR_PREVIEW + default "7270_v1" if FREETZ_TYPE_FON_WLAN_7270_V1 && ! FREETZ_TYPE_LABOR +# default "7270_v1_preview" if FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_TYPE_LABOR_PREVIEW + default "7270_v2" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7270_7270 ) && \ + ! FREETZ_TYPE_LABOR + default "7270_v2_preview" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7270_7270 ) && \ + FREETZ_TYPE_LABOR_PREVIEW + default "7270_v3" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7240_7270 ) && \ + ! FREETZ_TYPE_LABOR + default "7270_v3_preview" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7240_7270 ) && \ + FREETZ_TYPE_LABOR_PREVIEW + default "7320" if FREETZ_TYPE_FON_WLAN_7320 && ! FREETZ_TYPE_LABOR + default "7330" if FREETZ_TYPE_FON_WLAN_7330 + default "7340" if FREETZ_TYPE_FON_WLAN_7340 + default "7390" if FREETZ_TYPE_FON_WLAN_7390 && ! FREETZ_TYPE_LABOR + default "7390_preview" if FREETZ_TYPE_FON_WLAN_7390 && FREETZ_TYPE_LABOR_PREVIEW + default "7570" if FREETZ_TYPE_FON_WLAN_7570 + default "W501V" if FREETZ_TYPE_SPEEDPORT_W501V + default "custom" if FREETZ_TYPE_CUSTOM + +config FREETZ_TYPE_PREFIX_ALIEN_HARDWARE + string + default "W500V_" if FREETZ_TYPE_SINUS_W500V_7150 + default "W701V_" if FREETZ_TYPE_SPEEDPORT_W701V_7170 + default "W900V_" if FREETZ_TYPE_SPEEDPORT_W900V_7170 + default "W920V_" if FREETZ_TYPE_SPEEDPORT_W920V_7570 + default "3170_" if FREETZ_TYPE_3170_7170 + default "7112_" if FREETZ_TYPE_7112_7170 + default "7113_" if FREETZ_TYPE_7113_7170 + default "7140_" if FREETZ_TYPE_7140_7170 + default "7141_" if FREETZ_TYPE_7141_7170 + default "7240_" if FREETZ_TYPE_7240_7270 + +comment "Custom options -------------------------" + depends on FREETZ_TYPE_CUSTOM + +config FREETZ_INSTALL_BASE + bool + select FREETZ_PACKAGE_MOD + select FREETZ_PACKAGE_HASERL + select FREETZ_LIB_ld_uClibc + select FREETZ_LIB_libcrypt + select FREETZ_LIB_libdl + select FREETZ_LIB_libgcc_s + select FREETZ_LIB_libm + select FREETZ_LIB_libnsl + select FREETZ_LIB_libpthread + select FREETZ_LIB_librt + select FREETZ_LIB_libuClibc + select FREETZ_LIB_libfreetz if FREETZ_HAS_USB_HOST + default y + help + This is mandatory + +config FREETZ_REPLACE_BUSYBOX + bool + select FREETZ_BUSYBOX_REALPATH + default y + help + This is mandatory + +config FREETZ_SHOW_ADVANCED + bool "Show advanced options" + default n + help + Show advanced Options for patching the firmware. This is only useful + for experienced users who really know what they are doing + +if FREETZ_SHOW_ADVANCED + +comment "Replace kernel (currently not available)" + depends on ! FREETZ_REPLACE_KERNEL_AVAILABLE + +config FREETZ_REPLACE_KERNEL_AVAILABLE + bool + depends on \ + ! (FREETZ_TYPE_FON && FREETZ_TYPE_LANG_EN) && \ + ! FREETZ_TYPE_LABOR + default y + +config FREETZ_REPLACE_KERNEL + bool "Replace kernel" + depends on FREETZ_REPLACE_KERNEL_AVAILABLE + select FREETZ_MODULE_fuse if ( \ + FREETZ_AVM_VERSION_7270_04_86 || \ + FREETZ_AVM_VERSION_7270_05_05 || \ + FREETZ_AVM_VERSION_7320_04_86 || \ + FREETZ_AVM_VERSION_7390_04_90 || \ + FREETZ_AVM_VERSION_7390_05_05 \ + ) + select FREETZ_MODULE_jffs2 if FREETZ_AVM_VERSION_7320_04_86 + select FREETZ_MODULE_msdos if FREETZ_AVM_VERSION_7270_05_05 + select FREETZ_MODULE_usbcore if \ + FREETZ_KERNEL_LAYOUT_UR8 && FREETZ_AVM_VERSION_7270_04_86 + select FREETZ_MODULE_vfat if FREETZ_AVM_VERSION_7270_05_05 + default n + help + Replace AVM kernel with self-built kernel. + +endif # FREETZ_SHOW_ADVANCED # + +comment "Hint: Select build toolchain if you want to enable IPv6 support" + depends on \ + ( \ + FREETZ_HAS_AVM_IPV6 || \ + (FREETZ_SHOW_ADVANCED && FREETZ_REPLACE_KERNEL_AVAILABLE) \ + ) && \ + (FREETZ_TARGET_UCLIBC_VERSION_0_9_28 && FREETZ_DOWNLOAD_TOOLCHAIN) + +config FREETZ_TARGET_IPV6_SUPPORT + bool "Enable IPv6 support" + depends on \ + ( \ + FREETZ_HAS_AVM_IPV6 || \ + (FREETZ_SHOW_ADVANCED && FREETZ_REPLACE_KERNEL_AVAILABLE) \ + ) && \ + ! (FREETZ_TARGET_UCLIBC_VERSION_0_9_28 && FREETZ_DOWNLOAD_TOOLCHAIN) + select FREETZ_REPLACE_KERNEL if ! (FREETZ_HAS_AVM_IPV6) + select FREETZ_MODULE_ipv6 if ! (FREETZ_HAS_AVM_IPV6) && FREETZ_REPLACE_KERNEL + select FREETZ_BUSYBOX_IP + select FREETZ_BUSYBOX_FEATURE_IP_ADDRESS + select FREETZ_BUSYBOX_FEATURE_IP_LINK + select FREETZ_BUSYBOX_FEATURE_IP_ROUTE + select FREETZ_BUSYBOX_FEATURE_IP_TUNNEL + default n + help + Copies the ipv6 kernel module to the firmware and enables ipv6 support + in uClibc and busybox. + Shows additional options for busybox and iptables and other packages. + To use IPv6 with Fritz!Box, at least the kernel, ucLibc and busybox + have to be recompiled with IPv6 enabled. + The toolchain will automatically be rebuild to achieve this. + It is also recommended to include the package iptables/ip6tables for + firewall settings. + +config FREETZ_TARGET_REF_4MB + bool + default y if \ + FREETZ_TYPE_2170 || \ + FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON || \ + FREETZ_TYPE_FON_5010 || \ + FREETZ_TYPE_FON_5050 || \ + FREETZ_TYPE_FON_5140 || \ + FREETZ_TYPE_FON_WLAN || \ + FREETZ_TYPE_FON_WLAN_7050 || \ + FREETZ_TYPE_SPEEDPORT_W501V || \ + FREETZ_TYPE_WLAN_3020 || \ + FREETZ_TYPE_WLAN_3030 || \ + FREETZ_TYPE_WLAN_3130 || \ + FREETZ_TYPE_WLAN_3131 || \ + FREETZ_TYPE_WLAN_3170 + +config FREETZ_TARGET_REF_8MB + bool + default y if \ + FREETZ_TYPE_FON_5124 || \ + FREETZ_TYPE_FON_WLAN_7112 || \ + FREETZ_TYPE_FON_WLAN_7113 || \ + FREETZ_TYPE_FON_WLAN_7141 || \ + FREETZ_TYPE_FON_WLAN_7140 || \ + FREETZ_TYPE_FON_7150 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + ( FREETZ_TYPE_FON_WLAN_7270_V1 && ! FREETZ_TYPE_72702_72701 ) + +config FREETZ_TARGET_REF_16MB + bool + default y if \ + FREETZ_TYPE_FON_WLAN_7240 || \ + ( FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_TYPE_72702_72701 ) || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + +config FREETZ_TARGET_REF + string "Target ref" if FREETZ_TYPE_CUSTOM + default "4mb" if FREETZ_TARGET_REF_4MB + default "8mb" if FREETZ_TARGET_REF_8MB + default "16mb" if FREETZ_TARGET_REF_16MB + +config FREETZ_KERNEL_REF_4MB + bool + default y if \ + FREETZ_TYPE_2170 || \ + FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON || \ + FREETZ_TYPE_FON_5010 || \ + FREETZ_TYPE_FON_5050 || \ + FREETZ_TYPE_FON_5140 || \ + FREETZ_TYPE_FON_WLAN || \ + FREETZ_TYPE_FON_WLAN_7050 || \ + FREETZ_TYPE_SPEEDPORT_W501V || \ + FREETZ_TYPE_WLAN_3020 || \ + FREETZ_TYPE_WLAN_3030 || \ + FREETZ_TYPE_WLAN_3130 || \ + FREETZ_TYPE_WLAN_3131 || \ + FREETZ_TYPE_WLAN_3170 + +config FREETZ_KERNEL_REF_8MB + bool + default y if \ + FREETZ_TYPE_FON_5124 || \ + FREETZ_TYPE_FON_WLAN_7112 || \ + FREETZ_TYPE_FON_WLAN_7113 || \ + FREETZ_TYPE_FON_WLAN_7141 || \ + FREETZ_TYPE_FON_WLAN_7140 || \ + FREETZ_TYPE_FON_7150 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + (FREETZ_TYPE_FON_WLAN_7270_V1 && ! FREETZ_TYPE_72702_72701) + +config FREETZ_KERNEL_REF_16MB + bool + default y if \ + FREETZ_TYPE_FON_WLAN_7240 || \ + (FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_TYPE_72702_72701) || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + +config FREETZ_KERNEL_REF + string "Kernel ref" if FREETZ_TYPE_CUSTOM + default "4mb" if FREETZ_KERNEL_REF_4MB + default "8mb" if FREETZ_KERNEL_REF_8MB + default "16mb" if FREETZ_KERNEL_REF_16MB + +config FREETZ_KERNEL_MTD_SIZE + int "Kernel (64K blocks)" if FREETZ_TYPE_CUSTOM + default 119 if \ + FREETZ_TYPE_FON_5124 || \ + FREETZ_TYPE_FON_7150 || \ + FREETZ_TYPE_FON_WLAN_7112 || \ + FREETZ_TYPE_FON_WLAN_7113 || \ + FREETZ_TYPE_FON_WLAN_7140 || \ + FREETZ_TYPE_FON_WLAN_7141 || \ + (FREETZ_TYPE_FON_WLAN_7170 && ! FREETZ_TYPE_3170_7170) || \ + (FREETZ_TYPE_FON_WLAN_7270_V1 && ! FREETZ_TYPE_72702_72701) || \ + FREETZ_TYPE_7270_7270 + default 122 if \ + FREETZ_TYPE_FON_WLAN_7570_IAD && ! FREETZ_REPLACE_KERNEL + default 238 if \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 + default 244 if \ + FREETZ_TYPE_FON_WLAN_7570_IAD && FREETZ_REPLACE_KERNEL + default 246 if \ + FREETZ_TYPE_FON_WLAN_7240 || \ + (FREETZ_TYPE_FON_WLAN_7270_V1 && FREETZ_TYPE_72702_72701) || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + (FREETZ_TYPE_FON_WLAN_7570 && ! FREETZ_TYPE_FON_WLAN_7570_IAD) || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default 59 + help + Number of 64K blocks in the kernel mtd device. + +config FREETZ_HAS_AVM_AURA_USB + bool "Has remote USB connection (AURA = AVM USB Remote-Architcture)" if FREETZ_TYPE_CUSTOM + select FREETZ_REMOVE_AURA_USB if ! FREETZ_HAS_USB_HOST + default y if \ + FREETZ_HAS_USB_HOST || \ + FREETZ_TYPE_SPEEDPORT_W701V_7170 || \ + FREETZ_TYPE_7112_7170 || \ + FREETZ_TYPE_7113_7170 + default n + help + Select this if your original firmware has an aura-usb-daemon (remote USB + connection, USB-Fernanschluss) + +config FREETZ_HAS_AVM_MINID + bool "Has mini-daemon (minid)" if FREETZ_TYPE_CUSTOM + select FREETZ_REMOVE_MINID if \ + FREETZ_TYPE_7113_7170 || \ + FREETZ_TYPE_7112_7170 || \ + FREETZ_TYPE_3170_7170 || \ + FREETZ_TYPE_SPEEDPORT_W701V_7170 + default y if \ + FREETZ_TYPE_FON_WLAN_7141 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default n + help + Select this if your original firmware has a mini-daemon (minid) + +config FREETZ_HAS_AVM_NTFS + bool "Has AVM NTFS" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default n + help + Select this if your original firmware has ntfs support. + +config FREETZ_HAS_AVM_IPV6 + bool "Has AVM IPv6" if FREETZ_TYPE_CUSTOM + select FREETZ_TARGET_IPV6_SUPPORT + default y if \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default n + help + Select this if your original firmware has IPv6 support. + +config FREETZ_HAS_AVM_WEBDAV + bool "Has AVM WebDAV" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default n + help + Select this if your original firmware has WebDAV support. + +config FREETZ_HAS_AVM_INETD + bool "Has AVM inetd" if FREETZ_TYPE_CUSTOM + select FREETZ_PACKAGE_INETD + default y if \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 + default n + help + Select this if your original firmware has inetd support. + +config FREETZ_HAS_AVM_EXT3 + bool "Has AVM ext3 built into the kernel" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7390 + default n + help + Select this if your original firmware has ext3 support into the kernel. + +config FREETZ_HAS_AVM_TR069 + bool "Has AVM tr069" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON || \ + FREETZ_TYPE_FON_5124 || \ + FREETZ_TYPE_FON_WLAN || \ + FREETZ_TYPE_FON_WLAN_7050 || \ + FREETZ_TYPE_FON_WLAN_7113 || \ + FREETZ_TYPE_FON_WLAN_7140 || \ + FREETZ_TYPE_FON_WLAN_7141 || \ + FREETZ_TYPE_FON_7150 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 || \ + FREETZ_TYPE_WLAN_3020 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default n + help + Select this if your original firmware has tr069 support (libtr069, libtr064). + +config FREETZ_HAS_CHRONYD + bool "Has chronyd" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 + default n + help + Select this if you have a box with chronyd. + +config FREETZ_HAS_DECT + bool "Has DECT" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_FON_7150 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 || \ + FREETZ_TYPE_SPEEDPORT_W900V_7170 + default n + help + Select this if you have a box with DECT. + +config FREETZ_HAS_OPENSSL_LIBS + bool "Has libssl" if FREETZ_TYPE_CUSTOM + default n if \ + FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON_5010 || \ + FREETZ_TYPE_FON_5050 || \ + FREETZ_TYPE_FON_WLAN || \ + FREETZ_TYPE_FON_WLAN_7050 || \ + FREETZ_TYPE_FON_WLAN_7140 || \ + FREETZ_TYPE_SPEEDPORT_W501V || \ + FREETZ_TYPE_WLAN_3020 || \ + FREETZ_TYPE_WLAN_3030 + default y + help + Select this if you have a box with AVM libcrypto and libssl. + +config FREETZ_HAS_LSOF + bool "Has lsof" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default n + help + Select this if you have a box with lsof binary. + +config FREETZ_HAS_NAS + bool "Has NAS" if FREETZ_TYPE_CUSTOM + select FREETZ_BUSYBOX_TAR_OLDGNU_COMPATIBILITY + default y if \ + ( \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 \ + ) + default n + help + Select this if you have a box with NAS support. + +config FREETZ_HAS_PHONE + bool "Has Phone" if FREETZ_TYPE_CUSTOM + default n if \ + FREETZ_TYPE_2170 || \ + FREETZ_TYPE_WLAN_3020 || \ + FREETZ_TYPE_WLAN_3030 || \ + FREETZ_TYPE_WLAN_3130 || \ + FREETZ_TYPE_WLAN_3131 || \ + FREETZ_TYPE_WLAN_3170 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default y + help + Select this if you have a box with phone support. + +config FREETZ_HAS_STRACE + bool "Has strace" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default n + help + Select this if you have a box with strace binary. + +config FREETZ_HAS_TAM + bool "Has TAM" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_FON_7150 || \ + FREETZ_TYPE_FON_WLAN_7141 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 + default n + help + Select this if you have a box with TAM (Telephone Answering Machine) support. + +config FREETZ_HAS_UDEV + bool "udev" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default n + help + Select this if you have a box with udev. + +config FREETZ_HAS_USB_CLIENT + bool "USB client" if FREETZ_TYPE_CUSTOM + default y if \ + FREETZ_TYPE_2170 || \ + FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON || \ + FREETZ_TYPE_FON_5050 || \ + FREETZ_TYPE_FON_WLAN || \ + FREETZ_TYPE_FON_WLAN_7050 || \ + FREETZ_TYPE_WLAN_3020 || \ + FREETZ_TYPE_WLAN_3030 || \ + FREETZ_TYPE_WLAN_3131 || \ + FREETZ_TYPE_WLAN_3170 + default n + help + Select this if you have a box with USB. + +config FREETZ_HAS_USB_HOST + bool "USB host" if FREETZ_TYPE_CUSTOM + default n if \ + FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON || \ + FREETZ_TYPE_FON_5010 || \ + FREETZ_TYPE_FON_5050 || \ + FREETZ_TYPE_FON_5140 || \ + FREETZ_TYPE_FON_WLAN || \ + FREETZ_TYPE_FON_WLAN_7050 || \ + FREETZ_TYPE_FON_WLAN_7112 || \ + FREETZ_TYPE_7112_7170 || \ + FREETZ_TYPE_FON_WLAN_7113 || \ + FREETZ_TYPE_7113_7170 || \ + FREETZ_TYPE_WLAN_3020 || \ + FREETZ_TYPE_WLAN_3030 || \ + FREETZ_TYPE_SINUS_W500V_7150 || \ + FREETZ_TYPE_SPEEDPORT_W501V || \ + FREETZ_TYPE_SPEEDPORT_W701V_7170 + default y + help + Select this if your USB port is a host adapter. + +config FREETZ_HAS_USB_HOST_AVM + bool "AVM USB host" if FREETZ_TYPE_CUSTOM + depends on FREETZ_HAS_USB_HOST + default y if \ + FREETZ_TYPE_2170 || \ + FREETZ_TYPE_FON_5124 || \ + FREETZ_TYPE_FON_7150 || \ + FREETZ_TYPE_FON_WLAN_7141 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_WLAN_3130 || \ + FREETZ_TYPE_WLAN_3131 || \ + FREETZ_TYPE_WLAN_3170 + default n + help + Select this if you have a box with AVM USB host. + +config FREETZ_HAS_AVM_E2FSPROGS + bool "Has AVM e2fsprogs files" if FREETZ_TYPE_CUSTOM + default y if\ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + default n + help + Select this if you have a firmware with blkid, fsck and mkfs. + +config FREETZ_HAS_WLAN + bool "Has WLAN" if FREETZ_TYPE_CUSTOM + default n if \ + FREETZ_TYPE_2170 || \ + FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON || \ + FREETZ_TYPE_FON_5010 || \ + FREETZ_TYPE_FON_5050 || \ + FREETZ_TYPE_FON_5124 || \ + FREETZ_TYPE_FON_5140 + default y + help + Select this if you have a box with WLAN. + +comment "Mod ------------------------------------" + +choice + prompt "Freetz Language" + default FREETZ_LANG_DE if FREETZ_TYPE_LANG_DE + default FREETZ_LANG_DE if FREETZ_TYPE_LANG_A_CH + default FREETZ_LANG_EN if FREETZ_TYPE_LANG_EN + + config FREETZ_LANG_DE + bool "de - deutsch" + + config FREETZ_LANG_EN + bool "en - english" + +endchoice # "Freetz Language" # + +config FREETZ_LANG_STRING + string + default "de" if FREETZ_LANG_DE + default "en" if FREETZ_LANG_EN + +menu "Patches" + +# INCLUDE_BEGIN patches/Config.in +comment "Web menu patches -----------------------" + +config FREETZ_PATCH_VCC + bool "Patch 2nd VCC" + depends on FREETZ_HAS_PHONE && FREETZ_TYPE_LANG_DE + default n + help + Patches the setting for 2nd VCC into web menu. It also adds two additional + settings (PCR & SCR) not available in the original AVM firmware. + + Please also note that it is not possible to change the value of traffic_class + setting via the web-interface. You have to do it some other way (e.g. using + FBEditor or nvi ar7.cfg). + + Warning: Please read up on what each VCC setting means before setting/changing it. + Besides not working wrong values may cause additional costs for you as your provider + may treat it as simultaneous dial-in attempts (Doppeleinwahl). + + The correct values for an 1&1-Komplettanschluss are: + VPI = 1; + VCI = 35; + traffic_class = atm_traffic_class_CBR; + pcr = 603; + scr = 0; + +config FREETZ_PATCH_ATA + bool "Patch ATA" + depends on \ + FREETZ_TYPE_SPEEDPORT_W501V + default n + help + Patches the ATA mode configuration pages into the web menu. + +config FREETZ_PATCH_ENUM + bool "Patch enum" + depends on \ + FREETZ_TYPE_LANG_DE && \ + ( \ + FREETZ_TYPE_FON || \ + FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON_5050 || \ + FREETZ_TYPE_FON_WLAN || \ + FREETZ_TYPE_FON_WLAN_7050 || \ + FREETZ_TYPE_FON_WLAN_7140 \ + ) + default n + help + Patches the enum configuration pages into the web menu. + +config FREETZ_PATCH_DSL_EXPERT + bool +# bool "Patch extended DSL settings" + depends on \ + ! FREETZ_TYPE_LABOR_DSL && \ + ! FREETZ_REMOVE_DSLD && \ + FREETZ_TYPE_LANG_DE && \ + ( \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 \ + ) + default n + help + Patches the extended dsl-settings from labor-dsl into all-in-one-firmwares. + +config FREETZ_ADD_REGEXT_GUI + bool "Patch GUI to enable external SIP connections" + depends on \ + FREETZ_TYPE_FON_WLAN_7570 || \ + ( \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7390 \ + ) && FREETZ_TYPE_LANG_DE + default n + help + Patches the WebUI and add a checkbox to enable setting "reg_from_outside" in the voip.conf. + +#config FREETZ_PATCH_INTERNATIONAL +# bool "Patch international" +# depends on FREETZ_HAS_PHONE && FREETZ_TYPE_LANG_DE +# default y +# help +# Reveals some options from the international firmware in the web menu. + +config FREETZ_PATCH_ALARMCLOCK + bool "Patch third alarm-clock" + depends on ( \ + FREETZ_TYPE_FON_WLAN_7150 || \ + FREETZ_TYPE_FON_WLAN_7112 || \ + FREETZ_TYPE_FON_WLAN_7141 || \ + (FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE) || \ + FREETZ_TYPE_FON_WLAN_7270_V1 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7570 \ + ) + default n + help + Adds a third alarm-clock to AVM-Webinterface + +config FREETZ_PATCH_SIGNED + bool "Patch web menu signed message" + default n + help + Hides the "unsupported changes" message from the web interface. + +if FREETZ_HAS_USB_HOST +comment "USB storage patches --------------------" + +config FREETZ_PATCH_FREETZMOUNT + bool "FREETZMOUNT: Patch AVMs hotplug scripts, USB storage names, ..." + select FREETZ_USBSTORAGE_AUTOMOUNT + select FREETZ_BUSYBOX_BLKID if FREETZ_REMOVE_AVM_E2FSPROGS || ! FREETZ_HAS_AVM_E2FSPROGS + select FREETZ_BUSYBOX_BLKID_TYPE if FREETZ_REMOVE_AVM_E2FSPROGS || ! FREETZ_HAS_AVM_E2FSPROGS + select FREETZ_BUSYBOX_VOLUMEID + default y + help + 1. Replaces and deselects usb-storage patch. + - The names of USB storage directories can be defined by WebIF (default uStorXY) (or by volume LABEL). + 2. Replaces and deselects autorun.sh/autoend.sh patch. + - autorun/autoend behaviour can be activated/deactivated via WebIF. + - autorun/autoend are useful to start/terminate applications located on USB devices, eg + apache, samba or even swapfiles, after connecting or before disconnecting of USB devices. + 3. Auto-mounted USB storage devices will be fully accessible, eg it is now possible to put + user home directories for (e.g. for FTP) on a FAT32-formatted partition and permit shell + and FTP users to actually write to their own home directories. + 4. Avoid deleting whole filesystems on USB devices. + 5. Enhanced behaviour during mounting and unmounting. + 6. Provides mount-by-label feature. + + It is highly recommended to select this patch. + +config FREETZ_USBSTORAGE_AUTOMOUNT + bool "Automount filesystems" + depends on FREETZ_PATCH_FREETZMOUNT + default y + help + The filesystems ext2, ext3, ext4, fat, hfs, hfs+, ntfs and reiserfs and swap are mounted + automatically. Detection is done by blkid utility . It depends on the original firmware + which of the following points you have to select. + +if FREETZ_USBSTORAGE_AUTOMOUNT +config FREETZ_AUTOMOUNT_EXT2 + bool "ext2" + select FREETZ_BUSYBOX_VOLUMEID_EXT + select FREETZ_MODULE_ext2 + default n + help + This adds ext2 module to your firmware. + +config FREETZ_AUTOMOUNT_EXT3 + bool "ext3" + select FREETZ_BUSYBOX_VOLUMEID_EXT + select FREETZ_MODULE_ext3 if ! FREETZ_HAS_AVM_EXT3 + default n + help + This adds ext3 module to your firmware. + +config FREETZ_AUTOMOUNT_EXT4 + bool "ext4" + depends on FREETZ_KERNEL_VERSION_2_6_28 || \ + FREETZ_KERNEL_VERSION_2_6_32 + select FREETZ_BUSYBOX_VOLUMEID_EXT + select FREETZ_MODULE_ext4 + default n + help + This adds ext4 module to your firmware. + +config FREETZ_AUTOMOUNT_FAT + bool "fat" + select FREETZ_BUSYBOX_VOLUMEID_FAT + default n + help + This enables detection of fat partitions. + +config FREETZ_AUTOMOUNT_HFS + bool "HFS" + select FREETZ_BUSYBOX_VOLUMEID_HFS + select FREETZ_MODULE_hfs + default n + help + This adds hfs module to your firmware. + +config FREETZ_AUTOMOUNT_HFS_PLUS + bool "HFS+" + select FREETZ_BUSYBOX_VOLUMEID_HFS + select FREETZ_MODULE_hfsplus + default n + help + This adds hfs+ module to your firmware. + +config FREETZ_AUTOMOUNT_LUKS + bool "luks" + select FREETZ_BUSYBOX_VOLUMEID_LUKS + default n + help + This enables detection (not mounting) of luks partitions. + +config FREETZ_AUTOMOUNT_NTFS + bool "NTFS" + select FREETZ_PACKAGE_NTFS if ! FREETZ_HAS_AVM_NTFS + select FREETZ_BUSYBOX_VOLUMEID_NTFS + default n + help + This adds ntfs-3g mount helper to your firmware. + +config FREETZ_AUTOMOUNT_REISER_FS + bool "ReiserFS" + select FREETZ_BUSYBOX_VOLUMEID_REISERFS + select FREETZ_MODULE_reiserfs + default n + help + This adds reiserfs module to your firmware. + +config FREETZ_AUTOMOUNT_LINUXSWAP + bool "swap" + select FREETZ_BUSYBOX_VOLUMEID_LINUXSWAP + default n + help + This enables detection of linux-swap partitions. + +endif + +config FREETZ_PATCH_MAXDEVCOUNT + bool "Raise the count of connectable usb device to 9" + default n + help + Use this patch if you would connect more than 3 device to the box + +config FREETZ_PATCH_MULTIPLE_PRINTERS + bool "Add support for multiple printers" + depends on ! FREETZ_REMOVE_PRINTSERV && \ + ( \ + ( FREETZ_TYPE_FON_WLAN_7140 && ! FREETZ_TYPE_LANG_DE ) || \ + FREETZ_TYPE_FON_WLAN_7570 || \ + FREETZ_TYPE_FON_5124 || \ + FREETZ_TYPE_2170 || \ + FREETZ_TYPE_WLAN_3131 || \ + FREETZ_TYPE_WLAN_3170 || \ + FREETZ_TYPE_FON_WLAN_7141 || \ + FREETZ_TYPE_FON_7150 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7270_V1 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 \ + ) + # no patch available atm: 7140_DE 2070 3070 3050 3130 + default n + help + Use this patch if you want to use more than one printer. + +endif + +comment "Removal patches ------------------------" + +config FREETZ_REMOVE_ANNEX_A_FIRMWARE + bool "Remove Annex A firmware file" + depends on \ + FREETZ_TYPE_FON_WLAN_7270_V2 || \ + FREETZ_TYPE_FON_WLAN_7270_V3 || \ + FREETZ_TYPE_FON_WLAN_7320 + default n + help + Remove lib/modules/dsp_ur8/ur8-A-dsl.bin. This saves about 400 KB of + uncompressed data size. + +config FREETZ_REMOVE_ANNEX_B_FIRMWARE + bool "Remove Annex B firmware file" + depends on \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 + default n + help + Remove lib/modules/dsp_ur8/ur8-B-dsl.bin. This saves about 400 KB of + uncompressed data size. + +menu "Remove v1/v2 piglet file(s)" + depends on FREETZ_SHOW_ADVANCED && \ + ( \ + (FREETZ_TYPE_FON_WLAN_7170 && ! FREETZ_TYPE_ALIEN_HARDWARE) || \ + FREETZ_TYPE_SPEEDPORT_W701V_7170 || \ + FREETZ_TYPE_SPEEDPORT_W900V_7170 || \ + FREETZ_TYPE_IAD_3331_7170 \ + ) + + config FREETZ_REMOVE_PIGLET_V1 + bool "Remove v1 piglet file(s)" + help + The firmware of this model contains double piglet files. Which instance is needed depends + on the hardware version (v1 or v2) of your box. You can safely remove the + unneeded instance. + + Hint: If "echo $HWRevision_BitFileCount" returns "1" you could select this patch. + + + config FREETZ_REMOVE_PIGLET_V2 + bool "Remove v2 piglet file(s)" + help + The firmware of this model contains double piglet files. Which instance is needed depends + on the hardware version (v1 or v2) of your box. You can safely remove the + unneeded instance. + + Hint: If "echo $HWRevision_BitFileCount" returns "" (nothing) you could select this patch. + +endmenu + +comment "WARNING: Both (v1 and v2) piglet files are selected for removal." + depends on \ + FREETZ_REMOVE_PIGLET_V1 && \ + FREETZ_REMOVE_PIGLET_V2 + +menu "Remove ISDN/POTS piglet file(s) (EXPERIMENTAL)" + depends on FREETZ_SHOW_ADVANCED && \ + ( \ + FREETZ_TYPE_FON_5113 || \ + FREETZ_TYPE_FON_WLAN_7113 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_5113_7170 || \ + FREETZ_TYPE_7113_7170 \ + ) + + config FREETZ_REMOVE_PIGLET_ISDN + bool "Remove ISDN piglet file(s) (EXPERIMENTAL)" + help + The firmware of this model contains separate piglet files for ISDN and POTS. Depending + on your type of fixed line usage you can safely remove the unneeded bitfile(s). + + Hint: If you are using POTS fixed line you could select this patch. + + + config FREETZ_REMOVE_PIGLET_POTS + bool "Remove POTS piglet file(s) (EXPERIMENTAL)" + help + The firmware of this model contains separate piglet files for ISDN and POTS. Depending + on your type of fixed line usage you can safely remove the unneeded bitfile(s). + + Hint: If you are using ISDN fixed line you could select this patch. + +endmenu + +comment "WARNING: Both (ISDN and POTS) piglet files are selected for removal." + depends on \ + FREETZ_REMOVE_PIGLET_ISDN && \ + FREETZ_REMOVE_PIGLET_POTS + +config FREETZ_REMOVE_ASSISTANT + bool "Remove assistant" + default n + depends on \ + ! ( \ + ( \ + FREETZ_TYPE_FON_5124 || \ + FREETZ_TYPE_FON_WLAN_7140 || \ + FREETZ_TYPE_FON_WLAN_7170 \ + ) \ + && FREETZ_TYPE_LANG_EN \ + ) + help + Removes the installation assistant from the web menu. + +config FREETZ_REMOVE_AURA_USB + bool "Remove remote USB connection (AURA = AVM USB Remote-Architcture)" if FREETZ_SHOW_ADVANCED + default n + depends on FREETZ_HAS_AVM_AURA_USB + help + Remove the aura-usb-daemon (remote USB connection, USB-Fernanschluss) and some + related files. + + This patch only removes the files, not the settings in AVM's web interface. + +config FREETZ_REMOVE_USB_MODULE + bool "Remove avalanche_usb.ko" if FREETZ_SHOW_ADVANCED + depends on FREETZ_HAS_USB_CLIENT + default n + help + Removes avalanche_usb.ko to save 60kB uncompressed space. + +config FREETZ_REMOVE_NAS + bool "Remove AVM NAS Webinterface" + default n + depends on FREETZ_HAS_NAS && FREETZ_TYPE_LANG_DE + help + Removes the AVM NAS Webinterface and internal memory file (saves about 390 KB in compressed image). + +config FREETZ_REMOVE_AVM_VPN + bool "Remove AVM vpn" if FREETZ_SHOW_ADVANCED + default n + depends on \ + FREETZ_TYPE_2170 || \ + FREETZ_TYPE_FON_7150 || \ + (FREETZ_TYPE_FON_WLAN_7170 && FREETZ_TYPE_LANG_DE) || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_FON_WLAN_7570 || \ + FREETZ_TYPE_WLAN_3170 || \ + FREETZ_TYPE_WLAN_3270 || \ + FREETZ_TYPE_WLAN_3270_V3 + + help + Remove AVM's vpn and some other related files + This patch removes the files and related Web UI entrys, but not the + vpn settings. This will save about 120kB compressed size. + +config FREETZ_REMOVE_WEBSRV + bool "Remove AVM web server (replaced by httpd)" + depends on \ + ! FREETZ_TYPE_2170 \ + && ! FREETZ_TYPE_FON_5124 \ + && ! FREETZ_TYPE_FON_5140 \ + && ! FREETZ_TYPE_FON_WLAN_7112 \ + && ! ( FREETZ_TYPE_FON_WLAN_7140 && FREETZ_TYPE_LANG_EN ) \ + && ! ( FREETZ_TYPE_FON_WLAN_7140 && FREETZ_TYPE_LANG_A_CH ) \ + && ! ( FREETZ_TYPE_FON && FREETZ_TYPE_LANG_EN ) \ + && ! ( FREETZ_TYPE_300IP_AS_FON && FREETZ_TYPE_LANG_EN ) \ + && ! ( FREETZ_TYPE_FON_WLAN && FREETZ_TYPE_LANG_EN ) \ + && ! FREETZ_TYPE_FON_WLAN_7141 \ + && ! FREETZ_TYPE_FON_WLAN_7170 \ + && ! FREETZ_TYPE_FON_WLAN_7240 \ + && ! FREETZ_TYPE_FON_WLAN_7270 \ + && ! FREETZ_TYPE_FON_WLAN_7320 \ + && ! FREETZ_TYPE_FON_WLAN_7340 \ + && ! FREETZ_TYPE_FON_WLAN_7390 \ + && ! FREETZ_TYPE_FON_WLAN_7570 \ + && ! FREETZ_TYPE_WLAN_3131 \ + && ! FREETZ_TYPE_WLAN_3170 \ + && ! FREETZ_TYPE_WLAN_3270 \ + && ! FREETZ_TYPE_WLAN_3270_V3 + + default n + help + Patch init scripts so BusyBox's httpd is used instead of AVM's websrv. + The websrv binary will be removed from the firmware image. + + If "Remove UPnP daemon (igdd/upnpd)" patch is also selected and "Integrate + Media Server from USB Labor firmware" is not selected, 'libwebsrv.so' + will also be removed, because only those three binaries use it. + +comment "No brandings available to remove" + depends on \ + FREETZ_TYPE_SPEEDPORT_W501V + +menu "Remove brandings" + depends on \ + ! FREETZ_TYPE_SPEEDPORT_W501V + +comment "avm and tcom branding can't be removed" + depends on \ + FREETZ_TYPE_ALIEN_HARDWARE + +config FREETZ_REMOVE_BRANDING_1und1 + bool "1&1" + depends on \ + FREETZ_TYPE_LANG_DE && \ + ( \ + FREETZ_TYPE_FON || \ + FREETZ_TYPE_FON_5050 || \ + FREETZ_TYPE_FON_5140 || \ + FREETZ_TYPE_FON_WLAN || \ + FREETZ_TYPE_FON_WLAN_7050 || \ + FREETZ_TYPE_FON_WLAN_7112 || \ + FREETZ_TYPE_FON_WLAN_7113 || \ + FREETZ_TYPE_FON_WLAN_7141 || \ + FREETZ_TYPE_FON_WLAN_7170 || \ + FREETZ_TYPE_FON_WLAN_7240 || \ + FREETZ_TYPE_FON_WLAN_7270 || \ + FREETZ_TYPE_FON_WLAN_7320 || \ + FREETZ_TYPE_FON_WLAN_7330 || \ + FREETZ_TYPE_FON_WLAN_7340 || \ + FREETZ_TYPE_FON_WLAN_7390 || \ + FREETZ_TYPE_WLAN_3020 || \ + FREETZ_TYPE_WLAN_3030 || \ + FREETZ_TYPE_WLAN_3130 || \ + FREETZ_TYPE_CUSTOM \ + ) + default n + help + 1&1 branding + + Each branding provides the web UI templates for a certain manufacturer or OEM. + + NOTE: Make sure not to remove the branding corresponding to the one defined + in your box's boot loader environment. It can be determined by calling the + following command from the box's shell prompt: + + echo $(cat /proc/sys/urlader/firmware_version) + +config FREETZ_REMOVE_BRANDING_avm + bool "AVM" + depends on \ + ( \ + FREETZ_TYPE_LANG_A_CH || \ + FREETZ_TYPE_LANG_DE || \ + FREETZ_TYPE_CUSTOM \ + ) \ + && ! FREETZ_TYPE_ALIEN_HARDWARE + default n + help + AVM branding + + Each branding provides the web UI templates for a certain manufacturer or OEM. + + NOTE: Make sure not to remove the branding corresponding to the one defined + in your box's boot loader environment. It can be determined by calling the + following command from the box's shell prompt: + + echo $(cat /proc/sys/urlader/firmware_version) + +config FREETZ_REMOVE_BRANDING_avme + bool "AVM international" + depends on \ + ( \ + FREETZ_TYPE_LANG_EN || \ + FREETZ_TYPE_CUSTOM \ + ) + default n + help + AVM international branding + + Each branding provides the web UI templates for a certain manufacturer or OEM. + + NOTE: Make sure not to remove the branding corresponding to the one defined + in your box's boot loader environment. It can be determined by calling the + following command from the box's shell prompt: + + echo $(cat /proc/sys/urlader/firmware_version) + +config FREETZ_DL_KERNEL_SITE + string "Kernel site" if FREETZ_DL_OVERRIDE + default "ftp.avm.de/develper/opensrc" if FREETZ_AVM_VERSION_04_30 || \ + FREETZ_AVM_VERSION_04_33 || \ + FREETZ_AVM_VERSION_04_40 || \ + FREETZ_AVM_VERSION_04_49 || \ + FREETZ_AVM_VERSION_04_57 || \ + FREETZ_AVM_VERSION_04_67 || \ + FREETZ_AVM_VERSION_04_70 + default "@AVM/fritzbox.fon_wlan_7170/x_misc/opensrc" if FREETZ_AVM_VERSION_04_76 + default "@AVM/fritzbox.fon_wlan_7170/x_misc/opensrc" if FREETZ_AVM_VERSION_04_80 + default "@AVM/fritzbox.fon_wlan_7170/x_misc/opensrc" if FREETZ_AVM_VERSION_04_87 + default "@AVM/fritzbox.fon_wlan_7270_v1/x_misc/opensrc" if FREETZ_AVM_VERSION_7270_04_86 + default "@AVM/fritzbox.fon_wlan_7270_v3/x_misc/opensrc" if FREETZ_AVM_VERSION_7270_05_05 + default "@AVM/fritzbox.fon_wlan_7320/x_misc/opensrc" if FREETZ_AVM_VERSION_7320_04_86 + default "http://gpl.back2roots.org/source/fritzbox" if FREETZ_AVM_VERSION_7390_04_90 + default "@AVM/fritzbox.fon_wlan_7390/x_misc/opensrc" if FREETZ_AVM_VERSION_7390_05_05 + default "@TELEKOM/Speedport/Speedport_W501V" if FREETZ_AVM_VERSION_r7203 + +config FREETZ_DL_KERNEL_SOURCE + string "Kernel source" if FREETZ_DL_OVERRIDE + default "fritzbox7141-source-files-04.30.tar.bz2" if FREETZ_AVM_VERSION_04_30 + default "fritzbox-source-files-04.33.tar.bz2" if FREETZ_AVM_VERSION_04_33 + default "fritzbox-source-files.04.40.tar.bz2" if FREETZ_AVM_VERSION_04_40 + default "fritzbox-source-files-04.49.tar.gz" if FREETZ_AVM_VERSION_04_49 + default "fritzbox-source-files.04.57.tar.gz" if FREETZ_AVM_VERSION_04_57 + default "fritzbox-source-files.04.67.tar.gz" if FREETZ_AVM_VERSION_04_67 + default "fritzbox-source-files-04.70.tar.gz" if FREETZ_AVM_VERSION_04_70 + default "fritzbox7170-source-files-04.76.tar.gz" if FREETZ_AVM_VERSION_04_76 + default "fritzbox7170-source-files-04.80.tar.gz" if FREETZ_AVM_VERSION_04_80 + default "fritzbox7170-source-files-04.87.tar.gz" if FREETZ_AVM_VERSION_04_87 + default "fritzbox7270-source-files-04.86.tar.gz" if FREETZ_AVM_VERSION_7270_04_86 + default "fritzbox-source-files-05.05.tar.gz" if FREETZ_AVM_VERSION_7270_05_05 + default "fritzbox7320-source-files-04.86.tar.gz" if FREETZ_AVM_VERSION_7320_04_86 + default "fritz_box_fon_wlan_7390_source_files.04.91.tar.gz" if FREETZ_AVM_VERSION_7390_04_90 + default "fritz_box_fon_wlan_7390_source_files.05.05.tar.gz" if FREETZ_AVM_VERSION_7390_05_05 + default "GPL-r7203-4mb_26-tar.bz2" if FREETZ_AVM_VERSION_r7203 + +config FREETZ_DL_KERNEL_SOURCE_MD5 + string "MD5 checksum for downloaded Kernel source file" if FREETZ_DL_OVERRIDE + default "1a43eaf94b7989b8cf8e50b2e50c756c" if FREETZ_AVM_VERSION_04_30 + default "99b6a701f9cd09319086c8655fced242" if FREETZ_AVM_VERSION_04_33 + default "008ecd257e584fc5bbf5e276d4b03ff1" if FREETZ_AVM_VERSION_04_40 + default "e6889745b437bde0f5bdb5ada93c913d" if FREETZ_AVM_VERSION_04_49 + default "702f4adf12638bfa34a6b10c0ede4b55" if FREETZ_AVM_VERSION_04_57 + default "ec2c233bb836e822d9018fd41e123a91" if FREETZ_AVM_VERSION_04_67 + default "855d4ad80fc894d9dff52fcaf55d3c12" if FREETZ_AVM_VERSION_04_70 + default "4ffc088502c896c11931ba81536fa0e6" if FREETZ_AVM_VERSION_04_76 + default "6bf92b81b48a3a05efd3aae6c05fe3e2" if FREETZ_AVM_VERSION_04_80 + default "cad33bda041910e2aae01f027465162b" if FREETZ_AVM_VERSION_04_87 + default "55a11af7dcfd617c39e75877045ab468" if FREETZ_AVM_VERSION_7270_04_86 + default "19280ad861a7e88698d41211996c5ac6" if FREETZ_AVM_VERSION_7270_05_05 + default "0e2ddf32808eb329efc4b486c6de0011" if FREETZ_AVM_VERSION_7320_04_86 + default "2cad066e0e57aa3e58bf784b396ee676" if FREETZ_AVM_VERSION_7390_04_90 + default "fbf515bd77f3d3a64a3095889777cc13" if FREETZ_AVM_VERSION_7390_05_05 + default "582c74f0959a687c41c1bcfa599ace9c" if FREETZ_AVM_VERSION_r7203 + +config FREETZ_DL_SITE + string "Firmware site" if FREETZ_DL_OVERRIDE + depends on ! FREETZ_TYPE_LABOR + default "@AVM/fritzbox.2170/firmware/deutsch" if FREETZ_TYPE_2170 + default "@AVM/fritzbox.fon/firmware/deutsch" if (FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON) && \ + FREETZ_TYPE_LANG_DE + default "@AVM/fritzbox.fon/firmware/english/annex_a" if (FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON) && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "@AVM/fritzbox.fon/firmware/english/annex_b" if (FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON) && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "@AVM/fritzbox.fon_5010/firmware/deutsch_a-ch" if FREETZ_TYPE_FON_5010 + default "@AVM/fritzbox.fon_5050/firmware" if FREETZ_TYPE_FON_5050 + default "@AVM/fritzbox.fon_5124/firmware/english/annex_a" if FREETZ_TYPE_FON_5124 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "@AVM/fritzbox.fon_5124/firmware/english/annex_b" if FREETZ_TYPE_FON_5124 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "@AVM/fritzbox.fon_5140/firmware" if FREETZ_TYPE_FON_5140 + default "@AVM/fritzbox.fon_wlan/firmware/deutsch" if FREETZ_TYPE_FON_WLAN && \ + FREETZ_TYPE_LANG_DE + default "@AVM/fritzbox.fon_wlan/firmware/english/annex_a" if FREETZ_TYPE_FON_WLAN && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "@AVM/fritzbox.fon_wlan/firmware/english/annex_b" if FREETZ_TYPE_FON_WLAN && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "@AVM/fritzbox.fon_wlan_7050/firmware" if FREETZ_TYPE_FON_WLAN_7050 + default "@AVM/fritzbox.fon_wlan_7112/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7112 + default "@AVM/fritzbox.fon_wlan_7113/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7113 && \ + FREETZ_TYPE_LANG_DE + default "@AVM/fritzbox.fon_wlan_7113/firmware/english/annex_a" if FREETZ_TYPE_FON_WLAN_7113 && \ + FREETZ_TYPE_LANG_EN + default "@AVM/fritzbox.fon_wlan_7140/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7140 && \ + FREETZ_TYPE_LANG_DE + default "@AVM/fritzbox.fon_wlan_7140/firmware/deutsch_a-ch" if FREETZ_TYPE_FON_WLAN_7140 && \ + FREETZ_TYPE_LANG_A_CH + default "@AVM/fritzbox.fon_wlan_7140/firmware/english/annex_a" if FREETZ_TYPE_FON_WLAN_7140 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "@AVM/fritzbox.fon_wlan_7140/firmware/english/annex_b" if FREETZ_TYPE_FON_WLAN_7140 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "@AVM/fritzbox.fon_wlan_7141/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7141 + default "@AVM/fritzfon.7150/firmware" if FREETZ_TYPE_FON_7150 + default "@AVM/fritzbox.fon_wlan_7170/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7170 && \ + FREETZ_TYPE_LANG_DE + default "@AVM/fritzbox.fon_wlan_7170/firmware/deutsch_a-ch" if FREETZ_TYPE_FON_WLAN_7170 && \ + FREETZ_TYPE_LANG_A_CH + default "@AVM/fritzbox.fon_wlan_7170/firmware/english/annex_a" if FREETZ_TYPE_FON_WLAN_7170 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "@AVM/fritzbox.fon_wlan_7170/firmware/english/annex_b" if FREETZ_TYPE_FON_WLAN_7170 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "@AVM/fritzbox.fon_wlan_7240/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7240 + default "@AVM/fritzbox.fon_wlan_7270_v1/firmware/deutsch" if ( ( FREETZ_TYPE_FON_WLAN_7270_V1 && \ + ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_72702_72701 ) && \ + FREETZ_TYPE_LANG_DE + default "@AVM/fritzbox.fon_wlan_7270_v2/firmware/deutsch" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && \ + ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7270_7270 ) && \ + ! FREETZ_TYPE_LABOR && \ + FREETZ_TYPE_LANG_DE + default "@AVM/fritzbox.fon_wlan_7270_v2/firmware/english" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && \ + ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7270_7270 ) && \ + FREETZ_TYPE_LANG_EN + default "@AVM/fritzbox.fon_wlan_7270_v3/firmware/deutsch" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && \ + ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7240_7270 ) && \ + ! FREETZ_TYPE_LABOR && \ + FREETZ_TYPE_LANG_DE + default "@AVM/fritzbox.fon_wlan_7270_v3/firmware/english" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && \ + ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7240_7270 ) && \ + FREETZ_TYPE_LANG_EN + default "@AVM/fritzbox.fon_wlan_7320/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7320 + default "@AVM/fritzbox.fon_wlan_7330/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7330 + default "@AVM/fritzbox.fon_wlan_7340/firmware/english" if FREETZ_TYPE_FON_WLAN_7340 + default "@AVM/fritzbox.fon_wlan_7390/firmware/deutsch" if FREETZ_TYPE_FON_WLAN_7390 && \ + FREETZ_TYPE_LANG_DE + default "@AVM/fritzbox.fon_wlan_7390/firmware/english" if FREETZ_TYPE_FON_WLAN_7390 && \ + FREETZ_TYPE_LANG_EN + default "@AVM/fritzbox.fon_wlan_7570/firmware/english" if FREETZ_TYPE_FON_WLAN_7570 + default "@AVM/fritzbox.sl_wlan/firmware" if FREETZ_TYPE_WLAN_3020 + default "@AVM/fritzbox.wlan_3030/firmware" if FREETZ_TYPE_WLAN_3030 + default "@AVM/fritzbox.wlan_3130/firmware" if FREETZ_TYPE_WLAN_3130 + default "@AVM/fritzbox.wlan_3131/firmware/deutsch" if FREETZ_TYPE_WLAN_3131 + default "@AVM/fritzbox.wlan_3170/firmware/deutsch" if FREETZ_TYPE_WLAN_3170 + default "@AVM/fritzbox.wlan_3270/firmware/deutsch" if FREETZ_TYPE_WLAN_3270 + default "@AVM/fritzbox.wlan_3270_v3/firmware/deutsch" if FREETZ_TYPE_WLAN_3270_V3 + default "@TELEKOM/Speedport/Speedport_W501V" if FREETZ_TYPE_SPEEDPORT_W501V + default "@AVM/..." if FREETZ_TYPE_CUSTOM + +config FREETZ_DL_SOURCE + string "Firmware source" if FREETZ_DL_OVERRIDE + default "FRITZ.Box_2170.51.04.57.image" if FREETZ_TYPE_2170 + default "fritz.box_fon.06.04.33.image" if (FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON) && \ + FREETZ_TYPE_LANG_DE + default "fritz.box_fon.annexa.en.06.04.49.image" if (FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON) && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "fritz.box_fon.en.06.04.49.image" if (FREETZ_TYPE_300IP_AS_FON || \ + FREETZ_TYPE_FON) && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "fritz.box_fon_5010.annexa.48.04.43.image" if FREETZ_TYPE_FON_5010 + default "fritz.box_fon_5050.12.04.31.image" if FREETZ_TYPE_FON_5050 + default "FRITZ.Box_Fon_5124.AnnexA.en.57.04.76.image" if FREETZ_TYPE_FON_5124 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "FRITZ.Box_Fon_5124.AnnexB.en.56.04.76.image" if FREETZ_TYPE_FON_5124 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "FRITZ.Box_Fon_5140.AnnexB.43.04.67.image" if FREETZ_TYPE_FON_5140 + default "fritz.box_fon_wlan.08.04.34.image" if FREETZ_TYPE_FON_WLAN && \ + FREETZ_TYPE_LANG_DE + default "FRITZ.Box_Fon_WLAN.AnnexA.en.08.04.49.image" if FREETZ_TYPE_FON_WLAN && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "FRITZ.Box_Fon_WLAN.AnnexB.en.08.04.49.image" if FREETZ_TYPE_FON_WLAN && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "fritz.box_fon_wlan_7050.14.04.33.image" if FREETZ_TYPE_FON_WLAN_7050 + default "FRITZ.Box_Fon_WLAN_7112.87.04.87.image" if FREETZ_TYPE_FON_WLAN_7112 + default "FRITZ.Box_Fon_WLAN_7113.60.04.68.image" if FREETZ_TYPE_FON_WLAN_7113 && \ + FREETZ_TYPE_LANG_DE + default "FRITZ.Box_Fon_WLAN_7113.AnnexA.de-en-es-it-fr.90.04.84.image" if FREETZ_TYPE_FON_WLAN_7113 && \ + FREETZ_TYPE_LANG_EN + default "fritz.box_fon_wlan_7140.annexb.30.04.33.image" if FREETZ_TYPE_FON_WLAN_7140 && \ + FREETZ_TYPE_LANG_DE + default "FRITZ.Box_Fon_WLAN_7140.AnnexA.39.04.76.image" if FREETZ_TYPE_FON_WLAN_7140 && \ + FREETZ_TYPE_LANG_A_CH + default "FRITZ.Box_Fon_WLAN_7140.AnnexA.en.39.04.67.image" if FREETZ_TYPE_FON_WLAN_7140 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "FRITZ.Box_Fon_WLAN_7140.AnnexB.en.30.04.67.image" if FREETZ_TYPE_FON_WLAN_7140 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "FRITZ.Box_Fon_WLAN_7141.40.04.76.image" if FREETZ_TYPE_FON_WLAN_7141 + default "fritz.fon_7150.annexb.38.04.71.image" if FREETZ_TYPE_FON_7150 + default "FRITZ.Box_Fon_WLAN_7170.29.04.87.image" if FREETZ_TYPE_FON_WLAN_7170 && \ + FREETZ_TYPE_LANG_DE + default "FRITZ.Box_Fon_WLAN_7170.AnnexA.58.04.76.image" if FREETZ_TYPE_FON_WLAN_7170 && \ + FREETZ_TYPE_LANG_A_CH + default "FRITZ.Box_Fon_WLAN_7170.AnnexA.en.58.04.84.image" if FREETZ_TYPE_FON_WLAN_7170 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_A + default "FRITZ.Box_Fon_WLAN_7170.AnnexB.en.29.04.82.image" if FREETZ_TYPE_FON_WLAN_7170 && \ + FREETZ_TYPE_LANG_EN && \ + FREETZ_TYPE_ANNEX_B + default "FRITZ.Box_Fon_WLAN_7240.73.05.05.image" if FREETZ_TYPE_FON_WLAN_7240 && \ + ! FREETZ_TYPE_LABOR +# default "Labor_FRITZ.Box_Fon_WLAN_7240.73.05.04-20170.image" if FREETZ_TYPE_FON_WLAN_7240 && \ +# FREETZ_TYPE_LABOR_PREVIEW + default "FRITZ.Box_Fon_WLAN_7270_v1.54.04.88.image" if FREETZ_TYPE_FON_WLAN_7270_V1 && \ + ! FREETZ_TYPE_LABOR && \ + FREETZ_TYPE_LANG_DE +# default "Labor_FRITZ.Box_Fon_WLAN_7270_v1.54.04.86-18582.image" if FREETZ_TYPE_FON_WLAN_7270_V1 && \ +# FREETZ_TYPE_LABOR_PREVIEW + default "FRITZ.Box_Fon_WLAN_7270_v2.54.05.05.image" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && \ + ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7270_7270 ) && \ + ! FREETZ_TYPE_LABOR && \ + FREETZ_TYPE_LANG_DE + default "FRITZ.Box_Fon_WLAN_7270_v2_Labor.54.05.07-20870.image" if FREETZ_TYPE_FON_WLAN_7270_V2 && \ + FREETZ_TYPE_LABOR_PREVIEW + default "FRITZ.Box_Fon_WLAN_7270_16.en-de-es-it-fr.54.05.05.image" if ( ( FREETZ_TYPE_FON_WLAN_7270_V2 && \ + ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7270_7270 ) && \ + FREETZ_TYPE_LANG_EN + default "FRITZ.Box_Fon_WLAN_7270_v3.74.05.05.image" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && \ + ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7240_7270 ) && \ + ! FREETZ_TYPE_LABOR && \ + FREETZ_TYPE_LANG_DE + default "FRITZ.Box_Fon_WLAN_7270_v3.en-de-es-it-fr.74.05.05.image" if ( ( FREETZ_TYPE_FON_WLAN_7270_V3 && \ + ! FREETZ_TYPE_ALIEN_HARDWARE ) || \ + FREETZ_TYPE_7240_7270 ) && \ + FREETZ_TYPE_LANG_EN + default "FRITZ.Box_Fon_WLAN_7270_v3_Labor.74.05.07-20870.image" if ( FREETZ_TYPE_FON_WLAN_7270_V3 || \ + ( FREETZ_TYPE_FON_WLAN_7270 && \ + FREETZ_TYPE_ALIEN_HARDWARE ) ) && \ + FREETZ_TYPE_LABOR_PREVIEW + default "FRITZ.Box_Fon_WLAN_7320.100.04.89.image" if FREETZ_TYPE_FON_WLAN_7320 && \ + ! FREETZ_TYPE_LABOR + default "FRITZ.Box_7330.107.05.06.image" if FREETZ_TYPE_FON_WLAN_7330 + default "FRITZ.Box_Fon_WLAN_7340.en-de-es-it-fr.99.05.05.image" if FREETZ_TYPE_FON_WLAN_7340 + default "FRITZ.Box_Fon_WLAN_7390.84.05.05.image" if FREETZ_TYPE_FON_WLAN_7390 && \ + ! FREETZ_TYPE_LABOR && \ + FREETZ_TYPE_LANG_DE + default "FRITZ.Box_Fon_WLAN_7390.en-de-es-it-fr.84.05.05.image" if FREETZ_TYPE_FON_WLAN_7390 && \ + ! FREETZ_TYPE_LANG_DE + default "FRITZ.Box_Fon_WLAN_7390_Labor.84.05.07-20869.image" if FREETZ_TYPE_FON_WLAN_7390 && \ + FREETZ_TYPE_LABOR_PREVIEW + default "FRITZ.Box_Fon_WLAN_7570_vDSL.en-de-fr.75.04.91.image" if FREETZ_TYPE_FON_WLAN_7570 + default "fritz.box_sl_wlan.09.04.34.image" if FREETZ_TYPE_WLAN_3020 + default "fritz.box_wlan_3030.21.04.34.image" if FREETZ_TYPE_WLAN_3030 + default "fritz.box_wlan_3130.44.04.34.image" if FREETZ_TYPE_WLAN_3130 + default "fritz.box_wlan_3131.50.04.57.image" if FREETZ_TYPE_WLAN_3131 + default "fritz.box_wlan_3170.49.04.58.image" if FREETZ_TYPE_WLAN_3170 + default "fritz.box_wlan_3270.67.05.05.image" if FREETZ_TYPE_WLAN_3270 + default "fritz.box_wlan_3270_v3.96.05.05.image" if FREETZ_TYPE_WLAN_3270_V3 + default "fw_Speedport_W501V_v_28.04.38.image" if FREETZ_TYPE_SPEEDPORT_W501V + default "fritz.box..." if FREETZ_TYPE_CUSTOM + +endmenu # "Toolchain options" # + +endmenu # "Advanced options" # + +# INCLUDE_END Config.in diff --git a/tests/examplefiles/Deflate.fs b/tests/examplefiles/Deflate.fs new file mode 100755 index 00000000..7d3680ec --- /dev/null +++ b/tests/examplefiles/Deflate.fs @@ -0,0 +1,578 @@ +// public domain
+
+module Deflate
+
+open System
+open System.Collections.Generic
+open System.IO
+open System.Linq
+open Crc
+
+let maxbuf = 32768
+let maxlen = 258
+
+let getBit (b:byte) (bit:int) =
+ if b &&& (1uy <<< bit) = 0uy then 0 else 1
+
+type BitReader(sin:Stream) =
+ let mutable bit = 8
+ let mutable cur = 0uy
+
+ member x.Skip() =
+ bit <- 8
+
+ member x.ReadBit() =
+ if bit = 8 then
+ bit <- 0
+ let b = sin.ReadByte()
+ if b = -1 then
+ failwith "バッファを超過しました"
+ cur <- byte b
+ let ret = if cur &&& (1uy <<< bit) = 0uy then 0 else 1
+ bit <- bit + 1
+ ret
+
+ member x.ReadLE n =
+ let mutable ret = 0
+ for i = 0 to n - 1 do
+ if x.ReadBit() = 1 then ret <- ret ||| (1 <<< i)
+ ret
+
+ member x.ReadBE n =
+ let mutable ret = 0
+ for i = 0 to n - 1 do
+ ret <- (ret <<< 1) ||| x.ReadBit()
+ ret
+
+ member x.ReadBytes len =
+ if bit <> 8 then bit <- 8
+ let buf = Array.zeroCreate<byte> len
+ ignore <| sin.Read(buf, 0, len)
+ buf
+
+type WriteBuffer(sout:Stream) =
+ let mutable prev:byte[] = null
+ let mutable buf = Array.zeroCreate<byte> maxbuf
+ let mutable p = 0
+
+ let next newbuf =
+ prev <- buf
+ buf <- if newbuf then Array.zeroCreate<byte> maxbuf else null
+ p <- 0
+
+ member x.Close() =
+ next false
+ next false
+
+ interface IDisposable with
+ member x.Dispose() = x.Close()
+
+ member x.WriteByte (b:byte) =
+ buf.[p] <- b
+ sout.WriteByte b
+ p <- p + 1
+ if p = maxbuf then next true
+
+ member x.Write (src:byte[]) start len =
+ let maxlen = maxbuf - p
+ if len <= maxlen then
+ Array.Copy(src, start, buf, p, len)
+ sout.Write(src, start, len)
+ p <- p + len
+ if p = maxbuf then next true
+ else
+ x.Write src start maxlen
+ x.Write src (start + maxlen) (len - maxlen)
+
+ member x.Copy len dist =
+ if dist < 1 then
+ failwith <| sprintf "dist too small: %d < 1" dist
+ elif dist > maxbuf then
+ failwith <| sprintf "dist too big: %d > %d" dist maxbuf
+ let pp = p - dist
+ if pp < 0 then
+ if prev = null then
+ failwith <| sprintf "dist too big: %d > %d" dist p
+ let pp = pp + maxbuf
+ let maxlen = maxbuf - pp
+ if len <= maxlen then
+ x.Write prev pp len
+ else
+ x.Write prev pp maxlen
+ x.Copy (len - maxlen) dist
+ else
+ let maxlen = p - pp
+ if len <= maxlen then
+ x.Write buf pp len
+ else
+ if dist = 1 then
+ let b = buf.[pp]
+ for i = 1 to len do
+ x.WriteByte b
+ else
+ let buf' = buf
+ let mutable len' = len
+ while len' > 0 do
+ let len'' = Math.Min(len', maxlen)
+ x.Write buf' pp len''
+ len' <- len' - len''
+
+type Huffman(lens:int[]) =
+ let vals = Array.zeroCreate<int> lens.Length
+ let min = lens.Where(fun x -> x > 0).Min()
+ let max = lens.Max()
+ let counts = Array.zeroCreate<int> (max + 1)
+ let firsts = Array.zeroCreate<int> (max + 1)
+ let nexts = Array.zeroCreate<int> (max + 1)
+ let tables = Array.zeroCreate<int[]>(max + 1)
+
+ do
+ for len in lens do
+ if len > 0 then counts.[len] <- counts.[len] + 1
+ for i = 1 to max do
+ firsts.[i] <- (firsts.[i - 1] + counts.[i - 1]) <<< 1
+ Array.Copy(firsts, 0, nexts, 0, max + 1)
+ for i = 0 to vals.Length - 1 do
+ let len = lens.[i]
+ if len > 0 then
+ vals.[i] <- nexts.[len]
+ nexts.[len] <- nexts.[len] + 1
+
+ for i = 0 to vals.Length - 1 do
+ let len = lens.[i]
+ if len > 0 then
+ let start = firsts.[len]
+ if tables.[len] = null then
+ let count = nexts.[len] - start
+ tables.[len] <- Array.zeroCreate<int> count
+ tables.[len].[vals.[i] - start] <- i
+
+ member x.GetValue h =
+ let rec getv i =
+ if i > max then -1 else
+ if h < nexts.[i] then
+ tables.[i].[h - firsts.[i]]
+ else
+ getv (i + 1)
+ getv min
+
+ member x.Read(br:BitReader) =
+ let rec read h i =
+ if h < nexts.[i] then
+ tables.[i].[h - firsts.[i]]
+ else
+ read ((h <<< 1) ||| br.ReadBit()) (i + 1)
+ read (br.ReadBE min) min
+
+type [<AbstractClass>] HuffmanDecoder() =
+ abstract GetValue: unit->int
+ abstract GetDistance: unit->int
+
+type FixedHuffman(br:BitReader) =
+ inherit HuffmanDecoder()
+
+ override x.GetValue() =
+ let v = br.ReadBE 7
+ if v < 24 then v + 256 else
+ let v = (v <<< 1) ||| br.ReadBit()
+ if v < 192 then v - 48
+ elif v < 200 then v + 88
+ else ((v <<< 1) ||| br.ReadBit()) - 256
+
+ override x.GetDistance() = br.ReadBE 5
+
+type DynamicHuffman(br:BitReader) =
+ inherit HuffmanDecoder()
+
+ let lit, dist =
+ let hlit =
+ let hlit = (br.ReadLE 5) + 257
+ if hlit > 286 then failwith <| sprintf "hlit: %d > 286" hlit
+ hlit
+
+ let hdist =
+ let hdist = (br.ReadLE 5) + 1
+ if hdist > 32 then failwith <| sprintf "hdist: %d > 32" hdist
+ hdist
+
+ let hclen =
+ let hclen = (br.ReadLE 4) + 4
+ if hclen > 19 then failwith <| sprintf "hclen: %d > 19" hclen
+ hclen
+
+ let clen =
+ let hclens = Array.zeroCreate<int> 19
+ let order = [| 16; 17; 18; 0; 8; 7; 9; 6; 10; 5;
+ 11; 4; 12; 3; 13; 2; 14; 1; 15 |]
+ for i = 0 to hclen - 1 do
+ hclens.[order.[i]] <- br.ReadLE 3
+ new Huffman(hclens)
+
+ let ld = Array.zeroCreate<int>(hlit + hdist)
+ let mutable i = 0
+ while i < ld.Length do
+ let v = clen.Read(br)
+ if v < 16 then
+ ld.[i] <- v
+ i <- i + 1
+ else
+ let r, v =
+ match v with
+ | 16 -> (br.ReadLE 2) + 3, ld.[i - 1]
+ | 17 -> (br.ReadLE 3) + 3, 0
+ | 18 -> (br.ReadLE 7) + 11, 0
+ | _ -> failwith "不正な値です。"
+ for j = 0 to r - 1 do
+ ld.[i + j] <- v
+ i <- i + r
+
+ new Huffman(ld.[0 .. hlit - 1]),
+ new Huffman(ld.[hlit .. hlit + hdist - 1])
+
+ override x.GetValue() = lit.Read br
+ override x.GetDistance() = dist.Read br
+
+let getLitExLen v = if v < 265 || v = 285 then 0 else (v - 261) >>> 2
+let getDistExLen d = if d < 4 then 0 else (d - 2) >>> 1
+
+let litlens =
+ let litlens = Array.zeroCreate<int> 286
+ let mutable v = 3
+ for i = 257 to 284 do
+ litlens.[i] <- v
+ v <- v + (1 <<< (getLitExLen i))
+ litlens.[285] <- maxlen
+ litlens.[257..285]
+
+let distlens =
+ let distlens = Array.zeroCreate<int> 30
+ let mutable v = 1
+ for i = 0 to 29 do
+ distlens.[i] <- v
+ v <- v + (1 <<< (getDistExLen i))
+ distlens
+
+type Reader(sin:Stream) =
+ inherit Stream()
+
+ let br = new BitReader(sin)
+ let fh = new FixedHuffman(br)
+
+ let sout = new MemoryStream()
+ let dbuf = new WriteBuffer(sout)
+
+ let mutable cache:byte[] = null
+ let mutable canRead = true
+
+ let rec read (h:HuffmanDecoder) =
+ let v = h.GetValue()
+ if v > 285 then failwith <| sprintf "不正な値: %d" v
+ if v < 256 then
+ dbuf.WriteByte(byte v)
+ elif v > 256 then
+ let len =
+ if v < 265 then v - 254 else
+ litlens.[v - 257] + (br.ReadLE (getLitExLen v))
+ let dist =
+ let d = h.GetDistance()
+ if d > 29 then failwith <| sprintf "不正な距離: %d" d
+ if d < 4 then d + 1 else
+ distlens.[d] + (br.ReadLE (getDistExLen d))
+ dbuf.Copy len dist
+ if v <> 256 then read h
+
+ override x.CanRead = canRead
+ override x.CanWrite = false
+ override x.CanSeek = false
+ override x.Flush() = ()
+
+ override x.Close() =
+ dbuf.Close()
+ canRead <- false
+
+ override x.Read(buffer, offset, count) =
+ let offset =
+ if cache = null then 0 else
+ let clen = cache.Length
+ let len = Math.Min(clen, count)
+ Array.Copy(cache, 0, buffer, offset, len)
+ cache <- if len = clen then null
+ else cache.[len .. clen - 1]
+ len
+ let req = int64 <| count - offset
+ while canRead && sout.Length < req do
+ x.readBlock()
+ let len =
+ if sout.Length = 0L then 0 else
+ let data = sout.ToArray()
+ sout.SetLength(0L)
+ let dlen = data.Length
+ let len = Math.Min(int req, dlen)
+ Array.Copy(data, 0, buffer, offset, len)
+ if dlen > len then
+ cache <- data.[len..]
+ len
+ offset + len
+
+ override x.Position
+ with get() = raise <| new NotImplementedException()
+ and set(v) = raise <| new NotImplementedException()
+
+ override x.Length = raise <| new NotImplementedException()
+ override x.Seek(_, _) = raise <| new NotImplementedException()
+ override x.Write(_, _, _) = raise <| new NotImplementedException()
+ override x.SetLength(_) = raise <| new NotImplementedException()
+
+ member private x.readBlock() =
+ let bfinal = br.ReadBit()
+ match br.ReadLE 2 with
+ | 0 -> br.Skip()
+ let len = br.ReadLE 16
+ let nlen = br.ReadLE 16
+ if len + nlen <> 0x10000 then
+ failwith "不正な非圧縮長"
+ dbuf.Write (br.ReadBytes len) 0 len
+ | 1 -> read fh
+ | 2 -> read (new DynamicHuffman(br))
+ | _ -> failwith "不正なブロックタイプ"
+ if bfinal = 1 then
+ canRead <- false
+ x.Close()
+
+type BitWriter(sout:Stream) =
+ let mutable bit = 0
+ let mutable cur = 0uy
+
+ member x.Skip() =
+ if bit > 0 then
+ sout.WriteByte(cur)
+ bit <- 0
+ cur <- 0uy
+
+ interface IDisposable with
+ member x.Dispose() =
+ x.Skip()
+ sout.Flush()
+
+ member x.WriteBit(b:int) =
+ cur <- cur ||| ((byte b) <<< bit)
+ bit <- bit + 1
+ if bit = 8 then
+ sout.WriteByte(cur)
+ bit <- 0
+ cur <- 0uy
+
+ member x.WriteLE (len:int) (b:int) =
+ for i = 0 to len - 1 do
+ x.WriteBit <| if (b &&& (1 <<< i)) = 0 then 0 else 1
+
+ member x.WriteBE (len:int) (b:int) =
+ for i = len - 1 downto 0 do
+ x.WriteBit <| if (b &&& (1 <<< i)) = 0 then 0 else 1
+
+ member x.WriteBytes(data:byte[]) =
+ x.Skip()
+ sout.Write(data, 0, data.Length)
+
+type FixedHuffmanWriter(bw:BitWriter) =
+ member x.Write (b:int) =
+ if b < 144 then
+ bw.WriteBE 8 (b + 0b110000)
+ elif b < 256 then
+ bw.WriteBE 9 (b - 144 + 0b110010000)
+ elif b < 280 then
+ bw.WriteBE 7 (b - 256)
+ elif b < 288 then
+ bw.WriteBE 8 (b - 280 + 0b11000000)
+
+ member x.WriteLen (len:int) =
+ if len < 3 || len > maxlen then
+ failwith <| sprintf "不正な長さ: %d" len
+ let mutable ll = 285
+ while len < litlens.[ll - 257] do
+ ll <- ll - 1
+ x.Write ll
+ bw.WriteLE (getLitExLen ll) (len - litlens.[ll - 257])
+
+ member x.WriteDist (d:int) =
+ if d < 1 || d > maxbuf then
+ failwith <| sprintf "不正な距離: %d" d
+ let mutable dl = 29
+ while d < distlens.[dl] do
+ dl <- dl - 1
+ bw.WriteBE 5 dl
+ bw.WriteLE (getDistExLen dl) (d - distlens.[dl])
+
+let maxbuf2 = maxbuf * 2
+let buflen = maxbuf2 + maxlen
+
+let inline getHash (buf:byte[]) pos =
+ ((int buf.[pos]) <<< 4) ^^^ ((int buf.[pos + 1]) <<< 2) ^^^ (int buf.[pos + 2])
+
+let inline addHash (hash:List<int>[]) (buf:byte[]) pos =
+ if buf.[pos] <> buf.[pos + 1] then
+ hash.[getHash buf pos].Add pos
+
+let inline addHash2 (tables:int[,]) (counts:int[]) (buf:byte[]) pos =
+ if buf.[pos] <> buf.[pos + 1] then
+ let h = getHash buf pos
+ let c = counts.[h]
+ tables.[h, c &&& 15] <- pos
+ counts.[h] <- c + 1
+
+type Writer(t:int, sin:Stream) =
+ let mutable length = buflen
+ let buf = Array.zeroCreate<byte> buflen
+ let tables, counts =
+ if t = 2 then Array2D.zeroCreate<int> 4096 16, Array.create 4096 0 else null, null
+ let hash = if tables = null then [| for _ in 0..4095 -> new List<int>() |] else null
+ let mutable crc = ~~~0u
+
+ let read pos len =
+ let rlen = sin.Read(buf, pos, len)
+ if rlen < len then length <- pos + rlen
+ for i = pos to pos + rlen - 1 do
+ let b = int(crc ^^^ (uint32 buf.[i])) &&& 0xff
+ crc <- (crc >>> 8) ^^^ crc32_table.[b]
+ if hash <> null then
+ for list in hash do list.Clear()
+ else
+ Array.fill counts 0 counts.Length 0
+
+ do
+ read 0 buflen
+
+ let search (pos:int) =
+ let mutable maxp = -1
+ let mutable maxl = 2
+ let mlen = Math.Min(maxlen, length - pos)
+ let last = Math.Max(0, pos - maxbuf)
+ let h = getHash buf pos
+ if hash <> null then
+ let list = hash.[h]
+ let mutable i = list.Count - 1
+ while i >= 0 do
+ let p = list.[i]
+ if p < last then i <- 0 else
+ let mutable len = 0
+ while len < mlen && buf.[p + len] = buf.[pos + len] do
+ len <- len + 1
+ if len > maxl then
+ maxp <- p
+ maxl <- len
+ i <- i - 1
+ else
+ let c = counts.[h]
+ let p1, p2 = if c < 16 then 0, c - 1 else c + 1, c + 16
+ let mutable i = p2
+ while i >= p1 do
+ let p = tables.[h, i &&& 15]
+ if p < last then i <- 0 else
+ let mutable len = 0
+ while len < mlen && buf.[p + len] = buf.[pos + len] do
+ len <- len + 1
+ if len > maxl then
+ maxp <- p
+ maxl <- len
+ i <- i - 1
+ maxp, maxl
+
+ member x.Crc = ~~~crc
+
+ member x.Compress (sout:Stream) =
+ use bw = new BitWriter(sout)
+ bw.WriteBit 1
+ bw.WriteLE 2 1
+ let hw = new FixedHuffmanWriter(bw)
+ let mutable p = 0
+ match t with
+ | 2 ->
+ while p < length do
+ let b = buf.[p]
+ if p < length - 4 && b = buf.[p + 1] && b = buf.[p + 2] && b = buf.[p + 3] then
+ let mutable len = 4
+ let mlen = Math.Min(maxlen + 1, length - p)
+ while len < mlen && b = buf.[p + len] do
+ len <- len + 1
+ hw.Write(int b)
+ hw.WriteLen(len - 1)
+ hw.WriteDist 1
+ p <- p + len
+ else
+ let maxp, maxl = search p
+ if maxp < 0 then
+ hw.Write(int b)
+ addHash2 tables counts buf p
+ p <- p + 1
+ else
+ hw.WriteLen maxl
+ hw.WriteDist (p - maxp)
+ for i = p to p + maxl - 1 do
+ addHash2 tables counts buf i
+ p <- p + maxl
+ if p > maxbuf2 then
+ Array.Copy(buf, maxbuf, buf, 0, maxbuf + maxlen)
+ if length < buflen then length <- length - maxbuf else
+ read (maxbuf + maxlen) maxbuf
+ p <- p - maxbuf
+ for i = 0 to p - 1 do
+ addHash2 tables counts buf i
+ | 1 ->
+ while p < length do
+ let b = buf.[p]
+ if p < length - 4 && b = buf.[p + 1] && b = buf.[p + 2] && b = buf.[p + 3] then
+ let mutable len = 4
+ let mlen = Math.Min(maxlen + 1, length - p)
+ while len < mlen && b = buf.[p + len] do
+ len <- len + 1
+ hw.Write(int b)
+ hw.WriteLen(len - 1)
+ hw.WriteDist 1
+ p <- p + len
+ else
+ let maxp, maxl = search p
+ if maxp < 0 then
+ hw.Write(int b)
+ addHash hash buf p
+ p <- p + 1
+ else
+ hw.WriteLen maxl
+ hw.WriteDist (p - maxp)
+ for i = p to p + maxl - 1 do
+ addHash hash buf i
+ p <- p + maxl
+ if p > maxbuf2 then
+ Array.Copy(buf, maxbuf, buf, 0, maxbuf + maxlen)
+ if length < buflen then length <- length - maxbuf else
+ read (maxbuf + maxlen) maxbuf
+ p <- p - maxbuf
+ for i = 0 to p - 1 do
+ addHash hash buf i
+ | _ ->
+ while p < length do
+ let maxp, maxl = search p
+ if maxp < 0 then
+ hw.Write(int buf.[p])
+ hash.[getHash buf p].Add p
+ p <- p + 1
+ else
+ hw.WriteLen maxl
+ hw.WriteDist (p - maxp)
+ for i = p to p + maxl - 1 do
+ hash.[getHash buf i].Add i
+ p <- p + maxl
+ if p > maxbuf2 then
+ Array.Copy(buf, maxbuf, buf, 0, maxbuf + maxlen)
+ if length < buflen then length <- length - maxbuf else
+ read (maxbuf + maxlen) maxbuf
+ p <- p - maxbuf
+ for i = 0 to p - 1 do
+ hash.[getHash buf i].Add i
+ hw.Write 256
+
+let GetCompressBytes (sin:Stream) =
+ let now = DateTime.Now
+ let ms = new MemoryStream()
+ let w = new Writer(1, sin)
+ w.Compress ms
+ ms.ToArray(), w.Crc
diff --git a/tests/examplefiles/Error.pmod b/tests/examplefiles/Error.pmod new file mode 100644 index 00000000..808ecb0e --- /dev/null +++ b/tests/examplefiles/Error.pmod @@ -0,0 +1,38 @@ +#pike __REAL_VERSION__ + +constant Generic = __builtin.GenericError; + +constant Index = __builtin.IndexError; + +constant BadArgument = __builtin.BadArgumentError; + +constant Math = __builtin.MathError; + +constant Resource = __builtin.ResourceError; + +constant Permission = __builtin.PermissionError; + +constant Decode = __builtin.DecodeError; + +constant Cpp = __builtin.CppError; + +constant Compilation = __builtin.CompilationError; + +constant MasterLoad = __builtin.MasterLoadError; + +constant ModuleLoad = __builtin.ModuleLoadError; + +//! Returns an Error object for any argument it receives. If the +//! argument already is an Error object or is empty, it does nothing. +object mkerror(mixed error) +{ + if (error == UNDEFINED) + return error; + if (objectp(error) && error->is_generic_error) + return error; + if (arrayp(error)) + return Error.Generic(@error); + if (stringp(error)) + return Error.Generic(error); + return Error.Generic(sprintf("%O", error)); +}
\ No newline at end of file diff --git a/tests/examplefiles/FakeFile.pike b/tests/examplefiles/FakeFile.pike new file mode 100644 index 00000000..48f3ea64 --- /dev/null +++ b/tests/examplefiles/FakeFile.pike @@ -0,0 +1,360 @@ +#pike __REAL_VERSION__ + +//! A string wrapper that pretends to be a @[Stdio.File] object +//! in addition to some features of a @[Stdio.FILE] object. + + +//! This constant can be used to distinguish a FakeFile object +//! from a real @[Stdio.File] object. +constant is_fake_file = 1; + +protected string data; +protected int ptr; +protected int(0..1) r; +protected int(0..1) w; +protected int mtime; + +protected function read_cb; +protected function read_oob_cb; +protected function write_cb; +protected function write_oob_cb; +protected function close_cb; + +//! @seealso +//! @[Stdio.File()->close()] +int close(void|string direction) { + direction = lower_case(direction||"rw"); + int cr = has_value(direction, "r"); + int cw = has_value(direction, "w"); + + if(cr) { + r = 0; + } + + if(cw) { + w = 0; + } + + // FIXME: Close callback + return 1; +} + +//! @decl void create(string data, void|string type, void|int pointer) +//! @seealso +//! @[Stdio.File()->create()] +void create(string _data, void|string type, int|void _ptr) { + if(!_data) error("No data string given to FakeFile.\n"); + data = _data; + ptr = _ptr; + mtime = time(); + if(type) { + type = lower_case(type); + if(has_value(type, "r")) + r = 1; + if(has_value(type, "w")) + w = 1; + } + else + r = w = 1; +} + +protected string make_type_str() { + string type = ""; + if(r) type += "r"; + if(w) type += "w"; + return type; +} + +//! @seealso +//! @[Stdio.File()->dup()] +this_program dup() { + return this_program(data, make_type_str(), ptr); +} + +//! Always returns 0. +//! @seealso +//! @[Stdio.File()->errno()] +int errno() { return 0; } + +//! Returns size and the creation time of the string. +Stdio.Stat stat() { + Stdio.Stat st = Stdio.Stat(); + st->size = sizeof(data); + st->mtime=st->ctime=mtime; + st->atime=time(); + return st; +} + +//! @seealso +//! @[Stdio.File()->line_iterator()] +String.SplitIterator line_iterator(int|void trim) { + if(trim) + return String.SplitIterator( data-"\r", '\n' ); + return String.SplitIterator( data, '\n' ); +} + +protected mixed id; + +//! @seealso +//! @[Stdio.File()->query_id()] +mixed query_id() { return id; } + +//! @seealso +//! @[Stdio.File()->set_id()] +void set_id(mixed _id) { id = _id; } + +//! @seealso +//! @[Stdio.File()->read_function()] +function(:string) read_function(int nbytes) { + return lambda() { return read(nbytes); }; +} + +//! @seealso +//! @[Stdio.File()->peek()] +int(-1..1) peek(int|float|void timeout) { + if(!r) return -1; + if(ptr >= sizeof(data)) return 0; + return 1; +} + +//! Always returns 0. +//! @seealso +//! @[Stdio.File()->query_address()] +string query_address(void|int(0..1) is_local) { return 0; } + +//! @seealso +//! @[Stdio.File()->read()] +string read(void|int(0..) len, void|int(0..1) not_all) { + if(!r) return 0; + if (len < 0) error("Cannot read negative number of characters.\n"); + int start=ptr; + ptr += len; + if(zero_type(len) || ptr>sizeof(data)) + ptr = sizeof(data); + + // FIXME: read callback + return data[start..ptr-1]; +} + +//! @seealso +//! @[Stdio.FILE()->gets()] +string gets() { + if(!r) return 0; + string ret; + sscanf(data,"%*"+(string)ptr+"s%[^\n]",ret); + if(ret) + { + ptr+=sizeof(ret)+1; + if(ptr>sizeof(data)) + { + ptr=sizeof(data); + if(!sizeof(ret)) + ret = 0; + } + } + + // FIXME: read callback + return ret; +} + +//! @seealso +//! @[Stdio.FILE()->getchar()] +int getchar() { + if(!r) return 0; + int c; + if(catch(c=data[ptr])) + c=-1; + else + ptr++; + + // FIXME: read callback + return c; +} + +//! @seealso +//! @[Stdio.FILE()->unread()] +void unread(string s) { + if(!r) return; + if(data[ptr-sizeof(s)..ptr-1]==s) + ptr-=sizeof(s); + else + { + data=s+data[ptr..]; + ptr=0; + } +} + +//! @seealso +//! @[Stdio.File()->seek()] +int seek(int pos, void|int mult, void|int add) { + if(mult) + pos = pos*mult+add; + if(pos<0) + { + pos = sizeof(data)+pos; + if( pos < 0 ) + pos = 0; + } + ptr = pos; + if( ptr > strlen( data ) ) + ptr = strlen(data); + return ptr; +} + +//! Always returns 1. +//! @seealso +//! @[Stdio.File()->sync()] +int(1..1) sync() { return 1; } + +//! @seealso +//! @[Stdio.File()->tell()] +int tell() { return ptr; } + +//! @seealso +//! @[Stdio.File()->truncate()] +int(0..1) truncate(int length) { + data = data[..length-1]; + return sizeof(data)==length; +} + +//! @seealso +//! @[Stdio.File()->write()] +int(-1..) write(string|array(string) str, mixed ... extra) { + if(!w) return -1; + if(arrayp(str)) str=str*""; + if(sizeof(extra)) str=sprintf(str, @extra); + + if(ptr==sizeof(data)) { + data += str; + ptr = sizeof(data); + } + else if(sizeof(str)==1) + data[ptr++] = str[0]; + else { + data = data[..ptr-1] + str + data[ptr+sizeof(str)..]; + ptr += sizeof(str); + } + + // FIXME: write callback + return sizeof(str); +} + +//! @seealso +//! @[Stdio.File()->set_blocking] +void set_blocking() { + close_cb = 0; + read_cb = 0; + read_oob_cb = 0; + write_cb = 0; + write_oob_cb = 0; +} + +//! @seealso +//! @[Stdio.File()->set_blocking_keep_callbacks] +void set_blocking_keep_callbacks() { } + +//! @seealso +//! @[Stdio.File()->set_blocking] +void set_nonblocking(function rcb, function wcb, function ccb, + function rocb, function wocb) { + read_cb = rcb; + write_cb = wcb; + close_cb = ccb; + read_oob_cb = rocb; + write_oob_cb = wocb; +} + +//! @seealso +//! @[Stdio.File()->set_blocking_keep_callbacks] +void set_nonblocking_keep_callbacks() { } + + +//! @seealso +//! @[Stdio.File()->set_close_callback] +void set_close_callback(function cb) { close_cb = cb; } + +//! @seealso +//! @[Stdio.File()->set_read_callback] +void set_read_callback(function cb) { read_cb = cb; } + +//! @seealso +//! @[Stdio.File()->set_read_oob_callback] +void set_read_oob_callback(function cb) { read_oob_cb = cb; } + +//! @seealso +//! @[Stdio.File()->set_write_callback] +void set_write_callback(function cb) { write_cb = cb; } + +//! @seealso +//! @[Stdio.File()->set_write_oob_callback] +void set_write_oob_callback(function cb) { write_oob_cb = cb; } + + +//! @seealso +//! @[Stdio.File()->query_close_callback] +function query_close_callback() { return close_cb; } + +//! @seealso +//! @[Stdio.File()->query_read_callback] +function query_read_callback() { return read_cb; } + +//! @seealso +//! @[Stdio.File()->query_read_oob_callback] +function query_read_oob_callback() { return read_oob_cb; } + +//! @seealso +//! @[Stdio.File()->query_write_callback] +function query_write_callback() { return write_cb; } + +//! @seealso +//! @[Stdio.File()->query_write_oob_callback] +function query_write_oob_callback() { return write_oob_cb; } + +string _sprintf(int t) { + return t=='O' && sprintf("%O(%d,%O)", this_program, sizeof(data), + make_type_str()); +} + + +// FakeFile specials. + +//! A FakeFile can be casted to a string. +mixed cast(string to) { + switch(to) { + case "string": return data; + case "object": return this; + } + error("Can not cast object to %O.\n", to); +} + +//! Sizeof on a FakeFile returns the size of its contents. +int(0..) _sizeof() { + return sizeof(data); +} + +//! @ignore + +#define NOPE(X) mixed X (mixed ... args) { error("This is a FakeFile. %s is not available.\n", #X); } +NOPE(assign); +NOPE(async_connect); +NOPE(connect); +NOPE(connect_unix); +NOPE(open); +NOPE(open_socket); +NOPE(pipe); +NOPE(tcgetattr); +NOPE(tcsetattr); + +// Stdio.Fd +NOPE(dup2); +NOPE(lock); // We could implement this +NOPE(mode); // We could implement this +NOPE(proxy); // We could implement this +NOPE(query_fd); +NOPE(read_oob); +NOPE(set_close_on_exec); +NOPE(set_keepalive); +NOPE(trylock); // We could implement this +NOPE(write_oob); + +//! @endignore
\ No newline at end of file diff --git a/tests/examplefiles/Get-CommandDefinitionHtml.ps1 b/tests/examplefiles/Get-CommandDefinitionHtml.ps1 new file mode 100644 index 00000000..b181955f --- /dev/null +++ b/tests/examplefiles/Get-CommandDefinitionHtml.ps1 @@ -0,0 +1,66 @@ +
+function Get-CommandDefinitionHtml {
+
+ # this tells powershell to allow advanced features,
+ # like the [validatenotnullorempty()] attribute below.
+ [CmdletBinding()]
+ param(
+ [ValidateNotNullOrEmpty()]
+ [string]$name
+ )
+
+ $command = get-command $name
+
+ # Look mom! I'm a cmdlet!
+ $PSCmdlet.WriteVerbose("Dumping HTML for " + $command)
+
+@"
+ <html>
+ <head>
+ <title>$($command.name)</title>
+ </head>
+ <body>
+ <table border="1">
+$(
+ $command.parametersets | % {
+@"
+
+ <tr>
+ <td>$($_.name)</td>
+ <td>
+ <table border="1">
+ <tr>
+ <th colspan="8">Parameters</th>
+
+$(
+ $count = 0
+ $_.parameters | % {
+ if (0 -eq ($count % 8)) {
+@'
+ </tr>
+ <tr>
+'@
+ }
+@"
+ <td>$($_.name)</td>
+"@
+ $count++
+ }
+)
+ </tr>
+ </table>
+ </td>
+ </tr>
+"@
+ }
+)
+ </table>
+ </body>
+ </html>
+"@
+}
+
+Get-CommandDefinitionHtml get-item > out.html
+
+# show in browser
+invoke-item out.html
diff --git a/tests/examplefiles/IPDispatchC.nc b/tests/examplefiles/IPDispatchC.nc new file mode 100644 index 00000000..95a61a2c --- /dev/null +++ b/tests/examplefiles/IPDispatchC.nc @@ -0,0 +1,104 @@ +/* + * "Copyright (c) 2008-2011 The Regents of the University of California. + * All rights reserved." + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose, without fee, and without written agreement is + * hereby granted, provided that the above copyright notice, the following + * two paragraphs and the author appear in all copies of this software. + * + * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT + * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF + * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." + * + */ + +/** + * + * + */ +#include "IPDispatch.h" +#include "BlipStatistics.h" + +configuration IPDispatchC { + provides { + interface SplitControl; + interface IPLower; + interface BlipStatistics<ip_statistics_t>; + } +} implementation { + + components MainC; + components NoLedsC as LedsC; + + /* IPDispatchP wiring -- fragment rassembly and lib6lowpan bindings */ + components IPDispatchP; + components CC2420RadioC as MessageC; + components ReadLqiC; + components new TimerMilliC(); + + SplitControl = IPDispatchP.SplitControl; + IPLower = IPDispatchP; + BlipStatistics = IPDispatchP; + + IPDispatchP.Boot -> MainC; +/* #else */ +/* components ResourceSendP; */ +/* ResourceSendP.SubSend -> MessageC; */ +/* ResourceSendP.Resource -> MessageC.SendResource[unique("RADIO_SEND_RESOURCE")]; */ +/* IPDispatchP.Ieee154Send -> ResourceSendP.Ieee154Send; */ +/* #endif */ + IPDispatchP.RadioControl -> MessageC; + + IPDispatchP.BarePacket -> MessageC.BarePacket; + IPDispatchP.Ieee154Send -> MessageC.BareSend; + IPDispatchP.Ieee154Receive -> MessageC.BareReceive; + +#ifdef LOW_POWER_LISTENING + IPDispatchP.LowPowerListening -> MessageC; +#endif + MainC.SoftwareInit -> IPDispatchP.Init; + + IPDispatchP.PacketLink -> MessageC; + IPDispatchP.ReadLqi -> ReadLqiC; + IPDispatchP.Leds -> LedsC; + IPDispatchP.ExpireTimer -> TimerMilliC; + + components new PoolC(message_t, N_FRAGMENTS) as FragPool; + components new PoolC(struct send_entry, N_FRAGMENTS) as SendEntryPool; + components new QueueC(struct send_entry *, N_FRAGMENTS); + components new PoolC(struct send_info, N_CONCURRENT_SENDS) as SendInfoPool; + + IPDispatchP.FragPool -> FragPool; + IPDispatchP.SendEntryPool -> SendEntryPool; + IPDispatchP.SendInfoPool -> SendInfoPool; + IPDispatchP.SendQueue -> QueueC; + + components IPNeighborDiscoveryP; + IPDispatchP.NeighborDiscovery -> IPNeighborDiscoveryP; + +/* components ICMPResponderC; */ +/* #ifdef BLIP_MULTICAST */ +/* components MulticastP; */ +/* components new TrickleTimerMilliC(2, 30, 2, 1); */ +/* IP = MulticastP.IP; */ + +/* MainC.SoftwareInit -> MulticastP.Init; */ +/* MulticastP.MulticastRx -> IPDispatchP.Multicast; */ +/* MulticastP.HopHeader -> IPExtensionP.HopByHopExt[0]; */ +/* MulticastP.TrickleTimer -> TrickleTimerMilliC.TrickleTimer[0]; */ +/* MulticastP.IPExtensions -> IPDispatchP; */ +/* #endif */ + +#ifdef DELUGE + components NWProgC; +#endif + +} diff --git a/tests/examplefiles/IPDispatchP.nc b/tests/examplefiles/IPDispatchP.nc new file mode 100644 index 00000000..628f39a0 --- /dev/null +++ b/tests/examplefiles/IPDispatchP.nc @@ -0,0 +1,671 @@ +/* + * "Copyright (c) 2008 The Regents of the University of California. + * All rights reserved." + * + * Permission to use, copy, modify, and distribute this software and its + * documentation for any purpose, without fee, and without written agreement is + * hereby granted, provided that the above copyright notice, the following + * two paragraphs and the author appear in all copies of this software. + * + * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR + * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT + * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF + * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES, + * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY + * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS + * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO + * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS." + * + */ + +#include <lib6lowpan/blip-tinyos-includes.h> +#include <lib6lowpan/6lowpan.h> +#include <lib6lowpan/lib6lowpan.h> +#include <lib6lowpan/ip.h> +#include <lib6lowpan/in_cksum.h> +#include <lib6lowpan/ip_malloc.h> + +#include "blip_printf.h" +#include "IPDispatch.h" +#include "BlipStatistics.h" +#include "table.h" + +/* + * Provides IP layer reception to applications on motes. + * + * @author Stephen Dawson-Haggerty <stevedh@cs.berkeley.edu> + */ + +module IPDispatchP { + provides { + interface SplitControl; + // interface for protocols not requiring special hand-holding + interface IPLower; + + interface BlipStatistics<ip_statistics_t>; + + } + uses { + interface Boot; + + + /* link-layer wiring */ + interface SplitControl as RadioControl; + + interface Packet as BarePacket; + interface Send as Ieee154Send; + interface Receive as Ieee154Receive; + + /* context lookup */ + interface NeighborDiscovery; + + interface ReadLqi; + interface PacketLink; + interface LowPowerListening; + + /* buffers for outgoing fragments */ + interface Pool<message_t> as FragPool; + interface Pool<struct send_info> as SendInfoPool; + interface Pool<struct send_entry> as SendEntryPool; + interface Queue<struct send_entry *> as SendQueue; + + /* expire reconstruction */ + interface Timer<TMilli> as ExpireTimer; + + interface Leds; + + } + provides interface Init; +} implementation { + +#define HAVE_LOWPAN_EXTERN_MATCH_CONTEXT +int lowpan_extern_read_context(struct in6_addr *addr, int context) { + return call NeighborDiscovery.getContext(context, addr); +} + +int lowpan_extern_match_context(struct in6_addr *addr, uint8_t *ctx_id) { + return call NeighborDiscovery.matchContext(addr, ctx_id); +} + + // generally including source files like this is a no-no. I'm doing + // this in the hope that the optimizer will do a better job when + // they're part of a component. +#include <lib6lowpan/ieee154_header.c> +#include <lib6lowpan/lib6lowpan.c> +#include <lib6lowpan/lib6lowpan_4944.c> +#include <lib6lowpan/lib6lowpan_frag.c> + + enum { + S_RUNNING, + S_STOPPED, + S_STOPPING, + }; + uint8_t state = S_STOPPED; + bool radioBusy; + uint8_t current_local_label = 0; + ip_statistics_t stats; + + // this in theory could be arbitrarily large; however, it needs to + // be large enough to hold all active reconstructions, and any tags + // which we are dropping. It's important to keep dropped tags + // around for a while, or else there are pathological situations + // where you continually allocate buffers for packets which will + // never complete. + + //////////////////////////////////////// + // + // + + table_t recon_cache; + + // table of packets we are currently receiving fragments from, that + // are destined to us + struct lowpan_reconstruct recon_data[N_RECONSTRUCTIONS]; + + // + // + //////////////////////////////////////// + + // task void sendTask(); + + void reconstruct_clear(void *ent) { + struct lowpan_reconstruct *recon = (struct lowpan_reconstruct *)ent; + memclr((uint8_t *)&recon->r_meta, sizeof(struct ip6_metadata)); + recon->r_timeout = T_UNUSED; + recon->r_buf = NULL; + } + + struct send_info *getSendInfo() { + struct send_info *ret = call SendInfoPool.get(); + if (ret == NULL) return ret; + ret->_refcount = 1; + ret->upper_data = NULL; + ret->failed = FALSE; + ret->link_transmissions = 0; + ret->link_fragments = 0; + ret->link_fragment_attempts = 0; + return ret; + } +#define SENDINFO_INCR(X) ((X)->_refcount)++ +void SENDINFO_DECR(struct send_info *si) { + if (--(si->_refcount) == 0) { + call SendInfoPool.put(si); + } +} + + command error_t SplitControl.start() { + return call RadioControl.start(); + } + + command error_t SplitControl.stop() { + if (!radioBusy) { + state = S_STOPPED; + return call RadioControl.stop(); + } else { + // if there's a packet in the radio, wait for it to exit before + // stopping + state = S_STOPPING; + return SUCCESS; + } + } + + event void RadioControl.startDone(error_t error) { +#ifdef LPL_SLEEP_INTERVAL + call LowPowerListening.setLocalWakeupInterval(LPL_SLEEP_INTERVAL); +#endif + + if (error == SUCCESS) { + call Leds.led2Toggle(); + call ExpireTimer.startPeriodic(FRAG_EXPIRE_TIME); + state = S_RUNNING; + radioBusy = FALSE; + } + + signal SplitControl.startDone(error); + } + + event void RadioControl.stopDone(error_t error) { + signal SplitControl.stopDone(error); + } + + command error_t Init.init() { + // ip_malloc_init needs to be in init, not booted, because + // context for coap is initialised in init + ip_malloc_init(); + return SUCCESS; + } + + event void Boot.booted() { + call BlipStatistics.clear(); + + /* set up our reconstruction cache */ + table_init(&recon_cache, recon_data, sizeof(struct lowpan_reconstruct), N_RECONSTRUCTIONS); + table_map(&recon_cache, reconstruct_clear); + + call SplitControl.start(); + } + + /* + * Receive-side code. + */ + void deliver(struct lowpan_reconstruct *recon) { + struct ip6_hdr *iph = (struct ip6_hdr *)recon->r_buf; + + // printf("deliver [%i]: ", recon->r_bytes_rcvd); + // printf_buf(recon->r_buf, recon->r_bytes_rcvd); + + /* the payload length field is always compressed, have to put it back here */ + iph->ip6_plen = htons(recon->r_bytes_rcvd - sizeof(struct ip6_hdr)); + signal IPLower.recv(iph, (void *)(iph + 1), &recon->r_meta); + + // printf("ip_free(%p)\n", recon->r_buf); + ip_free(recon->r_buf); + recon->r_timeout = T_UNUSED; + recon->r_buf = NULL; + } + + /* + * Bulletproof recovery logic is very important to make sure we + * don't get wedged with no free buffers. + * + * The table is managed as follows: + * - unused entries are marked T_UNUSED + * - entries which + * o have a buffer allocated + * o have had a fragment reception before we fired + * are marked T_ACTIVE + * - entries which have not had a fragment reception during the last timer period + * and were active are marked T_ZOMBIE + * - zombie receptions are deleted: their buffer is freed and table entry marked unused. + * - when a fragment is dropped, it is entered into the table as T_FAILED1. + * no buffer is allocated + * - when the timer fires, T_FAILED1 entries are aged to T_FAILED2. + * - T_FAILED2 entries are deleted. Incomming fragments with tags + * that are marked either FAILED1 or FAILED2 are dropped; this + * prevents us from allocating a buffer for a packet which we + * have already dropped fragments from. + * + */ + void reconstruct_age(void *elt) { + struct lowpan_reconstruct *recon = (struct lowpan_reconstruct *)elt; + if (recon->r_timeout != T_UNUSED) + printf("recon src: 0x%x tag: 0x%x buf: %p recvd: %i/%i\n", + recon->r_source_key, recon->r_tag, recon->r_buf, + recon->r_bytes_rcvd, recon->r_size); + switch (recon->r_timeout) { + case T_ACTIVE: + recon->r_timeout = T_ZOMBIE; break; // age existing receptions + case T_FAILED1: + recon->r_timeout = T_FAILED2; break; // age existing receptions + case T_ZOMBIE: + case T_FAILED2: + // deallocate the space for reconstruction + printf("timing out buffer: src: %i tag: %i\n", recon->r_source_key, recon->r_tag); + if (recon->r_buf != NULL) { + printf("ip_free(%p)\n", recon->r_buf); + ip_free(recon->r_buf); + } + recon->r_timeout = T_UNUSED; + recon->r_buf = NULL; + break; + } + } + + void ip_print_heap() { +#ifdef PRINTFUART_ENABLED + bndrt_t *cur = (bndrt_t *)heap; + while (((uint8_t *)cur) - heap < IP_MALLOC_HEAP_SIZE) { + printf ("heap region start: %p length: %u used: %u\n", + cur, (*cur & IP_MALLOC_LEN), (*cur & IP_MALLOC_INUSE) >> 15); + cur = (bndrt_t *)(((uint8_t *)cur) + ((*cur) & IP_MALLOC_LEN)); + } +#endif + } + + event void ExpireTimer.fired() { + table_map(&recon_cache, reconstruct_age); + + + printf("Frag pool size: %i\n", call FragPool.size()); + printf("SendInfo pool size: %i\n", call SendInfoPool.size()); + printf("SendEntry pool size: %i\n", call SendEntryPool.size()); + printf("Forward queue length: %i\n", call SendQueue.size()); + ip_print_heap(); + printfflush(); + } + + /* + * allocate a structure for recording information about incomming fragments. + */ + + struct lowpan_reconstruct *get_reconstruct(uint16_t key, uint16_t tag) { + struct lowpan_reconstruct *ret = NULL; + int i; + + // printf("get_reconstruct: %x %i\n", key, tag); + + for (i = 0; i < N_RECONSTRUCTIONS; i++) { + struct lowpan_reconstruct *recon = (struct lowpan_reconstruct *)&recon_data[i]; + + if (recon->r_tag == tag && + recon->r_source_key == key) { + + if (recon->r_timeout > T_UNUSED) { + recon->r_timeout = T_ACTIVE; + ret = recon; + goto done; + + } else if (recon->r_timeout < T_UNUSED) { + // if we have already tried and failed to get a buffer, we + // need to drop remaining fragments. + ret = NULL; + goto done; + } + } + if (recon->r_timeout == T_UNUSED) + ret = recon; + } + done: + // printf("got%p\n", ret); + return ret; + } + + event message_t *Ieee154Receive.receive(message_t *msg, void *msg_payload, uint8_t len) { + struct packed_lowmsg lowmsg; + struct ieee154_frame_addr frame_address; + uint8_t *buf = msg_payload; + + // printf(" -- RECEIVE -- len : %i\n", len); + + BLIP_STATS_INCR(stats.rx_total); + + /* unpack the 802.15.4 address fields */ + buf = unpack_ieee154_hdr(msg_payload, &frame_address); + len -= buf - (uint8_t *)msg_payload; + + /* unpack and 6lowpan headers */ + lowmsg.data = buf; + lowmsg.len = len; + lowmsg.headers = getHeaderBitmap(&lowmsg); + if (lowmsg.headers == LOWMSG_NALP) { + goto fail; + } + + if (hasFrag1Header(&lowmsg) || hasFragNHeader(&lowmsg)) { + // start reassembly + int rv; + struct lowpan_reconstruct *recon; + uint16_t tag, source_key; + + source_key = ieee154_hashaddr(&frame_address.ieee_src); + getFragDgramTag(&lowmsg, &tag); + recon = get_reconstruct(source_key, tag); + if (!recon) { + goto fail; + } + + /* fill in metadata: on fragmented packets, it applies to the + first fragment only */ + memcpy(&recon->r_meta.sender, &frame_address.ieee_src, + sizeof(ieee154_addr_t)); + recon->r_meta.lqi = call ReadLqi.readLqi(msg); + recon->r_meta.rssi = call ReadLqi.readRssi(msg); + + if (hasFrag1Header(&lowmsg)) { + if (recon->r_buf != NULL) goto fail; + rv = lowpan_recon_start(&frame_address, recon, buf, len); + } else { + rv = lowpan_recon_add(recon, buf, len); + } + + if (rv < 0) { + recon->r_timeout = T_FAILED1; + goto fail; + } else { + // printf("start recon buf: %p\n", recon->r_buf); + recon->r_timeout = T_ACTIVE; + recon->r_source_key = source_key; + recon->r_tag = tag; + } + + if (recon->r_size == recon->r_bytes_rcvd) { + deliver(recon); + } + + } else { + /* no fragmentation, just deliver it */ + int rv; + struct lowpan_reconstruct recon; + + /* fill in metadata */ + memcpy(&recon.r_meta.sender, &frame_address.ieee_src, + sizeof(ieee154_addr_t)); + recon.r_meta.lqi = call ReadLqi.readLqi(msg); + recon.r_meta.rssi = call ReadLqi.readRssi(msg); + + buf = getLowpanPayload(&lowmsg); + if ((rv = lowpan_recon_start(&frame_address, &recon, buf, len)) < 0) { + goto fail; + } + + if (recon.r_size == recon.r_bytes_rcvd) { + deliver(&recon); + } else { + // printf("ip_free(%p)\n", recon.r_buf); + ip_free(recon.r_buf); + } + } + goto done; + fail: + BLIP_STATS_INCR(stats.rx_drop); + done: + return msg; + } + + + /* + * Send-side functionality + */ + task void sendTask() { + struct send_entry *s_entry; + + // printf("sendTask() - sending\n"); + + if (radioBusy || state != S_RUNNING) return; + if (call SendQueue.empty()) return; + // this does not dequeue + s_entry = call SendQueue.head(); + +#ifdef LPL_SLEEP_INTERVAL + call LowPowerListening.setRemoteWakeupInterval(s_entry->msg, + call LowPowerListening.getLocalWakeupInterval()); +#endif + + if (s_entry->info->failed) { + dbg("Drops", "drops: sendTask: dropping failed fragment\n"); + goto fail; + } + + if ((call Ieee154Send.send(s_entry->msg, + call BarePacket.payloadLength(s_entry->msg))) != SUCCESS) { + dbg("Drops", "drops: sendTask: send failed\n"); + goto fail; + } else { + radioBusy = TRUE; + } + + return; + fail: + printf("SEND FAIL\n"); + post sendTask(); + BLIP_STATS_INCR(stats.tx_drop); + + // deallocate the memory associated with this request. + // other fragments associated with this packet will get dropped. + s_entry->info->failed = TRUE; + SENDINFO_DECR(s_entry->info); + call FragPool.put(s_entry->msg); + call SendEntryPool.put(s_entry); + call SendQueue.dequeue(); + } + + + /* + * it will pack the message into the fragment pool and enqueue + * those fragments for sending + * + * it will set + * - payload length + * - version, traffic class and flow label + * + * the source and destination IP addresses must be set by higher + * layers. + */ + command error_t IPLower.send(struct ieee154_frame_addr *frame_addr, + struct ip6_packet *msg, + void *data) { + struct lowpan_ctx ctx; + struct send_info *s_info; + struct send_entry *s_entry; + message_t *outgoing; + + int frag_len = 1; + error_t rc = SUCCESS; + + if (state != S_RUNNING) { + return EOFF; + } + + /* set version to 6 in case upper layers forgot */ + msg->ip6_hdr.ip6_vfc &= ~IPV6_VERSION_MASK; + msg->ip6_hdr.ip6_vfc |= IPV6_VERSION; + + ctx.tag = current_local_label++; + ctx.offset = 0; + + s_info = getSendInfo(); + if (s_info == NULL) { + rc = ERETRY; + goto cleanup_outer; + } + s_info->upper_data = data; + + while (frag_len > 0) { + s_entry = call SendEntryPool.get(); + outgoing = call FragPool.get(); + + if (s_entry == NULL || outgoing == NULL) { + if (s_entry != NULL) + call SendEntryPool.put(s_entry); + if (outgoing != NULL) + call FragPool.put(outgoing); + // this will cause any fragments we have already enqueued to + // be dropped by the send task. + s_info->failed = TRUE; + printf("drops: IP send: no fragments\n"); + rc = ERETRY; + goto done; + } + + call BarePacket.clear(outgoing); + frag_len = lowpan_frag_get(call Ieee154Send.getPayload(outgoing, 0), + call BarePacket.maxPayloadLength(), + msg, + frame_addr, + &ctx); + if (frag_len < 0) { + printf(" get frag error: %i\n", frag_len); + } + + printf("fragment length: %i offset: %i\n", frag_len, ctx.offset); + call BarePacket.setPayloadLength(outgoing, frag_len); + + if (frag_len <= 0) { + call FragPool.put(outgoing); + call SendEntryPool.put(s_entry); + goto done; + } + + if (call SendQueue.enqueue(s_entry) != SUCCESS) { + BLIP_STATS_INCR(stats.encfail); + s_info->failed = TRUE; + printf("drops: IP send: enqueue failed\n"); + goto done; + } + + s_info->link_fragments++; + s_entry->msg = outgoing; + s_entry->info = s_info; + + /* configure the L2 */ + if (frame_addr->ieee_dst.ieee_mode == IEEE154_ADDR_SHORT && + frame_addr->ieee_dst.i_saddr == IEEE154_BROADCAST_ADDR) { + call PacketLink.setRetries(s_entry->msg, 0); + } else { + call PacketLink.setRetries(s_entry->msg, BLIP_L2_RETRIES); + } + call PacketLink.setRetryDelay(s_entry->msg, BLIP_L2_DELAY); + + SENDINFO_INCR(s_info);} + + // printf("got %i frags\n", s_info->link_fragments); + done: + BLIP_STATS_INCR(stats.sent); + SENDINFO_DECR(s_info); + post sendTask(); + cleanup_outer: + return rc; + } + + event void Ieee154Send.sendDone(message_t *msg, error_t error) { + struct send_entry *s_entry = call SendQueue.head(); + + radioBusy = FALSE; + + // printf("sendDone: %p %i\n", msg, error); + + if (state == S_STOPPING) { + call RadioControl.stop(); + state = S_STOPPED; + goto done; + } + + s_entry->info->link_transmissions += (call PacketLink.getRetries(msg)); + s_entry->info->link_fragment_attempts++; + + if (!call PacketLink.wasDelivered(msg)) { + printf("sendDone: was not delivered! (%i tries)\n", + call PacketLink.getRetries(msg)); + s_entry->info->failed = TRUE; + signal IPLower.sendDone(s_entry->info); +/* if (s_entry->info->policy.dest[0] != 0xffff) */ +/* dbg("Drops", "drops: sendDone: frag was not delivered\n"); */ + // need to check for broadcast frames + // BLIP_STATS_INCR(stats.tx_drop); + } else if (s_entry->info->link_fragment_attempts == + s_entry->info->link_fragments) { + signal IPLower.sendDone(s_entry->info); + } + + done: + // kill off any pending fragments + SENDINFO_DECR(s_entry->info); + call FragPool.put(s_entry->msg); + call SendEntryPool.put(s_entry); + call SendQueue.dequeue(); + + post sendTask(); + } + +#if 0 + command struct tlv_hdr *IPExtensions.findTlv(struct ip6_ext *ext, uint8_t tlv_val) { + int len = ext->len - sizeof(struct ip6_ext); + struct tlv_hdr *tlv = (struct tlv_hdr *)(ext + 1); + while (len > 0) { + if (tlv->type == tlv_val) return tlv; + if (tlv->len == 0) return NULL; + tlv = (struct tlv_hdr *)(((uint8_t *)tlv) + tlv->len); + len -= tlv->len; + } + return NULL; + } +#endif + + + /* + * BlipStatistics interface + */ + command void BlipStatistics.get(ip_statistics_t *statistics) { +#ifdef BLIP_STATS_IP_MEM + stats.fragpool = call FragPool.size(); + stats.sendinfo = call SendInfoPool.size(); + stats.sendentry= call SendEntryPool.size(); + stats.sndqueue = call SendQueue.size(); + stats.heapfree = ip_malloc_freespace(); + printf("frag: %i sendinfo: %i sendentry: %i sendqueue: %i heap: %i\n", + stats.fragpool, + stats.sendinfo, + stats.sendentry, + stats.sndqueue, + stats.heapfree); +#endif + memcpy(statistics, &stats, sizeof(ip_statistics_t)); + + } + + command void BlipStatistics.clear() { + memclr((uint8_t *)&stats, sizeof(ip_statistics_t)); + } + +/* default event void IP.recv[uint8_t nxt_hdr](struct ip6_hdr *iph, */ +/* void *payload, */ +/* struct ip_metadata *meta) { */ +/* } */ + +/* default event void Multicast.recv[uint8_t scope](struct ip6_hdr *iph, */ +/* void *payload, */ +/* struct ip_metadata *meta) { */ +/* } */ +} diff --git a/tests/examplefiles/RoleQ.pm6 b/tests/examplefiles/RoleQ.pm6 new file mode 100644 index 00000000..9b66bde4 --- /dev/null +++ b/tests/examplefiles/RoleQ.pm6 @@ -0,0 +1,23 @@ +role q { + token stopper { \' } + + token escape:sym<\\> { <sym> <item=.backslash> } + + token backslash:sym<qq> { <?before 'q'> <quote=.LANG('MAIN','quote')> } + token backslash:sym<\\> { <text=.sym> } + token backslash:sym<stopper> { <text=.stopper> } + + token backslash:sym<miscq> { {} . } + + method tweak_q($v) { self.panic("Too late for :q") } + method tweak_qq($v) { self.panic("Too late for :qq") } +} + +role qq does b1 does c1 does s1 does a1 does h1 does f1 { + token stopper { \" } + token backslash:sym<unrec> { {} (\w) { self.throw_unrecog_backslash_seq: $/[0].Str } } + token backslash:sym<misc> { \W } + + method tweak_q($v) { self.panic("Too late for :q") } + method tweak_qq($v) { self.panic("Too late for :qq") } +} diff --git a/tests/examplefiles/ANTLRv3.g b/tests/examplefiles/antlr_ANTLRv3.g index fbe6d654..fbe6d654 100644 --- a/tests/examplefiles/ANTLRv3.g +++ b/tests/examplefiles/antlr_ANTLRv3.g diff --git a/tests/examplefiles/antlr_throws b/tests/examplefiles/antlr_throws new file mode 100644 index 00000000..816d8914 --- /dev/null +++ b/tests/examplefiles/antlr_throws @@ -0,0 +1 @@ +public f throws a, b, c : x ; diff --git a/tests/examplefiles/as3_test.as b/tests/examplefiles/as3_test.as index 7e19f887..d6b08424 100644 --- a/tests/examplefiles/as3_test.as +++ b/tests/examplefiles/as3_test.as @@ -7,7 +7,7 @@ private static const ADD_SONG:uint = 1; private static const SONG_DETAIL:uint = 2; - private var playList:PlayList = new PlayList(); + private var playList:PlayList = new PlayList.<T>(); private function initApp():void { @@ -24,7 +24,7 @@ } - private function sortList(sortField:SortProperty):void + private function sortList(sortField:SortProperty.<T>):void { // Make all the sort type buttons enabled. // The active one will be grayed-out below diff --git a/tests/examplefiles/autoit_submit.au3 b/tests/examplefiles/autoit_submit.au3 new file mode 100644 index 00000000..e5054dea --- /dev/null +++ b/tests/examplefiles/autoit_submit.au3 @@ -0,0 +1,25 @@ +#include <IE.au3>
+;http://msdn.microsoft.com/en-us/library/Aa752084.aspx
+$ourl="http://localhost:5000/"
+
+$oIE = _IEAttach ($ourl,"url")
+If @error = $_IEStatus_NoMatch Then
+ $oIE = _IECreate ($ourl & "sample.html")
+endIf
+
+$oForm = _IEFormGetObjByName ($oIE, "form1")
+;username, call DOM directly
+$oIE.document.getElementById("username").value="helloAutoIT"
+;state select
+$oSelect = _IEFormElementGetObjByName ($oForm, "state")
+_IEFormElementOptionSelect ($oSelect, "S2", 1, "byText")
+;options raido
+_IEFormElementRadioSelect($oForm, "2nd", "type", 1, "byValue")
+
+ConsoleWrite(@Error)
+Sleep(10000)
+_IEFormSubmit($oForm, 0)
+_IELoadWait($oIE)
+Sleep(60000)
+_IEQuit($oIE)
+
diff --git a/tests/examplefiles/bigtest.nsi b/tests/examplefiles/bigtest.nsi new file mode 100644 index 00000000..62f5211c --- /dev/null +++ b/tests/examplefiles/bigtest.nsi @@ -0,0 +1,308 @@ +; bigtest.nsi +; +; This script attempts to test most of the functionality of the NSIS exehead. + +;-------------------------------- + +!ifdef HAVE_UPX +!packhdr tmp.dat "upx\upx -9 tmp.dat" +!endif + +!ifdef NOCOMPRESS +SetCompress off +!endif + +;-------------------------------- + +Name "BigNSISTest" +Caption "NSIS Big Test" +Icon "${NSISDIR}\Contrib\Graphics\Icons\nsis1-install.ico" +OutFile "bigtest.exe" + +SetDateSave on +SetDatablockOptimize on +CRCCheck on +SilentInstall normal +BGGradient 000000 800000 FFFFFF +InstallColors FF8080 000030 +XPStyle on + +InstallDir "$PROGRAMFILES\NSISTest\BigNSISTest" +InstallDirRegKey HKLM "Software\NSISTest\BigNSISTest" "Install_Dir" + +CheckBitmap "${NSISDIR}\Contrib\Graphics\Checks\classic-cross.bmp" + +LicenseText "A test text, make sure it's all there" +LicenseData "bigtest.nsi" + +RequestExecutionLevel admin + +;-------------------------------- + +Page license +Page components +Page directory +Page instfiles + +UninstPage uninstConfirm +UninstPage instfiles + +;-------------------------------- + +!ifndef NOINSTTYPES ; only if not defined + InstType "Most" + InstType "Full" + InstType "More" + InstType "Base" + ;InstType /NOCUSTOM + ;InstType /COMPONENTSONLYONCUSTOM +!endif + +AutoCloseWindow false +ShowInstDetails show + +;-------------------------------- + +Section "" ; empty string makes it hidden, so would starting with - + + ; write reg info + StrCpy $1 "POOOOOOOOOOOP" + DetailPrint "I like to be able to see what is going on (debug) $1" + WriteRegStr HKLM SOFTWARE\NSISTest\BigNSISTest "Install_Dir" "$INSTDIR" + + ; write uninstall strings + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\BigNSISTest" "DisplayName" "BigNSISTest (remove only)" + WriteRegStr HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\BigNSISTest" "UninstallString" '"$INSTDIR\bt-uninst.exe"' + + SetOutPath $INSTDIR + File /a "silent.nsi" + CreateDirectory "$INSTDIR\MyProjectFamily\MyProject" ; 2 recursively create a directory for fun. + WriteUninstaller "bt-uninst.exe" + + Nop ; for fun + +SectionEnd + +Section "TempTest" + +SectionIn 1 2 3 + Start: MessageBox MB_OK "Start:" + + MessageBox MB_YESNO "Goto MyLabel" IDYES MyLabel + + MessageBox MB_OK "Right before MyLabel:" + + MyLabel: MessageBox MB_OK "MyLabel:" + + MessageBox MB_OK "Right after MyLabel:" + + MessageBox MB_YESNO "Goto Start:?" IDYES Start + +SectionEnd + +SectionGroup /e SectionGroup1 + +Section "Test Registry/INI functions" + +SectionIn 1 4 3 + + WriteRegStr HKLM SOFTWARE\NSISTest\BigNSISTest "StrTest_INSTDIR" "$INSTDIR" + WriteRegDword HKLM SOFTWARE\NSISTest\BigNSISTest "DwordTest_0xDEADBEEF" 0xdeadbeef + WriteRegDword HKLM SOFTWARE\NSISTest\BigNSISTest "DwordTest_123456" 123456 + WriteRegDword HKLM SOFTWARE\NSISTest\BigNSISTest "DwordTest_0123" 0123 + WriteRegBin HKLM SOFTWARE\NSISTest\BigNSISTest "BinTest_deadbeef01f00dbeef" "DEADBEEF01F00DBEEF" + StrCpy $8 "$SYSDIR\IniTest" + WriteINIStr "$INSTDIR\test.ini" "MySection" "Value1" $8 + WriteINIStr "$INSTDIR\test.ini" "MySectionIni" "Value1" $8 + WriteINIStr "$INSTDIR\test.ini" "MySectionIni" "Value2" $8 + WriteINIStr "$INSTDIR\test.ini" "IniOn" "Value1" $8 + + Call MyFunctionTest + + DeleteINIStr "$INSTDIR\test.ini" "IniOn" "Value1" + DeleteINISec "$INSTDIR\test.ini" "MySectionIni" + + ReadINIStr $1 "$INSTDIR\test.ini" "MySectionIni" "Value1" + StrCmp $1 "" INIDelSuccess + MessageBox MB_OK "DeleteINISec failed" + INIDelSuccess: + + ClearErrors + ReadRegStr $1 HKCR "software\microsoft" xyz_cc_does_not_exist + IfErrors 0 NoError + MessageBox MB_OK "could not read from HKCR\software\microsoft\xyz_cc_does_not_exist" + Goto ErrorYay + NoError: + MessageBox MB_OK "read '$1' from HKCR\software\microsoft\xyz_cc_does_not_exist" + ErrorYay: + +SectionEnd + +Section "Test CreateShortCut" + + SectionIn 1 2 3 + + Call CSCTest + +SectionEnd + +SectionGroup Group2 + +Section "Test Branching" + + BeginTestSection: + SectionIn 1 2 3 + + SetOutPath $INSTDIR + + IfFileExists "$INSTDIR\LogicLib.nsi" 0 BranchTest69 + + MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to overwrite $INSTDIR\LogicLib.nsi?" IDNO NoOverwrite ; skipped if file doesn't exist + + BranchTest69: + + SetOverwrite ifnewer ; NOT AN INSTRUCTION, NOT COUNTED IN SKIPPINGS + + NoOverwrite: + + File "LogicLib.nsi" ; skipped if answered no + SetOverwrite try ; NOT AN INSTRUCTION, NOT COUNTED IN SKIPPINGS + + MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to skip the rest of this section?" IDYES EndTestBranch + MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to go back to the beginning of this section?" IDYES BeginTestSection + MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to hide the installer and wait five seconds?" IDNO NoHide + + HideWindow + Sleep 5000 + BringToFront + + NoHide: + + MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to call the function 5 times?" IDNO NoRecurse + + StrCpy $1 "x" + + LoopTest: + + Call myfunc + StrCpy $1 "x$1" + StrCmp $1 "xxxxxx" 0 LoopTest + + NoRecurse: + + EndTestBranch: + +SectionEnd + +SectionGroupEnd + +Section "Test CopyFiles" + + SectionIn 1 2 3 + + SetOutPath $INSTDIR\cpdest + CopyFiles "$WINDIR\*.ini" "$INSTDIR\cpdest" 0 + +SectionEnd + +SectionGroupEnd + +Section "Test Exec functions" TESTIDX + + SectionIn 1 2 3 + + SearchPath $1 notepad.exe + + MessageBox MB_OK "notepad.exe=$1" + Exec '"$1"' + ExecShell "open" '"$INSTDIR"' + Sleep 500 + BringToFront + +SectionEnd + +Section "Test ActiveX control registration" + + SectionIn 2 + + UnRegDLL "$SYSDIR\spin32.ocx" + Sleep 1000 + RegDLL "$SYSDIR\spin32.ocx" + Sleep 1000 + +SectionEnd + +;-------------------------------- + +Function "CSCTest" + + CreateDirectory "$SMPROGRAMS\Big NSIS Test" + SetOutPath $INSTDIR ; for working directory + CreateShortCut "$SMPROGRAMS\Big NSIS Test\Uninstall BIG NSIS Test.lnk" "$INSTDIR\bt-uninst.exe" ; use defaults for parameters, icon, etc. + ; this one will use notepad's icon, start it minimized, and give it a hotkey (of Ctrl+Shift+Q) + CreateShortCut "$SMPROGRAMS\Big NSIS Test\silent.nsi.lnk" "$INSTDIR\silent.nsi" "" "$WINDIR\notepad.exe" 0 SW_SHOWMINIMIZED CONTROL|SHIFT|Q + CreateShortCut "$SMPROGRAMS\Big NSIS Test\TheDir.lnk" "$INSTDIR\" "" "" 0 SW_SHOWMAXIMIZED CONTROL|SHIFT|Z + +FunctionEnd + +Function myfunc + + StrCpy $2 "MyTestVar=$1" + MessageBox MB_OK "myfunc: $2" + +FunctionEnd + +Function MyFunctionTest + + ReadINIStr $1 "$INSTDIR\test.ini" "MySectionIni" "Value1" + StrCmp $1 $8 NoFailedMsg + MessageBox MB_OK "WriteINIStr failed" + + NoFailedMsg: + +FunctionEnd + +Function .onSelChange + + SectionGetText ${TESTIDX} $0 + StrCmp $0 "" e + SectionSetText ${TESTIDX} "" + Goto e2 +e: + SectionSetText ${TESTIDX} "TextInSection" +e2: + +FunctionEnd + +;-------------------------------- + +; Uninstaller + +UninstallText "This will uninstall example2. Hit next to continue." +UninstallIcon "${NSISDIR}\Contrib\Graphics\Icons\nsis1-uninstall.ico" + +Section "Uninstall" + + DeleteRegKey HKLM "Software\Microsoft\Windows\CurrentVersion\Uninstall\BigNSISTest" + DeleteRegKey HKLM "SOFTWARE\NSISTest\BigNSISTest" + Delete "$INSTDIR\silent.nsi" + Delete "$INSTDIR\LogicLib.nsi" + Delete "$INSTDIR\bt-uninst.exe" + Delete "$INSTDIR\test.ini" + Delete "$SMPROGRAMS\Big NSIS Test\*.*" + RMDir "$SMPROGRAMS\BiG NSIS Test" + + MessageBox MB_YESNO|MB_ICONQUESTION "Would you like to remove the directory $INSTDIR\cpdest?" IDNO NoDelete + Delete "$INSTDIR\cpdest\*.*" + RMDir "$INSTDIR\cpdest" ; skipped if no + NoDelete: + + RMDir "$INSTDIR\MyProjectFamily\MyProject" + RMDir "$INSTDIR\MyProjectFamily" + RMDir "$INSTDIR" + + IfFileExists "$INSTDIR" 0 NoErrorMsg + MessageBox MB_OK "Note: $INSTDIR could not be removed!" IDOK 0 ; skipped if file doesn't exist + NoErrorMsg: + +SectionEnd diff --git a/tests/examplefiles/ca65_example b/tests/examplefiles/ca65_example new file mode 100644 index 00000000..67c6313e --- /dev/null +++ b/tests/examplefiles/ca65_example @@ -0,0 +1,284 @@ +;-------------------------------------- +; Lychrel numbers. +; +; :author: Marc 'BlackJack' Rintsch +; :date: 2008-03-07 +; :version: 0.1 +; +; Prints all `Lychrel numbers`_ between 1 and 100000. +; +; The numbers are stored as array of "digits" in little endian +; order. Each digit is a byte with a value between 0 and 9. +; +; Runtime on C64: 00:21:01 +; +; .. _Lychrel numbers: http://en.wikipedia.org/wiki/Lychrel_number +; +; .. cl65 -l -tnone -C simple.cfg lychrel.s -o lychrel.prg +;-------------------------------------- + +;-------------------------------------- +; External addresses. +;-------------------------------------- + chrout = $ffd2 + +;-------------------------------------- +; Constants. +;-------------------------------------- + TO = 100000 + TO_DIGITS = 10 + ITERATIONS = 100 + MAX_DIGITS = TO_DIGITS + ITERATIONS + +;-------------------------------------- +; Global variables. +;-------------------------------------- +.zeropage +; +; Length of the currently tested `n` in digits. +; +n_length: + .res 1 +; +; Length of the number(s) `xa` and `xb` while testing. +; +length: + .res 1 + +.bss +; +; Number to be tested as digits i.e. bytes with values between +; 0 and 9. The length is stored in `n_length`. +; +n: + .res TO_DIGITS +; +; Space for calculating the reversed and added values. +; In the `main` code the current number is copied into `xa` +; and then repeatedly `reverse_add`\ed to itself with the +; result of that adding stored in `xb`. +; +xa: + .res MAX_DIGITS +xb: + .res MAX_DIGITS + +;-------------------------------------- +; BASIC header. +;-------------------------------------- +.code + .word 0800h ; Load address. + .byte 0 + .word @line_end + .word 2008 ; Line number. + .byte $9e ; SYS token. + .byte "2080 " ; SYS argument. + .byte "LYCHREL NUMBERS/BJ" +@line_end: + .byte 0, 0, 0 ; Line and program end marker. + +;-------------------------------------- +; Main program. +;-------------------------------------- +.proc main + +.zeropage +; +; Three byte counter for `TO` iterations (100000 = $0186a0). +; +i: + .res 3 + +.code +; +; Clear and set `n` and `i` to 1. +; + lda #0 ; n := 0; n := 1; i := 1 + sta i+1 + sta i+2 + ldx #TO_DIGITS +clear_n: + sta n-1,x + dex + bne clear_n + inx + stx i + stx n + stx n_length + +mainloop: + jsr is_lychrel + bcc no_lychrel + jsr print_n +no_lychrel: + jsr increase_n + + inc i ; INC(i) + bne skip + inc i+1 + bne skip + inc i+2 +skip: + lda i + cmp #<TO + bne mainloop + lda i+1 + cmp #>TO + bne mainloop + lda i+2 + cmp #^TO + bne mainloop + + rts +.endproc + +;-------------------------------------- +; Print `n` and a trailing newline. +; +; :in: `n_length`, `n` +;-------------------------------------- +.proc print_n + ldy n_length +L1: + lda n-1,y + ora #%110000 ; = '0' + jsr chrout + dey + bne L1 + + lda #13 + jmp chrout +.endproc + +;-------------------------------------- +; Increase `n` by one. +; +; This procedure expects n[n_length] == 0 in case the number gets +; one digit longer. +; +; :in: `n`, `n_length` +; :out: `n`, `n_length` +;-------------------------------------- +.proc increase_n + ldx #0 +L1: + inc n,x ; Increase digit. + lda n,x + cmp #10 ; If "carry", store 0 and go to next digit. + bne return + lda #0 + sta n,x + inx + bne L1 +return: + cpx n_length ; If "carry" after last digit, increase length. + bcc skip + inc n_length +skip: + rts +.endproc + +;-------------------------------------- +; Tests if `n` is a Lychrel number. +; +; :in: `n`, `n_length` +; :out: C is set if yes, cleared otherwise. +; :uses: `length`, `xa`, `xb` +;-------------------------------------- +.proc is_lychrel +.zeropage +i: + .res 1 + +.code + ldx n_length ; xa := n; length := n_length + stx length +L1: + lda n-1,x + sta xa-1,x + dex + bne L1 + + lda #ITERATIONS ; i := ITERATIONS + sta i +L2: + jsr reverse_add + jsr is_palindrome + bne no_palindrome + clc + rts +no_palindrome: + ldx length ; a := b +L3: + lda xb-1,x + sta xa-1,x + dex + bne L3 + + dec i ; Loop body end. + bne L2 + + sec + rts +.endproc + +;-------------------------------------- +; Add the reverse to `xa` to itself and store the result in `xb`. +; +; :in: `length`, `xa` +; :out: `length`, `xb` +;-------------------------------------- +.proc reverse_add +.code + ldx #0 + ldy length + clc +L1: + lda xa,x + adc xa-1,y + + cmp #10 + bcc no_adjust + sbc #10 +no_adjust: + sta xb,x + + dey + inx + txa ; ``eor`` instead of ``cpx`` to keep the carry flag + eor length ; of the addition above. + bne L1 + + bcc no_carry + lda #1 + sta xb,x + inc length +no_carry: + rts +.endproc + +;-------------------------------------- +; Checks if `xb` is a palindrome. +; +; :in: `length`, `xb` +; :out: Z flag set if `xb` is a palindrome, cleared otherwise. +;-------------------------------------- +.proc is_palindrome +.code + ldx #0 + lda length + tay + lsr + sta L1+1 ; Self modifying code! +L1: + cpx #0 ; <<< 0 replaced by (`length` / 2). + beq return + lda xb,x + cmp xb-1,y + bne return + dey + inx + bne L1 +return: + rts +.endproc diff --git a/tests/examplefiles/cbmbas_example b/tests/examplefiles/cbmbas_example new file mode 100644 index 00000000..8d8ded9e --- /dev/null +++ b/tests/examplefiles/cbmbas_example @@ -0,0 +1,9 @@ +10 rem cbm basic v2 example +20 rem comment with keywords: for, data +30 dim a$(20) +35 rem the typical space efficient form of leaving spaces out: +40 fort=0to15:poke646,t:print"{revers on} ";:next +50 geta$:ifa$=chr$(0):goto40 +55 rem it is legal to omit the closing " on line end +60 print"{white}":print"bye... +70 end diff --git a/tests/examplefiles/classes.dylan b/tests/examplefiles/classes.dylan index ff435b77..83faf69c 100644 --- a/tests/examplefiles/classes.dylan +++ b/tests/examplefiles/classes.dylan @@ -1,12 +1,26 @@ +module: sample +comment: for make sure that does not highlight per word. + and it continues on to the next line. + define class <car> (<object>) slot serial-number :: <integer> = unique-serial-number(); - slot model-name :: <string>, + constant slot model-name :: <string>, required-init-keyword: model:; - slot has-sunroof? :: <boolean>, + each-subclass slot has-sunroof? :: <boolean>, init-keyword: sunroof?:, init-value: #f; + keyword foo:; + required keyword bar:; end class <car>; +define class <flying-car> (<car>) +end class <flying-car>; + +let flying-car = make(<flying-car>); +let car? :: <car?> = #f; +let prefixed-car :: <vehicles/car> = #f; +let model :: <car-911> = #f; + define constant $empty-string = ""; define constant $escaped-backslash = '\\'; define constant $escaped-single-quote = '\''; @@ -22,3 +36,90 @@ end function; define constant $blue-car = make(<car>, model: "Viper"); define constant $black-car = make(<car>, model: "Town Car", sunroof?: #t); define constant $red-car = make(<car>, model: "F40", sunroof?: #f); + +define method foo() => _ :: <boolean> + #t +end method; + +define method foo() => _ :: <boolean>; + #t +end method; + +define method \+ + (offset1 :: <time-offset>, offset2 :: <time-offset>) + => (sum :: <time-offset>) + let sum = offset1.total-seconds + offset2.total-seconds; + make(<time-offset>, total-seconds: sum); +end method \+; + +define method bar () + 1 | 2 & 3 +end + +if (bar) + 1 +elseif (foo) + 2 +else + 3 +end if; + +select (foo by instance?) + <integer> => 1 + otherwise => 3 +end select; + +/* multi + line + comment +*/ + +/* multi line comments + /* can be */ + nested */ + +define constant $symbol = #"hello"; +define variable *vector* = #[3.5, 5] +define constant $list = #(1, 2); +define constant $pair = #(1 . "foo") + +let octal-number = #o238; +let hex-number = #x3890ADEF; +let binary-number = #b1010; +let float-exponent = 3.5e10; + +block (return) + with-lock (lock) + return(); + end; +exception (e :: <error>) + format-out("Oh no"); +cleanup + return(); +afterwards + format-out("Hello"); +end; + +define macro repeat + { repeat ?:body end } + => { block (?=stop!) + local method again() ?body; again() end; + again(); + end } +end macro repeat; + +define macro with-decoded-seconds + { + with-decoded-seconds + (?max:variable, ?min:variable, ?sec:variable = ?time:expression) + ?:body + end + } + => { + let (?max, ?min, ?sec) = decode-total-seconds(?time); + ?body + } +end macro; + +let x = "This size call should be seen as a builtin despite the odd case.".siZe; + diff --git a/tests/examplefiles/coq_RelationClasses b/tests/examplefiles/coq_RelationClasses new file mode 100644 index 00000000..94c51bf1 --- /dev/null +++ b/tests/examplefiles/coq_RelationClasses @@ -0,0 +1,447 @@ +(* -*- coding: utf-8 -*- *) +(************************************************************************) +(* v * The Coq Proof Assistant / The Coq Development Team *) +(* <O___,, * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999-2011 *) +(* \VV/ **************************************************************) +(* // * This file is distributed under the terms of the *) +(* * GNU Lesser General Public License Version 2.1 *) +(************************************************************************) + +(** * Typeclass-based relations, tactics and standard instances + + This is the basic theory needed to formalize morphisms and setoids. + + Author: Matthieu Sozeau + Institution: LRI, CNRS UMR 8623 - University Paris Sud +*) + +(* $Id: RelationClasses.v 14641 2011-11-06 11:59:10Z herbelin $ *) + +Require Export Coq.Classes.Init. +Require Import Coq.Program.Basics. +Require Import Coq.Program.Tactics. +Require Import Coq.Relations.Relation_Definitions. + +(** We allow to unfold the [relation] definition while doing morphism search. *) + +Notation inverse R := (flip (R:relation _) : relation _). + +Definition complement {A} (R : relation A) : relation A := fun x y => R x y -> False. + +(** Opaque for proof-search. *) +Typeclasses Opaque complement. + +(** These are convertible. *) + +Lemma complement_inverse : forall A (R : relation A), complement (inverse R) = inverse (complement R). +Proof. reflexivity. Qed. + +(** We rebind relations in separate classes to be able to overload each proof. *) + +Set Implicit Arguments. +Unset Strict Implicit. + +Class Reflexive {A} (R : relation A) := + reflexivity : forall x, R x x. + +Class Irreflexive {A} (R : relation A) := + irreflexivity : Reflexive (complement R). + +Hint Extern 1 (Reflexive (complement _)) => class_apply @irreflexivity : typeclass_instances. + +Class Symmetric {A} (R : relation A) := + symmetry : forall x y, R x y -> R y x. + +Class Asymmetric {A} (R : relation A) := + asymmetry : forall x y, R x y -> R y x -> False. + +Class Transitive {A} (R : relation A) := + transitivity : forall x y z, R x y -> R y z -> R x z. + +Hint Resolve @irreflexivity : ord. + +Unset Implicit Arguments. + +(** A HintDb for relations. *) + +Ltac solve_relation := + match goal with + | [ |- ?R ?x ?x ] => reflexivity + | [ H : ?R ?x ?y |- ?R ?y ?x ] => symmetry ; exact H + end. + +Hint Extern 4 => solve_relation : relations. + +(** We can already dualize all these properties. *) + +Generalizable Variables A B C D R S T U l eqA eqB eqC eqD. + +Lemma flip_Reflexive `{Reflexive A R} : Reflexive (flip R). +Proof. tauto. Qed. + +Hint Extern 3 (Reflexive (flip _)) => apply flip_Reflexive : typeclass_instances. + +Program Definition flip_Irreflexive `(Irreflexive A R) : Irreflexive (flip R) := + irreflexivity (R:=R). + +Program Definition flip_Symmetric `(Symmetric A R) : Symmetric (flip R) := + fun x y H => symmetry (R:=R) H. + +Program Definition flip_Asymmetric `(Asymmetric A R) : Asymmetric (flip R) := + fun x y H H' => asymmetry (R:=R) H H'. + +Program Definition flip_Transitive `(Transitive A R) : Transitive (flip R) := + fun x y z H H' => transitivity (R:=R) H' H. + +Hint Extern 3 (Irreflexive (flip _)) => class_apply flip_Irreflexive : typeclass_instances. +Hint Extern 3 (Symmetric (flip _)) => class_apply flip_Symmetric : typeclass_instances. +Hint Extern 3 (Asymmetric (flip _)) => class_apply flip_Asymmetric : typeclass_instances. +Hint Extern 3 (Transitive (flip _)) => class_apply flip_Transitive : typeclass_instances. + +Definition Reflexive_complement_Irreflexive `(Reflexive A (R : relation A)) + : Irreflexive (complement R). +Proof. firstorder. Qed. + +Definition complement_Symmetric `(Symmetric A (R : relation A)) : Symmetric (complement R). +Proof. firstorder. Qed. + +Hint Extern 3 (Symmetric (complement _)) => class_apply complement_Symmetric : typeclass_instances. +Hint Extern 3 (Irreflexive (complement _)) => class_apply Reflexive_complement_Irreflexive : typeclass_instances. + +(** * Standard instances. *) + +Ltac reduce_hyp H := + match type of H with + | context [ _ <-> _ ] => fail 1 + | _ => red in H ; try reduce_hyp H + end. + +Ltac reduce_goal := + match goal with + | [ |- _ <-> _ ] => fail 1 + | _ => red ; intros ; try reduce_goal + end. + +Tactic Notation "reduce" "in" hyp(Hid) := reduce_hyp Hid. + +Ltac reduce := reduce_goal. + +Tactic Notation "apply" "*" constr(t) := + first [ refine t | refine (t _) | refine (t _ _) | refine (t _ _ _) | refine (t _ _ _ _) | + refine (t _ _ _ _ _) | refine (t _ _ _ _ _ _) | refine (t _ _ _ _ _ _ _) ]. + +Ltac simpl_relation := + unfold flip, impl, arrow ; try reduce ; program_simpl ; + try ( solve [ intuition ]). + +Local Obligation Tactic := simpl_relation. + +(** Logical implication. *) + +Program Instance impl_Reflexive : Reflexive impl. +Program Instance impl_Transitive : Transitive impl. + +(** Logical equivalence. *) + +Program Instance iff_Reflexive : Reflexive iff. +Program Instance iff_Symmetric : Symmetric iff. +Program Instance iff_Transitive : Transitive iff. + +(** Leibniz equality. *) + +Instance eq_Reflexive {A} : Reflexive (@eq A) := @eq_refl A. +Instance eq_Symmetric {A} : Symmetric (@eq A) := @eq_sym A. +Instance eq_Transitive {A} : Transitive (@eq A) := @eq_trans A. + +(** Various combinations of reflexivity, symmetry and transitivity. *) + +(** A [PreOrder] is both Reflexive and Transitive. *) + +Class PreOrder {A} (R : relation A) : Prop := { + PreOrder_Reflexive :> Reflexive R ; + PreOrder_Transitive :> Transitive R }. + +(** A partial equivalence relation is Symmetric and Transitive. *) + +Class PER {A} (R : relation A) : Prop := { + PER_Symmetric :> Symmetric R ; + PER_Transitive :> Transitive R }. + +(** Equivalence relations. *) + +Class Equivalence {A} (R : relation A) : Prop := { + Equivalence_Reflexive :> Reflexive R ; + Equivalence_Symmetric :> Symmetric R ; + Equivalence_Transitive :> Transitive R }. + +(** An Equivalence is a PER plus reflexivity. *) + +Instance Equivalence_PER `(Equivalence A R) : PER R | 10 := + { PER_Symmetric := Equivalence_Symmetric ; + PER_Transitive := Equivalence_Transitive }. + +(** We can now define antisymmetry w.r.t. an equivalence relation on the carrier. *) + +Class Antisymmetric A eqA `{equ : Equivalence A eqA} (R : relation A) := + antisymmetry : forall {x y}, R x y -> R y x -> eqA x y. + +Program Definition flip_antiSymmetric `(Antisymmetric A eqA R) : + Antisymmetric A eqA (flip R). +Proof. firstorder. Qed. + +(** Leibinz equality [eq] is an equivalence relation. + The instance has low priority as it is always applicable + if only the type is constrained. *) + +Program Instance eq_equivalence : Equivalence (@eq A) | 10. + +(** Logical equivalence [iff] is an equivalence relation. *) + +Program Instance iff_equivalence : Equivalence iff. + +(** We now develop a generalization of results on relations for arbitrary predicates. + The resulting theory can be applied to homogeneous binary relations but also to + arbitrary n-ary predicates. *) + +Local Open Scope list_scope. + +(* Notation " [ ] " := nil : list_scope. *) +(* Notation " [ x ; .. ; y ] " := (cons x .. (cons y nil) ..) (at level 1) : list_scope. *) + +(** A compact representation of non-dependent arities, with the codomain singled-out. *) + +Fixpoint arrows (l : list Type) (r : Type) : Type := + match l with + | nil => r + | A :: l' => A -> arrows l' r + end. + +(** We can define abbreviations for operation and relation types based on [arrows]. *) + +Definition unary_operation A := arrows (A::nil) A. +Definition binary_operation A := arrows (A::A::nil) A. +Definition ternary_operation A := arrows (A::A::A::nil) A. + +(** We define n-ary [predicate]s as functions into [Prop]. *) + +Notation predicate l := (arrows l Prop). + +(** Unary predicates, or sets. *) + +Definition unary_predicate A := predicate (A::nil). + +(** Homogeneous binary relations, equivalent to [relation A]. *) + +Definition binary_relation A := predicate (A::A::nil). + +(** We can close a predicate by universal or existential quantification. *) + +Fixpoint predicate_all (l : list Type) : predicate l -> Prop := + match l with + | nil => fun f => f + | A :: tl => fun f => forall x : A, predicate_all tl (f x) + end. + +Fixpoint predicate_exists (l : list Type) : predicate l -> Prop := + match l with + | nil => fun f => f + | A :: tl => fun f => exists x : A, predicate_exists tl (f x) + end. + +(** Pointwise extension of a binary operation on [T] to a binary operation + on functions whose codomain is [T]. + For an operator on [Prop] this lifts the operator to a binary operation. *) + +Fixpoint pointwise_extension {T : Type} (op : binary_operation T) + (l : list Type) : binary_operation (arrows l T) := + match l with + | nil => fun R R' => op R R' + | A :: tl => fun R R' => + fun x => pointwise_extension op tl (R x) (R' x) + end. + +(** Pointwise lifting, equivalent to doing [pointwise_extension] and closing using [predicate_all]. *) + +Fixpoint pointwise_lifting (op : binary_relation Prop) (l : list Type) : binary_relation (predicate l) := + match l with + | nil => fun R R' => op R R' + | A :: tl => fun R R' => + forall x, pointwise_lifting op tl (R x) (R' x) + end. + +(** The n-ary equivalence relation, defined by lifting the 0-ary [iff] relation. *) + +Definition predicate_equivalence {l : list Type} : binary_relation (predicate l) := + pointwise_lifting iff l. + +(** The n-ary implication relation, defined by lifting the 0-ary [impl] relation. *) + +Definition predicate_implication {l : list Type} := + pointwise_lifting impl l. + +(** Notations for pointwise equivalence and implication of predicates. *) + +Infix "<∙>" := predicate_equivalence (at level 95, no associativity) : predicate_scope. +Infix "-∙>" := predicate_implication (at level 70, right associativity) : predicate_scope. + +Open Local Scope predicate_scope. + +(** The pointwise liftings of conjunction and disjunctions. + Note that these are [binary_operation]s, building new relations out of old ones. *) + +Definition predicate_intersection := pointwise_extension and. +Definition predicate_union := pointwise_extension or. + +Infix "/∙\" := predicate_intersection (at level 80, right associativity) : predicate_scope. +Infix "\∙/" := predicate_union (at level 85, right associativity) : predicate_scope. + +(** The always [True] and always [False] predicates. *) + +Fixpoint true_predicate {l : list Type} : predicate l := + match l with + | nil => True + | A :: tl => fun _ => @true_predicate tl + end. + +Fixpoint false_predicate {l : list Type} : predicate l := + match l with + | nil => False + | A :: tl => fun _ => @false_predicate tl + end. + +Notation "∙⊤∙" := true_predicate : predicate_scope. +Notation "∙⊥∙" := false_predicate : predicate_scope. + +(** Predicate equivalence is an equivalence, and predicate implication defines a preorder. *) + +Program Instance predicate_equivalence_equivalence : Equivalence (@predicate_equivalence l). + Next Obligation. + induction l ; firstorder. + Qed. + Next Obligation. + induction l ; firstorder. + Qed. + Next Obligation. + fold pointwise_lifting. + induction l. firstorder. + intros. simpl in *. pose (IHl (x x0) (y x0) (z x0)). + firstorder. + Qed. + +Program Instance predicate_implication_preorder : + PreOrder (@predicate_implication l). + Next Obligation. + induction l ; firstorder. + Qed. + Next Obligation. + induction l. firstorder. + unfold predicate_implication in *. simpl in *. + intro. pose (IHl (x x0) (y x0) (z x0)). firstorder. + Qed. + +(** We define the various operations which define the algebra on binary relations, + from the general ones. *) + +Definition relation_equivalence {A : Type} : relation (relation A) := + @predicate_equivalence (_::_::nil). + +Class subrelation {A:Type} (R R' : relation A) : Prop := + is_subrelation : @predicate_implication (A::A::nil) R R'. + +Implicit Arguments subrelation [[A]]. + +Definition relation_conjunction {A} (R : relation A) (R' : relation A) : relation A := + @predicate_intersection (A::A::nil) R R'. + +Definition relation_disjunction {A} (R : relation A) (R' : relation A) : relation A := + @predicate_union (A::A::nil) R R'. + +(** Relation equivalence is an equivalence, and subrelation defines a partial order. *) + +Set Automatic Introduction. + +Instance relation_equivalence_equivalence (A : Type) : + Equivalence (@relation_equivalence A). +Proof. exact (@predicate_equivalence_equivalence (A::A::nil)). Qed. + +Instance relation_implication_preorder A : PreOrder (@subrelation A). +Proof. exact (@predicate_implication_preorder (A::A::nil)). Qed. + +(** *** Partial Order. + A partial order is a preorder which is additionally antisymmetric. + We give an equivalent definition, up-to an equivalence relation + on the carrier. *) + +Class PartialOrder {A} eqA `{equ : Equivalence A eqA} R `{preo : PreOrder A R} := + partial_order_equivalence : relation_equivalence eqA (relation_conjunction R (inverse R)). + +(** The equivalence proof is sufficient for proving that [R] must be a morphism + for equivalence (see Morphisms). + It is also sufficient to show that [R] is antisymmetric w.r.t. [eqA] *) + +Instance partial_order_antisym `(PartialOrder A eqA R) : ! Antisymmetric A eqA R. +Proof with auto. + reduce_goal. + pose proof partial_order_equivalence as poe. do 3 red in poe. + apply <- poe. firstorder. +Qed. + +(** The partial order defined by subrelation and relation equivalence. *) + +Program Instance subrelation_partial_order : + ! PartialOrder (relation A) relation_equivalence subrelation. + + Next Obligation. + Proof. + unfold relation_equivalence in *. firstorder. + Qed. + +Typeclasses Opaque arrows predicate_implication predicate_equivalence + relation_equivalence pointwise_lifting. + +(** Rewrite relation on a given support: declares a relation as a rewrite + relation for use by the generalized rewriting tactic. + It helps choosing if a rewrite should be handled + by the generalized or the regular rewriting tactic using leibniz equality. + Users can declare an [RewriteRelation A RA] anywhere to declare default + relations. This is also done automatically by the [Declare Relation A RA] + commands. *) + +Class RewriteRelation {A : Type} (RA : relation A). + +Instance: RewriteRelation impl. +Instance: RewriteRelation iff. +Instance: RewriteRelation (@relation_equivalence A). + +(** Any [Equivalence] declared in the context is automatically considered + a rewrite relation. *) + +Instance equivalence_rewrite_relation `(Equivalence A eqA) : RewriteRelation eqA. + +(** Strict Order *) + +Class StrictOrder {A : Type} (R : relation A) := { + StrictOrder_Irreflexive :> Irreflexive R ; + StrictOrder_Transitive :> Transitive R +}. + +Instance StrictOrder_Asymmetric `(StrictOrder A R) : Asymmetric R. +Proof. firstorder. Qed. + +(** Inversing a [StrictOrder] gives another [StrictOrder] *) + +Lemma StrictOrder_inverse `(StrictOrder A R) : StrictOrder (inverse R). +Proof. firstorder. Qed. + +(** Same for [PartialOrder]. *) + +Lemma PreOrder_inverse `(PreOrder A R) : PreOrder (inverse R). +Proof. firstorder. Qed. + +Hint Extern 3 (StrictOrder (inverse _)) => class_apply StrictOrder_inverse : typeclass_instances. +Hint Extern 3 (PreOrder (inverse _)) => class_apply PreOrder_inverse : typeclass_instances. + +Lemma PartialOrder_inverse `(PartialOrder A eqA R) : PartialOrder eqA (inverse R). +Proof. firstorder. Qed. + +Hint Extern 3 (PartialOrder (inverse _)) => class_apply PartialOrder_inverse : typeclass_instances. diff --git a/tests/examplefiles/core.cljs b/tests/examplefiles/core.cljs new file mode 100644 index 00000000..f135b832 --- /dev/null +++ b/tests/examplefiles/core.cljs @@ -0,0 +1,52 @@ + +(ns bounder.core + (:require [bounder.html :as html] + [domina :refer [value set-value! single-node]] + [domina.css :refer [sel]] + [lowline.functions :refer [debounce]] + [enfocus.core :refer [at]] + [cljs.reader :as reader] + [clojure.string :as s]) + (:require-macros [enfocus.macros :as em])) + +(def filter-input + (single-node + (sel ".search input"))) + +(defn project-matches [query project] + (let [words (cons (:name project) + (map name (:categories project))) + to-match (->> words + (s/join "") + (s/lower-case))] + (<= 0 (.indexOf to-match (s/lower-case query))))) + +(defn apply-filter-for [projects] + (let [query (value filter-input)] + (html/render-projects + (filter (partial project-matches query) + projects)))) + +(defn filter-category [projects evt] + (let [target (.-currentTarget evt)] + (set-value! filter-input + (.-innerHTML target)) + (apply-filter-for projects))) + +(defn init-listeners [projects] + (at js/document + ["input"] (em/listen + :keyup + (debounce + (partial apply-filter-for projects) + 500)) + [".category-links li"] (em/listen + :click + (partial filter-category projects)))) + +(defn init [projects-edn] + (let [projects (reader/read-string projects-edn)] + (init-listeners projects) + (html/render-projects projects) + (html/loaded))) + diff --git a/tests/examplefiles/demo.hbs b/tests/examplefiles/demo.hbs new file mode 100644 index 00000000..1b9ed5a7 --- /dev/null +++ b/tests/examplefiles/demo.hbs @@ -0,0 +1,12 @@ +<!-- post.handlebars --> + +<div class='intro'> + {{intro}} +</div> + +{{#if isExpanded}} + <div class='body'>{{body}}</div> + <button {{action contract}}>Contract</button> +{{else}} + <button {{action expand}}>Show More...</button> +{{/if}} diff --git a/tests/examplefiles/ember.handlebars b/tests/examplefiles/ember.handlebars new file mode 100644 index 00000000..515dffbd --- /dev/null +++ b/tests/examplefiles/ember.handlebars @@ -0,0 +1,33 @@ +{{#view EmberFirebaseChat.ChatView class="chat-container"}} + <div class="chat-messages-container"> + <ul class="chat-messages"> + {{#each message in content}} + <li> + [{{formatTimestamp "message.timestamp" fmtString="h:mm:ss A"}}] + <strong>{{message.sender}}</strong>: {{message.content}} + </li> + {{/each}} + </ul> + </div> + + {{! Comment }} + {{{unescaped value}}} + + {{#view EmberFirebaseChat.InputView class="chat-input-container"}} + <form class="form-inline"> + {{#if "auth.authed"}} + {{#if "auth.hasName"}} + <input type="text" id="message" placeholder="Message"> + <button {{action "postMessage" target="view"}} class="btn">Send</button> + {{else}} + <input type="text" id="username" placeholder="Enter your username..."> + <button {{action "pickName" target="view"}} class="btn">Send</button> + {{/if}} + {{else}} + <input type="text" placeholder="Log in with Persona to chat!" disabled="disabled"> + <button {{action "login"}} class="btn">Login</button> + {{/if}} + </form> + {{/view}} +{{/view}} + diff --git a/tests/examplefiles/example.Rd b/tests/examplefiles/example.Rd new file mode 100644 index 00000000..2b8de0b8 --- /dev/null +++ b/tests/examplefiles/example.Rd @@ -0,0 +1,78 @@ +\name{foo} +\alias{foo} +% I'm a comment +\title{The foo function} + +\description{It doesn't do much} + +\usage{ +foo(x, y) +} + +\arguments{ + \item{x}{A number} + \item{y}{Another number} +} +\details{ + I just adds \code{x} and \code{y}, +} +\value{\code{numeric}. The sum of \code{x} and \code{y}.} +\references{ + \href{http://en.wikipedia.org/wiki/Sum}{Sum} +} +\author{ + Anonymous +} +\note{ + Lorem ipsum \dots \R \emph{emp}, \strong{strong}, \bold{bold}, + \sQuote{single quotes}, \dQuote{double quotes}, \code{code}, + \preformatted{x <- 2 + 2}, \kbd{type this}, \samp{literal seq}, + \pkg{base}, \file{foo.txt}, \email{email@hostname}, + \url{http://cran.r-project.org/}, \var{foo}, \env{HOME}, + \option{-d}, \dfn{something new}, \acronym{GNU}. + + Escaped symbols: \\ \{ \} \% not comment. \\NotAMacro. + + \tabular{rlll}{ + [,1] \tab alpha \tab numeric \tab A (ppb)\cr + [,2] \tab bravo \tab integer \tab B \cr + [,3] \tab charlie \tab character \tab C \cr + } + \enumerate{ + \item delta + \item echo + } + \itemize{ + \item foxtrot + \item golf + } + + \deqn{p(x; \mu, \sigma^2) = \frac{1}{\sigma \sqrt{2 \pi}} \exp \frac{-(x - \mu)^2}{2 \sigma}{% + p(\mu; x) = 1/\sigma (2 \pi)^(-1/2) exp( -(x - \mu)^2 / (2 \sigma)) } + for \eqn{x = 0, 1, 2, \ldots}. + + \if{latex}{\out{\beta}}\ifelse{html}{\out{β}}{beta} + +#ifdef unix +Now windows +#endif +#ifndef windows +Using windows +#endif + +} +\section{Misc}{ + Stuff. +} + +\seealso{ + \code{\link{sum}} +} +\examples{ +x <- 1 +y <- 2 +z <- foo(x, y) +\dontrun{plot(z)} +\dontshow{log(x)} +} +\keyword{arith} diff --git a/tests/examplefiles/example.bug b/tests/examplefiles/example.bug new file mode 100644 index 00000000..9ccd531d --- /dev/null +++ b/tests/examplefiles/example.bug @@ -0,0 +1,54 @@ +# Alligators: multinomial - logistic regression +# http://www.openbugs.info/Examples/Aligators.html +model { + # PRIORS + alpha[1] <- 0; # zero contrast for baseline food + for (k in 2 : K) { + alpha[k] ~ dnorm(0, 0.00001) # vague priors + } + # Loop around lakes: + for (k in 1 : K){ + beta[1, k] <- 0 + } # corner-point contrast with first lake + for (i in 2 : I) { + beta[i, 1] <- 0 ; # zero contrast for baseline food + for (k in 2 : K){ + beta[i, k] ~ dnorm(0, 0.00001) # vague priors + } + } + # Loop around sizes: + for (k in 1 : K){ + gamma[1, k] <- 0 # corner-point contrast with first size + } + for (j in 2 : J) { + gamma[j, 1] <- 0 ; # zero contrast for baseline food + for ( k in 2 : K){ + gamma[j, k] ~ dnorm(0, 0.00001) # vague priors + } + } + + # LIKELIHOOD + for (i in 1 : I) { # loop around lakes + for (j in 1 : J) { # loop around sizes + + # Fit standard Poisson regressions relative to baseline + lambda[i, j] ~ dflat() # vague priors + for (k in 1 : K) { # loop around foods + X[i, j, k] ~ dpois(mu[i, j, k]) + log(mu[i, j, k]) <- lambda[i, j] + alpha[k] + beta[i, k] + gamma[j, k] + culmative.X[i, j, k] <- culmative(X[i, j, k], X[i, j, k]) + } + } + } + + # TRANSFORM OUTPUT TO ENABLE COMPARISON + # WITH AGRESTI'S RESULTS + for (k in 1 : K) { # loop around foods + for (i in 1 : I) { # loop around lakes + b[i, k] <- beta[i, k] - mean(beta[, k]); # sum to zero constraint + } + for (j in 1 : J) { # loop around sizes + g[j, k] <- gamma[j, k] - mean(gamma[, k]); # sum to zero constraint + } + } +} diff --git a/tests/examplefiles/example.c b/tests/examplefiles/example.c index a7f546d1..7bf70149 100644 --- a/tests/examplefiles/example.c +++ b/tests/examplefiles/example.c @@ -195,7 +195,7 @@ char convertType(int type) { case TYPE_INT: return 'I'; case TYPE_FLOAT: return 'F'; case TYPE_BOOLEAN: return 'Z'; - default: yyerror("compiler-intern error in convertType().\n"); + default : yyerror("compiler-intern error in convertType().\n"); } return 0; /* to avoid compiler-warning */ } diff --git a/tests/examplefiles/example.ceylon b/tests/examplefiles/example.ceylon new file mode 100644 index 00000000..04223c56 --- /dev/null +++ b/tests/examplefiles/example.ceylon @@ -0,0 +1,52 @@ +import ceylon.language { parseInteger } + +doc "A top-level function, + with multi-line documentation." +void topLevel(String? a, Integer b=5, String* seqs) { + function nested(String s) { + print(s[1..2]); + return true; + } + for (s in seqs.filter((String x) => x.size > 2)) { + nested(s); + } + value uppers = seqs.map((String x) { + return x.uppercased; + }); + String|Null z = a; + {Integer+} ints = { 1, 2, 3, 4, 5 }; + value numbers = [ 1, #ffff, #ffff_ffff, $10101010, $1010_1010_1010_1010, + 123_456_789 ]; + value chars = ['a', '\{#ffff}' ]; +} + +shared class Example_1<Element>(name, element) satisfies Comparable<Example_1<Element>> + given Element satisfies Comparable<Element> { + shared String name; + shared Element element; + shared [Integer,String] tuple = [1, "2"]; + shared late String lastName; + variable Integer cnt = 0; + + shared Integer count => cnt; + assign count { + assert(count >= cnt); + cnt = count; + } + + shared actual Comparison compare(Example_1<Element> other) { + return element <=> other.element; + } + + shared actual String string { + return "Example with ``element.string``"; + } +} + +Example_1<Integer> instance = Example_1 { + element = 5; + name = "Named args call \{#0060}"; +}; + +object example1 extends Example_1<Integer>("object", 5) { +}
\ No newline at end of file diff --git a/tests/examplefiles/example.clay b/tests/examplefiles/example.clay new file mode 100644 index 00000000..784752c6 --- /dev/null +++ b/tests/examplefiles/example.clay @@ -0,0 +1,33 @@ + +/// @section StringLiteralRef + +record StringLiteralRef ( + sizep : Pointer[SizeT], +); + + +/// @section predicates + +overload ContiguousSequence?(#StringLiteralRef) : Bool = true; +[s when StringLiteral?(s)] +overload ContiguousSequence?(#Static[s]) : Bool = true; + + + +/// @section size, begin, end, index + +forceinline overload size(a:StringLiteralRef) = a.sizep^; + +forceinline overload begin(a:StringLiteralRef) : Pointer[Char] = Pointer[Char](a.sizep + 1); +forceinline overload end(a:StringLiteralRef) = begin(a) + size(a); + +[I when Integer?(I)] +forceinline overload index(a:StringLiteralRef, i:I) : ByRef[Char] { + assert["boundsChecks"](i >= 0 and i < size(a), "StringLiteralRef index out of bounds"); + return ref (begin(a) + i)^; +} + +foo() = """ +long\tlong +story +""" diff --git a/tests/examplefiles/example.cls b/tests/examplefiles/example.cls new file mode 100644 index 00000000..d36ad6f0 --- /dev/null +++ b/tests/examplefiles/example.cls @@ -0,0 +1,15 @@ +USING Progress.Lang.*. + +CLASS Test INHERITS Progress.Sucks: + + DEFINE PRIVATE VARIABLE cTest AS CHAR NO-UNDO. + + CONSTRUCTOR PUBLIC Test(): + SUPER(). + MESSAGE "Why are you punishing yourself by coding in this language?". + END CONSTRUCTOR. + + METHOD PUBLIC LOGICAL Blowup(INPUT iTime AS INT): + END. + +END CLASS. diff --git a/tests/examplefiles/example.cob b/tests/examplefiles/example.cob new file mode 100644 index 00000000..3f65e498 --- /dev/null +++ b/tests/examplefiles/example.cob @@ -0,0 +1,3556 @@ + IDENTIFICATION DIVISION.
+ PROGRAM-ID. OCic.
+ *****************************************************************
+ ** This program provides a Textual User Interface (TUI) to the **
+ ** process of compiling and (optionally) executing an OpenCOBOL**
+ ** program. **
+ ** **
+ ** This programs execution syntax is as follows: **
+ ** **
+ ** ocic <program-path-and-filename> [ <switch>... ] **
+ ** **
+ ** Once executed, a display screen will be presented showing **
+ ** the compilation options that will be used. The user will **
+ ** have the opportunity to change options, specify new ones **
+ ** and specify any program execution arguments to be used if **
+ ** you select the "Execute" option. When you press the Enter **
+ ** key the program will be compiled. **
+ ** **
+ ** The SCREEN SECTION contains an image of the screen. **
+ ** **
+ ** The "010-Parse-Args" section in the PROCEDURE DIVISION has **
+ ** documentation on switches and their function. **
+ *****************************************************************
+ ** **
+ ** AUTHOR: GARY L. CUTLER **
+ ** CutlerGL@gmail.com **
+ ** Copyright (C) 2009-2010, Gary L. Cutler, GPL **
+ ** **
+ ** DATE-WRITTEN: June 14, 2009 **
+ ** **
+ *****************************************************************
+ ** Note: Depending on which extended DISPLAY handler you're **
+ ** using (PDCurses, Curses, ...), you may need to un- **
+ ** comment any source lines tagged with "SCROLL" in cols **
+ ** 1-6 in order to have error messages scroll properly **
+ ** in the OCic shell window. **
+ *****************************************************************
+ ** DATE CHANGE DESCRIPTION **
+ ** ====== ==================================================== **
+ ** GC0609 Don't display compiler messages file if compilation **
+ ** Is successful. Also don't display messages if the **
+ ** output file is busy (just put a message on the **
+ ** screen, leave the OC screen up & let the user fix **
+ ** the problem & resubmit. **
+ ** GC0709 When 'EXECUTE' is selected, a 'FILE BUSY' error will **
+ ** still cause the (old) executable to be launched. **
+ ** Also, the 'EXTRA SWITCHES' field is being ignored. **
+ ** Changed the title bar to lowlighted reverse video & **
+ ** the message area to highlighted reverse-video. **
+ ** GC0809 Add a SPACE in from of command-line args when **
+ ** executing users program. Add a SPACE after the **
+ ** -ftraceall switch when building cobc command. **
+ ** GC0909 Convert to work on Cygwin/Linux as well as MinGW **
+ ** GC0310 Virtualized the key codes for S-F1 thru S-F7 as they **
+ ** differ depending upon whether PDCurses or NCurses is **
+ ** being used. **
+ ** GC0410 Introduced the cross-reference and source listing **
+ ** features. Also fixed a bug in @EXTRA switch proces- **
+ ** sing where garbage will result if more than the **
+ ** @EXTRA switch is specified. **
+ *****************************************************************
+ ENVIRONMENT DIVISION.
+ CONFIGURATION SECTION.
+ REPOSITORY.
+ FUNCTION ALL INTRINSIC.
+ INPUT-OUTPUT SECTION.
+ FILE-CONTROL.
+ SELECT Bat-File ASSIGN TO Bat-File-Name
+ ORGANIZATION IS LINE SEQUENTIAL.
+
+ SELECT Cobc-Output ASSIGN TO Cobc-Output-File
+ ORGANIZATION IS LINE SEQUENTIAL.
+
+ SELECT Source-Code ASSIGN TO File-Name
+ ORGANIZATION IS LINE SEQUENTIAL
+ FILE STATUS IS FSM-Status.
+ DATA DIVISION.
+ FILE SECTION.
+ FD Bat-File.
+ 01 Bat-File-Rec PIC X(2048).
+
+ FD Cobc-Output.
+ 01 Cobc-Output-Rec PIC X(256).
+
+ FD Source-Code.
+ 01 Source-Code-Record PIC X(80).
+
+ WORKING-STORAGE SECTION.
+ COPY screenio.
+
+ 01 Bat-File-Name PIC X(256).
+
+GC0909 01 Cmd PIC X(512).
+
+ 01 Cobc-Cmd PIC X(256).
+
+ 01 Cobc-Output-File PIC X(256).
+
+ 01 Command-Line-Args PIC X(256).
+
+ 01 Config-File PIC X(12).
+
+GC0310 01 Config-Keys.
+GC0310 05 CK-S-F1 PIC 9(4).
+GC0310 05 CK-S-F2 PIC 9(4).
+GC0310 05 CK-S-F3 PIC 9(4).
+GC0310 05 CK-S-F4 PIC 9(4).
+GC0310 05 CK-S-F5 PIC 9(4).
+GC0310 05 CK-S-F6 PIC 9(4).
+GC0310 05 CK-S-F7 PIC 9(4).
+
+GC0909 01 Dir-Char PIC X(1).
+
+ 01 Dummy PIC X(1).
+
+ 01 Env-TEMP PIC X(256).
+
+ 01 File-Name.
+ 05 FN-Char OCCURS 256 TIMES PIC X(1).
+
+ 01 File-Status-Message.
+ 05 FILLER PIC X(13) VALUE 'Status Code: '.
+ 05 FSM-Status PIC 9(2).
+ 05 FILLER PIC X(11) VALUE ', Meaning: '.
+ 05 FSM-Msg PIC X(25).
+
+ 01 Flags.
+ 05 F-Compilation-Succeeded PIC X(1).
+ 88 88-Compile-OK VALUE 'Y'.
+GC0909 88 88-Compile-OK-Warn VALUE 'W'.
+ 88 88-Compile-Failed VALUE 'N'.
+GC0609 05 F-Complete PIC X(1).
+GC0609 88 88-Complete VALUE 'Y'.
+GC0609 88 88-Not-Complete VALUE 'N'.
+GC0809 05 F-IDENT-DIVISION PIC X(1).
+GC0809 88 88-1st-Prog-Complete VALUE 'Y'.
+GC0809 88 88-More-To-1st-Prog VALUE 'N'.
+ 05 F-LINKAGE-SECTION PIC X(1).
+ 88 88-Compile-As-Subpgm VALUE 'Y'.
+ 88 88-Compile-As-Mainpgm VALUE 'N'.
+ 05 F-No-Switch-Changes PIC X(1).
+ 88 88-No-Switch-Changes VALUE 'Y'.
+ 88 88-Switch-Changes VALUE 'N'.
+GC0709 05 F-Output-File-Busy PIC X(1).
+GC0709 88 88-Output-File-Busy VALUE 'Y'.
+GC0709 88 88-Output-File-Avail VALUE 'N'.
+GC0809 05 F-Source-Record-Type PIC X(1).
+GC0809 88 88-Source-Rec-Linkage VALUE 'L'.
+GC0809 88 88-Source-Rec-Ident VALUE 'I'.
+GC0809 88 88-Source-Rec-IgnoCOB-COLOR-RED VALUE ' '.
+ 05 F-Switch-Error PIC X(1).
+ 88 88-Switch-Is-Bad VALUE 'Y'.
+ 88 88-Switch-Is-Good VALUE 'N'.
+
+GC0909 01 Horizontal-Line PIC X(80).
+GC0909
+ 01 I USAGE BINARY-LONG.
+
+ 01 J USAGE BINARY-LONG.
+
+GC0909 01 MS USAGE BINARY-LONG.
+
+GC0909 01 ML USAGE BINARY-LONG.
+
+ 01 OC-Compiled PIC XXXX/XX/XXBXX/XX.
+
+GC0909 01 OS-Type USAGE BINARY-LONG.
+GC0909 88 OS-Unknown VALUE 0.
+GC0909 88 OS-Windows VALUE 1.
+GC0909 88 OS-Cygwin VALUE 2.
+GC0909 88 OS-UNIX VALUE 3.
+
+GC0909 01 OS-Type-Literal PIC X(7).
+
+ 01 Output-Message PIC X(80).
+
+ 01 Path-Delimiter PIC X(1).
+
+ 01 Prog-Folder PIC X(256).
+
+ 01 Prog-Extension PIC X(30).
+
+ 01 Prog-File-Name PIC X(40).
+
+ 01 Prog-Name PIC X(31).
+
+ 78 Selection-Char VALUE '>'.
+
+ 01 Switch-Display.
+ 05 SD-Switch-And-Value PIC X(19).
+ 05 FILLER PIC X(1).
+ 05 SD-Description PIC X(60).
+
+ 01 Switch-Keyword PIC X(12).
+GC0410 88 Switch-Is-CONFIG VALUE '@CONFIG', '@C'.
+GC0410 88 Switch-Is-DEBUG VALUE '@DEBUG', '@D'.
+GC0410 88 Switch-Is-DLL VALUE '@DLL'.
+GC0410 88 Switch-Is-EXECUTE VALUE '@EXECUTE', '@E'.
+GC0410 88 Switch-Is-EXTRA VALUE '@EXTRA', '@EX'.
+GC0410 88 Switch-Is-NOTRUNC VALUE '@NOTRUNC', '@N'.
+GC0410 88 Switch-Is-TRACE VALUE '@TRACE', '@T'.
+GC0410 88 Switch-Is-SOURCE VALUE '@SOURCE', '@S'.
+GC0410 88 Switch-Is-XREF VALUE '@XREF', '@X'.
+
+ 01 Switch-Keyword-And-Value PIC X(256).
+
+ 01 Switch-Value.
+ 05 SV-1 PIC X(1).
+ 05 FILLER PIC X(255).
+ 01 Switch-Value-Alt REDEFINES Switch-Value
+ PIC X(256).
+ 88 Valid-Config-Filename
+ VALUE 'BS2000', 'COBOL85', 'COBOL2002', 'DEFAULT',
+ 'IBM', 'MF', 'MVS'.
+
+ 01 Switches.
+ 05 S-ARGS PIC X(75) VALUE SPACES.
+ 05 S-CfgS.
+ 10 S-Cfg-BS2000 PIC X(1) VALUE ' '.
+ 10 S-Cfg-COBOL85 PIC X(1) VALUE ' '.
+ 10 S-Cfg-COBOL2002 PIC X(1) VALUE ' '.
+ 10 S-Cfg-DEFAULT PIC X(1) VALUE Selection-Char.
+ 10 S-Cfg-IBM PIC X(1) VALUE ' '.
+ 10 S-Cfg-MF PIC X(1) VALUE ' '.
+ 10 S-Cfg-MVS PIC X(1) VALUE ' '.
+ 05 S-EXTRA PIC X(75) VALUE SPACES.
+ 05 S-Yes-No-Switches.
+ 10 S-DEBUG PIC X(1) VALUE 'N'.
+ 10 S-DLL PIC X(1) VALUE 'N'.
+GC0410 10 S-XREF PIC X(1) VALUE 'N'.
+GC0410 10 S-SOURCE PIC X(1) VALUE 'N'.
+ 10 S-EXECUTE PIC X(1) VALUE 'N'.
+ 10 S-NOTRUNC PIC X(1) VALUE 'Y'.
+ 10 S-SUBROUTINE PIC X(1) VALUE 'A'.
+ 10 S-TRACE PIC X(1) VALUE 'N'.
+ 10 S-TRACEALL PIC X(1) VALUE 'N'.
+
+ 01 Tally USAGE BINARY-LONG.
+
+ SCREEN SECTION.
+ *>
+ *> Here is the layout of the OCic screen.
+ *>
+ *> Note that this program can utilize the traditional PC line-drawing characters,
+ *> if they are available.
+ *>
+ *> If this program is run on Windows, it must run with codepage 437 activated to
+ *> display the line-drawing characters. With a native Windows build or a
+ *> Windows/MinGW build, one could use the command "chcp 437" to set that codepage
+ *> for display within a Windows console window (that should be the default, though).
+ *> With a Windows/Cygwin build, set the environment variable CYGWIN to a value of
+ *> "codepage:oem" (this cannot be done from within the program though - you will
+ *> have to use the "Computer/Advanced System Settings/Environment Variables" (Vista or
+ *> Windows 7) function to define the variable. XP Users: use "My Computer/Properties/
+ *> Advanced/Environment Variables".
+ *>
+ *> To use OCic without the line-drawing characters, comment-out the first set of
+ *> 78 "LD" items and uncomment the second.
+ *>
+ *> The following sample screen layout shows how the screen looks with line-drawing
+ *> characters disabled.
+ *>
+ *>===================================================================================
+ *> OCic (2010/04/02 11:36) - OpenCOBOL V1.1 Interactive Compilation Windows 01
+ *> +-----------------------------------------------------------------------------+ 02
+ *> | Program: OCic F-Key: Select Opt | 03
+ *> | Folder: E:\OpenCOBOL\Samples Enter: Compile | 04
+ *> | Filename: OCic.cbl Esc: Quit | 05
+ *> +-----------------------------------------------------------------------------+ 06
+ *> On/Off Switches: Configuration: 07
+ *> +---------------------------------------------------------+-------------------+ 08
+ *> | F1 Compile debug lines F8 Produce source listing | S-F1 BS2000 | 09
+ *> | F2 Always make DLLs F9 Produce xref listing | S-F2 COBOL85 | 10
+ *> | F3 Pgm is a SUBROUTINE | S-F3 COBOL2002 | 11
+ *> | F4 Execute if compile OK | S-F4 > Default | 12
+ *> | F5 > No COMP/BINARY trunc | S-F5 IBM | 13
+ *> | F6 Trace procedures | S-F6 MicroFocus | 14
+ *> | F7 Trace proc + stmnts | S-F7 MVS | 15
+ *> +---------------------------------------------------------+-------------------+ 16
+ *> Additional "cobc" Switches (if any): 17
+ *> +-----------------------------------------------------------------------------+ 18
+ *> | -O2________________________________________________________________________ | 19
+ *> +-----------------------------------------------------------------------------+ 20
+ *> Program Execution Arguments (if any): 21
+ *> +-----------------------------------------------------------------------------+ 22
+ *> | ___________________________________________________________________________ | 23
+ *> +-----------------------------------------------------------------------------+ 24
+ *> OCic Copyright (C) 2009-2010, Gary L. Cutler, GPL 25
+ *>===================================================================================
+ *>12345678901234567890123456789012345678901234567890123456789012345678901234567890
+ *> 1 2 3 4 5 6 7 8
+ *>
+ *> USE THESE CHARS FOR LINE-DRAWING IF YOU HAVE ACCESS TO PC-DOS CODEPAGE 437:
+ *>
+ 78 LD-UL-Corner VALUE X"DA".
+ 78 LD-LL-Corner VALUE X"C0".
+ 78 LD-UR-Corner VALUE X"BF".
+ 78 LD-LR-Corner VALUE X"D9".
+ 78 LD-Upper-T VALUE X"C2".
+ 78 LD-Lower-T VALUE X"C1".
+ 78 LD-Horiz-Line VALUE X"C4".
+ 78 LD-Vert-Line VALUE X"B3".
+ *>
+ *> USE THESE CHARS FOR LINE-DRAWING IF YOU DO NOT HAVE ACCESS TO PC-DOS CODEPAGE 437:
+ *>
+ *> 78 LD-UL-Corner VALUE '+'.
+ *> 78 LD-LL-Corner VALUE '+'.
+ *> 78 LD-UR-Corner VALUE '+'.
+ *> 78 LD-LR-Corner VALUE '+'.
+ *> 78 LD-Upper-T VALUE '+'.
+ *> 78 LD-Lower-T VALUE '+'.
+ *> 78 LD-Horiz-Line VALUE '-'.
+ *> 78 LD-Vert-Line VALUE '|'.
+ *>
+ 01 Blank-Screen LINE 1 COLUMN 1 BLANK SCREEN.
+
+ 01 Switches-Screen BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-WHITE AUTO.
+ *>
+ *> GENERAL SCREEN FRAMEWORK
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-BLUE HIGHLIGHT.
+ 05 LINE 02 COL 02 VALUE LD-UL-Corner.
+ 05 PIC X(77) FROM Horizontal-Line.
+ 05 COL 80 VALUE LD-UR-Corner.
+
+ 05 LINE 03 COL 02 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 04 COL 02 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 05 COL 02 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 06 COL 02 VALUE LD-LL-Corner.
+ 05 PIC X(77) FROM Horizontal-Line.
+ 05 COL 80 VALUE LD-LR-Corner.
+
+ 05 LINE 08 COL 02 VALUE LD-UL-Corner.
+ 05 PIC X(57) FROM Horizontal-Line.
+ 05 COL 60 VALUE LD-Upper-T.
+ 05 PIC X(19) FROM Horizontal-Line.
+ 05 COL 80 VALUE LD-UR-Corner.
+
+ 05 LINE 09 COL 02 VALUE LD-Vert-Line.
+ 05 COL 60 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 10 COL 02 VALUE LD-Vert-Line.
+ 05 COL 60 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 11 COL 02 VALUE LD-Vert-Line.
+ 05 COL 60 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 12 COL 02 VALUE LD-Vert-Line.
+ 05 COL 60 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 13 COL 02 VALUE LD-Vert-Line.
+ 05 COL 60 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 14 COL 02 VALUE LD-Vert-Line.
+ 05 COL 60 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 15 COL 02 VALUE LD-Vert-Line.
+ 05 COL 60 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 16 COL 02 VALUE LD-LL-Corner.
+ 05 PIC X(57) FROM Horizontal-Line.
+ 05 COL 60 VALUE LD-Lower-T.
+ 05 PIC X(19) FROM Horizontal-Line.
+ 05 COL 80 VALUE LD-LR-Corner.
+
+ 05 LINE 18 COL 02 VALUE LD-UL-Corner.
+ 05 PIC X(77) FROM Horizontal-Line.
+ 05 COL 80 VALUE LD-UR-Corner.
+
+ 05 LINE 19 COL 02 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 20 COL 02 VALUE LD-LL-Corner.
+ 05 PIC X(77) FROM Horizontal-Line.
+ 05 COL 80 VALUE LD-LR-Corner.
+
+ 05 LINE 22 COL 02 VALUE LD-UL-Corner.
+ 05 PIC X(77) FROM Horizontal-Line.
+ 05 COL 80 VALUE LD-UR-Corner.
+
+ 05 LINE 23 COL 02 VALUE LD-Vert-Line.
+ 05 COL 80 VALUE LD-Vert-Line.
+
+ 05 LINE 24 COL 02 VALUE LD-LL-Corner.
+ 05 PIC X(77) FROM Horizontal-Line.
+ 05 COL 80 VALUE LD-LR-Corner.
+ *>
+ *> TOP AND BOTTOM LINES
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLUE BLINK
+ FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT.
+GC0410 05 LINE 01 COL 01 VALUE ' OCic ('.
+GC0410 05 PIC X(16) FROM OC-Compiled.
+GC0410 05 VALUE ') OpenCOBOL V1.1 06FEB2009 ' &
+GC0410 'Interactive Compilation '.
+GC0410 05 LINE 25 COL 01 PIC X(81) FROM Output-Message.
+ *>
+ *> LABELS
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-CYAN HIGHLIGHT.
+ 05 LINE 07 COL 04 VALUE 'On/Off Switches:'.
+ 05 COL 62 VALUE 'Configuration:'.
+ 05 LINE 17 COL 04 VALUE 'Additional "cobc" Switches (if any
+ - '):'.
+ 05 LINE 21 COL 04 VALUE 'Program Execution Arguments (if an
+ - 'y):'.
+ *>
+ *> TOP SECTION BACKGROUND
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-CYAN LOWLIGHT.
+ 05 LINE 03 COL 04 VALUE 'Program: '.
+ 05 LINE 04 COL 04 VALUE 'Folder: '.
+ 05 LINE 05 COL 04 VALUE 'Filename: '.
+
+ 05 LINE 03 COL 62 VALUE 'F-Key: Select Opt'.
+ 05 LINE 04 COL 62 VALUE 'Enter: Compile '.
+ 05 LINE 05 COL 62 VALUE 'Esc: Quit '.
+ *>
+ *> TOP SECTION PROGRAM INFO
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT.
+ 05 LINE 03 COL 14 PIC X(47) FROM Prog-Name.
+ 05 LINE 04 COL 14 PIC X(47) FROM Prog-Folder.
+ 05 LINE 05 COL 14 PIC X(47) FROM Prog-File-Name.
+ *>
+ *> MIDDLE LEFT SECTION F-KEYS
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT.
+ 05 LINE 09 COL 04 VALUE 'F1'.
+ 05 LINE 10 COL 04 VALUE 'F2'.
+ 05 LINE 11 COL 04 VALUE 'F3'.
+ 05 LINE 12 COL 04 VALUE 'F4'.
+ 05 LINE 13 COL 04 VALUE 'F5'.
+ 05 LINE 14 COL 04 VALUE 'F6'.
+ 05 LINE 15 COL 04 VALUE 'F7'.
+ 05 LINE 09 COL 32 VALUE 'F8'.
+ 05 LINE 10 COL 32 VALUE 'F9'.
+ *>
+ *> MIDDLE LEFT SECTION SWITCHES
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-RED HIGHLIGHT.
+ 05 LINE 09 COL 07 PIC X(1) FROM S-DEBUG.
+ 05 LINE 10 COL 07 PIC X(1) FROM S-DLL.
+ 05 LINE 11 COL 07 PIC X(1) FROM S-SUBROUTINE.
+ 05 LINE 12 COL 07 PIC X(1) FROM S-EXECUTE.
+ 05 LINE 13 COL 07 PIC X(1) FROM S-NOTRUNC.
+ 05 LINE 14 COL 07 PIC X(1) FROM S-TRACE.
+ 05 LINE 15 COL 07 PIC X(1) FROM S-TRACEALL.
+ 05 LINE 09 COL 35 PIC X(1) FROM S-SOURCE.
+ 05 LINE 10 COL 35 PIC X(1) FROM S-XREF.
+ *>
+ *> MIDDLE LEFT SECTION BACKGROUND
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-CYAN LOWLIGHT.
+ 05 LINE 09 COL 09 VALUE 'Compile debug lines '.
+ 05 LINE 10 COL 09 VALUE 'Always make DLLs '.
+ 05 LINE 11 COL 09 VALUE 'Pgm is a SUBROUTINE '.
+ 05 LINE 12 COL 09 VALUE 'Execute if compile OK '.
+ 05 LINE 13 COL 09 VALUE 'No COMP/BINARY trunc '.
+ 05 LINE 14 COL 09 VALUE 'Trace procedures '.
+ 05 LINE 15 COL 09 VALUE 'Trace proc + stmnts '.
+ 05 LINE 09 COL 37 VALUE 'Produce source listing'.
+ 05 LINE 10 COL 37 VALUE 'Produce xref listing '.
+ *>
+ *> MIDDLE RIGHT SECTION F-KEYS
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT.
+ 05 LINE 09 COL 62 VALUE 'S-F1'.
+ 05 LINE 10 COL 62 VALUE 'S-F2'.
+ 05 LINE 11 COL 62 VALUE 'S-F3'.
+ 05 LINE 12 COL 62 VALUE 'S-F4'.
+ 05 LINE 13 COL 62 VALUE 'S-F5'.
+ 05 LINE 14 COL 62 VALUE 'S-F6'.
+ 05 LINE 15 COL 62 VALUE 'S-F7'.
+ *>
+ *> MIDDLE RIGHT SECTION SWITCHES
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-RED HIGHLIGHT.
+ 05 LINE 09 COL 67 PIC X(1) FROM S-Cfg-BS2000.
+ 05 LINE 10 COL 67 PIC X(1) FROM S-Cfg-COBOL85.
+ 05 LINE 11 COL 67 PIC X(1) FROM S-Cfg-COBOL2002.
+ 05 LINE 12 COL 67 PIC X(1) FROM S-Cfg-DEFAULT.
+ 05 LINE 13 COL 67 PIC X(1) FROM S-Cfg-IBM.
+ 05 LINE 14 COL 67 PIC X(1) FROM S-Cfg-MF.
+ 05 LINE 15 COL 67 PIC X(1) FROM S-Cfg-MVS.
+ *>
+ *> MIDDLE RIGHT SECTION BACKGROUND
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-CYAN LOWLIGHT.
+ 05 LINE 09 COL 69 VALUE 'BS2000 '.
+ 05 LINE 10 COL 69 VALUE 'COBOL85 '.
+ 05 LINE 11 COL 69 VALUE 'COBOL2002 '.
+ 05 LINE 12 COL 69 VALUE 'Default '.
+ 05 LINE 13 COL 69 VALUE 'IBM '.
+ 05 LINE 14 COL 69 VALUE 'MicroFocus'.
+ 05 LINE 15 COL 69 VALUE 'MVS '.
+ *>
+ *> FREE-FORM OPTIONS FIELDS
+ *>
+ 03 BACKGROUND-COLOR COB-COLOR-BLACK
+ FOREGROUND-COLOR COB-COLOR-WHITE HIGHLIGHT.
+ 05 LINE 19 COL 04 PIC X(75) USING S-EXTRA.
+ 05 LINE 23 COL 04 PIC X(75) USING S-ARGS.
+ /
+ PROCEDURE DIVISION.
+ *****************************************************************
+ ** Legend to procedure names: **
+ ** **
+ ** 00x-xxx All MAIN driver procedures **
+ ** 0xx-xxx All GLOBAL UTILITY procedures **
+ ** 1xx-xxx All INITIALIZATION procedures **
+ ** 2xx-xxx All CORE PROCESSING procedures **
+ ** 9xx-xxx All TERMINATION procedures **
+ *****************************************************************
+ DECLARATIVES.
+ 000-File-Error SECTION.
+ USE AFTER STANDARD ERROR PROCEDURE ON Source-Code.
+ 000-Handle-Error.
+ COPY FileStat-Msgs
+ REPLACING STATUS BY FSM-Status
+ MSG BY FSM-Msg.
+ MOVE SPACES TO Output-Message
+ IF FSM-Status = 35
+ DISPLAY
+ 'File not found: "'
+ TRIM(File-Name,TRAILING)
+ '"'
+ END-DISPLAY
+ ELSE
+ DISPLAY
+ 'Error accessing file: "'
+ TRIM(File-Name,TRAILING)
+ '"'
+ END-DISPLAY
+ END-IF
+ GOBACK
+ .
+ END DECLARATIVES.
+ /
+ 000-Main SECTION.
+
+ PERFORM 100-Initialization
+GC0609 SET 88-Not-Complete TO TRUE
+GC0609 PERFORM UNTIL 88-Complete
+GC0609 PERFORM 200-Let-User-Set-Switches
+GC0609 PERFORM 210-Run-Compiler
+GC0410 IF (88-Compile-OK OR 88-Compile-OK-Warn)
+GC0410 AND (S-XREF NOT = SPACE OR S-SOURCE NOT = SPACE)
+GC0410 PERFORM 220-Make-Listing
+GC0410 END-IF
+GC0709 IF (S-EXECUTE NOT = SPACES)
+GC0709 AND (88-Output-File-Avail)
+GC0609 PERFORM 230-Run-Program
+GC0609 END-IF
+GC0609 END-PERFORM
+ .
+
+ 009-Done.
+ PERFORM 900-Terminate
+ .
+ * -- Control will NOT return
+ /
+ 010-Parse-Args SECTION.
+ *****************************************************************
+ ** Process a sequence of KEYWORD=VALUE items. These are items **
+ ** specified on the command-line to provide the initial **
+ ** options shown selected on the screen. When integrating **
+ ** OCic into an edirot or framework, include these switches on **
+ ** the ocic.exe command the editor/framework executes. Any **
+ ** underlined choice is the default value for that switch. **
+ ** **
+ ** @CONFIG=BS2000|COBOL85|COBOL2002|DEFAULT|IBM|MF|MVS **
+ ** ======= **
+ ** This switch specifies the default cobc compiler configura- **
+ ** tion file to be used **
+ ** **
+ ** @DEBUG=YES|NO **
+ ** == **
+ ** This switch specifies whether (YES) or not (NO) debugging **
+ ** lines (those with a "D" in column 7) will be compiled. **
+ ** **
+ ** @DLL=YES|NO **
+ ** == **
+ ** Use this switch to force ALL compiled programs to be built **
+ ** as DLLs ("@DLL=YES"). When main programs are built as DLLs **
+ ** they must be executed using the cobcrun utility. When **
+ ** "@DLL=NO" is in effect, main programs are generated as **
+ ** actual "exe" files and only subprograms will be generated **
+ ** as DLLs. **
+ ** **
+ ** @EXECUTE=YES|NO **
+ ** == **
+ ** This switch specifies whether ("@EXECUTE=YES") or not **
+ ** ("@EXECUTE=NO") the program will be executed after it is **
+ ** successfully compiled. **
+ ** **
+ ** @EXTRA=extra cobc argument(s) **
+ ** **
+ ** This switch allows you to specify additional cobc arguments **
+ ** that aren't managed by the other OC switches. If used, **
+ ** this must be the last switch specified on the command line, **
+ ** as everything that follows the "=" will be placed on the **
+ ** cobc command generated by OC. **
+ ** **
+ ** @NOTRUNC=YES|NO **
+ ** === **
+ ** This switch specifies whether (YES) or not (NO) the sup- **
+ ** pression of binary field truncation will occur. If a PIC **
+ ** 99 COMP field (one byte of storage), for example, is given **
+ ** the value 123, it may have its value truncated to 23 when **
+ ** DISPLAYed. Regardless of the NOTRUNC setting, internally **
+ ** the full precision of the field (allowing a maximum value **
+ ** of 255) will be preserved. Even though truncation - if it **
+ ** does occur - would appear to have a minimal disruption on **
+ ** program operation, it has a significant effect on program **
+ ** run-time speed. **
+ ** **
+ ** @TRACE=YES|NO|ALL **
+ ** == **
+ ** This switch controls whether or not code will be added to **
+ ** the object program to produce execution-time logic traces. **
+ ** A specification of "@TRACE=NO" means no such code will be **
+ ** produced. By specifying "@TRACE=YES", code will be genera- **
+ ** ted to display procedure names as they are entered. A **
+ ** "@TRACE=ALL" specification will generate not only procedure **
+ ** traces (as "@TRACE=YES" would) but also statement-level **
+ ** traces too! All trace output is written to STDERR, so **
+ ** adding a "2>file" to the execution of the program will pipe **
+ ** the trace output to a file. You may find it valuable to **
+ ** add your own DISPLAY statements to the debugging output via **
+ ** "DISPLAY xx UPON SYSERR" The SYSERR device corresponds to **
+ ** the Windows or UNIX STDERR device and will therefore honor **
+ ** any "2>file" placed at the end of your program's execution. **
+ ** Add a "D" in column 7 and you can control the generation or **
+ ** ignoring of these DISPLAY statements via the "@DEBUG" **
+ ** switch. **
+ ** **
+GC0410** @SOURCE=YES|NO **
+GC0410** == **
+GC0410** Use this switch to produce a source listing of the program, **
+GC0410** PROVIDED it compiles without errors. **
+ ** **
+GC0410** @XREF=YES|NO **
+GC0410** == **
+GC0410** Use this switch to produce a cross-reference listing of the **
+GC0410** program, PROVIDED it compiles without errors. **
+ *****************************************************************
+
+ 011-Init.
+ MOVE 1 TO I
+ .
+
+ 012-Extract-Kwd-And-Value.
+ PERFORM UNTIL I NOT < LENGTH(Command-Line-Args)
+ MOVE I TO J
+ UNSTRING Command-Line-Args
+ DELIMITED BY ALL SPACES
+ INTO Switch-Keyword-And-Value
+ WITH POINTER I
+ END-UNSTRING
+ IF Switch-Keyword-And-Value NOT = SPACES
+ UNSTRING Switch-Keyword-And-Value
+ DELIMITED BY '='
+ INTO Switch-Keyword, Switch-Value
+ END-UNSTRING
+ PERFORM 030-Process-Keyword
+ END-IF
+ END-PERFORM
+ .
+
+ 019-Done.
+ EXIT.
+
+ *****************************************************************
+ ** Since this program uses the SCREEN SECTION, it cannot do **
+ ** conventional console DISPLAY operations. This routine **
+ ** (which, I admit, is like using an H-bomb to hunt rabbits) **
+ ** will submit an "ECHO" command to the system to simulate a **
+ ** DISPLAY. **
+ *****************************************************************
+ 021-Build-And-Issue-Command.
+ DISPLAY
+ Output-Message
+ END-DISPLAY
+ .
+
+ 029-Done.
+ EXIT.
+ /
+ 030-Process-Keyword SECTION.
+ *****************************************************************
+ ** Process a single KEYWORD=VALUE item. **
+ *****************************************************************
+
+ 031-Init.
+ MOVE UPPER-CASE(Switch-Keyword) TO Switch-Keyword
+ SET 88-Switch-Is-Good TO TRUE
+ .
+
+ 032-Process.
+ EVALUATE TRUE
+ WHEN Switch-Is-EXTRA
+GC0410 MOVE J TO I
+ UNSTRING Command-Line-Args DELIMITED BY '='
+ INTO Dummy, S-EXTRA
+GC0410 WITH POINTER I
+GC0410 END-UNSTRING
+ MOVE LENGTH(Command-Line-Args) TO I
+ WHEN Switch-Is-CONFIG
+ MOVE 'CONFIG' TO Switch-Keyword
+ MOVE UPPER-CASE(Switch-Value)
+ TO Switch-Value
+ EVALUATE Switch-Value
+ WHEN 'BS2000'
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-BS2000
+ WHEN 'COBOL85'
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-COBOL85
+ WHEN 'COBOL2002'
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-COBOL2002
+ WHEN 'DEFAULT'
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-DEFAULT
+ WHEN 'IBM'
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-IBM
+ WHEN 'MF'
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-MF
+ WHEN 'MVS'
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-MVS
+ WHEN OTHER
+ MOVE 'An invalid /CONFIG switch value ' &
+ 'was specified on the command line ' &
+ '- ignored'
+ TO Output-Message
+ END-EVALUATE
+ WHEN Switch-Is-DEBUG
+ MOVE 'DEBUG' TO Switch-Keyword
+ MOVE UPPER-CASE(Switch-Value)
+ TO Switch-Value
+ PERFORM 040-Process-Yes-No-Value
+ IF 88-Switch-Is-Good
+ MOVE SV-1 TO S-DEBUG
+ END-IF
+GC0410 WHEN Switch-Is-DLL
+GC0410 MOVE 'DLL' TO Switch-Keyword
+GC0410 MOVE UPPER-CASE(Switch-Value)
+GC0410 TO Switch-Value
+GC0410 PERFORM 040-Process-Yes-No-Value
+GC0410 IF 88-Switch-Is-Good
+GC0410 MOVE SV-1 TO S-DLL
+GC0410 END-IF
+ WHEN Switch-Is-EXECUTE
+ MOVE 'EXECUTE' TO Switch-Keyword
+ MOVE UPPER-CASE(Switch-Value)
+ TO Switch-Value
+ PERFORM 040-Process-Yes-No-Value
+ IF 88-Switch-Is-Good
+ MOVE SV-1 TO S-EXECUTE
+ END-IF
+ WHEN Switch-Is-NOTRUNC
+ MOVE 'NOTRUNC' TO Switch-Keyword
+ MOVE UPPER-CASE(Switch-Value)
+ TO Switch-Value
+ PERFORM 040-Process-Yes-No-Value
+ IF 88-Switch-Is-Good
+ MOVE SV-1 TO S-NOTRUNC
+ END-IF
+GC0410 WHEN Switch-Is-SOURCE
+GC0410 MOVE 'SOURCE' TO Switch-Keyword
+GC0410 MOVE UPPER-CASE(Switch-Value)
+GC0410 TO Switch-Value
+GC0410 PERFORM 050-Process-Yes-No-All
+GC0410 IF 88-Switch-Is-Good
+GC0410 MOVE SV-1 TO S-SOURCE
+GC0410 END-IF
+ WHEN Switch-Is-TRACE
+ MOVE 'TRACE' TO Switch-Keyword
+ MOVE UPPER-CASE(Switch-Value)
+ TO Switch-Value
+ PERFORM 050-Process-Yes-No-All
+ IF 88-Switch-Is-Good
+ MOVE SV-1 TO S-TRACE
+ END-IF
+GC0410 WHEN Switch-Is-XREF
+GC0410 MOVE 'XREF' TO Switch-Keyword
+GC0410 MOVE UPPER-CASE(Switch-Value)
+GC0410 TO Switch-Value
+GC0410 PERFORM 050-Process-Yes-No-All
+GC0410 IF 88-Switch-Is-Good
+GC0410 MOVE SV-1 TO S-XREF
+GC0410 END-IF
+ WHEN OTHER
+ MOVE SPACES TO Output-Message
+ STRING '"'
+ TRIM(Switch-Keyword)
+ '" is not a valid switch ' &
+ '- ignored'
+ DELIMITED SIZE
+ INTO Output-Message
+ END-STRING
+ SET 88-Switch-Is-Bad TO TRUE
+ END-EVALUATE
+ .
+
+ 039-Done.
+ EXIT.
+ /
+ 040-Process-Yes-No-Value SECTION.
+ *****************************************************************
+ ** Process a switch value of YES or NO **
+ *****************************************************************
+
+ 042-Process.
+ EVALUATE SV-1
+ WHEN 'Y'
+ MOVE 'YES' TO Switch-Value
+ WHEN 'N'
+ MOVE 'NO' To Switch-Value
+ WHEN OTHER
+ MOVE SPACES TO Output-Message
+ STRING '*ERROR: "' TRIM(Switch-Value)
+ '" is not a valid value for the "'
+ TRIM(Switch-Keyword) '" switch'
+ DELIMITED SPACES
+ INTO Output-Message
+ END-STRING
+ SET 88-Switch-Is-Bad TO TRUE
+ END-EVALUATE
+ .
+
+ 049-Done.
+ EXIT.
+ /
+ 050-Process-Yes-No-All SECTION.
+ *****************************************************************
+ ** Process a switch value of YES, NO or ALL **
+ *****************************************************************
+
+ 052-Process.
+ IF SV-1 = 'A'
+ MOVE 'ALL' TO Switch-Value
+ ELSE
+ PERFORM 040-Process-Yes-No-Value
+ END-IF
+ .
+
+ 059-Done.
+ EXIT.
+ /
+ 060-Process-Yes-No-Auto SECTION.
+ *****************************************************************
+ ** Process a switch value of YES, NO or AUTO **
+ *****************************************************************
+
+ 061-Init.
+ IF SV-1 = 'A'
+ PERFORM 070-Find-LINKAGE-SECTION
+ IF 88-Compile-As-Subpgm
+ MOVE 'Y' TO Switch-Value
+ ELSE
+ MOVE 'N' TO Switch-Value
+ END-IF
+ ELSE
+ PERFORM 040-Process-Yes-No-Value
+ END-IF
+ .
+ /
+ 070-Find-LINKAGE-SECTION SECTION.
+ *****************************************************************
+ ** Determine if the program being compiled is a MAIN program **
+ *****************************************************************
+
+ 071-Init.
+ OPEN INPUT Source-Code
+ SET 88-Compile-As-Mainpgm TO TRUE
+ SET 88-More-To-1st-Prog TO TRUE
+ PERFORM UNTIL 88-1st-Prog-Complete
+ READ Source-Code AT END
+ CLOSE Source-Code
+ EXIT SECTION
+ END-READ
+ CALL 'CHECKSOURCE' USING Source-Code-Record
+ F-Source-Record-Type
+ END-CALL
+ IF 88-Source-Rec-Ident
+ SET 88-1st-Prog-Complete TO TRUE
+ END-IF
+ END-PERFORM
+ .
+
+ 072-Process-Source.
+ SET 88-Source-Rec-IgnoCOB-COLOR-RED TO TRUE
+ PERFORM UNTIL 88-Source-Rec-Linkage
+ OR 88-Source-Rec-Ident
+ READ Source-Code AT END
+ CLOSE Source-Code
+ EXIT SECTION
+ END-READ
+ CALL 'CHECKSOURCE' USING Source-Code-Record
+ F-Source-Record-Type
+ END-CALL
+ END-PERFORM
+ CLOSE Source-Code
+ IF 88-Source-Rec-Linkage
+ SET 88-Compile-As-Subpgm TO TRUE
+ END-IF
+ .
+
+ 079-Done.
+ EXIT.
+ /
+ 100-Initialization SECTION.
+ *****************************************************************
+ ** Perform all program-wide initialization operations **
+ *****************************************************************
+
+
+GC0909 101-Determine-OS-Type.
+GC0909 CALL 'GETOSTYPE'
+GC0909 END-CALL
+GC0909 MOVE RETURN-CODE TO OS-Type
+GC0909 EVALUATE TRUE
+GC0909 WHEN OS-Unknown
+GC0909 MOVE '\' TO Dir-Char
+GC0909 MOVE 'Unknown' TO OS-Type-Literal
+GC0310 MOVE COB-SCR-F11 TO CK-S-F1
+GC0310 MOVE COB-SCR-F12 TO CK-S-F2
+GC0310 MOVE COB-SCR-F13 TO CK-S-F3
+GC0310 MOVE COB-SCR-F14 TO CK-S-F4
+GC0310 MOVE COB-SCR-F15 TO CK-S-F5
+GC0310 MOVE COB-SCR-F16 TO CK-S-F6
+GC0310 MOVE COB-SCR-F17 TO CK-S-F7
+GC0909 WHEN OS-Windows
+GC0909 MOVE '\' TO Dir-Char
+GC0909 MOVE 'Windows' TO OS-Type-Literal
+GC0310 MOVE COB-SCR-F13 TO CK-S-F1
+GC0310 MOVE COB-SCR-F14 TO CK-S-F2
+GC0310 MOVE COB-SCR-F15 TO CK-S-F3
+GC0310 MOVE COB-SCR-F16 TO CK-S-F4
+GC0310 MOVE COB-SCR-F17 TO CK-S-F5
+GC0310 MOVE COB-SCR-F18 TO CK-S-F6
+GC0310 MOVE COB-SCR-F19 TO CK-S-F7
+GC0909 WHEN OS-Cygwin
+GC0909 MOVE '/' TO Dir-Char
+GC0410 MOVE 'Cygwin' TO OS-Type-Literal
+GC0310 MOVE COB-SCR-F11 TO CK-S-F1
+GC0310 MOVE COB-SCR-F12 TO CK-S-F2
+GC0310 MOVE COB-SCR-F13 TO CK-S-F3
+GC0310 MOVE COB-SCR-F14 TO CK-S-F4
+GC0310 MOVE COB-SCR-F15 TO CK-S-F5
+GC0310 MOVE COB-SCR-F16 TO CK-S-F6
+GC0310 MOVE COB-SCR-F17 TO CK-S-F7
+GC0909 WHEN OS-UNIX
+GC0909 MOVE '/' TO Dir-Char
+GC0410 MOVE 'UNIX ' TO OS-Type-Literal
+GC0310 MOVE COB-SCR-F11 TO CK-S-F1
+GC0310 MOVE COB-SCR-F12 TO CK-S-F2
+GC0310 MOVE COB-SCR-F13 TO CK-S-F3
+GC0310 MOVE COB-SCR-F14 TO CK-S-F4
+GC0310 MOVE COB-SCR-F15 TO CK-S-F5
+GC0310 MOVE COB-SCR-F16 TO CK-S-F6
+GC0310 MOVE COB-SCR-F17 TO CK-S-F7
+GC0909 END-EVALUATE
+GC0909 .
+
+ 102-Set-Environment-Vars.
+ SET ENVIRONMENT 'COB_SCREEN_EXCEPTIONS' TO 'Y'
+ SET ENVIRONMENT 'COB_SCREEN_ESC' TO 'Y'
+ .
+
+ 103-Generate-Cobc-Output-Fn.
+ ACCEPT Env-TEMP
+ FROM ENVIRONMENT "TEMP"
+ END-ACCEPT
+ MOVE SPACES TO Cobc-Output-File
+ STRING TRIM(Env-TEMP,TRAILING)
+GC0909 Dir-Char
+GC0909 'OC-Messages.TXT'
+ DELIMITED SIZE
+ INTO Cobc-Output-File
+ END-STRING
+ .
+
+ 104-Generate-Banner-Line-Info.
+ MOVE WHEN-COMPILED (1:12) TO OC-Compiled
+ INSPECT OC-Compiled
+ REPLACING ALL '/' BY ':'
+ AFTER INITIAL SPACE
+ .
+
+ 105-Establish-Switch-Settings.
+ ACCEPT Command-Line-Args
+ FROM COMMAND-LINE
+ END-ACCEPT
+ MOVE TRIM(Command-Line-Args, Leading)
+ TO Command-Line-Args
+ MOVE 0 TO Tally
+GC0410 INSPECT Command-Line-Args TALLYING Tally FOR ALL '@'
+ IF Tally = 0
+ MOVE Command-Line-Args TO File-Name
+ MOVE SPACES TO Command-Line-Args
+ ELSE
+GC0410 UNSTRING Command-Line-Args DELIMITED BY '@'
+ INTO File-Name, Dummy
+ END-UNSTRING
+ INSPECT Command-Line-Args
+GC0410 REPLACING FIRST '@' BY LOW-VALUES
+ UNSTRING Command-Line-Args
+ DELIMITED BY LOW-VALUES
+ INTO Dummy, Cmd
+ END-UNSTRING
+ MOVE SPACES TO Command-Line-Args
+GC0410 STRING '@' Cmd DELIMITED SIZE
+ INTO Command-Line-Args
+ END-STRING
+ END-IF
+ IF File-Name = SPACES
+ DISPLAY
+ 'No program filename was specified'
+ END-DISPLAY
+ PERFORM 900-Terminate
+ END-IF
+ PERFORM 010-Parse-Args
+ IF S-SUBROUTINE = 'A'
+ MOVE 'S' TO Switch-Keyword
+ MOVE 'A' TO Switch-Value
+ PERFORM 070-Find-LINKAGE-SECTION
+ IF 88-Compile-As-Subpgm
+ MOVE 'Y' TO S-SUBROUTINE
+ ELSE
+ MOVE 'N' TO S-SUBROUTINE
+ END-IF
+ END-IF
+ INSPECT S-Yes-No-Switches REPLACING ALL 'Y' BY Selection-Char
+ INSPECT S-Yes-No-Switches REPLACING ALL 'N' BY ' '
+ .
+
+ 106-Determine-Folder-Path.
+ Move 256 TO I
+GC0909 IF OS-Cygwin AND File-Name (2:1) = ':'
+GC0909 MOVE '\' TO Dir-Char
+GC0909 END-IF
+ PERFORM UNTIL I = 0 OR FN-Char (I) = Dir-Char
+ SUBTRACT 1 FROM I
+ END-PERFORM
+ IF I = 0
+ MOVE SPACES TO Prog-Folder
+ MOVE File-Name TO Prog-File-Name
+ ELSE
+ MOVE '*' TO FN-Char (I)
+ UNSTRING File-Name DELIMITED BY '*'
+ INTO Prog-Folder
+ Prog-File-Name
+ END-UNSTRING
+ MOVE Dir-Char TO FN-Char (I)
+ END-IF
+ UNSTRING Prog-File-Name DELIMITED BY '.'
+ INTO Prog-Name, Prog-Extension
+ END-UNSTRING
+ IF Prog-Folder = SPACES
+ ACCEPT Prog-Folder
+ FROM ENVIRONMENT 'CD'
+ END-ACCEPT
+GC0909 ELSE
+GC0909 CALL "CBL_CHANGE_DIR"
+GC0909 USING TRIM(Prog-Folder,TRAILING)
+GC0909 END-CALL
+ END-IF
+GC0909 IF OS-Cygwin AND File-Name (2:1) = ':'
+GC0909 MOVE '/' TO Dir-Char
+GC0909 END-IF
+ .
+
+GC0909 107-Other.
+GC0909 MOVE ALL LD-Horiz-Line TO Horizontal-Line.
+GC0410 MOVE CONCATENATE(' OCic for ',
+GC0410 TRIM(OS-Type-Literal,Trailing),
+GC0410 ' Copyright (C) 2009-2010, Gary L. Cutler,',
+GC0410 ' GPL')
+GC0410 TO Output-Message.
+GC0909 .
+GC0909
+ 109-Done.
+ EXIT.
+ /
+ 200-Let-User-Set-Switches SECTION.
+ *****************************************************************
+ ** Show the user the current switch settings and allow them to **
+ ** be changed. **
+ *****************************************************************
+
+ 201-Init.
+ SET 88-Switch-Changes TO TRUE
+ .
+
+ 202-Show-And-Change-Switches.
+ PERFORM UNTIL 88-No-Switch-Changes
+ ACCEPT
+ Switches-Screen
+ END-ACCEPT
+ IF COB-CRT-STATUS > 0
+ EVALUATE COB-CRT-STATUS
+ WHEN COB-SCR-F1
+ IF S-DEBUG = SPACE
+ MOVE Selection-Char TO S-DEBUG
+ ELSE
+ MOVE ' ' TO S-DEBUG
+ END-IF
+ WHEN COB-SCR-F2
+ IF S-DLL = SPACE
+ MOVE Selection-Char TO S-DLL
+ ELSE
+ MOVE ' ' TO S-DLL
+ END-IF
+ WHEN COB-SCR-F3
+ IF S-SUBROUTINE = SPACE
+ MOVE Selection-Char TO S-SUBROUTINE
+ MOVE ' ' TO S-EXECUTE
+ ELSE
+ MOVE ' ' TO S-SUBROUTINE
+ END-IF
+ WHEN COB-SCR-F4
+ IF S-EXECUTE = SPACE
+ AND S-SUBROUTINE = SPACE
+ MOVE Selection-Char TO S-EXECUTE
+ ELSE
+ MOVE ' ' TO S-EXECUTE
+ END-IF
+ WHEN COB-SCR-F5
+ IF S-NOTRUNC = SPACE
+ MOVE Selection-Char TO S-NOTRUNC
+ ELSE
+ MOVE ' ' TO S-NOTRUNC
+ END-IF
+ WHEN COB-SCR-F6
+ IF S-TRACE = SPACE
+ MOVE Selection-Char TO S-TRACE
+ MOVE ' ' TO S-TRACEALL
+ ELSE
+ MOVE ' ' TO S-TRACE
+ END-IF
+ WHEN COB-SCR-F7
+ IF S-TRACEALL = SPACE
+ MOVE Selection-Char TO S-TRACEALL
+ MOVE ' ' TO S-TRACE
+ ELSE
+ MOVE ' ' TO S-TRACEALL
+ END-IF
+GC0410 WHEN COB-SCR-F8
+GC0410 IF S-SOURCE = SPACE
+GC0410 MOVE Selection-Char TO S-SOURCE
+GC0410 ELSE
+GC0410 MOVE ' ' TO S-SOURCE
+GC0410 END-IF
+GC0410 WHEN COB-SCR-F9
+GC0410 IF S-XREF = SPACE
+GC0410 MOVE Selection-Char TO S-XREF
+GC0410 ELSE
+GC0410 MOVE ' ' TO S-XREF
+GC0410 END-IF
+ WHEN COB-SCR-ESC
+ PERFORM 900-Terminate
+GC0310 WHEN CK-S-F1
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-BS2000
+GC0310 WHEN CK-S-F2
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-COBOL85
+GC0310 WHEN CK-S-F3
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-COBOL2002
+GC0310 WHEN CK-S-F4
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-DEFAULT
+GC0310 WHEN CK-S-F5
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-IBM
+GC0310 WHEN CK-S-F6
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-MF
+GC0310 WHEN CK-S-F7
+ MOVE SPACES TO S-CfgS
+ MOVE Selection-Char TO S-Cfg-MVS
+ WHEN OTHER
+ MOVE 'An unsupported key was pressed'
+ TO Output-Message
+ END-EVALUATE
+ ELSE
+ SET 88-No-Switch-Changes TO TRUE
+ END-IF
+ END-PERFORM
+ .
+
+ 209-Done.
+ EXIT.
+ /
+ 210-Run-Compiler SECTION.
+ *****************************************************************
+ ** Run the compiler using the switch settings we've prepared. **
+ *****************************************************************
+
+ 211-Init.
+ MOVE SPACES TO Cmd
+ Cobc-Cmd
+ Output-Message
+ DISPLAY
+ Switches-Screen
+ END-DISPLAY
+ MOVE 1 TO I
+ EVALUATE TRUE
+ WHEN S-Cfg-BS2000 NOT = SPACES
+ MOVE 'bs2000' TO Config-File
+ WHEN S-Cfg-COBOL85 NOT = SPACES
+ MOVE 'cobol85' TO Config-File
+ WHEN S-Cfg-COBOL2002 NOT = SPACES
+ MOVE 'cobol2002' TO Config-File
+ WHEN S-Cfg-IBM NOT = SPACES
+ MOVE 'ibm' TO Config-File
+ WHEN S-Cfg-MF NOT = SPACES
+ MOVE 'mf' TO Config-File
+ WHEN S-Cfg-MVS NOT = SPACES
+ MOVE 'mvs' TO Config-File
+ WHEN OTHER
+ MOVE 'default' TO Config-File
+ END-EVALUATE
+ .
+
+ 212-Build-Compile-Command.
+GC0909 MOVE SPACES TO Cobc-Cmd
+GC0909 STRING 'cobc -std='
+GC0909 TRIM(Config-File,TRAILING)
+GC0909 ' '
+GC0909 INTO Cobc-Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+ IF S-SUBROUTINE NOT = ' '
+ STRING '-m '
+ DELIMITED SIZE INTO Cobc-Cmd
+ WITH POINTER I
+ END-STRING
+ ELSE
+ STRING '-x '
+ DELIMITED SIZE INTO Cobc-Cmd
+ WITH POINTER I
+ END-STRING
+ END-IF
+ IF S-DEBUG NOT = ' '
+ STRING '-fdebugging-line '
+ DELIMITED SIZE INTO Cobc-Cmd
+ WITH POINTER I
+ END-STRING
+ END-IF
+ IF S-NOTRUNC NOT = ' '
+ STRING '-fnotrunc '
+ DELIMITED SIZE INTO Cobc-Cmd
+ WITH POINTER I
+ END-STRING
+ END-IF
+ IF S-TRACEALL NOT = ' '
+GC0809 STRING '-ftraceall '
+ DELIMITED SIZE INTO Cobc-Cmd
+ WITH POINTER I
+ END-STRING
+ END-IF
+ IF S-TRACE NOT = ' '
+ STRING '-ftrace '
+ DELIMITED SIZE INTO Cobc-Cmd
+ WITH POINTER I
+ END-STRING
+ END-IF
+
+GC0709 IF S-EXTRA > SPACES
+GC0709 STRING ' '
+GC0709 TRIM(S-Extra,TRAILING)
+GC0709 ' '
+GC0709 DELIMITED SIZE INTO Cobc-Cmd
+GC0709 WITH POINTER I
+GC0709 END-STRING
+GC0709 END-IF
+GC0909 STRING TRIM(Prog-File-Name,TRAILING)
+GC0909 DELIMITED SIZE INTO Cobc-Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+ .
+
+ 213-Run-Compiler.
+GC0410 MOVE ' Compiling...' TO Output-Message
+GC0410 DISPLAY
+GC0410 Switches-Screen
+GC0410 END-DISPLAY
+GC0609 SET 88-Output-File-Avail TO TRUE
+ MOVE SPACES TO Cmd
+ STRING TRIM(Cobc-Cmd,TRAILING)
+ ' 2>'
+ TRIM(Cobc-Output-File,TRAILING)
+ DELIMITED SIZE
+ INTO Cmd
+ END-STRING
+ CALL 'SYSTEM'
+ USING TRIM(Cmd,TRAILING)
+ END-CALL
+GC0909 IF RETURN-CODE = 0
+GC0909 SET 88-Compile-OK TO TRUE
+GC0909 ELSE
+GC0909 SET 88-Compile-Failed TO TRUE
+GC0909 END-IF
+GC0909 IF 88-Compile-OK
+GC0909 OPEN INPUT Cobc-Output
+GC0909 READ Cobc-Output
+GC0909 AT END
+GC0909 CONTINUE
+GC0909 NOT AT END
+GC0909 SET 88-Compile-OK-Warn TO TRUE
+GC0909 END-READ
+GC0909 CLOSE Cobc-Output
+GC0909 END-IF
+GC0909 MOVE SPACES TO Output-Message
+ IF 88-Compile-OK
+GC0909 MOVE ' Compilation Was Successful' TO Output-Message
+GC0909 DISPLAY
+GC0909 Switches-Screen
+GC0909 END-DISPLAY
+GC0909 CALL 'C$SLEEP'
+GC0909 USING 2
+GC0909 END-CALL
+GC0909 MOVE SPACES TO Output-Message
+GC0609 SET 88-Complete TO TRUE
+ ELSE
+GC0909 DISPLAY
+GC0909 Blank-Screen
+GC0909 END-DISPLAY
+GC0909 IF 88-Compile-OK-Warn
+GC0909 DISPLAY ' Compilation was successful, but ' &
+GC0909 'warnings were generated:'
+SCROLL* AT LINE 24 COLUMN 1
+SCROLL* WITH SCROLL UP 1 LINE
+GC0909 END-DISPLAY
+GC0909 ELSE
+GC0909 DISPLAY 'Compilation Failed:'
+SCROLL* AT LINE 24 COLUMN 1
+SCROLL* WITH SCROLL UP 1 LINE
+GC0909 END-DISPLAY
+GC0909 END-IF
+GC0609 SET 88-Compile-Failed TO TRUE
+GC0609 SET 88-Complete TO TRUE
+GC0909 DISPLAY ' '
+SCROLL* AT LINE 24 COLUMN 1
+SCROLL* WITH SCROLL UP 1 LINE
+GC0909 END-DISPLAY
+GC0909 OPEN INPUT Cobc-Output
+GC0909 PERFORM FOREVER
+GC0909 READ Cobc-Output AT END
+GC0909 EXIT PERFORM
+GC0909 END-READ
+GC0909 DISPLAY TRIM(Cobc-Output-Rec,TRAILING)
+SCROLL* AT LINE 24 COLUMN 1
+SCROLL* WITH SCROLL UP 1 LINE
+GC0909 END-DISPLAY
+GC0909 END-PERFORM
+GC0909 CLOSE Cobc-Output
+GC0909 DISPLAY ' '
+SCROLL* AT LINE 24 COLUMN 1
+SCROLL* WITH SCROLL UP 2 LINES
+GC0909 END-DISPLAY
+GC0909 DISPLAY 'Press ENTER to close:'
+SCROLL* AT LINE 24 COLUMN 1
+SCROLL* WITH SCROLL UP 1 LINE
+GC0909 END-DISPLAY
+GC0909 ACCEPT Dummy
+GC0909 FROM CONSOLE
+GC0909 END-ACCEPT
+GC0909 DISPLAY
+GC0909 Blank-Screen
+GC0909 END-DISPLAY
+ END-IF
+ .
+
+ 219-Done.
+ IF 88-Compile-Failed
+ PERFORM 900-Terminate
+ END-IF
+ .
+ /
+GC0410 220-Make-Listing SECTION.
+GC0410*****************************************************************
+GC0410** Generate a source and/or xref listing using XREF **
+GC0410*****************************************************************
+GC0410
+GC0410 221-Init.
+GC0410 MOVE ' Generating cross-reference listing...'
+GC0410 TO Output-Message
+GC0410 DISPLAY
+GC0410 Switches-Screen
+GC0410 END-DISPLAY
+GC0410 CALL "CBL_DELETE_FILE"
+GC0410 USING CONCATENATE(TRIM(Prog-Name,Trailing),".lst")
+GC0410 END-CALL
+GC0410 MOVE 0 TO RETURN-CODE
+GC0410 .
+GC0410
+GC0410 213-Run-OCXref.
+GC0410 MOVE SPACES TO Output-Message
+GC0410 CALL 'LISTING'
+GC0410 USING S-SOURCE
+GC0410 S-XREF
+GC0410 File-Name
+GC0410 ON EXCEPTION
+GC0410 MOVE ' LISTING module is not available'
+GC0410 TO Output-Message
+GC0410 MOVE 1 TO RETURN-CODE
+GC0410 END-CALL
+GC0410 IF RETURN-CODE = 0
+GC0410 MOVE ' Listing generated'
+GC0410 TO Output-Message
+GC0410 IF OS-Windows OR OS-Cygwin
+GC0410 MOVE SPACES TO Cmd
+GC0410 STRING
+GC0410 'cmd /c '
+GC0410 TRIM(Prog-Name,TRAILING)
+GC0410 '.lst'
+GC0410 DELIMITED SIZE INTO Cmd
+GC0410 END-STRING
+GC0410 CALL 'SYSTEM'
+GC0410 USING TRIM(Cmd,TRAILING)
+GC0410 END-CALL
+GC0410 END-IF
+GC0410 ELSE
+GC0410 IF Output-Message = SPACES
+GC0410 MOVE ' Listing generation failed'
+GC0410 TO Output-Message
+GC0410 END-IF
+GC0410 END-IF
+GC0410 DISPLAY
+GC0410 Switches-Screen
+GC0410 END-DISPLAY
+GC0410 CALL 'C$SLEEP'
+GC0410 USING 2
+GC0410 END-CALL
+GC0410 .
+ /
+ 230-Run-Program SECTION.
+ *****************************************************************
+ ** Run the compiled program **
+ *****************************************************************
+
+ 232-Build-Command.
+GC0909 MOVE SPACES TO Cmd
+GC0909 MOVE 1 TO I
+ IF S-SUBROUTINE NOT = ' '
+ OR S-DLL NOT = ' '
+ STRING 'cobcrun ' DELIMITED SIZE
+ INTO Cmd
+ WITH POINTER I
+ END-STRING
+ END-IF
+ IF Prog-Folder NOT = SPACES
+GC0909 IF OS-Cygwin AND Prog-Folder (2:1) = ':'
+GC0909 STRING '/cygdrive/'
+GC0909 INTO Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+GC0909 STRING LOWER-CASE(Prog-Folder (1:1))
+GC0909 INTO Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+GC0909 PERFORM VARYING J FROM 3 BY 1
+GC0909 UNTIL J > LENGTH(TRIM(Prog-Folder))
+GC0909 IF Prog-Folder (J:1) = '\'
+GC0909 STRING '/'
+GC0909 INTO Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+GC0909 ELSE
+GC0909 STRING Prog-Folder (J:1)
+GC0909 INTO Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+GC0909 END-IF
+GC0909 END-PERFORM
+GC0909 ELSE
+GC0410 STRING '"' TRIM(Prog-Folder,TRAILING)
+GC0909 INTO Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+GC0909 END-IF
+GC0909 STRING Dir-Char
+GC0909 INTO Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+GC0909 ELSE
+GC0909 IF OS-Cygwin OR OS-UNIX
+GC0909 STRING './'
+GC0909 INTO Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+GC0909 END-IF
+ END-IF
+GC0909 STRING TRIM(Prog-Name,TRAILING)
+GC0909 INTO Cmd
+GC0909 WITH POINTER I
+GC0909 END-STRING
+GC0909 IF S-SUBROUTINE = ' '
+GC0909 AND S-DLL NOT = ' '
+GC0909 STRING '.exe' DELIMITED SIZE
+ INTO Cmd
+ WITH POINTER I
+ END-STRING
+ END-IF
+ IF S-ARGS NOT = SPACES
+GC0809 STRING ' ' TRIM(S-ARGS,TRAILING)
+ INTO Cmd
+ WITH POINTER I
+ END-STRING
+ END-IF
+ IF OS-Unknown OR OS-Windows
+GC0410 STRING '"&&pause'
+ INTO Cmd
+ WITH POINTER I
+ END-STRING
+ ELSE
+ STRING ';echo "Press ENTER to close...";read'
+ INTO Cmd
+ WITH POINTER I
+ END-STRING
+ END-IF
+ .
+
+ 233-Run-Program.
+GC0909 DISPLAY
+GC0909 Blank-Screen
+GC0909 END-DISPLAY
+
+ CALL 'SYSTEM'
+ USING TRIM(Cmd,TRAILING)
+ END-CALL
+ PERFORM 900-Terminate
+ .
+
+ 239-Done.
+ EXIT.
+ /
+ 900-Terminate SECTION.
+ *****************************************************************
+ ** Display a message and halt the program **
+ *****************************************************************
+
+ 901-Display-Message.
+GC0909 IF Output-Message > SPACES
+GC0909 DISPLAY
+GC0909 Switches-Screen
+GC0909 END-DISPLAY
+GC0909 CALL 'C$SLEEP'
+GC0909 USING 2
+GC0909 END-CALL
+GC0909 END-IF
+ DISPLAY
+ Blank-Screen
+ END-DISPLAY
+ .
+
+ 909-Done.
+ GOBACK
+ .
+
+ END PROGRAM OCic.
+
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. GETOSTYPE.
+ *****************************************************************
+ ** This subprogram determine the OS type the program is run- **
+ ** ning under, passing that result back in RETURN-CODE as fol- **
+ ** lows: **
+ ** **
+ ** 0: Cannot be determined **
+ ** 1: Native Windows or Windows/MinGW **
+ ** 2: Cygwin **
+ ** 3: UNIX/Linux/MacOS **
+ *****************************************************************
+ ** DATE CHANGE DESCRIPTION **
+ ** ====== ==================================================== **
+ ** GC0909 Initial coding. **
+ *****************************************************************
+ ENVIRONMENT DIVISION.
+ CONFIGURATION SECTION.
+ REPOSITORY.
+ FUNCTION ALL INTRINSIC.
+ DATA DIVISION.
+ WORKING-STORAGE SECTION.
+ 01 Env-Path PIC X(1024).
+ 01 Tally USAGE BINARY-LONG.
+ PROCEDURE DIVISION.
+ 000-Main SECTION.
+ 010-Get-TEMP-Var.
+ MOVE SPACES TO Env-Path
+ ACCEPT Env-Path
+ FROM ENVIRONMENT "PATH"
+ ON EXCEPTION
+ MOVE 0 TO RETURN-CODE
+ GOBACK
+ END-ACCEPT
+ IF Env-Path = SPACES
+ MOVE 0 TO RETURN-CODE
+ ELSE
+ MOVE 0 TO Tally
+ INSPECT Env-Path
+ TALLYING Tally FOR ALL ";"
+ IF Tally = 0 *> Must be some form of UNIX
+ MOVE 0 TO Tally
+ INSPECT Env-Path
+ TALLYING TALLY FOR ALL "/cygdrive/"
+ IF Tally = 0 *> UNIX/MacOS
+ MOVE 3 TO RETURN-CODE
+ ELSE *> Cygwin
+ MOVE 2 TO RETURN-CODE
+ END-IF
+ ELSE *> Assume Windows[/MinGW]
+ MOVE 1 TO RETURN-CODE
+ END-IF
+ END-IF
+ GOBACK
+ .
+ END PROGRAM GETOSTYPE.
+
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. CHECKSOURCE.
+ *****************************************************************
+ ** This subprogram will scan a line of source code it is given **
+ ** looking for "LINKAGE SECTION" or "IDENTIFICATION DIVISION". **
+ ** **
+ ** ****NOTE**** ****NOTE**** ****NOTE**** ****NOTE*** **
+ ** **
+ ** These two strings must be found IN THEIR ENTIRETY within **
+ ** the 1st 80 columns of program source records, and cannot **
+ ** follow either a "*>" sequence OR a "*" in col 7. **
+ *****************************************************************
+ ** DATE CHANGE DESCRIPTION **
+ ** ====== ==================================================== **
+ ** GC0809 Initial coding. **
+ *****************************************************************
+ ENVIRONMENT DIVISION.
+ CONFIGURATION SECTION.
+ REPOSITORY.
+ FUNCTION ALL INTRINSIC.
+ DATA DIVISION.
+ WORKING-STORAGE SECTION.
+ 01 Compressed-Src.
+ 05 CS-Char OCCURS 80 TIMES PIC X(1).
+
+ 01 Flags.
+ 05 F-Found-SPACE PIC X(1).
+ 88 88-Skipping-SPACE VALUE 'Y'.
+ 88 88-Not-Skipping-SPACE VALUE 'N'.
+
+ 01 I USAGE BINARY-CHAR.
+
+ 01 J USAGE BINARY-CHAR.
+ LINKAGE SECTION.
+ 01 Argument-1.
+ 02 A1-Char OCCURS 80 TIMES PIC X(1).
+
+ 01 Argument-2 PIC X(1).
+ 88 88-A2-LINKAGE-SECTION VALUE 'L'.
+ 88 88-A2-IDENTIFICATION-DIVISION VALUE 'I'.
+ 88 88-A2-Nothing-Special VALUE ' '.
+ PROCEDURE DIVISION USING Argument-1, Argument-2.
+ 000-Main SECTION.
+
+ 010-Initialize.
+ SET 88-A2-Nothing-Special TO TRUE
+ IF A1-Char (7) = '*'
+ GOBACK
+ END-IF
+ .
+
+ 020-Compress-Multiple-SPACES.
+ SET 88-Not-Skipping-SPACE TO TRUE
+ MOVE 0 TO J
+ MOVE SPACES TO Compressed-Src
+ PERFORM VARYING I FROM 1 BY 1
+ UNTIL I > 80
+ IF A1-Char (I) = SPACE
+ IF 88-Not-Skipping-SPACE
+ ADD 1 TO J
+ MOVE UPPER-CASE(A1-Char (I)) TO CS-Char (J)
+ SET 88-Skipping-SPACE TO TRUE
+ END-IF
+ ELSE
+ SET 88-Not-Skipping-SPACE TO TRUE
+ ADD 1 TO J
+ MOVE A1-Char (I) TO CS-Char (J)
+ END-IF
+ END-PERFORM
+ .
+
+ 030-Scan-Compressed-Src.
+ PERFORM VARYING I FROM 1 BY 1
+ UNTIL I > 66
+ EVALUATE TRUE
+ WHEN CS-Char (I) = '*'
+ IF Compressed-Src (I : 2) = '*>'
+ GOBACK
+ END-IF
+ WHEN (CS-Char (I) = 'L') AND (I < 66)
+ IF Compressed-Src (I : 15) = 'LINKAGE SECTION'
+ SET 88-A2-LINKAGE-SECTION TO TRUE
+ GOBACK
+ END-IF
+ WHEN (CS-Char (I) = 'I') AND (I < 58)
+ IF Compressed-Src (I : 23) = 'IDENTIFICATION ' &
+ 'DIVISION'
+ SET 88-A2-IDENTIFICATION-DIVISION TO TRUE
+ GOBACK
+ END-IF
+ END-EVALUATE
+ END-PERFORM
+ .
+
+ 099-Never-Found-Either-One.
+ GOBACK
+ .
+ END PROGRAM CHECKSOURCE.
+
+ IDENTIFICATION DIVISION.
+ PROGRAM-ID. LISTING.
+ *****************************************************************
+ ** This subprogram generates a cross-reference listing of an **
+ ** OpenCOBOL program. **
+ ** **
+ ** Linkage: CALL "LISTING" USING <source> **
+ ** <xref> **
+ ** <filename> **
+ ** **
+ ** Where: **
+ ** <source> is a PIC X(1) flag indicating **
+ ** whether or not a source listing **
+ ** should be produced (space=NO, **
+ ** non-space=yes) **
+ ** <xref> is a PIC X(1) flag indicating **
+ ** whether or not an xref listing **
+ ** should be produced (space=NO, **
+ ** non-space=yes) **
+ ** <filename> is the [path]filename of the **
+ ** program being listed and/or **
+ ** xreffed in a PIC X(256) form. **
+ *****************************************************************
+ ** **
+ ** AUTHOR: GARY L. CUTLER **
+ ** CutlerGL@gmail.com **
+ ** Copyright (C) 2010, Gary L. Cutler, GPL **
+ ** **
+ ** DATE-WRITTEN: April 1, 2010 **
+ ** **
+ *****************************************************************
+ ** DATE CHANGE DESCRIPTION **
+ ** ====== ==================================================== **
+ ** GC0410 Initial coding **
+ ** GC0710 Handle duplicate data names (i.e. "CORRESPONDING" or **
+ ** qualified items) better; ignore "END PROGRAM" recs **
+ ** so program name doesn't appear in listing. **
+ *****************************************************************
+ ENVIRONMENT DIVISION.
+ CONFIGURATION SECTION.
+ REPOSITORY.
+ FUNCTION ALL INTRINSIC.
+ INPUT-OUTPUT SECTION.
+ FILE-CONTROL.
+ SELECT Expand-Code ASSIGN TO Expanded-Src-Filename
+ ORGANIZATION IS LINE SEQUENTIAL.
+ SELECT Report-File ASSIGN TO Report-Filename
+ ORGANIZATION IS LINE SEQUENTIAL.
+ SELECT Sort-File ASSIGN TO DISK.
+ SELECT Source-Code ASSIGN TO Src-Filename
+ ORGANIZATION IS LINE SEQUENTIAL.
+ DATA DIVISION.
+ FILE SECTION.
+ FD Expand-Code.
+ 01 Expand-Code-Rec.
+ 05 ECR-1 PIC X.
+ 05 ECR-2-256 PIC X(256).
+ 01 Expand-Code-Rec-Alt.
+ 05 ECR-1-128 PIC X(128).
+ 05 ECR-129-256 PIC X(128).
+
+ FD Report-File.
+ 01 Report-Rec PIC X(135).
+
+ SD Sort-File.
+ 01 Sort-Rec.
+ 05 SR-Prog-ID PIC X(15).
+ 05 SR-Token-UC PIC X(32).
+ 05 SR-Token PIC X(32).
+ 05 SR-Section PIC X(15).
+ 05 SR-Line-No-Def PIC 9(6).
+ 05 SR-Reference.
+ 10 SR-Line-No-Ref PIC 9(6).
+ 10 SR-Ref-Flag PIC X(1).
+
+ FD Source-Code.
+ 01 Source-Code-Rec.
+GC0410 05 SCR-1-128.
+GC0410 10 FILLER PIC X(6).
+GC0410 10 SCR-7 PIC X(1).
+GC0410 10 FILLER PIC X(121).
+ 05 SCR-129-256 PIC X(128).
+
+ WORKING-STORAGE SECTION.
+ 78 Line-Nos-Per-Rec VALUE 8.
+
+ 01 Cmd PIC X(256).
+
+ 01 Delim PIC X(2).
+
+ 01 Detail-Line-S.
+ 05 DLS-Line-No PIC ZZZZZ9.
+ 05 FILLER PIC X(1).
+ 05 DLS-Statement PIC X(128).
+
+ 01 Detail-Line-X.
+ 05 DLX-Prog-ID PIC X(15).
+ 05 FILLER PIC X(1).
+ 05 DLX-Token PIC X(32).
+ 05 FILLER PIC X(1).
+ 05 DLX-Line-No-Def PIC ZZZZZ9.
+ 05 FILLER PIC X(1).
+ 05 DLX-Section PIC X(15).
+ 05 FILLER PIC X(1).
+ 05 DLX-Reference OCCURS Line-Nos-Per-Rec TIMES.
+ 10 DLX-Line-No-Ref PIC ZZZZZ9.
+ 10 DLX-Ref-Flag PIC X(1).
+ 10 FILLER PIC X(1).
+
+ 01 Dummy PIC X(1).
+
+ 01 Env-TEMP PIC X(256).
+
+ 01 Expanded-Src-Filename PIC X(256).
+
+ 01 Filename PIC X(256).
+
+ 01 Flags.
+GC0710 05 F-Duplicate PIC X(1).
+ 05 F-First-Record PIC X(1).
+ 05 F-In-Which-Pgm PIC X(1).
+ 88 In-Main-Module VALUE 'M'.
+ 88 In-Copybook VALUE 'C'.
+ 05 F-Last-Token-Ended-Sent PIC X(1).
+ 05 F-Processing-PICTURE PIC X(1).
+ 05 F-Token-Ended-Sentence PIC X(1).
+GC0710 05 F-Verb-Has-Been-Found PIC X(1).
+
+ 01 Group-Indicators.
+ 05 GI-Prog-ID PIC X(15).
+ 05 GI-Token PIC X(32).
+
+ 01 Heading-1S.
+ 05 FILLER PIC X(125) VALUE
+ "OpenCOBOL 1.1 06FEB2009 Source Listing - " &
+ "OCic Copyright (C) 2009-2010, Gary L. Cutler, GPL".
+ 05 H1S-Date PIC 9999/99/99.
+
+ 01 Heading-1X.
+ 05 FILLER PIC X(125) VALUE
+ "OpenCOBOL 1.1 06FEB2009 Cross-Reference Listing - " &
+ "OCic Copyright (C) 2009-2010, Gary L. Cutler, GPL".
+ 05 H1X-Date PIC 9999/99/99.
+
+ 01 Heading-2 PIC X(135).
+
+ 01 Heading-4S PIC X(16) VALUE
+ "Line Statement".
+
+ 01 Heading-4X PIC X(96) VALUE
+ "PROGRAM-ID Identifier/Register/Function Defn Wher
+ - "e Defined References (* = Updated)".
+
+ 01 Heading-5S PIC X(135) VALUE
+ "====== =====================================================
+ - "============================================================
+ - "===============".
+
+ 01 Heading-5X PIC X(135) VALUE
+ "=============== ================================ ====== ====
+ - "=========== ================================================
+ - "===============".
+
+ 01 Held-Reference PIC X(100).
+
+ 01 I USAGE BINARY-LONG.
+
+ 01 J USAGE BINARY-LONG.
+
+ 01 Lines-Left USAGE BINARY-LONG.
+
+ 01 Lines-Per-Page USAGE BINARY-LONG.
+
+ 01 Lines-Per-Page-ENV PIC X(256).
+
+ 01 Num-UserNames USAGE BINARY-LONG.
+
+ 01 PIC-X10 PIC X(10).
+
+ 01 PIC-X32 PIC X(32).
+
+ 01 PIC-X256 PIC X(256).
+
+ 01 Program-Path PIC X(256).
+
+ 01 Report-Filename PIC X(256).
+
+ 01 Reserved-Words.
+ 05 FILLER PIC X(33) VALUE "IABS".
+ 05 FILLER PIC X(33) VALUE "VACCEPT".
+ 05 FILLER PIC X(33) VALUE " ACCESS".
+ 05 FILLER PIC X(33) VALUE "IACOS".
+ 05 FILLER PIC X(33) VALUE " ACTIVE-CLASS".
+ 05 FILLER PIC X(33) VALUE "VADD".
+ 05 FILLER PIC X(33) VALUE " ADDRESS".
+ 05 FILLER PIC X(33) VALUE " ADVANCING".
+ 05 FILLER PIC X(33) VALUE "KAFTER".
+ 05 FILLER PIC X(33) VALUE " ALIGNED".
+ 05 FILLER PIC X(33) VALUE " ALL".
+ 05 FILLER PIC X(33) VALUE "VALLOCATE".
+ 05 FILLER PIC X(33) VALUE " ALPHABET".
+ 05 FILLER PIC X(33) VALUE " ALPHABETIC".
+ 05 FILLER PIC X(33) VALUE " ALPHABETIC-LOWER".
+ 05 FILLER PIC X(33) VALUE " ALPHABETIC-UPPER".
+ 05 FILLER PIC X(33) VALUE " ALPHANUMERIC".
+ 05 FILLER PIC X(33) VALUE " ALPHANUMERIC-EDITED".
+ 05 FILLER PIC X(33) VALUE " ALSO".
+ 05 FILLER PIC X(33) VALUE "VALTER".
+ 05 FILLER PIC X(33) VALUE " ALTERNATE".
+ 05 FILLER PIC X(33) VALUE " AND".
+ 05 FILLER PIC X(33) VALUE "IANNUITY".
+ 05 FILLER PIC X(33) VALUE " ANY".
+ 05 FILLER PIC X(33) VALUE " ANYCASE".
+ 05 FILLER PIC X(33) VALUE " ARE".
+ 05 FILLER PIC X(33) VALUE " AREA".
+ 05 FILLER PIC X(33) VALUE " AREAS".
+ 05 FILLER PIC X(33) VALUE " ARGUMENT-NUMBER".
+ 05 FILLER PIC X(33) VALUE " ARGUMENT-VALUE".
+ 05 FILLER PIC X(33) VALUE " AS".
+ 05 FILLER PIC X(33) VALUE " ASCENDING".
+ 05 FILLER PIC X(33) VALUE "IASIN".
+ 05 FILLER PIC X(33) VALUE " ASSIGN".
+ 05 FILLER PIC X(33) VALUE " AT".
+ 05 FILLER PIC X(33) VALUE "IATAN".
+ 05 FILLER PIC X(33) VALUE " AUTHOR".
+ 05 FILLER PIC X(33) VALUE " AUTO".
+ 05 FILLER PIC X(33) VALUE " AUTO-SKIP".
+ 05 FILLER PIC X(33) VALUE " AUTOMATIC".
+ 05 FILLER PIC X(33) VALUE " AUTOTERMINATE".
+ 05 FILLER PIC X(33) VALUE " BACKGROUND-COLOR".
+ 05 FILLER PIC X(33) VALUE " BASED".
+ 05 FILLER PIC X(33) VALUE " BEEP".
+ 05 FILLER PIC X(33) VALUE " BEFORE".
+ 05 FILLER PIC X(33) VALUE " BELL".
+ 05 FILLER PIC X(33) VALUE " BINARY".
+ 05 FILLER PIC X(33) VALUE " BINARY-C-LONG".
+ 05 FILLER PIC X(33) VALUE " BINARY-CHAR".
+ 05 FILLER PIC X(33) VALUE " BINARY-DOUBLE".
+ 05 FILLER PIC X(33) VALUE " BINARY-LONG".
+ 05 FILLER PIC X(33) VALUE " BINARY-SHORT".
+ 05 FILLER PIC X(33) VALUE " BIT".
+ 05 FILLER PIC X(33) VALUE " BLANK".
+ 05 FILLER PIC X(33) VALUE " BLINK".
+ 05 FILLER PIC X(33) VALUE " BLOCK".
+ 05 FILLER PIC X(33) VALUE " BOOLEAN".
+ 05 FILLER PIC X(33) VALUE " BOTTOM".
+ 05 FILLER PIC X(33) VALUE "YBY".
+ 05 FILLER PIC X(33) VALUE "IBYTE-LENGTH".
+ 05 FILLER PIC X(33) VALUE "MC01".
+ 05 FILLER PIC X(33) VALUE "MC02".
+ 05 FILLER PIC X(33) VALUE "MC03".
+ 05 FILLER PIC X(33) VALUE "MC04".
+ 05 FILLER PIC X(33) VALUE "MC05".
+ 05 FILLER PIC X(33) VALUE "MC06".
+ 05 FILLER PIC X(33) VALUE "MC07".
+ 05 FILLER PIC X(33) VALUE "MC08".
+ 05 FILLER PIC X(33) VALUE "MC09".
+ 05 FILLER PIC X(33) VALUE "MC10".
+ 05 FILLER PIC X(33) VALUE "MC11".
+ 05 FILLER PIC X(33) VALUE "MC12".
+ 05 FILLER PIC X(33) VALUE "VCALL".
+ 05 FILLER PIC X(33) VALUE "VCANCEL".
+ 05 FILLER PIC X(33) VALUE " CF".
+ 05 FILLER PIC X(33) VALUE " CH".
+ 05 FILLER PIC X(33) VALUE " CHAINING".
+ 05 FILLER PIC X(33) VALUE "ICHAR".
+ 05 FILLER PIC X(33) VALUE " CHARACTER".
+ 05 FILLER PIC X(33) VALUE " CHARACTERS".
+ 05 FILLER PIC X(33) VALUE " CLASS".
+ 05 FILLER PIC X(33) VALUE " CLASS-ID".
+ 05 FILLER PIC X(33) VALUE "VCLOSE".
+ 05 FILLER PIC X(33) VALUE "ICOB-CRT-STATUS".
+ 05 FILLER PIC X(33) VALUE " CODE".
+ 05 FILLER PIC X(33) VALUE " CODE-SET".
+ 05 FILLER PIC X(33) VALUE " COL".
+ 05 FILLER PIC X(33) VALUE " COLLATING".
+ 05 FILLER PIC X(33) VALUE " COLS".
+ 05 FILLER PIC X(33) VALUE " COLUMN".
+ 05 FILLER PIC X(33) VALUE " COLUMNS".
+ 05 FILLER PIC X(33) VALUE "ICOMBINED-DATETIME".
+ 05 FILLER PIC X(33) VALUE " COMMA".
+ 05 FILLER PIC X(33) VALUE " COMMAND-LINE".
+ 05 FILLER PIC X(33) VALUE "VCOMMIT".
+ 05 FILLER PIC X(33) VALUE " COMMON".
+ 05 FILLER PIC X(33) VALUE " COMP".
+ 05 FILLER PIC X(33) VALUE " COMP-1".
+ 05 FILLER PIC X(33) VALUE " COMP-2".
+ 05 FILLER PIC X(33) VALUE " COMP-3".
+ 05 FILLER PIC X(33) VALUE " COMP-4".
+ 05 FILLER PIC X(33) VALUE " COMP-5".
+ 05 FILLER PIC X(33) VALUE " COMP-X".
+ 05 FILLER PIC X(33) VALUE " COMPUTATIONAL".
+ 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-1".
+ 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-2".
+ 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-3".
+ 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-4".
+ 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-5".
+ 05 FILLER PIC X(33) VALUE " COMPUTATIONAL-X".
+ 05 FILLER PIC X(33) VALUE "VCOMPUTE".
+ 05 FILLER PIC X(33) VALUE "ICONCATENATE".
+ 05 FILLER PIC X(33) VALUE " CONDITION".
+ 05 FILLER PIC X(33) VALUE "KCONFIGURATION".
+ 05 FILLER PIC X(33) VALUE "MCONSOLE".
+ 05 FILLER PIC X(33) VALUE " CONSTANT".
+ 05 FILLER PIC X(33) VALUE " CONTAINS".
+ 05 FILLER PIC X(33) VALUE " CONTENT".
+ 05 FILLER PIC X(33) VALUE "VCONTINUE".
+ 05 FILLER PIC X(33) VALUE " CONTROL".
+ 05 FILLER PIC X(33) VALUE " CONTROLS".
+ 05 FILLER PIC X(33) VALUE "KCONVERTING".
+ 05 FILLER PIC X(33) VALUE " COPY".
+ 05 FILLER PIC X(33) VALUE " CORR".
+ 05 FILLER PIC X(33) VALUE " CORRESPONDING".
+ 05 FILLER PIC X(33) VALUE "ICOS".
+ 05 FILLER PIC X(33) VALUE "KCOUNT".
+ 05 FILLER PIC X(33) VALUE " CRT".
+ 05 FILLER PIC X(33) VALUE " CURRENCY".
+ 05 FILLER PIC X(33) VALUE "ICURRENT-DATE".
+ 05 FILLER PIC X(33) VALUE " CURSOR".
+ 05 FILLER PIC X(33) VALUE " CYCLE".
+ 05 FILLER PIC X(33) VALUE "KDATA".
+ 05 FILLER PIC X(33) VALUE " DATA-POINTER".
+ 05 FILLER PIC X(33) VALUE " DATE".
+ 05 FILLER PIC X(33) VALUE " DATE-COMPILED".
+ 05 FILLER PIC X(33) VALUE " DATE-MODIFIED".
+ 05 FILLER PIC X(33) VALUE "IDATE-OF-INTEGER".
+ 05 FILLER PIC X(33) VALUE "IDATE-TO-YYYYMMDD".
+ 05 FILLER PIC X(33) VALUE " DATE-WRITTEN".
+ 05 FILLER PIC X(33) VALUE " DAY".
+ 05 FILLER PIC X(33) VALUE "IDAY-OF-INTEGER".
+ 05 FILLER PIC X(33) VALUE " DAY-OF-WEEK".
+ 05 FILLER PIC X(33) VALUE "IDAY-TO-YYYYDDD".
+ 05 FILLER PIC X(33) VALUE " DE".
+ 05 FILLER PIC X(33) VALUE " DEBUGGING".
+ 05 FILLER PIC X(33) VALUE " DECIMAL-POINT".
+ 05 FILLER PIC X(33) VALUE " DECLARATIVES".
+ 05 FILLER PIC X(33) VALUE " DEFAULT".
+ 05 FILLER PIC X(33) VALUE "VDELETE".
+ 05 FILLER PIC X(33) VALUE " DELIMITED".
+ 05 FILLER PIC X(33) VALUE "KDELIMITER".
+ 05 FILLER PIC X(33) VALUE " DEPENDING".
+ 05 FILLER PIC X(33) VALUE " DESCENDING".
+ 05 FILLER PIC X(33) VALUE " DESTINATION".
+ 05 FILLER PIC X(33) VALUE " DETAIL".
+ 05 FILLER PIC X(33) VALUE " DISABLE".
+ 05 FILLER PIC X(33) VALUE " DISK".
+ 05 FILLER PIC X(33) VALUE "VDISPLAY".
+ 05 FILLER PIC X(33) VALUE "VDIVIDE".
+ 05 FILLER PIC X(33) VALUE "KDIVISION".
+ 05 FILLER PIC X(33) VALUE "KDOWN".
+ 05 FILLER PIC X(33) VALUE " DUPLICATES".
+ 05 FILLER PIC X(33) VALUE " DYNAMIC".
+ 05 FILLER PIC X(33) VALUE "IE".
+ 05 FILLER PIC X(33) VALUE " EBCDIC".
+ 05 FILLER PIC X(33) VALUE " EC".
+ 05 FILLER PIC X(33) VALUE "VELSE".
+GC0710 05 FILLER PIC X(33) VALUE "KEND".
+ 05 FILLER PIC X(33) VALUE " END-ACCEPT".
+ 05 FILLER PIC X(33) VALUE " END-ADD".
+ 05 FILLER PIC X(33) VALUE " END-CALL".
+ 05 FILLER PIC X(33) VALUE " END-COMPUTE".
+ 05 FILLER PIC X(33) VALUE " END-DELETE".
+ 05 FILLER PIC X(33) VALUE " END-DISPLAY".
+ 05 FILLER PIC X(33) VALUE " END-DIVIDE".
+ 05 FILLER PIC X(33) VALUE " END-EVALUATE".
+ 05 FILLER PIC X(33) VALUE " END-IF".
+ 05 FILLER PIC X(33) VALUE " END-MULTIPLY".
+ 05 FILLER PIC X(33) VALUE " END-OF-PAGE".
+ 05 FILLER PIC X(33) VALUE " END-PERFORM".
+ 05 FILLER PIC X(33) VALUE " END-READ".
+ 05 FILLER PIC X(33) VALUE " END-RETURN".
+ 05 FILLER PIC X(33) VALUE " END-REWRITE".
+ 05 FILLER PIC X(33) VALUE " END-SEARCH".
+ 05 FILLER PIC X(33) VALUE " END-START".
+ 05 FILLER PIC X(33) VALUE " END-STRING".
+ 05 FILLER PIC X(33) VALUE " END-SUBTRACT".
+ 05 FILLER PIC X(33) VALUE " END-UNSTRING".
+ 05 FILLER PIC X(33) VALUE " END-WRITE".
+ 05 FILLER PIC X(33) VALUE "VENTRY".
+ 05 FILLER PIC X(33) VALUE "KENVIRONMENT".
+ 05 FILLER PIC X(33) VALUE " ENVIRONMENT-NAME".
+ 05 FILLER PIC X(33) VALUE " ENVIRONMENT-VALUE".
+ 05 FILLER PIC X(33) VALUE " EO".
+ 05 FILLER PIC X(33) VALUE " EOL".
+ 05 FILLER PIC X(33) VALUE " EOP".
+ 05 FILLER PIC X(33) VALUE " EOS".
+ 05 FILLER PIC X(33) VALUE " EQUAL".
+ 05 FILLER PIC X(33) VALUE "KEQUALS".
+ 05 FILLER PIC X(33) VALUE " ERASE".
+ 05 FILLER PIC X(33) VALUE " ERROR".
+ 05 FILLER PIC X(33) VALUE " ESCAPE".
+ 05 FILLER PIC X(33) VALUE "VEVALUATE".
+ 05 FILLER PIC X(33) VALUE " EXCEPTION".
+ 05 FILLER PIC X(33) VALUE "IEXCEPTION-FILE".
+ 05 FILLER PIC X(33) VALUE "IEXCEPTION-LOCATION".
+ 05 FILLER PIC X(33) VALUE " EXCEPTION-OBJECT".
+ 05 FILLER PIC X(33) VALUE "IEXCEPTION-STATEMENT".
+ 05 FILLER PIC X(33) VALUE "IEXCEPTION-STATUS".
+ 05 FILLER PIC X(33) VALUE " EXCLUSIVE".
+ 05 FILLER PIC X(33) VALUE "VEXIT".
+ 05 FILLER PIC X(33) VALUE "IEXP".
+ 05 FILLER PIC X(33) VALUE "IEXP10".
+ 05 FILLER PIC X(33) VALUE " EXTEND".
+ 05 FILLER PIC X(33) VALUE " EXTERNAL".
+ 05 FILLER PIC X(33) VALUE "IFACTORIAL".
+ 05 FILLER PIC X(33) VALUE " FACTORY".
+ 05 FILLER PIC X(33) VALUE " FALSE".
+ 05 FILLER PIC X(33) VALUE "KFD".
+ 05 FILLER PIC X(33) VALUE "KFILE".
+ 05 FILLER PIC X(33) VALUE " FILE-CONTROL".
+ 05 FILLER PIC X(33) VALUE " FILE-ID".
+ 05 FILLER PIC X(33) VALUE " FILLER".
+ 05 FILLER PIC X(33) VALUE " FINAL".
+ 05 FILLER PIC X(33) VALUE " FIRST".
+ 05 FILLER PIC X(33) VALUE " FLOAT-BINARY-16".
+ 05 FILLER PIC X(33) VALUE " FLOAT-BINARY-34".
+ 05 FILLER PIC X(33) VALUE " FLOAT-BINARY-7".
+ 05 FILLER PIC X(33) VALUE " FLOAT-DECIMAL-16".
+ 05 FILLER PIC X(33) VALUE " FLOAT-DECIMAL-34".
+ 05 FILLER PIC X(33) VALUE " FLOAT-EXTENDED".
+ 05 FILLER PIC X(33) VALUE " FLOAT-LONG".
+ 05 FILLER PIC X(33) VALUE " FLOAT-SHORT".
+ 05 FILLER PIC X(33) VALUE " FOOTING".
+ 05 FILLER PIC X(33) VALUE " FOR".
+ 05 FILLER PIC X(33) VALUE " FOREGROUND-COLOR".
+ 05 FILLER PIC X(33) VALUE " FOREVER".
+ 05 FILLER PIC X(33) VALUE " FORMAT".
+ 05 FILLER PIC X(33) VALUE "MFORMFEED".
+ 05 FILLER PIC X(33) VALUE "IFRACTION-PART".
+ 05 FILLER PIC X(33) VALUE "VFREE".
+ 05 FILLER PIC X(33) VALUE " FROM".
+ 05 FILLER PIC X(33) VALUE " FULL".
+ 05 FILLER PIC X(33) VALUE " FUNCTION".
+ 05 FILLER PIC X(33) VALUE " FUNCTION-ID".
+ 05 FILLER PIC X(33) VALUE " FUNCTION-POINTER".
+ 05 FILLER PIC X(33) VALUE "VGENERATE".
+ 05 FILLER PIC X(33) VALUE " GET".
+ 05 FILLER PIC X(33) VALUE "KGIVING".
+ 05 FILLER PIC X(33) VALUE " GLOBAL".
+ 05 FILLER PIC X(33) VALUE "VGO".
+ 05 FILLER PIC X(33) VALUE "VGOBACK".
+ 05 FILLER PIC X(33) VALUE " GREATER".
+ 05 FILLER PIC X(33) VALUE " GROUP".
+ 05 FILLER PIC X(33) VALUE " GROUP-USAGE".
+ 05 FILLER PIC X(33) VALUE " HEADING".
+ 05 FILLER PIC X(33) VALUE " HIGH-VALUE".
+ 05 FILLER PIC X(33) VALUE " HIGH-VALUES".
+ 05 FILLER PIC X(33) VALUE " HIGHLIGHT".
+ 05 FILLER PIC X(33) VALUE " I-O".
+ 05 FILLER PIC X(33) VALUE " I-O-CONTROL".
+ 05 FILLER PIC X(33) VALUE "KID".
+ 05 FILLER PIC X(33) VALUE "KIDENTIFICATION".
+ 05 FILLER PIC X(33) VALUE "VIF".
+ 05 FILLER PIC X(33) VALUE " IGNORE".
+ 05 FILLER PIC X(33) VALUE " IGNORING".
+ 05 FILLER PIC X(33) VALUE " IN".
+ 05 FILLER PIC X(33) VALUE " INDEX".
+ 05 FILLER PIC X(33) VALUE "KINDEXED".
+ 05 FILLER PIC X(33) VALUE " INDICATE".
+ 05 FILLER PIC X(33) VALUE " INFINITY".
+ 05 FILLER PIC X(33) VALUE " INHERITS".
+ 05 FILLER PIC X(33) VALUE " INITIAL".
+ 05 FILLER PIC X(33) VALUE " INITIALISED".
+ 05 FILLER PIC X(33) VALUE "VINITIALIZE".
+ 05 FILLER PIC X(33) VALUE " INITIALIZED".
+ 05 FILLER PIC X(33) VALUE "VINITIATE".
+ 05 FILLER PIC X(33) VALUE " INPUT".
+ 05 FILLER PIC X(33) VALUE "KINPUT-OUTPUT".
+ 05 FILLER PIC X(33) VALUE "VINSPECT".
+ 05 FILLER PIC X(33) VALUE " INSTALLATION".
+ 05 FILLER PIC X(33) VALUE "IINTEGER".
+ 05 FILLER PIC X(33) VALUE "IINTEGER-OF-DATE".
+ 05 FILLER PIC X(33) VALUE "IINTEGER-OF-DAY".
+ 05 FILLER PIC X(33) VALUE "IINTEGER-PART".
+ 05 FILLER PIC X(33) VALUE " INTERFACE".
+ 05 FILLER PIC X(33) VALUE " INTERFACE-ID".
+ 05 FILLER PIC X(33) VALUE "KINTO".
+ 05 FILLER PIC X(33) VALUE " INTRINSIC".
+ 05 FILLER PIC X(33) VALUE " INVALID".
+ 05 FILLER PIC X(33) VALUE " INVOKE".
+ 05 FILLER PIC X(33) VALUE " IS".
+ 05 FILLER PIC X(33) VALUE " JUST".
+ 05 FILLER PIC X(33) VALUE " JUSTIFIED".
+ 05 FILLER PIC X(33) VALUE " KEY".
+ 05 FILLER PIC X(33) VALUE " LABEL".
+ 05 FILLER PIC X(33) VALUE " LAST".
+ 05 FILLER PIC X(33) VALUE " LEADING".
+ 05 FILLER PIC X(33) VALUE " LEFT".
+ 05 FILLER PIC X(33) VALUE " LEFT-JUSTIFY".
+ 05 FILLER PIC X(33) VALUE "ILENGTH".
+ 05 FILLER PIC X(33) VALUE " LESS".
+ 05 FILLER PIC X(33) VALUE " LIMIT".
+ 05 FILLER PIC X(33) VALUE " LIMITS".
+ 05 FILLER PIC X(33) VALUE " LINAGE".
+ 05 FILLER PIC X(33) VALUE "ILINAGE-COUNTER".
+ 05 FILLER PIC X(33) VALUE " LINE".
+ 05 FILLER PIC X(33) VALUE " LINE-COUNTER".
+ 05 FILLER PIC X(33) VALUE " LINES".
+ 05 FILLER PIC X(33) VALUE "KLINKAGE".
+ 05 FILLER PIC X(33) VALUE "KLOCAL-STORAGE".
+ 05 FILLER PIC X(33) VALUE " LOCALE".
+ 05 FILLER PIC X(33) VALUE "ILOCALE-DATE".
+ 05 FILLER PIC X(33) VALUE "ILOCALE-TIME".
+ 05 FILLER PIC X(33) VALUE "ILOCALE-TIME-FROM-SECONDS".
+ 05 FILLER PIC X(33) VALUE " LOCK".
+ 05 FILLER PIC X(33) VALUE "ILOG".
+ 05 FILLER PIC X(33) VALUE "ILOG10".
+ 05 FILLER PIC X(33) VALUE " LOW-VALUE".
+ 05 FILLER PIC X(33) VALUE " LOW-VALUES".
+ 05 FILLER PIC X(33) VALUE " LOWER".
+ 05 FILLER PIC X(33) VALUE "ILOWER-CASE".
+ 05 FILLER PIC X(33) VALUE " LOWLIGHT".
+ 05 FILLER PIC X(33) VALUE " MANUAL".
+ 05 FILLER PIC X(33) VALUE "IMAX".
+ 05 FILLER PIC X(33) VALUE "IMEAN".
+ 05 FILLER PIC X(33) VALUE "IMEDIAN".
+ 05 FILLER PIC X(33) VALUE " MEMORY".
+ 05 FILLER PIC X(33) VALUE "VMERGE".
+ 05 FILLER PIC X(33) VALUE " METHOD".
+ 05 FILLER PIC X(33) VALUE " METHOD-ID".
+ 05 FILLER PIC X(33) VALUE "IMIDRANGE".
+ 05 FILLER PIC X(33) VALUE "IMIN".
+ 05 FILLER PIC X(33) VALUE " MINUS".
+ 05 FILLER PIC X(33) VALUE "IMOD".
+ 05 FILLER PIC X(33) VALUE " MODE".
+ 05 FILLER PIC X(33) VALUE "VMOVE".
+ 05 FILLER PIC X(33) VALUE " MULTIPLE".
+ 05 FILLER PIC X(33) VALUE "VMULTIPLY".
+ 05 FILLER PIC X(33) VALUE " NATIONAL".
+ 05 FILLER PIC X(33) VALUE " NATIONAL-EDITED".
+ 05 FILLER PIC X(33) VALUE " NATIVE".
+ 05 FILLER PIC X(33) VALUE " NEGATIVE".
+ 05 FILLER PIC X(33) VALUE " NESTED".
+ 05 FILLER PIC X(33) VALUE "VNEXT".
+ 05 FILLER PIC X(33) VALUE " NO".
+ 05 FILLER PIC X(33) VALUE " NOT".
+ 05 FILLER PIC X(33) VALUE " NULL".
+ 05 FILLER PIC X(33) VALUE " NULLS".
+ 05 FILLER PIC X(33) VALUE " NUMBER".
+ 05 FILLER PIC X(33) VALUE "INUMBER-OF-CALL-PARAMETERS".
+ 05 FILLER PIC X(33) VALUE " NUMBERS".
+ 05 FILLER PIC X(33) VALUE " NUMERIC".
+ 05 FILLER PIC X(33) VALUE " NUMERIC-EDITED".
+ 05 FILLER PIC X(33) VALUE "INUMVAL".
+ 05 FILLER PIC X(33) VALUE "INUMVAL-C".
+ 05 FILLER PIC X(33) VALUE " OBJECT".
+ 05 FILLER PIC X(33) VALUE " OBJECT-COMPUTER".
+ 05 FILLER PIC X(33) VALUE " OBJECT-REFERENCE".
+ 05 FILLER PIC X(33) VALUE " OCCURS".
+ 05 FILLER PIC X(33) VALUE " OF".
+ 05 FILLER PIC X(33) VALUE " OFF".
+ 05 FILLER PIC X(33) VALUE " OMITTED".
+ 05 FILLER PIC X(33) VALUE " ON".
+ 05 FILLER PIC X(33) VALUE " ONLY".
+ 05 FILLER PIC X(33) VALUE "VOPEN".
+ 05 FILLER PIC X(33) VALUE " OPTIONAL".
+ 05 FILLER PIC X(33) VALUE " OPTIONS".
+ 05 FILLER PIC X(33) VALUE " OR".
+ 05 FILLER PIC X(33) VALUE "IORD".
+ 05 FILLER PIC X(33) VALUE "IORD-MAX".
+ 05 FILLER PIC X(33) VALUE "IORD-MIN".
+ 05 FILLER PIC X(33) VALUE " ORDER".
+ 05 FILLER PIC X(33) VALUE " ORGANIZATION".
+ 05 FILLER PIC X(33) VALUE " OTHER".
+ 05 FILLER PIC X(33) VALUE " OUTPUT".
+ 05 FILLER PIC X(33) VALUE " OVERFLOW".
+ 05 FILLER PIC X(33) VALUE " OVERLINE".
+ 05 FILLER PIC X(33) VALUE " OVERRIDE".
+ 05 FILLER PIC X(33) VALUE " PACKED-DECIMAL".
+ 05 FILLER PIC X(33) VALUE " PADDING".
+ 05 FILLER PIC X(33) VALUE " PAGE".
+ 05 FILLER PIC X(33) VALUE " PAGE-COUNTER".
+ 05 FILLER PIC X(33) VALUE " PARAGRAPH".
+ 05 FILLER PIC X(33) VALUE "VPERFORM".
+ 05 FILLER PIC X(33) VALUE " PF".
+ 05 FILLER PIC X(33) VALUE " PH".
+ 05 FILLER PIC X(33) VALUE "IPI".
+ 05 FILLER PIC X(33) VALUE "KPIC".
+ 05 FILLER PIC X(33) VALUE "KPICTURE".
+ 05 FILLER PIC X(33) VALUE " PLUS".
+ 05 FILLER PIC X(33) VALUE "KPOINTER".
+ 05 FILLER PIC X(33) VALUE " POSITION".
+ 05 FILLER PIC X(33) VALUE " POSITIVE".
+ 05 FILLER PIC X(33) VALUE " PRESENT".
+ 05 FILLER PIC X(33) VALUE "IPRESENT-VALUE".
+ 05 FILLER PIC X(33) VALUE " PREVIOUS".
+ 05 FILLER PIC X(33) VALUE "MPRINTER".
+ 05 FILLER PIC X(33) VALUE " PRINTING".
+ 05 FILLER PIC X(33) VALUE "KPROCEDURE".
+ 05 FILLER PIC X(33) VALUE " PROCEDURE-POINTER".
+ 05 FILLER PIC X(33) VALUE " PROCEDURES".
+ 05 FILLER PIC X(33) VALUE " PROCEED".
+ 05 FILLER PIC X(33) VALUE " PROGRAM".
+ 05 FILLER PIC X(33) VALUE "KPROGRAM-ID".
+ 05 FILLER PIC X(33) VALUE " PROGRAM-POINTER".
+ 05 FILLER PIC X(33) VALUE " PROMPT".
+ 05 FILLER PIC X(33) VALUE " PROPERTY".
+ 05 FILLER PIC X(33) VALUE " PROTOTYPE".
+ 05 FILLER PIC X(33) VALUE " QUOTE".
+ 05 FILLER PIC X(33) VALUE " QUOTES".
+ 05 FILLER PIC X(33) VALUE " RAISE".
+ 05 FILLER PIC X(33) VALUE " RAISING".
+ 05 FILLER PIC X(33) VALUE "IRANDOM".
+ 05 FILLER PIC X(33) VALUE "IRANGE".
+ 05 FILLER PIC X(33) VALUE " RD".
+ 05 FILLER PIC X(33) VALUE "VREAD".
+ 05 FILLER PIC X(33) VALUE "VREADY".
+ 05 FILLER PIC X(33) VALUE " RECORD".
+ 05 FILLER PIC X(33) VALUE " RECORDING".
+ 05 FILLER PIC X(33) VALUE " RECORDS".
+ 05 FILLER PIC X(33) VALUE " RECURSIVE".
+ 05 FILLER PIC X(33) VALUE "KREDEFINES".
+ 05 FILLER PIC X(33) VALUE " REEL".
+ 05 FILLER PIC X(33) VALUE " REFERENCE".
+ 05 FILLER PIC X(33) VALUE " RELATIVE".
+ 05 FILLER PIC X(33) VALUE "VRELEASE".
+ 05 FILLER PIC X(33) VALUE "IREM".
+ 05 FILLER PIC X(33) VALUE " REMAINDER".
+ 05 FILLER PIC X(33) VALUE " REMARKS".
+ 05 FILLER PIC X(33) VALUE " REMOVAL".
+ 05 FILLER PIC X(33) VALUE "KRENAMES".
+ 05 FILLER PIC X(33) VALUE "KREPLACING".
+ 05 FILLER PIC X(33) VALUE "KREPORT".
+ 05 FILLER PIC X(33) VALUE " REPORTING".
+ 05 FILLER PIC X(33) VALUE " REPORTS".
+ 05 FILLER PIC X(33) VALUE " REPOSITORY".
+ 05 FILLER PIC X(33) VALUE " REPRESENTS-NOT-A-NUMBER".
+ 05 FILLER PIC X(33) VALUE " REQUIRED".
+ 05 FILLER PIC X(33) VALUE " RESERVE".
+ 05 FILLER PIC X(33) VALUE " RESUME".
+ 05 FILLER PIC X(33) VALUE " RETRY".
+ 05 FILLER PIC X(33) VALUE "VRETURN".
+ 05 FILLER PIC X(33) VALUE "IRETURN-CODE".
+ 05 FILLER PIC X(33) VALUE "KRETURNING".
+ 05 FILLER PIC X(33) VALUE "IREVERSE".
+ 05 FILLER PIC X(33) VALUE " REVERSE-VIDEO".
+ 05 FILLER PIC X(33) VALUE " REWIND".
+ 05 FILLER PIC X(33) VALUE "VREWRITE".
+ 05 FILLER PIC X(33) VALUE " RF".
+ 05 FILLER PIC X(33) VALUE " RH".
+ 05 FILLER PIC X(33) VALUE " RIGHT".
+ 05 FILLER PIC X(33) VALUE " RIGHT-JUSTIFY".
+ 05 FILLER PIC X(33) VALUE "VROLLBACK".
+ 05 FILLER PIC X(33) VALUE " ROUNDED".
+ 05 FILLER PIC X(33) VALUE " RUN".
+ 05 FILLER PIC X(33) VALUE " SAME".
+ 05 FILLER PIC X(33) VALUE "KSCREEN".
+ 05 FILLER PIC X(33) VALUE " SCROLL".
+ 05 FILLER PIC X(33) VALUE "KSD".
+ 05 FILLER PIC X(33) VALUE "VSEARCH".
+ 05 FILLER PIC X(33) VALUE "ISECONDS-FROM-FORMATTED-TIME".
+ 05 FILLER PIC X(33) VALUE "ISECONDS-PAST-MIDNIGHT".
+ 05 FILLER PIC X(33) VALUE "KSECTION".
+ 05 FILLER PIC X(33) VALUE " SECURE".
+ 05 FILLER PIC X(33) VALUE " SECURITY".
+ 05 FILLER PIC X(33) VALUE " SEGMENT-LIMIT".
+ 05 FILLER PIC X(33) VALUE " SELECT".
+ 05 FILLER PIC X(33) VALUE " SELF".
+ 05 FILLER PIC X(33) VALUE " SENTENCE".
+ 05 FILLER PIC X(33) VALUE " SEPARATE".
+ 05 FILLER PIC X(33) VALUE " SEQUENCE".
+ 05 FILLER PIC X(33) VALUE " SEQUENTIAL".
+ 05 FILLER PIC X(33) VALUE "VSET".
+ 05 FILLER PIC X(33) VALUE " SHARING".
+ 05 FILLER PIC X(33) VALUE "ISIGN".
+ 05 FILLER PIC X(33) VALUE " SIGNED".
+ 05 FILLER PIC X(33) VALUE " SIGNED-INT".
+ 05 FILLER PIC X(33) VALUE " SIGNED-LONG".
+ 05 FILLER PIC X(33) VALUE " SIGNED-SHORT".
+ 05 FILLER PIC X(33) VALUE "ISIN".
+ 05 FILLER PIC X(33) VALUE " SIZE".
+ 05 FILLER PIC X(33) VALUE "VSORT".
+ 05 FILLER PIC X(33) VALUE " SORT-MERGE".
+ 05 FILLER PIC X(33) VALUE "ISORT-RETURN".
+ 05 FILLER PIC X(33) VALUE " SOURCE".
+ 05 FILLER PIC X(33) VALUE " SOURCE-COMPUTER".
+ 05 FILLER PIC X(33) VALUE " SOURCES".
+ 05 FILLER PIC X(33) VALUE " SPACE".
+ 05 FILLER PIC X(33) VALUE " SPACE-FILL".
+ 05 FILLER PIC X(33) VALUE " SPACES".
+ 05 FILLER PIC X(33) VALUE " SPECIAL-NAMES".
+ 05 FILLER PIC X(33) VALUE "ISQRT".
+ 05 FILLER PIC X(33) VALUE " STANDARD".
+ 05 FILLER PIC X(33) VALUE " STANDARD-1".
+ 05 FILLER PIC X(33) VALUE " STANDARD-2".
+ 05 FILLER PIC X(33) VALUE "ISTANDARD-DEVIATION".
+ 05 FILLER PIC X(33) VALUE "VSTART".
+ 05 FILLER PIC X(33) VALUE " STATUS".
+ 05 FILLER PIC X(33) VALUE "VSTOP".
+ 05 FILLER PIC X(33) VALUE "ISTORED-CHAR-LENGTH".
+ 05 FILLER PIC X(33) VALUE "VSTRING".
+ 05 FILLER PIC X(33) VALUE "ISUBSTITUTE".
+ 05 FILLER PIC X(33) VALUE "ISUBSTITUTE-CASE".
+ 05 FILLER PIC X(33) VALUE "VSUBTRACT".
+ 05 FILLER PIC X(33) VALUE "ISUM".
+ 05 FILLER PIC X(33) VALUE " SUPER".
+ 05 FILLER PIC X(33) VALUE "VSUPPRESS".
+ 05 FILLER PIC X(33) VALUE "MSWITCH-1".
+ 05 FILLER PIC X(33) VALUE "MSWITCH-2".
+ 05 FILLER PIC X(33) VALUE "MSWITCH-3".
+ 05 FILLER PIC X(33) VALUE "MSWITCH-4".
+ 05 FILLER PIC X(33) VALUE "MSWITCH-5".
+ 05 FILLER PIC X(33) VALUE "MSWITCH-6".
+ 05 FILLER PIC X(33) VALUE "MSWITCH-7".
+ 05 FILLER PIC X(33) VALUE "MSWITCH-8".
+ 05 FILLER PIC X(33) VALUE " SYMBOLIC".
+ 05 FILLER PIC X(33) VALUE " SYNC".
+ 05 FILLER PIC X(33) VALUE " SYNCHRONIZED".
+ 05 FILLER PIC X(33) VALUE "MSYSERR".
+ 05 FILLER PIC X(33) VALUE "MSYSIN".
+ 05 FILLER PIC X(33) VALUE "MSYSIPT".
+ 05 FILLER PIC X(33) VALUE "MSYSLIST".
+ 05 FILLER PIC X(33) VALUE "MSYSLST".
+ 05 FILLER PIC X(33) VALUE "MSYSOUT".
+ 05 FILLER PIC X(33) VALUE " SYSTEM-DEFAULT".
+ 05 FILLER PIC X(33) VALUE " TABLE".
+ 05 FILLER PIC X(33) VALUE "KTALLYING".
+ 05 FILLER PIC X(33) VALUE "ITAN".
+ 05 FILLER PIC X(33) VALUE " TAPE".
+ 05 FILLER PIC X(33) VALUE "VTERMINATE".
+ 05 FILLER PIC X(33) VALUE " TEST".
+ 05 FILLER PIC X(33) VALUE "ITEST-DATE-YYYYMMDD".
+ 05 FILLER PIC X(33) VALUE "ITEST-DAY-YYYYDDD".
+ 05 FILLER PIC X(33) VALUE " THAN".
+ 05 FILLER PIC X(33) VALUE " THEN".
+ 05 FILLER PIC X(33) VALUE " THROUGH".
+ 05 FILLER PIC X(33) VALUE " THRU".
+ 05 FILLER PIC X(33) VALUE " TIME".
+ 05 FILLER PIC X(33) VALUE " TIMES".
+ 05 FILLER PIC X(33) VALUE "KTO".
+ 05 FILLER PIC X(33) VALUE " TOP".
+ 05 FILLER PIC X(33) VALUE " TRAILING".
+ 05 FILLER PIC X(33) VALUE " TRAILING-SIGN".
+ 05 FILLER PIC X(33) VALUE "VTRANSFORM".
+ 05 FILLER PIC X(33) VALUE "ITRIM".
+ 05 FILLER PIC X(33) VALUE " TRUE".
+ 05 FILLER PIC X(33) VALUE " TYPE".
+ 05 FILLER PIC X(33) VALUE " TYPEDEF".
+ 05 FILLER PIC X(33) VALUE " UNDERLINE".
+ 05 FILLER PIC X(33) VALUE " UNIT".
+ 05 FILLER PIC X(33) VALUE " UNIVERSAL".
+ 05 FILLER PIC X(33) VALUE "VUNLOCK".
+ 05 FILLER PIC X(33) VALUE " UNSIGNED".
+ 05 FILLER PIC X(33) VALUE " UNSIGNED-INT".
+ 05 FILLER PIC X(33) VALUE " UNSIGNED-LONG".
+ 05 FILLER PIC X(33) VALUE " UNSIGNED-SHORT".
+ 05 FILLER PIC X(33) VALUE "VUNSTRING".
+ 05 FILLER PIC X(33) VALUE " UNTIL".
+ 05 FILLER PIC X(33) VALUE "KUP".
+ 05 FILLER PIC X(33) VALUE " UPDATE".
+ 05 FILLER PIC X(33) VALUE " UPON".
+ 05 FILLER PIC X(33) VALUE " UPPER".
+ 05 FILLER PIC X(33) VALUE "IUPPER-CASE".
+ 05 FILLER PIC X(33) VALUE " USAGE".
+ 05 FILLER PIC X(33) VALUE "VUSE".
+ 05 FILLER PIC X(33) VALUE " USER-DEFAULT".
+ 05 FILLER PIC X(33) VALUE "KUSING".
+ 05 FILLER PIC X(33) VALUE " VAL-STATUS".
+ 05 FILLER PIC X(33) VALUE " VALID".
+ 05 FILLER PIC X(33) VALUE " VALIDATE".
+ 05 FILLER PIC X(33) VALUE " VALIDATE-STATUS".
+ 05 FILLER PIC X(33) VALUE " VALUE".
+ 05 FILLER PIC X(33) VALUE " VALUES".
+ 05 FILLER PIC X(33) VALUE "IVARIANCE".
+ 05 FILLER PIC X(33) VALUE "KVARYING".
+ 05 FILLER PIC X(33) VALUE " WAIT".
+ 05 FILLER PIC X(33) VALUE "VWHEN".
+ 05 FILLER PIC X(33) VALUE "IWHEN-COMPILED".
+ 05 FILLER PIC X(33) VALUE " WITH".
+ 05 FILLER PIC X(33) VALUE " WORDS".
+ 05 FILLER PIC X(33) VALUE "KWORKING-STORAGE".
+ 05 FILLER PIC X(33) VALUE "VWRITE".
+ 05 FILLER PIC X(33) VALUE "IYEAR-TO-YYYY".
+ 05 FILLER PIC X(33) VALUE " YYYYDDD".
+ 05 FILLER PIC X(33) VALUE " YYYYMMDD".
+ 05 FILLER PIC X(33) VALUE " ZERO".
+ 05 FILLER PIC X(33) VALUE " ZERO-FILL".
+ 05 FILLER PIC X(33) VALUE " ZEROES".
+ 05 FILLER PIC X(33) VALUE " ZEROS".
+ 01 Reserved-Word-Table REDEFINES Reserved-Words.
+ 05 Reserved-Word OCCURS 591 TIMES
+ ASCENDING KEY RW-Word
+ INDEXED RW-Idx.
+ 10 RW-Type PIC X(1).
+ 10 RW-Word PIC X(32).
+
+ 01 Saved-Section PIC X(15).
+
+ 01 Search-Token PIC X(32).
+
+ 01 Source-Line-No PIC 9(6).
+
+ 01 Src-Ptr USAGE BINARY-LONG.
+
+ 01 Syntax-Parsing-Items.
+ 05 SPI-Current-Char PIC X(1).
+ 88 Current-Char-Is-Punct VALUE "=", "(", ")", "*", "/",
+ "&", ";", ",", "<", ">",
+ ":".
+ 88 Current-Char-Is-Quote VALUE '"', "'".
+ 88 Current-Char-Is-X VALUE "x", "X".
+ 88 Current-Char-Is-Z VALUE "z", "Z".
+ 05 SPI-Current-Division PIC X(1).
+ 88 In-IDENTIFICATION-DIVISION VALUE "I", "?".
+ 88 In-ENVIRONMENT-DIVISION VALUE "E".
+ 88 In-DATA-DIVISION VALUE "D".
+ 88 In-PROCEDURE-DIVISION VALUE "P".
+ 05 SPI-Current-Line-No PIC 9(6).
+ 05 SPI-Current-Program-ID.
+ 10 FILLER PIC X(12).
+ 10 SPI-CP-13-15 PIC X(3).
+ 05 SPI-Current-Section.
+ 10 SPI-CS-1 PIC X(1).
+ 10 SPI-CS-2-14.
+ 15 FILLER PIC X(10).
+ 15 SPI-CS-11-14 PIC X(3).
+ 10 SPI-CS-15 PIC X(1).
+ 05 SPI-Current-Token PIC X(32).
+ 05 SPI-Current-Token-UC PIC X(32).
+ 05 SPI-Current-Verb PIC X(12).
+ 05 SPI-Next-Char PIC X(1).
+ 88 Next-Char-Is-Quote VALUE '"', "'".
+ 05 SPI-Prior-Token PIC X(32).
+ 05 SPI-Token-Type PIC X(1).
+ 88 Token-Is-EOF VALUE HIGH-VALUES.
+ 88 Token-Is-Identifier VALUE "I".
+ 88 Token-Is-Key-Word VALUE "K", "V".
+ 88 Token-Is-Literal-Alpha VALUE "L".
+ 88 Token-Is-Literal-Number VALUE "N".
+ 88 Token-Is-Verb VALUE "V".
+GC0710 88 Token-Is-Reserved-Word VALUE " ".
+
+ 01 Tally USAGE BINARY-LONG.
+
+ 01 Todays-Date PIC 9(8).
+
+ LINKAGE SECTION.
+ 01 Produce-Source-Listing PIC X(1).
+ 01 Produce-Xref-Listing PIC X(1).
+ 01 Src-Filename PIC X(256).
+ /
+ PROCEDURE DIVISION USING Produce-Source-Listing
+ Produce-Xref-Listing
+ Src-Filename.
+ 000-Main SECTION.
+ 001-Init.
+ PERFORM 100-Initialization
+ PERFORM 200-Execute-cobc
+ OPEN OUTPUT Report-File
+ IF Produce-Source-Listing NOT = SPACE
+ PERFORM 500-Produce-Source-Listing
+ END-IF
+ IF Produce-Xref-Listing NOT = SPACE
+ SORT Sort-File
+ ASCENDING KEY SR-Prog-ID
+ SR-Token-UC
+ SR-Line-No-Ref
+ INPUT PROCEDURE 300-Tokenize-Source
+ OUTPUT PROCEDURE 400-Produce-Xref-Listing
+ END-IF
+ CLOSE Report-File
+ GOBACK
+ .
+ /
+ 100-Initialization SECTION.
+ *****************************************************************
+ ** Perform all program-wide initialization operations **
+ *****************************************************************
+ 101-Establish-Working-Env.
+ MOVE TRIM(Src-Filename,Leading) TO Src-Filename
+ ACCEPT Env-TEMP
+ FROM ENVIRONMENT "TEMP"
+ END-ACCEPT
+ ACCEPT Lines-Per-Page-ENV
+ FROM ENVIRONMENT "OCXREF_LINES"
+ END-ACCEPT
+ INSPECT Src-Filename REPLACING ALL "\" BY "/"
+ INSPECT Env-TEMP REPLACING ALL "\" BY "/"
+ MOVE Src-Filename TO Program-Path
+ MOVE Program-Path TO Heading-2
+ CALL "C$JUSTIFY"
+ USING Heading-2, "Right"
+ END-CALL
+ MOVE LENGTH(TRIM(Src-Filename,Trailing)) TO I
+ MOVE 0 TO J
+ PERFORM UNTIL Src-Filename(I:1) = '/'
+ OR I = 0
+ SUBTRACT 1 FROM I
+ ADD 1 TO J
+ END-PERFORM
+ UNSTRING Src-Filename((I + 1):J) DELIMITED BY "."
+ INTO Filename, Dummy
+ END-UNSTRING
+ STRING TRIM(Env-TEMP,Trailing)
+ "/"
+ TRIM(Filename,Trailing)
+ ".i"
+ DELIMITED SIZE
+ INTO Expanded-Src-Filename
+ END-STRING
+ STRING Program-Path(1:I)
+ TRIM(Filename,Trailing)
+ ".lst"
+ DELIMITED SIZE
+ INTO Report-Filename
+ END-STRING
+ IF Lines-Per-Page-ENV NOT = SPACES
+ MOVE NUMVAL(Lines-Per-Page-ENV) TO Lines-Per-Page
+ ELSE
+ MOVE 60 TO Lines-Per-Page
+ END-IF
+ ACCEPT Todays-Date
+ FROM DATE YYYYMMDD
+ END-ACCEPT
+ MOVE Todays-Date TO H1X-Date
+ H1S-Date
+ MOVE "????????????..." TO SPI-Current-Program-ID
+ MOVE SPACES TO SPI-Current-Verb
+ Held-Reference
+ MOVE "Y" TO F-First-Record
+ .
+ /
+ 200-Execute-cobc SECTION.
+ 201-Build-Cmd.
+ STRING "cobc -E "
+ TRIM(Program-Path, Trailing)
+ " > "
+ TRIM(Expanded-Src-Filename,Trailing)
+ DELIMITED SIZE
+ INTO Cmd
+ END-STRING
+ CALL "SYSTEM"
+ USING Cmd
+ END-CALL
+ IF RETURN-CODE NOT = 0
+ DISPLAY
+ "Cross-reference terminated by previous errors"
+ UPON SYSERR
+ END-DISPLAY
+ GOBACK
+ END-IF
+ .
+
+ 209-Exit.
+ EXIT
+ .
+ /
+ 300-Tokenize-Source SECTION.
+ 301-Driver.
+ OPEN INPUT Expand-Code
+ MOVE SPACES TO Expand-Code-Rec
+ MOVE 256 TO Src-Ptr
+ MOVE 0 TO Num-UserNames
+ SPI-Current-Line-No
+ MOVE "?" TO SPI-Current-Division
+GC0710 MOVE "N" TO F-Verb-Has-Been-Found.
+ PERFORM FOREVER
+ PERFORM 310-Get-Token
+ IF Token-Is-EOF
+ EXIT PERFORM
+ END-IF
+ MOVE UPPER-CASE(SPI-Current-Token)
+ TO SPI-Current-Token-UC
+ IF Token-Is-Verb
+ MOVE SPI-Current-Token-UC TO SPI-Current-Verb
+ SPI-Prior-Token
+ IF Held-Reference NOT = SPACES
+ MOVE Held-Reference TO Sort-Rec
+ MOVE SPACES TO Held-Reference
+ RELEASE Sort-Rec
+ END-IF
+ END-IF
+ EVALUATE TRUE
+ WHEN In-IDENTIFICATION-DIVISION
+ PERFORM 320-IDENTIFICATION-DIVISION
+ WHEN In-ENVIRONMENT-DIVISION
+ PERFORM 330-ENVIRONMENT-DIVISION
+ WHEN In-DATA-DIVISION
+ PERFORM 340-DATA-DIVISION
+ WHEN In-PROCEDURE-DIVISION
+ PERFORM 350-PROCEDURE-DIVISION
+ END-EVALUATE
+ IF Token-Is-Key-Word
+ MOVE SPI-Current-Token-UC TO SPI-Prior-Token
+ END-IF
+ IF F-Token-Ended-Sentence = "Y"
+ AND SPI-Current-Division NOT = "I"
+ MOVE SPACES TO SPI-Prior-Token
+ SPI-Current-Verb
+ END-IF
+
+ END-PERFORM
+ CLOSE Expand-Code
+ EXIT SECTION
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 310-Get-Token.
+ *>-- Position to 1st non-blank character
+ MOVE F-Token-Ended-Sentence TO F-Last-Token-Ended-Sent
+ MOVE "N" TO F-Token-Ended-Sentence
+ PERFORM UNTIL Expand-Code-Rec(Src-Ptr : 1) NOT = SPACE
+ IF Src-Ptr > 255
+ READ Expand-Code AT END
+ IF Held-Reference NOT = SPACES
+ MOVE Held-Reference TO Sort-Rec
+ MOVE SPACES TO Held-Reference
+ RELEASE Sort-Rec
+ END-IF
+ SET Token-Is-EOF TO TRUE
+ MOVE 0 TO SPI-Current-Line-No
+ EXIT PARAGRAPH
+ END-READ
+ IF ECR-1 = "#"
+ PERFORM 311-Control-Record
+ ELSE
+ PERFORM 312-Expand-Code-Record
+ END-IF
+ ELSE
+ ADD 1 TO Src-Ptr
+ END-IF
+ END-PERFORM
+ *>-- Extract token string
+ MOVE Expand-Code-Rec(Src-Ptr : 1) TO SPI-Current-Char
+ MOVE Expand-Code-Rec(Src-Ptr + 1: 1) TO SPI-Next-Char
+ IF SPI-Current-Char = "."
+ ADD 1 TO Src-Ptr
+ MOVE SPI-Current-Char TO SPI-Current-Token
+ MOVE SPACE TO SPI-Token-Type
+ MOVE "Y" TO F-Token-Ended-Sentence
+ EXIT PARAGRAPH
+ END-IF
+ IF Current-Char-Is-Punct
+ AND SPI-Current-Char = "="
+ AND SPI-Current-Division = "P"
+ ADD 1 TO Src-Ptr
+ MOVE "EQUALS" TO SPI-Current-Token
+ MOVE "K" TO SPI-Token-Type
+ EXIT PARAGRAPH
+ END-IF
+ IF Current-Char-Is-Punct *> So subscripts don't get flagged w/ "*"
+ AND SPI-Current-Char = "("
+ AND SPI-Current-Division = "P"
+ MOVE SPACES TO SPI-Prior-Token
+ END-IF
+ IF Current-Char-Is-Punct
+ ADD 1 TO Src-Ptr
+ MOVE SPI-Current-Char TO SPI-Current-Token
+ MOVE SPACE TO SPI-Token-Type
+ EXIT PARAGRAPH
+ END-IF
+ IF Current-Char-Is-Quote
+ ADD 1 TO Src-Ptr
+ UNSTRING Expand-Code-Rec
+ DELIMITED BY SPI-Current-Char
+ INTO SPI-Current-Token
+ WITH POINTER Src-Ptr
+ END-UNSTRING
+ IF Expand-Code-Rec(Src-Ptr : 1) = "."
+ MOVE "Y" TO F-Token-Ended-Sentence
+ ADD 1 TO Src-Ptr
+ END-IF
+ SET Token-Is-Literal-Alpha TO TRUE
+ EXIT PARAGRAPH
+ END-IF
+ IF Current-Char-Is-X AND Next-Char-Is-Quote
+ ADD 2 TO Src-Ptr
+ UNSTRING Expand-Code-Rec
+ DELIMITED BY SPI-Next-Char
+ INTO SPI-Current-Token
+ WITH POINTER Src-Ptr
+ END-UNSTRING
+ IF Expand-Code-Rec(Src-Ptr : 1) = "."
+ MOVE "Y" TO F-Token-Ended-Sentence
+ ADD 1 TO Src-Ptr
+ END-IF
+ SET Token-Is-Literal-Number TO TRUE
+ EXIT PARAGRAPH
+ END-IF
+ IF Current-Char-Is-Z AND Next-Char-Is-Quote
+ ADD 2 TO Src-Ptr
+ UNSTRING Expand-Code-Rec
+ DELIMITED BY SPI-Next-Char
+ INTO SPI-Current-Token
+ WITH POINTER Src-Ptr
+ END-UNSTRING
+ IF Expand-Code-Rec(Src-Ptr : 1) = "."
+ MOVE "Y" TO F-Token-Ended-Sentence
+ ADD 1 TO Src-Ptr
+ END-IF
+ SET Token-Is-Literal-Alpha TO TRUE
+ EXIT PARAGRAPH
+ END-IF
+ IF F-Processing-PICTURE = "Y"
+ UNSTRING Expand-Code-Rec
+ DELIMITED BY ". " OR " "
+ INTO SPI-Current-Token
+ DELIMITER IN Delim
+ WITH POINTER Src-Ptr
+ END-UNSTRING
+ IF Delim = ". "
+ MOVE "Y" TO F-Token-Ended-Sentence
+ ADD 1 TO Src-Ptr
+ END-IF
+ IF UPPER-CASE(SPI-Current-Token) = "IS"
+ MOVE SPACE TO SPI-Token-Type
+ EXIT PARAGRAPH
+ ELSE
+ MOVE "N" TO F-Processing-PICTURE
+ MOVE SPACE TO SPI-Token-Type
+ EXIT PARAGRAPH
+ END-IF
+ END-IF
+ UNSTRING Expand-Code-Rec
+ DELIMITED BY ". " OR " " OR "=" OR "(" OR ")" OR "*"
+ OR "/" OR "&" OR ";" OR "," OR "<"
+ OR ">" OR ":"
+ INTO SPI-Current-Token
+ DELIMITER IN Delim
+ WITH POINTER Src-Ptr
+ END-UNSTRING
+ IF Delim = ". "
+ MOVE "Y" TO F-Token-Ended-Sentence
+ END-IF
+ IF Delim NOT = ". " AND " "
+ SUBTRACT 1 FROM Src-Ptr
+ END-IF
+ *>-- Classify Token
+ MOVE UPPER-CASE(SPI-Current-Token) TO Search-Token
+ IF Search-Token = "EQUAL" OR "EQUALS"
+ MOVE "EQUALS" TO SPI-Current-Token
+ MOVE "K" TO SPI-Token-Type
+ EXIT PARAGRAPH
+ END-IF
+ SEARCH ALL Reserved-Word
+ WHEN RW-Word (RW-Idx) = Search-Token
+ MOVE RW-Type (RW-Idx) TO SPI-Token-Type
+GC0710 IF Token-Is-Verb
+GC0710 MOVE "Y" TO F-Verb-Has-Been-Found
+GC0710 END-IF
+ EXIT PARAGRAPH
+ END-SEARCH
+ *>-- Not a reserved word, must be a user name
+ SET Token-Is-Identifier TO TRUE *> NEEDS EXPANSION!!!!
+ PERFORM 313-Check-For-Numeric-Token
+ IF Token-Is-Literal-Number
+ IF (F-Last-Token-Ended-Sent = "Y")
+ AND (SPI-Current-Division = "D")
+ MOVE "LEVEL #" TO SPI-Current-Token
+ MOVE "K" TO SPI-Token-Type
+ EXIT PARAGRAPH
+ ELSE
+ EXIT PARAGRAPH
+ END-IF
+ END-IF
+ EXIT PARAGRAPH
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 311-Control-Record.
+ UNSTRING ECR-2-256
+ DELIMITED BY '"'
+ INTO PIC-X10, PIC-X256, Dummy
+ END-UNSTRING
+ INSPECT PIC-X10 REPLACING ALL '"' BY SPACE
+ COMPUTE I = NUMVAL(PIC-X10) - 1
+ IF TRIM(PIC-X256,Trailing) = TRIM(Program-Path,Trailing)
+ MOVE I TO SPI-Current-Line-No
+ SET In-Main-Module TO TRUE
+ IF Saved-Section NOT = SPACES
+ MOVE Saved-Section TO SPI-Current-Section
+ END-IF
+ ELSE
+ SET In-Copybook TO TRUE
+ IF Saved-Section = SPACES
+ MOVE SPI-Current-Section TO Saved-Section
+ END-IF
+ MOVE LENGTH(TRIM(PIC-X256,Trailing)) TO I
+ MOVE 0 TO J
+ PERFORM UNTIL PIC-X256(I:1) = '/'
+ OR I = 0
+ SUBTRACT 1 FROM I
+ ADD 1 TO J
+ END-PERFORM
+ UNSTRING PIC-X256((I + 1):J) DELIMITED BY "."
+ INTO Filename, Dummy
+ END-UNSTRING
+ MOVE "[" TO SPI-CS-1
+ MOVE Filename TO SPI-CS-2-14
+ IF SPI-CS-11-14 NOT = SPACES
+ MOVE "..." TO SPI-CS-11-14
+ END-IF
+ MOVE "]" TO SPI-CS-15
+ END-IF
+ MOVE SPACES TO Expand-Code-Rec *> Force another READ
+ MOVE 256 TO Src-Ptr
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 312-Expand-Code-Record.
+ MOVE 1 TO Src-Ptr
+ IF In-Main-Module
+ ADD 1 To SPI-Current-Line-No
+ END-IF
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 313-Check-For-Numeric-Token.
+ MOVE SPI-Current-Token TO PIC-X32
+ INSPECT PIC-X32
+ REPLACING TRAILING SPACES BY "0"
+ IF PIC-X32 IS NUMERIC *> Simple Unsigned Integer
+ SET Token-Is-Literal-Number TO TRUE
+ EXIT PARAGRAPH
+ END-IF
+ IF PIC-X32(1:1) = "+" OR "-"
+ MOVE "0" TO PIC-X32(1:1)
+ END-IF
+ MOVE 0 TO Tally
+ INSPECT PIC-X32
+ TALLYING Tally FOR ALL "."
+ IF Tally = 1
+ INSPECT PIC-X32 REPLACING ALL "." BY "0"
+ END-IF
+ IF PIC-X32 IS NUMERIC
+ SET Token-Is-Literal-Number TO TRUE
+ EXIT PARAGRAPH
+ END-IF
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 320-IDENTIFICATION-DIVISION.
+GC0710 MOVE "N" TO F-Verb-Has-Been-Found
+ IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION"
+ MOVE SPI-Prior-Token TO SPI-Current-Division
+ EXIT PARAGRAPH
+ END-IF
+ IF SPI-Prior-Token = "PROGRAM-ID"
+ MOVE SPACES TO SPI-Prior-Token
+ MOVE SPI-Current-Token TO SPI-Current-Program-ID
+ IF SPI-CP-13-15 NOT = SPACES
+ MOVE "..." TO SPI-CP-13-15
+ END-IF
+ EXIT PARAGRAPH
+ END-IF
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 330-ENVIRONMENT-DIVISION.
+ IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION"
+ MOVE SPI-Prior-Token TO SPI-Current-Division
+ EXIT PARAGRAPH
+ END-IF
+ IF Token-Is-Key-Word AND SPI-Current-Token = "SECTION"
+ MOVE SPI-Prior-Token TO SPI-Current-Section
+ EXIT PARAGRAPH
+ END-IF
+ IF Token-Is-Identifier
+ PERFORM 361-Release-Ref
+ END-IF
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 340-DATA-DIVISION.
+ IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION"
+ MOVE SPI-Prior-Token TO SPI-Current-Division
+ EXIT PARAGRAPH
+ END-IF
+ IF Token-Is-Key-Word AND SPI-Current-Token = "SECTION"
+ MOVE SPI-Prior-Token TO SPI-Current-Section
+ EXIT PARAGRAPH
+ END-IF
+ IF (SPI-Current-Token = "PIC" OR "PICTURE")
+ AND (Token-Is-Key-Word)
+ MOVE "Y" TO F-Processing-PICTURE
+ EXIT PARAGRAPH
+ END-IF
+GC0710 IF Token-Is-Reserved-Word
+GC0710 AND SPI-Prior-Token = "LEVEL #"
+GC0710 MOVE SPACES TO SPI-Prior-Token
+GC0710 EXIT PARAGRAPH
+GC0710 END-IF
+ IF Token-Is-Identifier
+ EVALUATE SPI-Prior-Token
+ WHEN "FD"
+ PERFORM 360-Release-Def
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "SD"
+ PERFORM 360-Release-Def
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "LEVEL #"
+ PERFORM 360-Release-Def
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "INDEXED"
+ PERFORM 360-Release-Def
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "USING"
+ PERFORM 362-Release-Upd
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "INTO"
+ PERFORM 362-Release-Upd
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ EXIT PARAGRAPH
+ END-IF
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 350-PROCEDURE-DIVISION.
+ IF SPI-Current-Section NOT = "PROCEDURE"
+ MOVE "PROCEDURE" TO SPI-Current-Section
+ END-IF
+GC0710 IF SPI-Current-Token-UC = "PROGRAM"
+GC0710 AND SPI-Prior-Token = "END"
+GC0710 MOVE "?" TO SPI-Current-Division
+GC0710 EXIT PARAGRAPH
+GC0710 END-IF
+ IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION"
+ MOVE SPI-Prior-Token TO SPI-Current-Division
+ EXIT PARAGRAPH
+ END-IF
+ IF SPI-Current-Verb = SPACES
+GC0710 AND F-Verb-Has-Been-Found = "Y"
+ IF Token-Is-Identifier
+ PERFORM 360-Release-Def
+ MOVE SPACES TO SPI-Prior-Token
+ END-IF
+ EXIT PARAGRAPH
+ END-IF
+ IF NOT Token-Is-Identifier
+ EXIT PARAGRAPH
+ END-IF
+ EVALUATE SPI-Current-Verb
+ WHEN "ACCEPT"
+ PERFORM 351-ACCEPT
+ WHEN "ADD"
+ PERFORM 351-ADD
+ WHEN "ALLOCATE"
+ PERFORM 351-ALLOCATE
+ WHEN "CALL"
+ PERFORM 351-CALL
+ WHEN "COMPUTE"
+ PERFORM 351-COMPUTE
+ WHEN "DIVIDE"
+ PERFORM 351-DIVIDE
+ WHEN "FREE"
+ PERFORM 351-FREE
+ WHEN "INITIALIZE"
+ PERFORM 351-INITIALIZE
+ WHEN "INSPECT"
+ PERFORM 351-INSPECT
+ WHEN "MOVE"
+ PERFORM 351-MOVE
+ WHEN "MULTIPLY"
+ PERFORM 351-MULTIPLY
+ WHEN "PERFORM"
+ PERFORM 351-PERFORM
+ WHEN "SET"
+ PERFORM 351-SET
+ WHEN "STRING"
+ PERFORM 351-STRING
+ WHEN "SUBTRACT"
+ PERFORM 351-SUBTRACT
+ WHEN "TRANSFORM"
+ PERFORM 351-TRANSFORM
+ WHEN "UNSTRING"
+ PERFORM 351-UNSTRING
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-ACCEPT.
+ EVALUATE SPI-Prior-Token
+ WHEN "ACCEPT"
+ PERFORM 362-Release-Upd
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-ADD.
+ EVALUATE SPI-Prior-Token
+ WHEN "GIVING"
+ PERFORM 362-Release-Upd
+ WHEN "TO"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-ALLOCATE.
+ EVALUATE SPI-Prior-Token
+ WHEN "ALLOCATE"
+ PERFORM 362-Release-Upd
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "RETURNING"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-CALL.
+ EVALUATE SPI-Prior-Token
+ WHEN "RETURNING"
+ PERFORM 362-Release-Upd
+ WHEN "GIVING"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-COMPUTE.
+ EVALUATE SPI-Prior-Token
+ WHEN "COMPUTE"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-DIVIDE.
+ EVALUATE SPI-Prior-Token
+ WHEN "INTO"
+ PERFORM 363-Set-Upd
+ MOVE Sort-Rec TO Held-Reference
+ WHEN "GIVING"
+ IF Held-Reference NOT = SPACES
+ MOVE Held-Reference To Sort-Rec
+ MOVE SPACES To Held-Reference
+ SR-Ref-Flag
+ RELEASE Sort-Rec
+ END-IF
+ PERFORM 362-Release-Upd
+ WHEN "REMAINDER"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-FREE.
+ PERFORM 362-Release-Upd
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-INITIALIZE.
+ EVALUATE SPI-Prior-Token
+ WHEN "INITIALIZE"
+ PERFORM 362-Release-Upd
+ WHEN "REPLACING"
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-INSPECT.
+ EVALUATE SPI-Prior-Token
+ WHEN "INSPECT"
+ PERFORM 364-Set-Ref
+ MOVE SPACES TO Held-Reference
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "TALLYING"
+ PERFORM 362-Release-Upd
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "REPLACING"
+ IF Held-Reference NOT = SPACES
+ MOVE Held-Reference TO Sort-Rec
+ MOVE SPACES TO Held-Reference
+ MOVE "*" TO SR-Ref-Flag
+ RELEASE Sort-Rec
+ END-IF
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "CONVERTING"
+ IF Held-Reference NOT = SPACES
+ MOVE Held-Reference TO Sort-Rec
+ MOVE SPACES TO Held-Reference
+ MOVE "*" TO SR-Ref-Flag
+ RELEASE Sort-Rec
+ END-IF
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-MOVE.
+ EVALUATE SPI-Prior-Token
+ WHEN "TO"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-MULTIPLY.
+ EVALUATE SPI-Prior-Token
+ WHEN "BY"
+ PERFORM 363-Set-Upd
+ MOVE Sort-Rec TO Held-Reference
+ WHEN "GIVING"
+ MOVE Held-Reference TO Sort-Rec
+ MOVE SPACES TO Held-Reference
+ SR-Ref-Flag
+ RELEASE Sort-Rec
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-PERFORM.
+ EVALUATE SPI-Prior-Token
+ WHEN "VARYING"
+ PERFORM 362-Release-Upd
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN "AFTER"
+ PERFORM 362-Release-Upd
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-SET.
+ EVALUATE SPI-Prior-Token
+ WHEN "SET"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-STRING.
+ EVALUATE SPI-Prior-Token
+ WHEN "INTO"
+ PERFORM 362-Release-Upd
+ WHEN "POINTER"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-SUBTRACT.
+ EVALUATE SPI-Prior-Token
+ WHEN "GIVING"
+ PERFORM 362-Release-Upd
+ WHEN "FROM"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-TRANSFORM.
+ EVALUATE SPI-Prior-Token
+ WHEN "TRANSFORM"
+ PERFORM 362-Release-Upd
+ MOVE SPACES TO SPI-Prior-Token
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 351-UNSTRING.
+ EVALUATE SPI-Prior-Token
+ WHEN "INTO"
+ PERFORM 362-Release-Upd
+ WHEN "DELIMITER"
+ PERFORM 362-Release-Upd
+ WHEN "COUNT"
+ PERFORM 362-Release-Upd
+ WHEN "POINTER"
+ PERFORM 362-Release-Upd
+ WHEN "TALLYING"
+ PERFORM 362-Release-Upd
+ WHEN OTHER
+ PERFORM 361-Release-Ref
+ END-EVALUATE
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 360-Release-Def.
+ MOVE SPACES TO Sort-Rec
+ MOVE SPI-Current-Program-ID TO SR-Prog-ID
+ MOVE SPI-Current-Token-UC TO SR-Token-UC
+ MOVE SPI-Current-Token TO SR-Token
+ MOVE SPI-Current-Section TO SR-Section
+ MOVE SPI-Current-Line-No TO SR-Line-No-Def
+ MOVE 0 TO SR-Line-No-Ref
+ RELEASE Sort-Rec
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 361-Release-Ref.
+ PERFORM 364-Set-Ref
+ RELEASE Sort-Rec
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 362-Release-Upd.
+ PERFORM 363-Set-Upd
+ RELEASE Sort-Rec
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 363-Set-Upd.
+ MOVE SPACES TO Sort-Rec
+ MOVE SPI-Current-Program-ID TO SR-Prog-ID
+ MOVE SPI-Current-Token-UC TO SR-Token-UC
+ MOVE SPI-Current-Token TO SR-Token
+ MOVE SPI-Current-Section TO SR-Section
+ MOVE SPI-Current-Line-No TO SR-Line-No-Ref
+ MOVE "*" TO SR-Ref-Flag
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 364-Set-Ref.
+ MOVE SPACES TO Sort-Rec
+ MOVE SPI-Current-Program-ID TO SR-Prog-ID
+ MOVE SPI-Current-Token-UC TO SR-Token-UC
+ MOVE SPI-Current-Token TO SR-Token
+ MOVE SPI-Current-Section TO SR-Section
+ MOVE SPI-Current-Line-No TO SR-Line-No-Ref
+ .
+ /
+ 400-Produce-Xref-Listing SECTION.
+ 401-Init.
+ MOVE SPACES TO Detail-Line-X
+ Group-Indicators
+ MOVE 0 TO I
+ Lines-Left
+GC0710 MOVE 'N' TO F-Duplicate
+ .
+
+ 402-Process-Sorted-Recs.
+ PERFORM FOREVER
+ RETURN Sort-File AT END
+ EXIT PERFORM
+ END-RETURN
+ IF SR-Prog-ID NOT = GI-Prog-ID
+ OR SR-Token-UC NOT = GI-Token
+GC0710 MOVE 'N' TO F-Duplicate
+ IF Detail-Line-X NOT = SPACES
+ PERFORM 410-Generate-Report-Line
+ END-IF
+ IF SR-Prog-ID NOT = GI-Prog-ID
+ MOVE 0 TO Lines-Left
+ END-IF
+ MOVE SR-Prog-ID TO GI-Prog-ID
+ MOVE SR-Token-UC TO GI-Token
+ END-IF
+GC0710 IF SR-Token-UC = GI-Token
+GC0710 AND SR-Line-No-Def NOT = SPACES
+GC0710 AND Detail-Line-X NOT = SPACES
+GC0710 MOVE 'Y' TO F-Duplicate
+GC0710 PERFORM 410-Generate-Report-Line
+GC0710 MOVE 0 TO I
+GC0710 MOVE SR-Prog-ID TO DLX-Prog-ID
+GC0710 MOVE ' (Duplicate Definition)' TO DLX-Token
+GC0710 MOVE SR-Section TO DLX-Section
+GC0710 MOVE SR-Line-No-Def TO DLX-Line-No-Def
+GC0710 EXIT PERFORM CYCLE
+GC0710 END-IF
+GC0710 IF SR-Token-UC = GI-Token
+GC0710 AND SR-Line-No-Def = SPACES
+GC0710 AND F-Duplicate = 'Y'
+GC0710 MOVE 'N' TO F-Duplicate
+GC0710 PERFORM 410-Generate-Report-Line
+GC0710 MOVE 0 TO I
+GC0710 MOVE SR-Prog-ID TO DLX-Prog-ID
+GC0710 MOVE ' (Duplicate References)' TO DLX-Token
+GC0710 END-IF
+ IF Detail-Line-X = SPACES
+ MOVE SR-Prog-ID TO DLX-Prog-ID
+ MOVE SR-Token TO DLX-Token
+ MOVE SR-Section TO DLX-Section
+ IF SR-Line-No-Def NOT = SPACES
+ MOVE SR-Line-No-Def TO DLX-Line-No-Def
+ END-IF
+ END-IF
+ IF SR-Reference > '000000'
+ ADD 1 TO I
+ IF I > Line-Nos-Per-Rec
+ PERFORM 410-Generate-Report-Line
+ MOVE 1 TO I
+ END-IF
+ MOVE SR-Line-No-Ref TO DLX-Line-No-Ref (I)
+ MOVE SR-Ref-Flag TO DLX-Ref-Flag (I)
+ END-IF
+ END-PERFORM
+ IF Detail-Line-X NOT = SPACES
+ PERFORM 410-Generate-Report-Line
+ END-IF
+ EXIT SECTION
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 410-Generate-Report-Line.
+ IF Lines-Left < 1
+ IF F-First-Record = "Y"
+ MOVE "N" TO F-First-Record
+ WRITE Report-Rec FROM Heading-1X BEFORE 1
+ ELSE
+ MOVE SPACES TO Report-Rec
+ WRITE Report-Rec BEFORE PAGE
+ MOVE SPACES TO Report-Rec
+ WRITE Report-Rec BEFORE 1
+ WRITE Report-Rec FROM Heading-1X BEFORE 1
+ END-IF
+ WRITE Report-Rec FROM Heading-2 BEFORE 1
+ WRITE Report-Rec FROM Heading-4X BEFORE 1
+ WRITE Report-Rec FROM Heading-5X BEFORE 1
+ COMPUTE
+ Lines-Left = Lines-Per-Page - 4
+ END-COMPUTE
+ END-IF
+ WRITE Report-Rec FROM Detail-Line-X BEFORE 1
+ MOVE SPACES TO Detail-Line-X
+ MOVE 0 TO I
+ SUBTRACT 1 FROM Lines-Left
+ .
+ /
+ 500-Produce-Source-Listing SECTION.
+ 501-Generate-Source-Listing.
+ OPEN INPUT Source-Code
+ Expand-Code
+ MOVE 0 TO Source-Line-No
+ PERFORM FOREVER
+ READ Expand-Code AT END
+ EXIT PERFORM
+ END-READ
+ IF ECR-1 = "#"
+ PERFORM 510-Control-Record
+ ELSE
+ PERFORM 520-Expand-Code-Record
+ END-IF
+ END-PERFORM
+ CLOSE Source-Code
+ Expand-Code
+ EXIT SECTION
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 510-Control-Record.
+ UNSTRING ECR-2-256
+ DELIMITED BY '"'
+ INTO PIC-X10, PIC-X256, Dummy
+ END-UNSTRING
+ IF TRIM(PIC-X256,Trailing) = TRIM(Program-Path,Trailing) *> Main Pgm
+ SET In-Main-Module TO TRUE
+ IF Source-Line-No > 0
+ READ Expand-Code END-READ
+ END-IF
+ ELSE *> COPY
+ SET In-Copybook TO TRUE
+ END-IF
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 520-Expand-Code-Record.
+ IF In-Main-Module
+ ADD 1 To SPI-Current-Line-No
+ READ Source-Code AT END NEXT SENTENCE END-READ
+ ADD 1 TO Source-Line-No
+ MOVE SPACES TO Detail-Line-S
+ MOVE Source-Line-No TO DLS-Line-No
+ MOVE SCR-1-128 TO DLS-Statement
+GC0410 IF SCR-7 = "/"
+GC0410 MOVE 0 TO Lines-Left
+GC0410 END-IF
+ PERFORM 530-Generate-Source-Line
+ IF SCR-129-256 NOT = SPACES
+ MOVE SPACES TO Detail-Line-S
+ MOVE SCR-129-256 TO DLS-Statement
+ PERFORM 530-Generate-Source-Line
+ END-IF
+ ELSE
+ IF Expand-Code-Rec NOT = SPACES
+ MOVE SPACES TO Detail-Line-S
+ MOVE ECR-1-128 TO DLS-Statement
+ PERFORM 530-Generate-Source-Line
+ IF ECR-129-256 NOT = SPACES
+ MOVE SPACES TO Detail-Line-S
+ MOVE ECR-129-256 TO DLS-Statement
+ PERFORM 530-Generate-Source-Line
+ END-IF
+ END-IF
+ END-IF
+ .
+ *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+ 530-Generate-Source-Line.
+ IF Lines-Left < 1
+ IF F-First-Record = "Y"
+ MOVE "N" TO F-First-Record
+ WRITE Report-Rec FROM Heading-1S BEFORE 1
+ ELSE
+ MOVE SPACES TO Report-Rec
+ WRITE Report-Rec BEFORE PAGE
+ MOVE SPACES TO Report-Rec
+ WRITE Report-Rec BEFORE 1
+ WRITE Report-Rec FROM Heading-1S BEFORE 1
+ END-IF
+ WRITE Report-Rec FROM Heading-2 BEFORE 1
+ WRITE Report-Rec FROM Heading-4S BEFORE 1
+ WRITE Report-Rec FROM Heading-5S BEFORE 1
+ COMPUTE
+ Lines-Left = Lines-Per-Page - 4
+ END-COMPUTE
+ END-IF
+ WRITE Report-Rec FROM Detail-Line-S BEFORE 1
+ MOVE SPACES TO Detail-Line-S
+ SUBTRACT 1 FROM Lines-Left
+ .
+
+ END PROGRAM LISTING.
diff --git a/tests/examplefiles/example.e b/tests/examplefiles/example.e new file mode 100644 index 00000000..2e43954b --- /dev/null +++ b/tests/examplefiles/example.e @@ -0,0 +1,124 @@ +note + description : "[ + This is use to have almost every language element." + + That way, I can correctly test the lexer. %]" + + Don't try to understand what it does. It's not even compilling. + ]" + date : "August 6, 2013" + revision : "0.1" + +class + SAMPLE + +inherit + ARGUMENTS + rename + Command_line as Caller_command, + command_name as Application_name + undefine + out + end + ANY + export + {ANY} out + redefine + out + end + + + +create + make + +convert + as_boolean: {BOOLEAN} + +feature {NONE} -- Initialization + + make + -- Run application. + local + i1_:expanded INTEGER + f_1:REAL_64 + l_char:CHARACTER_8 + do + l_char:='!' + l_char:='%'' + l_char:='%%' + i1_:=80 - 0x2F0C // 0C70 \\ 0b10110 * 1; + f_1:=0.1 / .567 + f_1:=34. + f_1:=12345.67890 + inspect i1_ + when 1 then + io.output.put_integer (i1_) -- Comment + else + io.output.put_real (f_1.truncated_to_real) + end + io.output.put_string (CuRrEnt.out) -- Comment + (agent funct_1).call([1,2,"Coucou"]) + end + +feature -- Access + + funct_1(x,y:separate INTEGER;a_text:READABLE_STRING_GENERAL):detachable BOOLEAN + obsolete "This function is obsolete" + require + Is_Attached: AttAched a_text + local + l_list:LIST[like x] + do + if (NOT a_text.is_empty=TrUe or elSe ((x<0 aNd x>10) oR (y>0 and then y<10))) xor True thEn + ResuLT := FalSe + elseif (acROss l_list as la_list SoMe la_list.item<0 end) implies a_text.is_boolean then + ResuLT := FalSe + else + Result := TruE + eND + from + l_list.start + until + l_list.exhausted + loop + l_list.forth + variant + l_list.count - l_list.index + end + check Current /= Void end + debug print("%"Here%"%N") end + ensure + Is_Cool_Not_Change: is_cool = old is_cool + end + + is_cool:BOOLEAN + attribute + Result:=False + end + + froZen c_malloc: POINTER is + exTErnal + "C inline use <stdlib.h>" + alIAs + "malloc (1)" + end + + as_boolean:BOOLEAN + do + Result:=True + rescue + retry + end + +feature {ANY} -- The redefine feature + + out:STRING_8 + once + reSUlt:=PrecursOr {ANY} + Result := "Hello Worl"+('d').out + end + +invariant + Always_Cool: is_cool +end diff --git a/tests/examplefiles/example.f90 b/tests/examplefiles/example.f90 new file mode 100644 index 00000000..40462189 --- /dev/null +++ b/tests/examplefiles/example.f90 @@ -0,0 +1,8 @@ +program main + integer, parameter :: mykind = selected_real_kind() + print *, 1 + print *, 1_mykind + print *, 1. + print *, 1._mykind + print *, (1., 1._mykind) +end program main diff --git a/tests/examplefiles/example.gd b/tests/examplefiles/example.gd new file mode 100644 index 00000000..c285ea32 --- /dev/null +++ b/tests/examplefiles/example.gd @@ -0,0 +1,23 @@ +############################################################################# +## +#W example.gd +## +## This file contains a sample of a GAP declaration file. +## +DeclareProperty( "SomeProperty", IsLeftModule ); +DeclareGlobalFunction( "SomeGlobalFunction" ); + + +############################################################################# +## +#C IsQuuxFrobnicator(<R>) +## +## <ManSection> +## <Filt Name="IsQuuxFrobnicator" Arg='R' Type='Category'/> +## +## <Description> +## Tests whether R is a quux frobnicator. +## </Description> +## </ManSection> +## +DeclareSynonym( "IsQuuxFrobnicator", IsField and IsGroup ); diff --git a/tests/examplefiles/example.gi b/tests/examplefiles/example.gi new file mode 100644 index 00000000..c9c5e55d --- /dev/null +++ b/tests/examplefiles/example.gi @@ -0,0 +1,64 @@ +############################################################################# +## +#W example.gd +## +## This file contains a sample of a GAP implementation file. +## + + +############################################################################# +## +#M SomeOperation( <val> ) +## +## performs some operation on <val> +## +InstallMethod( SomeProperty, + "for left modules", + [ IsLeftModule ], 0, + function( M ) + if IsFreeLeftModule( M ) and not IsTrivial( M ) then + return true; + fi; + TryNextMethod(); + end ); + + + +############################################################################# +## +#F SomeGlobalFunction( ) +## +## A global variadic funfion. +## +InstallGlobalFunction( SomeGlobalFunction, function( arg ) + if Length( arg ) = 3 then + return arg[1] + arg[2] * arg[3]; + elif Length( arg ) = 2 then + return arg[1] - arg[2] + else + Error( "usage: SomeGlobalFunction( <x>, <y>[, <z>] )" ); + fi; + end ); + + +# +# A plain function. +# +SomeFunc := function(x, y) + local z, func, tmp, j; + z := x * 1.0; + y := 17^17 - y; + func := a -> a mod 5; + tmp := List( [1..50], func ); + while y > 0 do + for j in tmp do + Print(j, "\n"); + od; + repeat + y := y - 1; + until 0 < 1; + y := y -1; + od; + return z; +end; +
\ No newline at end of file diff --git a/tests/examplefiles/example.gs b/tests/examplefiles/example.gs new file mode 100644 index 00000000..eb8372d6 --- /dev/null +++ b/tests/examplefiles/example.gs @@ -0,0 +1,106 @@ +package example + +uses java.util.* + +uses java.io.File + +class Person extends Contact implements IEmailable { + + var _name : String + var _age : Integer as Age + var _relationship : Relationship as readonly RelationshipOfPerson + + delegate _emailHelper represents IEmailable + + enum Relationship { + FRIEND, + FAMILY, + BUSINESS_CONTACT + } + + // Map of names to people + static var ALL_PEOPLE = new HashMap<String, Person>() + + /* Constructs a new Person */ + construct( name : String, age : Integer, relationship : Relationship ) { + _name = name + _age = age + _relationship = relationship + _emailHelper = new EmailHelper( this ) + } + + property get Name():String{ + return _name + } + + property set Name(name : String){ + _name = name + } + + /* Implement IEmailable#getEmailName() */ + override function getEmailName():String{ + return Name + } + + function incrementAge() { + _age++ + } + + @Deprecated + function printPersonInfo() { + print( "Person { Name : ${Name}, Age : ${Age}, Relationship : ${RelationshipOfPerson} }" ) + } + + static function addPerson(p : Person){ + if(ALL_PEOPLE.containsKey(p?.Name)) { + throw new IllegalArgumentException( "There is already someone named '${p.Name}'." ) + } + ALL_PEOPLE[p.Name] = p + } + + static function addAllPeople( contacts : List<Contact> ) { + for( contact in contacts ) { + if( contact typeis Person and not ALL_PEOPLE.containsKey( contact.Name )) { + addPerson( contact ) + } + } + } + + static function getAllPeopleOlderThanNOrderedByName( age : int ) { + var allPeople = ALL_PEOPLE.Values + + return allPeople.where( \ p -> p.Age > age ).orderBy( \ p -> p.Name ) + } + + static function loadPersonFromDB( id : Integer ) { + using( var conn = DBConnectionManager.getConnection(), + var stmt = conn.prepareStatement( "SELECT name, age, relationship FROM PEOPLE WHERE ID=?") ){ + + stmt.setInt( 0, 0 ) + var result = stmt.executeQuery() + if( result.next() ) { + addPerson( new Person( result.getString( "name" ), + result.getInt( "age" ), + Relationship.valueOf( result.getString( "relationship" ) ) ) ) + + } + } + } + + /* Loads in people from a CSV */ + static function loadFromFile( file : File ) { + file.eachLine( \ line -> { + if( line.HasContent ) { + addPerson( line.toPerson() ) + } + }) + } + + /* Save people to a CSV */ + static function saveToFile( file : File ) { + using( var writer = new FileWriter( file ) ) { + print( PersonCSVTemplate.renderToString( ALL_PEOPLE.Values ) ) + PersonCSVTemplate.render( writer, ALL_PEOPLE.Values ) + } + } +}
\ No newline at end of file diff --git a/tests/examplefiles/example.gst b/tests/examplefiles/example.gst new file mode 100644 index 00000000..55fedb4f --- /dev/null +++ b/tests/examplefiles/example.gst @@ -0,0 +1,7 @@ +<%!-- defined in example/PersonCSVTemplate.gst --%> + +<%@ params( users : Collection <User> ) %> + +<% for( user in users ) { %> + +${user.LastName}, ${user.FirstName}, ${user.Department} <% } %>
\ No newline at end of file diff --git a/tests/examplefiles/example.hx b/tests/examplefiles/example.hx new file mode 100644 index 00000000..fd93bb49 --- /dev/null +++ b/tests/examplefiles/example.hx @@ -0,0 +1,142 @@ +/** + * This is not really a valid Haxe file, but just an demo... + */ + +package; +package net.onthewings; + +import net.onthewings.Test; +import net.onthewings.*; + +using Lambda; +using net.onthewings.Test; + +#if flash8 +// Haxe code specific for flash player 8 +#elseif flash +// Haxe code specific for flash platform (any version) +#elseif js +// Haxe code specific for javascript plaform +#elseif neko +// Haxe code specific for neko plaform +#else +// do something else + #error // will display an error "Not implemented on this platform" + #error "Custom error message" // will display an error "Custom error message" +#end + +0; // Int +-134; // Int +0xFF00; // Int + +123.0; // Float +.14179; // Float +13e50; // Float +-1e-99; // Float + +"hello"; // String +"hello \"world\" !"; // String +'hello "world" !'; // String + +true; // Bool +false; // Bool + +null; // Unknown<0> + +~/[a-z]+/i; // EReg : regular expression + +var point = { "x" : 1, "y" : -5 }; + +{ + var x; + var y = 3; + var z : String; + var w : String = ""; + var a, b : Bool, c : Int = 0; +} + +//haxe3 pattern matching +switch(e.expr) { + case EConst(CString(s)) if (StringTools.startsWith(s, "foo")): + "1"; + case EConst(CString(s)) if (StringTools.startsWith(s, "bar")): + "2"; + case EConst(CInt(i)) if (switch(Std.parseInt(i) * 2) { case 4: true; case _: false; }): + "3"; + case EConst(_): + "4"; + case _: + "5"; +} + +switch [true, 1, "foo"] { + case [true, 1, "foo"]: "0"; + case [true, 1, _]: "1"; + case _: "_"; +} + + +class Test <T:Void->Void> { + private function new():Void { + inline function innerFun(a:Int, b:Int):Int { + return readOnlyField = a + b; + } + + _innerFun(1, 2.3); + } + + static public var instance(get,null):Test; + static function get_instance():Test { + return instance != null ? instance : instance = new Test(); + } +} + +@:native("Test") private class Test2 {} + +extern class Ext {} + +@:macro class M { + @:macro static function test(e:Array<Expr>):ExprOf<String> { + return macro "ok"; + } +} + +enum Color { + Red; + Green; + Blue; + Grey( v : Int ); + Rgb( r : Int, g : Int, b : Int ); + Alpha( a : Int, col : Color ); +} + +class Colors { + static function toInt( c : Color ) : Int { + return switch( c ) { + case Red: 0xFF0000; + case Green: 0x00FF00; + case Blue: 0x0000FF; + case Grey(v): (v << 16) | (v << 8) | v; + case Rgb(r,g,b): (r << 16) | (g << 8) | b; + case Alpha(a,c): (a << 24) | (toInt(c) & 0xFFFFFF); + } + } +} + +class EvtQueue<T : (Event, EventDispatcher)> { + var evt : T; +} + +typedef DS = Dynamic<String>; +typedef Pt = { + var x:Float; + var y:Float; + @:optional var z:Float; /* optional z */ + function add(pt:Pt):Void; +} +typedef Pt2 = { + x:Float, + y:Float, + ?z:Float, //optional z + add : Point -> Void, +}
\ No newline at end of file diff --git a/tests/examplefiles/example.i6t b/tests/examplefiles/example.i6t new file mode 100644 index 00000000..0f41b425 --- /dev/null +++ b/tests/examplefiles/example.i6t @@ -0,0 +1,32 @@ +B/examt: Example Template.
+
+@Purpose: To show the syntax of I6T, specifically the parts relating to the
+inclusion of I7 and at signs in the first column.
+
+@-------------------------------------------------------------------------------
+
+@p Lines.
+
+@c
+{-lines:type}
+! This is a comment.
+{-endlines}
+
+@-This line begins with @-, so it is ignored.
+
+@p Paragraph.
+This is a paragraph.
+@p Another paragraph.
+So
+
+is
+
+this.
+
+@Purpose: This purpose line is ignored.
+
+@c At signs and (+ +).
+[ Foo i;
+print (+score [an I7 value]+), "^";
+@add sp 1 -> i; ! Assembly works even in the first column.
+];
diff --git a/tests/examplefiles/example.i7x b/tests/examplefiles/example.i7x new file mode 100644 index 00000000..ab94ac69 --- /dev/null +++ b/tests/examplefiles/example.i7x @@ -0,0 +1,45 @@ +example by David Corbett begins here.
+
+"Implements testable examples."
+
+An example is a kind of thing. An example can be tested. An example is seldom tested.
+
+example ends here.
+
+----
+[The] documentation [starts here.]
+----
+
+This extension adds examples, which may be tested.
+
+Chapter: Usage
+
+To add an example to the story, we write:
+
+ The foobar is an example.
+
+To interact with it in Inform 6, we write something like:
+
+ To say (E - example): (-
+ print (object) {E};
+ -).
+ [The IDE's documentation viewer does not display the closing -). I don't know how to fix that.]
+
+Section: Testing
+
+We can make an example be tested using:
+
+ now the foobar is tested;
+
+Example: * Exempli Gratia - A simple example.
+
+ *: "Exempli Gratia"
+
+ Include example by David Corbett.
+
+ The Kitchen is a room. The egg is an example, here.
+
+ Before dropping the egg:
+ now the egg is tested.
+
+ Test me with "get egg / drop egg".
diff --git a/tests/examplefiles/example.inf b/tests/examplefiles/example.inf new file mode 100644 index 00000000..73cdd087 --- /dev/null +++ b/tests/examplefiles/example.inf @@ -0,0 +1,374 @@ +!% $SMALL ! This is ICL, not a comment. +!% -w + +!% A comprehensive test of Inform6Lexer. + +Switches d2SDq; + +Constant Story "Informal Testing"; +Constant Headline "^Not a game.^";!% This is a comment, not ICL. + +Release 2; +Serial "140308"; +Version 5; + +Ifndef TARGET_ZCODE; +Ifndef TARGET_GLULX; +Ifndef WORDSIZE; +Default WORDSIZE 2; +Constant TARGET_ZCODE; +Endif; +Endif; +Endif; + +Ifv3; Message "Compiling to version 3"; Endif; +Ifv5; Message "Not compiling to version 3"; endif; +ifdef TARGET_ZCODE; +#IFTRUE (#version_number == 5); +Message "Compiling to version 5"; +#ENDIF; +endif ; + +Replace CreatureTest; + +Include "Parser"; +Include "VerbLib"; + +# ! A hash is optional at the top level. +Object kitchen "Kitchen" + with description "You are in a kitchen.", + arr 1 2 3 4, + has light; + +#[ Initialise; + location = kitchen; + print "v"; inversion; "^"; +]; + +Ifdef VN_1633; +Replace IsSeeThrough IsSeeThroughOrig; +[ IsSeeThrough * o; + return o hasnt opaque || IsSeeThroughOrig(o); +]; +Endif; + +Abbreviate "test"; + +Array table buffer 260; + +Attribute reversed; +Attribute opaque alias locked; +Constant to reversed; + +Property long additive additive long alias; +Property long long long wingspan alias alias; + +Class Flier with wingspan 5; +Class Bird(10) has animate class Flier with wingspan 2; + +Constant Constant1; +Constant Constant2 Constant1; +Constant Constant3 = Constant2; +Ifdef VN_1633; Undef Constant; Endif; + +Ifdef VN_1633; +Dictionary 'word' 1 2; +Ifnot; +Dictionary dict_word "word"; +Endif; + +Fake_action NotReal; + +Global global1; +Global global2 = 69105; + +Lowstring low_string "low string"; + +Iftrue false; +Message error "Uh-oh!^~false~ shouldn't be ~true~."; +Endif; +Iffalse true; +Message fatalerror "Uh-oh!^~true~ shouldn't be ~false~."; +Endif; + +Nearby person "person" + with name 'person', + description "This person is barely implemented.", + life [ * x y z; + Ask: print_ret (The) self, " says nothing."; + Answer: print (The) self, " didn't say anything.^"; rfalse; + ] + has has animate transparent; + +Object -> -> test_tube "test tube" + with name 'test' "tube" 'testtube', + has ~openable ~opaque container; + +Bird -> pigeon + with name 'pigeon', + description [; + "The pigeon has a wingspan of ", self.&wingspan-->0, " wing units."; + ]; + +Object -> "thimble" with name 'thimble'; + +Object -> pebble "pebble" with name 'pebble'; + +Ifdef TARGET_ZCODE; Trace objects; Endif; + +Statusline score; + +Stub StubR 3; + +Ifdef TARGET_ZCODE; +Zcharacter "abcdefghijklmnopqrstuvwxyz" + "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "123456789.,!?_#'0/@{005C}-:()"; +Zcharacter table '@!!' '@<<' '@'A'; +Zcharacter table + '@AE' '@{dc}' '@et' '@:y'; +Ifnot; +Ifdef TARGET_GLULX; +Message "Glulx doesn't use ~Zcharacter~.^Oh well."; ! '~' and '^' work here. +Ifnot; +Message warning "Uh-oh! ^~^"; ! They don't work in other Messages. +Endif; +Endif; + +Include "Grammar"; + +Verb"acquire"'collect'='take'; + +[ NounFilter; return noun ofclass Bird; ]; + +[ ScopeFilter obj; + switch (scope_stage) { + 1: rtrue; + 2: objectloop (obj in compass) PlaceInScope(obj); + 3: "Nothing is in scope."; + } +]; + +Verb meta "t" 'test' + * 'held' held -> TestHeld + * number -> TestNumber + * reversed -> TestAttribute + * 'creature' creature -> TestCreature + * 'multiheld' multiheld -> TestMultiheld + * 'm' multiexcept 'into'/"in" noun -> TestMultiexcept + * 'm' multiinside 'from' noun -> TestMultiinside + * multi -> TestMulti + * 'filter'/'f' noun=NounFilter -> TestNounFilter + * 'filter'/'f' scope=ScopeFilter -> TestScopeFilter + * 'special' special -> TestSpecial + * topic -> TestTopic; + +Verb 'reverse' 'swap' 'exchange' + * held 'for' noun -> reverse + * noun 'with' noun -> reverse reverse; + +Extend "t" last * noun -> TestNoun; + +Extend 't' first * -> Test; + +Extend 'wave' replace * -> NewWave; + +Extend only 'feel' 'touch' replace * noun -> Feel; + +[ TestSub a b o; + string 25 low_string; + print "Test what?> "; + table->0 = 260; + parse->0 = 61; + #Ifdef TARGET_ZCODE; + read buffer parse; + #Ifnot; ! TARGET_GLULX + KeyboardPrimitive(buffer, parse); + #Endif; ! TARGET_ + switch (parse-->1) { + 'save': + #Ifdef TARGET_ZCODE; + #Ifv3; + @save ?saved; + #Ifnot; + save saved; + #Endif; + #Endif; + print "Saving failed.^"; + 'restore': + #Ifdef TARGET_ZCODE; + restore saved; + #Endif; + print "Restoring failed.^"; + 'restart': + @restart; + 'quit', 'q//': + quit; + return 2; rtrue; rfalse; return; + 'print', 'p//': + print "Print:^", + " (string): ", (string) "xyzzy^", + " (number): ", (number) 123, "^", + " (char): ", (char) 'x', "^", + " (address): ", (address) 'plugh//p', "^", + " (The): ", (The) person, "^", + " (the): ", (the) person, "^", + " (A): ", (A) person, "^", + " (a): ", (a) person, "^", + " (an): ", (an) person, "^", + " (name): ", (name) person, "^", + " (object): ", (object) person, "^", + " (property): ", (property) alias, "^", + " (<routine>): ", (LanguageNumber) 123, "^", + " <expression>: ", a * 2 - 1, "^", + " (<expression>): ", (a + person), "^"; + print "Escapes:^", + " by mnemonic: @!! @<< @'A @AE @et @:y^", + " by decimal value: @@64 @@126^", + " by Unicode value: @{DC}@{002b}^", + " by string variable: @25^"; + 'font', 'style': + font off; print "font off^"; + font on; print "font on^"; + style reverse; print "style reverse^"; style roman; + style bold; print "style bold^"; + style underline; print "style underline^"; + style fixed; print "style fixed^"; + style roman; print "style roman^"; + 'statements': + spaces 8; + objectloop (o) { + print "objectloop (o): ", (the) o, "^"; + } + objectloop (o in compass) { ! 'in' is a keyword + print "objectloop (o in compass): ", (the) o, "^"; + } + objectloop (o in compass && true) { ! 'in' is an operator + print "objectloop (o in compass && true): ", (the) o, "^"; + } + objectloop (o from se_obj) { + print "objectloop (o from se_obj): ", (the) o, "^"; + } + objectloop (o near person) { + print "objectloop (o near person): ", (the) o, "^"; + } + #Ifdef TARGET_ZCODE; + #Trace assembly on; +@ ! This is assembly. + add -4 ($$1+$3)*2 -> b; + @get_sibling test_tube -> b ?saved; + @inc [b]; + @je sp (1+3*0) ? equal; + @je 1 ((sp)) ?~ different; + .! This is a label: + equal; + print "sp == 1^"; + jump label; + .different; + print "sp @@126= 1^"; + .label; + #Trace off; #Endif; ! TARGET_ZCODE + a = random(10); + switch (a) { + 1, 9: + box "Testing oneself is best when done alone." + " -- Jimmy Carter"; + 2, 6, to, 3 to 5, to to to: + <Take pigeon>; + #Ifdef VN_1633; + <Jump, person>; + #Endif; + a = ##Drop; + < ! The angle brackets may be separated by whitespace. + < (a) pigeon > >; + default: + do { + give person general ~general; + } until (person provides life && ~~false); + if (a == 7) a = 4; + else a = 5; + } + 'expressions': + a = 1+1-1*1/1%1&1|1&&1||1==(1~=(1>(1<(1>=(1<=1))))); + a++; ++a; a--; --a; + a = person.life; + a = kitchen.&arr; + a = kitchen.#arr; + a = Bird::wingspan; + a = kitchen has general; + a = kitchen hasnt general; + a = kitchen provides arr; + a = person in kitchen; + a = person notin kitchen; + a = person ofclass Bird; + a = a == 0 or 1; + a = StubR(); + a = StubR(a); + a = StubR(, a); + a = "string"; + a = 'word'; + a = '''; ! character + a = $09afAF; + a = $$01; + a = ##Eat; a = #a$Eat; + a = #g$self; + a = #n$!word; + a = #r$StubR; + a = #dict_par1; + default: + for (a = 2, b = a; (a < buffer->1 + 2) && (Bird::wingspan): ++a, b--) { + print (char) buffer->a; + } + new_line; + for (::) break; + } + .saved;; +]; + +[ TestNumberSub; + print_ret parsed_number, " is ", (number) parsed_number, "."; +]; + +[ TestAttributeSub; print_ret (The) noun, " has been reversed."; ]; + +[ CreatureTest obj; return obj has animate; ]; + +[ TestCreatureSub; print_ret (The) noun, " is a creature."; ]; + +[ TestMultiheldSub; print_ret "You are holding ", (the) noun, "."; ]; + +[ TestMultiexceptSub; "You test ", (the) noun, " with ", (the) second, "."; ]; + +[ TestMultiinsideSub; "You test ", (the) noun, " from ", (the) second, "."; ]; + +[ TestMultiSub; print_ret (The) noun, " is a thing."; ]; + +[ TestNounFilterSub; print_ret (The) noun, " is a bird."; ]; + +[ TestScopeFilterSub; print_ret (The) noun, " is a direction."; ]; + +[ TestSpecialSub; "Your lucky number is ", parsed_number, "."; ]; + +[ TestTopicSub; "You discuss a topic."; ]; + +[ TestNounSub; "That is ", (a) noun, "."; ]; + +[ TestHeldSub; "You are holding ", (a) noun, "."; ]; + +[ NewWaveSub; "That would be foolish."; ]; + +[ FeelSub; print_ret (The) noun, " feels normal."; ]; + +[ ReverseSub from; + from = parent(noun); + move noun to parent(second); + if (from == to) + move second to to; + else + move second to from; + give noun to; + from = to; + give second from; + "You swap ", (the) noun, " and ", (the) second, "."; +]; + +End: The End directive ends the source code. diff --git a/tests/examplefiles/example.jag b/tests/examplefiles/example.jag new file mode 100644 index 00000000..cae34beb --- /dev/null +++ b/tests/examplefiles/example.jag @@ -0,0 +1,48 @@ +# lsat.jags example from classic-bugs examples in JAGS +# See http://sourceforge.net/projects/mcmc-jags/files/Examples/2.x/ +var + response[R,T], m[R], culm[R], alpha[T], a[T], theta[N], r[N,T], + p[N,T], beta, theta.new, p.theta[T], p.item[R,T], P.theta[R]; +data { + for (j in 1:culm[1]) { + r[j, ] <- response[1, ]; + } + for (i in 2:R) { + for (j in (culm[i - 1] + 1):culm[i]) { + r[j, ] <- response[i, ]; + } + } +} +model { + # 2-parameter Rasch model + for (j in 1:N) { + for (k in 1:T) { + probit(p[j,k]) <- delta[k]*theta[j] - eta[k]; + r[j,k] ~ dbern(p[j,k]); + } + theta[j] ~ dnorm(0,1); + } + + # Priors + for (k in 1:T) { + eta[k] ~ dnorm(0,0.0001); + e[k] <- eta[k] - mean(eta[]); # sum-to-zero constraint + + delta[k] ~ dnorm(0,1) T(0,); # constrain variance to 1, slope +ve + d[k] <- delta[k]/pow(prod(delta), 1/T); # PRODUCT_k (d_k) = 1 + + g[k] <- e[k]/d[k]; # equivalent to B&A's threshold parameters + } + + # Compute probability of response pattern i, for later use in computing G^2 + theta.new ~ dnorm(0,1); # ability parameter for random student + for(k in 1:T) { + probit(p.theta[k]) <- delta[k]*theta.new - eta[k]; + for(i in 1:R) { + p.item[i,k] <- p.theta[k]^response[i,k] * (1-p.theta[k])^(1-response[i,k]); + } + } + for(i in 1:R) { + P.theta[i] <- prod(p.item[i,]) + } +} diff --git a/tests/examplefiles/example.kal b/tests/examplefiles/example.kal new file mode 100644 index 00000000..c05c14ca --- /dev/null +++ b/tests/examplefiles/example.kal @@ -0,0 +1,75 @@ +#!/usr/bin/env kal + +# This demo executes GET requests in parallel and in series +# using `for` loops and `wait for` statements. + +# Notice how the serial GET requests always return in order +# and take longer in total. Parallel requests come back in +# order of receipt. + +http = require 'http' + +urls = ['http://www.google.com' + 'http://www.apple.com' + 'http://www.microsoft.com' + 'http://www.nodejs.org' + 'http://www.yahoo.com'] + +# This function does a GET request for each URL in series +# It will wait for a response from each request before moving on +# to the next request. Notice the output will be in the same order as the +# urls variable every time regardless of response time. +# It is a task rather than a function because it is called asynchronously +# This allows us to use `return` to implicitly call back +task series_demo() + # The `series` keyword is optional here (for loops are serial by default) + total_time = 0 + + for series url in urls + timer = new Date + + # we use the `safe` keyword because get is a "nonstandard" task + # that does not call back with an error argument + safe wait for response from http.get url + + delay = new Date() - timer + total_time += delay + + print "GET #{url} - #{response.statusCode} - #{response.connection.bytesRead} bytes - #{delay} ms" + + # because we are in a task rather than a function, this actually exectutes a callback + return total_time + +# This function does a GET request for each URL in parallel +# It will NOT wait for a response from each request before moving on +# to the next request. Notice the output will be determined by the order in which +# the requests complete! +task parallel_demo() + total_time = 0 + + # The `parallel` keyword is only meaningful here because the loop contains + # a `wait for` statement (meaning callbacks are used) + for parallel url in urls + timer = new Date + + # we use the `safe` keyword because get is a "nonstandard" task + # that does not call back with an error argument + safe wait for response from http.get url + + delay = new Date() - timer + total_time += delay + + print "GET #{url} - #{response.statusCode} - #{response.connection.bytesRead} bytes - #{delay}ms" + + # because we are in a task rather than a function, this actually exectutes a callback + return total_time + +print 'Series Requests...' +wait for time1 from series_demo() +print "Total duration #{time1}ms" + +print '' + +print 'Parallel Requests...' +wait for time2 from parallel_demo() +print "Total duration #{time2}ms" diff --git a/tests/examplefiles/example.kt b/tests/examplefiles/example.kt new file mode 100644 index 00000000..59291333 --- /dev/null +++ b/tests/examplefiles/example.kt @@ -0,0 +1,47 @@ +package addressbook + +class Contact( + val name : String, + val emails : List<EmailAddress>, + val addresses : List<PostalAddress>, + val phonenums : List<PhoneNumber> +) + +class EmailAddress( + val user : String, + val host : String +) + +class PostalAddress( + val streetAddress : String, + val city : String, + val zip : String, + val state : USState?, + val country : Country +) { + assert {(state == null) xor (country == Countries["US"]) } +} + +class PhoneNumber( + val country : Country, + val areaCode : Int, + val number : Long +) + +object Countries { + fun get(id : CountryID) : Country = countryTable[id] + + private var table : Map<String, Country>? = null + private val countryTable : Map<String, Country> + get() { + if (table == null) { + table = HashMap() + for (line in TextFile("countries.txt").lines(stripWhiteSpace = true)) { + table[line] = Country(line) + } + } + return table + } +} + +class Country(val name : String)
\ No newline at end of file diff --git a/tests/examplefiles/example.lagda b/tests/examplefiles/example.lagda new file mode 100644 index 00000000..b5476fa0 --- /dev/null +++ b/tests/examplefiles/example.lagda @@ -0,0 +1,19 @@ +\documentclass{article} +% this is a LaTeX comment +\usepackage{agda} + +\begin{document} + +Here's how you can define \emph{RGB} colors in Agda: + +\begin{code} +module example where + +open import Data.Fin +open import Data.Nat + +data Color : Set where + RGB : Fin 256 → Fin 256 → Fin 256 → Color +\end{code} + +\end{document}
\ No newline at end of file diff --git a/tests/examplefiles/example.ma b/tests/examplefiles/example.ma new file mode 100644 index 00000000..a8119ea5 --- /dev/null +++ b/tests/examplefiles/example.ma @@ -0,0 +1,8 @@ +1 + 1 (* This is a comment *) +Global` +SomeNamespace`Foo +f[x_, y__, 3, z___] := tsneirsnteintie "fosrt" neisnrteiasrn +E + 3 +Plus[1,Times[2,3]] +Map[#1 + #2&, SomePairList] +Plus[1.,-1,-1.,-1.0,]
\ No newline at end of file diff --git a/tests/examplefiles/example.monkey b/tests/examplefiles/example.monkey new file mode 100644 index 00000000..facd3a73 --- /dev/null +++ b/tests/examplefiles/example.monkey @@ -0,0 +1,152 @@ +Strict + +' single line comment + +#rem +multi +line +comment +#end + +#rem +nested +#rem +multi +line +#end +comment +#end + +Import mojo + +Const ONECONST:Int = 1 +Const TWOCONST := 2 +Const THREECONST := 3, FOURCONST:Int = 4 + +Global someVariable:Int = 4 + +' sample class from the documentation +Class Game Extends App + + Function New() + End + + Function DrawSpiral(clock) + Local w=DeviceWidth/2 + For Local i#=0 Until w*1.5 Step .2 + Local x#,y# + x=w+i*Sin(i*3+clock) + y=w+i*Cos(i*2+clock) + DrawRect x,y,1,1 + Next + hitbox.Collide(event.pos) + End + + Field updateCount + + Method OnCreate() + Print "spiral" + + SetUpdateRate 60 + End + + Method OnUpdate() + updateCount+=1 + End + + Method OnRender() + Cls + DrawSpiral updateCount + DrawSpiral updateCount*1.1 + End + +End + +Class Enemy + Method Die () Abstract +End + +' extending +Class Hoodlum Extends Enemy + ' field + Field testField:Bool = True + + ' naming class with modulepath + Local currentNode:list.Node<Vector2D> + + Method Die () + Print "B'oss, he-- he killed me, b'oss!" + End +End + +' extending with generics +Class VectorNode Extends Node<Vector2D> +End + +' interfaces +Interface Computer + Method Boot () + Method Process () + Method Display () +End + +Class PC Implements Computer +End + +' array syntax +Global listOfStuff:String[42] +Global lessStuff:String[5] = listOfStuff[4..8] +Global oneStuff:String = listOfStuff[23] + +'a comma separated sequence +Global scores:Int[]=[10,20,30] +'a comma separated sequence +Global text:String[]=["Hello","There","World"] +Global worstCase:worst.List<String[]> + +' string type +Global string1:String = "Hello world" +Global string2$ = "Hello world" + +' escape characers in strings +Global string3 := "Hello~zWorld" +Global string4 := "~qHello World~q" +Global string5 := "~tIndented~n" +Global string6 := "tilda is wavey... ~~" + +' string pseudofunctions +Print " Hello World ~n".Trim() ' prints "Hello World" +Print "Hello World".ToUpper() ' prints "HELLO WORLD" + +' Boolean shorttype +Global boolVariable1:Bool = True +Global boolVariable2? = False + +' number formats +Global hexNum1:Int = $3d0dead +Global hexNum2% = $CAFEBABE + +Global floatNum1:Float = 3.141516 +Global floatNum2# = 3.141516 +Global floatNum3 := .141516 + +' preprocessor keywords +#If TARGET = "android" +DoStuff() +#ElseIf TARGET = "ios" +DoOtherStuff() +#End + +' preprocessor variable +#SOMETHING = True +#Print SOMETHING +#If SOMETHING +#End + +' operators +Global a = 32 +Global b = 32 ~ 0 +b ~= 16 +b |= 16 +b &= 16 +Global c = a | b diff --git a/tests/examplefiles/example.moon b/tests/examplefiles/example.moon new file mode 100644 index 00000000..d4415e32 --- /dev/null +++ b/tests/examplefiles/example.moon @@ -0,0 +1,629 @@ +-- transform.moon +-- Leaf Corcoran (leafot@gmail.com) 2011 +-- +-- This is part of the MoonScript compiler. See <http://moonscript.org> +-- MoonScript is licensed under the MIT License +-- + +module "moonscript.transform", package.seeall + +types = require "moonscript.types" +util = require "moonscript.util" +data = require "moonscript.data" + +import reversed from util +import ntype, build, smart_node, is_slice from types +import insert from table + +export Statement, Value, NameProxy, LocalName, Run + +-- always declares as local +class LocalName + new: (@name) => self[1] = "temp_name" + get_name: => @name + +class NameProxy + new: (@prefix) => + self[1] = "temp_name" + + get_name: (scope) => + if not @name + @name = scope\free_name @prefix, true + @name + + chain: (...) => + items = {...} -- todo: fix ... propagation + items = for i in *items + if type(i) == "string" + {"dot", i} + else + i + + build.chain { + base: self + unpack items + } + + index: (key) => + build.chain { + base: self, {"index", key} + } + + __tostring: => + if @name + ("name<%s>")\format @name + else + ("name<prefix(%s)>")\format @prefix + +class Run + new: (@fn) => + self[1] = "run" + + call: (state) => + self.fn state + +-- transform the last stm is a list of stms +-- will puke on group +apply_to_last = (stms, fn) -> + -- find last (real) exp + last_exp_id = 0 + for i = #stms, 1, -1 + stm = stms[i] + if stm and util.moon.type(stm) != Run + last_exp_id = i + break + + return for i, stm in ipairs stms + if i == last_exp_id + fn stm + else + stm + +-- is a body a sindle expression/statement +is_singular = (body) -> + return false if #body != 1 + if "group" == ntype body + is_singular body[2] + else + true + +constructor_name = "new" + +class Transformer + new: (@transformers, @scope) => + @seen_nodes = {} + + transform: (scope, node, ...) => + -- print scope, node, ... + return node if @seen_nodes[node] + @seen_nodes[node] = true + while true + transformer = @transformers[ntype node] + res = if transformer + transformer(scope, node, ...) or node + else + node + return node if res == node + node = res + + __call: (node, ...) => + @transform @scope, node, ... + + instance: (scope) => + Transformer @transformers, scope + + can_transform: (node) => + @transformers[ntype node] != nil + +construct_comprehension = (inner, clauses) -> + current_stms = inner + for _, clause in reversed clauses + t = clause[1] + current_stms = if t == "for" + _, names, iter = unpack clause + {"foreach", names, iter, current_stms} + elseif t == "when" + _, cond = unpack clause + {"if", cond, current_stms} + else + error "Unknown comprehension clause: "..t + current_stms = {current_stms} + + current_stms[1] + +Statement = Transformer { + assign: (node) => + _, names, values = unpack node + -- bubble cascading assigns + if #values == 1 and types.cascading[ntype values[1]] + values[1] = @transform.statement values[1], (stm) -> + t = ntype stm + if types.is_value stm + {"assign", names, {stm}} + else + stm + + build.group { + {"declare", names} + values[1] + } + else + node + + export: (node) => + -- assign values if they are included + if #node > 2 + if node[2] == "class" + cls = smart_node node[3] + build.group { + {"export", {cls.name}} + cls + } + else + build.group { + node + build.assign { + names: node[2] + values: node[3] + } + } + else + nil + + update: (node) => + _, name, op, exp = unpack node + op_final = op\match "^(.+)=$" + error "Unknown op: "..op if not op_final + build.assign_one name, {"exp", name, op_final, exp} + + import: (node) => + _, names, source = unpack node + + stubs = for name in *names + if type(name) == "table" + name + else + {"dot", name} + + real_names = for name in *names + type(name) == "table" and name[2] or name + + if type(source) == "string" + build.assign { + names: real_names + values: [build.chain { base: source, stub} for stub in *stubs] + } + else + source_name = NameProxy "table" + build.group { + {"declare", real_names} + build["do"] { + build.assign_one source_name, source + build.assign { + names: real_names + values: [build.chain { base: source_name, stub} for stub in *stubs] + } + } + } + + comprehension: (node, action) => + _, exp, clauses = unpack node + + action = action or (exp) -> {exp} + construct_comprehension action(exp), clauses + + -- handle cascading return decorator + if: (node, ret) => + if ret + smart_node node + -- mutate all the bodies + node['then'] = apply_to_last node['then'], ret + for i = 4, #node + case = node[i] + body_idx = #node[i] + case[body_idx] = apply_to_last case[body_idx], ret + node + + with: (node, ret) => + _, exp, block = unpack node + scope_name = NameProxy "with" + build["do"] { + build.assign_one scope_name, exp + Run => @set "scope_var", scope_name + build.group block + if ret + ret scope_name + } + + foreach: (node) => + smart_node node + if ntype(node.iter) == "unpack" + list = node.iter[2] + + index_name = NameProxy "index" + list_name = NameProxy "list" + + slice_var = nil + bounds = if is_slice list + slice = list[#list] + table.remove list + table.remove slice, 1 + + slice[2] = if slice[2] and slice[2] != "" + max_tmp_name = NameProxy "max" + slice_var = build.assign_one max_tmp_name, slice[2] + {"exp", max_tmp_name, "<", 0 + "and", {"length", list_name}, "+", max_tmp_name + "or", max_tmp_name } + else + {"length", list_name} + + slice + else + {1, {"length", list_name}} + + build.group { + build.assign_one list_name, list + slice_var + build["for"] { + name: index_name + bounds: bounds + body: { + {"assign", node.names, {list_name\index index_name}} + build.group node.body + } + } + } + + switch: (node, ret) => + _, exp, conds = unpack node + exp_name = NameProxy "exp" + + -- convert switch conds into if statment conds + convert_cond = (cond) -> + t, case_exp, body = unpack cond + out = {} + insert out, t == "case" and "elseif" or "else" + if t != "else" + insert out, {"exp", case_exp, "==", exp_name} if t != "else" + else + body = case_exp + + if ret + body = apply_to_last body, ret + + insert out, body + + out + + first = true + if_stm = {"if"} + for cond in *conds + if_cond = convert_cond cond + if first + first = false + insert if_stm, if_cond[2] + insert if_stm, if_cond[3] + else + insert if_stm, if_cond + + build.group { + build.assign_one exp_name, exp + if_stm + } + + class: (node) => + _, name, parent_val, body = unpack node + + -- split apart properties and statements + statements = {} + properties = {} + for item in *body + switch item[1] + when "stm" + insert statements, item[2] + when "props" + for tuple in *item[2,] + insert properties, tuple + + -- find constructor + constructor = nil + properties = for tuple in *properties + if tuple[1] == constructor_name + constructor = tuple[2] + nil + else + tuple + + parent_cls_name = NameProxy "parent" + base_name = NameProxy "base" + self_name = NameProxy "self" + cls_name = NameProxy "class" + + if not constructor + constructor = build.fndef { + args: {{"..."}} + arrow: "fat" + body: { + build["if"] { + cond: parent_cls_name + then: { + build.chain { base: "super", {"call", {"..."}} } + } + } + } + } + else + smart_node constructor + constructor.arrow = "fat" + + cls = build.table { + {"__init", constructor} + {"__base", base_name} + {"__name", {"string", '"', name}} -- "quote the string" + {"__parent", parent_cls_name} + } + + -- look up a name in the class object + class_lookup = build["if"] { + cond: {"exp", "val", "==", "nil", "and", parent_cls_name} + then: { + parent_cls_name\index"name" + } + } + insert class_lookup, {"else", {"val"}} + + cls_mt = build.table { + {"__index", build.fndef { + args: {{"cls"}, {"name"}} + body: { + build.assign_one LocalName"val", build.chain { + base: "rawget", {"call", {base_name, "name"}} + } + class_lookup + } + }} + {"__call", build.fndef { + args: {{"cls"}, {"..."}} + body: { + build.assign_one self_name, build.chain { + base: "setmetatable" + {"call", {"{}", base_name}} + } + build.chain { + base: "cls.__init" + {"call", {self_name, "..."}} + } + self_name + } + }} + } + + cls = build.chain { + base: "setmetatable" + {"call", {cls, cls_mt}} + } + + value = nil + with build + value = .block_exp { + Run => + @set "super", (block, chain) -> + if chain + slice = [item for item in *chain[3,]] + new_chain = {"chain", parent_cls_name} + + head = slice[1] + + if head == nil + return parent_cls_name + + switch head[1] + -- calling super, inject calling name and self into chain + when "call" + calling_name = block\get"current_block" + slice[1] = {"call", {"self", unpack head[2]}} + act = if ntype(calling_name) != "value" then "index" else "dot" + insert new_chain, {act, calling_name} + + -- colon call on super, replace class with self as first arg + when "colon" + call = head[3] + insert new_chain, {"dot", head[2]} + slice[1] = { "call", { "self", unpack call[2] } } + + insert new_chain, item for item in *slice + + new_chain + else + parent_cls_name + + .assign_one parent_cls_name, parent_val == "" and "nil" or parent_val + .assign_one base_name, {"table", properties} + .assign_one base_name\chain"__index", base_name + + build["if"] { + cond: parent_cls_name + then: { + .chain { + base: "setmetatable" + {"call", { + base_name, + .chain { base: parent_cls_name, {"dot", "__base"}} + }} + } + } + } + + .assign_one cls_name, cls + .assign_one base_name\chain"__class", cls_name + + .group if #statements > 0 { + .assign_one LocalName"self", cls_name + .group statements + } else {} + + cls_name + } + + value = .group { + .declare names: {name} + .assign { + names: {name} + values: {value} + } + } + + value +} + +class Accumulator + body_idx: { for: 4, while: 3, foreach: 4 } + + new: => + @accum_name = NameProxy "accum" + @value_name = NameProxy "value" + @len_name = NameProxy "len" + + -- wraps node and mutates body + convert: (node) => + index = @body_idx[ntype node] + node[index] = @mutate_body node[index] + @wrap node + + -- wrap the node into a block_exp + wrap: (node) => + build.block_exp { + build.assign_one @accum_name, build.table! + build.assign_one @len_name, 0 + node + @accum_name + } + + -- mutates the body of a loop construct to save last value into accumulator + -- can optionally skip nil results + mutate_body: (body, skip_nil=true) => + val = if not skip_nil and is_singular body + with body[1] + body = {} + else + body = apply_to_last body, (n) -> + build.assign_one @value_name, n + @value_name + + update = { + {"update", @len_name, "+=", 1} + build.assign_one @accum_name\index(@len_name), val + } + + if skip_nil + table.insert body, build["if"] { + cond: {"exp", @value_name, "!=", "nil"} + then: update + } + else + table.insert body, build.group update + + body + +default_accumulator = (node) => + Accumulator!\convert node + + +implicitly_return = (scope) -> + fn = (stm) -> + t = ntype stm + if types.manual_return[t] or not types.is_value stm + stm + elseif types.cascading[t] + scope.transform.statement stm, fn + else + if t == "comprehension" and not types.comprehension_has_value stm + stm + else + {"return", stm} + + fn + +Value = Transformer { + for: default_accumulator + while: default_accumulator + foreach: default_accumulator + + comprehension: (node) => + a = Accumulator! + node = @transform.statement node, (exp) -> + a\mutate_body {exp}, false + a\wrap node + + tblcomprehension: (node) => + _, key_exp, value_exp, clauses = unpack node + + accum = NameProxy "tbl" + dest = build.chain { base: accum, {"index", key_exp} } + inner = build.assign_one dest, value_exp + + build.block_exp { + build.assign_one accum, build.table! + construct_comprehension {inner}, clauses + accum + } + + fndef: (node) => + smart_node node + node.body = apply_to_last node.body, implicitly_return self + node + + if: (node) => build.block_exp { node } + with: (node) => build.block_exp { node } + switch: (node) => + build.block_exp { node } + + -- pull out colon chain + chain: (node) => + stub = node[#node] + if type(stub) == "table" and stub[1] == "colon_stub" + table.remove node, #node + + base_name = NameProxy "base" + fn_name = NameProxy "fn" + + is_super = node[2] == "super" + @transform.value build.block_exp { + build.assign { + names: {base_name} + values: {node} + } + + build.assign { + names: {fn_name} + values: { + build.chain { base: base_name, {"dot", stub[2]} } + } + } + + build.fndef { + args: {{"..."}} + body: { + build.chain { + base: fn_name, {"call", {is_super and "self" or base_name, "..."}} + } + } + } + } + + block_exp: (node) => + _, body = unpack node + + fn = nil + arg_list = {} + + insert body, Run => + if @has_varargs + insert arg_list, "..." + insert fn.args, {"..."} + + fn = smart_node build.fndef body: body + build.chain { base: {"parens", fn}, {"call", arg_list} } +} + diff --git a/tests/examplefiles/example.mq4 b/tests/examplefiles/example.mq4 new file mode 100644 index 00000000..54a5fa60 --- /dev/null +++ b/tests/examplefiles/example.mq4 @@ -0,0 +1,187 @@ +//+------------------------------------------------------------------+
+//| PeriodConverter.mq4 |
+//| Copyright 2006-2014, MetaQuotes Software Corp. |
+//| http://www.metaquotes.net |
+//+------------------------------------------------------------------+
+#property copyright "2006-2014, MetaQuotes Software Corp."
+#property link "http://www.mql4.com"
+#property description "Period Converter to updated format of history base"
+#property strict
+#property show_inputs
+#include <WinUser32.mqh>
+
+input int InpPeriodMultiplier=3; // Period multiplier factor
+int ExtHandle=-1;
+//+------------------------------------------------------------------+
+//| script program start function |
+//+------------------------------------------------------------------+
+void OnStart()
+ {
+ datetime time0;
+ ulong last_fpos=0;
+ long last_volume=0;
+ int i,start_pos,periodseconds;
+ int hwnd=0,cnt=0;
+//---- History header
+ int file_version=401;
+ string c_copyright;
+ string c_symbol=Symbol();
+ int i_period=Period()*InpPeriodMultiplier;
+ int i_digits=Digits;
+ int i_unused[13];
+ MqlRates rate;
+//---
+ ExtHandle=FileOpenHistory(c_symbol+(string)i_period+".hst",FILE_BIN|FILE_WRITE|FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_ANSI);
+ if(ExtHandle<0)
+ return;
+ c_copyright="(C)opyright 2003, MetaQuotes Software Corp.";
+ ArrayInitialize(i_unused,0);
+//--- write history file header
+ FileWriteInteger(ExtHandle,file_version,LONG_VALUE);
+ FileWriteString(ExtHandle,c_copyright,64);
+ FileWriteString(ExtHandle,c_symbol,12);
+ FileWriteInteger(ExtHandle,i_period,LONG_VALUE);
+ FileWriteInteger(ExtHandle,i_digits,LONG_VALUE);
+ FileWriteInteger(ExtHandle,0,LONG_VALUE);
+ FileWriteInteger(ExtHandle,0,LONG_VALUE);
+ FileWriteArray(ExtHandle,i_unused,0,13);
+//--- write history file
+ periodseconds=i_period*60;
+ start_pos=Bars-1;
+ rate.open=Open[start_pos];
+ rate.low=Low[start_pos];
+ rate.high=High[start_pos];
+ rate.tick_volume=(long)Volume[start_pos];
+ rate.spread=0;
+ rate.real_volume=0;
+ //--- normalize open time
+ rate.time=Time[start_pos]/periodseconds;
+ rate.time*=periodseconds;
+ for(i=start_pos-1; i>=0; i--)
+ {
+ if(IsStopped())
+ break;
+ time0=Time[i];
+ //--- history may be updated
+ if(i==0)
+ {
+ //--- modify index if history was updated
+ if(RefreshRates())
+ i=iBarShift(NULL,0,time0);
+ }
+ //---
+ if(time0>=rate.time+periodseconds || i==0)
+ {
+ if(i==0 && time0<rate.time+periodseconds)
+ {
+ rate.tick_volume+=(long)Volume[0];
+ if(rate.low>Low[0])
+ rate.low=Low[0];
+ if(rate.high<High[0])
+ rate.high=High[0];
+ rate.close=Close[0];
+ }
+ last_fpos=FileTell(ExtHandle);
+ last_volume=(long)Volume[i];
+ FileWriteStruct(ExtHandle,rate);
+ cnt++;
+ if(time0>=rate.time+periodseconds)
+ {
+ rate.time=time0/periodseconds;
+ rate.time*=periodseconds;
+ rate.open=Open[i];
+ rate.low=Low[i];
+ rate.high=High[i];
+ rate.close=Close[i];
+ rate.tick_volume=last_volume;
+ }
+ }
+ else
+ {
+ rate.tick_volume+=(long)Volume[i];
+ if(rate.low>Low[i])
+ rate.low=Low[i];
+ if(rate.high<High[i])
+ rate.high=High[i];
+ rate.close=Close[i];
+ }
+ }
+ FileFlush(ExtHandle);
+ Print(cnt," record(s) written");
+//--- collect incoming ticks
+ datetime last_time=LocalTime()-5;
+ while(!IsStopped())
+ {
+ datetime cur_time=LocalTime();
+ //--- check for new rates
+ if(RefreshRates())
+ {
+ time0=Time[0];
+ FileSeek(ExtHandle,last_fpos,SEEK_SET);
+ //--- is there current bar?
+ if(time0<rate.time+periodseconds)
+ {
+ rate.tick_volume+=(long)Volume[0]-last_volume;
+ last_volume=(long)Volume[0];
+ if(rate.low>Low[0])
+ rate.low=Low[0];
+ if(rate.high<High[0])
+ rate.high=High[0];
+ rate.close=Close[0];
+ }
+ else
+ {
+ //--- no, there is new bar
+ rate.tick_volume+=(long)Volume[1]-last_volume;
+ if(rate.low>Low[1])
+ rate.low=Low[1];
+ if(rate.high<High[1])
+ rate.high=High[1];
+ //--- write previous bar remains
+ FileWriteStruct(ExtHandle,rate);
+ last_fpos=FileTell(ExtHandle);
+ //----
+ rate.time=time0/periodseconds;
+ rate.time*=periodseconds;
+ rate.open=Open[0];
+ rate.low=Low[0];
+ rate.high=High[0];
+ rate.close=Close[0];
+ rate.tick_volume=(long)Volume[0];
+ last_volume=rate.tick_volume;
+ }
+ //----
+ FileWriteStruct(ExtHandle,rate);
+ FileFlush(ExtHandle);
+ //---
+ if(hwnd==0)
+ {
+ hwnd=WindowHandle(Symbol(),i_period);
+ if(hwnd!=0)
+ Print("Chart window detected");
+ }
+ //--- refresh window not frequently than 1 time in 2 seconds
+ if(hwnd!=0 && cur_time-last_time>=2)
+ {
+ PostMessageA(hwnd,WM_COMMAND,33324,0);
+ last_time=cur_time;
+ }
+ }
+ Sleep(50);
+ }
+//---
+ }
+//+------------------------------------------------------------------+
+//| |
+//+------------------------------------------------------------------+
+void OnDeinit(const int reason)
+ {
+//---
+ if(ExtHandle>=0)
+ {
+ FileClose(ExtHandle);
+ ExtHandle=-1;
+ }
+//---
+ }
+//+------------------------------------------------------------------+
\ No newline at end of file diff --git a/tests/examplefiles/example.mqh b/tests/examplefiles/example.mqh new file mode 100644 index 00000000..ee80ed52 --- /dev/null +++ b/tests/examplefiles/example.mqh @@ -0,0 +1,123 @@ +//+------------------------------------------------------------------+
+//| Array.mqh |
+//| Copyright 2009-2013, MetaQuotes Software Corp. |
+//| http://www.mql4.com |
+//+------------------------------------------------------------------+
+#include <Object.mqh>
+//+------------------------------------------------------------------+
+//| Class CArray |
+//| Purpose: Base class of dynamic arrays. |
+//| Derives from class CObject. |
+//+------------------------------------------------------------------+
+class CArray : public CObject
+ {
+protected:
+ int m_step_resize; // increment size of the array
+ int m_data_total; // number of elements
+ int m_data_max; // maximmum size of the array without memory reallocation
+ int m_sort_mode; // mode of array sorting
+
+public:
+ CArray(void);
+ ~CArray(void);
+ //--- methods of access to protected data
+ int Step(void) const { return(m_step_resize); }
+ bool Step(const int step);
+ int Total(void) const { return(m_data_total); }
+ int Available(void) const { return(m_data_max-m_data_total); }
+ int Max(void) const { return(m_data_max); }
+ bool IsSorted(const int mode=0) const { return(m_sort_mode==mode); }
+ int SortMode(void) const { return(m_sort_mode); }
+ //--- cleaning method
+ void Clear(void) { m_data_total=0; }
+ //--- methods for working with files
+ virtual bool Save(const int file_handle);
+ virtual bool Load(const int file_handle);
+ //--- sorting method
+ void Sort(const int mode=0);
+
+protected:
+ virtual void QuickSort(int beg,int end,const int mode=0) { }
+ };
+//+------------------------------------------------------------------+
+//| Constructor |
+//+------------------------------------------------------------------+
+CArray::CArray(void) : m_step_resize(16),
+ m_data_total(0),
+ m_data_max(0),
+ m_sort_mode(-1)
+ {
+ }
+//+------------------------------------------------------------------+
+//| Destructor |
+//+------------------------------------------------------------------+
+CArray::~CArray(void)
+ {
+ }
+//+------------------------------------------------------------------+
+//| Method Set for variable m_step_resize |
+//+------------------------------------------------------------------+
+bool CArray::Step(const int step)
+ {
+//--- check
+ if(step>0)
+ {
+ m_step_resize=step;
+ return(true);
+ }
+//--- failure
+ return(false);
+ }
+//+------------------------------------------------------------------+
+//| Sorting an array in ascending order |
+//+------------------------------------------------------------------+
+void CArray::Sort(const int mode)
+ {
+//--- check
+ if(IsSorted(mode))
+ return;
+ m_sort_mode=mode;
+ if(m_data_total<=1)
+ return;
+//--- sort
+ QuickSort(0,m_data_total-1,mode);
+ }
+//+------------------------------------------------------------------+
+//| Writing header of array to file |
+//+------------------------------------------------------------------+
+bool CArray::Save(const int file_handle)
+ {
+//--- check handle
+ if(file_handle!=INVALID_HANDLE)
+ {
+ //--- write start marker - 0xFFFFFFFFFFFFFFFF
+ if(FileWriteLong(file_handle,-1)==sizeof(long))
+ {
+ //--- write array type
+ if(FileWriteInteger(file_handle,Type(),INT_VALUE)==INT_VALUE)
+ return(true);
+ }
+ }
+//--- failure
+ return(false);
+ }
+//+------------------------------------------------------------------+
+//| Reading header of array from file |
+//+------------------------------------------------------------------+
+bool CArray::Load(const int file_handle)
+ {
+//--- check handle
+ if(file_handle!=INVALID_HANDLE)
+ {
+ //--- read and check start marker - 0xFFFFFFFFFFFFFFFF
+ if(FileReadLong(file_handle)==-1)
+ {
+ //--- read and check array type
+ if(FileReadInteger(file_handle,INT_VALUE)==Type())
+ return(true);
+ }
+ }
+//--- failure
+ return(false);
+ }
+//+------------------------------------------------------------------+
diff --git a/tests/examplefiles/example.msc b/tests/examplefiles/example.msc new file mode 100644 index 00000000..d51b32a6 --- /dev/null +++ b/tests/examplefiles/example.msc @@ -0,0 +1,43 @@ +msc { + hscale=5; + + //test comment + + a,b,c,d; + +/* another +comment +goes here */ /* too */ // now + + ... [label="test1", id="1"]; + --- [label="test2", id="2"]; + ||| [label="test3", id="2"]; + a ABOX b; + a--b [label="test4", id="2"]; + a == b [label="test5", id="2"]; + a .. b [label="test6", id="2"]; + a::b [label="test7", id="2"]; + a<<=>> b [label="test8", id="2"], + b <->c [label="test9", id="2"], + b RBOX c; + a BOX d; + a<=> b [label="test10", id="2"]; + a <<>> b [label="test11", id="2"]; + a<:>b [label="test12", id="2"]; + a->b [label="test13", id="2"]; + a =>> b [label="test14", id="2"], + b >> c [label="test15", id="2"], + a=> b [label="test16", id="2"]; + a :>b [label="test17", id="2"]; + a-x b [label="test18", id="2"]; + a -Xb [label="test19", id="2"]; + a<- b [label="test20", id="2"]; + a <<=b [label="test21", id="2"]; + a<< b [label="test22", id="2"]; + a <= b [label="test23", id="2"]; + a<: b [label="test24", id="2"]; + a -xb [label="test25", id="2"]; + a-X b [ label="test26",id="2" ]; + a->* [label="test27" , id="2"]; + *<-b [label="test28",id="28"]; +} diff --git a/tests/examplefiles/example.ni b/tests/examplefiles/example.ni new file mode 100644 index 00000000..32279e80 --- /dev/null +++ b/tests/examplefiles/example.ni @@ -0,0 +1,57 @@ + | | |
+"Informal by Nature"
+[ * * * ]
+by
+[ * * * ]
+David Corbett
+
+[This is a [nested] comment.]
+
+Section 1 - Use option translation
+
+Use maximum tests of at least 100 translates as (-
+@c
+Constant MAX_TESTS = {N}; —). | Section 2
+
+A room has a number called size.
+
+The Kitchen is a room. "A nondescript kitchen.“ The Kitchen has size 2.
+
+When play begins:
+ say "Testing:[line break]";
+ test 0.
+
+To test (N — number): (—
+ if (Test({N}) == (+size of the Kitchen [this should succeed]+)) {-open—brace}
+ print ”Success.^”;
+ {-close-brace} else {
+ print “Failure.^";
+ }
+]; ! You shouldn't end a routine within a phrase definition, but it works.
+[ Unused;
+ #Include "\
+@p \
+"; ! At signs hold no power here.
+! Of course, the file "@p .h" must exist.
+-).
+
+Include (-!% This is not ICL.
+
+[ Test x;
+ if (x) {x++;}
+ {–! Single line comment.}
+@inc x;
+@p At signs.
+...
+@Purpose: ...
+...
+@-...
+@c ...
+@inc x;
+@c
+@c
+ return x;
+];
+@Purpose: ...
+@-------------------------------------------------------------------------------
+-).
diff --git a/tests/examplefiles/example.nim b/tests/examplefiles/example.nim new file mode 100644 index 00000000..319da016 --- /dev/null +++ b/tests/examplefiles/example.nim @@ -0,0 +1,1010 @@ +import glib2, gtk2, gdk2, gtksourceview, dialogs, os, pango, osproc, strutils +import pegs, streams +import settings, types, cfg, search + +{.push callConv:cdecl.} + +const + NimrodProjectExt = ".nimprj" + +var win: types.MainWin +win.Tabs = @[] + +search.win = addr(win) + +var lastSession: seq[string] = @[] + +var confParseFail = False # This gets set to true + # When there is an error parsing the config + +# Load the settings +try: + win.settings = cfg.load(lastSession) +except ECFGParse: + # TODO: Make the dialog show the exception + confParseFail = True + win.settings = cfg.defaultSettings() +except EIO: + win.settings = cfg.defaultSettings() + +proc getProjectTab(): int = + for i in 0..high(win.tabs): + if win.tabs[i].filename.endswith(NimrodProjectExt): return i + +proc saveTab(tabNr: int, startpath: string) = + if tabNr < 0: return + if win.Tabs[tabNr].saved: return + var path = "" + if win.Tabs[tabNr].filename == "": + path = ChooseFileToSave(win.w, startpath) + # dialogs.nim STOCK_OPEN instead of STOCK_SAVE + else: + path = win.Tabs[tabNr].filename + + if path != "": + var buffer = PTextBuffer(win.Tabs[tabNr].buffer) + # Get the text from the TextView + var startIter: TTextIter + buffer.getStartIter(addr(startIter)) + + var endIter: TTextIter + buffer.getEndIter(addr(endIter)) + + var text = buffer.getText(addr(startIter), addr(endIter), False) + # Save it to a file + var f: TFile + if open(f, path, fmWrite): + f.write(text) + f.close() + + win.tempStuff.lastSaveDir = splitFile(path).dir + + # Change the tab name and .Tabs.filename etc. + win.Tabs[tabNr].filename = path + win.Tabs[tabNr].saved = True + var name = extractFilename(path) + + var cTab = win.Tabs[tabNr] + cTab.label.setText(name) + else: + error(win.w, "Unable to write to file") + +proc saveAllTabs() = + for i in 0..high(win.tabs): + saveTab(i, os.splitFile(win.tabs[i].filename).dir) + +# GTK Events +# -- w(PWindow) +proc destroy(widget: PWidget, data: pgpointer) {.cdecl.} = + # gather some settings + win.settings.VPanedPos = PPaned(win.sourceViewTabs.getParent()).getPosition() + win.settings.winWidth = win.w.allocation.width + win.settings.winHeight = win.w.allocation.height + + # save the settings + win.save() + # then quit + main_quit() + +proc delete_event(widget: PWidget, event: PEvent, user_data: pgpointer): bool = + var quit = True + for i in low(win.Tabs)..len(win.Tabs)-1: + if not win.Tabs[i].saved: + var askSave = dialogNewWithButtons("", win.w, 0, + STOCK_SAVE, RESPONSE_ACCEPT, STOCK_CANCEL, + RESPONSE_CANCEL, + "Close without saving", RESPONSE_REJECT, nil) + askSave.setTransientFor(win.w) + # TODO: Make this dialog look better + var label = labelNew(win.Tabs[i].filename & + " is unsaved, would you like to save it ?") + PBox(askSave.vbox).pack_start(label, False, False, 0) + label.show() + + var resp = askSave.run() + gtk2.destroy(PWidget(askSave)) + case resp + of RESPONSE_ACCEPT: + saveTab(i, os.splitFile(win.tabs[i].filename).dir) + quit = True + of RESPONSE_CANCEL: + quit = False + break + of RESPONSE_REJECT: + quit = True + else: + quit = False + break + + # If False is returned the window will close + return not quit + +proc windowState_Changed(widget: PWidget, event: PEventWindowState, + user_data: pgpointer) = + win.settings.winMaximized = (event.newWindowState and + WINDOW_STATE_MAXIMIZED) != 0 + +# -- SourceView(PSourceView) & SourceBuffer +proc updateStatusBar(buffer: PTextBuffer){.cdecl.} = + # Incase this event gets fired before + # bottomBar is initialized + if win.bottomBar != nil and not win.tempStuff.stopSBUpdates: + var iter: TTextIter + + win.bottomBar.pop(0) + buffer.getIterAtMark(addr(iter), buffer.getInsert()) + var row = getLine(addr(iter)) + 1 + var col = getLineOffset(addr(iter)) + discard win.bottomBar.push(0, "Line: " & $row & " Column: " & $col) + +proc cursorMoved(buffer: PTextBuffer, location: PTextIter, + mark: PTextMark, user_data: pgpointer){.cdecl.} = + updateStatusBar(buffer) + +proc onCloseTab(btn: PButton, user_data: PWidget) = + if win.sourceViewTabs.getNPages() > 1: + var tab = win.sourceViewTabs.pageNum(user_data) + win.sourceViewTabs.removePage(tab) + + win.Tabs.delete(tab) + +proc onSwitchTab(notebook: PNotebook, page: PNotebookPage, pageNum: guint, + user_data: pgpointer) = + if win.Tabs.len()-1 >= pageNum: + win.w.setTitle("Aporia IDE - " & win.Tabs[pageNum].filename) + +proc createTabLabel(name: string, t_child: PWidget): tuple[box: PWidget, + label: PLabel] = + var box = hboxNew(False, 0) + var label = labelNew(name) + var closebtn = buttonNew() + closeBtn.setLabel(nil) + var iconSize = iconSizeFromName("tabIconSize") + if iconSize == 0: + iconSize = iconSizeRegister("tabIconSize", 10, 10) + var image = imageNewFromStock(STOCK_CLOSE, iconSize) + discard gSignalConnect(closebtn, "clicked", G_Callback(onCloseTab), t_child) + closebtn.setImage(image) + gtk2.setRelief(closebtn, RELIEF_NONE) + box.packStart(label, True, True, 0) + box.packEnd(closebtn, False, False, 0) + box.showAll() + return (box, label) + +proc changed(buffer: PTextBuffer, user_data: pgpointer) = + # Update the 'Line & Column' + #updateStatusBar(buffer) + + # Change the tabs state to 'unsaved' + # and add '*' to the Tab Name + var current = win.SourceViewTabs.getCurrentPage() + var name = "" + if win.Tabs[current].filename == "": + win.Tabs[current].saved = False + name = "Untitled *" + else: + win.Tabs[current].saved = False + name = extractFilename(win.Tabs[current].filename) & " *" + + var cTab = win.Tabs[current] + cTab.label.setText(name) + +# Other(Helper) functions + +proc initSourceView(SourceView: var PWidget, scrollWindow: var PScrolledWindow, + buffer: var PSourceBuffer) = + # This gets called by addTab + # Each tabs creates a new SourceView + # SourceScrolledWindow(ScrolledWindow) + scrollWindow = scrolledWindowNew(nil, nil) + scrollWindow.setPolicy(POLICY_AUTOMATIC, POLICY_AUTOMATIC) + scrollWindow.show() + + # SourceView(gtkSourceView) + SourceView = sourceViewNew(buffer) + PSourceView(SourceView).setInsertSpacesInsteadOfTabs(True) + PSourceView(SourceView).setIndentWidth(win.settings.indentWidth) + PSourceView(SourceView).setShowLineNumbers(win.settings.showLineNumbers) + PSourceView(SourceView).setHighlightCurrentLine( + win.settings.highlightCurrentLine) + PSourceView(SourceView).setShowRightMargin(win.settings.rightMargin) + PSourceView(SourceView).setAutoIndent(win.settings.autoIndent) + + var font = font_description_from_string(win.settings.font) + SourceView.modifyFont(font) + + scrollWindow.add(SourceView) + SourceView.show() + + buffer.setHighlightMatchingBrackets( + win.settings.highlightMatchingBrackets) + + # UGLY workaround for yet another compiler bug: + discard gsignalConnect(buffer, "mark-set", + GCallback(aporia.cursorMoved), nil) + discard gsignalConnect(buffer, "changed", GCallback(aporia.changed), nil) + + # -- Set the syntax highlighter scheme + buffer.setScheme(win.scheme) + +proc addTab(name, filename: string) = + ## Adds a tab, if filename is not "" reads the file. And sets + ## the tabs SourceViews text to that files contents. + assert(win.nimLang != nil) + var buffer: PSourceBuffer = sourceBufferNew(win.nimLang) + + if filename != nil and filename != "": + var lang = win.langMan.guessLanguage(filename, nil) + if lang != nil: + buffer.setLanguage(lang) + else: + buffer.setHighlightSyntax(False) + + var nam = name + if nam == "": nam = "Untitled" + if filename == "": nam.add(" *") + elif filename != "" and name == "": + # Disable the undo/redo manager. + buffer.begin_not_undoable_action() + + # Load the file. + var file: string = readFile(filename) + if file != nil: + buffer.set_text(file, len(file)) + + # Enable the undo/redo manager. + buffer.end_not_undoable_action() + + # Get the name.ext of the filename, for the tabs title + nam = extractFilename(filename) + + # Init the sourceview + var sourceView: PWidget + var scrollWindow: PScrolledWindow + initSourceView(sourceView, scrollWindow, buffer) + + var (TabLabel, labelText) = createTabLabel(nam, scrollWindow) + # Add a tab + discard win.SourceViewTabs.appendPage(scrollWindow, TabLabel) + + var nTab: Tab + nTab.buffer = buffer + nTab.sourceView = sourceView + nTab.label = labelText + nTab.saved = (filename != "") + nTab.filename = filename + win.Tabs.add(nTab) + + PTextView(SourceView).setBuffer(nTab.buffer) + +# GTK Events Contd. +# -- TopMenu & TopBar + +proc newFile(menuItem: PMenuItem, user_data: pgpointer) = + addTab("", "") + win.sourceViewTabs.setCurrentPage(win.Tabs.len()-1) + +proc openFile(menuItem: PMenuItem, user_data: pgpointer) = + var startpath = "" + var currPage = win.SourceViewTabs.getCurrentPage() + if currPage <% win.tabs.len: + startpath = os.splitFile(win.tabs[currPage].filename).dir + + if startpath.len == 0: + # Use lastSavePath as the startpath + startpath = win.tempStuff.lastSaveDir + if startpath.len == 0: + startpath = os.getHomeDir() + + var files = ChooseFilesToOpen(win.w, startpath) + if files.len() > 0: + for f in items(files): + try: + addTab("", f) + except EIO: + error(win.w, "Unable to read from file") + # Switch to the newly created tab + win.sourceViewTabs.setCurrentPage(win.Tabs.len()-1) + +proc saveFile_Activate(menuItem: PMenuItem, user_data: pgpointer) = + var current = win.SourceViewTabs.getCurrentPage() + saveTab(current, os.splitFile(win.tabs[current].filename).dir) + +proc saveFileAs_Activate(menuItem: PMenuItem, user_data: pgpointer) = + var current = win.SourceViewTabs.getCurrentPage() + var (filename, saved) = (win.Tabs[current].filename, win.Tabs[current].saved) + + win.Tabs[current].saved = False + win.Tabs[current].filename = "" + saveTab(current, os.splitFile(filename).dir) + # If the user cancels the save file dialog. Restore the previous filename + # and saved state + if win.Tabs[current].filename == "": + win.Tabs[current].filename = filename + win.Tabs[current].saved = saved + +proc undo(menuItem: PMenuItem, user_data: pgpointer) = + var current = win.SourceViewTabs.getCurrentPage() + if win.Tabs[current].buffer.canUndo(): + win.Tabs[current].buffer.undo() + +proc redo(menuItem: PMenuItem, user_data: pgpointer) = + var current = win.SourceViewTabs.getCurrentPage() + if win.Tabs[current].buffer.canRedo(): + win.Tabs[current].buffer.redo() + +proc find_Activate(menuItem: PMenuItem, user_data: pgpointer) = + # Get the selected text, and set the findEntry to it. + var currentTab = win.SourceViewTabs.getCurrentPage() + var insertIter: TTextIter + win.Tabs[currentTab].buffer.getIterAtMark(addr(insertIter), + win.Tabs[currentTab].buffer.getInsert()) + var insertOffset = addr(insertIter).getOffset() + + var selectIter: TTextIter + win.Tabs[currentTab].buffer.getIterAtMark(addr(selectIter), + win.Tabs[currentTab].buffer.getSelectionBound()) + var selectOffset = addr(selectIter).getOffset() + + if insertOffset != selectOffset: + var text = win.Tabs[currentTab].buffer.getText(addr(insertIter), + addr(selectIter), false) + win.findEntry.setText(text) + + win.findBar.show() + win.findEntry.grabFocus() + win.replaceEntry.hide() + win.replaceLabel.hide() + win.replaceBtn.hide() + win.replaceAllBtn.hide() + +proc replace_Activate(menuitem: PMenuItem, user_data: pgpointer) = + win.findBar.show() + win.findEntry.grabFocus() + win.replaceEntry.show() + win.replaceLabel.show() + win.replaceBtn.show() + win.replaceAllBtn.show() + +proc settings_Activate(menuitem: PMenuItem, user_data: pgpointer) = + settings.showSettings(win) + +proc viewBottomPanel_Toggled(menuitem: PCheckMenuItem, user_data: pgpointer) = + win.settings.bottomPanelVisible = menuitem.itemGetActive() + if win.settings.bottomPanelVisible: + win.bottomPanelTabs.show() + else: + win.bottomPanelTabs.hide() + +var + pegLineError = peg"{[^(]*} '(' {\d+} ', ' \d+ ') Error:' \s* {.*}" + pegLineWarning = peg"{[^(]*} '(' {\d+} ', ' \d+ ') ' ('Warning:'/'Hint:') \s* {.*}" + pegOtherError = peg"'Error:' \s* {.*}" + pegSuccess = peg"'Hint: operation successful'.*" + +proc addText(textView: PTextView, text: string, colorTag: PTextTag = nil) = + if text != nil: + var iter: TTextIter + textView.getBuffer().getEndIter(addr(iter)) + + if colorTag == nil: + textView.getBuffer().insert(addr(iter), text, len(text)) + else: + textView.getBuffer().insertWithTags(addr(iter), text, len(text), colorTag, + nil) + +proc createColor(textView: PTextView, name, color: string): PTextTag = + var tagTable = textView.getBuffer().getTagTable() + result = tagTable.tableLookup(name) + if result == nil: + result = textView.getBuffer().createTag(name, "foreground", color, nil) + +when not defined(os.findExe): + proc findExe(exe: string): string = + ## returns "" if the exe cannot be found + result = addFileExt(exe, os.exeExt) + if ExistsFile(result): return + var path = os.getEnv("PATH") + for candidate in split(path, pathSep): + var x = candidate / result + if ExistsFile(x): return x + result = "" + +proc GetCmd(cmd, filename: string): string = + var f = quoteIfContainsWhite(filename) + if cmd =~ peg"\s* '$' y'findExe' '(' {[^)]+} ')' {.*}": + var exe = quoteIfContainsWhite(findExe(matches[0])) + if exe.len == 0: exe = matches[0] + result = exe & " " & matches[1] % f + else: + result = cmd % f + +proc showBottomPanel() = + if not win.settings.bottomPanelVisible: + win.bottomPanelTabs.show() + win.settings.bottomPanelVisible = true + PCheckMenuItem(win.viewBottomPanelMenuItem).itemSetActive(true) + # Scroll to the end of the TextView + # This is stupid, it works sometimes... it's random + var endIter: TTextIter + win.outputTextView.getBuffer().getEndIter(addr(endIter)) + discard win.outputTextView.scrollToIter( + addr(endIter), 0.25, False, 0.0, 0.0) + +proc compileRun(currentTab: int, shouldRun: bool) = + if win.Tabs[currentTab].filename.len == 0: return + # Clear the outputTextView + win.outputTextView.getBuffer().setText("", 0) + + var outp = osProc.execProcess(GetCmd(win.settings.nimrodCmd, + win.Tabs[currentTab].filename)) + # Colors + var normalTag = createColor(win.outputTextView, "normalTag", "#3d3d3d") + var errorTag = createColor(win.outputTextView, "errorTag", "red") + var warningTag = createColor(win.outputTextView, "warningTag", "darkorange") + var successTag = createColor(win.outputTextView, "successTag", "darkgreen") + for x in outp.splitLines(): + if x =~ pegLineError / pegOtherError: + win.outputTextView.addText("\n" & x, errorTag) + elif x=~ pegSuccess: + win.outputTextView.addText("\n" & x, successTag) + + # Launch the process + if shouldRun: + var filename = changeFileExt(win.Tabs[currentTab].filename, os.ExeExt) + var output = "\n" & osProc.execProcess(filename) + win.outputTextView.addText(output) + elif x =~ pegLineWarning: + win.outputTextView.addText("\n" & x, warningTag) + else: + win.outputTextView.addText("\n" & x, normalTag) + showBottomPanel() + +proc CompileCurrent_Activate(menuitem: PMenuItem, user_data: pgpointer) = + saveFile_Activate(nil, nil) + compileRun(win.SourceViewTabs.getCurrentPage(), false) + +proc CompileRunCurrent_Activate(menuitem: PMenuItem, user_data: pgpointer) = + saveFile_Activate(nil, nil) + compileRun(win.SourceViewTabs.getCurrentPage(), true) + +proc CompileProject_Activate(menuitem: PMenuItem, user_data: pgpointer) = + saveAllTabs() + compileRun(getProjectTab(), false) + +proc CompileRunProject_Activate(menuitem: PMenuItem, user_data: pgpointer) = + saveAllTabs() + compileRun(getProjectTab(), true) + +proc RunCustomCommand(cmd: string) = + saveFile_Activate(nil, nil) + var currentTab = win.SourceViewTabs.getCurrentPage() + if win.Tabs[currentTab].filename.len == 0 or cmd.len == 0: return + # Clear the outputTextView + win.outputTextView.getBuffer().setText("", 0) + var outp = osProc.execProcess(GetCmd(cmd, win.Tabs[currentTab].filename)) + var normalTag = createColor(win.outputTextView, "normalTag", "#3d3d3d") + for x in outp.splitLines(): + win.outputTextView.addText("\n" & x, normalTag) + showBottomPanel() + +proc RunCustomCommand1(menuitem: PMenuItem, user_data: pgpointer) = + RunCustomCommand(win.settings.customCmd1) + +proc RunCustomCommand2(menuitem: PMenuItem, user_data: pgpointer) = + RunCustomCommand(win.settings.customCmd2) + +proc RunCustomCommand3(menuitem: PMenuItem, user_data: pgpointer) = + RunCustomCommand(win.settings.customCmd3) + +# -- FindBar + +proc nextBtn_Clicked(button: PButton, user_data: pgpointer) = findText(True) +proc prevBtn_Clicked(button: PButton, user_data: pgpointer) = findText(False) + +proc replaceBtn_Clicked(button: PButton, user_data: pgpointer) = + var currentTab = win.SourceViewTabs.getCurrentPage() + var start, theEnd: TTextIter + if not win.Tabs[currentTab].buffer.getSelectionBounds( + addr(start), addr(theEnd)): + # If no text is selected, try finding a match. + findText(True) + if not win.Tabs[currentTab].buffer.getSelectionBounds( + addr(start), addr(theEnd)): + # No match + return + + # Remove the text + win.Tabs[currentTab].buffer.delete(addr(start), addr(theEnd)) + # Insert the replacement + var text = getText(win.replaceEntry) + win.Tabs[currentTab].buffer.insert(addr(start), text, len(text)) + +proc replaceAllBtn_Clicked(button: PButton, user_data: pgpointer) = + var find = getText(win.findEntry) + var replace = getText(win.replaceEntry) + discard replaceAll(find, replace) + +proc closeBtn_Clicked(button: PButton, user_data: pgpointer) = + win.findBar.hide() + +proc caseSens_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = + win.settings.search = "casesens" +proc caseInSens_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = + win.settings.search = "caseinsens" +proc style_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = + win.settings.search = "style" +proc regex_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = + win.settings.search = "regex" +proc peg_Changed(radiomenuitem: PRadioMenuitem, user_data: pgpointer) = + win.settings.search = "peg" + +proc extraBtn_Clicked(button: PButton, user_data: pgpointer) = + var extraMenu = menuNew() + var group: PGSList + + var caseSensMenuItem = radio_menu_item_new(group, "Case sensitive") + extraMenu.append(caseSensMenuItem) + discard signal_connect(caseSensMenuItem, "toggled", + SIGNAL_FUNC(caseSens_Changed), nil) + caseSensMenuItem.show() + group = caseSensMenuItem.ItemGetGroup() + + var caseInSensMenuItem = radio_menu_item_new(group, "Case insensitive") + extraMenu.append(caseInSensMenuItem) + discard signal_connect(caseInSensMenuItem, "toggled", + SIGNAL_FUNC(caseInSens_Changed), nil) + caseInSensMenuItem.show() + group = caseInSensMenuItem.ItemGetGroup() + + var styleMenuItem = radio_menu_item_new(group, "Style insensitive") + extraMenu.append(styleMenuItem) + discard signal_connect(styleMenuItem, "toggled", + SIGNAL_FUNC(style_Changed), nil) + styleMenuItem.show() + group = styleMenuItem.ItemGetGroup() + + var regexMenuItem = radio_menu_item_new(group, "Regex") + extraMenu.append(regexMenuItem) + discard signal_connect(regexMenuItem, "toggled", + SIGNAL_FUNC(regex_Changed), nil) + regexMenuItem.show() + group = regexMenuItem.ItemGetGroup() + + var pegMenuItem = radio_menu_item_new(group, "Pegs") + extraMenu.append(pegMenuItem) + discard signal_connect(pegMenuItem, "toggled", + SIGNAL_FUNC(peg_Changed), nil) + pegMenuItem.show() + + # Make the correct radio button active + case win.settings.search + of "casesens": + PCheckMenuItem(caseSensMenuItem).ItemSetActive(True) + of "caseinsens": + PCheckMenuItem(caseInSensMenuItem).ItemSetActive(True) + of "style": + PCheckMenuItem(styleMenuItem).ItemSetActive(True) + of "regex": + PCheckMenuItem(regexMenuItem).ItemSetActive(True) + of "peg": + PCheckMenuItem(pegMenuItem).ItemSetActive(True) + + extraMenu.popup(nil, nil, nil, nil, 0, get_current_event_time()) + +# GUI Initialization + +proc createAccelMenuItem(toolsMenu: PMenu, accGroup: PAccelGroup, + label: string, acc: gint, + action: proc (i: PMenuItem, p: pgpointer)) = + var result = menu_item_new(label) + result.addAccelerator("activate", accGroup, acc, 0, ACCEL_VISIBLE) + ToolsMenu.append(result) + show(result) + discard signal_connect(result, "activate", SIGNAL_FUNC(action), nil) + +proc createSeparator(menu: PMenu) = + var sep = separator_menu_item_new() + menu.append(sep) + sep.show() + +proc initTopMenu(MainBox: PBox) = + # Create a accelerator group, used for shortcuts + # like CTRL + S in SaveMenuItem + var accGroup = accel_group_new() + add_accel_group(win.w, accGroup) + + # TopMenu(MenuBar) + var TopMenu = menuBarNew() + + # FileMenu + var FileMenu = menuNew() + + var NewMenuItem = menu_item_new("New") # New + FileMenu.append(NewMenuItem) + show(NewMenuItem) + discard signal_connect(NewMenuItem, "activate", + SIGNAL_FUNC(newFile), nil) + + createSeparator(FileMenu) + + var OpenMenuItem = menu_item_new("Open...") # Open... + # CTRL + O + OpenMenuItem.add_accelerator("activate", accGroup, + KEY_o, CONTROL_MASK, ACCEL_VISIBLE) + FileMenu.append(OpenMenuItem) + show(OpenMenuItem) + discard signal_connect(OpenMenuItem, "activate", + SIGNAL_FUNC(aporia.openFile), nil) + + var SaveMenuItem = menu_item_new("Save") # Save + # CTRL + S + SaveMenuItem.add_accelerator("activate", accGroup, + KEY_s, CONTROL_MASK, ACCEL_VISIBLE) + FileMenu.append(SaveMenuItem) + show(SaveMenuItem) + discard signal_connect(SaveMenuItem, "activate", + SIGNAL_FUNC(saveFile_activate), nil) + + var SaveAsMenuItem = menu_item_new("Save As...") # Save as... + + SaveAsMenuItem.add_accelerator("activate", accGroup, + KEY_s, CONTROL_MASK or gdk2.SHIFT_MASK, ACCEL_VISIBLE) + FileMenu.append(SaveAsMenuItem) + show(SaveAsMenuItem) + discard signal_connect(SaveAsMenuItem, "activate", + SIGNAL_FUNC(saveFileAs_Activate), nil) + + var FileMenuItem = menuItemNewWithMnemonic("_File") + + FileMenuItem.setSubMenu(FileMenu) + FileMenuItem.show() + TopMenu.append(FileMenuItem) + + # Edit menu + var EditMenu = menuNew() + + var UndoMenuItem = menu_item_new("Undo") # Undo + EditMenu.append(UndoMenuItem) + show(UndoMenuItem) + discard signal_connect(UndoMenuItem, "activate", + SIGNAL_FUNC(aporia.undo), nil) + + var RedoMenuItem = menu_item_new("Redo") # Undo + EditMenu.append(RedoMenuItem) + show(RedoMenuItem) + discard signal_connect(RedoMenuItem, "activate", + SIGNAL_FUNC(aporia.redo), nil) + + createSeparator(EditMenu) + + var FindMenuItem = menu_item_new("Find") # Find + FindMenuItem.add_accelerator("activate", accGroup, + KEY_f, CONTROL_MASK, ACCEL_VISIBLE) + EditMenu.append(FindMenuItem) + show(FindMenuItem) + discard signal_connect(FindMenuItem, "activate", + SIGNAL_FUNC(aporia.find_Activate), nil) + + var ReplaceMenuItem = menu_item_new("Replace") # Replace + ReplaceMenuItem.add_accelerator("activate", accGroup, + KEY_h, CONTROL_MASK, ACCEL_VISIBLE) + EditMenu.append(ReplaceMenuItem) + show(ReplaceMenuItem) + discard signal_connect(ReplaceMenuItem, "activate", + SIGNAL_FUNC(aporia.replace_Activate), nil) + + createSeparator(EditMenu) + + var SettingsMenuItem = menu_item_new("Settings...") # Settings + EditMenu.append(SettingsMenuItem) + show(SettingsMenuItem) + discard signal_connect(SettingsMenuItem, "activate", + SIGNAL_FUNC(aporia.Settings_Activate), nil) + + var EditMenuItem = menuItemNewWithMnemonic("_Edit") + + EditMenuItem.setSubMenu(EditMenu) + EditMenuItem.show() + TopMenu.append(EditMenuItem) + + # View menu + var ViewMenu = menuNew() + + win.viewBottomPanelMenuItem = check_menu_item_new("Bottom Panel") + PCheckMenuItem(win.viewBottomPanelMenuItem).itemSetActive( + win.settings.bottomPanelVisible) + win.viewBottomPanelMenuItem.add_accelerator("activate", accGroup, + KEY_f9, CONTROL_MASK, ACCEL_VISIBLE) + ViewMenu.append(win.viewBottomPanelMenuItem) + show(win.viewBottomPanelMenuItem) + discard signal_connect(win.viewBottomPanelMenuItem, "toggled", + SIGNAL_FUNC(aporia.viewBottomPanel_Toggled), nil) + + var ViewMenuItem = menuItemNewWithMnemonic("_View") + + ViewMenuItem.setSubMenu(ViewMenu) + ViewMenuItem.show() + TopMenu.append(ViewMenuItem) + + + # Tools menu + var ToolsMenu = menuNew() + + createAccelMenuItem(ToolsMenu, accGroup, "Compile current file", + KEY_F4, aporia.CompileCurrent_Activate) + createAccelMenuItem(ToolsMenu, accGroup, "Compile & run current file", + KEY_F5, aporia.CompileRunCurrent_Activate) + createSeparator(ToolsMenu) + createAccelMenuItem(ToolsMenu, accGroup, "Compile project", + KEY_F8, aporia.CompileProject_Activate) + createAccelMenuItem(ToolsMenu, accGroup, "Compile & run project", + KEY_F9, aporia.CompileRunProject_Activate) + createSeparator(ToolsMenu) + createAccelMenuItem(ToolsMenu, accGroup, "Run custom command 1", + KEY_F1, aporia.RunCustomCommand1) + createAccelMenuItem(ToolsMenu, accGroup, "Run custom command 2", + KEY_F2, aporia.RunCustomCommand2) + createAccelMenuItem(ToolsMenu, accGroup, "Run custom command 3", + KEY_F3, aporia.RunCustomCommand3) + + var ToolsMenuItem = menuItemNewWithMnemonic("_Tools") + + ToolsMenuItem.setSubMenu(ToolsMenu) + ToolsMenuItem.show() + TopMenu.append(ToolsMenuItem) + + # Help menu + MainBox.packStart(TopMenu, False, False, 0) + TopMenu.show() + +proc initToolBar(MainBox: PBox) = + # TopBar(ToolBar) + var TopBar = toolbarNew() + TopBar.setStyle(TOOLBAR_ICONS) + + var NewFileItem = TopBar.insertStock(STOCK_NEW, "New File", + "New File", SIGNAL_FUNC(aporia.newFile), nil, 0) + TopBar.appendSpace() + var OpenItem = TopBar.insertStock(STOCK_OPEN, "Open", + "Open", SIGNAL_FUNC(aporia.openFile), nil, -1) + var SaveItem = TopBar.insertStock(STOCK_SAVE, "Save", + "Save", SIGNAL_FUNC(saveFile_Activate), nil, -1) + TopBar.appendSpace() + var UndoItem = TopBar.insertStock(STOCK_UNDO, "Undo", + "Undo", SIGNAL_FUNC(aporia.undo), nil, -1) + var RedoItem = TopBar.insertStock(STOCK_REDO, "Redo", + "Redo", SIGNAL_FUNC(aporia.redo), nil, -1) + + MainBox.packStart(TopBar, False, False, 0) + TopBar.show() + +proc initSourceViewTabs() = + win.SourceViewTabs = notebookNew() + #win.sourceViewTabs.dragDestSet(DEST_DEFAULT_DROP, nil, 0, ACTION_MOVE) + discard win.SourceViewTabs.signalConnect( + "switch-page", SIGNAL_FUNC(onSwitchTab), nil) + #discard win.SourceViewTabs.signalConnect( + # "drag-drop", SIGNAL_FUNC(svTabs_DragDrop), nil) + #discard win.SourceViewTabs.signalConnect( + # "drag-data-received", SIGNAL_FUNC(svTabs_DragDataRecv), nil) + #discard win.SourceViewTabs.signalConnect( + # "drag-motion", SIGNAL_FUNC(svTabs_DragMotion), nil) + win.SourceViewTabs.set_scrollable(True) + + win.SourceViewTabs.show() + if lastSession.len != 0: + for i in 0 .. len(lastSession)-1: + var splitUp = lastSession[i].split('|') + var (filename, offset) = (splitUp[0], splitUp[1]) + addTab("", filename) + + var iter: TTextIter + win.Tabs[i].buffer.getIterAtOffset(addr(iter), offset.parseInt()) + win.Tabs[i].buffer.moveMarkByName("insert", addr(iter)) + win.Tabs[i].buffer.moveMarkByName("selection_bound", addr(iter)) + + # TODO: Fix this..... :( + discard PTextView(win.Tabs[i].sourceView). + scrollToIter(addr(iter), 0.25, true, 0.0, 0.0) + else: + addTab("", "") + + # This doesn't work :\ + win.Tabs[0].sourceView.grabFocus() + + +proc initBottomTabs() = + win.bottomPanelTabs = notebookNew() + if win.settings.bottomPanelVisible: + win.bottomPanelTabs.show() + + # output tab + var tabLabel = labelNew("Output") + var outputTab = vboxNew(False, 0) + discard win.bottomPanelTabs.appendPage(outputTab, tabLabel) + # Compiler tabs, gtktextview + var outputScrolledWindow = scrolledwindowNew(nil, nil) + outputScrolledWindow.setPolicy(POLICY_AUTOMATIC, POLICY_AUTOMATIC) + outputTab.packStart(outputScrolledWindow, true, true, 0) + outputScrolledWindow.show() + + win.outputTextView = textviewNew() + outputScrolledWindow.add(win.outputTextView) + win.outputTextView.show() + + outputTab.show() + +proc initTAndBP(MainBox: PBox) = + # This init's the HPaned, which splits the sourceViewTabs + # and the BottomPanelTabs + initSourceViewTabs() + initBottomTabs() + + var TAndBPVPaned = vpanedNew() + tandbpVPaned.pack1(win.sourceViewTabs, resize=True, shrink=False) + tandbpVPaned.pack2(win.bottomPanelTabs, resize=False, shrink=False) + MainBox.packStart(TAndBPVPaned, True, True, 0) + tandbpVPaned.setPosition(win.settings.VPanedPos) + TAndBPVPaned.show() + +proc initFindBar(MainBox: PBox) = + # Create a fixed container + win.findBar = HBoxNew(False, 0) + win.findBar.setSpacing(4) + + # Add a Label 'Find' + var findLabel = labelNew("Find:") + win.findBar.packStart(findLabel, False, False, 0) + findLabel.show() + + # Add a (find) text entry + win.findEntry = entryNew() + win.findBar.packStart(win.findEntry, False, False, 0) + discard win.findEntry.signalConnect("activate", SIGNAL_FUNC( + aporia.nextBtn_Clicked), nil) + win.findEntry.show() + var rq: TRequisition + win.findEntry.sizeRequest(addr(rq)) + + # Make the (find) text entry longer + win.findEntry.set_size_request(190, rq.height) + + # Add a Label 'Replace' + # - This Is only shown, when the 'Search & Replace'(CTRL + H) is shown + win.replaceLabel = labelNew("Replace:") + win.findBar.packStart(win.replaceLabel, False, False, 0) + #replaceLabel.show() + + # Add a (replace) text entry + # - This Is only shown, when the 'Search & Replace'(CTRL + H) is shown + win.replaceEntry = entryNew() + win.findBar.packStart(win.replaceEntry, False, False, 0) + #win.replaceEntry.show() + var rq1: TRequisition + win.replaceEntry.sizeRequest(addr(rq1)) + + # Make the (replace) text entry longer + win.replaceEntry.set_size_request(100, rq1.height) + + # Find next button + var nextBtn = buttonNew("Next") + win.findBar.packStart(nextBtn, false, false, 0) + discard nextBtn.signalConnect("clicked", + SIGNAL_FUNC(aporia.nextBtn_Clicked), nil) + nextBtn.show() + var nxtBtnRq: TRequisition + nextBtn.sizeRequest(addr(nxtBtnRq)) + + # Find previous button + var prevBtn = buttonNew("Previous") + win.findBar.packStart(prevBtn, false, false, 0) + discard prevBtn.signalConnect("clicked", + SIGNAL_FUNC(aporia.prevBtn_Clicked), nil) + prevBtn.show() + + # Replace button + # - This Is only shown, when the 'Search & Replace'(CTRL + H) is shown + win.replaceBtn = buttonNew("Replace") + win.findBar.packStart(win.replaceBtn, false, false, 0) + discard win.replaceBtn.signalConnect("clicked", + SIGNAL_FUNC(aporia.replaceBtn_Clicked), nil) + #replaceBtn.show() + + # Replace all button + # - this Is only shown, when the 'Search & Replace'(CTRL + H) is shown + win.replaceAllBtn = buttonNew("Replace All") + win.findBar.packStart(win.replaceAllBtn, false, false, 0) + discard win.replaceAllBtn.signalConnect("clicked", + SIGNAL_FUNC(aporia.replaceAllBtn_Clicked), nil) + #replaceAllBtn.show() + + # Right side ... + + # Close button - With a close stock image + var closeBtn = buttonNew() + var closeImage = imageNewFromStock(STOCK_CLOSE, ICON_SIZE_SMALL_TOOLBAR) + var closeBox = hboxNew(False, 0) + closeBtn.add(closeBox) + closeBox.show() + closeBox.add(closeImage) + closeImage.show() + discard closeBtn.signalConnect("clicked", + SIGNAL_FUNC(aporia.closeBtn_Clicked), nil) + win.findBar.packEnd(closeBtn, False, False, 2) + closeBtn.show() + + # Extra button - When clicked shows a menu with options like 'Use regex' + var extraBtn = buttonNew() + var extraImage = imageNewFromStock(STOCK_PROPERTIES, ICON_SIZE_SMALL_TOOLBAR) + + var extraBox = hboxNew(False, 0) + extraBtn.add(extraBox) + extraBox.show() + extraBox.add(extraImage) + extraImage.show() + discard extraBtn.signalConnect("clicked", + SIGNAL_FUNC(aporia.extraBtn_Clicked), nil) + win.findBar.packEnd(extraBtn, False, False, 0) + extraBtn.show() + + MainBox.packStart(win.findBar, False, False, 0) + win.findBar.show() + +proc initStatusBar(MainBox: PBox) = + win.bottomBar = statusbarNew() + MainBox.packStart(win.bottomBar, False, False, 0) + win.bottomBar.show() + + discard win.bottomBar.push(0, "Line: 0 Column: 0") + +proc initControls() = + # Load up the language style + win.langMan = languageManagerGetDefault() + var langpaths: array[0..1, cstring] = + [cstring(os.getApplicationDir() / langSpecs), nil] + win.langMan.setSearchPath(addr(langpaths)) + var nimLang = win.langMan.getLanguage("nimrod") + win.nimLang = nimLang + + # Load the scheme + var schemeMan = schemeManagerGetDefault() + var schemepaths: array[0..1, cstring] = + [cstring(os.getApplicationDir() / styles), nil] + schemeMan.setSearchPath(addr(schemepaths)) + win.scheme = schemeMan.getScheme(win.settings.colorSchemeID) + + # Window + win.w = windowNew(gtk2.WINDOW_TOPLEVEL) + win.w.setDefaultSize(win.settings.winWidth, win.settings.winHeight) + win.w.setTitle("Aporia IDE") + if win.settings.winMaximized: win.w.maximize() + + win.w.show() # The window has to be shown before + # setting the position of the VPaned so that + # it gets set correctly, when the window is maximized. + + discard win.w.signalConnect("destroy", SIGNAL_FUNC(aporia.destroy), nil) + discard win.w.signalConnect("delete_event", + SIGNAL_FUNC(aporia.delete_event), nil) + discard win.w.signalConnect("window-state-event", + SIGNAL_FUNC(aporia.windowState_Changed), nil) + + # MainBox (vbox) + var MainBox = vboxNew(False, 0) + win.w.add(MainBox) + + initTopMenu(MainBox) + initToolBar(MainBox) + initTAndBP(MainBox) + initFindBar(MainBox) + initStatusBar(MainBox) + + MainBox.show() + if confParseFail: + dialogs.warning(win.w, "Error parsing config file, using default settings.") + +nimrod_init() +initControls() +main() + diff --git a/tests/examplefiles/example.nix b/tests/examplefiles/example.nix new file mode 100644 index 00000000..515b686f --- /dev/null +++ b/tests/examplefiles/example.nix @@ -0,0 +1,80 @@ +{ stdenv, fetchurl, fetchgit, openssl, zlib, pcre, libxml2, libxslt, expat +, rtmp ? false +, fullWebDAV ? false +, syslog ? false +, moreheaders ? false, ...}: + +let + version = "1.4.4"; + mainSrc = fetchurl { + url = "http://nginx.org/download/nginx-${version}.tar.gz"; + sha256 = "1f82845mpgmhvm151fhn2cnqjggw9w7cvsqbva9rb320wmc9m63w"; + }; + + rtmp-ext = fetchgit { + url = git://github.com/arut/nginx-rtmp-module.git; + rev = "1cfb7aeb582789f3b15a03da5b662d1811e2a3f1"; + sha256 = "03ikfd2l8mzsjwx896l07rdrw5jn7jjfdiyl572yb9jfrnk48fwi"; + }; + + dav-ext = fetchgit { + url = git://github.com/arut/nginx-dav-ext-module.git; + rev = "54cebc1f21fc13391aae692c6cce672fa7986f9d"; + sha256 = "1dvpq1fg5rslnl05z8jc39sgnvh3akam9qxfl033akpczq1bh8nq"; + }; + + syslog-ext = fetchgit { + url = https://github.com/yaoweibin/nginx_syslog_patch.git; + rev = "165affd9741f0e30c4c8225da5e487d33832aca3"; + sha256 = "14dkkafjnbapp6jnvrjg9ip46j00cr8pqc2g7374z9aj7hrvdvhs"; + }; + + moreheaders-ext = fetchgit { + url = https://github.com/agentzh/headers-more-nginx-module.git; + rev = "refs/tags/v0.23"; + sha256 = "12pbjgsxnvcf2ff2i2qdn39q4cm5czlgrng96j8ml4cgxvnbdh39"; + }; +in + +stdenv.mkDerivation rec { + name = "nginx-${version}"; + src = mainSrc; + + buildInputs = [ openssl zlib pcre libxml2 libxslt + ] ++ stdenv.lib.optional fullWebDAV expat; + + patches = if syslog then [ "${syslog-ext}/syslog_1.4.0.patch" ] else []; + + configureFlags = [ + "--with-http_ssl_module" + "--with-http_spdy_module" + "--with-http_xslt_module" + "--with-http_sub_module" + "--with-http_dav_module" + "--with-http_gzip_static_module" + "--with-http_secure_link_module" + "--with-ipv6" + # Install destination problems + # "--with-http_perl_module" + ] ++ stdenv.lib.optional rtmp "--add-module=${rtmp-ext}" + ++ stdenv.lib.optional fullWebDAV "--add-module=${dav-ext}" + ++ stdenv.lib.optional syslog "--add-module=${syslog-ext}" + ++ stdenv.lib.optional moreheaders "--add-module=${moreheaders-ext}"; + + preConfigure = '' + export NIX_CFLAGS_COMPILE="$NIX_CFLAGS_COMPILE -I${libxml2 }/include/libxml2" + ''; + + # escape example + postInstall = '' + mv $out/sbin $out/bin ''' ''${ + ${ if true then ${ "" } else false } + ''; + + meta = { + description = "A reverse proxy and lightweight webserver"; + maintainers = [ stdenv.lib.maintainers.raskin]; + platforms = stdenv.lib.platforms.all; + inherit version; + }; +} diff --git a/tests/examplefiles/example.pp b/tests/examplefiles/example.pp new file mode 100644 index 00000000..ea697be2 --- /dev/null +++ b/tests/examplefiles/example.pp @@ -0,0 +1,8 @@ +exec { 'grep': + command => 'grep "\'" -rI *', + path => '/bin:/usr/bin', +} + +node default { + notify {"Hello World":;} +} diff --git a/tests/examplefiles/example.prg b/tests/examplefiles/example.prg new file mode 100644 index 00000000..b70d9e42 --- /dev/null +++ b/tests/examplefiles/example.prg @@ -0,0 +1,161 @@ +&& This is a concatenation of all VFP examples on Wikipedia. +&& Copyright 2013 Wikimedia, under the GFDL. + +FOR i = 1 to 10 + x = x + 6.5 +ENDFOR + +IF i = 25 + i = i + 1 +ELSE + i = i + 3 +ENDIF + +x = 1 +DO WHILE x < 50 + x = x + 1 +ENDDO + +x = 1 +DO WHILE .T. + x = x + 1 + IF x < 50 + LOOP + ELSE + EXIT + ENDIF +ENDDO + +nMonth = MONTH(DATE()) +DO CASE + CASE nMonth <= 3 + MESSAGEBOX("Q1") + + CASE nMonth <= 6 + MESSAGEBOX("Q2") + + CASE nMonth <= 9 + MESSAGEBOX("Q3") + + OTHERWISE + MESSAGEBOX("Q4") +ENDCASE + +FOR EACH oControl IN THISFORM.Controls + MESSAGEBOX(oControl.Name) +ENDFOR + +f = Factorial(10) + +FUNCTION Factorial(n) + LOCAL i,r + r = 1 + FOR i = n TO 1 STEP -1 + r = r * n + ENDFOR + RETURN r +ENDFUNC + +loForm = CREATEOBJECT("HiForm") +loForm.Show(1) + +DEFINE CLASS HiForm AS Form + AutoCenter = .T. + Caption = "Hello, World" + + ADD OBJECT lblHi as Label WITH ; + Caption = "Hello, World!" +ENDDEFINE + +loMine = CREATEOBJECT("MyClass") +? loMine.cProp1 && This will work. (Double-ampersand marks an end-of-line comment) +? loMine.cProp2 && Program Error: Property CPROP2 is not found. + +? loMine.MyMethod1() && This will work. +? loMine.MyMethod2() && Program Error: Property MYMETHOD2 is not found. + +DEFINE CLASS MyClass AS Custom + cProp1 = "My Property" && This is a public property + HIDDEN cProp2 && This is a private (hidden) property + dProp3 = {} && Another public property + + PROCEDURE Init() && Class constructor + This.cProp2 = "This is a hidden property." + ENDPROC + + PROCEDURE dProp3_Access && Property Getter + RETURN DATE() + ENDPROC + PROCEDURE dProp3_Assign(vNewVal) && Property Setter + IF VARTYPE(vNewVal) = "D" + THIS.dProp3 = vNewVal + ENDIF + ENDPROC + + PROCEDURE MyMethod1() + * This is a public method, calling a hidden method that returns + * the value of a hidden property. + RETURN This.MyMethod2() + ENDPROC + + HIDDEN PROCEDURE MyMethod2() && This is a private (hidden) method + RETURN This.cProp2 + ENDPROC +ENDDEFINE + +&& Create a table +CREATE TABLE randData (iData I) + +&& Populate with random data using xBase and SQL DML commands +FOR i = 1 TO 50 + APPEND BLANK + REPLACE iData WITH (RAND() * 100) + + INSERT INTO randData (iData) VALUES (RAND() * 100) +ENDFOR + +&& Place a structural index on the data +INDEX ON iData TAG iData +CLOSE ALL + +&& Display ordered data using xBase-style commands +USE randData +SET ORDER TO iData +GO TOP +LIST NEXT 10 && First 10 +GO BOTTOM +SKIP -10 +LIST REST && Last 10 +CLOSE ALL + +&& Browse ordered data using SQL DML commands +SELECT * ; + FROM randData ; + ORDER BY iData DESCENDING + + +&& Connect to an ODBC data source +LOCAL nHnd +nHnd = SQLCONNECT ("ODBCDSN", "user", "pwd") + +&& Execute a SQL command +LOCAL nResult +nResult = SQLEXEC (nHnd, "USE master") +IF nResult < 0 + MESSAGEBOX ("MASTER database does not exist!") + RETURN +ENDIF + +&& Retrieve data from the remote server and stores it in +&& a local data cursor +nResult = SQLEXEC (nHnd, "SELECT * FROM authors", "QAUTHORS") + +&& Update a record in a remote table using parameters +PRIVATE cAuthorID, cAuthorName +cAuthorID = "1001" +cAuthorName = "New name" +nResult = SQLEXEC (nHnd, "UPDATE authors SET auth_name = ?cAuthorName WHERE auth_id = ?cAuthorID") + +&& Close the connection +SQLDISCONNECT(nHnd) + diff --git a/tests/examplefiles/example.reg b/tests/examplefiles/example.reg new file mode 100644 index 00000000..bc4e9df4 --- /dev/null +++ b/tests/examplefiles/example.reg @@ -0,0 +1,19 @@ +Windows Registry Editor Version 5.00 +; comment + +[HKEY_CURRENT_USER\SOFTWARE\Pygments] +@="Hello" +"Key With Spaces"="Something" +"Key With ="="With Quotes" +"Key With = 2"=dword:123 +"Key" = "Value" +"Hex"=hex(0):1,2,3,a,b,f +"Hex 2"=hex(5):80,00,00,ff + +[-HKEY_CURRENT_USER\SOFTWARE\Pygments\Subkey] + +[HKEY_CURRENT_USER\SOFTWARE\Pygments\Subkey2] +; comment +@=- +"Foo"=- +"Foo"="Value" diff --git a/tests/examplefiles/example.rexx b/tests/examplefiles/example.rexx new file mode 100644 index 00000000..ec4da5ad --- /dev/null +++ b/tests/examplefiles/example.rexx @@ -0,0 +1,50 @@ +/* REXX example. */ + +/* Some basic constructs. */ +almost_pi = 0.1415 + 3 +if almost_pi < 3 then + say 'huh?' +else do + say 'almost_pi=' almost_pi || " - ok" +end +x = '"' || "'" || '''' || """" /* quotes */ + +/* A comment + * spawning multiple + lines. /* / */ + +/* Built-in functions. */ +line = 'line containing some short text' +say WordPos(line, 'some') +say Word(line, 4) + +/* Labels and procedures. */ +some_label : + +divide: procedure + parse arg some other + return some / other + +call divide(5, 2) + +/* Loops */ +do i = 1 to 5 + do j = -3 to -9 by -3 + say i '+' j '=' i + j + end j +end i + +do forever + leave +end + +/* Print a text file on MVS. */ +ADDRESS TSO +"ALLOC F(TEXTFILE) DSN('some.text.dsn') SHR REU" +"EXECIO * DISKR TEXTFILE ( FINIS STEM LINES." +"FREE F(TEXTFILE)" +I = 1 +DO WHILE I <= LINES.0 + SAY ' LINE ' I ' : ' LINES.I + I = I + 1 +END diff --git a/tests/examplefiles/example.rkt b/tests/examplefiles/example.rkt new file mode 100644 index 00000000..a3e4a29e --- /dev/null +++ b/tests/examplefiles/example.rkt @@ -0,0 +1,95 @@ +#lang racket + +; Single-line comment style. + +;; Single-line comment style. + +#| Multi-line comment style ... on one line |# + +#| +Multi-line comment style ... +... on multiple lines +|# + +(define (a-function x #:keyword [y 0]) + (define foo0 'symbol) ; () + [define foo1 'symbol] ; [] + {define foo2 'symbol} ; {} + (and (append (car '(1 2 3)))) + (regexp-match? #rx"foobar" "foobar") + (regexp-match? #px"foobar" "foobar") + (define a 1)) + (let ([b "foo"]) + (displayln b)) + (for/list ([x (in-list (list 1 2 (list 3 4)))]) + (cond + [(pair? x) (car x)] + [else x]))) + +;; Literal number examples +(values + ;; #b + #b1.1 + #b-1.1 + #b1e1 + #b0/1 + #b1/1 + #b1e-1 + #b101 + + ;; #d + #d-1.23 + #d1.123 + #d1e3 + #d1e-22 + #d1/2 + #d-1/2 + #d1 + #d-1 + + ;; No # reader prefix -- same as #d + -1.23 + 1.123 + 1e3 + 1e-22 + 1/2 + -1/2 + 1 + -1 + + ;; #e + #e-1.23 + #e1.123 + #e1e3 + #e1e-22 + #e1 + #e-1 + #e1/2 + #e-1/2 + + ;; #i always float + #i-1.23 + #i1.123 + #i1e3 + #i1e-22 + #i1/2 + #i-1/2 + #i1 + #i-1 + + ;; #o + #o777.777 + #o-777.777 + #o777e777 + #o777e-777 + #o3/7 + #o-3/7 + #o777 + #o-777 + + ;; #x + #x-f.f + #xf.f + #x-f + #xf + ) diff --git a/tests/examplefiles/example.rpf b/tests/examplefiles/example.rpf new file mode 100644 index 00000000..162b5ed3 --- /dev/null +++ b/tests/examplefiles/example.rpf @@ -0,0 +1,4 @@ +declare xyz true +declare s "some string" +i = 2 +f = 0.2 diff --git a/tests/examplefiles/example.sh b/tests/examplefiles/example.sh new file mode 100644 index 00000000..2112cdd1 --- /dev/null +++ b/tests/examplefiles/example.sh @@ -0,0 +1,22 @@ +#!/bin/bash + +printf "%d %s\n" 10 "foo" +printf "%d %s\n" $((10#1)) "bar" + +let "m = 10#${1:1:2}" +echo $m + +m=$((10#${1:4:3} + 10#${1:1:3})) +echo $m + +m=$((10#${1:4:3})) +echo $m + +m=$((10#$1)) +echo $m + +m=$((10#1)) +echo $m + +m=$((10)) +echo $m diff --git a/tests/examplefiles/example.sh-session b/tests/examplefiles/example.sh-session index 35b81ebb..02f3bb0d 100644 --- a/tests/examplefiles/example.sh-session +++ b/tests/examplefiles/example.sh-session @@ -15,3 +15,5 @@ user@host:~/path$ su root@host:~# sh-3.1$ # on hardy sh$ # on etch +(virtualenv-name)user@host:~$ ls -a + diff --git a/tests/examplefiles/example.shell-session b/tests/examplefiles/example.shell-session new file mode 100644 index 00000000..66984aa5 --- /dev/null +++ b/tests/examplefiles/example.shell-session @@ -0,0 +1,45 @@ +[user@linuxbox imx-bootlets-src-10.05.02]$ make CROSS_COMPILE=arm-none-eabi- clean +rm -rf *.sb +rm -f sd_mmc_bootstream.raw +rm -f linux_prep/board/*.o +... +Files: +rm -f power_prep.o eabi.o +Build output: +make[1]: Leaving directory `/home/...' +[user@linuxbox imx-bootlets-src-10.05.02]$ make CROSS_COMPILE=arm-none-eabi- +make[1]: Entering directory `/home/...' +... +#@echo "generating U-Boot boot stream image" +#elftosb2 -z -c ./uboot_prebuilt.db -o imx23_uboot.sb +echo "generating kernel bootstream file sd_mmc_bootstream.raw" +generating kernel bootstream file sd_mmc_bootstream.raw +#Please use cfimager to burn xxx_linux.sb. The below way will no +#work at imx28 platform. +> test +$ test +rm -f sd_mmc_bootstream.raw +[user@linuxbox imx-bootlets-src-10.05.02]$ +pi@raspberrypi ~ $ sudo sh -c "echo 17 > /sys/class/gpio/export" +pi@raspberrypi ~ $ sudo sh -c "echo out > /sys/class/gpio/gpio17/direction" +pi@raspberrypi ~ $ sudo sh -c "echo 1 > /sys/class/gpio/gpio17/value" +pi@raspberrypi ~ $ sudo sh -c "echo 0 > /sys/class/gpio/gpio17/value" +pi@raspberrypi ~ $ +[user@linuxbox ~]$ # copy other stuff to the SD card +root@imx233-olinuxino-micro:~# lsmod + Not tainted +[user@linuxbox ~]$ tail -n 2 /mnt/rpi/etc/inittab +#Spawn a getty on Raspberry Pi serial line +T0:23:respawn:/sbin/getty -L ttyAMA0 115200 vt100 +pi@raspberrypi:~/Adafruit-WebIDE$ mkdir tmp +pi@raspberrypi:~/Adafruit-WebIDE$ npm config set tmp tmp +pi@raspberrypi:~/Adafruit-WebIDE$ npm install +pi@raspberrypi ~/Adafruit-WebIDE $ ifconfig eth0 +eth0 Link encap:Ethernet HWaddr b5:33:ff:33:ee:aq + inet addr:10.42.0.60 Bcast:10.42.0.255 Mask:255.255.255.0 + UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 + RX packets:21867 errors:0 dropped:0 overruns:0 frame:0 + TX packets:8684 errors:0 dropped:0 overruns:0 carrier:0 + collisions:0 txqueuelen:1000 + RX bytes:27338495 (26.0 MiB) TX bytes:1268356 (1.2 MiB) + diff --git a/tests/examplefiles/example.sml b/tests/examplefiles/example.sml new file mode 100644 index 00000000..31db47d2 --- /dev/null +++ b/tests/examplefiles/example.sml @@ -0,0 +1,156 @@ +structure C = struct + val a = 12 + fun f x = x + 5 +end + +(*(*(*(*(* This file is all pretty strange Standard ML *)*)*)*) (**)*) +(* Robert J. Simmons *) + +(* Comments (* can be nested *) *) +structure S = struct + val x = (1, 2, "three") +end + +structure Sv = struct + (* These look good *) + val x = (1, 2, "three") + val z = #2 x + + (* Although these look bad (not all the numbers are constants), * + * they never occur in practice, as they are equivalent to the above. *) + val x = {1 = 1, 3 = "three", 2 = 2} + val z = # + 2 x + + val || = 12 +end + +signature S = sig end + +structure S = struct + val x = (1, 2, "three") + datatype 'a t = T of 'a + and u = U of v * v + withtype v = {left: int t, right: int t} + exception E1 of int and E2 + fun 'a id (x: 'a) : 'a = x + + val + 'a id = fn (x : 'a) => x +end + +signature R = sig + type t + val x : t + val f : t * int -> int +end +structure R : R = struct + datatype t = T of int + val x : t = T 0 + fun f (T x, i : int) : int = x + i + fun 'a id (x: 'a) : 'a = x +end + +signature BA_Z = sig + val s: int + include S R +end + +structure b______ = struct (* What (* A * strange * name *) for ) a ( struct *) + +val !%&$#+-/:<=>?@\~`^|* = 3 + +type struct' = int list +and 'a sig' = 'a list +and ('a, 'b) end' = 'b option * 'a list + +structure baz = struct + structure Bar = struct + val foo = !%&$#+-/:<=>?@\~`^|* + end +end + +infixr +!+ +fun (a +!+ b) = (op +) (a, b) + +open baz S R + +val$$$ = fn x => fn y => fn z => fn w => w +val (foo, ++, bar, ||) = (4, baz.Bar.foo, !%&$#+-/:<=>?@\~`^|*, Bar.foo) +val _ = $$$foo++bar|| + +val val'ue : ' list = [] +val struct3 : (' -> ') = fn x => x +val end_struct_' : ('a -> 'a) = fn x => x +val x : (''a -> ''a) = fn x => x +val x : ('''' -> '''') = fn x => x +val x : unit = print "Weird, huh?\n" +val w = {x=1,y=2,##= =3,4=3} +val {##=, x, 4=a,...} = w +val z = #4 w +val z = # ##= w + +fun f x y 0 = 4 + | f x y z = 4 + Sv.|| + +exception Foo of int +datatype ('0, 'b, '_, ') f'o'o = Bar | baZ12' | dsfa_fad | #@$ | Bug +and (', ''', '''', ''''') bar = + Bee of unit + | Ben of (', ''', '''', ''''') f'o'o * int + | X of ''' list + +fun q x = raise Foo x +and h x = raise Foo (~x) + +val x = 4 +and y = 5 + +fun q 0 = 4 + | q 1 = (case 1 of 1 => 2 | 3 => 4 | x => y) + | q y = case y of 1 => 2 | 3 => 4 | x => y + +val x = ref true +fun q 0 = 4 + | q 1 = if false then case 1 of 1 => 2 | 3 => 4 | x => y else 19 + | q 2 = (while !x handle Match => !x | Fail _ => !x do () ; 2) + | q x = (raise Match) handle Domain => 9 | Match => 3 + +fun p 0 = 12 + | p 1 = 8 + | p 2 = r false + | p x = r true +and r true = 19 + | r false = 12 + +val _ = 123 +val _ = 0001 +val _ = ~123 +val _ = ~0001 +val _ = 0w12412 +val _ = 0w12412 +val _ = 0xfA0 +val _ = ~0xfA0 +val _ = 0wxfA0 +val _ = 1.4 +val _ = ~1.4 +val _ = 1e~2 +val _ = 1E~2 +val _ = 1e2 +val _ = 1E2 +val _ = 1.4e~2 +val _ = 1.4E~2 +val _ = 1.4e2 +val _ = 1.4E2 + +val c = #"\000" +val st = "foo \ + \ bar" ^ "baz \ + \ and \ + \ such\n" + +val () = print st + +val _ = foo::bar::4::[++] + +end diff --git a/tests/examplefiles/example.snobol b/tests/examplefiles/example.snobol new file mode 100644 index 00000000..26ca5cf4 --- /dev/null +++ b/tests/examplefiles/example.snobol @@ -0,0 +1,15 @@ +-SOME RANDOM DIRECTIVE WOULD GO HERE +* +* SNOBOL4 example file for lexer +* + SOME.THING_OR_OTHER32 = 1 + 1.0 - 1E3 * 1E-3 ** 2.718284590E0 ++ :F(END)S(IN_LOOP) + PATTERN = LEN(3) ("GAR" | "BAR") +IN_LOOP THING = INPUT :F(END) + THING LEN(3) ("GAR" | "BAR") :S(OK) + OUTPUT = THING " : Failure!" :(IN_LOOP) +OK OUTPUT = THING ' : "Success"!' :(IN_LOOP) +END +FOOBAR +FOOGAR +THiNIg diff --git a/tests/examplefiles/example.stan b/tests/examplefiles/example.stan new file mode 100644 index 00000000..7eb6fdfc --- /dev/null +++ b/tests/examplefiles/example.stan @@ -0,0 +1,110 @@ +/* +A file for testing Stan syntax highlighting. + +It is not a real model and will not compile +*/ +# also a comment +// also a comment +data { + // valid name + int abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_abc; + // all types should be highlighed + int a3; + real foo[2]; + vector[3] bar; + row_vector[3] baz; + matrix[3,3] qux; + simplex[3] quux; + ordered[3] corge; + positive_ordered[3] wibble; + corr_matrix[3] grault; + cov_matrix[3] garply; + cholesky_factor_cov[3] waldo; + + real<lower=-1,upper=1> foo1; + real<lower=0> foo2; + real<upper=0> foo3; +} +transformed data { + real xyzzy; + int thud; + row_vector grault2; + matrix qux2; + + // all floating point literals should be recognized + // all operators should be recognized + // paren should be recognized; + xyzzy <- 1234.5687 + .123 - (2.7e3 / 2E-5 * 135e-5); + // integer literal + thud <- -12309865; + // ./ and .* should be recognized as operators + grault2 <- grault .* garply ./ garply; + // ' and \ should be regognized as operators + qux2 <- qux' \ bar; + +} +parameters { + real fred; + real plugh; +} +transformed parameters { +} +model { + // ~, <- are operators, + // T may be be recognized + // normal is a function + fred ~ normal(0, 1) T(-0.5, 0.5); + real tmp; + // C++ reserved + real public; + + // control structures + for (i in 1:10) { + tmp <- tmp + 0.1; + } + tmp <- 0.0; + while (tmp < 5.0) { + tmp <- tmp + 1; + } + if (tmp > 0.0) { + print(tmp); + } else { + print(tmp); + } + + // operators + tmp || tmp; + tmp && tmp; + tmp == tmp; + tmp != tmp; + tmp < tmp; + tmp <= tmp; + tmp > tmp; + tmp >= tmp; + tmp + tmp; + tmp - tmp; + tmp * tmp; + tmp / tmp; + tmp .* tmp; + tmp ./ tmp; + ! tmp; + - tmp; + + tmp; + tmp '; + + // lp__ should be highlighted + // normal_log as a function + lp__ <- lp__ + normal_log(plugh, 0, 1); + increment_log_prob(normal_log(plugh, 0, 1)); + + // print statement and string literal + print("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_~@#$%^&*`'-+={}[].,;: "); + print("Hello, world!"); + print(""); + +} +generated quantities { + real bar1; + bar1 <- foo + 1; +} + diff --git a/tests/examplefiles/example.tea b/tests/examplefiles/example.tea new file mode 100644 index 00000000..6859e34d --- /dev/null +++ b/tests/examplefiles/example.tea @@ -0,0 +1,34 @@ +<% template example() {...} +a = 123 +b = "test"; +c = 4.5 +d = call other() +f = other2() + +define g as String + +h = true +i = false +j = null +%> +<html> +<head> +<title>Example<title> +<body> +<a href="http://example.com">Test link</a> +<% // Second block +if(a == 123 and b == "test") { + 'yes' +} else { + 'no' +} + +foreach(i in 1..10) { + i & "," +} + +foreach(i in #(1,2,3) reverse { + i & ";" +} + +%>
\ No newline at end of file diff --git a/tests/examplefiles/example.todotxt b/tests/examplefiles/example.todotxt new file mode 100644 index 00000000..55ee5286 --- /dev/null +++ b/tests/examplefiles/example.todotxt @@ -0,0 +1,9 @@ +(A) Call Mom @Phone +Family +(A) 2014-01-08 Schedule annual checkup +Health +(B) Outline chapter 5 +Novel @Computer +(C) Add cover sheets @Office +TPSReports +Plan backyard herb garden @Home +Pick up milk @GroceryStore +Research self-publishing services +Novel @Computer +x 2014-01-10 Download Todo.txt mobile app @Phone +x 2014-01-10 2014-01-07 Download Todo.txt CLI @Computer diff --git a/tests/examplefiles/example.ts b/tests/examplefiles/example.ts new file mode 100644 index 00000000..545c6cf5 --- /dev/null +++ b/tests/examplefiles/example.ts @@ -0,0 +1,28 @@ +class Animal { + constructor(public name) { } + move(meters) { + alert(this.name + " moved " + meters + "m."); + } +} + +class Snake extends Animal { + constructor(name) { super(name); } + move() { + alert("Slithering..."); + super.move(5); + } +} + +class Horse extends Animal { + constructor(name) { super(name); } + move() { + alert("Galloping..."); + super.move(45); + } +} + +var sam = new Snake("Sammy the Python") +var tom: Animal = new Horse("Tommy the Palomino") + +sam.move() +tom.move(34) diff --git a/tests/examplefiles/example.u b/tests/examplefiles/example.u new file mode 100644 index 00000000..42c85902 --- /dev/null +++ b/tests/examplefiles/example.u @@ -0,0 +1,548 @@ + // This is a one line comment. + /* an inner comment */ + + /* nested /* comments */ */ + + /* + /* + Multi-line. + */ + */ + +// Binary blob escape. +//"some text \B(3)("\") ouhyeah" == "\"\\\""; +"some text \B(3)("\") ouhyeah" == "\"\\\""; +'some text \B(3)('\') ouhyeah' == '\'\\\''; + +//"\B(4)()"'()"; +"\B(4)()"'()"; +'\B(4)()'"()'; + +//blob size limits +"hey ! \B(0)() oh !" + +//blob format is wrong +"hey ! \B(2)(aaa) oh !" +"hey ! \B(100)(aaa) oh !" + +//multiple blob in a string +"hey ! \B(3)(aaa) hey ! \B(3)(aaa) oh !" + +// multiple digits blob size +"hey ! \B(10)(aaaaaaaaaa) !" +"hey ! \B(10)(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa) !" +"hey ! \B(100)(a) !" + +// multiple digits blob size +"hey ! \B(007)(aaaaaaa) !" +"hey ! \B(007)(aa) !" +"hey ! \B(007)(aaaaaaaaaaaaaaaaaa) !" + +// deprecated and restricted keyworks +emit Event.new; +static int main(); + +loopn (2) {echo("a");}; + +foreach (var i : [1,2,3,4]) { + echo(i); +}; + +function() {}; + +var 'if'; +var this.'else'; + +var '%x'; +var '1 2 3'; +var this.'[]'; + +// angles +pi == 180deg; +pi == 200grad; + +// Dictionary +[ => ]; // The empty dictionary + +// duration +1d == 24h; +0.5d == 12h; +1h == 60min; +1min == 60s; +1s == 1000ms; + +1s == 1; +1s 2s 3s == 6; +1s 1ms == 1.001; +1ms 1s == 1.001; + + + 1 == 1; + 1 == 1.0; + 1.2 == 1.2000; + 1.234e6 == 1234000; + 1e+11 == 1E+11; + 1e10 == 10000000000; + 1e30 == 1e10 * 1e10 * 1e10; + + +0.000001; + +0.0000001; + +0.00000000001; + +1e+3; + +1E-5; + + +1.; +// [00004701:error] !!! syntax error: unexpected ; + + 0x2a == 42; + 0x2A == 42; + 0xabcdef == 11259375; + 0xABCDEF == 11259375; +0xFFFFFFFF == 4294967295; + + +//123foo; +//[00005658:error] !!! syntax error: invalid token: '123foo' +//12.3foo; +//[00018827:error] !!! syntax error: invalid token: '12.3foo' +0xabcdef; +//[00060432] 11259375 +//0xabcdefg; +//[00061848:error] !!! syntax error: invalid token: '0xabcdefg' + + +[]; // The empty list +[1, 2, 3]; + +// Special characters. +"\"" == "\""; +"\\" == "\\"; + +// ASCII characters. +"\a" == "\007"; "\a" == "\x07"; +"\b" == "\010"; "\b" == "\x08"; +"\f" == "\014"; "\f" == "\x0c"; +"\n" == "\012"; "\n" == "\x0a"; +"\r" == "\015"; "\r" == "\x0d"; +"\t" == "\011"; "\t" == "\x09"; +"\v" == "\013"; "\v" == "\x0b"; + +// Octal escapes. +"\0" == "\00"; "\0" == "\000"; +"\0000" == "\0""0"; +"\062\063" == "23"; + +// Hexadecimal escapes. +"\x00" == "\0"; +"\x32\x33" == "23"; + + + +"foo" "bar" "baz" == "foobarbaz"; + +// Tuples +(); +[00000000] () +(1,); +[00000000] (1,) +(1, 2); +[00000000] (1, 2) +(1, 2, 3, 4,); +[00000000] (1, 2, 3, 4) + +function Global.verboseId(var x) +{ + echo(x) | x +}|; +class verboseId(Global).math : verboseId(Math) +{ +}; + +{ + for (3) + { + sleep(1s); + echo("ping"); + }, + sleep(0.5s); + for (3) + { + sleep(1s); + echo("pong"); + }, +}; + + 1 + 1 == 2; + 1 - 2 == -1; + 2 * 3 == 6; + 10 / 2 == 5; + 2 ** 10 == 1024; + -(1 + 2) == -3; + 1 + 2 * 3 == 7; + (1 + 2) * 3 == 9; + -2 ** 2 == -4; + - - - - 1 == 1; + +a = b +a += b +a -= b +a *= b +a /= b +a %= b +a ^= b + + +var value = 0|; +var valueAlias = value|; +value += 10; +valueAlias; +var myList = []|; +var myList.specialFeature = 42|; +myList += [1, 2, 3]; +myList.specialFeature; +var myOtherList = myList + [4, 5]; +myOtherList.specialFeature; +var something = []|; +var somethingElse = something|; +something += [1, 2]; +somethingElse += [3, 4]; +something; + + +class Counter +{ + var count = 0; + function init (n) { var this.count = n }; + // Display the value, and the identity. + function asString() { "%s @ %s" % [count, uid ] }; + function '+'(var n) { new(count + n) }; + function '-'(var n) { new(count - n) }; +}|; + + +class ImmutableCounter : Counter +{ + function '+='(var n) { this + n }; + function '-='(var n) { this - n }; +}|; + +var ic1 = ImmutableCounter.new(0); +var ic2 = ic1; + +ic1 += 1; +ic1; +ic2; + + +a << b +a >> b +a ^ b + +4 << 2 == 16; +4 >> 2 == 1; + +!a +a && b +a || b + +true && true; +true || false; +!true == false; +true || (1 / 0); +(false && (1 / 0)) == false; + +a == b +a != b +a === b +a !== b +a ~= b +a =~= b +a < b +a <= b +a > b +a >= b + +assert{ + ! (0 < 0); + 0 <= 0; + 0 == 0; + 0 !== 0; +}; + +a in b +a not in b +a[args] +a[args] = v + +1 in [0, 1, 2]; +3 not in [0, 1, 2]; + +"one" in ["zero" => 0, "one" => 1, "two" => 2]; +"three" not in ["zero" => 0, "one" => 1, "two" => 2]; + +a.b +a.b(args) +a->b +a->b = v +a.&b + +var obj = Object.new|; +function obj.f() { 24 }|; + + +var f = function(a, b) { + echo(b + a); +}| +f(1, 0); + + +function g3() +{ + return; // Stop execution at this point and return void + echo(0); // This is not executed +}| + +Object.setProperty, to define/set a property. +Object.getProperty, to get a property. +Object.removeProperty, to delete a property. +Object.hasProperty, to test for the existence of a property. +Object.properties, to get all the properties of a slot. + +enum Suit +{ + hearts, + diamonds, + clubs, + spades, // Last comma is optional +}; + +for (var suit in Suit) + echo("%s the ace of %s." % [find_ace(suit), suit]); + +switch ( ("foo", [1, 2]) ) +{ + // The pattern does not match the values of the list. + case ("foo", [2, 1]): + echo("fail"); + + // The pattern does not match the tuple. + case ["foo", [1, 2]]: + echo("fail"); + + // The pattern matches and binds the variable "l" + // but the condition is not verified. + case ("foo", var l) if l.size == 0: + echo("fail"); + + // The pattern matches. + case ("foo", [var a, var b]): + echo("foo(%s, %s)" % [a, b]); +}; +//[00000000] *** foo(1, 2) + +{ + ["b" => var b, "a" => var a] = ["a" => 1, "b" => 2, "c" => 3]; + echo("a = %d, b = %d" % [a, b]); +}; +//[00000000] *** a = 1, b = 2 + + +switch (["speed" => 2, "time" => 6s]) +{ + case ["speed" => var s] if s > 3: + echo("Too fast"); + case ["speed" => var s, "time" => var t] if s * t > 10: + echo("Too far"); +}; +//[00000000] *** Too far + + +try +{ + throw ("message", 0) +} +catch (var e if e.isA(Exception)) +{ + echo(e.message) +} +catch ((var msg, var value) if value.isA(Float)) +{ + echo("%s: %d" % [msg, value]) +}; +//[00000000] *** message: 0 + + +{ + var e = Event.new; + at (e?(var msg, var value) if value % 2 == 0) + echo("%s: %d" % [msg, value]); + + // Does not trigger the "at" because the guard is not verified. + e!("message", 1); + + // Trigger the "at". + e!("message", 2); +}; +//[00000000] *** message: 2 + +for (var i = 0; i < 8; i++) +{ + if (i % 2 != 0) + continue; + echo(i); +}; + +do (1024) +{ + assert(this == 1024); + assert(sqrt == 32); + setSlot("y", 23); +}.y; + +{ + var n = 10|; + var res = []|; + loop;{ + n--; + res << n; + if (n == 0) + break + }; + res +} + + +{ + var n = 10|; + var res = []|; + loop|{ + n--; + res << n; + if (n == 0) + break + }; + res +} + + +var j = 3| +while (0 < j) +{ + echo(j); + j--; +}; + + +{ + var i = 4| + while| (true) + { + i -= 1; + echo ("in: " + i); + if (i == 1) + break + else if (i == 2) + continue; + echo ("out: " + i); + }; +}; + + + +function test(e) +{ + try + { throw e; } + catch (0) + { echo("zero") } + catch ([var x, var y]) + { echo(x + y) } +} | {}; + +try { echo("try") } +catch { echo("catch")} +else { echo("else")}; + + +try +{ + echo("inside"); +} +finally +{ + echo("finally"); +}; +//[00000001] *** inside +//[00000002] *** finally + +at (e?(var start) ~ 1s) + echo("in : %s" % (time - start).round) +onleave + echo("out: %s" % (time - start).round); + +// This emission is too short to trigger the at. +e!(time); + +// This one is long enough. +// The body triggers 1s after the emission started. +e!(time) ~ 2s; +//[00001000] *** in : 1 +//[00002000] *** out: 2 + + +timeout (2.1s) + every (1s) + echo("Are you still there?"); +//[00000000] *** Are you still there? +//[00001000] *** Are you still there? +//[00002000] *** Are you still there? + + every| (1s) + { + echo("aba"); + }; + +for, (var i = 3; 0 < i; i -= 1) +{ + echo (i); +}; + + +for& (var i: [0, 1, 2]) +{ + echo (i * i); +}; + +loop,{ +}; + + +waituntil (e?(1, var b)); + +whenever (e?("arg", var arg) if arg % 2) + echo("e (%s) on" % arg) +else + echo("e off"); + + + while, (i) + { + var j = i -= 1; + }| + + +var y = 0; +{ + sleep(0.5s); + y = 100 smooth:3s, +}, + + + + diff --git a/tests/examplefiles/example.xtend b/tests/examplefiles/example.xtend new file mode 100644 index 00000000..f6a51f7a --- /dev/null +++ b/tests/examplefiles/example.xtend @@ -0,0 +1,34 @@ +package beer + +import static extension beer.BottleSupport.* +import org.junit.Test + +class BottleSong { + + @Test + def void singIt() { + println(singTheSong(99)) + } + + def singTheSong(int all) ''' + FOR i : all .. 1 + i.Bottles of beer on the wall, i.bottles of beer. + Take one down and pass it around, (i - 1).bottles of beer on the wall. + + ENDFOR + No more bottles of beer on the wall, no more bottles of beer. + Go to the store and buy some more, all.bottles of beer on the wall. + ''' + + def private java.lang.String bottles(int i) { + switch i { + case 0 : 'no more bottles' + case 1 : 'one bottle' + default : '''i bottles''' + }.toString + } + + def String Bottles(int i) { + bottles(i).toFirstUpper + } +}
\ No newline at end of file diff --git a/tests/examplefiles/example2.msc b/tests/examplefiles/example2.msc new file mode 100644 index 00000000..61e2ef83 --- /dev/null +++ b/tests/examplefiles/example2.msc @@ -0,0 +1,79 @@ +#!/usr/bin/mscgen -Tpng +# +# testinput2.msc : Sample msc input file with URLs +# +# This file is PUBLIC DOMAIN and may be freely reproduced, distributed, +# transmitted, used, modified, built upon, or otherwise exploited by +# anyone for any purpose, commercial or non-commercial, and in any way, +# including by methods that have not yet been invented or conceived. +# +# This file is provided "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER +# EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +# + +# Note: This is from mscgen-0.20 + +msc { + +A,B; + +--- [label="Start", ID="1"]; + +A->B [label="signal"]; +A<-B [label="signal"]; + + +A=>B [label="method"]; +A<=B [label="method"]; + +A>>B [label="return"]; +A<<B [label="return"]; + +A=>>B [label="call-back"]; +A<<=B [label="call-back", URL="www.google.com"]; + +A x- B [label="loss"]; +A -x B [label="loss"]; + +--- [label="Left arcs", ID="2", IDURL="www.google.co.uk"]; + +A->A [label="signal"]; +A<-A [label="signal"]; + + +A=>A [label="method"]; +A<=A [label="method"]; + +A>>A [label="return"]; +A<<A [label="return"]; + +A=>>A [label="call-back"]; +A<<=A [label="call-back", URL="www.google.com", ID="3"]; + +A x- A [label="loss"]; +A -x A [label="loss"]; + +--- [label="Right arcs"]; + +B->B [label="signal"]; +B<-B [label="signal"]; + + +B=>B [label="method"]; +B<=B [label="method"]; + +B>>B [label="return"]; +B<<B [label="return"]; + +B=>>B [label="call-back", ID="4"]; +B<<=B [label="call-back", URL="www.google.com"]; + +B x- B [label="loss"]; +B -x B [label="loss"]; + +--- [label="End of arcs", URL="www.google.com"]; + + +... [label="Some time passes", URL="www.google.com"]; +} diff --git a/tests/examplefiles/exampleScript.cfc b/tests/examplefiles/exampleScript.cfc new file mode 100644 index 00000000..002acbcd --- /dev/null +++ b/tests/examplefiles/exampleScript.cfc @@ -0,0 +1,241 @@ +<cfscript>
+/**
+********************************************************************************
+ContentBox - A Modular Content Platform
+Copyright 2012 by Luis Majano and Ortus Solutions, Corp
+www.gocontentbox.org | www.luismajano.com | www.ortussolutions.com
+********************************************************************************
+Apache License, Version 2.0
+
+Copyright Since [2012] [Luis Majano and Ortus Solutions,Corp]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+********************************************************************************
+* A generic content service for content objects
+*/
+component extends="coldbox.system.orm.hibernate.VirtualEntityService" singleton{
+
+ // DI
+ property name="settingService" inject="id:settingService@cb";
+ property name="cacheBox" inject="cachebox";
+ property name="log" inject="logbox:logger:{this}";
+ property name="customFieldService" inject="customFieldService@cb";
+ property name="categoryService" inject="categoryService@cb";
+ property name="commentService" inject="commentService@cb";
+ property name="contentVersionService" inject="contentVersionService@cb";
+ property name="authorService" inject="authorService@cb";
+ property name="populator" inject="wirebox:populator";
+ property name="systemUtil" inject="SystemUtil@cb";
+
+ /*
+ * Constructor
+ * @entityName.hint The content entity name to bind this service to.
+ */
+ ContentService function init(entityName="cbContent"){
+ // init it
+ super.init(entityName=arguments.entityName, useQueryCaching=true);
+
+ // Test scope coloring in pygments
+ this.colorTestVar = "Just for testing pygments!";
+ cookie.colorTestVar = "";
+ client.colorTestVar = ""
+ session.colorTestVar = "";
+ application.colorTestVar = "";
+
+ return this;
+ }
+
+ /**
+ * Clear all content caches
+ * @async.hint Run it asynchronously or not, defaults to false
+ */
+ function clearAllCaches(boolean async=false){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clearByKeySnippet(keySnippet="cb-content",async=arguments.async);
+ return this;
+ }
+
+ /**
+ * Clear all page wrapper caches
+ * @async.hint Run it asynchronously or not, defaults to false
+ */
+ function clearAllPageWrapperCaches(boolean async=false){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clearByKeySnippet(keySnippet="cb-content-pagewrapper",async=arguments.async);
+ return this;
+ }
+
+ /**
+ * Clear all page wrapper caches
+ * @slug.hint The slug partial to clean on
+ * @async.hint Run it asynchronously or not, defaults to false
+ */
+ function clearPageWrapperCaches(required any slug, boolean async=false){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clearByKeySnippet(keySnippet="cb-content-pagewrapper-#arguments.slug#",async=arguments.async);
+ return this;
+ }
+
+ /**
+ * Clear a page wrapper cache
+ * @slug.hint The slug to clean
+ * @async.hint Run it asynchronously or not, defaults to false
+ */
+ function clearPageWrapper(required any slug, boolean async=false){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clear("cb-content-pagewrapper-#arguments.slug#/");
+ return this;
+ }
+
+ /**
+ * Searches published content with cool paramters, remember published content only
+ * @searchTerm.hint The search term to search
+ * @max.hint The maximum number of records to paginate
+ * @offset.hint The offset in the pagination
+ * @asQuery.hint Return as query or array of objects, defaults to array of objects
+ * @sortOrder.hint The sorting of the search results, defaults to publishedDate DESC
+ * @isPublished.hint Search for published, non-published or both content objects [true, false, 'all']
+ * @searchActiveContent.hint Search only content titles or both title and active content. Defaults to both.
+ */
+ function searchContent(
+ any searchTerm="",
+ numeric max=0,
+ numeric offset=0,
+ boolean asQuery=false,
+ any sortOrder="publishedDate DESC",
+ any isPublished=true,
+ boolean searchActiveContent=true){
+
+ var results = {};
+ var c = newCriteria();
+
+ // only published content
+ if( isBoolean( arguments.isPublished ) ){
+ // Published bit
+ c.isEq( "isPublished", javaCast( "Boolean", arguments.isPublished ) );
+ // Published eq true evaluate other params
+ if( arguments.isPublished ){
+ c.isLt("publishedDate", now() )
+ .$or( c.restrictions.isNull("expireDate"), c.restrictions.isGT("expireDate", now() ) )
+ .isEq("passwordProtection","");
+ }
+ }
+
+ // Search Criteria
+ if( len( arguments.searchTerm ) ){
+ // like disjunctions
+ c.createAlias("activeContent","ac");
+ // Do we search title and active content or just title?
+ if( arguments.searchActiveContent ){
+ c.$or( c.restrictions.like("title","%#arguments.searchTerm#%"),
+ c.restrictions.like("ac.content", "%#arguments.searchTerm#%") );
+ }
+ else{
+ c.like( "title", "%#arguments.searchTerm#%" );
+ }
+ }
+
+ // run criteria query and projections count
+ results.count = c.count( "contentID" );
+ results.content = c.resultTransformer( c.DISTINCT_ROOT_ENTITY )
+ .list(offset=arguments.offset, max=arguments.max, sortOrder=arguments.sortOrder, asQuery=arguments.asQuery);
+
+ return results;
+ }
+
+/********************************************* PRIVATE *********************************************/
+
+
+ /**
+ * Update the content hits
+ * @contentID.hint The content id to update
+ */
+ private function syncUpdateHits(required contentID){
+ var q = new Query(sql="UPDATE cb_content SET hits = hits + 1 WHERE contentID = #arguments.contentID#").execute();
+ return this;
+ }
+
+
+ private function closureTest(){
+ methodCall(
+ param1,
+ function( arg1, required arg2 ){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clear("cb-content-pagewrapper-#arguments.slug#/");
+ return this;
+ },
+ param1
+ );
+ }
+
+ private function StructliteralTest(){
+ return {
+ foo = bar,
+ brad = 'Wood',
+ func = function( arg1, required arg2 ){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clear("cb-content-pagewrapper-#arguments.slug#/");
+ return this;
+ },
+ array = [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 'test',
+ 'testing',
+ 'testerton',
+ {
+ foo = true,
+ brad = false,
+ wood = null
+ }
+ ],
+ last = "final"
+ };
+ }
+
+ private function arrayliteralTest(){
+ return [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 'test',
+ 'testing',
+ 'testerton',
+ {
+ foo = true,
+ brad = false,
+ wood = null
+ },
+ 'testy-von-testavich'
+ ];
+ }
+
+}
+</cfscript>
\ No newline at end of file diff --git a/tests/examplefiles/exampleTag.cfc b/tests/examplefiles/exampleTag.cfc new file mode 100644 index 00000000..753bb826 --- /dev/null +++ b/tests/examplefiles/exampleTag.cfc @@ -0,0 +1,18 @@ +<cfcomponent>
+
+ <cffunction name="init" access="public" returntype="any">
+ <cfargument name="arg1" type="any" required="true">
+ <cfset this.myVariable = arguments.arg1>
+
+ <cfreturn this>
+ </cffunction>
+
+ <cffunction name="testFunc" access="private" returntype="void">
+ <cfargument name="arg1" type="any" required="false">
+
+ <cfif structKeyExists(arguments, "arg1")>
+ <cfset writeoutput("Argument exists")>
+ </cfif>
+ </cffunction>
+
+</cfcomponent>
\ No newline at end of file diff --git a/tests/examplefiles/example_elixir.ex b/tests/examplefiles/example_elixir.ex new file mode 100644 index 00000000..e3ce7816 --- /dev/null +++ b/tests/examplefiles/example_elixir.ex @@ -0,0 +1,365 @@ +# We cannot use to_char_list because it depends on inspect, +# which depends on protocol, which depends on this module. +import Elixir::Builtin, except: [to_char_list: 1] + +defmodule Module do + require Erlang.ets, as: ETS + + @moduledoc """ + This module provides many functions to deal with modules during + compilation time. It allows a developer to dynamically attach + documentation, merge data, register attributes and so forth. + + After the module is compiled, using many of the functions in + this module will raise errors, since it is out of their purpose + to inspect runtime data. Most of the runtime data can be inspected + via the `__info__(attr)` function attached to each compiled module. + """ + + @doc """ + Evalutes the quotes contents in the given module context. + Raises an error if the module was already compiled. + + ## Examples + + defmodule Foo do + contents = quote do: (def sum(a, b), do: a + b) + Module.eval_quoted __MODULE__, contents, [], __FILE__, __LINE__ + end + + Foo.sum(1, 2) #=> 3 + """ + def eval_quoted(module, quoted, binding, filename, line) do + assert_not_compiled!(:eval_quoted, module) + { binding, scope } = Erlang.elixir_module.binding_and_scope_for_eval(line, to_char_list(filename), module, binding) + Erlang.elixir_def.reset_last(module) + Erlang.elixir.eval_quoted([quoted], binding, line, scope) + end + + @doc """ + Checks if the module is compiled or not. + + ## Examples + + defmodule Foo do + Module.compiled?(__MODULE__) #=> false + end + + Module.compiled?(Foo) #=> true + + """ + def compiled?(module) do + table = data_table_for(module) + table == ETS.info(table, :name) + end + + @doc """ + Reads the data for the given module. This is used + to read data of uncompiled modules. If the module + was already compiled, you shoul access the data + directly by invoking `__info__(:data)` in that module. + + ## Examples + + defmodule Foo do + Module.merge_data __MODULE__, value: 1 + Module.read_data __MODULE__ #=> [value: 1] + end + + """ + def read_data(module) do + assert_not_compiled!(:read_data, module) + ETS.lookup_element(data_table_for(module), :data, 2) + end + + @doc """ + Reads the data from `module` at the given key `at`. + + ## Examples + + defmodule Foo do + Module.merge_data __MODULE__, value: 1 + Module.read_data __MODULE__, :value #=> 1 + end + + """ + def read_data(module, at) do + Orddict.get read_data(module), at + end + + @doc """ + Merge the given data into the module, overriding any + previous one. + + If any of the given data is a registered attribute, it is + automatically added to the attribute set, instead of marking + it as data. See register_attribute/2 and add_attribute/3 for + more info. + + ## Examples + + defmodule Foo do + Module.merge_data __MODULE__, value: 1 + end + + Foo.__info__(:data) #=> [value: 1] + + """ + def merge_data(module, data) do + assert_not_compiled!(:merge_data, module) + + table = data_table_for(module) + old = ETS.lookup_element(table, :data, 2) + registered = ETS.lookup_element(table, :registered_attributes, 2) + + { attrs, new } = Enum.partition data, fn({k,_}) -> List.member?(registered, k) end + Enum.each attrs, fn({k,v}) -> add_attribute(module, k, v) end + ETS.insert(table, { :data, Orddict.merge(old, new) }) + end + + @doc """ + Attaches documentation to a given function. It expects + the module the function belongs to, the line (a non negative + integer), the kind (def or defmacro), a tuple representing + the function and its arity and the documentation, which should + be either a binary or a boolean. + + ## Examples + + defmodule MyModule do + Module.add_doc(__MODULE__, __LINE__ + 1, :def, { :version, 0 }, "Manually added docs") + def version, do: 1 + end + + """ + def add_doc(module, line, kind, tuple, doc) when + is_binary(doc) or is_boolean(doc) do + assert_not_compiled!(:add_doc, module) + case kind do + match: :defp + :warn + else: + table = docs_table_for(module) + ETS.insert(table, { tuple, line, kind, doc }) + :ok + end + end + + @doc """ + Checks if a function was defined, regardless if it is + a macro or a private function. Use function_defined?/3 + to assert for an specific type. + + ## Examples + + defmodule Example do + Module.function_defined? __MODULE__, { :version, 0 } #=> false + def version, do: 1 + Module.function_defined? __MODULE__, { :version, 0 } #=> true + end + + """ + def function_defined?(module, tuple) when is_tuple(tuple) do + assert_not_compiled!(:function_defined?, module) + table = function_table_for(module) + ETS.lookup(table, tuple) != [] + end + + @doc """ + Checks if a function was defined and also for its `kind`. + `kind` can be either :def, :defp or :defmacro. + + ## Examples + + defmodule Example do + Module.function_defined? __MODULE__, { :version, 0 }, :defp #=> false + def version, do: 1 + Module.function_defined? __MODULE__, { :version, 0 }, :defp #=> false + end + + """ + def function_defined?(module, tuple, kind) do + List.member? defined_functions(module, kind), tuple + end + + @doc """ + Return all functions defined in the given module. + + ## Examples + + defmodule Example do + def version, do: 1 + Module.defined_functions __MODULE__ #=> [{:version,1}] + end + + """ + def defined_functions(module) do + assert_not_compiled!(:defined_functions, module) + table = function_table_for(module) + lc { tuple, _, _ } in ETS.tab2list(table), do: tuple + end + + @doc """ + Returns all functions defined in te given module according + to its kind. + + ## Examples + + defmodule Example do + def version, do: 1 + Module.defined_functions __MODULE__, :def #=> [{:version,1}] + Module.defined_functions __MODULE__, :defp #=> [] + end + + """ + def defined_functions(module, kind) do + assert_not_compiled!(:defined_functions, module) + table = function_table_for(module) + entry = kind_to_entry(kind) + ETS.lookup_element(table, entry, 2) + end + + @doc """ + Adds a compilation callback hook that is invoked + exactly before the module is compiled. + + This callback is useful when used with `use` as a mechanism + to clean up any internal data in the module before it is compiled. + + ## Examples + + Imagine you are creating a module/library that is meant for + external usage called `MyLib`. It could be defined as: + + defmodule MyLib do + def __using__(target) do + Module.merge_data target, some_data: true + Module.add_compile_callback(target, __MODULE__, :__callback__) + end + + defmacro __callback__(target) do + value = Orddict.get(Module.read_data(target), :some_data, []) + quote do: (def my_lib_value, do: unquote(value)) + end + end + + And a module could use `MyLib` with: + + defmodule App do + use ModuleTest::ToBeUsed + end + + In the example above, `MyLib` defines a data to the target. This data + can be updated throughout the module definition and therefore, the final + value of the data can only be compiled using a compiation callback, + which will read the final value of :some_data and compile to a function. + """ + def add_compile_callback(module, target, fun // :__compiling__) do + assert_not_compiled!(:add_compile_callback, module) + new = { target, fun } + table = data_table_for(module) + old = ETS.lookup_element(table, :compile_callbacks, 2) + ETS.insert(table, { :compile_callbacks, [new|old] }) + end + + @doc """ + Adds an Erlang attribute to the given module with the given + key and value. The same attribute can be added more than once. + + ## Examples + + defmodule MyModule do + Module.add_attribute __MODULE__, :custom_threshold_for_lib, 10 + end + + """ + def add_attribute(module, key, value) when is_atom(key) do + assert_not_compiled!(:add_attribute, module) + table = data_table_for(module) + attrs = ETS.lookup_element(table, :attributes, 2) + ETS.insert(table, { :attributes, [{key, value}|attrs] }) + end + + @doc """ + Deletes all attributes that matches the given key. + + ## Examples + + defmodule MyModule do + Module.add_attribute __MODULE__, :custom_threshold_for_lib, 10 + Module.delete_attribute __MODULE__, :custom_threshold_for_lib + end + + """ + def delete_attribute(module, key) when is_atom(key) do + assert_not_compiled!(:delete_attribute, module) + table = data_table_for(module) + attrs = ETS.lookup_element(table, :attributes, 2) + final = lc {k,v} in attrs, k != key, do: {k,v} + ETS.insert(table, { :attributes, final }) + end + + @doc """ + Registers an attribute. This allows a developer to use the data API + but Elixir will register the data as an attribute automatically. + By default, `vsn`, `behavior` and other Erlang attributes are + automatically registered. + + ## Examples + + defmodule MyModule do + Module.register_attribute __MODULE__, :custom_threshold_for_lib + @custom_threshold_for_lib 10 + end + + """ + def register_attribute(module, new) do + assert_not_compiled!(:register_attribute, module) + table = data_table_for(module) + old = ETS.lookup_element(table, :registered_attributes, 2) + ETS.insert(table, { :registered_attributes, [new|old] }) + end + + @doc false + # Used internally to compile documentation. This function + # is private and must be used only internally. + def compile_doc(module, line, kind, pair) do + case read_data(module, :doc) do + match: nil + # We simply discard nil + match: doc + result = add_doc(module, line, kind, pair, doc) + merge_data(module, doc: nil) + result + end + end + + ## Helpers + + defp kind_to_entry(:def), do: :public + defp kind_to_entry(:defp), do: :private + defp kind_to_entry(:defmacro), do: :macros + + defp to_char_list(list) when is_list(list), do: list + defp to_char_list(bin) when is_binary(bin), do: binary_to_list(bin) + + defp data_table_for(module) do + list_to_atom Erlang.lists.concat([:d, module]) + end + + defp function_table_for(module) do + list_to_atom Erlang.lists.concat([:f, module]) + end + + defp docs_table_for(module) do + list_to_atom Erlang.lists.concat([:o, module]) + end + + defp assert_not_compiled!(fun, module) do + compiled?(module) || + raise ArgumentError, message: + "could not call #{fun} on module #{module} because it was already compiled" + end +end + +HashDict.new [{'A', 0}, {'T', 0}, {'C', 0}, {'G', 0}] diff --git a/tests/examplefiles/example_file.fy b/tests/examplefiles/example_file.fy new file mode 100644 index 00000000..43e80c1d --- /dev/null +++ b/tests/examplefiles/example_file.fy @@ -0,0 +1,128 @@ +class Person { + def initialize: @name age: @age { + """ + This is a docstring for the Person constructor method. + Docstrings usually are multi-line, like this one. + """ + } + + def to_s { + # return is optional in this case, but we use it nontheless + return "Person with name: #{@name inspect} and age: #{@age}" + } +} + +class PersonWithCity : Person { + def initialize: @name age: @age city: @city { + } + + def to_s { + super to_s ++ " living in: #{@city inspect}" + } +} + +p1 = Person new: "Johnny Jackson" age: 42 +p1 println # prints: Person with name: "Johnny Jackson" and age: 42 + +p2 = PersonWithCity new: "John Appleseed" age: 55 city: "New York" +p2 println # prints: Person with name: "John Appleseed" age: 55 living in: "New York" + +array = [1,2,3, "foo", 'bar] +hash = <['foo => "bar", 'bar => 42]> +tuple = (1,2,"hello","world") +block = |x, y| { + x + y println +} +block call: [4,2] + +0b010101 & 0b00101 to_s: 2 . println +0xFF & 0xAB to_s: 16 . println +0o77 > 0o76 println +123.123 + 0.222 println + +x = 0 +try { + 10 / x println +} catch ZeroDivisionError => e { + x = 3 + retry +} finally { + "Finally, done!" println +} + +def a_method: arg1 with_default_arg: arg2 (42) { + arg1 * arg2 println +} + +a_method: 42 +a_method: 42 with_default_arg: 85 + +class ClassWithClassMethod { + def self class_method1 { + 'works + } + + def ClassWithClassMethod class_method2 { + 'this_as_well + } +} + +ClassWithClassMethod class_method1 println +ClassWithClassMethod class_method2 println + +def another_method: block { + 1 upto: 10 . map: block +} + +# local returns +another_method: |x| { return_local x * 2 } . inspect println + + +# pattern matching: +class PatternMatching { + def match_it: obj { + match obj { + case String -> "It's a String!" println + case Fixnum -> "It's a Number!" println + case _ -> "Aything else!" println + } + } + + def match_with_extract: str { + match str { + # m holds the MatchData object, m1 & m2 the first and second matches + case /^(.*) : (.*)$/ -> |m, m1, m2| + "First match: #{m1}" println + "Second match: #{m2}" println + } + } +} + +pm = PatternMatching new +pm match_it: "foo" +pm match_it: 42 +pm match_it: 'foo + +pm match_with_extract: "Hello : World!" + + +# calling ruby methods: +[3, 2, 1] reverse() each() |a| { puts(a) } +"Hello" sub("ll", "y") println +[3, 2, 1] map() |a| { a * 2 } inject(0) |s i| { s + i } println + +# test symbol highlighting +['foo] +['foo?!] +{'foo} +{'foo!?} +{'foo:bar?!=&/:} +('foo) + +# future sends +42 @ to_s class println +42 @ to_s: 16 . value println + +# async sends +42 @@ println +42 @@ upto: 100 diff --git a/tests/examplefiles/foo.sce b/tests/examplefiles/foo.sce new file mode 100644 index 00000000..0e5d6afe --- /dev/null +++ b/tests/examplefiles/foo.sce @@ -0,0 +1,6 @@ +// Scilab +// +disp(%pi); + +assert_checkequal(2+2,4); + diff --git a/tests/examplefiles/function.mu b/tests/examplefiles/function.mu new file mode 100644 index 00000000..46bb259d --- /dev/null +++ b/tests/examplefiles/function.mu @@ -0,0 +1 @@ +a::b () diff --git a/tests/examplefiles/function_arrows.coffee b/tests/examplefiles/function_arrows.coffee new file mode 100644 index 00000000..cd1ef1e8 --- /dev/null +++ b/tests/examplefiles/function_arrows.coffee @@ -0,0 +1,11 @@ +methodA:-> 'A' +methodB:=> 'B' +methodC:()=> 'C' +methodD:()-> 'D' +methodE:(a,b)-> 'E' +methodF:(c,d)-> 'F' +-> 'G' +=> 'H' + +(-> 'I') +(=> 'J') diff --git a/tests/examplefiles/garcia-wachs.kk b/tests/examplefiles/garcia-wachs.kk new file mode 100644 index 00000000..91a01fbe --- /dev/null +++ b/tests/examplefiles/garcia-wachs.kk @@ -0,0 +1,133 @@ +// Koka language test module
+
+// This module implements the GarsiaWachs algorithm.
+// It is an adaptation of the algorithm in ML as described by JeanChristophe Filli�tre:
+// in ''A functional implementation of the GarsiaWachs algorithm. (functional pearl). ML workshop 2008, pages 91--96''.
+// See: http://www.lri.fr/~filliatr/publis/gwWml08.pdf
+//
+// The algorithm is interesting since it uses mutable references shared between a list and tree but the
+// side effects are not observable from outside. Koka automatically infers that the final algorithm is pure.
+// Note: due to a current limitation in the divergence analysis, koka cannot yet infer that mutually recursive
+// definitions in "insert" and "extract" are terminating and the final algorithm still has a divergence effect.
+// However, koka does infer that no other effect (i.e. an exception due to a partial match) can occur.
+module garcsiaWachs
+
+import test = qualified std/flags
+
+# pre processor test
+
+public function main() {
+ wlist = Cons1(('a',3), [('b',2),('c',1),('d',4),('e',5)])
+ tree = wlist.garsiaWachs()
+ tree.show.println()
+}
+
+//----------------------------------------------------
+// Trees
+//----------------------------------------------------
+public type tree<a> {
+ con Leaf(value :a)
+ con Node(left :tree<a>, right :tree<a>)
+}
+
+function show( t : tree<char> ) : string {
+ match(t) {
+ Leaf(c) -> core/show(c)
+ Node(l,r) -> "Node(" + show(l) + "," + show(r) + ")"
+ }
+}
+
+
+//----------------------------------------------------
+// Non empty lists
+//----------------------------------------------------
+public type list1<a> {
+ Cons1( head : a, tail : list<a> )
+}
+
+function map( xs, f ) {
+ val Cons1(y,ys) = xs
+ return Cons1(f(y), core/map(ys,f))
+}
+
+function zip( xs :list1<a>, ys :list1<b> ) : list1<(a,b)> {
+ Cons1( (xs.head, ys.head), zip(xs.tail, ys.tail))
+}
+
+
+//----------------------------------------------------
+// Phase 1
+//----------------------------------------------------
+
+function insert( after : list<(tree<a>,int)>, t : (tree<a>,int), before : list<(tree<a>,int)> ) : div tree<a>
+{
+ match(before) {
+ Nil -> extract( [], Cons1(t,after) )
+ Cons(x,xs) -> {
+ if (x.snd < t.snd) then return insert( Cons(x,after), t, xs )
+ match(xs) {
+ Nil -> extract( [], Cons1(x,Cons(t,after)) )
+ Cons(y,ys) -> extract( ys, Cons1(y,Cons(x,Cons(t,after))) )
+ }
+ }
+ }
+}
+
+function extract( before : list<(tree<a>,int)>, after : list1<(tree<a>,int)> ) : div tree<a>
+{
+ val Cons1((t1,w1) as x, xs ) = after
+ match(xs) {
+ Nil -> t1
+ Cons((t2,w2) as y, ys) -> match(ys) {
+ Nil -> insert( [], (Node(t1,t2), w1+w2), before )
+ Cons((_,w3),_zs) ->
+ if (w1 <= w3)
+ then insert(ys, (Node(t1,t2), w1+w2), before)
+ else extract(Cons(x,before), Cons1(y,ys))
+ }
+ }
+}
+
+function balance( xs : list1<(tree<a>,int)> ) : div tree<a> {
+ extract( [], xs )
+}
+
+//----------------------------------------------------
+// Phase 2
+//----------------------------------------------------
+
+function mark( depth :int, t :tree<(a,ref<h,int>)> ) : <write<h>> () {
+ match(t) {
+ Leaf((_,d)) -> d := depth
+ Node(l,r) -> { mark(depth+1,l); mark(depth+1,r) }
+ }
+}
+
+function build( depth :int, xs :list1<(a,ref<h,int>)> ) : <read<h>,div> (tree<a>,list<(a,ref<h,int>)>)
+{
+ if (!(xs.head.snd) == depth) return (Leaf(xs.head.fst), xs.tail)
+
+ l = build(depth+1, xs)
+ match(l.snd) {
+ Nil -> (l.fst, Nil)
+ Cons(y,ys) -> {
+ r = build(depth+1, Cons1(y,ys))
+ (Node(l.fst,r.fst), r.snd)
+ }
+ }
+}
+
+//----------------------------------------------------
+// Main
+//----------------------------------------------------
+
+public function garsiaWachs( xs : list1<(a,int)> ) : div tree<a>
+{
+ refs = xs.map(fst).map( fun(x) { (x, ref(0)) } )
+ wleafs = zip( refs.map(Leaf), xs.map(snd) )
+
+ tree = balance(wleafs)
+ mark(0,tree)
+ build(0,refs).fst
+}
+
diff --git a/tests/examplefiles/grammar-test.p6 b/tests/examplefiles/grammar-test.p6 new file mode 100644 index 00000000..28107f3e --- /dev/null +++ b/tests/examplefiles/grammar-test.p6 @@ -0,0 +1,22 @@ +token pod_formatting_code { + $<code>=<[A..Z]> + '<' { $*POD_IN_FORMATTINGCODE := 1 } + $<content>=[ <!before '>'> <pod_string_character> ]+ + '>' { $*POD_IN_FORMATTINGCODE := 0 } +} + +token pod_string { + <pod_string_character>+ +} + +token something:sym«<» { + <!> +} + +token name { + <!> +} + +token comment:sym<#> { + '#' {} \N* +} diff --git a/tests/examplefiles/hash_syntax.rb b/tests/examplefiles/hash_syntax.rb new file mode 100644 index 00000000..35b27723 --- /dev/null +++ b/tests/examplefiles/hash_syntax.rb @@ -0,0 +1,5 @@ +{ :old_syntax => 'ok' } +{ 'stings as key' => 'should be ok' } +{ new_syntax: 'broken until now' } +{ withoutunderscore: 'should be ok' } +{ _underscoreinfront: 'might be ok, if I understand the pygments code correct' } diff --git a/tests/examplefiles/hello.at b/tests/examplefiles/hello.at new file mode 100644 index 00000000..23af2f2d --- /dev/null +++ b/tests/examplefiles/hello.at @@ -0,0 +1,6 @@ +def me := object: { + def name := "Kevin"; + def sayHello(peerName) { + system.println(peerName + " says hello!"); + }; +}; diff --git a/tests/examplefiles/hello.golo b/tests/examplefiles/hello.golo new file mode 100644 index 00000000..7e8ca214 --- /dev/null +++ b/tests/examplefiles/hello.golo @@ -0,0 +1,5 @@ +module hello.World + +function main = |args| { + println("Hello world!") +} diff --git a/tests/examplefiles/hello.lsl b/tests/examplefiles/hello.lsl new file mode 100644 index 00000000..61697e7f --- /dev/null +++ b/tests/examplefiles/hello.lsl @@ -0,0 +1,12 @@ +default +{ + state_entry() + { + llSay(0, "Hello, Avatar!"); + } + + touch_start(integer total_number) + { + llSay(0, "Touched."); + } +} diff --git a/tests/examplefiles/hello.smali b/tests/examplefiles/hello.smali new file mode 100644 index 00000000..e539f00e --- /dev/null +++ b/tests/examplefiles/hello.smali @@ -0,0 +1,40 @@ +# To Recreate: +# +# echo -e 'class hello {\n public static void main(String[] args) {\n +# System.out.println("hi");\n }\n}\n' > hello.java +# javac -target 1.4 -source 1.4 hello.java +# dx --dex --output=hello.dex hello.class +# baksmali hello.dex +# cat out/hello.smali + +.class Lhello; +.super Ljava/lang/Object; +.source "hello.java" + + +# direct methods +.method constructor <init>()V + .registers 1 + + .prologue + .line 1 + invoke-direct {p0}, Ljava/lang/Object;-><init>()V + + return-void +.end method + +.method public static main([Ljava/lang/String;)V + .registers 3 + .parameter + + .prologue + .line 3 + sget-object v0, Ljava/lang/System;->out:Ljava/io/PrintStream; + + const-string v1, "hi" + + invoke-virtual {v0, v1}, Ljava/io/PrintStream;->println(Ljava/lang/String;)V + + .line 4 + return-void +.end method diff --git a/tests/examplefiles/hello.sp b/tests/examplefiles/hello.sp new file mode 100644 index 00000000..7102d273 --- /dev/null +++ b/tests/examplefiles/hello.sp @@ -0,0 +1,9 @@ +#include <sourcemod> + +// Single line comment +/* Multi line + comment */ + +public OnPluginStart() { + PrintToServer("Hello."); +} diff --git a/tests/examplefiles/http_request_example b/tests/examplefiles/http_request_example new file mode 100644 index 00000000..675d1691 --- /dev/null +++ b/tests/examplefiles/http_request_example @@ -0,0 +1,15 @@ +POST /demo/submit/ HTTP/1.1
+Host: pygments.org
+Connection: keep-alivk
+Cache-Control: max-age=0
+Origin: http://pygments.org
+User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2)
+ AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.63 Safari/535.7
+Content-Type: application/x-www-form-urlencoded
+Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
+Referer: http://pygments.org/
+Accept-Encoding: gzip,deflate,sdch
+Accept-Language: en-US,en;q=0.8
+Accept-Charset: windows-949,utf-8;q=0.7,*;q=0.3
+
+name=test&lang=text&code=asdf&user= diff --git a/tests/examplefiles/http_response_example b/tests/examplefiles/http_response_example new file mode 100644 index 00000000..51340ca4 --- /dev/null +++ b/tests/examplefiles/http_response_example @@ -0,0 +1,29 @@ +HTTP/1.1 200 OK
+Date: Tue, 13 Dec 2011 00:11:44 GMT
+Status: 200 OK
+X-Transaction: 50b85fff78dab4a3
+X-RateLimit-Limit: 150
+ETag: "b31143be48ebfe7512b65fe64fe092f3"
+X-Frame-Options: SAMEORIGIN
+Last-Modified: Tue, 13 Dec 2011 00:11:44 GMT
+X-RateLimit-Remaining: 145
+X-Runtime: 0.01190
+X-Transaction-Mask: a6183ffa5f8ca943ff1b53b5644ef1145f6f285d
+Content-Type: application/json; charset=utf-8
+Content-Length: 2389
+Pragma: no-cache
+X-RateLimit-Class: api
+X-Revision: DEV
+Expires: Tue, 31 Mar 1981 05:00:00 GMT
+Cache-Control: no-cache, no-store, must-revalidate, pre-check=0, post-check=0
+X-MID: a55f21733bc52bb11d1fc58f9b51b4974fbb8f83
+X-RateLimit-Reset: 1323738416
+Set-Cookie: k=10.34.234.116.1323735104238974; path=/;
+ expires=Tue, 20-Dec-11 00:11:44 GMT; domain=.twitter.com
+Set-Cookie: guest_id=v1%3A13237351042425496; domain=.twitter.com; path=/;
+ expires=Thu, 12-Dec-2013 12:11:44 GMT
+Set-Cookie: _twitter_sess=BAh7CDoPY3JlYXRlZF9hdGwrCPS6wjQ0AToHaWQiJTFiMTlhY2E1ZjczYThk%250ANDUwMWQxNjMwZGU2YTQ1ODBhIgpmbGFzaElDOidBY3Rpb25Db250cm9sbGVy%250AOjpGbGFzaDo6Rmxhc2hIYXNoewAGOgpAdXNlZHsA--6b502f30a083e8a41a64f10930e142ea362b1561; domain=.twitter.com; path=/; HttpOnly
+Vary: Accept-Encoding
+Server: tfe
+
+[{"contributors_enabled":false,"profile_background_tile":true,"followers_count":644,"protected":false,"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/69064242\/gb_normal.jpg","screen_name":"birkenfeld","default_profile_image":false,"following":null,"friends_count":88,"profile_sidebar_fill_color":"7AC3EE","url":"http:\/\/pythonic.pocoo.org\/","name":"Georg Brandl","default_profile":false,"is_translator":false,"utc_offset":3600,"profile_sidebar_border_color":"65B0DA","description":"","profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme10\/bg.gif","favourites_count":0,"profile_use_background_image":true,"created_at":"Tue Dec 30 22:25:11 +0000 2008","status":{"retweet_count":10,"favorited":false,"geo":null,"possibly_sensitive":false,"coordinates":null,"in_reply_to_screen_name":null,"in_reply_to_status_id_str":null,"retweeted":false,"in_reply_to_status_id":null,"in_reply_to_user_id_str":null,"created_at":"Sat Jul 09 13:42:35 +0000 2011","truncated":false,"id_str":"89690914515206144","contributors":null,"place":null,"source":"web","in_reply_to_user_id":null,"id":89690914515206144,"retweeted_status":{"retweet_count":10,"favorited":false,"geo":null,"possibly_sensitive":false,"coordinates":null,"in_reply_to_screen_name":null,"in_reply_to_status_id_str":null,"retweeted":false,"in_reply_to_status_id":null,"in_reply_to_user_id_str":null,"created_at":"Sat Jul 09 13:07:04 +0000 2011","truncated":false,"id_str":"89681976755372032","contributors":null,"place":null,"source":"web","in_reply_to_user_id":null,"id":89681976755372032,"text":"Excellent Python posts from @mitsuhiko - http:\/\/t.co\/k1wt6e4 and @ncoghlan_dev - http:\/\/t.co\/eTxacgZ (links fixed)"},"text":"RT @jessenoller: Excellent Python posts from @mitsuhiko - http:\/\/t.co\/k1wt6e4 and @ncoghlan_dev - http:\/\/t.co\/eTxacgZ (links fixed)"},"follow_request_sent":null,"statuses_count":553,"geo_enabled":false,"notifications":null,"profile_text_color":"3D1957","id_str":"18490730","lang":"en","profile_background_image_url":"http:\/\/a1.twimg.com\/images\/themes\/theme10\/bg.gif","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/69064242\/gb_normal.jpg","show_all_inline_media":true,"listed_count":65,"profile_link_color":"FF0000","verified":false,"id":18490730,"time_zone":"Berlin","profile_background_color":"642D8B","location":"Bavaria, Germany"}] diff --git a/tests/examplefiles/File.hy b/tests/examplefiles/hybris_File.hy index 9c86c641..9c86c641 100644 --- a/tests/examplefiles/File.hy +++ b/tests/examplefiles/hybris_File.hy diff --git a/tests/examplefiles/idl_sample.pro b/tests/examplefiles/idl_sample.pro new file mode 100644 index 00000000..814d510d --- /dev/null +++ b/tests/examplefiles/idl_sample.pro @@ -0,0 +1,73 @@ +; docformat = 'rst' + +; Example IDL (Interactive Data Language) source code. + +;+ +; Get `nIndices` random indices for an array of size `nValues` (without +; repeating an index). +; +; :Examples: +; Try:: +; +; IDL> r = randomu(seed, 10) +; IDL> print, r, format='(4F)' +; 0.6297589 0.7815896 0.2508559 0.7546844 +; 0.1353382 0.1245834 0.8733745 0.0753110 +; 0.8054136 0.9513228 +; IDL> ind = mg_sample(10, 3, seed=seed) +; IDL> print, ind +; 2 4 7 +; IDL> print, r[ind] +; 0.250856 0.135338 0.0753110 +; +; :Returns: +; lonarr(`nIndices`) +; +; :Params: +; nValues : in, required, type=long +; size of array to choose indices from +; nIndices : in, required, type=long +; number of indices needed +; +; :Keywords: +; seed : in, out, optional, type=integer or lonarr(36) +; seed to use for random number generation, leave undefined to use a +; seed generated from the system clock; new seed will be output +;- +function mg_sample, nValues, nIndices, seed=seed + compile_opt strictarr + + ; get random nIndices by finding the indices of the smallest nIndices in a + ; array of random values + values = randomu(seed, nValues) + + ; our random values are uniformly distributed, so ideally the nIndices + ; smallest values are in the first bin of the below histogram + nBins = nValues / nIndices + h = histogram(values, nbins=nBins, reverse_indices=ri) + + ; the candidates for being in the first nIndices will live in bins 0..bin + nCandidates = 0L + for bin = 0L, nBins - 1L do begin + nCandidates += h[bin] + if (nCandidates ge nIndices) then break + endfor + + ; get the candidates and sort them + candidates = ri[ri[0] : ri[bin + 1L] - 1L] + sortedCandidates = sort(values[candidates]) + + ; return the first nIndices of them + return, (candidates[sortedCandidates])[0:nIndices-1L] +end + + +; main-level example program + +r = randomu(seed, 10) +print, r +ind = mg_sample(10, 3, seed=seed) +print, ind +print, r[ind] + +end
\ No newline at end of file diff --git a/tests/examplefiles/import.hs b/tests/examplefiles/import.hs index 09058ae6..f266f62e 100644 --- a/tests/examplefiles/import.hs +++ b/tests/examplefiles/import.hs @@ -1,4 +1,15 @@ -import "mtl" Control.Monad.Trans +import "base" Data.Char +import "base" Data.Char (isControl, isSpace) +import "base" Data.Char (isControl, --isSpace) + isSpace) +import "base" Data.Char (isControl, -- isSpace) + isSpace) + +(-->) :: Num a => a -- signature +(-->) = 2 -- >implementation + +--test comment +-- test comment main :: IO () main = putStrLn "hello world" diff --git a/tests/examplefiles/inet_pton6.dg b/tests/examplefiles/inet_pton6.dg new file mode 100644 index 00000000..3813d5b8 --- /dev/null +++ b/tests/examplefiles/inet_pton6.dg @@ -0,0 +1,71 @@ +import '/re' +import '/sys' + + +# IPv6address = hexpart [ ":" IPv4address ] +# IPv4address = 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT "." 1*3DIGIT +# hexpart = [ hexseq ] [ "::" [ hexseq ] ] +# hexseq = hex4 *( ":" hex4) +# hex4 = 1*4HEXDIG +hexpart = r'({0}|)(?:::({0}|)|)'.format r'(?:[\da-f]{1,4})(?::[\da-f]{1,4})*' +addrv4 = r'(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})' +addrv6 = re.compile $ r'(?i)(?:{})(?::{})?$'.format hexpart addrv4 + + +# Parse a base-N number given a list of its digits. +# +# :param q: the number of digits in that numeral system +# +# :param digits: an iterable of integers in range [0..q] +# +# :return: a decimal integer +# +base_n = q digits -> foldl (x y -> x * q + y) 0 digits + + +# Parse a sequence of hexadecimal numbers +# +# :param q: a string of colon-separated base-16 integers +# +# :return: an iterable of Python ints +# +unhex = q -> q and map (p -> int p 16) (q.split ':') + + +# Parse an IPv6 address as specified in RFC 4291. +# +# :param address: a string, obviously. +# +# :return: an integer which, written in binary form, points to the same node. +# +inet_pton6 = address -> + not (match = addrv6.match address) => raise $ ValueError 'not a valid IPv6 address' + start, end, *ipv4 = match.groups! + + is_ipv4 = not $ None in ipv4 + shift = (7 - start.count ':' - 2 * is_ipv4) * 16 + + (end is None and shift) or shift < 0 => raise $ ValueError 'not a valid IPv6 address' + hexaddr = (base_n 0x10000 (unhex start) << shift) + base_n 0x10000 (unhex $ end or '') + if (is_ipv4 => (hexaddr << 32) + base_n 0x100 (map int ipv4)) (otherwise => hexaddr) + + +inet6_type = q -> if + q == 0 => 'unspecified' + q == 1 => 'loopback' + (q >> 32) == 0x000000000000ffff => 'IPv4-mapped' + (q >> 64) == 0xfe80000000000000 => 'link-local' + (q >> 120) != 0x00000000000000ff => 'general unicast' + (q >> 112) % (1 << 4) == 0x0000000000000000 => 'multicast w/ reserved scope value' + (q >> 112) % (1 << 4) == 0x000000000000000f => 'multicast w/ reserved scope value' + (q >> 112) % (1 << 4) == 0x0000000000000001 => 'interface-local multicast' + (q >> 112) % (1 << 4) == 0x0000000000000004 => 'admin-local multicast' + (q >> 112) % (1 << 4) == 0x0000000000000005 => 'site-local multicast' + (q >> 112) % (1 << 4) == 0x0000000000000008 => 'organization-local multicast' + (q >> 112) % (1 << 4) == 0x000000000000000e => 'global multicast' + (q >> 112) % (1 << 4) != 0x0000000000000002 => 'multicast w/ unknown scope value' + (q >> 24) % (1 << 112) == 0x00000000000001ff => 'solicited-node multicast' + otherwise => 'link-local multicast' + + +print $ (x -> inet6_type x, hex x) $ inet_pton6 $ sys.stdin.read!.strip! diff --git a/tests/examplefiles/intsyn.fun b/tests/examplefiles/intsyn.fun new file mode 100644 index 00000000..777b0fdb --- /dev/null +++ b/tests/examplefiles/intsyn.fun @@ -0,0 +1,675 @@ +(* Internal Syntax *) +(* Author: Frank Pfenning, Carsten Schuermann *) +(* Modified: Roberto Virga *) + +functor IntSyn (structure Global : GLOBAL) :> INTSYN = +struct + + type cid = int (* Constant identifier *) + type name = string (* Variable name *) + type mid = int (* Structure identifier *) + type csid = int (* CS module identifier *) + + + (* Contexts *) + datatype 'a Ctx = (* Contexts *) + Null (* G ::= . *) + | Decl of 'a Ctx * 'a (* | G, D *) + + (* ctxPop (G) => G' + Invariant: G = G',D + *) + fun ctxPop (Decl (G, D)) = G + + exception Error of string (* raised if out of space *) + (* ctxLookup (G, k) = D, kth declaration in G from right to left + Invariant: 1 <= k <= |G|, where |G| is length of G + *) + + fun ctxLookup (Decl (G', D), 1) = D + | ctxLookup (Decl (G', _), k') = ctxLookup (G', k'-1) +(* | ctxLookup (Null, k') = (print ("Looking up k' = " ^ Int.toString k' ^ "\n"); raise Error "Out of Bounce\n")*) + (* ctxLookup (Null, k') should not occur by invariant *) + + (* ctxLength G = |G|, the number of declarations in G *) + fun ctxLength G = + let + fun ctxLength' (Null, n) = n + | ctxLength' (Decl(G, _), n)= ctxLength' (G, n+1) + in + ctxLength' (G, 0) + end + + type FgnExp = exn (* foreign expression representation *) + exception UnexpectedFgnExp of FgnExp + (* raised by a constraint solver + if passed an incorrect arg *) + + type FgnCnstr = exn (* foreign unification constraint + representation *) + exception UnexpectedFgnCnstr of FgnCnstr + (* raised by a constraint solver + if passed an incorrect arg *) + + datatype Depend = (* Dependency information *) + No (* P ::= No *) + | Maybe (* | Maybe *) + | Meta (* | Meta *) + + (* Expressions *) + + datatype Uni = (* Universes: *) + Kind (* L ::= Kind *) + | Type (* | Type *) + + datatype Exp = (* Expressions: *) + Uni of Uni (* U ::= L *) + | Pi of (Dec * Depend) * Exp (* | bPi (D, P). V *) + | Root of Head * Spine (* | C @ S *) + | Redex of Exp * Spine (* | U @ S *) + | Lam of Dec * Exp (* | lam D. U *) + | EVar of Exp option ref * Dec Ctx * Exp * (Cnstr ref) list ref + (* | X<I> : G|-V, Cnstr *) + + | EClo of Exp * Sub (* | U[s] *) + | AVar of Exp option ref (* | A<I> *) + | NVar of int (* | n (linear, fully applied) *) + (* grafting variable *) + + | FgnExp of csid * FgnExp + (* | (foreign expression) *) + + and Head = (* Heads: *) + BVar of int (* H ::= k *) + | Const of cid (* | c *) + | Proj of Block * int (* | #k(b) *) + | Skonst of cid (* | c# *) + | Def of cid (* | d *) + | NSDef of cid (* | d (non strict) *) + | FVar of name * Exp * Sub (* | F[s] *) + | FgnConst of csid * ConDec (* | (foreign constant) *) + + and Spine = (* Spines: *) + Nil (* S ::= Nil *) + | App of Exp * Spine (* | U ; S *) + | SClo of Spine * Sub (* | S[s] *) + + and Sub = (* Explicit substitutions: *) + Shift of int (* s ::= ^n *) + | Dot of Front * Sub (* | Ft.s *) + + and Front = (* Fronts: *) + Idx of int (* Ft ::= k *) + | Exp of Exp (* | U *) + | Axp of Exp (* | U (assignable) *) + | Block of Block (* | _x *) + | Undef (* | _ *) + + and Dec = (* Declarations: *) + Dec of name option * Exp (* D ::= x:V *) + | BDec of name option * (cid * Sub) (* | v:l[s] *) + | ADec of name option * int (* | v[^-d] *) + | NDec of name option + + and Block = (* Blocks: *) + Bidx of int (* b ::= v *) + | LVar of Block option ref * Sub * (cid * Sub) + (* | L(l[^k],t) *) + | Inst of Exp list (* | u1, ..., Un *) + + + (* Constraints *) + + and Cnstr = (* Constraint: *) + Solved (* Cnstr ::= solved *) + | Eqn of Dec Ctx * Exp * Exp (* | G|-(U1 == U2) *) + | FgnCnstr of csid * FgnCnstr (* | (foreign) *) + + and Status = (* Status of a constant: *) + Normal (* inert *) + | Constraint of csid * (Dec Ctx * Spine * int -> Exp option) + (* acts as constraint *) + | Foreign of csid * (Spine -> Exp) (* is converted to foreign *) + + and FgnUnify = (* Result of foreign unify *) + Succeed of FgnUnifyResidual list + (* succeed with a list of residual operations *) + | Fail + + and FgnUnifyResidual = (* Residual of foreign unify *) + Assign of Dec Ctx * Exp * Exp * Sub + (* perform the assignment G |- X = U [ss] *) + | Delay of Exp * Cnstr ref + (* delay cnstr, associating it with all the rigid EVars in U *) + + (* Global signature *) + + and ConDec = (* Constant declaration *) + ConDec of string * mid option * int * Status + (* a : K : kind or *) + * Exp * Uni (* c : A : type *) + | ConDef of string * mid option * int (* a = A : K : kind or *) + * Exp * Exp * Uni (* d = M : A : type *) + * Ancestor (* Ancestor info for d or a *) + | AbbrevDef of string * mid option * int + (* a = A : K : kind or *) + * Exp * Exp * Uni (* d = M : A : type *) + | BlockDec of string * mid option (* %block l : SOME G1 PI G2 *) + * Dec Ctx * Dec list + + | BlockDef of string * mid option * cid list + (* %block l = (l1 | ... | ln) *) + + | SkoDec of string * mid option * int (* sa: K : kind or *) + * Exp * Uni (* sc: A : type *) + + and Ancestor = (* Ancestor of d or a *) + Anc of cid option * int * cid option (* head(expand(d)), height, head(expand[height](d)) *) + (* NONE means expands to {x:A}B *) + + datatype StrDec = (* Structure declaration *) + StrDec of string * mid option + + (* Form of constant declaration *) + datatype ConDecForm = + FromCS (* from constraint domain *) + | Ordinary (* ordinary declaration *) + | Clause (* %clause declaration *) + + (* Type abbreviations *) + type dctx = Dec Ctx (* G = . | G,D *) + type eclo = Exp * Sub (* Us = U[s] *) + type bclo = Block * Sub (* Bs = B[s] *) + type cnstr = Cnstr ref + +(* exception Error of string (* raised if out of space *) *) + + + structure FgnExpStd = struct + + structure ToInternal = FgnOpnTable (type arg = unit + type result = Exp) + + structure Map = FgnOpnTable (type arg = Exp -> Exp + type result = Exp) + + structure App = FgnOpnTable (type arg = Exp -> unit + type result = unit) + + structure EqualTo = FgnOpnTable (type arg = Exp + type result = bool) + + structure UnifyWith = FgnOpnTable (type arg = Dec Ctx * Exp + type result = FgnUnify) + + + + fun fold csfe f b = let + val r = ref b + fun g U = r := f (U,!r) + in + App.apply csfe g ; !r + end + + end + + structure FgnCnstrStd = struct + + structure ToInternal = FgnOpnTable (type arg = unit + type result = (Dec Ctx * Exp) list) + + structure Awake = FgnOpnTable (type arg = unit + type result = bool) + + structure Simplify = FgnOpnTable (type arg = unit + type result = bool) + + end + + fun conDecName (ConDec (name, _, _, _, _, _)) = name + | conDecName (ConDef (name, _, _, _, _, _, _)) = name + | conDecName (AbbrevDef (name, _, _, _, _, _)) = name + | conDecName (SkoDec (name, _, _, _, _)) = name + | conDecName (BlockDec (name, _, _, _)) = name + | conDecName (BlockDef (name, _, _)) = name + + fun conDecParent (ConDec (_, parent, _, _, _, _)) = parent + | conDecParent (ConDef (_, parent, _, _, _, _, _)) = parent + | conDecParent (AbbrevDef (_, parent, _, _, _, _)) = parent + | conDecParent (SkoDec (_, parent, _, _, _)) = parent + | conDecParent (BlockDec (_, parent, _, _)) = parent + | conDecParent (BlockDef (_, parent, _)) = parent + + + (* conDecImp (CD) = k + + Invariant: + If CD is either a declaration, definition, abbreviation, or + a Skolem constant + then k stands for the number of implicit elements. + *) + fun conDecImp (ConDec (_, _, i, _, _, _)) = i + | conDecImp (ConDef (_, _, i, _, _, _, _)) = i + | conDecImp (AbbrevDef (_, _, i, _, _, _)) = i + | conDecImp (SkoDec (_, _, i, _, _)) = i + | conDecImp (BlockDec (_, _, _, _)) = 0 (* watch out -- carsten *) + + fun conDecStatus (ConDec (_, _, _, status, _, _)) = status + | conDecStatus _ = Normal + + (* conDecType (CD) = V + + Invariant: + If CD is either a declaration, definition, abbreviation, or + a Skolem constant + then V is the respective type + *) + fun conDecType (ConDec (_, _, _, _, V, _)) = V + | conDecType (ConDef (_, _, _, _, V, _, _)) = V + | conDecType (AbbrevDef (_, _, _, _, V, _)) = V + | conDecType (SkoDec (_, _, _, V, _)) = V + + + (* conDecBlock (CD) = (Gsome, Lpi) + + Invariant: + If CD is block definition + then Gsome is the context of some variables + and Lpi is the list of pi variables + *) + fun conDecBlock (BlockDec (_, _, Gsome, Lpi)) = (Gsome, Lpi) + + (* conDecUni (CD) = L + + Invariant: + If CD is either a declaration, definition, abbreviation, or + a Skolem constant + then L is the respective universe + *) + fun conDecUni (ConDec (_, _, _, _, _, L)) = L + | conDecUni (ConDef (_, _, _, _, _, L, _)) = L + | conDecUni (AbbrevDef (_, _, _, _, _, L)) = L + | conDecUni (SkoDec (_, _, _, _, L)) = L + + + fun strDecName (StrDec (name, _)) = name + + fun strDecParent (StrDec (_, parent)) = parent + + local + val maxCid = Global.maxCid + val dummyEntry = ConDec("", NONE, 0, Normal, Uni (Kind), Kind) + val sgnArray = Array.array (maxCid+1, dummyEntry) + : ConDec Array.array + val nextCid = ref(0) + + val maxMid = Global.maxMid + val sgnStructArray = Array.array (maxMid+1, StrDec("", NONE)) + : StrDec Array.array + val nextMid = ref (0) + + in + (* Invariants *) + (* Constant declarations are all well-typed *) + (* Constant declarations are stored in beta-normal form *) + (* All definitions are strict in all their arguments *) + (* If Const(cid) is valid, then sgnArray(cid) = ConDec _ *) + (* If Def(cid) is valid, then sgnArray(cid) = ConDef _ *) + + fun sgnClean (i) = if i >= !nextCid then () + else (Array.update (sgnArray, i, dummyEntry); + sgnClean (i+1)) + + fun sgnReset () = ((* Fri Dec 20 12:04:24 2002 -fp *) + (* this circumvents a space leak *) + sgnClean (0); + nextCid := 0; nextMid := 0) + fun sgnSize () = (!nextCid, !nextMid) + + fun sgnAdd (conDec) = + let + val cid = !nextCid + in + if cid > maxCid + then raise Error ("Global signature size " ^ Int.toString (maxCid+1) ^ " exceeded") + else (Array.update (sgnArray, cid, conDec) ; + nextCid := cid + 1; + cid) + end + + (* 0 <= cid < !nextCid *) + fun sgnLookup (cid) = Array.sub (sgnArray, cid) + + fun sgnApp (f) = + let + fun sgnApp' (cid) = + if cid = !nextCid then () else (f cid; sgnApp' (cid+1)) + in + sgnApp' (0) + end + + fun sgnStructAdd (strDec) = + let + val mid = !nextMid + in + if mid > maxMid + then raise Error ("Global signature size " ^ Int.toString (maxMid+1) ^ " exceeded") + else (Array.update (sgnStructArray, mid, strDec) ; + nextMid := mid + 1; + mid) + end + + (* 0 <= mid < !nextMid *) + fun sgnStructLookup (mid) = Array.sub (sgnStructArray, mid) + + (* A hack used in Flit - jcreed 6/05 *) + fun rename (cid, new) = + let + val newConDec = case sgnLookup cid of + ConDec (n,m,i,s,e,u) => ConDec(new,m,i,s,e,u) + | ConDef (n,m,i,e,e',u,a) => ConDef(new,m,i,e,e',u,a) + | AbbrevDef (n,m,i,e,e',u) => AbbrevDef (new,m,i,e,e',u) + | BlockDec (n,m,d,d') => BlockDec (new,m,d,d') + | SkoDec (n,m,i,e,u) => SkoDec (new,m,i,e,u) + in + Array.update (sgnArray, cid, newConDec) + end + + end + + fun constDef (d) = + (case sgnLookup (d) + of ConDef(_, _, _, U,_, _, _) => U + | AbbrevDef (_, _, _, U,_, _) => U) + + fun constType (c) = conDecType (sgnLookup c) + fun constImp (c) = conDecImp (sgnLookup c) + fun constUni (c) = conDecUni (sgnLookup c) + fun constBlock (c) = conDecBlock (sgnLookup c) + + fun constStatus (c) = + (case sgnLookup (c) + of ConDec (_, _, _, status, _, _) => status + | _ => Normal) + + + (* Explicit Substitutions *) + + (* id = ^0 + + Invariant: + G |- id : G id is patsub + *) + val id = Shift(0) + + (* shift = ^1 + + Invariant: + G, V |- ^ : G ^ is patsub + *) + val shift = Shift(1) + + (* invShift = ^-1 = _.^0 + Invariant: + G |- ^-1 : G, V ^-1 is patsub + *) + val invShift = Dot(Undef, id) + + + (* comp (s1, s2) = s' + + Invariant: + If G' |- s1 : G + and G'' |- s2 : G' + then s' = s1 o s2 + and G'' |- s1 o s2 : G + + If s1, s2 patsub + then s' patsub + *) + fun comp (Shift (0), s) = s + (* next line is an optimization *) + (* roughly 15% on standard suite for Twelf 1.1 *) + (* Sat Feb 14 10:15:16 1998 -fp *) + | comp (s, Shift (0)) = s + | comp (Shift (n), Dot (Ft, s)) = comp (Shift (n-1), s) + | comp (Shift (n), Shift (m)) = Shift (n+m) + | comp (Dot (Ft, s), s') = Dot (frontSub (Ft, s'), comp (s, s')) + + (* bvarSub (n, s) = Ft' + + Invariant: + If G |- s : G' G' |- n : V + then Ft' = Ftn if s = Ft1 .. Ftn .. ^k + or Ft' = ^(n+k) if s = Ft1 .. Ftm ^k and m<n + and G |- Ft' : V [s] + *) + and bvarSub (1, Dot(Ft, s)) = Ft + | bvarSub (n, Dot(Ft, s)) = bvarSub (n-1, s) + | bvarSub (n, Shift(k)) = Idx (n+k) + + (* blockSub (B, s) = B' + + Invariant: + If G |- s : G' + and G' |- B block + then G |- B' block + and B [s] == B' + *) + (* in front of substitutions, first case is irrelevant *) + (* Sun Dec 2 11:56:41 2001 -fp *) + and blockSub (Bidx k, s) = + (case bvarSub (k, s) + of Idx k' => Bidx k' + | Block B => B) + | blockSub (LVar (ref (SOME B), sk, _), s) = + blockSub (B, comp (sk, s)) + (* -fp Sun Dec 1 21:18:30 2002 *) + (* --cs Sun Dec 1 11:25:41 2002 *) + (* Since always . |- t : Gsome, discard s *) + (* where is this needed? *) + (* Thu Dec 6 20:30:26 2001 -fp !!! *) + | blockSub (LVar (r as ref NONE, sk, (l, t)), s) = + LVar(r, comp(sk, s), (l, t)) + (* was: + LVar (r, comp(sk, s), (l, comp (t, s))) + July 22, 2010 -fp -cs + *) + (* comp(^k, s) = ^k' for some k' by invariant *) + | blockSub (L as Inst ULs, s') = Inst (map (fn U => EClo (U, s')) ULs) + (* this should be right but somebody should verify *) + + (* frontSub (Ft, s) = Ft' + + Invariant: + If G |- s : G' G' |- Ft : V + then Ft' = Ft [s] + and G |- Ft' : V [s] + + NOTE: EClo (U, s) might be undefined, so if this is ever + computed eagerly, we must introduce an "Undefined" exception, + raise it in whnf and handle it here so Exp (EClo (U, s)) => Undef + *) + and frontSub (Idx (n), s) = bvarSub (n, s) + | frontSub (Exp (U), s) = Exp (EClo (U, s)) + | frontSub (Undef, s) = Undef + | frontSub (Block (B), s) = Block (blockSub (B, s)) + + (* decSub (x:V, s) = D' + + Invariant: + If G |- s : G' G' |- V : L + then D' = x:V[s] + and G |- V[s] : L + *) + (* First line is an optimization suggested by cs *) + (* D[id] = D *) + (* Sat Feb 14 18:37:44 1998 -fp *) + (* seems to have no statistically significant effect *) + (* undo for now Sat Feb 14 20:22:29 1998 -fp *) + (* + fun decSub (D, Shift(0)) = D + | decSub (Dec (x, V), s) = Dec (x, EClo (V, s)) + *) + fun decSub (Dec (x, V), s) = Dec (x, EClo (V, s)) + | decSub (NDec x, s) = NDec x + | decSub (BDec (n, (l, t)), s) = BDec (n, (l, comp (t, s))) + + (* dot1 (s) = s' + + Invariant: + If G |- s : G' + then s' = 1. (s o ^) + and for all V s.t. G' |- V : L + G, V[s] |- s' : G', V + + If s patsub then s' patsub + *) + (* first line is an optimization *) + (* roughly 15% on standard suite for Twelf 1.1 *) + (* Sat Feb 14 10:16:16 1998 -fp *) + fun dot1 (s as Shift (0)) = s + | dot1 s = Dot (Idx(1), comp(s, shift)) + + (* invDot1 (s) = s' + invDot1 (1. s' o ^) = s' + + Invariant: + s = 1 . s' o ^ + If G' |- s' : G + (so G',V[s] |- s : G,V) + *) + fun invDot1 (s) = comp (comp(shift, s), invShift) + + + (* Declaration Contexts *) + + (* ctxDec (G, k) = x:V + Invariant: + If |G| >= k, where |G| is size of G, + then G |- k : V and G |- V : L + *) + fun ctxDec (G, k) = + let (* ctxDec' (G'', k') = x:V + where G |- ^(k-k') : G'', 1 <= k' <= k + *) + fun ctxDec' (Decl (G', Dec (x, V')), 1) = Dec (x, EClo (V', Shift (k))) + | ctxDec' (Decl (G', BDec (n, (l, s))), 1) = BDec (n, (l, comp (s, Shift (k)))) + | ctxDec' (Decl (G', _), k') = ctxDec' (G', k'-1) + (* ctxDec' (Null, k') should not occur by invariant *) + in + ctxDec' (G, k) + end + + (* blockDec (G, v, i) = V + + Invariant: + If G (v) = l[s] + and Sigma (l) = SOME Gsome BLOCK Lblock + and G |- s : Gsome + then G |- pi (v, i) : V + *) + + fun blockDec (G, v as (Bidx k), i) = + let + val BDec (_, (l, s)) = ctxDec (G, k) + (* G |- s : Gsome *) + val (Gsome, Lblock) = conDecBlock (sgnLookup l) + fun blockDec' (t, D :: L, 1, j) = decSub (D, t) + | blockDec' (t, _ :: L, n, j) = + blockDec' (Dot (Exp (Root (Proj (v, j), Nil)), t), + L, n-1, j+1) + in + blockDec' (s, Lblock, i, 1) + end + + + (* EVar related functions *) + + (* newEVar (G, V) = newEVarCnstr (G, V, nil) *) + fun newEVar (G, V) = EVar(ref NONE, G, V, ref nil) + + (* newAVar G = new AVar (assignable variable) *) + (* AVars carry no type, ctx, or cnstr *) + fun newAVar () = AVar(ref NONE) + + (* newTypeVar (G) = X, X new + where G |- X : type + *) + fun newTypeVar (G) = EVar(ref NONE, G, Uni(Type), ref nil) + + (* newLVar (l, s) = (l[s]) *) + fun newLVar (sk, (cid, t)) = LVar (ref NONE, sk, (cid, t)) + + (* Definition related functions *) + (* headOpt (U) = SOME(H) or NONE, U should be strict, normal *) + fun headOpt (Root (H, _)) = SOME(H) + | headOpt (Lam (_, U)) = headOpt U + | headOpt _ = NONE + + fun ancestor' (NONE) = Anc(NONE, 0, NONE) + | ancestor' (SOME(Const(c))) = Anc(SOME(c), 1, SOME(c)) + | ancestor' (SOME(Def(d))) = + (case sgnLookup(d) + of ConDef(_, _, _, _, _, _, Anc(_, height, cOpt)) + => Anc(SOME(d), height+1, cOpt)) + | ancestor' (SOME _) = (* FgnConst possible, BVar impossible by strictness *) + Anc(NONE, 0, NONE) + (* ancestor(U) = ancestor info for d = U *) + fun ancestor (U) = ancestor' (headOpt U) + + (* defAncestor(d) = ancestor of d, d must be defined *) + fun defAncestor (d) = + (case sgnLookup(d) + of ConDef(_, _, _, _, _, _, anc) => anc) + + (* Type related functions *) + + (* targetHeadOpt (V) = SOME(H) or NONE + where H is the head of the atomic target type of V, + NONE if V is a kind or object or have variable type. + Does not expand type definitions. + *) + (* should there possibly be a FgnConst case? also targetFamOpt -kw *) + fun targetHeadOpt (Root (H, _)) = SOME(H) + | targetHeadOpt (Pi(_, V)) = targetHeadOpt V + | targetHeadOpt (Redex (V, S)) = targetHeadOpt V + | targetHeadOpt (Lam (_, V)) = targetHeadOpt V + | targetHeadOpt (EVar (ref (SOME(V)),_,_,_)) = targetHeadOpt V + | targetHeadOpt (EClo (V, s)) = targetHeadOpt V + | targetHeadOpt _ = NONE + (* Root(Bvar _, _), Root(FVar _, _), Root(FgnConst _, _), + EVar(ref NONE,..), Uni, FgnExp _ + *) + (* Root(Skonst _, _) can't occur *) + (* targetHead (A) = a + as in targetHeadOpt, except V must be a valid type + *) + fun targetHead (A) = valOf (targetHeadOpt A) + + (* targetFamOpt (V) = SOME(cid) or NONE + where cid is the type family of the atomic target type of V, + NONE if V is a kind or object or have variable type. + Does expand type definitions. + *) + fun targetFamOpt (Root (Const(cid), _)) = SOME(cid) + | targetFamOpt (Pi(_, V)) = targetFamOpt V + | targetFamOpt (Root (Def(cid), _)) = targetFamOpt (constDef cid) + | targetFamOpt (Redex (V, S)) = targetFamOpt V + | targetFamOpt (Lam (_, V)) = targetFamOpt V + | targetFamOpt (EVar (ref (SOME(V)),_,_,_)) = targetFamOpt V + | targetFamOpt (EClo (V, s)) = targetFamOpt V + | targetFamOpt _ = NONE + (* Root(Bvar _, _), Root(FVar _, _), Root(FgnConst _, _), + EVar(ref NONE,..), Uni, FgnExp _ + *) + (* Root(Skonst _, _) can't occur *) + (* targetFam (A) = a + as in targetFamOpt, except V must be a valid type + *) + fun targetFam (A) = valOf (targetFamOpt A) + +end; (* functor IntSyn *) + +structure IntSyn :> INTSYN = + IntSyn (structure Global = Global); diff --git a/tests/examplefiles/intsyn.sig b/tests/examplefiles/intsyn.sig new file mode 100644 index 00000000..ea505362 --- /dev/null +++ b/tests/examplefiles/intsyn.sig @@ -0,0 +1,286 @@ +(* Internal Syntax *) +(* Author: Frank Pfenning, Carsten Schuermann *) +(* Modified: Roberto Virga *) + +signature INTSYN = +sig + + type cid = int (* Constant identifier *) + type mid = int (* Structure identifier *) + type csid = int (* CS module identifier *) + + + type FgnExp = exn (* foreign expression representation *) + exception UnexpectedFgnExp of FgnExp + (* raised by a constraint solver + if passed an incorrect arg *) + type FgnCnstr = exn (* foreign constraint representation *) + exception UnexpectedFgnCnstr of FgnCnstr + (* raised by a constraint solver + if passed an incorrect arg *) + + (* Contexts *) + + datatype 'a Ctx = (* Contexts *) + Null (* G ::= . *) + | Decl of 'a Ctx * 'a (* | G, D *) + + val ctxPop : 'a Ctx -> 'a Ctx + val ctxLookup: 'a Ctx * int -> 'a + val ctxLength: 'a Ctx -> int + + datatype Depend = (* Dependency information *) + No (* P ::= No *) + | Maybe (* | Maybe *) + | Meta (* | Meta *) + + (* expressions *) + + datatype Uni = (* Universes: *) + Kind (* L ::= Kind *) + | Type (* | Type *) + + datatype Exp = (* Expressions: *) + Uni of Uni (* U ::= L *) + | Pi of (Dec * Depend) * Exp (* | Pi (D, P). V *) + | Root of Head * Spine (* | H @ S *) + | Redex of Exp * Spine (* | U @ S *) + | Lam of Dec * Exp (* | lam D. U *) + | EVar of Exp option ref * Dec Ctx * Exp * (Cnstr ref) list ref + (* | X<I> : G|-V, Cnstr *) + | EClo of Exp * Sub (* | U[s] *) + | AVar of Exp option ref (* | A<I> *) + + | FgnExp of csid * FgnExp (* | (foreign expression) *) + + | NVar of int (* | n (linear, + fully applied variable + used in indexing *) + + and Head = (* Head: *) + BVar of int (* H ::= k *) + | Const of cid (* | c *) + | Proj of Block * int (* | #k(b) *) + | Skonst of cid (* | c# *) + | Def of cid (* | d (strict) *) + | NSDef of cid (* | d (non strict) *) + | FVar of string * Exp * Sub (* | F[s] *) + | FgnConst of csid * ConDec (* | (foreign constant) *) + + and Spine = (* Spines: *) + Nil (* S ::= Nil *) + | App of Exp * Spine (* | U ; S *) + | SClo of Spine * Sub (* | S[s] *) + + and Sub = (* Explicit substitutions: *) + Shift of int (* s ::= ^n *) + | Dot of Front * Sub (* | Ft.s *) + + and Front = (* Fronts: *) + Idx of int (* Ft ::= k *) + | Exp of Exp (* | U *) + | Axp of Exp (* | U *) + | Block of Block (* | _x *) + | Undef (* | _ *) + + and Dec = (* Declarations: *) + Dec of string option * Exp (* D ::= x:V *) + | BDec of string option * (cid * Sub) (* | v:l[s] *) + | ADec of string option * int (* | v[^-d] *) + | NDec of string option + + and Block = (* Blocks: *) + Bidx of int (* b ::= v *) + | LVar of Block option ref * Sub * (cid * Sub) + (* | L(l[^k],t) *) + | Inst of Exp list (* | U1, ..., Un *) + (* It would be better to consider having projections count + like substitutions, then we could have Inst of Sub here, + which would simplify a lot of things. + + I suggest however to wait until the next big overhaul + of the system -- cs *) + + +(* | BClo of Block * Sub (* | b[s] *) *) + + (* constraints *) + + and Cnstr = (* Constraint: *) + Solved (* Cnstr ::= solved *) + | Eqn of Dec Ctx * Exp * Exp (* | G|-(U1 == U2) *) + | FgnCnstr of csid * FgnCnstr (* | (foreign) *) + + and Status = (* Status of a constant: *) + Normal (* inert *) + | Constraint of csid * (Dec Ctx * Spine * int -> Exp option) + (* acts as constraint *) + | Foreign of csid * (Spine -> Exp) (* is converted to foreign *) + + and FgnUnify = (* Result of foreign unify *) + Succeed of FgnUnifyResidual list + (* succeed with a list of residual operations *) + | Fail + + and FgnUnifyResidual = + Assign of Dec Ctx * Exp * Exp * Sub + (* perform the assignment G |- X = U [ss] *) + | Delay of Exp * Cnstr ref + (* delay cnstr, associating it with all the rigid EVars in U *) + + (* Global signature *) + + and ConDec = (* Constant declaration *) + ConDec of string * mid option * int * Status + (* a : K : kind or *) + * Exp * Uni (* c : A : type *) + | ConDef of string * mid option * int (* a = A : K : kind or *) + * Exp * Exp * Uni (* d = M : A : type *) + * Ancestor (* Ancestor info for d or a *) + | AbbrevDef of string * mid option * int + (* a = A : K : kind or *) + * Exp * Exp * Uni (* d = M : A : type *) + | BlockDec of string * mid option (* %block l : SOME G1 PI G2 *) + * Dec Ctx * Dec list + | BlockDef of string * mid option * cid list + (* %block l = (l1 | ... | ln) *) + | SkoDec of string * mid option * int (* sa: K : kind or *) + * Exp * Uni (* sc: A : type *) + + and Ancestor = (* Ancestor of d or a *) + Anc of cid option * int * cid option (* head(expand(d)), height, head(expand[height](d)) *) + (* NONE means expands to {x:A}B *) + + datatype StrDec = (* Structure declaration *) + StrDec of string * mid option + + (* Form of constant declaration *) + datatype ConDecForm = + FromCS (* from constraint domain *) + | Ordinary (* ordinary declaration *) + | Clause (* %clause declaration *) + + (* Type abbreviations *) + type dctx = Dec Ctx (* G = . | G,D *) + type eclo = Exp * Sub (* Us = U[s] *) + type bclo = Block * Sub (* Bs = B[s] *) + type cnstr = Cnstr ref + + exception Error of string (* raised if out of space *) + + (* standard operations on foreign expressions *) + structure FgnExpStd : sig + (* convert to internal syntax *) + structure ToInternal : FGN_OPN where type arg = unit + where type result = Exp + + (* apply function to subterms *) + structure Map : FGN_OPN where type arg = Exp -> Exp + where type result = Exp + + (* apply function to subterms, for effect *) + structure App : FGN_OPN where type arg = Exp -> unit + where type result = unit + + (* test for equality *) + structure EqualTo : FGN_OPN where type arg = Exp + where type result = bool + + (* unify with another term *) + structure UnifyWith : FGN_OPN where type arg = Dec Ctx * Exp + where type result = FgnUnify + + (* fold a function over the subterms *) + val fold : (csid * FgnExp) -> (Exp * 'a -> 'a) -> 'a -> 'a + end + + (* standard operations on foreign constraints *) + structure FgnCnstrStd : sig + (* convert to internal syntax *) + structure ToInternal : FGN_OPN where type arg = unit + where type result = (Dec Ctx * Exp) list + + (* awake *) + structure Awake : FGN_OPN where type arg = unit + where type result = bool + + (* simplify *) + structure Simplify : FGN_OPN where type arg = unit + where type result = bool + end + + val conDecName : ConDec -> string + val conDecParent : ConDec -> mid option + val conDecImp : ConDec -> int + val conDecStatus : ConDec -> Status + val conDecType : ConDec -> Exp + val conDecBlock : ConDec -> dctx * Dec list + val conDecUni : ConDec -> Uni + + val strDecName : StrDec -> string + val strDecParent : StrDec -> mid option + + val sgnReset : unit -> unit + val sgnSize : unit -> cid * mid + + val sgnAdd : ConDec -> cid + val sgnLookup: cid -> ConDec + val sgnApp : (cid -> unit) -> unit + + val sgnStructAdd : StrDec -> mid + val sgnStructLookup : mid -> StrDec + + val constType : cid -> Exp (* type of c or d *) + val constDef : cid -> Exp (* definition of d *) + val constImp : cid -> int + val constStatus : cid -> Status + val constUni : cid -> Uni + val constBlock : cid -> dctx * Dec list + + (* Declaration Contexts *) + + val ctxDec : dctx * int -> Dec (* get variable declaration *) + val blockDec : dctx * Block * int -> Dec + + (* Explicit substitutions *) + + val id : Sub (* id *) + val shift : Sub (* ^ *) + val invShift : Sub (* ^-1 *) + + val bvarSub : int * Sub -> Front (* k[s] *) + val frontSub : Front * Sub -> Front (* H[s] *) + val decSub : Dec * Sub -> Dec (* x:V[s] *) + val blockSub : Block * Sub -> Block (* B[s] *) + + val comp : Sub * Sub -> Sub (* s o s' *) + val dot1 : Sub -> Sub (* 1 . (s o ^) *) + val invDot1 : Sub -> Sub (* (^ o s) o ^-1) *) + + (* EVar related functions *) + + val newEVar : dctx * Exp -> Exp (* creates X:G|-V, [] *) + val newAVar : unit -> Exp (* creates A (bare) *) + val newTypeVar : dctx -> Exp (* creates X:G|-type, [] *) + val newLVar : Sub * (cid * Sub) -> Block + (* creates B:(l[^k],t) *) + + (* Definition related functions *) + val headOpt : Exp -> Head option + val ancestor : Exp -> Ancestor + val defAncestor : cid -> Ancestor + + (* Type related functions *) + + (* Not expanding type definitions *) + val targetHeadOpt : Exp -> Head option (* target type family or NONE *) + val targetHead : Exp -> Head (* target type family *) + + (* Expanding type definitions *) + val targetFamOpt : Exp -> cid option (* target type family or NONE *) + val targetFam : Exp -> cid (* target type family *) + + (* Used in Flit *) + val rename : cid * string -> unit + +end; (* signature INTSYN *) diff --git a/tests/examplefiles/irc.lsp b/tests/examplefiles/irc.lsp new file mode 100755 index 00000000..6f45976a --- /dev/null +++ b/tests/examplefiles/irc.lsp @@ -0,0 +1,214 @@ +#!/usr/bin/env newlisp + +;; @module IRC +;; @description a basic irc library +;; @version early alpha! 0.1 2011-10-31 14:21:26 +;; @author cormullion +;; Usage: +;; (IRC:init "newlithper") ; a username/nick (not that one obviously :-) +;; (IRC:connect "irc.freenode.net" 6667) ; irc/server +;; (IRC:join-channel {#newlisp}) ; join a room +;; either (IRC:read-irc-loop) ; loop - monitor only, no input +;; or (IRC:session) ; a command-line session, end with /QUIT + +(context 'IRC) + (define Inickname) + (define Ichannels) + (define Iserver) + (define Iconnected) + (define Icallbacks '()) + (define Idle-time 400) ; seconds + (define Itime-stamp) ; time since last message was processed + +(define (register-callback callback-name callback-function) + (println {registering callback for } callback-name { : } (sym (term callback-function) (prefix callback-function))) + (push (list callback-name (sym (term callback-function) (prefix callback-function))) Icallbacks)) + +(define (do-callback callback-name data) + (when (set 'func (lookup callback-name Icallbacks)) ; find first callback + (if-not (catch (apply func (list data)) 'error) + (println {error in callback } callback-name {: } error)))) + +(define (do-callbacks callback-name data) + (dolist (rf (ref-all callback-name Icallbacks)) + (set 'callback-entry (Icallbacks (first rf))) + (when (set 'func (last callback-entry)) + (if-not (catch (apply func (list data)) 'error) + (println {error in callback } callback-name {: } error))))) + +(define (init str) + (set 'Inickname str) + (set 'Iconnected nil) + (set 'Ichannels '()) + (set 'Itime-stamp (time-of-day))) + +(define (connect server port) + (set 'Iserver (net-connect server port)) + (net-send Iserver (format "USER %s %s %s :%s\r\n" Inickname Inickname Inickname Inickname)) + (net-send Iserver (format "NICK %s \r\n" Inickname)) + (set 'Iconnected true) + (do-callbacks "connect" (list (list "server" server) (list "port" port)))) + +(define (identify password) + (net-send Iserver (format "PRIVMSG nickserv :identify %s\r\n" password))) + +(define (join-channel channel) + (when (net-send Iserver (format "JOIN %s \r\n" channel)) + (push channel Ichannels) + (do-callbacks "join-channel" (list (list "channel" channel) (list "nickname" Inickname))))) + +(define (part chan) + (if-not (empty? chan) + ; leave specified + (begin + (net-send Iserver (format "PART %s\r\n" chan)) + (replace channel Ichannels) + (do-callbacks "part" (list (list "channel" channel)))) + ; leave all + (begin + (dolist (channel Ichannels) + (net-send Iserver (format "PART %s\r\n" channel)) + (replace channel Ichannels) + (do-callbacks "part" (list (list "channel" channel))))))) + +(define (do-quit message) + (do-callbacks "quit" '()) ; chance to do stuff before quit... + (net-send Iserver (format "QUIT :%s\r\n" message)) + (sleep 1000) + (set 'Ichannels '()) + (close Iserver) + (set 'Iconnected nil)) + +(define (privmsg user message) + (net-send Iserver (format "PRIVMSG %s :%s\r\n" user message))) + +(define (notice user message) + (net-send Iserver (format "NOTICE %s :%s\r\n" user message))) + +(define (send-to-server message (channel nil)) + (cond + ((starts-with message {/}) ; default command character + (set 'the-message (replace "^/" (copy message) {} 0)) ; keep original + (net-send Iserver (format "%s \r\n" the-message)) ; send it + ; do a quit + (if (starts-with (lower-case the-message) "quit") + (do-quit { enough}))) + (true + (if (nil? channel) + ; say to all channels + (dolist (c Ichannels) + (net-send Iserver (format "PRIVMSG %s :%s\r\n" c message))) + ; say to specified channel + (if (find channel Ichannels) + (net-send Iserver (format "PRIVMSG %s :%s\r\n" channel message)))))) + (do-callbacks "send-to-server" (list (list "channel" channel) (list "message" message)))) + +(define (process-command sender command text) + (cond + ((= sender "PING") + (net-send Iserver (format "PONG %s\r\n" command))) + ((or (= command "NOTICE") (= command "PRIVMSG")) + (process-message sender command text)) + ((= command "JOIN") + (set 'username (first (clean empty? (parse sender {!|:} 0)))) + (set 'channel (last (clean empty? (parse sender {!|:} 0)))) + (println {username } username { joined } channel) + (do-callbacks "join" (list (list "channel" channel) (list "username" username)))) + (true + nil))) + +(define (process-message sender command text) + (let ((username {} target {} message {})) + (set 'username (first (clean empty? (parse sender {!|:} 0)))) + (set 'target (trim (first (clean empty? (parse text {!|:} 0))))) + (set 'message (slice text (+ (find {:} text) 1))) + (cond + ((starts-with message "\001") + (process-ctcp username target message)) + ((find target Ichannels) + (cond + ((= command {PRIVMSG}) + (do-callbacks "channel-message" (list (list "channel" target) (list "username" username) (list "message" message)))) + ((= command {NOTICE}) + (do-callbacks "channel-notice" (list (list "channel" target) (list "username" username) (list "message" message)))))) + ((= target Inickname) + (cond + ((= command {PRIVMSG}) + (do-callbacks "private-message" (list (list "username" username) (list "message" message)))) + ((= command {NOTICE}) + (do-callbacks "private-notice" (list (list "username" username) (list "message" message)))))) + (true + nil)))) + +(define (process-ctcp username target message) + (cond + ((starts-with message "\001VERSION\001") + (net-send Iserver (format "NOTICE %s :\001VERSION %s\001\r\n" username version))) + ((starts-with message "\001PING") + (set 'data (first (rest (clean empty? (parse message { } 0))))) + (set 'data (trim data "\001" "\001")) + (net-send Iserver (format "NOTICE %s :\001PING %s\001\r\n" username data))) + ((starts-with message "\001ACTION") + (set 'data (first (rest (clean empty? (parse message { } 0))))) + (set 'data (join data { })) + (set 'data (trim data "\001" "\001")) + (if (find target Ichannels) + (do-callbacks "channel-action" (list (list "username" username) (list "message" message)))) + (if (= target Inickname) + (do-callbacks "private-action" (list (list "username" username) (list "message" message))))) + ((starts-with message "\001TIME\001") + (net-send Iserver (format "NOTICE %s:\001TIME :%s\001\r\n" username (date)))))) + +(define (parse-buffer raw-buffer) + (let ((messages (clean empty? (parse raw-buffer "\r\n" 0))) + (sender {} command {} text {})) + ; check for elapsed time since last activity + (when (> (sub (time-of-day) Itime-stamp) (mul Idle-time 1000)) + (do-callbacks "idle-event") + (set 'Itime-stamp (time-of-day))) + (dolist (message messages) + (set 'message-parts (parse message { })) + (unless (empty? message-parts) + (set 'sender (first message-parts)) + (catch (set 'command (first (rest message-parts))) 'error) + (catch (set 'text (join (rest (rest message-parts)) { })) 'error)) + (process-command sender command text)))) + +(define (read-irc) + (let ((buffer {})) + (when (!= (net-peek Iserver) 0) + (net-receive Iserver buffer 8192 "\n") + (unless (empty? buffer) + (parse-buffer buffer))))) + +(define (read-irc-loop) ; monitoring + (let ((buffer {})) + (while Iconnected + (read-irc) + (sleep 1000)))) + +(define (print-raw-message data) ; example of using a callback + (set 'raw-data (lookup "message" data)) + (set 'channel (lookup "channel" data)) + (set 'message-text raw-data) + (println (date (date-value) 0 {%H:%M:%S }) username {> } message-text)) + +(define (print-outgoing-message data) + (set 'raw-data (lookup "message" data)) + (set 'channel (lookup "channel" data)) + (set 'message-text raw-data) + (println (date (date-value) 0 {%H:%M:%S }) Inickname {> } message-text)) + +(define (session); interactive terminal + ; must add callbacks to display messages + (register-callback "channel-message" 'print-raw-message) + (register-callback "send-to-server" 'print-outgoing-message) + (while Iconnected + (while (zero? (peek 0)) + (read-irc)) + (send-to-server (string (read-line 0)))) + (println {finished session } (date)) + (exit)) + +; end of IRC code + diff --git a/tests/examplefiles/json.lasso b/tests/examplefiles/json.lasso new file mode 100644 index 00000000..72926112 --- /dev/null +++ b/tests/examplefiles/json.lasso @@ -0,0 +1,301 @@ +<?LassoScript + + // + // JSON Encoding and Decoding + // + // Copyright 2007-2012 LassoSoft Inc. + // + // <http://json.org/> + // <http://json-rpc.org/> + // <http://www.ietf.org/rfc/rfc4627.txt?number=4627> + // + +If: (Lasso_TagExists: 'Encode_JSON') == False; + + Define_Tag: 'JSON', -Namespace='Encode_', -Required='value', -Optional='options'; + + Local: 'escapes' = Map('\\' = '\\', '"' = '"', '\r' = 'r', '\n' = 'n', '\t' = 't', '\f' = 'f', '\b' = 'b'); + Local: 'output' = ''; + Local: 'newoptions' = (Array: -Internal); + If: !(Local_Defined: 'options') || (#options->(IsA: 'array') == False); + Local: 'options' = (Array); + /If; + If: (#options >> -UseNative) || (Params >> -UseNative); + #newoptions->(Insert: -UseNative); + /If; + If: (#options >> -NoNative) || (Params >> -NoNative); + #newoptions->(Insert: -NoNative); + /If; + If: (#options !>> -UseNative) && ((#value->(IsA: 'set')) || (#value->(IsA: 'list')) || (#value->(IsA: 'queue')) || (#value->(IsA: 'priorityqueue')) || (#value->(IsA: 'stack'))); + #output += (Encode_JSON: Array->(insertfrom: #value->iterator) &, -Options=#newoptions); + Else: (#options !>> -UseNative) && (#value->(IsA: 'pair')); + #output += (Encode_JSON: (Array: #value->First, #value->Second)); + Else: (#options !>> -Internal) && (#value->(Isa: 'array') == False) && (#value->(IsA: 'map') == False); + #output += '[' + (Encode_JSON: #value, -Options=#newoptions) + ']'; + Else: (#value->(IsA: 'literal')); + #output += #value; + Else: (#value->(IsA: 'string')); + #output += '"'; + Loop: (#value->Length); + Local('character' = #value->(Get: Loop_Count)); + #output->(Append: + (Match_RegExp('[\\x{0020}-\\x{21}\\x{23}-\\x{5b}\\x{5d}-\\x{10fff}]') == #character) ? #character | + '\\' + (#escapes->(Contains: #character) ? #escapes->(Find: #character) | 'u' + String(Encode_Hex(#character))->PadLeading(4, '0')&) + ); + /Loop; + #output += '"'; + Else: (#value->(IsA: 'integer')) || (#value->(IsA: 'decimal')) || (#value->(IsA: 'boolean')); + #output += (String: #value); + Else: (#value->(IsA: 'null')); + #output += 'null'; + Else: (#value->(IsA: 'date')); + If: #value->gmt; + #output += '"' + #value->(format: '%QT%TZ') + '"'; + Else; + #output += '"' + #value->(format: '%QT%T') + '"'; + /If; + Else: (#value->(IsA: 'array')); + #output += '['; + Iterate: #value, (Local: 'temp'); + #output += (Encode_JSON: #temp, -Options=#newoptions); + If: #value->Size != Loop_Count; + #output += ', '; + /If; + /Iterate; + #output += ']'; + Else: (#value->(IsA: 'object')); + #output += '{'; + Iterate: #value, (Local: 'temp'); + #output += #temp->First + ': ' + (Encode_JSON: #temp->Second, -Options=#newoptions); + If: (#value->Size != Loop_Count); + #output += ', '; + /If; + /Iterate; + #output += '}'; + Else: (#value->(IsA: 'map')); + #output += '{'; + Iterate: #value, (Local: 'temp'); + #output += (Encode_JSON: #temp->First, -Options=#newoptions) + ': ' + (Encode_JSON: #temp->Second, -Options=#newoptions); + If: (#value->Size != Loop_Count); + #output += ', '; + /If; + /Iterate; + #output += '}'; + Else: (#value->(IsA: 'client_ip')) || (#value->(IsA: 'client_address')); + #output += (Encode_JSON: (String: #value), -Options=#newoptions); + Else: (#options !>> -UseNative) && (#value->(IsA: 'set')) || (#value->(IsA: 'list')) || (#value->(IsA: 'queue')) || (#value->(IsA: 'priorityqueue')) || (#value->(IsA: 'stack')); + #output += (Encode_JSON: Array->(insertfrom: #value->iterator) &, -Options=#newoptions); + Else: (#options !>> -NoNative); + #output += (Encode_JSON: (Map: '__jsonclass__'=(Array:'deserialize',(Array:'<LassoNativeType>' + #value->Serialize + '</LassoNativeType>')))); + /If; + Return: @#output; + + /Define_Tag; + +/If; + +If: (Lasso_TagExists: 'Decode_JSON') == False; + + Define_Tag: 'JSON', -Namespace='Decode_', -Required='value'; + + (#value == '') ? Return: Null; + + Define_Tag: 'consume_string', -Required='ibytes'; + Local: 'unescapes' = (map: 34 = '"', 92 = '\\', 98 = '\b', 102 = '\f', 110 = '\n', 114 = '\r', 116 = '\t'); + Local: 'temp' = 0, 'obytes' = Bytes; + While: ((#temp := #ibytes->export8bits) != 34); // '"' + If: (#temp === 92); // '\' + #temp = #ibytes->export8bits; + If: (#temp === 117); // 'u' + #obytes->(ImportString: (Decode_Hex: (String: #ibytes->(GetRange: #ibytes->Position + 1, 4)))->(ExportString: 'UTF-16'), 'UTF-8'); + #ibytes->(SetPosition: #ibytes->Position + 4); + Else; + If: (#unescapes->(Contains: #temp)); + #obytes->(ImportString: #unescapes->(Find: #temp), 'UTF-8'); + Else; + #obytes->(Import8Bits: #temp); + /If; + /If; + Else; + #obytes->(Import8Bits: #temp); + /If; + /While; + Local('output' = #obytes->(ExportString: 'UTF-8')); + If: #output->(BeginsWith: '<LassoNativeType>') && #output->(EndsWith: '</LassoNativeType>'); + Local: 'temp' = #output - '<LassoNativeType>' - '</LassoNativeType>'; + Local: 'output' = null; + Protect; + #output->(Deserialize: #temp); + /Protect; + Else: (Valid_Date: #output, -Format='%QT%TZ'); + Local: 'output' = (Date: #output, -Format='%QT%TZ'); + Else: (Valid_Date: #output, -Format='%QT%T'); + Local: 'output' = (Date: #output, -Format='%QT%T'); + /If; + Return: @#output; + /Define_Tag; + + Define_Tag: 'consume_token', -Required='ibytes', -required='temp'; + Local: 'obytes' = bytes->(import8bits: #temp) &; + local: 'delimit' = (array: 9, 10, 13, 32, 44, 58, 93, 125); // \t\r\n ,:]} + While: (#delimit !>> (#temp := #ibytes->export8bits)); + #obytes->(import8bits: #temp); + /While; + Local: 'output' = (String: #obytes); + If: (#output == 'true') || (#output == 'false'); + Return: (Boolean: #output); + Else: (#output == 'null'); + Return: Null; + Else: (String_IsNumeric: #output); + Return: (#output >> '.') ? (Decimal: #output) | (Integer: #output); + /If; + Return: @#output; + /Define_Tag; + + Define_Tag: 'consume_array', -Required='ibytes'; + Local: 'output' = array; + local: 'delimit' = (array: 9, 10, 13, 32, 44); // \t\r\n , + local: 'temp' = 0; + While: ((#temp := #ibytes->export8bits) != 93); // ] + If: (#delimit >> #temp); + // Discard whitespace + Else: (#temp == 34); // " + #output->(insert: (consume_string: @#ibytes)); + Else: (#temp == 91); // [ + #output->(insert: (consume_array: @#ibytes)); + Else: (#temp == 123); // { + #output->(insert: (consume_object: @#ibytes)); + Else; + #output->(insert: (consume_token: @#ibytes, @#temp)); + (#temp == 93) ? Loop_Abort; + /If; + /While; + Return: @#output; + /Define_Tag; + + Define_Tag: 'consume_object', -Required='ibytes'; + Local: 'output' = map; + local: 'delimit' = (array: 9, 10, 13, 32, 44); // \t\r\n , + local: 'temp' = 0; + local: 'key' = null; + local: 'val' = null; + While: ((#temp := #ibytes->export8bits) != 125); // } + If: (#delimit >> #temp); + // Discard whitespace + Else: (#key !== null) && (#temp == 34); // " + #output->(insert: #key = (consume_string: @#ibytes)); + #key = null; + Else: (#key !== null) && (#temp == 91); // [ + #output->(insert: #key = (consume_array: @#ibytes)); + #key = null; + Else: (#key !== null) && (#temp == 123); // { + #output->(insert: #key = (consume_object: @#ibytes)); + #key = null; + Else: (#key !== null); + #output->(insert: #key = (consume_token: @#ibytes, @#temp)); + (#temp == 125) ? Loop_abort; + #key = null; + Else; + #key = (consume_string: @#ibytes); + while(#delimit >> (#temp := #ibytes->export8bits)); + /while; + #temp != 58 ? Loop_Abort; + /If; + /While; + If: (#output >> '__jsonclass__') && (#output->(Find: '__jsonclass__')->(isa: 'array')) && (#output->(Find: '__jsonclass__')->size >= 2) && (#output->(Find: '__jsonclass__')->First == 'deserialize'); + Return: #output->(find: '__jsonclass__')->Second->First; + Else: (#output >> 'native') && (#output >> 'comment') && (#output->(find: 'comment') == 'http://www.lassosoft.com/json'); + Return: #output->(find: 'native'); + /If; + Return: @#output; + /Define_Tag; + + Local: 'ibytes' = (bytes: #value); + Local: 'start' = 1; + #ibytes->removeLeading(BOM_UTF8); + Local: 'temp' = #ibytes->export8bits; + If: (#temp == 91); // [ + Local: 'output' = (consume_array: @#ibytes); + Return: @#output; + Else: (#temp == 123); // { + Local: 'output' = (consume_object: @#ibytes); + Return: @#output; + /If; + + /Define_Tag; + +/If; + +If: (Lasso_TagExists: 'Literal') == False; + + Define_Type: 'Literal', 'String'; + /Define_Type; + +/If; + +If: (Lasso_TagExists: 'Object') == False; + + Define_Type: 'Object', 'Map'; + /Define_Type; + +/If; + +If: (Lasso_TagExists: 'JSON_RPCCall') == False; + + Define_Tag: 'RPCCall', -Namespace='JSON_', + -Required='method', + -Optional='params', + -Optional='id', + -Optional='host'; + + !(Local_Defined: 'host') ? Local: 'host' = 'http://localhost/lassoapps.8/rpc/rpc.lasso'; + !(Local_Defined: 'id') ? Local: 'id' = Lasso_UniqueID; + Local: 'request' = (Map: 'method' = #method, 'params' = #params, 'id' = #id); + Local: 'request' = (Encode_JSON: #request); + Local: 'result' = (Include_URL: #host, -PostParams=#request); + Local: 'result' = (Decode_JSON: #result); + Return: @#result; + + /Define_Tag; + +/If; + +If: (Lasso_TagExists: 'JSON_Records') == False; + + Define_Tag: 'JSON_Records', + -Optional='KeyField', + -Optional='ReturnField', + -Optional='ExcludeField', + -Optional='Fields'; + + Local: '_fields' = (Local_Defined: 'fields') && #fields->(IsA: 'array') ? #fields | Field_Names; + Fail_If: #_fields->size == 0, -1, 'No fields found for [JSON_Records]'; + Local: '_keyfield' = (Local: 'keyfield'); + If: #_fields !>> #_keyfield; + Local: '_keyfield' = (KeyField_Name); + If: #_fields !>> #_keyfield; + Local: '_keyfield' = 'ID'; + If: #_fields !>> #_keyfield; + Local: '_keyfield' = #_fields->First; + /If; + /If; + /If; + Local: '_index' = #_fields->(FindPosition: #_keyfield)->First; + Local: '_return' = (Local_Defined: 'returnfield') ? (Params->(Find: -ReturnField)->(ForEach: {Params->First = Params->First->Second; Return: True}) &) | @#_fields; + Local: '_exclude' = (Local_Defined: 'excludefield') ? (Params->(Find: -ExcludeField)->(ForEach: {Params->First = Params->First->Second; Return: True}) &) | Array; + Local: '_records' = Array; + Iterate: Records_Array, (Local: '_record'); + Local: '_temp' = Map; + Iterate: #_fields, (Local: '_field'); + ((#_return >> #_field) && (#_exclude !>> #_field)) ? #_temp->Insert(#_field = #_record->(Get: Loop_Count)); + /Iterate; + #_records->Insert(#_temp); + /Iterate; + Local: '_output' = (Encode_JSON: (Object: 'error_msg'=Error_Msg, 'error_code'=Error_Code, 'found_count'=Found_Count, 'keyfield'=#_keyfield, 'rows'=#_records)); + Return: @#_output; + + /Define_Tag; + +/If; + +?> diff --git a/tests/examplefiles/json.lasso9 b/tests/examplefiles/json.lasso9 new file mode 100644 index 00000000..732ab2af --- /dev/null +++ b/tests/examplefiles/json.lasso9 @@ -0,0 +1,213 @@ + +/** + trait_json_serialize + Objects with this trait will be assumed to convert to json data + when its ->asString method is called +*/ +define trait_json_serialize => trait { + require asString() +} + +define json_serialize(e::bytes)::string => ('"' + (string(#e)->Replace(`\`, `\\`) & Replace('\"', '\\"') & Replace('\r', '\\r') & Replace('\n', '\\n') & Replace('\t', '\\t') & Replace('\f', '\\f') & Replace('\b', '\\b') &) + '"') +define json_serialize(e::string)::string => ('"' + (string(#e)->Replace(`\`, `\\`) & Replace('\"', '\\"') & Replace('\r', '\\r') & Replace('\n', '\\n') & Replace('\t', '\\t') & Replace('\f', '\\f') & Replace('\b', '\\b') &) + '"') +define json_serialize(e::json_literal)::string => (#e->asstring) +define json_serialize(e::integer)::string => (#e->asstring) +define json_serialize(e::decimal)::string => (#e->asstring) +define json_serialize(e::boolean)::string => (#e->asstring) +define json_serialize(e::null)::string => ('null') +define json_serialize(e::date)::string => ('"' + #e->format(#e->gmt ? '%QT%TZ' | '%Q%T') + '"') +/* +define json_serialize(e::array)::string => { + local(output) = ''; + local(delimit) = ''; + #e->foreach => { #output += #delimit + json_serialize(#1); #delimit = ', '; } + return('[' + #output + ']'); +} +define json_serialize(e::staticarray)::string => { + local(output) = ''; + local(delimit) = ''; + #e->foreach => { #output += #delimit + json_serialize(#1); #delimit = ', '; } + return('[' + #output + ']'); +} +*/ +define json_serialize(e::trait_forEach)::string => { + local(output) = ''; + local(delimit) = ''; + #e->foreach => { #output += #delimit + json_serialize(#1); #delimit = ', '; } + return('[' + #output + ']'); +} +define json_serialize(e::map)::string => { + local(output = with pr in #e->eachPair + select json_serialize(#pr->first->asString) + ': ' + json_serialize(#pr->second)) + return '{' + #output->join(',') + '}' +} +define json_serialize(e::json_object)::string => { + local(output) = ''; + local(delimit) = ''; + #e->foreachpair => { #output += #delimit + #1->first + ': ' + json_serialize(#1->second); #delimit = ', '; } + return('{' + #output + '}'); +} +define json_serialize(e::trait_json_serialize) => #e->asString +define json_serialize(e::any)::string => json_serialize('<LassoNativeType>' + #e->serialize + '</LassoNativeType>') + +// Bil Corry fixes for decoding json +define json_consume_string(ibytes::bytes) => { + local(obytes) = bytes; + local(temp) = 0; + while((#temp := #ibytes->export8bits) != 34); + #obytes->import8bits(#temp); + (#temp == 92) ? #obytes->import8bits(#ibytes->export8bits); // Escape \ + /while; + local(output = string(#obytes)->unescape) + //Replace('\\"', '\"') & Replace('\\r', '\r') & Replace('\\n', '\n') & Replace('\\t', '\t') & Replace('\\f', '\f') & Replace('\\b', '\b') &; + if(#output->BeginsWith('<LassoNativeType>') && #output->EndsWith('</LassoNativeType>')); + Protect; + return serialization_reader(xml(#output - '<LassoNativeType>' - '</LassoNativeType>'))->read + /Protect; + else( (#output->size == 16 or #output->size == 15) and regexp(`\d{8}T\d{6}Z?`, '', #output)->matches) + return date(#output, -Format=#output->size == 16?`yyyyMMdd'T'HHmmssZ`|`yyyyMMdd'T'HHmmss`) + /if + return #output +} + +// Bil Corry fix + Ke fix +define json_consume_token(ibytes::bytes, temp::integer) => { + + local(obytes = bytes->import8bits(#temp) &, + delimit = array(9, 10, 13, 32, 44, 58, 93, 125)) // \t\r\n ,:]} + + while(#delimit !>> (#temp := #ibytes->export8bits)) + #obytes->import8bits(#temp) + /while + + #temp == 125? // } + #ibytes->marker -= 1 +//============================================================================ +// Is also end of token if end of array[] + #temp == 93? // ] + #ibytes->marker -= 1 +//............................................................................ + + local(output = string(#obytes)) + #output == 'true'? + return true + #output == 'false'? + return false + #output == 'null'? + return null + string_IsNumeric(#output)? + return (#output >> '.')? decimal(#output) | integer(#output) + + return #output +} + +// Bil Corry fix +define json_consume_array(ibytes::bytes)::array => { + Local(output) = array; + local(delimit) = array( 9, 10, 13, 32, 44); // \t\r\n , + local(temp) = 0; + While((#temp := #ibytes->export8bits) != 93); // ] + If(#delimit >> #temp); + // Discard whitespace + Else(#temp == 34); // " + #output->insert(json_consume_string(#ibytes)); + Else(#temp == 91); // [ + #output->insert(json_consume_array(#ibytes)); + Else(#temp == 123); // { + #output->insert(json_consume_object(#ibytes)); + Else; + #output->insert(json_consume_token(#ibytes, #temp)); + (#temp == 93) ? Loop_Abort; + /If; + /While; + Return(#output); +} + +// Bil Corry fix +define json_consume_object(ibytes::bytes)::map => { + Local('output' = map, + 'delimit' = array( 9, 10, 13, 32, 44), // \t\r\n , + 'temp' = 0, + 'key' = null, + 'val' = null); + While((#temp := #ibytes->export8bits) != 125); // } + If(#delimit >> #temp); + // Discard whitespace + Else((#key !== null) && (#temp == 34)); // " + #output->insert(#key = json_consume_string(#ibytes)); + #key = null; + Else((#key !== null) && (#temp == 91)); // [ + #output->insert(#key = json_consume_array(#ibytes)); + #key = null; + Else((#key !== null) && (#temp == 123)); // { + #output->insert(#key = json_consume_object(#ibytes)); + #key = null; + Else((#key !== null)); + #output->insert(#key = json_consume_token(#ibytes, #temp)); + #key = null; + Else; + #key = json_consume_string(#ibytes); + while(#delimit >> (#temp := #ibytes->export8bits)); + /while; + #temp != 58 ? Loop_Abort; + /If; + /While; + + If((#output >> '__jsonclass__') && (#output->Find('__jsonclass__')->isa('array')) && (#output->Find('__jsonclass__')->size >= 2) && (#output->Find('__jsonclass__')->First == 'deserialize')); + Return(#output->find('__jsonclass__')->Second->First); + Else((#output >> 'native') && (#output >> 'comment') && (#output->find('comment') == 'http://www.lassosoft.com/json')); + Return(#output->find('native')); + /If; + Return(#output); +} + +// Bil Corry fix + Ke fix +define json_deserialize(ibytes::bytes)::any => { + #ibytes->removeLeading(bom_utf8); + +//============================================================================ +// Reset marker on provided bytes + #ibytes->marker = 0 +//............................................................................ + + Local(temp) = #ibytes->export8bits; + If(#temp == 91); // [ + Return(json_consume_array(#ibytes)); + Else(#temp == 123); // { + Return(json_consume_object(#ibytes)); + else(#temp == 34) // " + return json_consume_string(#ibytes) + /If; +} + +define json_deserialize(s::string) => json_deserialize(bytes(#s)) + +/**! json_literal - This is a subclass of String used for JSON encoding. + + A json_literal works exactly like a string, but will be inserted directly + rather than being encoded into JSON. This allows JavaScript elements + like functions to be inserted into JSON objects. This is most useful + when the JSON object will be used within a JavaScript on the local page. + [Map: 'fn'=Literal('function(){ ...})] => {'fn': function(){ ...}} +**/ +define json_literal => type { + parent string +} + +/**! json_object - This is a subclass of Map used for JSON encoding. + + An object works exactly like a map, but when it is encoded into JSON all + of the keys will be inserted literally. This makes it easy to create a + JavaScript object without extraneous quote marks. + Object('name'='value') => {name: "value"} +**/ +define json_object => type { + parent map + public onCreate(...) => ..onCreate(:#rest or (:)) +} + +define json_rpccall(method::string, params=map, id='', host='') => { + #id == '' ? #host = Lasso_UniqueID; + #host == '' ? #host = 'http://localhost/lassoapps.8/rpc/rpc.lasso'; + Return(Decode_JSON(Include_URL(#host, -PostParams=Encode_JSON(Map('method' = #method, 'params' = #params, 'id' = #id))))); +} diff --git a/tests/examplefiles/language.hy b/tests/examplefiles/language.hy new file mode 100644 index 00000000..9768c39c --- /dev/null +++ b/tests/examplefiles/language.hy @@ -0,0 +1,165 @@ +;;;; This contains some of the core Hy functions used +;;;; to make functional programming slightly easier. +;;;; + + +(defn _numeric-check [x] + (if (not (numeric? x)) + (raise (TypeError (.format "{0!r} is not a number" x))))) + +(defn cycle [coll] + "Yield an infinite repetition of the items in coll" + (setv seen []) + (for [x coll] + (yield x) + (.append seen x)) + (while seen + (for [x seen] + (yield x)))) + +(defn dec [n] + "Decrement n by 1" + (_numeric-check n) + (- n 1)) + +(defn distinct [coll] + "Return a generator from the original collection with duplicates + removed" + (let [[seen []] [citer (iter coll)]] + (for [val citer] + (if (not_in val seen) + (do + (yield val) + (.append seen val)))))) + +(defn drop [count coll] + "Drop `count` elements from `coll` and yield back the rest" + (let [[citer (iter coll)]] + (try (for [i (range count)] + (next citer)) + (catch [StopIteration])) + citer)) + +(defn even? [n] + "Return true if n is an even number" + (_numeric-check n) + (= (% n 2) 0)) + +(defn filter [pred coll] + "Return all elements from `coll` that pass `pred`" + (let [[citer (iter coll)]] + (for [val citer] + (if (pred val) + (yield val))))) + +(defn inc [n] + "Increment n by 1" + (_numeric-check n) + (+ n 1)) + +(defn instance? [klass x] + (isinstance x klass)) + +(defn iterable? [x] + "Return true if x is iterable" + (try (do (iter x) true) + (catch [Exception] false))) + +(defn iterate [f x] + (setv val x) + (while true + (yield val) + (setv val (f val)))) + +(defn iterator? [x] + "Return true if x is an iterator" + (try (= x (iter x)) + (catch [TypeError] false))) + +(defn neg? [n] + "Return true if n is < 0" + (_numeric-check n) + (< n 0)) + +(defn none? [x] + "Return true if x is None" + (is x None)) + +(defn numeric? [x] + (import numbers) + (instance? numbers.Number x)) + +(defn nth [coll index] + "Return nth item in collection or sequence, counting from 0" + (if (not (neg? index)) + (if (iterable? coll) + (try (first (list (take 1 (drop index coll)))) + (catch [IndexError] None)) + (try (get coll index) + (catch [IndexError] None))) + None)) + +(defn odd? [n] + "Return true if n is an odd number" + (_numeric-check n) + (= (% n 2) 1)) + +(defn pos? [n] + "Return true if n is > 0" + (_numeric_check n) + (> n 0)) + +(defn remove [pred coll] + "Return coll with elements removed that pass `pred`" + (let [[citer (iter coll)]] + (for [val citer] + (if (not (pred val)) + (yield val))))) + +(defn repeat [x &optional n] + "Yield x forever or optionally n times" + (if (none? n) + (setv dispatch (fn [] (while true (yield x)))) + (setv dispatch (fn [] (for [_ (range n)] (yield x))))) + (dispatch)) + +(defn repeatedly [func] + "Yield result of running func repeatedly" + (while true + (yield (func)))) + +(defn take [count coll] + "Take `count` elements from `coll`, or the whole set if the total + number of entries in `coll` is less than `count`." + (let [[citer (iter coll)]] + (for [_ (range count)] + (yield (next citer))))) + +(defn take-nth [n coll] + "Return every nth member of coll + raises ValueError for (not (pos? n))" + (if (pos? n) + (let [[citer (iter coll)] [skip (dec n)]] + (for [val citer] + (yield val) + (for [_ (range skip)] + (next citer)))) + (raise (ValueError "n must be positive")))) + +(defn take-while [pred coll] + "Take all elements while `pred` is true" + (let [[citer (iter coll)]] + (for [val citer] + (if (pred val) + (yield val) + (break))))) + +(defn zero? [n] + "Return true if n is 0" + (_numeric_check n) + (= n 0)) + +(def *exports* ["cycle" "dec" "distinct" "drop" "even?" "filter" "inc" + "instance?" "iterable?" "iterate" "iterator?" "neg?" + "none?" "nth" "numeric?" "odd?" "pos?" "remove" "repeat" + "repeatedly" "take" "take_nth" "take_while" "zero?"]) diff --git a/tests/examplefiles/limbo.b b/tests/examplefiles/limbo.b new file mode 100644 index 00000000..e55a0a62 --- /dev/null +++ b/tests/examplefiles/limbo.b @@ -0,0 +1,456 @@ +implement Ninewin; +include "sys.m"; + sys: Sys; +include "draw.m"; + draw: Draw; + Image, Display, Pointer: import draw; +include "arg.m"; +include "keyboard.m"; +include "tk.m"; +include "wmclient.m"; + wmclient: Wmclient; + Window: import wmclient; +include "sh.m"; + sh: Sh; + +# run a p9 graphics program (default rio) under inferno wm, +# making available to it: +# /dev/winname - naming the current inferno window (changing on resize) +# /dev/mouse - pointer file + resize events; write to change position +# /dev/cursor - change appearance of cursor. +# /dev/draw - inferno draw device +# /dev/cons - read keyboard events, write to 9win stdout. + +Ninewin: module { + init: fn(ctxt: ref Draw->Context, argv: list of string); +}; +winname: string; + +init(ctxt: ref Draw->Context, argv: list of string) +{ + size := Draw->Point(500, 500); + sys = load Sys Sys->PATH; + draw = load Draw Draw->PATH; + wmclient = load Wmclient Wmclient->PATH; + wmclient->init(); + sh = load Sh Sh->PATH; + + buts := Wmclient->Resize; + if(ctxt == nil){ + ctxt = wmclient->makedrawcontext(); + buts = Wmclient->Plain; + } + arg := load Arg Arg->PATH; + arg->init(argv); + arg->setusage("9win [-s] [-x width] [-y height]"); + exportonly := 0; + while(((opt := arg->opt())) != 0){ + case opt { + 's' => + exportonly = 1; + 'x' => + size.x = int arg->earg(); + 'y' => + size.y = int arg->earg(); + * => + arg->usage(); + } + } + if(size.x < 1 || size.y < 1) + arg->usage(); + argv = arg->argv(); + if(argv != nil && hd argv == "-s"){ + exportonly = 1; + argv = tl argv; + } + if(argv == nil && !exportonly) + argv = "rio" :: nil; + if(argv != nil && exportonly){ + sys->fprint(sys->fildes(2), "9win: no command allowed with -s flag\n"); + raise "fail:usage"; + } + title := "9win"; + if(!exportonly) + title += " " + hd argv; + w := wmclient->window(ctxt, title, buts); + w.reshape(((0, 0), size)); + w.onscreen(nil); + if(w.image == nil){ + sys->fprint(sys->fildes(2), "9win: cannot get image to draw on\n"); + raise "fail:no window"; + } + + sys->pctl(Sys->FORKNS|Sys->NEWPGRP, nil); + ld := "/n/9win"; + if(sys->bind("#s", ld, Sys->MREPL) == -1 && + sys->bind("#s", ld = "/n/local", Sys->MREPL) == -1){ + sys->fprint(sys->fildes(2), "9win: cannot bind files: %r\n"); + raise "fail:error"; + } + w.startinput("kbd" :: "ptr" :: nil); + spawn ptrproc(rq := chan of Sys->Rread, ptr := chan[10] of ref Pointer, reshape := chan[1] of int); + + + fwinname := sys->file2chan(ld, "winname"); + fconsctl := sys->file2chan(ld, "consctl"); + fcons := sys->file2chan(ld, "cons"); + fmouse := sys->file2chan(ld, "mouse"); + fcursor := sys->file2chan(ld, "cursor"); + if(!exportonly){ + spawn run(sync := chan of string, w.ctl, ld, argv); + if((e := <-sync) != nil){ + sys->fprint(sys->fildes(2), "9win: %s", e); + raise "fail:error"; + } + } + spawn serveproc(w, rq, fwinname, fconsctl, fcons, fmouse, fcursor); + if(!exportonly){ + # handle events synchronously so that we don't get a "killed" message + # from the shell. + handleevents(w, ptr, reshape); + }else{ + spawn handleevents(w, ptr, reshape); + sys->bind(ld, "/dev", Sys->MBEFORE); + export(sys->fildes(0), w.ctl); + } +} + +handleevents(w: ref Window, ptr: chan of ref Pointer, reshape: chan of int) +{ + for(;;)alt{ + c := <-w.ctxt.ctl or + c = <-w.ctl => + e := w.wmctl(c); + if(e != nil) + sys->fprint(sys->fildes(2), "9win: ctl error: %s\n", e); + if(e == nil && c != nil && c[0] == '!'){ + alt{ + reshape <-= 1 => + ; + * => + ; + } + winname = nil; + } + p := <-w.ctxt.ptr => + if(w.pointer(*p) == 0){ + # XXX would block here if client isn't reading mouse... but we do want to + # extert back-pressure, which conflicts. + alt{ + ptr <-= p => + ; + * => + ; # sys->fprint(sys->fildes(2), "9win: discarding mouse event\n"); + } + } + } +} + +serveproc(w: ref Window, mouserq: chan of Sys->Rread, fwinname, fconsctl, fcons, fmouse, fcursor: ref Sys->FileIO) +{ + winid := 0; + krc: list of Sys->Rread; + ks: string; + + for(;;)alt { + c := <-w.ctxt.kbd => + ks[len ks] = inf2p9key(c); + if(krc != nil){ + hd krc <-= (array of byte ks, nil); + ks = nil; + krc = tl krc; + } + (nil, d, nil, wc) := <-fcons.write => + if(wc != nil){ + sys->write(sys->fildes(1), d, len d); + wc <-= (len d, nil); + } + (nil, nil, nil, rc) := <-fcons.read => + if(rc != nil){ + if(ks != nil){ + rc <-= (array of byte ks, nil); + ks = nil; + }else + krc = rc :: krc; + } + (offset, nil, nil, rc) := <-fwinname.read => + if(rc != nil){ + if(winname == nil){ + winname = sys->sprint("noborder.9win.%d", winid++); + if(w.image.name(winname, 1) == -1){ + sys->fprint(sys->fildes(2), "9win: namewin %q failed: %r", winname); + rc <-= (nil, "namewin failure"); + break; + } + } + d := array of byte winname; + if(offset < len d) + d = d[offset:]; + else + d = nil; + rc <-= (d, nil); + } + (nil, nil, nil, wc) := <-fwinname.write => + if(wc != nil) + wc <-= (-1, "permission denied"); + (nil, nil, nil, rc) := <-fconsctl.read => + if(rc != nil) + rc <-= (nil, "permission denied"); + (nil, d, nil, wc) := <-fconsctl.write => + if(wc != nil){ + if(string d != "rawon") + wc <-= (-1, "cannot change console mode"); + else + wc <-= (len d, nil); + } + (nil, nil, nil, rc) := <-fmouse.read => + if(rc != nil) + mouserq <-= rc; + (nil, d, nil, wc) := <-fmouse.write => + if(wc != nil){ + e := cursorset(w, string d); + if(e == nil) + wc <-= (len d, nil); + else + wc <-= (-1, e); + } + (nil, nil, nil, rc) := <-fcursor.read => + if(rc != nil) + rc <-= (nil, "permission denied"); + (nil, d, nil, wc) := <-fcursor.write => + if(wc != nil){ + e := cursorswitch(w, d); + if(e == nil) + wc <-= (len d, nil); + else + wc <-= (-1, e); + } + } +} + +ptrproc(rq: chan of Sys->Rread, ptr: chan of ref Pointer, reshape: chan of int) +{ + rl: list of Sys->Rread; + c := ref Pointer(0, (0, 0), 0); + for(;;){ + ch: int; + alt{ + p := <-ptr => + ch = 'm'; + c = p; + <-reshape => + ch = 'r'; + rc := <-rq => + rl = rc :: rl; + continue; + } + if(rl == nil) + rl = <-rq :: rl; + hd rl <-= (sys->aprint("%c%11d %11d %11d %11d ", ch, c.xy.x, c.xy.y, c.buttons, c.msec), nil); + rl = tl rl; + } +} + +cursorset(w: ref Window, m: string): string +{ + if(m == nil || m[0] != 'm') + return "invalid mouse message"; + x := int m[1:]; + for(i := 1; i < len m; i++) + if(m[i] == ' '){ + while(m[i] == ' ') + i++; + break; + } + if(i == len m) + return "invalid mouse message"; + y := int m[i:]; + return w.wmctl(sys->sprint("ptr %d %d", x, y)); +} + +cursorswitch(w: ref Window, d: array of byte): string +{ + Hex: con "0123456789abcdef"; + if(len d != 2*4+64) + return w.wmctl("cursor"); + hot := Draw->Point(bglong(d, 0*4), bglong(d, 1*4)); + s := sys->sprint("cursor %d %d 16 32 ", hot.x, hot.y); + for(i := 2*4; i < len d; i++){ + c := int d[i]; + s[len s] = Hex[c >> 4]; + s[len s] = Hex[c & 16rf]; + } + return w.wmctl(s); +} + +run(sync, ctl: chan of string, ld: string, argv: list of string) +{ + Rcmeta: con "|<>&^*[]?();"; + sys->pctl(Sys->FORKNS, nil); + if(sys->bind("#₪", "/srv", Sys->MCREATE) == -1){ + sync <-= sys->sprint("cannot bind srv device: %r"); + exit; + } + srvname := "/srv/9win."+string sys->pctl(0, nil); # XXX do better. + fd := sys->create(srvname, Sys->ORDWR, 8r600); + if(fd == nil){ + sync <-= sys->sprint("cannot create %s: %r", srvname); + exit; + } + sync <-= nil; + spawn export(fd, ctl); + sh->run(nil, "os" :: + "rc" :: "-c" :: + "mount "+srvname+" /mnt/term;"+ + "rm "+srvname+";"+ + "bind -b /mnt/term"+ld+" /dev;"+ + "bind /mnt/term/dev/draw /dev/draw ||"+ + "bind -a /mnt/term/dev /dev;"+ + quotedc("cd"::"/mnt/term"+cwd()::nil, Rcmeta)+";"+ + quotedc(argv, Rcmeta)+";":: + nil + ); +} + +export(fd: ref Sys->FD, ctl: chan of string) +{ + sys->export(fd, "/", Sys->EXPWAIT); + ctl <-= "exit"; +} + +inf2p9key(c: int): int +{ + KF: import Keyboard; + + P9KF: con 16rF000; + Spec: con 16rF800; + Khome: con P9KF|16r0D; + Kup: con P9KF|16r0E; + Kpgup: con P9KF|16r0F; + Kprint: con P9KF|16r10; + Kleft: con P9KF|16r11; + Kright: con P9KF|16r12; + Kdown: con Spec|16r00; + Kview: con Spec|16r00; + Kpgdown: con P9KF|16r13; + Kins: con P9KF|16r14; + Kend: con P9KF|16r18; + Kalt: con P9KF|16r15; + Kshift: con P9KF|16r16; + Kctl: con P9KF|16r17; + + case c { + Keyboard->LShift => + return Kshift; + Keyboard->LCtrl => + return Kctl; + Keyboard->LAlt => + return Kalt; + Keyboard->Home => + return Khome; + Keyboard->End => + return Kend; + Keyboard->Up => + return Kup; + Keyboard->Down => + return Kdown; + Keyboard->Left => + return Kleft; + Keyboard->Right => + return Kright; + Keyboard->Pgup => + return Kpgup; + Keyboard->Pgdown => + return Kpgdown; + Keyboard->Ins => + return Kins; + + # function keys + KF|1 or + KF|2 or + KF|3 or + KF|4 or + KF|5 or + KF|6 or + KF|7 or + KF|8 or + KF|9 or + KF|10 or + KF|11 or + KF|12 => + return (c - KF) + P9KF; + } + return c; +} + +cwd(): string +{ + return sys->fd2path(sys->open(".", Sys->OREAD)); +} + +# from string.b, waiting for declaration to be uncommented. +quotedc(argv: list of string, cl: string): string +{ + s := ""; + while (argv != nil) { + arg := hd argv; + for (i := 0; i < len arg; i++) { + c := arg[i]; + if (c == ' ' || c == '\t' || c == '\n' || c == '\'' || in(c, cl)) + break; + } + if (i < len arg || arg == nil) { + s += "'" + arg[0:i]; + for (; i < len arg; i++) { + if (arg[i] == '\'') + s[len s] = '\''; + s[len s] = arg[i]; + } + s[len s] = '\''; + } else + s += arg; + if (tl argv != nil) + s[len s] = ' '; + argv = tl argv; + } + return s; +} + +in(c: int, s: string): int +{ + n := len s; + if(n == 0) + return 0; + ans := 0; + negate := 0; + if(s[0] == '^') { + negate = 1; + s = s[1:]; + n--; + } + for(i := 0; i < n; i++) { + if(s[i] == '-' && i > 0 && i < n-1) { + if(c >= s[i-1] && c <= s[i+1]) { + ans = 1; + break; + } + i++; + } + else + if(c == s[i]) { + ans = 1; + break; + } + } + if(negate) + ans = !ans; + + # just to showcase labels +skip: + return ans; +} + +bglong(d: array of byte, i: int): int +{ + return int d[i] | (int d[i+1]<<8) | (int d[i+2]<<16) | (int d[i+3]<<24); +} diff --git a/tests/examplefiles/livescript-demo.ls b/tests/examplefiles/livescript-demo.ls new file mode 100644 index 00000000..03cbcc99 --- /dev/null +++ b/tests/examplefiles/livescript-demo.ls @@ -0,0 +1,43 @@ +a = -> [1 to 50] +const b = --> [2 til 5] +var c = ~~> 10_000_000km * 500ms - 16~ff / 32~lol +e = (a) -> (b) ~> (c) --> (d, e) ~~> <[list of words]> +dashes-identifiers = -> + a - a b -- c 1-1 1- -1 a- a a -a +underscores_i$d = -> + /regexp1/ + //regexp2//g + 'strings' and "strings" and \strings and \#$-"\'strings + +another-word-list = <[ more words ]> + +[2 til 10] + |> map (* 2) + |> filter (> 5) + |> fold (+) + +obj = + prop1: 1 + prop2: 2 + +class Class extends Anc-est-or + (args) -> + <- # Comment + <~ /* Comment */ + void undefined yes no on off + a.void b.undefined c.off d.if f.no g.not + avoid bundefined coff dif fno gnot + "inter #{2 + 2} #variable" + '''HELLO 'world' ''' + +copy = (from, to, callback) --> + error, data <- read file + return callback error if error? + error <~ write file, data + return callback error if error? + callback() + +take(n, [x, ...xs]:list) = + | n <= 0 => [] + | empty list => [] + | otherwise => [x] +++ take n - 1, xs diff --git a/tests/examplefiles/logos_example.xm b/tests/examplefiles/logos_example.xm new file mode 100644 index 00000000..39753e23 --- /dev/null +++ b/tests/examplefiles/logos_example.xm @@ -0,0 +1,28 @@ +%hook ABC +- (id)a:(B)b { + %log; + return %orig(nil); +} +%end + +%subclass DEF: NSObject +- (id)init { + [%c(RuntimeAccessibleClass) alloc]; + return nil; +} +%end + +%group OptionalHooks +%hook ABC +- (void)release { + [self retain]; + %orig; +} +%end +%end + +%ctor { + %init; + if(OptionalCondition) + %init(OptionalHooks); +} diff --git a/tests/examplefiles/main.cmake b/tests/examplefiles/main.cmake index dac3da43..71dc3ce7 100644 --- a/tests/examplefiles/main.cmake +++ b/tests/examplefiles/main.cmake @@ -1,3 +1,5 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6 FATAL_ERROR) + SET( SOURCES back.c io.c main.c ) MESSAGE( ${SOURCES} ) # three arguments, prints "back.cio.cmain.c" MESSAGE( "${SOURCES}" ) # one argument, prints "back.c;io.c;main.c" diff --git a/tests/examplefiles/markdown.lsp b/tests/examplefiles/markdown.lsp new file mode 100755 index 00000000..8159082b --- /dev/null +++ b/tests/examplefiles/markdown.lsp @@ -0,0 +1,679 @@ +#!/usr/bin/env newlisp + +;; @module markdown +;; @author cormullion +;; @description a port of John Gruber's Markdown to newLISP +;; @location http://unbalanced-parentheses.nfshost.com/ +;; @version of date 2011-10-02 22:36:02 +;; version history: at the end +;; a port of John Gruber's Markdown.pl (http://daringfireball.net/markdown) script to newLISP... +;; see his original Perl script for explanations of the fearsome regexen and +;; byzantine logic, etc... +;; TODO: +;; the following Markdown tests fail: +;; Inline HTML (Advanced) ... FAILED +;; Links, reference style ... FAILED -- nested brackets +;; Links, shortcut references ... FAILED +;; Markdown Documentation - Syntax ... FAILED +;; Ordered and unordered lists ... FAILED -- a nested ordered list error +;; parens in url : .jpg) see (Images.text) +;; Add: email address scrambling + +(context 'Hash) +(define HashTable:HashTable) + +(define (build-escape-table) + (set '*escape-chars* [text]\`*_{}[]()>#+-.![/text]) + (dolist (c (explode *escape-chars*)) + (HashTable c (hash c)))) + +(define (init-hash txt) + ; finds a hash identifier that doesn't occur anywhere in the text + (set 'counter 0) + (set 'hash-prefix "HASH") + (set 'hash-id (string hash-prefix counter)) + (do-while (find hash-id txt) + (set 'hash-id (string hash-prefix (inc counter)))) + (Hash:build-escape-table)) + +(define (hash s) + (HashTable s (string hash-id (inc counter)))) + +(context 'markdown) + +(define (markdown:markdown txt) + (initialize) + (Hash:init-hash txt) + (unescape-special-chars + (block-transforms + (strip-link-definitions + (protect + (cleanup txt)))))) + +(define (initialize) + (set '*escape-pairs* '( + ({\\\\} {\}) + ({\\`} {`}) + ({\\\*} {*}) + ({\\_} {_}) + ([text]\\\{[/text] [text]{[/text]) + ([text]\\\}[/text] [text]}[/text]) + ({\\\[} {[}) + ({\\\]} {]}) + ({\\\(} {(}) + ({\\\)} {)}) + ({\\>} {>}) + ({\\\#} {#}) + ({\\\+} {+}) + ({\\\-} {-}) + ({\\\.} {.}) + ({\\!} {!}))) + (set '*hashed-html-blocks* '()) + (set '*list-level* 0)) + +(define (block-transforms txt) + (form-paragraphs + (protect + (block-quotes + (code-blocks + (lists + (horizontal-rules + (headers txt)))))))) + +(define (span-transforms txt) + (line-breaks + (emphasis + (amps-and-angles + (auto-links + (anchors + (images + (escape-special-chars + (escape-special-chars (code-spans txt) 'inside-attributes))))))))) + +(define (tokenize-html xhtml) +; return list of tag/text portions of xhtml text + (letn ( + (tag-match [text]((?s:<!(-- .*? -- \s*)+>)| +(?s:<\?.*?\?>)| +(?:<[a-z/!$](?:[^<>]| +(?:<[a-z/!$](?:[^<>]| +(?:<[a-z/!$](?:[^<>]| +(?:<[a-z/!$](?:[^<>]| +(?:<[a-z/!$](?:[^<>]| +(?:<[a-z/!$](?:[^<>])*>))*>))*>))*>))*>))*>))[/text]) ; yeah, well... + (str xhtml) + (len (length str)) + (pos 0) + (tokens '())) + (while (set 'tag-start (find tag-match str 8)) + (if (< pos tag-start) + (push (list 'text (slice str pos (- tag-start pos))) tokens -1)) + (push (list 'tag $0) tokens -1) + (set 'str (slice str (+ tag-start (length $0)))) + (set 'pos 0)) + ; leftovers + (if (< pos len) + (push (list 'text (slice str pos (- len pos))) tokens -1)) + tokens)) + +(define (escape-special-chars txt (within-tag-attributes nil)) + (let ((temp (tokenize-html txt)) + (new-text {})) + (dolist (pair temp) + (if (= (first pair) 'tag) + ; 'tag + (begin + (set 'new-text (replace {\\} (last pair) (HashTable {\\}) 0)) + (replace [text](?<=.)</?code>(?=.)[/text] new-text (HashTable {`}) 0) + (replace {\*} new-text (HashTable {*}) 0) + (replace {_} new-text (HashTable {_} ) 0)) + ; 'text + (if within-tag-attributes + (set 'new-text (last pair)) + (set 'new-text (encode-backslash-escapes (last pair))))) + (setf (temp $idx) (list (first pair) new-text))) + ; return as text + (join (map last temp)))) + +(define (encode-backslash-escapes t) + (dolist (pair *escape-pairs*) + (replace (first pair) t (HashTable (last pair)) 14))) + +(define (encode-code s) + ; encode/escape certain characters inside Markdown code runs + (replace {&} s "&" 0) + (replace {<} s "<" 0) + (replace {>} s ">" 0) + (replace {\*} s (HashTable {\\}) 0) + (replace {_} s (HashTable {_}) 0) + (replace "{" s (HashTable "{") 0) + (replace {\[} s (HashTable {[}) 0) + (replace {\]} s (HashTable {]}) 0) + (replace {\\} s (HashTable "\\") 0)) + +(define (code-spans s) + (replace + {(?<!\\)(`+)(.+?)(?<!`)\1(?!`)} + s + (string {<code>} (encode-code (trim $2)) {</code>}) + 2)) + +(define (encode-alt s) + (replace {&} s "&" 0) + (replace {"} s """ 0)) + +(define (images txt) + (let ((alt-text {}) + (url {}) + (title {}) + (ref-regex {(!\[(.*?)\][ ]?(?:\n[ ]*)?\[(.*?)\])}) + (inline-regex {(!\[(.*?)\]\([ \t]*<?(\S+?)>?[ \t]*((['"])(.*?)\5[ \t]*)?\))}) + (whole-match {}) + (result {}) + (id-ref {}) + (url {})) + ; reference links ![alt text][id] + (replace + ref-regex + txt + (begin + (set 'whole-match $1 'alt-text $2 'id-ref $3) + (if alt-text + (replace {"} alt-text {"} 0)) + (if (empty? id-ref) + (set 'id-ref (lower-case alt-text))) + (if (lookup id-ref *link-database*) + (set 'url (first (lookup id-ref *link-database*))) + (set 'url nil)) + (if url + (begin + (replace {\*} url (HashTable {*}) 0) + (replace {_} url (HashTable {_}) 0) + )) + (if (last (lookup id-ref *link-database*)) + ; title + (begin + (set 'title (last (lookup id-ref *link-database*))) + (replace {"} title {"} 0) + (replace {\*} title (HashTable {*}) 0) + (replace {_} title (HashTable {_}) 0)) + ; no title + (set 'title {}) + ) + (if url + (set 'result (string + {<img src="} + (trim url) + {" alt="} + alt-text {" } + (if (not (empty? title)) + (string { title="} title {"}) {}) + { />})) + (set 'result whole-match)) + ) + 0 + ) + ; inline image refs:  + (replace + inline-regex + txt + (begin + (set 'whole-match $1) + (set 'alt-text $2) + (set 'url $3) + (set 'title $6) + (if alt-text + (replace {"} alt-text {"} 0) + (set 'alt-text {})) + (if title + (begin + (replace {"} title {"} 0) + (replace {\*} title (HashTable {*}) 0) + (replace {_} title (HashTable {_}) 0)) + (set 'title {})) + (replace {\*} url (HashTable {*}) 0) + (replace {_} url (HashTable {_}) 0) + (string + {<img src="} + (trim url) + {" alt="} + alt-text {" } + (if title (string {title="} title {"}) {}) { />}) + ) + 0 + ) + ; empty ones are possible + (set '$1 {}) + (replace {!\[(.*?)\]\([ \t]*\)} + txt + (string {<img src="" alt="} $1 {" title="" />}) + 0))) + +(define (make-anchor link-text id-ref ) +; Link defs are in the form: ^[id]: url "optional title" +; stored in link db list as (id (url title)) +; params are text to be linked and the id of the link in the db +; eg bar 1 for [bar][1] + + (let ((title {}) + (id id-ref) + (url nil)) + (if link-text + (begin + (replace {"} link-text {"} 0) + (replace {\n} link-text { } 0) + (replace {[ ]?\n} link-text { } 0))) + (if (null? id ) (set 'id (lower-case link-text))) + (if (not (nil? (lookup id *link-database*))) + (begin + (set 'url (first (lookup id *link-database*))) + (replace {\*} url (HashTable {*}) 0) + (replace {_} url (HashTable {_}) 0) + (if (set 'title (last (lookup id *link-database*))) + (begin + (replace {"} title {"} 0) + (replace {\*} title (HashTable {*}) 0) + (replace {_} title (HashTable {_}) 0)) + (set 'title {}))) + (set 'url nil)) + (if url + (string {<a href="} (trim url) + {"} + (if (not (= title {})) (string { title="} (trim title) {"}) {}) + {>} link-text {</a>}) + (string {[} link-text {][} id-ref {]})))) + +(define (anchors txt) + (letn ((nested-brackets {(?>[^\[\]]+)*}) + (ref-link-regex (string {(\[(} nested-brackets {)\][ ]?(?:\n[ ]*)?\[(.*?)\])})) + (inline-regex {(\[(.*?)\]\([ ]*<?(.*?\)?)>?[ ]*((['"])(.*?)\5[ \t]*)?\))}) + (link-text {}) + (url {}) + (title {})) + ; reference-style links: [link text] [id] + (set '$1 {} '$2 {} '$3 {} '$4 {} '$5 {} '$6 {}) ; i still don't think I should have to do this... + + ; what about this regex instead? + (set 'ref-link-regex {(\[(.*?)\][ ]?\[(.*?)\])}) + + (replace ref-link-regex txt (make-anchor $2 $3) 8) ; $2 is link text, $3 is id + ; inline links: [link text](url "optional title") + (set '$1 {} '$2 {} '$3 {} '$4 {} '$5 {} '$6 {}) + (replace + inline-regex + txt + (begin + (set 'link-text $2) + (set 'url $3) + (set 'title $6) + (if link-text (replace {"} link-text {"} 0)) + (if title + (begin + (replace {"} title {"} 0) + (replace {\*} title (HashTable {*}) 0) + (replace {_} title (HashTable {_}) 0)) + (set 'title {})) + (replace {\*} url (HashTable {*}) 0) + (replace {_} url (HashTable {_}) 0) + (replace {^<(.*)>$} url $1 0) + (string + {<a href="} + (trim url) + {"} + (if (not (= title {})) + (string { title="} (trim title) {"}) + {}) + {>} link-text {</a>} + )) + 8 + ) ; replace + ) txt) + +(define (auto-links txt) + (replace + [text]<((https?|ftp):[^'">\s]+)>[/text] + txt + (string {<a href="} $1 {">} $1 {</a>}) + 0 + ) + ; to-do: email ... +) + +(define (amps-and-angles txt) +; Smart processing for ampersands and angle brackets + (replace + [text]&(?!\#?[xX]?(?:[0-9a-fA-F]+|\w+);)[/text] + txt + {&} + 10 + ) + (replace + [text]<(?![a-z/?\$!])[/text] + txt + {<} + 10)) + +(define (emphasis txt) + ; italics/bold: strong first + (replace + [text] (\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1 [/text] + txt + (string {<strong>} $2 {</strong>}) + 8 + ) + (replace + [text] (\*|_) (?=\S) (.+?) (?<=\S) \1 [/text] + txt + (string {<em>} $2 {</em>}) + 8 + )) + +(define (line-breaks txt) + ; handles line break markers + (replace " {2,}\n" txt " <br/>\n" 0)) + +(define (hex-str-to-unicode-char strng) + ; given a five character string, assume it's "U" + 4 hex chars and convert + ; return the character... + (char (int (string "0x" (1 strng)) 0 16))) + +(define (ustring s) + ; any four digit string preceded by U + (replace "U[0-9a-f]{4,}" s (hex-str-to-unicode-char $0) 0)) + +(define (cleanup txt) + ; cleanup the text by normalizing some possible variations + (replace "\r\n|\r" txt "\n" 0) ; standardize line ends + (push "\n\n" txt -1) ; end with two returns + (set 'txt (detab txt)) ; convert tabs to spaces + + ; convert inline Unicode: + (set 'txt (ustring txt)) + (replace "\n[ \t]+\n" txt "\n\n" 0) ; lines with only spaces and tabs + ) + +(define (protect txt) + ; protect or "hash html blocks" + (letn ((nested-block-regex [text](^<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math|ins|del)\b(.*\n)*?</\2>[ \t]*(?=\n+|\Z))[/text]) + (liberal-tag-regex [text](^<(p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|script|noscript|form|fieldset|iframe|math)\b(.*\n)*?.*</\2>[ \t]*(?=\n+|\Z))[/text]) + (hr-regex [text](?:(?<=\n\n)|\A\n?)([ ]{0,3}<(hr)\b([^<>])*?/?>[ \t]*(?=\n{2,}|\Z))[/text]) + (html-comment-regex [text](?:(?<=\n\n)|\A\n?)([ ]{0,3}(?s:<!(--.*?--\s*)+>)[ \t]*(?=\n{2,}|\Z))[/text]) + (results '()) + (chunk-count (length (set 'chunks (parse txt "\n\n")))) + (chunk-size 500)) + + ; due to a limitation in PCRE, long sections have to be divided up otherwise we'll crash + ; so divide up long texts into chunks, then do the regex on each chunk + ; not an ideal solution, but it works ok :( + + (for (i 0 chunk-count chunk-size) + ; do a chunk + (set 'text-chunk (join (i (- (min chunk-count (- (+ i chunk-size) 1)) i) chunks) "\n\n")) + (dolist (rgx (list nested-block-regex liberal-tag-regex hr-regex html-comment-regex)) + (replace + rgx + text-chunk + (begin + (set 'key (Hash:hash $1)) + (push (list key $1 ) *hashed-html-blocks* -1) + (string "\n\n" key "\n\n")) + 2)) + ; save this partial result + (push text-chunk results -1) + ) ; for + ; return string result + (join results "\n\n"))) + +(define (unescape-special-chars t) + ; Swap back in all the special characters we've hidden. + (dolist (pair (HashTable)) + (replace (last pair) t (first pair) 10)) t) + +(define (strip-link-definitions txt) + ; strip link definitions from the text and store them + ; Link defs are in the form: ^[id]: url "optional title" + ; stored in link db list as (id (url title)) + (let ((link-db '()) + (url {}) + (id {}) + (title {})) + (replace + [text]^[ ]{0,3}\[(.+)\]:[ \t]*\n?[ \t]*<?(\S+?)>?[ \t]*\n?[ \t]*(?:(?<=\s)["(](.+?)[")][ \t]*)?(?:\n+|\Z)[/text] + txt + (begin + (set 'id (lower-case $1) 'url (amps-and-angles $2) 'title $3) + (if title (replace {"} title {"} 0)) + (push (list id (list url title)) link-db) + (set '$3 {}) ; necessary? + (string {}) ; remove from text + ) + 10) + (set '*link-database* link-db) + txt)) + +(define (horizontal-rules txt) + (replace + [text]^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$[/text] + txt + "\n<hr />" + 14) + (replace + [text]^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$[/text] + txt + "\n<hr />" + 14) + (replace + [text]^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$[/text] + txt + "\n<hr />" + 14)) + +(define (headers txt) + ; setext headers + (let ((level 1)) + (replace + [text]^(.+)[ \t]*\n=+[ \t]*\n+[/text] + txt + (string "<h1>" (span-transforms $1) "</h1>\n\n") + 2) + + (replace + [text]^(.+)[ \t]*\n-+[ \t]*\n+[/text] + txt + (string "<h2>" (span-transforms $1) "</h2>\n\n") + 2) + ; atx headers + (replace + [text]^(\#{1,6})\s*(.+?)[ ]*\#*(\n+)[/text] + txt + (begin + (set 'level (length $1)) + (string "<h" level ">" (span-transforms $2) "</h" level ">\n\n") + ) + 2))) + +(define (lists txt) + (letn ((marker-ul {[*+-]}) + (marker-ol {\d+[.]}) + (marker-any (string {(?:} marker-ul {|} marker-ol {)})) + (whole-list-regex (string [text](([ ]{0,3}([/text] marker-any [text])[ \t]+)(?s:.+?)(\z|\n{2,}(?=\S)(?![ \t]*[/text] marker-any [text][ \t]+)))[/text])) + (my-list {}) + (list-type {}) + (my-result {})) + (replace + (if (> *list-level* 0) + (string {^} whole-list-regex) + (string {(?:(?<=\n\n)|\A\n?)} whole-list-regex)) + txt + (begin + (set 'my-list $1) + (if (find $3 marker-ul) + (set 'list-type "ul" 'marker-type marker-ul) + (set 'list-type "ol" 'marker-type marker-ol)) + (replace [text]\n{2,}[/text] my-list "\n\n\n" 0) + (set 'my-result (process-list-items my-list marker-any)) + (replace {\s+$} my-result {} 0) + (string {<} list-type {>} "\n" my-result "\n" {</} list-type {>} "\n")) + 10 ; must be multiline + ))) + +(define (process-list-items list-text marker-any) + (let ((list-regex (string [text](\n)?(^[ \t]*)([/text] marker-any [text])[ \t]+((?s:.+?)(\n{1,2}))(?=\n*(\z|\2([/text] marker-any [text])[ \t]+))[/text])) + (item {}) + (leading-line {}) + (leading-space {}) + (result {})) + (inc *list-level*) + (replace [text]\n{2,}\z[/text] list-text "\n" 0) + (set '$1 {} '$2 {} '$3 {} '$4 {} '$5 {}) + (replace + list-regex + list-text + (begin + (set 'item $4) + (set 'leading-line $1) + (set 'leading-space $2) + (if (or (not (empty? leading-line)) (ends-with item "\n{2,}" 0)) + (set 'item (block-transforms (outdent item))) + ; recurse for sub lists + (begin + (set 'item (lists (outdent item))) + (set 'item (span-transforms (trim item "\n"))) + )) + (string {<li>} item {</li>} "\n")) + 10) + (dec *list-level*) + list-text)) + +(define (code-blocks txt) + (let ((code-block {}) + (token-list '())) + (replace + [text](?:\n\n|\A)((?:(?:[ ]{4}|\t).*\n+)+)((?=^[ ]{0,3}\S)|\Z)[/text] + txt + (begin + (set 'code-block $1) + ; format if Nestor module is loaded and it's not marked as plain + (if (and (not (starts-with code-block " ;plain\n")) (context? Nestor)) + ; format newlisp + (begin + ; remove flag if present + (replace "[ ]{4};newlisp\n" code-block {} 0) + (set 'code-block (protect (Nestor:nlx-to-html (Nestor:my-read (trim (detab (outdent code-block)) "\n"))))) + code-block) + ; don't format + (begin + ; trim leading and trailing newlines + (replace "[ ]{4};plain\n" code-block {} 0) + (set 'code-block (trim (detab (encode-code (outdent code-block))) "\n")) + (set '$1 {}) + (set 'code-block (string "\n\n<pre><code>" code-block "\n</code></pre>\n\n"))))) + 10))) + +(define (block-quotes txt) + (let ((block-quote {})) + (replace + [text]((^[ \t]*>[ \t]?.+\n(.+\n)*\n*)+)[/text] + txt + (begin + (set 'block-quote $1) + (replace {^[ ]*>[ ]?} block-quote {} 2) + (replace {^[ ]+$} block-quote {} 2) + (set 'block-quote (block-transforms block-quote)) ; recurse + ; remove leading spaces + (replace + {(\s*<pre>.+?</pre>)} + block-quote + (trim $1) + 2) + (string "<blockquote>\n" block-quote "\n</blockquote>\n\n")) + 2))) + +(define (outdent s) + (replace [text]^(\t|[ ]{1,4})[/text] s {} 2)) + +(define (detab s) + (replace [text](.*?)\t[/text] + s + (string $1 (dup { } (- 4 (% (length $1) 4)))) + 2)) + +(define (form-paragraphs txt) + (let ((grafs '()) + (original nil)) + (set 'txt (trim txt "\n")) ; strip blank lines before and after + (set 'grafs (parse txt "\n{2,}" 0)) ; split + (dolist (p grafs) + (if (set 'original (lookup p *hashed-html-blocks*)) + ; html blocks + (setf (grafs $idx) original) + ; wrap <p> tags round everything else + (setf (grafs $idx) (string {<p>} (replace {^[ ]*} (span-transforms p) {} (+ 4 8 16)) {</p>})))) + (join grafs "\n\n"))) + +[text] +; three command line arguments: let's hope last one is a file +(when (= 3 (length (main-args))) + (println (markdown (read-file (main-args 2)))) + (exit)) + +; hack for command-line and module loading +(set 'level (sys-info 3)) + +; if level is 2, then we're probably invoking markdown.lsp directly +; if level is > 3, then we're probably loading it into another script... + +(when (= level 2) + ; running on command line, read STDIN and execute: + (while (read-line) + (push (current-line) *stdin* -1)) + (println (markdown (join *stdin* "\n"))) + (exit)) +[/text] + +;; version 2011-09-16 16:31:29 +;; Changed to different hash routine. Profiling shows that hashing takes 40% of the execution time. +;; Unfortunately this new version is only very slightly faster. +;; Command-line arguments hack in previous version doesn't work. +;; +;; version 2011-08-18 15:04:40 +;; various fixes, and added hack for running this from the command-line: +;; echo "hi there" | newlisp markdown.lsp +;; echo "hello world" | markdown.lsp +;; cat file.text | newlisp markdown.lsp +;; +;; version 2010-11-14 17:34:52 +;; some problems in ustring. Probably remove it one day, as it's non standard... +;; +;; version 2010-10-14 18:41:38 +;; added code to work round PCRE crash in (protect ... +;; +;; version date 2010-07-10 22:20:25 +;; modified call to 'read' since lutz has changed it +;; +;; version date 2009-11-16 22:10:10 +;; fixed bug in tokenize.html +;; +;; version date 2008-10-08 18:44:46 +;; changed nth-set to setf to be version-10 ready. +;; This means that now this script will NOT work with +;; earlier versions of newLISP!!!!!!!!!!! +;; requires Nestor if you want source code colouring... +;; +;; version date 2008-08-08 16:54:56 +;; changed (unless to (if (not ... :( +;; +;; version date 2008-07-20 14:!2:29 +;; added hex-str-to-unicode-char ustring +;; +;; version date 2008-03-07 15:36:09 +;; fixed load error +;; +;; version date 2007-11-17 16:20:57 +;; added syntax colouring module +;; +;; version date 2007-11-14 09:19:42 +;; removed reliance on dostring for compatibility with 9.1 + + +; eof
\ No newline at end of file diff --git a/tests/examplefiles/matlab_sample b/tests/examplefiles/matlab_sample index 1834050c..4f61afe8 100644 --- a/tests/examplefiles/matlab_sample +++ b/tests/examplefiles/matlab_sample @@ -13,7 +13,8 @@ end a = rand(30); b = rand(30); -c = a .* b ./ a \ (b .* a + b - a); +c = a .* b ./ a \ ... comment at end of line and continuation + (b .* a + b - a); c = a' * b'; % note: these ticks are for transpose, not quotes. @@ -24,4 +25,6 @@ disp('a comment symbol, %, in a string'); function y=myfunc(x) y = exp(x); - + {% +a block comment + %} diff --git a/tests/examplefiles/metagrammar.treetop b/tests/examplefiles/metagrammar.treetop new file mode 100644 index 00000000..acd6af63 --- /dev/null +++ b/tests/examplefiles/metagrammar.treetop @@ -0,0 +1,455 @@ +module Treetop + module Compiler + grammar Metagrammar + rule treetop_file + requires:(space? require_statement)* prefix:space? module_or_grammar suffix:space? { + def compile + requires.text_value + prefix.text_value + module_or_grammar.compile + suffix.text_value + end + } + end + + rule require_statement + prefix:space? "require" [ \t]+ [^\n\r]+ [\n\r] + end + + rule module_or_grammar + module_declaration / grammar + end + + rule module_declaration + prefix:('module' space name:([A-Z] alphanumeric_char* ('::' [A-Z] alphanumeric_char*)*) space) module_contents:(module_declaration / grammar) suffix:(space 'end') { + def compile + prefix.text_value + module_contents.compile + suffix.text_value + end + + def parser_name + prefix.name.text_value+'::'+module_contents.parser_name + end + } + end + + rule grammar + 'grammar' space grammar_name space ('do' space)? declaration_sequence space? 'end' <Grammar> + end + + rule grammar_name + ([A-Z] alphanumeric_char*) + end + + rule declaration_sequence + head:declaration tail:(space declaration)* <DeclarationSequence> { + def declarations + [head] + tail + end + + def tail + super.elements.map { |elt| elt.declaration } + end + } + / + '' { + def compile(builder) + end + } + end + + rule declaration + parsing_rule / include_declaration + end + + rule include_declaration + 'include' space [A-Z] (alphanumeric_char / '::')* { + def compile(builder) + builder << text_value + end + } + end + + rule parsing_rule + 'rule' space nonterminal space ('do' space)? parsing_expression space 'end' <ParsingRule> + end + + rule parsing_expression + choice / sequence / primary + end + + rule choice + head:alternative tail:(space? '/' space? alternative)+ <Choice> { + def alternatives + [head] + tail + end + + def tail + super.elements.map {|elt| elt.alternative} + end + + def inline_modules + (alternatives.map {|alt| alt.inline_modules }).flatten + end + } + end + + rule sequence + head:labeled_sequence_primary tail:(space labeled_sequence_primary)+ node_class_declarations <Sequence> { + def sequence_elements + [head] + tail + end + + def tail + super.elements.map {|elt| elt.labeled_sequence_primary } + end + + def inline_modules + (sequence_elements.map {|elt| elt.inline_modules}).flatten + + [sequence_element_accessor_module] + + node_class_declarations.inline_modules + end + + def inline_module_name + node_class_declarations.inline_module_name + end + } + end + + rule alternative + sequence / primary + end + + rule primary + prefix atomic { + def compile(address, builder, parent_expression=nil) + prefix.compile(address, builder, self) + end + + def prefixed_expression + atomic + end + + def inline_modules + atomic.inline_modules + end + + def inline_module_name + nil + end + } + / + prefix space? predicate_block { + def compile(address, builder, parent_expression=nil) + prefix.compile(address, builder, self) + end + def prefixed_expression + predicate_block + end + def inline_modules + [] + end + } + / + atomic suffix node_class_declarations { + def compile(address, builder, parent_expression=nil) + suffix.compile(address, builder, self) + end + + def optional_expression + atomic + end + + def node_class_name + node_class_declarations.node_class_name + end + + def inline_modules + atomic.inline_modules + node_class_declarations.inline_modules + end + + def inline_module_name + node_class_declarations.inline_module_name + end + } + / + atomic node_class_declarations { + def compile(address, builder, parent_expression=nil) + atomic.compile(address, builder, self) + end + + def node_class_name + node_class_declarations.node_class_name + end + + def inline_modules + atomic.inline_modules + node_class_declarations.inline_modules + end + + def inline_module_name + node_class_declarations.inline_module_name + end + } + end + + rule labeled_sequence_primary + label sequence_primary { + def compile(lexical_address, builder) + sequence_primary.compile(lexical_address, builder) + end + + def inline_modules + sequence_primary.inline_modules + end + + def label_name + if label.name + label.name + elsif sequence_primary.instance_of?(Nonterminal) + sequence_primary.text_value + else + nil + end + end + } + end + + rule label + (alpha_char alphanumeric_char*) ':' { + def name + elements[0].text_value + end + } + / + '' { + def name + nil + end + } + end + + rule sequence_primary + prefix atomic { + def compile(lexical_address, builder) + prefix.compile(lexical_address, builder, self) + end + + def prefixed_expression + elements[1] + end + + def inline_modules + atomic.inline_modules + end + + def inline_module_name + nil + end + } + / + prefix space? predicate_block { + def compile(address, builder, parent_expression=nil) + prefix.compile(address, builder, self) + end + def prefixed_expression + predicate_block + end + def inline_modules + [] + end + } + / + atomic suffix { + def compile(lexical_address, builder) + suffix.compile(lexical_address, builder, self) + end + + def node_class_name + nil + end + + def inline_modules + atomic.inline_modules + end + + def inline_module_name + nil + end + } + / + atomic + end + + rule suffix + repetition_suffix / optional_suffix + end + + rule optional_suffix + '?' <Optional> + end + + rule node_class_declarations + node_class_expression trailing_inline_module { + def node_class_name + node_class_expression.node_class_name + end + + def inline_modules + trailing_inline_module.inline_modules + end + + def inline_module + trailing_inline_module.inline_module + end + + def inline_module_name + inline_module.module_name if inline_module + end + } + end + + rule repetition_suffix + '+' <OneOrMore> / '*' <ZeroOrMore> / occurrence_range + end + + rule occurrence_range + space? min:([0-9])* '..' max:([0-9])* <OccurrenceRange> + end + + rule prefix + '&' <AndPredicate> / '!' <NotPredicate> / '~' <TransientPrefix> + end + + rule atomic + terminal + / + nonterminal + / + parenthesized_expression + end + + rule parenthesized_expression + '(' space? parsing_expression space? ')' <ParenthesizedExpression> { + def inline_modules + parsing_expression.inline_modules + end + } + end + + rule nonterminal + !keyword_inside_grammar (alpha_char alphanumeric_char*) <Nonterminal> + end + + rule terminal + quoted_string / character_class / anything_symbol + end + + rule quoted_string + (single_quoted_string / double_quoted_string) { + def string + super.text_value + end + } + end + + rule double_quoted_string + '"' string:(!'"' ("\\\\" / '\"' / .))* '"' <Terminal> + end + + rule single_quoted_string + "'" string:(!"'" ("\\\\" / "\\'" / .))* "'" <Terminal> + end + + rule character_class + '[' characters:(!']' ('\\' . / bracket_expression / !'\\' .))+ ']' <CharacterClass> { + def characters + super.text_value + end + } + end + + rule bracket_expression + '[:' '^'? ( + 'alnum' / 'alpha' / 'blank' / 'cntrl' / 'digit' / 'graph' / 'lower' / + 'print' / 'punct' / 'space' / 'upper' / 'xdigit' / 'word' + ) ':]' + end + + rule anything_symbol + '.' <AnythingSymbol> + end + + rule node_class_expression + space '<' (!'>' .)+ '>' { + def node_class_name + elements[2].text_value + end + } + / + '' { + def node_class_name + nil + end + } + end + + rule trailing_inline_module + space inline_module { + def inline_modules + [inline_module] + end + + def inline_module_name + inline_module.module_name + end + } + / + '' { + def inline_modules + [] + end + + def inline_module + nil + end + + def inline_module_name + nil + end + } + end + + rule predicate_block + '' inline_module <PredicateBlock> + end + + rule inline_module + '{' (inline_module / ![{}] .)* '}' <InlineModule> + end + + rule keyword_inside_grammar + ('rule' / 'end') !non_space_char + end + + rule non_space_char + !space . + end + + rule alpha_char + [A-Za-z_] + end + + rule alphanumeric_char + alpha_char / [0-9] + end + + rule space + (white / comment_to_eol)+ + end + + rule comment_to_eol + '#' (!"\n" .)* + end + + rule white + [ \t\n\r] + end + end + end +end diff --git a/tests/examplefiles/minehunt.qml b/tests/examplefiles/minehunt.qml new file mode 100644 index 00000000..548e7e89 --- /dev/null +++ b/tests/examplefiles/minehunt.qml @@ -0,0 +1,112 @@ + /**************************************************************************** + ** + ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). + ** All rights reserved. + ** Contact: Nokia Corporation (qt-info@nokia.com) + ** + ** This file is part of the QtDeclarative module of the Qt Toolkit. + ** + ** $QT_BEGIN_LICENSE:LGPL$ + ** GNU Lesser General Public License Usage + ** This file may be used under the terms of the GNU Lesser General Public + ** License version 2.1 as published by the Free Software Foundation and + ** appearing in the file LICENSE.LGPL included in the packaging of this + ** file. Please review the following information to ensure the GNU Lesser + ** General Public License version 2.1 requirements will be met: + ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. + ** + ** In addition, as a special exception, Nokia gives you certain additional + ** rights. These rights are described in the Nokia Qt LGPL Exception + ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. + ** + ** GNU General Public License Usage + ** Alternatively, this file may be used under the terms of the GNU General + ** Public License version 3.0 as published by the Free Software Foundation + ** and appearing in the file LICENSE.GPL included in the packaging of this + ** file. Please review the following information to ensure the GNU General + ** Public License version 3.0 requirements will be met: + ** http://www.gnu.org/copyleft/gpl.html. + ** + ** Other Usage + ** Alternatively, this file may be used in accordance with the terms and + ** conditions contained in a signed written agreement between you and Nokia. + ** + ** + ** + ** + ** + ** $QT_END_LICENSE$ + ** + ****************************************************************************/ + + import QtQuick 1.0 + import "MinehuntCore" 1.0 + + Item { + id: field + property int clickx: 0 + property int clicky: 0 + + width: 450; height: 450 + + Image { source: "MinehuntCore/pics/background.png"; anchors.fill: parent; fillMode: Image.Tile } + + Grid { + anchors.horizontalCenter: parent.horizontalCenter + columns: 9; spacing: 1 + + Repeater { + id: repeater + model: tiles + delegate: Tile {} + } + } + + Row { + id: gamedata + x: 20; spacing: 20 + anchors.bottom: field.bottom; anchors.bottomMargin: 15 + + Image { + source: "MinehuntCore/pics/quit.png" + scale: quitMouse.pressed ? 0.8 : 1.0 + smooth: quitMouse.pressed + y: 10 + MouseArea { + id: quitMouse + anchors.fill: parent + anchors.margins: -20 + onClicked: Qt.quit() + } + } + Column { + spacing: 2 + Image { source: "MinehuntCore/pics/bomb-color.png" } + Text { anchors.horizontalCenter: parent.horizontalCenter; color: "white"; text: numMines } + } + + Column { + spacing: 2 + Image { source: "MinehuntCore/pics/flag-color.png" } + Text { anchors.horizontalCenter: parent.horizontalCenter; color: "white"; text: numFlags } + } + } + + Image { + anchors.bottom: field.bottom; anchors.bottomMargin: 15 + anchors.right: field.right; anchors.rightMargin: 20 + source: isPlaying ? 'MinehuntCore/pics/face-smile.png' : + hasWon ? 'MinehuntCore/pics/face-smile-big.png': 'MinehuntCore/pics/face-sad.png' + + MouseArea { anchors.fill: parent; onPressed: reset() } + } + Text { + anchors.centerIn: parent; width: parent.width - 20 + horizontalAlignment: Text.AlignHCenter + wrapMode: Text.WordWrap + text: "Minehunt demo has to be compiled to run.\n\nPlease see README." + color: "white"; font.bold: true; font.pixelSize: 14 + visible: tiles == undefined + } + + } diff --git a/tests/examplefiles/nanomsg.intr b/tests/examplefiles/nanomsg.intr new file mode 100644 index 00000000..d21f62cc --- /dev/null +++ b/tests/examplefiles/nanomsg.intr @@ -0,0 +1,95 @@ +module: nanomsg +synopsis: generated bindings for the nanomsg library +author: Bruce Mitchener, Jr. +copyright: See LICENSE file in this distribution. + +define simple-C-mapped-subtype <C-buffer-offset> (<C-char*>) + export-map <machine-word>, export-function: identity; +end; + +define interface + #include { + "sp/sp.h", + "sp/fanin.h", + "sp/inproc.h", + "sp/pair.h", + "sp/reqrep.h", + "sp/survey.h", + "sp/fanout.h", + "sp/ipc.h", + "sp/pubsub.h", + "sp/tcp.h" + }, + + exclude: { + "SP_HAUSNUMERO", + "SP_PAIR_ID", + "SP_PUBSUB_ID", + "SP_REQREP_ID", + "SP_FANIN_ID", + "SP_FANOUT_ID", + "SP_SURVEY_ID" + }, + + equate: {"char *" => <c-string>}, + + rename: { + "sp_recv" => %sp-recv, + "sp_send" => %sp-send, + "sp_setsockopt" => %sp-setsockopt + }; + + function "sp_version", + output-argument: 1, + output-argument: 2, + output-argument: 3; + + function "sp_send", + map-argument: { 2 => <C-buffer-offset> }; + + function "sp_recv", + map-argument: { 2 => <C-buffer-offset> }; + +end interface; + +// Function for adding the base address of the repeated slots of a <buffer> +// to an offset and returning the result as a <machine-word>. This is +// necessary for passing <buffer> contents across the FFI. + +define function buffer-offset + (the-buffer :: <buffer>, data-offset :: <integer>) + => (result-offset :: <machine-word>) + u%+(data-offset, + primitive-wrap-machine-word + (primitive-repeated-slot-as-raw + (the-buffer, primitive-repeated-slot-offset(the-buffer)))) +end function; + +define inline function sp-send (socket :: <integer>, data :: <buffer>, flags :: <integer>) => (res :: <integer>) + %sp-send(socket, buffer-offset(data, 0), data.size, flags) +end; + +define inline function sp-recv (socket :: <integer>, data :: <buffer>, flags :: <integer>) => (res :: <integer>) + %sp-recv(socket, buffer-offset(data, 0), data.size, flags); +end; + +define inline method sp-setsockopt (socket :: <integer>, level :: <integer>, option :: <integer>, value :: <integer>) + with-stack-structure (int :: <C-int*>) + pointer-value(int) := value; + let setsockopt-result = + %sp-setsockopt(socket, level, option, int, size-of(<C-int*>)); + if (setsockopt-result < 0) + // Check error! + end; + setsockopt-result + end; +end; + +define inline method sp-setsockopt (socket :: <integer>, level :: <integer>, option :: <integer>, data :: <byte-string>) + let setsockopt-result = + %sp-setsockopt(socket, level, option, as(<c-string>, data), data.size); + if (setsockopt-result < 0) + // Check error! + end; + setsockopt-result +end; diff --git a/tests/examplefiles/nemerle_sample.n b/tests/examplefiles/nemerle_sample.n new file mode 100644 index 00000000..5236857d --- /dev/null +++ b/tests/examplefiles/nemerle_sample.n @@ -0,0 +1,87 @@ +using System; + +namespace Demo.Ns +{ + /// sample class + public class ClassSample : Base + { + /* sample multiline comment */ +#region region sample + fieldSample : int; +#endregion + + public virtual someMethod(str : string) : list[double] + { + def x = "simple string"; + def x = $"simple $splice string $(spliceMethod() + 1)"; + def x = <# + recursive <# string #> sample + #>; + def x = $<# + recursive $splice <# string #> sample + ..$(lst; "; "; x => $"x * 2 = $(x * 2)") str + #>; + def x = @"somestring \"; + + def localFunc(arg) + { + arg + 1; + } + + match (localFunc(2)) + { + | 3 => "ok"; + | _ => "fail"; + } + + using (x = SomeObject()) + { + foreach (item in someCollection) + { + def i = try + { + int.Parse(item) + } + catch + { + | _ is FormatException => 0; + } + when (i > 0xff) + unless (i < 555L) + WriteLine(i); + + } + } + protected override overrideSample() : void + {} + + private privateSample() : void + {} + + public abstract abstractSample() : void + {} + } + + } + + module ModuleSample + { + } + + variant RgbColor { + | Red + | Yellow + | Green + | Different { + red : float; + green : float; + blue : float; + } + } + + macro sampleMacro(expr) + syntax ("write", expr) + { + <[ WriteLine($(expr : dyn)) ]> + } +} diff --git a/tests/examplefiles/objc_example.m b/tests/examplefiles/objc_example.m index c2a1c414..f4f27170 100644 --- a/tests/examplefiles/objc_example.m +++ b/tests/examplefiles/objc_example.m @@ -1,5 +1,19 @@ #import "Somefile.h" +@implementation ABC + +- (id)a:(B)b { + return 1; +} + +@end + +@implementation ABC + +- (void)xyz; + +@end + NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys: @"quattuor", @"four", @"quinque", @"five", @"sex", @"six", nil]; @@ -9,3 +23,13 @@ for (key in dictionary) { NSLog(@"English: %@, Latin: %@", key, [dictionary valueForKey:key]); } +// Literals +NSArray *a = @[ @"1", @"2" ]; + +NSDictionary *d = @{ @"key": @"value" }; + +NSNumber *n1 = @( 1 ); +NSNumber *n2 = @( [a length] ); + ++ (void)f1:(NSString *)s1; ++ (void)f2:(NSString *) s2; diff --git a/tests/examplefiles/objc_example2.m b/tests/examplefiles/objc_example2.m index 8cd9b060..b7a5a685 100644 --- a/tests/examplefiles/objc_example2.m +++ b/tests/examplefiles/objc_example2.m @@ -22,3 +22,6 @@ @synthesize lastModifiedDate; // implementation continues @end + ++ (void)f1:(NSString *)s1; ++ (void)f2:(NSString *)s2; diff --git a/tests/examplefiles/openedge_example b/tests/examplefiles/openedge_example new file mode 100644 index 00000000..e8c17e33 --- /dev/null +++ b/tests/examplefiles/openedge_example @@ -0,0 +1,34 @@ +{include.i} +{nested.i {include.i}} + +&SCOPED-DEFINE MY_NAME "Abe" + +DEF VAR i AS INT NO-UNDO. +i = 0xABE + 1337 / (1 * 1.00) + +def var clowercasetest as char no-undo. +DEF VAR vardashtest AS DATETIME-TZ NO-UNDO. + +DEFINE TEMP-TABLE ttNames NO-UNDO + FIELD cName AS CHAR + INDEX IXPK_ttNames IS PRIMARY UNIQUE cName. + +/* One-line comment */ +/* Two-line + Comment */ +/* + Nested + /* + Multiline + /* + Comment + */ + */ +*/ + +CREATE ttNames. +ASSIGN ttNames.cName = {&MY_NAME}. + +FOR EACH ttNames: + MESSAGE "Hello, " + ttNames.cName + '!' VIEW-AS ALERT-BOX. +END. diff --git a/tests/examplefiles/phpMyAdmin.spec b/tests/examplefiles/phpMyAdmin.spec new file mode 100644 index 00000000..120fbc92 --- /dev/null +++ b/tests/examplefiles/phpMyAdmin.spec @@ -0,0 +1,163 @@ +%define _myadminpath /var/www/myadmin +%define pkgrelease rc1 +%define microrelease 1 + +Name: phpMyAdmin +Version: 3.1.1 +Release: %{pkgrelease}.%{microrelease} +License: GPL +Group: Applications/Databases/Interfaces +Source0: http://prdownloads.sourceforge.net/phpmyadmin/%{name}-%{version}-%{pkgrelease}.tar.bz2 +Source1: phpMyAdmin-http.conf +URL: http://sourceforge.net/projects/phpmyadmin/ +Requires: mysql +Requires: php-mysql +Buildarch: noarch +#BuildRoot: %{_tmppath}/%{name}-root + +Summary: phpMyAdmin - web-based MySQL administration + +%description +phpMyAdmin can manage a whole MySQL-server (needs a super-user) but +also a single database. To accomplish the latter you'll need a +properly set up MySQL-user which can read/write only the desired +database. It's up to you to look up the appropiate part in the MySQL +manual. Currently phpMyAdmin can: + - create and drop databases + - create, copy, drop and alter tables + - delete, edit and add fields + - execute any SQL-statement, even batch-queries + - manage keys on fields + - load text files into tables + - create (*) and read dumps of tables + - export (*) and import data to CSV values + - administer multiple servers and single databases + - check referencial integrity + - create complex queries automatically connecting required tables + - create PDF graphics of your database layout + - communicate in more than 38 different languages + + +%prep +%setup -q -n %{name}-%{version}-%{pkgrelease} + + +%build + + +%install +[ "${RPM_BUILD_ROOT}" != "/" ] && [ -d "${RPM_BUILD_ROOT}" ] && \ + rm -rf "${RPM_BUILD_ROOT}" + +# Create directories. + +install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/{css,js,lang,libraries,themes} +install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/{auth,dbg,dbi,engines} +install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/{export,tcpdf,import} +install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/transformations +install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/libraries/tcpdf/font +install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/themes/{darkblue_orange,original} +install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/themes/darkblue_orange/{css,img} +install -d "${RPM_BUILD_ROOT}%{_myadminpath}"/themes/original/{css,img} + +# Install files. + +install libraries/config.default.php \ + "${RPM_BUILD_ROOT}%{_myadminpath}"/config.inc.php +install *.{php,ico} "${RPM_BUILD_ROOT}%{_myadminpath}"/ +install ChangeLog LICENSE README "${RPM_BUILD_ROOT}%{_myadminpath}"/ +install Documentation.html docs.css "${RPM_BUILD_ROOT}%{_myadminpath}"/ +install css/* "${RPM_BUILD_ROOT}%{_myadminpath}/css"/ +install js/* "${RPM_BUILD_ROOT}%{_myadminpath}/js"/ +install lang/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/lang"/ +install libraries/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries"/ +install libraries/auth/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/auth"/ +install libraries/dbg/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/dbg"/ +install libraries/dbi/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/dbi"/ +install libraries/engines/*.php \ + "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/engines"/ +install libraries/export/*.php \ + "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/export"/ +install libraries/tcpdf/*.php "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/tcpdf"/ +install libraries/tcpdf/font/*.{php,z} \ + "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/tcpdf/font"/ +install libraries/import/*.php \ + "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/import"/ +install libraries/transformations/*.php \ + "${RPM_BUILD_ROOT}%{_myadminpath}/libraries/transformations"/ +install themes/darkblue_orange/*.{php,png} \ + "${RPM_BUILD_ROOT}%{_myadminpath}/themes/darkblue_orange"/ +install themes/darkblue_orange/css/*.php \ + "${RPM_BUILD_ROOT}%{_myadminpath}/themes/darkblue_orange/css"/ +install themes/darkblue_orange/img/*.{png,ico} \ + "${RPM_BUILD_ROOT}%{_myadminpath}/themes/darkblue_orange/img"/ +install themes/original/*.{php,png} \ + "${RPM_BUILD_ROOT}%{_myadminpath}/themes/original"/ +install themes/original/css/*.php \ + "${RPM_BUILD_ROOT}%{_myadminpath}/themes/original/css"/ +install themes/original/img/*.{png,ico} \ + "${RPM_BUILD_ROOT}%{_myadminpath}/themes/original/img"/ + +# Create documentation directories. + +DOCROOT="${RPM_BUILD_ROOT}%{_docdir}/%{name}-%{version}" +install -d "${DOCROOT}" +install -d "${DOCROOT}"/{lang,scripts,transformations} + +# Install documentation files. + +install RELEASE-DATE-* "${DOCROOT}"/ +install CREDITS ChangeLog INSTALL LICENSE "${DOCROOT}"/ +install README TODO "${DOCROOT}"/ +install Documentation.* docs.css "${DOCROOT}"/ +install translators.html "${DOCROOT}"/ +install lang/*.sh "${DOCROOT}"/lang/ +install scripts/* "${DOCROOT}"/scripts/ +install libraries/tcpdf/README "${DOCROOT}"/README.tcpdf +install libraries/import/README "${DOCROOT}"/README.import +install libraries/transformations/README "${DOCROOT}"/transformations/ +install libraries/transformations/TEMPLATE* "${DOCROOT}"/transformations/ +install libraries/transformations/*.sh "${DOCROOT}"/transformations/ + +# Install configuration file for Apache. + +install -d "${RPM_BUILD_ROOT}%{_sysconfdir}/httpd/conf.d" +install "%{SOURCE1}" \ + "${RPM_BUILD_ROOT}%{_sysconfdir}/httpd/conf.d/phpMyAdmin.conf" + +# Generate non-configuration file list. + +(cd "${RPM_BUILD_ROOT}"; ls -d ."%{_myadminpath}"/*) | + sed -e '/\/config\.inc\.php$/d' -e 's/^.//' > files.list + + + +%clean +[ "${RPM_BUILD_ROOT}" != "/" ] && [ -d "${RPM_BUILD_ROOT}" ] && \ + rm -rf "${RPM_BUILD_ROOT}" + + +%files -f files.list +%defattr(644, root, root, 755) +%doc %{_docdir}/%{name}-%{version} +%dir %{_myadminpath} +%attr(640,root,apache) %config(noreplace) %verify(not size mtime md5) %{_myadminpath}/config.inc.php +%config(noreplace) %verify(not size mtime md5) %{_sysconfdir}/httpd/conf.d/* + + +%changelog +* Thu Feb 23 2006 Patrick Monnerat <pm@datasphere.ch> +- Version 2.8.0-rc1.1. + +* Thu Dec 22 2005 Patrick Monnerat <patrick.monnerat@econophone.ch> +- Path "nullpw" to allow trying connection with null password after failure. +- Version 2.7.0-pl1.1. + +* Mon Aug 22 2005 Patrick Monnerat <patrick.monnerat@econophone.ch> +- Version 2.6.3-pl1. + +* Wed Jul 21 2004 Patrick Monnerat <patrick.monnerat@econophone.ch> +- Version 2.5.7-pl1. + +* Fri Nov 22 2002 Patrick Monnerat <patrick.monnerat@econophone.ch> +- Version 2.3.0-rc1. diff --git a/tests/examplefiles/postgresql_test.txt b/tests/examplefiles/postgresql_test.txt new file mode 100644 index 00000000..190d184f --- /dev/null +++ b/tests/examplefiles/postgresql_test.txt @@ -0,0 +1,47 @@ +CREATE OR REPLACE FUNCTION something() RETURNS int4 AS +$x$ +BEGIN + RETURN 42; +END +$x$ +LANGUAGE 'plpgsql'; + +CREATE FUNCTION pymax (a integer, b integer) + RETURNS integer +AS $$ + if a > b: + return a + return b +$$ language plpythonu; + +CREATE FUNCTION nested_lexers (a integer, b integer) +$function$ +BEGIN + SELECT ($1 ~ $q$[\t\r\n\v\\]$q$); +END; +$function$ +LANGUAGE sql; + +CREATE OR REPLACE FUNCTION measurement_insert_trigger() +RETURNS TRIGGER AS $$ +BEGIN + <<test>> + INSERT INTO measurement_y2008m01 VALUES (NEW.*); + RETURN NULL; +END; +$$ +LANGUAGE plpgsql; + +-- As returned by pg_dump +CREATE FUNCTION test_function() RETURNS integer + LANGUAGE plpgsql STABLE STRICT + AS $$ +begin + return 42; +end +$$; + +-- Unicode names and strings +SELECT U&'\0441\043B\043E\043D' +FROM U&"\0441\043B\043E\043D"; + diff --git a/tests/examplefiles/psql_session.txt b/tests/examplefiles/psql_session.txt new file mode 100644 index 00000000..7096072b --- /dev/null +++ b/tests/examplefiles/psql_session.txt @@ -0,0 +1,122 @@ +regression=# select foo; +ERROR: column "foo" does not exist +CONTEXT: PL/pgSQL function "test1" while casting return value to function's return type +LINE 1: select foo; + ^ +regression=# \q + +peter@localhost testdb=> \a \t \x +Output format is aligned. +Tuples only is off. +Expanded display is on. + +regression=# select '\x'; +WARNING: nonstandard use of escape in a string literal +LINE 1: select '\x'; + ^ +HINT: Use the escape string syntax for escapes, e.g., E'\r\n'. + ?column? +---------- + x +(1 row) + +regression=# select E'\x'; + +piro=> \set foo 30; +piro=> select * from test where foo <= :foo; + foo | bar +-----+----- + 10 | + 20 | +(2 rows) + +testdb=> \set foo 'my_table' +testdb=> SELECT * FROM :"foo"; + +testdb=> \set content `cat my_file.txt` +testdb=> INSERT INTO my_table VALUES (:'content'); + +regression=# select ( +regression(# 1); + ?column? +---------- + 1 +(1 row) + +piro=> select ( +piro(> ' +piro'> ' || $$ +piro$> $$) +piro-> from " +piro"> foo"; +ERROR: relation " +foo" does not exist +LINE 5: from " + ^ + +testdb=> CREATE TABLE my_table ( +first integer not null default 0, +second text) ; -- end of command +CREATE TABLE + +-- Table output +=# SELECT '0x10'::mpz AS "hex", '10'::mpz AS "dec", +-# '010'::mpz AS oct, '0b10'::mpz AS bin; + hex | dec | oct | bin +-----+-----+-----+----- + 16 | 10 | 8 | 2 +(1 row) + +-- One field output +regression=# select schemaname from pg_tables limit 3; + schemaname +------------ + pg_catalog + pg_catalog + pg_catalog +(3 rows) + +-- TODO: prompt in multiline comments still not handled correctly +test=> select 1 /* multiline +test*> and 2 /* and 3 */ +test*> end comment */, 2; + ?column? | ?column? +----------+---------- + 1 | 2 + +=# select 10.0, 1e-6, 1E+6; + ?column? | ?column? | ?column? +----------+----------+---------- + 10.0 | 0.000001 | 1000000 +(1 row) + +regression=# begin; +BEGIN +regression=# create table asdf (foo serial primary key); +NOTICE: CREATE TABLE will create implicit sequence "asdf_foo_seq" for serial column "asdf.foo" +NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index "asdf_pkey" for table "asdf" +CREATE TABLE +regression=# insert into asdf values (10) returning foo; + foo +----- + 10 +(1 row) + +INSERT 0 1 +regression=# ROLLBACK ; +ROLLBACK + +=> EXPLAIN SELECT * FROM tenk1 +-> WHERE unique1 < 100; -- Don't take -> in the plan as a prompt + + QUERY PLAN +------------------------------------------------------------------------------ + Bitmap Heap Scan on tenk1 (cost=2.37..232.35 rows=106 width=244) + Recheck Cond: (unique1 < 100) + -> Bitmap Index Scan on tenk1_unique1 (cost=0.00..2.37 rows=106 width=0) + Index Cond: (unique1 < 100) + + +-- don't swallow the end of a malformed line +test=> select 1, +'this line must be emitted' diff --git a/tests/examplefiles/py3tb_test.py3tb b/tests/examplefiles/py3tb_test.py3tb new file mode 100644 index 00000000..706a540f --- /dev/null +++ b/tests/examplefiles/py3tb_test.py3tb @@ -0,0 +1,4 @@ + File "<stdin>", line 1 + 1+ + ^ +SyntaxError: invalid syntax diff --git a/tests/examplefiles/pytb_test3.pytb b/tests/examplefiles/pytb_test3.pytb new file mode 100644 index 00000000..6947c1ef --- /dev/null +++ b/tests/examplefiles/pytb_test3.pytb @@ -0,0 +1,4 @@ +>>> 3/"3" +Traceback (most recent call last): + File "<stdin>", line 1, in <module> +TypeError: unsupported operand type(s) for /: 'int' and 'str' diff --git a/tests/examplefiles/reversi.lsp b/tests/examplefiles/reversi.lsp new file mode 100644 index 00000000..fa9a333c --- /dev/null +++ b/tests/examplefiles/reversi.lsp @@ -0,0 +1,427 @@ +#!/usr/bin/env newlisp +;; @module reversi.lsp +;; @description a simple version of Reversi: you as white against newLISP as black +;; @version 0.1 alpha August 2007 +;; @author cormullion +;; +;; 2008-10-08 21:46:54 +;; updated for newLISP version 10. (changed nth-set to setf) +;; this now does not work with newLISP version 9! +;; +;; This is my first attempt at writing a simple application using newLISP-GS. +;; The game algorithms are basically by +;; Peter Norvig http://norvig.com/paip/othello.lisp +;; and all I've done is translate to newLISP and add the interface... +;; +;; To-Do: work out how to handle the end of the game properly... +;; To-Do: complete newlispdoc for the functions + +(constant 'empty 0) +(constant 'black 1) +(constant 'white 2) +(constant 'outer 3) ; squares outside the 8x8 board + +(set '*board* '()) ; the master board is a 100 element list +(set '*moves* '()) ; list of moves made + +; these are the 8 different directions from a square on the board + +(set 'all-directions '(-11 -10 -9 -1 1 9 10 11)) + +; return a list of all the playable squares (the 8 by 8 grid inside the 10by10 + +(define (all-squares) + (local (result) + (for (square 11 88) + (if (<= 1 (mod square 10) 8) + (push square result -1))) +result)) + +; make a board + +(define (make-board) + (set '*board* (dup outer 100)) + (dolist (s (all-squares)) + (setf (*board* s) empty))) + +; for testing and working at a terminal + +(define (print-board) + (print { }) + (for (c 1 8) + (print c)) + (set 'c 0) + (for (i 0 99) + (cond + ((= (*board* i) 0) (print {.})) + ((= (*board* i) 1) (print {b})) + ((= (*board* i) 2) (print {w}))) + (if (and (<= i 88) (= (mod (+ i 1) 10) 0)) ; newline + (print "\n" (inc c)))) + (println "\n")) + +; the initial starting pattern + +(define (initial-board) + (make-board) + (setf (*board* 44) white) + (setf (*board* 55) white) + (setf (*board* 45) black) + (setf (*board* 54) black)) + +(define (opponent player) + (if (= player black) white black)) + +(define (player-name player) + (if (= player white) "white" "black")) + +(define (valid-move? move) + (and + (integer? move) + (<= 11 move 88) + (<= 1 (mod move 10) 8))) + +(define (empty-square? square) + (and + (valid-move? square) + (= (*board* square) empty))) + +; test whether a move is legal. The square must be empty +; and it must flip at least one of the opponent's piece + +(define (legal-move? move player) + (and + (empty-square? move) + (exists (fn (dir) (would-flip? move player dir)) all-directions))) + +; would this move by player result in any flips in the given direction? +; if so, return the number of the 'opposite' (bracketing) piece's square + +(define (would-flip? move player dir) + (let + ((c (+ move dir))) + (and + (= (*board* c) (opponent player)) + (find-bracketing-piece (+ c dir) player dir)))) + +(define (find-bracketing-piece square player dir) + ; return the square of the bracketing piece, if any + (cond + ((= (*board* square) player) square) + ((= (*board* square) (opponent player)) + (find-bracketing-piece (+ square dir) player dir)) + (true nil))) + +(define (make-flips move player dir) + (let + ((bracketer (would-flip? move player dir)) + (c (+ move dir))) + (if bracketer + (do-until (= c bracketer) + (setf (*board* c) player) + (push c *flips* -1) + (inc c dir))))) + +; make the move on the master game board, not yet visually + +(define (make-move move player) + (setf (*board* move) player) + (push move *moves* -1) + (set '*flips* '()) ; we're going to keep a record of the flips made + (dolist (dir all-directions) + (make-flips move player dir))) + +(define (next-to-play previous-player) + (let ((opp (opponent previous-player))) + (cond + ((any-legal-move? opp) opp) + ((any-legal-move? previous-player) + (println (player-name opp) " has no moves") + previous-player) + (true nil)))) + +; are there any legal moves (returns first) for this player? +(define (any-legal-move? player) + (exists (fn (move) (legal-move? move player)) + (all-squares))) + +; a list of all legal moves might be useful +(define (legal-moves player) + (let ((result '())) + (dolist (move (all-squares)) + (if (legal-move? move player) + (push move result))) + (unique result))) + +; define any number of strategies that can be called on to calculate +; the next computer move. This is the only one I've done... - make +; any legal move at random! + +(define (random-strategy player) + (seed (date-value)) + (apply amb (legal-moves player))) + +; get the next move using a particular strategy + +(define (get-move strategy player) + (let ((move (apply strategy (list player)))) + (cond + ((and + (valid-move? move) + (legal-move? move player)) + (make-move move player)) + (true + (println "no valid or legal move for " (player-name player) ) + nil)) + move)) + +; that's about all the game algorithms for now +; now for the interface + +(if (= ostype "Win32") + (load (string (env "PROGRAMFILES") "/newlisp/guiserver.lsp")) + (load "/usr/share/newlisp/guiserver.lsp") +) + +(gs:init) +(map set '(screen-width screen-height) (gs:get-screen)) +(set 'board-width 540) +; center on screen +(gs:frame 'Reversi (- (/ screen-width 2) (/ board-width 2)) 60 board-width 660 "Reversi") +(gs:set-border-layout 'Reversi) + +(gs:canvas 'MyCanvas 'Reversi) + (gs:set-background 'MyCanvas '(.8 .9 .7 .8)) + (gs:mouse-released 'MyCanvas 'mouse-released-action true) + +(gs:panel 'Controls) + (gs:button 'Start 'start-game "Start") + +(gs:panel 'Lower) + (gs:label 'WhiteScore "") + (gs:label 'BlackScore "") + +(gs:add-to 'Controls 'Start ) +(gs:add-to 'Lower 'WhiteScore 'BlackScore) +(gs:add-to 'Reversi 'MyCanvas "center" 'Controls "north" 'Lower "south") + +(gs:set-anti-aliasing true) +(gs:set-visible 'Reversi true) + +; size of board square, and radius/width of counter +(set 'size 60 'width 30) + +; initialize the master board + +(define (initial-board) + (make-board) + (setf (*board* 44) white) + (setf (*board* 55) white) + (setf (*board* 45) black) + (setf (*board* 54) black) +) + +; draw a graphical repesentation of the board + +(define (draw-board) + (local (x y) + (dolist (i (all-squares)) + (map set '(x y) (square-to-xy i)) + (gs:draw-rect + (string x y) + (- (* y size) width ) ; !!!!!! + (- (* x size) width ) + (* width 2) + (* width 2) + gs:white)))) + +(define (draw-first-four-pieces) + (draw-piece 44 "white") + (draw-piece 55 "white") + (draw-piece 45 "black") + (draw-piece 54 "black")) + +; this next function can mark the legal moves available to a player + +(define (show-legal-moves player) + (local (legal-move-list x y) + (set 'legal-move-list (legal-moves player)) + (dolist (m (all-squares)) + (map set '(x y) (square-to-xy m)) + (gs:draw-rect + (string x y) + (- (* y size) width ) ; !!!!!! + (- (* x size) width ) + (* width 2) + (* width 2) + (if (find m legal-move-list) gs:blue gs:white) + ) + ) + ) +) + +; convert the number of a square on the master board to coordinates + +(define (square-to-xy square) + (list (/ square 10) (mod square 10))) + +; draw one of the pieces + +(define (draw-piece square colour) + (local (x y) + (map set '(x y) (square-to-xy square)) + (cond + ((= colour "white") + (gs:fill-circle + (string x y) + (* y size) ; !!!!!!! y first, cos y is x ;-) + (* x size) + width + gs:white)) + + ((= colour "black") + (gs:fill-circle + (string x y) + (* y size) + (* x size) + width + gs:black)) + + ((= colour "empty") + (gs:draw-rect + (string x y) + (- (* y size) width ) + (- (* x size) width ) + (* width 2) + (* width 2) + gs:white)) + ))) + +; animate the pieces flipping + +(define (flip-piece square player) +; flip by drawing thinner and fatter ellipses +; go from full disk in opposite colour to invisible +; then from invisible to full disk in true colour + (local (x y colour) + (map set '(x y) (square-to-xy square)) + ; delete original piece + (gs:delete-tag (string x y)) + (set 'colour (if (= player 2) gs:black gs:white )) + (for (i width 1 -3) + (gs:fill-ellipse + (string x y {flip} i) + (* y size) ; y first :-) !!! + (* x size) + i + width + colour) + (sleep 20) ; this might need adjusting... + (gs:delete-tag (string x y {flip} i)) + ) + (set 'colour (if (= player 2) gs:white gs:black)) + (for (i 1 width 3) + (gs:fill-ellipse + (string x y {flip} i) + (* y size) ; :-) !!! + (* x size) + i + width + colour) + (sleep 20) + (gs:delete-tag (string x y {flip} i)) + ) + ; draw the piece again + (gs:fill-circle + (string x y) + (* y size) + (* x size) + width + colour) + ) +) + +(define (do-move move player) + (cond + ; check if the move is good ... + ((and (!= player nil) + (valid-move? move) + (legal-move? move player)) + + ; ... play it + ; make move on board + (make-move move player) + ; and on screen + (draw-piece move (player-name player)) + (gs:update) + ; do flipping stuff + + ; wait for a while + (sleep 1000) + + ; then do flipping + (dolist (f *flips*) + (flip-piece f player)) + + (inc *move-number*) + (draw-piece move (player-name player)) + (gs:update) + + ; update scores + (gs:set-text 'WhiteScore + (string "White: " (first (count (list white) *board*)))) + (gs:set-text 'BlackScore + (string "Black: " (first (count (list black) *board*)))) + ) + ; or return nil + (true + nil))) + +; the game is driven by the mouse clicks of the user +; in reply, the computer plays a black piece +; premature clicking is possible and possibly a bad thing... + +(define (mouse-released-action x y button modifiers tags) + ; extract the tag of the clicked square + (set 'move (int (string (first tags)) 0 10)) + (if (do-move move player) + (begin + (set 'player (next-to-play player)) + ; there is a training mode - legal squares are highlighted + ; you can uncomment the next line... + ; (show-legal-moves player) + (gs:update) + + ; wait for black's reply + (gs:set-cursor 'Reversi "wait") + (gs:set-text 'Start "black's move - thinking...") + ; give the illusion of Deep Thought... + (sleep 2000) + ; black's reply + ; currently only the random strategy has been defined... + (set 'strategy random-strategy) + (set 'move (apply strategy (list player))) + (do-move move player) + (set 'player (next-to-play player)) + ; (show-legal-moves player) ; to see black's moves + (gs:set-text 'Start "your move") + (gs:set-cursor 'Reversi "default") + (gs:update)))) + +(define (start-game) + (gs:set-text 'Start "Click a square to place a piece!") + (gs:disable 'Start) + (set 'player white)) + +(define (start) + (gs:set-text 'Start "Start") + (gs:enable 'Start) + (set '*move-number* 1 + '*flips* '()) + (initial-board) + (draw-board) + (draw-first-four-pieces)) + +(start) + +(gs:listen)
\ No newline at end of file diff --git a/tests/examplefiles/robotframework_test.txt b/tests/examplefiles/robotframework_test.txt new file mode 100644 index 00000000..63ba63e6 --- /dev/null +++ b/tests/examplefiles/robotframework_test.txt @@ -0,0 +1,39 @@ +*** Settings *** +Documentation Simple example demonstrating syntax highlighting. +Library ExampleLibrary +Test Setup Keyword argument argument with ${VARIABLE} + +*** Variables *** +${VARIABLE} Variable value +@{LIST} List variable here + +*** Test Cases *** +Keyword-driven example + Initialize System + Do Something + Result Should Be 42 + [Teardown] Cleanup System + +Data-driven example + [Template] Keyword + argument1 argument2 + argument ${VARIABLE} + @{LIST} + +Gherkin + Given system is initialized + When something is done + Then result should be "42" + +| Pipes | +| | [Documentation] | Also pipe separated format is supported. | +| | Log | As this example demonstrates. | + +*** Keywords *** +Result Should Be + [Arguments] ${expected} + ${actual} = Get Value + Should be Equal ${actual} ${expected} + +Then result should be "${expected}" + Result Should Be ${expected} diff --git a/tests/examplefiles/rql-queries.rql b/tests/examplefiles/rql-queries.rql new file mode 100644 index 00000000..1d86df3c --- /dev/null +++ b/tests/examplefiles/rql-queries.rql @@ -0,0 +1,34 @@ +Any N, N2 where N is Note, N2 is Note, N a_faire_par P1, P1 nom 'john', N2 a_faire_par P2, P2 nom 'jane' ; +DISTINCT Any N, D, C, T, A ORDERBY D DESC LIMIT 40 where N is Note, N diem D, W is Workcase, W concerned_by N, N cost C, N text T, N author A, N diem <= today +Bookmark B WHERE B owned_by G, G eid 5; +Any X WHERE E eid 22762, NOT E is_in X, X modification_date D ORDERBY D DESC LIMIT 41; +Any A, R, SUB ORDERBY R WHERE A is "Workcase", S is Division, S concerned_by A, A subject SUB, S eid 85, A ref R; +Any D, T, L WHERE D is Document, A concerned_by D,A eid 14533, D title T, D location L; +Any N,A,B,C,D ORDERBY A DESC WHERE N is Note, W concerned_by N, W eid 14533, N diem A,N author B,N text C,N cost D; +Any X ORDERBY D DESC LIMIT 41 WHERE E eid 18134, NOT E concerned_by X, X modification_date D +DISTINCT Any N, D, C, T, A ORDERBY D ASC LIMIT 40 WHERE N is Note, N diem D, P is Person, N to_be_contacted_by G, N cost C, N text T, N author A, G login "john"; +INSERT Person X: X surname "Doe", X firstname "John"; +Workcase W where W ref "ABCD12"; +Workcase W where W ref LIKE "AB%"; +Any X WHERE X X eid 53 +Any X WHERE X Document X occurence_of F, F class C, C name 'Comics' X owned_by U, U login 'syt' X available true +Person P WHERE P work_for P, S name 'Acme', P interested_by T, T name 'training' +Note N WHERE N written_on D, D day> (today -10), N written_by P, P name 'joe' or P name 'jack' +Person P WHERE (P interested_by T, T name 'training') or (P city 'Paris') +Any N, P WHERE X is Person, X name N, X first_name P +String N, P WHERE X is Person, X name N, X first_name P +INSERT Person X: X name 'widget' +INSERT Person X, Person Y: X name 'foo', Y name 'nice', X friend Y +INSERT Person X: X name 'foo', X friend Y WHERE name 'nice' +SET X name 'bar', X first_name 'original' where X is Person X name 'foo' +SET X know Y WHERE X friend Y +DELETE Person X WHERE X name 'foo' +DELETE X friend Y WHERE X is Person, X name 'foo' +Any X WHERE X name LIKE '%lt' +Any X WHERE X name IN ( 'joe', 'jack', 'william', 'averell') +Any X, V WHERE X concerns P, P eid 42, X corrected_in V? +Any C, P WHERE C is Card, P? documented_by C +Point P where P abs X, P ord Y, P value X+Y +Document X where X class C, C name 'Cartoon', X owned_by U, U login 'joe', X available true +(Any X WHERE X is Document) UNION (Any X WHERE X is File) +Any A,B WHERE A creation_date B WITH A BEING (Any X WHERE X is Document) UNION (Any X WHERE X is File) diff --git a/tests/examplefiles/rust_example.rs b/tests/examplefiles/rust_example.rs new file mode 100644 index 00000000..1c0a70c3 --- /dev/null +++ b/tests/examplefiles/rust_example.rs @@ -0,0 +1,233 @@ +// Copyright 2012 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or +// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license +// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +// based on: +// http://shootout.alioth.debian.org/u32/benchmark.php?test=nbody&lang=java + +extern mod std; + +use core::os; + +// Using sqrt from the standard library is way slower than using libc +// directly even though std just calls libc, I guess it must be +// because the the indirection through another dynamic linker +// stub. Kind of shocking. Might be able to make it faster still with +// an llvm intrinsic. +#[nolink] +extern mod libc { + #[legacy_exports]; + fn sqrt(n: float) -> float; +} + +fn main() { + let args = os::args(); + let args = if os::getenv(~"RUST_BENCH").is_some() { + ~[~"", ~"4000000"] + } else if args.len() <= 1u { + ~[~"", ~"100000"] + } else { + args + }; + let n = int::from_str(args[1]).get(); + let mut bodies: ~[Body::props] = NBodySystem::make(); + io::println(fmt!("%f", NBodySystem::energy(bodies))); + let mut i = 0; + while i < n { + NBodySystem::advance(bodies, 0.01); + i += 1; + } + io::println(fmt!("%f", NBodySystem::energy(bodies))); +} + +mod NBodySystem { + use Body; + + pub fn make() -> ~[Body::props] { + let mut bodies: ~[Body::props] = + ~[Body::sun(), + Body::jupiter(), + Body::saturn(), + Body::uranus(), + Body::neptune()]; + + let mut px = 0.0; + let mut py = 0.0; + let mut pz = 0.0; + + let mut i = 0; + while i < 5 { + px += bodies[i].vx * bodies[i].mass; + py += bodies[i].vy * bodies[i].mass; + pz += bodies[i].vz * bodies[i].mass; + + i += 1; + } + + // side-effecting + Body::offset_momentum(&mut bodies[0], px, py, pz); + + return bodies; + } + + pub fn advance(bodies: &mut [Body::props], dt: float) { + let mut i = 0; + while i < 5 { + let mut j = i + 1; + while j < 5 { + advance_one(&mut bodies[i], + &mut bodies[j], dt); + j += 1; + } + + i += 1; + } + + i = 0; + while i < 5 { + move_(&mut bodies[i], dt); + i += 1; + } + } + + pub fn advance_one(bi: &mut Body::props, + bj: &mut Body::props, + dt: float) unsafe { + let dx = bi.x - bj.x; + let dy = bi.y - bj.y; + let dz = bi.z - bj.z; + + let dSquared = dx * dx + dy * dy + dz * dz; + + let distance = ::libc::sqrt(dSquared); + let mag = dt / (dSquared * distance); + + bi.vx -= dx * bj.mass * mag; + bi.vy -= dy * bj.mass * mag; + bi.vz -= dz * bj.mass * mag; + + bj.vx += dx * bi.mass * mag; + bj.vy += dy * bi.mass * mag; + bj.vz += dz * bi.mass * mag; + } + + pub fn move_(b: &mut Body::props, dt: float) { + b.x += dt * b.vx; + b.y += dt * b.vy; + b.z += dt * b.vz; + } + + pub fn energy(bodies: &[Body::props]) -> float unsafe { + let mut dx; + let mut dy; + let mut dz; + let mut distance; + let mut e = 0.0; + + let mut i = 0; + while i < 5 { + e += + 0.5 * bodies[i].mass * + (bodies[i].vx * bodies[i].vx + bodies[i].vy * bodies[i].vy + + bodies[i].vz * bodies[i].vz); + + let mut j = i + 1; + while j < 5 { + dx = bodies[i].x - bodies[j].x; + dy = bodies[i].y - bodies[j].y; + dz = bodies[i].z - bodies[j].z; + + distance = ::libc::sqrt(dx * dx + dy * dy + dz * dz); + e -= bodies[i].mass * bodies[j].mass / distance; + + j += 1; + } + + i += 1; + } + return e; + + } +} + +mod Body { + use Body; + + pub const PI: float = 3.141592653589793; + pub const SOLAR_MASS: float = 39.478417604357432; + // was 4 * PI * PI originally + pub const DAYS_PER_YEAR: float = 365.24; + + pub type props = + {mut x: float, + mut y: float, + mut z: float, + mut vx: float, + mut vy: float, + mut vz: float, + mass: float}; + + pub fn jupiter() -> Body::props { + return {mut x: 4.84143144246472090e+00, + mut y: -1.16032004402742839e+00, + mut z: -1.03622044471123109e-01, + mut vx: 1.66007664274403694e-03 * DAYS_PER_YEAR, + mut vy: 7.69901118419740425e-03 * DAYS_PER_YEAR, + mut vz: -6.90460016972063023e-05 * DAYS_PER_YEAR, + mass: 9.54791938424326609e-04 * SOLAR_MASS}; + } + + pub fn saturn() -> Body::props { + return {mut x: 8.34336671824457987e+00, + mut y: 4.12479856412430479e+00, + mut z: -4.03523417114321381e-01, + mut vx: -2.76742510726862411e-03 * DAYS_PER_YEAR, + mut vy: 4.99852801234917238e-03 * DAYS_PER_YEAR, + mut vz: 2.30417297573763929e-05 * DAYS_PER_YEAR, + mass: 2.85885980666130812e-04 * SOLAR_MASS}; + } + + pub fn uranus() -> Body::props { + return {mut x: 1.28943695621391310e+01, + mut y: -1.51111514016986312e+01, + mut z: -2.23307578892655734e-01, + mut vx: 2.96460137564761618e-03 * DAYS_PER_YEAR, + mut vy: 2.37847173959480950e-03 * DAYS_PER_YEAR, + mut vz: -2.96589568540237556e-05 * DAYS_PER_YEAR, + mass: 4.36624404335156298e-05 * SOLAR_MASS}; + } + + pub fn neptune() -> Body::props { + return {mut x: 1.53796971148509165e+01, + mut y: -2.59193146099879641e+01, + mut z: 1.79258772950371181e-01, + mut vx: 2.68067772490389322e-03 * DAYS_PER_YEAR, + mut vy: 1.62824170038242295e-03 * DAYS_PER_YEAR, + mut vz: -9.51592254519715870e-05 * DAYS_PER_YEAR, + mass: 5.15138902046611451e-05 * SOLAR_MASS}; + } + + pub fn sun() -> Body::props { + return {mut x: 0.0, + mut y: 0.0, + mut z: 0.0, + mut vx: 0.0, + mut vy: 0.0, + mut vz: 0.0, + mass: SOLAR_MASS}; + } + + pub fn offset_momentum(props: &mut Body::props, + px: float, py: float, pz: float) { + props.vx = -px / SOLAR_MASS; + props.vy = -py / SOLAR_MASS; + props.vz = -pz / SOLAR_MASS; + } + +} diff --git a/tests/examplefiles/scilab.sci b/tests/examplefiles/scilab.sci new file mode 100644 index 00000000..8dea7b9c --- /dev/null +++ b/tests/examplefiles/scilab.sci @@ -0,0 +1,30 @@ +// Scilab ( http://www.scilab.org/ ) +// Copyright (C) INRIA - Serge STEER +// + +function I=sub2ind(dims,varargin) +//sub2ind is used to determine the equivalent single index +//corresponding to a given set of subscript values. + +//I = sub2ind(dims,i1,i2,..) returns the linear index equivalent to the +//row, column, ... subscripts in the arrays i1,i2,.. for an matrix of +//size dims. + +//I = sub2ind(dims,Mi) returns the linear index +//equivalent to the n subscripts in the columns of the matrix Mi for a matrix +//of size dims. + + d=[1;cumprod(matrix(dims(1:$-1),-1,1))] + for i=1:size(varargin) + if varargin(i)==[] then I=[],return,end + end + + if size(varargin)==1 then //subindices are the columns of the argument + I=(varargin(1)-1)*d+1 + else //subindices are given as separated arguments + I=1 + for i=1:size(varargin) + I=I+(varargin(i)-1)*d(i) + end + end +endfunction diff --git a/tests/examplefiles/scope.cirru b/tests/examplefiles/scope.cirru new file mode 100644 index 00000000..728bcabf --- /dev/null +++ b/tests/examplefiles/scope.cirru @@ -0,0 +1,43 @@ + +-- https://github.com/Cirru/cirru-gopher/blob/master/code/scope.cr + +set a (int 2) + +print (self) + +set c (child) + +under c + under parent + print a + +print $ get c a + +set c x (int 3) +print $ get c x + +set just-print $ code + print a + +print just-print + +eval (self) just-print +eval just-print + +print (string "string with space") +print (string "escapes \n \"\\") + +brackets ((((())))) + +"eval" $ string "eval" + +print (add $ (int 1) (int 2)) + +print $ unwrap $ + map (a $ int 1) (b $ int 2) + +print a + int 1 + , b c + int 2 + , d
\ No newline at end of file diff --git a/tests/examplefiles/session.dylan-console b/tests/examplefiles/session.dylan-console new file mode 100644 index 00000000..6f289c8e --- /dev/null +++ b/tests/examplefiles/session.dylan-console @@ -0,0 +1,9 @@ +? 7 * 52; +=> 364 +? define variable *your-variable* = $foo; +? begin + let yours = "apple"; + let mine = yours; + mine == yours; + end; +=> #t diff --git a/tests/examplefiles/sparql.rq b/tests/examplefiles/sparql.rq new file mode 100644 index 00000000..caedfd14 --- /dev/null +++ b/tests/examplefiles/sparql.rq @@ -0,0 +1,23 @@ +# This is a test SPARQL query + +PREFIX foaf: <http://xmlns.com/foaf/0.1/> +PREFIX ex: <http://example.org/> +PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> +PREFIX dcterms: <http://purl.org/dc/terms/> + +SELECT ?person (COUNT(?nick) AS ?nickCount) { + ?person foaf:nick ?nick ; + foaf:lastName "Smith" ; + foaf:age "21"^^xsd:int ; + ex:title 'Mr' ; # single-quoted string + ex:height 1.80 ; # float + ex:distanceToSun +1.4e8 ; # float with exponent + ex:ownsACat true ; + dcterms:description "Someone with a cat called \"cat\"."@en . + OPTIONAL { ?person foaf:isPrimaryTopicOf ?page } + OPTIONAL { ?person foaf:name ?name + { ?person foaf:depiction ?img } + UNION + { ?person foaf:firstName ?firstN } } + FILTER ( bound(?page) || bound(?img) || bound(?firstN) ) +} GROUP BY ?person ORDER BY ?img diff --git a/tests/examplefiles/squid.conf b/tests/examplefiles/squid.conf index 31e611d6..833d4fca 100644 --- a/tests/examplefiles/squid.conf +++ b/tests/examplefiles/squid.conf @@ -1,27 +1,30 @@ -# First, a comment block for the deafult conf: +# Some multiline comments -# TAG: buffered_logs on|off -# cache.log log file is written with stdio functions, and as such -# it can be buffered or unbuffered. By default it will be unbuffered. -# Buffering it can speed up the writing slightly (though you are -# unlikely to need to worry unless you run with tons of debugging -# enabled in which case performance will suffer badly anyway..). -# -#Default: -# buffered_logs off - -# Now, a slightly useful (but in no way complete) set of options: - -cache_peer upstream1.example.com parent 8080 0 no-query proxy-only round-robin -cache_peer upstream2.example.com parent 3128 0 no-query proxy-only round-robin -never_direct allow all -never_direct allow CONNECT - -acl myclients src 127.0.0.1 -http_access allow myclients - -acl mynet src 192.168.0.0/255.255.0.0 -no_cache deny mynet - -acl mynetlocal dst 192.168.0.0/255.255.0.0 -always_direct allow mynetlocal +acl manager proto cache_object +acl localhost src 127.0.0.1/32 ::1 +acl to_localhost dst 127.0.0.0/8 0.0.0.0/32 ::1 +acl SSL_ports port 443 +acl Safe_ports port 80 # http +acl Safe_ports port 21 # ftp +acl Safe_ports port 443 # https +acl Safe_ports port 70 # gopher +acl Safe_ports port 210 # wais +acl Safe_ports port 1025-65535 # unregistered ports +acl Safe_ports port 280 # http-mgmt +acl Safe_ports port 488 # gss-http +acl Safe_ports port 591 # filemaker +acl Safe_ports port 777 # multiling http +acl CONNECT method CONNECT +http_access allow manager localhost +http_access deny manager +http_access deny !Safe_ports +http_access deny CONNECT !SSL_ports +http_access allow localhost +http_access deny all +http_port 3128 +hierarchy_stoplist cgi-bin ? +coredump_dir /var/spool/squid3 +refresh_pattern ^ftp: 1440 20% 10080 +refresh_pattern ^gopher: 1440 0% 1440 +refresh_pattern -i (/cgi-bin/|\?) 0 0% 0 +refresh_pattern . 0 20% 4320 diff --git a/tests/examplefiles/string.jl b/tests/examplefiles/string.jl new file mode 100644 index 00000000..67bf6c70 --- /dev/null +++ b/tests/examplefiles/string.jl @@ -0,0 +1,1031 @@ +## core string functions ## + +length(s::String) = error("you must implement length(",typeof(s),")") +next(s::String, i::Int) = error("you must implement next(",typeof(s),",Int)") +next(s::DirectIndexString, i::Int) = (s[i],i+1) +next(s::String, i::Integer) = next(s,int(i)) + +## generic supplied functions ## + +start(s::String) = 1 +done(s::String,i) = (i > length(s)) +isempty(s::String) = done(s,start(s)) +ref(s::String, i::Int) = next(s,i)[1] +ref(s::String, i::Integer) = s[int(i)] +ref(s::String, x::Real) = s[iround(x)] +ref{T<:Integer}(s::String, r::Range1{T}) = s[int(first(r)):int(last(r))] + +symbol(s::String) = symbol(cstring(s)) +string(s::String) = s + +print(s::String) = for c=s; print(c); end +print(x...) = for i=x; print(i); end +println(args...) = print(args..., '\n') + +show(s::String) = print_quoted(s) + +(*)(s::String...) = strcat(s...) +(^)(s::String, r::Integer) = repeat(s,r) + +size(s::String) = (length(s),) +size(s::String, d::Integer) = d==1 ? length(s) : + error("in size: dimension ",d," out of range") + +strlen(s::DirectIndexString) = length(s) +function strlen(s::String) + i = start(s) + if done(s,i) + return 0 + end + n = 1 + while true + c, j = next(s,i) + if done(s,j) + return n + end + n += 1 + i = j + end +end + +isvalid(s::DirectIndexString, i::Integer) = (start(s) <= i <= length(s)) +function isvalid(s::String, i::Integer) + try + next(s,i) + true + catch + false + end +end + +prevind(s::DirectIndexString, i::Integer) = i-1 +thisind(s::DirectIndexString, i::Integer) = i +nextind(s::DirectIndexString, i::Integer) = i+1 + +prevind(s::String, i::Integer) = thisind(s,thisind(s,i)-1) + +function thisind(s::String, i::Integer) + for j = i:-1:1 + if isvalid(s,j) + return j + end + end + return 0 # out of range +end + +function nextind(s::String, i::Integer) + for j = i+1:length(s) + if isvalid(s,j) + return j + end + end + length(s)+1 # out of range +end + +ind2chr(s::DirectIndexString, i::Integer) = i +chr2ind(s::DirectIndexString, i::Integer) = i + +function ind2chr(s::String, i::Integer) + s[i] # throws error if invalid + j = 1 + k = start(s) + while true + c, l = next(s,k) + if i <= k + return j + end + j += 1 + k = l + end +end + +function chr2ind(s::String, i::Integer) + if i < 1 + return i + end + j = 1 + k = start(s) + while true + c, l = next(s,k) + if i == j + return k + end + j += 1 + k = l + end +end + +function strchr(s::String, c::Char, i::Integer) + i = nextind(s,i) + while !done(s,i) + d, j = next(s,i) + if c == d + return i + end + i = j + end + return 0 +end +strchr(s::String, c::Char) = strchr(s, c, start(s)) +contains(s::String, c::Char) = (strchr(s,c)!=0) + +function chars(s::String) + cx = Array(Char,strlen(s)) + i = 0 + for c in s + cx[i += 1] = c + end + return cx +end + +function cmp(a::String, b::String) + i = start(a) + j = start(b) + while !done(a,i) && !done(b,i) + c, i = next(a,i) + d, j = next(b,j) + if c != d + return c < d ? -1 : +1 + end + end + done(a,i) && !done(b,j) ? -1 : + !done(a,i) && done(b,j) ? +1 : 0 +end + +isequal(a::String, b::String) = cmp(a,b) == 0 +isless(a::String, b::String) = cmp(a,b) < 0 + +# faster comparisons for byte strings + +cmp(a::ByteString, b::ByteString) = lexcmp(a.data, b.data) +isequal(a::ByteString, b::ByteString) = length(a)==length(b) && cmp(a,b)==0 + +## character column width function ## + +charwidth(c::Char) = max(0,int(ccall(:wcwidth, Int32, (Char,), c))) +strwidth(s::String) = (w=0; for c in s; w += charwidth(c); end; w) +strwidth(s::ByteString) = ccall(:u8_strwidth, Int, (Ptr{Uint8},), s.data) +# TODO: implement and use u8_strnwidth that takes a length argument + +## generic string uses only length and next ## + +type GenericString <: String + string::String +end + +length(s::GenericString) = length(s.string) +next(s::GenericString, i::Int) = next(s.string, i) + +## plain old character arrays ## + +type CharString <: String + chars::Array{Char,1} + + CharString(a::Array{Char,1}) = new(a) + CharString(c::Char...) = new([ c[i] | i=1:length(c) ]) +end +CharString(x...) = CharString(map(char,x)...) + +next(s::CharString, i::Int) = (s.chars[i], i+1) +length(s::CharString) = length(s.chars) +strlen(s::CharString) = length(s) + +string(c::Char) = CharString(c) +string(c::Char, x::Char...) = CharString(c, x...) + +## substrings reference original strings ## + +type SubString <: String + string::String + offset::Int + length::Int + + SubString(s::String, i::Int, j::Int) = new(s, i-1, j-i+1) + SubString(s::SubString, i::Int, j::Int) = + new(s.string, i-1+s.offset, j-i+1) +end +SubString(s::String, i::Integer, j::Integer) = SubString(s, int(i), int(j)) + +function next(s::SubString, i::Int) + if i < 1 || i > s.length + error("string index out of bounds") + end + c, i = next(s.string, i+s.offset) + c, i-s.offset +end + +length(s::SubString) = s.length +# TODO: strlen(s::SubString) = ?? +# default implementation will work but it's slow +# can this be delegated efficiently somehow? +# that may require additional string interfaces + +function ref(s::String, r::Range1{Int}) + if first(r) < 1 || length(s) < last(r) + error("in substring slice: index out of range") + end + SubString(s, first(r), last(r)) +end + +## efficient representation of repeated strings ## + +type RepString <: String + string::String + repeat::Integer +end + +length(s::RepString) = length(s.string)*s.repeat +strlen(s::RepString) = strlen(s.string)*s.repeat + +function next(s::RepString, i::Int) + if i < 1 || i > length(s) + error("string index out of bounds") + end + j = mod1(i,length(s.string)) + c, k = next(s.string, j) + c, k-j+i +end + +function repeat(s::String, r::Integer) + r < 0 ? error("can't repeat a string ",r," times") : + r == 0 ? "" : + r == 1 ? s : + RepString(s,r) +end + +## reversed strings without data movement ## + +type RevString <: String + string::String +end + +length(s::RevString) = length(s.string) +strlen(s::RevString) = strlen(s.string) + +start(s::RevString) = (n=length(s); n-thisind(s.string,n)+1) +function next(s::RevString, i::Int) + n = length(s); j = n-i+1 + (s.string[j], n-thisind(s.string,j-1)+1) +end + +reverse(s::String) = RevString(s) +reverse(s::RevString) = s.string + +## ropes for efficient concatenation, etc. ## + +# Idea: instead of this standard binary tree structure, +# how about we keep an array of substrings, with an +# offset array. We can do binary search on the offset +# array so we get O(log(n)) indexing time still, but we +# can compute the offsets lazily and avoid all the +# futzing around while the string is being constructed. + +type RopeString <: String + head::String + tail::String + depth::Int32 + length::Int + + RopeString(h::RopeString, t::RopeString) = + depth(h.tail) + depth(t) < depth(h.head) ? + RopeString(h.head, RopeString(h.tail, t)) : + new(h, t, max(h.depth,t.depth)+1, length(h)+length(t)) + + RopeString(h::RopeString, t::String) = + depth(h.tail) < depth(h.head) ? + RopeString(h.head, RopeString(h.tail, t)) : + new(h, t, h.depth+1, length(h)+length(t)) + + RopeString(h::String, t::RopeString) = + depth(t.head) < depth(t.tail) ? + RopeString(RopeString(h, t.head), t.tail) : + new(h, t, t.depth+1, length(h)+length(t)) + + RopeString(h::String, t::String) = + new(h, t, 1, length(h)+length(t)) +end + +depth(s::String) = 0 +depth(s::RopeString) = s.depth + +function next(s::RopeString, i::Int) + if i <= length(s.head) + return next(s.head, i) + else + c, j = next(s.tail, i-length(s.head)) + return c, j+length(s.head) + end +end + +length(s::RopeString) = s.length +strlen(s::RopeString) = strlen(s.head) + strlen(s.tail) + +strcat() = "" +strcat(s::String) = s +strcat(x...) = strcat(map(string,x)...) +strcat(s::String, t::String...) = + (t = strcat(t...); isempty(s) ? t : isempty(t) ? s : RopeString(s, t)) + +print(s::RopeString) = print(s.head, s.tail) + +## transformed strings ## + +type TransformedString <: String + transform::Function + string::String +end + +length(s::TransformedString) = length(s.string) +strlen(s::TransformedString) = strlen(s.string) + +function next(s::TransformedString, i::Int) + c, j = next(s.string,i) + c = s.transform(c, i) + return c, j +end + +## uppercase and lowercase transformations ## + +uppercase(c::Char) = ccall(:towupper, Char, (Char,), c) +lowercase(c::Char) = ccall(:towlower, Char, (Char,), c) + +uppercase(s::String) = TransformedString((c,i)->uppercase(c), s) +lowercase(s::String) = TransformedString((c,i)->lowercase(c), s) + +ucfirst(s::String) = TransformedString((c,i)->i==1 ? uppercase(c) : c, s) +lcfirst(s::String) = TransformedString((c,i)->i==1 ? lowercase(c) : c, s) + +const uc = uppercase +const lc = lowercase + +## string map ## + +function map(f::Function, s::String) + out = memio(length(s)) + for c in s + write(out, f(c)::Char) + end + takebuf_string(out) +end + +## conversion of general objects to strings ## + +string(x) = print_to_string(show, x) +cstring(x...) = print_to_string(print, x...) + +function cstring(p::Ptr{Uint8}) + p == C_NULL ? error("cannot convert NULL to string") : + ccall(:jl_cstr_to_string, Any, (Ptr{Uint8},), p)::ByteString +end + +## string promotion rules ## + +promote_rule(::Type{UTF8String} , ::Type{ASCIIString}) = UTF8String +promote_rule(::Type{UTF8String} , ::Type{CharString} ) = UTF8String +promote_rule(::Type{ASCIIString}, ::Type{CharString} ) = UTF8String + +## printing literal quoted string data ## + +# TODO: this is really the inverse of print_unbackslashed + +function print_quoted_literal(s::String) + print('"') + for c = s; c == '"' ? print("\\\"") : print(c); end + print('"') +end + +## string escaping & unescaping ## + +escape_nul(s::String, i::Int) = + !done(s,i) && '0' <= next(s,i)[1] <= '7' ? L"\x00" : L"\0" + +is_hex_digit(c::Char) = '0'<=c<='9' || 'a'<=c<='f' || 'A'<=c<='F' +need_full_hex(s::String, i::Int) = !done(s,i) && is_hex_digit(next(s,i)[1]) + +function print_escaped(s::String, esc::String) + i = start(s) + while !done(s,i) + c, j = next(s,i) + c == '\0' ? print(escape_nul(s,j)) : + c == '\e' ? print(L"\e") : + c == '\\' ? print("\\\\") : + contains(esc,c) ? print('\\', c) : + iswprint(c) ? print(c) : + 7 <= c <= 13 ? print('\\', "abtnvfr"[c-6]) : + c <= '\x7f' ? print(L"\x", hex(c, 2)) : + c <= '\uffff' ? print(L"\u", hex(c, need_full_hex(s,j) ? 4 : 2)) : + print(L"\U", hex(c, need_full_hex(s,j) ? 8 : 4)) + i = j + end +end + +escape_string(s::String) = print_to_string(length(s), print_escaped, s, "\"") +print_quoted(s::String) = (print('"'); print_escaped(s, "\"\$"); print('"')) +#" # work around syntax highlighting problem +quote_string(s::String) = print_to_string(length(s)+2, print_quoted, s) + +# bare minimum unescaping function unescapes only given characters + +function print_unescaped_chars(s::String, esc::String) + if !contains(esc,'\\') + esc = strcat("\\", esc) + end + i = start(s) + while !done(s,i) + c, i = next(s,i) + if c == '\\' && !done(s,i) && contains(esc,s[i]) + c, i = next(s,i) + end + print(c) + end +end + +unescape_chars(s::String, esc::String) = + print_to_string(length(s), print_unescaped_chars, s, esc) + +# general unescaping of traditional C and Unicode escape sequences + +function print_unescaped(s::String) + i = start(s) + while !done(s,i) + c, i = next(s,i) + if !done(s,i) && c == '\\' + c, i = next(s,i) + if c == 'x' || c == 'u' || c == 'U' + n = k = 0 + m = c == 'x' ? 2 : + c == 'u' ? 4 : 8 + while (k+=1) <= m && !done(s,i) + c, j = next(s,i) + n = '0' <= c <= '9' ? n<<4 + c-'0' : + 'a' <= c <= 'f' ? n<<4 + c-'a'+10 : + 'A' <= c <= 'F' ? n<<4 + c-'A'+10 : break + i = j + end + if k == 1 + error("\\x used with no following hex digits") + end + if m == 2 # \x escape sequence + write(uint8(n)) + else + print(char(n)) + end + elseif '0' <= c <= '7' + k = 1 + n = c-'0' + while (k+=1) <= 3 && !done(s,i) + c, j = next(s,i) + n = '0' <= c <= '7' ? n<<3 + c-'0' : break + i = j + end + if n > 255 + error("octal escape sequence out of range") + end + write(uint8(n)) + else + print(c == 'a' ? '\a' : + c == 'b' ? '\b' : + c == 't' ? '\t' : + c == 'n' ? '\n' : + c == 'v' ? '\v' : + c == 'f' ? '\f' : + c == 'r' ? '\r' : + c == 'e' ? '\e' : c) + end + else + print(c) + end + end +end + +unescape_string(s::String) = print_to_string(length(s), print_unescaped, s) + +## checking UTF-8 & ACSII validity ## + +byte_string_classify(s::ByteString) = + ccall(:u8_isvalid, Int32, (Ptr{Uint8}, Int), s.data, length(s)) + # 0: neither valid ASCII nor UTF-8 + # 1: valid ASCII + # 2: valid UTF-8 + +is_valid_ascii(s::ByteString) = byte_string_classify(s) == 1 +is_valid_utf8 (s::ByteString) = byte_string_classify(s) != 0 + +check_ascii(s::ByteString) = is_valid_ascii(s) ? s : error("invalid ASCII sequence") +check_utf8 (s::ByteString) = is_valid_utf8(s) ? s : error("invalid UTF-8 sequence") + +## string interpolation parsing ## + +function _jl_interp_parse(s::String, unescape::Function, printer::Function) + sx = {} + i = j = start(s) + while !done(s,j) + c, k = next(s,j) + if c == '$' + if !isempty(s[i:j-1]) + push(sx, unescape(s[i:j-1])) + end + ex, j = parseatom(s,k) + push(sx, ex) + i = j + elseif c == '\\' && !done(s,k) + if s[k] == '$' + if !isempty(s[i:j-1]) + push(sx, unescape(s[i:j-1])) + end + i = k + end + c, j = next(s,k) + else + j = k + end + end + if !isempty(s[i:]) + push(sx, unescape(s[i:j-1])) + end + length(sx) == 1 && isa(sx[1],ByteString) ? sx[1] : + expr(:call, :print_to_string, printer, sx...) +end + +_jl_interp_parse(s::String, u::Function) = _jl_interp_parse(s, u, print) +_jl_interp_parse(s::String) = _jl_interp_parse(s, x->check_utf8(unescape_string(x))) + +function _jl_interp_parse_bytes(s::String) + writer(x...) = for w=x; write(w); end + _jl_interp_parse(s, unescape_string, writer) +end + +## core string macros ## + +macro str(s); _jl_interp_parse(s); end +macro S_str(s); _jl_interp_parse(s); end +macro I_str(s); _jl_interp_parse(s, x->unescape_chars(x,"\"")); end +macro E_str(s); check_utf8(unescape_string(s)); end +macro B_str(s); _jl_interp_parse_bytes(s); end +macro b_str(s); ex = _jl_interp_parse_bytes(s); :(($ex).data); end + +## shell-like command parsing ## + +function _jl_shell_parse(s::String, interp::Bool) + + in_single_quotes = false + in_double_quotes = false + + args = {} + arg = {} + i = start(s) + j = i + + function update_arg(x) + if !isa(x,String) || !isempty(x) + push(arg, x) + end + end + function append_arg() + if isempty(arg); arg = {"",}; end + push(args, arg) + arg = {} + end + + while !done(s,j) + c, k = next(s,j) + if !in_single_quotes && !in_double_quotes && iswspace(c) + update_arg(s[i:j-1]) + append_arg() + j = k + while !done(s,j) + c, k = next(s,j) + if !iswspace(c) + i = j + break + end + j = k + end + elseif interp && !in_single_quotes && c == '$' + update_arg(s[i:j-1]); i = k; j = k + if done(s,k) + error("\$ right before end of command") + end + if iswspace(s[k]) + error("space not allowed right after \$") + end + ex, j = parseatom(s,j) + update_arg(ex); i = j + else + if !in_double_quotes && c == '\'' + in_single_quotes = !in_single_quotes + update_arg(s[i:j-1]); i = k + elseif !in_single_quotes && c == '"' + in_double_quotes = !in_double_quotes + update_arg(s[i:j-1]); i = k + elseif c == '\\' + if in_double_quotes + if done(s,k) + error("unterminated double quote") + end + if s[k] == '"' || s[k] == '$' + update_arg(s[i:j-1]); i = k + c, k = next(s,k) + end + elseif !in_single_quotes + if done(s,k) + error("dangling backslash") + end + update_arg(s[i:j-1]); i = k + c, k = next(s,k) + end + end + j = k + end + end + + if in_single_quotes; error("unterminated single quote"); end + if in_double_quotes; error("unterminated double quote"); end + + update_arg(s[i:]) + append_arg() + + if !interp + return args + end + + # construct an expression + exprs = {} + for arg in args + push(exprs, expr(:tuple, arg)) + end + expr(:tuple,exprs) +end +_jl_shell_parse(s::String) = _jl_shell_parse(s,true) + +function shell_split(s::String) + parsed = _jl_shell_parse(s,false) + args = String[] + for arg in parsed + push(args, strcat(arg...)) + end + args +end + +function print_shell_word(word::String) + if isempty(word) + print("''") + end + has_single = false + has_special = false + for c in word + if iswspace(c) || c=='\\' || c=='\'' || c=='"' || c=='$' + has_special = true + if c == '\'' + has_single = true + end + end + end + if !has_special + print(word) + elseif !has_single + print('\'', word, '\'') + else + print('"') + for c in word + if c == '"' || c == '$' + print('\\') + end + print(c) + end + print('"') + end +end + +function print_shell_escaped(cmd::String, args::String...) + print_shell_word(cmd) + for arg in args + print(' ') + print_shell_word(arg) + end +end + +shell_escape(cmd::String, args::String...) = + print_to_string(print_shell_escaped, cmd, args...) + +## interface to parser ## + +function parse(s::String, pos, greedy) + # returns (expr, end_pos). expr is () in case of parse error. + ex, pos = ccall(:jl_parse_string, Any, + (Ptr{Uint8}, Int32, Int32), + cstring(s), pos-1, greedy ? 1:0) + if isa(ex,Expr) && is(ex.head,:error) + throw(ParseError(ex.args[1])) + end + if ex == (); throw(ParseError("end of input")); end + ex, pos+1 # C is zero-based, Julia is 1-based +end + +parse(s::String) = parse(s, 1, true) +parse(s::String, pos) = parse(s, pos, true) +parseatom(s::String) = parse(s, 1, false) +parseatom(s::String, pos) = parse(s, pos, false) + +## miscellaneous string functions ## + +function lpad(s::String, n::Integer, p::String) + m = n - strlen(s) + if m <= 0; return s; end + l = strlen(p) + if l==1 + return p^m * s + end + q = div(m,l) + r = m - q*l + cstring(p^q*p[1:chr2ind(p,r)]*s) +end + +function rpad(s::String, n::Integer, p::String) + m = n - strlen(s) + if m <= 0; return s; end + l = strlen(p) + if l==1 + return s * p^m + end + q = div(m,l) + r = m - q*l + cstring(s*p^q*p[1:chr2ind(p,r)]) +end + +lpad(s, n::Integer, p) = lpad(string(s), n, string(p)) +rpad(s, n::Integer, p) = rpad(string(s), n, string(p)) + +lpad(s, n::Integer) = lpad(string(s), n, " ") +rpad(s, n::Integer) = rpad(string(s), n, " ") + +function split(s::String, delims, include_empty::Bool) + i = 1 + strs = String[] + len = length(s) + while true + tokstart = tokend = i + while !done(s,i) + (c,i) = next(s,i) + if contains(delims, c) + break + end + tokend = i + end + tok = s[tokstart:(tokend-1)] + if include_empty || !isempty(tok) + push(strs, tok) + end + if !((i <= len) || (i==len+1 && tokend!=i)) + break + end + end + strs +end + +split(s::String) = split(s, (' ','\t','\n','\v','\f','\r'), false) +split(s::String, x) = split(s, x, true) +split(s::String, x::Char, incl::Bool) = split(s, (x,), incl) + +function print_joined(strings, delim, last) + i = start(strings) + if done(strings,i) + return + end + str, i = next(strings,i) + print(str) + while !done(strings,i) + str, i = next(strings,i) + print(done(strings,i) ? last : delim) + print(str) + end +end + +function print_joined(strings, delim) + i = start(strings) + while !done(strings,i) + str, i = next(strings,i) + print(str) + if !done(strings,i) + print(delim) + end + end +end +print_joined(strings) = print_joined(strings, "") + +join(args...) = print_to_string(print_joined, args...) + +chop(s::String) = s[1:thisind(s,length(s))-1] +chomp(s::String) = (i=thisind(s,length(s)); s[i]=='\n' ? s[1:i-1] : s) +chomp(s::ByteString) = s.data[end]==0x0a ? s[1:end-1] : s + +function lstrip(s::String) + i = start(s) + while !done(s,i) + c, j = next(s,i) + if !iswspace(c) + return s[i:end] + end + i = j + end + "" +end + +function rstrip(s::String) + r = reverse(s) + i = start(r) + while !done(r,i) + c, j = next(r,i) + if !iswspace(c) + return s[1:end-i+1] + end + i = j + end + "" +end + +strip(s::String) = lstrip(rstrip(s)) + +## string to integer functions ## + +function parse_int{T<:Integer}(::Type{T}, s::String, base::Integer) + if !(2 <= base <= 36); error("invalid base: ",base); end + i = start(s) + if done(s,i) + error("premature end of integer (in ",show_to_string(s),")") + end + c,i = next(s,i) + sgn = one(T) + if T <: Signed && c == '-' + sgn = -sgn + if done(s,i) + error("premature end of integer (in ",show_to_string(s),")") + end + c,i = next(s,i) + end + base = convert(T,base) + n::T = 0 + while true + d = '0' <= c <= '9' ? c-'0' : + 'A' <= c <= 'Z' ? c-'A'+10 : + 'a' <= c <= 'z' ? c-'a'+10 : typemax(Int) + if d >= base + error(show_to_string(c)," is not a valid digit (in ",show_to_string(s),")") + end + # TODO: overflow detection? + n = n*base + d + if done(s,i) + break + end + c,i = next(s,i) + end + return flipsign(n,sgn) +end + +parse_int(s::String, base::Integer) = parse_int(Int,s,base) +parse_int(T::Type, s::String) = parse_int(T,s,10) +parse_int(s::String) = parse_int(Int,s,10) + +parse_bin(T::Type, s::String) = parse_int(T,s,2) +parse_oct(T::Type, s::String) = parse_int(T,s,8) +parse_hex(T::Type, s::String) = parse_int(T,s,16) + +parse_bin(s::String) = parse_int(Int,s,2) +parse_oct(s::String) = parse_int(Int,s,8) +parse_hex(s::String) = parse_int(Int,s,16) + +integer (s::String) = int(s) +unsigned(s::String) = uint(s) +int (s::String) = parse_int(Int,s) +uint (s::String) = parse_int(Uint,s) +int8 (s::String) = parse_int(Int8,s) +uint8 (s::String) = parse_int(Uint8,s) +int16 (s::String) = parse_int(Int16,s) +uint16 (s::String) = parse_int(Uint16,s) +int32 (s::String) = parse_int(Int32,s) +uint32 (s::String) = parse_int(Uint32,s) +int64 (s::String) = parse_int(Int64,s) +uint64 (s::String) = parse_int(Uint64,s) + +## integer to string functions ## + +const _jl_dig_syms = "0123456789abcdefghijklmnopqrstuvwxyz".data + +function int2str(n::Union(Int64,Uint64), b::Integer, l::Int) + if b < 2 || b > 36; error("int2str: invalid base ", b); end + neg = n < 0 + n = unsigned(abs(n)) + b = convert(typeof(n), b) + ndig = ndigits(n, b) + sz = max(convert(Int, ndig), l) + neg + data = Array(Uint8, sz) + i = sz + if ispow2(b) + digmask = b-1 + shift = trailing_zeros(b) + while i > neg + ch = n & digmask + data[i] = _jl_dig_syms[int(ch)+1] + n >>= shift + i -= 1 + end + else + while i > neg + ch = n % b + data[i] = _jl_dig_syms[int(ch)+1] + n = div(n,b) + i -= 1 + end + end + if neg + data[1] = '-' + end + ASCIIString(data) +end +int2str(n::Integer, b::Integer) = int2str(n, b, 0) +int2str(n::Integer, b::Integer, l::Int) = int2str(int64(n), b, l) + +string(x::Signed) = dec(int64(x)) +cstring(x::Signed) = dec(int64(x)) + +## string to float functions ## + +function float64_isvalid(s::String, out::Array{Float64,1}) + s = cstring(s) + return (ccall(:jl_strtod, Int32, (Ptr{Uint8},Ptr{Float64}), s, out)==0) +end + +function float32_isvalid(s::String, out::Array{Float32,1}) + s = cstring(s) + return (ccall(:jl_strtof, Int32, (Ptr{Uint8},Ptr{Float32}), s, out)==0) +end + +begin + local tmp::Array{Float64,1} = Array(Float64,1) + local tmpf::Array{Float32,1} = Array(Float32,1) + global float64, float32 + function float64(s::String) + if !float64_isvalid(s, tmp) + throw(ArgumentError("float64(String): invalid number format")) + end + return tmp[1] + end + + function float32(s::String) + if !float32_isvalid(s, tmpf) + throw(ArgumentError("float32(String): invalid number format")) + end + return tmpf[1] + end +end + +float(x::String) = float64(x) +parse_float(x::String) = float64(x) +parse_float(::Type{Float64}, x::String) = float64(x) +parse_float(::Type{Float32}, x::String) = float32(x) + +# copying a byte string (generally not needed due to "immutability") + +strcpy{T<:ByteString}(s::T) = T(copy(s.data)) + +# lexicographically compare byte arrays (used by Latin-1 and UTF-8) + +function lexcmp(a::Array{Uint8,1}, b::Array{Uint8,1}) + c = ccall(:memcmp, Int32, (Ptr{Uint8}, Ptr{Uint8}, Uint), + a, b, min(length(a),length(b))) + c < 0 ? -1 : c > 0 ? +1 : cmp(length(a),length(b)) +end + +# find the index of the first occurrence of a byte value in a byte array + +function memchr(a::Array{Uint8,1}, b::Integer) + p = pointer(a) + q = ccall(:memchr, Ptr{Uint8}, (Ptr{Uint8}, Int32, Uint), p, b, length(a)) + q == C_NULL ? 0 : q - p + 1 +end + +# concatenate byte arrays into a single array + +memcat() = Array(Uint8,0) +memcat(a::Array{Uint8,1}) = copy(a) + +function memcat(arrays::Array{Uint8,1}...) + n = 0 + for a in arrays + n += length(a) + end + arr = Array(Uint8, n) + ptr = pointer(arr) + offset = 0 + for a in arrays + ccall(:memcpy, Ptr{Uint8}, (Ptr{Uint8}, Ptr{Uint8}, Uint), + ptr+offset, a, length(a)) + offset += length(a) + end + return arr +end + +# concatenate the data fields of byte strings + +memcat(s::ByteString) = memcat(s.data) +memcat(sx::ByteString...) = memcat(map(s->s.data, sx)...) diff --git a/tests/examplefiles/swig_java.swg b/tests/examplefiles/swig_java.swg new file mode 100644 index 00000000..6126a55e --- /dev/null +++ b/tests/examplefiles/swig_java.swg @@ -0,0 +1,1329 @@ +/* ----------------------------------------------------------------------------- + * java.swg + * + * Java typemaps + * ----------------------------------------------------------------------------- */ + +%include <javahead.swg> + +/* The jni, jtype and jstype typemaps work together and so there should be one of each. + * The jni typemap contains the JNI type used in the JNI (C/C++) code. + * The jtype typemap contains the Java type used in the JNI intermediary class. + * The jstype typemap contains the Java type used in the Java proxy classes, type wrapper classes and module class. */ + +/* Fragments */ +%fragment("SWIG_PackData", "header") { +/* Pack binary data into a string */ +SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) { + static const char hex[17] = "0123456789abcdef"; + register const unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register unsigned char uu = *u; + *(c++) = hex[(uu & 0xf0) >> 4]; + *(c++) = hex[uu & 0xf]; + } + return c; +} +} + +%fragment("SWIG_UnPackData", "header") { +/* Unpack binary data from a string */ +SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) { + register unsigned char *u = (unsigned char *) ptr; + register const unsigned char *eu = u + sz; + for (; u != eu; ++u) { + register char d = *(c++); + register unsigned char uu; + if ((d >= '0') && (d <= '9')) + uu = ((d - '0') << 4); + else if ((d >= 'a') && (d <= 'f')) + uu = ((d - ('a'-10)) << 4); + else + return (char *) 0; + d = *(c++); + if ((d >= '0') && (d <= '9')) + uu |= (d - '0'); + else if ((d >= 'a') && (d <= 'f')) + uu |= (d - ('a'-10)); + else + return (char *) 0; + *u = uu; + } + return c; +} +} + +/* Primitive types */ +%typemap(jni) bool, const bool & "jboolean" +%typemap(jni) char, const char & "jchar" +%typemap(jni) signed char, const signed char & "jbyte" +%typemap(jni) unsigned char, const unsigned char & "jshort" +%typemap(jni) short, const short & "jshort" +%typemap(jni) unsigned short, const unsigned short & "jint" +%typemap(jni) int, const int & "jint" +%typemap(jni) unsigned int, const unsigned int & "jlong" +%typemap(jni) long, const long & "jint" +%typemap(jni) unsigned long, const unsigned long & "jlong" +%typemap(jni) long long, const long long & "jlong" +%typemap(jni) unsigned long long, const unsigned long long & "jobject" +%typemap(jni) float, const float & "jfloat" +%typemap(jni) double, const double & "jdouble" +%typemap(jni) void "void" + +%typemap(jtype) bool, const bool & "boolean" +%typemap(jtype) char, const char & "char" +%typemap(jtype) signed char, const signed char & "byte" +%typemap(jtype) unsigned char, const unsigned char & "short" +%typemap(jtype) short, const short & "short" +%typemap(jtype) unsigned short, const unsigned short & "int" +%typemap(jtype) int, const int & "int" +%typemap(jtype) unsigned int, const unsigned int & "long" +%typemap(jtype) long, const long & "int" +%typemap(jtype) unsigned long, const unsigned long & "long" +%typemap(jtype) long long, const long long & "long" +%typemap(jtype) unsigned long long, const unsigned long long & "java.math.BigInteger" +%typemap(jtype) float, const float & "float" +%typemap(jtype) double, const double & "double" +%typemap(jtype) void "void" + +%typemap(jstype) bool, const bool & "boolean" +%typemap(jstype) char, const char & "char" +%typemap(jstype) signed char, const signed char & "byte" +%typemap(jstype) unsigned char, const unsigned char & "short" +%typemap(jstype) short, const short & "short" +%typemap(jstype) unsigned short, const unsigned short & "int" +%typemap(jstype) int, const int & "int" +%typemap(jstype) unsigned int, const unsigned int & "long" +%typemap(jstype) long, const long & "int" +%typemap(jstype) unsigned long, const unsigned long & "long" +%typemap(jstype) long long, const long long & "long" +%typemap(jstype) unsigned long long, const unsigned long long & "java.math.BigInteger" +%typemap(jstype) float, const float & "float" +%typemap(jstype) double, const double & "double" +%typemap(jstype) void "void" + +%typemap(jni) char *, char *&, char[ANY], char[] "jstring" +%typemap(jtype) char *, char *&, char[ANY], char[] "String" +%typemap(jstype) char *, char *&, char[ANY], char[] "String" + +/* JNI types */ +%typemap(jni) jboolean "jboolean" +%typemap(jni) jchar "jchar" +%typemap(jni) jbyte "jbyte" +%typemap(jni) jshort "jshort" +%typemap(jni) jint "jint" +%typemap(jni) jlong "jlong" +%typemap(jni) jfloat "jfloat" +%typemap(jni) jdouble "jdouble" +%typemap(jni) jstring "jstring" +%typemap(jni) jobject "jobject" +%typemap(jni) jbooleanArray "jbooleanArray" +%typemap(jni) jcharArray "jcharArray" +%typemap(jni) jbyteArray "jbyteArray" +%typemap(jni) jshortArray "jshortArray" +%typemap(jni) jintArray "jintArray" +%typemap(jni) jlongArray "jlongArray" +%typemap(jni) jfloatArray "jfloatArray" +%typemap(jni) jdoubleArray "jdoubleArray" +%typemap(jni) jobjectArray "jobjectArray" + +%typemap(jtype) jboolean "boolean" +%typemap(jtype) jchar "char" +%typemap(jtype) jbyte "byte" +%typemap(jtype) jshort "short" +%typemap(jtype) jint "int" +%typemap(jtype) jlong "long" +%typemap(jtype) jfloat "float" +%typemap(jtype) jdouble "double" +%typemap(jtype) jstring "String" +%typemap(jtype) jobject "Object" +%typemap(jtype) jbooleanArray "boolean[]" +%typemap(jtype) jcharArray "char[]" +%typemap(jtype) jbyteArray "byte[]" +%typemap(jtype) jshortArray "short[]" +%typemap(jtype) jintArray "int[]" +%typemap(jtype) jlongArray "long[]" +%typemap(jtype) jfloatArray "float[]" +%typemap(jtype) jdoubleArray "double[]" +%typemap(jtype) jobjectArray "Object[]" + +%typemap(jstype) jboolean "boolean" +%typemap(jstype) jchar "char" +%typemap(jstype) jbyte "byte" +%typemap(jstype) jshort "short" +%typemap(jstype) jint "int" +%typemap(jstype) jlong "long" +%typemap(jstype) jfloat "float" +%typemap(jstype) jdouble "double" +%typemap(jstype) jstring "String" +%typemap(jstype) jobject "Object" +%typemap(jstype) jbooleanArray "boolean[]" +%typemap(jstype) jcharArray "char[]" +%typemap(jstype) jbyteArray "byte[]" +%typemap(jstype) jshortArray "short[]" +%typemap(jstype) jintArray "int[]" +%typemap(jstype) jlongArray "long[]" +%typemap(jstype) jfloatArray "float[]" +%typemap(jstype) jdoubleArray "double[]" +%typemap(jstype) jobjectArray "Object[]" + +/* Non primitive types */ +%typemap(jni) SWIGTYPE "jlong" +%typemap(jtype) SWIGTYPE "long" +%typemap(jstype) SWIGTYPE "$&javaclassname" + +%typemap(jni) SWIGTYPE [] "jlong" +%typemap(jtype) SWIGTYPE [] "long" +%typemap(jstype) SWIGTYPE [] "$javaclassname" + +%typemap(jni) SWIGTYPE * "jlong" +%typemap(jtype) SWIGTYPE * "long" +%typemap(jstype) SWIGTYPE * "$javaclassname" + +%typemap(jni) SWIGTYPE & "jlong" +%typemap(jtype) SWIGTYPE & "long" +%typemap(jstype) SWIGTYPE & "$javaclassname" + +/* pointer to a class member */ +%typemap(jni) SWIGTYPE (CLASS::*) "jstring" +%typemap(jtype) SWIGTYPE (CLASS::*) "String" +%typemap(jstype) SWIGTYPE (CLASS::*) "$javaclassname" + +/* The following are the in, out, freearg, argout typemaps. These are the JNI code generating typemaps for converting from Java to C and visa versa. */ + +/* primitive types */ +%typemap(in) bool +%{ $1 = $input ? true : false; %} + +%typemap(directorout) bool +%{ $result = $input ? true : false; %} + +%typemap(javadirectorin) bool "$jniinput" +%typemap(javadirectorout) bool "$javacall" + +%typemap(in) char, + signed char, + unsigned char, + short, + unsigned short, + int, + unsigned int, + long, + unsigned long, + long long, + float, + double +%{ $1 = ($1_ltype)$input; %} + +%typemap(directorout) char, + signed char, + unsigned char, + short, + unsigned short, + int, + unsigned int, + long, + unsigned long, + long long, + float, + double +%{ $result = ($1_ltype)$input; %} + +%typemap(directorin, descriptor="Z") bool "$input = (jboolean) $1;" +%typemap(directorin, descriptor="C") char "$input = (jint) $1;" +%typemap(directorin, descriptor="B") signed char "$input = (jbyte) $1;" +%typemap(directorin, descriptor="S") unsigned char "$input = (jshort) $1;" +%typemap(directorin, descriptor="S") short "$input = (jshort) $1;" +%typemap(directorin, descriptor="I") unsigned short "$input = (jint) $1;" +%typemap(directorin, descriptor="I") int "$input = (jint) $1;" +%typemap(directorin, descriptor="J") unsigned int "$input = (jlong) $1;" +%typemap(directorin, descriptor="I") long "$input = (jint) $1;" +%typemap(directorin, descriptor="J") unsigned long "$input = (jlong) $1;" +%typemap(directorin, descriptor="J") long long "$input = (jlong) $1;" +%typemap(directorin, descriptor="F") float "$input = (jfloat) $1;" +%typemap(directorin, descriptor="D") double "$input = (jdouble) $1;" + +%typemap(javadirectorin) char, + signed char, + unsigned char, + short, + unsigned short, + int, + unsigned int, + long, + unsigned long, + long long, + float, + double + "$jniinput" + +%typemap(javadirectorout) char, + signed char, + unsigned char, + short, + unsigned short, + int, + unsigned int, + long, + unsigned long, + long long, + float, + double + "$javacall" + +%typemap(out) bool %{ $result = (jboolean)$1; %} +%typemap(out) char %{ $result = (jchar)$1; %} +%typemap(out) signed char %{ $result = (jbyte)$1; %} +%typemap(out) unsigned char %{ $result = (jshort)$1; %} +%typemap(out) short %{ $result = (jshort)$1; %} +%typemap(out) unsigned short %{ $result = (jint)$1; %} +%typemap(out) int %{ $result = (jint)$1; %} +%typemap(out) unsigned int %{ $result = (jlong)$1; %} +%typemap(out) long %{ $result = (jint)$1; %} +%typemap(out) unsigned long %{ $result = (jlong)$1; %} +%typemap(out) long long %{ $result = (jlong)$1; %} +%typemap(out) float %{ $result = (jfloat)$1; %} +%typemap(out) double %{ $result = (jdouble)$1; %} + +/* unsigned long long */ +/* Convert from BigInteger using the toByteArray member function */ +%typemap(in) unsigned long long { + jclass clazz; + jmethodID mid; + jbyteArray ba; + jbyte* bae; + jsize sz; + int i; + + if (!$input) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null"); + return $null; + } + clazz = JCALL1(GetObjectClass, jenv, $input); + mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B"); + ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid); + bae = JCALL2(GetByteArrayElements, jenv, ba, 0); + sz = JCALL1(GetArrayLength, jenv, ba); + $1 = 0; + for(i=0; i<sz; i++) { + $1 = ($1 << 8) | ($1_type)(unsigned char)bae[i]; + } + JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); +} + +%typemap(directorout) unsigned long long { + jclass clazz; + jmethodID mid; + jbyteArray ba; + jbyte* bae; + jsize sz; + int i; + + if (!$input) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null"); + return $null; + } + clazz = JCALL1(GetObjectClass, jenv, $input); + mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B"); + ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid); + bae = JCALL2(GetByteArrayElements, jenv, ba, 0); + sz = JCALL1(GetArrayLength, jenv, ba); + $result = 0; + for(i=0; i<sz; i++) { + $result = ($result << 8) | ($1_type)(unsigned char)bae[i]; + } + JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); +} + + +/* Convert to BigInteger - byte array holds number in 2's complement big endian format */ +%typemap(out) unsigned long long { + jbyteArray ba = JCALL1(NewByteArray, jenv, 9); + jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0); + jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger"); + jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V"); + jobject bigint; + int i; + + bae[0] = 0; + for(i=1; i<9; i++ ) { + bae[i] = (jbyte)($1>>8*(8-i)); + } + + JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); + bigint = JCALL3(NewObject, jenv, clazz, mid, ba); + $result = bigint; +} + +/* Convert to BigInteger (see out typemap) */ +%typemap(directorin, descriptor="Ljava/math/BigInteger;") unsigned long long, const unsigned long long & { + jbyteArray ba = JCALL1(NewByteArray, jenv, 9); + jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0); + jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger"); + jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V"); + jobject bigint; + int swig_i; + + bae[0] = 0; + for(swig_i=1; swig_i<9; swig_i++ ) { + bae[swig_i] = (jbyte)($1>>8*(8-swig_i)); + } + + JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); + bigint = JCALL3(NewObject, jenv, clazz, mid, ba); + $input = bigint; +} + +%typemap(javadirectorin) unsigned long long "$jniinput" +%typemap(javadirectorout) unsigned long long "$javacall" + +/* char * - treat as String */ +%typemap(in, noblock=1) char * { + $1 = 0; + if ($input) { + $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); + if (!$1) return $null; + } +} + +%typemap(directorout, noblock=1, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) char * { + $1 = 0; + if ($input) { + $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); + if (!$result) return $null; + } +} + +%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char * { + $input = 0; + if ($1) { + $input = JCALL1(NewStringUTF, jenv, (const char *)$1); + if (!$input) return $null; + } +} + +%typemap(freearg, noblock=1) char * { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); } +%typemap(out, noblock=1) char * { if ($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); } +%typemap(javadirectorin) char * "$jniinput" +%typemap(javadirectorout) char * "$javacall" + +/* char *& - treat as String */ +%typemap(in, noblock=1) char *& ($*1_ltype temp = 0) { + $1 = 0; + if ($input) { + temp = ($*1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); + if (!temp) return $null; + } + $1 = &temp; +} +%typemap(freearg, noblock=1) char *& { if ($1 && *$1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)*$1); } +%typemap(out, noblock=1) char *& { if (*$1) $result = JCALL1(NewStringUTF, jenv, (const char *)*$1); } + +%typemap(out) void "" +%typemap(javadirectorin) void "$jniinput" +%typemap(javadirectorout) void "$javacall" +%typemap(directorin, descriptor="V") void "" + +/* primitive types by reference */ +%typemap(in) const bool & ($*1_ltype temp) +%{ temp = $input ? true : false; + $1 = &temp; %} + +%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const bool & +%{ static $*1_ltype temp; + temp = $input ? true : false; + $result = &temp; %} + +%typemap(javadirectorin) const bool & "$jniinput" +%typemap(javadirectorout) const bool & "$javacall" + +%typemap(in) const char & ($*1_ltype temp), + const signed char & ($*1_ltype temp), + const unsigned char & ($*1_ltype temp), + const short & ($*1_ltype temp), + const unsigned short & ($*1_ltype temp), + const int & ($*1_ltype temp), + const unsigned int & ($*1_ltype temp), + const long & ($*1_ltype temp), + const unsigned long & ($*1_ltype temp), + const long long & ($*1_ltype temp), + const float & ($*1_ltype temp), + const double & ($*1_ltype temp) +%{ temp = ($*1_ltype)$input; + $1 = &temp; %} + +%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const char &, + const signed char &, + const unsigned char &, + const short &, + const unsigned short &, + const int &, + const unsigned int &, + const long &, + const unsigned long &, + const long long &, + const float &, + const double & +%{ static $*1_ltype temp; + temp = ($*1_ltype)$input; + $result = &temp; %} + +%typemap(directorin, descriptor="Z") const bool & "$input = (jboolean)$1;" +%typemap(directorin, descriptor="C") const char & "$input = (jchar)$1;" +%typemap(directorin, descriptor="B") const signed char & "$input = (jbyte)$1;" +%typemap(directorin, descriptor="S") const unsigned char & "$input = (jshort)$1;" +%typemap(directorin, descriptor="S") const short & "$input = (jshort)$1;" +%typemap(directorin, descriptor="I") const unsigned short & "$input = (jint)$1;" +%typemap(directorin, descriptor="I") const int & "$input = (jint)$1;" +%typemap(directorin, descriptor="J") const unsigned int & "$input = (jlong)$1;" +%typemap(directorin, descriptor="I") const long & "$input = (jint)$1;" +%typemap(directorin, descriptor="J") const unsigned long & "$input = (jlong)$1;" +%typemap(directorin, descriptor="J") const long long & "$input = (jlong)$1;" +%typemap(directorin, descriptor="F") const float & "$input = (jfloat)$1;" +%typemap(directorin, descriptor="D") const double & "$input = (jdouble)$1;" + +%typemap(javadirectorin) const char & ($*1_ltype temp), + const signed char & ($*1_ltype temp), + const unsigned char & ($*1_ltype temp), + const short & ($*1_ltype temp), + const unsigned short & ($*1_ltype temp), + const int & ($*1_ltype temp), + const unsigned int & ($*1_ltype temp), + const long & ($*1_ltype temp), + const unsigned long & ($*1_ltype temp), + const long long & ($*1_ltype temp), + const float & ($*1_ltype temp), + const double & ($*1_ltype temp) + "$jniinput" + +%typemap(javadirectorout) const char & ($*1_ltype temp), + const signed char & ($*1_ltype temp), + const unsigned char & ($*1_ltype temp), + const short & ($*1_ltype temp), + const unsigned short & ($*1_ltype temp), + const int & ($*1_ltype temp), + const unsigned int & ($*1_ltype temp), + const long & ($*1_ltype temp), + const unsigned long & ($*1_ltype temp), + const long long & ($*1_ltype temp), + const float & ($*1_ltype temp), + const double & ($*1_ltype temp) + "$javacall" + + +%typemap(out) const bool & %{ $result = (jboolean)*$1; %} +%typemap(out) const char & %{ $result = (jchar)*$1; %} +%typemap(out) const signed char & %{ $result = (jbyte)*$1; %} +%typemap(out) const unsigned char & %{ $result = (jshort)*$1; %} +%typemap(out) const short & %{ $result = (jshort)*$1; %} +%typemap(out) const unsigned short & %{ $result = (jint)*$1; %} +%typemap(out) const int & %{ $result = (jint)*$1; %} +%typemap(out) const unsigned int & %{ $result = (jlong)*$1; %} +%typemap(out) const long & %{ $result = (jint)*$1; %} +%typemap(out) const unsigned long & %{ $result = (jlong)*$1; %} +%typemap(out) const long long & %{ $result = (jlong)*$1; %} +%typemap(out) const float & %{ $result = (jfloat)*$1; %} +%typemap(out) const double & %{ $result = (jdouble)*$1; %} + +/* const unsigned long long & */ +/* Similar to unsigned long long */ +%typemap(in) const unsigned long long & ($*1_ltype temp) { + jclass clazz; + jmethodID mid; + jbyteArray ba; + jbyte* bae; + jsize sz; + int i; + + if (!$input) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null"); + return $null; + } + clazz = JCALL1(GetObjectClass, jenv, $input); + mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B"); + ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid); + bae = JCALL2(GetByteArrayElements, jenv, ba, 0); + sz = JCALL1(GetArrayLength, jenv, ba); + $1 = &temp; + temp = 0; + for(i=0; i<sz; i++) { + temp = (temp << 8) | ($*1_ltype)(unsigned char)bae[i]; + } + JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); +} + +%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const unsigned long long & { + static $*1_ltype temp; + jclass clazz; + jmethodID mid; + jbyteArray ba; + jbyte* bae; + jsize sz; + int i; + + if (!$input) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null"); + return $null; + } + clazz = JCALL1(GetObjectClass, jenv, $input); + mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B"); + ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid); + bae = JCALL2(GetByteArrayElements, jenv, ba, 0); + sz = JCALL1(GetArrayLength, jenv, ba); + $result = &temp; + temp = 0; + for(i=0; i<sz; i++) { + temp = (temp << 8) | ($*1_ltype)(unsigned char)bae[i]; + } + JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); +} + +%typemap(out) const unsigned long long & { + jbyteArray ba = JCALL1(NewByteArray, jenv, 9); + jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0); + jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger"); + jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V"); + jobject bigint; + int i; + + bae[0] = 0; + for(i=1; i<9; i++ ) { + bae[i] = (jbyte)(*$1>>8*(8-i)); + } + + JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0); + bigint = JCALL3(NewObject, jenv, clazz, mid, ba); + $result = bigint; +} + +%typemap(javadirectorin) const unsigned long long & "$jniinput" +%typemap(javadirectorout) const unsigned long long & "$javacall" + +/* Default handling. Object passed by value. Convert to a pointer */ +%typemap(in) SWIGTYPE ($&1_type argp) +%{ argp = *($&1_ltype*)&$input; + if (!argp) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Attempt to dereference null $1_type"); + return $null; + } + $1 = *argp; %} + +%typemap(directorout) SWIGTYPE ($&1_type argp) +%{ argp = *($&1_ltype*)&$input; + if (!argp) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type"); + return $null; + } + $result = *argp; %} + +%typemap(out) SWIGTYPE +#ifdef __cplusplus +%{ *($&1_ltype*)&$result = new $1_ltype((const $1_ltype &)$1); %} +#else +{ + $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype)); + memmove($1ptr, &$1, sizeof($1_type)); + *($&1_ltype*)&$result = $1ptr; +} +#endif + +%typemap(directorin,descriptor="L$packagepath/$&javaclassname;") SWIGTYPE +%{ $input = 0; + *(($&1_ltype*)&$input) = &$1; %} +%typemap(javadirectorin) SWIGTYPE "new $&javaclassname($jniinput, false)" +%typemap(javadirectorout) SWIGTYPE "$&javaclassname.getCPtr($javacall)" + +/* Generic pointers and references */ +%typemap(in) SWIGTYPE * %{ $1 = *($&1_ltype)&$input; %} +%typemap(in, fragment="SWIG_UnPackData") SWIGTYPE (CLASS::*) { + const char *temp = 0; + if ($input) { + temp = JCALL2(GetStringUTFChars, jenv, $input, 0); + if (!temp) return $null; + } + SWIG_UnpackData(temp, (void *)&$1, sizeof($1)); +} +%typemap(in) SWIGTYPE & %{ $1 = *($&1_ltype)&$input; + if (!$1) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null"); + return $null; + } %} +%typemap(out) SWIGTYPE * +%{ *($&1_ltype)&$result = $1; %} +%typemap(out, fragment="SWIG_PackData", noblock=1) SWIGTYPE (CLASS::*) { + char buf[128]; + char *data = SWIG_PackData(buf, (void *)&$1, sizeof($1)); + *data = '\0'; + $result = JCALL1(NewStringUTF, jenv, buf); +} +%typemap(out) SWIGTYPE & +%{ *($&1_ltype)&$result = $1; %} + +%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE * +%{ $result = *($&1_ltype)&$input; %} +%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE (CLASS::*) +%{ $result = *($&1_ltype)&$input; %} + +%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE * +%{ *(($&1_ltype)&$input) = ($1_ltype) $1; %} +%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE (CLASS::*) +%{ *(($&1_ltype)&$input) = ($1_ltype) $1; %} + +%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE & +%{ if (!$input) { + SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type"); + return $null; + } + $result = *($&1_ltype)&$input; %} +%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE & +%{ *($&1_ltype)&$input = ($1_ltype) &$1; %} + +%typemap(javadirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*) "($jniinput == 0) ? null : new $javaclassname($jniinput, false)" +%typemap(javadirectorin) SWIGTYPE & "new $javaclassname($jniinput, false)" +%typemap(javadirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "$javaclassname.getCPtr($javacall)" + +/* Default array handling */ +%typemap(in) SWIGTYPE [] %{ $1 = *($&1_ltype)&$input; %} +%typemap(out) SWIGTYPE [] %{ *($&1_ltype)&$result = $1; %} +%typemap(freearg) SWIGTYPE [ANY], SWIGTYPE [] "" + +/* char arrays - treat as String */ +%typemap(in, noblock=1) char[ANY], char[] { + $1 = 0; + if ($input) { + $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); + if (!$1) return $null; + } +} + +%typemap(directorout, noblock=1) char[ANY], char[] { + $1 = 0; + if ($input) { + $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0); + if (!$result) return $null; + } +} + +%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char[ANY], char[] { + $input = 0; + if ($1) { + $input = JCALL1(NewStringUTF, jenv, (const char *)$1); + if (!$input) return $null; + } +} + +%typemap(argout) char[ANY], char[] "" +%typemap(freearg, noblock=1) char[ANY], char[] { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); } +%typemap(out, noblock=1) char[ANY], char[] { if ($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); } +%typemap(javadirectorin) char[ANY], char[] "$jniinput" +%typemap(javadirectorout) char[ANY], char[] "$javacall" + +/* JNI types */ +%typemap(in) jboolean, + jchar, + jbyte, + jshort, + jint, + jlong, + jfloat, + jdouble, + jstring, + jobject, + jbooleanArray, + jcharArray, + jbyteArray, + jshortArray, + jintArray, + jlongArray, + jfloatArray, + jdoubleArray, + jobjectArray +%{ $1 = $input; %} + +%typemap(directorout) jboolean, + jchar, + jbyte, + jshort, + jint, + jlong, + jfloat, + jdouble, + jstring, + jobject, + jbooleanArray, + jcharArray, + jbyteArray, + jshortArray, + jintArray, + jlongArray, + jfloatArray, + jdoubleArray, + jobjectArray +%{ $result = $input; %} + +%typemap(out) jboolean, + jchar, + jbyte, + jshort, + jint, + jlong, + jfloat, + jdouble, + jstring, + jobject, + jbooleanArray, + jcharArray, + jbyteArray, + jshortArray, + jintArray, + jlongArray, + jfloatArray, + jdoubleArray, + jobjectArray +%{ $result = $1; %} + +%typemap(directorin,descriptor="Z") jboolean "$input = $1;" +%typemap(directorin,descriptor="C") jchar "$input = $1;" +%typemap(directorin,descriptor="B") jbyte "$input = $1;" +%typemap(directorin,descriptor="S") jshort "$input = $1;" +%typemap(directorin,descriptor="I") jint "$input = $1;" +%typemap(directorin,descriptor="J") jlong "$input = $1;" +%typemap(directorin,descriptor="F") jfloat "$input = $1;" +%typemap(directorin,descriptor="D") jdouble "$input = $1;" +%typemap(directorin,descriptor="Ljava/lang/String;") jstring "$input = $1;" +%typemap(directorin,descriptor="Ljava/lang/Object;",nouse="1") jobject "$input = $1;" +%typemap(directorin,descriptor="[Z") jbooleanArray "$input = $1;" +%typemap(directorin,descriptor="[C") jcharArray "$input = $1;" +%typemap(directorin,descriptor="[B") jbyteArray "$input = $1;" +%typemap(directorin,descriptor="[S") jshortArray "$input = $1;" +%typemap(directorin,descriptor="[I") jintArray "$input = $1;" +%typemap(directorin,descriptor="[J") jlongArray "$input = $1;" +%typemap(directorin,descriptor="[F") jfloatArray "$input = $1;" +%typemap(directorin,descriptor="[D") jdoubleArray "$input = $1;" +%typemap(directorin,descriptor="[Ljava/lang/Object;",nouse="1") jobjectArray "$input = $1;" + +%typemap(javadirectorin) jboolean, + jchar, + jbyte, + jshort, + jint, + jlong, + jfloat, + jdouble, + jstring, + jobject, + jbooleanArray, + jcharArray, + jbyteArray, + jshortArray, + jintArray, + jlongArray, + jfloatArray, + jdoubleArray, + jobjectArray + "$jniinput" + +%typemap(javadirectorout) jboolean, + jchar, + jbyte, + jshort, + jint, + jlong, + jfloat, + jdouble, + jstring, + jobject, + jbooleanArray, + jcharArray, + jbyteArray, + jshortArray, + jintArray, + jlongArray, + jfloatArray, + jdoubleArray, + jobjectArray + "$javacall" + +/* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions + * that cannot be overloaded in Java as more than one C++ type maps to a single Java type */ + +%typecheck(SWIG_TYPECHECK_BOOL) /* Java boolean */ + jboolean, + bool, + const bool & + "" + +%typecheck(SWIG_TYPECHECK_CHAR) /* Java char */ + jchar, + char, + const char & + "" + +%typecheck(SWIG_TYPECHECK_INT8) /* Java byte */ + jbyte, + signed char, + const signed char & + "" + +%typecheck(SWIG_TYPECHECK_INT16) /* Java short */ + jshort, + unsigned char, + short, + const unsigned char &, + const short & + "" + +%typecheck(SWIG_TYPECHECK_INT32) /* Java int */ + jint, + unsigned short, + int, + long, + const unsigned short &, + const int &, + const long & + "" + +%typecheck(SWIG_TYPECHECK_INT64) /* Java long */ + jlong, + unsigned int, + unsigned long, + long long, + const unsigned int &, + const unsigned long &, + const long long & + "" + +%typecheck(SWIG_TYPECHECK_INT128) /* Java BigInteger */ + unsigned long long, + const unsigned long long & + "" + +%typecheck(SWIG_TYPECHECK_FLOAT) /* Java float */ + jfloat, + float, + const float & + "" + +%typecheck(SWIG_TYPECHECK_DOUBLE) /* Java double */ + jdouble, + double, + const double & + "" + +%typecheck(SWIG_TYPECHECK_STRING) /* Java String */ + jstring, + char *, + char *&, + char[ANY], + char [] + "" + +%typecheck(SWIG_TYPECHECK_BOOL_ARRAY) /* Java boolean[] */ + jbooleanArray + "" + +%typecheck(SWIG_TYPECHECK_CHAR_ARRAY) /* Java char[] */ + jcharArray + "" + +%typecheck(SWIG_TYPECHECK_INT8_ARRAY) /* Java byte[] */ + jbyteArray + "" + +%typecheck(SWIG_TYPECHECK_INT16_ARRAY) /* Java short[] */ + jshortArray + "" + +%typecheck(SWIG_TYPECHECK_INT32_ARRAY) /* Java int[] */ + jintArray + "" + +%typecheck(SWIG_TYPECHECK_INT64_ARRAY) /* Java long[] */ + jlongArray + "" + +%typecheck(SWIG_TYPECHECK_FLOAT_ARRAY) /* Java float[] */ + jfloatArray + "" + +%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY) /* Java double[] */ + jdoubleArray + "" + +%typecheck(SWIG_TYPECHECK_OBJECT_ARRAY) /* Java jobject[] */ + jobjectArray + "" + +%typecheck(SWIG_TYPECHECK_POINTER) /* Default */ + SWIGTYPE, + SWIGTYPE *, + SWIGTYPE &, + SWIGTYPE *const&, + SWIGTYPE [], + SWIGTYPE (CLASS::*) + "" + + +/* Exception handling */ + +%typemap(throws) int, + long, + short, + unsigned int, + unsigned long, + unsigned short +%{ char error_msg[256]; + sprintf(error_msg, "C++ $1_type exception thrown, value: %d", $1); + SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, error_msg); + return $null; %} + +%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY] +%{ (void)$1; + SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown"); + return $null; %} + +%typemap(throws) char * +%{ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1); + return $null; %} + + +/* Typemaps for code generation in proxy classes and Java type wrapper classes */ + +/* The javain typemap is used for converting function parameter types from the type + * used in the proxy, module or type wrapper class to the type used in the JNI class. */ +%typemap(javain) bool, const bool &, + char, const char &, + signed char, const signed char &, + unsigned char, const unsigned char &, + short, const short &, + unsigned short, const unsigned short &, + int, const int &, + unsigned int, const unsigned int &, + long, const long &, + unsigned long, const unsigned long &, + long long, const long long &, + unsigned long long, const unsigned long long &, + float, const float &, + double, const double & + "$javainput" +%typemap(javain) char *, char *&, char[ANY], char[] "$javainput" +%typemap(javain) jboolean, + jchar, + jbyte, + jshort, + jint, + jlong, + jfloat, + jdouble, + jstring, + jobject, + jbooleanArray, + jcharArray, + jbyteArray, + jshortArray, + jintArray, + jlongArray, + jfloatArray, + jdoubleArray, + jobjectArray + "$javainput" +%typemap(javain) SWIGTYPE "$&javaclassname.getCPtr($javainput)" +%typemap(javain) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] "$javaclassname.getCPtr($javainput)" +%typemap(javain) SWIGTYPE (CLASS::*) "$javaclassname.getCMemberPtr($javainput)" + +/* The javaout typemap is used for converting function return types from the return type + * used in the JNI class to the type returned by the proxy, module or type wrapper class. */ +%typemap(javaout) bool, const bool &, + char, const char &, + signed char, const signed char &, + unsigned char, const unsigned char &, + short, const short &, + unsigned short, const unsigned short &, + int, const int &, + unsigned int, const unsigned int &, + long, const long &, + unsigned long, const unsigned long &, + long long, const long long &, + unsigned long long, const unsigned long long &, + float, const float &, + double, const double & { + return $jnicall; + } +%typemap(javaout) char *, char *&, char[ANY], char[] { + return $jnicall; + } +%typemap(javaout) jboolean, + jchar, + jbyte, + jshort, + jint, + jlong, + jfloat, + jdouble, + jstring, + jobject, + jbooleanArray, + jcharArray, + jbyteArray, + jshortArray, + jintArray, + jlongArray, + jfloatArray, + jdoubleArray, + jobjectArray { + return $jnicall; + } +%typemap(javaout) void { + $jnicall; + } +%typemap(javaout) SWIGTYPE { + return new $&javaclassname($jnicall, true); + } +%typemap(javaout) SWIGTYPE & { + return new $javaclassname($jnicall, $owner); + } +%typemap(javaout) SWIGTYPE *, SWIGTYPE [] { + long cPtr = $jnicall; + return (cPtr == 0) ? null : new $javaclassname(cPtr, $owner); + } +%typemap(javaout) SWIGTYPE (CLASS::*) { + String cMemberPtr = $jnicall; + return (cMemberPtr == null) ? null : new $javaclassname(cMemberPtr, $owner); + } + +/* Pointer reference typemaps */ +%typemap(jni) SWIGTYPE *const& "jlong" +%typemap(jtype) SWIGTYPE *const& "long" +%typemap(jstype) SWIGTYPE *const& "$*javaclassname" +%typemap(javain) SWIGTYPE *const& "$*javaclassname.getCPtr($javainput)" +%typemap(javaout) SWIGTYPE *const& { + long cPtr = $jnicall; + return (cPtr == 0) ? null : new $*javaclassname(cPtr, $owner); + } +%typemap(in) SWIGTYPE *const& ($*1_ltype temp = 0) +%{ temp = *($1_ltype)&$input; + $1 = ($1_ltype)&temp; %} +%typemap(out) SWIGTYPE *const& +%{ *($1_ltype)&$result = *$1; %} + +/* Typemaps used for the generation of proxy and type wrapper class code */ +%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(javaclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class" +%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(javaimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" +%typemap(javainterfaces) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "" + +/* javabody typemaps */ + +%define SWIG_JAVABODY_METHODS(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) SWIG_JAVABODY_PROXY(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE) %enddef // legacy name + +%define SWIG_JAVABODY_PROXY(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) +// Base proxy classes +%typemap(javabody) TYPE %{ + private long swigCPtr; + protected boolean swigCMemOwn; + + PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { + swigCMemOwn = cMemoryOwn; + swigCPtr = cPtr; + } + + CPTR_VISIBILITY static long getCPtr($javaclassname obj) { + return (obj == null) ? 0 : obj.swigCPtr; + } +%} + +// Derived proxy classes +%typemap(javabody_derived) TYPE %{ + private long swigCPtr; + + PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) { + super($imclassname.$javaclazznameSWIGUpcast(cPtr), cMemoryOwn); + swigCPtr = cPtr; + } + + CPTR_VISIBILITY static long getCPtr($javaclassname obj) { + return (obj == null) ? 0 : obj.swigCPtr; + } +%} +%enddef + +%define SWIG_JAVABODY_TYPEWRAPPER(PTRCTOR_VISIBILITY, DEFAULTCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) +// Typewrapper classes +%typemap(javabody) TYPE *, TYPE &, TYPE [] %{ + private long swigCPtr; + + PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean futureUse) { + swigCPtr = cPtr; + } + + DEFAULTCTOR_VISIBILITY $javaclassname() { + swigCPtr = 0; + } + + CPTR_VISIBILITY static long getCPtr($javaclassname obj) { + return (obj == null) ? 0 : obj.swigCPtr; + } +%} + +%typemap(javabody) TYPE (CLASS::*) %{ + private String swigCMemberPtr; + + PTRCTOR_VISIBILITY $javaclassname(String cMemberPtr, boolean futureUse) { + swigCMemberPtr = cMemberPtr; + } + + DEFAULTCTOR_VISIBILITY $javaclassname() { + swigCMemberPtr = null; + } + + CPTR_VISIBILITY static String getCMemberPtr($javaclassname obj) { + return obj.swigCMemberPtr; + } +%} +%enddef + +/* Set the default javabody typemaps to use protected visibility. + Use the macros to change to public if using multiple modules. */ +SWIG_JAVABODY_PROXY(protected, protected, SWIGTYPE) +SWIG_JAVABODY_TYPEWRAPPER(protected, protected, protected, SWIGTYPE) + +%typemap(javafinalize) SWIGTYPE %{ + protected void finalize() { + delete(); + } +%} + +/* + * Java constructor typemaps: + * + * The javaconstruct typemap is inserted when a proxy class's constructor is generated. + * This typemap allows control over what code is executed in the constructor as + * well as specifying who owns the underlying C/C++ object. Normally, Java has + * ownership and the underlying C/C++ object is deallocated when the Java object + * is finalized (swigCMemOwn is true.) If swigCMemOwn is false, C/C++ is + * ultimately responsible for deallocating the underlying object's memory. + * + * The SWIG_PROXY_CONSTRUCTOR macro defines the javaconstruct typemap for a proxy + * class for a particular TYPENAME. OWNERSHIP is passed as the value of + * swigCMemOwn to the pointer constructor method. WEAKREF determines which kind + * of Java object reference will be used by the C++ director class (WeakGlobalRef + * vs. GlobalRef.) + * + * The SWIG_DIRECTOR_OWNED macro sets the ownership of director-based proxy + * classes and the weak reference flag to false, meaning that the underlying C++ + * object will be reclaimed by C++. + */ + +%define SWIG_PROXY_CONSTRUCTOR(OWNERSHIP, WEAKREF, TYPENAME...) +%typemap(javaconstruct,directorconnect="\n $imclassname.$javaclazznamedirector_connect(this, swigCPtr, swigCMemOwn, WEAKREF);") TYPENAME { + this($imcall, OWNERSHIP);$directorconnect + } +%enddef + +%define SWIG_DIRECTOR_OWNED(TYPENAME...) +SWIG_PROXY_CONSTRUCTOR(true, false, TYPENAME) +%enddef + +// Set the default for SWIGTYPE: Java owns the C/C++ object. +SWIG_PROXY_CONSTRUCTOR(true, true, SWIGTYPE) + +%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE { + if (swigCPtr != 0) { + if (swigCMemOwn) { + swigCMemOwn = false; + $jnicall; + } + swigCPtr = 0; + } + } + +%typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE { + if (swigCPtr != 0) { + if (swigCMemOwn) { + swigCMemOwn = false; + $jnicall; + } + swigCPtr = 0; + } + super.delete(); + } + +%typemap(directordisconnect, methodname="swigDirectorDisconnect") SWIGTYPE %{ + protected void $methodname() { + swigCMemOwn = false; + $jnicall; + } +%} + +%typemap(directorowner_release, methodname="swigReleaseOwnership") SWIGTYPE %{ + public void $methodname() { + swigCMemOwn = false; + $jnicall; + } +%} + +%typemap(directorowner_take, methodname="swigTakeOwnership") SWIGTYPE %{ + public void $methodname() { + swigCMemOwn = true; + $jnicall; + } +%} + +/* Java specific directives */ +#define %javaconst(flag) %feature("java:const","flag") +#define %javaconstvalue(value) %feature("java:constvalue",value) +#define %javaenum(wrapapproach) %feature("java:enum","wrapapproach") +#define %javamethodmodifiers %feature("java:methodmodifiers") +#define %javaexception(exceptionclasses) %feature("except",throws=exceptionclasses) +#define %nojavaexception %feature("except","0",throws="") +#define %clearjavaexception %feature("except","",throws="") + +%pragma(java) jniclassclassmodifiers="public class" +%pragma(java) moduleclassmodifiers="public class" + +/* Some ANSI C typemaps */ + +%apply unsigned long { size_t }; +%apply const unsigned long & { const size_t & }; + +/* Array reference typemaps */ +%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) } + +/* const pointers */ +%apply SWIGTYPE * { SWIGTYPE *const } + +/* String & length */ +%typemap(jni) (char *STRING, size_t LENGTH) "jbyteArray" +%typemap(jtype) (char *STRING, size_t LENGTH) "byte[]" +%typemap(jstype) (char *STRING, size_t LENGTH) "byte[]" +%typemap(javain) (char *STRING, size_t LENGTH) "$javainput" +%typemap(freearg) (char *STRING, size_t LENGTH) "" +%typemap(in) (char *STRING, size_t LENGTH) { + if ($input) { + $1 = (char *) JCALL2(GetByteArrayElements, jenv, $input, 0); + $2 = (size_t) JCALL1(GetArrayLength, jenv, $input); + } else { + $1 = 0; + $2 = 0; + } +} +%typemap(argout) (char *STRING, size_t LENGTH) { + if ($input) JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *)$1, 0); +} +%typemap(directorin, descriptor="[B") (char *STRING, size_t LENGTH) { + jbyteArray jb = (jenv)->NewByteArray($2); + (jenv)->SetByteArrayRegion(jb, 0, $2, (jbyte *)$1); + $input = jb; +} +%typemap(directorargout) (char *STRING, size_t LENGTH) +%{(jenv)->GetByteArrayRegion($input, 0, $2, (jbyte *)$1); %} +%apply (char *STRING, size_t LENGTH) { (char *STRING, int LENGTH) } + +/* java keywords */ +%include <javakw.swg> + +// Default enum handling +%include <enumtypesafe.swg> + diff --git a/tests/examplefiles/swig_std_vector.i b/tests/examplefiles/swig_std_vector.i new file mode 100644 index 00000000..baecf850 --- /dev/null +++ b/tests/examplefiles/swig_std_vector.i @@ -0,0 +1,225 @@ +// +// std::vector +// + +%include <std_container.i> + +// Vector + +%define %std_vector_methods(vector...) + %std_sequence_methods(vector) + + void reserve(size_type n); + size_type capacity() const; +%enddef + + +%define %std_vector_methods_val(vector...) + %std_sequence_methods_val(vector) + + void reserve(size_type n); + size_type capacity() const; +%enddef + + +// ------------------------------------------------------------------------ +// std::vector +// +// The aim of all that follows would be to integrate std::vector with +// as much as possible, namely, to allow the user to pass and +// be returned tuples or lists. +// const declarations are used to guess the intent of the function being +// exported; therefore, the following rationale is applied: +// +// -- f(std::vector<T>), f(const std::vector<T>&): +// the parameter being read-only, either a sequence or a +// previously wrapped std::vector<T> can be passed. +// -- f(std::vector<T>&), f(std::vector<T>*): +// the parameter may be modified; therefore, only a wrapped std::vector +// can be passed. +// -- std::vector<T> f(), const std::vector<T>& f(): +// the vector is returned by copy; therefore, a sequence of T:s +// is returned which is most easily used in other functions +// -- std::vector<T>& f(), std::vector<T>* f(): +// the vector is returned by reference; therefore, a wrapped std::vector +// is returned +// -- const std::vector<T>* f(), f(const std::vector<T>*): +// for consistency, they expect and return a plain vector pointer. +// ------------------------------------------------------------------------ + +%{ +#include <vector> +%} + +// exported classes + + +namespace std { + + template<class _Tp, class _Alloc = allocator< _Tp > > + class vector { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef _Tp value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef _Tp& reference; + typedef const _Tp& const_reference; + typedef _Alloc allocator_type; + + %traits_swigtype(_Tp); + %traits_enum(_Tp); + + %fragment(SWIG_Traits_frag(std::vector<_Tp, _Alloc >), "header", + fragment=SWIG_Traits_frag(_Tp), + fragment="StdVectorTraits") { + namespace swig { + template <> struct traits<std::vector<_Tp, _Alloc > > { + typedef pointer_category category; + static const char* type_name() { + return "std::vector<" #_Tp "," #_Alloc " >"; + } + }; + } + } + + %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp, _Alloc >); + +#ifdef %swig_vector_methods + // Add swig/language extra methods + %swig_vector_methods(std::vector<_Tp, _Alloc >); +#endif + + %std_vector_methods(vector); + }; + + // *** + // This specialization should disappear or get simplified when + // a 'const SWIGTYPE*&' can be defined + // *** + template<class _Tp, class _Alloc > + class vector<_Tp*, _Alloc > { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef _Tp* value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type reference; + typedef value_type const_reference; + typedef _Alloc allocator_type; + + %traits_swigtype(_Tp); + + %fragment(SWIG_Traits_frag(std::vector<_Tp*, _Alloc >), "header", + fragment=SWIG_Traits_frag(_Tp), + fragment="StdVectorTraits") { + namespace swig { + template <> struct traits<std::vector<_Tp*, _Alloc > > { + typedef value_category category; + static const char* type_name() { + return "std::vector<" #_Tp " *," #_Alloc " >"; + } + }; + } + } + + %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp*, _Alloc >); + +#ifdef %swig_vector_methods_val + // Add swig/language extra methods + %swig_vector_methods_val(std::vector<_Tp*, _Alloc >); +#endif + + %std_vector_methods_val(vector); + }; + + // *** + // const pointer specialization + // *** + template<class _Tp, class _Alloc > + class vector<_Tp const *, _Alloc > { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef _Tp const * value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type reference; + typedef value_type const_reference; + typedef _Alloc allocator_type; + + %traits_swigtype(_Tp); + + %fragment(SWIG_Traits_frag(std::vector<_Tp const*, _Alloc >), "header", + fragment=SWIG_Traits_frag(_Tp), + fragment="StdVectorTraits") { + namespace swig { + template <> struct traits<std::vector<_Tp const*, _Alloc > > { + typedef value_category category; + static const char* type_name() { + return "std::vector<" #_Tp " const*," #_Alloc " >"; + } + }; + } + } + + %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp const*, _Alloc >); + +#ifdef %swig_vector_methods_val + // Add swig/language extra methods + %swig_vector_methods_val(std::vector<_Tp const*, _Alloc >); +#endif + + %std_vector_methods_val(vector); + }; + + // *** + // bool specialization + // *** + + template<class _Alloc > + class vector<bool,_Alloc > { + public: + typedef size_t size_type; + typedef ptrdiff_t difference_type; + typedef bool value_type; + typedef value_type* pointer; + typedef const value_type* const_pointer; + typedef value_type reference; + typedef value_type const_reference; + typedef _Alloc allocator_type; + + %traits_swigtype(bool); + + %fragment(SWIG_Traits_frag(std::vector<bool, _Alloc >), "header", + fragment=SWIG_Traits_frag(bool), + fragment="StdVectorTraits") { + namespace swig { + template <> struct traits<std::vector<bool, _Alloc > > { + typedef value_category category; + static const char* type_name() { + return "std::vector<bool, _Alloc >"; + } + }; + } + } + + %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<bool, _Alloc >); + + +#ifdef %swig_vector_methods_val + // Add swig/language extra methods + %swig_vector_methods_val(std::vector<bool, _Alloc >); +#endif + + %std_vector_methods_val(vector); + +#if defined(SWIG_STD_MODERN_STL) && !defined(SWIG_STD_NOMODERN_STL) + void flip(); +#endif + + }; + +} diff --git a/tests/examplefiles/test.R b/tests/examplefiles/test.R index c53edd13..1dd8f64b 100644 --- a/tests/examplefiles/test.R +++ b/tests/examplefiles/test.R @@ -1,119 +1,185 @@ -################################### -####### emplikH1.test() ########## -################################### - -emplikH1.test <- function(x, d, theta, fun, - tola = .Machine$double.eps^.25) -{ -n <- length(x) -if( n <= 2 ) stop("Need more observations") -if( length(d) != n ) stop("length of x and d must agree") -if(any((d!=0)&(d!=1))) stop("d must be 0/1's for censor/not-censor") -if(!is.numeric(x)) stop("x must be numeric values --- observed times") - -#temp<-summary(survfit(Surv(x,d),se.fit=F,type="fleming",conf.type="none")) -# -newdata <- Wdataclean2(x,d) -temp <- DnR(newdata$value, newdata$dd, newdata$weight) - -time <- temp$time # only uncensored time? Yes. -risk <- temp$n.risk -jump <- (temp$n.event)/risk - -funtime <- fun(time) -funh <- (n/risk) * funtime # that is Zi -funtimeTjump <- funtime * jump - -if(jump[length(jump)] >= 1) funh[length(jump)] <- 0 #for inthaz and weights - -inthaz <- function(x, ftj, fh, thet){ sum(ftj/(1 + x * fh)) - thet } - -diff <- inthaz(0, funtimeTjump, funh, theta) - -if( diff == 0 ) { lam <- 0 } else { - step <- 0.2/sqrt(n) - if(abs(diff) > 6*log(n)*step ) - stop("given theta value is too far away from theta0") - - mini<-0 - maxi<-0 - if(diff > 0) { - maxi <- step - while(inthaz(maxi, funtimeTjump, funh, theta) > 0 && maxi < 50*log(n)*step) - maxi <- maxi+step - } - else { - mini <- -step - while(inthaz(mini, funtimeTjump, funh, theta) < 0 && mini > - 50*log(n)*step) - mini <- mini - step - } - - if(inthaz(mini, funtimeTjump, funh, theta)*inthaz(maxi, funtimeTjump, funh, theta) > 0 ) - stop("given theta is too far away from theta0") - - temp2 <- uniroot(inthaz,c(mini,maxi), tol = tola, - ftj=funtimeTjump, fh=funh, thet=theta) - lam <- temp2$root +#!/usr/bin/env Rscript +### Example R script for syntax highlighting + +# This is also a comment + +## Valid names +abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV0123456789._a <- NULL +.foo_ <- NULL +._foo <- NULL + +## Invalid names +0abc <- NULL +.0abc <- NULL +abc+cde <- NULL + +## Reserved Words +NA +NA_integer_ +NA_real_ +NA_character_ +NA_complex_ +NULL +NaN +Inf +## Not reserved +NULLa <- NULL +NULL1 <- NULL +NULL. <- NULL +NA_foo_ <- NULL + +## Numbers +12345678901 +123456.78901 +123e3 +123E3 +6.02e23 +1.6e-35 +1.E12 +.1234 +## integers +123L +1.23L +## imaginary numbers +123i +-123i +123e4i +123e-4i +## Hex numbers +0xabcdefABCDEF01234 +0xabcp123 +0xabcP123 +## Not hex +0xg + +## Special operators %xyz% +## %xyz% +1 %% 2 +diag(2) %*% diag(2) +1 %/% 2 +1 %in% 1:10 +diag(2) %o% diag(2) +diag(2) %x% diag(2) +`%foo bar%` <- function(x, y) x + y +1 %foo bar% 2 + +## Control Structures (3.2) and Function +## if, else +if (TRUE) print("foo") else print("bar") +## For, in +for(i in 1:5) { + print(i) } - -onepluslamh<- 1 + lam * funh ### this is 1 + lam Zi in Ref. - -weights <- jump/onepluslamh #need to change last jump to 1? NO. see above - -loglik <- 2*(sum(log(onepluslamh)) - sum((onepluslamh-1)/onepluslamh) ) -#?is that right? YES see (3.2) in Ref. above. This ALR, or Poisson LR. - -#last <- length(jump) ## to compute loglik2, we need to drop last jump -#if (jump[last] == 1) { -# risk1 <- risk[-last] -# jump1 <- jump[-last] -# weights1 <- weights[-last] -# } else { -# risk1 <- risk -# jump1 <- jump -# weights1 <- weights -# } -#loglik2 <- 2*( sum(log(onepluslamh)) + -# sum( (risk1 -1)*log((1-jump1)/(1- weights1) ) ) ) -##? this likelihood seems have negative values sometimes??? - -list( logemlik=loglik, ### logemlikv2=loglik2, - lambda=lam, times=time, wts=weights, - nits=temp2$nf, message=temp2$message ) +## While, break +i <- 1 +while (TRUE) { + i <- i + 1 + if (i > 3) break } - -library("graphics") - -par(mfrow = c(1, 2)) -# plot histogram -x <- rnorm(100) -if (max(x) > 100) - stop("Quite unexpected.") -else - hist(x, plot=TRUE, col="ivory") - -# from doc: lowess -plot(cars, main = "lowess(cars)") - lines(lowess(cars), col = 2) - lines(lowess(cars, f=.2), col = 3) - legend(5, 120, c(paste("f = ", c("2/3", ".2"))), lty = 1, col = 2:3) - -# from doc: is.na -is.na(c(1, NA)) - -# from doc: Extract -y <- list(1,2,a=4,5) -y[c(3,4)] # a list containing elements 3 and 4 of y -y$a # the element of y named a - -# from doc: for -for(n in c(2,5,10,20,50)) { - x <- stats::rnorm(n) - cat(n,":", sum(x2),"\n") +## Repeat +repeat {1+1} +## Switch +x <- 3 +switch(x, 2+2, mean(1:10), rnorm(5)) +## Function, dot-dot-dot, return, sum +foo <- function(...) { + return(sum(...)) +} +# Not keywords +functiona <- 2 + 2 +function. <- 2 + 2 +function1 <- 2 + 2 + + +## Grouping Tokens 10.3.7 +## Parentheses +1 + (2 + 3) +## brackets +foo <- function(a) { + a + 1 } -class(fo <- y ~ x1*x2) # "formula" - - - - +## Indexing 10.3.8 +## [] +bar <- 1:10 +bar[3] +## [[]] +foo <- list(a=1, b=2, c=3) +foo[["a"]] +## $ +foo$a +foo$"a" + +## Operators +2 - 2 +2 + 2 +2 ~ 2 +! TRUE +?"help" +1:2 +2 * 2 +2 / 2 +2^2 +2 < 2 +2 > 2 +2 == 2 +2 >= 2 +2 <= 2 +2 != 2 +TRUE & FALSE +TRUE && FALSE +TRUE | FALSE +TRUE || FALSE +foo <- 2 + 2 +foo = 2 + 2 +2 + 2 -> foo +foo <<- 2 + 2 +2 + 2 ->> foo +base:::sum +base::sum + +## Strings +foo <- "hello, world!" +foo <- 'hello, world!' +foo <- "Hello, 'world!" +foo <- 'Hello, "world!' +foo <- 'Hello, \'world!\'' +foo <- "Hello, \"world!\"" +foo <- "Hello, +world!" +foo <- 'Hello, +world!' + +## Backtick strings +`foo123 +!"bar'baz` <- 2 + 2 + +## Builtin funcitons +file.create() +gamma() +grep() +paste() +rbind() +rownames() +R.Version() +R.version.string() +sample() +sapply() +save.image() +seq() +setwd() +sin() + +## Data structures +servo <- matrix(1:25, nrow = 5) +numeric() +vector(servo) +data.frame() +list1 <- list(time = 1:40) +# multidimensional array +array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2)) + +## Namespace +library(ggplot2) +require(plyr) +attach(cars) +source("test.R") diff --git a/tests/examplefiles/test.agda b/tests/examplefiles/test.agda new file mode 100644 index 00000000..d930a77b --- /dev/null +++ b/tests/examplefiles/test.agda @@ -0,0 +1,102 @@ +-- An Agda example file + +module test where + +open import Coinduction +open import Data.Bool +open import {- pointless comment between import and module name -} Data.Char +open import Data.Nat +open import Data.Nat.Properties +open import Data.String +open import Data.List hiding ([_]) +open import Data.Vec hiding ([_]) +open import Relation.Nullary.Core +open import Relation.Binary.PropositionalEquality using (_≡_; refl; cong; trans; inspect; [_]) + +open SemiringSolver + +{- this is a {- nested -} comment -} + +-- Factorial +_! : ℕ → ℕ +0 ! = 1 +(suc n) ! = (suc n) * n ! + +-- The binomial coefficient +_choose_ : ℕ → ℕ → ℕ +_ choose 0 = 1 +0 choose _ = 0 +(suc n) choose (suc m) = (n choose m) + (n choose (suc m)) -- Pascal's rule + +choose-too-many : ∀ n m → n ≤ m → n choose (suc m) ≡ 0 +choose-too-many .0 m z≤n = refl +choose-too-many (suc n) (suc m) (s≤s le) with n choose (suc m) | choose-too-many n m le | n choose (suc (suc m)) | choose-too-many n (suc m) (≤-step le) +... | .0 | refl | .0 | refl = refl + +_++'_ : ∀ {a n m} {A : Set a} → Vec A n → Vec A m → Vec A (m + n) +_++'_ {_} {n} {m} v₁ v₂ rewrite solve 2 (λ a b → b :+ a := a :+ b) refl n m = v₁ Data.Vec.++ v₂ + +++'-test : (1 ∷ 2 ∷ 3 ∷ []) ++' (4 ∷ 5 ∷ []) ≡ (1 ∷ 2 ∷ 3 ∷ 4 ∷ 5 ∷ []) +++'-test = refl + +data Coℕ : Set where + co0 : Coℕ + cosuc : ∞ Coℕ → Coℕ + +nanana : Coℕ +nanana = let two = ♯ cosuc (♯ (cosuc (♯ co0))) in cosuc two + +abstract + data VacuumCleaner : Set where + Roomba : VacuumCleaner + +pointlessLemmaAboutBoolFunctions : (f : Bool → Bool) → f (f (f true)) ≡ f true +pointlessLemmaAboutBoolFunctions f with f true | inspect f true +... | true | [ eq₁ ] = trans (cong f eq₁) eq₁ +... | false | [ eq₁ ] with f false | inspect f false +... | true | _ = eq₁ +... | false | [ eq₂ ] = eq₂ + +mutual + isEven : ℕ → Bool + isEven 0 = true + isEven (suc n) = not (isOdd n) + + isOdd : ℕ → Bool + isOdd 0 = false + isOdd (suc n) = not (isEven n) + +foo : String +foo = "Hello World!" + +nl : Char +nl = '\n' + +private + intersperseString : Char → List String → String + intersperseString c [] = "" + intersperseString c (x ∷ xs) = Data.List.foldl (λ a b → a Data.String.++ Data.String.fromList (c ∷ []) Data.String.++ b) x xs + +baz : String +baz = intersperseString nl (Data.List.replicate 5 foo) + +postulate + Float : Set + +{-# BUILTIN FLOAT Float #-} + +pi : Float +pi = 3.141593 + +-- Astronomical unit +au : Float +au = 1.496e11 -- m + +plusFloat : Float → Float → Float +plusFloat a b = {! !} + +record Subset (A : Set) (P : A → Set) : Set where + constructor _#_ + field + elem : A + .proof : P elem diff --git a/tests/examplefiles/test.apl b/tests/examplefiles/test.apl new file mode 100644 index 00000000..26ecf971 --- /dev/null +++ b/tests/examplefiles/test.apl @@ -0,0 +1,26 @@ +∇ R←M COMBIN N;D;E;F;G;P + ⍝ Returns a matrix of every possible + ⍝ combination of M elements from the + ⍝ vector ⍳N. That is, returns a + ⍝ matrix with M!N rows and N columns. + ⍝ + E←(⍳P←N-R←M-1)-⎕IO + D←R+⍳P + R←(P,1)⍴D + P←P⍴1 + L1:→(⎕IO>1↑D←D-1)⍴0 + P←+\P + G←+\¯1↓0,F←⌽P + E←F/E-G + R←(F/D),R[E+⍳⍴E;] + E←G + →L1 +∇ + +∇ R←M QUICKEXP N + ⍝ Matrix exponentiation + B ← ⌊ 1 + 2 ⍟ N + V ← (B ⍴ 2) ⊤ N + L ← ⊂ M + R ← ⊃ +.× / V / L ⊣ { L ← (⊂ A +.× A ← ↑L) , L }¨ ⍳ B-1 +∇ diff --git a/tests/examplefiles/test.awk b/tests/examplefiles/test.awk new file mode 100644 index 00000000..9f0e3ec9 --- /dev/null +++ b/tests/examplefiles/test.awk @@ -0,0 +1,121 @@ +#!/bin/awk -f + +BEGIN { + # It is not possible to define output file names here because + # FILENAME is not define in the BEGIN section + n = ""; + printf "Generating data files ..."; + network_max_bandwidth_in_byte = 10000000; + network_max_packet_per_second = 1000000; + last3 = 0; + last4 = 0; + last5 = 0; + last6 = 0; +} +{ + if ($1 ~ /Average/) + { # Skip the Average values + n = ""; + next; + } + + if ($2 ~ /all/) + { # This is the cpu info + print $3 > FILENAME".cpu.user.dat"; +# print $4 > FILENAME".cpu.nice.dat"; + print $5 > FILENAME".cpu.system.dat"; +# print $6 > FILENAME".cpu.iowait.dat"; + print $7 > FILENAME".cpu.idle.dat"; + print 100-$7 > FILENAME".cpu.busy.dat"; + } + if ($2 ~ /eth0/) + { # This is the eth0 network info + if ($3 > network_max_packet_per_second) + print last3 > FILENAME".net.rxpck.dat"; # Total number of packets received per second. + else + { + last3 = $3; + print $3 > FILENAME".net.rxpck.dat"; # Total number of packets received per second. + } + if ($4 > network_max_packet_per_second) + print last4 > FILENAME".net.txpck.dat"; # Total number of packets transmitted per second. + else + { + last4 = $4; + print $4 > FILENAME".net.txpck.dat"; # Total number of packets transmitted per second. + } + if ($5 > network_max_bandwidth_in_byte) + print last5 > FILENAME".net.rxbyt.dat"; # Total number of bytes received per second. + else + { + last5 = $5; + print $5 > FILENAME".net.rxbyt.dat"; # Total number of bytes received per second. + } + if ($6 > network_max_bandwidth_in_byte) + print last6 > FILENAME".net.txbyt.dat"; # Total number of bytes transmitted per second. + else + { + last6 = $6; + print $6 > FILENAME".net.txbyt.dat"; # Total number of bytes transmitted per second. + } +# print $7 > FILENAME".net.rxcmp.dat"; # Number of compressed packets received per second (for cslip etc.). +# print $8 > FILENAME".net.txcmp.dat"; # Number of compressed packets transmitted per second. +# print $9 > FILENAME".net.rxmcst.dat"; # Number of multicast packets received per second. + } + + # Detect which is the next info to be parsed + if ($2 ~ /proc|cswch|tps|kbmemfree|totsck/) + { + n = $2; + } + + # Only get lines with numbers (real data !) + if ($2 ~ /[0-9]/) + { + if (n == "proc/s") + { # This is the proc/s info + print $2 > FILENAME".proc.dat"; +# n = ""; + } + if (n == "cswch/s") + { # This is the context switches per second info + print $2 > FILENAME".ctxsw.dat"; +# n = ""; + } + if (n == "tps") + { # This is the disk info + print $2 > FILENAME".disk.tps.dat"; # total transfers per second + print $3 > FILENAME".disk.rtps.dat"; # read requests per second + print $4 > FILENAME".disk.wtps.dat"; # write requests per second + print $5 > FILENAME".disk.brdps.dat"; # block reads per second + print $6 > FILENAME".disk.bwrps.dat"; # block writes per second +# n = ""; + } + if (n == "kbmemfree") + { # This is the mem info + print $2 > FILENAME".mem.kbmemfree.dat"; # Amount of free memory available in kilobytes. + print $3 > FILENAME".mem.kbmemused.dat"; # Amount of used memory in kilobytes. This does not take into account memory used by the kernel itself. + print $4 > FILENAME".mem.memused.dat"; # Percentage of used memory. +# It appears the kbmemshrd has been removed from the sysstat output - ntolia +# print $X > FILENAME".mem.kbmemshrd.dat"; # Amount of memory shared by the system in kilobytes. Always zero with 2.4 kernels. +# print $5 > FILENAME".mem.kbbuffers.dat"; # Amount of memory used as buffers by the kernel in kilobytes. + print $6 > FILENAME".mem.kbcached.dat"; # Amount of memory used to cache data by the kernel in kilobytes. +# print $7 > FILENAME".mem.kbswpfree.dat"; # Amount of free swap space in kilobytes. +# print $8 > FILENAME".mem.kbswpused.dat"; # Amount of used swap space in kilobytes. + print $9 > FILENAME".mem.swpused.dat"; # Percentage of used swap space. +# n = ""; + } + if (n == "totsck") + { # This is the socket info + print $2 > FILENAME".sock.totsck.dat"; # Total number of used sockets. + print $3 > FILENAME".sock.tcpsck.dat"; # Number of TCP sockets currently in use. +# print $4 > FILENAME".sock.udpsck.dat"; # Number of UDP sockets currently in use. +# print $5 > FILENAME".sock.rawsck.dat"; # Number of RAW sockets currently in use. +# print $6 > FILENAME".sock.ip-frag.dat"; # Number of IP fragments currently in use. +# n = ""; + } + } +} +END { + print " '" FILENAME "' done."; +} diff --git a/tests/examplefiles/test.bb b/tests/examplefiles/test.bb new file mode 100644 index 00000000..026ef22a --- /dev/null +++ b/tests/examplefiles/test.bb @@ -0,0 +1,95 @@ +
+;foobar!
+
+;Include "blurg/blurg.bb"
+
+Const ca = $10000000 ; Hex
+Const cb = %10101010 ; Binary
+Global ga$ = "blargh"
+Local a = 124, b$ = "abcdef"
+
+Function name_123#(zorp$, ll = False, blah#, waffles% = 100)
+ Return 235.7804 ; comment
+End Function
+Function TestString$()
+End Function
+
+Function hub(blah$, abc = Pi)
+End Function
+Function Blar%()
+ Local aa %, ab # ,ac #, ad# ,ae$,af% ; Intentional mangling
+ Local ba#, bb.TBlarf , bc%,bd#,be. TFooBar,ff = True
+End Function
+
+abc()
+
+Function abc()
+ Print "abc" ; I cannot find a way to parse these as function calls without messing something up
+ Print ; Anyhow, they're generally not used in this way
+ Goto Eww_Goto
+ .Eww_Goto
+End Function
+
+Type TBlarf
+End Type
+
+Type TFooBar
+End Type
+
+Local myinst.MyClass = New MyClass
+TestMethod(myinst)
+
+Type MyClass
+
+ Field m_foo.MyClass
+ Field m_bar.MyClass
+
+; abc
+; def
+End Type
+
+Function TestMethod(self.MyClass) ; foobar
+ self\m_foo = self
+ self\m_bar = Object.MyClass(Handle self\m_foo)
+ Yell self\m_foo\m_bar\m_foo\m_bar
+End Function
+
+Function Yell(self.MyClass)
+ Print("huzzah!")
+End Function
+
+Function Wakka$(foo$)
+ Return foo + "bar"
+End Function
+
+
+Print("blah " + "blah " + "blah.")
+
+Local i : For i = 0 To 10 Step 1
+ Print("Index: " + i)
+Next
+Local array$[5]
+array[0] = "foo": array[1] = "bar":array[2] = "11":array[3] = "22":array[4] = "33"
+For i = 0 To 4
+ Local value$ = array[i]
+ Print("Value: " + value)
+Next
+
+Local foobar = Not (1 Or (2 And (4 Shl 5 Shr 6)) Sar 7) Mod (8+2)
+Local az = 1234567890
+az = az + 1
+az = az - 2
+az = az* 3
+az = az/ 4
+az = az And 5
+az = az Or 6
+az= ~ 7
+az = az Shl 8
+az= az Shr 9
+az = az Sar 10
+az = az Mod 11
+az = ((10-5+2/4*2)>(((8^2)) < 2)) And 12 Or 2
+
+
+;~IDEal Editor Parameters:
+;~C#Blitz3D
\ No newline at end of file diff --git a/tests/examplefiles/test.bro b/tests/examplefiles/test.bro new file mode 100644 index 00000000..9a1b42de --- /dev/null +++ b/tests/examplefiles/test.bro @@ -0,0 +1,250 @@ +@load notice +@load utils/thresholds + +module SSH; + +export { + redef enum Log::ID += { SSH }; + + redef enum Notice::Type += { + Login, + Password_Guessing, + Login_By_Password_Guesser, + Login_From_Interesting_Hostname, + Bytecount_Inconsistency, + }; + + type Info: record { + ts: time &log; + uid: string &log; + id: conn_id &log; + status: string &log &optional; + direction: string &log &optional; + remote_location: geo_location &log &optional; + client: string &log &optional; + server: string &log &optional; + resp_size: count &log &default=0; + + ## Indicate if the SSH session is done being watched. + done: bool &default=F; + }; + + const password_guesses_limit = 30 &redef; + + # The size in bytes at which the SSH connection is presumed to be + # successful. + const authentication_data_size = 5500 &redef; + + # The amount of time to remember presumed non-successful logins to build + # model of a password guesser. + const guessing_timeout = 30 mins &redef; + + # The set of countries for which you'd like to throw notices upon successful login + # requires Bro compiled with libGeoIP support + const watched_countries: set[string] = {"RO"} &redef; + + # Strange/bad host names to originate successful SSH logins + const interesting_hostnames = + /^d?ns[0-9]*\./ | + /^smtp[0-9]*\./ | + /^mail[0-9]*\./ | + /^pop[0-9]*\./ | + /^imap[0-9]*\./ | + /^www[0-9]*\./ | + /^ftp[0-9]*\./ &redef; + + # This is a table with orig subnet as the key, and subnet as the value. + const ignore_guessers: table[subnet] of subnet &redef; + + # If true, we tell the event engine to not look at further data + # packets after the initial SSH handshake. Helps with performance + # (especially with large file transfers) but precludes some + # kinds of analyses (e.g., tracking connection size). + const skip_processing_after_detection = F &redef; + + # Keeps count of how many rejections a host has had + global password_rejections: table[addr] of TrackCount + &write_expire=guessing_timeout + &synchronized; + + # Keeps track of hosts identified as guessing passwords + # TODO: guessing_timeout doesn't work correctly here. If a user redefs + # the variable, it won't take effect. + global password_guessers: set[addr] &read_expire=guessing_timeout+1hr &synchronized; + + global log_ssh: event(rec: Info); +} + +# Configure DPD and the packet filter +redef capture_filters += { ["ssh"] = "tcp port 22" }; +redef dpd_config += { [ANALYZER_SSH] = [$ports = set(22/tcp)] }; + +redef record connection += { + ssh: Info &optional; +}; + +event bro_init() +{ + Log::create_stream(SSH, [$columns=Info, $ev=log_ssh]); +} + +function set_session(c: connection) + { + if ( ! c?$ssh ) + { + local info: Info; + info$ts=network_time(); + info$uid=c$uid; + info$id=c$id; + c$ssh = info; + } + } + +function check_ssh_connection(c: connection, done: bool) + { + # If done watching this connection, just return. + if ( c$ssh$done ) + return; + + # If this is still a live connection and the byte count has not + # crossed the threshold, just return and let the resheduled check happen later. + if ( !done && c$resp$size < authentication_data_size ) + return; + + # Make sure the server has sent back more than 50 bytes to filter out + # hosts that are just port scanning. Nothing is ever logged if the server + # doesn't send back at least 50 bytes. + if ( c$resp$size < 50 ) + return; + + local status = "failure"; + local direction = Site::is_local_addr(c$id$orig_h) ? "to" : "from"; + local location: geo_location; + location = (direction == "to") ? lookup_location(c$id$resp_h) : lookup_location(c$id$orig_h); + + if ( done && c$resp$size < authentication_data_size ) + { + # presumed failure + if ( c$id$orig_h !in password_rejections ) + password_rejections[c$id$orig_h] = new_track_count(); + + # Track the number of rejections + if ( !(c$id$orig_h in ignore_guessers && + c$id$resp_h in ignore_guessers[c$id$orig_h]) ) + ++password_rejections[c$id$orig_h]$n; + + if ( default_check_threshold(password_rejections[c$id$orig_h]) ) + { + add password_guessers[c$id$orig_h]; + NOTICE([$note=Password_Guessing, + $conn=c, + $msg=fmt("SSH password guessing by %s", c$id$orig_h), + $sub=fmt("%d failed logins", password_rejections[c$id$orig_h]$n), + $n=password_rejections[c$id$orig_h]$n]); + } + } + # TODO: This is to work around a quasi-bug in Bro which occasionally + # causes the byte count to be oversized. + # Watch for Gregors work that adds an actual counter of bytes transferred. + else if ( c$resp$size < 20000000 ) + { + # presumed successful login + status = "success"; + c$ssh$done = T; + + if ( c$id$orig_h in password_rejections && + password_rejections[c$id$orig_h]$n > password_guesses_limit && + c$id$orig_h !in password_guessers ) + { + add password_guessers[c$id$orig_h]; + NOTICE([$note=Login_By_Password_Guesser, + $conn=c, + $n=password_rejections[c$id$orig_h]$n, + $msg=fmt("Successful SSH login by password guesser %s", c$id$orig_h), + $sub=fmt("%d failed logins", password_rejections[c$id$orig_h]$n)]); + } + + local message = fmt("SSH login %s %s \"%s\" \"%s\" %f %f %s (triggered with %d bytes)", + direction, location$country_code, location$region, location$city, + location$latitude, location$longitude, + id_string(c$id), c$resp$size); + NOTICE([$note=Login, + $conn=c, + $msg=message, + $sub=location$country_code]); + + # Check to see if this login came from an interesting hostname + when ( local hostname = lookup_addr(c$id$orig_h) ) + { + if ( interesting_hostnames in hostname ) + { + NOTICE([$note=Login_From_Interesting_Hostname, + $conn=c, + $msg=fmt("Strange login from %s", hostname), + $sub=hostname]); + } + } + + if ( location$country_code in watched_countries ) + { + + } + + } + else if ( c$resp$size >= 200000000 ) + { + NOTICE([$note=Bytecount_Inconsistency, + $conn=c, + $msg="During byte counting in SSH analysis, an overly large value was seen.", + $sub=fmt("%d",c$resp$size)]); + } + + c$ssh$remote_location = location; + c$ssh$status = status; + c$ssh$direction = direction; + c$ssh$resp_size = c$resp$size; + + Log::write(SSH, c$ssh); + + # Set the "done" flag to prevent the watching event from rescheduling + # after detection is done. + c$ssh$done; + + # Stop watching this connection, we don't care about it anymore. + if ( skip_processing_after_detection ) + { + skip_further_processing(c$id); + set_record_packets(c$id, F); + } + } + +event connection_state_remove(c: connection) &priority=-5 + { + if ( c?$ssh ) + check_ssh_connection(c, T); + } + +event ssh_watcher(c: connection) + { + local id = c$id; + # don't go any further if this connection is gone already! + if ( !connection_exists(id) ) + return; + + check_ssh_connection(c, F); + if ( ! c$ssh$done ) + schedule +15secs { ssh_watcher(c) }; + } + +event ssh_server_version(c: connection, version: string) &priority=5 + { + set_session(c); + c$ssh$server = version; + } + +event ssh_client_version(c: connection, version: string) &priority=5 + { + set_session(c); + c$ssh$client = version; + schedule +15secs { ssh_watcher(c) }; + } diff --git a/tests/examplefiles/test.cs b/tests/examplefiles/test.cs index ffa9bfea..faab7e42 100644 --- a/tests/examplefiles/test.cs +++ b/tests/examplefiles/test.cs @@ -153,6 +153,29 @@ namespace Diva.Core { public OpenerTask (string fileName) { this.fileName = fileName; + var verbatimString = @"c:\test\"; + + var verbatimStringWithNewline = @"test \\ \n \t \r +a +b +c"; + var verbatimStringWithEscapedQuotes = @"He said +""she says \"" is not an escaped character in verbatimstrings"" +"; + + int[] numbers = { 5,6,4,2,4,6,8,9,7,0 }; + var linqExample = from n in numbers + where n > 5 + select n; + + var anotherlinqExample = from n in numbers + orderby n descending + select n; + + int[] someMoreNumbers = { 8,2,17,34,8,9,9,5,3,4,2,1,5 }; + var moreLinq = from n in numbers + join mn in moreNumbers on n equals mn + 2 + select new {n, mn}; } public override void Reset () diff --git a/tests/examplefiles/test.css b/tests/examplefiles/test.css index e59ad301..3f9ffb20 100644 --- a/tests/examplefiles/test.css +++ b/tests/examplefiles/test.css @@ -9,6 +9,11 @@ body { #nav .new { display: block; + -webkit-border-radius: 5px; + -moz-border-radius: 5px; + -ms-border-radius: 5px; + -o-border-radius: 5px; + border-radius: 5px; } ul#nav li.new { diff --git a/tests/examplefiles/test.cu b/tests/examplefiles/test.cu new file mode 100644 index 00000000..19f66802 --- /dev/null +++ b/tests/examplefiles/test.cu @@ -0,0 +1,36 @@ +#include <stdio.h> + +// __device__ function +__device__ void func() +{ + short* array0 = (short*)array; + float* array1 = (float*)&array0[127]; +} + +/* __global__ function */ +__global__ static void reduction(const float* __restrict__ input, float *output, clock_t *timer) +{ + // __shared__ float shared[2 * blockDim.x]; + extern __shared__ float shared[]; + + const int tid = threadIdx.x; + const int bid = blockIdx.x; + + if (threadIdx.x == 0) { + __threadfence(); + } + + // Perform reduction to find minimum. + for (int d = blockDim.x; d > 0; d /= 2) + { + __syncthreads(); + } +} + +int main(int argc, char **argv) +{ + dim3 dimBlock(8, 8, 1); + + timedReduction<<<dimBlock, 256, 256, 0>>>(dinput, doutput, dtimer); + cudaDeviceReset(); +} diff --git a/tests/examplefiles/test.dart b/tests/examplefiles/test.dart new file mode 100644 index 00000000..aa1fb0ed --- /dev/null +++ b/tests/examplefiles/test.dart @@ -0,0 +1,23 @@ +// Greeter example from +// <http://www.dartlang.org/docs/getting-started/interface.html> +class Greeter implements Comparable { + String prefix = 'Hello,'; + Greeter() {} + Greeter.withPrefix(this.prefix); + greet(String name) => print('$prefix $name'); + + int compareTo(Greeter other) => prefix.compareTo(other.prefix); +} + +void main() { + Greeter greeter = new Greeter(); + Greeter greeter2 = new Greeter.withPrefix('Hi,'); + + num result = greeter2.compareTo(greeter); + if (result == 0) { + greeter2.greet('you are the same.'); + } else { + greeter2.greet('you are different.'); + } +} + diff --git a/tests/examplefiles/test.dtd b/tests/examplefiles/test.dtd new file mode 100644 index 00000000..639b411a --- /dev/null +++ b/tests/examplefiles/test.dtd @@ -0,0 +1,89 @@ +<!DOCTYPE html> + +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + + +<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" +"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [ + <!-- an internal subset can be embedded here --> +]> + +<!DOCTYPE greeting SYSTEM "hello.dtd"> + +<!DOCTYPE greeting [ + <!ELEMENT greeting (#PCDATA)> + +<!-- examples from XML spec --> + +<!ELEMENT br EMPTY> +<!ELEMENT p (#PCDATA|emph)* > +<!ELEMENT %name.para; %content.para; > +<!ELEMENT container ANY> + +<!ELEMENT spec (front, body, back?)> +<!ELEMENT div1 (head, (p | list | note)*, div2*)> +<!ELEMENT dictionary-body (%div.mix; | %dict.mix;)*> + +<!ELEMENT p (#PCDATA|a|ul|b|i|em)*> +<!ELEMENT p (#PCDATA | %font; | %phrase; | %special; | %form;)* > +<!ELEMENT b (#PCDATA)> + +<!ATTLIST termdef + id ID #REQUIRED + name CDATA #IMPLIED> +<!ATTLIST list + type (bullets|ordered|glossary) "ordered"> +<!ATTLIST form + method CDATA #FIXED "POST"> + +<!ENTITY d "
"> +<!ENTITY a "
"> +<!ENTITY da "
"> + +<!ENTITY % ISOLat2 + SYSTEM "http://www.xml.com/iso/isolat2-xml.entities" > + +<!ENTITY Pub-Status "This is a pre-release of the + specification."> + + <!ENTITY open-hatch + SYSTEM "http://www.textuality.com/boilerplate/OpenHatch.xml"> +<!ENTITY open-hatch + PUBLIC "-//Textuality//TEXT Standard open-hatch boilerplate//EN" + "http://www.textuality.com/boilerplate/OpenHatch.xml"> +<!ENTITY hatch-pic + SYSTEM "../grafix/OpenHatch.gif" + NDATA gif > + +<!NOTATION gif PUBLIC "gif viewer"> + +<!ENTITY % YN '"Yes"' > +<!ENTITY WhatHeSaid "He said %YN;" > + +<!ENTITY EndAttr "27'" > + +<!ENTITY % pub "Éditions Gallimard" > +<!ENTITY rights "All rights reserved" > +<!ENTITY book "La Peste: Albert Camus, +© 1947 %pub;. &rights;" > + +<!ENTITY lt "&#60;"> +<!ENTITY gt ">"> +<!ENTITY amp "&#38;"> +<!ENTITY apos "'"> +<!ENTITY quot """> + +<!ENTITY % draft 'INCLUDE' > +<!ENTITY % final 'IGNORE' > + +<![%draft;[ +<!ELEMENT book (comments*, title, body, supplements?)> +]]> +<![%final;[ +<!ELEMENT book (title, body, supplements?)> +]]> + +]> + + diff --git a/tests/examplefiles/test.ebnf b/tests/examplefiles/test.ebnf new file mode 100644 index 00000000..a96171b0 --- /dev/null +++ b/tests/examplefiles/test.ebnf @@ -0,0 +1,31 @@ +letter = "A" | "B" | "C" | "D" | "E" | "F" | "G" + | "H" | "I" | "J" | "K" | "L" | "M" | "N" + | "O" | "P" | "Q" | "R" | "S" | "T" | "U" + | "V" | "W" | "X" | "Y" | "Z" ; +digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ; +symbol = "[" | "]" | "{" | "}" | "(" | ")" | "<" | ">" + | "'" | '"' | "=" | "|" | "." | "," | ";" ; +character = letter | digit | symbol | " " ; + +identifier = letter , { letter | digit | " " } ; +terminal = "'" , character , { character } , "'" + | '"' , character , { character } , '"' ; + +special = "?" , any , "?" ; + +comment = (* this is a comment "" *) "(*" , any-symbol , "*)" ; +any-symbol = ? any visible character ? ; (* ? ... ? *) + +lhs = identifier ; +rhs = identifier + | terminal + | comment , rhs + | rhs , comment + | "[" , rhs , "]" + | "{" , rhs , "}" + | "(" , rhs , ")" + | rhs , "|" , rhs + | rhs , "," , rhs ; + +rule = lhs , "=" , rhs , ";" | comment ; +grammar = { rule } ; diff --git a/tests/examplefiles/test.ec b/tests/examplefiles/test.ec new file mode 100644 index 00000000..37868b52 --- /dev/null +++ b/tests/examplefiles/test.ec @@ -0,0 +1,605 @@ +namespace gui; + +import "Window" + +public struct AnchorValue +{ + AnchorValueType type; + + union + { + int distance; + float percent; + }; + property int + { + set { distance = value; type = offset; } + get { return distance; } + } + property double + { + set { percent = (float) value; type = relative; } + get { return (double) percent; } + } + + char * OnGetString(char * stringOutput, void * fieldData, bool * needClass) + { + if(type == offset) + { + sprintf(stringOutput, "%d", distance); + } + else if(type == relative) + { + int c; + int last = 0; + sprintf(stringOutput, "%f", percent); + c = strlen(stringOutput)-1; + for( ; c >= 0; c--) + { + if(stringOutput[c] != '0') + last = Max(last, c); + if(stringOutput[c] == '.') + { + if(last == c) + { + stringOutput[c+1] = '0'; + stringOutput[c+2] = 0; + } + else + stringOutput[last+1] = 0; + break; + } + } + } + if(needClass) *needClass = false; + return stringOutput; + } + + bool OnGetDataFromString(char * stringOutput) + { + char * end; + if(strchr(stringOutput, '.')) + { + float percent = (float)strtod(stringOutput, &end); + + if(end != stringOutput) + { + this.percent = percent; + type = relative; + return true; + } + } + else if(stringOutput[0]) + { + int distance = strtol(stringOutput, &end, 0); + if(end != stringOutput) + { + this.distance = distance; + type = offset; + return true; + } + } + else + { + distance = 0; + type = 0; + } + return false; + } +}; + +public struct MiddleAnchorValue +{ + AnchorValueType type; + + union + { + int distance; + float percent; + }; + property int + { + set { distance = value; type = none; } + get { return distance; } + } + property double + { + set { percent = (float) value; type = middleRelative; } + get { return (double) percent; } + } + + char * OnGetString(char * stringOutput, void * fieldData, bool * needClass) + { + if(type == middleRelative) + { + int c; + int last = 0; + sprintf(stringOutput, "%f", percent); + c = strlen(stringOutput)-1; + for( ; c >= 0; c--) + { + if(stringOutput[c] != '0') + last = Max(last, c); + if(stringOutput[c] == '.') + { + if(last == c) + { + stringOutput[c+1] = '0'; + stringOutput[c+2] = 0; + } + else + stringOutput[last+1] = 0; + break; + } + } + } + else if(type == none && distance) + { + sprintf(stringOutput, "%d", distance); + } + if(needClass) *needClass = false; + return stringOutput; + } + + bool OnGetDataFromString(char * stringOutput) + { + if(strchr(stringOutput, '.')) + { + percent = (float)strtod(stringOutput, null); + type = middleRelative; + } + else + { + distance = strtol(stringOutput, null, 0); + type = none; + } + return true; + } +}; + +public enum AnchorValueType { none, offset, relative, middleRelative, cascade, vTiled, hTiled }; + +public struct Anchor +{ + union { AnchorValue left; MiddleAnchorValue horz; }; + union { AnchorValue top; MiddleAnchorValue vert; }; + AnchorValue right, bottom; + + char * OnGetString(char * stringOutput, void * fieldData, bool * needClass) + { + char tempString[256]; + char * anchorValue; + bool subNeedClass; + + tempString[0] = '\0'; + anchorValue = left.OnGetString(tempString, null, &subNeedClass); + if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "left = "); strcat(stringOutput, anchorValue); } + + //if(((!left.type && !right.type) && horz.distance) || horz.type == middleRelative) + if(!right.type && ((!left.type && horz.distance) || horz.type == middleRelative)) + { + tempString[0] = '\0'; + anchorValue = horz.OnGetString(tempString, null, &subNeedClass); + if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "horz = "); strcat(stringOutput, anchorValue); } + } + + tempString[0] = '\0'; + anchorValue = top.OnGetString(tempString, null, &subNeedClass); + if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "top = "); strcat(stringOutput, anchorValue); } + + tempString[0] = '\0'; + anchorValue = right.OnGetString(tempString, null, &subNeedClass); + if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "right = "); strcat(stringOutput, anchorValue); } + + // if(((!top.type && !bottom.type) && vert.distance) || vert.type == middleRelative) + if(!bottom.type && ((!top.type && vert.distance) || vert.type == middleRelative)) + { + tempString[0] = '\0'; + anchorValue = vert.OnGetString(tempString, null, &subNeedClass); + if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "vert = "); strcat(stringOutput, anchorValue); } + } + + tempString[0] = '\0'; + anchorValue = bottom.OnGetString(tempString, null, &subNeedClass); + if(anchorValue[0]) { if(stringOutput[0]) strcat(stringOutput, ", "); strcat(stringOutput, "bottom = "); strcat(stringOutput, anchorValue); } + + return stringOutput; + } + + bool OnGetDataFromString(char * string) + { + this = Anchor {}; + return class::OnGetDataFromString(string); + } + + bool OnSaveEdit(DropBox dropBox, void * object) + { + return dropBox.Save(); + } + + Window OnEdit(Window listBox, Window master, int x, int y, int w, int h, Window control) + { + char * string = ""; + AnchorDropBox comboBox + { + editText = true; + parent = listBox; + master = master; + position = Point { x, y }; + //clientSize = Size { h = h }; + //size.w = w; + size = { w, h }; + anchorValue = this; + control = control; + borderStyle = 0; + }; + + comboBox.Create(); + + { + char tempString[MAX_F_STRING] = ""; + bool needClass = false; + char * result = OnGetString(tempString, null, &needClass); + if(result) string = result; + } + comboBox.contents = string; + return comboBox; + } +}; + +private class AnchorButton : Button +{ + toggle = true, bevel = false; + + void OnRedraw(Surface surface) + { + int cw = clientSize.w; + int ch = clientSize.h; + + surface.SetForeground(black); + if(checked) + { + surface.SetBackground(Color { 85,85,85 }); + surface.Area(0,0, cw-1, ch-1); + } + else + surface.LineStipple(0xAAAA); + + surface.Rectangle(0,0,cw-1,ch-1); + + if(active) + { + surface.LineStipple(0xAAAA); + surface.Rectangle(2,2,cw-3,ch-3); + } + } + + bool AnchorEditor::NotifyClicked(Button button, int x, int y, Modifiers mods) + { + AnchorDropBox anchorDropBox = (AnchorDropBox)master; + Anchor anchor = anchorDropBox.anchorValue; + Window control = anchorDropBox.control; + DataBox dropMaster = (DataBox)anchorDropBox.master; + int id = button.id; + + switch(id) + { + case 0: anchor.left.type = button.checked ? offset : none; break; + case 1: anchor.top.type = button.checked ? offset : none; break; + case 2: anchor.right.type = button.checked ? offset : none; break; + case 3: anchor.bottom.type = button.checked ? offset : none; break; + } + + if(anchor.horz.type == middleRelative && (id == 0 || id == 2)) + { + anchorDropBox.relButtons[0].checked = false; + anchorDropBox.relButtons[2].checked = false; + } + if(anchor.vert.type == middleRelative && (id == 1 || id == 3)) + { + anchorDropBox.relButtons[1].checked = false; + anchorDropBox.relButtons[3].checked = false; + } + anchorDropBox.relButtons[id].checked = false; + + //anchor.horz.type = none; + //anchor.vert.type = none; + + { + int vpw, vph; + int x,y,w,h; + Window parent = control.parent; + + // Fix Anchor + x = control.position.x; + y = control.position.y; + w = control.size.w; + h = control.size.h; + + vpw = parent.clientSize.w; + vph = parent.clientSize.h; + if(control.nonClient) + { + vpw = parent.size.w; + vph = parent.size.h; + } + else if(((BorderBits)control.borderStyle).fixed) + { + if(!control.dontScrollHorz && parent.scrollArea.w) vpw = parent.scrollArea.w; + if(!control.dontScrollVert && parent.scrollArea.h) vph = parent.scrollArea.h; + } + + if(anchor.left.type == offset) anchor.left.distance = x; + else if(anchor.left.type == relative) anchor.left.percent = (float)x / vpw; + if(anchor.top.type == offset) anchor.top.distance = y; + else if(anchor.top.type == relative) anchor.top.percent = (float)y / vph; + if(anchor.right.type == offset) anchor.right.distance = vpw - (x + w); + //else if(anchor.right.type == relative) anchor.right.percent = (float) (x + w) / vpw; + else if(anchor.right.type == relative) anchor.right.percent = (float) (vpw - (x + w)) / vpw; + if(anchor.bottom.type == offset) anchor.bottom.distance = vph - (y + h); + //else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (y + h) / vph; + else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (vph - (y + h)) / vph; + + if(!anchor.left.type && !anchor.right.type) + { + anchor.horz.distance = (x + w / 2) - (vpw / 2); + //anchor.horz.type = anchor.horz.distance ? offset : 0; + } + else if(anchor.horz.type == middleRelative) anchor.horz.percent = (float) ((x + w / 2) - (vpw / 2)) / vpw; + if(!anchor.top.type && !anchor.bottom.type) + { + anchor.vert.distance = (y + h / 2) - (vph / 2); + //anchor.vert.type = anchor.vert.distance ? offset : 0; + } + else if(anchor.vert.type == middleRelative) anchor.vert.percent = (float)((y + h / 2) - (vph / 2)) / vph; + } + + { + char tempString[1024] = ""; + bool needClass = false; + char * string = anchor.OnGetString(tempString, null, &needClass); + anchorDropBox.contents = string; + } + + dropMaster.SetData(&anchor, false); + anchorDropBox.anchorValue = anchor; + return true; + } +} + +private class AnchorRelButton : Button +{ + toggle = true; + bevel = false; + text = "%"; + //bevelOver = true; + + void OnRedraw(Surface surface) + { + int cw = clientSize.w; + int ch = clientSize.h; + + if(checked) + { + surface.SetForeground(black); + } + else + { + surface.SetForeground(Color{170,170,170}); + } + surface.WriteText(5,2, "%", 1); + + if(active) + { + surface.LineStipple(0xAAAA); + surface.Rectangle(3,3,cw-4,ch-4); + } + } + + bool AnchorEditor::NotifyClicked(Button button, int x, int y, Modifiers mods) + { + AnchorDropBox anchorDropBox = (AnchorDropBox)master; + Anchor anchor = anchorDropBox.anchorValue; + Window control = anchorDropBox.control; + DataBox dropMaster = (DataBox)anchorDropBox.master; + int id = button.id; + + if((id == 0 || id == 2) && ((!anchor.left.type && !anchor.right.type) || anchor.left.type == middleRelative)) + { + if(button.checked) anchor.horz.type = middleRelative; else anchor.horz.type = none; + anchorDropBox.relButtons[(id + 2)%4].checked = button.checked; + } + else if((id == 1 || id == 3) && ((!anchor.top.type && !anchor.bottom.type) || anchor.top.type == middleRelative)) + { + if(button.checked) anchor.vert.type = middleRelative; else anchor.vert.type = none; + anchorDropBox.relButtons[(id + 2)%4].checked = button.checked; + } + else + { + switch(id) + { + case 0: anchor.left.type = button.checked ? relative : (anchor.left.type ? offset : none); break; + case 1: anchor.top.type = button.checked ? relative : (anchor.top.type ? offset : none); break; + case 2: anchor.right.type = button.checked ? relative : (anchor.right.type ? offset : none); break; + case 3: anchor.bottom.type = button.checked ? relative : (anchor.bottom.type ? offset : none); break; + } + anchorDropBox.buttons[id].checked = true; + if(anchor.horz.type == middleRelative) anchor.horz.type = none; + if(anchor.vert.type == middleRelative) anchor.vert.type = none; + } + + { + int vpw, vph; + int x,y,w,h; + Window parent = control.parent; + + // Fix Anchor + x = control.position.x; + y = control.position.y; + w = control.size.w; + h = control.size.h; + + vpw = parent.clientSize.w; + vph = parent.clientSize.h; + if(control.nonClient) + { + vpw = parent.size.w; + vph = parent.size.h; + } + else if(((BorderBits)control.borderStyle).fixed) + { + if(!control.dontScrollHorz && parent.scrollArea.w) vpw = parent.scrollArea.w; + if(!control.dontScrollVert && parent.scrollArea.h) vph = parent.scrollArea.h; + } + + if(anchor.left.type == offset) anchor.left.distance = x; + else if(anchor.left.type == relative) anchor.left.percent = (float)x / vpw; + if(anchor.top.type == offset) anchor.top.distance = y; + else if(anchor.top.type == relative) anchor.top.percent = (float)y / vph; + if(anchor.right.type == offset) anchor.right.distance = vpw - (x + w); + //else if(anchor.right.type == relative) anchor.right.percent = (float) (x + w) / vpw; + else if(anchor.right.type == relative) anchor.right.percent = (float) (vpw - (x + w)) / vpw; + if(anchor.bottom.type == offset) anchor.bottom.distance = vph - (y + h); + //else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (y + h) / vph; + else if(anchor.bottom.type == relative) anchor.bottom.percent = (float) (vph - (y + h)) / vph; + + if(!anchor.left.type && !anchor.right.type) + { + anchor.horz.distance = (x + w / 2) - (vpw / 2); + //anchor.horz.type = anchor.horz.distance ? offset : none; + } + else if(anchor.horz.type == middleRelative) anchor.horz.percent = (float) ((x + w / 2) - (vpw / 2)) / vpw; + if(!anchor.top.type && !anchor.bottom.type) + { + anchor.vert.distance = (y + h / 2) - (vph / 2); + //anchor.vert.type = anchor.vert.distance ? offset : none; + } + else if(anchor.vert.type == middleRelative) anchor.vert.percent = (float)((y + h / 2) - (vph / 2)) / vph; + } + + { + char tempString[1024] = ""; + bool needClass = false; + char * string = anchor.OnGetString(tempString, null, &needClass); + anchorDropBox.contents = string; + } + + dropMaster.SetData(&anchor, false); + anchorDropBox.anchorValue = anchor; + return true; + } +} + +private class AnchorEditor : Window +{ + interim = true; + borderStyle = deepContour; + size.h = 92; + + bool OnKeyDown(Key key, unichar ch) + { + if(key == escape) + return master.OnKeyDown(key, ch); + return true; + } +} + +private class AnchorDropBox : DropBox +{ + Anchor anchorValue; + Window control; + Button relButtons[4], buttons[4]; + + AnchorEditor anchorEditor + { + master = this; + autoCreate = false; + }; + + Window OnDropDown() + { + int c; + Button + { + anchorEditor, + anchor = Anchor { left = 28, top = 28, right = 28, bottom = 28 }, + inactive = true, disabled = true + }; + for(c = 0; c<4; c++) + { + Button button = buttons[c] = AnchorButton + { + anchorEditor, id = c, + size = Size { (c%2)?10:28, (c%2)?28:10 } + }; + Button relButton = relButtons[c] = AnchorRelButton + { + anchorEditor, id = c; + }; + + switch(c) + { + case 0: + if(anchorValue.left.type && anchorValue.left.type != middleRelative) button.checked = true; + if(anchorValue.left.type == relative || anchorValue.horz.type == middleRelative) relButton.checked = true; + + button.anchor = Anchor { left = 0 }; + relButton.anchor = Anchor { left = 5, vert = 16 }; + break; + case 1: + if(anchorValue.top.type && anchorValue.top.type != middleRelative) button.checked = true; + if(anchorValue.top.type == relative || anchorValue.vert.type == middleRelative) relButton.checked = true; + + button.anchor = Anchor { top = 0 }; + relButton.anchor = Anchor { top = 5, horz = 16 }; + break; + case 2: + if(anchorValue.right.type && anchorValue.right.type != middleRelative) button.checked = true; + if(anchorValue.right.type == relative || anchorValue.horz.type == middleRelative) relButton.checked = true; + + button.anchor = Anchor { right = 0 }; + relButton.anchor = Anchor { right = 5, vert = 16 }; + break; + case 3: + if(anchorValue.bottom.type && anchorValue.bottom.type != middleRelative) button.checked = true; + if(anchorValue.bottom.type == relative || anchorValue.vert.type == middleRelative) relButton.checked = true; + + button.anchor = Anchor { bottom = 0 }; + relButton.anchor = Anchor { bottom = 5, horz = 16 }; + break; + } + } + anchorEditor.Create(); + return anchorEditor; + } + + void OnCloseDropDown(Window anchorEditor) + { + // TOFIX: Patch for update bug + master.Update(null); + anchorEditor.Destroy(0); + } + + bool DataBox::NotifyTextEntry(AnchorDropBox dropBox, char * string, bool save) + { + Anchor anchor = dropBox.anchorValue; + Window control = dropBox.control; + + if(save) + { + if(anchor.OnGetDataFromString(string)) + { + SetData(&anchor, false); + dropBox.anchorValue = anchor; + } + } + else + { + char tempString[1024] = ""; + bool needClass = false; + char * string = anchor.OnGetString(tempString, null, &needClass); + dropBox.contents = string; + } + return true; + } +} diff --git a/tests/examplefiles/test.ecl b/tests/examplefiles/test.ecl new file mode 100644 index 00000000..b686492a --- /dev/null +++ b/tests/examplefiles/test.ecl @@ -0,0 +1,58 @@ +/*############################################################################## + + Copyright (C) 2011 HPCC Systems. + + All rights reserved. This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <http://www.gnu.org/licenses/>. +############################################################################## */ + +#option ('slidingJoins', true); + +namesRecord := + RECORD +string20 surname; +string10 forename; +integer2 age; +integer2 dadAge; +integer2 mumAge; + END; + +namesRecord2 := + record +string10 extra; +namesRecord; + end; + +namesTable := dataset('x',namesRecord,FLAT); +namesTable2 := dataset('y',namesRecord2,FLAT); + +integer2 aveAgeL(namesRecord l) := (l.dadAge+l.mumAge)/2; +integer2 aveAgeR(namesRecord2 r) := (r.dadAge+r.mumAge)/2; + +// Standard join on a function of left and right +output(join(namesTable, namesTable2, aveAgeL(left) = aveAgeR(right))); + +//Several simple examples of sliding join syntax +output(join(namesTable, namesTable2, left.age >= right.age - 10 and left.age <= right.age +10)); +output(join(namesTable, namesTable2, left.age between right.age - 10 and right.age +10)); +output(join(namesTable, namesTable2, left.age between right.age + 10 and right.age +30)); +output(join(namesTable, namesTable2, left.age between (right.age + 20) - 10 and (right.age +20) + 10)); +output(join(namesTable, namesTable2, aveAgeL(left) between aveAgeR(right)+10 and aveAgeR(right)+40)); + +//Same, but on strings. Also includes age to ensure sort is done by non-sliding before sliding. +output(join(namesTable, namesTable2, left.surname between right.surname[1..10]+'AAAAAAAAAA' and right.surname[1..10]+'ZZZZZZZZZZ' and left.age=right.age)); +output(join(namesTable, namesTable2, left.surname between right.surname[1..10]+'AAAAAAAAAA' and right.surname[1..10]+'ZZZZZZZZZZ' and left.age=right.age,all)); + +//This should not generate a self join +output(join(namesTable, namesTable, left.age between right.age - 10 and right.age +10)); + diff --git a/tests/examplefiles/test.eh b/tests/examplefiles/test.eh new file mode 100644 index 00000000..1ed173fb --- /dev/null +++ b/tests/examplefiles/test.eh @@ -0,0 +1,315 @@ +/* A Bison parser, made by GNU Bison 2.0. */ + +/* Skeleton parser for Yacc-like parsing with Bison, + Copyright (C) 1984, 1989, 1990, 2000, 2001, 2002, 2003, 2004 Free Software Foundation, Inc. + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2, or (at your option) + any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program; if not, write to the Free Software + Foundation, Inc., 59 Temple Place - Suite 330, + Boston, MA 02111-1307, USA. */ + +/* As a special exception, when this file is copied by Bison into a + Bison output file, you may use that output file without restriction. + This special exception was added by the Free Software Foundation + in version 1.24 of Bison. */ + +/* Tokens. */ +#ifndef YYTOKENTYPE +# define YYTOKENTYPE + /* Put the tokens into the symbol table, so that GDB and other debuggers + know about them. */ + enum yytokentype { + IDENTIFIER = 258, + CONSTANT = 259, + STRING_LITERAL = 260, + SIZEOF = 261, + PTR_OP = 262, + INC_OP = 263, + DEC_OP = 264, + LEFT_OP = 265, + RIGHT_OP = 266, + LE_OP = 267, + GE_OP = 268, + EQ_OP = 269, + NE_OP = 270, + AND_OP = 271, + OR_OP = 272, + MUL_ASSIGN = 273, + DIV_ASSIGN = 274, + MOD_ASSIGN = 275, + ADD_ASSIGN = 276, + SUB_ASSIGN = 277, + LEFT_ASSIGN = 278, + RIGHT_ASSIGN = 279, + AND_ASSIGN = 280, + XOR_ASSIGN = 281, + OR_ASSIGN = 282, + TYPE_NAME = 283, + TYPEDEF = 284, + EXTERN = 285, + STATIC = 286, + AUTO = 287, + REGISTER = 288, + CHAR = 289, + SHORT = 290, + INT = 291, + UINT = 292, + INT64 = 293, + LONG = 294, + SIGNED = 295, + UNSIGNED = 296, + FLOAT = 297, + DOUBLE = 298, + CONST = 299, + VOLATILE = 300, + VOID = 301, + VALIST = 302, + STRUCT = 303, + UNION = 304, + ENUM = 305, + ELLIPSIS = 306, + CASE = 307, + DEFAULT = 308, + IF = 309, + SWITCH = 310, + WHILE = 311, + DO = 312, + FOR = 313, + GOTO = 314, + CONTINUE = 315, + BREAK = 316, + RETURN = 317, + IFX = 318, + ELSE = 319, + CLASS = 320, + THISCLASS = 321, + CLASS_NAME = 322, + PROPERTY = 323, + SETPROP = 324, + GETPROP = 325, + NEWOP = 326, + RENEW = 327, + DELETE = 328, + EXT_DECL = 329, + EXT_STORAGE = 330, + IMPORT = 331, + DEFINE = 332, + VIRTUAL = 333, + EXT_ATTRIB = 334, + PUBLIC = 335, + PRIVATE = 336, + TYPED_OBJECT = 337, + ANY_OBJECT = 338, + _INCREF = 339, + EXTENSION = 340, + ASM = 341, + TYPEOF = 342, + WATCH = 343, + STOPWATCHING = 344, + FIREWATCHERS = 345, + WATCHABLE = 346, + CLASS_DESIGNER = 347, + CLASS_NO_EXPANSION = 348, + CLASS_FIXED = 349, + ISPROPSET = 350, + CLASS_DEFAULT_PROPERTY = 351, + PROPERTY_CATEGORY = 352, + CLASS_DATA = 353, + CLASS_PROPERTY = 354, + SUBCLASS = 355, + NAMESPACE = 356, + NEW0OP = 357, + RENEW0 = 358, + VAARG = 359, + DBTABLE = 360, + DBFIELD = 361, + DBINDEX = 362, + DATABASE_OPEN = 363 + }; +#endif +#define IDENTIFIER 258 +#define CONSTANT 259 +#define STRING_LITERAL 260 +#define SIZEOF 261 +#define PTR_OP 262 +#define INC_OP 263 +#define DEC_OP 264 +#define LEFT_OP 265 +#define RIGHT_OP 266 +#define LE_OP 267 +#define GE_OP 268 +#define EQ_OP 269 +#define NE_OP 270 +#define AND_OP 271 +#define OR_OP 272 +#define MUL_ASSIGN 273 +#define DIV_ASSIGN 274 +#define MOD_ASSIGN 275 +#define ADD_ASSIGN 276 +#define SUB_ASSIGN 277 +#define LEFT_ASSIGN 278 +#define RIGHT_ASSIGN 279 +#define AND_ASSIGN 280 +#define XOR_ASSIGN 281 +#define OR_ASSIGN 282 +#define TYPE_NAME 283 +#define TYPEDEF 284 +#define EXTERN 285 +#define STATIC 286 +#define AUTO 287 +#define REGISTER 288 +#define CHAR 289 +#define SHORT 290 +#define INT 291 +#define UINT 292 +#define INT64 293 +#define LONG 294 +#define SIGNED 295 +#define UNSIGNED 296 +#define FLOAT 297 +#define DOUBLE 298 +#define CONST 299 +#define VOLATILE 300 +#define VOID 301 +#define VALIST 302 +#define STRUCT 303 +#define UNION 304 +#define ENUM 305 +#define ELLIPSIS 306 +#define CASE 307 +#define DEFAULT 308 +#define IF 309 +#define SWITCH 310 +#define WHILE 311 +#define DO 312 +#define FOR 313 +#define GOTO 314 +#define CONTINUE 315 +#define BREAK 316 +#define RETURN 317 +#define IFX 318 +#define ELSE 319 +#define CLASS 320 +#define THISCLASS 321 +#define CLASS_NAME 322 +#define PROPERTY 323 +#define SETPROP 324 +#define GETPROP 325 +#define NEWOP 326 +#define RENEW 327 +#define DELETE 328 +#define EXT_DECL 329 +#define EXT_STORAGE 330 +#define IMPORT 331 +#define DEFINE 332 +#define VIRTUAL 333 +#define EXT_ATTRIB 334 +#define PUBLIC 335 +#define PRIVATE 336 +#define TYPED_OBJECT 337 +#define ANY_OBJECT 338 +#define _INCREF 339 +#define EXTENSION 340 +#define ASM 341 +#define TYPEOF 342 +#define WATCH 343 +#define STOPWATCHING 344 +#define FIREWATCHERS 345 +#define WATCHABLE 346 +#define CLASS_DESIGNER 347 +#define CLASS_NO_EXPANSION 348 +#define CLASS_FIXED 349 +#define ISPROPSET 350 +#define CLASS_DEFAULT_PROPERTY 351 +#define PROPERTY_CATEGORY 352 +#define CLASS_DATA 353 +#define CLASS_PROPERTY 354 +#define SUBCLASS 355 +#define NAMESPACE 356 +#define NEW0OP 357 +#define RENEW0 358 +#define VAARG 359 +#define DBTABLE 360 +#define DBFIELD 361 +#define DBINDEX 362 +#define DATABASE_OPEN 363 + + + + +#if ! defined (YYSTYPE) && ! defined (YYSTYPE_IS_DECLARED) +#line 42 "grammar.y" +typedef union YYSTYPE { + SpecifierType specifierType; + int i; + AccessMode declMode; + Identifier id; + Expression exp; + Specifier specifier; + OldList * list; + Enumerator enumerator; + Declarator declarator; + Pointer pointer; + Initializer initializer; + InitDeclarator initDeclarator; + TypeName typeName; + Declaration declaration; + Statement stmt; + FunctionDefinition function; + External external; + Context context; + AsmField asmField; + + Instantiation instance; + MembersInit membersInit; + MemberInit memberInit; + ClassFunction classFunction; + ClassDefinition _class; + ClassDef classDef; + PropertyDef prop; + char * string; + Symbol symbol; + PropertyWatch propertyWatch; + TemplateParameter templateParameter; + TemplateArgument templateArgument; + TemplateDatatype templateDatatype; + + DBTableEntry dbtableEntry; + DBIndexItem dbindexItem; + DBTableDef dbtableDef; +} YYSTYPE; +/* Line 1318 of yacc.c. */ +#line 293 "grammar.eh" +# define yystype YYSTYPE /* obsolescent; will be withdrawn */ +# define YYSTYPE_IS_DECLARED 1 +# define YYSTYPE_IS_TRIVIAL 1 +#endif + +extern YYSTYPE yylval; + +#if ! defined (YYLTYPE) && ! defined (YYLTYPE_IS_DECLARED) +typedef struct YYLTYPE +{ + int first_line; + int first_column; + int last_line; + int last_column; +} YYLTYPE; +# define yyltype YYLTYPE /* obsolescent; will be withdrawn */ +# define YYLTYPE_IS_DECLARED 1 +# define YYLTYPE_IS_TRIVIAL 1 +#endif + +extern YYLTYPE yylloc; + + diff --git a/tests/examplefiles/test.fan b/tests/examplefiles/test.fan new file mode 100755 index 00000000..00e80b60 --- /dev/null +++ b/tests/examplefiles/test.fan @@ -0,0 +1,818 @@ +// +// Copyright (c) 2008, Brian Frank and Andy Frank +// Licensed under the Academic Free License version 3.0 +// +// History: +// 17 Nov 08 Brian Frank Creation +// + +using compiler + +** +** JavaBridge is the compiler plugin for bringing Java +** classes into the Fantom type system. +** +class JavaBridge : CBridge +{ + +////////////////////////////////////////////////////////////////////////// +// Constructor +////////////////////////////////////////////////////////////////////////// + + ** + ** Construct a JavaBridge for current environment + ** + new make(Compiler c, ClassPath cp := ClassPath.makeForCurrent) + : super(c) + { + this.cp = cp + } + +////////////////////////////////////////////////////////////////////////// +// Namespace +////////////////////////////////////////////////////////////////////////// + + ** + ** Map a FFI "podName" to a Java package. + ** + override CPod resolvePod(Str name, Loc? loc) + { + // the empty package is used to represent primitives + if (name == "") return primitives + + // look for package name in classpatch + classes := cp.classes[name] + if (classes == null) + throw CompilerErr("Java package '$name' not found", loc) + + // map package to JavaPod + return JavaPod(this, name, classes) + } + + ** + ** Map class meta-data and Java members to Fantom slots + ** for the specified JavaType. + ** + virtual Void loadType(JavaType type, Str:CSlot slots) + { + JavaReflect.loadType(type, slots) + } + +////////////////////////////////////////////////////////////////////////// +// Call Resolution +////////////////////////////////////////////////////////////////////////// + + ** + ** Resolve a construction call to a Java constructor. + ** + override Expr resolveConstruction(CallExpr call) + { + // if the last argument is an it-block, then we know + // right away that we will not be passing it thru to Java, + // so strip it off to be appended as call to Obj.with + itBlock := call.args.last as ClosureExpr + if (itBlock != null && itBlock.isItBlock) + call.args.removeAt(-1) + else + itBlock = null + + // if this is an interop array like IntArray/int[] use make + // factory otherwise look for Java constructor called <init> + JavaType base := call.target.ctype + if (base.isInteropArray) + call.method = base.method("make") + else + call.method = base.method("<init>") + + // call resolution to deal with overloading + call = resolveCall(call) + + // we need to create an implicit target for the Java runtime + // to perform the new opcode to ensure it is on the stack + // before the args (we don't do this for interop Array classes) + if (!base.isInteropArray) + { + loc := call.loc + call.target = CallExpr.makeWithMethod(loc, null, base.newMethod) { synthetic=true } + } + + // if we stripped an it-block argument, + // add it as trailing call to Obj.with + if (itBlock != null) return itBlock.toWith(call) + return call + } + + ** + ** Resolve a construction chain call where a Fantom constructor + ** calls the super-class constructor. Type check the arguments + ** and insert any conversions needed. + ** + override Expr resolveConstructorChain(CallExpr call) + { + // we don't allow chaining to a this ctor for Java FFI + if (call.target.id !== ExprId.superExpr) + throw err("Must use super constructor call in Java FFI", call.loc) + + // route to a superclass constructor + JavaType base := call.target.ctype.deref + call.method = base.method("<init>") + + // call resolution to deal with overloading + return resolveCall(call) + } + + ** + ** Given a dot operator slot access on the given foreign + ** base type, determine the appopriate slot to use based on + ** whether parens were used + ** base.name => noParens = true + ** base.name() => noParens = false + ** + ** In Java a given name could be bound to both a field and + ** a method. In this case we only resolve the field if + ** no parens are used. We also handle the special case of + ** Java annotations here because their element methods are + ** also mapped as Fantom fields (instance based mixin field). + ** + override CSlot? resolveSlotAccess(CType base, Str name, Bool noParens) + { + // first try to resolve as a field + field := base.field(name) + if (field != null) + { + // if no () we used and this isn't an annotation field + if (noParens && (field.isStatic || !base.isMixin)) + return field + + // if we did find a field, then make sure we use that + // field's parent type to resolve a method (becuase the + // base type might be a sub-class of a Java type in which + // case it is unware of field/method overloads) + return field.parent.method(name) + } + + // lookup method + return base.method(name) + } + + ** + ** Resolve a method call: try to find the best match + ** and apply any coercions needed. + ** + override CallExpr resolveCall(CallExpr call) + { + // try to match against all the overloaded methods + matches := CallMatch[,] + CMethod? m := call.method + while (m != null) + { + match := matchCall(call, m) + if (match != null) matches.add(match) + m = m is JavaMethod ? ((JavaMethod)m).next : null + } + + // if we have exactly one match use then use that one + if (matches.size == 1) return matches[0].apply(call) + + // if we have multiple matches; resolve to + // most specific match according to JLS rules + // TODO: this does not correct resolve when using Fantom implicit casting + if (matches.size > 1) + { + best := resolveMostSpecific(matches) + if (best != null) return best.apply(call) + } + + // zero or multiple ambiguous matches is a compiler error + s := StrBuf() + s.add(matches.isEmpty ? "Invalid args " : "Ambiguous call ") + s.add(call.name).add("(") + s.add(call.args.join(", ") |Expr arg->Str| { return arg.toTypeStr }) + s.add(")") + throw err(s.toStr, call.loc) + } + + ** + ** Check if the call matches the specified overload method. + ** If so return method and coerced args otherwise return null. + ** + internal CallMatch? matchCall(CallExpr call, CMethod m) + { + // first check if have matching numbers of args and params + args := call.args + if (m.params.size < args.size) return null + + // check if each argument is ok or can be coerced + isErr := false + newArgs := args.dup + m.params.each |CParam p, Int i| + { + if (i >= args.size) + { + // param has a default value, then that is ok + if (!p.hasDefault) isErr = true + } + else + { + // ensure arg fits parameter type (or auto-cast) + newArgs[i] = coerce(args[i], p.paramType) |->| { isErr = true } + } + } + if (isErr) return null + return CallMatch { it.method = m; it.args = newArgs } + } + + ** + ** Given a list of overloaed methods find the most specific method + ** according to Java Language Specification 15.11.2.2. The "informal + ** intuition" rule is that a method is more specific than another + ** if the first could be could be passed onto the second one. + ** + internal static CallMatch? resolveMostSpecific(CallMatch[] matches) + { + CallMatch? best := matches[0] + for (i:=1; i<matches.size; ++i) + { + x := matches[i] + if (isMoreSpecific(best, x)) { continue } + if (isMoreSpecific(x, best)) { best = x; continue } + return null + } + return best + } + + ** + ** Is 'a' more specific than 'b' such that 'a' could be used + ** passed to 'b' without a compile time error. + ** + internal static Bool isMoreSpecific(CallMatch a, CallMatch b) + { + return a.method.params.all |CParam ap, Int i->Bool| + { + bp := b.method.params[i] + return ap.paramType.fits(bp.paramType) + } + } + +////////////////////////////////////////////////////////////////////////// +// Overrides +////////////////////////////////////////////////////////////////////////// + + ** + ** Called during Inherit step when a Fantom slot overrides a FFI slot. + ** Log and throw compiler error if there is a problem. + ** + override Void checkOverride(TypeDef t, CSlot base, SlotDef def) + { + // we don't allow Fantom to override Java methods with multiple + // overloaded versions since the Fantom type system can't actually + // override all the overloaded versions + jslot := base as JavaSlot + if (jslot?.next != null) + throw err("Cannot override Java overloaded method: '$jslot.name'", def.loc) + + // route to method override checking + if (base is JavaMethod && def is MethodDef) + checkMethodOverride(t, base, def) + } + + ** + ** Called on method/method overrides in the checkOverride callback. + ** + private Void checkMethodOverride(TypeDef t, JavaMethod base, MethodDef def) + { + // bail early if we know things aren't going to work out + if (base.params.size != def.params.size) return + + // if the return type is primitive or Java array and the + // Fantom declaration matches how it is inferred into the Fan + // type system, then just change the return type - the compiler + // will impliclty do all the return coercions + if (isOverrideInferredType(base.returnType, def.returnType)) + { + def.ret = def.inheritedRet = base.returnType + } + + // if any of the parameters is a primitive or Java array + // and the Fantom declaration matches how it is inferred into + // the Fantom type type, then change the parameter type to + // the Java override type and make the Fantom type a local + // variable: + // Java: void foo(int a) { ... } + // Fantom: Void foo(Int a) { ... } + // Result: Void foo(int a_$J) { Int a := a_$J; ... } + // + base.params.eachr |CParam bp, Int i| + { + dp := def.paramDefs[i] + if (!isOverrideInferredType(bp.paramType, dp.paramType)) return + + // add local variable: Int bar := bar_$J + local := LocalDefStmt(def.loc) + local.ctype = dp.paramType + local.name = dp.name + local.init = UnknownVarExpr(def.loc, null, dp.name + "_\$J") + def.code.stmts.insert(0, local) + + // rename parameter Int bar -> int bar_$J + dp.name = dp.name + "_\$J" + dp.paramType = bp.paramType + } + } + + ** + ** When overriding a Java method check if the base type is + ** is a Java primitive or array and the override definition is + ** matches how the Java type is inferred in the Fantom type system. + ** If we have a match return true and we'll swizzle things in + ** checkMethodOverride. + ** + static private Bool isOverrideInferredType(CType base, CType def) + { + // check if base class slot is a JavaType + java := base.toNonNullable as JavaType + if (java != null) + { + // allow primitives is it matches the inferred type + if (java.isPrimitive) return java.inferredAs == def + + // allow arrays if mapped as Foo[] -> Foo?[]? + if (java.isArray) return java.inferredAs == def.toNonNullable && def.isNullable + } + return false + } + +////////////////////////////////////////////////////////////////////////// +// CheckErrors +////////////////////////////////////////////////////////////////////////// + + ** + ** Called during CheckErrors step for a type which extends + ** a FFI class or implements any FFI mixins. + ** + override Void checkType(TypeDef def) + { + // can't subclass a primitive array like ByteArray/byte[] + if (def.base.deref is JavaType && def.base.deref->isInteropArray) + { + err("Cannot subclass from Java interop array: $def.base", def.loc) + return + } + + // we don't allow deep inheritance of Java classes because + // the Fantom constructor and Java constructor model don't match + // up past one level of inheritance + // NOTE: that that when we remove this restriction we need to + // test how field initialization works because instance$init + // is almost certain to break with the current emit design + javaBase := def.base + while (javaBase != null && !javaBase.isForeign) javaBase = javaBase.base + if (javaBase != null && javaBase !== def.base) + { + err("Cannot subclass Java class more than one level: $javaBase", def.loc) + return + } + + // ensure that when we map Fantom constructors to Java + // constructors that we don't have duplicate signatures + ctors := def.ctorDefs + ctors.each |MethodDef a, Int i| + { + ctors.each |MethodDef b, Int j| + { + if (i > j && areParamsSame(a, b)) + err("Duplicate Java FFI constructor signatures: '$b.name' and '$a.name'", a.loc) + } + } + } + + ** + ** Do the two methods have the exact same parameter types. + ** + static Bool areParamsSame(CMethod a, CMethod b) + { + if (a.params.size != b.params.size) return false + for (i:=0; i<a.params.size; ++i) + { + if (a.params[i].paramType != b.params[i].paramType) + return false + } + return true + } + +////////////////////////////////////////////////////////////////////////// +// Coercion +////////////////////////////////////////////////////////////////////////// + + ** + ** Return if we can make the actual type fit the expected + ** type, potentially using a coercion. + ** + Bool fits(CType actual, CType expected) + { + // use dummy expression and route to coerce code + dummy := UnknownVarExpr(Loc("dummy"), null, "dummy") { ctype = actual } + fits := true + coerce(dummy, expected) |->| { fits=false } + return fits + } + + ** + ** Coerce expression to expected type. If not a type match + ** then run the onErr function. + ** + override Expr coerce(Expr expr, CType expected, |->| onErr) + { + // handle easy case + actual := expr.ctype + expected = expected.deref + if (actual == expected) return expr + + // handle null literal + if (expr.id === ExprId.nullLiteral && expected.isNullable) + return expr + + // handle Fantom to Java primitives + if (expected.pod == primitives) + return coerceToPrimitive(expr, expected, onErr) + + // handle Java primitives to Fan + if (actual.pod == primitives) + return coerceFromPrimitive(expr, expected, onErr) + + // handle Java array to Fantom list + if (actual.name[0] == '[') + return coerceFromArray(expr, expected, onErr) + + // handle Fantom list to Java array + if (expected.name[0] == '[') + return coerceToArray(expr, expected, onErr) + + // handle sys::Func -> Java interface + if (actual is FuncType && expected.isMixin && expected.toNonNullable is JavaType) + return coerceFuncToInterface(expr, expected.toNonNullable, onErr) + + // handle special classes and interfaces for built-in Fantom + // classes which actually map directly to Java built-in types + if (actual.isBool && boolTypes.contains(expected.toNonNullable.signature)) return box(expr) + if (actual.isInt && intTypes.contains(expected.toNonNullable.signature)) return box(expr) + if (actual.isFloat && floatTypes.contains(expected.toNonNullable.signature)) return box(expr) + if (actual.isDecimal && decimalTypes.contains(expected.toNonNullable.signature)) return expr + if (actual.isStr && strTypes.contains(expected.toNonNullable.signature)) return expr + + // use normal Fantom coercion behavior + return super.coerce(expr, expected, onErr) + } + + ** + ** Ensure value type is boxed. + ** + private Expr box(Expr expr) + { + if (expr.ctype.isVal) + return TypeCheckExpr.coerce(expr, expr.ctype.toNullable) + else + return expr + } + + ** + ** Coerce a fan expression to a Java primitive (other + ** than the ones we support natively) + ** + Expr coerceToPrimitive(Expr expr, JavaType expected, |->| onErr) + { + actual := expr.ctype + + // sys::Int (long) -> int, short, byte + if (actual.isInt && expected.isPrimitiveIntLike) + return TypeCheckExpr.coerce(expr, expected) + + // sys::Float (double) -> float + if (actual.isFloat && expected.isPrimitiveFloat) + return TypeCheckExpr.coerce(expr, expected) + + // no coercion - type error + onErr() + return expr + } + + ** + ** Coerce a Java primitive to a Fantom type. + ** + Expr coerceFromPrimitive(Expr expr, CType expected, |->| onErr) + { + actual := (JavaType)expr.ctype + + // int, short, byte -> sys::Int (long) + if (actual.isPrimitiveIntLike) + { + if (expected.isInt || expected.isObj) + return TypeCheckExpr.coerce(expr, expected) + } + + // float -> sys::Float (float) + if (actual.isPrimitiveFloat) + { + if (expected.isFloat || expected.isObj) + return TypeCheckExpr.coerce(expr, expected) + } + + // no coercion - type error + onErr() + return expr + } + + ** + ** Coerce a Java array to a Fantom list. + ** + Expr coerceFromArray(Expr expr, CType expected, |->| onErr) + { + actual := (JavaType)expr.ctype.toNonNullable + + // if expected is array type + if (expected is JavaType && ((JavaType)expected).isArray) + if (actual.arrayOf.fits(((JavaType)expected).arrayOf)) return expr + + // if expected is Obj + if (expected.isObj) return arrayToList(expr, actual.inferredArrayOf) + + // if expected is list type + if (expected.toNonNullable is ListType) + { + expectedOf := ((ListType)expected.toNonNullable).v + if (actual.inferredArrayOf.fits(expectedOf)) return arrayToList(expr, expectedOf) + } + + // no coercion available + onErr() + return expr + } + + ** + ** Generate List.make(of, expr) where expr is Object[] + ** + private Expr arrayToList(Expr expr, CType of) + { + loc := expr.loc + ofExpr := LiteralExpr(loc, ExprId.typeLiteral, ns.typeType, of) + call := CallExpr.makeWithMethod(loc, null, listMakeFromArray, [ofExpr, expr]) + call.synthetic = true + return call + } + + ** + ** Coerce a Fantom list to Java array. + ** + Expr coerceToArray(Expr expr, CType expected, |->| onErr) + { + loc := expr.loc + expectedOf := ((JavaType)expected.toNonNullable).inferredArrayOf + actual := expr.ctype + + // if actual is list type + if (actual.toNonNullable is ListType) + { + actualOf := ((ListType)actual.toNonNullable).v + if (actualOf.fits(expectedOf)) + { + // (Foo[])list.asArray(cls) + clsLiteral := CallExpr.makeWithMethod(loc, null, JavaType.classLiteral(this, expectedOf)) + asArray := CallExpr.makeWithMethod(loc, expr, listAsArray, [clsLiteral]) + return TypeCheckExpr.coerce(asArray, expected) + } + } + + // no coercion available + onErr() + return expr + } + + ** + ** Attempt to coerce a parameterized sys::Func expr to a Java + ** interface if the interface supports exactly one matching method. + ** + Expr coerceFuncToInterface(Expr expr, JavaType expected, |->| onErr) + { + // check if we have exactly one abstract method in the expected type + loc := expr.loc + abstracts := expected.methods.findAll |CMethod m->Bool| { return m.isAbstract } + if (abstracts.size != 1) { onErr(); return expr } + method := abstracts.first + + // check if we have a match + FuncType funcType := (FuncType)expr.ctype + if (!isFuncToInterfaceMatch(funcType, method)) { onErr(); return expr } + + // check if we've already generated a wrapper for this combo + key := "${funcType.signature}+${method.qname}" + ctor := funcWrappers[key] + if (ctor == null) + { + ctor = generateFuncToInterfaceWrapper(expr.loc, funcType, expected, method) + funcWrappers[key] = ctor + } + + // replace expr with FuncWrapperX(expr) + call := CallExpr.makeWithMethod(loc, null, ctor, [expr]) + call.synthetic = true + return call + } + + ** + ** Return if the specified function type can be used to implement + ** the specified interface method. + ** + Bool isFuncToInterfaceMatch(FuncType funcType, CMethod method) + { + // sanity check to map to callX method - can't handle more than 8 args + if (method.params.size > 8) return false + + // check if method is match for function; first check is that + // method must supply all the arguments required by the function + if (funcType.params.size > method.params.size) return false + + // check that func return type fits method return + retOk := method.returnType.isVoid || fits(funcType.ret, method.returnType) + if (!retOk) return false + + // check all the method parameters fit the function parameters + paramsOk := funcType.params.all |CType f, Int i->Bool| { return fits(f, method.params[i].paramType) } + if (!paramsOk) return false + + return true + } + + ** + ** Generate the wrapper which implements the specified expected interface + ** and overrides the specified method which calls the function. + ** + CMethod generateFuncToInterfaceWrapper(Loc loc, FuncType funcType, CType expected, CMethod method) + { + // Fantom: func typed as |Str| + // Java: interface Foo { void bar(String) } + // Result: FuncWrapperX(func) + // + // class FuncWrapperX : Foo + // { + // new make(Func f) { _func = f } + // override Void bar(Str a) { _func.call(a) } + // Func _func + // } + + // generate FuncWrapper class + name := "FuncWrapper" + funcWrappers.size + cls := TypeDef(ns, loc, compiler.types[0].unit, name, FConst.Internal + FConst.Synthetic) + cls.base = ns.objType + cls.mixins = [expected] + addTypeDef(cls) + + // generate FuncWrapper._func field + field := FieldDef(loc, cls) + ((SlotDef)field).name = "_func" + ((DefNode)field).flags = FConst.Private + FConst.Storage + FConst.Synthetic + field.fieldType = funcType + cls.addSlot(field) + + // generate FuncWrapper.make constructor + ctor := MethodDef(loc, cls, "make", FConst.Internal + FConst.Ctor + FConst.Synthetic) + ctor.ret = ns.voidType + ctor.paramDefs = [ParamDef(loc, funcType, "f")] + ctor.code = Block.make(loc) + ctor.code.stmts.add(BinaryExpr.makeAssign( + FieldExpr(loc, ThisExpr(loc), field), + UnknownVarExpr(loc, null, "f")).toStmt) + ctor.code.stmts.add(ReturnStmt.make(loc)) + cls.addSlot(ctor) + + // generate FuncWrapper override of abstract method + over := MethodDef(loc, cls, method.name, FConst.Public + FConst.Override + FConst.Synthetic) + over.ret = method.returnType + over.paramDefs = ParamDef[,] + over.code = Block.make(loc) + callArity := "call" + call := CallExpr.makeWithMethod(loc, FieldExpr(loc, ThisExpr(loc), field), funcType.method(callArity)) + method.params.each |CParam param, Int i| + { + paramName := "p$i" + over.params.add(ParamDef(loc, param.paramType, paramName)) + if (i < funcType.params.size) + call.args.add(UnknownVarExpr(loc, null, paramName)) + } + if (method.returnType.isVoid) + over.code.stmts.add(call.toStmt).add(ReturnStmt(loc)) + else + over.code.stmts.add(ReturnStmt(loc, call)) + cls.addSlot(over) + + // return the ctor which we use for coercion + return ctor + } + +////////////////////////////////////////////////////////////////////////// +// Reflection +////////////////////////////////////////////////////////////////////////// + + ** + ** Get a CMethod representation for 'List.make(Type, Object[])' + ** + once CMethod listMakeFromArray() + { + return JavaMethod( + this.ns.listType, + "make", + FConst.Public + FConst.Static, + this.ns.listType.toNullable, + [ + JavaParam("of", this.ns.typeType), + JavaParam("array", objectArrayType) + ]) + } + + ** + ** Get a CMethod representation for 'Object[] List.asArray()' + ** + once CMethod listAsArray() + { + return JavaMethod( + this.ns.listType, + "asArray", + FConst.Public, + objectArrayType, + [JavaParam("cls", classType)]) + } + + ** + ** Get a CType representation for 'java.lang.Class' + ** + once JavaType classType() + { + return ns.resolveType("[java]java.lang::Class") + } + + ** + ** Get a CType representation for 'java.lang.Object[]' + ** + once JavaType objectArrayType() + { + return ns.resolveType("[java]java.lang::[Object") + } + +////////////////////////////////////////////////////////////////////////// +// Fields +////////////////////////////////////////////////////////////////////////// + + const static Str[] boolTypes := Str[ + "[java]java.io::Serializable", + "[java]java.lang::Comparable", + ] + + const static Str[] intTypes := Str[ + "[java]java.lang::Number", + "[java]java.io::Serializable", + "[java]java.lang::Comparable", + ] + + const static Str[] floatTypes := Str[ + "[java]java.lang::Number", + "[java]java.io::Serializable", + "[java]java.lang::Comparable", + ] + + const static Str[] decimalTypes := Str[ + "[java]java.lang::Number", + "[java]java.io::Serializable", + "[java]java.lang::Comparable", + ] + + const static Str[] strTypes := Str[ + "[java]java.io::Serializable", + "[java]java.lang::CharSequence", + "[java]java.lang::Comparable", + ] + + JavaPrimitives primitives := JavaPrimitives(this) + ClassPath cp + + private Str:CMethod funcWrappers := Str:CMethod[:] // funcType+method:ctor + +} + +************************************************************************** +** CallMatch +************************************************************************** + +internal class CallMatch +{ + CallExpr apply(CallExpr call) + { + call.args = args + call.method = method + call.ctype = method.isCtor ? method.parent : method.returnType + return call + } + + override Str toStr() { return method.signature } + + CMethod? method // matched method + Expr[]? args // coerced arguments +}
\ No newline at end of file diff --git a/tests/examplefiles/test.groovy b/tests/examplefiles/test.groovy new file mode 100644 index 00000000..903863d2 --- /dev/null +++ b/tests/examplefiles/test.groovy @@ -0,0 +1,97 @@ +// This source code comes from http://www.odelia-technologies.com/node/200 + +package com.odelia.groovy.simpleworkflow + + +class SimpleWorkflowEngine { + def workflowMap = [:] + def context = [:] + def beforeActivityName = 'beforeActivity' + def afterActivityName = 'afterActivity' + + SimpleWorkflowEngine(workflow, context = [:]) { + this.context = context + parseWorkflow(workflow) + } + + def parseWorkflow(workflow) { + workflowMap = new WorkflowParser().parse(workflow) + } + + def getActivityValue(activity) { + assert activity instanceof String + if (!workflowMap[activity]) + throw new RuntimeException("$activity activity doesn't exist") + workflowMap[activity] + } + + def execute(activity, pause) { + if (workflowMap[beforeActivityName]) { + getActivityValue(beforeActivityName)(context, activity) + } + + def activityValue = getActivityValue(activity) + + // Determine the next activity to execute + def nextActivity + switch (activityValue) { + case String: nextActivity = activityValue; break + case Closure: nextActivity = activityValue(context); break + case Class: nextActivity = activityValue.newInstance()(context) + } + + if (workflowMap[afterActivityName]) { + getActivityValue(afterActivityName)(context, activity, nextActivity) + } + + if (!pause && nextActivity) + call(nextActivity) + else + nextActivity + } + + def call(activity) { + execute(activity, false) + } + + def nextActivity(activity) { + execute(activity, true) + } + + static void main(String[] args) { + if (args.size() != 2) { + println 'Usage: com.odelia.groovy.simpleworkflow.SimpleWorkflowEngine <dsl_filename> <activity_name>' + return + } + SimpleWorkflowEngine.newInstance(new File(args[0]))(args[1]) + } + +} + +private class WorkflowParser { + def map = [:] + + def methodMissing(String name, args) { + map[name] = args[0] + } + + def parse(Closure wf) { + wf.delegate = this + wf.resolveStrategy = Closure.DELEGATE_FIRST + wf() + map + } + + def workflow = { it -> + it.delegate = this + it.resolveStrategy = Closure.DELEGATE_FIRST + it() + } + + def parse(File workflowDef) { + def binding = new Binding([workflow: workflow]) + def shell = new GroovyShell(binding) + shell.evaluate(workflowDef) + map + } +}
\ No newline at end of file diff --git a/tests/examplefiles/test.idr b/tests/examplefiles/test.idr new file mode 100644 index 00000000..f0e96d88 --- /dev/null +++ b/tests/examplefiles/test.idr @@ -0,0 +1,93 @@ +module Main + +data Ty = TyInt | TyBool | TyFun Ty Ty + +interpTy : Ty -> Type +interpTy TyInt = Int +interpTy TyBool = Bool +interpTy (TyFun s t) = interpTy s -> interpTy t + +using (G : Vect n Ty) + + data Env : Vect n Ty -> Type where + Nil : Env Nil + (::) : interpTy a -> Env G -> Env (a :: G) + + data HasType : (i : Fin n) -> Vect n Ty -> Ty -> Type where + stop : HasType fZ (t :: G) t + pop : HasType k G t -> HasType (fS k) (u :: G) t + + lookup : HasType i G t -> Env G -> interpTy t + lookup stop (x :: xs) = x + lookup (pop k) (x :: xs) = lookup k xs + + data Expr : Vect n Ty -> Ty -> Type where + Var : HasType i G t -> Expr G t + Val : (x : Int) -> Expr G TyInt + Lam : Expr (a :: G) t -> Expr G (TyFun a t) + App : Expr G (TyFun a t) -> Expr G a -> Expr G t + Op : (interpTy a -> interpTy b -> interpTy c) -> Expr G a -> Expr G b -> + Expr G c + If : Expr G TyBool -> Expr G a -> Expr G a -> Expr G a + Bind : Expr G a -> (interpTy a -> Expr G b) -> Expr G b + + dsl expr + lambda = Lam + variable = Var + index_first = stop + index_next = pop + + (<$>) : |(f : Expr G (TyFun a t)) -> Expr G a -> Expr G t + (<$>) = \f, a => App f a + + pure : Expr G a -> Expr G a + pure = id + + syntax IF [x] THEN [t] ELSE [e] = If x t e + + (==) : Expr G TyInt -> Expr G TyInt -> Expr G TyBool + (==) = Op (==) + + (<) : Expr G TyInt -> Expr G TyInt -> Expr G TyBool + (<) = Op (<) + + instance Num (Expr G TyInt) where + (+) x y = Op (+) x y + (-) x y = Op (-) x y + (*) x y = Op (*) x y + + abs x = IF (x < 0) THEN (-x) ELSE x + + fromInteger = Val . fromInteger + + interp : Env G -> {static} Expr G t -> interpTy t + interp env (Var i) = lookup i env + interp env (Val x) = x + interp env (Lam sc) = \x => interp (x :: env) sc + interp env (App f s) = (interp env f) (interp env s) + interp env (Op op x y) = op (interp env x) (interp env y) + interp env (If x t e) = if (interp env x) then (interp env t) else (interp env e) + interp env (Bind v f) = interp env (f (interp env v)) + + eId : Expr G (TyFun TyInt TyInt) + eId = expr (\x => x) + + eTEST : Expr G (TyFun TyInt (TyFun TyInt TyInt)) + eTEST = expr (\x, y => y) + + eAdd : Expr G (TyFun TyInt (TyFun TyInt TyInt)) + eAdd = expr (\x, y => Op (+) x y) + + eDouble : Expr G (TyFun TyInt TyInt) + eDouble = expr (\x => App (App eAdd x) (Var stop)) + + eFac : Expr G (TyFun TyInt TyInt) + eFac = expr (\x => IF x == 0 THEN 1 ELSE [| eFac (x - 1) |] * x) + +testFac : Int +testFac = interp [] eFac 4 + +main : IO () +main = print testFac + + diff --git a/tests/examplefiles/test.mask b/tests/examplefiles/test.mask new file mode 100644 index 00000000..39134d74 --- /dev/null +++ b/tests/examplefiles/test.mask @@ -0,0 +1,41 @@ +
+// comment
+h4.class-1#id.class-2.other checked='true' disabled name = x param > 'Enter ..'
+input placeholder=Password type=password >
+ :dualbind x-signal='dom:create' value=user.passord;
+% each='flowers' >
+ div style='
+ position: absolute;
+ display: inline-block;
+ background: url("image.png") center center no-repeat;
+ ';
+#skippedDiv.other {
+ img src='~[url]';
+ div style="text-align:center;" {
+ '~[: $obj.foo("username", name) + 2]'
+ "~[Localize: stringId]"
+ }
+
+ p > """
+
+ Hello "world"
+ """
+
+ p > '
+ Hello "world"
+ '
+
+ p > "Hello 'world'"
+
+ :customComponent x-value='tt';
+ /* footer > '(c) 2014' */
+}
+
+.skippedDiv >
+ span >
+ #skipped >
+ table >
+ td >
+ tr > ';)'
+
+br;
\ No newline at end of file diff --git a/tests/examplefiles/test.nim b/tests/examplefiles/test.nim new file mode 100644 index 00000000..20610bb6 --- /dev/null +++ b/tests/examplefiles/test.nim @@ -0,0 +1,93 @@ +import re + +for x in lines("myfile.txt"): + if x =~ re"(\w+)=(.*)": + echo "Key: ", matches[0], + " Value: ", matches[1] + +Echo("What's your name? ") +var name: string = readLine(stdin) +if name == "": + echo("Poor soul, you lost your name?") +elif name == "name": + echo("Very funny, your name is name.") +else: + Echo("Hi, ", name, "!") + +var name = readLine(stdin) +case name +of "": + echo("Poor soul, you lost your name?") +of "name": + echo("Very funny, your name is name.") +else: + Echo("Hi, ", name, "!") + +from strutils import parseInt + +Echo("A number please: ") +var n = parseInt(readLine(stdin)) +case n +of 0..2, 4..7: Echo("The number is in the set: {0, 1, 2, 4, 5, 6, 7}") +of 3, 8: Echo("The number is 3 or 8") + +Echo("Counting to 10: ") +var i = 1 +while i <= 10: + Echo($i) + inc(i) + +proc yes(question: string): bool = + Echo(question, " (y/n)") + while true: + case readLine(stdin) + of "y", "Y", "yes", "Yes": return true + of "n", "N", "no", "No": return false + else: Echo("Please be clear: yes or no") + +proc even(n: int): bool + +proc odd(n: int): bool = + if n == 1: return true + else: return even(n-1) + +iterator countup(a, b: int): int = + var res = a + while res <= b: + yield res + inc(res) + +type + TPerson = object of TObject + name*: string # the * means that `name` is accessible from other modules + age: int # no * means that the field is hidden from other modules + + TStudent = object of TPerson # TStudent inherits from TPerson + id: int # with an id field + +var + student: TStudent + person: TPerson +assert(student is TStudent) + +echo({'a', 'b', 'c'}.card) +stdout.writeln("Hallo") +var + f: TFile +if open(f, "numbers.txt"): + try: + var a = readLine(f) + var b = readLine(f) + echo("sum: " & $(parseInt(a) + parseInt(b))) + except EOverflow: + echo("overflow!") + except EInvalidValue: + echo("could not convert string to integer") + except EIO: + echo("IO error!") + except: + echo("Unknown exception!") + # reraise the unknown exception: + raise + finally: + close(f)
\ No newline at end of file diff --git a/tests/examplefiles/test.opa b/tests/examplefiles/test.opa new file mode 100644 index 00000000..ec287ac5 --- /dev/null +++ b/tests/examplefiles/test.opa @@ -0,0 +1,10 @@ +function sample_page() { + <header> + <h3>HTML in Opa</h3> + </header> + <article> + <div class=container> + <p>Learning by examples.</p> + </div> + </article> +} diff --git a/tests/examplefiles/test.p6 b/tests/examplefiles/test.p6 new file mode 100644 index 00000000..3d12b56c --- /dev/null +++ b/tests/examplefiles/test.p6 @@ -0,0 +1,252 @@ +#!/usr/bin/env perl6 + +use v6; + +my $string = 'I look like a # comment!'; + +if $string eq 'foo' { + say 'hello'; +} + +regex http-verb { + 'GET' + | 'POST' + | 'PUT' + | 'DELETE' + | 'TRACE' + | 'OPTIONS' + | 'HEAD' +} + +# a sample comment + +say 'Hello from Perl 6!' + + +#`{ +multi-line comment! +} + +say 'here'; + +#`( +multi-line comment! +) + +say 'here'; + +#`{{{ +I'm a special comment! +}}} + +say 'there'; + +#`{{ +I'm { even } specialer! +}} + +say 'there'; + +#`{{ +does {{nesting}} work? +}} + +#`«< +trying mixed delimiters +» + +my $string = qq<Hooray, arbitrary delimiter!>; +my $string = qq«Hooray, arbitrary delimiter!»; +my $string = q <now with whitespace!>; +my $string = qq<<more strings>>; + +my %hash := Hash.new; + +=begin pod + +Here's some POD! Wooo + +=end pod + +=for Testing + This is POD (see? role isn't highlighted) + +say('this is not!'); + +=table + Of role things + +say('not in your table'); +#= A single line declarator "block" (with a keyword like role) +#| Another single line declarator "block" (with a keyword like role) +#={ + A declarator block (with a keyword like role) + } +#|{ + Another declarator block (with a keyword like role) + } +#= { A single line declarator "block" with a brace (with a keyword like role) +#=« + More declarator blocks! (with a keyword like role) + » +#|« + More declarator blocks! (with a keyword like role) + » + +say 'Moar code!'; + +my $don't = 16; + +sub don't($x) { + !$x +} + +say don't 'foo'; + +my %hash = ( + :foo(1), +); + +say %hash<foo>; +say %hash<<foo>>; +say %hash«foo»; + +say %*hash<foo>; +say %*hash<<foo>>; +say %*hash«foo»; + +say $<todo>; +say $<todo>; + +for (@A Z @B) -> $a, $b { + say $a + $b; +} + +Q:PIR { + .loadlib "somelib" +} + +my $longstring = q/ + lots + of + text +/; + +my $heredoc = q:to/END_SQL/; +SELECT * FROM Users +WHERE first_name = 'Rob' +END_SQL +my $hello; + +# Fun with regexen + +if 'food' ~~ /foo/ { + say 'match!' +} + +my $re = /foo/; +my $re2 = m/ foo /; +my $re3 = m:i/ FOO /; + +call-a-sub(/ foo /); +call-a-sub(/ foo \/ bar /); + +my $re4 = rx/something | something-else/; +my $result = ms/regexy stuff/; +my $sub0 = s/regexy stuff/more stuff/; +my $sub = ss/regexy stuff/more stuff/; +my $trans = tr/regexy stuff/more stuff/; + +my @values = <a b c d>; +call-sub(<a b c d>); +call-sub <a b c d>; + +my $result = $a < $b; + +for <a b c d> -> $letter { + say $letter; +} + +sub test-sub { + say @_; + say $!; + say $/; + say $0; + say $1; + say @*ARGS; + say $*ARGFILES; + say &?BLOCK; + say ::?CLASS; + say $?CLASS; + say @=COMMENT; + say %?CONFIG; + say $*CWD; + say $=data; + say %?DEEPMAGIC; + say $?DISTRO; + say $*DISTRO; + say $*EGID; + say %*ENV; + say $*ERR; + say $*EUID; + say $*EXECUTABLE_NAME; + say $?FILE; + say $?GRAMMAR; + say $*GID; + say $*IN; + say @*INC; + say %?LANG; + say $*LANG; + say $?LINE; + say %*META-ARGS; + say $?MODULE; + say %*OPTS; + say %*OPT; + say $?KERNEL; + say $*KERNEL; + say $*OUT; + say $?PACKAGE; + say $?PERL; + say $*PERL; + say $*PID; + say %=pod; + say $*PROGRAM_NAME; + say %*PROTOCOLS; + say ::?ROLE; + say $?ROLE; + say &?ROUTINE; + say $?SCOPE; + say $*TZ; + say $*UID; + say $?USAGE; + say $?VM; + say $?XVM; +} + +say <a b c>; + +my $perl5_re = m:P5/ fo{2} /; +my $re5 = rx«something | something-else»; + +my $M := %*COMPILING<%?OPTIONS><M>; + +say $M; + +sub regex-name { ... } +my $pair = role-name => 'foo'; +$pair = rolesque => 'foo'; + +my sub something(Str:D $value) { ... } + +my $s = q«< +some +string +stuff +»; + +my $regex = m«< some chars »; +# after + +say $/<foo><bar>; + +roleq; diff --git a/tests/examplefiles/test.php b/tests/examplefiles/test.php index 97e21f73..218892fe 100644 --- a/tests/examplefiles/test.php +++ b/tests/examplefiles/test.php @@ -1,5 +1,7 @@ <?php +$disapproval_ಠ_ಠ_of_php = 'unicode var'; + $test = function($a) { $lambda = 1; } /** @@ -16,7 +18,7 @@ if(!defined('UNLOCK') || !UNLOCK) // Load the parent archive class require_once(ROOT_PATH.'/classes/archive.class.php'); -class Zip\Zipp { +class Zip\Zippಠ_ಠ_ { } diff --git a/tests/examplefiles/test.pig b/tests/examplefiles/test.pig new file mode 100644 index 00000000..f67b0268 --- /dev/null +++ b/tests/examplefiles/test.pig @@ -0,0 +1,148 @@ +/** + * This script is an example recommender (using made up data) showing how you might modify item-item links + * by defining similar relations between items in a dataset and customizing the change in weighting. + * This example creates metadata by using the genre field as the metadata_field. The items with + * the same genre have it's weight cut in half in order to boost the signals of movies that do not have the same genre. + * This technique requires a customization of the standard GetItemItemRecommendations macro + */ +import 'recommenders.pig'; + + + +%default INPUT_PATH_PURCHASES '../data/retail/purchases.json' +%default INPUT_PATH_WISHLIST '../data/retail/wishlists.json' +%default INPUT_PATH_INVENTORY '../data/retail/inventory.json' +%default OUTPUT_PATH '../data/retail/out/modify_item_item' + + +/******** Custom GetItemItemRecommnedations *********/ +define recsys__GetItemItemRecommendations_ModifyCustom(user_item_signals, metadata) returns item_item_recs { + + -- Convert user_item_signals to an item_item_graph + ii_links_raw, item_weights = recsys__BuildItemItemGraph( + $user_item_signals, + $LOGISTIC_PARAM, + $MIN_LINK_WEIGHT, + $MAX_LINKS_PER_USER + ); + -- NOTE this function is added in order to combine metadata with item-item links + -- See macro for more detailed explination + ii_links_metadata = recsys__AddMetadataToItemItemLinks( + ii_links_raw, + $metadata + ); + + /********* Custom Code starts here ********/ + + --The code here should adjust the weights based on an item-item link and the equality of metadata. + -- In this case, if the metadata is the same, the weight is reduced. Otherwise the weight is left alone. + ii_links_adjusted = foreach ii_links_metadata generate item_A, item_B, + -- the amount of weight adjusted is dependant on the domain of data and what is expected + -- It is always best to adjust the weight by multiplying it by a factor rather than addition with a constant + (metadata_B == metadata_A ? (weight * 0.5): weight) as weight; + + + /******** Custom Code stops here *********/ + + -- remove negative numbers just incase + ii_links_adjusted_filt = foreach ii_links_adjusted generate item_A, item_B, + (weight <= 0 ? 0: weight) as weight; + -- Adjust the weights of the graph to improve recommendations. + ii_links = recsys__AdjustItemItemGraphWeight( + ii_links_adjusted_filt, + item_weights, + $BAYESIAN_PRIOR + ); + + -- Use the item-item graph to create item-item recommendations. + $item_item_recs = recsys__BuildItemItemRecommendationsFromGraph( + ii_links, + $NUM_RECS_PER_ITEM, + $NUM_RECS_PER_ITEM + ); +}; + + +/******* Load Data **********/ + +--Get purchase signals +purchase_input = load '$INPUT_PATH_PURCHASES' using org.apache.pig.piggybank.storage.JsonLoader( + 'row_id: int, + movie_id: chararray, + movie_name: chararray, + user_id: chararray, + purchase_price: int'); + +--Get wishlist signals +wishlist_input = load '$INPUT_PATH_WISHLIST' using org.apache.pig.piggybank.storage.JsonLoader( + 'row_id: int, + movie_id: chararray, + movie_name: chararray, + user_id: chararray'); + + +/******* Convert Data to Signals **********/ + +-- Start with choosing 1 as max weight for a signal. +purchase_signals = foreach purchase_input generate + user_id as user, + movie_name as item, + 1.0 as weight; + + +-- Start with choosing 0.5 as weight for wishlist items because that is a weaker signal than +-- purchasing an item. +wishlist_signals = foreach wishlist_input generate + user_id as user, + movie_name as item, + 0.5 as weight; + +user_signals = union purchase_signals, wishlist_signals; + + +/******** Changes for Modifying item-item links ******/ +inventory_input = load '$INPUT_PATH_INVENTORY' using org.apache.pig.piggybank.storage.JsonLoader( + 'movie_title: chararray, + genres: bag{tuple(content:chararray)}'); + + +metadata = foreach inventory_input generate + FLATTEN(genres) as metadata_field, + movie_title as item; +-- requires the macro to be written seperately + --NOTE this macro is defined within this file for clarity +item_item_recs = recsys__GetItemItemRecommendations_ModifyCustom(user_signals, metadata); +/******* No more changes ********/ + + +user_item_recs = recsys__GetUserItemRecommendations(user_signals, item_item_recs); + +--Completely unrelated code stuck in the middle +data = LOAD 's3n://my-s3-bucket/path/to/responses' + USING org.apache.pig.piggybank.storage.JsonLoader(); +responses = FOREACH data GENERATE object#'response' AS response: map[]; +out = FOREACH responses + GENERATE response#'id' AS id: int, response#'thread' AS thread: chararray, + response#'comments' AS comments: {t: (comment: chararray)}; +STORE out INTO 's3n://path/to/output' USING PigStorage('|'); + + +/******* Store recommendations **********/ + +-- If your output folder exists already, hadoop will refuse to write data to it. + +rmf $OUTPUT_PATH/item_item_recs; +rmf $OUTPUT_PATH/user_item_recs; + +store item_item_recs into '$OUTPUT_PATH/item_item_recs' using PigStorage(); +store user_item_recs into '$OUTPUT_PATH/user_item_recs' using PigStorage(); + +-- STORE the item_item_recs into dynamo +STORE item_item_recs + INTO '$OUTPUT_PATH/unused-ii-table-data' +USING com.mortardata.pig.storage.DynamoDBStorage('$II_TABLE', '$AWS_ACCESS_KEY_ID', '$AWS_SECRET_ACCESS_KEY'); + +-- STORE the user_item_recs into dynamo +STORE user_item_recs + INTO '$OUTPUT_PATH/unused-ui-table-data' +USING com.mortardata.pig.storage.DynamoDBStorage('$UI_TABLE', '$AWS_ACCESS_KEY_ID', '$AWS_SECRET_ACCESS_KEY'); diff --git a/tests/examplefiles/test.ps1 b/tests/examplefiles/test.ps1 new file mode 100644 index 00000000..385fb6f4 --- /dev/null +++ b/tests/examplefiles/test.ps1 @@ -0,0 +1,108 @@ +<# +.SYNOPSIS +Runs a T-SQL Query and optional outputs results to a delimited file. +.DESCRIPTION +Invoke-Sql script will run a T-SQL query or stored procedure and optionally outputs a delimited file. +.EXAMPLE +PowerShell.exe -File "C:\Scripts\Invoke-Sql.ps1" -ServerInstance "Z003\sqlprod2" -Database orders -Query "EXEC usp_accounts '12445678'" +This example connects to Z003\sqlprod2.Orders and executes a stored procedure which does not return a result set +.EXAMPLE +PowerShell.exe -File "C:\Scripts\Invoke-Sql.ps1" -ServerInstance "Z003\sqlprod2" -Database orders -Query "SELECT * FROM dbo.accounts" -FilePath "C:\Scripts\accounts.txt" -Delimiter "," +This example connects to Z003\sqlprod2.Orders and selects the records from the accounts tables, the data is outputed to a CSV file +.NOTES +Version History +v1.0 - Chad Miller - 12/14/2010 - Initial release +IMPORTANT!!! The EventLog source which is set to the application needs to be registered with +the Event log: +New-EventLog -LogName Application -Source $Application +#> +param( +#ServerInstance is Mandatory! +[Parameter(Position=0, Mandatory=$false)] [string]$ServerInstance, +#Database is Mandatory! +[Parameter(Position=1, Mandatory=$false)] [string]$Database, +#Query is Mandatory! +[Parameter(Position=2, Mandatory=$false)] [string]$Query, +[Parameter(Position=3, Mandatory=$false)] [string]$Application="Invoke-Sql.ps1", +[Parameter(Position=4, Mandatory=$false)] [string]$FilePath, +[Parameter(Position=7, Mandatory=$false)] [string]$Delimiter="|", +#If UserName isn't supplied a trusted connection will be used +[Parameter(Position=5, Mandatory=$false)] [string]$UserName, +[Parameter(Position=6, Mandatory=$false)] [string]$Password, +[Parameter(Position=8, Mandatory=$false)] [Int32]$QueryTimeout=600, +[Parameter(Position=9, Mandatory=$false)] [Int32]$ConnectionTimeout=15 +) + + +#This must be run as administrator on Windows 2008 and higher! +New-EventLog -LogName Application -Source $Application -EA SilentlyContinue +$Error.Clear() + +####################### +function Invoke-SqlCmd2 +{ + param( + [Parameter(Position=0, Mandatory=$true)] [string]$ServerInstance, + [Parameter(Position=1, Mandatory=$true)] [string]$Database, + [Parameter(Position=2, Mandatory=$true)] [string]$Query, + [Parameter(Position=3, Mandatory=$false)] [string]$UserName, + [Parameter(Position=4, Mandatory=$false)] [string]$Password, + [Parameter(Position=5, Mandatory=$false)] [Int32]$QueryTimeout, + [Parameter(Position=6, Mandatory=$false)] [Int32]$ConnectionTimeout + ) + + try { + if ($Username) + { $ConnectionString = "Server={0};Database={1};User ID={2};Password={3};Trusted_Connection=False;Connect Timeout={4}" -f $ServerInstance,$Database,$Username,$Password,$ConnectionTimeout } + else + { $ConnectionString = "Server={0};Database={1};Integrated Security=True;Connect Timeout={2}" -f $ServerInstance,$Database,$ConnectionTimeout } + $conn=new-object System.Data.SqlClient.SQLConnection + $conn.ConnectionString=$ConnectionString + $conn.Open() + $cmd=new-object system.Data.SqlClient.SqlCommand($Query,$conn) + $cmd.CommandTimeout=$QueryTimeout + $ds=New-Object system.Data.DataSet + $da=New-Object system.Data.SqlClient.SqlDataAdapter($cmd) + [void]$da.fill($ds) + Write-Output ($ds.Tables[0]) + } + finally { + $conn.Dispose() + } + +} #Invoke-SqlCmd2 + +####################### +# MAIN # +####################### +if ($PSBoundParameters.Count -eq 0) +{ + get-help $myInvocation.MyCommand.Path -full + break +} + +try { + $msg = $null + $msg += "Application/Job Name: $Application`n" + $msg += "Query: $Query`n" + $msg += "ServerInstance: $ServerInstance`n" + $msg += "Database: $Database`n" + $msg += "FilePath: $FilePath`n" + + Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Starting`n$msg" + $dt = Invoke-SqlCmd2 -ServerInstance $ServerInstance -Database $Database -Query $Query -UserName $UserName -Password $Password -QueryTimeOut $QueryTimeOut -ConnectionTimeout $ConnectionTimeout + if ($FilePath) + { + if ($dt) + { $dt | export-csv -Delimiter $Delimiter -Path $FilePath -NoTypeInformation } + else #Query Returned No Output! + {Write-EventLog -LogName Application -Source "$Application" -EntryType Warning -EventId 12345 -Message "NoOutput`n$msg" } + } + + Write-EventLog -LogName Application -Source "$Application" -EntryType Information -EventId 12345 -Message "Completed`n$msg" +} +catch { + $Exception = "{0}, {1}" -f $_.Exception.GetType().FullName,$( $_.Exception.Message -replace "'" ) + Write-EventLog -LogName Application -Source "$Application" -EntryType Error -EventId 12345 -Message "Error`n$msg`n$Exception" + throw +} diff --git a/tests/examplefiles/test.pwn b/tests/examplefiles/test.pwn new file mode 100644 index 00000000..d6468617 --- /dev/null +++ b/tests/examplefiles/test.pwn @@ -0,0 +1,253 @@ +#include <core> + +// Single line comment +/* Multi line + comment */ + +/// documentation +/** + + documentation multi line + +**/ + +public OnGameModeInit() { + printf("Hello, World!"); +} + +enum info { + Float:ex; + exa, + exam[5], +} +new arr[5][info]; + +stock Float:test_func() +{ + new a = 5, Float:b = 10.3; + if (a == b) { + + } else { + + } + + for (new i = 0; i < 10; i++) { + continue; + } + + do { + a--; + } while (a > 0); + + while (a < 5) { + a++; + break; + } + + switch (a) { + case 0: { + } + case 0..4: { + } + case 5, 6: { + } + } + + static x; + new xx = a > 5 ? 5 : 0; + new array[sizeof arr] = {0}; + tagof a; + state a; + goto label; + new byte[2 char]; + byte{0} = 'a'; + + return (float(a) + b); +} + + +// float.inc +/* Float arithmetic + * + * (c) Copyright 1999, Artran, Inc. + * Written by Greg Garner (gmg@artran.com) + * Modified in March 2001 to include user defined + * operators for the floating point functions. + * + * This file is provided as is (no warranties). + */ +#if defined _Float_included + #endinput +#endif +#define _Float_included +#pragma library Float + +/* Different methods of rounding */ +enum floatround_method { + floatround_round, + floatround_floor, + floatround_ceil, + floatround_tozero, + floatround_unbiased +} +enum anglemode { + radian, + degrees, + grades +} + +/**************************************************/ +/* Convert an integer into a floating point value */ +native Float:float(value); + +/**************************************************/ +/* Convert a string into a floating point value */ +native Float:floatstr(const string[]); + +/**************************************************/ +/* Multiple two floats together */ +native Float:floatmul(Float:oper1, Float:oper2); + +/**************************************************/ +/* Divide the dividend float by the divisor float */ +native Float:floatdiv(Float:dividend, Float:divisor); + +/**************************************************/ +/* Add two floats together */ +native Float:floatadd(Float:oper1, Float:oper2); + +/**************************************************/ +/* Subtract oper2 float from oper1 float */ +native Float:floatsub(Float:oper1, Float:oper2); + +/**************************************************/ +/* Return the fractional part of a float */ +native Float:floatfract(Float:value); + +/**************************************************/ +/* Round a float into a integer value */ +native floatround(Float:value, floatround_method:method=floatround_round); + +/**************************************************/ +/* Compare two integers. If the two elements are equal, return 0. + If the first argument is greater than the second argument, return 1, + If the first argument is less than the second argument, return -1. */ +native floatcmp(Float:oper1, Float:oper2); + +/**************************************************/ +/* Return the square root of the input value, same as floatpower(value, 0.5) */ +native Float:floatsqroot(Float:value); + +/**************************************************/ +/* Return the value raised to the power of the exponent */ +native Float:floatpower(Float:value, Float:exponent); + +/**************************************************/ +/* Return the logarithm */ +native Float:floatlog(Float:value, Float:base=10.0); + +/**************************************************/ +/* Return the sine, cosine or tangent. The input angle may be in radian, + degrees or grades. */ +native Float:floatsin(Float:value, anglemode:mode=radian); +native Float:floatcos(Float:value, anglemode:mode=radian); +native Float:floattan(Float:value, anglemode:mode=radian); + +/**************************************************/ +/* Return the absolute value */ +native Float:floatabs(Float:value); + + +/**************************************************/ +#pragma rational Float + +/* user defined operators */ +native Float:operator*(Float:oper1, Float:oper2) = floatmul; +native Float:operator/(Float:oper1, Float:oper2) = floatdiv; +native Float:operator+(Float:oper1, Float:oper2) = floatadd; +native Float:operator-(Float:oper1, Float:oper2) = floatsub; +native Float:operator=(oper) = float; + +stock Float:operator++(Float:oper) + return oper+1.0; + +stock Float:operator--(Float:oper) + return oper-1.0; + +stock Float:operator-(Float:oper) + return oper^Float:cellmin; /* IEEE values are sign/magnitude */ + +stock Float:operator*(Float:oper1, oper2) + return floatmul(oper1, float(oper2)); /* "*" is commutative */ + +stock Float:operator/(Float:oper1, oper2) + return floatdiv(oper1, float(oper2)); + +stock Float:operator/(oper1, Float:oper2) + return floatdiv(float(oper1), oper2); + +stock Float:operator+(Float:oper1, oper2) + return floatadd(oper1, float(oper2)); /* "+" is commutative */ + +stock Float:operator-(Float:oper1, oper2) + return floatsub(oper1, float(oper2)); + +stock Float:operator-(oper1, Float:oper2) + return floatsub(float(oper1), oper2); + +stock bool:operator==(Float:oper1, Float:oper2) + return floatcmp(oper1, oper2) == 0; + +stock bool:operator==(Float:oper1, oper2) + return floatcmp(oper1, float(oper2)) == 0; /* "==" is commutative */ + +stock bool:operator!=(Float:oper1, Float:oper2) + return floatcmp(oper1, oper2) != 0; + +stock bool:operator!=(Float:oper1, oper2) + return floatcmp(oper1, float(oper2)) != 0; /* "!=" is commutative */ + +stock bool:operator>(Float:oper1, Float:oper2) + return floatcmp(oper1, oper2) > 0; + +stock bool:operator>(Float:oper1, oper2) + return floatcmp(oper1, float(oper2)) > 0; + +stock bool:operator>(oper1, Float:oper2) + return floatcmp(float(oper1), oper2) > 0; + +stock bool:operator>=(Float:oper1, Float:oper2) + return floatcmp(oper1, oper2) >= 0; + +stock bool:operator>=(Float:oper1, oper2) + return floatcmp(oper1, float(oper2)) >= 0; + +stock bool:operator>=(oper1, Float:oper2) + return floatcmp(float(oper1), oper2) >= 0; + +stock bool:operator<(Float:oper1, Float:oper2) + return floatcmp(oper1, oper2) < 0; + +stock bool:operator<(Float:oper1, oper2) + return floatcmp(oper1, float(oper2)) < 0; + +stock bool:operator<(oper1, Float:oper2) + return floatcmp(float(oper1), oper2) < 0; + +stock bool:operator<=(Float:oper1, Float:oper2) + return floatcmp(oper1, oper2) <= 0; + +stock bool:operator<=(Float:oper1, oper2) + return floatcmp(oper1, float(oper2)) <= 0; + +stock bool:operator<=(oper1, Float:oper2) + return floatcmp(float(oper1), oper2) <= 0; + +stock bool:operator!(Float:oper) + return (_:oper & cellmax) == 0; + +/* forbidden operations */ +forward operator%(Float:oper1, Float:oper2); +forward operator%(Float:oper1, oper2); +forward operator%(oper1, Float:oper2); + diff --git a/tests/examplefiles/test.pypylog b/tests/examplefiles/test.pypylog new file mode 100644 index 00000000..f85030cb --- /dev/null +++ b/tests/examplefiles/test.pypylog @@ -0,0 +1,1839 @@ +[5ed621f277b8] {jit-backend-counts +[5ed621f309bc] jit-backend-counts} +[5ed622c957b0] {jit-log-opt-loop +# Loop 0 : loop with 145 ops +[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, f11, p12, p13, p14, p15, i16, f17, i18, i19, i20, i21, i22, i23, i24, i25, i26, f27, i28, f29, f30] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +i32 = int_gt(i18, 0) +guard_true(i32, descr=<Guard3>) [p1, p0, p5, p2, p3, p4, p6, p7, p8, p9, p10, p12, p13, p14, p15, i16, f17, f11] +i33 = int_add(i19, i20) +i35 = int_sub(i18, 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #128 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #131 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #134 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #137 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #140 BINARY_MULTIPLY', 0) +setfield_gc(p5, i33, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p5, i35, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +i36 = int_mul_ovf(i21, i22) +guard_no_overflow(, descr=<Guard4>) [p1, p0, p12, p15, i36, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p13, i19, None, f17, f11] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #141 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #144 BINARY_ADD', 0) +i38 = int_add_ovf(i36, i19) +guard_no_overflow(, descr=<Guard5>) [p1, p0, i38, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, i36, i19, None, f17, f11] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #145 BINARY_SUBSCR', 0) +i40 = int_lt(i38, 0) +guard_false(i40, descr=<Guard6>) [p1, p0, p14, i38, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, i19, None, f17, f11] +i41 = int_lt(i38, i23) +guard_true(i41, descr=<Guard7>) [p1, p0, p14, i38, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, i19, None, f17, f11] +f42 = getarrayitem_raw(i24, i38, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #146 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #149 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #152 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #155 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #158 BINARY_SUBTRACT', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #159 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #162 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #163 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #166 BINARY_ADD', 0) +i43 = int_add_ovf(i25, i19) +guard_no_overflow(, descr=<Guard8>) [p1, p0, i43, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, f42, i25, None, i19, None, None, f11] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #167 BINARY_SUBSCR', 0) +i45 = int_lt(i43, 0) +guard_false(i45, descr=<Guard9>) [p1, p0, p14, i43, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f42, None, None, i19, None, None, f11] +i46 = int_lt(i43, i23) +guard_true(i46, descr=<Guard10>) [p1, p0, p14, i43, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f42, None, None, i19, None, None, f11] +f47 = getarrayitem_raw(i24, i43, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #168 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #171 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #174 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #177 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #178 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #181 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #182 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #185 BINARY_ADD', 0) +i48 = int_add_ovf(i26, i19) +guard_no_overflow(, descr=<Guard11>) [p1, p0, i48, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, i26, f47, f42, None, None, i19, None, None, f11] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #186 BINARY_SUBSCR', 0) +i50 = int_lt(i48, 0) +guard_false(i50, descr=<Guard12>) [p1, p0, p14, i48, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f47, f42, None, None, i19, None, None, f11] +i51 = int_lt(i48, i23) +guard_true(i51, descr=<Guard13>) [p1, p0, p14, i48, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f47, f42, None, None, i19, None, None, f11] +f52 = getarrayitem_raw(i24, i48, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #187 BINARY_ADD', 0) +f53 = float_add(f47, f52) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #188 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #191 BINARY_MULTIPLY', 0) +f54 = float_mul(f53, f27) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #192 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #195 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #198 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #201 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #202 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #205 BINARY_ADD', 0) +i55 = int_add_ovf(i28, i19) +guard_no_overflow(, descr=<Guard14>) [p1, p0, i55, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, f54, i28, None, None, f42, None, None, i19, None, None, f11] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #206 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #209 BINARY_SUBTRACT', 0) +i57 = int_sub_ovf(i55, 1) +guard_no_overflow(, descr=<Guard15>) [p1, p0, i57, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, i55, f54, None, None, None, f42, None, None, i19, None, None, f11] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #210 BINARY_SUBSCR', 0) +i59 = int_lt(i57, 0) +guard_false(i59, descr=<Guard16>) [p1, p0, p14, i57, i23, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f54, None, None, None, f42, None, None, i19, None, None, f11] +i60 = int_lt(i57, i23) +guard_true(i60, descr=<Guard17>) [p1, p0, p14, i57, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, None, f54, None, None, None, f42, None, None, i19, None, None, f11] +f61 = getarrayitem_raw(i24, i57, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #211 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #214 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #217 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #220 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #221 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #224 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #225 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #228 BINARY_ADD', 0) +i63 = int_add_ovf(i55, 1) +guard_no_overflow(, descr=<Guard18>) [p1, p0, i63, p2, p3, p4, p5, p14, p6, p7, p8, p9, p10, p12, p13, p15, f61, i55, f54, None, None, None, f42, None, None, i19, None, None, f11] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #229 BINARY_SUBSCR', 0) +i64 = int_lt(i63, i23) +guard_true(i64, descr=<Guard19>) [p1, p0, p14, i63, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f61, None, f54, None, None, None, f42, None, None, i19, None, None, f11] +f65 = getarrayitem_raw(i24, i63, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #230 BINARY_ADD', 0) +f66 = float_add(f61, f65) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #231 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #234 BINARY_MULTIPLY', 0) +f67 = float_mul(f66, f29) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #235 BINARY_ADD', 0) +f68 = float_add(f54, f67) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #236 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #239 BINARY_MULTIPLY', 0) +f69 = float_mul(f68, f30) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #240 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #243 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #246 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #249 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #250 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #253 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #254 STORE_SUBSCR', 0) +i70 = int_lt(i55, i23) +guard_true(i70, descr=<Guard20>) [p1, p0, p14, i55, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p15, f69, None, None, None, None, None, None, f42, None, None, i19, None, None, f11] +setarrayitem_raw(i24, i55, f69, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #255 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #258 LOAD_GLOBAL', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #261 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #264 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #267 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #270 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #271 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #274 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #275 BINARY_SUBSCR', 0) +f71 = getarrayitem_raw(i24, i55, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #276 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #279 BINARY_SUBTRACT', 0) +f72 = float_sub(f71, f42) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #280 CALL_FUNCTION', 0) +i73 = force_token() +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #0 LOAD_FAST', 1) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #3 LOAD_FAST', 1) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #6 BINARY_MULTIPLY', 1) +f74 = float_mul(f72, f72) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #7 RETURN_VALUE', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #283 INPLACE_ADD', 0) +f75 = float_add(f11, f74) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #284 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #287 JUMP_ABSOLUTE', 0) +i77 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i79 = int_sub(i77, 26) +setfield_raw(38968960, i79, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i81 = int_lt(i79, 0) +guard_false(i81, descr=<Guard21>) [p1, p0, p2, p3, p4, p5, p6, p7, p8, p9, p10, p12, p13, p14, p15, f75, None, None, None, None, None, None, None, f42, None, None, i19, None, None, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +jump(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, f75, p12, p13, p14, p15, i19, f42, i35, i33, i20, i21, i22, i23, i24, i25, i26, f27, i36, f29, f30, descr=<Loop0>) +[5ed622d5187e] jit-log-opt-loop} +[5ed622e116d0] {jit-log-opt-loop +# Loop 1 : entry bridge with 188 ops +[p0, p1, p2, p3, i4, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +guard_value(i4, 2, descr=<Guard22>) [i4, p1, p0, p2, p3, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] +guard_class(p9, 19861240, descr=<Guard23>) [p1, p0, p9, p2, p3, p5, i6, p8, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] +i29 = getfield_gc(p9, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +i31 = int_gt(i29, 0) +guard_true(i31, descr=<Guard24>) [p1, p0, p9, p2, p3, p5, i6, p8, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26] +i32 = getfield_gc(p9, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +i33 = getfield_gc(p9, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +i34 = int_add(i32, i33) +i36 = int_sub(i29, 1) +setfield_gc(p9, i34, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p9, i36, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +guard_value(i6, 0, descr=<Guard25>) [i6, p1, p0, p2, p3, p5, p8, p9, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24, p25, p26, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #128 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #131 LOAD_FAST', 0) +guard_nonnull_class(p23, 19886912, descr=<Guard26>) [p1, p0, p23, p2, p3, p5, p8, p9, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #134 LOAD_FAST', 0) +guard_nonnull_class(p24, ConstClass(W_IntObject), descr=<Guard27>) [p1, p0, p24, p2, p3, p5, p8, p9, p23, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p26, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #137 LOAD_FAST', 0) +guard_nonnull_class(p21, ConstClass(W_IntObject), descr=<Guard28>) [p1, p0, p21, p2, p3, p5, p8, p9, p23, p24, p12, p13, p14, p15, p16, p17, p18, p19, p20, p22, p26, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #140 BINARY_MULTIPLY', 0) +i41 = getfield_gc_pure(p24, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i42 = getfield_gc_pure(p21, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i43 = int_mul_ovf(i41, i42) +guard_no_overflow(, descr=<Guard29>) [p1, p0, p21, p24, i43, p2, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p22, p26, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #141 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #144 BINARY_ADD', 0) +i44 = int_add_ovf(i43, i32) +guard_no_overflow(, descr=<Guard30>) [p1, p0, i44, p2, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, i43, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #145 BINARY_SUBSCR', 0) +i45 = getfield_gc(p23, descr=<SignedFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_len 32>) +i47 = int_lt(i44, 0) +guard_false(i47, descr=<Guard31>) [p1, p0, p23, i44, i45, p2, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, None, i32] +i49 = int_lt(i44, i45) +guard_true(i49, descr=<Guard32>) [p1, p0, p23, i44, p2, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, p26, None, i32] +i50 = getfield_gc(p23, descr=<NonGcPtrFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_buffer 24>) +f51 = getarrayitem_raw(i50, i44, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #146 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #149 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #152 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #155 LOAD_CONST', 0) +guard_value(p2, ConstPtr(ptr52), descr=<Guard33>) [p1, p0, p2, p3, p5, p8, p9, p23, p24, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #158 BINARY_SUBTRACT', 0) +i54 = int_sub_ovf(i41, 1) +guard_no_overflow(, descr=<Guard34>) [p1, p0, p24, i54, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #159 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #162 BINARY_MULTIPLY', 0) +i55 = int_mul_ovf(i54, i42) +guard_no_overflow(, descr=<Guard35>) [p1, p0, p21, i55, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p22, p24, i54, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #163 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #166 BINARY_ADD', 0) +i56 = int_add_ovf(i55, i32) +guard_no_overflow(, descr=<Guard36>) [p1, p0, i56, p3, p5, p8, p9, p23, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, i55, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #167 BINARY_SUBSCR', 0) +i58 = int_lt(i56, 0) +guard_false(i58, descr=<Guard37>) [p1, p0, p23, i56, i45, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f51, None, i32] +i59 = int_lt(i56, i45) +guard_true(i59, descr=<Guard38>) [p1, p0, p23, i56, p3, p5, p8, p9, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f51, None, i32] +f60 = getarrayitem_raw(i50, i56, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #168 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #171 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #174 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #177 BINARY_ADD', 0) +i62 = int_add_ovf(i41, 1) +guard_no_overflow(, descr=<Guard39>) [p1, p0, p24, i62, p3, p5, p8, p9, p23, p14, p15, p16, p17, p18, p19, p20, p21, p22, f60, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #178 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #181 BINARY_MULTIPLY', 0) +i63 = int_mul_ovf(i62, i42) +guard_no_overflow(, descr=<Guard40>) [p1, p0, p21, i63, p3, p5, p8, p9, p23, p14, p15, p16, p17, p18, p19, p20, p22, p24, i62, f60, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #182 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #185 BINARY_ADD', 0) +i64 = int_add_ovf(i63, i32) +guard_no_overflow(, descr=<Guard41>) [p1, p0, i64, p3, p5, p8, p9, p23, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, i63, None, f60, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #186 BINARY_SUBSCR', 0) +i66 = int_lt(i64, 0) +guard_false(i66, descr=<Guard42>) [p1, p0, p23, i64, i45, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f60, None, None, f51, None, i32] +i67 = int_lt(i64, i45) +guard_true(i67, descr=<Guard43>) [p1, p0, p23, i64, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, None, None, f60, None, None, f51, None, i32] +f68 = getarrayitem_raw(i50, i64, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #187 BINARY_ADD', 0) +f69 = float_add(f60, f68) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #188 LOAD_FAST', 0) +guard_nonnull_class(p18, 19800744, descr=<Guard44>) [p1, p0, p18, p3, p5, p8, p9, p14, p15, p16, p17, p19, p20, p21, p22, p23, p24, f69, None, None, None, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #191 BINARY_MULTIPLY', 0) +f71 = getfield_gc_pure(p18, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f72 = float_mul(f69, f71) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #192 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #195 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #198 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #201 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #202 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #205 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #206 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #209 BINARY_SUBTRACT', 0) +i74 = int_sub(i44, 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #210 BINARY_SUBSCR', 0) +i76 = int_lt(i74, 0) +guard_false(i76, descr=<Guard45>) [p1, p0, p23, i74, i45, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, f72, None, None, None, None, None, None, f51, None, i32] +i77 = int_lt(i74, i45) +guard_true(i77, descr=<Guard46>) [p1, p0, p23, i74, p3, p5, p8, p9, p14, p15, p16, p17, p18, p19, p20, p21, p22, p24, f72, None, None, None, None, None, None, f51, None, i32] +f78 = getarrayitem_raw(i50, i74, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #211 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #214 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #217 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #220 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #221 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #224 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #225 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #228 BINARY_ADD', 0) +i80 = int_add(i44, 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #229 BINARY_SUBSCR', 0) +i81 = int_lt(i80, i45) +guard_true(i81, descr=<Guard47>) [p1, p0, p23, i80, p3, p5, p8, p9, p15, p16, p17, p18, p19, p20, p21, p22, p24, f78, f72, None, None, None, None, None, None, f51, None, i32] +f82 = getarrayitem_raw(i50, i80, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #230 BINARY_ADD', 0) +f83 = float_add(f78, f82) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #231 LOAD_FAST', 0) +guard_nonnull_class(p17, 19800744, descr=<Guard48>) [p1, p0, p17, p3, p5, p8, p9, p15, p16, p18, p19, p20, p21, p22, p23, p24, f83, None, f72, None, None, None, None, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #234 BINARY_MULTIPLY', 0) +f85 = getfield_gc_pure(p17, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f86 = float_mul(f83, f85) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #235 BINARY_ADD', 0) +f87 = float_add(f72, f86) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #236 LOAD_FAST', 0) +guard_nonnull_class(p19, 19800744, descr=<Guard49>) [p1, p0, p19, p3, p5, p8, p9, p15, p16, p17, p18, p20, p21, p22, p23, p24, f87, None, None, None, None, None, None, None, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #239 BINARY_MULTIPLY', 0) +f89 = getfield_gc_pure(p19, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f90 = float_mul(f87, f89) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #240 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #243 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #246 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #249 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #250 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #253 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #254 STORE_SUBSCR', 0) +setarrayitem_raw(i50, i44, f90, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #255 LOAD_FAST', 0) +guard_nonnull_class(p20, 19800744, descr=<Guard50>) [p1, p0, p20, p3, p5, p8, p9, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #258 LOAD_GLOBAL', 0) +p92 = getfield_gc(p0, descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>) +guard_value(p92, ConstPtr(ptr93), descr=<Guard51>) [p1, p0, p92, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] +p94 = getfield_gc(p92, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p94, descr=<Guard52>) [p1, p0, p94, p92, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] +p96 = getfield_gc(ConstPtr(ptr95), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_nonnull_class(p96, ConstClass(Function), descr=<Guard53>) [p1, p0, p96, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, None, None, None, None, None, None, None, None, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #261 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #264 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #267 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #270 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #271 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #274 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #275 BINARY_SUBSCR', 0) +f98 = getarrayitem_raw(i50, i44, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #276 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #279 BINARY_SUBTRACT', 0) +f99 = float_sub(f98, f51) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #280 CALL_FUNCTION', 0) +p100 = getfield_gc(p96, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>) +guard_value(p100, ConstPtr(ptr101), descr=<Guard54>) [p1, p0, p100, p96, p3, p5, p8, p9, p20, p15, p16, p17, p18, p19, p21, p22, p23, p24, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] +p102 = getfield_gc(p96, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>) +p103 = getfield_gc(p96, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>) +p105 = call(ConstClass(getexecutioncontext), descr=<GcPtrCallDescr>) +p106 = getfield_gc(p105, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>) +i107 = force_token() +p108 = getfield_gc(p105, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_w_tracefunc 72>) +guard_isnull(p108, descr=<Guard55>) [p1, p0, p105, p108, p3, p5, p8, p9, p20, p96, p15, p16, p17, p18, p19, p21, p22, p23, p24, p106, p102, i107, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] +i109 = getfield_gc(p105, descr=<NonGcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_profilefunc 40>) +i110 = int_is_zero(i109) +guard_true(i110, descr=<Guard56>) [p1, p0, p105, p3, p5, p8, p9, p20, p96, p15, p16, p17, p18, p19, p21, p22, p23, p24, p106, p102, i107, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #0 LOAD_FAST', 1) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #3 LOAD_FAST', 1) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #6 BINARY_MULTIPLY', 1) +f111 = float_mul(f99, f99) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #7 RETURN_VALUE', 1) +i112 = int_is_true(i109) +guard_false(i112, descr=<Guard57>) [p1, p0, p105, p3, p5, p8, p9, p20, p96, p15, p16, p17, p18, p19, p21, p22, p23, p24, f111, p106, p102, i107, f99, None, None, None, None, None, None, None, None, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #283 INPLACE_ADD', 0) +f113 = getfield_gc_pure(p20, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f114 = float_add(f113, f111) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #284 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #287 JUMP_ABSOLUTE', 0) +i116 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i118 = int_sub(i116, 26) +setfield_raw(38968960, i118, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i120 = int_lt(i118, 0) +guard_false(i120, descr=<Guard58>) [p1, p0, p3, p5, p8, p9, p15, p16, p17, p18, p19, p21, p22, p23, p24, f114, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, f51, None, i32] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +jump(p0, p1, p3, p5, p8, p9, p15, p16, p17, p18, p19, f114, p21, p22, p23, p24, i32, f51, i36, i34, i33, i41, i42, i45, i50, i55, i63, f71, i43, f85, f89, descr=<Loop0>) +[5ed622ea316e] jit-log-opt-loop} +[5ed62326a846] {jit-log-opt-bridge +# bridge out of Guard 21 with 13 ops +[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] +i18 = force_token() +setfield_gc(p1, i18, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.vable_token 24>) +call_may_force(ConstClass(action_dispatcher), p0, p1, descr=<VoidCallDescr>) +guard_not_forced(, descr=<Guard59>) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i17, f16, f15] +guard_no_exception(, descr=<Guard60>) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i17, f16, f15] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +p21 = new_with_vtable(19800744) +setfield_gc(p21, f15, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +p23 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p23, i17, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +p25 = new_with_vtable(19800744) +setfield_gc(p25, f16, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +jump(p1, p0, ConstPtr(ptr26), p2, 2, p3, 0, 125, p4, p5, ConstPtr(ptr30), ConstPtr(ptr31), ConstPtr(ptr32), ConstPtr(ptr33), ConstPtr(ptr34), p6, p7, p8, p9, p10, p21, p11, p12, p13, p14, p23, p25, descr=<Loop1>) +[5ed62327d096] jit-log-opt-bridge} +[5ed623eb929c] {jit-log-opt-bridge +# bridge out of Guard 3 with 260 ops +[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #290 POP_BLOCK', 0) +p18 = getfield_gc(p3, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>) +guard_class(p3, 19865144, descr=<Guard61>) [p0, p1, p3, p18, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] +i20 = getfield_gc(p3, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>) +guard_value(i20, 1, descr=<Guard62>) [p0, p1, i20, p18, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #291 JUMP_ABSOLUTE', 0) +i23 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i25 = int_sub(i23, 1) +setfield_raw(38968960, i25, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i27 = int_lt(i25, 0) +guard_false(i27, descr=<Guard63>) [p0, p1, p18, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #99 FOR_ITER', 0) +guard_class(p5, 19861240, descr=<Guard64>) [p0, p1, p5, p18, p4, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] +i29 = getfield_gc(p5, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +i31 = int_gt(i29, 0) +guard_true(i31, descr=<Guard65>) [p0, p1, p5, p18, p4, p6, p7, p8, p9, p10, p11, p12, p13, p14, i15, f16, f17] +i32 = getfield_gc(p5, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +i33 = getfield_gc(p5, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +i34 = int_add(i32, i33) +i36 = int_sub(i29, 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #102 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #105 SETUP_LOOP', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #108 LOAD_GLOBAL', 0) +p37 = getfield_gc(p1, descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>) +setfield_gc(p5, i34, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p5, i36, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +guard_value(p37, ConstPtr(ptr38), descr=<Guard66>) [p0, p1, p37, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] +p39 = getfield_gc(p37, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p39, descr=<Guard67>) [p0, p1, p39, p37, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] +p41 = getfield_gc(ConstPtr(ptr40), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_isnull(p41, descr=<Guard68>) [p0, p1, p41, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] +p43 = getfield_gc(ConstPtr(ptr42), descr=<GcPtrFieldDescr pypy.interpreter.module.Module.inst_w_dict 8>) +guard_value(p43, ConstPtr(ptr44), descr=<Guard69>) [p0, p1, p43, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] +p45 = getfield_gc(p43, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p45, descr=<Guard70>) [p0, p1, p45, p43, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] +p47 = getfield_gc(ConstPtr(ptr46), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_value(p47, ConstPtr(ptr48), descr=<Guard71>) [p0, p1, p47, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i32, p18, i15, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #111 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #114 LOAD_FAST', 0) +guard_nonnull_class(p12, ConstClass(W_IntObject), descr=<Guard72>) [p0, p1, p12, p4, p5, p47, p6, p7, p8, p9, p10, p11, p13, i32, p18, i15, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #117 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #120 BINARY_SUBTRACT', 0) +i50 = getfield_gc_pure(p12, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i52 = int_sub_ovf(i50, 1) +guard_no_overflow(, descr=<Guard73>) [p0, p1, p12, i52, p4, p5, p47, p6, p7, p8, p9, p10, p11, p13, i32, p18, i15, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #121 CALL_FUNCTION', 0) +p54 = getfield_gc(ConstPtr(ptr53), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_name 40>) +p55 = getfield_gc(ConstPtr(ptr53), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_defs 32>) +i56 = getfield_gc_pure(p55, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i56, descr=<Guard74>) [p0, p1, p54, p55, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] +p57 = getfield_gc_pure(p55, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +i58 = arraylen_gc(p57, descr=<GcPtrArrayDescr>) +i60 = int_sub(4, i58) +i62 = int_ge(3, i60) +guard_true(i62, descr=<Guard75>) [p0, p1, p54, i60, p55, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] +i63 = int_sub(3, i60) +i64 = getfield_gc_pure(p55, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i64, descr=<Guard76>) [p0, p1, p54, i63, i60, p55, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] +p65 = getfield_gc_pure(p55, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +p66 = getarrayitem_gc(p65, i63, descr=<GcPtrArrayDescr>) +guard_class(p66, ConstClass(W_IntObject), descr=<Guard77>) [p0, p1, p66, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i52, i32, p18, i15, f16, f17] +i68 = getfield_gc_pure(p66, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i69 = int_is_zero(i68) +guard_false(i69, descr=<Guard78>) [p0, p1, i68, i52, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, None, i32, p18, i15, f16, f17] +i72 = int_lt(i68, 0) +guard_false(i72, descr=<Guard79>) [p0, p1, i68, i52, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, None, i32, p18, i15, f16, f17] +i74 = int_lt(1, i52) +guard_true(i74, descr=<Guard80>) [p0, p1, i68, i52, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, None, i32, p18, i15, f16, f17] +i75 = int_sub(i52, 1) +i77 = int_sub(i75, 1) +i78 = uint_floordiv(i77, i68) +i80 = int_add(i78, 1) +i82 = int_lt(i80, 0) +guard_false(i82, descr=<Guard81>) [p0, p1, i68, i80, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p66, i52, i32, p18, i15, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #124 GET_ITER', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +i84 = int_gt(i80, 0) +guard_true(i84, descr=<Guard82>) [p0, p1, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i80, i68, None, None, i32, p18, i15, f16, f17] +i85 = int_add(1, i68) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #128 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #131 LOAD_FAST', 0) +guard_nonnull_class(p13, 19886912, descr=<Guard83>) [p0, p1, p13, p4, p5, p6, p7, p8, p9, p10, p11, p12, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #134 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #137 LOAD_FAST', 0) +guard_nonnull_class(p11, ConstClass(W_IntObject), descr=<Guard84>) [p0, p1, p11, p4, p5, p13, p6, p7, p8, p9, p10, p12, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #140 BINARY_MULTIPLY', 0) +i88 = getfield_gc_pure(p11, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i89 = int_mul_ovf(i32, i88) +guard_no_overflow(, descr=<Guard85>) [p0, p1, p11, i89, p4, p5, p13, p6, p7, p8, p9, p10, p12, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #141 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #144 BINARY_ADD', 0) +i90 = int_add_ovf(i89, 1) +guard_no_overflow(, descr=<Guard86>) [p0, p1, i90, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, i89, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #145 BINARY_SUBSCR', 0) +i91 = getfield_gc(p13, descr=<SignedFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_len 32>) +i93 = int_lt(i90, 0) +guard_false(i93, descr=<Guard87>) [p0, p1, p13, i90, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] +i94 = int_lt(i90, i91) +guard_true(i94, descr=<Guard88>) [p0, p1, p13, i90, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, i78, i85, None, i68, None, None, i32, p18, None, f16, f17] +i95 = getfield_gc(p13, descr=<NonGcPtrFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_buffer 24>) +f96 = getarrayitem_raw(i95, i90, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #146 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #149 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #152 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #155 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #158 BINARY_SUBTRACT', 0) +i98 = int_sub_ovf(i32, 1) +guard_no_overflow(, descr=<Guard89>) [p0, p1, i98, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #159 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #162 BINARY_MULTIPLY', 0) +i99 = int_mul_ovf(i98, i88) +guard_no_overflow(, descr=<Guard90>) [p0, p1, p11, i99, p4, p5, p13, p6, p7, p8, p9, p10, p12, i98, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #163 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #166 BINARY_ADD', 0) +i100 = int_add_ovf(i99, 1) +guard_no_overflow(, descr=<Guard91>) [p0, p1, i100, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, i99, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #167 BINARY_SUBSCR', 0) +i102 = int_lt(i100, 0) +guard_false(i102, descr=<Guard92>) [p0, p1, p13, i100, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +i103 = int_lt(i100, i91) +guard_true(i103, descr=<Guard93>) [p0, p1, p13, i100, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +f104 = getarrayitem_raw(i95, i100, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #168 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #171 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #174 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #177 BINARY_ADD', 0) +i106 = int_add_ovf(i32, 1) +guard_no_overflow(, descr=<Guard94>) [p0, p1, i106, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #178 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #181 BINARY_MULTIPLY', 0) +i107 = int_mul_ovf(i106, i88) +guard_no_overflow(, descr=<Guard95>) [p0, p1, p11, i107, p4, p5, p13, p6, p7, p8, p9, p10, p12, i106, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #182 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #185 BINARY_ADD', 0) +i108 = int_add_ovf(i107, 1) +guard_no_overflow(, descr=<Guard96>) [p0, p1, i108, p4, p5, p13, p6, p7, p8, p9, p10, p11, p12, i107, None, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #186 BINARY_SUBSCR', 0) +i110 = int_lt(i108, 0) +guard_false(i110, descr=<Guard97>) [p0, p1, p13, i108, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +i111 = int_lt(i108, i91) +guard_true(i111, descr=<Guard98>) [p0, p1, p13, i108, p4, p5, p6, p7, p8, p9, p10, p11, p12, None, None, f104, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +f112 = getarrayitem_raw(i95, i108, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #187 BINARY_ADD', 0) +f113 = float_add(f104, f112) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #188 LOAD_FAST', 0) +guard_nonnull_class(p9, 19800744, descr=<Guard99>) [p0, p1, p9, p4, p5, p6, p7, p8, p10, p11, p12, p13, f113, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #191 BINARY_MULTIPLY', 0) +f115 = getfield_gc_pure(p9, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f116 = float_mul(f113, f115) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #192 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #195 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #198 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #201 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #202 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #205 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #206 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #209 BINARY_SUBTRACT', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #210 BINARY_SUBSCR', 0) +i118 = int_lt(i89, 0) +guard_false(i118, descr=<Guard100>) [p0, p1, p13, i89, i91, p4, p5, p6, p7, p8, p9, p10, p11, p12, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +i119 = int_lt(i89, i91) +guard_true(i119, descr=<Guard101>) [p0, p1, p13, i89, p4, p5, p6, p7, p8, p9, p10, p11, p12, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +f120 = getarrayitem_raw(i95, i89, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #211 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #214 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #217 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #220 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #221 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #224 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #225 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #228 BINARY_ADD', 0) +i122 = int_add(i90, 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #229 BINARY_SUBSCR', 0) +i123 = int_lt(i122, i91) +guard_true(i123, descr=<Guard102>) [p0, p1, p13, i122, p4, p5, p6, p7, p8, p9, p10, p11, p12, f120, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +f124 = getarrayitem_raw(i95, i122, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #230 BINARY_ADD', 0) +f125 = float_add(f120, f124) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #231 LOAD_FAST', 0) +guard_nonnull_class(p8, 19800744, descr=<Guard103>) [p0, p1, p8, p4, p5, p6, p7, p9, p10, p11, p12, p13, f125, None, f116, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #234 BINARY_MULTIPLY', 0) +f127 = getfield_gc_pure(p8, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f128 = float_mul(f125, f127) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #235 BINARY_ADD', 0) +f129 = float_add(f116, f128) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #236 LOAD_FAST', 0) +guard_nonnull_class(p10, 19800744, descr=<Guard104>) [p0, p1, p10, p4, p5, p6, p7, p8, p9, p11, p12, p13, f129, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #239 BINARY_MULTIPLY', 0) +f131 = getfield_gc_pure(p10, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f132 = float_mul(f129, f131) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #240 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #243 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #246 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #249 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #250 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #253 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #254 STORE_SUBSCR', 0) +setarrayitem_raw(i95, i90, f132, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #255 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #258 LOAD_GLOBAL', 0) +p134 = getfield_gc(ConstPtr(ptr133), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_nonnull_class(p134, ConstClass(Function), descr=<Guard105>) [p0, p1, p134, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #261 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #264 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #267 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #270 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #271 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #274 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #275 BINARY_SUBSCR', 0) +f136 = getarrayitem_raw(i95, i90, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #276 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #279 BINARY_SUBTRACT', 0) +f137 = float_sub(f136, f96) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #280 CALL_FUNCTION', 0) +p138 = getfield_gc(p134, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>) +guard_value(p138, ConstPtr(ptr139), descr=<Guard106>) [p0, p1, p138, p134, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +p140 = getfield_gc(p134, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>) +p141 = getfield_gc(p134, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>) +p143 = call(ConstClass(getexecutioncontext), descr=<GcPtrCallDescr>) +p144 = getfield_gc(p143, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>) +i145 = force_token() +p146 = getfield_gc(p143, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_w_tracefunc 72>) +guard_isnull(p146, descr=<Guard107>) [p0, p1, p143, p146, p4, p5, p134, p6, p7, p8, p9, p10, p11, p12, p13, p144, i145, p140, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +i147 = getfield_gc(p143, descr=<NonGcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_profilefunc 40>) +i148 = int_is_zero(i147) +guard_true(i148, descr=<Guard108>) [p0, p1, p143, p4, p5, p134, p6, p7, p8, p9, p10, p11, p12, p13, p144, i145, p140, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #0 LOAD_FAST', 1) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #3 LOAD_FAST', 1) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #6 BINARY_MULTIPLY', 1) +f149 = float_mul(f137, f137) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #7 RETURN_VALUE', 1) +i150 = int_is_true(i147) +guard_false(i150, descr=<Guard109>) [p0, p1, p143, p4, p5, p134, p6, p7, p8, p9, p10, p11, p12, p13, f149, p144, i145, p140, f137, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, f17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #283 INPLACE_ADD', 0) +f151 = float_add(f17, f149) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #284 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #287 JUMP_ABSOLUTE', 0) +i153 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i155 = int_sub(i153, 35) +setfield_raw(38968960, i155, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i157 = int_lt(i155, 0) +guard_false(i157, descr=<Guard110>) [p0, p1, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f151, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, f96, None, i78, i85, None, i68, None, None, i32, p18, None, None, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +p159 = new_with_vtable(19865144) +setfield_gc(p159, 291, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>) +setfield_gc(p159, 1, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>) +setfield_gc(p159, p18, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>) +p163 = new_with_vtable(19861240) +setfield_gc(p163, i85, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p163, i78, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +setfield_gc(p163, i68, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +p165 = new_with_vtable(19800744) +setfield_gc(p165, f151, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +p167 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p167, i32, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +p169 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p169, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +p171 = new_with_vtable(19800744) +setfield_gc(p171, f96, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +jump(p1, p0, ConstPtr(ptr172), p159, 2, p4, 0, 125, p5, p163, ConstPtr(ptr176), ConstPtr(ptr177), ConstPtr(ptr178), ConstPtr(ptr179), ConstPtr(ptr180), p6, p7, p8, p9, p10, p165, p11, p12, p13, p167, p169, p171, descr=<Loop1>) +[5ed623fc609b] jit-log-opt-bridge} +[5ed63ea5fa94] {jit-log-opt-bridge +# bridge out of Guard 110 with 23 ops +[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, f12, f13, i14, i15, i16, i17, p18] +i19 = force_token() +setfield_gc(p1, i19, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.vable_token 24>) +call_may_force(ConstClass(action_dispatcher), p0, p1, descr=<VoidCallDescr>) +guard_not_forced(, descr=<Guard111>) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, i14, i17, i16, i15, f12, f13, p18] +guard_no_exception(, descr=<Guard112>) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, i14, i17, i16, i15, f12, f13, p18] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +p22 = new_with_vtable(19865144) +setfield_gc(p22, 291, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>) +setfield_gc(p22, p18, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>) +setfield_gc(p22, 1, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>) +p26 = new_with_vtable(19861240) +setfield_gc(p26, i15, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p26, i14, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +setfield_gc(p26, i16, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +p28 = new_with_vtable(19800744) +setfield_gc(p28, f12, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +p30 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p30, i17, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +p32 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p32, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +p35 = new_with_vtable(19800744) +setfield_gc(p35, f13, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +jump(p1, p0, ConstPtr(ptr36), p22, 2, p2, 0, 125, p3, p26, ConstPtr(ptr40), ConstPtr(ptr41), ConstPtr(ptr42), ConstPtr(ptr43), ConstPtr(ptr44), p4, p5, p6, p7, p8, p28, p9, p10, p11, p30, p32, p35, descr=<Loop1>) +[5ed63ea8ea04] jit-log-opt-bridge} +[5ed640a0a34c] {jit-log-opt-bridge +# bridge out of Guard 58 with 13 ops +[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] +i18 = force_token() +setfield_gc(p1, i18, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.vable_token 24>) +call_may_force(ConstClass(action_dispatcher), p0, p1, descr=<VoidCallDescr>) +guard_not_forced(, descr=<Guard113>) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] +guard_no_exception(, descr=<Guard114>) [p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, f15, f16, i17] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +p21 = new_with_vtable(19800744) +setfield_gc(p21, f15, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +p23 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p23, i17, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +p25 = new_with_vtable(19800744) +setfield_gc(p25, f16, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +jump(p1, p0, ConstPtr(ptr26), p2, 2, p3, 0, 125, p4, p5, ConstPtr(ptr30), ConstPtr(ptr31), ConstPtr(ptr32), ConstPtr(ptr33), ConstPtr(ptr34), p6, p7, p8, p9, p10, p21, p11, p12, p13, p14, p23, p25, descr=<Loop1>) +[5ed640a1e8c2] jit-log-opt-bridge} +[5ed6431fc824] {jit-log-opt-bridge +# bridge out of Guard 24 with 264 ops +[p0, p1, p2, p3, p4, p5, i6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] +guard_value(i6, 0, descr=<Guard115>) [i6, p0, p1, p3, p4, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #290 POP_BLOCK', 0) +p26 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>) +guard_class(p4, 19865144, descr=<Guard116>) [p0, p1, p4, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] +i28 = getfield_gc(p4, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>) +guard_value(i28, 1, descr=<Guard117>) [p0, p1, i28, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #291 JUMP_ABSOLUTE', 0) +i31 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i33 = int_sub(i31, 1) +setfield_raw(38968960, i33, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i35 = int_lt(i33, 0) +guard_false(i35, descr=<Guard118>) [p0, p1, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] +guard_value(p3, ConstPtr(ptr36), descr=<Guard119>) [p0, p1, p3, p26, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #99 FOR_ITER', 0) +guard_class(p7, 19861240, descr=<Guard120>) [p0, p1, p7, p26, p5, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] +i38 = getfield_gc(p7, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +i40 = int_gt(i38, 0) +guard_true(i40, descr=<Guard121>) [p0, p1, p7, p26, p5, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p22, p23, p24] +i41 = getfield_gc(p7, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +i42 = getfield_gc(p7, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +i43 = int_add(i41, i42) +i45 = int_sub(i38, 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #102 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #105 SETUP_LOOP', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #108 LOAD_GLOBAL', 0) +p46 = getfield_gc(p1, descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>) +setfield_gc(p7, i43, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p7, i45, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +guard_value(p46, ConstPtr(ptr47), descr=<Guard122>) [p0, p1, p46, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] +p48 = getfield_gc(p46, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p48, descr=<Guard123>) [p0, p1, p48, p46, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] +p50 = getfield_gc(ConstPtr(ptr49), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_isnull(p50, descr=<Guard124>) [p0, p1, p50, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] +p52 = getfield_gc(ConstPtr(ptr51), descr=<GcPtrFieldDescr pypy.interpreter.module.Module.inst_w_dict 8>) +guard_value(p52, ConstPtr(ptr53), descr=<Guard125>) [p0, p1, p52, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] +p54 = getfield_gc(p52, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p54, descr=<Guard126>) [p0, p1, p54, p52, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] +p56 = getfield_gc(ConstPtr(ptr55), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_value(p56, ConstPtr(ptr57), descr=<Guard127>) [p0, p1, p56, p5, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #111 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #114 LOAD_FAST', 0) +guard_nonnull_class(p20, ConstClass(W_IntObject), descr=<Guard128>) [p0, p1, p20, p5, p7, p56, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p21, p23, p24, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #117 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #120 BINARY_SUBTRACT', 0) +i59 = getfield_gc_pure(p20, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i61 = int_sub_ovf(i59, 1) +guard_no_overflow(, descr=<Guard129>) [p0, p1, p20, i61, p5, p7, p56, p11, p12, p13, p14, p15, p16, p17, p18, p19, p21, p23, p24, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #121 CALL_FUNCTION', 0) +p63 = getfield_gc(ConstPtr(ptr62), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_name 40>) +p64 = getfield_gc(ConstPtr(ptr62), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_defs 32>) +i65 = getfield_gc_pure(p64, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i65, descr=<Guard130>) [p0, p1, p63, p64, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] +p66 = getfield_gc_pure(p64, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +i67 = arraylen_gc(p66, descr=<GcPtrArrayDescr>) +i69 = int_sub(4, i67) +i71 = int_ge(3, i69) +guard_true(i71, descr=<Guard131>) [p0, p1, p63, i69, p64, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] +i72 = int_sub(3, i69) +i73 = getfield_gc_pure(p64, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i73, descr=<Guard132>) [p0, p1, p63, i72, i69, p64, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] +p74 = getfield_gc_pure(p64, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +p75 = getarrayitem_gc(p74, i72, descr=<GcPtrArrayDescr>) +guard_class(p75, ConstClass(W_IntObject), descr=<Guard133>) [p0, p1, p75, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i61, p26, i41] +i77 = getfield_gc_pure(p75, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i78 = int_is_zero(i77) +guard_false(i78, descr=<Guard134>) [p0, p1, i77, i61, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, None, p26, i41] +i81 = int_lt(i77, 0) +guard_false(i81, descr=<Guard135>) [p0, p1, i77, i61, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, None, p26, i41] +i83 = int_lt(1, i61) +guard_true(i83, descr=<Guard136>) [p0, p1, i77, i61, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, None, p26, i41] +i84 = int_sub(i61, 1) +i86 = int_sub(i84, 1) +i87 = uint_floordiv(i86, i77) +i89 = int_add(i87, 1) +i91 = int_lt(i89, 0) +guard_false(i91, descr=<Guard137>) [p0, p1, i77, i89, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, p75, i61, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #124 GET_ITER', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +i93 = int_gt(i89, 0) +guard_true(i93, descr=<Guard138>) [p0, p1, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p21, p23, p24, i89, i77, None, None, p26, i41] +i94 = int_add(1, i77) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #128 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #131 LOAD_FAST', 0) +guard_nonnull_class(p21, 19886912, descr=<Guard139>) [p0, p1, p21, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #134 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #137 LOAD_FAST', 0) +guard_nonnull_class(p19, ConstClass(W_IntObject), descr=<Guard140>) [p0, p1, p19, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p20, p24, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #140 BINARY_MULTIPLY', 0) +i97 = getfield_gc_pure(p19, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i98 = int_mul_ovf(i41, i97) +guard_no_overflow(, descr=<Guard141>) [p0, p1, p19, i98, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p20, p24, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #141 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #144 BINARY_ADD', 0) +i99 = int_add_ovf(i98, 1) +guard_no_overflow(, descr=<Guard142>) [p0, p1, i99, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, i98, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #145 BINARY_SUBSCR', 0) +i100 = getfield_gc(p21, descr=<SignedFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_len 32>) +i102 = int_lt(i99, 0) +guard_false(i102, descr=<Guard143>) [p0, p1, p21, i99, i100, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, None, i87, i94, None, i77, None, None, p26, i41] +i103 = int_lt(i99, i100) +guard_true(i103, descr=<Guard144>) [p0, p1, p21, i99, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, p24, None, i87, i94, None, i77, None, None, p26, i41] +i104 = getfield_gc(p21, descr=<NonGcPtrFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_buffer 24>) +f105 = getarrayitem_raw(i104, i99, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #146 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #149 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #152 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #155 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #158 BINARY_SUBTRACT', 0) +i107 = int_sub_ovf(i41, 1) +guard_no_overflow(, descr=<Guard145>) [p0, p1, i107, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #159 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #162 BINARY_MULTIPLY', 0) +i108 = int_mul_ovf(i107, i97) +guard_no_overflow(, descr=<Guard146>) [p0, p1, p19, i108, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p20, i107, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #163 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #166 BINARY_ADD', 0) +i109 = int_add_ovf(i108, 1) +guard_no_overflow(, descr=<Guard147>) [p0, p1, i109, p5, p7, p21, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, i108, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #167 BINARY_SUBSCR', 0) +i111 = int_lt(i109, 0) +guard_false(i111, descr=<Guard148>) [p0, p1, p21, i109, i100, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +i112 = int_lt(i109, i100) +guard_true(i112, descr=<Guard149>) [p0, p1, p21, i109, p5, p7, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +f113 = getarrayitem_raw(i104, i109, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #168 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #171 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #174 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #177 BINARY_ADD', 0) +i115 = int_add_ovf(i41, 1) +guard_no_overflow(, descr=<Guard150>) [p0, p1, i115, p5, p7, p21, p12, p13, p14, p15, p16, p17, p18, p19, p20, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #178 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #181 BINARY_MULTIPLY', 0) +i116 = int_mul_ovf(i115, i97) +guard_no_overflow(, descr=<Guard151>) [p0, p1, p19, i116, p5, p7, p21, p12, p13, p14, p15, p16, p17, p18, p20, i115, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #182 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #185 BINARY_ADD', 0) +i117 = int_add_ovf(i116, 1) +guard_no_overflow(, descr=<Guard152>) [p0, p1, i117, p5, p7, p21, p12, p13, p14, p15, p16, p17, p18, p19, p20, i116, None, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #186 BINARY_SUBSCR', 0) +i119 = int_lt(i117, 0) +guard_false(i119, descr=<Guard153>) [p0, p1, p21, i117, i100, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +i120 = int_lt(i117, i100) +guard_true(i120, descr=<Guard154>) [p0, p1, p21, i117, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, None, None, f113, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +f121 = getarrayitem_raw(i104, i117, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #187 BINARY_ADD', 0) +f122 = float_add(f113, f121) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #188 LOAD_FAST', 0) +guard_nonnull_class(p16, 19800744, descr=<Guard155>) [p0, p1, p16, p5, p7, p12, p13, p14, p15, p17, p18, p19, p20, p21, f122, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #191 BINARY_MULTIPLY', 0) +f124 = getfield_gc_pure(p16, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f125 = float_mul(f122, f124) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #192 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #195 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #198 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #201 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #202 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #205 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #206 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #209 BINARY_SUBTRACT', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #210 BINARY_SUBSCR', 0) +i127 = int_lt(i98, 0) +guard_false(i127, descr=<Guard156>) [p0, p1, p21, i98, i100, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +i128 = int_lt(i98, i100) +guard_true(i128, descr=<Guard157>) [p0, p1, p21, i98, p5, p7, p12, p13, p14, p15, p16, p17, p18, p19, p20, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +f129 = getarrayitem_raw(i104, i98, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #211 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #214 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #217 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #220 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #221 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #224 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #225 LOAD_CONST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #228 BINARY_ADD', 0) +i131 = int_add(i99, 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #229 BINARY_SUBSCR', 0) +i132 = int_lt(i131, i100) +guard_true(i132, descr=<Guard158>) [p0, p1, p21, i131, p5, p7, p13, p14, p15, p16, p17, p18, p19, p20, f129, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +f133 = getarrayitem_raw(i104, i131, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #230 BINARY_ADD', 0) +f134 = float_add(f129, f133) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #231 LOAD_FAST', 0) +guard_nonnull_class(p15, 19800744, descr=<Guard159>) [p0, p1, p15, p5, p7, p13, p14, p16, p17, p18, p19, p20, p21, f134, None, f125, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #234 BINARY_MULTIPLY', 0) +f136 = getfield_gc_pure(p15, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f137 = float_mul(f134, f136) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #235 BINARY_ADD', 0) +f138 = float_add(f125, f137) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #236 LOAD_FAST', 0) +guard_nonnull_class(p17, 19800744, descr=<Guard160>) [p0, p1, p17, p5, p7, p13, p14, p15, p16, p18, p19, p20, p21, f138, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #239 BINARY_MULTIPLY', 0) +f140 = getfield_gc_pure(p17, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f141 = float_mul(f138, f140) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #240 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #243 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #246 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #249 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #250 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #253 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #254 STORE_SUBSCR', 0) +setarrayitem_raw(i104, i99, f141, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #255 LOAD_FAST', 0) +guard_nonnull_class(p18, 19800744, descr=<Guard161>) [p0, p1, p18, p5, p7, p13, p14, p15, p16, p17, p19, p20, p21, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #258 LOAD_GLOBAL', 0) +p144 = getfield_gc(ConstPtr(ptr143), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_nonnull_class(p144, ConstClass(Function), descr=<Guard162>) [p0, p1, p144, p5, p7, p18, p13, p14, p15, p16, p17, p19, p20, p21, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #261 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #264 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #267 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #270 BINARY_MULTIPLY', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #271 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #274 BINARY_ADD', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #275 BINARY_SUBSCR', 0) +f146 = getarrayitem_raw(i104, i99, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #276 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #279 BINARY_SUBTRACT', 0) +f147 = float_sub(f146, f105) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #280 CALL_FUNCTION', 0) +p148 = getfield_gc(p144, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>) +guard_value(p148, ConstPtr(ptr149), descr=<Guard163>) [p0, p1, p148, p144, p5, p7, p18, p13, p14, p15, p16, p17, p19, p20, p21, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +p150 = getfield_gc(p144, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>) +p151 = getfield_gc(p144, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>) +p153 = call(ConstClass(getexecutioncontext), descr=<GcPtrCallDescr>) +p154 = getfield_gc(p153, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>) +i155 = force_token() +p156 = getfield_gc(p153, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_w_tracefunc 72>) +guard_isnull(p156, descr=<Guard164>) [p0, p1, p153, p156, p5, p7, p18, p144, p13, p14, p15, p16, p17, p19, p20, p21, p150, p154, i155, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +i157 = getfield_gc(p153, descr=<NonGcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_profilefunc 40>) +i158 = int_is_zero(i157) +guard_true(i158, descr=<Guard165>) [p0, p1, p153, p5, p7, p18, p144, p13, p14, p15, p16, p17, p19, p20, p21, p150, p154, i155, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #0 LOAD_FAST', 1) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #3 LOAD_FAST', 1) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #6 BINARY_MULTIPLY', 1) +f159 = float_mul(f147, f147) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #7 RETURN_VALUE', 1) +i160 = int_is_true(i157) +guard_false(i160, descr=<Guard166>) [p0, p1, p153, p5, p7, p18, p144, p13, p14, p15, p16, p17, p19, p20, p21, f159, p150, p154, i155, f147, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #283 INPLACE_ADD', 0) +f161 = getfield_gc_pure(p18, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f162 = float_add(f161, f159) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #284 STORE_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #287 JUMP_ABSOLUTE', 0) +i164 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i166 = int_sub(i164, 34) +setfield_raw(38968960, i166, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i168 = int_lt(i166, 0) +guard_false(i168, descr=<Guard167>) [p0, p1, p5, p7, p13, p14, p15, p16, p17, p19, p20, p21, f162, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, f105, None, i87, i94, None, i77, None, None, p26, i41] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 0) +p170 = new_with_vtable(19865144) +setfield_gc(p170, 291, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>) +setfield_gc(p170, 1, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>) +setfield_gc(p170, p26, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>) +p174 = new_with_vtable(19861240) +setfield_gc(p174, i94, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p174, i87, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +setfield_gc(p174, i77, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +p176 = new_with_vtable(19800744) +setfield_gc(p176, f162, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +p178 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p178, i41, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +p180 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p180, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +p182 = new_with_vtable(19800744) +setfield_gc(p182, f105, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +jump(p1, p0, ConstPtr(ptr183), p170, 2, p5, 0, 125, p7, p174, ConstPtr(ptr187), ConstPtr(ptr188), ConstPtr(ptr189), ConstPtr(ptr190), ConstPtr(ptr191), p13, p14, p15, p16, p17, p176, p19, p20, p21, p178, p180, p182, descr=<Loop1>) +[5ed6432f4a2c] jit-log-opt-bridge} +[5ed66199330c] {jit-log-opt-bridge +# bridge out of Guard 65 with 72 ops +[p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, i14, f15, f16] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #294 POP_BLOCK', 0) +p17 = getfield_gc(p3, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>) +guard_class(p3, 19865144, descr=<Guard168>) [p0, p1, p3, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] +i19 = getfield_gc(p3, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>) +guard_value(i19, 0, descr=<Guard169>) [p0, p1, i19, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #295 LOAD_GLOBAL', 0) +p21 = getfield_gc(p1, descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>) +guard_value(p21, ConstPtr(ptr22), descr=<Guard170>) [p0, p1, p21, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] +p23 = getfield_gc(p21, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p23, descr=<Guard171>) [p0, p1, p23, p21, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] +p25 = getfield_gc(ConstPtr(ptr24), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_nonnull_class(p25, 19905496, descr=<Guard172>) [p0, p1, p25, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #298 LOOKUP_METHOD', 0) +p27 = getfield_gc(p25, descr=<GcPtrFieldDescr pypy.interpreter.module.Module.inst_w_dict 8>) +guard_value(p27, ConstPtr(ptr28), descr=<Guard173>) [p0, p1, p25, p27, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] +p29 = getfield_gc(p27, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p29, descr=<Guard174>) [p0, p1, p25, p29, p27, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] +p31 = getfield_gc(ConstPtr(ptr30), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_value(p31, ConstPtr(ptr32), descr=<Guard175>) [p0, p1, p31, p25, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #301 LOAD_FAST', 0) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #304 CALL_METHOD', 0) +call(ConstClass(set_errno), 0, descr=<VoidCallDescr>) +f36 = call(ConstClass(sqrt), f16, descr=<FloatCallDescr>) +i38 = call(ConstClass(get_errno), descr=<INTCallDescr>) +i39 = float_ne(f36, f36) +guard_false(i39, descr=<Guard176>) [p0, p1, i38, f36, f16, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, None, i14, f15] +i42 = float_eq(f36, inf) +i44 = float_eq(f36, -inf) +i45 = int_or(i42, i44) +i46 = int_is_true(i45) +guard_false(i46, descr=<Guard177>) [p0, p1, i38, f36, f16, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, None, i14, f15] +i47 = int_is_true(i38) +guard_false(i47, descr=<Guard178>) [p0, p1, i38, f36, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f16, i14, f15] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #307 RETURN_VALUE', 0) +guard_isnull(p17, descr=<Guard179>) [p0, p1, p17, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, f36, f16, i14, f15] +p48 = getfield_gc(p1, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestack_w 120>) +setarrayitem_gc(p48, 0, ConstPtr(ptr50), descr=<GcPtrArrayDescr>) +setarrayitem_gc(p48, 1, ConstPtr(ptr52), descr=<GcPtrArrayDescr>) +setarrayitem_gc(p48, 2, ConstPtr(ptr52), descr=<GcPtrArrayDescr>) +setarrayitem_gc(p48, 3, ConstPtr(ptr55), descr=<GcPtrArrayDescr>) +setarrayitem_gc(p48, 4, ConstPtr(ptr55), descr=<GcPtrArrayDescr>) +setarrayitem_gc(p48, 5, ConstPtr(ptr55), descr=<GcPtrArrayDescr>) +setarrayitem_gc(p48, 6, ConstPtr(ptr55), descr=<GcPtrArrayDescr>) +setarrayitem_gc(p48, 7, p5, descr=<GcPtrArrayDescr>) +p60 = getfield_gc(p1, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_fastlocals_w 56>) +setarrayitem_gc(p60, 0, p6, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p60, 1, p7, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p60, 2, p8, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p60, 3, p9, descr=<GcPtrArrayDescr>) +p66 = new_with_vtable(19800744) +setfield_gc(p66, f16, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p60, 4, p66, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p60, 5, p10, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p60, 6, p11, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p60, 7, p12, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p60, 8, p13, descr=<GcPtrArrayDescr>) +p73 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p73, i14, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +setarrayitem_gc(p60, 9, p73, descr=<GcPtrArrayDescr>) +p76 = new_with_vtable(19800744) +setfield_gc(p76, f15, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p60, 10, p76, descr=<GcPtrArrayDescr>) +setfield_gc(p1, 1, descr=<BoolFieldDescr pypy.interpreter.pyframe.PyFrame.inst_frame_finished_execution 148>) +setfield_gc(p1, ConstPtr(ptr79), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_pycode 112>) +setfield_gc(p1, ConstPtr(ptr55), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_lastblock 104>) +setfield_gc(p1, 0, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestackdepth 128>) +setfield_gc(p1, p4, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_exception 88>) +setfield_gc(p1, 0, descr=<BoolFieldDescr pypy.interpreter.pyframe.PyFrame.inst_is_being_profiled 149>) +setfield_gc(p1, 307, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_instr 96>) +p84 = new_with_vtable(19800744) +setfield_gc(p84, f36, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +finish(p84, descr=<DoneWithThisFrameDescrRef object at 0x140bcc0>) +[5ed6619e9448] jit-log-opt-bridge} +[5ed74f2eef6e] {jit-log-opt-loop +# Loop 2 : loop with 394 ops +[p0, p1, p2, p3, p4, p5, p6, p7, i8, f9, i10, i11, p12, p13] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #21 LOAD_FAST', 0) +guard_nonnull_class(p7, 19800744, descr=<Guard180>) [p1, p0, p7, p2, p3, p4, p5, p6, i8] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #24 LOAD_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #27 COMPARE_OP', 0) +f15 = getfield_gc_pure(p7, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +i16 = float_gt(f15, f9) +guard_true(i16, descr=<Guard181>) [p1, p0, p6, p7, p2, p3, p4, p5, i8] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #30 POP_JUMP_IF_FALSE', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #33 LOAD_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #36 POP_JUMP_IF_FALSE', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #39 LOAD_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #42 LOAD_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #45 COMPARE_OP', 0) +i17 = int_ge(i8, i10) +guard_false(i17, descr=<Guard182>) [p1, p0, p5, p2, p3, p4, p6, p7, i8] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #48 POP_JUMP_IF_FALSE', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #55 LOAD_GLOBAL', 0) +p18 = getfield_gc(p0, descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>) +guard_value(p18, ConstPtr(ptr19), descr=<Guard183>) [p1, p0, p18, p2, p3, p4, p5, p6, p7, i8] +p20 = getfield_gc(p18, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p20, descr=<Guard184>) [p1, p0, p20, p18, p2, p3, p4, p5, p6, p7, i8] +p22 = getfield_gc(ConstPtr(ptr21), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_nonnull_class(p22, ConstClass(Function), descr=<Guard185>) [p1, p0, p22, p2, p3, p4, p5, p6, p7, i8] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #58 LOAD_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #61 CALL_FUNCTION', 0) +p24 = getfield_gc(p22, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>) +guard_value(p24, ConstPtr(ptr25), descr=<Guard186>) [p1, p0, p24, p22, p2, p3, p4, p5, p6, p7, i8] +p26 = getfield_gc(p22, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>) +p27 = getfield_gc(p22, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>) +i28 = force_token() +i29 = int_is_zero(i11) +guard_true(i29, descr=<Guard187>) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, p26, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #0 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #3 LOAD_ATTR', 1) +p30 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst_map 48>) +guard_value(p30, ConstPtr(ptr31), descr=<Guard188>) [p1, p0, p12, p4, p30, p2, p3, p22, p5, p6, p7, p26, p13, i28, i8] +p33 = getfield_gc(ConstPtr(ptr32), descr=<GcPtrFieldDescr pypy.objspace.std.typeobject.W_TypeObject.inst__version_tag 16>) +guard_value(p33, ConstPtr(ptr34), descr=<Guard189>) [p1, p0, p12, p4, p33, p2, p3, p22, p5, p6, p7, p26, p13, i28, i8] +p35 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value2 24>) +guard_nonnull_class(p35, 19800744, descr=<Guard190>) [p1, p0, p12, p35, p4, p2, p3, p22, p5, p6, p7, p26, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #6 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #9 LOAD_ATTR', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #12 BINARY_MULTIPLY', 1) +f37 = getfield_gc_pure(p35, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f38 = float_mul(f37, f37) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #13 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #16 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #19 LOAD_ATTR', 1) +p39 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value3 32>) +guard_nonnull_class(p39, 19800744, descr=<Guard191>) [p1, p0, p12, p39, p4, p2, p3, p22, p5, p6, p7, f38, p26, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #22 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #25 LOAD_ATTR', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #28 BINARY_MULTIPLY', 1) +f41 = getfield_gc_pure(p39, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f42 = float_mul(f41, f41) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #29 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #32 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #35 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #38 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #41 BINARY_ADD', 1) +f43 = float_add(f38, f42) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #42 BINARY_DIVIDE', 1) +i45 = float_eq(f43, 0.000000) +guard_false(i45, descr=<Guard192>) [p1, p0, p12, f43, p2, p3, p22, p4, p5, p6, p7, f42, f38, p26, p13, i28, i8] +f47 = float_truediv(0.500000, f43) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #43 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #46 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #49 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #52 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #55 LOAD_ATTR', 1) +p48 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value0 8>) +guard_nonnull_class(p48, ConstClass(W_IntObject), descr=<Guard193>) [p1, p0, p12, p48, p4, p2, p3, p22, p5, p6, p7, f47, f42, f38, p26, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #58 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #61 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #64 LOAD_ATTR', 1) +p50 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value1 16>) +guard_nonnull_class(p50, ConstClass(W_IntObject), descr=<Guard194>) [p1, p0, p12, p50, p4, p2, p3, p22, p5, p6, p7, p48, f47, f42, f38, p26, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #67 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #70 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #73 LOAD_ATTR', 1) +p52 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value4 40>) +guard_nonnull_class(p52, 19886912, descr=<Guard195>) [p1, p0, p12, p52, p4, p2, p3, p22, p5, p6, p7, p50, p48, f47, f42, f38, p26, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #76 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #79 SETUP_LOOP', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #82 LOAD_GLOBAL', 1) +guard_value(p26, ConstPtr(ptr54), descr=<Guard196>) [p1, p0, p12, p26, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p56 = getfield_gc(p26, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p56, descr=<Guard197>) [p1, p0, p12, p56, p26, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p58 = getfield_gc(ConstPtr(ptr57), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_isnull(p58, descr=<Guard198>) [p1, p0, p12, p58, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p60 = getfield_gc(ConstPtr(ptr59), descr=<GcPtrFieldDescr pypy.interpreter.module.Module.inst_w_dict 8>) +guard_value(p60, ConstPtr(ptr61), descr=<Guard199>) [p1, p0, p12, p60, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p62 = getfield_gc(p60, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p62, descr=<Guard200>) [p1, p0, p12, p62, p60, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p64 = getfield_gc(ConstPtr(ptr63), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_value(p64, ConstPtr(ptr65), descr=<Guard201>) [p1, p0, p12, p64, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #85 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #88 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #91 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #94 BINARY_SUBTRACT', 1) +i66 = getfield_gc_pure(p48, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i68 = int_sub_ovf(i66, 1) +guard_no_overflow(, descr=<Guard202>) [p1, p0, p12, p48, i68, p2, p3, p22, p4, p5, p6, p7, p64, p52, p50, None, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #95 CALL_FUNCTION', 1) +p70 = getfield_gc(ConstPtr(ptr69), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_name 40>) +p71 = getfield_gc(ConstPtr(ptr69), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_defs 32>) +i72 = getfield_gc_pure(p71, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i72, descr=<Guard203>) [p1, p0, p12, p70, p71, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p73 = getfield_gc_pure(p71, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +i74 = arraylen_gc(p73, descr=<GcPtrArrayDescr>) +i76 = int_sub(4, i74) +i78 = int_ge(3, i76) +guard_true(i78, descr=<Guard204>) [p1, p0, p12, p70, i76, p71, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i79 = int_sub(3, i76) +i80 = getfield_gc_pure(p71, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i80, descr=<Guard205>) [p1, p0, p12, p70, i79, i76, p71, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p81 = getfield_gc_pure(p71, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +p82 = getarrayitem_gc(p81, i79, descr=<GcPtrArrayDescr>) +guard_class(p82, ConstClass(W_IntObject), descr=<Guard206>) [p1, p0, p12, p82, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i84 = getfield_gc_pure(p82, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i85 = int_is_zero(i84) +guard_false(i85, descr=<Guard207>) [p1, p0, p12, i84, i68, p2, p3, p22, p4, p5, p6, p7, p82, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i87 = int_lt(i84, 0) +guard_false(i87, descr=<Guard208>) [p1, p0, p12, i84, i68, p2, p3, p22, p4, p5, p6, p7, p82, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i89 = int_lt(1, i68) +guard_true(i89, descr=<Guard209>) [p1, p0, p12, i84, i68, p2, p3, p22, p4, p5, p6, p7, p82, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i90 = int_sub(i68, 1) +i92 = int_sub(i90, 1) +i93 = uint_floordiv(i92, i84) +i95 = int_add(i93, 1) +i97 = int_lt(i95, 0) +guard_false(i97, descr=<Guard210>) [p1, p0, p12, i84, i95, p2, p3, p22, p4, p5, p6, p7, p82, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #98 GET_ITER', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #99 FOR_ITER', 1) +i99 = int_gt(i95, 0) +guard_true(i99, descr=<Guard211>) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, i84, i95, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i100 = int_add(1, i84) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #102 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #105 SETUP_LOOP', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #108 LOAD_GLOBAL', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #111 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #114 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #117 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #120 BINARY_SUBTRACT', 1) +i101 = getfield_gc_pure(p50, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i103 = int_sub_ovf(i101, 1) +guard_no_overflow(, descr=<Guard212>) [p1, p0, p12, p50, i103, p2, p3, p22, p4, p5, p6, p7, i100, i93, i84, None, None, None, None, p52, None, p48, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #121 CALL_FUNCTION', 1) +i104 = getfield_gc_pure(p71, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i104, descr=<Guard213>) [p1, p0, p12, p70, p71, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p105 = getfield_gc_pure(p71, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +i106 = arraylen_gc(p105, descr=<GcPtrArrayDescr>) +i108 = int_sub(4, i106) +i110 = int_ge(3, i108) +guard_true(i110, descr=<Guard214>) [p1, p0, p12, p70, i108, p71, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i111 = int_sub(3, i108) +i112 = getfield_gc_pure(p71, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i112, descr=<Guard215>) [p1, p0, p12, p70, i111, i108, p71, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p113 = getfield_gc_pure(p71, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +p114 = getarrayitem_gc(p113, i111, descr=<GcPtrArrayDescr>) +guard_class(p114, ConstClass(W_IntObject), descr=<Guard216>) [p1, p0, p12, p114, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i116 = getfield_gc_pure(p114, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i117 = int_is_zero(i116) +guard_false(i117, descr=<Guard217>) [p1, p0, p12, i116, i103, p2, p3, p22, p4, p5, p6, p7, p114, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i119 = int_lt(i116, 0) +guard_false(i119, descr=<Guard218>) [p1, p0, p12, i116, i103, p2, p3, p22, p4, p5, p6, p7, p114, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i121 = int_lt(1, i103) +guard_true(i121, descr=<Guard219>) [p1, p0, p12, i116, i103, p2, p3, p22, p4, p5, p6, p7, p114, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i122 = int_sub(i103, 1) +i124 = int_sub(i122, 1) +i125 = uint_floordiv(i124, i116) +i127 = int_add(i125, 1) +i129 = int_lt(i127, 0) +guard_false(i129, descr=<Guard220>) [p1, p0, p12, i116, i127, p2, p3, p22, p4, p5, p6, p7, p114, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #124 GET_ITER', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 1) +i131 = int_gt(i127, 0) +guard_true(i131, descr=<Guard221>) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, i116, i127, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +i132 = int_add(1, i116) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #128 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #131 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #134 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #137 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #140 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #141 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #144 BINARY_ADD', 1) +i133 = int_add_ovf(i66, 1) +guard_no_overflow(, descr=<Guard222>) [p1, p0, p12, i133, p2, p3, p22, p4, p5, p6, p7, i132, i125, i66, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #145 BINARY_SUBSCR', 1) +i134 = getfield_gc(p52, descr=<SignedFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_len 32>) +i135 = int_lt(i133, i134) +guard_true(i135, descr=<Guard223>) [p1, p0, p12, p52, i133, p2, p3, p22, p4, p5, p6, p7, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] +i136 = getfield_gc(p52, descr=<NonGcPtrFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_buffer 24>) +f137 = getarrayitem_raw(i136, i133, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #146 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #149 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #152 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #155 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #158 BINARY_SUBTRACT', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #159 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #162 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #163 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #166 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #167 BINARY_SUBSCR', 1) +f138 = getarrayitem_raw(i136, 1, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #168 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #171 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #174 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #177 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #178 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #181 BINARY_MULTIPLY', 1) +i140 = int_mul_ovf(2, i66) +guard_no_overflow(, descr=<Guard224>) [p1, p0, p12, p48, i140, p2, p3, p22, p4, p5, p6, p7, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, None, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #182 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #185 BINARY_ADD', 1) +i141 = int_add_ovf(i140, 1) +guard_no_overflow(, descr=<Guard225>) [p1, p0, p12, i141, p2, p3, p22, p4, p5, p6, p7, i140, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #186 BINARY_SUBSCR', 1) +i143 = int_lt(i141, 0) +guard_false(i143, descr=<Guard226>) [p1, p0, p12, p52, i141, i134, p2, p3, p22, p4, p5, p6, p7, None, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] +i144 = int_lt(i141, i134) +guard_true(i144, descr=<Guard227>) [p1, p0, p12, p52, i141, p2, p3, p22, p4, p5, p6, p7, None, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] +f145 = getarrayitem_raw(i136, i141, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #187 BINARY_ADD', 1) +f146 = float_add(f138, f145) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #188 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #191 BINARY_MULTIPLY', 1) +f147 = float_mul(f146, f42) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #192 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #195 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #198 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #201 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #202 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #205 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #206 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #209 BINARY_SUBTRACT', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #210 BINARY_SUBSCR', 1) +i148 = int_lt(i66, i134) +guard_true(i148, descr=<Guard228>) [p1, p0, p12, p52, i66, p2, p3, p22, p4, p5, p6, p7, f147, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] +f149 = getarrayitem_raw(i136, i66, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #211 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #214 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #217 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #220 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #221 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #224 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #225 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #228 BINARY_ADD', 1) +i151 = int_add(i133, 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #229 BINARY_SUBSCR', 1) +i152 = int_lt(i151, i134) +guard_true(i152, descr=<Guard229>) [p1, p0, p12, p52, i151, p2, p3, p22, p4, p5, p6, p7, f149, f147, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8] +f153 = getarrayitem_raw(i136, i151, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #230 BINARY_ADD', 1) +f154 = float_add(f149, f153) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #231 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #234 BINARY_MULTIPLY', 1) +f155 = float_mul(f154, f38) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #235 BINARY_ADD', 1) +f156 = float_add(f147, f155) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #236 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #239 BINARY_MULTIPLY', 1) +f157 = float_mul(f156, f47) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #240 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #243 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #246 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #249 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #250 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #253 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #254 STORE_SUBSCR', 1) +setarrayitem_raw(i136, i133, f157, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #255 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #258 LOAD_GLOBAL', 1) +p159 = getfield_gc(ConstPtr(ptr158), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_nonnull_class(p159, ConstClass(Function), descr=<Guard230>) [p1, p0, p12, p159, p2, p3, p22, p4, p5, p6, p7, None, None, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #261 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #264 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #267 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #270 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #271 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #274 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #275 BINARY_SUBSCR', 1) +f161 = getarrayitem_raw(i136, i133, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #276 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #279 BINARY_SUBTRACT', 1) +f162 = float_sub(f161, f137) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #280 CALL_FUNCTION', 1) +p163 = getfield_gc(p159, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>) +guard_value(p163, ConstPtr(ptr164), descr=<Guard231>) [p1, p0, p12, p163, p159, p2, p3, p22, p4, p5, p6, p7, f162, None, None, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +p165 = getfield_gc(p159, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>) +p166 = getfield_gc(p159, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>) +i167 = force_token() +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #0 LOAD_FAST', 2) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #3 LOAD_FAST', 2) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #6 BINARY_MULTIPLY', 2) +f168 = float_mul(f162, f162) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #7 RETURN_VALUE', 2) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #283 INPLACE_ADD', 1) +f170 = float_add(0.000000, f168) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #284 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #287 JUMP_ABSOLUTE', 1) +i172 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i174 = int_sub(i172, 100) +setfield_raw(38968960, i174, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i176 = int_lt(i174, 0) +guard_false(i176, descr=<Guard232>) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, f170, None, None, None, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 1) +i177 = force_token() +p179 = new_with_vtable(19809200) +setfield_gc(p179, i28, descr=<SignedFieldDescr JitVirtualRef.virtual_token 8>) +setfield_gc(p12, p179, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>) +setfield_gc(p0, i177, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.vable_token 24>) +p181 = new_with_vtable(19863424) +setfield_gc(p181, p13, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_backref 48>) +setfield_gc(p181, ConstPtr(ptr54), descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>) +setfield_gc(p181, 34, descr=<INTFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_lineno 144>) +setfield_gc(p181, ConstPtr(ptr25), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_pycode 112>) +p184 = new_array(8, descr=<GcPtrArrayDescr>) +p186 = new_with_vtable(19861240) +setfield_gc(p186, i100, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p186, i93, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +setfield_gc(p186, i84, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +setarrayitem_gc(p184, 0, p186, descr=<GcPtrArrayDescr>) +p189 = new_with_vtable(19861240) +setfield_gc(p189, i132, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p189, i125, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +setfield_gc(p189, i116, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +setarrayitem_gc(p184, 1, p189, descr=<GcPtrArrayDescr>) +setfield_gc(p181, p184, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestack_w 120>) +setfield_gc(p181, 125, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_instr 96>) +p193 = new_with_vtable(19865144) +setfield_gc(p193, 291, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>) +setfield_gc(p193, 1, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>) +p197 = new_with_vtable(19865144) +setfield_gc(p197, 295, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>) +setfield_gc(p193, p197, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>) +setfield_gc(p181, p193, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_lastblock 104>) +p200 = new_array(11, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p200, 0, p4, descr=<GcPtrArrayDescr>) +p203 = new_with_vtable(19800744) +setfield_gc(p203, f38, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p200, 1, p203, descr=<GcPtrArrayDescr>) +p206 = new_with_vtable(19800744) +setfield_gc(p206, f42, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p200, 2, p206, descr=<GcPtrArrayDescr>) +p209 = new_with_vtable(19800744) +setfield_gc(p209, f47, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p200, 3, p209, descr=<GcPtrArrayDescr>) +p212 = new_with_vtable(19800744) +setfield_gc(p212, f170, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p200, 4, p212, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p200, 5, p48, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p200, 6, p50, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p200, 7, p52, descr=<GcPtrArrayDescr>) +p218 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p218, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +setarrayitem_gc(p200, 8, p218, descr=<GcPtrArrayDescr>) +p221 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p221, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +setarrayitem_gc(p200, 9, p221, descr=<GcPtrArrayDescr>) +p224 = new_with_vtable(19800744) +setfield_gc(p224, f137, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p200, 10, p224, descr=<GcPtrArrayDescr>) +setfield_gc(p181, p200, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_fastlocals_w 56>) +setfield_gc(p181, 2, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestackdepth 128>) +p235 = call_assembler(p181, p12, ConstPtr(ptr25), p193, 2, ConstPtr(ptr227), 0, 125, p186, p189, ConstPtr(ptr229), ConstPtr(ptr230), ConstPtr(ptr231), ConstPtr(ptr232), ConstPtr(ptr233), ConstPtr(ptr234), p4, p203, p206, p209, p212, p48, p50, p52, p218, p221, p224, descr=<Loop1>) +guard_not_forced(, descr=<Guard233>) [p1, p0, p12, p181, p235, p179, p2, p3, p22, p4, p5, p6, p7, i8] +guard_no_exception(, descr=<Guard234>) [p1, p0, p12, p181, p235, p179, p2, p3, p22, p4, p5, p6, p7, i8] +p236 = getfield_gc(p12, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_w_tracefunc 72>) +guard_isnull(p236, descr=<Guard235>) [p1, p0, p12, p235, p181, p236, p179, p2, p3, p22, p4, p5, p6, p7, i8] +i237 = ptr_eq(p181, p0) +guard_false(i237, descr=<Guard236>) [p1, p0, p12, p235, p181, p179, p2, p3, p22, p4, p5, p6, p7, i8] +i238 = getfield_gc(p12, descr=<NonGcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_profilefunc 40>) +setfield_gc(p181, ConstPtr(ptr239), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_exception 88>) +i240 = int_is_true(i238) +guard_false(i240, descr=<Guard237>) [p1, p0, p235, p181, p12, p179, p2, p3, p22, p4, p5, p6, p7, i8] +p241 = getfield_gc(p181, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_backref 48>) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #64 STORE_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #67 LOAD_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #70 LOAD_CONST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #73 INPLACE_ADD', 0) +i243 = int_add(i8, 1) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #74 STORE_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #77 JUMP_ABSOLUTE', 0) +i245 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i247 = int_sub(i245, 100) +setfield_raw(38968960, i247, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +setfield_gc(p12, p241, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>) +setfield_gc(p179, p181, descr=<GcPtrFieldDescr JitVirtualRef.forced 16>) +setfield_gc(p179, -3, descr=<SignedFieldDescr JitVirtualRef.virtual_token 8>) +i250 = int_lt(i247, 0) +guard_false(i250, descr=<Guard238>) [p1, p0, p2, p3, p4, p5, p6, p235, i243, None] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #21 LOAD_FAST', 0) +jump(p0, p1, p2, p3, p4, p5, p6, p235, i243, f9, i10, i238, p12, p241, descr=<Loop2>) +[5ed74fc965fa] jit-log-opt-loop} +[5ed74fe43ee0] {jit-log-opt-loop +# Loop 3 : entry bridge with 413 ops +[p0, p1, p2, p3, i4, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #21 LOAD_FAST', 0) +guard_value(i4, 0, descr=<Guard239>) [i4, p1, p0, p2, p3, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14] +guard_nonnull_class(p13, 19800744, descr=<Guard240>) [p1, p0, p13, p2, p3, p5, i6, p8, p9, p10, p11, p12, p14] +guard_value(i6, 0, descr=<Guard241>) [i6, p1, p0, p2, p3, p5, p13, p9, p10, p11, p12, p14] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #24 LOAD_FAST', 0) +guard_nonnull_class(p12, 19800744, descr=<Guard242>) [p1, p0, p12, p2, p3, p5, p13, p9, p10, p11, p14] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #27 COMPARE_OP', 0) +f19 = getfield_gc_pure(p13, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f20 = getfield_gc_pure(p12, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +i21 = float_gt(f19, f20) +guard_true(i21, descr=<Guard243>) [p1, p0, p12, p13, p2, p3, p5, p10, p11, p14] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #30 POP_JUMP_IF_FALSE', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #33 LOAD_FAST', 0) +guard_nonnull_class(p11, ConstClass(W_IntObject), descr=<Guard244>) [p1, p0, p11, p2, p3, p5, p10, p12, p13, p14] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #36 POP_JUMP_IF_FALSE', 0) +i23 = getfield_gc_pure(p11, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i24 = int_is_true(i23) +guard_true(i24, descr=<Guard245>) [p1, p0, p11, p2, p3, p5, p10, p12, p13, p14] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #39 LOAD_FAST', 0) +guard_nonnull_class(p14, ConstClass(W_IntObject), descr=<Guard246>) [p1, p0, p14, p2, p3, p5, p10, p11, p12, p13] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #42 LOAD_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #45 COMPARE_OP', 0) +i26 = getfield_gc_pure(p14, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i27 = int_ge(i26, i23) +guard_false(i27, descr=<Guard247>) [p1, p0, p11, p14, p2, p3, p5, p10, p12, p13] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #48 POP_JUMP_IF_FALSE', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #55 LOAD_GLOBAL', 0) +guard_value(p2, ConstPtr(ptr28), descr=<Guard248>) [p1, p0, p2, p3, p5, p10, p11, p12, p13, p14] +p29 = getfield_gc(p0, descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>) +guard_value(p29, ConstPtr(ptr30), descr=<Guard249>) [p1, p0, p29, p3, p5, p10, p11, p12, p13, p14] +p31 = getfield_gc(p29, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p31, descr=<Guard250>) [p1, p0, p31, p29, p3, p5, p10, p11, p12, p13, p14] +p33 = getfield_gc(ConstPtr(ptr32), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_nonnull_class(p33, ConstClass(Function), descr=<Guard251>) [p1, p0, p33, p3, p5, p10, p11, p12, p13, p14] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #58 LOAD_FAST', 0) +guard_nonnull_class(p10, 19852624, descr=<Guard252>) [p1, p0, p10, p3, p5, p33, p11, p12, p13, p14] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #61 CALL_FUNCTION', 0) +p36 = getfield_gc(p33, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>) +guard_value(p36, ConstPtr(ptr37), descr=<Guard253>) [p1, p0, p36, p33, p3, p5, p10, p11, p12, p13, p14] +p38 = getfield_gc(p33, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>) +p39 = getfield_gc(p33, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>) +p41 = call(ConstClass(getexecutioncontext), descr=<GcPtrCallDescr>) +p42 = getfield_gc(p41, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>) +i43 = force_token() +p44 = getfield_gc(p41, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_w_tracefunc 72>) +guard_isnull(p44, descr=<Guard254>) [p1, p0, p41, p44, p3, p5, p33, p10, p11, p12, p13, p14, i43, p42, p38] +i45 = getfield_gc(p41, descr=<NonGcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_profilefunc 40>) +i46 = int_is_zero(i45) +guard_true(i46, descr=<Guard255>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, i43, p42, p38] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #0 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #3 LOAD_ATTR', 1) +p47 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst_map 48>) +guard_value(p47, ConstPtr(ptr48), descr=<Guard256>) [p1, p0, p41, p10, p47, p3, p5, p33, p11, p12, p13, p14, i43, p42, p38] +p50 = getfield_gc(ConstPtr(ptr49), descr=<GcPtrFieldDescr pypy.objspace.std.typeobject.W_TypeObject.inst__version_tag 16>) +guard_value(p50, ConstPtr(ptr51), descr=<Guard257>) [p1, p0, p41, p10, p50, p3, p5, p33, p11, p12, p13, p14, i43, p42, p38] +p52 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value2 24>) +guard_nonnull_class(p52, 19800744, descr=<Guard258>) [p1, p0, p41, p52, p10, p3, p5, p33, p11, p12, p13, p14, i43, p42, p38] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #6 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #9 LOAD_ATTR', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #12 BINARY_MULTIPLY', 1) +f54 = getfield_gc_pure(p52, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f55 = float_mul(f54, f54) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #13 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #16 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #19 LOAD_ATTR', 1) +p56 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value3 32>) +guard_nonnull_class(p56, 19800744, descr=<Guard259>) [p1, p0, p41, p56, p10, p3, p5, p33, p11, p12, p13, p14, f55, i43, p42, p38] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #22 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #25 LOAD_ATTR', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #28 BINARY_MULTIPLY', 1) +f58 = getfield_gc_pure(p56, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +f59 = float_mul(f58, f58) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #29 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #32 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #35 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #38 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #41 BINARY_ADD', 1) +f60 = float_add(f55, f59) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #42 BINARY_DIVIDE', 1) +i62 = float_eq(f60, 0.000000) +guard_false(i62, descr=<Guard260>) [p1, p0, p41, f60, p3, p5, p33, p10, p11, p12, p13, p14, f59, f55, i43, p42, p38] +f64 = float_truediv(0.500000, f60) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #43 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #46 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #49 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #52 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #55 LOAD_ATTR', 1) +p65 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value0 8>) +guard_nonnull_class(p65, ConstClass(W_IntObject), descr=<Guard261>) [p1, p0, p41, p65, p10, p3, p5, p33, p11, p12, p13, p14, f64, f59, f55, i43, p42, p38] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #58 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #61 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #64 LOAD_ATTR', 1) +p67 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value1 16>) +guard_nonnull_class(p67, ConstClass(W_IntObject), descr=<Guard262>) [p1, p0, p41, p67, p10, p3, p5, p33, p11, p12, p13, p14, p65, f64, f59, f55, i43, p42, p38] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #67 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #70 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #73 LOAD_ATTR', 1) +p69 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value4 40>) +guard_nonnull_class(p69, 19886912, descr=<Guard263>) [p1, p0, p41, p69, p10, p3, p5, p33, p11, p12, p13, p14, p67, p65, f64, f59, f55, i43, p42, p38] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #76 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #79 SETUP_LOOP', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #82 LOAD_GLOBAL', 1) +guard_value(p38, ConstPtr(ptr71), descr=<Guard264>) [p1, p0, p41, p38, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] +p73 = getfield_gc(p38, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p73, descr=<Guard265>) [p1, p0, p41, p73, p38, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] +p75 = getfield_gc(ConstPtr(ptr74), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_isnull(p75, descr=<Guard266>) [p1, p0, p41, p75, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] +p77 = getfield_gc(ConstPtr(ptr76), descr=<GcPtrFieldDescr pypy.interpreter.module.Module.inst_w_dict 8>) +guard_value(p77, ConstPtr(ptr78), descr=<Guard267>) [p1, p0, p41, p77, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] +p79 = getfield_gc(p77, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>) +guard_isnull(p79, descr=<Guard268>) [p1, p0, p41, p79, p77, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] +p81 = getfield_gc(ConstPtr(ptr80), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_value(p81, ConstPtr(ptr82), descr=<Guard269>) [p1, p0, p41, p81, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #85 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #88 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #91 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #94 BINARY_SUBTRACT', 1) +i83 = getfield_gc_pure(p65, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i85 = int_sub_ovf(i83, 1) +guard_no_overflow(, descr=<Guard270>) [p1, p0, p41, p65, i85, p3, p5, p33, p10, p11, p12, p13, p14, p81, p69, p67, None, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #95 CALL_FUNCTION', 1) +p87 = getfield_gc(ConstPtr(ptr86), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_name 40>) +p88 = getfield_gc(ConstPtr(ptr86), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_defs 32>) +i89 = getfield_gc_pure(p88, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i89, descr=<Guard271>) [p1, p0, p41, p87, p88, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +p90 = getfield_gc_pure(p88, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +i91 = arraylen_gc(p90, descr=<GcPtrArrayDescr>) +i93 = int_sub(4, i91) +i95 = int_ge(3, i93) +guard_true(i95, descr=<Guard272>) [p1, p0, p41, p87, i93, p88, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i96 = int_sub(3, i93) +i97 = getfield_gc_pure(p88, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i97, descr=<Guard273>) [p1, p0, p41, p87, i96, i93, p88, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +p98 = getfield_gc_pure(p88, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +p99 = getarrayitem_gc(p98, i96, descr=<GcPtrArrayDescr>) +guard_class(p99, ConstClass(W_IntObject), descr=<Guard274>) [p1, p0, p41, p99, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i101 = getfield_gc_pure(p99, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i102 = int_is_zero(i101) +guard_false(i102, descr=<Guard275>) [p1, p0, p41, i101, i85, p3, p5, p33, p10, p11, p12, p13, p14, p99, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i104 = int_lt(i101, 0) +guard_false(i104, descr=<Guard276>) [p1, p0, p41, i101, i85, p3, p5, p33, p10, p11, p12, p13, p14, p99, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i106 = int_lt(1, i85) +guard_true(i106, descr=<Guard277>) [p1, p0, p41, i101, i85, p3, p5, p33, p10, p11, p12, p13, p14, p99, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i107 = int_sub(i85, 1) +i109 = int_sub(i107, 1) +i110 = uint_floordiv(i109, i101) +i112 = int_add(i110, 1) +i114 = int_lt(i112, 0) +guard_false(i114, descr=<Guard278>) [p1, p0, p41, i101, i112, p3, p5, p33, p10, p11, p12, p13, p14, p99, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #98 GET_ITER', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #99 FOR_ITER', 1) +i116 = int_gt(i112, 0) +guard_true(i116, descr=<Guard279>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, i112, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i117 = int_add(1, i101) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #102 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #105 SETUP_LOOP', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #108 LOAD_GLOBAL', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #111 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #114 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #117 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #120 BINARY_SUBTRACT', 1) +i118 = getfield_gc_pure(p67, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i120 = int_sub_ovf(i118, 1) +guard_no_overflow(, descr=<Guard280>) [p1, p0, p41, p67, i120, p3, p5, p33, p10, p11, p12, p13, p14, i110, i117, None, i101, None, None, None, p69, None, p65, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #121 CALL_FUNCTION', 1) +i121 = getfield_gc_pure(p88, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i121, descr=<Guard281>) [p1, p0, p41, p87, p88, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +p122 = getfield_gc_pure(p88, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +i123 = arraylen_gc(p122, descr=<GcPtrArrayDescr>) +i125 = int_sub(4, i123) +i127 = int_ge(3, i125) +guard_true(i127, descr=<Guard282>) [p1, p0, p41, p87, i125, p88, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i128 = int_sub(3, i125) +i129 = getfield_gc_pure(p88, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>) +guard_false(i129, descr=<Guard283>) [p1, p0, p41, p87, i128, i125, p88, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +p130 = getfield_gc_pure(p88, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>) +p131 = getarrayitem_gc(p130, i128, descr=<GcPtrArrayDescr>) +guard_class(p131, ConstClass(W_IntObject), descr=<Guard284>) [p1, p0, p41, p131, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i133 = getfield_gc_pure(p131, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +i134 = int_is_zero(i133) +guard_false(i134, descr=<Guard285>) [p1, p0, p41, i133, i120, p3, p5, p33, p10, p11, p12, p13, p14, p131, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i136 = int_lt(i133, 0) +guard_false(i136, descr=<Guard286>) [p1, p0, p41, i133, i120, p3, p5, p33, p10, p11, p12, p13, p14, p131, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i138 = int_lt(1, i120) +guard_true(i138, descr=<Guard287>) [p1, p0, p41, i133, i120, p3, p5, p33, p10, p11, p12, p13, p14, p131, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i139 = int_sub(i120, 1) +i141 = int_sub(i139, 1) +i142 = uint_floordiv(i141, i133) +i144 = int_add(i142, 1) +i146 = int_lt(i144, 0) +guard_false(i146, descr=<Guard288>) [p1, p0, p41, i133, i144, p3, p5, p33, p10, p11, p12, p13, p14, p131, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #124 GET_ITER', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 1) +i148 = int_gt(i144, 0) +guard_true(i148, descr=<Guard289>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, i144, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +i149 = int_add(1, i133) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #128 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #131 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #134 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #137 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #140 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #141 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #144 BINARY_ADD', 1) +i150 = int_add_ovf(i83, 1) +guard_no_overflow(, descr=<Guard290>) [p1, p0, p41, i150, p3, p5, p33, p10, p11, p12, p13, p14, i83, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #145 BINARY_SUBSCR', 1) +i151 = getfield_gc(p69, descr=<SignedFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_len 32>) +i152 = int_lt(i150, i151) +guard_true(i152, descr=<Guard291>) [p1, p0, p41, p69, i150, p3, p5, p33, p10, p11, p12, p13, p14, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] +i153 = getfield_gc(p69, descr=<NonGcPtrFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_buffer 24>) +f154 = getarrayitem_raw(i153, i150, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #146 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #149 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #152 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #155 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #158 BINARY_SUBTRACT', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #159 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #162 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #163 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #166 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #167 BINARY_SUBSCR', 1) +f155 = getarrayitem_raw(i153, 1, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #168 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #171 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #174 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #177 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #178 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #181 BINARY_MULTIPLY', 1) +i157 = int_mul_ovf(2, i83) +guard_no_overflow(, descr=<Guard292>) [p1, p0, p41, p65, i157, p3, p5, p33, p10, p11, p12, p13, p14, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, None, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #182 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #185 BINARY_ADD', 1) +i158 = int_add_ovf(i157, 1) +guard_no_overflow(, descr=<Guard293>) [p1, p0, p41, i158, p3, p5, p33, p10, p11, p12, p13, p14, i157, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #186 BINARY_SUBSCR', 1) +i160 = int_lt(i158, 0) +guard_false(i160, descr=<Guard294>) [p1, p0, p41, p69, i158, i151, p3, p5, p33, p10, p11, p12, p13, p14, None, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] +i161 = int_lt(i158, i151) +guard_true(i161, descr=<Guard295>) [p1, p0, p41, p69, i158, p3, p5, p33, p10, p11, p12, p13, p14, None, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] +f162 = getarrayitem_raw(i153, i158, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #187 BINARY_ADD', 1) +f163 = float_add(f155, f162) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #188 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #191 BINARY_MULTIPLY', 1) +f164 = float_mul(f163, f59) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #192 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #195 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #198 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #201 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #202 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #205 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #206 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #209 BINARY_SUBTRACT', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #210 BINARY_SUBSCR', 1) +i165 = int_lt(i83, i151) +guard_true(i165, descr=<Guard296>) [p1, p0, p41, p69, i83, p3, p5, p33, p10, p11, p12, p13, p14, f164, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] +f166 = getarrayitem_raw(i153, i83, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #211 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #214 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #217 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #220 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #221 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #224 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #225 LOAD_CONST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #228 BINARY_ADD', 1) +i168 = int_add(i150, 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #229 BINARY_SUBSCR', 1) +i169 = int_lt(i168, i151) +guard_true(i169, descr=<Guard297>) [p1, p0, p41, p69, i168, p3, p5, p33, p10, p11, p12, p13, p14, f166, f164, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None] +f170 = getarrayitem_raw(i153, i168, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #230 BINARY_ADD', 1) +f171 = float_add(f166, f170) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #231 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #234 BINARY_MULTIPLY', 1) +f172 = float_mul(f171, f55) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #235 BINARY_ADD', 1) +f173 = float_add(f164, f172) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #236 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #239 BINARY_MULTIPLY', 1) +f174 = float_mul(f173, f64) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #240 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #243 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #246 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #249 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #250 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #253 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #254 STORE_SUBSCR', 1) +setarrayitem_raw(i153, i150, f174, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #255 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #258 LOAD_GLOBAL', 1) +p176 = getfield_gc(ConstPtr(ptr175), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>) +guard_nonnull_class(p176, ConstClass(Function), descr=<Guard298>) [p1, p0, p41, p176, p3, p5, p33, p10, p11, p12, p13, p14, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #261 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #264 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #267 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #270 BINARY_MULTIPLY', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #271 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #274 BINARY_ADD', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #275 BINARY_SUBSCR', 1) +f178 = getarrayitem_raw(i153, i150, descr=<FloatArrayNoLengthDescr>) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #276 LOAD_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #279 BINARY_SUBTRACT', 1) +f179 = float_sub(f178, f154) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #280 CALL_FUNCTION', 1) +p180 = getfield_gc(p176, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>) +guard_value(p180, ConstPtr(ptr181), descr=<Guard299>) [p1, p0, p41, p180, p176, p3, p5, p33, p10, p11, p12, p13, p14, f179, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +p182 = getfield_gc(p176, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>) +p183 = getfield_gc(p176, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>) +i184 = force_token() +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #0 LOAD_FAST', 2) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #3 LOAD_FAST', 2) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #6 BINARY_MULTIPLY', 2) +f185 = float_mul(f179, f179) +debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #7 RETURN_VALUE', 2) +i186 = int_is_true(i45) +guard_false(i186, descr=<Guard300>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, p182, i184, p176, f185, f179, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #283 INPLACE_ADD', 1) +f188 = float_add(0.000000, f185) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #284 STORE_FAST', 1) +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #287 JUMP_ABSOLUTE', 1) +i190 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i192 = int_sub(i190, 100) +setfield_raw(38968960, i192, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i194 = int_lt(i192, 0) +guard_false(i194, descr=<Guard301>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, f188, None, None, None, None, None, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None] +debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 1) +i195 = force_token() +p197 = new_with_vtable(19809200) +setfield_gc(p197, i43, descr=<SignedFieldDescr JitVirtualRef.virtual_token 8>) +setfield_gc(p41, p197, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>) +setfield_gc(p0, i195, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.vable_token 24>) +p199 = new_with_vtable(19863424) +setfield_gc(p199, p42, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_backref 48>) +setfield_gc(p199, ConstPtr(ptr71), descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>) +setfield_gc(p199, 34, descr=<INTFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_lineno 144>) +setfield_gc(p199, ConstPtr(ptr37), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_pycode 112>) +p202 = new_array(8, descr=<GcPtrArrayDescr>) +p204 = new_with_vtable(19861240) +setfield_gc(p204, i117, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p204, i110, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +setfield_gc(p204, i101, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +setarrayitem_gc(p202, 0, p204, descr=<GcPtrArrayDescr>) +p207 = new_with_vtable(19861240) +setfield_gc(p207, i149, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>) +setfield_gc(p207, i142, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>) +setfield_gc(p207, i133, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>) +setarrayitem_gc(p202, 1, p207, descr=<GcPtrArrayDescr>) +setfield_gc(p199, p202, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestack_w 120>) +setfield_gc(p199, 125, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_instr 96>) +p211 = new_with_vtable(19865144) +setfield_gc(p211, 291, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>) +setfield_gc(p211, 1, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>) +p215 = new_with_vtable(19865144) +setfield_gc(p215, 295, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>) +setfield_gc(p211, p215, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>) +setfield_gc(p199, p211, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_lastblock 104>) +p218 = new_array(11, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p218, 0, p10, descr=<GcPtrArrayDescr>) +p221 = new_with_vtable(19800744) +setfield_gc(p221, f55, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p218, 1, p221, descr=<GcPtrArrayDescr>) +p224 = new_with_vtable(19800744) +setfield_gc(p224, f59, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p218, 2, p224, descr=<GcPtrArrayDescr>) +p227 = new_with_vtable(19800744) +setfield_gc(p227, f64, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p218, 3, p227, descr=<GcPtrArrayDescr>) +p230 = new_with_vtable(19800744) +setfield_gc(p230, f188, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p218, 4, p230, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p218, 5, p65, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p218, 6, p67, descr=<GcPtrArrayDescr>) +setarrayitem_gc(p218, 7, p69, descr=<GcPtrArrayDescr>) +p236 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p236, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +setarrayitem_gc(p218, 8, p236, descr=<GcPtrArrayDescr>) +p239 = new_with_vtable(ConstClass(W_IntObject)) +setfield_gc(p239, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>) +setarrayitem_gc(p218, 9, p239, descr=<GcPtrArrayDescr>) +p242 = new_with_vtable(19800744) +setfield_gc(p242, f154, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>) +setarrayitem_gc(p218, 10, p242, descr=<GcPtrArrayDescr>) +setfield_gc(p199, p218, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_fastlocals_w 56>) +setfield_gc(p199, 2, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestackdepth 128>) +p253 = call_assembler(p199, p41, ConstPtr(ptr37), p211, 2, ConstPtr(ptr245), 0, 125, p204, p207, ConstPtr(ptr247), ConstPtr(ptr248), ConstPtr(ptr249), ConstPtr(ptr250), ConstPtr(ptr251), ConstPtr(ptr252), p10, p221, p224, p227, p230, p65, p67, p69, p236, p239, p242, descr=<Loop1>) +guard_not_forced(, descr=<Guard302>) [p1, p0, p41, p199, p253, p197, p3, p5, p33, p10, p11, p12, p13, p14] +guard_no_exception(, descr=<Guard303>) [p1, p0, p41, p199, p253, p197, p3, p5, p33, p10, p11, p12, p13, p14] +p254 = getfield_gc(p41, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_w_tracefunc 72>) +guard_isnull(p254, descr=<Guard304>) [p1, p0, p41, p253, p199, p254, p197, p3, p5, p33, p10, p11, p12, p13, p14] +i255 = ptr_eq(p199, p0) +guard_false(i255, descr=<Guard305>) [p1, p0, p41, p253, p199, p197, p3, p5, p33, p10, p11, p12, p13, p14] +i256 = getfield_gc(p41, descr=<NonGcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_profilefunc 40>) +setfield_gc(p199, ConstPtr(ptr257), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_exception 88>) +i258 = int_is_true(i256) +guard_false(i258, descr=<Guard306>) [p1, p0, p253, p199, p41, p197, p3, p5, p33, p10, p11, p12, p13, p14] +p259 = getfield_gc(p199, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_backref 48>) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #64 STORE_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #67 LOAD_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #70 LOAD_CONST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #73 INPLACE_ADD', 0) +i261 = int_add(i26, 1) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #74 STORE_FAST', 0) +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #77 JUMP_ABSOLUTE', 0) +i263 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +i265 = int_sub(i263, 100) +setfield_raw(38968960, i265, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>) +setfield_gc(p41, p259, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>) +setfield_gc(p197, p199, descr=<GcPtrFieldDescr JitVirtualRef.forced 16>) +setfield_gc(p197, -3, descr=<SignedFieldDescr JitVirtualRef.virtual_token 8>) +i268 = int_lt(i265, 0) +guard_false(i268, descr=<Guard307>) [p1, p0, p3, p5, p10, p11, p12, p253, i261] +debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #21 LOAD_FAST', 0) +jump(p0, p1, p3, p5, p10, p11, p12, p253, i261, f20, i23, i256, p41, p259, descr=<Loop2>) +[5ed74ff695c8] jit-log-opt-loop} +[5ed8737e9776] {jit-backend-counts +0:493724565 +1:2281802 +2:1283242 +3:993105 +4:2933 +5:2163 +6:2492 +7:1799 +8:963 +9:36 +[5ed8737ee19c] jit-backend-counts} diff --git a/tests/examplefiles/test.rb b/tests/examplefiles/test.rb index 1f609e32..8ac102e6 100644 --- a/tests/examplefiles/test.rb +++ b/tests/examplefiles/test.rb @@ -10,6 +10,9 @@ while x<10000 g=%w{} x=0 +#leere regex +test //, 123 + while x<100 puts"#{g[x]}" x+=1 diff --git a/tests/examplefiles/test.vhdl b/tests/examplefiles/test.vhdl new file mode 100644 index 00000000..426f2375 --- /dev/null +++ b/tests/examplefiles/test.vhdl @@ -0,0 +1,161 @@ +library ieee; +use ieee.std_logic_unsigned.all; +use ieee.std_logic_1164.all; +use ieee.numeric_std.all; + + +entity top_testbench is --test + generic ( -- test + n : integer := 8 -- test + ); -- test +end top_testbench; -- test + + +architecture top_testbench_arch of top_testbench is + + component top is + generic ( + n : integer + ) ; + port ( + clk : in std_logic; + rst : in std_logic; + d1 : in std_logic_vector (n-1 downto 0); + d2 : in std_logic_vector (n-1 downto 0); + operation : in std_logic; + result : out std_logic_vector (2*n-1 downto 0) + ); + end component; + + signal clk : std_logic; + signal rst : std_logic; + signal operation : std_logic; + signal d1 : std_logic_vector (n-1 downto 0); + signal d2 : std_logic_vector (n-1 downto 0); + signal result : std_logic_vector (2*n-1 downto 0); + + type test_type is ( a1, a2, a3, a4, a5, a6, a7, a8, a9, a10); + attribute enum_encoding of my_state : type is "001 010 011 100 111"; +begin + + TESTUNIT : top generic map (n => n) + port map (clk => clk, + rst => rst, + d1 => d1, + d2 => d2, + operation => operation, + result => result); + + clock_process : process + begin + clk <= '0'; + wait for 5 ns; + clk <= '1'; + wait for 5 ns; + end process; + + data_process : process + begin + + -- test case #1 + operation <= '0'; + + rst <= '1'; + wait for 5 ns; + rst <= '0'; + wait for 5 ns; + + d1 <= std_logic_vector(to_unsigned(60, d1'length)); + d2 <= std_logic_vector(to_unsigned(12, d2'length)); + wait for 360 ns; + + assert (result = std_logic_vector(to_unsigned(720, result'length))) + report "Test case #1 failed" severity error; + + -- test case #2 + operation <= '0'; + + rst <= '1'; + wait for 5 ns; + rst <= '0'; + wait for 5 ns; + + d1 <= std_logic_vector(to_unsigned(55, d1'length)); + d2 <= std_logic_vector(to_unsigned(1, d2'length)); + wait for 360 ns; + + assert (result = std_logic_vector(to_unsigned(55, result'length))) + report "Test case #2 failed" severity error; + + -- etc + + end process; + +end top_testbench_arch; + + +configuration testbench_for_top of top_testbench is + for top_testbench_arch + for TESTUNIT : top + use entity work.top(top_arch); + end for; + end for; +end testbench_for_top; + + +function compare(A: std_logic, B: std_Logic) return std_logic is + constant pi : real := 3.14159; + constant half_pi : real := pi / 2.0; + constant cycle_time : time := 2 ns; + constant N, N5 : integer := 5; +begin + if (A = '0' and B = '1') then + return B; + else + return A; + end if ; +end compare; + + +procedure print(P : std_logic_vector(7 downto 0); + U : std_logic_vector(3 downto 0)) is + variable my_line : line; + alias swrite is write [line, string, side, width] ; +begin + swrite(my_line, "sqrt( "); + write(my_line, P); + swrite(my_line, " )= "); + write(my_line, U); + writeline(output, my_line); +end print; + + +entity add32csa is -- one stage of carry save adder for multiplier + port( + b : in std_logic; -- a multiplier bit + a : in std_logic_vector(31 downto 0); -- multiplicand + sum_in : in std_logic_vector(31 downto 0); -- sums from previous stage + cin : in std_logic_vector(31 downto 0); -- carrys from previous stage + sum_out : out std_logic_vector(31 downto 0); -- sums to next stage + cout : out std_logic_vector(31 downto 0)); -- carrys to next stage +end add32csa; + + +ARCHITECTURE circuits of add32csa IS + SIGNAL zero : STD_LOGIC_VECTOR(31 downto 0) := X"00000000"; + SIGNAL aa : std_logic_vector(31 downto 0) := X"00000000"; + + COMPONENT fadd -- duplicates entity port + PoRT(a : in std_logic; + b : in std_logic; + cin : in std_logic; + s : out std_logic; + cout : out std_logic); + end comPonent fadd; + +begin -- circuits of add32csa + aa <= a when b='1' else zero after 1 ns; + stage: for I in 0 to 31 generate + sta: fadd port map(aa(I), sum_in(I), cin(I) , sum_out(I), cout(I)); + end generate stage; +end architecture circuits; -- of add32csa diff --git a/tests/examplefiles/test.xqy b/tests/examplefiles/test.xqy index 92f9d5a6..c626ea96 100644 --- a/tests/examplefiles/test.xqy +++ b/tests/examplefiles/test.xqy @@ -25,13 +25,15 @@ define function whatsit($param as xs:string) as xs:string { element test { 'a' }, attribute foo { "bar" }, fn:doc()[ foo/@bar eq $let ], - //x/with/another/xpath/@attr } + //x/with/another/*/*:version/xpath/@attr } }; let $bride := "Bride" let $test := validate lax { <some>html</some> } let $test := validate strict { <some>html</some> } let $test := validate { <some>html</some> } +let $test := $var1/*:Article (: comment here :) [fn:not()] +let $test := $var1/@*:name/fn:string() let $noop := ordered { $test } let $noop := unordered { $test } diff --git a/tests/examplefiles/test.zep b/tests/examplefiles/test.zep new file mode 100644 index 00000000..4724d4c4 --- /dev/null +++ b/tests/examplefiles/test.zep @@ -0,0 +1,33 @@ +namespace Test; + +use Test\Foo; + +class Bar +{ + protected a; + private b; + public c {set, get}; + + public function __construct(string str, boolean bool) + { + let this->c = str; + this->setC(bool); + let this->b = []; + } + + public function sayHello(string name) + { + echo "Hello " . name; + } + + protected function loops() + { + for a in b { + echo a; + } + loop { + return "boo!"; + } + } + +}
\ No newline at end of file diff --git a/tests/examplefiles/test2.pypylog b/tests/examplefiles/test2.pypylog new file mode 100644 index 00000000..543e21dd --- /dev/null +++ b/tests/examplefiles/test2.pypylog @@ -0,0 +1,120 @@ +[2f1dd6c3b8b7] {jit-log-opt-loop +# Loop 0 (<Function object at 0xb720e550> ds1dr4 dsdr3 ds1dr4) : loop with 115 ops +[p0, p1] ++33: label(p0, p1, descr=TargetToken(-1223434224)) +debug_merge_point(0, 0, '<Function object at 0xb710b120> ds1dr4 dsdr3 ds1dr4') ++33: guard_nonnull_class(p1, 138371488, descr=<Guard2>) [p1, p0] ++54: p3 = getfield_gc_pure(p1, descr=<FieldP pyhaskell.interpreter.haskell.Substitution.inst_rhs 8>) ++57: guard_value(p3, ConstPtr(ptr4), descr=<Guard3>) [p1, p0, p3] ++69: p5 = getfield_gc_pure(p1, descr=<FieldP pyhaskell.interpreter.haskell.Substitution.inst_subst 12>) ++72: p7 = getarrayitem_gc(p5, 0, descr=<ArrayP 4>) ++75: guard_class(p7, 138371552, descr=<Guard4>) [p0, p5, p7] ++88: p9 = getfield_gc(p7, descr=<FieldP pyhaskell.interpreter.haskell.Thunk.inst_application 8>) ++91: guard_nonnull_class(p9, 138373024, descr=<Guard5>) [p0, p5, p7, p9] ++109: p12 = getarrayitem_gc(p5, 1, descr=<ArrayP 4>) ++112: guard_class(p12, 138371552, descr=<Guard6>) [p0, p5, p12, p7] ++125: p14 = getfield_gc(p12, descr=<FieldP pyhaskell.interpreter.haskell.Thunk.inst_application 8>) ++128: guard_nonnull_class(p14, 138373024, descr=<Guard7>) [p0, p5, p12, p14, p7] +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, 'None') ++146: p16 = getfield_gc_pure(p9, descr=<FieldP pyhaskell.interpreter.haskell.Application.inst_function 8>) ++149: guard_value(p16, ConstPtr(ptr17), descr=<Guard8>) [p16, p9, p0, p12, p7] ++161: p18 = getfield_gc_pure(p9, descr=<FieldP pyhaskell.interpreter.haskell.Application3.inst_arg0 12>) ++164: guard_class(p18, 138371648, descr=<Guard9>) [p18, p9, p0, p12, p7] ++177: p20 = getfield_gc_pure(p9, descr=<FieldP pyhaskell.interpreter.haskell.Application3.inst_arg1 16>) ++180: guard_class(p20, 138371648, descr=<Guard10>) [p20, p9, p18, p0, p12, p7] ++193: p22 = getfield_gc_pure(p9, descr=<FieldP pyhaskell.interpreter.haskell.Application3.inst_arg2 20>) ++196: guard_class(p22, 138371936, descr=<Guard11>) [p22, p9, p20, p18, p0, p12, p7] +debug_merge_point(0, 0, 'None') ++209: p24 = getfield_gc_pure(p22, descr=<FieldP pyhaskell.interpreter.haskell.Application.inst_function 8>) ++215: guard_value(p24, ConstPtr(ptr25), descr=<Guard12>) [p24, p22, p9, None, None, p0, p12, p7] ++227: p27 = getfield_gc_pure(p22, descr=<FieldP pyhaskell.interpreter.haskell.Application1.inst_arg0 12>) ++230: guard_class(p27, 138371648, descr=<Guard13>) [p22, p27, p9, None, None, p0, p12, p7] +debug_merge_point(0, 0, '_') +debug_merge_point(0, 0, 'None') ++243: p30 = getfield_gc(ConstPtr(ptr29), descr=<FieldP pyhaskell.interpreter.module.CoreMod.inst_qvars 24>) ++249: i34 = call(ConstClass(ll_dict_lookup_trampoline__v64___simple_call__function_ll), p30, ConstPtr(ptr32), 360200661, descr=<Calli 4 rri EF=4>) ++281: guard_no_exception(, descr=<Guard14>) [p27, p20, p18, i34, p30, None, None, None, p0, p12, p7] ++294: i36 = int_and(i34, -2147483648) ++302: i37 = int_is_true(i36) +guard_false(i37, descr=<Guard15>) [p27, p20, p18, i34, p30, None, None, None, p0, p12, p7] ++311: p38 = getfield_gc(p30, descr=<FieldP dicttable.entries 12>) ++314: p39 = getinteriorfield_gc(p38, i34, descr=<InteriorFieldDescr <FieldP dictentry.value 4>>) ++318: i40 = instance_ptr_eq(p18, p39) +guard_true(i40, descr=<Guard16>) [p27, p20, None, None, None, p0, p12, p7] +debug_merge_point(0, 0, 'None') ++327: i41 = getfield_gc_pure(p20, descr=<FieldS pyhaskell.interpreter.primtype.Int.inst_value 8>) ++330: i42 = getfield_gc_pure(p27, descr=<FieldS pyhaskell.interpreter.primtype.Int.inst_value 8>) ++333: i43 = int_sub(i41, i42) +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, 'None') ++335: i45 = int_eq(0, i43) +guard_false(i45, descr=<Guard17>) [p0, i43, None, None, None, None, p12, p7] +p47 = new_with_vtable(138371648) ++393: setfield_gc(p47, i43, descr=<FieldS pyhaskell.interpreter.primtype.Int.inst_value 8>) +setfield_gc(p7, p47, descr=<FieldP pyhaskell.interpreter.haskell.Thunk.inst_application 8>) ++414: p48 = getfield_gc(p12, descr=<FieldP pyhaskell.interpreter.haskell.Thunk.inst_application 8>) ++420: guard_nonnull_class(p48, 138371648, descr=<Guard18>) [p0, p48, p12, p47, p7] +debug_merge_point(0, 0, '<PrimFunction object at 0x83f3f6c> 1 <Function object at 0xb710b3b0> 1 <Function object at 0xb710b3c0> <PrimFunction object at 0x83f3f3c> 1 dsdr3 <Function object at 0xb710b210> 1') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, '_') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, '<Function object at 0xb710b3d0> dsdr3 dsdr3') +debug_merge_point(0, 0, '<Function object at 0xb710b120> ds1dr4 dsdr3 ds1dr4') ++438: label(p0, p48, p30, p38, descr=TargetToken(-1223434176)) +debug_merge_point(0, 0, '<Function object at 0xb710b120> ds1dr4 dsdr3 ds1dr4') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, '_') +debug_merge_point(0, 0, 'None') ++438: i50 = call(ConstClass(ll_dict_lookup_trampoline__v64___simple_call__function_ll), p30, ConstPtr(ptr32), 360200661, descr=<Calli 4 rri EF=4>) ++464: guard_no_exception(, descr=<Guard19>) [p48, i50, p30, p0] ++477: i51 = int_and(i50, -2147483648) ++485: i52 = int_is_true(i51) +guard_false(i52, descr=<Guard20>) [p48, i50, p30, p0] ++494: p53 = getinteriorfield_gc(p38, i50, descr=<InteriorFieldDescr <FieldP dictentry.value 4>>) ++501: i55 = instance_ptr_eq(ConstPtr(ptr54), p53) +guard_true(i55, descr=<Guard21>) [p48, p0] +debug_merge_point(0, 0, 'None') ++513: i56 = getfield_gc_pure(p48, descr=<FieldS pyhaskell.interpreter.primtype.Int.inst_value 8>) ++516: i58 = int_sub(i56, 1) +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, 'None') ++519: i59 = int_eq(0, i58) +guard_false(i59, descr=<Guard22>) [i58, p48, p0] +debug_merge_point(0, 0, '<PrimFunction object at 0x83f3f6c> 1 <Function object at 0xb710b3b0> 1 <Function object at 0xb710b3c0> <PrimFunction object at 0x83f3f3c> 1 dsdr3 <Function object at 0xb710b210> 1') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, '_') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, 'None') +debug_merge_point(0, 0, '<Function object at 0xb710b3d0> dsdr3 dsdr3') +debug_merge_point(0, 0, '<Function object at 0xb710b120> ds1dr4 dsdr3 ds1dr4') +p61 = new_with_vtable(138371700) +p63 = new_with_vtable(138373024) +p65 = new_with_vtable(138371936) ++606: setfield_gc(p63, ConstPtr(ptr66), descr=<FieldP pyhaskell.interpreter.haskell.Application.inst_function 8>) +p68 = new_with_vtable(138373024) ++632: setfield_gc(p65, ConstPtr(ptr69), descr=<FieldP pyhaskell.interpreter.haskell.Application.inst_function 8>) +p71 = new_with_vtable(138371936) ++658: setfield_gc(p68, ConstPtr(ptr17), descr=<FieldP pyhaskell.interpreter.haskell.Application.inst_function 8>) ++665: setfield_gc(p71, ConstPtr(ptr72), descr=<FieldP pyhaskell.interpreter.haskell.Application1.inst_arg0 12>) ++672: setfield_gc(p68, p71, descr=<FieldP pyhaskell.interpreter.haskell.Application3.inst_arg2 20>) ++675: setfield_gc(p68, p48, descr=<FieldP pyhaskell.interpreter.haskell.Application3.inst_arg1 16>) ++678: setfield_gc(p68, ConstPtr(ptr54), descr=<FieldP pyhaskell.interpreter.haskell.Application3.inst_arg0 12>) +p73 = new_with_vtable(138371648) ++701: setfield_gc(p61, p0, descr=<FieldP pyhaskell.interpreter.haskell.StackElement.inst_next 8>) ++716: setfield_gc(p61, 2, descr=<FieldS pyhaskell.interpreter.haskell.CopyStackElement.inst_index 16>) ++723: setfield_gc(p71, ConstPtr(ptr25), descr=<FieldP pyhaskell.interpreter.haskell.Application.inst_function 8>) ++730: setfield_gc(p65, p68, descr=<FieldP pyhaskell.interpreter.haskell.Application1.inst_arg0 12>) ++733: setfield_gc(p63, p65, descr=<FieldP pyhaskell.interpreter.haskell.Application3.inst_arg2 20>) ++736: setfield_gc(p63, ConstPtr(ptr75), descr=<FieldP pyhaskell.interpreter.haskell.Application3.inst_arg1 16>) ++743: setfield_gc(p63, ConstPtr(ptr54), descr=<FieldP pyhaskell.interpreter.haskell.Application3.inst_arg0 12>) ++750: setfield_gc(p61, p63, descr=<FieldP pyhaskell.interpreter.haskell.CopyStackElement.inst_application 12>) ++753: setfield_gc(p73, i58, descr=<FieldS pyhaskell.interpreter.primtype.Int.inst_value 8>) ++762: jump(p61, p73, p30, p38, descr=TargetToken(-1223434176)) ++775: --end of the loop-- +[2f1dd6da3b99] jit-log-opt-loop} diff --git a/tests/examplefiles/type.lisp b/tests/examplefiles/type.lisp index 9c769379..c02c29df 100644 --- a/tests/examplefiles/type.lisp +++ b/tests/examplefiles/type.lisp @@ -1200,3 +1200,19 @@ Henry Baker: (unless (clos::funcallable-instance-p #'clos::class-name) (fmakunbound 'clos::class-name)) + + +(keywordp :junk) + T + +(keywordp ::junk) + T + +(symbol-name ::junk) + "JUNK" + +(symbol-name :#junk) + "#JUNK" + +(symbol-name :#.junk) + "#.JUNK" diff --git a/tests/examplefiles/unix-io.lid b/tests/examplefiles/unix-io.lid new file mode 100644 index 00000000..617fcaa4 --- /dev/null +++ b/tests/examplefiles/unix-io.lid @@ -0,0 +1,37 @@ +Library: io +Synopsis: A portable IO library +Author: Gail Zacharias +Files: library + streams/defs + streams/stream + streams/sequence-stream + streams/native-buffer + streams/buffer + streams/typed-stream + streams/external-stream + streams/buffered-stream + streams/convenience + streams/wrapper-stream + streams/cleanup-streams + streams/native-speed + streams/async-writes + streams/file-stream + streams/multi-buffered-streams + pprint + print + print-double-integer-kludge + format + buffered-format + format-condition + unix-file-accessor + unix-standard-io + unix-interface + format-out +C-Source-Files: unix-portability.c +Major-Version: 2 +Minor-Version: 1 +Target-Type: dll +Copyright: Original Code is Copyright (c) 1995-2004 Functional Objects, Inc. + All rights reserved. +License: See License.txt in this distribution for details. +Warranty: Distributed WITHOUT WARRANTY OF ANY KIND diff --git a/tests/examplefiles/test.bas b/tests/examplefiles/vbnet_test.bas index af5f2574..af5f2574 100644 --- a/tests/examplefiles/test.bas +++ b/tests/examplefiles/vbnet_test.bas diff --git a/tests/examplefiles/vctreestatus_hg b/tests/examplefiles/vctreestatus_hg new file mode 100644 index 00000000..193ed803 --- /dev/null +++ b/tests/examplefiles/vctreestatus_hg @@ -0,0 +1,4 @@ +M LICENSE +M setup.py +! setup.cfg +? vctreestatus_hg diff --git a/tests/old_run.py b/tests/old_run.py deleted file mode 100644 index 2d6fc368..00000000 --- a/tests/old_run.py +++ /dev/null @@ -1,138 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Pygments unit tests - ~~~~~~~~~~~~~~~~~~ - - Usage:: - - python run.py [testfile ...] - - - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. - :license: BSD, see LICENSE for details. -""" - -import sys, os -import unittest - -from os.path import dirname, basename, join, abspath - -import pygments - -try: - import coverage -except ImportError: - coverage = None - -testdir = abspath(dirname(__file__)) - -failed = [] -total_test_count = 0 -error_test_count = 0 - - -def err(file, what, exc): - print >>sys.stderr, file, 'failed %s:' % what, - print >>sys.stderr, exc - failed.append(file[:-3]) - - -class QuietTestRunner(object): - """Customized test runner for relatively quiet output""" - - def __init__(self, testname, stream=sys.stderr): - self.testname = testname - self.stream = unittest._WritelnDecorator(stream) - - def run(self, test): - global total_test_count - global error_test_count - result = unittest._TextTestResult(self.stream, True, 1) - test(result) - if not result.wasSuccessful(): - self.stream.write(' FAIL:') - result.printErrors() - failed.append(self.testname) - else: - self.stream.write(' ok\n') - total_test_count += result.testsRun - error_test_count += len(result.errors) + len(result.failures) - return result - - -def run_tests(with_coverage=False): - # needed to avoid confusion involving atexit handlers - import logging - - if sys.argv[1:]: - # test only files given on cmdline - files = [entry + '.py' for entry in sys.argv[1:] if entry.startswith('test_')] - else: - files = [entry for entry in os.listdir(testdir) - if (entry.startswith('test_') and entry.endswith('.py'))] - files.sort() - - WIDTH = 85 - - print >>sys.stderr, \ - ('Pygments %s Test Suite running%s, stand by...' % - (pygments.__version__, - with_coverage and " with coverage analysis" or "")).center(WIDTH) - print >>sys.stderr, ('(using Python %s)' % sys.version.split()[0]).center(WIDTH) - print >>sys.stderr, '='*WIDTH - - if with_coverage: - coverage.erase() - coverage.start() - - for testfile in files: - globs = {'__file__': join(testdir, testfile)} - try: - execfile(join(testdir, testfile), globs) - except Exception, exc: - raise - err(testfile, 'execfile', exc) - continue - sys.stderr.write(testfile[:-3] + ': ') - try: - runner = QuietTestRunner(testfile[:-3]) - # make a test suite of all TestCases in the file - tests = [] - for name, thing in globs.iteritems(): - if name.endswith('Test'): - tests.append((name, unittest.makeSuite(thing))) - tests.sort() - suite = unittest.TestSuite() - suite.addTests([x[1] for x in tests]) - runner.run(suite) - except Exception, exc: - err(testfile, 'running test', exc) - - print >>sys.stderr, '='*WIDTH - if failed: - print >>sys.stderr, '%d of %d tests failed.' % \ - (error_test_count, total_test_count) - print >>sys.stderr, 'Tests failed in:', ', '.join(failed) - ret = 1 - else: - if total_test_count == 1: - print >>sys.stderr, '1 test happy.' - else: - print >>sys.stderr, 'All %d tests happy.' % total_test_count - ret = 0 - - if with_coverage: - coverage.stop() - modules = [mod for name, mod in sys.modules.iteritems() - if name.startswith('pygments.') and mod] - coverage.report(modules) - - return ret - - -if __name__ == '__main__': - with_coverage = False - if sys.argv[1:2] == ['-C']: - with_coverage = bool(coverage) - del sys.argv[1] - sys.exit(run_tests(with_coverage)) diff --git a/tests/run.py b/tests/run.py index 954f6f78..e87837e5 100644 --- a/tests/run.py +++ b/tests/run.py @@ -8,41 +8,37 @@ python run.py [testfile ...] - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ +from __future__ import print_function + import sys, os -if sys.version_info >= (3,): - # copy test suite over to "build/lib" and convert it - print ('Copying and converting sources to build/lib/test...') - from distutils.util import copydir_run_2to3 - testroot = os.path.dirname(__file__) - newroot = os.path.join(testroot, '..', 'build/lib/test') - copydir_run_2to3(testroot, newroot) - # make nose believe that we run from the converted dir - os.chdir(newroot) -else: - # only find tests in this directory +# only find tests in this directory +if os.path.dirname(__file__): os.chdir(os.path.dirname(__file__)) try: import nose except ImportError: - print ('nose is required to run the Pygments test suite') + print('nose is required to run the Pygments test suite') sys.exit(1) try: # make sure the current source is first on sys.path sys.path.insert(0, '..') import pygments -except ImportError: - print ('Cannot find Pygments to test: %s' % sys.exc_info()[1]) +except SyntaxError as err: + print('Syntax error: %s' % err) + sys.exit(1) +except ImportError as err: + print('Cannot find Pygments to test: %s' % err) sys.exit(1) else: - print ('Pygments %s test suite running (Python %s)...' % - (pygments.__version__, sys.version.split()[0])) + print('Pygments %s test suite running (Python %s)...' % + (pygments.__version__, sys.version.split()[0])) nose.main() diff --git a/tests/support/tags b/tests/support/tags new file mode 100644 index 00000000..193779f6 --- /dev/null +++ b/tests/support/tags @@ -0,0 +1,36 @@ +!_TAG_FILE_FORMAT 2 /extended format; --format=1 will not append ;" to lines/ +!_TAG_FILE_SORTED 1 /0=unsorted, 1=sorted, 2=foldcase/ +!_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/ +!_TAG_PROGRAM_NAME Exuberant Ctags // +!_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/ +!_TAG_PROGRAM_VERSION 5.8 // +HtmlFormatter test_html_formatter.py 19;" i +HtmlFormatterTest test_html_formatter.py 34;" c +NullFormatter test_html_formatter.py 19;" i +PythonLexer test_html_formatter.py 18;" i +StringIO test_html_formatter.py 13;" i +dirname test_html_formatter.py 16;" i +escape_html test_html_formatter.py 20;" i +fp test_html_formatter.py 27;" v +inspect test_html_formatter.py 15;" i +isfile test_html_formatter.py 16;" i +join test_html_formatter.py 16;" i +os test_html_formatter.py 10;" i +re test_html_formatter.py 11;" i +subprocess test_html_formatter.py 125;" i +support test_html_formatter.py 23;" i +tempfile test_html_formatter.py 14;" i +test_all_options test_html_formatter.py 72;" m class:HtmlFormatterTest +test_correct_output test_html_formatter.py 35;" m class:HtmlFormatterTest +test_ctags test_html_formatter.py 165;" m class:HtmlFormatterTest +test_external_css test_html_formatter.py 48;" m class:HtmlFormatterTest +test_get_style_defs test_html_formatter.py 141;" m class:HtmlFormatterTest +test_lineanchors test_html_formatter.py 98;" m class:HtmlFormatterTest +test_lineanchors_with_startnum test_html_formatter.py 106;" m class:HtmlFormatterTest +test_linenos test_html_formatter.py 82;" m class:HtmlFormatterTest +test_linenos_with_startnum test_html_formatter.py 90;" m class:HtmlFormatterTest +test_unicode_options test_html_formatter.py 155;" m class:HtmlFormatterTest +test_valid_output test_html_formatter.py 114;" m class:HtmlFormatterTest +tokensource test_html_formatter.py 29;" v +uni_open test_html_formatter.py 21;" i +unittest test_html_formatter.py 12;" i diff --git a/tests/test_basic_api.py b/tests/test_basic_api.py index 1e7dff14..be7a4747 100644 --- a/tests/test_basic_api.py +++ b/tests/test_basic_api.py @@ -3,11 +3,12 @@ Pygments basic API tests ~~~~~~~~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ -import os +from __future__ import print_function + import random import unittest @@ -15,7 +16,7 @@ from pygments import lexers, formatters, filters, format from pygments.token import _TokenType, Text from pygments.lexer import RegexLexer from pygments.formatters.img import FontNotFound -from pygments.util import BytesIO, StringIO, bytes, b +from pygments.util import text_type, StringIO, xrange, ClassNotFound import support @@ -28,7 +29,7 @@ test_content = ''.join(test_content) + '\n' def test_lexer_import_all(): # instantiate every lexer, to see if the token type defs are correct - for x in lexers.LEXERS.keys(): + for x in lexers.LEXERS: c = getattr(lexers, x)() @@ -42,6 +43,10 @@ def test_lexer_classes(): "%s: %s attribute wrong" % (cls, attr) result = cls.analyse_text("abc") assert isinstance(result, float) and 0.0 <= result <= 1.0 + result = cls.analyse_text(".abc") + assert isinstance(result, float) and 0.0 <= result <= 1.0 + + assert all(al.lower() == al for al in cls.aliases) inst = cls(opt1="val1", opt2="val2") if issubclass(cls, RegexLexer): @@ -55,17 +60,20 @@ def test_lexer_classes(): assert 'root' in cls._tokens, \ '%s has no root state' % cls - if cls.name == 'XQuery': # XXX temporary + if cls.name in ['XQuery', 'Opa']: # XXX temporary return - tokens = list(inst.get_tokens(test_content)) + try: + tokens = list(inst.get_tokens(test_content)) + except KeyboardInterrupt: + raise KeyboardInterrupt('interrupted %s.get_tokens(): test_content=%r' % (cls.__name__, test_content)) txt = "" for token in tokens: assert isinstance(token, tuple) assert isinstance(token[0], _TokenType) if isinstance(token[1], str): - print repr(token[1]) - assert isinstance(token[1], unicode) + print(repr(token[1])) + assert isinstance(token[1], text_type) txt += token[1] assert txt == test_content, "%s lexer roundtrip failed: %r != %r" % \ (cls.name, test_content, txt) @@ -90,7 +98,10 @@ def test_lexer_options(): if cls.__name__ not in ( 'PythonConsoleLexer', 'RConsoleLexer', 'RubyConsoleLexer', 'SqliteConsoleLexer', 'MatlabSessionLexer', 'ErlangShellLexer', - 'BashSessionLexer', 'LiterateHaskellLexer'): + 'BashSessionLexer', 'LiterateHaskellLexer', 'LiterateAgdaLexer', + 'PostgresConsoleLexer', 'ElixirConsoleLexer', 'JuliaConsoleLexer', + 'RobotFrameworkLexer', 'DylanConsoleLexer', 'ShellSessionLexer', + 'LiterateIdrisLexer'): inst = cls(ensurenl=False) ensure(inst.get_tokens('a\nb'), 'a\nb') inst = cls(ensurenl=False, stripall=True) @@ -118,6 +129,22 @@ def test_get_lexers(): ]: yield verify, func, args + for cls, (_, lname, aliases, _, mimetypes) in lexers.LEXERS.items(): + assert cls == lexers.find_lexer_class(lname).__name__ + + for alias in aliases: + assert cls == lexers.get_lexer_by_name(alias).__class__.__name__ + + for mimetype in mimetypes: + assert cls == lexers.get_lexer_for_mimetype(mimetype).__class__.__name__ + + try: + lexers.get_lexer_by_name(None) + except ClassNotFound: + pass + else: + raise Exception + def test_formatter_public_api(): ts = list(lexers.PythonLexer().get_tokens("def f(): pass")) @@ -144,7 +171,7 @@ def test_formatter_public_api(): pass inst.format(ts, out) - for formatter, info in formatters.FORMATTERS.iteritems(): + for formatter, info in formatters.FORMATTERS.items(): yield verify, formatter, info def test_formatter_encodings(): @@ -154,7 +181,7 @@ def test_formatter_encodings(): fmt = HtmlFormatter() tokens = [(Text, u"ä")] out = format(tokens, fmt) - assert type(out) is unicode + assert type(out) is text_type assert u"ä" in out # encoding option @@ -183,7 +210,7 @@ def test_formatter_unicode_handling(): if formatter.name != 'Raw tokens': out = format(tokens, inst) if formatter.unicodeoutput: - assert type(out) is unicode + assert type(out) is text_type inst = formatter(encoding='utf-8') out = format(tokens, inst) @@ -195,7 +222,7 @@ def test_formatter_unicode_handling(): out = format(tokens, inst) assert type(out) is bytes, '%s: %r' % (formatter, out) - for formatter, info in formatters.FORMATTERS.iteritems(): + for formatter, info in formatters.FORMATTERS.items(): yield verify, formatter @@ -223,16 +250,20 @@ class FiltersTest(unittest.TestCase): 'whitespace': {'spaces': True, 'tabs': True, 'newlines': True}, 'highlight': {'names': ['isinstance', 'lexers', 'x']}, } - for x in filters.FILTERS.keys(): + for x in filters.FILTERS: lx = lexers.PythonLexer() lx.add_filter(x, **filter_args.get(x, {})) - text = open(TESTFILE, 'rb').read().decode('utf-8') + fp = open(TESTFILE, 'rb') + try: + text = fp.read().decode('utf-8') + finally: + fp.close() tokens = list(lx.get_tokens(text)) roundtext = ''.join([t[1] for t in tokens]) if x not in ('whitespace', 'keywordcase'): # these filters change the text - self.assertEquals(roundtext, text, - "lexer roundtrip with %s filter failed" % x) + self.assertEqual(roundtext, text, + "lexer roundtrip with %s filter failed" % x) def test_raiseonerror(self): lx = lexers.PythonLexer() @@ -242,24 +273,32 @@ class FiltersTest(unittest.TestCase): def test_whitespace(self): lx = lexers.PythonLexer() lx.add_filter('whitespace', spaces='%') - text = open(TESTFILE, 'rb').read().decode('utf-8') + fp = open(TESTFILE, 'rb') + try: + text = fp.read().decode('utf-8') + finally: + fp.close() lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))]) - self.failIf(' ' in lxtext) + self.assertFalse(' ' in lxtext) def test_keywordcase(self): lx = lexers.PythonLexer() lx.add_filter('keywordcase', case='capitalize') - text = open(TESTFILE, 'rb').read().decode('utf-8') + fp = open(TESTFILE, 'rb') + try: + text = fp.read().decode('utf-8') + finally: + fp.close() lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))]) - self.assert_('Def' in lxtext and 'Class' in lxtext) + self.assertTrue('Def' in lxtext and 'Class' in lxtext) def test_codetag(self): lx = lexers.PythonLexer() lx.add_filter('codetagify') text = u'# BUG: text' tokens = list(lx.get_tokens(text)) - self.assertEquals('# ', tokens[0][1]) - self.assertEquals('BUG', tokens[1][1]) + self.assertEqual('# ', tokens[0][1]) + self.assertEqual('BUG', tokens[1][1]) def test_codetag_boundary(self): # ticket #368 @@ -267,4 +306,4 @@ class FiltersTest(unittest.TestCase): lx.add_filter('codetagify') text = u'# DEBUG: text' tokens = list(lx.get_tokens(text)) - self.assertEquals('# DEBUG: text', tokens[0][1]) + self.assertEqual('# DEBUG: text', tokens[0][1]) diff --git a/tests/test_clexer.py b/tests/test_clexer.py index c172116c..c995bb2b 100644 --- a/tests/test_clexer.py +++ b/tests/test_clexer.py @@ -3,7 +3,7 @@ Basic CLexer Test ~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ diff --git a/tests/test_cmdline.py b/tests/test_cmdline.py index 15134607..ef14661c 100644 --- a/tests/test_cmdline.py +++ b/tests/test_cmdline.py @@ -3,17 +3,18 @@ Command line test ~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ # Test the command line interface -import sys, os +import io +import sys import unittest -import StringIO from pygments import highlight +from pygments.util import StringIO from pygments.cmdline import main as cmdline_main import support @@ -24,8 +25,8 @@ TESTFILE, TESTDIR = support.location(__file__) def run_cmdline(*args): saved_stdout = sys.stdout saved_stderr = sys.stderr - new_stdout = sys.stdout = StringIO.StringIO() - new_stderr = sys.stderr = StringIO.StringIO() + new_stdout = sys.stdout = StringIO() + new_stderr = sys.stderr = StringIO() try: ret = cmdline_main(["pygmentize"] + list(args)) finally: @@ -38,64 +39,68 @@ class CmdLineTest(unittest.TestCase): def test_L_opt(self): c, o, e = run_cmdline("-L") - self.assertEquals(c, 0) - self.assert_("Lexers" in o and "Formatters" in o and - "Filters" in o and "Styles" in o) + self.assertEqual(c, 0) + self.assertTrue("Lexers" in o and "Formatters" in o and + "Filters" in o and "Styles" in o) c, o, e = run_cmdline("-L", "lexer") - self.assertEquals(c, 0) - self.assert_("Lexers" in o and "Formatters" not in o) + self.assertEqual(c, 0) + self.assertTrue("Lexers" in o and "Formatters" not in o) c, o, e = run_cmdline("-L", "lexers") - self.assertEquals(c, 0) + self.assertEqual(c, 0) def test_O_opt(self): filename = TESTFILE c, o, e = run_cmdline("-Ofull=1,linenos=true,foo=bar", "-fhtml", filename) - self.assertEquals(c, 0) - self.assert_("<html" in o) - self.assert_('class="linenos"' in o) + self.assertEqual(c, 0) + self.assertTrue("<html" in o) + self.assertTrue('class="linenos"' in o) def test_P_opt(self): filename = TESTFILE c, o, e = run_cmdline("-Pfull", "-Ptitle=foo, bar=baz=,", "-fhtml", filename) - self.assertEquals(c, 0) - self.assert_("<title>foo, bar=baz=,</title>" in o) + self.assertEqual(c, 0) + self.assertTrue("<title>foo, bar=baz=,</title>" in o) def test_F_opt(self): filename = TESTFILE c, o, e = run_cmdline("-Fhighlight:tokentype=Name.Blubb," "names=TESTFILE filename", "-fhtml", filename) - self.assertEquals(c, 0) - self.assert_('<span class="n-Blubb' in o) + self.assertEqual(c, 0) + self.assertTrue('<span class="n-Blubb' in o) def test_H_opt(self): c, o, e = run_cmdline("-H", "formatter", "html") - self.assertEquals(c, 0) - self.assert_('HTML' in o) + self.assertEqual(c, 0) + self.assertTrue('HTML' in o) def test_S_opt(self): c, o, e = run_cmdline("-S", "default", "-f", "html", "-O", "linenos=1") - self.assertEquals(c, 0) + self.assertEqual(c, 0) def test_invalid_opts(self): for opts in [("-L", "-lpy"), ("-L", "-fhtml"), ("-L", "-Ox"), ("-a",), ("-Sst", "-lpy"), ("-H",), ("-H", "formatter"),]: - self.assert_(run_cmdline(*opts)[0] == 2) + self.assertTrue(run_cmdline(*opts)[0] == 2) def test_normal(self): # test that cmdline gives the same output as library api from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter filename = TESTFILE - code = open(filename, 'rb').read() + fp = open(filename, 'rb') + try: + code = fp.read() + finally: + fp.close() output = highlight(code, PythonLexer(), HtmlFormatter()) c, o, e = run_cmdline("-lpython", "-fhtml", filename) - self.assertEquals(o, output) - self.assertEquals(e, "") - self.assertEquals(c, 0) + self.assertEqual(o, output) + self.assertEqual(e, "") + self.assertEqual(c, 0) diff --git a/tests/test_examplefiles.py b/tests/test_examplefiles.py index 877cbecf..0547ffd3 100644 --- a/tests/test_examplefiles.py +++ b/tests/test_examplefiles.py @@ -3,18 +3,20 @@ Pygments tests with example files ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ +from __future__ import print_function + import os import pprint import difflib -import cPickle as pickle +import pickle from pygments.lexers import get_lexer_for_filename, get_lexer_by_name from pygments.token import Error -from pygments.util import ClassNotFound, b +from pygments.util import ClassNotFound STORE_OUTPUT = False @@ -31,39 +33,57 @@ def test_example_files(): absfn = os.path.join(testdir, 'examplefiles', fn) if not os.path.isfile(absfn): continue - outfn = os.path.join(outdir, fn) + print(absfn) + code = open(absfn, 'rb').read() try: - lx = get_lexer_for_filename(absfn) - except ClassNotFound: - if "_" not in fn: + code = code.decode('utf-8') + except UnicodeError: + code = code.decode('latin1') + + outfn = os.path.join(outdir, fn) + + lx = None + if '_' in fn: + try: + lx = get_lexer_by_name(fn.split('_')[0]) + except ClassNotFound: + pass + if lx is None: + try: + lx = get_lexer_for_filename(absfn, code=code) + except ClassNotFound: raise AssertionError('file %r has no registered extension, ' 'nor is of the form <lexer>_filename ' 'for overriding, thus no lexer found.' - % fn) - try: - name, rest = fn.split("_", 1) - lx = get_lexer_by_name(name) - except ClassNotFound: - raise AssertionError('no lexer found for file %r' % fn) + % fn) yield check_lexer, lx, absfn, outfn def check_lexer(lx, absfn, outfn): - text = open(absfn, 'rb').read() - text = text.replace(b('\r\n'), b('\n')) - text = text.strip(b('\n')) + b('\n') + fp = open(absfn, 'rb') + try: + text = fp.read() + finally: + fp.close() + text = text.replace(b'\r\n', b'\n') + text = text.strip(b'\n') + b'\n' try: text = text.decode('utf-8') + if text.startswith(u'\ufeff'): + text = text[len(u'\ufeff'):] except UnicodeError: text = text.decode('latin1') ntext = [] tokens = [] for type, val in lx.get_tokens(text): ntext.append(val) - assert type != Error, 'lexer %s generated error token for %s' % \ - (lx, absfn) + assert type != Error, \ + 'lexer %s generated error token for %s: %r at position %d' % \ + (lx, absfn, val, len(u''.join(ntext))) tokens.append((type, val)) if u''.join(ntext) != text: + print('\n'.join(difflib.unified_diff(u''.join(ntext).splitlines(), + text.splitlines()))) raise AssertionError('round trip failed for ' + absfn) # check output against previous run if enabled @@ -85,6 +105,6 @@ def check_lexer(lx, absfn, outfn): if stored_tokens != tokens: f1 = pprint.pformat(stored_tokens) f2 = pprint.pformat(tokens) - print '\n'.join(difflib.unified_diff(f1.splitlines(), - f2.splitlines())) + print('\n'.join(difflib.unified_diff(f1.splitlines(), + f2.splitlines()))) assert False, absfn diff --git a/tests/test_html_formatter.py b/tests/test_html_formatter.py index ae54b919..91225cd3 100644 --- a/tests/test_html_formatter.py +++ b/tests/test_html_formatter.py @@ -3,43 +3,48 @@ Pygments HTML formatter tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ +from __future__ import print_function + +import io import os import re import unittest -import StringIO import tempfile from os.path import join, dirname, isfile +from pygments.util import StringIO from pygments.lexers import PythonLexer from pygments.formatters import HtmlFormatter, NullFormatter from pygments.formatters.html import escape_html -from pygments.util import uni_open import support TESTFILE, TESTDIR = support.location(__file__) -tokensource = list(PythonLexer().get_tokens( - uni_open(TESTFILE, encoding='utf-8').read())) +fp = io.open(TESTFILE, encoding='utf-8') +try: + tokensource = list(PythonLexer().get_tokens(fp.read())) +finally: + fp.close() class HtmlFormatterTest(unittest.TestCase): def test_correct_output(self): hfmt = HtmlFormatter(nowrap=True) - houtfile = StringIO.StringIO() + houtfile = StringIO() hfmt.format(tokensource, houtfile) nfmt = NullFormatter() - noutfile = StringIO.StringIO() + noutfile = StringIO() nfmt.format(tokensource, noutfile) stripped_html = re.sub('<.*?>', '', houtfile.getvalue()) escaped_text = escape_html(noutfile.getvalue()) - self.assertEquals(stripped_html, escaped_text) + self.assertEqual(stripped_html, escaped_text) def test_external_css(self): # test correct behavior @@ -52,13 +57,13 @@ class HtmlFormatterTest(unittest.TestCase): fmt1.format(tokensource, tfile) try: fmt2.format(tokensource, tfile) - self.assert_(isfile(join(TESTDIR, 'fmt2.css'))) + self.assertTrue(isfile(join(TESTDIR, 'fmt2.css'))) except IOError: # test directory not writable pass tfile.close() - self.assert_(isfile(join(dirname(tfile.name), 'fmt1.css'))) + self.assertTrue(isfile(join(dirname(tfile.name), 'fmt1.css'))) os.unlink(join(dirname(tfile.name), 'fmt1.css')) try: os.unlink(join(TESTDIR, 'fmt2.css')) @@ -71,10 +76,42 @@ class HtmlFormatterTest(unittest.TestCase): dict(linenos=True, full=True), dict(linenos=True, full=True, noclasses=True)]: - outfile = StringIO.StringIO() + outfile = StringIO() fmt = HtmlFormatter(**optdict) fmt.format(tokensource, outfile) + def test_linenos(self): + optdict = dict(linenos=True) + outfile = StringIO() + fmt = HtmlFormatter(**optdict) + fmt.format(tokensource, outfile) + html = outfile.getvalue() + self.assertTrue(re.search("<pre>\s+1\s+2\s+3", html)) + + def test_linenos_with_startnum(self): + optdict = dict(linenos=True, linenostart=5) + outfile = StringIO() + fmt = HtmlFormatter(**optdict) + fmt.format(tokensource, outfile) + html = outfile.getvalue() + self.assertTrue(re.search("<pre>\s+5\s+6\s+7", html)) + + def test_lineanchors(self): + optdict = dict(lineanchors="foo") + outfile = StringIO() + fmt = HtmlFormatter(**optdict) + fmt.format(tokensource, outfile) + html = outfile.getvalue() + self.assertTrue(re.search("<pre><a name=\"foo-1\">", html)) + + def test_lineanchors_with_startnum(self): + optdict = dict(lineanchors="foo", linenostart=5) + outfile = StringIO() + fmt = HtmlFormatter(**optdict) + fmt.format(tokensource, outfile) + html = outfile.getvalue() + self.assertTrue(re.search("<pre><a name=\"foo-5\">", html)) + def test_valid_output(self): # test all available wrappers fmt = HtmlFormatter(full=True, linenos=True, noclasses=True, @@ -87,29 +124,34 @@ class HtmlFormatterTest(unittest.TestCase): catname = os.path.join(TESTDIR, 'dtds', 'HTML4.soc') try: import subprocess - ret = subprocess.Popen(['nsgmls', '-s', '-c', catname, pathname], - stdout=subprocess.PIPE).wait() + po = subprocess.Popen(['nsgmls', '-s', '-c', catname, pathname], + stdout=subprocess.PIPE) + ret = po.wait() + output = po.stdout.read() + po.stdout.close() except OSError: # nsgmls not available pass else: - self.failIf(ret, 'nsgmls run reported errors') + if ret: + print(output) + self.assertFalse(ret, 'nsgmls run reported errors') os.unlink(pathname) def test_get_style_defs(self): fmt = HtmlFormatter() sd = fmt.get_style_defs() - self.assert_(sd.startswith('.')) + self.assertTrue(sd.startswith('.')) fmt = HtmlFormatter(cssclass='foo') sd = fmt.get_style_defs() - self.assert_(sd.startswith('.foo')) + self.assertTrue(sd.startswith('.foo')) sd = fmt.get_style_defs('.bar') - self.assert_(sd.startswith('.bar')) + self.assertTrue(sd.startswith('.bar')) sd = fmt.get_style_defs(['.bar', '.baz']) fl = sd.splitlines()[0] - self.assert_('.bar' in fl and '.baz' in fl) + self.assertTrue('.bar' in fl and '.baz' in fl) def test_unicode_options(self): fmt = HtmlFormatter(title=u'Föö', @@ -120,3 +162,19 @@ class HtmlFormatterTest(unittest.TestCase): tfile = os.fdopen(handle, 'w+b') fmt.format(tokensource, tfile) tfile.close() + + def test_ctags(self): + try: + import ctags + except ImportError: + # we can't check without the ctags module, but at least check the exception + self.assertRaises(RuntimeError, HtmlFormatter, tagsfile='support/tags') + else: + # this tagfile says that test_ctags() is on line 165, even if it isn't + # anymore in the actual source + fmt = HtmlFormatter(tagsfile='support/tags', lineanchors='L', + tagurlformat='%(fname)s%(fext)s') + outfile = StringIO() + fmt.format(tokensource, outfile) + self.assertTrue('<a href="test_html_formatter.py#L-165">test_ctags</a>' + in outfile.getvalue()) diff --git a/tests/test_latex_formatter.py b/tests/test_latex_formatter.py index dc8231be..13ae87cd 100644 --- a/tests/test_latex_formatter.py +++ b/tests/test_latex_formatter.py @@ -3,10 +3,12 @@ Pygments LaTeX formatter tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ +from __future__ import print_function + import os import unittest import tempfile @@ -22,7 +24,11 @@ TESTFILE, TESTDIR = support.location(__file__) class LatexFormatterTest(unittest.TestCase): def test_valid_output(self): - tokensource = list(PythonLexer().get_tokens(open(TESTFILE).read())) + fp = open(TESTFILE) + try: + tokensource = list(PythonLexer().get_tokens(fp.read())) + finally: + fp.close() fmt = LatexFormatter(full=True, encoding='latin1') handle, pathname = tempfile.mkstemp('.tex') @@ -34,14 +40,18 @@ class LatexFormatterTest(unittest.TestCase): tfile.close() try: import subprocess - ret = subprocess.Popen(['latex', '-interaction=nonstopmode', - pathname], - stdout=subprocess.PIPE).wait() + po = subprocess.Popen(['latex', '-interaction=nonstopmode', + pathname], stdout=subprocess.PIPE) + ret = po.wait() + output = po.stdout.read() + po.stdout.close() except OSError: # latex not available pass else: - self.failIf(ret, 'latex run reported errors') + if ret: + print(output) + self.assertFalse(ret, 'latex run reported errors') os.unlink(pathname) os.chdir(old_wd) diff --git a/tests/test_lexers_other.py b/tests/test_lexers_other.py new file mode 100644 index 00000000..91b0dc70 --- /dev/null +++ b/tests/test_lexers_other.py @@ -0,0 +1,68 @@ +# -*- coding: utf-8 -*- +""" + Tests for other lexers + ~~~~~~~~~~~~~~~~~~~~~~ + + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import glob +import os +import unittest + +from pygments.lexers import guess_lexer +from pygments.lexers.other import RexxLexer + + +def _exampleFilePath(filename): + return os.path.join(os.path.dirname(__file__), 'examplefiles', filename) + + +class AnalyseTextTest(unittest.TestCase): + def _testCanRecognizeAndGuessExampleFiles(self, lexer): + assert lexer is not None + + for pattern in lexer.filenames: + exampleFilesPattern = _exampleFilePath(pattern) + for exampleFilePath in glob.glob(exampleFilesPattern): + exampleFile = open(exampleFilePath, 'rb') + try: + text = exampleFile.read().decode('utf-8') + probability = lexer.analyse_text(text) + self.assertTrue(probability > 0, + '%s must recognize %r' % ( + lexer.name, exampleFilePath)) + guessedLexer = guess_lexer(text) + self.assertEqual(guessedLexer.name, lexer.name) + finally: + exampleFile.close() + + def testCanRecognizeAndGuessExampleFiles(self): + self._testCanRecognizeAndGuessExampleFiles(RexxLexer) + + +class RexxLexerTest(unittest.TestCase): + def testCanGuessFromText(self): + self.assertAlmostEqual(0.01, + RexxLexer.analyse_text('/* */')) + self.assertAlmostEqual(1.0, + RexxLexer.analyse_text('''/* Rexx */ + say "hello world"''')) + val = RexxLexer.analyse_text('/* */\n' + 'hello:pRoceduRe\n' + ' say "hello world"') + self.assertTrue(val > 0.5, val) + val = RexxLexer.analyse_text('''/* */ + if 1 > 0 then do + say "ok" + end + else do + say "huh?" + end''') + self.assertTrue(val > 0.2, val) + val = RexxLexer.analyse_text('''/* */ + greeting = "hello world!" + parse value greeting "hello" name "!" + say name''') + self.assertTrue(val > 0.2, val) diff --git a/tests/test_perllexer.py b/tests/test_perllexer.py new file mode 100644 index 00000000..bfa3aeb8 --- /dev/null +++ b/tests/test_perllexer.py @@ -0,0 +1,137 @@ +# -*- coding: utf-8 -*- +""" + Pygments regex lexer tests + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. + :license: BSD, see LICENSE for details. +""" + +import time +import unittest + +from pygments.token import String +from pygments.lexers.agile import PerlLexer + + +class RunawayRegexTest(unittest.TestCase): + # A previous version of the Perl lexer would spend a great deal of + # time backtracking when given particular strings. These tests show that + # the runaway backtracking doesn't happen any more (at least for the given + # cases). + + lexer = PerlLexer() + + ### Test helpers. + + def assert_single_token(self, s, token): + """Show that a given string generates only one token.""" + tokens = list(self.lexer.get_tokens_unprocessed(s)) + self.assertEqual(len(tokens), 1, tokens) + self.assertEqual(s, tokens[0][2]) + self.assertEqual(token, tokens[0][1]) + + def assert_tokens(self, strings, expected_tokens): + """Show that a given string generates the expected tokens.""" + tokens = list(self.lexer.get_tokens_unprocessed(''.join(strings))) + self.assertEqual(len(tokens), len(expected_tokens), tokens) + for index, s in enumerate(strings): + self.assertEqual(s, tokens[index][2]) + self.assertEqual(expected_tokens[index], tokens[index][1]) + + def assert_fast_tokenization(self, s): + """Show that a given string is tokenized quickly.""" + start = time.time() + tokens = list(self.lexer.get_tokens_unprocessed(s)) + end = time.time() + # Isn't 10 seconds kind of a long time? Yes, but we don't want false + # positives when the tests are starved for CPU time. + if end-start > 10: + self.fail('tokenization took too long') + return tokens + + ### Strings. + + def test_single_quote_strings(self): + self.assert_single_token(r"'foo\tbar\\\'baz'", String) + self.assert_fast_tokenization("'" + '\\'*999) + + def test_double_quote_strings(self): + self.assert_single_token(r'"foo\tbar\\\"baz"', String) + self.assert_fast_tokenization('"' + '\\'*999) + + def test_backtick_strings(self): + self.assert_single_token(r'`foo\tbar\\\`baz`', String.Backtick) + self.assert_fast_tokenization('`' + '\\'*999) + + ### Regex matches with various delimiters. + + def test_match(self): + self.assert_single_token(r'/aa\tbb/', String.Regex) + self.assert_fast_tokenization('/' + '\\'*999) + + def test_match_with_slash(self): + self.assert_tokens(['m', '/\n\\t\\\\/'], [String.Regex, String.Regex]) + self.assert_fast_tokenization('m/xxx\n' + '\\'*999) + + def test_match_with_bang(self): + self.assert_tokens(['m', r'!aa\t\!bb!'], [String.Regex, String.Regex]) + self.assert_fast_tokenization('m!' + '\\'*999) + + def test_match_with_brace(self): + self.assert_tokens(['m', r'{aa\t\}bb}'], [String.Regex, String.Regex]) + self.assert_fast_tokenization('m{' + '\\'*999) + + def test_match_with_angle_brackets(self): + self.assert_tokens(['m', r'<aa\t\>bb>'], [String.Regex, String.Regex]) + self.assert_fast_tokenization('m<' + '\\'*999) + + def test_match_with_parenthesis(self): + self.assert_tokens(['m', r'(aa\t\)bb)'], [String.Regex, String.Regex]) + self.assert_fast_tokenization('m(' + '\\'*999) + + def test_match_with_at_sign(self): + self.assert_tokens(['m', r'@aa\t\@bb@'], [String.Regex, String.Regex]) + self.assert_fast_tokenization('m@' + '\\'*999) + + def test_match_with_percent_sign(self): + self.assert_tokens(['m', r'%aa\t\%bb%'], [String.Regex, String.Regex]) + self.assert_fast_tokenization('m%' + '\\'*999) + + def test_match_with_dollar_sign(self): + self.assert_tokens(['m', r'$aa\t\$bb$'], [String.Regex, String.Regex]) + self.assert_fast_tokenization('m$' + '\\'*999) + + ### Regex substitutions with various delimeters. + + def test_substitution_with_slash(self): + self.assert_single_token('s/aaa/bbb/g', String.Regex) + self.assert_fast_tokenization('s/foo/' + '\\'*999) + + def test_substitution_with_at_sign(self): + self.assert_single_token(r's@aaa@bbb@g', String.Regex) + self.assert_fast_tokenization('s@foo@' + '\\'*999) + + def test_substitution_with_percent_sign(self): + self.assert_single_token(r's%aaa%bbb%g', String.Regex) + self.assert_fast_tokenization('s%foo%' + '\\'*999) + + def test_substitution_with_brace(self): + self.assert_single_token(r's{aaa}', String.Regex) + self.assert_fast_tokenization('s{' + '\\'*999) + + def test_substitution_with_angle_bracket(self): + self.assert_single_token(r's<aaa>', String.Regex) + self.assert_fast_tokenization('s<' + '\\'*999) + + def test_substitution_with_angle_bracket(self): + self.assert_single_token(r's<aaa>', String.Regex) + self.assert_fast_tokenization('s<' + '\\'*999) + + def test_substitution_with_square_bracket(self): + self.assert_single_token(r's[aaa]', String.Regex) + self.assert_fast_tokenization('s[' + '\\'*999) + + def test_substitution_with_parenthesis(self): + self.assert_single_token(r's(aaa)', String.Regex) + self.assert_fast_tokenization('s(' + '\\'*999) diff --git a/tests/test_regexlexer.py b/tests/test_regexlexer.py index f9c1b7ac..b12dce0a 100644 --- a/tests/test_regexlexer.py +++ b/tests/test_regexlexer.py @@ -3,7 +3,7 @@ Pygments regex lexer tests ~~~~~~~~~~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ @@ -11,6 +11,7 @@ import unittest from pygments.token import Text from pygments.lexer import RegexLexer +from pygments.lexer import bygroups class TestLexer(RegexLexer): @@ -34,6 +35,13 @@ class TupleTransTest(unittest.TestCase): def test(self): lx = TestLexer() toks = list(lx.get_tokens_unprocessed('abcde')) - self.assertEquals(toks, + self.assertEqual(toks, [(0, Text.Root, 'a'), (1, Text.Rag, 'b'), (2, Text.Rag, 'c'), (3, Text.Beer, 'd'), (4, Text.Root, 'e')]) + + def test_multiline(self): + lx = TestLexer() + toks = list(lx.get_tokens_unprocessed('a\ne')) + self.assertEqual(toks, + [(0, Text.Root, 'a'), (1, Text, u'\n'), + (2, Text.Root, 'e')]) diff --git a/tests/test_token.py b/tests/test_token.py index 9a836845..c5cc4990 100644 --- a/tests/test_token.py +++ b/tests/test_token.py @@ -3,13 +3,11 @@ Test suite for the token module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ import unittest -import StringIO -import sys from pygments import token @@ -17,8 +15,7 @@ from pygments import token class TokenTest(unittest.TestCase): def test_tokentype(self): - e = self.assertEquals - r = self.assertRaises + e = self.assertEqual t = token.String @@ -27,23 +24,23 @@ class TokenTest(unittest.TestCase): e(t.__class__, token._TokenType) def test_functions(self): - self.assert_(token.is_token_subtype(token.String, token.String)) - self.assert_(token.is_token_subtype(token.String, token.Literal)) - self.failIf(token.is_token_subtype(token.Literal, token.String)) + self.assertTrue(token.is_token_subtype(token.String, token.String)) + self.assertTrue(token.is_token_subtype(token.String, token.Literal)) + self.assertFalse(token.is_token_subtype(token.Literal, token.String)) - self.assert_(token.string_to_tokentype(token.String) is token.String) - self.assert_(token.string_to_tokentype('') is token.Token) - self.assert_(token.string_to_tokentype('String') is token.String) + self.assertTrue(token.string_to_tokentype(token.String) is token.String) + self.assertTrue(token.string_to_tokentype('') is token.Token) + self.assertTrue(token.string_to_tokentype('String') is token.String) def test_sanity_check(self): stp = token.STANDARD_TYPES.copy() stp[token.Token] = '---' # Token and Text do conflict, that is okay t = {} - for k, v in stp.iteritems(): + for k, v in stp.items(): t.setdefault(v, []).append(k) if len(t) == len(stp): return # Okay - for k, v in t.iteritems(): + for k, v in t.items(): if len(v) > 1: self.fail("%r has more than one key: %r" % (k, v)) diff --git a/tests/test_using_api.py b/tests/test_using_api.py index 3d824f51..9e53c206 100644 --- a/tests/test_using_api.py +++ b/tests/test_using_api.py @@ -3,7 +3,7 @@ Pygments tests for using() ~~~~~~~~~~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ @@ -32,7 +32,7 @@ class UsingStateTest(unittest.TestCase): expected = [(Text, 'a'), (String, '"'), (Keyword, 'bcd'), (String, '"'), (Text, 'e\n')] t = list(TestLexer().get_tokens('a"bcd"e')) - self.assertEquals(t, expected) + self.assertEqual(t, expected) def test_error(self): def gen(): diff --git a/tests/test_util.py b/tests/test_util.py index b0fc2579..59ecf14f 100644 --- a/tests/test_util.py +++ b/tests/test_util.py @@ -3,21 +3,27 @@ Test suite for the util module ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - :copyright: Copyright 2006-2010 by the Pygments team, see AUTHORS. + :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS. :license: BSD, see LICENSE for details. """ +import re import unittest -import os from pygments import util +class FakeLexer(object): + def analyse(text): + return float(text) + analyse = util.make_analysator(analyse) + + class UtilTest(unittest.TestCase): def test_getoptions(self): raises = self.assertRaises - equals = self.assertEquals + equals = self.assertEqual equals(util.get_bool_opt({}, 'a', True), True) equals(util.get_bool_opt({}, 'a', 1), True) @@ -50,38 +56,80 @@ class UtilTest(unittest.TestCase): other text """ - self.assertEquals(util.docstring_headline(f1), "docstring headline") - self.assertEquals(util.docstring_headline(f2), "docstring headline") - - def test_analysator(self): - class X(object): + self.assertEqual(util.docstring_headline(f1), "docstring headline") + self.assertEqual(util.docstring_headline(f2), "docstring headline") + + def test_analysator_returns_float(self): + # If an analysator wrapped by make_analysator returns a floating point + # number, then that number will be returned by the wrapper. + self.assertEqual(FakeLexer.analyse('0.5'), 0.5) + + def test_analysator_returns_boolean(self): + # If an analysator wrapped by make_analysator returns a boolean value, + # then the wrapper will return 1.0 if the boolean was True or 0.0 if + # it was False. + self.assertEqual(FakeLexer.analyse(True), 1.0) + self.assertEqual(FakeLexer.analyse(False), 0.0) + + def test_analysator_raises_exception(self): + # If an analysator wrapped by make_analysator raises an exception, + # then the wrapper will return 0.0. + class ErrorLexer(object): def analyse(text): - return 0.5 + raise RuntimeError('something bad happened') analyse = util.make_analysator(analyse) - self.assertEquals(X.analyse(''), 0.5) + self.assertEqual(ErrorLexer.analyse(''), 0.0) - def test_shebang_matches(self): - self.assert_(util.shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?')) - self.assert_(util.shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?')) - self.assert_(util.shebang_matches('#!/usr/bin/startsomethingwith python', - r'python(2\.\d)?')) - self.assert_(util.shebang_matches('#!C:\\Python2.4\\Python.exe', - r'python(2\.\d)?')) + def test_analysator_value_error(self): + # When converting the analysator's return value to a float a + # ValueError may occur. If that happens 0.0 is returned instead. + self.assertEqual(FakeLexer.analyse('bad input'), 0.0) + + def test_analysator_type_error(self): + # When converting the analysator's return value to a float a + # TypeError may occur. If that happens 0.0 is returned instead. + self.assertEqual(FakeLexer.analyse(None), 0.0) - self.failIf(util.shebang_matches('#!/usr/bin/python-ruby', r'python(2\.\d)?')) - self.failIf(util.shebang_matches('#!/usr/bin/python/ruby', r'python(2\.\d)?')) - self.failIf(util.shebang_matches('#!', r'python')) + def test_shebang_matches(self): + self.assertTrue(util.shebang_matches('#!/usr/bin/env python', r'python(2\.\d)?')) + self.assertTrue(util.shebang_matches('#!/usr/bin/python2.4', r'python(2\.\d)?')) + self.assertTrue(util.shebang_matches('#!/usr/bin/startsomethingwith python', + r'python(2\.\d)?')) + self.assertTrue(util.shebang_matches('#!C:\\Python2.4\\Python.exe', + r'python(2\.\d)?')) + + self.assertFalse(util.shebang_matches('#!/usr/bin/python-ruby', + r'python(2\.\d)?')) + self.assertFalse(util.shebang_matches('#!/usr/bin/python/ruby', + r'python(2\.\d)?')) + self.assertFalse(util.shebang_matches('#!', r'python')) def test_doctype_matches(self): - self.assert_(util.doctype_matches('<!DOCTYPE html PUBLIC "a"> <html>', - 'html.*')) - self.failIf(util.doctype_matches('<?xml ?> <DOCTYPE html PUBLIC "a"> <html>', - 'html.*')) - self.assert_(util.html_doctype_matches( + self.assertTrue(util.doctype_matches( + '<!DOCTYPE html PUBLIC "a"> <html>', 'html.*')) + self.assertFalse(util.doctype_matches( + '<?xml ?> <DOCTYPE html PUBLIC "a"> <html>', 'html.*')) + self.assertTrue(util.html_doctype_matches( '<?xml ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">')) def test_xml(self): - self.assert_(util.looks_like_xml( + self.assertTrue(util.looks_like_xml( '<?xml ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN">')) - self.assert_(util.looks_like_xml('<html xmlns>abc</html>')) - self.failIf(util.looks_like_xml('<html>')) + self.assertTrue(util.looks_like_xml('<html xmlns>abc</html>')) + self.assertFalse(util.looks_like_xml('<html>')) + + def test_unirange(self): + first_non_bmp = u'\U00010000' + r = re.compile(util.unirange(0x10000, 0x20000)) + m = r.match(first_non_bmp) + self.assertTrue(m) + self.assertEquals(m.end(), len(first_non_bmp)) + self.assertFalse(r.match(u'\uffff')) + self.assertFalse(r.match(u'xxx')) + # Tests that end is inclusive + r = re.compile(util.unirange(0x10000, 0x10000) + '+') + # Tests that the plus works for the entire unicode point, if narrow + # build + m = r.match(first_non_bmp * 2) + self.assertTrue(m) + self.assertEquals(m.end(), len(first_non_bmp) * 2) |