_id stringlengths 64 64 | repository stringlengths 6 84 | name stringlengths 4 110 | content stringlengths 0 248k | license null | download_url stringlengths 89 454 | language stringclasses 7
values | comments stringlengths 0 74.6k | code stringlengths 0 248k |
|---|---|---|---|---|---|---|---|---|
e84cf3b539da99f7ebe2569ca325cfd4ecb29c71d28f21c0a0ac4e0d2f5c32a0 | bdeket/rktsicm | Lagrangian-transformations.rkt | #lang s-exp "../../main.rkt"
(require rackunit
"../helper.rkt")
(rename-part 'derivative 'D)
(define the-tests
(test-suite
"mechanics/Lagrangian-transformation"
(check-simplified? (velocity
((F->C p->r)
(->local 't
(coordinate-tuple 'r 'phi)
(velocity-tuple 'rdot 'phidot))))
'(up (+ (* -1 r phidot (sin phi)) (* rdot (cos phi)))
(+ (* r phidot (cos phi)) (* rdot (sin phi)))))
(test-case
"central-polar"
(define ((L-central-rectangular m V) local)
(let ((q (coordinate local))
(v (velocity local)))
(- (* 1/2 m (square v))
(V (sqrt (square q))))))
(define (L-central-polar m V)
(compose (L-central-rectangular m V)
(F->C p->r)))
(check-simplified? ((L-central-polar 'm (literal-function 'V))
(->local 't (coordinate-tuple 'r 'phi)
(velocity-tuple 'rdot 'phidot)))
'(+ (* 1/2 m (expt phidot 2) (expt r 2))
(* 1/2 m (expt rdot 2))
(* -1 (V r)))))
(test-case
"driven pendulum"
(define ((T-pend m l g ys) local)
(let ((t (time local))
(theta (coordinate local))
(thetadot (velocity local)))
(let ((ysdot (D ys)))
(* 1/2 m
(+ (square (* l thetadot))
(square (ysdot t))
(* 2 (ysdot t) l (sin theta) thetadot))))))
(define ((V-pend m l g ys) local)
(let ((t (time local))
(theta (coordinate local)))
(* m g (- (ys t) (* l (cos theta))))))
(define L-pend (- T-pend V-pend))
(check-simplified? ((L-pend 'm 'l 'g (literal-function 'y_s))
(->local 't 'theta 'thetadot))
'(+ (* 1/2 (expt l 2) m (expt thetadot 2))
(* l m thetadot ((D y_s) t) (sin theta))
(* g l m (cos theta))
(* -1 g m (y_s t))
(* 1/2 m (expt ((D y_s) t) 2))))
(check-simplified? (((Lagrange-equations
(L-pend 'm 'l 'g (literal-function 'y_s)))
(literal-function 'theta))
't)
'(+ (* g l m (sin (theta t)))
(* (expt l 2) m (((expt D 2) theta) t))
(* l m (((expt D 2) y_s) t) (sin (theta t))))))
(test-case
"driven pendulum - coord transform"
(define ((Lf m g) local)
(let ((q (coordinate local))
(v (velocity local)))
(let ((h (ref q 1)))
(- (* 1/2 m (square v)) (* m g h)))))
(define ((dp-coordinates l y_s) local)
(let ((t (time local))
(theta (coordinate local)))
(let ((x (* l (sin theta)))
(y (- (y_s t) (* l (cos theta)))))
(coordinate-tuple x y))))
(define (L-pend m l g y_s)
(compose (Lf m g)
(F->C (dp-coordinates l y_s))))
(check-simplified? ((L-pend 'm 'l 'g (literal-function 'y_s))
(->local 't 'theta 'thetadot))
'(+ (* 1/2 (expt l 2) m (expt thetadot 2))
(* l m thetadot (sin theta) ((D y_s) t))
(* g l m (cos theta))
(* -1 g m (y_s t))
(* 1/2 m (expt ((D y_s) t) 2))))
(check-simplified? (((Lagrange-equations
(L-pend 'm 'l 'g (literal-function 'y_s)))
(literal-function 'theta))
't)
'(+ (* g l m (sin (theta t)))
(* (expt l 2) m (((expt D 2) theta) t))
(* l m (((expt D 2) y_s) t) (sin (theta t))))))
(test-case
"L3-central"
(define ((T3-spherical m) local)
(let ((t (time local))
(q (coordinate local))
(qdot (velocity local)))
(let ((r (ref q 0))
(theta (ref q 1))
(phi (ref q 2))
(rdot (ref qdot 0))
(thetadot (ref qdot 1))
(phidot (ref qdot 2)))
(* 1/2 m
(+ (square rdot)
(square (* r thetadot))
(square (* r (sin theta) phidot)))))))
(define (L3-central m Vr)
(define (Vs local)
(let ((r (ref (coordinate local) 0)))
(Vr r)))
(- (T3-spherical m) Vs))
(define ((ang-mom-z m) local)
(let ((q (coordinate local))
(v (velocity local)))
(ref (cross-product q (* m v)) 2)))
(check-simplified? ((compose (ang-mom-z 'm) (F->C s->r))
(->local 't
(coordinate-tuple 'r 'theta 'phi)
(velocity-tuple 'rdot 'thetadot 'phidot)))
'(* m (expt r 2) phidot (expt (sin theta) 2)))
(check-simplified? ((Lagrangian->energy
(L3-central 'm (literal-function 'V)))
(->local 't
(coordinate-tuple 'r 'theta 'phi)
(velocity-tuple 'rdot 'thetadot 'phidot)))
'(+ (* 1/2 m (expt r 2) (expt phidot 2) (expt (sin theta) 2))
(* 1/2 m (expt r 2) (expt thetadot 2))
(* 1/2 m (expt rdot 2))
(V r))))
))
(module+ test
(require rackunit/text-ui)
(run-tests the-tests)) | null | https://raw.githubusercontent.com/bdeket/rktsicm/9a6177d98040f058214add392bd791f5259b83b5/rktsicm/sicm/tests/mechanics/Lagrangian-transformations.rkt | racket | #lang s-exp "../../main.rkt"
(require rackunit
"../helper.rkt")
(rename-part 'derivative 'D)
(define the-tests
(test-suite
"mechanics/Lagrangian-transformation"
(check-simplified? (velocity
((F->C p->r)
(->local 't
(coordinate-tuple 'r 'phi)
(velocity-tuple 'rdot 'phidot))))
'(up (+ (* -1 r phidot (sin phi)) (* rdot (cos phi)))
(+ (* r phidot (cos phi)) (* rdot (sin phi)))))
(test-case
"central-polar"
(define ((L-central-rectangular m V) local)
(let ((q (coordinate local))
(v (velocity local)))
(- (* 1/2 m (square v))
(V (sqrt (square q))))))
(define (L-central-polar m V)
(compose (L-central-rectangular m V)
(F->C p->r)))
(check-simplified? ((L-central-polar 'm (literal-function 'V))
(->local 't (coordinate-tuple 'r 'phi)
(velocity-tuple 'rdot 'phidot)))
'(+ (* 1/2 m (expt phidot 2) (expt r 2))
(* 1/2 m (expt rdot 2))
(* -1 (V r)))))
(test-case
"driven pendulum"
(define ((T-pend m l g ys) local)
(let ((t (time local))
(theta (coordinate local))
(thetadot (velocity local)))
(let ((ysdot (D ys)))
(* 1/2 m
(+ (square (* l thetadot))
(square (ysdot t))
(* 2 (ysdot t) l (sin theta) thetadot))))))
(define ((V-pend m l g ys) local)
(let ((t (time local))
(theta (coordinate local)))
(* m g (- (ys t) (* l (cos theta))))))
(define L-pend (- T-pend V-pend))
(check-simplified? ((L-pend 'm 'l 'g (literal-function 'y_s))
(->local 't 'theta 'thetadot))
'(+ (* 1/2 (expt l 2) m (expt thetadot 2))
(* l m thetadot ((D y_s) t) (sin theta))
(* g l m (cos theta))
(* -1 g m (y_s t))
(* 1/2 m (expt ((D y_s) t) 2))))
(check-simplified? (((Lagrange-equations
(L-pend 'm 'l 'g (literal-function 'y_s)))
(literal-function 'theta))
't)
'(+ (* g l m (sin (theta t)))
(* (expt l 2) m (((expt D 2) theta) t))
(* l m (((expt D 2) y_s) t) (sin (theta t))))))
(test-case
"driven pendulum - coord transform"
(define ((Lf m g) local)
(let ((q (coordinate local))
(v (velocity local)))
(let ((h (ref q 1)))
(- (* 1/2 m (square v)) (* m g h)))))
(define ((dp-coordinates l y_s) local)
(let ((t (time local))
(theta (coordinate local)))
(let ((x (* l (sin theta)))
(y (- (y_s t) (* l (cos theta)))))
(coordinate-tuple x y))))
(define (L-pend m l g y_s)
(compose (Lf m g)
(F->C (dp-coordinates l y_s))))
(check-simplified? ((L-pend 'm 'l 'g (literal-function 'y_s))
(->local 't 'theta 'thetadot))
'(+ (* 1/2 (expt l 2) m (expt thetadot 2))
(* l m thetadot (sin theta) ((D y_s) t))
(* g l m (cos theta))
(* -1 g m (y_s t))
(* 1/2 m (expt ((D y_s) t) 2))))
(check-simplified? (((Lagrange-equations
(L-pend 'm 'l 'g (literal-function 'y_s)))
(literal-function 'theta))
't)
'(+ (* g l m (sin (theta t)))
(* (expt l 2) m (((expt D 2) theta) t))
(* l m (((expt D 2) y_s) t) (sin (theta t))))))
(test-case
"L3-central"
(define ((T3-spherical m) local)
(let ((t (time local))
(q (coordinate local))
(qdot (velocity local)))
(let ((r (ref q 0))
(theta (ref q 1))
(phi (ref q 2))
(rdot (ref qdot 0))
(thetadot (ref qdot 1))
(phidot (ref qdot 2)))
(* 1/2 m
(+ (square rdot)
(square (* r thetadot))
(square (* r (sin theta) phidot)))))))
(define (L3-central m Vr)
(define (Vs local)
(let ((r (ref (coordinate local) 0)))
(Vr r)))
(- (T3-spherical m) Vs))
(define ((ang-mom-z m) local)
(let ((q (coordinate local))
(v (velocity local)))
(ref (cross-product q (* m v)) 2)))
(check-simplified? ((compose (ang-mom-z 'm) (F->C s->r))
(->local 't
(coordinate-tuple 'r 'theta 'phi)
(velocity-tuple 'rdot 'thetadot 'phidot)))
'(* m (expt r 2) phidot (expt (sin theta) 2)))
(check-simplified? ((Lagrangian->energy
(L3-central 'm (literal-function 'V)))
(->local 't
(coordinate-tuple 'r 'theta 'phi)
(velocity-tuple 'rdot 'thetadot 'phidot)))
'(+ (* 1/2 m (expt r 2) (expt phidot 2) (expt (sin theta) 2))
(* 1/2 m (expt r 2) (expt thetadot 2))
(* 1/2 m (expt rdot 2))
(V r))))
))
(module+ test
(require rackunit/text-ui)
(run-tests the-tests)) | |
2854a5b62bcb1591beb855c507e741c09690f9332c2204adb43e270042686bce | marigold-dev/deku | state_entry.mli | open Deku_ledger
type t =
| Entry : {
encoded_module : string;
storage : Value.t;
originated_by : Address.t;
entrypoints : Entrypoints.t;
constants : (int * Value.t) array;
module_ : Wasm.Ast.module_';
}
-> t
[@@deriving show, ord]
val make :
entrypoints:Entrypoints.t ->
encoded_module:string ->
storage:Value.t ->
constants:(int * Value.t) array ->
source:Address.t ->
module_:Wasm.Ast.module_' ->
unit ->
t
val update : t -> storage:Value.t -> t
val encoding : t Data_encoding.t
| null | https://raw.githubusercontent.com/marigold-dev/deku/cdf82852196b55f755f40850515580be4fd9a3fa/deku-c/wasm-vm-ocaml/state_entry.mli | ocaml | open Deku_ledger
type t =
| Entry : {
encoded_module : string;
storage : Value.t;
originated_by : Address.t;
entrypoints : Entrypoints.t;
constants : (int * Value.t) array;
module_ : Wasm.Ast.module_';
}
-> t
[@@deriving show, ord]
val make :
entrypoints:Entrypoints.t ->
encoded_module:string ->
storage:Value.t ->
constants:(int * Value.t) array ->
source:Address.t ->
module_:Wasm.Ast.module_' ->
unit ->
t
val update : t -> storage:Value.t -> t
val encoding : t Data_encoding.t
| |
a4c6442feb8fdef6ef6965ff310a0d99dfcd0b9c429eedc1e86b40ca7765c1e1 | brendanhay/terrafomo | Provider.hs | -- This module is auto-generated.
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# OPTIONS_GHC -fno - warn - unused - imports #
-- |
Module : Terrafomo . AzureRM.Provider
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
-- Stability : auto-generated
Portability : non - portable ( GHC extensions )
--
module Terrafomo.AzureRM.Provider
(
-- * AzureRM Specific Aliases
Provider
, DataSource
, Resource
-- * AzureRM Configuration
, currentVersion
, newProvider
, AzureRM (..)
, AzureRM_Required (..)
) where
import Data.Function ((&))
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import Data.Version (Version, makeVersion, showVersion)
import GHC.Base (($))
import Terrafomo.AzureRM.Settings
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.AzureRM.Types as P
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.Schema as TF
type Provider = TF.Provider AzureRM
type DataSource = TF.Resource AzureRM TF.Ignored
type Resource = TF.Resource AzureRM TF.Meta
type instance TF.ProviderName AzureRM = "azurerm"
currentVersion :: Version
currentVersion = makeVersion [1, 15, 0]
| The @azurerm@ Terraform provider configuration .
data AzureRM = AzureRM_Internal
{ client_id :: P.Maybe TF.Id
-- ^ @client_id@
-- - (Optional)
, client_secret :: P.Maybe P.Text
-- ^ @client_secret@
-- - (Optional)
, environment :: P.Text
-- ^ @environment@
-- - (Required)
, msi_endpoint :: P.Maybe P.Text
^ @msi_endpoint@
-- - (Optional)
, skip_credentials_validation :: P.Maybe P.Bool
-- ^ @skip_credentials_validation@
-- - (Optional)
, skip_provider_registration :: P.Maybe P.Bool
-- ^ @skip_provider_registration@
-- - (Optional)
, subscription_id :: P.Maybe TF.Id
-- ^ @subscription_id@
-- - (Optional)
, tenant_id :: P.Maybe TF.Id
-- ^ @tenant_id@
-- - (Optional)
, use_msi :: P.Maybe P.Bool
-- ^ @use_msi@
-- - (Optional)
} deriving (P.Show)
{- | Specify a new AzureRM provider configuration.
See the < terraform documentation> for more information.
-}
newProvider
:: AzureRM_Required -- ^ The minimal/required arguments.
-> Provider
newProvider x =
TF.Provider
{ TF.providerVersion = P.Just ("~> " P.++ showVersion currentVersion)
, TF.providerConfig =
(let AzureRM{..} = x in AzureRM_Internal
{ client_id = P.Nothing
, client_secret = P.Nothing
, environment = environment
, msi_endpoint = P.Nothing
, skip_credentials_validation = P.Nothing
, skip_provider_registration = P.Nothing
, subscription_id = P.Nothing
, tenant_id = P.Nothing
, use_msi = P.Nothing
})
, TF.providerEncoder =
(\AzureRM_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "client_id") client_id
<> P.maybe P.mempty (TF.pair "client_secret") client_secret
<> TF.pair "environment" environment
<> P.maybe P.mempty (TF.pair "msi_endpoint") msi_endpoint
<> P.maybe P.mempty (TF.pair "skip_credentials_validation") skip_credentials_validation
<> P.maybe P.mempty (TF.pair "skip_provider_registration") skip_provider_registration
<> P.maybe P.mempty (TF.pair "subscription_id") subscription_id
<> P.maybe P.mempty (TF.pair "tenant_id") tenant_id
<> P.maybe P.mempty (TF.pair "use_msi") use_msi
)
}
-- | The required arguments for 'newProvider'.
data AzureRM_Required = AzureRM
{ environment :: P.Text
-- ^ (Required)
} deriving (P.Show)
instance Lens.HasField "client_id" f Provider (P.Maybe TF.Id) where
field = Lens.providerLens P.. Lens.lens'
(client_id :: AzureRM -> P.Maybe TF.Id)
(\s a -> s { client_id = a } :: AzureRM)
instance Lens.HasField "client_secret" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(client_secret :: AzureRM -> P.Maybe P.Text)
(\s a -> s { client_secret = a } :: AzureRM)
instance Lens.HasField "environment" f Provider (P.Text) where
field = Lens.providerLens P.. Lens.lens'
(environment :: AzureRM -> P.Text)
(\s a -> s { environment = a } :: AzureRM)
instance Lens.HasField "msi_endpoint" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(msi_endpoint :: AzureRM -> P.Maybe P.Text)
(\s a -> s { msi_endpoint = a } :: AzureRM)
instance Lens.HasField "skip_credentials_validation" f Provider (P.Maybe P.Bool) where
field = Lens.providerLens P.. Lens.lens'
(skip_credentials_validation :: AzureRM -> P.Maybe P.Bool)
(\s a -> s { skip_credentials_validation = a } :: AzureRM)
instance Lens.HasField "skip_provider_registration" f Provider (P.Maybe P.Bool) where
field = Lens.providerLens P.. Lens.lens'
(skip_provider_registration :: AzureRM -> P.Maybe P.Bool)
(\s a -> s { skip_provider_registration = a } :: AzureRM)
instance Lens.HasField "subscription_id" f Provider (P.Maybe TF.Id) where
field = Lens.providerLens P.. Lens.lens'
(subscription_id :: AzureRM -> P.Maybe TF.Id)
(\s a -> s { subscription_id = a } :: AzureRM)
instance Lens.HasField "tenant_id" f Provider (P.Maybe TF.Id) where
field = Lens.providerLens P.. Lens.lens'
(tenant_id :: AzureRM -> P.Maybe TF.Id)
(\s a -> s { tenant_id = a } :: AzureRM)
instance Lens.HasField "use_msi" f Provider (P.Maybe P.Bool) where
field = Lens.providerLens P.. Lens.lens'
(use_msi :: AzureRM -> P.Maybe P.Bool)
(\s a -> s { use_msi = a } :: AzureRM)
| null | https://raw.githubusercontent.com/brendanhay/terrafomo/387a0e9341fb9cd5543ef8332dea126f50f1070e/provider/terrafomo-azurerm/gen/Terrafomo/AzureRM/Provider.hs | haskell | This module is auto-generated.
|
Stability : auto-generated
* AzureRM Specific Aliases
* AzureRM Configuration
^ @client_id@
- (Optional)
^ @client_secret@
- (Optional)
^ @environment@
- (Required)
- (Optional)
^ @skip_credentials_validation@
- (Optional)
^ @skip_provider_registration@
- (Optional)
^ @subscription_id@
- (Optional)
^ @tenant_id@
- (Optional)
^ @use_msi@
- (Optional)
| Specify a new AzureRM provider configuration.
See the < terraform documentation> for more information.
^ The minimal/required arguments.
| The required arguments for 'newProvider'.
^ (Required) |
# LANGUAGE NoImplicitPrelude #
# LANGUAGE RecordWildCards #
# LANGUAGE StrictData #
# OPTIONS_GHC -fno - warn - unused - imports #
Module : Terrafomo . AzureRM.Provider
Copyright : ( c ) 2017 - 2018
License : Mozilla Public License , v. 2.0 .
Maintainer : < brendan.g.hay+ >
Portability : non - portable ( GHC extensions )
module Terrafomo.AzureRM.Provider
(
Provider
, DataSource
, Resource
, currentVersion
, newProvider
, AzureRM (..)
, AzureRM_Required (..)
) where
import Data.Function ((&))
import Data.Functor ((<$>))
import Data.Semigroup ((<>))
import Data.Version (Version, makeVersion, showVersion)
import GHC.Base (($))
import Terrafomo.AzureRM.Settings
import qualified Data.Functor.Const as P
import qualified Data.List.NonEmpty as P
import qualified Data.Map.Strict as P
import qualified Data.Maybe as P
import qualified Data.Text.Lazy as P
import qualified Prelude as P
import qualified Terrafomo.AzureRM.Types as P
import qualified Terrafomo.HCL as TF
import qualified Terrafomo.Lens as Lens
import qualified Terrafomo.Schema as TF
type Provider = TF.Provider AzureRM
type DataSource = TF.Resource AzureRM TF.Ignored
type Resource = TF.Resource AzureRM TF.Meta
type instance TF.ProviderName AzureRM = "azurerm"
currentVersion :: Version
currentVersion = makeVersion [1, 15, 0]
| The @azurerm@ Terraform provider configuration .
data AzureRM = AzureRM_Internal
{ client_id :: P.Maybe TF.Id
, client_secret :: P.Maybe P.Text
, environment :: P.Text
, msi_endpoint :: P.Maybe P.Text
^ @msi_endpoint@
, skip_credentials_validation :: P.Maybe P.Bool
, skip_provider_registration :: P.Maybe P.Bool
, subscription_id :: P.Maybe TF.Id
, tenant_id :: P.Maybe TF.Id
, use_msi :: P.Maybe P.Bool
} deriving (P.Show)
newProvider
-> Provider
newProvider x =
TF.Provider
{ TF.providerVersion = P.Just ("~> " P.++ showVersion currentVersion)
, TF.providerConfig =
(let AzureRM{..} = x in AzureRM_Internal
{ client_id = P.Nothing
, client_secret = P.Nothing
, environment = environment
, msi_endpoint = P.Nothing
, skip_credentials_validation = P.Nothing
, skip_provider_registration = P.Nothing
, subscription_id = P.Nothing
, tenant_id = P.Nothing
, use_msi = P.Nothing
})
, TF.providerEncoder =
(\AzureRM_Internal{..} ->
P.mempty
<> P.maybe P.mempty (TF.pair "client_id") client_id
<> P.maybe P.mempty (TF.pair "client_secret") client_secret
<> TF.pair "environment" environment
<> P.maybe P.mempty (TF.pair "msi_endpoint") msi_endpoint
<> P.maybe P.mempty (TF.pair "skip_credentials_validation") skip_credentials_validation
<> P.maybe P.mempty (TF.pair "skip_provider_registration") skip_provider_registration
<> P.maybe P.mempty (TF.pair "subscription_id") subscription_id
<> P.maybe P.mempty (TF.pair "tenant_id") tenant_id
<> P.maybe P.mempty (TF.pair "use_msi") use_msi
)
}
data AzureRM_Required = AzureRM
{ environment :: P.Text
} deriving (P.Show)
instance Lens.HasField "client_id" f Provider (P.Maybe TF.Id) where
field = Lens.providerLens P.. Lens.lens'
(client_id :: AzureRM -> P.Maybe TF.Id)
(\s a -> s { client_id = a } :: AzureRM)
instance Lens.HasField "client_secret" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(client_secret :: AzureRM -> P.Maybe P.Text)
(\s a -> s { client_secret = a } :: AzureRM)
instance Lens.HasField "environment" f Provider (P.Text) where
field = Lens.providerLens P.. Lens.lens'
(environment :: AzureRM -> P.Text)
(\s a -> s { environment = a } :: AzureRM)
instance Lens.HasField "msi_endpoint" f Provider (P.Maybe P.Text) where
field = Lens.providerLens P.. Lens.lens'
(msi_endpoint :: AzureRM -> P.Maybe P.Text)
(\s a -> s { msi_endpoint = a } :: AzureRM)
instance Lens.HasField "skip_credentials_validation" f Provider (P.Maybe P.Bool) where
field = Lens.providerLens P.. Lens.lens'
(skip_credentials_validation :: AzureRM -> P.Maybe P.Bool)
(\s a -> s { skip_credentials_validation = a } :: AzureRM)
instance Lens.HasField "skip_provider_registration" f Provider (P.Maybe P.Bool) where
field = Lens.providerLens P.. Lens.lens'
(skip_provider_registration :: AzureRM -> P.Maybe P.Bool)
(\s a -> s { skip_provider_registration = a } :: AzureRM)
instance Lens.HasField "subscription_id" f Provider (P.Maybe TF.Id) where
field = Lens.providerLens P.. Lens.lens'
(subscription_id :: AzureRM -> P.Maybe TF.Id)
(\s a -> s { subscription_id = a } :: AzureRM)
instance Lens.HasField "tenant_id" f Provider (P.Maybe TF.Id) where
field = Lens.providerLens P.. Lens.lens'
(tenant_id :: AzureRM -> P.Maybe TF.Id)
(\s a -> s { tenant_id = a } :: AzureRM)
instance Lens.HasField "use_msi" f Provider (P.Maybe P.Bool) where
field = Lens.providerLens P.. Lens.lens'
(use_msi :: AzureRM -> P.Maybe P.Bool)
(\s a -> s { use_msi = a } :: AzureRM)
|
221199f17a7be4ae624bf4160f7b068d0be000ec9a8e7821a70092756d5da204 | michaelklishin/welle | links_test.clj | (ns clojurewerkz.welle.test.links-test
(:require [clojurewerkz.welle.kv :as kv]
[clojurewerkz.welle.buckets :as wb]
[clojurewerkz.welle.mr :as mr]
[clojure.test :refer :all]
[clojurewerkz.welle.testkit :refer [drain]]
[clojurewerkz.welle.test.test-helpers :as th]
[clojurewerkz.welle.links :refer :all]))
(deftest ^{:links true} test-link-walking-with-a-single-step
(let [conn (th/connect)
bucket-name "people"
_ (wb/update conn bucket-name)]
(drain conn bucket-name)
(kv/store conn bucket-name "joe" {:name "Joe" :age 30} {:content-type "application/clojure"})
(kv/store conn bucket-name "jane" {:name "Jane" :age 32}
{:content-type "application/clojure"
:links [{:bucket bucket-name :key "joe" :tag "friend"}]})
(let [result (walk conn
(start-at "people" "jane")
(step "people" "friend" true))]
(is (= {:name "Joe" :age 30} (:value (ffirst result)))))
(drain conn bucket-name)))
| null | https://raw.githubusercontent.com/michaelklishin/welle/3f3cd24af7c0d95489298e4096b362b6943f85ef/test/clojurewerkz/welle/test/links_test.clj | clojure | (ns clojurewerkz.welle.test.links-test
(:require [clojurewerkz.welle.kv :as kv]
[clojurewerkz.welle.buckets :as wb]
[clojurewerkz.welle.mr :as mr]
[clojure.test :refer :all]
[clojurewerkz.welle.testkit :refer [drain]]
[clojurewerkz.welle.test.test-helpers :as th]
[clojurewerkz.welle.links :refer :all]))
(deftest ^{:links true} test-link-walking-with-a-single-step
(let [conn (th/connect)
bucket-name "people"
_ (wb/update conn bucket-name)]
(drain conn bucket-name)
(kv/store conn bucket-name "joe" {:name "Joe" :age 30} {:content-type "application/clojure"})
(kv/store conn bucket-name "jane" {:name "Jane" :age 32}
{:content-type "application/clojure"
:links [{:bucket bucket-name :key "joe" :tag "friend"}]})
(let [result (walk conn
(start-at "people" "jane")
(step "people" "friend" true))]
(is (= {:name "Joe" :age 30} (:value (ffirst result)))))
(drain conn bucket-name)))
| |
a0bf94a9a2d5fc2160f5dbad363f4620f246ede88e83276d708792e37ced3739 | puppetlabs/trapperkeeper | custom_exit_behavior_test.clj | (ns puppetlabs.trapperkeeper.custom-exit-behavior-test
(:require
[puppetlabs.trapperkeeper.core :as core]))
(defprotocol CustomExitBehaviorTestService)
(core/defservice custom-exit-behavior-test-service
CustomExitBehaviorTestService
[[:ShutdownService request-shutdown]]
(init [this context] context)
(start [this context]
(request-shutdown {::core/exit {:messages [["Some excitement!\n" *out*]
["More excitement!\n" *err*]]
:status 7}})
context)
(stop [this context] context))
| null | https://raw.githubusercontent.com/puppetlabs/trapperkeeper/3e5e7e286287d75e7fdf7eb1dabb2fa534091329/test/puppetlabs/trapperkeeper/custom_exit_behavior_test.clj | clojure | (ns puppetlabs.trapperkeeper.custom-exit-behavior-test
(:require
[puppetlabs.trapperkeeper.core :as core]))
(defprotocol CustomExitBehaviorTestService)
(core/defservice custom-exit-behavior-test-service
CustomExitBehaviorTestService
[[:ShutdownService request-shutdown]]
(init [this context] context)
(start [this context]
(request-shutdown {::core/exit {:messages [["Some excitement!\n" *out*]
["More excitement!\n" *err*]]
:status 7}})
context)
(stop [this context] context))
| |
e2a644412890979d4629d5b01b9b809d07342c31116a59b067e141268db7a50c | noprompt/lein-describe | project.clj | (defproject lein-describe "0.3.0-SNAPSHOT"
:description "A Leiningen plugin for displaying detailed project information."
:url "-describe"
:license {:name "Unlicense"
:url ""}
:eval-in-leiningen true)
| null | https://raw.githubusercontent.com/noprompt/lein-describe/ad23cf1a8c8a75946f4046f854533d71dea77b63/project.clj | clojure | (defproject lein-describe "0.3.0-SNAPSHOT"
:description "A Leiningen plugin for displaying detailed project information."
:url "-describe"
:license {:name "Unlicense"
:url ""}
:eval-in-leiningen true)
| |
cf25b748d6b8a33c64487324f1290a62a5859e2aad3316996173796021556759 | static-analysis-engineering/codehawk | jCHAnalysisUtils.ml | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
open Big_int_Z
chlib
open CHAtlas
open CHIntervals
open CHLanguage
open CHNonRelationalDomainValues
open CHNonRelationalDomainNoArrays
open CHNumerical
open CHPretty
open CHUtils
(* chutil *)
open CHPrettyUtil
(* jchlib *)
open JCHBasicTypes
open JCHBasicTypesAPI
open JCHDictionary
(* jchpre *)
open JCHApplication
open JCHPreAPI
(* jchsys *)
open JCHGlobals
open JCHPrintUtils
let current_proc_name = ref proc_name_sym
let current_jproc_info = ref None
let set_current_proc_name proc_name =
current_proc_name := proc_name ;
current_jproc_info := Some (JCHSystem.jsystem#get_jproc_info !current_proc_name)
let get_current_proc_name () = !current_proc_name
let get_current_jproc_info () = Option.get (!current_jproc_info)
let exit_inv = ref (None : CHAtlas.atlas_t option)
let set_exit_invariant inv = exit_inv := Some inv
let get_exit_invariant () = !exit_inv
let jch_op_semantics
~(invariant: atlas_t)
~(stable: bool)
~(fwd_direction: bool)
~context ~(operation: operation_t) =
let setWriteVarsToTop =
let write_vars = JCHSystemUtils.get_write_vars operation.op_args in
if write_vars = [] then
invariant
else
invariant#analyzeFwd (ABSTRACT_VARS write_vars) in
match operation.op_name#getBaseName with
| "loop_cond"
| "check_loop"
| "save_interval"
| "v" -> invariant
| "exit" ->
if fwd_direction && stable then
set_exit_invariant invariant
else
() ;
invariant
| "i"
| "ii" ->
let mInfo = app#get_method (retrieve_cms !current_proc_name#getSeqNumber) in
let pc = operation.op_name#getSeqNumber in
begin
match mInfo#get_opcode pc with
| OpBreakpoint (* used for debugging only *)
| OpIfNull _
| OpIfNonNull _
| OpIfCmpAEq _
The 3 above are just branches
| OpCheckCast _ -> (* checks that a ref is of a certain type,
return same variable or throws exception. NOT SURE *)
invariant
| _ -> setWriteVarsToTop
end
| "e" -> invariant
| "exn-exit" -> invariant
| "method-init" -> invariant
| _ ->
pr__debug [STR "unknown operation in op_semantics ";
operation_to_pretty operation; NL;
pp_list_str operation.op_name#getSymbol; NL] ;
setWriteVarsToTop
exception JCH_num_analysis_failure of string
class numeric_run_params_t =
object
val analysis_level = ref 1 (* larger level -> more precise analysis *)
val use_types = ref true (* if true then use type intervals *)
(* if true then use only intervals for all analysis form the beginning *)
val system_use_intervals = ref false
(* if true then use only intervals if system_use_intervals is true or
* when the analysis of the proc is too long, etc. *)
val use_intervals = ref false
val use_loop_counters = ref true
val use_lengths = ref true
val use_overflow = ref true
used in JCHIntervalArray ;
* 80 seemed too large : on xerces ,
* swap space went up to 21 GB
* 80 seemed too large: on xerces,
* swap space went up to 21GB *)
val interval_array_size = 50
val max_number_rays = ref 400
(* largest coefficient allowed in a constraint *)
val max_poly_coefficient = ref (big_int_of_int 1000)
(* maximum number of constraints encountered in the analysis *)
val max_number_constraints = ref 0
(* maximum number of constraints allowed *)
val max_number_constraints_allowed = ref 20
val max_number_vars_in_constrant_allowed = ref 3
val number_joins = ref 3;
val use_time_limits = ref false
val st_time = ref 0.0
val max_numeric_analysis_time = ref 500.0
val drop_constraint_analysis_time = ref 100.0
val time_limit = ref 0.0
val drop_constraint_analysis_time_limit = ref 0.0
0 : fine ; 1 : failed - continue with intervals ;
* 2 : retry with intervals ;
* 3 : abort - various problems ;
* 10 : abort - out of time
* 2: retry with intervals;
* 3: abort - various problems;
* 10: abort - out of time *)
val analysis_status = ref 0
val analysis_failure_reason = ref ""
20000
10000
val swap_increase = 500
val swap_used = ref 0
val initial_swap = ref 0
val create_model = ref false
method set_analysis_level (n:int) = analysis_level := n
method analysis_level = !analysis_level
method set_use_types (b:bool) = use_types := b
method use_types = !use_types
method set_system_use_intervals (b:bool) =
system_use_intervals := b ;
use_intervals := b
method get_system_use_intervals = !system_use_intervals
method set_use_intervals (b:bool) =
begin
use_intervals := b ;
if b then pr__debug [STR "set use_intervals to true"; NL]
end
method use_intervals = !use_intervals
method set_use_lengths (b:bool) = use_lengths := b
method use_lengths = !use_lengths
method set_use_loop_counters (b:bool) = use_loop_counters := b
method use_loop_counters = !use_loop_counters
method set_use_overflow (b:bool) = use_overflow := b
method use_overflow = !use_overflow
method interval_array_size = interval_array_size
method set_max_number_rays (n:int) = max_number_rays := n
method max_number_rays = !max_number_rays
method set_max_poly_coefficient (n:int) =
max_poly_coefficient := big_int_of_int n
method max_poly_coefficient = !max_poly_coefficient
method is_good_coefficient n =
le_big_int n !max_poly_coefficient
&& le_big_int (minus_big_int !max_poly_coefficient) n
method record_number_constraints (n:int) =
max_number_constraints := max n !max_number_constraints
method max_number_constraints = !max_number_constraints
method set_max_number_constraints_allowed (n:int) =
max_number_constraints_allowed := n
method max_number_constraints_allowed = !max_number_constraints_allowed
method set_max_number_vars_in_constraint_allowed (n:int) =
max_number_vars_in_constrant_allowed := n
method max_number_vars_in_constraint_allowed =
!max_number_vars_in_constrant_allowed
method reset reset_use_intervals =
begin
(if reset_use_intervals then use_intervals := !system_use_intervals);
max_number_constraints := 0
end
method set_number_joins (n:int) = number_joins := n
method number_joins = !number_joins
method start_numeric_analysis_time =
begin
st_time := Sys.time () ;
time_limit := !st_time +. !max_numeric_analysis_time ;
drop_constraint_analysis_time_limit :=
!st_time +. !drop_constraint_analysis_time
end
method set_use_time_limits (b:bool) = use_time_limits := b
method set_constraint_analysis_time_limit (n:int) =
drop_constraint_analysis_time := float n
method set_numeric_analysis_time_limit (n:int) =
begin
pr__debug [STR "set_numeric_analysis_time_limit "; INT n; NL] ;
max_numeric_analysis_time := float n
end
method reached_constraint_analysis_time_limit =
Sys.time () > !drop_constraint_analysis_time_limit
method reached_numeric_analysis_time_limit =
Sys.time () > !time_limit
method check_time_limit =
if not !use_time_limits then
0
else if Sys.time () > !time_limit then
if !use_intervals then
begin
analysis_status := 10;
analysis_failure_reason := "reached analysis time limit";
10
end
else
begin
analysis_status := 1;
analysis_failure_reason := "reached analysis time limit with constraints";
use_intervals := true;
pr_debug [STR "set use_intervals to true"; NL] ;
time_limit := Sys.time() +. !drop_constraint_analysis_time ; (* give some more time *)
1
end
else if Sys.time () > !drop_constraint_analysis_time_limit && not !use_intervals then
begin
analysis_status := 1;
analysis_failure_reason := "reached constraint analysis time limit";
use_intervals := true;
pr_debug [STR "set use_intervals to true"; NL] ;
1
end
else
0
method analysis_failed (status:int) (str:string) =
begin
analysis_status := status ;
analysis_failure_reason := str ;
pr__debug [STR "analysis_failed "; INT status; STR (" " ^ str); NL] ;
(if status = 1 then use_intervals := true) ;
JCH_num_analysis_failure str
end
method get_analysis_status = !analysis_status
method get_analysis_failure_reason = !analysis_failure_reason
method reset_analysis_failure_status = analysis_status := 0
method create_model = !create_model
method set_create_model (b:bool) = create_model := b
end
let numeric_params = new numeric_run_params_t
let has_untranslated_caller (proc_name:symbol_t) =
let jproc_info = JCHSystem.jsystem#get_jproc_info proc_name in
let method_info = jproc_info#get_method_info in
let callers = method_info#get_callers in
let untranslated cmsg =
let mInfo = app#get_method cmsg in
match mInfo#get_implementation with
| UntranslatedConcreteMethod _ -> true
| _ -> false in
List.exists untranslated callers
let get_slot_interval (slot:logical_stack_slot_int) =
match slot#get_value#to_interval with
| Some int -> int
| _ -> topInterval
(* It could be a collection *)
let is_collection (jproc_info: JCHProcInfo.jproc_info_t) (var:variable_t) =
let jvar_info = jproc_info#get_jvar_info var in
JCHTypeUtils.can_be_collection jvar_info#get_types
(* It is for sure an array *)
let is_array (jproc_info:JCHProcInfo.jproc_info_t) (var:variable_t) =
try
let var_info = jproc_info#get_jvar_info var in
let types = var_info#get_types in
List.for_all JCHTypeUtils.is_array types
with _ -> false
let is_collection_or_array
(jproc_info:JCHProcInfo.jproc_info_t) (var:variable_t) =
is_collection jproc_info var || is_array jproc_info var
is number or wrapper or array of numbers
* Experiment : include all arrays as we need to keep track of the
* length of arrays in the
* Experiment: include all arrays as we need to keep track of the
* length of arrays in the numeric_info_t *)
let is_numeric (jproc_info:JCHProcInfo.jproc_info_t) (var:variable_t) =
try
let var_info = jproc_info#get_jvar_info var in
var_info#is_numeric || is_array jproc_info var
with _ -> false
let float_to_interval (f:float) =
let big_int_of_float (f:float) =
let s = string_of_float f in
let s' =
try
List.hd (Str.split (Str.regexp_string ".") s)
with
| _ ->
raise
(JCH_failure
(LBLOCK [ STR "JCHAnalysisUtils:float_to_interval: " ;
STR s ])) in
big_int_of_string s' in
let max = new numerical_t (big_int_of_float (ceil f)) in
let min = new numerical_t (big_int_of_float (floor f)) in
(min, max, mkInterval min max)
let get_length_vars
(jproc_info:JCHProcInfo.jproc_info_t) (vars:variable_t list) =
let vars_with_lengths = ref [] in
let lengths = ref [] in
let length_to_var = new VariableCollections.table_t in
let add_var var =
try
let len = Option.get (jproc_info#get_length var) in
begin
lengths := len :: !lengths ;
vars_with_lengths := var :: !vars_with_lengths ;
length_to_var#set len var
end
with _ -> () in
begin
List.iter add_var vars ;
(List.rev !lengths , List.rev !vars_with_lengths, length_to_var)
end
let include_length_vars
(jproc_info:JCHProcInfo.jproc_info_t) (vars:variable_t list) =
let lengths = ref [] in
let add_var var =
try
lengths := (Option.get (jproc_info#get_length var)) :: !lengths
with _ -> () in
begin
List.iter add_var vars ;
vars @ (List.rev !lengths)
end
let include_all_length_vars
(jproc_info:JCHProcInfo.jproc_info_t)
(vars:variable_t list)
(vs:variable_t list)
(length_to_array: variable_t VariableCollections.table_t) =
let v_arrays = length_to_array#listOfValues in
let lengths = ref [] in
let lengths_not_included = ref [] in
let pairs = List.combine vars vs in
let missing_length_indices = ref [] in
let length_index = ref (List.length vars) in
let add_var (var, v) =
if List.mem v v_arrays then
match jproc_info#get_length var with
| Some len -> lengths := len :: !lengths
| _ ->
begin
lengths_not_included :=
(JCHSystemUtils.make_length var) :: !lengths_not_included ;
missing_length_indices := !length_index :: !missing_length_indices ;
incr length_index
end in
begin
List.iter add_var pairs ;
(vars @ (List.rev !lengths), !lengths_not_included, !missing_length_indices)
end
(* CHIntervals.div is not integer division *)
let integer_div (int1:interval_t) (int2:interval_t) =
if int1#isBottom || int2#isBottom then
bottomInterval
else if int2#contains numerical_zero then
topInterval
else
begin
let (a1, b1) = (int1#getMin, int1#getMax) in
let (a2, b2) = (int2#getMin, int2#getMax) in
let l = [a1#div_floor a2; a1#div_floor b2; b1#div_floor a2; b1#div_floor b2] in
let min = CHBounds.min_in_bounds l in
let max = CHBounds.max_in_bounds l in
if max#lt min then
bottomInterval
else
new interval_t min max
end
| null | https://raw.githubusercontent.com/static-analysis-engineering/codehawk/98ced4d5e6d7989575092df232759afc2cb851f6/CodeHawk/CHJ/jchpoly/jCHAnalysisUtils.ml | ocaml | chutil
jchlib
jchpre
jchsys
used for debugging only
checks that a ref is of a certain type,
return same variable or throws exception. NOT SURE
larger level -> more precise analysis
if true then use type intervals
if true then use only intervals for all analysis form the beginning
if true then use only intervals if system_use_intervals is true or
* when the analysis of the proc is too long, etc.
largest coefficient allowed in a constraint
maximum number of constraints encountered in the analysis
maximum number of constraints allowed
give some more time
It could be a collection
It is for sure an array
CHIntervals.div is not integer division | = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author :
------------------------------------------------------------------------------
The MIT License ( MIT )
Copyright ( c ) 2005 - 2020 Kestrel Technology LLC
Permission is hereby granted , free of charge , to any person obtaining a copy
of this software and associated documentation files ( the " Software " ) , to deal
in the Software without restriction , including without limitation the rights
to use , copy , modify , merge , publish , distribute , sublicense , and/or sell
copies of the Software , and to permit persons to whom the Software is
furnished to do so , subject to the following conditions :
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY ,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT . IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM , DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE .
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
CodeHawk Java Analyzer
Author: Anca Browne
------------------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2005-2020 Kestrel Technology LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================= *)
open Big_int_Z
chlib
open CHAtlas
open CHIntervals
open CHLanguage
open CHNonRelationalDomainValues
open CHNonRelationalDomainNoArrays
open CHNumerical
open CHPretty
open CHUtils
open CHPrettyUtil
open JCHBasicTypes
open JCHBasicTypesAPI
open JCHDictionary
open JCHApplication
open JCHPreAPI
open JCHGlobals
open JCHPrintUtils
let current_proc_name = ref proc_name_sym
let current_jproc_info = ref None
let set_current_proc_name proc_name =
current_proc_name := proc_name ;
current_jproc_info := Some (JCHSystem.jsystem#get_jproc_info !current_proc_name)
let get_current_proc_name () = !current_proc_name
let get_current_jproc_info () = Option.get (!current_jproc_info)
let exit_inv = ref (None : CHAtlas.atlas_t option)
let set_exit_invariant inv = exit_inv := Some inv
let get_exit_invariant () = !exit_inv
let jch_op_semantics
~(invariant: atlas_t)
~(stable: bool)
~(fwd_direction: bool)
~context ~(operation: operation_t) =
let setWriteVarsToTop =
let write_vars = JCHSystemUtils.get_write_vars operation.op_args in
if write_vars = [] then
invariant
else
invariant#analyzeFwd (ABSTRACT_VARS write_vars) in
match operation.op_name#getBaseName with
| "loop_cond"
| "check_loop"
| "save_interval"
| "v" -> invariant
| "exit" ->
if fwd_direction && stable then
set_exit_invariant invariant
else
() ;
invariant
| "i"
| "ii" ->
let mInfo = app#get_method (retrieve_cms !current_proc_name#getSeqNumber) in
let pc = operation.op_name#getSeqNumber in
begin
match mInfo#get_opcode pc with
| OpIfNull _
| OpIfNonNull _
| OpIfCmpAEq _
The 3 above are just branches
invariant
| _ -> setWriteVarsToTop
end
| "e" -> invariant
| "exn-exit" -> invariant
| "method-init" -> invariant
| _ ->
pr__debug [STR "unknown operation in op_semantics ";
operation_to_pretty operation; NL;
pp_list_str operation.op_name#getSymbol; NL] ;
setWriteVarsToTop
exception JCH_num_analysis_failure of string
class numeric_run_params_t =
object
val system_use_intervals = ref false
val use_intervals = ref false
val use_loop_counters = ref true
val use_lengths = ref true
val use_overflow = ref true
used in JCHIntervalArray ;
* 80 seemed too large : on xerces ,
* swap space went up to 21 GB
* 80 seemed too large: on xerces,
* swap space went up to 21GB *)
val interval_array_size = 50
val max_number_rays = ref 400
val max_poly_coefficient = ref (big_int_of_int 1000)
val max_number_constraints = ref 0
val max_number_constraints_allowed = ref 20
val max_number_vars_in_constrant_allowed = ref 3
val number_joins = ref 3;
val use_time_limits = ref false
val st_time = ref 0.0
val max_numeric_analysis_time = ref 500.0
val drop_constraint_analysis_time = ref 100.0
val time_limit = ref 0.0
val drop_constraint_analysis_time_limit = ref 0.0
0 : fine ; 1 : failed - continue with intervals ;
* 2 : retry with intervals ;
* 3 : abort - various problems ;
* 10 : abort - out of time
* 2: retry with intervals;
* 3: abort - various problems;
* 10: abort - out of time *)
val analysis_status = ref 0
val analysis_failure_reason = ref ""
20000
10000
val swap_increase = 500
val swap_used = ref 0
val initial_swap = ref 0
val create_model = ref false
method set_analysis_level (n:int) = analysis_level := n
method analysis_level = !analysis_level
method set_use_types (b:bool) = use_types := b
method use_types = !use_types
method set_system_use_intervals (b:bool) =
system_use_intervals := b ;
use_intervals := b
method get_system_use_intervals = !system_use_intervals
method set_use_intervals (b:bool) =
begin
use_intervals := b ;
if b then pr__debug [STR "set use_intervals to true"; NL]
end
method use_intervals = !use_intervals
method set_use_lengths (b:bool) = use_lengths := b
method use_lengths = !use_lengths
method set_use_loop_counters (b:bool) = use_loop_counters := b
method use_loop_counters = !use_loop_counters
method set_use_overflow (b:bool) = use_overflow := b
method use_overflow = !use_overflow
method interval_array_size = interval_array_size
method set_max_number_rays (n:int) = max_number_rays := n
method max_number_rays = !max_number_rays
method set_max_poly_coefficient (n:int) =
max_poly_coefficient := big_int_of_int n
method max_poly_coefficient = !max_poly_coefficient
method is_good_coefficient n =
le_big_int n !max_poly_coefficient
&& le_big_int (minus_big_int !max_poly_coefficient) n
method record_number_constraints (n:int) =
max_number_constraints := max n !max_number_constraints
method max_number_constraints = !max_number_constraints
method set_max_number_constraints_allowed (n:int) =
max_number_constraints_allowed := n
method max_number_constraints_allowed = !max_number_constraints_allowed
method set_max_number_vars_in_constraint_allowed (n:int) =
max_number_vars_in_constrant_allowed := n
method max_number_vars_in_constraint_allowed =
!max_number_vars_in_constrant_allowed
method reset reset_use_intervals =
begin
(if reset_use_intervals then use_intervals := !system_use_intervals);
max_number_constraints := 0
end
method set_number_joins (n:int) = number_joins := n
method number_joins = !number_joins
method start_numeric_analysis_time =
begin
st_time := Sys.time () ;
time_limit := !st_time +. !max_numeric_analysis_time ;
drop_constraint_analysis_time_limit :=
!st_time +. !drop_constraint_analysis_time
end
method set_use_time_limits (b:bool) = use_time_limits := b
method set_constraint_analysis_time_limit (n:int) =
drop_constraint_analysis_time := float n
method set_numeric_analysis_time_limit (n:int) =
begin
pr__debug [STR "set_numeric_analysis_time_limit "; INT n; NL] ;
max_numeric_analysis_time := float n
end
method reached_constraint_analysis_time_limit =
Sys.time () > !drop_constraint_analysis_time_limit
method reached_numeric_analysis_time_limit =
Sys.time () > !time_limit
method check_time_limit =
if not !use_time_limits then
0
else if Sys.time () > !time_limit then
if !use_intervals then
begin
analysis_status := 10;
analysis_failure_reason := "reached analysis time limit";
10
end
else
begin
analysis_status := 1;
analysis_failure_reason := "reached analysis time limit with constraints";
use_intervals := true;
pr_debug [STR "set use_intervals to true"; NL] ;
1
end
else if Sys.time () > !drop_constraint_analysis_time_limit && not !use_intervals then
begin
analysis_status := 1;
analysis_failure_reason := "reached constraint analysis time limit";
use_intervals := true;
pr_debug [STR "set use_intervals to true"; NL] ;
1
end
else
0
method analysis_failed (status:int) (str:string) =
begin
analysis_status := status ;
analysis_failure_reason := str ;
pr__debug [STR "analysis_failed "; INT status; STR (" " ^ str); NL] ;
(if status = 1 then use_intervals := true) ;
JCH_num_analysis_failure str
end
method get_analysis_status = !analysis_status
method get_analysis_failure_reason = !analysis_failure_reason
method reset_analysis_failure_status = analysis_status := 0
method create_model = !create_model
method set_create_model (b:bool) = create_model := b
end
let numeric_params = new numeric_run_params_t
let has_untranslated_caller (proc_name:symbol_t) =
let jproc_info = JCHSystem.jsystem#get_jproc_info proc_name in
let method_info = jproc_info#get_method_info in
let callers = method_info#get_callers in
let untranslated cmsg =
let mInfo = app#get_method cmsg in
match mInfo#get_implementation with
| UntranslatedConcreteMethod _ -> true
| _ -> false in
List.exists untranslated callers
let get_slot_interval (slot:logical_stack_slot_int) =
match slot#get_value#to_interval with
| Some int -> int
| _ -> topInterval
let is_collection (jproc_info: JCHProcInfo.jproc_info_t) (var:variable_t) =
let jvar_info = jproc_info#get_jvar_info var in
JCHTypeUtils.can_be_collection jvar_info#get_types
let is_array (jproc_info:JCHProcInfo.jproc_info_t) (var:variable_t) =
try
let var_info = jproc_info#get_jvar_info var in
let types = var_info#get_types in
List.for_all JCHTypeUtils.is_array types
with _ -> false
let is_collection_or_array
(jproc_info:JCHProcInfo.jproc_info_t) (var:variable_t) =
is_collection jproc_info var || is_array jproc_info var
is number or wrapper or array of numbers
* Experiment : include all arrays as we need to keep track of the
* length of arrays in the
* Experiment: include all arrays as we need to keep track of the
* length of arrays in the numeric_info_t *)
let is_numeric (jproc_info:JCHProcInfo.jproc_info_t) (var:variable_t) =
try
let var_info = jproc_info#get_jvar_info var in
var_info#is_numeric || is_array jproc_info var
with _ -> false
let float_to_interval (f:float) =
let big_int_of_float (f:float) =
let s = string_of_float f in
let s' =
try
List.hd (Str.split (Str.regexp_string ".") s)
with
| _ ->
raise
(JCH_failure
(LBLOCK [ STR "JCHAnalysisUtils:float_to_interval: " ;
STR s ])) in
big_int_of_string s' in
let max = new numerical_t (big_int_of_float (ceil f)) in
let min = new numerical_t (big_int_of_float (floor f)) in
(min, max, mkInterval min max)
let get_length_vars
(jproc_info:JCHProcInfo.jproc_info_t) (vars:variable_t list) =
let vars_with_lengths = ref [] in
let lengths = ref [] in
let length_to_var = new VariableCollections.table_t in
let add_var var =
try
let len = Option.get (jproc_info#get_length var) in
begin
lengths := len :: !lengths ;
vars_with_lengths := var :: !vars_with_lengths ;
length_to_var#set len var
end
with _ -> () in
begin
List.iter add_var vars ;
(List.rev !lengths , List.rev !vars_with_lengths, length_to_var)
end
let include_length_vars
(jproc_info:JCHProcInfo.jproc_info_t) (vars:variable_t list) =
let lengths = ref [] in
let add_var var =
try
lengths := (Option.get (jproc_info#get_length var)) :: !lengths
with _ -> () in
begin
List.iter add_var vars ;
vars @ (List.rev !lengths)
end
let include_all_length_vars
(jproc_info:JCHProcInfo.jproc_info_t)
(vars:variable_t list)
(vs:variable_t list)
(length_to_array: variable_t VariableCollections.table_t) =
let v_arrays = length_to_array#listOfValues in
let lengths = ref [] in
let lengths_not_included = ref [] in
let pairs = List.combine vars vs in
let missing_length_indices = ref [] in
let length_index = ref (List.length vars) in
let add_var (var, v) =
if List.mem v v_arrays then
match jproc_info#get_length var with
| Some len -> lengths := len :: !lengths
| _ ->
begin
lengths_not_included :=
(JCHSystemUtils.make_length var) :: !lengths_not_included ;
missing_length_indices := !length_index :: !missing_length_indices ;
incr length_index
end in
begin
List.iter add_var pairs ;
(vars @ (List.rev !lengths), !lengths_not_included, !missing_length_indices)
end
let integer_div (int1:interval_t) (int2:interval_t) =
if int1#isBottom || int2#isBottom then
bottomInterval
else if int2#contains numerical_zero then
topInterval
else
begin
let (a1, b1) = (int1#getMin, int1#getMax) in
let (a2, b2) = (int2#getMin, int2#getMax) in
let l = [a1#div_floor a2; a1#div_floor b2; b1#div_floor a2; b1#div_floor b2] in
let min = CHBounds.min_in_bounds l in
let max = CHBounds.max_in_bounds l in
if max#lt min then
bottomInterval
else
new interval_t min max
end
|
2ea2179d7c81af1edfe8d44a408c2b45d929670f29f43331132a670a8f2e9eb1 | typedclojure/typedclojure | unanalyzed.clj | Copyright ( c ) , contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
(ns ^:no-doc typed.clj.checker.check.unanalyzed
(:require [typed.cljc.checker.check.unanalyzed :as un]))
;; API
(def ^:private this-impl :clojure)
(defn install-unanalyzed-special [v impl-sym]
(un/install-unanalyzed-special #{this-impl} v impl-sym))
(defn install-defuspecial [v impl-sym]
(un/install-defuspecial #{this-impl} v impl-sym))
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/514f2a46ae0145f34bef0400495079ba3292b82b/typed/clj.checker/src/typed/clj/checker/check/unanalyzed.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software.
API | Copyright ( c ) , contributors .
(ns ^:no-doc typed.clj.checker.check.unanalyzed
(:require [typed.cljc.checker.check.unanalyzed :as un]))
(def ^:private this-impl :clojure)
(defn install-unanalyzed-special [v impl-sym]
(un/install-unanalyzed-special #{this-impl} v impl-sym))
(defn install-defuspecial [v impl-sym]
(un/install-defuspecial #{this-impl} v impl-sym))
|
557a4017d91c615331e195e09b3aaaf9f7af1531d9d32690b3653bbaeb1178b0 | Helium4Haskell/helium | DerivingNone.hs | data A = A Int
| B Float
deriving ()
data B = C Int
| D Float
| null | https://raw.githubusercontent.com/Helium4Haskell/helium/5928bff479e6f151b4ceb6c69bbc15d71e29eb47/test/parser/DerivingNone.hs | haskell | data A = A Int
| B Float
deriving ()
data B = C Int
| D Float
| |
255ebf997985fa775deffc94b55d23ea76c9e18c752a5b031a6e0a442317ff51 | ddmcdonald/sparser | vectors.lisp | -*- Mode : LISP ; Syntax : Common - Lisp ; Package : SPARSER -*- ; ; ; copyright ( c ) 1990,1991 Content Technologies Inc.
copyright ( c ) 1992 - 1994,2013,2019 - 2021 -- all rights reserved
;;;
;;; File: "vectors"
;;; Module: "objects/chart/edge vectors/"
Version : August 2021
;; 2.0 (11/26/92 v2.3) bumped on general principles anticipating changes.
2.1 ( 4/6/93 ) Put in switch for vs. vector versions
2.2 ( 4/1/94 ) added remove - edge - from - chart
;; (7/30/13) Added a set of function to lift up the fringe of an
;; established edge, where one of its edges has been composed
;; (to the right) with another edge, and reknit everything together
;; properly. 9/19/13 moved the new stuff to objects/chart/edge-vectors/
;; tuck. 9/23/13 added cleanup-vectors-if-needed
(in-package :sparser)
;;;-------------------------------
;;; adding edges to edge-vectors
;;;-------------------------------
(defun knit-edge-into-positions (edge
starting-vector
ending-vector)
;; The edge has been filled out, all we have to do is add it
;; to the appropriate edge-vector arrays. Since this call
;; has already differentiated which vectors are involved
( i.e. which one does it start in , which one end ) , then
;; the same primitive call can be used on each.
(knit-edge-into-position edge starting-vector)
(knit-edge-into-position edge ending-vector))
(defun knit-edge-into-position (edge vector)
(declare (ignore edge vector))
(error "No value for this switched function.~
~%Call Establish-type-of-edge-vector-to-use"))
(defun knit-edge-into-position/vector (edge vector)
(let ((array (ev-edge-vector vector))
(count (ev-number-of-edges vector)))
(declare (special *maximum-number-of-edges-in-an-edge-vector*))
(when (= 0 count)
This may be the very first time the edge vector at this point
;; in the chart has had edges, have to check and put in an array
;; if needed
(when (null array)
(setf (ev-edge-vector vector)
(setq array (make-edge-vector-array)))))
;;/// there's something wrong with the format expression in
this break but I ca n't see it yet ( ddm 7/31/21 )
(when (>= count *maximum-number-of-edges-in-an-edge-vector*)
(break "Reached the maximum number of edges (~a) allowed on ~
~%an edge-vector.~
~% next edge to add: ~A~
~% at edge-vector: ~A"
*maximum-number-of-edges-in-an-edge-vector*
edge vector))
(setf (aref array count) edge)
(setq count (incf (ev-number-of-edges vector)))
(setf (ev-top-node vector) edge)
vector))
(defun knit-edge-into-position/kcons (edge vector)
(let ((list-so-far (ev-edge-vector vector)))
(setf (ev-edge-vector vector)
(kcons edge list-so-far))
(incf (ev-number-of-edges vector))
(setf (ev-top-node vector) edge)
vector))
;;--- delicate editing // consider refactoring
(defun change-edge-end-position (edge new-ev)
"For chart editing operations only. Reset the
end position of 'edge' to be 'new-pos' sorting out the
edge vectors as needed."
(let ((old-ev (edge-ends-at edge)))
(setf (edge-ends-at edge) new-ev)
(remove-edge-from-vector-ev old-ev edge)
(knit-edge-into-position edge new-ev)
edge))
;;;----------------
;;; removing edges
;;;----------------
(defun remove-and-unhook-edge-from-chart (edge daughters)
(loop for d in daughters
do (setf (edge-used-in d) nil))
(loop for daughter in daughters
do
(set-edge-referent daughter (edge-referent daughter) t))
(remove-edge-from-chart edge))
(defun remove-edge-from-chart (edge)
;; Called by form-rule-completion and by
;; filter-chunk-compatible-edges-from-ev in the chunker
(let ((edges (ev-edges (edge-starts-at edge)))
(starting-vector (edge-starts-at edge))
(ending-vector (edge-ends-at edge)))
(remove-edge-from-position starting-vector edge)
(remove-edge-from-position ending-vector edge)))
(defun remove-edge-from-position (ev edge)
(ecase *edge-vector-type*
(:vector (remove-edge-from-vector-ev ev edge))
(:kcons-list
(break "Stub: write the routine for removing an edge from an~
~%edge-vector based on kcons lists."))))
(defun remove-edge-from-vector-ev (ev edge)
"Remove 'edge' from the the edge vector 'ev', adjusting
the other edges in its array and its meta data accordingly."
(let ((array (ev-edge-vector ev))
(count (ev-number-of-edges ev))
(top-node (ev-top-node ev)))
(cond
((eq edge (aref array (1- count))) ;; it is the last one added
(setf (aref array (decf (ev-number-of-edges ev))) nil)
(reset-ev-top-node ev))
(t
(reset-ev-edges ;; it's in the middle somewhere
ev (loop for e in (all-edges-on ev)
unless (eq e edge) collect e))))
edge ))
(defun reset-ev-top-node (ev)
"Fixes the top-node field after remove-edge-from-vector-ev has taken away
the edge it was told to remove. The ev-number-of-edges of the ev
is already correct, and the edge has been removed from the array."
(let ((count (ev-number-of-edges ev))
(edge-list (all-edges-on ev)))
(cond
((= count 1)
(setf (ev-top-node ev) (car edge-list)))
((every #'one-word-long? edge-list)
(setf (ev-top-node ev) :multiple-initial-edges))
(t
(setf (ev-top-node ev) (aref (ev-edge-vector ev) (1- count)))))
ev))
moved from psp / chunker.lisp
"Called from remove-edge-from-vector-ev when the edge to be
removed is not the last one that was added.
The edge-list contains all of the edges that should still be on
the vector after the removal. This code first clears the array
(sets the cells to nil) and then repopulates it from the
edge-list."
(when ev
#+ignore(if (null (cdr edge-list))
(setf (ev-top-node ev) (car edge-list))
(setf (ev-top-node ev) :multiple-initial-edges))
(loop for i from 0 to (- (length (ev-edge-vector ev)) 1)
do (setf (aref (ev-edge-vector ev) i)
nil))
(loop for i from 0 to (- (length edge-list) 1)
as e in edge-list
do (setf (aref (ev-edge-vector ev) i)
e))
(setf (ev-number-of-edges ev) (length edge-list))
(reset-ev-top-node ev)))
(defun reduce-multiple-initial-edges (ev)
"Some routine has gotten an edge vector where it wanted an edge
and the reason is :multiple-initial-edges. We go through the
edges on the vector and return a list of edges that omits
any that are literals."
;; Called by check-out-possible-conjunction and
;; look-for-da-patterns though should review what they're
;; up to
(let ((count (ev-number-of-edges ev))
(vector (ev-edge-vector ev))
edge good-edges )
(ecase *edge-vector-type*
(:kcons-list (error "Write this routine for kcons list version"))
(:vector
(dotimes (i count)
(setq edge (aref vector i))
(unless (edge-for-literal? edge)
(push edge good-edges)))
(nreverse good-edges)))))
;;;--------------------------------------
;;; Correcting edge order on the vectors
;;;--------------------------------------
(defun cleanup-vectors-if-needed (top-edge)
"Called from peek-rightward just afer it has run a rule that
created a new edge (whose right end happens to be within the
span of this edge). It can happen, e.g. with the word 'driver',
that we create another edge as a side effect (in that case
it's a person given the heuristic about titles in isolation
being take as roles). When something like that happens, the
new edge will have started at the same place as the known-to-be-
top-edge and screw up the ordering on the vector. "
(flet ((swap-top-edge (ev top-edge)
(let* ((array (ev-edge-vector ev))
(index (index-of-edge-in-vector top-edge ev))
(incorrect-top-edge (ev-top-node ev)))
;; swapping them ought to suffice
(setf (aref array index) incorrect-top-edge)
(setf (aref array (1- (ev-number-of-edges ev)))
top-edge)
(setf (ev-top-node ev) top-edge))))
(let ((start (edge-starts-at top-edge))
(end (edge-ends-at top-edge)))
(unless (eq (ev-top-node start) top-edge)
(swap-top-edge start top-edge))
(unless (eq (ev-top-node end) top-edge)
(swap-top-edge end top-edge)))))
| null | https://raw.githubusercontent.com/ddmcdonald/sparser/ad3aae62e6c581fc6e912c143b994af0ca77964d/Sparser/code/s/objects/chart/edge-vectors/vectors.lisp | lisp | Syntax : Common - Lisp ; Package : SPARSER -*- ; ; ; copyright ( c ) 1990,1991 Content Technologies Inc.
File: "vectors"
Module: "objects/chart/edge vectors/"
2.0 (11/26/92 v2.3) bumped on general principles anticipating changes.
(7/30/13) Added a set of function to lift up the fringe of an
established edge, where one of its edges has been composed
(to the right) with another edge, and reknit everything together
properly. 9/19/13 moved the new stuff to objects/chart/edge-vectors/
tuck. 9/23/13 added cleanup-vectors-if-needed
-------------------------------
adding edges to edge-vectors
-------------------------------
The edge has been filled out, all we have to do is add it
to the appropriate edge-vector arrays. Since this call
has already differentiated which vectors are involved
the same primitive call can be used on each.
in the chart has had edges, have to check and put in an array
if needed
/// there's something wrong with the format expression in
--- delicate editing // consider refactoring
----------------
removing edges
----------------
Called by form-rule-completion and by
filter-chunk-compatible-edges-from-ev in the chunker
it is the last one added
it's in the middle somewhere
Called by check-out-possible-conjunction and
look-for-da-patterns though should review what they're
up to
--------------------------------------
Correcting edge order on the vectors
--------------------------------------
swapping them ought to suffice | copyright ( c ) 1992 - 1994,2013,2019 - 2021 -- all rights reserved
Version : August 2021
2.1 ( 4/6/93 ) Put in switch for vs. vector versions
2.2 ( 4/1/94 ) added remove - edge - from - chart
(in-package :sparser)
(defun knit-edge-into-positions (edge
starting-vector
ending-vector)
( i.e. which one does it start in , which one end ) , then
(knit-edge-into-position edge starting-vector)
(knit-edge-into-position edge ending-vector))
(defun knit-edge-into-position (edge vector)
(declare (ignore edge vector))
(error "No value for this switched function.~
~%Call Establish-type-of-edge-vector-to-use"))
(defun knit-edge-into-position/vector (edge vector)
(let ((array (ev-edge-vector vector))
(count (ev-number-of-edges vector)))
(declare (special *maximum-number-of-edges-in-an-edge-vector*))
(when (= 0 count)
This may be the very first time the edge vector at this point
(when (null array)
(setf (ev-edge-vector vector)
(setq array (make-edge-vector-array)))))
this break but I ca n't see it yet ( ddm 7/31/21 )
(when (>= count *maximum-number-of-edges-in-an-edge-vector*)
(break "Reached the maximum number of edges (~a) allowed on ~
~%an edge-vector.~
~% next edge to add: ~A~
~% at edge-vector: ~A"
*maximum-number-of-edges-in-an-edge-vector*
edge vector))
(setf (aref array count) edge)
(setq count (incf (ev-number-of-edges vector)))
(setf (ev-top-node vector) edge)
vector))
(defun knit-edge-into-position/kcons (edge vector)
(let ((list-so-far (ev-edge-vector vector)))
(setf (ev-edge-vector vector)
(kcons edge list-so-far))
(incf (ev-number-of-edges vector))
(setf (ev-top-node vector) edge)
vector))
(defun change-edge-end-position (edge new-ev)
"For chart editing operations only. Reset the
end position of 'edge' to be 'new-pos' sorting out the
edge vectors as needed."
(let ((old-ev (edge-ends-at edge)))
(setf (edge-ends-at edge) new-ev)
(remove-edge-from-vector-ev old-ev edge)
(knit-edge-into-position edge new-ev)
edge))
(defun remove-and-unhook-edge-from-chart (edge daughters)
(loop for d in daughters
do (setf (edge-used-in d) nil))
(loop for daughter in daughters
do
(set-edge-referent daughter (edge-referent daughter) t))
(remove-edge-from-chart edge))
(defun remove-edge-from-chart (edge)
(let ((edges (ev-edges (edge-starts-at edge)))
(starting-vector (edge-starts-at edge))
(ending-vector (edge-ends-at edge)))
(remove-edge-from-position starting-vector edge)
(remove-edge-from-position ending-vector edge)))
(defun remove-edge-from-position (ev edge)
(ecase *edge-vector-type*
(:vector (remove-edge-from-vector-ev ev edge))
(:kcons-list
(break "Stub: write the routine for removing an edge from an~
~%edge-vector based on kcons lists."))))
(defun remove-edge-from-vector-ev (ev edge)
"Remove 'edge' from the the edge vector 'ev', adjusting
the other edges in its array and its meta data accordingly."
(let ((array (ev-edge-vector ev))
(count (ev-number-of-edges ev))
(top-node (ev-top-node ev)))
(cond
(setf (aref array (decf (ev-number-of-edges ev))) nil)
(reset-ev-top-node ev))
(t
ev (loop for e in (all-edges-on ev)
unless (eq e edge) collect e))))
edge ))
(defun reset-ev-top-node (ev)
"Fixes the top-node field after remove-edge-from-vector-ev has taken away
the edge it was told to remove. The ev-number-of-edges of the ev
is already correct, and the edge has been removed from the array."
(let ((count (ev-number-of-edges ev))
(edge-list (all-edges-on ev)))
(cond
((= count 1)
(setf (ev-top-node ev) (car edge-list)))
((every #'one-word-long? edge-list)
(setf (ev-top-node ev) :multiple-initial-edges))
(t
(setf (ev-top-node ev) (aref (ev-edge-vector ev) (1- count)))))
ev))
moved from psp / chunker.lisp
"Called from remove-edge-from-vector-ev when the edge to be
removed is not the last one that was added.
The edge-list contains all of the edges that should still be on
the vector after the removal. This code first clears the array
(sets the cells to nil) and then repopulates it from the
edge-list."
(when ev
#+ignore(if (null (cdr edge-list))
(setf (ev-top-node ev) (car edge-list))
(setf (ev-top-node ev) :multiple-initial-edges))
(loop for i from 0 to (- (length (ev-edge-vector ev)) 1)
do (setf (aref (ev-edge-vector ev) i)
nil))
(loop for i from 0 to (- (length edge-list) 1)
as e in edge-list
do (setf (aref (ev-edge-vector ev) i)
e))
(setf (ev-number-of-edges ev) (length edge-list))
(reset-ev-top-node ev)))
(defun reduce-multiple-initial-edges (ev)
"Some routine has gotten an edge vector where it wanted an edge
and the reason is :multiple-initial-edges. We go through the
edges on the vector and return a list of edges that omits
any that are literals."
(let ((count (ev-number-of-edges ev))
(vector (ev-edge-vector ev))
edge good-edges )
(ecase *edge-vector-type*
(:kcons-list (error "Write this routine for kcons list version"))
(:vector
(dotimes (i count)
(setq edge (aref vector i))
(unless (edge-for-literal? edge)
(push edge good-edges)))
(nreverse good-edges)))))
(defun cleanup-vectors-if-needed (top-edge)
"Called from peek-rightward just afer it has run a rule that
created a new edge (whose right end happens to be within the
span of this edge). It can happen, e.g. with the word 'driver',
that we create another edge as a side effect (in that case
it's a person given the heuristic about titles in isolation
being take as roles). When something like that happens, the
new edge will have started at the same place as the known-to-be-
top-edge and screw up the ordering on the vector. "
(flet ((swap-top-edge (ev top-edge)
(let* ((array (ev-edge-vector ev))
(index (index-of-edge-in-vector top-edge ev))
(incorrect-top-edge (ev-top-node ev)))
(setf (aref array index) incorrect-top-edge)
(setf (aref array (1- (ev-number-of-edges ev)))
top-edge)
(setf (ev-top-node ev) top-edge))))
(let ((start (edge-starts-at top-edge))
(end (edge-ends-at top-edge)))
(unless (eq (ev-top-node start) top-edge)
(swap-top-edge start top-edge))
(unless (eq (ev-top-node end) top-edge)
(swap-top-edge end top-edge)))))
|
5222c9ab930105bc61919a31f89142efd1c9c8af7b1b04e8ff7d65c520d03934 | peak6/mmd_core | mmd_core_app.erl | %%%-------------------------------------------------------------------
@author < >
( C ) 2011 ,
%%% @doc
%%%
%%% @end
Created : 17 Mar 2011 by < >
%%%-------------------------------------------------------------------
-module(mmd_core_app).
-behaviour(application).
%% Application callbacks
-export([start/2, stop/1]).
-include("mmd.hrl").
%%%===================================================================
%%% Application callbacks
%%%===================================================================
%%--------------------------------------------------------------------
@private
%% @doc
%% This function is called whenever an application is started using
application : start/[1,2 ] , and should start the processes of the
%% application. If the application is structured according to the OTP
%% design principles as a supervision tree, this means starting the
%% top supervisor of the tree.
%%
@spec start(StartType , ) - > { ok , Pid } |
{ ok , Pid , State } |
%% {error, Reason}
%% StartType = normal | {takeover, Node} | {failover, Node}
= term ( )
%% @end
%%--------------------------------------------------------------------
start(_StartType, _StartArgs) ->
case mmd_core_sup:start_link() of
{ok, Pid} ->
{ok, Pid};
Error ->
Error
end.
%%--------------------------------------------------------------------
@private
%% @doc
%% This function is called whenever an application has stopped. It
%% is intended to be the opposite of Module:start/2 and should do
%% any necessary cleaning up. The return value is ignored.
%%
%% @spec stop(State) -> void()
%% @end
%%--------------------------------------------------------------------
stop(_State) ->
init:stop(?EXIT_ERROR),
ok.
%%%===================================================================
Internal functions
%%%===================================================================
vim : ts=4 : sts=4 : sw=4 : et : :
| null | https://raw.githubusercontent.com/peak6/mmd_core/f90469ea9eac8cd607aa6ec5b9ad6ff003a35572/src/mmd_core_app.erl | erlang | -------------------------------------------------------------------
@doc
@end
-------------------------------------------------------------------
Application callbacks
===================================================================
Application callbacks
===================================================================
--------------------------------------------------------------------
@doc
This function is called whenever an application is started using
application. If the application is structured according to the OTP
design principles as a supervision tree, this means starting the
top supervisor of the tree.
{error, Reason}
StartType = normal | {takeover, Node} | {failover, Node}
@end
--------------------------------------------------------------------
--------------------------------------------------------------------
@doc
This function is called whenever an application has stopped. It
is intended to be the opposite of Module:start/2 and should do
any necessary cleaning up. The return value is ignored.
@spec stop(State) -> void()
@end
--------------------------------------------------------------------
===================================================================
=================================================================== | @author < >
( C ) 2011 ,
Created : 17 Mar 2011 by < >
-module(mmd_core_app).
-behaviour(application).
-export([start/2, stop/1]).
-include("mmd.hrl").
@private
application : start/[1,2 ] , and should start the processes of the
@spec start(StartType , ) - > { ok , Pid } |
{ ok , Pid , State } |
= term ( )
start(_StartType, _StartArgs) ->
case mmd_core_sup:start_link() of
{ok, Pid} ->
{ok, Pid};
Error ->
Error
end.
@private
stop(_State) ->
init:stop(?EXIT_ERROR),
ok.
Internal functions
vim : ts=4 : sts=4 : sw=4 : et : :
|
fbb3a7cfdbc2d71af470b98753a074db64440368b7ac39d761cc41c0e06f5a6c | ocamllabs/ocaml-effects | misc.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
(* Errors *)
exception Fatal_error
let fatal_error msg =
prerr_string ">> Fatal error: "; prerr_endline msg; raise Fatal_error
(* Exceptions *)
let try_finally work cleanup =
let result = (try work () with e -> cleanup (); raise e) in
cleanup ();
result
;;
(* List functions *)
let rec map_end f l1 l2 =
match l1 with
[] -> l2
| hd::tl -> f hd :: map_end f tl l2
let rec map_left_right f = function
[] -> []
| hd::tl -> let res = f hd in res :: map_left_right f tl
let rec for_all2 pred l1 l2 =
match (l1, l2) with
([], []) -> true
| (hd1::tl1, hd2::tl2) -> pred hd1 hd2 && for_all2 pred tl1 tl2
| (_, _) -> false
let rec replicate_list elem n =
if n <= 0 then [] else elem :: replicate_list elem (n-1)
let rec list_remove x = function
[] -> []
| hd :: tl ->
if hd = x then tl else hd :: list_remove x tl
let rec split_last = function
[] -> assert false
| [x] -> ([], x)
| hd :: tl ->
let (lst, last) = split_last tl in
(hd :: lst, last)
let rec samelist pred l1 l2 =
match (l1, l2) with
| ([], []) -> true
| (hd1 :: tl1, hd2 :: tl2) -> pred hd1 hd2 && samelist pred tl1 tl2
| (_, _) -> false
(* Options *)
let may f = function
Some x -> f x
| None -> ()
let may_map f = function
Some x -> Some (f x)
| None -> None
(* File functions *)
let find_in_path path name =
if not (Filename.is_implicit name) then
if Sys.file_exists name then name else raise Not_found
else begin
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name in
if Sys.file_exists fullname then fullname else try_dir rem
in try_dir path
end
let find_in_path_rel path name =
let rec simplify s =
let open Filename in
let base = basename s in
let dir = dirname s in
if dir = s then dir
else if base = current_dir_name then simplify dir
else concat (simplify dir) base
in
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = simplify (Filename.concat dir name) in
if Sys.file_exists fullname then fullname else try_dir rem
in try_dir path
let find_in_path_uncap path name =
let uname = String.uncapitalize_ascii name in
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name
and ufullname = Filename.concat dir uname in
if Sys.file_exists ufullname then ufullname
else if Sys.file_exists fullname then fullname
else try_dir rem
in try_dir path
let remove_file filename =
try
Sys.remove filename
with Sys_error msg ->
()
(* Expand a -I option: if it starts with +, make it relative to the standard
library directory *)
let expand_directory alt s =
if String.length s > 0 && s.[0] = '+'
then Filename.concat alt
(String.sub s 1 (String.length s - 1))
else s
(* Hashtable functions *)
let create_hashtable size init =
let tbl = Hashtbl.create size in
List.iter (fun (key, data) -> Hashtbl.add tbl key data) init;
tbl
(* File copy *)
let copy_file ic oc =
let buff = Bytes.create 0x1000 in
let rec copy () =
let n = input ic buff 0 0x1000 in
if n = 0 then () else (output oc buff 0 n; copy())
in copy()
let copy_file_chunk ic oc len =
let buff = Bytes.create 0x1000 in
let rec copy n =
if n <= 0 then () else begin
let r = input ic buff 0 (min n 0x1000) in
if r = 0 then raise End_of_file else (output oc buff 0 r; copy(n-r))
end
in copy len
let string_of_file ic =
let b = Buffer.create 0x10000 in
let buff = Bytes.create 0x1000 in
let rec copy () =
let n = input ic buff 0 0x1000 in
if n = 0 then Buffer.contents b else
(Buffer.add_subbytes b buff 0 n; copy())
in copy()
Integer operations
let rec log2 n =
if n <= 1 then 0 else 1 + log2(n asr 1)
let align n a =
if n >= 0 then (n + a - 1) land (-a) else n land (-a)
let no_overflow_add a b = (a lxor b) lor (a lxor (lnot (a+b))) < 0
let no_overflow_sub a b = (a lxor (lnot b)) lor (b lxor (a-b)) < 0
let no_overflow_mul a b = b <> 0 && (a * b) / b = a
let no_overflow_lsl a k = 0 <= k && k < Sys.word_size && min_int asr k <= a && a <= max_int asr k
(* String operations *)
let chop_extension_if_any fname =
try Filename.chop_extension fname with Invalid_argument _ -> fname
let chop_extensions file =
let dirname = Filename.dirname file and basename = Filename.basename file in
try
let pos = String.index basename '.' in
let basename = String.sub basename 0 pos in
if Filename.is_implicit file && dirname = Filename.current_dir_name then
basename
else
Filename.concat dirname basename
with Not_found -> file
let search_substring pat str start =
let rec search i j =
if j >= String.length pat then i
else if i + j >= String.length str then raise Not_found
else if str.[i + j] = pat.[j] then search i (j+1)
else search (i+1) 0
in search start 0
let replace_substring ~before ~after str =
let rec search acc curr =
match search_substring before str curr with
| next ->
let prefix = String.sub str curr (next - curr) in
search (prefix :: acc) (next + String.length before)
| exception Not_found ->
let suffix = String.sub str curr (String.length str - curr) in
List.rev (suffix :: acc)
in String.concat after (search [] 0)
let rev_split_words s =
let rec split1 res i =
if i >= String.length s then res else begin
match s.[i] with
' ' | '\t' | '\r' | '\n' -> split1 res (i+1)
| _ -> split2 res i (i+1)
end
and split2 res i j =
if j >= String.length s then String.sub s i (j-i) :: res else begin
match s.[j] with
' ' | '\t' | '\r' | '\n' -> split1 (String.sub s i (j-i) :: res) (j+1)
| _ -> split2 res i (j+1)
end
in split1 [] 0
let get_ref r =
let v = !r in
r := []; v
let fst3 (x, _, _) = x
let snd3 (_,x,_) = x
let thd3 (_,_,x) = x
let fst4 (x, _, _, _) = x
let snd4 (_,x,_, _) = x
let thd4 (_,_,x,_) = x
let for4 (_,_,_,x) = x
module LongString = struct
type t = bytes array
let create str_size =
let tbl_size = str_size / Sys.max_string_length + 1 in
let tbl = Array.make tbl_size Bytes.empty in
for i = 0 to tbl_size - 2 do
tbl.(i) <- Bytes.create Sys.max_string_length;
done;
tbl.(tbl_size - 1) <- Bytes.create (str_size mod Sys.max_string_length);
tbl
let length tbl =
let tbl_size = Array.length tbl in
Sys.max_string_length * (tbl_size - 1) + Bytes.length tbl.(tbl_size - 1)
let get tbl ind =
Bytes.get tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length)
let set tbl ind c =
Bytes.set tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length)
c
let blit src srcoff dst dstoff len =
for i = 0 to len - 1 do
set dst (dstoff + i) (get src (srcoff + i))
done
let output oc tbl pos len =
for i = pos to pos + len - 1 do
output_char oc (get tbl i)
done
let unsafe_blit_to_bytes src srcoff dst dstoff len =
for i = 0 to len - 1 do
Bytes.unsafe_set dst (dstoff + i) (get src (srcoff + i))
done
let input_bytes ic len =
let tbl = create len in
Array.iter (fun str -> really_input ic str 0 (Bytes.length str)) tbl;
tbl
end
let edit_distance a b cutoff =
let la, lb = String.length a, String.length b in
let cutoff =
using max_int for cutoff would cause overflows in ( i + cutoff + 1 ) ;
we bring it back to the ( max la lb )
we bring it back to the (max la lb) worstcase *)
min (max la lb) cutoff in
if abs (la - lb) > cutoff then None
else begin
(* initialize with 'cutoff + 1' so that not-yet-written-to cases have
the worst possible cost; this is useful when computing the cost of
a case just at the boundary of the cutoff diagonal. *)
let m = Array.make_matrix (la + 1) (lb + 1) (cutoff + 1) in
m.(0).(0) <- 0;
for i = 1 to la do
m.(i).(0) <- i;
done;
for j = 1 to lb do
m.(0).(j) <- j;
done;
for i = 1 to la do
for j = max 1 (i - cutoff - 1) to min lb (i + cutoff + 1) do
let cost = if a.[i-1] = b.[j-1] then 0 else 1 in
let best =
(* insert, delete or substitute *)
min (1 + min m.(i-1).(j) m.(i).(j-1)) (m.(i-1).(j-1) + cost)
in
let best =
swap two adjacent letters ; we use " cost " again in case of
a swap between two identical letters ; this is slightly
redundant as this is a double - substitution case , but it
was done this way in most online implementations and
imitation has its virtues
a swap between two identical letters; this is slightly
redundant as this is a double-substitution case, but it
was done this way in most online implementations and
imitation has its virtues *)
if not (i > 1 && j > 1 && a.[i-1] = b.[j-2] && a.[i-2] = b.[j-1])
then best
else min best (m.(i-2).(j-2) + cost)
in
m.(i).(j) <- best
done;
done;
let result = m.(la).(lb) in
if result > cutoff
then None
else Some result
end
let spellcheck env name =
let cutoff =
match String.length name with
| 1 | 2 -> 0
| 3 | 4 -> 1
| 5 | 6 -> 2
| _ -> 3
in
let compare target acc head =
match edit_distance target head cutoff with
| None -> acc
| Some dist ->
let (best_choice, best_dist) = acc in
if dist < best_dist then ([head], dist)
else if dist = best_dist then (head :: best_choice, dist)
else acc
in
fst (List.fold_left (compare name) ([], max_int) env)
let did_you_mean ppf get_choices =
(* flush now to get the error report early, in the (unheard of) case
where the search in the get_choices function would take a bit of
time; in the worst case, the user has seen the error, she can
interrupt the process before the spell-checking terminates. *)
Format.fprintf ppf "@?";
match get_choices () with
| [] -> ()
| choices ->
let rest, last = split_last choices in
Format.fprintf ppf "@\nHint: Did you mean %s%s%s?"
(String.concat ", " rest)
(if rest = [] then "" else " or ")
last
(* split a string [s] at every char [c], and return the list of sub-strings *)
let split s c =
let len = String.length s in
let rec iter pos to_rev =
if pos = len then List.rev ("" :: to_rev) else
match try
Some ( String.index_from s pos c )
with Not_found -> None
with
Some pos2 ->
if pos2 = pos then iter (pos+1) ("" :: to_rev) else
iter (pos2+1) ((String.sub s pos (pos2-pos)) :: to_rev)
| None -> List.rev ( String.sub s pos (len-pos) :: to_rev )
in
iter 0 []
let cut_at s c =
let pos = String.index s c in
String.sub s 0 pos, String.sub s (pos+1) (String.length s - pos - 1)
module StringSet = Set.Make(struct type t = string let compare = compare end)
module StringMap = Map.Make(struct type t = string let compare = compare end)
| null | https://raw.githubusercontent.com/ocamllabs/ocaml-effects/36008b741adc201bf9b547545344507da603ae31/utils/misc.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
Errors
Exceptions
List functions
Options
File functions
Expand a -I option: if it starts with +, make it relative to the standard
library directory
Hashtable functions
File copy
String operations
initialize with 'cutoff + 1' so that not-yet-written-to cases have
the worst possible cost; this is useful when computing the cost of
a case just at the boundary of the cutoff diagonal.
insert, delete or substitute
flush now to get the error report early, in the (unheard of) case
where the search in the get_choices function would take a bit of
time; in the worst case, the user has seen the error, she can
interrupt the process before the spell-checking terminates.
split a string [s] at every char [c], and return the list of sub-strings | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
exception Fatal_error
let fatal_error msg =
prerr_string ">> Fatal error: "; prerr_endline msg; raise Fatal_error
let try_finally work cleanup =
let result = (try work () with e -> cleanup (); raise e) in
cleanup ();
result
;;
let rec map_end f l1 l2 =
match l1 with
[] -> l2
| hd::tl -> f hd :: map_end f tl l2
let rec map_left_right f = function
[] -> []
| hd::tl -> let res = f hd in res :: map_left_right f tl
let rec for_all2 pred l1 l2 =
match (l1, l2) with
([], []) -> true
| (hd1::tl1, hd2::tl2) -> pred hd1 hd2 && for_all2 pred tl1 tl2
| (_, _) -> false
let rec replicate_list elem n =
if n <= 0 then [] else elem :: replicate_list elem (n-1)
let rec list_remove x = function
[] -> []
| hd :: tl ->
if hd = x then tl else hd :: list_remove x tl
let rec split_last = function
[] -> assert false
| [x] -> ([], x)
| hd :: tl ->
let (lst, last) = split_last tl in
(hd :: lst, last)
let rec samelist pred l1 l2 =
match (l1, l2) with
| ([], []) -> true
| (hd1 :: tl1, hd2 :: tl2) -> pred hd1 hd2 && samelist pred tl1 tl2
| (_, _) -> false
let may f = function
Some x -> f x
| None -> ()
let may_map f = function
Some x -> Some (f x)
| None -> None
let find_in_path path name =
if not (Filename.is_implicit name) then
if Sys.file_exists name then name else raise Not_found
else begin
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name in
if Sys.file_exists fullname then fullname else try_dir rem
in try_dir path
end
let find_in_path_rel path name =
let rec simplify s =
let open Filename in
let base = basename s in
let dir = dirname s in
if dir = s then dir
else if base = current_dir_name then simplify dir
else concat (simplify dir) base
in
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = simplify (Filename.concat dir name) in
if Sys.file_exists fullname then fullname else try_dir rem
in try_dir path
let find_in_path_uncap path name =
let uname = String.uncapitalize_ascii name in
let rec try_dir = function
[] -> raise Not_found
| dir::rem ->
let fullname = Filename.concat dir name
and ufullname = Filename.concat dir uname in
if Sys.file_exists ufullname then ufullname
else if Sys.file_exists fullname then fullname
else try_dir rem
in try_dir path
let remove_file filename =
try
Sys.remove filename
with Sys_error msg ->
()
let expand_directory alt s =
if String.length s > 0 && s.[0] = '+'
then Filename.concat alt
(String.sub s 1 (String.length s - 1))
else s
let create_hashtable size init =
let tbl = Hashtbl.create size in
List.iter (fun (key, data) -> Hashtbl.add tbl key data) init;
tbl
let copy_file ic oc =
let buff = Bytes.create 0x1000 in
let rec copy () =
let n = input ic buff 0 0x1000 in
if n = 0 then () else (output oc buff 0 n; copy())
in copy()
let copy_file_chunk ic oc len =
let buff = Bytes.create 0x1000 in
let rec copy n =
if n <= 0 then () else begin
let r = input ic buff 0 (min n 0x1000) in
if r = 0 then raise End_of_file else (output oc buff 0 r; copy(n-r))
end
in copy len
let string_of_file ic =
let b = Buffer.create 0x10000 in
let buff = Bytes.create 0x1000 in
let rec copy () =
let n = input ic buff 0 0x1000 in
if n = 0 then Buffer.contents b else
(Buffer.add_subbytes b buff 0 n; copy())
in copy()
Integer operations
let rec log2 n =
if n <= 1 then 0 else 1 + log2(n asr 1)
let align n a =
if n >= 0 then (n + a - 1) land (-a) else n land (-a)
let no_overflow_add a b = (a lxor b) lor (a lxor (lnot (a+b))) < 0
let no_overflow_sub a b = (a lxor (lnot b)) lor (b lxor (a-b)) < 0
let no_overflow_mul a b = b <> 0 && (a * b) / b = a
let no_overflow_lsl a k = 0 <= k && k < Sys.word_size && min_int asr k <= a && a <= max_int asr k
let chop_extension_if_any fname =
try Filename.chop_extension fname with Invalid_argument _ -> fname
let chop_extensions file =
let dirname = Filename.dirname file and basename = Filename.basename file in
try
let pos = String.index basename '.' in
let basename = String.sub basename 0 pos in
if Filename.is_implicit file && dirname = Filename.current_dir_name then
basename
else
Filename.concat dirname basename
with Not_found -> file
let search_substring pat str start =
let rec search i j =
if j >= String.length pat then i
else if i + j >= String.length str then raise Not_found
else if str.[i + j] = pat.[j] then search i (j+1)
else search (i+1) 0
in search start 0
let replace_substring ~before ~after str =
let rec search acc curr =
match search_substring before str curr with
| next ->
let prefix = String.sub str curr (next - curr) in
search (prefix :: acc) (next + String.length before)
| exception Not_found ->
let suffix = String.sub str curr (String.length str - curr) in
List.rev (suffix :: acc)
in String.concat after (search [] 0)
let rev_split_words s =
let rec split1 res i =
if i >= String.length s then res else begin
match s.[i] with
' ' | '\t' | '\r' | '\n' -> split1 res (i+1)
| _ -> split2 res i (i+1)
end
and split2 res i j =
if j >= String.length s then String.sub s i (j-i) :: res else begin
match s.[j] with
' ' | '\t' | '\r' | '\n' -> split1 (String.sub s i (j-i) :: res) (j+1)
| _ -> split2 res i (j+1)
end
in split1 [] 0
let get_ref r =
let v = !r in
r := []; v
let fst3 (x, _, _) = x
let snd3 (_,x,_) = x
let thd3 (_,_,x) = x
let fst4 (x, _, _, _) = x
let snd4 (_,x,_, _) = x
let thd4 (_,_,x,_) = x
let for4 (_,_,_,x) = x
module LongString = struct
type t = bytes array
let create str_size =
let tbl_size = str_size / Sys.max_string_length + 1 in
let tbl = Array.make tbl_size Bytes.empty in
for i = 0 to tbl_size - 2 do
tbl.(i) <- Bytes.create Sys.max_string_length;
done;
tbl.(tbl_size - 1) <- Bytes.create (str_size mod Sys.max_string_length);
tbl
let length tbl =
let tbl_size = Array.length tbl in
Sys.max_string_length * (tbl_size - 1) + Bytes.length tbl.(tbl_size - 1)
let get tbl ind =
Bytes.get tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length)
let set tbl ind c =
Bytes.set tbl.(ind / Sys.max_string_length) (ind mod Sys.max_string_length)
c
let blit src srcoff dst dstoff len =
for i = 0 to len - 1 do
set dst (dstoff + i) (get src (srcoff + i))
done
let output oc tbl pos len =
for i = pos to pos + len - 1 do
output_char oc (get tbl i)
done
let unsafe_blit_to_bytes src srcoff dst dstoff len =
for i = 0 to len - 1 do
Bytes.unsafe_set dst (dstoff + i) (get src (srcoff + i))
done
let input_bytes ic len =
let tbl = create len in
Array.iter (fun str -> really_input ic str 0 (Bytes.length str)) tbl;
tbl
end
let edit_distance a b cutoff =
let la, lb = String.length a, String.length b in
let cutoff =
using max_int for cutoff would cause overflows in ( i + cutoff + 1 ) ;
we bring it back to the ( max la lb )
we bring it back to the (max la lb) worstcase *)
min (max la lb) cutoff in
if abs (la - lb) > cutoff then None
else begin
let m = Array.make_matrix (la + 1) (lb + 1) (cutoff + 1) in
m.(0).(0) <- 0;
for i = 1 to la do
m.(i).(0) <- i;
done;
for j = 1 to lb do
m.(0).(j) <- j;
done;
for i = 1 to la do
for j = max 1 (i - cutoff - 1) to min lb (i + cutoff + 1) do
let cost = if a.[i-1] = b.[j-1] then 0 else 1 in
let best =
min (1 + min m.(i-1).(j) m.(i).(j-1)) (m.(i-1).(j-1) + cost)
in
let best =
swap two adjacent letters ; we use " cost " again in case of
a swap between two identical letters ; this is slightly
redundant as this is a double - substitution case , but it
was done this way in most online implementations and
imitation has its virtues
a swap between two identical letters; this is slightly
redundant as this is a double-substitution case, but it
was done this way in most online implementations and
imitation has its virtues *)
if not (i > 1 && j > 1 && a.[i-1] = b.[j-2] && a.[i-2] = b.[j-1])
then best
else min best (m.(i-2).(j-2) + cost)
in
m.(i).(j) <- best
done;
done;
let result = m.(la).(lb) in
if result > cutoff
then None
else Some result
end
let spellcheck env name =
let cutoff =
match String.length name with
| 1 | 2 -> 0
| 3 | 4 -> 1
| 5 | 6 -> 2
| _ -> 3
in
let compare target acc head =
match edit_distance target head cutoff with
| None -> acc
| Some dist ->
let (best_choice, best_dist) = acc in
if dist < best_dist then ([head], dist)
else if dist = best_dist then (head :: best_choice, dist)
else acc
in
fst (List.fold_left (compare name) ([], max_int) env)
let did_you_mean ppf get_choices =
Format.fprintf ppf "@?";
match get_choices () with
| [] -> ()
| choices ->
let rest, last = split_last choices in
Format.fprintf ppf "@\nHint: Did you mean %s%s%s?"
(String.concat ", " rest)
(if rest = [] then "" else " or ")
last
let split s c =
let len = String.length s in
let rec iter pos to_rev =
if pos = len then List.rev ("" :: to_rev) else
match try
Some ( String.index_from s pos c )
with Not_found -> None
with
Some pos2 ->
if pos2 = pos then iter (pos+1) ("" :: to_rev) else
iter (pos2+1) ((String.sub s pos (pos2-pos)) :: to_rev)
| None -> List.rev ( String.sub s pos (len-pos) :: to_rev )
in
iter 0 []
let cut_at s c =
let pos = String.index s c in
String.sub s 0 pos, String.sub s (pos+1) (String.length s - pos - 1)
module StringSet = Set.Make(struct type t = string let compare = compare end)
module StringMap = Map.Make(struct type t = string let compare = compare end)
|
778142dc600a04e5e1d84a7c4c843197222fd29dbee66c21c99565bc152adb93 | spl/ivy | stypechecker.ml | (*
* stypechecker.ml
*
* The SharC type checker.
*
*
*)
open Cil
open Expcompare
open Pretty
open Ivyoptions
open Ivyutil
open Sfunctions
open Sutil
module E = Errormsg
module UD = Usedef
module VS = UD.VS
type compatType =
| Equal
| CheckRead of attrparam * attrparam option (* attrparam is size in bytes *)
| CheckWrite of attrparam * attrparam option
| Cast
| NotEqual
let ptrQualsCompatible (da : attributes) (sa : attributes) : compatType =
match qualFromAttrs da, qualFromAttrs sa with
| (NoQual | MultiQual), _
| _, (NoQual | MultiQual) ->
E.error "Malformed sharing types";
NotEqual
| OneQual(Attr(ds,apl)), OneQual(Attr(ss,dapl)) -> begin
let dgt = hasAttribute "sgroup" da in
let sgt = hasAttribute "sgroup" sa in
let onegroup = (dgt && not(sgt)) || (not(dgt) && sgt) in
if qeq ds ss && onegroup then NotEqual else
if qeq ds ss then Equal else
match ds, ss with
| "sreads", ("sprivate"|"sreadonly"|"sracy") -> Equal
| "sreads", "sdynbar" -> CheckRead (List.hd apl, Some(List.hd dapl))
| "sreads", _ -> CheckRead (List.hd apl, None)
| "swrites", ("sprivate"|"sracy") -> Equal
| "swrites", "sdynbar" -> CheckWrite (List.hd apl, Some(List.hd dapl))
| "swrites", _ -> CheckWrite (List.hd apl, None)
| "sindynamic", "sprivate" -> if onegroup then NotEqual else Equal
| _, _ -> Cast
end
* TODO :
An expression of structure type can be opened when it contains fields
with SSAME in their type(otherwise , there 's no need to ) , and when it
is either SPRIVATE , when the lock is heald , or SREADONLY so long
as the SSAME fields are not written .
Maybe ...
{ SOPEN(e )
/ * in here the SSAME fields of e can be read and written , but not
aliased . They can be SCAST , though . * /
}
An expression of structure type can be opened when it contains fields
with SSAME in their type(otherwise, there's no need to), and when it
is either SPRIVATE, SLOCKED when the lock is heald, or SREADONLY so long
as the SSAME fields are not written.
Maybe...
{ SOPEN(e)
/* in here the SSAME fields of e can be read and written, but not
aliased. They can be SCAST, though. */
}
*)
(* The Comp is castable if there are no sctx qualifiers on the target types
of pointers *)
CHANGE : This is obviated by placing on unqualified target types in
scasted structs , so just return true
scasted structs, so just return true *)
let rec isCastableComp ?(ctx : string list = []) (ci : compinfo) : bool = true
List.mem ci.cname ctx ||
not(List.exists ( fun fi - >
match unrollType fi.ftype with
| TPtr(rt , a ) | TArray(rt,_,a ) - > begin
isCtxType rt ||
match with
| TComp(ci',a ) - > isCastableComp ~ctx:(ci.cname::ctx ) ci '
| _ - > false
end
| TComp(ci',a ) - > isCastableComp ~ctx:(ci.cname::ctx ) '
| _ - > false )
ci.cfields )
List.mem ci.cname ctx ||
not(List.exists (fun fi ->
match unrollType fi.ftype with
| TPtr(rt,a) | TArray(rt,_,a) -> begin
isCtxType rt ||
match unrollType rt with
| TComp(ci',a) -> isCastableComp ~ctx:(ci.cname::ctx) ci'
| _ -> false
end
| TComp(ci',a) -> isCastableComp ~ctx:(ci.cname::ctx) ci'
| _ -> false)
ci.cfields)
*)
For type equality purposes , sdynamic = = sindynamic = = soutdynamic ,
so before comparing types , rename everything to sdynamic
so before comparing types, rename everything to sdynamic *)
class qualMergerClass = object(self)
inherit nopCilVisitor
method vattr (a : attribute) =
match a with
| Attr(("sindynamic"|"soutdynamic"),ap) ->
ChangeTo[Attr("sdynamic",ap)]
| Attr("slocked",_) ->
ChangeTo[Attr("slocked",[])]
| _ -> SkipChildren
end
let qualMerger (t : typ) : typ =
visitCilType (new qualMergerClass) t
let compareSharCTypes = compareTypes ~importantAttr:isSharCSharingAttr
are drt and srt compatible pointer target types ?
(*
Casting to and from void * is allowed if the sharing doesn't change.
Casting pointers to structures is allowed when all pointers in the structure
are explicitly given the ssame qualifier.
Casting between pointers to pointers is allowed if the referrent types are
equivalent.
*)
let rec ptrTypesCompatible (drt : typ) (srt : typ) : compatType =
let qres = ptrQualsCompatible (typeAttrs drt) (typeAttrs srt) in
let mdrt = qualMerger drt in
let msrt = qualMerger srt in
if compareSharCTypes mdrt msrt then qres else
match drt, srt with
| TNamed(ti, _), _ -> ptrTypesCompatible ti.ttype srt
| _, TNamed(ti, _) -> ptrTypesCompatible drt ti.ttype
| TVoid _, _ | _, TVoid _ when qres <> Cast -> qres
| TInt _, _ | _, TInt _ when qres <> Cast -> qres (* old code uses char as void *)
| TComp _, TComp _ when qres <> Cast -> qres
| TComp(ci1,_),TComp(ci2,_) when qres = Cast ->
if isCastableComp ci1 then Cast else NotEqual
| TInt _, (TPtr _ | TArray _) -> qres
| (TPtr(TVoid da,_)|TArray(TVoid da,_,_)),
(TPtr(srt,_)|TArray(srt,_,_)) -> begin
(* Can cast other pointer types to void * when the
sharing mode is the same *)
match qualFromAttrs da, qualFromAttrs (typeAttrs srt) with
| OneQual(Attr(dq,_)), OneQual(Attr(sq,_)) when qeq dq sq -> qres
| _ -> NotEqual
end
| (TPtr(drt,_)|TArray(drt,_,_)), (TPtr(srt,_)|TArray(srt,_,_)) ->
let mdrt = qualMerger drt in
let msrt = qualMerger srt in
if compareSharCTypes mdrt msrt then
qres
else if ptrTypesCompatible mdrt msrt = Equal then
qres
else NotEqual
| (TInt _ | TFloat _ | TEnum _ | TBuiltin_va_list _),
(TInt _ | TFloat _ | TEnum _ | TBuiltin_va_list _) ->
qres
| TFun(voidType,Some tal,false,_), TFun(_,Some sal,false,_)
when Dattrs.isDeallocator srt ->
(* pointers to deallocators match function pointer types with the
correct number of arguments *)
if List.length tal = List.length sal then
qres
else NotEqual
| _ -> NotEqual
(* x:t1 <-- y:t2, or f(y:t2) where f takes a t1,
or return y:t2 when the function returns t1 *)
let rec typesCompatible (dstt : typ) (srct : typ) : compatType =
if not(isPtrType dstt) && not(isPtrType srct) then Equal else
let mdstt = qualMerger dstt in
let msrct = qualMerger srct in
if compareSharCTypes mdstt msrct then Equal else
match dstt, srct with
| TNamed(ti,a), _ -> typesCompatible ti.ttype srct
| _, TNamed(ti,a) -> typesCompatible dstt ti.ttype
| (TInt(_,_)|TEnum(_,_)), TPtr(_,_) -> Equal (* casting pointer to int OK *)
| TPtr(rt,_), (TInt(_,_) | TEnum(_,_)) -> begin
match unrollType rt with
| TVoid _ -> Equal
| _ ->
(* Casting an integer to a pointer is definitely unsound, but it happens
often enough that we'll allow it and give a very stern warning *)
E.warn ("Casting an integer to a pointer is unsound at %a."^^
"You better know what you're doing.") d_loc (!currentLoc);
Equal
end
| (TPtr(drt,da) | TArray(drt,_,da)), (TPtr(srt, sa) | TArray(srt,_,sa)) ->
ptrTypesCompatible drt srt
| TPtr _, TFun _ -> (* promote function to function pointer *)
typesCompatible dstt (TPtr(srct,[sprivate]))
| _, _ ->
E.log "typesCompatible: %a != %a\n" sp_type dstt sp_type srct;
NotEqual
let isAllocator (fe : exp) : bool =
match fe with
| Lval(Var fvi, NoOffset)
when fvi.vname = "malloc" || fvi.vname = "realloc" -> true
| _ -> Dattrs.isAllocator(typeOf fe)
let isDeallocator (fe : exp) : bool =
match fe with
| Lval(Var fvi, NoOffset)
when fvi.vname = "free" -> true
| _ -> Dattrs.isDeallocator(typeOf fe)
(* This visitor does the type checking *)
class typeCheckerClass (fd : fundec) (checks : bool ref) = object(self)
Liveness.livenessVisitorClass true as super
method private isConst (e : exp) : bool =
match e with
| Const _ -> true
| CastE(_,e) -> self#isConst e
| _ -> false
method private getBaseLval (e : exp) : lval option =
match e with
| Lval lv -> Some lv
| StartOf lv -> begin
match lv with
| (Mem e, _) -> self#getBaseLval e
| _ -> None
end
| CastE(_,e)
| BinOp(_,e,_,_) -> self#getBaseLval e
| _ -> None
method private handleRet loc lvo rt : unit =
match lvo with
| None -> ()
| Some lv ->
let lvt = sharCTypeOfLval lv in
match typesCompatible lvt rt with
| Cast ->
E.error ("Sharing cast needed for assignment at %a\n\t"^^
"Got: %a\n\tExpected: %a")
d_loc loc sp_type rt sp_type lvt;
checks := false
| NotEqual ->
E.error ("Types not compatible in assignment at %a\n\t"^^
"Got: %a\n\tExpected: %a")
d_loc loc sp_type rt sp_type lvt;
checks := false
| _ -> ()
method private checkSingleArg loc (n,t,a) arg : unit =
if self#isConst arg then () else
match typesCompatible t (sharCTypeOf arg) with
| Cast ->
E.error ("Sharing cast needed for argument: %a at %a\n\t"^^
"Got: %a\n\tExpected: %a")
sp_exp arg d_loc loc sp_type (sharCTypeOf arg) sp_type t;
checks := false
| NotEqual ->
E.error ("Types not compatible for argument %a at %a\n\t"^^
"Got: %a\n\tExpected: %a")
sp_exp arg d_loc loc sp_type (sharCTypeOf arg) sp_type t;
checks := false
| _ -> ()
method private handleArgs loc args argtso : unit =
match argtso with
| Some argts -> begin
if List.length args <> List.length argts then begin
E.warn " Not checking call with wrong number of args at % a "
d_loc loc
d_loc loc*)
()
end else List.iter2 (self#checkSingleArg loc) argts args
end
| None when args <> [] ->
E.warn "Wrong number of arguments at %a" d_loc loc
| None -> ()
method private checkTCreateArgs loc (fnarg,argarg) args : unit =
try
let fn = List.nth args fnarg in
let arg = List.nth args argarg in
match unrollType(typeOf fn) with
| TPtr(TFun(_, Some [n,ft,a], _, _),_) -> begin
self#checkSingleArg loc (n,ft,a) arg;
match unrollType ft with
| TPtr(rt,_) when isPrivateType rt -> begin
checks := false;
E.error "Thread function %a can't take private arg at %a"
sp_exp fn d_loc loc
end
| _ -> ()
end
| _ ->
checks := false;
E.error "Bad thread create argument: %a:%a at %a"
sp_exp fn sp_type (unrollType(typeOf fn)) d_loc loc
with _ ->
checks := false;
E.error "Malformed stcreate annotations: STCREATE(%d,%d) #args=%d"
fnarg argarg (List.length args)
method vinst (i : instr) = (*ignore(super#vinst i);*)
if Dcheckdef.isDeputyFunctionInstr i then SkipChildren else
if Rcutils.isRcInstr i then SkipChildren else
match i with
| Set(_, e, _) when self#isConst e -> DoChildren
| Set(lv, e, loc) -> begin
let lvt = sharCTypeOfLval lv
and et = sharCTypeOf e in
match typesCompatible lvt et with
| Equal -> DoChildren
| Cast ->
E.error ("Sharing cast needed for assignment: %a at %a\n\t"^^
"Got: %a\n\tExpected: %a")
sp_instr i d_loc loc sp_type et sp_type lvt;
checks := false;
DoChildren
| _ ->
E.error ("Types not compatible in assignment: %a at %a\n\t"^^
"Got: %a\n\tExpected: %a")
sp_instr i d_loc loc sp_type et sp_type lvt;
checks := false;
DoChildren
end
| Call(_, fe, args, loc)
when isAllocator fe || isDeallocator fe -> begin
(* Checking malloc and free is handled by heapsafe *)
DoChildren
end
| Call(_, fe, args, loc)
when isTCreateType(typeOf fe) <> None -> begin
match isTCreateType(typeOf fe) with
| None -> DoChildren (* impossible *)
| Some(fnarg,argarg) ->
self#checkTCreateArgs loc (fnarg,argarg) args;
DoChildren
end
| Call(Some lv, Lval(Var fvi,NoOffset), [src], loc)
when fvi.vname = "SINIT" || fvi.vname = "SINIT_DOUBLE" ||
fvi.vname = "SINIT_FLOAT" ->
let lvt = sharCTypeOfLval lv in
let srct = sharCTypeOf src in
let tcres = typesCompatible lvt srct in
if tcres <> Equal then
E.error ("Bad types for SREADONLY initialization at %a\n\t"^^
"Got: %a\n\tTarget: %a")
d_loc loc sp_type srct sp_type lvt;
DoChildren
| Call(Some lv, Lval(Var fvi,NoOffset), ce :: _, loc)
when fvi.vname = "__sharc_sharing_cast" -> begin
let lvt = sharCTypeOfLval lv
and cet = sharCTypeOf ce in
let tcres = typesCompatible lvt cet in
if tcres <> Cast && tcres <> Equal then
E.error ("Types not suitable for sharing cast at %a\n\t"^^
"Got: %a\n\tTarget: %a")
d_loc loc sp_type cet sp_type lvt;
if tcres = Equal then
E.warn ("Types in sharing cast are equal at %a\n"^^
"Got: %a\n\tTarget: %a")
d_loc loc sp_type cet sp_type lvt;
ignore(self#vlval lv);
ignore(self#vexpr ce);
SkipChildren
match self#getBaseLval ce with
| Some blv - >
ignore(self#vlval lv ) ;
ignore(self#vexpr ce ) ;
ChangeTo [ make_sharing_cast fd lv ce ]
| None - >
E.error ( " Can not enforce linearity in cast of % a at % a " )
sp_exp ;
match self#getBaseLval ce with
| Some blv ->
ignore(self#vlval lv);
ignore(self#vexpr ce);
ChangeTo [make_sharing_cast fd lv ce blv loc]
| None ->
E.error ("Cannot enforce linearity in cast of %a at %a")
sp_exp ce d_loc loc;
DoChildren
*)
end
| Call(lvo, fe, args, loc) -> begin
match unrollType (sharCTypeOf fe) with
| TFun(rt, argtso, va, a) ->
self#handleRet loc lvo rt;
self#handleArgs loc args argtso;
DoChildren
| _ ->
E.error "Call on non-function type?? %a at %a"
sp_instr i d_loc loc;
DoChildren
end
| Asm(_,_,_,_,_,loc) ->
E.warn "Unchecked inline assembly at %a" d_loc loc;
DoChildren
ignore(super#vstmt s ) ;
match s.skind with
| Return(Some e, _) when self#isConst e -> DoChildren
| Return(Some e, loc) -> begin
let et = sharCTypeOf e in
match unrollType fd.svar.vtype with
| TFun(rt,_,_,_) -> begin
match typesCompatible rt et with
| Cast ->
E.error ("Sharing cast needed for return at %a\n\t"^^
"Source: %a\n\tTarget: %a")
d_loc loc sp_type et sp_type rt;
DoChildren
| NotEqual ->
E.error ("Type not compatible for return at %a\n\t"^^
"Got: %a\n\tExpected: %a")
d_loc loc sp_type et sp_type rt;
DoChildren
| _ -> DoChildren
end
| _ ->
E.bug "fundec has non-function type?? %s"
fd.svar.vname;
DoChildren
end
| _ -> DoChildren
method vexpr (e : exp) =
if self#isConst e then SkipChildren else
match e with
| CastE(t, e') -> begin
let et = sharCTypeOf e' in
match typesCompatible t et with
| Cast ->
E.error ("Sharing cast needed for C cast at %a\n\t"^^
"Source: %a\n\tTarget: %a")
d_loc (!currentLoc) sp_type et sp_type t;
DoChildren
| NotEqual ->
E.error ("Types not compatible in C cast at %a\n\t"^^
"Source: %a\n\tTarget: %a")
d_loc (!currentLoc) sp_type et sp_type t;
DoChildren
| _ -> DoChildren
end
| _ -> DoChildren
method vblock (b : block) =
if hasAttribute "trusted" b.battrs
then begin
E.log "Skipping TRUSTED block\n";
SkipChildren
end else DoChildren
end
class summaryInstrumenterClass fd ctx = object(self)
inherit nopCilVisitor
method private isConst (e : exp) : bool =
match e with
| Const _ -> true
| CastE(_,e) -> self#isConst e
| _ -> false
method private checkReadRange arg sz loc =
let amsg = sprint ~width:80 (sp_exp () arg) in
let szmsg = sprint ~width:80 (sp_exp () sz) in
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString("Read Range Check: ("^amsg^","^szmsg^") @ "^lmsg) in
Call(None,v2e sfuncs.readrange,[CastE(voidPtrType,arg);sz;msg],loc)
method private checkWriteRange arg sz loc =
let amsg = sprint ~width:80 (sp_exp () arg) in
let szmsg = sprint ~width:80 (sp_exp () sz) in
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString("Write Range Check: ("^amsg^","^szmsg^") @ "^lmsg) in
Call(None,v2e sfuncs.writerange,[CastE(voidPtrType,arg);sz;msg],loc)
method private checkDynBarReadRange bar arg sz loc =
let amsg = sprint ~width:80 (sp_exp () arg) in
let szmsg = sprint ~width:80 (sp_exp () sz) in
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString("Read Range Check: ("^amsg^","^szmsg^") @ "^lmsg) in
Call(None,v2e sfuncs.readdynbarrange,[bar;CastE(voidPtrType,arg);sz;msg],loc)
method private checkDynBarWriteRange bar arg sz loc =
let amsg = sprint ~width:80 (sp_exp () arg) in
let szmsg = sprint ~width:80 (sp_exp () sz) in
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString("Write Range Check: ("^amsg^","^szmsg^") @ "^lmsg) in
Call(None,v2e sfuncs.writedynbarrange,[bar;CastE(voidPtrType,arg);sz;msg],loc)
method private handleArgs loc args argtso : instr list =
match argtso with
| Some argts ->
if List.length args <> List.length argts then [] else begin
List.fold_left2 (fun cl (n,t,_) arg ->
if self#isConst arg then cl else
match typesCompatible t (sharCTypeOf arg) with
| CheckRead (ap, None) ->
let actualNames = List.combine args (List.map fst3 argts) in
let sz, slis =
Sattrconv.attrParamToExp ~actuals:actualNames ctx ap
|> Sattrconv.extractStrlenCalls fd
in
let chk = self#checkReadRange arg sz loc in
slis @ (chk :: cl)
| CheckRead (ap, Some barap) ->
let actualNames = List.combine args (List.map fst3 argts) in
let sz, slis =
Sattrconv.attrParamToExp ~actuals:actualNames ctx ap
|> Sattrconv.extractStrlenCalls fd
in
let bar =
Sattrconv.attrParamToExp ~actuals:actualNames ctx barap
in
let chk = self#checkDynBarReadRange bar arg sz loc in
slis @ (chk :: cl)
| CheckWrite (ap, None) ->
let actualNames = List.combine args (List.map fst3 argts) in
let sz, slis =
Sattrconv.attrParamToExp ~actuals:actualNames ctx ap
|> Sattrconv.extractStrlenCalls fd
in
let chk = self#checkWriteRange arg sz loc in
slis @(chk :: cl)
| CheckWrite (ap, Some barap) ->
let actualNames = List.combine args (List.map fst3 argts) in
let sz, slis =
Sattrconv.attrParamToExp ~actuals:actualNames ctx ap
|> Sattrconv.extractStrlenCalls fd
in
let bar =
Sattrconv.attrParamToExp ~actuals:actualNames ctx barap
in
let chk = self#checkDynBarWriteRange bar arg sz loc in
slis @(chk :: cl)
| _ -> cl) [] argts args
end
| None when args <> [] -> []
| None -> []
method vinst (i : instr) =
if Dcheckdef.isDeputyFunctionInstr i then SkipChildren else
if Rcutils.isRcInstr i then SkipChildren else
match i with
| Call(_, Lval(Var fvi, NoOffset), _, _)
when fvi.vname = "__sharc_sharing_cast" ->
SkipChildren
| Call(lvo, fe, args, loc)
when not(isAllocator fe) && not(isDeallocator fe) -> begin
match unrollType (sharCTypeOf fe) with
| TFun(rt, argtso, va, a) ->
let checks = self#handleArgs loc args argtso in
ChangeTo(checks@[i])
| _ ->
E.error "Call on non-function type?? %a at %a"
sp_instr i d_loc loc;
SkipChildren
end
| _ -> SkipChildren
method vblock (b : block) =
if hasAttribute "trusted" b.battrs
then SkipChildren
else DoChildren
end
(* Warn if the source of a sharing cast is not dead after the cast *)
class scastDeadnessCheckerClass = object(self)
inherit Liveness.deadnessVisitorClass as super
method vinst (i:instr) =
ignore(super#vinst i);
match i with
| Call(Some lv, Lval(Var vf,NoOffset), (Lval(Var srcv,_) as src) :: _, loc)
when vf.vname = "__sharc_sharing_cast" ->
if not(VS.mem srcv post_dead_vars) then
E.warn "Failed to prove that %a is dead after Sharing Cast at %a"
sp_exp src d_loc loc;
DoChildren
| Call(Some lv, Lval(Var vf,NoOffset), src :: _, loc)
when vf.vname = "__sharc_sharing_cast" ->
E.warn "Failed to prove that %a is dead after Sharing Cast at %a"
sp_exp src d_loc loc;
DoChildren
| _ -> DoChildren
end
let checkSharingTypes (f : file) : bool =
let checks = ref true in
let fdcheck fd loc =
Cfg.clearCFGinfo fd;
ignore(Cfg.cfgFun fd);
Liveness.registerIgnoreInst Rcutils.isRcInstr;
Liveness.computeLiveness fd;
ignore(visitCilFunction (new scastDeadnessCheckerClass) fd)
in
iterGlobals f (onlyFunctions fdcheck);
let fdcheck fd loc =
let vis = new typeCheckerClass fd checks in
ignore(visitCilFunction vis fd)
in
iterGlobals f (onlyFunctions fdcheck);
let ctx = Sattrconv.genContext f in
let fdcheck fd loc =
ignore(visitCilFunction (new summaryInstrumenterClass fd ctx) fd)
in
iterGlobals f (onlyFunctions fdcheck);
!checks
| null | https://raw.githubusercontent.com/spl/ivy/b1b516484fba637eb24e83d27555d273495e622b/src/sharC/stypechecker.ml | ocaml |
* stypechecker.ml
*
* The SharC type checker.
*
*
attrparam is size in bytes
The Comp is castable if there are no sctx qualifiers on the target types
of pointers
Casting to and from void * is allowed if the sharing doesn't change.
Casting pointers to structures is allowed when all pointers in the structure
are explicitly given the ssame qualifier.
Casting between pointers to pointers is allowed if the referrent types are
equivalent.
old code uses char as void
Can cast other pointer types to void * when the
sharing mode is the same
pointers to deallocators match function pointer types with the
correct number of arguments
x:t1 <-- y:t2, or f(y:t2) where f takes a t1,
or return y:t2 when the function returns t1
casting pointer to int OK
Casting an integer to a pointer is definitely unsound, but it happens
often enough that we'll allow it and give a very stern warning
promote function to function pointer
This visitor does the type checking
ignore(super#vinst i);
Checking malloc and free is handled by heapsafe
impossible
Warn if the source of a sharing cast is not dead after the cast |
open Cil
open Expcompare
open Pretty
open Ivyoptions
open Ivyutil
open Sfunctions
open Sutil
module E = Errormsg
module UD = Usedef
module VS = UD.VS
type compatType =
| Equal
| CheckWrite of attrparam * attrparam option
| Cast
| NotEqual
let ptrQualsCompatible (da : attributes) (sa : attributes) : compatType =
match qualFromAttrs da, qualFromAttrs sa with
| (NoQual | MultiQual), _
| _, (NoQual | MultiQual) ->
E.error "Malformed sharing types";
NotEqual
| OneQual(Attr(ds,apl)), OneQual(Attr(ss,dapl)) -> begin
let dgt = hasAttribute "sgroup" da in
let sgt = hasAttribute "sgroup" sa in
let onegroup = (dgt && not(sgt)) || (not(dgt) && sgt) in
if qeq ds ss && onegroup then NotEqual else
if qeq ds ss then Equal else
match ds, ss with
| "sreads", ("sprivate"|"sreadonly"|"sracy") -> Equal
| "sreads", "sdynbar" -> CheckRead (List.hd apl, Some(List.hd dapl))
| "sreads", _ -> CheckRead (List.hd apl, None)
| "swrites", ("sprivate"|"sracy") -> Equal
| "swrites", "sdynbar" -> CheckWrite (List.hd apl, Some(List.hd dapl))
| "swrites", _ -> CheckWrite (List.hd apl, None)
| "sindynamic", "sprivate" -> if onegroup then NotEqual else Equal
| _, _ -> Cast
end
* TODO :
An expression of structure type can be opened when it contains fields
with SSAME in their type(otherwise , there 's no need to ) , and when it
is either SPRIVATE , when the lock is heald , or SREADONLY so long
as the SSAME fields are not written .
Maybe ...
{ SOPEN(e )
/ * in here the SSAME fields of e can be read and written , but not
aliased . They can be SCAST , though . * /
}
An expression of structure type can be opened when it contains fields
with SSAME in their type(otherwise, there's no need to), and when it
is either SPRIVATE, SLOCKED when the lock is heald, or SREADONLY so long
as the SSAME fields are not written.
Maybe...
{ SOPEN(e)
/* in here the SSAME fields of e can be read and written, but not
aliased. They can be SCAST, though. */
}
*)
CHANGE : This is obviated by placing on unqualified target types in
scasted structs , so just return true
scasted structs, so just return true *)
let rec isCastableComp ?(ctx : string list = []) (ci : compinfo) : bool = true
List.mem ci.cname ctx ||
not(List.exists ( fun fi - >
match unrollType fi.ftype with
| TPtr(rt , a ) | TArray(rt,_,a ) - > begin
isCtxType rt ||
match with
| TComp(ci',a ) - > isCastableComp ~ctx:(ci.cname::ctx ) ci '
| _ - > false
end
| TComp(ci',a ) - > isCastableComp ~ctx:(ci.cname::ctx ) '
| _ - > false )
ci.cfields )
List.mem ci.cname ctx ||
not(List.exists (fun fi ->
match unrollType fi.ftype with
| TPtr(rt,a) | TArray(rt,_,a) -> begin
isCtxType rt ||
match unrollType rt with
| TComp(ci',a) -> isCastableComp ~ctx:(ci.cname::ctx) ci'
| _ -> false
end
| TComp(ci',a) -> isCastableComp ~ctx:(ci.cname::ctx) ci'
| _ -> false)
ci.cfields)
*)
For type equality purposes , sdynamic = = sindynamic = = soutdynamic ,
so before comparing types , rename everything to sdynamic
so before comparing types, rename everything to sdynamic *)
class qualMergerClass = object(self)
inherit nopCilVisitor
method vattr (a : attribute) =
match a with
| Attr(("sindynamic"|"soutdynamic"),ap) ->
ChangeTo[Attr("sdynamic",ap)]
| Attr("slocked",_) ->
ChangeTo[Attr("slocked",[])]
| _ -> SkipChildren
end
let qualMerger (t : typ) : typ =
visitCilType (new qualMergerClass) t
let compareSharCTypes = compareTypes ~importantAttr:isSharCSharingAttr
are drt and srt compatible pointer target types ?
let rec ptrTypesCompatible (drt : typ) (srt : typ) : compatType =
let qres = ptrQualsCompatible (typeAttrs drt) (typeAttrs srt) in
let mdrt = qualMerger drt in
let msrt = qualMerger srt in
if compareSharCTypes mdrt msrt then qres else
match drt, srt with
| TNamed(ti, _), _ -> ptrTypesCompatible ti.ttype srt
| _, TNamed(ti, _) -> ptrTypesCompatible drt ti.ttype
| TVoid _, _ | _, TVoid _ when qres <> Cast -> qres
| TComp _, TComp _ when qres <> Cast -> qres
| TComp(ci1,_),TComp(ci2,_) when qres = Cast ->
if isCastableComp ci1 then Cast else NotEqual
| TInt _, (TPtr _ | TArray _) -> qres
| (TPtr(TVoid da,_)|TArray(TVoid da,_,_)),
(TPtr(srt,_)|TArray(srt,_,_)) -> begin
match qualFromAttrs da, qualFromAttrs (typeAttrs srt) with
| OneQual(Attr(dq,_)), OneQual(Attr(sq,_)) when qeq dq sq -> qres
| _ -> NotEqual
end
| (TPtr(drt,_)|TArray(drt,_,_)), (TPtr(srt,_)|TArray(srt,_,_)) ->
let mdrt = qualMerger drt in
let msrt = qualMerger srt in
if compareSharCTypes mdrt msrt then
qres
else if ptrTypesCompatible mdrt msrt = Equal then
qres
else NotEqual
| (TInt _ | TFloat _ | TEnum _ | TBuiltin_va_list _),
(TInt _ | TFloat _ | TEnum _ | TBuiltin_va_list _) ->
qres
| TFun(voidType,Some tal,false,_), TFun(_,Some sal,false,_)
when Dattrs.isDeallocator srt ->
if List.length tal = List.length sal then
qres
else NotEqual
| _ -> NotEqual
let rec typesCompatible (dstt : typ) (srct : typ) : compatType =
if not(isPtrType dstt) && not(isPtrType srct) then Equal else
let mdstt = qualMerger dstt in
let msrct = qualMerger srct in
if compareSharCTypes mdstt msrct then Equal else
match dstt, srct with
| TNamed(ti,a), _ -> typesCompatible ti.ttype srct
| _, TNamed(ti,a) -> typesCompatible dstt ti.ttype
| TPtr(rt,_), (TInt(_,_) | TEnum(_,_)) -> begin
match unrollType rt with
| TVoid _ -> Equal
| _ ->
E.warn ("Casting an integer to a pointer is unsound at %a."^^
"You better know what you're doing.") d_loc (!currentLoc);
Equal
end
| (TPtr(drt,da) | TArray(drt,_,da)), (TPtr(srt, sa) | TArray(srt,_,sa)) ->
ptrTypesCompatible drt srt
typesCompatible dstt (TPtr(srct,[sprivate]))
| _, _ ->
E.log "typesCompatible: %a != %a\n" sp_type dstt sp_type srct;
NotEqual
let isAllocator (fe : exp) : bool =
match fe with
| Lval(Var fvi, NoOffset)
when fvi.vname = "malloc" || fvi.vname = "realloc" -> true
| _ -> Dattrs.isAllocator(typeOf fe)
let isDeallocator (fe : exp) : bool =
match fe with
| Lval(Var fvi, NoOffset)
when fvi.vname = "free" -> true
| _ -> Dattrs.isDeallocator(typeOf fe)
class typeCheckerClass (fd : fundec) (checks : bool ref) = object(self)
Liveness.livenessVisitorClass true as super
method private isConst (e : exp) : bool =
match e with
| Const _ -> true
| CastE(_,e) -> self#isConst e
| _ -> false
method private getBaseLval (e : exp) : lval option =
match e with
| Lval lv -> Some lv
| StartOf lv -> begin
match lv with
| (Mem e, _) -> self#getBaseLval e
| _ -> None
end
| CastE(_,e)
| BinOp(_,e,_,_) -> self#getBaseLval e
| _ -> None
method private handleRet loc lvo rt : unit =
match lvo with
| None -> ()
| Some lv ->
let lvt = sharCTypeOfLval lv in
match typesCompatible lvt rt with
| Cast ->
E.error ("Sharing cast needed for assignment at %a\n\t"^^
"Got: %a\n\tExpected: %a")
d_loc loc sp_type rt sp_type lvt;
checks := false
| NotEqual ->
E.error ("Types not compatible in assignment at %a\n\t"^^
"Got: %a\n\tExpected: %a")
d_loc loc sp_type rt sp_type lvt;
checks := false
| _ -> ()
method private checkSingleArg loc (n,t,a) arg : unit =
if self#isConst arg then () else
match typesCompatible t (sharCTypeOf arg) with
| Cast ->
E.error ("Sharing cast needed for argument: %a at %a\n\t"^^
"Got: %a\n\tExpected: %a")
sp_exp arg d_loc loc sp_type (sharCTypeOf arg) sp_type t;
checks := false
| NotEqual ->
E.error ("Types not compatible for argument %a at %a\n\t"^^
"Got: %a\n\tExpected: %a")
sp_exp arg d_loc loc sp_type (sharCTypeOf arg) sp_type t;
checks := false
| _ -> ()
method private handleArgs loc args argtso : unit =
match argtso with
| Some argts -> begin
if List.length args <> List.length argts then begin
E.warn " Not checking call with wrong number of args at % a "
d_loc loc
d_loc loc*)
()
end else List.iter2 (self#checkSingleArg loc) argts args
end
| None when args <> [] ->
E.warn "Wrong number of arguments at %a" d_loc loc
| None -> ()
method private checkTCreateArgs loc (fnarg,argarg) args : unit =
try
let fn = List.nth args fnarg in
let arg = List.nth args argarg in
match unrollType(typeOf fn) with
| TPtr(TFun(_, Some [n,ft,a], _, _),_) -> begin
self#checkSingleArg loc (n,ft,a) arg;
match unrollType ft with
| TPtr(rt,_) when isPrivateType rt -> begin
checks := false;
E.error "Thread function %a can't take private arg at %a"
sp_exp fn d_loc loc
end
| _ -> ()
end
| _ ->
checks := false;
E.error "Bad thread create argument: %a:%a at %a"
sp_exp fn sp_type (unrollType(typeOf fn)) d_loc loc
with _ ->
checks := false;
E.error "Malformed stcreate annotations: STCREATE(%d,%d) #args=%d"
fnarg argarg (List.length args)
if Dcheckdef.isDeputyFunctionInstr i then SkipChildren else
if Rcutils.isRcInstr i then SkipChildren else
match i with
| Set(_, e, _) when self#isConst e -> DoChildren
| Set(lv, e, loc) -> begin
let lvt = sharCTypeOfLval lv
and et = sharCTypeOf e in
match typesCompatible lvt et with
| Equal -> DoChildren
| Cast ->
E.error ("Sharing cast needed for assignment: %a at %a\n\t"^^
"Got: %a\n\tExpected: %a")
sp_instr i d_loc loc sp_type et sp_type lvt;
checks := false;
DoChildren
| _ ->
E.error ("Types not compatible in assignment: %a at %a\n\t"^^
"Got: %a\n\tExpected: %a")
sp_instr i d_loc loc sp_type et sp_type lvt;
checks := false;
DoChildren
end
| Call(_, fe, args, loc)
when isAllocator fe || isDeallocator fe -> begin
DoChildren
end
| Call(_, fe, args, loc)
when isTCreateType(typeOf fe) <> None -> begin
match isTCreateType(typeOf fe) with
| Some(fnarg,argarg) ->
self#checkTCreateArgs loc (fnarg,argarg) args;
DoChildren
end
| Call(Some lv, Lval(Var fvi,NoOffset), [src], loc)
when fvi.vname = "SINIT" || fvi.vname = "SINIT_DOUBLE" ||
fvi.vname = "SINIT_FLOAT" ->
let lvt = sharCTypeOfLval lv in
let srct = sharCTypeOf src in
let tcres = typesCompatible lvt srct in
if tcres <> Equal then
E.error ("Bad types for SREADONLY initialization at %a\n\t"^^
"Got: %a\n\tTarget: %a")
d_loc loc sp_type srct sp_type lvt;
DoChildren
| Call(Some lv, Lval(Var fvi,NoOffset), ce :: _, loc)
when fvi.vname = "__sharc_sharing_cast" -> begin
let lvt = sharCTypeOfLval lv
and cet = sharCTypeOf ce in
let tcres = typesCompatible lvt cet in
if tcres <> Cast && tcres <> Equal then
E.error ("Types not suitable for sharing cast at %a\n\t"^^
"Got: %a\n\tTarget: %a")
d_loc loc sp_type cet sp_type lvt;
if tcres = Equal then
E.warn ("Types in sharing cast are equal at %a\n"^^
"Got: %a\n\tTarget: %a")
d_loc loc sp_type cet sp_type lvt;
ignore(self#vlval lv);
ignore(self#vexpr ce);
SkipChildren
match self#getBaseLval ce with
| Some blv - >
ignore(self#vlval lv ) ;
ignore(self#vexpr ce ) ;
ChangeTo [ make_sharing_cast fd lv ce ]
| None - >
E.error ( " Can not enforce linearity in cast of % a at % a " )
sp_exp ;
match self#getBaseLval ce with
| Some blv ->
ignore(self#vlval lv);
ignore(self#vexpr ce);
ChangeTo [make_sharing_cast fd lv ce blv loc]
| None ->
E.error ("Cannot enforce linearity in cast of %a at %a")
sp_exp ce d_loc loc;
DoChildren
*)
end
| Call(lvo, fe, args, loc) -> begin
match unrollType (sharCTypeOf fe) with
| TFun(rt, argtso, va, a) ->
self#handleRet loc lvo rt;
self#handleArgs loc args argtso;
DoChildren
| _ ->
E.error "Call on non-function type?? %a at %a"
sp_instr i d_loc loc;
DoChildren
end
| Asm(_,_,_,_,_,loc) ->
E.warn "Unchecked inline assembly at %a" d_loc loc;
DoChildren
ignore(super#vstmt s ) ;
match s.skind with
| Return(Some e, _) when self#isConst e -> DoChildren
| Return(Some e, loc) -> begin
let et = sharCTypeOf e in
match unrollType fd.svar.vtype with
| TFun(rt,_,_,_) -> begin
match typesCompatible rt et with
| Cast ->
E.error ("Sharing cast needed for return at %a\n\t"^^
"Source: %a\n\tTarget: %a")
d_loc loc sp_type et sp_type rt;
DoChildren
| NotEqual ->
E.error ("Type not compatible for return at %a\n\t"^^
"Got: %a\n\tExpected: %a")
d_loc loc sp_type et sp_type rt;
DoChildren
| _ -> DoChildren
end
| _ ->
E.bug "fundec has non-function type?? %s"
fd.svar.vname;
DoChildren
end
| _ -> DoChildren
method vexpr (e : exp) =
if self#isConst e then SkipChildren else
match e with
| CastE(t, e') -> begin
let et = sharCTypeOf e' in
match typesCompatible t et with
| Cast ->
E.error ("Sharing cast needed for C cast at %a\n\t"^^
"Source: %a\n\tTarget: %a")
d_loc (!currentLoc) sp_type et sp_type t;
DoChildren
| NotEqual ->
E.error ("Types not compatible in C cast at %a\n\t"^^
"Source: %a\n\tTarget: %a")
d_loc (!currentLoc) sp_type et sp_type t;
DoChildren
| _ -> DoChildren
end
| _ -> DoChildren
method vblock (b : block) =
if hasAttribute "trusted" b.battrs
then begin
E.log "Skipping TRUSTED block\n";
SkipChildren
end else DoChildren
end
class summaryInstrumenterClass fd ctx = object(self)
inherit nopCilVisitor
method private isConst (e : exp) : bool =
match e with
| Const _ -> true
| CastE(_,e) -> self#isConst e
| _ -> false
method private checkReadRange arg sz loc =
let amsg = sprint ~width:80 (sp_exp () arg) in
let szmsg = sprint ~width:80 (sp_exp () sz) in
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString("Read Range Check: ("^amsg^","^szmsg^") @ "^lmsg) in
Call(None,v2e sfuncs.readrange,[CastE(voidPtrType,arg);sz;msg],loc)
method private checkWriteRange arg sz loc =
let amsg = sprint ~width:80 (sp_exp () arg) in
let szmsg = sprint ~width:80 (sp_exp () sz) in
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString("Write Range Check: ("^amsg^","^szmsg^") @ "^lmsg) in
Call(None,v2e sfuncs.writerange,[CastE(voidPtrType,arg);sz;msg],loc)
method private checkDynBarReadRange bar arg sz loc =
let amsg = sprint ~width:80 (sp_exp () arg) in
let szmsg = sprint ~width:80 (sp_exp () sz) in
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString("Read Range Check: ("^amsg^","^szmsg^") @ "^lmsg) in
Call(None,v2e sfuncs.readdynbarrange,[bar;CastE(voidPtrType,arg);sz;msg],loc)
method private checkDynBarWriteRange bar arg sz loc =
let amsg = sprint ~width:80 (sp_exp () arg) in
let szmsg = sprint ~width:80 (sp_exp () sz) in
let lmsg = sprint ~width:80 (d_loc () loc) in
let msg = mkString("Write Range Check: ("^amsg^","^szmsg^") @ "^lmsg) in
Call(None,v2e sfuncs.writedynbarrange,[bar;CastE(voidPtrType,arg);sz;msg],loc)
method private handleArgs loc args argtso : instr list =
match argtso with
| Some argts ->
if List.length args <> List.length argts then [] else begin
List.fold_left2 (fun cl (n,t,_) arg ->
if self#isConst arg then cl else
match typesCompatible t (sharCTypeOf arg) with
| CheckRead (ap, None) ->
let actualNames = List.combine args (List.map fst3 argts) in
let sz, slis =
Sattrconv.attrParamToExp ~actuals:actualNames ctx ap
|> Sattrconv.extractStrlenCalls fd
in
let chk = self#checkReadRange arg sz loc in
slis @ (chk :: cl)
| CheckRead (ap, Some barap) ->
let actualNames = List.combine args (List.map fst3 argts) in
let sz, slis =
Sattrconv.attrParamToExp ~actuals:actualNames ctx ap
|> Sattrconv.extractStrlenCalls fd
in
let bar =
Sattrconv.attrParamToExp ~actuals:actualNames ctx barap
in
let chk = self#checkDynBarReadRange bar arg sz loc in
slis @ (chk :: cl)
| CheckWrite (ap, None) ->
let actualNames = List.combine args (List.map fst3 argts) in
let sz, slis =
Sattrconv.attrParamToExp ~actuals:actualNames ctx ap
|> Sattrconv.extractStrlenCalls fd
in
let chk = self#checkWriteRange arg sz loc in
slis @(chk :: cl)
| CheckWrite (ap, Some barap) ->
let actualNames = List.combine args (List.map fst3 argts) in
let sz, slis =
Sattrconv.attrParamToExp ~actuals:actualNames ctx ap
|> Sattrconv.extractStrlenCalls fd
in
let bar =
Sattrconv.attrParamToExp ~actuals:actualNames ctx barap
in
let chk = self#checkDynBarWriteRange bar arg sz loc in
slis @(chk :: cl)
| _ -> cl) [] argts args
end
| None when args <> [] -> []
| None -> []
method vinst (i : instr) =
if Dcheckdef.isDeputyFunctionInstr i then SkipChildren else
if Rcutils.isRcInstr i then SkipChildren else
match i with
| Call(_, Lval(Var fvi, NoOffset), _, _)
when fvi.vname = "__sharc_sharing_cast" ->
SkipChildren
| Call(lvo, fe, args, loc)
when not(isAllocator fe) && not(isDeallocator fe) -> begin
match unrollType (sharCTypeOf fe) with
| TFun(rt, argtso, va, a) ->
let checks = self#handleArgs loc args argtso in
ChangeTo(checks@[i])
| _ ->
E.error "Call on non-function type?? %a at %a"
sp_instr i d_loc loc;
SkipChildren
end
| _ -> SkipChildren
method vblock (b : block) =
if hasAttribute "trusted" b.battrs
then SkipChildren
else DoChildren
end
class scastDeadnessCheckerClass = object(self)
inherit Liveness.deadnessVisitorClass as super
method vinst (i:instr) =
ignore(super#vinst i);
match i with
| Call(Some lv, Lval(Var vf,NoOffset), (Lval(Var srcv,_) as src) :: _, loc)
when vf.vname = "__sharc_sharing_cast" ->
if not(VS.mem srcv post_dead_vars) then
E.warn "Failed to prove that %a is dead after Sharing Cast at %a"
sp_exp src d_loc loc;
DoChildren
| Call(Some lv, Lval(Var vf,NoOffset), src :: _, loc)
when vf.vname = "__sharc_sharing_cast" ->
E.warn "Failed to prove that %a is dead after Sharing Cast at %a"
sp_exp src d_loc loc;
DoChildren
| _ -> DoChildren
end
let checkSharingTypes (f : file) : bool =
let checks = ref true in
let fdcheck fd loc =
Cfg.clearCFGinfo fd;
ignore(Cfg.cfgFun fd);
Liveness.registerIgnoreInst Rcutils.isRcInstr;
Liveness.computeLiveness fd;
ignore(visitCilFunction (new scastDeadnessCheckerClass) fd)
in
iterGlobals f (onlyFunctions fdcheck);
let fdcheck fd loc =
let vis = new typeCheckerClass fd checks in
ignore(visitCilFunction vis fd)
in
iterGlobals f (onlyFunctions fdcheck);
let ctx = Sattrconv.genContext f in
let fdcheck fd loc =
ignore(visitCilFunction (new summaryInstrumenterClass fd ctx) fd)
in
iterGlobals f (onlyFunctions fdcheck);
!checks
|
019a6409994a23668b2a71999315dc9b5b8bbfb212af2bf787274e8fb69fbe4e | herbelin/coq-hh | retroknowledge.ml | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
Created by , May 2007
Addition of native Head ( nb of heading 0 ) and Tail ( nb of trailing 0 ) by
, Jun 2007
Benjamin Grégoire, Jun 2007 *)
(* This file defines the knowledge that the kernel is able to optimize
for evaluation in the bytecode virtual machine *)
open Term
open Names
(* Type declarations, these types shouldn't be exported they are accessed
through specific functions. As being mutable and all it is wiser *)
These types are put into two distinct categories : proactive and reactive .
Proactive information allows to find the name of a combinator , constructor
or inductive type handling a specific function .
Reactive information is , on the other hand , everything you need to know
about a specific name .
Proactive information allows to find the name of a combinator, constructor
or inductive type handling a specific function.
Reactive information is, on the other hand, everything you need to know
about a specific name.*)
(* aliased type for clarity purpose*)
type entry = (constr, types) kind_of_term
(* the following types correspond to the different "things"
the kernel can learn about. These are the fields of the proactive knowledge*)
type nat_field =
| NatType
| NatPlus
| NatTimes
type n_field =
| NPositive
| NType
| NTwice
| NTwicePlusOne
| NPhi
| NPhiInv
| NPlus
| NTimes
type int31_field =
| Int31Bits
| Int31Type
| Int31Twice
| Int31TwicePlusOne
| Int31Phi
| Int31PhiInv
| Int31Plus
| Int31PlusC
| Int31PlusCarryC
| Int31Minus
| Int31MinusC
| Int31MinusCarryC
| Int31Times
| Int31TimesC
| Int31Div21
| Int31Div
| Int31AddMulDiv
| Int31Compare
| Int31Head0
| Int31Tail0
type field =
| KEq
| KNat of nat_field
| KN of n_field
| KNat of nat_field
| KN of n_field *)
| KInt31 of string*int31_field
(* record representing all the flags of the internal state of the kernel *)
type flags = {fastcomputation : bool}
A definition of maps from strings to pro_int31 , to be able
to have any amount of coq representation for the 31bits integers
to have any amount of coq representation for the 31bits integers *)
module Proactive =
Map.Make (struct type t = field let compare = compare end)
type proactive = entry Proactive.t
the reactive knowledge is represented as a functionaly map
from the type of terms ( actually it is the terms whose outermost
layer is unfolded ( typically by Term.kind_of_term ) ) to the
type reactive_end which is a record containing all the kind of reactive
information needed
from the type of terms (actually it is the terms whose outermost
layer is unfolded (typically by Term.kind_of_term)) to the
type reactive_end which is a record containing all the kind of reactive
information needed *)
(* todo: because of the bug with output state, reactive_end should eventually
contain no function. A forseen possibility is to make it a map from
a finite type describing the fields to the field of proactive retroknowledge
(and then to make as many functions as needed in environ.ml) *)
module Reactive =
Map.Make (struct type t = entry let compare = compare end)
type reactive_end = {(*information required by the compiler of the VM *)
vm_compiling :
fastcomputation flag - > continuation - > result
(bool->Cbytecodes.comp_env->constr array ->
int->Cbytecodes.bytecodes->Cbytecodes.bytecodes)
option;
vm_constant_static :
fastcomputation flag - > constructor - > args - > result
(bool->constr array->Cbytecodes.structured_constant)
option;
vm_constant_dynamic :
fastcomputation flag - > constructor - > reloc - > args - > sz - > cont - > result
(bool->Cbytecodes.comp_env->Cbytecodes.block array->int->
Cbytecodes.bytecodes->Cbytecodes.bytecodes)
option;
(* fastcomputation flag -> cont -> result *)
vm_before_match : (bool -> Cbytecodes.bytecodes -> Cbytecodes.bytecodes) option;
(* tag (= compiled int for instance) -> result *)
vm_decompile_const : (int -> Term.constr) option}
and reactive = reactive_end Reactive.t
and retroknowledge = {flags : flags; proactive : proactive; reactive : reactive}
(* This type represent an atomic action of the retroknowledge. It
is stored in the compiled libraries *)
(* As per now, there is only the possibility of registering things
the possibility of unregistering or changing the flag is under study *)
type action =
| RKRegister of field*entry
(*initialisation*)
let initial_flags =
{fastcomputation = true;}
let initial_proactive =
(Proactive.empty:proactive)
let initial_reactive =
(Reactive.empty:reactive)
let initial_retroknowledge =
{flags = initial_flags;
proactive = initial_proactive;
reactive = initial_reactive }
let empty_reactive_end =
{ vm_compiling = None ;
vm_constant_static = None;
vm_constant_dynamic = None;
vm_before_match = None;
vm_decompile_const = None }
(* acces functions for proactive retroknowledge *)
let add_field knowledge field value =
{knowledge with proactive = Proactive.add field value knowledge.proactive}
let mem knowledge field =
Proactive.mem field knowledge.proactive
let remove knowledge field =
{knowledge with proactive = Proactive.remove field knowledge.proactive}
let find knowledge field =
Proactive.find field knowledge.proactive
(*access functions for reactive retroknowledge*)
(* used for compiling of functions (add, mult, etc..) *)
let get_vm_compiling_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_compiling
with
| None -> raise Not_found
| Some f -> f knowledge.flags.fastcomputation
(* used for compilation of fully applied constructors *)
let get_vm_constant_static_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_constant_static
with
| None -> raise Not_found
| Some f -> f knowledge.flags.fastcomputation
(* used for compilation of partially applied constructors *)
let get_vm_constant_dynamic_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_constant_dynamic
with
| None -> raise Not_found
| Some f -> f knowledge.flags.fastcomputation
let get_vm_before_match_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_before_match
with
| None -> raise Not_found
| Some f -> f knowledge.flags.fastcomputation
let get_vm_decompile_constant_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_decompile_const
with
| None -> raise Not_found
| Some f -> f
(* functions manipulating reactive knowledge *)
let add_vm_compiling_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_compiling = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_compiling = Some nfo}
knowledge.reactive
}
let add_vm_constant_static_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_constant_static = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_constant_static = Some nfo}
knowledge.reactive
}
let add_vm_constant_dynamic_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_constant_dynamic = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_constant_dynamic = Some nfo}
knowledge.reactive
}
let add_vm_before_match_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_before_match = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_before_match = Some nfo}
knowledge.reactive
}
let add_vm_decompile_constant_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_decompile_const = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_decompile_const = Some nfo}
knowledge.reactive
}
let clear_info knowledge value =
{knowledge with reactive = Reactive.remove value knowledge.reactive}
| null | https://raw.githubusercontent.com/herbelin/coq-hh/296d03d5049fea661e8bdbaf305ed4bf6d2001d2/kernel/retroknowledge.ml | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
This file defines the knowledge that the kernel is able to optimize
for evaluation in the bytecode virtual machine
Type declarations, these types shouldn't be exported they are accessed
through specific functions. As being mutable and all it is wiser
aliased type for clarity purpose
the following types correspond to the different "things"
the kernel can learn about. These are the fields of the proactive knowledge
record representing all the flags of the internal state of the kernel
todo: because of the bug with output state, reactive_end should eventually
contain no function. A forseen possibility is to make it a map from
a finite type describing the fields to the field of proactive retroknowledge
(and then to make as many functions as needed in environ.ml)
information required by the compiler of the VM
fastcomputation flag -> cont -> result
tag (= compiled int for instance) -> result
This type represent an atomic action of the retroknowledge. It
is stored in the compiled libraries
As per now, there is only the possibility of registering things
the possibility of unregistering or changing the flag is under study
initialisation
acces functions for proactive retroknowledge
access functions for reactive retroknowledge
used for compiling of functions (add, mult, etc..)
used for compilation of fully applied constructors
used for compilation of partially applied constructors
functions manipulating reactive knowledge | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * INRIA - CNRS - LIX - LRI - PPS - Copyright 1999 - 2010
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Created by , May 2007
Addition of native Head ( nb of heading 0 ) and Tail ( nb of trailing 0 ) by
, Jun 2007
Benjamin Grégoire, Jun 2007 *)
open Term
open Names
These types are put into two distinct categories : proactive and reactive .
Proactive information allows to find the name of a combinator , constructor
or inductive type handling a specific function .
Reactive information is , on the other hand , everything you need to know
about a specific name .
Proactive information allows to find the name of a combinator, constructor
or inductive type handling a specific function.
Reactive information is, on the other hand, everything you need to know
about a specific name.*)
type entry = (constr, types) kind_of_term
type nat_field =
| NatType
| NatPlus
| NatTimes
type n_field =
| NPositive
| NType
| NTwice
| NTwicePlusOne
| NPhi
| NPhiInv
| NPlus
| NTimes
type int31_field =
| Int31Bits
| Int31Type
| Int31Twice
| Int31TwicePlusOne
| Int31Phi
| Int31PhiInv
| Int31Plus
| Int31PlusC
| Int31PlusCarryC
| Int31Minus
| Int31MinusC
| Int31MinusCarryC
| Int31Times
| Int31TimesC
| Int31Div21
| Int31Div
| Int31AddMulDiv
| Int31Compare
| Int31Head0
| Int31Tail0
type field =
| KEq
| KNat of nat_field
| KN of n_field
| KNat of nat_field
| KN of n_field *)
| KInt31 of string*int31_field
type flags = {fastcomputation : bool}
A definition of maps from strings to pro_int31 , to be able
to have any amount of coq representation for the 31bits integers
to have any amount of coq representation for the 31bits integers *)
module Proactive =
Map.Make (struct type t = field let compare = compare end)
type proactive = entry Proactive.t
the reactive knowledge is represented as a functionaly map
from the type of terms ( actually it is the terms whose outermost
layer is unfolded ( typically by Term.kind_of_term ) ) to the
type reactive_end which is a record containing all the kind of reactive
information needed
from the type of terms (actually it is the terms whose outermost
layer is unfolded (typically by Term.kind_of_term)) to the
type reactive_end which is a record containing all the kind of reactive
information needed *)
module Reactive =
Map.Make (struct type t = entry let compare = compare end)
vm_compiling :
fastcomputation flag - > continuation - > result
(bool->Cbytecodes.comp_env->constr array ->
int->Cbytecodes.bytecodes->Cbytecodes.bytecodes)
option;
vm_constant_static :
fastcomputation flag - > constructor - > args - > result
(bool->constr array->Cbytecodes.structured_constant)
option;
vm_constant_dynamic :
fastcomputation flag - > constructor - > reloc - > args - > sz - > cont - > result
(bool->Cbytecodes.comp_env->Cbytecodes.block array->int->
Cbytecodes.bytecodes->Cbytecodes.bytecodes)
option;
vm_before_match : (bool -> Cbytecodes.bytecodes -> Cbytecodes.bytecodes) option;
vm_decompile_const : (int -> Term.constr) option}
and reactive = reactive_end Reactive.t
and retroknowledge = {flags : flags; proactive : proactive; reactive : reactive}
type action =
| RKRegister of field*entry
let initial_flags =
{fastcomputation = true;}
let initial_proactive =
(Proactive.empty:proactive)
let initial_reactive =
(Reactive.empty:reactive)
let initial_retroknowledge =
{flags = initial_flags;
proactive = initial_proactive;
reactive = initial_reactive }
let empty_reactive_end =
{ vm_compiling = None ;
vm_constant_static = None;
vm_constant_dynamic = None;
vm_before_match = None;
vm_decompile_const = None }
let add_field knowledge field value =
{knowledge with proactive = Proactive.add field value knowledge.proactive}
let mem knowledge field =
Proactive.mem field knowledge.proactive
let remove knowledge field =
{knowledge with proactive = Proactive.remove field knowledge.proactive}
let find knowledge field =
Proactive.find field knowledge.proactive
let get_vm_compiling_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_compiling
with
| None -> raise Not_found
| Some f -> f knowledge.flags.fastcomputation
let get_vm_constant_static_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_constant_static
with
| None -> raise Not_found
| Some f -> f knowledge.flags.fastcomputation
let get_vm_constant_dynamic_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_constant_dynamic
with
| None -> raise Not_found
| Some f -> f knowledge.flags.fastcomputation
let get_vm_before_match_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_before_match
with
| None -> raise Not_found
| Some f -> f knowledge.flags.fastcomputation
let get_vm_decompile_constant_info knowledge key =
match (Reactive.find key knowledge.reactive).vm_decompile_const
with
| None -> raise Not_found
| Some f -> f
let add_vm_compiling_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_compiling = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_compiling = Some nfo}
knowledge.reactive
}
let add_vm_constant_static_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_constant_static = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_constant_static = Some nfo}
knowledge.reactive
}
let add_vm_constant_dynamic_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_constant_dynamic = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_constant_dynamic = Some nfo}
knowledge.reactive
}
let add_vm_before_match_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_before_match = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_before_match = Some nfo}
knowledge.reactive
}
let add_vm_decompile_constant_info knowledge value nfo =
{knowledge with reactive =
try
Reactive.add value
{(Reactive.find value (knowledge.reactive)) with vm_decompile_const = Some nfo}
knowledge.reactive
with Not_found ->
Reactive.add value {empty_reactive_end with vm_decompile_const = Some nfo}
knowledge.reactive
}
let clear_info knowledge value =
{knowledge with reactive = Reactive.remove value knowledge.reactive}
|
cc3603b39530ed50c7a834120d7c0b6e9a681d3c77945c379562602b473e2fea | acatton/yamlkeysdiff | Main.hs | Copyright ( c ) 2015
--
-- This file is part of YAMLKeysDiff and is distributed under EUPLv1.1,
-- see the LICENSE file for more information. If a LICENSE file wasn't
-- provided with this piece of software, you will find a copy at:
-- <>
--
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
import System.Environment (getArgs, getProgName)
import System.Exit (exitWith, ExitCode(ExitSuccess, ExitFailure))
import qualified Data.Yaml as Yaml
import qualified Data.List as List
import qualified Data.Either as Either
import qualified Data.HashMap.Lazy as HashMap
import Control.Monad (foldM)
import Data.Text (pack)
import qualified YamlKeysDiff.Opts as Opts
import YamlKeysDiff.Filename (parseFileName)
import YamlKeysDiff.Diff (diff, isSimilar)
decodeFilename :: String -> IO (FilePath, [String])
decodeFilename fileName =
case parseFileName fileName of
Either.Right a -> return a
Either.Left e ->
ioError $ userError $ "couldn't parse filename " ++ fileName
decodeFile :: FilePath -> IO Yaml.Value
decodeFile path = do
(fileName, keys) <- decodeFilename path
maybeContent <- Yaml.decodeFile fileName
content <- case maybeContent of
Just c -> return c
Nothing -> ioError $ userError $ "couldn't decode file " ++ fileName
case getValue keys content of
Just v -> return v
Nothing -> ioError $ userError $ "couldn't find the key " ++ List.intercalate ":" keys
getValue :: [String] -> Yaml.Value -> Maybe Yaml.Value
getValue keys value =
let getKey key value =
case value of
Yaml.Object obj -> HashMap.lookup key obj
_ -> Nothing
in foldM (flip getKey) value $ map pack keys
getFiles :: [String] -> IO (String, String)
getFiles args =
case args of
[a, b] -> return (a, b)
_ -> ioError (userError "Please specify two files")
main :: IO ()
main = do
progName <- getProgName
argv <- getArgs
(flags, args) <- Opts.getOptions progName argv
if List.elem Opts.Help flags then
putStr $ Opts.usage progName
else do
formattingFunction <- Opts.getFormattingFunction flags
(filePathA, filePathB) <- getFiles args
contentA <- decodeFile filePathA
contentB <- decodeFile filePathB
let diffLines = diff contentA contentB
putStr $ formattingFunction diffLines
FIXME : ioError also exit with 1
exitWith $ if all isSimilar diffLines then ExitSuccess
else (ExitFailure 1)
| null | https://raw.githubusercontent.com/acatton/yamlkeysdiff/1728b099ff17a003d6bf47d300384841471b4924/src/Main.hs | haskell |
This file is part of YAMLKeysDiff and is distributed under EUPLv1.1,
see the LICENSE file for more information. If a LICENSE file wasn't
provided with this piece of software, you will find a copy at:
<>
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. | Copyright ( c ) 2015
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
import System.Environment (getArgs, getProgName)
import System.Exit (exitWith, ExitCode(ExitSuccess, ExitFailure))
import qualified Data.Yaml as Yaml
import qualified Data.List as List
import qualified Data.Either as Either
import qualified Data.HashMap.Lazy as HashMap
import Control.Monad (foldM)
import Data.Text (pack)
import qualified YamlKeysDiff.Opts as Opts
import YamlKeysDiff.Filename (parseFileName)
import YamlKeysDiff.Diff (diff, isSimilar)
decodeFilename :: String -> IO (FilePath, [String])
decodeFilename fileName =
case parseFileName fileName of
Either.Right a -> return a
Either.Left e ->
ioError $ userError $ "couldn't parse filename " ++ fileName
decodeFile :: FilePath -> IO Yaml.Value
decodeFile path = do
(fileName, keys) <- decodeFilename path
maybeContent <- Yaml.decodeFile fileName
content <- case maybeContent of
Just c -> return c
Nothing -> ioError $ userError $ "couldn't decode file " ++ fileName
case getValue keys content of
Just v -> return v
Nothing -> ioError $ userError $ "couldn't find the key " ++ List.intercalate ":" keys
getValue :: [String] -> Yaml.Value -> Maybe Yaml.Value
getValue keys value =
let getKey key value =
case value of
Yaml.Object obj -> HashMap.lookup key obj
_ -> Nothing
in foldM (flip getKey) value $ map pack keys
getFiles :: [String] -> IO (String, String)
getFiles args =
case args of
[a, b] -> return (a, b)
_ -> ioError (userError "Please specify two files")
main :: IO ()
main = do
progName <- getProgName
argv <- getArgs
(flags, args) <- Opts.getOptions progName argv
if List.elem Opts.Help flags then
putStr $ Opts.usage progName
else do
formattingFunction <- Opts.getFormattingFunction flags
(filePathA, filePathB) <- getFiles args
contentA <- decodeFile filePathA
contentB <- decodeFile filePathB
let diffLines = diff contentA contentB
putStr $ formattingFunction diffLines
FIXME : ioError also exit with 1
exitWith $ if all isSimilar diffLines then ExitSuccess
else (ExitFailure 1)
|
32019b46b7259fcddc8051dc5f03a955922c5676911421ec5eccd97c5f283c5c | GaloisInc/macaw | RegisterUse.hs | | This analyzes a function to compute information about what
information must be available for the code to execute . It is a key analysis
task needed before deleting unused code .
information must be available for the code to execute. It is a key analysis
task needed before deleting unused code.
-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE KindSignatures #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PatternSynonyms #
# LANGUAGE PolyKinds #
{-# LANGUAGE RankNTypes #-}
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Data.Macaw.Analysis.RegisterUse
( -- * Exports for function recovery
registerUse
, BlockInvariantMap
, RegisterUseError(..)
, RegisterUseErrorReason(..)
, ppRegisterUseErrorReason
, RegisterUseErrorTag(..)
-- ** Input information
, RegisterUseContext(..)
, ArchFunType
, CallRegs(..)
, PostTermStmtInvariants
, PostValueMap
, pvmFind
, MemSlice(..)
-- * Architecture specific summarization
, ArchTermStmtUsageFn
, RegisterUseM
, BlockStartConstraints(..)
, locDomain
, postCallConstraints
, BlockUsageSummary(..)
, RegDependencyMap
, setRegDep
, StartInferContext
, InferState
, BlockInferValue(..)
, valueDeps
* * * FunPredMap
, FunPredMap
, funBlockPreds
-- ** Inferred information.
, BlockInvariants
, biStartConstraints
, biMemAccessList
, biPhiLocs
, biPredPostValues
, biLocMap
, biCallFunType
, biAssignMap
, LocList(..)
, StackAnalysis.LocMap(..)
, StackAnalysis.locMapToList
, StackAnalysis.BoundLoc(..)
, MemAccessInfo(..)
, InitInferValue(..)
* * * info
, StmtIndex
-- *** Use information
, biAssignIdUsed
, biWriteUsed
) where
import Control.Lens
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State.Strict
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString as BS
import Data.Foldable
import Data.Kind
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Parameterized
import Data.Parameterized.Map (MapF)
import qualified Data.Parameterized.Map as MapF
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Word (Word64)
import GHC.Stack
import Prettyprinter
import Text.Printf (printf)
import Data.Macaw.AbsDomain.StackAnalysis as StackAnalysis
import Data.Macaw.CFG
import Data.Macaw.CFG.DemandSet
( DemandContext
, archFnHasSideEffects
)
import Data.Macaw.Discovery.State
import qualified Data.Macaw.Types as M
import Data.Macaw.Types hiding (Type)
import Data.Macaw.Utils.Changed
import Data.Macaw.AbsDomain.CallParams
import Data.STRef
import Data.Parameterized.TH.GADT
-------------------------------------------------------------------------------
funBlockPreds
-- | A map from each starting block address @l@ to the addresses of
-- blocks that may jump to @l@.
type FunPredMap w = Map (MemSegmentOff w) [MemSegmentOff w]
-- | Return the FunPredMap for the discovered block function.
funBlockPreds :: DiscoveryFunInfo arch ids -> FunPredMap (ArchAddrWidth arch)
funBlockPreds info = Map.fromListWith (++)
[ (next, [addr])
| b <- Map.elems (info^.parsedBlocks)
-- Get address of region
, let addr = pblockAddr b
-- get the block successors
, next <- parsedTermSucc (pblockTermStmt b)
]
-------------------------------------------------------------------------------
-- RegisterUseError
-- | Errors from register use
--
-- Tag parameter used for addition information in tag
data RegisterUseErrorTag e where
-- | Could not resolve height of call stack at given block
CallStackHeightError :: RegisterUseErrorTag ()
-- | The value read at given block and statement index could not
-- be resolved.
UnresolvedStackRead :: RegisterUseErrorTag ()
-- | We do not have support for stack reads.
UnsupportedCondStackRead :: RegisterUseErrorTag ()
-- | Call with indirect target
IndirectCallTarget :: RegisterUseErrorTag ()
-- | Call target address was not a valid memory location.
InvalidCallTargetAddress :: RegisterUseErrorTag Word64
-- | Call target was not a known function.
CallTargetNotFunctionEntryPoint :: RegisterUseErrorTag Word64
-- | Could not determine arguments to call.
UnknownCallTargetArguments :: RegisterUseErrorTag BS.ByteString
-- | We could not resolve the arguments to a known var-args function.
ResolutonFailureCallToKnownVarArgsFunction :: RegisterUseErrorTag String
-- | We do not yet support the calling convention needed for this function.
UnsupportedCallTargetCallingConvention :: RegisterUseErrorTag BS.ByteString
instance Show (RegisterUseErrorTag e) where
show CallStackHeightError = "Symbolic call stack height"
show UnresolvedStackRead = "Unresolved stack read"
show UnsupportedCondStackRead = "Conditional stack read"
show IndirectCallTarget = "Indirect call target"
show InvalidCallTargetAddress = "Invalid call target address"
show CallTargetNotFunctionEntryPoint = "Call target not function entry point"
show UnknownCallTargetArguments = "Unresolved call target arguments"
show ResolutonFailureCallToKnownVarArgsFunction = "Could not resolve varargs args"
show UnsupportedCallTargetCallingConvention = "Unsupported calling convention"
$(pure [])
instance TestEquality RegisterUseErrorTag where
testEquality = $(structuralTypeEquality [t|RegisterUseErrorTag|] [])
instance OrdF RegisterUseErrorTag where
compareF = $(structuralTypeOrd [t|RegisterUseErrorTag|] [])
data RegisterUseErrorReason = forall e . Reason !(RegisterUseErrorTag e) !e
-- | Errors from register use
data RegisterUseError arch
= RegisterUseError {
ruBlock :: !(ArchSegmentOff arch),
ruStmt :: !StmtIndex,
ruReason :: !RegisterUseErrorReason
}
ppRegisterUseErrorReason :: RegisterUseErrorReason -> String
ppRegisterUseErrorReason (Reason tag v) =
case tag of
CallStackHeightError -> "Could not resolve concrete stack height."
UnresolvedStackRead -> "Unresolved stack read."
UnsupportedCondStackRead -> "Unsupported conditional stack read."
IndirectCallTarget -> "Indirect call target."
InvalidCallTargetAddress -> "Invalid call target address."
CallTargetNotFunctionEntryPoint -> "Call target not function entry point."
UnknownCallTargetArguments -> printf "Unknown arguments to %s." (BSC.unpack v)
ResolutonFailureCallToKnownVarArgsFunction -> "Could not resolve varargs args."
UnsupportedCallTargetCallingConvention -> "Unsupported calling convention."
-------------------------------------------------------------------------------
-- InitInferValue
| This denotes specific value equalities that
associates with values .
data InitInferValue arch tp where
-- | Denotes the value must be the given offset of the stack frame.
InferredStackOffset :: !(MemInt (ArchAddrWidth arch))
-> InitInferValue arch (BVType (ArchAddrWidth arch))
-- | Denotes the value must be the value passed into the function at
-- the given register.
FnStartRegister :: !(ArchReg arch tp)
-> InitInferValue arch tp
-- | Denotes a value is equal to the value stored at the
-- representative location when the block start.
--
-- Note. The location in this must a "representative" location.
-- Representative locations are those locations chosen to represent
-- equivalence classes of locations inferred equal by block inference.
RegEqualLoc :: !(BoundLoc (ArchReg arch) tp)
-> InitInferValue arch tp
instance ShowF (ArchReg arch) => Show (InitInferValue arch tp) where
showsPrec _ (InferredStackOffset o) =
showString "(stack_offset " . shows o . showString ")"
showsPrec _ (FnStartRegister r) =
showString "(saved_reg " . showsF r . showString ")"
showsPrec _ (RegEqualLoc l) =
showString "(block_loc " . shows (pretty l) . showString ")"
instance ShowF (ArchReg arch) => ShowF (InitInferValue arch)
instance TestEquality (ArchReg arch) => TestEquality (InitInferValue arch) where
testEquality (InferredStackOffset x) (InferredStackOffset y) =
if x == y then Just Refl else Nothing
testEquality (FnStartRegister x) (FnStartRegister y) =
testEquality x y
testEquality (RegEqualLoc x) (RegEqualLoc y) =
testEquality x y
testEquality _ _ = Nothing
instance OrdF (ArchReg arch) => OrdF (InitInferValue arch) where
compareF (InferredStackOffset x) (InferredStackOffset y) =
fromOrdering (compare x y)
compareF (InferredStackOffset _) _ = LTF
compareF _ (InferredStackOffset _) = GTF
compareF (FnStartRegister x) (FnStartRegister y) = compareF x y
compareF (FnStartRegister _) _ = LTF
compareF _ (FnStartRegister _) = GTF
compareF (RegEqualLoc x) (RegEqualLoc y) = compareF x y
------------------------------------------------------------------------
-- BlockStartConstraints
-- | This maps r registers and stack offsets at start of block to
-- inferred information about their value.
--
-- If a register or stack location does not appear here, it
-- is implicitly set to itself.
newtype BlockStartConstraints arch =
BSC { bscLocMap :: LocMap (ArchReg arch) (InitInferValue arch) }
data TypedPair (key :: k -> Type) (tp :: k) = TypedPair !(key tp) !(key tp)
instance TestEquality k => TestEquality (TypedPair k) where
testEquality (TypedPair x1 x2) (TypedPair y1 y2) = do
Refl <- testEquality x1 y1
testEquality x2 y2
instance OrdF k => OrdF (TypedPair k) where
compareF (TypedPair x1 x2) (TypedPair y1 y2) =
joinOrderingF (compareF x1 y1) (compareF x2 y2)
-- | Return domain for location in constraints
locDomain :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> BoundLoc (ArchReg arch) tp
-> InitInferValue arch tp
locDomain cns l = fromMaybe (RegEqualLoc l) (locLookup l (bscLocMap cns))
-- | Function for joining constraints on a specific location.
--
-- Used by @joinBlockStartConstraints@ below.
joinInitInferValue :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-- ^ New constraints being added to existing one.
-> STRef s (LocMap (ArchReg arch) (InitInferValue arch))
-- ^ Map from locations to values that will be used in resulr.
-> STRef s (MapF (TypedPair (InitInferValue arch)) (BoundLoc (ArchReg arch)))
-- ^ Cache that maps (old,new) constraints to
-- a location that satisfied those
-- constraints in old and new constraint set
-- respectively.
-> BoundLoc (ArchReg arch) tp
-> InitInferValue arch tp
-- ^ Old domain for location.
-> Changed s ()
joinInitInferValue newCns cnsRef cacheRef l oldDomain = do
case (oldDomain, locDomain newCns l) of
(InferredStackOffset i, InferredStackOffset j)
| i == j ->
changedST $ modifySTRef cnsRef $ nonOverlapLocInsert l oldDomain
(FnStartRegister rx, FnStartRegister ry)
| Just Refl <- testEquality rx ry ->
changedST $ modifySTRef cnsRef $ nonOverlapLocInsert l oldDomain
(_, newDomain) -> do
c <- changedST $ readSTRef cacheRef
let p = TypedPair oldDomain newDomain
case MapF.lookup p c of
Nothing -> do
-- This is a new class representative.
-- New class representives imply that there was a change as
-- the location in the old domain must not have been a free
-- class rep.
markChanged True
changedST $ modifySTRef cacheRef $ MapF.insert p l
Just prevRep -> do
changed if the old domain was not just a pointer to prevRep .
case testEquality oldDomain (RegEqualLoc prevRep) of
Just _ -> pure ()
Nothing -> markChanged True
changedST $ modifySTRef cnsRef $ nonOverlapLocInsert l (RegEqualLoc prevRep)
| @joinBlockStartConstraints old new@ returns @Nothing@ if @new@
-- implies constraints in @old@, and otherwise a set of constraints
@c@ that implies both @new@ and @old@.
joinBlockStartConstraints :: forall s arch
. (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> BlockStartConstraints arch
-> Changed s (BlockStartConstraints arch)
joinBlockStartConstraints (BSC oldCns) newCns = do
-- Reference to new constraints
cnsRef <- changedST $ newSTRef locMapEmpty
-- Cache for recording when we have seen class representatives
cacheRef <- changedST $ newSTRef MapF.empty
let regFn :: ArchReg arch tp
-> InitInferValue arch tp
-> Changed s ()
regFn r d = joinInitInferValue newCns cnsRef cacheRef (RegLoc r) d
MapF.traverseWithKey_ regFn (locMapRegs oldCns)
let stackFn :: MemInt (ArchAddrWidth arch)
-> MemRepr tp
-> InitInferValue arch tp
-> Changed s ()
stackFn o r d =
joinInitInferValue newCns cnsRef cacheRef (StackOffLoc o r) d
memMapTraverseWithKey_ stackFn (locMapStack oldCns)
changedST $ BSC <$> readSTRef cnsRef
-- | @unionBlockStartConstraints x y@ returns a set of constraints @r@
that entails both @x@ and @y@.
unionBlockStartConstraints :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> BlockStartConstraints arch
-> BlockStartConstraints arch
unionBlockStartConstraints n o =
fromMaybe o (runChanged (joinBlockStartConstraints o n))
-------------------------------------------------------------------------------
StmtIndex
| Index of a stmt in a block .
type StmtIndex = Int
-- | This is used to to control which parts of a value we need to read.
data MemSlice wtp rtp where
NoMemSlice :: MemSlice tp tp
| @MemSlize o w r@ indicates that we read a value of type @r@ @o@ bytes into the write of type @w@.
MemSlice :: !Integer -- ^ Offset of read relative to write.
-> !(MemRepr wtp) -- ^ Write repr
-> !(MemRepr rtp) -- ^ Read repr
-> MemSlice wtp rtp
deriving instance Show (MemSlice w r)
instance TestEquality (MemSlice wtp) where
testEquality NoMemSlice NoMemSlice = Just Refl
testEquality (MemSlice xo xw xr) (MemSlice yo yw yr)
| xo == yo, Just Refl <- testEquality xw yw = testEquality xr yr
testEquality _ _ = Nothing
joinOrdering :: Ordering -> OrderingF a b -> OrderingF a b
joinOrdering LT _ = LTF
joinOrdering EQ o = o
joinOrdering GT _ = GTF
instance OrdF (MemSlice wtp) where
compareF NoMemSlice NoMemSlice = EQF
compareF NoMemSlice MemSlice{} = LTF
compareF MemSlice{} NoMemSlice = GTF
compareF (MemSlice xo xw xr) (MemSlice yo yw yr) =
joinOrdering (compare xo yo) $
joinOrderingF (compareF xw yw) $
compareF xr yr
------------------------------------------------------------------------
BlockInferValue
-- | This is an expression that represents a more canonical representation
of a value inferred by the invariant inference routine .
--
This difference between ` InitInferValue ` and ` BlockInferValue ` is that
-- `InitInferValue` captures constraints important to capture between blocks
while ` BlockInferValue ` has a richer constraint language capturing
-- inferrences within a block.
data BlockInferValue arch ids tp where
-- | Value register use domain
IVDomain :: !(InitInferValue arch wtp)
-> !(MemSlice wtp rtp)
-> BlockInferValue arch ids rtp
-- | The value of an assignment.
IVAssignValue :: !(AssignId ids tp)
-> BlockInferValue arch ids tp
-- | A constant
IVCValue :: !(CValue arch tp) -> BlockInferValue arch ids tp
-- | Denotes the value written by a conditional write at the given
-- index if the condition is true, or the value currently stored in
-- memory if the condition is false.
--
The MemRepr is the type of the write , and used for comparison .
IVCondWrite :: !StmtIndex -> !(MemRepr tp) -> BlockInferValue arch ids tp
deriving instance ShowF (ArchReg arch) => Show (BlockInferValue arch ids tp)
instance ShowF (ArchReg arch) => ShowF (BlockInferValue arch ids)
-- | Pattern for stack offset expressions
pattern FrameExpr :: ()
=> (tp ~ BVType (ArchAddrWidth arch))
=> MemInt (ArchAddrWidth arch)
-> BlockInferValue arch ids tp
pattern FrameExpr o = IVDomain (InferredStackOffset o) NoMemSlice
This returns @Just Refl@ if the two expressions denote the same
-- value under the assumptions about the start of the block, and the
-- assumption that non-stack writes do not affect the curent stack
-- frame.
instance TestEquality (ArchReg arch) => TestEquality (BlockInferValue arch ids) where
testEquality (IVDomain x xs) (IVDomain y ys) = do
Refl <- testEquality x y
testEquality xs ys
testEquality (IVAssignValue x) (IVAssignValue y) = testEquality x y
testEquality (IVCValue x) (IVCValue y) = testEquality x y
testEquality (IVCondWrite x xtp) (IVCondWrite y ytp) =
case x == y of
True ->
case testEquality xtp ytp of
Just Refl -> Just Refl
Nothing -> error "Equal conditional writes with inequal types."
False -> Nothing
testEquality _ _ = Nothing
Note . The @OrdF@ instance is a total order over @BlockInferValue@.
If it returns @EqF@ then it guarantees the two expressions denote
-- the same value under the assumptions about the start of the block,
-- and the assumption that non-stack writes do not affect the current
-- stack frame.
instance OrdF (ArchReg arch) => OrdF (BlockInferValue arch ids) where
compareF (IVDomain x xs) (IVDomain y ys) =
joinOrderingF (compareF x y) (compareF xs ys)
compareF IVDomain{} _ = LTF
compareF _ IVDomain{} = GTF
compareF (IVAssignValue x) (IVAssignValue y) = compareF x y
compareF IVAssignValue{} _ = LTF
compareF _ IVAssignValue{} = GTF
compareF (IVCValue x) (IVCValue y) = compareF x y
compareF IVCValue{} _ = LTF
compareF _ IVCValue{} = GTF
compareF (IVCondWrite x xtp) (IVCondWrite y ytp) =
case compare x y of
LT -> LTF
EQ ->
case testEquality xtp ytp of
Just Refl -> EQF
Nothing -> error "Equal conditional writes with inequal types."
GT -> GTF
-- | Information about a stack location used in invariant inference.
data InferStackValue arch ids tp where
-- | The stack location had this value in the initial stack.
ISVInitValue :: !(InitInferValue arch tp)
-> InferStackValue arch ids tp
| The value was written to the stack by a @WriteMem@ instruction
-- in the current block at the given index, and the value written
-- had the given inferred value.
ISVWrite :: !StmtIndex
-> !(Value arch ids tp)
-> InferStackValue arch ids tp
| denotes the value written to
-- the stack by a @CondWriteMem@ instruction in the current block
with the given instruction index @idx@ , condition @c@ , value @v@
-- and existing stack value @pv@.
--
The arguments are the index , the Boolean , the value written , and
-- the value overwritten.
ISVCondWrite :: !StmtIndex
-> !(Value arch ids BoolType)
-> !(Value arch ids tp)
-> !(InferStackValue arch ids tp)
-> InferStackValue arch ids tp
------------------------------------------------------------------------
-- StartInfer
-- | Read-only information needed to infer successor start
constraints for a lbok .
data StartInferContext arch =
SIC { sicAddr :: !(MemSegmentOff (ArchAddrWidth arch))
-- ^ Address of block we are inferring state for.
, sicRegs :: !(MapF (ArchReg arch) (InitInferValue arch))
-- ^ Map rep register to rheir initial domain information.
}
deriving instance (ShowF (ArchReg arch), MemWidth (ArchAddrWidth arch))
=> Show (StartInferContext arch)
-- | Evaluate a value in the context of the start infer state and
-- initial register assignment.
valueToStartExpr' :: OrdF (ArchReg arch)
=> StartInferContext arch
-- ^ Initial value of registers
-> MapF (AssignId ids) (BlockInferValue arch ids)
-- ^ Map from assignments to value.
-> Value arch ids wtp
-- ^ Value to convert.
-> MemSlice wtp rtp
-> Maybe (BlockInferValue arch ids rtp)
valueToStartExpr' _ _ (CValue c) NoMemSlice = Just (IVCValue c)
valueToStartExpr' _ _ (CValue _) MemSlice{} = Nothing
valueToStartExpr' _ am (AssignedValue (Assignment aid _)) NoMemSlice = Just $
MapF.findWithDefault (IVAssignValue aid) aid am
valueToStartExpr' _ _ (AssignedValue (Assignment _ _)) MemSlice{} = Nothing
valueToStartExpr' ctx _ (Initial r) ms = Just $
IVDomain (MapF.findWithDefault (RegEqualLoc (RegLoc r)) r (sicRegs ctx)) ms
-- | Evaluate a value in the context of the start infer state and
-- initial register assignment.
valueToStartExpr :: OrdF (ArchReg arch)
=> StartInferContext arch
-- ^ Initial value of registers
-> MapF (AssignId ids) (BlockInferValue arch ids)
-- ^ Map from assignments to value.
-> Value arch ids tp
-> BlockInferValue arch ids tp
valueToStartExpr _ _ (CValue c) = IVCValue c
valueToStartExpr _ am (AssignedValue (Assignment aid _)) =
MapF.findWithDefault (IVAssignValue aid) aid am
valueToStartExpr ctx _ (Initial r) =
IVDomain (MapF.findWithDefault (RegEqualLoc (RegLoc r)) r (sicRegs ctx))
NoMemSlice
inferStackValueToValue :: OrdF (ArchReg arch)
=> StartInferContext arch
-- ^ Initial value of registers
-> MapF (AssignId ids) (BlockInferValue arch ids)
-- ^ Map from assignments to value.
-> InferStackValue arch ids tp
-> MemRepr tp
-> BlockInferValue arch ids tp
inferStackValueToValue _ _ (ISVInitValue d) _ = IVDomain d NoMemSlice
inferStackValueToValue ctx m (ISVWrite _idx v) _ = valueToStartExpr ctx m v
inferStackValueToValue _ _ (ISVCondWrite idx _ _ _) repr = IVCondWrite idx repr
-- | Information about a memory access within a block
data MemAccessInfo arch ids
= -- | The access was not inferred to affect the current frame
NotFrameAccess
-- | The access read a frame offset that has not been written to
-- by the current block. The inferred value describes the value read.
| forall tp
. FrameReadInitAccess !(MemInt (ArchAddrWidth arch)) !(InitInferValue arch tp)
-- | The access read a frame offset that has been written to by a
-- previous write or cond-write in this block, and the
-- instruction had the given index.
| FrameReadWriteAccess !StmtIndex
-- | The access was a memory read that overlapped, but did not
-- exactly match a previous write.
| FrameReadOverlapAccess
!(MemInt (ArchAddrWidth arch))
-- | The access was a write to the current frame.
| FrameWriteAccess !(MemInt (ArchAddrWidth arch))
-- | The access was a conditional write to the current frame at the
-- given offset. The current
| forall tp
. FrameCondWriteAccess !(MemInt (ArchAddrWidth arch))
!(MemRepr tp)
!(InferStackValue arch ids tp)
-- | The access was a conditional write to the current frame at the
-- given offset, and the default value would overlap with a previous
-- write.
| FrameCondWriteOverlapAccess !(MemInt (ArchAddrWidth arch))
-- | State tracked to infer block preconditions.
data InferState arch ids =
SIS { -- | Current stack map.
--
Note . An uninitialized region at offset @o@ and type @repr@
-- implicitly is associated with
-- @ISVInitValue (RegEqualLoc (StackOffLoc o repr))@.
sisStack :: !(MemMap (MemInt (ArchAddrWidth arch)) (InferStackValue arch ids))
-- | Maps assignment identifiers to the associated value.
--
-- If an assignment id @aid@ is not in this map, then we assume it
-- is equal to @SAVEqualAssign aid@
, sisAssignMap :: !(MapF (AssignId ids) (BlockInferValue arch ids))
-- | Maps apps to the assignment identifier that created it.
, sisAppCache :: !(MapF (App (BlockInferValue arch ids)) (AssignId ids))
| Offset of current instruction relative to first
-- instruction in block.
, sisCurrentInstructionOffset :: !(ArchAddrWord arch)
-- | Information about memory accesses in reverse order of statement.
--
-- There should be one for each statement that is a @ReadMem@,
-- @CondReadMem@, @WriteMem@ and @CondWriteMem@.
, sisMemAccessStack :: ![(StmtIndex, MemAccessInfo arch ids)]
}
-- | Current state of stack.
sisStackLens :: Lens' (InferState arch ids)
(MemMap (MemInt (ArchAddrWidth arch)) (InferStackValue arch ids))
sisStackLens = lens sisStack (\s v -> s { sisStack = v })
-- | Maps assignment identifiers to the associated value.
--
-- If an assignment id is not in this map, then we assume it could not
-- be interpreted by the analysis.
sisAssignMapLens :: Lens' (InferState arch ids)
(MapF (AssignId ids) (BlockInferValue arch ids))
sisAssignMapLens = lens sisAssignMap (\s v -> s { sisAssignMap = v })
-- | Maps apps to the assignment identifier that created it.
sisAppCacheLens :: Lens' (InferState arch ids)
(MapF (App (BlockInferValue arch ids)) (AssignId ids))
sisAppCacheLens = lens sisAppCache (\s v -> s { sisAppCache = v })
-- | Maps apps to the assignment identifier that created it.
sisCurrentInstructionOffsetLens :: Lens' (InferState arch ids) (ArchAddrWord arch)
sisCurrentInstructionOffsetLens =
lens sisCurrentInstructionOffset (\s v -> s { sisCurrentInstructionOffset = v })
-- | Monad used for inferring start constraints.
--
-- Note. The process of inferring start constraints intentionally does
-- not do stack escape analysis or other
type StartInfer arch ids =
ReaderT (StartInferContext arch) (StateT (InferState arch ids) (Except (RegisterUseError arch)))
-- | Set the value associated with an assignment
setAssignVal :: AssignId ids tp
-> BlockInferValue arch ids tp
-> StartInfer arch ids ()
setAssignVal aid v = sisAssignMapLens %= MapF.insert aid v
-- | Record the mem access information
addMemAccessInfo :: StmtIndex -> MemAccessInfo arch ids -> StartInfer arch ids ()
addMemAccessInfo idx i = seq idx $ seq i $ do
modify $ \s -> s { sisMemAccessStack = (idx,i) : sisMemAccessStack s }
processApp :: (OrdF (ArchReg arch), MemWidth (ArchAddrWidth arch))
=> AssignId ids tp
-> App (Value arch ids) tp
-> StartInfer arch ids ()
processApp aid app = do
ctx <- ask
am <- gets sisAssignMap
case fmapFC (valueToStartExpr ctx am) app of
BVAdd _ (FrameExpr o) (IVCValue (BVCValue _ c)) ->
setAssignVal aid (FrameExpr (o+fromInteger c))
BVAdd _ (IVCValue (BVCValue _ c)) (FrameExpr o) ->
setAssignVal aid (FrameExpr (o+fromInteger c))
BVSub _ (FrameExpr o) (IVCValue (BVCValue _ c)) ->
setAssignVal aid (FrameExpr (o-fromInteger c))
appExpr -> do
c <- gets sisAppCache
-- Check to see if we have seen an app equivalent to
-- this one under the invariant assumption.
case MapF.lookup appExpr c of
-- If we have not, then record it in the cache for
-- later.
Nothing -> do
sisAppCacheLens %= MapF.insert appExpr aid
-- If we have seen this app, then we set it equal to previous.
Just prevId -> do
setAssignVal aid (IVAssignValue prevId)
-- | @checkReadWithinWrite writeOff writeType readOff readType@ checks that
-- the read is contained within the write and returns a mem slice if so.
checkReadWithinWrite :: MemWidth w
=> MemInt w -- ^ Write offset
-> MemRepr wtp -- ^ Write repr
-> MemInt w -- ^ Read offset
-> MemRepr rtp -- ^ Read repr
-> Maybe (MemSlice wtp rtp)
checkReadWithinWrite wo wr ro rr
| wo == ro, Just Refl <- testEquality wr rr =
Just NoMemSlice
| wo <= ro
, d <- toInteger ro - toInteger wo
, rEnd <- d + toInteger (memReprBytes rr)
, wEnd <- toInteger (memReprBytes wr)
, rEnd <= wEnd =
Just (MemSlice d wr rr)
| otherwise = Nothing
throwRegError :: StmtIndex -> RegisterUseErrorTag e -> e -> StartInfer arch ids a
throwRegError stmtIdx tag v = do
blockAddr <- asks sicAddr
throwError $
RegisterUseError
{ ruBlock = blockAddr,
ruStmt = stmtIdx,
ruReason = Reason tag v
}
unresolvedStackRead :: StmtIndex -> StartInfer arch ids as
unresolvedStackRead stmtIdx = do
throwRegError stmtIdx UnresolvedStackRead ()
-- | Infer constraints from a memory read
inferReadMem ::
(MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch)) =>
StmtIndex ->
AssignId ids tp ->
Value arch ids (BVType (ArchAddrWidth arch)) ->
MemRepr tp ->
StartInfer arch ids ()
inferReadMem stmtIdx aid addr repr = do
ctx <- ask
am <- gets sisAssignMap
case valueToStartExpr ctx am addr of
FrameExpr o -> do
stk <- gets sisStack
case memMapLookup' o repr stk of
Just (writeOff, MemVal writeRepr sv) ->
case checkReadWithinWrite writeOff writeRepr o repr of
-- Overlap reads just get recorded
Nothing ->
addMemAccessInfo stmtIdx (FrameReadOverlapAccess o)
-- Reads within writes get propagated.
Just ms -> do
(v, memInfo) <-
case sv of
ISVInitValue d -> do
pure (IVDomain d ms, FrameReadInitAccess o d)
ISVWrite writeIdx v ->
case valueToStartExpr' ctx am v ms of
Nothing -> do
unresolvedStackRead stmtIdx
Just iv ->
pure (iv, FrameReadWriteAccess writeIdx)
ISVCondWrite writeIdx _ _ _ -> do
case ms of
NoMemSlice ->
pure (IVCondWrite writeIdx repr, FrameReadWriteAccess writeIdx)
MemSlice _ _ _ ->
unresolvedStackRead stmtIdx
setAssignVal aid v
addMemAccessInfo stmtIdx memInfo
-- Uninitialized reads are equal to what came before.
Nothing -> do
let d = RegEqualLoc (StackOffLoc o repr)
setAssignVal aid (IVDomain d NoMemSlice)
addMemAccessInfo stmtIdx (FrameReadInitAccess o d)
-- Non-stack reads are just equal to themselves.
_ -> addMemAccessInfo stmtIdx NotFrameAccess
-- | Infer constraints from a memory read.
--
-- Unlike inferReadMem these are not assigned a value, but we still
-- track which write was associated if possible.
inferCondReadMem :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> StmtIndex
-> Value arch ids (BVType (ArchAddrWidth arch))
-> MemRepr tp
-> StartInfer arch ids ()
inferCondReadMem stmtIdx addr _repr = do
ctx <- ask
s <- gets sisAssignMap
case valueToStartExpr ctx s addr of
Stack reads need to record the offset .
FrameExpr _o -> do
throwRegError stmtIdx UnsupportedCondStackRead ()
-- Non-stack reads are just equal to themselves.
_ -> addMemAccessInfo stmtIdx NotFrameAccess
-- | Update start infer statement to reflect statement.
processStmt :: (OrdF (ArchReg arch), MemWidth (ArchAddrWidth arch))
=> StmtIndex
-> Stmt arch ids
-> StartInfer arch ids ()
processStmt stmtIdx stmt = do
case stmt of
AssignStmt (Assignment aid arhs) ->
case arhs of
EvalApp app -> processApp aid app
-- Assignment equal to itself.
SetUndefined _ -> pure ()
ReadMem addr repr -> inferReadMem stmtIdx aid addr repr
CondReadMem repr _cond addr _falseVal -> inferCondReadMem stmtIdx addr repr
-- Architecture-specific functions are just equal to themselves.
EvalArchFn _afn _repr -> pure ()
WriteMem addr repr val -> do
ctx <- ask
s <- gets sisAssignMap
case valueToStartExpr ctx s addr of
FrameExpr o -> do
addMemAccessInfo stmtIdx (FrameWriteAccess o)
-- Get value of val under current equality constraints.
sisStackLens %= memMapOverwrite o repr (ISVWrite stmtIdx val)
-- Do nothing for things that are not stack expressions.
--
Note . If @addr@ actually may point to the stack but we end
-- up in this case, then @sisStack@ will not be properly
-- updated to reflect real contents, and the value refered
-- to be subsequent @readMem@ operations may be incorrect.
--
-- This is currently unavoidable to fix in this code, and
-- perhaps can never be fully addressed as we'd basically need
-- a proof that that the stack could not be overwritten.
-- However, this will be caught by verification of the
eventual .
_ -> addMemAccessInfo stmtIdx NotFrameAccess
CondWriteMem cond addr repr val -> do
ctx <- ask
s <- gets sisAssignMap
case valueToStartExpr ctx s addr of
FrameExpr o -> do
stk <- gets sisStack
sv <-
case memMapLookup o repr stk of
MMLResult sv -> do
addMemAccessInfo stmtIdx (FrameCondWriteAccess o repr sv)
pure sv
MMLOverlap{} -> do
addMemAccessInfo stmtIdx (FrameCondWriteOverlapAccess o)
pure $ ISVInitValue (RegEqualLoc (StackOffLoc o repr))
MMLNone -> do
let sv = ISVInitValue (RegEqualLoc (StackOffLoc o repr))
addMemAccessInfo stmtIdx (FrameCondWriteAccess o repr sv)
pure sv
sisStackLens %= memMapOverwrite o repr (ISVCondWrite stmtIdx cond val sv)
_ -> do
addMemAccessInfo stmtIdx NotFrameAccess
-- Do nothing with instruction start/comment/register update
InstructionStart o _ ->
sisCurrentInstructionOffsetLens .= o
Comment _ -> pure ()
ArchState{} -> pure ()
-- For now we assume architecture statement does not modify any
-- of the locations.
ExecArchStmt _ -> pure ()
-- | Maps locations to the values to initialize next locations with.
newtype PostValueMap arch ids =
PVM { _pvmMap :: MapF (BoundLoc (ArchReg arch)) (BlockInferValue arch ids) }
emptyPVM :: PostValueMap arch ids
emptyPVM = PVM MapF.empty
pvmBind :: OrdF (ArchReg arch)
=> BoundLoc (ArchReg arch) tp
-> BlockInferValue arch ids tp
-> PostValueMap arch ids
-> PostValueMap arch ids
pvmBind l v (PVM m) = PVM (MapF.insert l v m)
pvmFind :: OrdF (ArchReg arch)
=> BoundLoc (ArchReg arch) tp
-> PostValueMap arch ids
-> BlockInferValue arch ids tp
pvmFind l (PVM m) = MapF.findWithDefault (IVDomain (RegEqualLoc l) NoMemSlice) l m
instance ShowF (ArchReg arch) => Show (PostValueMap arch ids) where
show (PVM m) = show m
ppPVM :: forall arch ids ann . ShowF (ArchReg arch) => PostValueMap arch ids -> Doc ann
ppPVM (PVM m) = vcat $ ppVal <$> MapF.toList m
where ppVal :: Pair (BoundLoc (ArchReg arch)) (BlockInferValue arch ids) -> Doc ann
ppVal (Pair l v) = pretty l <+> ":=" <+> viaShow v
type StartInferInfo arch ids =
( ParsedBlock arch ids
, BlockStartConstraints arch
, InferState arch ids
, Map (ArchSegmentOff arch) (PostValueMap arch ids)
)
siiCns :: StartInferInfo arch ids -> BlockStartConstraints arch
siiCns (_,cns,_,_) = cns
type FrontierMap arch = Map (ArchSegmentOff arch) (BlockStartConstraints arch)
data InferNextState arch ids =
InferNextState { insSeenValues :: !(MapF (BlockInferValue arch ids) (InitInferValue arch))
, insPVM :: !(PostValueMap arch ids)
}
-- | Monad for inferring next state.
type InferNextM arch ids = State (InferNextState arch ids)
runInferNextM :: InferNextM arch ids a -> a
runInferNextM m =
let s = InferNextState { insSeenValues = MapF.empty
, insPVM = emptyPVM
}
in evalState m s
| assumes that @expr@ is the value
assigned to @loc@ in the next function , and returns the domain to
-- use for that location in the next block start constraints or
-- @Nothing@ if the value is unconstrained.
memoNextDomain :: OrdF (ArchReg arch)
=> BoundLoc (ArchReg arch) tp
-> BlockInferValue arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
memoNextDomain _ (IVDomain d@InferredStackOffset{} NoMemSlice) =
pure (Just d)
memoNextDomain _ (IVDomain d@FnStartRegister{} NoMemSlice) = pure (Just d)
memoNextDomain loc e = do
m <- gets insSeenValues
case MapF.lookup e m of
Just d -> do
modify $ \s -> InferNextState { insSeenValues = m
, insPVM = pvmBind loc e (insPVM s)
}
pure (Just d)
Nothing -> do
modify $ \s -> InferNextState { insSeenValues = MapF.insert e (RegEqualLoc loc) m
, insPVM = pvmBind loc e (insPVM s)
}
pure Nothing
-- | Process terminal registers
addNextConstraints :: forall arch
. (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> (ArchSegmentOff arch -> Maybe (BlockStartConstraints arch))
-- ^ Map of previously explored constraints
-> ArchSegmentOff arch
-- ^ Address to jump to
-> BlockStartConstraints arch
-- ^ Start constraints at address.
-> FrontierMap arch
-- ^ New frontier
-> FrontierMap arch
addNextConstraints lastMap addr nextCns frontierMap =
let modifyFrontier :: Maybe (BlockStartConstraints arch)
-> Maybe (BlockStartConstraints arch)
modifyFrontier (Just prevCns) =
Just (unionBlockStartConstraints nextCns prevCns)
modifyFrontier Nothing =
case lastMap addr of
Nothing -> Just nextCns
Just prevCns -> runChanged (joinBlockStartConstraints prevCns nextCns)
in Map.alter modifyFrontier addr frontierMap
-- | Get post value map an dnext constraints for an intra-procedural jump to target.
intraJumpConstraints :: forall arch ids
. OrdF (ArchReg arch)
=> StartInferContext arch
-> InferState arch ids
-> RegState (ArchReg arch) (Value arch ids)
-- ^ Values assigned to registers at end of blocks.
--
-- Unassigned registers are considered to be assigned
-- arbitrary values. This is used for modeling calls
-- where only some registers are preserved.
-> (PostValueMap arch ids, BlockStartConstraints arch)
intraJumpConstraints ctx s regs = runInferNextM $ do
let intraRegFn :: ArchReg arch tp
-> Value arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
intraRegFn r v = memoNextDomain (RegLoc r) (valueToStartExpr ctx (sisAssignMap s) v)
regs' <- MapF.traverseMaybeWithKey intraRegFn (regStateMap regs)
let stackFn :: MemInt (ArchAddrWidth arch)
-> MemRepr tp
-> InferStackValue arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
stackFn o repr sv =
memoNextDomain (StackOffLoc o repr) (inferStackValueToValue ctx (sisAssignMap s) sv repr)
stk <- memMapTraverseMaybeWithKey stackFn (sisStack s)
postValMap <- gets insPVM
let cns = BSC LocMap { locMapRegs = regs'
, locMapStack = stk
}
pure (postValMap, cns)
-- | Post call constraints for return address.
postCallConstraints :: forall arch ids
. ArchConstraints arch
=> CallParams (ArchReg arch)
-- ^ Architecture-specific call parameters
-> StartInferContext arch
-- ^ Context for block invariants inference.
-> InferState arch ids
-- ^ State for start inference
-> Int
-- ^ Index of term statement
-> RegState (ArchReg arch) (Value arch ids)
-- ^ Registers at time of call.
-> Either (RegisterUseError arch)
(PostValueMap arch ids, BlockStartConstraints arch)
postCallConstraints params ctx s tidx regs =
runInferNextM $ do
case valueToStartExpr ctx (sisAssignMap s) (regs^.boundValue sp_reg) of
FrameExpr spOff -> do
when (not (stackGrowsDown params)) $
error "Do not yet support architectures where stack grows up."
when (postCallStackDelta params < 0) $
error "Unexpected post call stack delta."
-- Upper bound is stack offset before call.
let h = toInteger spOff
-- Lower bound is stack bound after call.
let l = h - postCallStackDelta params
-- Function to update register state.
let intraRegFn :: ArchReg arch tp
-> Value arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
intraRegFn r v
| Just Refl <- testEquality r sp_reg = do
let spOff' = spOff + fromInteger (postCallStackDelta params)
pure (Just (InferredStackOffset spOff'))
| preserveReg params r =
memoNextDomain (RegLoc r) (valueToStartExpr ctx (sisAssignMap s) v)
| otherwise =
pure Nothing
regs' <- MapF.traverseMaybeWithKey intraRegFn (regStateMap regs)
let stackFn :: MemInt (ArchAddrWidth arch)
-> MemRepr tp
-> InferStackValue arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
stackFn o repr sv
-- Drop the return address pointer
| l <= toInteger o, toInteger o < h =
pure Nothing
| otherwise =
-- Otherwise preserve the value.
memoNextDomain (StackOffLoc o repr) (inferStackValueToValue ctx (sisAssignMap s) sv repr)
stk <- memMapTraverseMaybeWithKey stackFn (sisStack s)
postValMap <- gets insPVM
let cns = BSC LocMap { locMapRegs = regs'
, locMapStack = stk
}
pure $ Right $ (postValMap, cns)
_ -> pure $ Left $
RegisterUseError
{ ruBlock = sicAddr ctx,
ruStmt = tidx,
ruReason = Reason CallStackHeightError ()
}
-------------------------------------------------------------------------------
-- DependencySet
-- | This records what assignments and initial value locations are
-- needed to compute a value or execute code in a block with side
-- effects.
data DependencySet (r :: M.Type -> Type) ids =
DepSet { dsLocSet :: !(Set (Some (BoundLoc r)))
-- ^ Set of locations that block reads the initial
-- value of.
, dsAssignSet :: !(Set (Some (AssignId ids)))
-- ^ Set of assignments that must be executed.
, dsWriteStmtIndexSet :: !(Set StmtIndex)
-- ^ Block start address and index of write statement that
-- writes a value to the stack that is read later.
}
ppSet :: (a -> Doc ann) -> Set a -> Doc ann
ppSet f s = encloseSep lbrace rbrace comma (f <$> Set.toList s)
ppSomeAssignId :: Some (AssignId ids) -> Doc ann
ppSomeAssignId (Some aid) = viaShow aid
ppSomeBoundLoc :: MapF.ShowF r => Some (BoundLoc r) -> Doc ann
ppSomeBoundLoc (Some loc) = pretty loc
instance MapF.ShowF r => Pretty (DependencySet r ids) where
pretty ds =
vcat [ "Assignments:" <+> ppSet ppSomeAssignId (dsAssignSet ds)
, "Locations: " <+> ppSet ppSomeBoundLoc (dsLocSet ds)
, "Write Stmts:" <+> ppSet pretty (dsWriteStmtIndexSet ds)
]
-- | Empty dependency set.
emptyDeps :: DependencySet r ids
emptyDeps =
DepSet { dsLocSet = Set.empty
, dsAssignSet = Set.empty
, dsWriteStmtIndexSet = Set.empty
}
-- | Dependency set for a single assignment
assignSet :: AssignId ids tp -> DependencySet r ids
assignSet aid =
DepSet { dsLocSet = Set.empty
, dsAssignSet = Set.singleton (Some aid)
, dsWriteStmtIndexSet = Set.empty
}
-- | Create a dependency set for a single location.
locDepSet :: BoundLoc r tp -> DependencySet r ids
locDepSet l =
DepSet { dsLocSet = Set.singleton (Some l)
, dsAssignSet = Set.empty
, dsWriteStmtIndexSet = Set.empty
}
-- | @addWriteDep stmtIdx
addWriteDep :: StmtIndex -> DependencySet r ids -> DependencySet r ids
addWriteDep idx s = seq idx $
s { dsWriteStmtIndexSet = Set.insert idx (dsWriteStmtIndexSet s) }
instance MapF.OrdF r => Semigroup (DependencySet r ids) where
x <> y = DepSet { dsAssignSet = Set.union (dsAssignSet x) (dsAssignSet y)
, dsLocSet = Set.union (dsLocSet x) (dsLocSet y)
, dsWriteStmtIndexSet =
Set.union (dsWriteStmtIndexSet x) (dsWriteStmtIndexSet y)
}
instance MapF.OrdF r => Monoid (DependencySet r ids) where
mempty = emptyDeps
------------------------------------------------------------------------
-- RegDependencyMap
-- | Map from register to the dependencies for that register.
newtype RegDependencyMap arch ids =
RDM { rdmMap :: MapF (ArchReg arch) (Const (DependencySet (ArchReg arch) ids)) }
emptyRegDepMap :: RegDependencyMap arch ids
emptyRegDepMap = RDM MapF.empty
instance OrdF (ArchReg arch) => Semigroup (RegDependencyMap arch ids) where
RDM x <> RDM y = RDM (MapF.union x y)
instance OrdF (ArchReg arch) => Monoid (RegDependencyMap arch ids) where
mempty = emptyRegDepMap
-- | Set dependency for register
setRegDep :: OrdF (ArchReg arch)
=> ArchReg arch tp
-> DependencySet (ArchReg arch) ids
-> RegDependencyMap arch ids
-> RegDependencyMap arch ids
setRegDep r d (RDM m) = RDM (MapF.insert r (Const d) m)
-- | Create dependencies from map
regDepsFromMap :: (forall tp . a tp -> DependencySet (ArchReg arch) ids)
-> MapF (ArchReg arch) a
-> RegDependencyMap arch ids
regDepsFromMap f m = RDM (fmapF (Const . f) m)
------------------------------------------------------------------------
-- BlockUsageSummary
-- | This contains information about a specific block needed to infer
-- which locations and assignments are needed to execute the block
-- along with information about the demands to compute the value of
-- particular locations after the block executes.
data BlockUsageSummary (arch :: Type) ids = BUS
{ blockUsageStartConstraints :: !(BlockStartConstraints arch)
-- | Offset of start of last instruction processed relative to start of block.
, blockCurOff :: !(ArchAddrWord arch)
-- | Inferred state computed at beginning
, blockInferState :: !(InferState arch ids)
-- | Dependencies needed to execute statements with side effects.
,_blockExecDemands :: !(DependencySet (ArchReg arch) ids)
-- | Map registers to the dependencies of the values they store.
--
-- Defined in block terminator.
, blockRegDependencies :: !(RegDependencyMap arch ids)
-- | Map indexes of writes and cond write instructions to their dependency set.
, blockWriteDependencies :: !(Map StmtIndex (DependencySet (ArchReg arch) ids))
-- | Maps assignments to their dependencies.
, assignDeps :: !(Map (Some (AssignId ids)) (DependencySet (ArchReg arch) ids))
-- | Information about next memory reads.
, pendingMemAccesses :: ![(StmtIndex, MemAccessInfo arch ids)]
-- | If this block ends with a call, this has the type of the function called.
Otherwise , the value should be @Nothing@.
, blockCallFunType :: !(Maybe (ArchFunType arch))
}
initBlockUsageSummary :: BlockStartConstraints arch
-> InferState arch ids
-> BlockUsageSummary arch ids
initBlockUsageSummary cns s =
let a = reverse (sisMemAccessStack s)
in BUS { blockUsageStartConstraints = cns
, blockCurOff = zeroMemWord
, blockInferState = s
, _blockExecDemands = emptyDeps
, blockRegDependencies = emptyRegDepMap
, blockWriteDependencies = Map.empty
, assignDeps = Map.empty
, pendingMemAccesses = a
, blockCallFunType = Nothing
}
-- | Dependencies needed to execute statements with side effects.
blockExecDemands :: Lens' (BlockUsageSummary arch ids) (DependencySet (ArchReg arch) ids)
blockExecDemands = lens _blockExecDemands (\s v -> s { _blockExecDemands = v })
-- | Maps registers to the dependencies needed to compute that
-- register value.
blockRegDependenciesLens :: Lens' (BlockUsageSummary arch ids) (RegDependencyMap arch ids)
blockRegDependenciesLens = lens blockRegDependencies (\s v -> s { blockRegDependencies = v })
-- | Maps stack offsets to the dependencies needed to compute the
-- value stored at that offset.
blockWriteDependencyLens :: Lens' (BlockUsageSummary arch ids)
(Map StmtIndex (DependencySet (ArchReg arch) ids))
blockWriteDependencyLens = lens blockWriteDependencies (\s v -> s { blockWriteDependencies = v })
assignmentCache :: Lens' (BlockUsageSummary arch ids)
(Map (Some (AssignId ids)) (DependencySet (ArchReg arch) ids))
assignmentCache = lens assignDeps (\s v -> s { assignDeps = v })
------------------------------------------------------------------------
-- | Identifies demand information about a particular call.
data CallRegs (arch :: Type) (ids :: Type) =
CallRegs { callRegsFnType :: !(ArchFunType arch)
, callArgValues :: [Some (Value arch ids)]
, callReturnRegs :: [Some (ArchReg arch)]
}
------------------------------------------------------------------------
-- RegisterUseContext
type PostTermStmtInvariants arch ids =
StartInferContext arch
-> InferState arch ids
-> Int
-> ArchTermStmt arch (Value arch ids)
-> RegState (ArchReg arch) (Value arch ids)
-> Either (RegisterUseError arch) (PostValueMap arch ids, BlockStartConstraints arch)
type ArchTermStmtUsageFn arch ids
= ArchTermStmt arch (Value arch ids)
-> RegState (ArchReg arch) (Value arch ids)
-> BlockUsageSummary arch ids
-> Either (RegisterUseError arch) (RegDependencyMap arch ids)
-- | Architecture specific information about the type of function
-- called by inferring call-site information.
--
-- Used to memoize analysis returned by @callDemandFn@.
type family ArchFunType (arch::Type) :: Type
data RegisterUseContext arch
= RegisterUseContext
{ -- | Set of registers preserved by a call.
archCallParams :: !(CallParams (ArchReg arch))
-- | Given a terminal statement and list of registers it returns
-- Map containing values afterwards.
, archPostTermStmtInvariants :: !(forall ids . PostTermStmtInvariants arch ids)
-- | Registers that are saved by calls (excludes rsp)
, calleeSavedRegisters :: ![Some (ArchReg arch)]
-- | List of registers that callers may freely change.
, callScratchRegisters :: ![Some (ArchReg arch)]
-- ^ The list of registers that are preserved by a function
-- call.
--
Note . Should not include stack pointer as thay is
-- handled differently.
-- | Return registers demanded by this function
, returnRegisters :: ![Some (ArchReg arch)]
-- | Callback function for summarizing register usage of terminal
-- statements.
, reguseTermFn :: !(forall ids . ArchTermStmtUsageFn arch ids)
-- | Given the address of a call instruction and registers, this returns the
-- values read and returned.
, callDemandFn :: !(forall ids
. ArchSegmentOff arch
-> RegState (ArchReg arch) (Value arch ids)
-> Either RegisterUseErrorReason (CallRegs arch ids))
-- | Information needed to demands of architecture-specific functions.
, demandContext :: !(DemandContext arch)
}
-- | Add frontier for an intra-procedural jump that preserves register
-- and stack.
visitIntraJumpTarget :: forall arch ids
. (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> (ArchSegmentOff arch -> Maybe (BlockStartConstraints arch))
-> StartInferContext arch
-> InferState arch ids
-> RegState (ArchReg arch) (Value arch ids)
-- ^ Values assigned to registers at end of blocks.
--
-- Unassigned registers are considered to be assigned
-- arbitrary values. This is used for modeling calls
-- where only some registers are preserved.
-> (Map (ArchSegmentOff arch) (PostValueMap arch ids), FrontierMap arch)
^ Frontier so far
-> ArchSegmentOff arch -- ^ Address to jump to
-> (Map (ArchSegmentOff arch) (PostValueMap arch ids), FrontierMap arch)
visitIntraJumpTarget lastMap ctx s regs (m,frontierMap) addr =
let nextCns :: BlockStartConstraints arch
(postValMap, nextCns) = intraJumpConstraints ctx s regs
in (Map.insert addr postValMap m, addNextConstraints lastMap addr nextCns frontierMap)
-- | Analyze block to update start constraints on successors and add blocks
-- with changed constraints to frontier.
blockStartConstraints :: ArchConstraints arch
=> RegisterUseContext arch
-> Map (ArchSegmentOff arch) (ParsedBlock arch ids)
-- ^ Map from starting addresses to blocks.
-> ArchSegmentOff arch
-- ^ Address of start of block.
-> BlockStartConstraints arch
-> Map (ArchSegmentOff arch) (StartInferInfo arch ids)
-- ^ Results from last explore map
-> FrontierMap arch
-- ^ Maps addresses of blocks to explore to the
-- starting constraints.
-> Except (RegisterUseError arch)
(Map (ArchSegmentOff arch) (StartInferInfo arch ids), FrontierMap arch)
blockStartConstraints rctx blockMap addr (BSC cns) lastMap frontierMap = do
let b = Map.findWithDefault (error "No block") addr blockMap
let ctx = SIC { sicAddr = addr
, sicRegs = locMapRegs cns
}
let s0 = SIS { sisStack = fmapF ISVInitValue (locMapStack cns)
, sisAssignMap = MapF.empty
, sisAppCache = MapF.empty
, sisCurrentInstructionOffset = 0
, sisMemAccessStack = []
}
-- Get statements in block
let stmts = pblockStmts b
let stmtCount = length stmts
-- Get state from processing all statements
s <- execStateT (runReaderT (zipWithM_ processStmt [0..] stmts) ctx) s0
let lastFn a = if a == addr then Just (BSC cns) else siiCns <$> Map.lookup a lastMap
case pblockTermStmt b of
ParsedJump regs next -> do
let (pvm,frontierMap') = visitIntraJumpTarget lastFn ctx s regs (Map.empty, frontierMap) next
let m' = Map.insert addr (b, BSC cns, s, pvm) lastMap
pure $ (m', frontierMap')
ParsedBranch regs _cond t f -> do
let (pvm, frontierMap') = foldl' (visitIntraJumpTarget lastFn ctx s regs) (Map.empty, frontierMap) [t,f]
let m' = Map.insert addr (b, BSC cns, s, pvm) lastMap
pure $ (m', frontierMap')
ParsedLookupTable _layout regs _idx lbls -> do
let (pvm, frontierMap') = foldl' (visitIntraJumpTarget lastFn ctx s regs) (Map.empty, frontierMap) lbls
let m' = Map.insert addr (b, BSC cns, s, pvm) lastMap
pure $ (m', frontierMap')
ParsedCall regs (Just next) -> do
(postValCns, nextCns) <-
case postCallConstraints (archCallParams rctx) ctx s stmtCount regs of
Left e -> throwError e
Right r -> pure r
let m' = Map.insert addr (b, BSC cns, s, Map.singleton next postValCns) lastMap
pure (m', addNextConstraints lastFn next nextCns frontierMap)
-- Tail call
ParsedCall _ Nothing -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
ParsedReturn _ -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
-- Works like a tail call.
ParsedArchTermStmt _ _ Nothing -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
ParsedArchTermStmt tstmt regs (Just next) -> do
case archPostTermStmtInvariants rctx ctx s stmtCount tstmt regs of
Left e ->
throwError e
Right (postValCns, nextCns) -> do
let m' = Map.insert addr (b, BSC cns, s, Map.singleton next postValCns) lastMap
pure (m', addNextConstraints lastFn next nextCns frontierMap)
ParsedTranslateError _ -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
ClassifyFailure _ _ -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
PLT stubs are essentiually tail calls with a non - standard
-- calling convention.
PLTStub{} -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
-- | Infer start constraints by recursively evaluating blocks
propStartConstraints :: ArchConstraints arch
=> RegisterUseContext arch
-> Map (ArchSegmentOff arch) (ParsedBlock arch ids)
-- ^ Map from starting addresses to blocks.
-> Map (ArchSegmentOff arch) (StartInferInfo arch ids)
-- ^ Map starting address of blocks to information
-- about block from last exploration.
-> FrontierMap arch
-- ^ Maps addresses of blocks to explore to
-- the starting constraints.
-> Except (RegisterUseError arch)
(Map (ArchSegmentOff arch) (StartInferInfo arch ids))
propStartConstraints rctx blockMap lastMap next =
case Map.minViewWithKey next of
Nothing -> pure lastMap
Just ((nextAddr, nextCns), rest) -> do
(lastMap', next') <- blockStartConstraints rctx blockMap nextAddr nextCns lastMap rest
propStartConstraints rctx blockMap lastMap' next'
-- | Infer start constraints by recursively evaluating blocks
inferStartConstraints :: forall arch ids
. ArchConstraints arch
=> RegisterUseContext arch
-> Map (ArchSegmentOff arch) (ParsedBlock arch ids)
-- ^ Map from starting addresses to blocks.
-> ArchSegmentOff arch
-- ^ Map starting address of blocks to information
-- about block from last exploration.
-> Except (RegisterUseError arch)
(Map (ArchSegmentOff arch) (StartInferInfo arch ids))
inferStartConstraints rctx blockMap addr = do
let savedRegs :: [Pair (ArchReg arch) (InitInferValue arch)]
savedRegs
= [ Pair sp_reg (InferredStackOffset 0) ]
++ [ Pair r (FnStartRegister r) | Some r <- calleeSavedRegisters rctx ]
let cns = BSC LocMap { locMapRegs = MapF.fromList savedRegs
, locMapStack = emptyMemMap
}
propStartConstraints rctx blockMap Map.empty (Map.singleton addr cns)
-- | Pretty print start constraints for debugging purposes.
ppStartConstraints :: forall arch ids ann
. (MemWidth (ArchAddrWidth arch), ShowF (ArchReg arch))
=> Map (ArchSegmentOff arch) (StartInferInfo arch ids)
-> Doc ann
ppStartConstraints m = vcat (pp <$> Map.toList m)
where pp :: (ArchSegmentOff arch, StartInferInfo arch ids) -> Doc ann
pp (addr, (_,_,_,pvm)) =
let pvmEntries = vcat (ppPVMPair <$> Map.toList pvm)
in vcat [ pretty addr
, indent 2 $ vcat ["post-values:", indent 2 pvmEntries] ]
ppPVMPair :: (ArchSegmentOff arch, PostValueMap arch ids) -> Doc ann
ppPVMPair (preaddr, pvm) =
vcat
[ "to" <+> pretty preaddr <> ":"
, indent 2 (ppPVM pvm) ]
_ppStartConstraints :: forall arch ids ann
. (MemWidth (ArchAddrWidth arch), ShowF (ArchReg arch))
=> Map (ArchSegmentOff arch) (StartInferInfo arch ids)
-> Doc ann
_ppStartConstraints = ppStartConstraints
------------------------------------------------------------------------
--
-- | This maps each location that could be accessed after a block
-- terminates to the set of values needed to compute the value of the
-- location.
type LocDependencyMap r ids = LocMap r (Const (DependencySet r ids))
-- | Get dependency set for location.
--
-- Note. This code is currently buggy in that it will back propagate
-- stack reads that are partially overwritten.
getLocDependencySet :: (MapF.OrdF r, MemWidth (RegAddrWidth r))
=> LocDependencyMap r ids
-> BoundLoc r tp
-> DependencySet r ids
getLocDependencySet srcDepMap l =
case locLookup l srcDepMap of
Nothing -> locDepSet l
Just (Const s) -> s
------------------------------------------------------------------------
RegisterUseM
type RegisterUseM arch ids =
ReaderT (RegisterUseContext arch)
(StateT (BlockUsageSummary arch ids)
(Except (RegisterUseError arch)))
-- ----------------------------------------------------------------------------------------
-- Phase one functions
-- ----------------------------------------------------------------------------------------
domainDeps :: InitInferValue arch tp -> DependencySet (ArchReg arch) ids
domainDeps (InferredStackOffset _) = emptyDeps
domainDeps (FnStartRegister _) = emptyDeps
domainDeps (RegEqualLoc l) = locDepSet l
-- | Return the register and assignment dependencies needed to
valueDeps :: (HasCallStack, MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> Map (Some (AssignId ids)) (DependencySet (ArchReg arch) ids)
-> Value arch ids tp
-> DependencySet (ArchReg arch) ids
valueDeps _ _ (CValue _) = emptyDeps
valueDeps cns _ (Initial r) = domainDeps (locDomain cns (RegLoc r))
valueDeps _ m (AssignedValue (Assignment a _)) =
case Map.lookup (Some a) m of
Nothing -> error $ "Assignment " ++ show a ++ " is not defined."
Just r -> r
-- | Record the given dependencies are needed to execute this block.
addDeps :: (HasCallStack, OrdF (ArchReg arch))
=> DependencySet (ArchReg arch) ids
-> RegisterUseM arch ids ()
addDeps deps = blockExecDemands %= mappend deps
-- | Record the values needed to compute the given value.
demandValue :: (HasCallStack, MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> Value arch ids tp
-> RegisterUseM arch ids ()
demandValue v = do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
addDeps (valueDeps cns cache v)
-- | Mark the given register has no dependencies
clearDependencySet :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> ArchReg arch tp
-> BlockUsageSummary arch ids
-> BlockUsageSummary arch ids
clearDependencySet r s =
s & blockRegDependenciesLens %~ setRegDep r mempty
| @recordRegMap m@ record that the values in are
-- used to initial registers in the next block and the registers in
-- @l@ can be depended upon.
recordRegMap :: forall arch ids
. (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> MapF (ArchReg arch) (Value arch ids)
-- ^ Register and assigned values available when block terminates.
-> RegisterUseM arch ids ()
recordRegMap m = do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
blockRegDependenciesLens .= regDepsFromMap (valueDeps cns cache) m
-- | Set dependencies for an assignment whose right-hand-side must be
-- evaluated for side effects.
requiredAssignDeps :: OrdF (ArchReg arch)
=> AssignId ids tp
-> DependencySet (ArchReg arch) ids
-> RegisterUseM arch ids ()
requiredAssignDeps aid deps = do
addDeps deps
assignmentCache %= Map.insert (Some aid) mempty
popAccessInfo :: StmtIndex -> RegisterUseM arch ids (MemAccessInfo arch ids)
popAccessInfo n = do
s <- get
case pendingMemAccesses s of
[] -> error "popAccessInfo invalid"
((i,a):r) -> do
put $! s { pendingMemAccesses = r }
if i < n then
popAccessInfo n
else if i > n then
error "popAccessInfo missing index."
else
pure a
demandReadMem :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> StmtIndex
-> AssignId ids tp
-> Value arch ids (BVType (ArchAddrWidth arch))
-> MemRepr tp
-> RegisterUseM arch ids ()
demandReadMem stmtIdx aid addr _repr = do
accessInfo <- popAccessInfo stmtIdx
case accessInfo of
NotFrameAccess -> do
that this value depends on both aid and any
-- dependencies needed to compute the address.
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = assignSet aid <> valueDeps cns cache addr
requiredAssignDeps aid deps
FrameReadInitAccess _o d -> do
let deps = assignSet aid <> domainDeps d
assignmentCache %= Map.insert (Some aid) deps
FrameReadWriteAccess writeIdx -> do
that this value depends on aid and any
dependencies needed to compute the value stored at o.
m <- gets blockWriteDependencies
let deps = Map.findWithDefault (error "Could not find write index.") writeIdx m
let allDeps = addWriteDep writeIdx (assignSet aid <> deps)
assignmentCache %= Map.insert (Some aid) allDeps
FrameReadOverlapAccess _ -> do
assignmentCache %= Map.insert (Some aid) (assignSet aid)
FrameWriteAccess{} ->
error "Expected read access."
FrameCondWriteAccess{} ->
error "Expected read access."
FrameCondWriteOverlapAccess _ ->
error "Expected read access."
demandCondReadMem ::
(MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch)) =>
StmtIndex ->
AssignId ids tp ->
Value arch ids BoolType ->
Value arch ids (BVType (ArchAddrWidth arch)) ->
MemRepr tp ->
Value arch ids tp ->
RegisterUseM arch ids ()
demandCondReadMem stmtIdx aid cond addr _repr val = do
accessInfo <- popAccessInfo stmtIdx
case accessInfo of
NotFrameAccess -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = mconcat
[ assignSet aid
, valueDeps cns cache cond
, valueDeps cns cache addr
, valueDeps cns cache val
]
requiredAssignDeps aid deps
addDeps $ assignSet aid
FrameReadInitAccess _o d -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = mconcat
[ assignSet aid
, valueDeps cns cache cond
, domainDeps d
, valueDeps cns cache val
]
assignmentCache %= Map.insert (Some aid) deps
FrameReadWriteAccess writeIdx -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
that this value depends on aid and any dependencies
needed to compute the value stored at o.
m <- gets blockWriteDependencies
let deps = Map.findWithDefault (error "Could not find write index.") writeIdx m
let allDeps = addWriteDep writeIdx $
mconcat [ assignSet aid
, valueDeps cns cache cond
, deps
, valueDeps cns cache val
]
assignmentCache %= Map.insert (Some aid) allDeps
FrameReadOverlapAccess _ -> do
assignmentCache %= Map.insert (Some aid) (assignSet aid)
FrameWriteAccess{} ->
error "Expected read access."
FrameCondWriteAccess{} ->
error "Expected read access."
FrameCondWriteOverlapAccess{} ->
error "Expected read access."
inferStackValueDeps :: (HasCallStack, MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> Map (Some (AssignId ids)) (DependencySet (ArchReg arch) ids)
-> InferStackValue arch ids tp
-> DependencySet (ArchReg arch) ids
inferStackValueDeps cns amap isv =
case isv of
ISVInitValue d -> domainDeps d
ISVWrite idx v -> addWriteDep idx (valueDeps cns amap v)
ISVCondWrite idx c v prevVal -> addWriteDep idx $
mconcat [ valueDeps cns amap c
, valueDeps cns amap v
, inferStackValueDeps cns amap prevVal
]
demandAssign ::
( MemWidth (ArchAddrWidth arch),
OrdF (ArchReg arch),
FoldableFC (ArchFn arch)
) =>
StmtIndex ->
Assignment arch ids tp ->
RegisterUseM arch ids ()
demandAssign stmtIdx (Assignment aid arhs) = do
sis <- gets blockInferState
case MapF.lookup aid (sisAssignMap sis) of
Just (IVDomain d _) -> do
assignmentCache %= Map.insert (Some aid) (domainDeps d)
Just (IVAssignValue a) -> do
dm <- gets assignDeps
case Map.lookup (Some a) dm of
Nothing -> error $ "Assignment " ++ show a ++ " is not defined."
Just deps -> assignmentCache .= Map.insert (Some aid) deps dm
Just (IVCValue _) -> do
assignmentCache %= Map.insert (Some aid) emptyDeps
_ -> do
case arhs of
EvalApp app -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = foldlFC' (\s v -> mappend s (valueDeps cns cache v)) (assignSet aid) app
assignmentCache %= Map.insert (Some aid) deps
SetUndefined{} -> do
assignmentCache %= Map.insert (Some aid) (assignSet aid)
ReadMem addr repr -> do
demandReadMem stmtIdx aid addr repr
CondReadMem repr c addr val -> do
demandCondReadMem stmtIdx aid c addr repr val
EvalArchFn fn _ -> do
ctx <- asks demandContext
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = foldlFC' (\s v -> mappend s (valueDeps cns cache v)) (assignSet aid) fn
if archFnHasSideEffects ctx fn then do
requiredAssignDeps aid deps
else
assignmentCache %= Map.insert (Some aid) deps
-- | Return values that must be evaluated to execute side effects.
demandStmtValues ::
( HasCallStack,
OrdF (ArchReg arch),
MemWidth (ArchAddrWidth arch),
ShowF (ArchReg arch),
FoldableFC (ArchFn arch),
FoldableF (ArchStmt arch)
) =>
-- | Index of statement we are processing.
StmtIndex ->
-- | Statement we want to demand.
Stmt arch ids ->
RegisterUseM arch ids ()
demandStmtValues stmtIdx stmt = do
case stmt of
AssignStmt a -> demandAssign stmtIdx a
WriteMem addr _repr val -> do
accessInfo <- popAccessInfo stmtIdx
case accessInfo of
NotFrameAccess -> do
demandValue addr
demandValue val
FrameReadInitAccess{} -> error "Expected write access"
FrameReadWriteAccess{} -> error "Expected write access"
FrameReadOverlapAccess{} -> error "Expected write access"
FrameWriteAccess _o -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let valDeps = addWriteDep stmtIdx (valueDeps cns cache val)
blockWriteDependencyLens %= Map.insert stmtIdx valDeps
FrameCondWriteAccess{} -> error "Expected write access."
FrameCondWriteOverlapAccess{} -> error "Expected write access."
CondWriteMem c addr _repr val -> do
accessInfo <- popAccessInfo stmtIdx
case accessInfo of
NotFrameAccess -> do
demandValue c
demandValue addr
demandValue val
FrameReadInitAccess{} -> error "Expected conditional write access"
FrameReadWriteAccess{} -> error "Expected conditional write access"
FrameReadOverlapAccess{} -> error "Expected conditional write access"
FrameWriteAccess{} -> error "Expectedf1 conditional write access"
FrameCondWriteAccess _o _repr sv -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = addWriteDep stmtIdx
$ valueDeps cns cache c
<> inferStackValueDeps cns cache sv
<> valueDeps cns cache val
blockWriteDependencyLens %= Map.insert stmtIdx deps
FrameCondWriteOverlapAccess _ -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let valDeps =
addWriteDep stmtIdx $
valueDeps cns cache c <> valueDeps cns cache val
blockWriteDependencyLens %= Map.insert stmtIdx valDeps
InstructionStart off _ -> do
modify $ \s -> s { blockCurOff = off }
-- Comment statements have no specific value.
Comment _ ->
pure ()
ExecArchStmt astmt -> do
traverseF_ demandValue astmt
ArchState _addr _assn -> do
pure ()
-- | This function figures out what the block requires (i.e.,
-- addresses that are stored to, and the value stored), along with a
-- map of how demands by successor blocks map back to assignments and
-- registers.
--
-- It returns a summary along with start constraints inferred by
-- blocks that follow this one.
mkBlockUsageSummary :: forall arch ids
. ( RegisterInfo (ArchReg arch)
, FoldableF (ArchStmt arch)
, FoldableFC (ArchFn arch)
)
=> RegisterUseContext arch
-> BlockStartConstraints arch
-- ^ Inferred state at start of block
-> InferState arch ids
-- ^ Information inferred from executed block.
-> ParsedBlock arch ids
-- ^ Block
-> Except (RegisterUseError arch) (BlockUsageSummary arch ids)
mkBlockUsageSummary ctx cns sis blk = do
flip execStateT (initBlockUsageSummary cns sis) $ flip runReaderT ctx $ do
let addr = pblockAddr blk
-- Add demanded values for terminal
zipWithM_ demandStmtValues [0..] (pblockStmts blk)
let tidx = length (pblockStmts blk)
case pblockTermStmt blk of
ParsedJump regs _tgt -> do
recordRegMap (regStateMap regs)
ParsedBranch regs cond _t _f -> do
demandValue cond
recordRegMap (regStateMap regs)
ParsedLookupTable _layout regs idx _tgts -> do
demandValue idx
recordRegMap (regStateMap regs)
ParsedCall regs _mret -> do
callFn <- asks $ \x -> callDemandFn x
-- Get function type associated with function
off <- gets blockCurOff
let insnAddr =
let msg = "internal: Expected valid instruction address."
in fromMaybe (error msg) (incSegmentOff addr (toInteger off))
demandValue (regs^.boundValue ip_reg)
ftr <-
case callFn insnAddr regs of
Right v -> pure v
Left rsn -> do
throwError $
RegisterUseError
{ ruBlock = addr,
ruStmt = tidx,
ruReason = rsn
}
-- Demand argument registers
do
forM_ (callArgValues ftr) $ \(Some v) -> do
case v of
-- No dependencies
CValue _ -> do
pure ()
Initial r -> do
addDeps (domainDeps (locDomain cns (RegLoc r)))
AssignedValue (Assignment a _) -> do
cache <- gets assignDeps
case Map.lookup (Some a) cache of
Nothing -> error $ "Assignment " ++ show a ++ " is not defined."
Just r -> addDeps r
-- Store call register type information
modify $ \s -> s { blockCallFunType = Just (callRegsFnType ftr) }
-- Get other things
cache <- gets assignDeps
savedRegs <- asks calleeSavedRegisters
let insReg m (Some r) = setRegDep r (valueDeps cns cache (regs^.boundValue r)) m
blockRegDependenciesLens %= \m -> foldl' insReg m (Some sp_reg : savedRegs)
clearedRegs <- asks callScratchRegisters
let clearReg m (Some r) = setRegDep r mempty m
blockRegDependenciesLens %= \m -> foldl' clearReg m clearedRegs
blockRegDependenciesLens %= \m -> foldl' clearReg m (callReturnRegs ftr)
PLTStub regs _ _ -> do
traverseF_ demandValue regs
MapF.traverseWithKey_ (\r _ -> modify $ clearDependencySet r) regs
ParsedReturn regs -> do
retRegs <- asks $ returnRegisters
traverse_ (\(Some r) -> demandValue (regs^.boundValue r)) retRegs
ParsedArchTermStmt tstmt regs _mnext -> do
summaryFn <- asks $ \x -> reguseTermFn x
s <- get
case summaryFn tstmt regs s of
Left emsg -> throwError emsg
Right rDeps -> blockRegDependenciesLens .= rDeps
ParsedTranslateError _ ->
error "Cannot identify register use in code where translation error occurs"
ClassifyFailure _ _ ->
error $ "Classification failed: " ++ show addr
-- | Maps the starting address of a block with the given register type to the value.
type BlockAddrMap r v = Map (MemSegmentOff (RegAddrWidth r)) v
-- | A list of blocks starting addresses and their final location
-- dependency map.
type SrcDependencies r ids =
[(MemSegmentOff (RegAddrWidth r), LocDependencyMap r ids)]
-- | Maps each block start address to the complete list of blocks that may transition to that block
-- along with the @LocDependencyMap@ for that block.
--
-- This data structure is used to reduce lookups in back-propagation
-- of demands.
type PredProvideMap r ids =
Map (MemSegmentOff (RegAddrWidth r)) (SrcDependencies r ids)
type NewDemandMap r = BlockAddrMap r (Set (Some (BoundLoc r)))
-- | This takes a list of registers that a block demands that have not
-- been back-propogated, and infers new demands for predecessor
-- registers.
backPropagateOne :: forall r ids
. (MapF.OrdF r, MemWidth (RegAddrWidth r))
=> BlockAddrMap r (DependencySet r ids)
-- ^ State that we are computing fixpoint for.
-> NewDemandMap r
-- ^ Maps block addresses to the set of register demands we
-- have not yet back propagated.
-> Set (Some (BoundLoc r))
-- ^ Set of new locations the target block depends on
-- that we have not yet backpropagate demands to the
-- previous block for.
-> [( MemSegmentOff (RegAddrWidth r)
, LocDependencyMap r ids
)]
-- ^ Predecessors for the target block and the map from locations
-- they provide to the dependency set.
-> ( Map (MemSegmentOff (RegAddrWidth r)) (DependencySet r ids)
, NewDemandMap r
)
backPropagateOne s rest _ [] = (s, rest)
backPropagateOne s rest newLocs ((srcAddr,srcDepMap):predRest) = do
-- Get dependencies for all new locations that are demanded.
let allDeps :: DependencySet r ids
allDeps = mconcat [ getLocDependencySet srcDepMap l | Some l <- Set.toList newLocs ]
-- Add demands for srcAddr and get existing demands.
let (mseenRegs, s') =
Map.insertLookupWithKey (\_ x y -> x <> y) srcAddr allDeps s
-- Get the difference in demands so that we can propagate further.
let d = case mseenRegs of
Nothing -> dsLocSet allDeps
Just oldDems -> dsLocSet allDeps `Set.difference` dsLocSet oldDems
-- Update list of additional propagations.
let rest' | Set.null d = rest
| otherwise = Map.insertWith Set.union srcAddr d rest
seq s' $ seq rest' $ backPropagateOne s' rest' newLocs predRest
------------------------------------------------------------------------
BlockInvariants
newtype LocList r tp = LL { llValues :: [BoundLoc r tp] }
instance Semigroup (LocList r tp) where
LL x <> LL y = LL (x++y)
-- | This describes information about a block inferred by
-- register-use.
data BlockInvariants arch ids = BI
{ biUsedAssignSet :: !(Set (Some (AssignId ids)))
-- | Indices of write and cond-write statements that write to stack
-- and whose value is later needed to execute the program.
, biUsedWriteSet :: !(Set StmtIndex)
-- | In-order list of memory accesses in block.
, biMemAccessList :: ![(StmtIndex, MemAccessInfo arch ids)]
-- | Map from locations to the non-representative locations that are
-- equal to them.
, biLocMap :: !(MapF (BoundLoc (ArchReg arch)) (LocList (ArchReg arch)))
-- | Map predecessors for this block along with map from locations
-- to phi value
, biPredPostValues :: !(Map (ArchSegmentOff arch) (PostValueMap arch ids))
| Locations from previous block used to initial phi variables .
, biPhiLocs :: ![Some (BoundLoc (ArchReg arch))]
-- | Start constraints for block
, biStartConstraints :: !(BlockStartConstraints arch)
-- | If this block ends with a call, this has the type of the function called.
Otherwise , the value should be @Nothing@.
, biCallFunType :: !(Maybe (ArchFunType arch))
-- | Maps assignment identifiers to the associated value.
--
-- If an assignment id @aid@ is not in this map, then we assume it
-- is equal to @SAVEqualAssign aid@
, biAssignMap :: !(MapF (AssignId ids) (BlockInferValue arch ids))
}
-- | Return true if assignment is needed to execute block.
biAssignIdUsed :: AssignId ids tp -> BlockInvariants arch ids -> Bool
biAssignIdUsed aid inv = Set.member (Some aid) (biUsedAssignSet inv)
-- | Return true if index corresponds to a write of the current stack
-- frame.
biWriteUsed :: StmtIndex -> BlockInvariants arch ids -> Bool
biWriteUsed idx inv = Set.member idx (biUsedWriteSet inv)
-- | This transitively back propagates blocks across
backPropagate :: forall arch ids
. (OrdF (ArchReg arch), MemWidth (ArchAddrWidth arch))
=> PredProvideMap (ArchReg arch) ids
-- ^ Pred provide map computed during summarization.
-> Map (ArchSegmentOff arch) (DependencySet (ArchReg arch) ids)
-> Map (ArchSegmentOff arch) (Set (Some (BoundLoc (ArchReg arch))))
-- ^ Maps block addresses to the set of locations that
-- we still need to back propagate demands for.
-> Map (ArchSegmentOff arch) (DependencySet (ArchReg arch) ids)
backPropagate predMap depMap new =
case Map.maxViewWithKey new of
Nothing -> depMap
Just ((currAddr, newRegs), rest) ->
let predAddrs = Map.findWithDefault [] currAddr predMap
(s', rest') = backPropagateOne depMap rest newRegs predAddrs
in backPropagate predMap s' rest'
------------------------------------------------------------------------
-- registerUse
-- | Create map from locations to the non-representative locations
-- that are equal to them.
mkDepLocMap :: forall arch
. OrdF (ArchReg arch)
=> BlockStartConstraints arch
-> MapF (BoundLoc (ArchReg arch)) (LocList (ArchReg arch))
mkDepLocMap cns =
let addNonRep :: MapF (BoundLoc (ArchReg arch)) (LocList (ArchReg arch))
-> BoundLoc (ArchReg arch) tp
-> InitInferValue arch tp
-> MapF (BoundLoc (ArchReg arch)) (LocList (ArchReg arch))
addNonRep m l (RegEqualLoc r) = MapF.insertWith (<>) r (LL [l]) m
addNonRep m _ _ = m
in foldLocMap addNonRep MapF.empty (bscLocMap cns)
mkBlockInvariants :: forall arch ids
. (HasRepr (ArchReg arch) TypeRepr
, OrdF (ArchReg arch)
, ShowF (ArchReg arch)
, MemWidth (ArchAddrWidth arch)
)
=> FunPredMap (ArchAddrWidth arch)
-> (ArchSegmentOff arch
-> ArchSegmentOff arch
-> PostValueMap arch ids)
-- ^ Maps precessor and successor block addresses to the post value from the
-- jump from predecessor to successor.
-> ArchSegmentOff arch
-- ^ Address of thsi block.
-> BlockUsageSummary arch ids
-> DependencySet (ArchReg arch) ids
-- ^ Dependency set for block.
-> BlockInvariants arch ids
mkBlockInvariants predMap valueMap addr summary deps =
let cns = blockUsageStartConstraints summary
-- Get addresses of blocks that jump to this block
preds = Map.findWithDefault [] addr predMap
-- Maps address of predecessor to the post value for this block.
predFn predAddr = (predAddr, valueMap predAddr addr)
predphilist = predFn <$> preds
in BI { biUsedAssignSet = dsAssignSet deps
, biUsedWriteSet = dsWriteStmtIndexSet deps
, biMemAccessList = reverse (sisMemAccessStack (blockInferState summary))
, biLocMap = mkDepLocMap cns
, biPredPostValues = Map.fromList predphilist
, biPhiLocs = Set.toList (dsLocSet deps)
, biStartConstraints = cns
, biCallFunType = blockCallFunType summary
, biAssignMap = sisAssignMap (blockInferState summary)
}
-- | Map from block starting addresses to the invariants inferred for that block.
type BlockInvariantMap arch ids
= Map (ArchSegmentOff arch) (BlockInvariants arch ids)
-- | This analyzes a function to determine which registers must be available to
-- the highest index above sp0 that is read or written.
registerUse :: forall arch ids
. ArchConstraints arch
=> RegisterUseContext arch
-> DiscoveryFunInfo arch ids
-> Except (RegisterUseError arch)
(BlockInvariantMap arch ids)
registerUse rctx fun = do
let predMap = funBlockPreds fun
let blockMap = fun^.parsedBlocks
-- Infer start constraints
cnsMap <- inferStartConstraints rctx blockMap (discoveredFunAddr fun)
-- Infer demand summary for each block
usageMap <- traverse (\(b, cns,s,_) -> mkBlockUsageSummary rctx cns s b) cnsMap
-- Back propagate to compute demands
let bru :: BlockAddrMap (ArchReg arch) (DependencySet (ArchReg arch) ids)
bru = view blockExecDemands <$> usageMap
let providePair :: ArchSegmentOff arch -> (ArchSegmentOff arch, LocDependencyMap (ArchReg arch) ids)
providePair prev = (prev, lm)
where usage = case Map.lookup prev usageMap of
Nothing -> error "registerUse: Could not find prev"
Just usage' -> usage'
cns = blockUsageStartConstraints usage
cache = assignDeps usage
lm = LocMap { locMapRegs = rdmMap (blockRegDependencies usage)
, locMapStack =
fmapF (Const . inferStackValueDeps cns cache)
(sisStack (blockInferState usage))
}
let predProvideMap = fmap (fmap providePair) predMap
let propMap = backPropagate predProvideMap bru (dsLocSet <$> bru)
-- Generate final invariants
let phiValFn :: ArchSegmentOff arch -> ArchSegmentOff arch -> PostValueMap arch ids
phiValFn predAddr nextAddr =
case Map.lookup predAddr cnsMap of
Nothing -> error "Could not find predAddr"
Just (_,_,_,nextVals) -> Map.findWithDefault emptyPVM nextAddr nextVals
pure $ Map.intersectionWithKey (mkBlockInvariants predMap phiValFn) usageMap propMap
| null | https://raw.githubusercontent.com/GaloisInc/macaw/9d2e1d4b9f163c8947a284c2031000c54a3a9330/base/src/Data/Macaw/Analysis/RegisterUse.hs | haskell | # LANGUAGE OverloadedStrings #
# LANGUAGE RankNTypes #
* Exports for function recovery
** Input information
* Architecture specific summarization
** Inferred information.
*** Use information
-----------------------------------------------------------------------------
| A map from each starting block address @l@ to the addresses of
blocks that may jump to @l@.
| Return the FunPredMap for the discovered block function.
Get address of region
get the block successors
-----------------------------------------------------------------------------
RegisterUseError
| Errors from register use
Tag parameter used for addition information in tag
| Could not resolve height of call stack at given block
| The value read at given block and statement index could not
be resolved.
| We do not have support for stack reads.
| Call with indirect target
| Call target address was not a valid memory location.
| Call target was not a known function.
| Could not determine arguments to call.
| We could not resolve the arguments to a known var-args function.
| We do not yet support the calling convention needed for this function.
| Errors from register use
-----------------------------------------------------------------------------
InitInferValue
| Denotes the value must be the given offset of the stack frame.
| Denotes the value must be the value passed into the function at
the given register.
| Denotes a value is equal to the value stored at the
representative location when the block start.
Note. The location in this must a "representative" location.
Representative locations are those locations chosen to represent
equivalence classes of locations inferred equal by block inference.
----------------------------------------------------------------------
BlockStartConstraints
| This maps r registers and stack offsets at start of block to
inferred information about their value.
If a register or stack location does not appear here, it
is implicitly set to itself.
| Return domain for location in constraints
| Function for joining constraints on a specific location.
Used by @joinBlockStartConstraints@ below.
^ New constraints being added to existing one.
^ Map from locations to values that will be used in resulr.
^ Cache that maps (old,new) constraints to
a location that satisfied those
constraints in old and new constraint set
respectively.
^ Old domain for location.
This is a new class representative.
New class representives imply that there was a change as
the location in the old domain must not have been a free
class rep.
implies constraints in @old@, and otherwise a set of constraints
Reference to new constraints
Cache for recording when we have seen class representatives
| @unionBlockStartConstraints x y@ returns a set of constraints @r@
-----------------------------------------------------------------------------
| This is used to to control which parts of a value we need to read.
^ Offset of read relative to write.
^ Write repr
^ Read repr
----------------------------------------------------------------------
| This is an expression that represents a more canonical representation
`InitInferValue` captures constraints important to capture between blocks
inferrences within a block.
| Value register use domain
| The value of an assignment.
| A constant
| Denotes the value written by a conditional write at the given
index if the condition is true, or the value currently stored in
memory if the condition is false.
| Pattern for stack offset expressions
value under the assumptions about the start of the block, and the
assumption that non-stack writes do not affect the curent stack
frame.
the same value under the assumptions about the start of the block,
and the assumption that non-stack writes do not affect the current
stack frame.
| Information about a stack location used in invariant inference.
| The stack location had this value in the initial stack.
in the current block at the given index, and the value written
had the given inferred value.
the stack by a @CondWriteMem@ instruction in the current block
and existing stack value @pv@.
the value overwritten.
----------------------------------------------------------------------
StartInfer
| Read-only information needed to infer successor start
^ Address of block we are inferring state for.
^ Map rep register to rheir initial domain information.
| Evaluate a value in the context of the start infer state and
initial register assignment.
^ Initial value of registers
^ Map from assignments to value.
^ Value to convert.
| Evaluate a value in the context of the start infer state and
initial register assignment.
^ Initial value of registers
^ Map from assignments to value.
^ Initial value of registers
^ Map from assignments to value.
| Information about a memory access within a block
| The access was not inferred to affect the current frame
| The access read a frame offset that has not been written to
by the current block. The inferred value describes the value read.
| The access read a frame offset that has been written to by a
previous write or cond-write in this block, and the
instruction had the given index.
| The access was a memory read that overlapped, but did not
exactly match a previous write.
| The access was a write to the current frame.
| The access was a conditional write to the current frame at the
given offset. The current
| The access was a conditional write to the current frame at the
given offset, and the default value would overlap with a previous
write.
| State tracked to infer block preconditions.
| Current stack map.
implicitly is associated with
@ISVInitValue (RegEqualLoc (StackOffLoc o repr))@.
| Maps assignment identifiers to the associated value.
If an assignment id @aid@ is not in this map, then we assume it
is equal to @SAVEqualAssign aid@
| Maps apps to the assignment identifier that created it.
instruction in block.
| Information about memory accesses in reverse order of statement.
There should be one for each statement that is a @ReadMem@,
@CondReadMem@, @WriteMem@ and @CondWriteMem@.
| Current state of stack.
| Maps assignment identifiers to the associated value.
If an assignment id is not in this map, then we assume it could not
be interpreted by the analysis.
| Maps apps to the assignment identifier that created it.
| Maps apps to the assignment identifier that created it.
| Monad used for inferring start constraints.
Note. The process of inferring start constraints intentionally does
not do stack escape analysis or other
| Set the value associated with an assignment
| Record the mem access information
Check to see if we have seen an app equivalent to
this one under the invariant assumption.
If we have not, then record it in the cache for
later.
If we have seen this app, then we set it equal to previous.
| @checkReadWithinWrite writeOff writeType readOff readType@ checks that
the read is contained within the write and returns a mem slice if so.
^ Write offset
^ Write repr
^ Read offset
^ Read repr
| Infer constraints from a memory read
Overlap reads just get recorded
Reads within writes get propagated.
Uninitialized reads are equal to what came before.
Non-stack reads are just equal to themselves.
| Infer constraints from a memory read.
Unlike inferReadMem these are not assigned a value, but we still
track which write was associated if possible.
Non-stack reads are just equal to themselves.
| Update start infer statement to reflect statement.
Assignment equal to itself.
Architecture-specific functions are just equal to themselves.
Get value of val under current equality constraints.
Do nothing for things that are not stack expressions.
up in this case, then @sisStack@ will not be properly
updated to reflect real contents, and the value refered
to be subsequent @readMem@ operations may be incorrect.
This is currently unavoidable to fix in this code, and
perhaps can never be fully addressed as we'd basically need
a proof that that the stack could not be overwritten.
However, this will be caught by verification of the
Do nothing with instruction start/comment/register update
For now we assume architecture statement does not modify any
of the locations.
| Maps locations to the values to initialize next locations with.
| Monad for inferring next state.
use for that location in the next block start constraints or
@Nothing@ if the value is unconstrained.
| Process terminal registers
^ Map of previously explored constraints
^ Address to jump to
^ Start constraints at address.
^ New frontier
| Get post value map an dnext constraints for an intra-procedural jump to target.
^ Values assigned to registers at end of blocks.
Unassigned registers are considered to be assigned
arbitrary values. This is used for modeling calls
where only some registers are preserved.
| Post call constraints for return address.
^ Architecture-specific call parameters
^ Context for block invariants inference.
^ State for start inference
^ Index of term statement
^ Registers at time of call.
Upper bound is stack offset before call.
Lower bound is stack bound after call.
Function to update register state.
Drop the return address pointer
Otherwise preserve the value.
-----------------------------------------------------------------------------
DependencySet
| This records what assignments and initial value locations are
needed to compute a value or execute code in a block with side
effects.
^ Set of locations that block reads the initial
value of.
^ Set of assignments that must be executed.
^ Block start address and index of write statement that
writes a value to the stack that is read later.
| Empty dependency set.
| Dependency set for a single assignment
| Create a dependency set for a single location.
| @addWriteDep stmtIdx
----------------------------------------------------------------------
RegDependencyMap
| Map from register to the dependencies for that register.
| Set dependency for register
| Create dependencies from map
----------------------------------------------------------------------
BlockUsageSummary
| This contains information about a specific block needed to infer
which locations and assignments are needed to execute the block
along with information about the demands to compute the value of
particular locations after the block executes.
| Offset of start of last instruction processed relative to start of block.
| Inferred state computed at beginning
| Dependencies needed to execute statements with side effects.
| Map registers to the dependencies of the values they store.
Defined in block terminator.
| Map indexes of writes and cond write instructions to their dependency set.
| Maps assignments to their dependencies.
| Information about next memory reads.
| If this block ends with a call, this has the type of the function called.
| Dependencies needed to execute statements with side effects.
| Maps registers to the dependencies needed to compute that
register value.
| Maps stack offsets to the dependencies needed to compute the
value stored at that offset.
----------------------------------------------------------------------
| Identifies demand information about a particular call.
----------------------------------------------------------------------
RegisterUseContext
| Architecture specific information about the type of function
called by inferring call-site information.
Used to memoize analysis returned by @callDemandFn@.
| Set of registers preserved by a call.
| Given a terminal statement and list of registers it returns
Map containing values afterwards.
| Registers that are saved by calls (excludes rsp)
| List of registers that callers may freely change.
^ The list of registers that are preserved by a function
call.
handled differently.
| Return registers demanded by this function
| Callback function for summarizing register usage of terminal
statements.
| Given the address of a call instruction and registers, this returns the
values read and returned.
| Information needed to demands of architecture-specific functions.
| Add frontier for an intra-procedural jump that preserves register
and stack.
^ Values assigned to registers at end of blocks.
Unassigned registers are considered to be assigned
arbitrary values. This is used for modeling calls
where only some registers are preserved.
^ Address to jump to
| Analyze block to update start constraints on successors and add blocks
with changed constraints to frontier.
^ Map from starting addresses to blocks.
^ Address of start of block.
^ Results from last explore map
^ Maps addresses of blocks to explore to the
starting constraints.
Get statements in block
Get state from processing all statements
Tail call
Works like a tail call.
calling convention.
| Infer start constraints by recursively evaluating blocks
^ Map from starting addresses to blocks.
^ Map starting address of blocks to information
about block from last exploration.
^ Maps addresses of blocks to explore to
the starting constraints.
| Infer start constraints by recursively evaluating blocks
^ Map from starting addresses to blocks.
^ Map starting address of blocks to information
about block from last exploration.
| Pretty print start constraints for debugging purposes.
----------------------------------------------------------------------
| This maps each location that could be accessed after a block
terminates to the set of values needed to compute the value of the
location.
| Get dependency set for location.
Note. This code is currently buggy in that it will back propagate
stack reads that are partially overwritten.
----------------------------------------------------------------------
----------------------------------------------------------------------------------------
Phase one functions
----------------------------------------------------------------------------------------
| Return the register and assignment dependencies needed to
| Record the given dependencies are needed to execute this block.
| Record the values needed to compute the given value.
| Mark the given register has no dependencies
used to initial registers in the next block and the registers in
@l@ can be depended upon.
^ Register and assigned values available when block terminates.
| Set dependencies for an assignment whose right-hand-side must be
evaluated for side effects.
dependencies needed to compute the address.
| Return values that must be evaluated to execute side effects.
| Index of statement we are processing.
| Statement we want to demand.
Comment statements have no specific value.
| This function figures out what the block requires (i.e.,
addresses that are stored to, and the value stored), along with a
map of how demands by successor blocks map back to assignments and
registers.
It returns a summary along with start constraints inferred by
blocks that follow this one.
^ Inferred state at start of block
^ Information inferred from executed block.
^ Block
Add demanded values for terminal
Get function type associated with function
Demand argument registers
No dependencies
Store call register type information
Get other things
| Maps the starting address of a block with the given register type to the value.
| A list of blocks starting addresses and their final location
dependency map.
| Maps each block start address to the complete list of blocks that may transition to that block
along with the @LocDependencyMap@ for that block.
This data structure is used to reduce lookups in back-propagation
of demands.
| This takes a list of registers that a block demands that have not
been back-propogated, and infers new demands for predecessor
registers.
^ State that we are computing fixpoint for.
^ Maps block addresses to the set of register demands we
have not yet back propagated.
^ Set of new locations the target block depends on
that we have not yet backpropagate demands to the
previous block for.
^ Predecessors for the target block and the map from locations
they provide to the dependency set.
Get dependencies for all new locations that are demanded.
Add demands for srcAddr and get existing demands.
Get the difference in demands so that we can propagate further.
Update list of additional propagations.
----------------------------------------------------------------------
| This describes information about a block inferred by
register-use.
| Indices of write and cond-write statements that write to stack
and whose value is later needed to execute the program.
| In-order list of memory accesses in block.
| Map from locations to the non-representative locations that are
equal to them.
| Map predecessors for this block along with map from locations
to phi value
| Start constraints for block
| If this block ends with a call, this has the type of the function called.
| Maps assignment identifiers to the associated value.
If an assignment id @aid@ is not in this map, then we assume it
is equal to @SAVEqualAssign aid@
| Return true if assignment is needed to execute block.
| Return true if index corresponds to a write of the current stack
frame.
| This transitively back propagates blocks across
^ Pred provide map computed during summarization.
^ Maps block addresses to the set of locations that
we still need to back propagate demands for.
----------------------------------------------------------------------
registerUse
| Create map from locations to the non-representative locations
that are equal to them.
^ Maps precessor and successor block addresses to the post value from the
jump from predecessor to successor.
^ Address of thsi block.
^ Dependency set for block.
Get addresses of blocks that jump to this block
Maps address of predecessor to the post value for this block.
| Map from block starting addresses to the invariants inferred for that block.
| This analyzes a function to determine which registers must be available to
the highest index above sp0 that is read or written.
Infer start constraints
Infer demand summary for each block
Back propagate to compute demands
Generate final invariants | | This analyzes a function to compute information about what
information must be available for the code to execute . It is a key analysis
task needed before deleting unused code .
information must be available for the code to execute. It is a key analysis
task needed before deleting unused code.
-}
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
# LANGUAGE KindSignatures #
# LANGUAGE PatternSynonyms #
# LANGUAGE PolyKinds #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TemplateHaskell #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
module Data.Macaw.Analysis.RegisterUse
registerUse
, BlockInvariantMap
, RegisterUseError(..)
, RegisterUseErrorReason(..)
, ppRegisterUseErrorReason
, RegisterUseErrorTag(..)
, RegisterUseContext(..)
, ArchFunType
, CallRegs(..)
, PostTermStmtInvariants
, PostValueMap
, pvmFind
, MemSlice(..)
, ArchTermStmtUsageFn
, RegisterUseM
, BlockStartConstraints(..)
, locDomain
, postCallConstraints
, BlockUsageSummary(..)
, RegDependencyMap
, setRegDep
, StartInferContext
, InferState
, BlockInferValue(..)
, valueDeps
* * * FunPredMap
, FunPredMap
, funBlockPreds
, BlockInvariants
, biStartConstraints
, biMemAccessList
, biPhiLocs
, biPredPostValues
, biLocMap
, biCallFunType
, biAssignMap
, LocList(..)
, StackAnalysis.LocMap(..)
, StackAnalysis.locMapToList
, StackAnalysis.BoundLoc(..)
, MemAccessInfo(..)
, InitInferValue(..)
* * * info
, StmtIndex
, biAssignIdUsed
, biWriteUsed
) where
import Control.Lens
import Control.Monad.Except
import Control.Monad.Reader
import Control.Monad.State.Strict
import qualified Data.ByteString.Char8 as BSC
import qualified Data.ByteString as BS
import Data.Foldable
import Data.Kind
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Maybe
import Data.Parameterized
import Data.Parameterized.Map (MapF)
import qualified Data.Parameterized.Map as MapF
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Word (Word64)
import GHC.Stack
import Prettyprinter
import Text.Printf (printf)
import Data.Macaw.AbsDomain.StackAnalysis as StackAnalysis
import Data.Macaw.CFG
import Data.Macaw.CFG.DemandSet
( DemandContext
, archFnHasSideEffects
)
import Data.Macaw.Discovery.State
import qualified Data.Macaw.Types as M
import Data.Macaw.Types hiding (Type)
import Data.Macaw.Utils.Changed
import Data.Macaw.AbsDomain.CallParams
import Data.STRef
import Data.Parameterized.TH.GADT
funBlockPreds
type FunPredMap w = Map (MemSegmentOff w) [MemSegmentOff w]
funBlockPreds :: DiscoveryFunInfo arch ids -> FunPredMap (ArchAddrWidth arch)
funBlockPreds info = Map.fromListWith (++)
[ (next, [addr])
| b <- Map.elems (info^.parsedBlocks)
, let addr = pblockAddr b
, next <- parsedTermSucc (pblockTermStmt b)
]
data RegisterUseErrorTag e where
CallStackHeightError :: RegisterUseErrorTag ()
UnresolvedStackRead :: RegisterUseErrorTag ()
UnsupportedCondStackRead :: RegisterUseErrorTag ()
IndirectCallTarget :: RegisterUseErrorTag ()
InvalidCallTargetAddress :: RegisterUseErrorTag Word64
CallTargetNotFunctionEntryPoint :: RegisterUseErrorTag Word64
UnknownCallTargetArguments :: RegisterUseErrorTag BS.ByteString
ResolutonFailureCallToKnownVarArgsFunction :: RegisterUseErrorTag String
UnsupportedCallTargetCallingConvention :: RegisterUseErrorTag BS.ByteString
instance Show (RegisterUseErrorTag e) where
show CallStackHeightError = "Symbolic call stack height"
show UnresolvedStackRead = "Unresolved stack read"
show UnsupportedCondStackRead = "Conditional stack read"
show IndirectCallTarget = "Indirect call target"
show InvalidCallTargetAddress = "Invalid call target address"
show CallTargetNotFunctionEntryPoint = "Call target not function entry point"
show UnknownCallTargetArguments = "Unresolved call target arguments"
show ResolutonFailureCallToKnownVarArgsFunction = "Could not resolve varargs args"
show UnsupportedCallTargetCallingConvention = "Unsupported calling convention"
$(pure [])
instance TestEquality RegisterUseErrorTag where
testEquality = $(structuralTypeEquality [t|RegisterUseErrorTag|] [])
instance OrdF RegisterUseErrorTag where
compareF = $(structuralTypeOrd [t|RegisterUseErrorTag|] [])
data RegisterUseErrorReason = forall e . Reason !(RegisterUseErrorTag e) !e
data RegisterUseError arch
= RegisterUseError {
ruBlock :: !(ArchSegmentOff arch),
ruStmt :: !StmtIndex,
ruReason :: !RegisterUseErrorReason
}
ppRegisterUseErrorReason :: RegisterUseErrorReason -> String
ppRegisterUseErrorReason (Reason tag v) =
case tag of
CallStackHeightError -> "Could not resolve concrete stack height."
UnresolvedStackRead -> "Unresolved stack read."
UnsupportedCondStackRead -> "Unsupported conditional stack read."
IndirectCallTarget -> "Indirect call target."
InvalidCallTargetAddress -> "Invalid call target address."
CallTargetNotFunctionEntryPoint -> "Call target not function entry point."
UnknownCallTargetArguments -> printf "Unknown arguments to %s." (BSC.unpack v)
ResolutonFailureCallToKnownVarArgsFunction -> "Could not resolve varargs args."
UnsupportedCallTargetCallingConvention -> "Unsupported calling convention."
| This denotes specific value equalities that
associates with values .
data InitInferValue arch tp where
InferredStackOffset :: !(MemInt (ArchAddrWidth arch))
-> InitInferValue arch (BVType (ArchAddrWidth arch))
FnStartRegister :: !(ArchReg arch tp)
-> InitInferValue arch tp
RegEqualLoc :: !(BoundLoc (ArchReg arch) tp)
-> InitInferValue arch tp
instance ShowF (ArchReg arch) => Show (InitInferValue arch tp) where
showsPrec _ (InferredStackOffset o) =
showString "(stack_offset " . shows o . showString ")"
showsPrec _ (FnStartRegister r) =
showString "(saved_reg " . showsF r . showString ")"
showsPrec _ (RegEqualLoc l) =
showString "(block_loc " . shows (pretty l) . showString ")"
instance ShowF (ArchReg arch) => ShowF (InitInferValue arch)
instance TestEquality (ArchReg arch) => TestEquality (InitInferValue arch) where
testEquality (InferredStackOffset x) (InferredStackOffset y) =
if x == y then Just Refl else Nothing
testEquality (FnStartRegister x) (FnStartRegister y) =
testEquality x y
testEquality (RegEqualLoc x) (RegEqualLoc y) =
testEquality x y
testEquality _ _ = Nothing
instance OrdF (ArchReg arch) => OrdF (InitInferValue arch) where
compareF (InferredStackOffset x) (InferredStackOffset y) =
fromOrdering (compare x y)
compareF (InferredStackOffset _) _ = LTF
compareF _ (InferredStackOffset _) = GTF
compareF (FnStartRegister x) (FnStartRegister y) = compareF x y
compareF (FnStartRegister _) _ = LTF
compareF _ (FnStartRegister _) = GTF
compareF (RegEqualLoc x) (RegEqualLoc y) = compareF x y
newtype BlockStartConstraints arch =
BSC { bscLocMap :: LocMap (ArchReg arch) (InitInferValue arch) }
data TypedPair (key :: k -> Type) (tp :: k) = TypedPair !(key tp) !(key tp)
instance TestEquality k => TestEquality (TypedPair k) where
testEquality (TypedPair x1 x2) (TypedPair y1 y2) = do
Refl <- testEquality x1 y1
testEquality x2 y2
instance OrdF k => OrdF (TypedPair k) where
compareF (TypedPair x1 x2) (TypedPair y1 y2) =
joinOrderingF (compareF x1 y1) (compareF x2 y2)
locDomain :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> BoundLoc (ArchReg arch) tp
-> InitInferValue arch tp
locDomain cns l = fromMaybe (RegEqualLoc l) (locLookup l (bscLocMap cns))
joinInitInferValue :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> STRef s (LocMap (ArchReg arch) (InitInferValue arch))
-> STRef s (MapF (TypedPair (InitInferValue arch)) (BoundLoc (ArchReg arch)))
-> BoundLoc (ArchReg arch) tp
-> InitInferValue arch tp
-> Changed s ()
joinInitInferValue newCns cnsRef cacheRef l oldDomain = do
case (oldDomain, locDomain newCns l) of
(InferredStackOffset i, InferredStackOffset j)
| i == j ->
changedST $ modifySTRef cnsRef $ nonOverlapLocInsert l oldDomain
(FnStartRegister rx, FnStartRegister ry)
| Just Refl <- testEquality rx ry ->
changedST $ modifySTRef cnsRef $ nonOverlapLocInsert l oldDomain
(_, newDomain) -> do
c <- changedST $ readSTRef cacheRef
let p = TypedPair oldDomain newDomain
case MapF.lookup p c of
Nothing -> do
markChanged True
changedST $ modifySTRef cacheRef $ MapF.insert p l
Just prevRep -> do
changed if the old domain was not just a pointer to prevRep .
case testEquality oldDomain (RegEqualLoc prevRep) of
Just _ -> pure ()
Nothing -> markChanged True
changedST $ modifySTRef cnsRef $ nonOverlapLocInsert l (RegEqualLoc prevRep)
| @joinBlockStartConstraints old new@ returns @Nothing@ if @new@
@c@ that implies both @new@ and @old@.
joinBlockStartConstraints :: forall s arch
. (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> BlockStartConstraints arch
-> Changed s (BlockStartConstraints arch)
joinBlockStartConstraints (BSC oldCns) newCns = do
cnsRef <- changedST $ newSTRef locMapEmpty
cacheRef <- changedST $ newSTRef MapF.empty
let regFn :: ArchReg arch tp
-> InitInferValue arch tp
-> Changed s ()
regFn r d = joinInitInferValue newCns cnsRef cacheRef (RegLoc r) d
MapF.traverseWithKey_ regFn (locMapRegs oldCns)
let stackFn :: MemInt (ArchAddrWidth arch)
-> MemRepr tp
-> InitInferValue arch tp
-> Changed s ()
stackFn o r d =
joinInitInferValue newCns cnsRef cacheRef (StackOffLoc o r) d
memMapTraverseWithKey_ stackFn (locMapStack oldCns)
changedST $ BSC <$> readSTRef cnsRef
that entails both @x@ and @y@.
unionBlockStartConstraints :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> BlockStartConstraints arch
-> BlockStartConstraints arch
unionBlockStartConstraints n o =
fromMaybe o (runChanged (joinBlockStartConstraints o n))
StmtIndex
| Index of a stmt in a block .
type StmtIndex = Int
data MemSlice wtp rtp where
NoMemSlice :: MemSlice tp tp
| @MemSlize o w r@ indicates that we read a value of type @r@ @o@ bytes into the write of type @w@.
-> MemSlice wtp rtp
deriving instance Show (MemSlice w r)
instance TestEquality (MemSlice wtp) where
testEquality NoMemSlice NoMemSlice = Just Refl
testEquality (MemSlice xo xw xr) (MemSlice yo yw yr)
| xo == yo, Just Refl <- testEquality xw yw = testEquality xr yr
testEquality _ _ = Nothing
joinOrdering :: Ordering -> OrderingF a b -> OrderingF a b
joinOrdering LT _ = LTF
joinOrdering EQ o = o
joinOrdering GT _ = GTF
instance OrdF (MemSlice wtp) where
compareF NoMemSlice NoMemSlice = EQF
compareF NoMemSlice MemSlice{} = LTF
compareF MemSlice{} NoMemSlice = GTF
compareF (MemSlice xo xw xr) (MemSlice yo yw yr) =
joinOrdering (compare xo yo) $
joinOrderingF (compareF xw yw) $
compareF xr yr
BlockInferValue
of a value inferred by the invariant inference routine .
This difference between ` InitInferValue ` and ` BlockInferValue ` is that
while ` BlockInferValue ` has a richer constraint language capturing
data BlockInferValue arch ids tp where
IVDomain :: !(InitInferValue arch wtp)
-> !(MemSlice wtp rtp)
-> BlockInferValue arch ids rtp
IVAssignValue :: !(AssignId ids tp)
-> BlockInferValue arch ids tp
IVCValue :: !(CValue arch tp) -> BlockInferValue arch ids tp
The MemRepr is the type of the write , and used for comparison .
IVCondWrite :: !StmtIndex -> !(MemRepr tp) -> BlockInferValue arch ids tp
deriving instance ShowF (ArchReg arch) => Show (BlockInferValue arch ids tp)
instance ShowF (ArchReg arch) => ShowF (BlockInferValue arch ids)
pattern FrameExpr :: ()
=> (tp ~ BVType (ArchAddrWidth arch))
=> MemInt (ArchAddrWidth arch)
-> BlockInferValue arch ids tp
pattern FrameExpr o = IVDomain (InferredStackOffset o) NoMemSlice
This returns @Just Refl@ if the two expressions denote the same
instance TestEquality (ArchReg arch) => TestEquality (BlockInferValue arch ids) where
testEquality (IVDomain x xs) (IVDomain y ys) = do
Refl <- testEquality x y
testEquality xs ys
testEquality (IVAssignValue x) (IVAssignValue y) = testEquality x y
testEquality (IVCValue x) (IVCValue y) = testEquality x y
testEquality (IVCondWrite x xtp) (IVCondWrite y ytp) =
case x == y of
True ->
case testEquality xtp ytp of
Just Refl -> Just Refl
Nothing -> error "Equal conditional writes with inequal types."
False -> Nothing
testEquality _ _ = Nothing
Note . The @OrdF@ instance is a total order over @BlockInferValue@.
If it returns @EqF@ then it guarantees the two expressions denote
instance OrdF (ArchReg arch) => OrdF (BlockInferValue arch ids) where
compareF (IVDomain x xs) (IVDomain y ys) =
joinOrderingF (compareF x y) (compareF xs ys)
compareF IVDomain{} _ = LTF
compareF _ IVDomain{} = GTF
compareF (IVAssignValue x) (IVAssignValue y) = compareF x y
compareF IVAssignValue{} _ = LTF
compareF _ IVAssignValue{} = GTF
compareF (IVCValue x) (IVCValue y) = compareF x y
compareF IVCValue{} _ = LTF
compareF _ IVCValue{} = GTF
compareF (IVCondWrite x xtp) (IVCondWrite y ytp) =
case compare x y of
LT -> LTF
EQ ->
case testEquality xtp ytp of
Just Refl -> EQF
Nothing -> error "Equal conditional writes with inequal types."
GT -> GTF
data InferStackValue arch ids tp where
ISVInitValue :: !(InitInferValue arch tp)
-> InferStackValue arch ids tp
| The value was written to the stack by a @WriteMem@ instruction
ISVWrite :: !StmtIndex
-> !(Value arch ids tp)
-> InferStackValue arch ids tp
| denotes the value written to
with the given instruction index @idx@ , condition @c@ , value @v@
The arguments are the index , the Boolean , the value written , and
ISVCondWrite :: !StmtIndex
-> !(Value arch ids BoolType)
-> !(Value arch ids tp)
-> !(InferStackValue arch ids tp)
-> InferStackValue arch ids tp
constraints for a lbok .
data StartInferContext arch =
SIC { sicAddr :: !(MemSegmentOff (ArchAddrWidth arch))
, sicRegs :: !(MapF (ArchReg arch) (InitInferValue arch))
}
deriving instance (ShowF (ArchReg arch), MemWidth (ArchAddrWidth arch))
=> Show (StartInferContext arch)
valueToStartExpr' :: OrdF (ArchReg arch)
=> StartInferContext arch
-> MapF (AssignId ids) (BlockInferValue arch ids)
-> Value arch ids wtp
-> MemSlice wtp rtp
-> Maybe (BlockInferValue arch ids rtp)
valueToStartExpr' _ _ (CValue c) NoMemSlice = Just (IVCValue c)
valueToStartExpr' _ _ (CValue _) MemSlice{} = Nothing
valueToStartExpr' _ am (AssignedValue (Assignment aid _)) NoMemSlice = Just $
MapF.findWithDefault (IVAssignValue aid) aid am
valueToStartExpr' _ _ (AssignedValue (Assignment _ _)) MemSlice{} = Nothing
valueToStartExpr' ctx _ (Initial r) ms = Just $
IVDomain (MapF.findWithDefault (RegEqualLoc (RegLoc r)) r (sicRegs ctx)) ms
valueToStartExpr :: OrdF (ArchReg arch)
=> StartInferContext arch
-> MapF (AssignId ids) (BlockInferValue arch ids)
-> Value arch ids tp
-> BlockInferValue arch ids tp
valueToStartExpr _ _ (CValue c) = IVCValue c
valueToStartExpr _ am (AssignedValue (Assignment aid _)) =
MapF.findWithDefault (IVAssignValue aid) aid am
valueToStartExpr ctx _ (Initial r) =
IVDomain (MapF.findWithDefault (RegEqualLoc (RegLoc r)) r (sicRegs ctx))
NoMemSlice
inferStackValueToValue :: OrdF (ArchReg arch)
=> StartInferContext arch
-> MapF (AssignId ids) (BlockInferValue arch ids)
-> InferStackValue arch ids tp
-> MemRepr tp
-> BlockInferValue arch ids tp
inferStackValueToValue _ _ (ISVInitValue d) _ = IVDomain d NoMemSlice
inferStackValueToValue ctx m (ISVWrite _idx v) _ = valueToStartExpr ctx m v
inferStackValueToValue _ _ (ISVCondWrite idx _ _ _) repr = IVCondWrite idx repr
data MemAccessInfo arch ids
NotFrameAccess
| forall tp
. FrameReadInitAccess !(MemInt (ArchAddrWidth arch)) !(InitInferValue arch tp)
| FrameReadWriteAccess !StmtIndex
| FrameReadOverlapAccess
!(MemInt (ArchAddrWidth arch))
| FrameWriteAccess !(MemInt (ArchAddrWidth arch))
| forall tp
. FrameCondWriteAccess !(MemInt (ArchAddrWidth arch))
!(MemRepr tp)
!(InferStackValue arch ids tp)
| FrameCondWriteOverlapAccess !(MemInt (ArchAddrWidth arch))
data InferState arch ids =
Note . An uninitialized region at offset @o@ and type @repr@
sisStack :: !(MemMap (MemInt (ArchAddrWidth arch)) (InferStackValue arch ids))
, sisAssignMap :: !(MapF (AssignId ids) (BlockInferValue arch ids))
, sisAppCache :: !(MapF (App (BlockInferValue arch ids)) (AssignId ids))
| Offset of current instruction relative to first
, sisCurrentInstructionOffset :: !(ArchAddrWord arch)
, sisMemAccessStack :: ![(StmtIndex, MemAccessInfo arch ids)]
}
sisStackLens :: Lens' (InferState arch ids)
(MemMap (MemInt (ArchAddrWidth arch)) (InferStackValue arch ids))
sisStackLens = lens sisStack (\s v -> s { sisStack = v })
sisAssignMapLens :: Lens' (InferState arch ids)
(MapF (AssignId ids) (BlockInferValue arch ids))
sisAssignMapLens = lens sisAssignMap (\s v -> s { sisAssignMap = v })
sisAppCacheLens :: Lens' (InferState arch ids)
(MapF (App (BlockInferValue arch ids)) (AssignId ids))
sisAppCacheLens = lens sisAppCache (\s v -> s { sisAppCache = v })
sisCurrentInstructionOffsetLens :: Lens' (InferState arch ids) (ArchAddrWord arch)
sisCurrentInstructionOffsetLens =
lens sisCurrentInstructionOffset (\s v -> s { sisCurrentInstructionOffset = v })
type StartInfer arch ids =
ReaderT (StartInferContext arch) (StateT (InferState arch ids) (Except (RegisterUseError arch)))
setAssignVal :: AssignId ids tp
-> BlockInferValue arch ids tp
-> StartInfer arch ids ()
setAssignVal aid v = sisAssignMapLens %= MapF.insert aid v
addMemAccessInfo :: StmtIndex -> MemAccessInfo arch ids -> StartInfer arch ids ()
addMemAccessInfo idx i = seq idx $ seq i $ do
modify $ \s -> s { sisMemAccessStack = (idx,i) : sisMemAccessStack s }
processApp :: (OrdF (ArchReg arch), MemWidth (ArchAddrWidth arch))
=> AssignId ids tp
-> App (Value arch ids) tp
-> StartInfer arch ids ()
processApp aid app = do
ctx <- ask
am <- gets sisAssignMap
case fmapFC (valueToStartExpr ctx am) app of
BVAdd _ (FrameExpr o) (IVCValue (BVCValue _ c)) ->
setAssignVal aid (FrameExpr (o+fromInteger c))
BVAdd _ (IVCValue (BVCValue _ c)) (FrameExpr o) ->
setAssignVal aid (FrameExpr (o+fromInteger c))
BVSub _ (FrameExpr o) (IVCValue (BVCValue _ c)) ->
setAssignVal aid (FrameExpr (o-fromInteger c))
appExpr -> do
c <- gets sisAppCache
case MapF.lookup appExpr c of
Nothing -> do
sisAppCacheLens %= MapF.insert appExpr aid
Just prevId -> do
setAssignVal aid (IVAssignValue prevId)
checkReadWithinWrite :: MemWidth w
-> Maybe (MemSlice wtp rtp)
checkReadWithinWrite wo wr ro rr
| wo == ro, Just Refl <- testEquality wr rr =
Just NoMemSlice
| wo <= ro
, d <- toInteger ro - toInteger wo
, rEnd <- d + toInteger (memReprBytes rr)
, wEnd <- toInteger (memReprBytes wr)
, rEnd <= wEnd =
Just (MemSlice d wr rr)
| otherwise = Nothing
throwRegError :: StmtIndex -> RegisterUseErrorTag e -> e -> StartInfer arch ids a
throwRegError stmtIdx tag v = do
blockAddr <- asks sicAddr
throwError $
RegisterUseError
{ ruBlock = blockAddr,
ruStmt = stmtIdx,
ruReason = Reason tag v
}
unresolvedStackRead :: StmtIndex -> StartInfer arch ids as
unresolvedStackRead stmtIdx = do
throwRegError stmtIdx UnresolvedStackRead ()
inferReadMem ::
(MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch)) =>
StmtIndex ->
AssignId ids tp ->
Value arch ids (BVType (ArchAddrWidth arch)) ->
MemRepr tp ->
StartInfer arch ids ()
inferReadMem stmtIdx aid addr repr = do
ctx <- ask
am <- gets sisAssignMap
case valueToStartExpr ctx am addr of
FrameExpr o -> do
stk <- gets sisStack
case memMapLookup' o repr stk of
Just (writeOff, MemVal writeRepr sv) ->
case checkReadWithinWrite writeOff writeRepr o repr of
Nothing ->
addMemAccessInfo stmtIdx (FrameReadOverlapAccess o)
Just ms -> do
(v, memInfo) <-
case sv of
ISVInitValue d -> do
pure (IVDomain d ms, FrameReadInitAccess o d)
ISVWrite writeIdx v ->
case valueToStartExpr' ctx am v ms of
Nothing -> do
unresolvedStackRead stmtIdx
Just iv ->
pure (iv, FrameReadWriteAccess writeIdx)
ISVCondWrite writeIdx _ _ _ -> do
case ms of
NoMemSlice ->
pure (IVCondWrite writeIdx repr, FrameReadWriteAccess writeIdx)
MemSlice _ _ _ ->
unresolvedStackRead stmtIdx
setAssignVal aid v
addMemAccessInfo stmtIdx memInfo
Nothing -> do
let d = RegEqualLoc (StackOffLoc o repr)
setAssignVal aid (IVDomain d NoMemSlice)
addMemAccessInfo stmtIdx (FrameReadInitAccess o d)
_ -> addMemAccessInfo stmtIdx NotFrameAccess
inferCondReadMem :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> StmtIndex
-> Value arch ids (BVType (ArchAddrWidth arch))
-> MemRepr tp
-> StartInfer arch ids ()
inferCondReadMem stmtIdx addr _repr = do
ctx <- ask
s <- gets sisAssignMap
case valueToStartExpr ctx s addr of
Stack reads need to record the offset .
FrameExpr _o -> do
throwRegError stmtIdx UnsupportedCondStackRead ()
_ -> addMemAccessInfo stmtIdx NotFrameAccess
processStmt :: (OrdF (ArchReg arch), MemWidth (ArchAddrWidth arch))
=> StmtIndex
-> Stmt arch ids
-> StartInfer arch ids ()
processStmt stmtIdx stmt = do
case stmt of
AssignStmt (Assignment aid arhs) ->
case arhs of
EvalApp app -> processApp aid app
SetUndefined _ -> pure ()
ReadMem addr repr -> inferReadMem stmtIdx aid addr repr
CondReadMem repr _cond addr _falseVal -> inferCondReadMem stmtIdx addr repr
EvalArchFn _afn _repr -> pure ()
WriteMem addr repr val -> do
ctx <- ask
s <- gets sisAssignMap
case valueToStartExpr ctx s addr of
FrameExpr o -> do
addMemAccessInfo stmtIdx (FrameWriteAccess o)
sisStackLens %= memMapOverwrite o repr (ISVWrite stmtIdx val)
Note . If @addr@ actually may point to the stack but we end
eventual .
_ -> addMemAccessInfo stmtIdx NotFrameAccess
CondWriteMem cond addr repr val -> do
ctx <- ask
s <- gets sisAssignMap
case valueToStartExpr ctx s addr of
FrameExpr o -> do
stk <- gets sisStack
sv <-
case memMapLookup o repr stk of
MMLResult sv -> do
addMemAccessInfo stmtIdx (FrameCondWriteAccess o repr sv)
pure sv
MMLOverlap{} -> do
addMemAccessInfo stmtIdx (FrameCondWriteOverlapAccess o)
pure $ ISVInitValue (RegEqualLoc (StackOffLoc o repr))
MMLNone -> do
let sv = ISVInitValue (RegEqualLoc (StackOffLoc o repr))
addMemAccessInfo stmtIdx (FrameCondWriteAccess o repr sv)
pure sv
sisStackLens %= memMapOverwrite o repr (ISVCondWrite stmtIdx cond val sv)
_ -> do
addMemAccessInfo stmtIdx NotFrameAccess
InstructionStart o _ ->
sisCurrentInstructionOffsetLens .= o
Comment _ -> pure ()
ArchState{} -> pure ()
ExecArchStmt _ -> pure ()
newtype PostValueMap arch ids =
PVM { _pvmMap :: MapF (BoundLoc (ArchReg arch)) (BlockInferValue arch ids) }
emptyPVM :: PostValueMap arch ids
emptyPVM = PVM MapF.empty
pvmBind :: OrdF (ArchReg arch)
=> BoundLoc (ArchReg arch) tp
-> BlockInferValue arch ids tp
-> PostValueMap arch ids
-> PostValueMap arch ids
pvmBind l v (PVM m) = PVM (MapF.insert l v m)
pvmFind :: OrdF (ArchReg arch)
=> BoundLoc (ArchReg arch) tp
-> PostValueMap arch ids
-> BlockInferValue arch ids tp
pvmFind l (PVM m) = MapF.findWithDefault (IVDomain (RegEqualLoc l) NoMemSlice) l m
instance ShowF (ArchReg arch) => Show (PostValueMap arch ids) where
show (PVM m) = show m
ppPVM :: forall arch ids ann . ShowF (ArchReg arch) => PostValueMap arch ids -> Doc ann
ppPVM (PVM m) = vcat $ ppVal <$> MapF.toList m
where ppVal :: Pair (BoundLoc (ArchReg arch)) (BlockInferValue arch ids) -> Doc ann
ppVal (Pair l v) = pretty l <+> ":=" <+> viaShow v
type StartInferInfo arch ids =
( ParsedBlock arch ids
, BlockStartConstraints arch
, InferState arch ids
, Map (ArchSegmentOff arch) (PostValueMap arch ids)
)
siiCns :: StartInferInfo arch ids -> BlockStartConstraints arch
siiCns (_,cns,_,_) = cns
type FrontierMap arch = Map (ArchSegmentOff arch) (BlockStartConstraints arch)
data InferNextState arch ids =
InferNextState { insSeenValues :: !(MapF (BlockInferValue arch ids) (InitInferValue arch))
, insPVM :: !(PostValueMap arch ids)
}
type InferNextM arch ids = State (InferNextState arch ids)
runInferNextM :: InferNextM arch ids a -> a
runInferNextM m =
let s = InferNextState { insSeenValues = MapF.empty
, insPVM = emptyPVM
}
in evalState m s
| assumes that @expr@ is the value
assigned to @loc@ in the next function , and returns the domain to
memoNextDomain :: OrdF (ArchReg arch)
=> BoundLoc (ArchReg arch) tp
-> BlockInferValue arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
memoNextDomain _ (IVDomain d@InferredStackOffset{} NoMemSlice) =
pure (Just d)
memoNextDomain _ (IVDomain d@FnStartRegister{} NoMemSlice) = pure (Just d)
memoNextDomain loc e = do
m <- gets insSeenValues
case MapF.lookup e m of
Just d -> do
modify $ \s -> InferNextState { insSeenValues = m
, insPVM = pvmBind loc e (insPVM s)
}
pure (Just d)
Nothing -> do
modify $ \s -> InferNextState { insSeenValues = MapF.insert e (RegEqualLoc loc) m
, insPVM = pvmBind loc e (insPVM s)
}
pure Nothing
addNextConstraints :: forall arch
. (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> (ArchSegmentOff arch -> Maybe (BlockStartConstraints arch))
-> ArchSegmentOff arch
-> BlockStartConstraints arch
-> FrontierMap arch
-> FrontierMap arch
addNextConstraints lastMap addr nextCns frontierMap =
let modifyFrontier :: Maybe (BlockStartConstraints arch)
-> Maybe (BlockStartConstraints arch)
modifyFrontier (Just prevCns) =
Just (unionBlockStartConstraints nextCns prevCns)
modifyFrontier Nothing =
case lastMap addr of
Nothing -> Just nextCns
Just prevCns -> runChanged (joinBlockStartConstraints prevCns nextCns)
in Map.alter modifyFrontier addr frontierMap
intraJumpConstraints :: forall arch ids
. OrdF (ArchReg arch)
=> StartInferContext arch
-> InferState arch ids
-> RegState (ArchReg arch) (Value arch ids)
-> (PostValueMap arch ids, BlockStartConstraints arch)
intraJumpConstraints ctx s regs = runInferNextM $ do
let intraRegFn :: ArchReg arch tp
-> Value arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
intraRegFn r v = memoNextDomain (RegLoc r) (valueToStartExpr ctx (sisAssignMap s) v)
regs' <- MapF.traverseMaybeWithKey intraRegFn (regStateMap regs)
let stackFn :: MemInt (ArchAddrWidth arch)
-> MemRepr tp
-> InferStackValue arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
stackFn o repr sv =
memoNextDomain (StackOffLoc o repr) (inferStackValueToValue ctx (sisAssignMap s) sv repr)
stk <- memMapTraverseMaybeWithKey stackFn (sisStack s)
postValMap <- gets insPVM
let cns = BSC LocMap { locMapRegs = regs'
, locMapStack = stk
}
pure (postValMap, cns)
postCallConstraints :: forall arch ids
. ArchConstraints arch
=> CallParams (ArchReg arch)
-> StartInferContext arch
-> InferState arch ids
-> Int
-> RegState (ArchReg arch) (Value arch ids)
-> Either (RegisterUseError arch)
(PostValueMap arch ids, BlockStartConstraints arch)
postCallConstraints params ctx s tidx regs =
runInferNextM $ do
case valueToStartExpr ctx (sisAssignMap s) (regs^.boundValue sp_reg) of
FrameExpr spOff -> do
when (not (stackGrowsDown params)) $
error "Do not yet support architectures where stack grows up."
when (postCallStackDelta params < 0) $
error "Unexpected post call stack delta."
let h = toInteger spOff
let l = h - postCallStackDelta params
let intraRegFn :: ArchReg arch tp
-> Value arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
intraRegFn r v
| Just Refl <- testEquality r sp_reg = do
let spOff' = spOff + fromInteger (postCallStackDelta params)
pure (Just (InferredStackOffset spOff'))
| preserveReg params r =
memoNextDomain (RegLoc r) (valueToStartExpr ctx (sisAssignMap s) v)
| otherwise =
pure Nothing
regs' <- MapF.traverseMaybeWithKey intraRegFn (regStateMap regs)
let stackFn :: MemInt (ArchAddrWidth arch)
-> MemRepr tp
-> InferStackValue arch ids tp
-> InferNextM arch ids (Maybe (InitInferValue arch tp))
stackFn o repr sv
| l <= toInteger o, toInteger o < h =
pure Nothing
| otherwise =
memoNextDomain (StackOffLoc o repr) (inferStackValueToValue ctx (sisAssignMap s) sv repr)
stk <- memMapTraverseMaybeWithKey stackFn (sisStack s)
postValMap <- gets insPVM
let cns = BSC LocMap { locMapRegs = regs'
, locMapStack = stk
}
pure $ Right $ (postValMap, cns)
_ -> pure $ Left $
RegisterUseError
{ ruBlock = sicAddr ctx,
ruStmt = tidx,
ruReason = Reason CallStackHeightError ()
}
data DependencySet (r :: M.Type -> Type) ids =
DepSet { dsLocSet :: !(Set (Some (BoundLoc r)))
, dsAssignSet :: !(Set (Some (AssignId ids)))
, dsWriteStmtIndexSet :: !(Set StmtIndex)
}
ppSet :: (a -> Doc ann) -> Set a -> Doc ann
ppSet f s = encloseSep lbrace rbrace comma (f <$> Set.toList s)
ppSomeAssignId :: Some (AssignId ids) -> Doc ann
ppSomeAssignId (Some aid) = viaShow aid
ppSomeBoundLoc :: MapF.ShowF r => Some (BoundLoc r) -> Doc ann
ppSomeBoundLoc (Some loc) = pretty loc
instance MapF.ShowF r => Pretty (DependencySet r ids) where
pretty ds =
vcat [ "Assignments:" <+> ppSet ppSomeAssignId (dsAssignSet ds)
, "Locations: " <+> ppSet ppSomeBoundLoc (dsLocSet ds)
, "Write Stmts:" <+> ppSet pretty (dsWriteStmtIndexSet ds)
]
emptyDeps :: DependencySet r ids
emptyDeps =
DepSet { dsLocSet = Set.empty
, dsAssignSet = Set.empty
, dsWriteStmtIndexSet = Set.empty
}
assignSet :: AssignId ids tp -> DependencySet r ids
assignSet aid =
DepSet { dsLocSet = Set.empty
, dsAssignSet = Set.singleton (Some aid)
, dsWriteStmtIndexSet = Set.empty
}
locDepSet :: BoundLoc r tp -> DependencySet r ids
locDepSet l =
DepSet { dsLocSet = Set.singleton (Some l)
, dsAssignSet = Set.empty
, dsWriteStmtIndexSet = Set.empty
}
addWriteDep :: StmtIndex -> DependencySet r ids -> DependencySet r ids
addWriteDep idx s = seq idx $
s { dsWriteStmtIndexSet = Set.insert idx (dsWriteStmtIndexSet s) }
instance MapF.OrdF r => Semigroup (DependencySet r ids) where
x <> y = DepSet { dsAssignSet = Set.union (dsAssignSet x) (dsAssignSet y)
, dsLocSet = Set.union (dsLocSet x) (dsLocSet y)
, dsWriteStmtIndexSet =
Set.union (dsWriteStmtIndexSet x) (dsWriteStmtIndexSet y)
}
instance MapF.OrdF r => Monoid (DependencySet r ids) where
mempty = emptyDeps
newtype RegDependencyMap arch ids =
RDM { rdmMap :: MapF (ArchReg arch) (Const (DependencySet (ArchReg arch) ids)) }
emptyRegDepMap :: RegDependencyMap arch ids
emptyRegDepMap = RDM MapF.empty
instance OrdF (ArchReg arch) => Semigroup (RegDependencyMap arch ids) where
RDM x <> RDM y = RDM (MapF.union x y)
instance OrdF (ArchReg arch) => Monoid (RegDependencyMap arch ids) where
mempty = emptyRegDepMap
setRegDep :: OrdF (ArchReg arch)
=> ArchReg arch tp
-> DependencySet (ArchReg arch) ids
-> RegDependencyMap arch ids
-> RegDependencyMap arch ids
setRegDep r d (RDM m) = RDM (MapF.insert r (Const d) m)
regDepsFromMap :: (forall tp . a tp -> DependencySet (ArchReg arch) ids)
-> MapF (ArchReg arch) a
-> RegDependencyMap arch ids
regDepsFromMap f m = RDM (fmapF (Const . f) m)
data BlockUsageSummary (arch :: Type) ids = BUS
{ blockUsageStartConstraints :: !(BlockStartConstraints arch)
, blockCurOff :: !(ArchAddrWord arch)
, blockInferState :: !(InferState arch ids)
,_blockExecDemands :: !(DependencySet (ArchReg arch) ids)
, blockRegDependencies :: !(RegDependencyMap arch ids)
, blockWriteDependencies :: !(Map StmtIndex (DependencySet (ArchReg arch) ids))
, assignDeps :: !(Map (Some (AssignId ids)) (DependencySet (ArchReg arch) ids))
, pendingMemAccesses :: ![(StmtIndex, MemAccessInfo arch ids)]
Otherwise , the value should be @Nothing@.
, blockCallFunType :: !(Maybe (ArchFunType arch))
}
initBlockUsageSummary :: BlockStartConstraints arch
-> InferState arch ids
-> BlockUsageSummary arch ids
initBlockUsageSummary cns s =
let a = reverse (sisMemAccessStack s)
in BUS { blockUsageStartConstraints = cns
, blockCurOff = zeroMemWord
, blockInferState = s
, _blockExecDemands = emptyDeps
, blockRegDependencies = emptyRegDepMap
, blockWriteDependencies = Map.empty
, assignDeps = Map.empty
, pendingMemAccesses = a
, blockCallFunType = Nothing
}
blockExecDemands :: Lens' (BlockUsageSummary arch ids) (DependencySet (ArchReg arch) ids)
blockExecDemands = lens _blockExecDemands (\s v -> s { _blockExecDemands = v })
blockRegDependenciesLens :: Lens' (BlockUsageSummary arch ids) (RegDependencyMap arch ids)
blockRegDependenciesLens = lens blockRegDependencies (\s v -> s { blockRegDependencies = v })
blockWriteDependencyLens :: Lens' (BlockUsageSummary arch ids)
(Map StmtIndex (DependencySet (ArchReg arch) ids))
blockWriteDependencyLens = lens blockWriteDependencies (\s v -> s { blockWriteDependencies = v })
assignmentCache :: Lens' (BlockUsageSummary arch ids)
(Map (Some (AssignId ids)) (DependencySet (ArchReg arch) ids))
assignmentCache = lens assignDeps (\s v -> s { assignDeps = v })
data CallRegs (arch :: Type) (ids :: Type) =
CallRegs { callRegsFnType :: !(ArchFunType arch)
, callArgValues :: [Some (Value arch ids)]
, callReturnRegs :: [Some (ArchReg arch)]
}
type PostTermStmtInvariants arch ids =
StartInferContext arch
-> InferState arch ids
-> Int
-> ArchTermStmt arch (Value arch ids)
-> RegState (ArchReg arch) (Value arch ids)
-> Either (RegisterUseError arch) (PostValueMap arch ids, BlockStartConstraints arch)
type ArchTermStmtUsageFn arch ids
= ArchTermStmt arch (Value arch ids)
-> RegState (ArchReg arch) (Value arch ids)
-> BlockUsageSummary arch ids
-> Either (RegisterUseError arch) (RegDependencyMap arch ids)
type family ArchFunType (arch::Type) :: Type
data RegisterUseContext arch
= RegisterUseContext
archCallParams :: !(CallParams (ArchReg arch))
, archPostTermStmtInvariants :: !(forall ids . PostTermStmtInvariants arch ids)
, calleeSavedRegisters :: ![Some (ArchReg arch)]
, callScratchRegisters :: ![Some (ArchReg arch)]
Note . Should not include stack pointer as thay is
, returnRegisters :: ![Some (ArchReg arch)]
, reguseTermFn :: !(forall ids . ArchTermStmtUsageFn arch ids)
, callDemandFn :: !(forall ids
. ArchSegmentOff arch
-> RegState (ArchReg arch) (Value arch ids)
-> Either RegisterUseErrorReason (CallRegs arch ids))
, demandContext :: !(DemandContext arch)
}
visitIntraJumpTarget :: forall arch ids
. (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> (ArchSegmentOff arch -> Maybe (BlockStartConstraints arch))
-> StartInferContext arch
-> InferState arch ids
-> RegState (ArchReg arch) (Value arch ids)
-> (Map (ArchSegmentOff arch) (PostValueMap arch ids), FrontierMap arch)
^ Frontier so far
-> (Map (ArchSegmentOff arch) (PostValueMap arch ids), FrontierMap arch)
visitIntraJumpTarget lastMap ctx s regs (m,frontierMap) addr =
let nextCns :: BlockStartConstraints arch
(postValMap, nextCns) = intraJumpConstraints ctx s regs
in (Map.insert addr postValMap m, addNextConstraints lastMap addr nextCns frontierMap)
blockStartConstraints :: ArchConstraints arch
=> RegisterUseContext arch
-> Map (ArchSegmentOff arch) (ParsedBlock arch ids)
-> ArchSegmentOff arch
-> BlockStartConstraints arch
-> Map (ArchSegmentOff arch) (StartInferInfo arch ids)
-> FrontierMap arch
-> Except (RegisterUseError arch)
(Map (ArchSegmentOff arch) (StartInferInfo arch ids), FrontierMap arch)
blockStartConstraints rctx blockMap addr (BSC cns) lastMap frontierMap = do
let b = Map.findWithDefault (error "No block") addr blockMap
let ctx = SIC { sicAddr = addr
, sicRegs = locMapRegs cns
}
let s0 = SIS { sisStack = fmapF ISVInitValue (locMapStack cns)
, sisAssignMap = MapF.empty
, sisAppCache = MapF.empty
, sisCurrentInstructionOffset = 0
, sisMemAccessStack = []
}
let stmts = pblockStmts b
let stmtCount = length stmts
s <- execStateT (runReaderT (zipWithM_ processStmt [0..] stmts) ctx) s0
let lastFn a = if a == addr then Just (BSC cns) else siiCns <$> Map.lookup a lastMap
case pblockTermStmt b of
ParsedJump regs next -> do
let (pvm,frontierMap') = visitIntraJumpTarget lastFn ctx s regs (Map.empty, frontierMap) next
let m' = Map.insert addr (b, BSC cns, s, pvm) lastMap
pure $ (m', frontierMap')
ParsedBranch regs _cond t f -> do
let (pvm, frontierMap') = foldl' (visitIntraJumpTarget lastFn ctx s regs) (Map.empty, frontierMap) [t,f]
let m' = Map.insert addr (b, BSC cns, s, pvm) lastMap
pure $ (m', frontierMap')
ParsedLookupTable _layout regs _idx lbls -> do
let (pvm, frontierMap') = foldl' (visitIntraJumpTarget lastFn ctx s regs) (Map.empty, frontierMap) lbls
let m' = Map.insert addr (b, BSC cns, s, pvm) lastMap
pure $ (m', frontierMap')
ParsedCall regs (Just next) -> do
(postValCns, nextCns) <-
case postCallConstraints (archCallParams rctx) ctx s stmtCount regs of
Left e -> throwError e
Right r -> pure r
let m' = Map.insert addr (b, BSC cns, s, Map.singleton next postValCns) lastMap
pure (m', addNextConstraints lastFn next nextCns frontierMap)
ParsedCall _ Nothing -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
ParsedReturn _ -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
ParsedArchTermStmt _ _ Nothing -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
ParsedArchTermStmt tstmt regs (Just next) -> do
case archPostTermStmtInvariants rctx ctx s stmtCount tstmt regs of
Left e ->
throwError e
Right (postValCns, nextCns) -> do
let m' = Map.insert addr (b, BSC cns, s, Map.singleton next postValCns) lastMap
pure (m', addNextConstraints lastFn next nextCns frontierMap)
ParsedTranslateError _ -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
ClassifyFailure _ _ -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
PLT stubs are essentiually tail calls with a non - standard
PLTStub{} -> do
let m' = Map.insert addr (b, BSC cns, s, Map.empty) lastMap
pure $ (m', frontierMap)
propStartConstraints :: ArchConstraints arch
=> RegisterUseContext arch
-> Map (ArchSegmentOff arch) (ParsedBlock arch ids)
-> Map (ArchSegmentOff arch) (StartInferInfo arch ids)
-> FrontierMap arch
-> Except (RegisterUseError arch)
(Map (ArchSegmentOff arch) (StartInferInfo arch ids))
propStartConstraints rctx blockMap lastMap next =
case Map.minViewWithKey next of
Nothing -> pure lastMap
Just ((nextAddr, nextCns), rest) -> do
(lastMap', next') <- blockStartConstraints rctx blockMap nextAddr nextCns lastMap rest
propStartConstraints rctx blockMap lastMap' next'
inferStartConstraints :: forall arch ids
. ArchConstraints arch
=> RegisterUseContext arch
-> Map (ArchSegmentOff arch) (ParsedBlock arch ids)
-> ArchSegmentOff arch
-> Except (RegisterUseError arch)
(Map (ArchSegmentOff arch) (StartInferInfo arch ids))
inferStartConstraints rctx blockMap addr = do
let savedRegs :: [Pair (ArchReg arch) (InitInferValue arch)]
savedRegs
= [ Pair sp_reg (InferredStackOffset 0) ]
++ [ Pair r (FnStartRegister r) | Some r <- calleeSavedRegisters rctx ]
let cns = BSC LocMap { locMapRegs = MapF.fromList savedRegs
, locMapStack = emptyMemMap
}
propStartConstraints rctx blockMap Map.empty (Map.singleton addr cns)
ppStartConstraints :: forall arch ids ann
. (MemWidth (ArchAddrWidth arch), ShowF (ArchReg arch))
=> Map (ArchSegmentOff arch) (StartInferInfo arch ids)
-> Doc ann
ppStartConstraints m = vcat (pp <$> Map.toList m)
where pp :: (ArchSegmentOff arch, StartInferInfo arch ids) -> Doc ann
pp (addr, (_,_,_,pvm)) =
let pvmEntries = vcat (ppPVMPair <$> Map.toList pvm)
in vcat [ pretty addr
, indent 2 $ vcat ["post-values:", indent 2 pvmEntries] ]
ppPVMPair :: (ArchSegmentOff arch, PostValueMap arch ids) -> Doc ann
ppPVMPair (preaddr, pvm) =
vcat
[ "to" <+> pretty preaddr <> ":"
, indent 2 (ppPVM pvm) ]
_ppStartConstraints :: forall arch ids ann
. (MemWidth (ArchAddrWidth arch), ShowF (ArchReg arch))
=> Map (ArchSegmentOff arch) (StartInferInfo arch ids)
-> Doc ann
_ppStartConstraints = ppStartConstraints
type LocDependencyMap r ids = LocMap r (Const (DependencySet r ids))
getLocDependencySet :: (MapF.OrdF r, MemWidth (RegAddrWidth r))
=> LocDependencyMap r ids
-> BoundLoc r tp
-> DependencySet r ids
getLocDependencySet srcDepMap l =
case locLookup l srcDepMap of
Nothing -> locDepSet l
Just (Const s) -> s
RegisterUseM
type RegisterUseM arch ids =
ReaderT (RegisterUseContext arch)
(StateT (BlockUsageSummary arch ids)
(Except (RegisterUseError arch)))
domainDeps :: InitInferValue arch tp -> DependencySet (ArchReg arch) ids
domainDeps (InferredStackOffset _) = emptyDeps
domainDeps (FnStartRegister _) = emptyDeps
domainDeps (RegEqualLoc l) = locDepSet l
valueDeps :: (HasCallStack, MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> Map (Some (AssignId ids)) (DependencySet (ArchReg arch) ids)
-> Value arch ids tp
-> DependencySet (ArchReg arch) ids
valueDeps _ _ (CValue _) = emptyDeps
valueDeps cns _ (Initial r) = domainDeps (locDomain cns (RegLoc r))
valueDeps _ m (AssignedValue (Assignment a _)) =
case Map.lookup (Some a) m of
Nothing -> error $ "Assignment " ++ show a ++ " is not defined."
Just r -> r
addDeps :: (HasCallStack, OrdF (ArchReg arch))
=> DependencySet (ArchReg arch) ids
-> RegisterUseM arch ids ()
addDeps deps = blockExecDemands %= mappend deps
demandValue :: (HasCallStack, MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> Value arch ids tp
-> RegisterUseM arch ids ()
demandValue v = do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
addDeps (valueDeps cns cache v)
clearDependencySet :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> ArchReg arch tp
-> BlockUsageSummary arch ids
-> BlockUsageSummary arch ids
clearDependencySet r s =
s & blockRegDependenciesLens %~ setRegDep r mempty
| @recordRegMap m@ record that the values in are
recordRegMap :: forall arch ids
. (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> MapF (ArchReg arch) (Value arch ids)
-> RegisterUseM arch ids ()
recordRegMap m = do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
blockRegDependenciesLens .= regDepsFromMap (valueDeps cns cache) m
requiredAssignDeps :: OrdF (ArchReg arch)
=> AssignId ids tp
-> DependencySet (ArchReg arch) ids
-> RegisterUseM arch ids ()
requiredAssignDeps aid deps = do
addDeps deps
assignmentCache %= Map.insert (Some aid) mempty
popAccessInfo :: StmtIndex -> RegisterUseM arch ids (MemAccessInfo arch ids)
popAccessInfo n = do
s <- get
case pendingMemAccesses s of
[] -> error "popAccessInfo invalid"
((i,a):r) -> do
put $! s { pendingMemAccesses = r }
if i < n then
popAccessInfo n
else if i > n then
error "popAccessInfo missing index."
else
pure a
demandReadMem :: (MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> StmtIndex
-> AssignId ids tp
-> Value arch ids (BVType (ArchAddrWidth arch))
-> MemRepr tp
-> RegisterUseM arch ids ()
demandReadMem stmtIdx aid addr _repr = do
accessInfo <- popAccessInfo stmtIdx
case accessInfo of
NotFrameAccess -> do
that this value depends on both aid and any
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = assignSet aid <> valueDeps cns cache addr
requiredAssignDeps aid deps
FrameReadInitAccess _o d -> do
let deps = assignSet aid <> domainDeps d
assignmentCache %= Map.insert (Some aid) deps
FrameReadWriteAccess writeIdx -> do
that this value depends on aid and any
dependencies needed to compute the value stored at o.
m <- gets blockWriteDependencies
let deps = Map.findWithDefault (error "Could not find write index.") writeIdx m
let allDeps = addWriteDep writeIdx (assignSet aid <> deps)
assignmentCache %= Map.insert (Some aid) allDeps
FrameReadOverlapAccess _ -> do
assignmentCache %= Map.insert (Some aid) (assignSet aid)
FrameWriteAccess{} ->
error "Expected read access."
FrameCondWriteAccess{} ->
error "Expected read access."
FrameCondWriteOverlapAccess _ ->
error "Expected read access."
demandCondReadMem ::
(MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch)) =>
StmtIndex ->
AssignId ids tp ->
Value arch ids BoolType ->
Value arch ids (BVType (ArchAddrWidth arch)) ->
MemRepr tp ->
Value arch ids tp ->
RegisterUseM arch ids ()
demandCondReadMem stmtIdx aid cond addr _repr val = do
accessInfo <- popAccessInfo stmtIdx
case accessInfo of
NotFrameAccess -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = mconcat
[ assignSet aid
, valueDeps cns cache cond
, valueDeps cns cache addr
, valueDeps cns cache val
]
requiredAssignDeps aid deps
addDeps $ assignSet aid
FrameReadInitAccess _o d -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = mconcat
[ assignSet aid
, valueDeps cns cache cond
, domainDeps d
, valueDeps cns cache val
]
assignmentCache %= Map.insert (Some aid) deps
FrameReadWriteAccess writeIdx -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
that this value depends on aid and any dependencies
needed to compute the value stored at o.
m <- gets blockWriteDependencies
let deps = Map.findWithDefault (error "Could not find write index.") writeIdx m
let allDeps = addWriteDep writeIdx $
mconcat [ assignSet aid
, valueDeps cns cache cond
, deps
, valueDeps cns cache val
]
assignmentCache %= Map.insert (Some aid) allDeps
FrameReadOverlapAccess _ -> do
assignmentCache %= Map.insert (Some aid) (assignSet aid)
FrameWriteAccess{} ->
error "Expected read access."
FrameCondWriteAccess{} ->
error "Expected read access."
FrameCondWriteOverlapAccess{} ->
error "Expected read access."
inferStackValueDeps :: (HasCallStack, MemWidth (ArchAddrWidth arch), OrdF (ArchReg arch))
=> BlockStartConstraints arch
-> Map (Some (AssignId ids)) (DependencySet (ArchReg arch) ids)
-> InferStackValue arch ids tp
-> DependencySet (ArchReg arch) ids
inferStackValueDeps cns amap isv =
case isv of
ISVInitValue d -> domainDeps d
ISVWrite idx v -> addWriteDep idx (valueDeps cns amap v)
ISVCondWrite idx c v prevVal -> addWriteDep idx $
mconcat [ valueDeps cns amap c
, valueDeps cns amap v
, inferStackValueDeps cns amap prevVal
]
demandAssign ::
( MemWidth (ArchAddrWidth arch),
OrdF (ArchReg arch),
FoldableFC (ArchFn arch)
) =>
StmtIndex ->
Assignment arch ids tp ->
RegisterUseM arch ids ()
demandAssign stmtIdx (Assignment aid arhs) = do
sis <- gets blockInferState
case MapF.lookup aid (sisAssignMap sis) of
Just (IVDomain d _) -> do
assignmentCache %= Map.insert (Some aid) (domainDeps d)
Just (IVAssignValue a) -> do
dm <- gets assignDeps
case Map.lookup (Some a) dm of
Nothing -> error $ "Assignment " ++ show a ++ " is not defined."
Just deps -> assignmentCache .= Map.insert (Some aid) deps dm
Just (IVCValue _) -> do
assignmentCache %= Map.insert (Some aid) emptyDeps
_ -> do
case arhs of
EvalApp app -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = foldlFC' (\s v -> mappend s (valueDeps cns cache v)) (assignSet aid) app
assignmentCache %= Map.insert (Some aid) deps
SetUndefined{} -> do
assignmentCache %= Map.insert (Some aid) (assignSet aid)
ReadMem addr repr -> do
demandReadMem stmtIdx aid addr repr
CondReadMem repr c addr val -> do
demandCondReadMem stmtIdx aid c addr repr val
EvalArchFn fn _ -> do
ctx <- asks demandContext
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = foldlFC' (\s v -> mappend s (valueDeps cns cache v)) (assignSet aid) fn
if archFnHasSideEffects ctx fn then do
requiredAssignDeps aid deps
else
assignmentCache %= Map.insert (Some aid) deps
demandStmtValues ::
( HasCallStack,
OrdF (ArchReg arch),
MemWidth (ArchAddrWidth arch),
ShowF (ArchReg arch),
FoldableFC (ArchFn arch),
FoldableF (ArchStmt arch)
) =>
StmtIndex ->
Stmt arch ids ->
RegisterUseM arch ids ()
demandStmtValues stmtIdx stmt = do
case stmt of
AssignStmt a -> demandAssign stmtIdx a
WriteMem addr _repr val -> do
accessInfo <- popAccessInfo stmtIdx
case accessInfo of
NotFrameAccess -> do
demandValue addr
demandValue val
FrameReadInitAccess{} -> error "Expected write access"
FrameReadWriteAccess{} -> error "Expected write access"
FrameReadOverlapAccess{} -> error "Expected write access"
FrameWriteAccess _o -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let valDeps = addWriteDep stmtIdx (valueDeps cns cache val)
blockWriteDependencyLens %= Map.insert stmtIdx valDeps
FrameCondWriteAccess{} -> error "Expected write access."
FrameCondWriteOverlapAccess{} -> error "Expected write access."
CondWriteMem c addr _repr val -> do
accessInfo <- popAccessInfo stmtIdx
case accessInfo of
NotFrameAccess -> do
demandValue c
demandValue addr
demandValue val
FrameReadInitAccess{} -> error "Expected conditional write access"
FrameReadWriteAccess{} -> error "Expected conditional write access"
FrameReadOverlapAccess{} -> error "Expected conditional write access"
FrameWriteAccess{} -> error "Expectedf1 conditional write access"
FrameCondWriteAccess _o _repr sv -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let deps = addWriteDep stmtIdx
$ valueDeps cns cache c
<> inferStackValueDeps cns cache sv
<> valueDeps cns cache val
blockWriteDependencyLens %= Map.insert stmtIdx deps
FrameCondWriteOverlapAccess _ -> do
cns <- gets blockUsageStartConstraints
cache <- gets assignDeps
let valDeps =
addWriteDep stmtIdx $
valueDeps cns cache c <> valueDeps cns cache val
blockWriteDependencyLens %= Map.insert stmtIdx valDeps
InstructionStart off _ -> do
modify $ \s -> s { blockCurOff = off }
Comment _ ->
pure ()
ExecArchStmt astmt -> do
traverseF_ demandValue astmt
ArchState _addr _assn -> do
pure ()
mkBlockUsageSummary :: forall arch ids
. ( RegisterInfo (ArchReg arch)
, FoldableF (ArchStmt arch)
, FoldableFC (ArchFn arch)
)
=> RegisterUseContext arch
-> BlockStartConstraints arch
-> InferState arch ids
-> ParsedBlock arch ids
-> Except (RegisterUseError arch) (BlockUsageSummary arch ids)
mkBlockUsageSummary ctx cns sis blk = do
flip execStateT (initBlockUsageSummary cns sis) $ flip runReaderT ctx $ do
let addr = pblockAddr blk
zipWithM_ demandStmtValues [0..] (pblockStmts blk)
let tidx = length (pblockStmts blk)
case pblockTermStmt blk of
ParsedJump regs _tgt -> do
recordRegMap (regStateMap regs)
ParsedBranch regs cond _t _f -> do
demandValue cond
recordRegMap (regStateMap regs)
ParsedLookupTable _layout regs idx _tgts -> do
demandValue idx
recordRegMap (regStateMap regs)
ParsedCall regs _mret -> do
callFn <- asks $ \x -> callDemandFn x
off <- gets blockCurOff
let insnAddr =
let msg = "internal: Expected valid instruction address."
in fromMaybe (error msg) (incSegmentOff addr (toInteger off))
demandValue (regs^.boundValue ip_reg)
ftr <-
case callFn insnAddr regs of
Right v -> pure v
Left rsn -> do
throwError $
RegisterUseError
{ ruBlock = addr,
ruStmt = tidx,
ruReason = rsn
}
do
forM_ (callArgValues ftr) $ \(Some v) -> do
case v of
CValue _ -> do
pure ()
Initial r -> do
addDeps (domainDeps (locDomain cns (RegLoc r)))
AssignedValue (Assignment a _) -> do
cache <- gets assignDeps
case Map.lookup (Some a) cache of
Nothing -> error $ "Assignment " ++ show a ++ " is not defined."
Just r -> addDeps r
modify $ \s -> s { blockCallFunType = Just (callRegsFnType ftr) }
cache <- gets assignDeps
savedRegs <- asks calleeSavedRegisters
let insReg m (Some r) = setRegDep r (valueDeps cns cache (regs^.boundValue r)) m
blockRegDependenciesLens %= \m -> foldl' insReg m (Some sp_reg : savedRegs)
clearedRegs <- asks callScratchRegisters
let clearReg m (Some r) = setRegDep r mempty m
blockRegDependenciesLens %= \m -> foldl' clearReg m clearedRegs
blockRegDependenciesLens %= \m -> foldl' clearReg m (callReturnRegs ftr)
PLTStub regs _ _ -> do
traverseF_ demandValue regs
MapF.traverseWithKey_ (\r _ -> modify $ clearDependencySet r) regs
ParsedReturn regs -> do
retRegs <- asks $ returnRegisters
traverse_ (\(Some r) -> demandValue (regs^.boundValue r)) retRegs
ParsedArchTermStmt tstmt regs _mnext -> do
summaryFn <- asks $ \x -> reguseTermFn x
s <- get
case summaryFn tstmt regs s of
Left emsg -> throwError emsg
Right rDeps -> blockRegDependenciesLens .= rDeps
ParsedTranslateError _ ->
error "Cannot identify register use in code where translation error occurs"
ClassifyFailure _ _ ->
error $ "Classification failed: " ++ show addr
type BlockAddrMap r v = Map (MemSegmentOff (RegAddrWidth r)) v
type SrcDependencies r ids =
[(MemSegmentOff (RegAddrWidth r), LocDependencyMap r ids)]
type PredProvideMap r ids =
Map (MemSegmentOff (RegAddrWidth r)) (SrcDependencies r ids)
type NewDemandMap r = BlockAddrMap r (Set (Some (BoundLoc r)))
backPropagateOne :: forall r ids
. (MapF.OrdF r, MemWidth (RegAddrWidth r))
=> BlockAddrMap r (DependencySet r ids)
-> NewDemandMap r
-> Set (Some (BoundLoc r))
-> [( MemSegmentOff (RegAddrWidth r)
, LocDependencyMap r ids
)]
-> ( Map (MemSegmentOff (RegAddrWidth r)) (DependencySet r ids)
, NewDemandMap r
)
backPropagateOne s rest _ [] = (s, rest)
backPropagateOne s rest newLocs ((srcAddr,srcDepMap):predRest) = do
let allDeps :: DependencySet r ids
allDeps = mconcat [ getLocDependencySet srcDepMap l | Some l <- Set.toList newLocs ]
let (mseenRegs, s') =
Map.insertLookupWithKey (\_ x y -> x <> y) srcAddr allDeps s
let d = case mseenRegs of
Nothing -> dsLocSet allDeps
Just oldDems -> dsLocSet allDeps `Set.difference` dsLocSet oldDems
let rest' | Set.null d = rest
| otherwise = Map.insertWith Set.union srcAddr d rest
seq s' $ seq rest' $ backPropagateOne s' rest' newLocs predRest
BlockInvariants
newtype LocList r tp = LL { llValues :: [BoundLoc r tp] }
instance Semigroup (LocList r tp) where
LL x <> LL y = LL (x++y)
data BlockInvariants arch ids = BI
{ biUsedAssignSet :: !(Set (Some (AssignId ids)))
, biUsedWriteSet :: !(Set StmtIndex)
, biMemAccessList :: ![(StmtIndex, MemAccessInfo arch ids)]
, biLocMap :: !(MapF (BoundLoc (ArchReg arch)) (LocList (ArchReg arch)))
, biPredPostValues :: !(Map (ArchSegmentOff arch) (PostValueMap arch ids))
| Locations from previous block used to initial phi variables .
, biPhiLocs :: ![Some (BoundLoc (ArchReg arch))]
, biStartConstraints :: !(BlockStartConstraints arch)
Otherwise , the value should be @Nothing@.
, biCallFunType :: !(Maybe (ArchFunType arch))
, biAssignMap :: !(MapF (AssignId ids) (BlockInferValue arch ids))
}
biAssignIdUsed :: AssignId ids tp -> BlockInvariants arch ids -> Bool
biAssignIdUsed aid inv = Set.member (Some aid) (biUsedAssignSet inv)
biWriteUsed :: StmtIndex -> BlockInvariants arch ids -> Bool
biWriteUsed idx inv = Set.member idx (biUsedWriteSet inv)
backPropagate :: forall arch ids
. (OrdF (ArchReg arch), MemWidth (ArchAddrWidth arch))
=> PredProvideMap (ArchReg arch) ids
-> Map (ArchSegmentOff arch) (DependencySet (ArchReg arch) ids)
-> Map (ArchSegmentOff arch) (Set (Some (BoundLoc (ArchReg arch))))
-> Map (ArchSegmentOff arch) (DependencySet (ArchReg arch) ids)
backPropagate predMap depMap new =
case Map.maxViewWithKey new of
Nothing -> depMap
Just ((currAddr, newRegs), rest) ->
let predAddrs = Map.findWithDefault [] currAddr predMap
(s', rest') = backPropagateOne depMap rest newRegs predAddrs
in backPropagate predMap s' rest'
mkDepLocMap :: forall arch
. OrdF (ArchReg arch)
=> BlockStartConstraints arch
-> MapF (BoundLoc (ArchReg arch)) (LocList (ArchReg arch))
mkDepLocMap cns =
let addNonRep :: MapF (BoundLoc (ArchReg arch)) (LocList (ArchReg arch))
-> BoundLoc (ArchReg arch) tp
-> InitInferValue arch tp
-> MapF (BoundLoc (ArchReg arch)) (LocList (ArchReg arch))
addNonRep m l (RegEqualLoc r) = MapF.insertWith (<>) r (LL [l]) m
addNonRep m _ _ = m
in foldLocMap addNonRep MapF.empty (bscLocMap cns)
mkBlockInvariants :: forall arch ids
. (HasRepr (ArchReg arch) TypeRepr
, OrdF (ArchReg arch)
, ShowF (ArchReg arch)
, MemWidth (ArchAddrWidth arch)
)
=> FunPredMap (ArchAddrWidth arch)
-> (ArchSegmentOff arch
-> ArchSegmentOff arch
-> PostValueMap arch ids)
-> ArchSegmentOff arch
-> BlockUsageSummary arch ids
-> DependencySet (ArchReg arch) ids
-> BlockInvariants arch ids
mkBlockInvariants predMap valueMap addr summary deps =
let cns = blockUsageStartConstraints summary
preds = Map.findWithDefault [] addr predMap
predFn predAddr = (predAddr, valueMap predAddr addr)
predphilist = predFn <$> preds
in BI { biUsedAssignSet = dsAssignSet deps
, biUsedWriteSet = dsWriteStmtIndexSet deps
, biMemAccessList = reverse (sisMemAccessStack (blockInferState summary))
, biLocMap = mkDepLocMap cns
, biPredPostValues = Map.fromList predphilist
, biPhiLocs = Set.toList (dsLocSet deps)
, biStartConstraints = cns
, biCallFunType = blockCallFunType summary
, biAssignMap = sisAssignMap (blockInferState summary)
}
type BlockInvariantMap arch ids
= Map (ArchSegmentOff arch) (BlockInvariants arch ids)
registerUse :: forall arch ids
. ArchConstraints arch
=> RegisterUseContext arch
-> DiscoveryFunInfo arch ids
-> Except (RegisterUseError arch)
(BlockInvariantMap arch ids)
registerUse rctx fun = do
let predMap = funBlockPreds fun
let blockMap = fun^.parsedBlocks
cnsMap <- inferStartConstraints rctx blockMap (discoveredFunAddr fun)
usageMap <- traverse (\(b, cns,s,_) -> mkBlockUsageSummary rctx cns s b) cnsMap
let bru :: BlockAddrMap (ArchReg arch) (DependencySet (ArchReg arch) ids)
bru = view blockExecDemands <$> usageMap
let providePair :: ArchSegmentOff arch -> (ArchSegmentOff arch, LocDependencyMap (ArchReg arch) ids)
providePair prev = (prev, lm)
where usage = case Map.lookup prev usageMap of
Nothing -> error "registerUse: Could not find prev"
Just usage' -> usage'
cns = blockUsageStartConstraints usage
cache = assignDeps usage
lm = LocMap { locMapRegs = rdmMap (blockRegDependencies usage)
, locMapStack =
fmapF (Const . inferStackValueDeps cns cache)
(sisStack (blockInferState usage))
}
let predProvideMap = fmap (fmap providePair) predMap
let propMap = backPropagate predProvideMap bru (dsLocSet <$> bru)
let phiValFn :: ArchSegmentOff arch -> ArchSegmentOff arch -> PostValueMap arch ids
phiValFn predAddr nextAddr =
case Map.lookup predAddr cnsMap of
Nothing -> error "Could not find predAddr"
Just (_,_,_,nextVals) -> Map.findWithDefault emptyPVM nextAddr nextVals
pure $ Map.intersectionWithKey (mkBlockInvariants predMap phiValFn) usageMap propMap
|
685347834a37e5d3620adec7704ff6286cebc1ecdfd9565d64553f828db6d892 | pkhuong/Napa-FFT | windowing.lisp | (in-package "NAPA-FFT")
Windowing code by
Originally part of Bordeaux - FFT , now dual - licensed as BSD
(defun rectangular (i n)
(declare (ignore i n))
1.0f0)
(defun hann (i n) (* 0.5 (- 1.0 (cos (/ (* 2 pi i) (1- n))))))
(defun blackman* (alpha i n)
(let ((a0 (/ (- 1 alpha) 2))
(a1 0.5)
(a2 (/ alpha 2)))
(+ a0
(- (* a1 (cos (/ (* 2 pi i) (1- n)))))
(* a2 (cos (/ (* 4 pi i) (1- n)))))))
(defun blackman (i n) (blackman* 0.16 i n))
(defun triangle (i n)
(* (/ 2 n) (- (* n 0.5) (abs (- i (* 0.5 (1- n)))))))
(defun bartlett (i n)
(* (/ 2 (1- n)) (- (* (1- n) 0.5) (abs (- i (* 0.5 (1- n)))))))
(defun gauss* (sigma i n)
(let (([n-1]/2 (* 0.5 (1- n))))
(exp (* -0.5 (expt (/ (- i [n-1]/2) (* sigma [n-1]/2)) 2)))))
(let ((cache (make-hash-table)))
(defun gaussian (sigma)
(or (gethash sigma cache)
(setf (gethash sigma cache)
(lambda (i n) (gauss* sigma i n))))))
(let ((cache (make-hash-table :test 'equal)))
(defun gaussian*bartlett^x (sigma triangle-exponent)
(or (gethash (list sigma triangle-exponent) cache)
(setf (gethash (list sigma triangle-exponent) cache)
(lambda (i n)
(* (realpart (expt (bartlett i n) triangle-exponent))
(gauss* sigma i n)))))))
(defun cosine-series (i n a0 a1 a2 a3)
(flet ((f (scale x) (* scale (cos (/ (* x pi i) (1- n))))))
(+ a0 (- (f a1 2)) (f a2 4) (- (f a3 6)))))
(defun blackman-harris (i n)
(cosine-series i n 0.35875f0 0.48829f0 0.14128f0 0.01168f0))
(let ((cache (make-hash-table :test 'equalp)))
(defun window-vector (function n)
(or (gethash (list function n) cache)
(setf (gethash (list function n) cache)
(let ((v (make-sequence '(simple-array double-float (*)) n)))
(dotimes (i n v)
(setf (aref v i)
(float (funcall function i n) 0.0d0))))))))
(defun clip-in-window (x start end) (max start (min x end)))
(defun extract-window-into (vector start length destination)
"Copy an extent of VECTOR to DESTINATION. Outside of its legal array
indices, VECTOR is considered to be zero."
(assert (<= length (length destination)))
(let ((start* (clip-in-window start 0 (length vector)))
(end* (clip-in-window (+ start length) 0 (length vector))))
(unless (= length (- end* start*))
(fill destination (coerce 0 (array-element-type destination))))
(when (< -1 (- start* start) (length destination))
(replace destination vector
:start1 (- start* start)
:end1 (+ (- start* start) (- end* start*))
:start2 start*
:end2 end*)))
destination)
(defun extract-window
(vector start length &optional (element-type (array-element-type vector)))
(extract-window-into
vector start length
(make-array length
:initial-element (coerce 0 element-type)
:element-type element-type
:adjustable nil
:fill-pointer nil)))
(defun extract-centered-window-into (vector center size destination)
"Extract a subsequence of SIZE from VECTOR, centered on OFFSET and
padding with zeros beyond the boundaries of the vector, storing it to
DESTINATION."
(extract-window-into vector (- center (floor size 2)) size destination))
(defun extract-centered-window
(vector center size &optional (element-type (array-element-type vector)))
"Extract a subsequence of SIZE from VECTOR, centered on CENTER and
padding with zeros beyond the edges of the vector."
(extract-centered-window-into
vector center size
(make-array size
:initial-element (coerce 0 element-type)
:element-type element-type
:adjustable nil
:fill-pointer nil)))
(defun convert-to-complex-sample-array (array)
(let ((output (make-array (length array)
:element-type 'complex-sample
:adjustable nil
:fill-pointer nil)))
(typecase array
((simple-array single-float 1)
(loop for index from 0 below (length array)
for x across array
do (setf (aref output index) (complex (float x 0.0d0) 0.0d0))))
((simple-array double-float 1)
(loop for index from 0 below (length array)
do (setf (aref output index) (complex (aref array index) 0.0d0))))
(t
(loop for index from 0 below (length array)
for x across array
do (setf (aref output index) (complex (float (realpart x) 0.0d0) 0.0d0)))))
output))
(defun windowed-fft (signal-vector center length &optional (window-fn 'hann))
"Perform an FFT on the window of a signal, centered on the given
index, multiplied by a window generated by the chosen window function"
(declare (type fixnum length)
(optimize (speed 3)))
(unless (power-of-two-p length)
(error "FFT size ~D is not a power of two" length))
(unless (typep signal-vector 'complex-sample-array)
(setf signal-vector (convert-to-complex-sample-array signal-vector)))
(let* ((input-window (extract-centered-window signal-vector center length))
(window (the (simple-array double-float 1)
(window-vector window-fn length))))
(declare (type complex-sample-array input-window))
(loop for index from 0 below length do
(setf (aref input-window index)
(* (aref input-window index)
(aref window index))))
(sfft input-window)))
| null | https://raw.githubusercontent.com/pkhuong/Napa-FFT/4a5ee157b5db8006e7a7bdbed47e23ad85bf184e/windowing.lisp | lisp | (in-package "NAPA-FFT")
Windowing code by
Originally part of Bordeaux - FFT , now dual - licensed as BSD
(defun rectangular (i n)
(declare (ignore i n))
1.0f0)
(defun hann (i n) (* 0.5 (- 1.0 (cos (/ (* 2 pi i) (1- n))))))
(defun blackman* (alpha i n)
(let ((a0 (/ (- 1 alpha) 2))
(a1 0.5)
(a2 (/ alpha 2)))
(+ a0
(- (* a1 (cos (/ (* 2 pi i) (1- n)))))
(* a2 (cos (/ (* 4 pi i) (1- n)))))))
(defun blackman (i n) (blackman* 0.16 i n))
(defun triangle (i n)
(* (/ 2 n) (- (* n 0.5) (abs (- i (* 0.5 (1- n)))))))
(defun bartlett (i n)
(* (/ 2 (1- n)) (- (* (1- n) 0.5) (abs (- i (* 0.5 (1- n)))))))
(defun gauss* (sigma i n)
(let (([n-1]/2 (* 0.5 (1- n))))
(exp (* -0.5 (expt (/ (- i [n-1]/2) (* sigma [n-1]/2)) 2)))))
(let ((cache (make-hash-table)))
(defun gaussian (sigma)
(or (gethash sigma cache)
(setf (gethash sigma cache)
(lambda (i n) (gauss* sigma i n))))))
(let ((cache (make-hash-table :test 'equal)))
(defun gaussian*bartlett^x (sigma triangle-exponent)
(or (gethash (list sigma triangle-exponent) cache)
(setf (gethash (list sigma triangle-exponent) cache)
(lambda (i n)
(* (realpart (expt (bartlett i n) triangle-exponent))
(gauss* sigma i n)))))))
(defun cosine-series (i n a0 a1 a2 a3)
(flet ((f (scale x) (* scale (cos (/ (* x pi i) (1- n))))))
(+ a0 (- (f a1 2)) (f a2 4) (- (f a3 6)))))
(defun blackman-harris (i n)
(cosine-series i n 0.35875f0 0.48829f0 0.14128f0 0.01168f0))
(let ((cache (make-hash-table :test 'equalp)))
(defun window-vector (function n)
(or (gethash (list function n) cache)
(setf (gethash (list function n) cache)
(let ((v (make-sequence '(simple-array double-float (*)) n)))
(dotimes (i n v)
(setf (aref v i)
(float (funcall function i n) 0.0d0))))))))
(defun clip-in-window (x start end) (max start (min x end)))
(defun extract-window-into (vector start length destination)
"Copy an extent of VECTOR to DESTINATION. Outside of its legal array
indices, VECTOR is considered to be zero."
(assert (<= length (length destination)))
(let ((start* (clip-in-window start 0 (length vector)))
(end* (clip-in-window (+ start length) 0 (length vector))))
(unless (= length (- end* start*))
(fill destination (coerce 0 (array-element-type destination))))
(when (< -1 (- start* start) (length destination))
(replace destination vector
:start1 (- start* start)
:end1 (+ (- start* start) (- end* start*))
:start2 start*
:end2 end*)))
destination)
(defun extract-window
(vector start length &optional (element-type (array-element-type vector)))
(extract-window-into
vector start length
(make-array length
:initial-element (coerce 0 element-type)
:element-type element-type
:adjustable nil
:fill-pointer nil)))
(defun extract-centered-window-into (vector center size destination)
"Extract a subsequence of SIZE from VECTOR, centered on OFFSET and
padding with zeros beyond the boundaries of the vector, storing it to
DESTINATION."
(extract-window-into vector (- center (floor size 2)) size destination))
(defun extract-centered-window
(vector center size &optional (element-type (array-element-type vector)))
"Extract a subsequence of SIZE from VECTOR, centered on CENTER and
padding with zeros beyond the edges of the vector."
(extract-centered-window-into
vector center size
(make-array size
:initial-element (coerce 0 element-type)
:element-type element-type
:adjustable nil
:fill-pointer nil)))
(defun convert-to-complex-sample-array (array)
(let ((output (make-array (length array)
:element-type 'complex-sample
:adjustable nil
:fill-pointer nil)))
(typecase array
((simple-array single-float 1)
(loop for index from 0 below (length array)
for x across array
do (setf (aref output index) (complex (float x 0.0d0) 0.0d0))))
((simple-array double-float 1)
(loop for index from 0 below (length array)
do (setf (aref output index) (complex (aref array index) 0.0d0))))
(t
(loop for index from 0 below (length array)
for x across array
do (setf (aref output index) (complex (float (realpart x) 0.0d0) 0.0d0)))))
output))
(defun windowed-fft (signal-vector center length &optional (window-fn 'hann))
"Perform an FFT on the window of a signal, centered on the given
index, multiplied by a window generated by the chosen window function"
(declare (type fixnum length)
(optimize (speed 3)))
(unless (power-of-two-p length)
(error "FFT size ~D is not a power of two" length))
(unless (typep signal-vector 'complex-sample-array)
(setf signal-vector (convert-to-complex-sample-array signal-vector)))
(let* ((input-window (extract-centered-window signal-vector center length))
(window (the (simple-array double-float 1)
(window-vector window-fn length))))
(declare (type complex-sample-array input-window))
(loop for index from 0 below length do
(setf (aref input-window index)
(* (aref input-window index)
(aref window index))))
(sfft input-window)))
| |
5d717d994994d61f58333aa19222d8f459572b9940330e19fd605771c99b5b38 | goodell/cppmem | xmlHttpRequest.ml | Js_of_ocaml library
* /
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser 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 .
* /
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*)
open Lwt
open Js
type readyState = UNSENT | OPENED | HEADERS_RECEIVED | LOADING | DONE
class type xmlHttpRequest = object ('self)
method onreadystatechange : (unit -> unit) Js.callback Js.writeonly_prop
method readyState : readyState readonly_prop
method _open :
js_string t -> js_string t -> bool t -> unit meth
method _open_full :
js_string t -> js_string t -> bool t ->
js_string t opt -> js_string t opt -> unit meth
method setRequestHeader : js_string t -> js_string t -> unit meth
method send : js_string t opt -> unit meth
method send_document : Dom.element Dom.document -> unit meth
method send_formData : Form.formData t -> unit meth
method abort : unit meth
method status : int readonly_prop
method statusText : js_string t readonly_prop
method getResponseHeader : js_string t -> js_string t opt meth
method getAllResponseHeaders : js_string t meth
method responseText : js_string t readonly_prop
method responseXML : Dom.element Dom.document t opt readonly_prop
method timeout : int writeonly_prop
inherit File.progressEventTarget
method ontimeout : ('self t, 'self File.progressEvent t) Dom.event_listener writeonly_prop
end
module Event = struct
type typ = xmlHttpRequest File.progressEvent t Dom.Event.typ
let readystatechange = Dom.Event.make "readystatechange"
let loadstart = Dom.Event.make "loadstart"
let progress = Dom.Event.make "progress"
let abort = Dom.Event.make "abort"
let error = Dom.Event.make "error"
let load = Dom.Event.make "load"
let timeout = Dom.Event.make "timeout"
let loadend = Dom.Event.make "loadend"
end
class type xmlHttpRequest_binary = object
inherit xmlHttpRequest
method sendAsBinary : js_string t opt -> unit meth
method sendAsBinary_presence : unit optdef readonly_prop
end
let xmlHttpRequest () : xmlHttpRequest t constr =
Js.Unsafe.variable "XMLHttpRequest"
let activeXObject () : (js_string t -> xmlHttpRequest t) constr =
Js.Unsafe.variable "ActiveXObject"
let create () =
try jsnew (xmlHttpRequest ()) () with _ ->
try jsnew (activeXObject ()) (Js.string "Msxml2.XMLHTTP") with _ ->
try jsnew (activeXObject ()) (Js.string "Msxml3.XMLHTTP") with _ ->
try jsnew (activeXObject ()) (Js.string "Microsoft.XMLHTTP") with _ ->
assert false
let encode = Url.encode_arguments
let encode_url args =
let args = List.map (fun (n,v) -> to_string n,to_string v) args in
string (Url.encode_arguments args)
let generateBoundary () =
let nine_digits () =
string_of_int (truncate (Js.to_float (Js.math##random()) *. 1000000000.))
in
"js_of_ocaml-------------------" ^ nine_digits () ^ nine_digits ()
(* TODO: test with elements = [] *)
let encode_multipart boundary elements =
let b = jsnew array_empty () in
(Lwt_list.iter_s
(fun v ->
ignore(b##push(Js.string ("--"^boundary^"\r\n")));
match v with
| name,`String value ->
ignore(b##push_3(Js.string ("Content-Disposition: form-data; name=\"" ^ name ^ "\"\r\n\r\n"),
value,
Js.string "\r\n"));
return ()
| name,`File value ->
File.readAsBinaryString (value :> File.blob Js.t)
>>= (fun file ->
ignore(b##push_4(Js.string ("Content-Disposition: form-data; name=\"" ^ name ^ "\"; filename=\""),
File.filename value,
Js.string "\"\r\n",
Js.string "Content-Type: application/octet-stream\r\n"));
ignore(b##push_3(Js.string "\r\n",
file,
Js.string "\r\n"));
return ())
)
elements)
>|= ( fun () -> ignore(b##push(Js.string ("--"^boundary^"--\r\n"))); b )
let encode_url l =
String.concat "&"
(List.map
(function
| name,`String s -> ((Url.urlencode name) ^ "=" ^ (Url.urlencode (to_string s)))
| name,`File s -> ((Url.urlencode name) ^ "=" ^ (Url.urlencode (to_string (s##name))))
) l)
let partition_string_file l = List.partition (function
| _,`String _ -> true
| _,`File _ -> false ) l
(* Higher level interface: *)
(** type of the http headers *)
type http_frame =
{
url: string;
code: int;
headers: string -> string option;
content: string;
content_xml: unit -> Dom.element Dom.document t option;
}
exception Wrong_headers of (int * (string -> string option))
let extract_get_param url =
let open Url in
match url_of_string url with
| Some (Http url) ->
Url.string_of_url (Http { url with hu_arguments = [] }),
url.hu_arguments
| Some (Https url) ->
Url.string_of_url (Https { url with hu_arguments = [] }),
url.hu_arguments
| _ -> url, []
let perform_raw_url
?(headers = [])
?content_type
?(post_args:(string * string) list option)
?(get_args=[])
?(form_arg:Form.form_contents option)
?(check_headers=(fun _ _ -> true))
?(timeout=None)
url =
let form_arg =
match form_arg with
| None ->
( match post_args with
| None -> None
| Some post_args ->
let contents = Form.empty_form_contents () in
List.iter (fun (name,value) -> Form.append contents (name,`String (string value))) post_args;
Some contents )
| Some form_arg ->
( match post_args with
| None -> ()
| Some post_args ->
List.iter (fun (name,value) -> Form.append form_arg (name,`String (string value))) post_args; );
Some form_arg
in
let method_, content_type, post_encode =
match form_arg, content_type with
| None, ct -> "GET", ct, `Urlencode
| Some form_args, None ->
(match form_args with
| `Fields l ->
let strings,files = partition_string_file !l in
(match files with
| [] -> "POST", (Some "application/x-www-form-urlencoded"), `Urlencode
| _ ->
let boundary = generateBoundary () in
"POST", (Some ("multipart/form-data; boundary="^boundary)), `Form_data (boundary))
| `FormData f -> "POST", None, `Urlencode)
| Some _, ct -> "POST", ct, `Urlencode
in
let url, url_get = extract_get_param url in
let url = match url_get@get_args with
| [] -> url
| _::_ as l -> url ^ "?" ^ encode l
in
let (res, w) = Lwt.task () in
let req = create () in
req##_open (Js.string method_, Js.string url, Js._true);
(match content_type with
| Some content_type ->
req##setRequestHeader (Js.string "Content-type", Js.string content_type)
| _ -> ());
List.iter (fun (n, v) -> req##setRequestHeader (Js.string n, Js.string v))
headers;
(match timeout with
| None -> ()
| Some (time, handler) ->
req##timeout <- time;
req##ontimeout <- handler);
let headers s =
Opt.case
(req##getResponseHeader (Js.bytestring s))
(fun () -> None)
(fun v -> Some (Js.to_string v))
in
let do_check_headers =
let checked = ref false in
fun () ->
if not (!checked) && not (check_headers (req##status) headers)
then begin
Lwt.wakeup_exn w (Wrong_headers ((req##status),headers));
req##abort ();
end;
checked := true
in
req##onreadystatechange <- Js.wrap_callback
(fun _ ->
(match req##readyState with
IE does n't have the same semantics for HEADERS_RECEIVED .
so we wait til LOADING to check headers . See :
-us/library/ms534361(v=vs.85).aspx
so we wait til LOADING to check headers. See:
-us/library/ms534361(v=vs.85).aspx *)
| HEADERS_RECEIVED when not Dom_html.onIE -> do_check_headers ()
| LOADING when Dom_html.onIE -> do_check_headers ()
| DONE ->
(* If we didn't catch a previous event, we check the header. *)
do_check_headers ();
Lwt.wakeup w
{url = url;
code = req##status;
content = Js.to_string req##responseText;
content_xml =
(fun () ->
match Js.Opt.to_option (req##responseXML) with
| None -> None
| Some doc ->
if (Js.some doc##documentElement) == Js.null
then None
else Some doc);
headers = headers
}
| _ -> ()));
(match form_arg with
| None -> req##send (Js.null)
| Some (`Fields l) ->
ignore (
match post_encode with
| `Urlencode -> req##send(Js.some (string (encode_url !l)));return ()
| `Form_data boundary ->
(encode_multipart boundary !l >|=
(fun data ->
let data = Js.some (data##join(Js.string "")) in
Firefox specific interface :
Chrome can use FormData : do n't need this
Chrome can use FormData: don't need this *)
let req = (Js.Unsafe.coerce req:xmlHttpRequest_binary t) in
if Optdef.test req##sendAsBinary_presence
then req##sendAsBinary(data)
else req##send(data))))
| Some (`FormData f) -> req##send_formData(f));
Lwt.on_cancel res (fun () -> req##abort ()) ;
res
let perform
?(headers = [])
?content_type
?post_args
?(get_args=[])
?form_arg
?check_headers
url =
perform_raw_url ~headers ?content_type ?post_args ~get_args ?form_arg ?check_headers
(Url.string_of_url url)
let get s = perform_raw_url s
| null | https://raw.githubusercontent.com/goodell/cppmem/eb3ce19b607a5d6ec81138cd8cacd236f9388e87/js_of_ocaml-1.2/lib/xmlHttpRequest.ml | ocaml | TODO: test with elements = []
Higher level interface:
* type of the http headers
If we didn't catch a previous event, we check the header. | Js_of_ocaml library
* /
* Copyright ( C ) 2010
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software ; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation , with linking exception ;
* either version 2.1 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 Lesser General Public License for more details .
*
* You should have received a copy of the GNU Lesser 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 .
* /
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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.
*)
open Lwt
open Js
type readyState = UNSENT | OPENED | HEADERS_RECEIVED | LOADING | DONE
class type xmlHttpRequest = object ('self)
method onreadystatechange : (unit -> unit) Js.callback Js.writeonly_prop
method readyState : readyState readonly_prop
method _open :
js_string t -> js_string t -> bool t -> unit meth
method _open_full :
js_string t -> js_string t -> bool t ->
js_string t opt -> js_string t opt -> unit meth
method setRequestHeader : js_string t -> js_string t -> unit meth
method send : js_string t opt -> unit meth
method send_document : Dom.element Dom.document -> unit meth
method send_formData : Form.formData t -> unit meth
method abort : unit meth
method status : int readonly_prop
method statusText : js_string t readonly_prop
method getResponseHeader : js_string t -> js_string t opt meth
method getAllResponseHeaders : js_string t meth
method responseText : js_string t readonly_prop
method responseXML : Dom.element Dom.document t opt readonly_prop
method timeout : int writeonly_prop
inherit File.progressEventTarget
method ontimeout : ('self t, 'self File.progressEvent t) Dom.event_listener writeonly_prop
end
module Event = struct
type typ = xmlHttpRequest File.progressEvent t Dom.Event.typ
let readystatechange = Dom.Event.make "readystatechange"
let loadstart = Dom.Event.make "loadstart"
let progress = Dom.Event.make "progress"
let abort = Dom.Event.make "abort"
let error = Dom.Event.make "error"
let load = Dom.Event.make "load"
let timeout = Dom.Event.make "timeout"
let loadend = Dom.Event.make "loadend"
end
class type xmlHttpRequest_binary = object
inherit xmlHttpRequest
method sendAsBinary : js_string t opt -> unit meth
method sendAsBinary_presence : unit optdef readonly_prop
end
let xmlHttpRequest () : xmlHttpRequest t constr =
Js.Unsafe.variable "XMLHttpRequest"
let activeXObject () : (js_string t -> xmlHttpRequest t) constr =
Js.Unsafe.variable "ActiveXObject"
let create () =
try jsnew (xmlHttpRequest ()) () with _ ->
try jsnew (activeXObject ()) (Js.string "Msxml2.XMLHTTP") with _ ->
try jsnew (activeXObject ()) (Js.string "Msxml3.XMLHTTP") with _ ->
try jsnew (activeXObject ()) (Js.string "Microsoft.XMLHTTP") with _ ->
assert false
let encode = Url.encode_arguments
let encode_url args =
let args = List.map (fun (n,v) -> to_string n,to_string v) args in
string (Url.encode_arguments args)
let generateBoundary () =
let nine_digits () =
string_of_int (truncate (Js.to_float (Js.math##random()) *. 1000000000.))
in
"js_of_ocaml-------------------" ^ nine_digits () ^ nine_digits ()
let encode_multipart boundary elements =
let b = jsnew array_empty () in
(Lwt_list.iter_s
(fun v ->
ignore(b##push(Js.string ("--"^boundary^"\r\n")));
match v with
| name,`String value ->
ignore(b##push_3(Js.string ("Content-Disposition: form-data; name=\"" ^ name ^ "\"\r\n\r\n"),
value,
Js.string "\r\n"));
return ()
| name,`File value ->
File.readAsBinaryString (value :> File.blob Js.t)
>>= (fun file ->
ignore(b##push_4(Js.string ("Content-Disposition: form-data; name=\"" ^ name ^ "\"; filename=\""),
File.filename value,
Js.string "\"\r\n",
Js.string "Content-Type: application/octet-stream\r\n"));
ignore(b##push_3(Js.string "\r\n",
file,
Js.string "\r\n"));
return ())
)
elements)
>|= ( fun () -> ignore(b##push(Js.string ("--"^boundary^"--\r\n"))); b )
let encode_url l =
String.concat "&"
(List.map
(function
| name,`String s -> ((Url.urlencode name) ^ "=" ^ (Url.urlencode (to_string s)))
| name,`File s -> ((Url.urlencode name) ^ "=" ^ (Url.urlencode (to_string (s##name))))
) l)
let partition_string_file l = List.partition (function
| _,`String _ -> true
| _,`File _ -> false ) l
type http_frame =
{
url: string;
code: int;
headers: string -> string option;
content: string;
content_xml: unit -> Dom.element Dom.document t option;
}
exception Wrong_headers of (int * (string -> string option))
let extract_get_param url =
let open Url in
match url_of_string url with
| Some (Http url) ->
Url.string_of_url (Http { url with hu_arguments = [] }),
url.hu_arguments
| Some (Https url) ->
Url.string_of_url (Https { url with hu_arguments = [] }),
url.hu_arguments
| _ -> url, []
let perform_raw_url
?(headers = [])
?content_type
?(post_args:(string * string) list option)
?(get_args=[])
?(form_arg:Form.form_contents option)
?(check_headers=(fun _ _ -> true))
?(timeout=None)
url =
let form_arg =
match form_arg with
| None ->
( match post_args with
| None -> None
| Some post_args ->
let contents = Form.empty_form_contents () in
List.iter (fun (name,value) -> Form.append contents (name,`String (string value))) post_args;
Some contents )
| Some form_arg ->
( match post_args with
| None -> ()
| Some post_args ->
List.iter (fun (name,value) -> Form.append form_arg (name,`String (string value))) post_args; );
Some form_arg
in
let method_, content_type, post_encode =
match form_arg, content_type with
| None, ct -> "GET", ct, `Urlencode
| Some form_args, None ->
(match form_args with
| `Fields l ->
let strings,files = partition_string_file !l in
(match files with
| [] -> "POST", (Some "application/x-www-form-urlencoded"), `Urlencode
| _ ->
let boundary = generateBoundary () in
"POST", (Some ("multipart/form-data; boundary="^boundary)), `Form_data (boundary))
| `FormData f -> "POST", None, `Urlencode)
| Some _, ct -> "POST", ct, `Urlencode
in
let url, url_get = extract_get_param url in
let url = match url_get@get_args with
| [] -> url
| _::_ as l -> url ^ "?" ^ encode l
in
let (res, w) = Lwt.task () in
let req = create () in
req##_open (Js.string method_, Js.string url, Js._true);
(match content_type with
| Some content_type ->
req##setRequestHeader (Js.string "Content-type", Js.string content_type)
| _ -> ());
List.iter (fun (n, v) -> req##setRequestHeader (Js.string n, Js.string v))
headers;
(match timeout with
| None -> ()
| Some (time, handler) ->
req##timeout <- time;
req##ontimeout <- handler);
let headers s =
Opt.case
(req##getResponseHeader (Js.bytestring s))
(fun () -> None)
(fun v -> Some (Js.to_string v))
in
let do_check_headers =
let checked = ref false in
fun () ->
if not (!checked) && not (check_headers (req##status) headers)
then begin
Lwt.wakeup_exn w (Wrong_headers ((req##status),headers));
req##abort ();
end;
checked := true
in
req##onreadystatechange <- Js.wrap_callback
(fun _ ->
(match req##readyState with
IE does n't have the same semantics for HEADERS_RECEIVED .
so we wait til LOADING to check headers . See :
-us/library/ms534361(v=vs.85).aspx
so we wait til LOADING to check headers. See:
-us/library/ms534361(v=vs.85).aspx *)
| HEADERS_RECEIVED when not Dom_html.onIE -> do_check_headers ()
| LOADING when Dom_html.onIE -> do_check_headers ()
| DONE ->
do_check_headers ();
Lwt.wakeup w
{url = url;
code = req##status;
content = Js.to_string req##responseText;
content_xml =
(fun () ->
match Js.Opt.to_option (req##responseXML) with
| None -> None
| Some doc ->
if (Js.some doc##documentElement) == Js.null
then None
else Some doc);
headers = headers
}
| _ -> ()));
(match form_arg with
| None -> req##send (Js.null)
| Some (`Fields l) ->
ignore (
match post_encode with
| `Urlencode -> req##send(Js.some (string (encode_url !l)));return ()
| `Form_data boundary ->
(encode_multipart boundary !l >|=
(fun data ->
let data = Js.some (data##join(Js.string "")) in
Firefox specific interface :
Chrome can use FormData : do n't need this
Chrome can use FormData: don't need this *)
let req = (Js.Unsafe.coerce req:xmlHttpRequest_binary t) in
if Optdef.test req##sendAsBinary_presence
then req##sendAsBinary(data)
else req##send(data))))
| Some (`FormData f) -> req##send_formData(f));
Lwt.on_cancel res (fun () -> req##abort ()) ;
res
let perform
?(headers = [])
?content_type
?post_args
?(get_args=[])
?form_arg
?check_headers
url =
perform_raw_url ~headers ?content_type ?post_args ~get_args ?form_arg ?check_headers
(Url.string_of_url url)
let get s = perform_raw_url s
|
5440d5e5e1f30de4f03c50a36bf78cea964b62e1d5ed485fd95f1b4d44d5babd | albertoruiz/easyVision | param2.hs | import EasyVision
import Graphics.UI.GLUT
import Control.Arrow
import Control.Applicative
camera' = camera ~> (grayscale >>> float)
data Param = Param { sigma :: Float, rad :: Int, thres :: Float }
main = run $ (camera' .&. userParam)
~> fst &&& corners
>>= monitor "corners" (mpSize 20) sh
corners (x,p) = gaussS (sigma p)
>>> gradients
>>> hessian
>>> fixscale
>>> thresholdVal32f (thres p) 0 IppCmpLess
>>> localMax (rad p)
>>> getPoints32f 100
$ x
fixscale im = (1/mn) .* im
where (mn,_) = EasyVision.minmax im
sh (im, pts) = do
drawImage im
pointSize $= 5; setColor 1 0 0
renderPrimitive Points $ mapM_ vertex pts
userParam = do
o <- createParameters [("sigma",realParam 3 0 20),
("rad" ,intParam 4 1 25),
("thres",realParam 0.6 0 1)]
return $ Param <$> getParam o "sigma"
<*> getParam o "rad"
<*> getParam o "thres"
| null | https://raw.githubusercontent.com/albertoruiz/easyVision/26bb2efaa676c902cecb12047560a09377a969f2/projects/old/tutorial/param2.hs | haskell | import EasyVision
import Graphics.UI.GLUT
import Control.Arrow
import Control.Applicative
camera' = camera ~> (grayscale >>> float)
data Param = Param { sigma :: Float, rad :: Int, thres :: Float }
main = run $ (camera' .&. userParam)
~> fst &&& corners
>>= monitor "corners" (mpSize 20) sh
corners (x,p) = gaussS (sigma p)
>>> gradients
>>> hessian
>>> fixscale
>>> thresholdVal32f (thres p) 0 IppCmpLess
>>> localMax (rad p)
>>> getPoints32f 100
$ x
fixscale im = (1/mn) .* im
where (mn,_) = EasyVision.minmax im
sh (im, pts) = do
drawImage im
pointSize $= 5; setColor 1 0 0
renderPrimitive Points $ mapM_ vertex pts
userParam = do
o <- createParameters [("sigma",realParam 3 0 20),
("rad" ,intParam 4 1 25),
("thres",realParam 0.6 0 1)]
return $ Param <$> getParam o "sigma"
<*> getParam o "rad"
<*> getParam o "thres"
| |
fa6ec62717cefdb228e1a5b0c0a9b55e697a62c3ad8b607e794e1042ce4f3496 | day8/re-frame-10x | views.cljs | (ns day8.re-frame-10x.panels.app-db.views
(:require-macros
[day8.re-frame-10x.components.re-com :refer [handler-fn]])
(:require
[clojure.data]
[devtools.prefs]
[devtools.formatters.core]
[day8.re-frame-10x.inlined-deps.garden.v1v3v10.garden.units :refer [px]]
[day8.re-frame-10x.inlined-deps.spade.git-sha-93ef290.core :refer [defclass]]
[day8.re-frame-10x.inlined-deps.re-frame.v1v1v2.re-frame.core :as rf]
[day8.re-frame-10x.components.buttons :as buttons]
[day8.re-frame-10x.components.cljs-devtools :as cljs-devtools]
[day8.re-frame-10x.components.hyperlinks :as hyperlinks]
[day8.re-frame-10x.components.re-com :as rc :refer [css-join]]
[day8.re-frame-10x.svgs :as svgs]
[day8.re-frame-10x.material :as material]
[day8.re-frame-10x.styles :as styles]
[day8.re-frame-10x.panels.settings.subs :as settings.subs]
[day8.re-frame-10x.panels.app-db.events :as app-db.events]
[day8.re-frame-10x.panels.app-db.subs :as app-db.subs]
[day8.re-frame-10x.panels.event.events :as event.events]
[day8.re-frame-10x.tools.coll :as tools.coll]
[day8.re-frame-10x.fx.clipboard :as clipboard]))
Overlap pods by 1px to avoid adjoining borders causing 2px borders
(def pod-padding "0px")
(defn path-inspector-button
[]
(let [ambiance @(rf/subscribe [::settings.subs/ambiance])
open-new-inspectors? @(rf/subscribe [::settings.subs/open-new-inspectors?])]
[rc/button
:class (styles/button ambiance)
:label [rc/h-box
:align :center
:children [[material/add
{:size styles/gs-19s}]
"path inspector"]]
:on-click #(rf/dispatch [::app-db.events/create-path open-new-inspectors?])]))
(defn panel-header []
[rc/h-box
:align :center
:gap "1"
:children [[path-inspector-button]
[buttons/icon
{:icon [material/content-copy]
:label "requires"
:title "Copy to the clipboard, the require form to set things up for the \"repl\" links below"
:on-click #(do (clipboard/copy! "(require '[day8.re-frame-10x.components.cljs-devtools])")
(rf/dispatch [::event.events/repl-msg-state :start]))}]]])
(defn data-path-annotations []
(let [render-path-annotations? @(rf/subscribe [::app-db.subs/data-path-annotations?])]
[rc/h-box
:align :center
:children [[rc/checkbox
:model render-path-annotations?
:label "data path annotations"
:on-change #(rf/dispatch [::app-db.events/set-data-path-annotations? %])]
[rc/gap-f :size styles/gs-7s]
[rc/box
:attr {:title "When ticked, you can right-click on the rendered data (below) to obtain path data \n and cause focus etc. But this feature comes with a performance hit on rendering which \n is proportional to the size/depth of app-db. So, if your app-db is large and you are \n noticing a delay/pause in rendering app-db, untick this option to get better performance."}
:child [hyperlinks/info]]]]))
(def pod-border-edge (str "1px solid " styles/nord4))
(defclass pod-header-section-style
[_ last?]
{:border-right (when-not last? [[(px 1) :solid styles/nord4]])
#_#_:padding-left (px 3)})
(defn pod-header-section
[& {:keys [size justify align gap width min-width children attr last?]
:or {size "none" justify :start align :center}}]
(let [ambiance @(rf/subscribe [::settings.subs/ambiance])]
[rc/h-box
:class (pod-header-section-style ambiance last?)
:size size
:justify justify
:align align
:gap gap
:width width
:min-width min-width
:height styles/gs-31s
:attr attr
:children children]))
(defn pod-header [{:keys [id path path-str open? diff? sort?]} data]
(let [ambiance @(rf/subscribe [::settings.subs/ambiance])
expand-all? @(rf/subscribe [::app-db.subs/expand-all? id])]
[rc/h-box
:class (styles/section-header ambiance)
:align :center
:height styles/gs-31s
:children
[[pod-header-section
:children
[[rc/box
:width "30px"
:height styles/gs-31s
:justify :center
:align :center
:class (styles/no-select)
:style {:cursor "pointer"}
:attr {:title (str (if open? "Close" "Open") " the pod bay doors, HAL")
:on-click (handler-fn (rf/dispatch [::app-db.events/set-path-visibility id (not open?)]))}
:child [buttons/expansion {:open? open?
:size styles/gs-31s}]]]]
[rc/h-box
:class (styles/path-header-style ambiance)
:size "auto"
:style {:height styles/gs-31s
:border-right pod-border-edge}
:align :center
:children
[[rc/input-text
:class (styles/path-text-input-style ambiance)
:attr {:on-blur #(rf/dispatch [::app-db.events/update-path-blur id])}
:width "100%"
:model path-str
:on-change #(rf/dispatch [::app-db.events/update-path id %]) ;;(fn [input-string] (rf/dispatch [:app-db/search-string input-string]))
:on-submit #() ;; #(rf/dispatch [::app-db.events/add-path %])
:change-on-blur? false
:placeholder "enter an app-db path like [:todos 1]"]]]
(when (> (count path) 0)
[buttons/icon
{:icon [material/clear]
:title "Clear path in current inspector"
:on-click #(rf/dispatch [::app-db.events/update-path id ""])}])
(when (> (count path) 0)
[rc/gap-f :size styles/gs-7s])
(when (> (count path) 0)
[buttons/icon
{:icon [material/arrow-drop-up]
:title "Open parent path in current inspector"
:on-click #(rf/dispatch [::app-db.events/update-path id (str (if (> (count path) 1) (pop path) ""))])}])
[pod-header-section
:width "49px"
:justify :center
:align :center
:attr {:on-click (handler-fn (rf/dispatch [::app-db.events/set-diff-visibility id (not diff?)]))}
:children
[[rc/checkbox
:model diff?
:label ""
#_#_:style {:margin-left "6px"
:margin-top "1px"}
:on-change #(rf/dispatch [::app-db.events/set-diff-visibility id (not diff?)])]]]
[pod-header-section
:width "49px"
:justify :center
:align :center
:attr {:on-click (handler-fn (rf/dispatch [::app-db.events/set-sort-form? id (not sort?)]))}
:children
[[rc/checkbox
:model sort?
:label ""
:on-change #(rf/dispatch [::app-db.events/set-sort-form? id (not sort?)])]]]
[pod-header-section
:width "49px"
:justify :center
:align :center
:attr {:on-click (handler-fn (rf/dispatch [::app-db.events/set-expand-all? id (not expand-all?)]))}
:children
[[buttons/icon {:icon [(if expand-all? material/unfold-less material/unfold-more)]
:title (str (if expand-all? "Close" "Expand") " all nodes in this inspector")
:on-click #(rf/dispatch [::app-db.events/set-expand-all? id (not expand-all?)])}]]]
[pod-header-section
:width styles/gs-50s
:justify :center
:children
[[buttons/icon
{:icon [material/close]
:title "Remove this inspector"
:on-click #(rf/dispatch [::app-db.events/remove-path id])}]]]
[pod-header-section
:width styles/gs-31s
:justify :center
:last? true
:children
[[rc/box
:style {:margin "auto"}
:child
[buttons/icon {:icon [material/print]
:title "Dump inspector data into DevTools"
:on-click #(js/console.log data)}]]]]]]))
(def diff-url "-frame-10x/blob/master/docs/HyperlinkedInformation/Diffs.md")
(defn pod [{:keys [id path open? diff? sort?] :as pod-info}]
(let [ambiance @(rf/subscribe [::settings.subs/ambiance])
render-diff? (and open? diff?)
app-db-after (rf/subscribe [::app-db.subs/current-epoch-app-db-after])
data (tools.coll/get-in-with-lists-and-sets @app-db-after path)]
[rc/v-box
:children
[[pod-header pod-info data]
[rc/v-box
:class (when open? (styles/pod-border ambiance))
:children
[(when open?
[rc/v-box
:class (styles/pod-data ambiance)
:style {:margin (css-join pod-padding pod-padding "0px" pod-padding)
:overflow-x "auto"
:overflow-y "hidden"}
:children
[[cljs-devtools/simple-render-with-path-annotations
data
["app-db-path" path]
{:path-id id
:update-path-fn [::app-db.events/update-path id]
:sort? sort?
:object @app-db-after}]]])
(when render-diff?
(let [app-db-before (rf/subscribe [::app-db.subs/current-epoch-app-db-before])
[diff-before diff-after _] (when render-diff?
(clojure.data/diff (get-in @app-db-before path)
(get-in @app-db-after path)))]
[rc/v-box
:children
[[rc/v-box
:class (styles/app-db-inspector-link ambiance)
:justify :end
:children
[[rc/hyperlink-href
:label "ONLY BEFORE"
:style {:margin-left styles/gs-7s}
:attr {:rel "noopener noreferrer"}
:target "_blank"
:href diff-url]]]
[rc/v-box
:style {:overflow-x "auto"
:overflow-y "hidden"}
:children
[[cljs-devtools/simple-render
diff-before
["app-db-diff" path]]]]
[rc/v-box
:class (styles/app-db-inspector-link ambiance)
:justify :end
:children
[[rc/hyperlink-href
;:class "app-db-path--label"
:label "ONLY AFTER"
:style {:margin-left styles/gs-7s}
:attr {:rel "noopener noreferrer"}
:target "_blank"
:href diff-url]]]
[rc/v-box
:style {:overflow-x "auto"
:overflow-y "hidden"}
:children
[[cljs-devtools/simple-render
diff-after
["app-db-diff" path]]]]]]))
(when open?
[rc/gap-f :size pod-padding])]]]]))
(defn no-pods []
[rc/h-box
:margin (css-join styles/gs-19s " 0px 0px 50px")
:gap styles/gs-12s
:align :start
:align-self :start
:children
[[svgs/round-arrow]
[rc/label
:style {:width "160px"
:margin-top "22px"}
:label "see the values in app-db by adding one or more inspectors"]]])
(defn pod-header-column-titles
[]
[rc/h-box
:height styles/gs-19s
:align :center
:children
[[rc/gap-f :size styles/gs-31s]
[rc/box
:size "1"
:height "31px"
:child ""]
[rc/box
:width styles/gs-50s ;; 50px + 1 border
:justify :center
:child [rc/label :style {:font-size "9px"} :label "DIFFS"]]
[rc/box
:width styles/gs-50s ;; 50px + 1 border
:justify :center
:child [rc/label :style {:font-size "9px"} :label "SORT"]]
[rc/box
:width styles/gs-50s ;; 50px + 1 border
:justify :center
:child [rc/label :style {:font-size "9px"} :label "EXPAND"]]
[rc/box
:width styles/gs-50s ;; 50px + 1 border
:justify :center
:child [rc/label :style {:font-size "9px"} :label "DELETE"]]
[rc/box
:width styles/gs-31s ;; 31px + 1 border
:justify :center
:child [rc/label :style {:font-size "9px"} :label ""]]
[rc/gap-f :size styles/gs-2s]
#_[rc/gap-f :size "6px"]]]) ;; Add extra space to look better when there is/aren't scrollbars
(defn pod-section []
(let [pods @(rf/subscribe [::app-db.subs/paths])]
[rc/v-box
:size "1"
:children
(into
[(if (empty? pods)
[no-pods]
[pod-header-column-titles])]
(for [p pods]
[:<>
[pod p]
[rc/gap-f :size styles/gs-12s]]))]))
(defclass panel-style
[]
{:margin-right styles/gs-5
:overflow :auto})
(defn panel [_]
[rc/v-box
:class (panel-style)
:size "1"
:children
[[data-path-annotations]
[rc/gap-f :size styles/gs-19s]
[panel-header]
[pod-section]
[rc/gap-f :size styles/gs-19s]]])
| null | https://raw.githubusercontent.com/day8/re-frame-10x/1a7ea3e65070648bf0aac54f3644938b6e1e2db8/src/day8/re_frame_10x/panels/app_db/views.cljs | clojure | (fn [input-string] (rf/dispatch [:app-db/search-string input-string]))
#(rf/dispatch [::app-db.events/add-path %])
:class "app-db-path--label"
50px + 1 border
50px + 1 border
50px + 1 border
50px + 1 border
31px + 1 border
Add extra space to look better when there is/aren't scrollbars | (ns day8.re-frame-10x.panels.app-db.views
(:require-macros
[day8.re-frame-10x.components.re-com :refer [handler-fn]])
(:require
[clojure.data]
[devtools.prefs]
[devtools.formatters.core]
[day8.re-frame-10x.inlined-deps.garden.v1v3v10.garden.units :refer [px]]
[day8.re-frame-10x.inlined-deps.spade.git-sha-93ef290.core :refer [defclass]]
[day8.re-frame-10x.inlined-deps.re-frame.v1v1v2.re-frame.core :as rf]
[day8.re-frame-10x.components.buttons :as buttons]
[day8.re-frame-10x.components.cljs-devtools :as cljs-devtools]
[day8.re-frame-10x.components.hyperlinks :as hyperlinks]
[day8.re-frame-10x.components.re-com :as rc :refer [css-join]]
[day8.re-frame-10x.svgs :as svgs]
[day8.re-frame-10x.material :as material]
[day8.re-frame-10x.styles :as styles]
[day8.re-frame-10x.panels.settings.subs :as settings.subs]
[day8.re-frame-10x.panels.app-db.events :as app-db.events]
[day8.re-frame-10x.panels.app-db.subs :as app-db.subs]
[day8.re-frame-10x.panels.event.events :as event.events]
[day8.re-frame-10x.tools.coll :as tools.coll]
[day8.re-frame-10x.fx.clipboard :as clipboard]))
Overlap pods by 1px to avoid adjoining borders causing 2px borders
(def pod-padding "0px")
(defn path-inspector-button
[]
(let [ambiance @(rf/subscribe [::settings.subs/ambiance])
open-new-inspectors? @(rf/subscribe [::settings.subs/open-new-inspectors?])]
[rc/button
:class (styles/button ambiance)
:label [rc/h-box
:align :center
:children [[material/add
{:size styles/gs-19s}]
"path inspector"]]
:on-click #(rf/dispatch [::app-db.events/create-path open-new-inspectors?])]))
(defn panel-header []
[rc/h-box
:align :center
:gap "1"
:children [[path-inspector-button]
[buttons/icon
{:icon [material/content-copy]
:label "requires"
:title "Copy to the clipboard, the require form to set things up for the \"repl\" links below"
:on-click #(do (clipboard/copy! "(require '[day8.re-frame-10x.components.cljs-devtools])")
(rf/dispatch [::event.events/repl-msg-state :start]))}]]])
(defn data-path-annotations []
(let [render-path-annotations? @(rf/subscribe [::app-db.subs/data-path-annotations?])]
[rc/h-box
:align :center
:children [[rc/checkbox
:model render-path-annotations?
:label "data path annotations"
:on-change #(rf/dispatch [::app-db.events/set-data-path-annotations? %])]
[rc/gap-f :size styles/gs-7s]
[rc/box
:attr {:title "When ticked, you can right-click on the rendered data (below) to obtain path data \n and cause focus etc. But this feature comes with a performance hit on rendering which \n is proportional to the size/depth of app-db. So, if your app-db is large and you are \n noticing a delay/pause in rendering app-db, untick this option to get better performance."}
:child [hyperlinks/info]]]]))
(def pod-border-edge (str "1px solid " styles/nord4))
(defclass pod-header-section-style
[_ last?]
{:border-right (when-not last? [[(px 1) :solid styles/nord4]])
#_#_:padding-left (px 3)})
(defn pod-header-section
[& {:keys [size justify align gap width min-width children attr last?]
:or {size "none" justify :start align :center}}]
(let [ambiance @(rf/subscribe [::settings.subs/ambiance])]
[rc/h-box
:class (pod-header-section-style ambiance last?)
:size size
:justify justify
:align align
:gap gap
:width width
:min-width min-width
:height styles/gs-31s
:attr attr
:children children]))
(defn pod-header [{:keys [id path path-str open? diff? sort?]} data]
(let [ambiance @(rf/subscribe [::settings.subs/ambiance])
expand-all? @(rf/subscribe [::app-db.subs/expand-all? id])]
[rc/h-box
:class (styles/section-header ambiance)
:align :center
:height styles/gs-31s
:children
[[pod-header-section
:children
[[rc/box
:width "30px"
:height styles/gs-31s
:justify :center
:align :center
:class (styles/no-select)
:style {:cursor "pointer"}
:attr {:title (str (if open? "Close" "Open") " the pod bay doors, HAL")
:on-click (handler-fn (rf/dispatch [::app-db.events/set-path-visibility id (not open?)]))}
:child [buttons/expansion {:open? open?
:size styles/gs-31s}]]]]
[rc/h-box
:class (styles/path-header-style ambiance)
:size "auto"
:style {:height styles/gs-31s
:border-right pod-border-edge}
:align :center
:children
[[rc/input-text
:class (styles/path-text-input-style ambiance)
:attr {:on-blur #(rf/dispatch [::app-db.events/update-path-blur id])}
:width "100%"
:model path-str
:change-on-blur? false
:placeholder "enter an app-db path like [:todos 1]"]]]
(when (> (count path) 0)
[buttons/icon
{:icon [material/clear]
:title "Clear path in current inspector"
:on-click #(rf/dispatch [::app-db.events/update-path id ""])}])
(when (> (count path) 0)
[rc/gap-f :size styles/gs-7s])
(when (> (count path) 0)
[buttons/icon
{:icon [material/arrow-drop-up]
:title "Open parent path in current inspector"
:on-click #(rf/dispatch [::app-db.events/update-path id (str (if (> (count path) 1) (pop path) ""))])}])
[pod-header-section
:width "49px"
:justify :center
:align :center
:attr {:on-click (handler-fn (rf/dispatch [::app-db.events/set-diff-visibility id (not diff?)]))}
:children
[[rc/checkbox
:model diff?
:label ""
#_#_:style {:margin-left "6px"
:margin-top "1px"}
:on-change #(rf/dispatch [::app-db.events/set-diff-visibility id (not diff?)])]]]
[pod-header-section
:width "49px"
:justify :center
:align :center
:attr {:on-click (handler-fn (rf/dispatch [::app-db.events/set-sort-form? id (not sort?)]))}
:children
[[rc/checkbox
:model sort?
:label ""
:on-change #(rf/dispatch [::app-db.events/set-sort-form? id (not sort?)])]]]
[pod-header-section
:width "49px"
:justify :center
:align :center
:attr {:on-click (handler-fn (rf/dispatch [::app-db.events/set-expand-all? id (not expand-all?)]))}
:children
[[buttons/icon {:icon [(if expand-all? material/unfold-less material/unfold-more)]
:title (str (if expand-all? "Close" "Expand") " all nodes in this inspector")
:on-click #(rf/dispatch [::app-db.events/set-expand-all? id (not expand-all?)])}]]]
[pod-header-section
:width styles/gs-50s
:justify :center
:children
[[buttons/icon
{:icon [material/close]
:title "Remove this inspector"
:on-click #(rf/dispatch [::app-db.events/remove-path id])}]]]
[pod-header-section
:width styles/gs-31s
:justify :center
:last? true
:children
[[rc/box
:style {:margin "auto"}
:child
[buttons/icon {:icon [material/print]
:title "Dump inspector data into DevTools"
:on-click #(js/console.log data)}]]]]]]))
(def diff-url "-frame-10x/blob/master/docs/HyperlinkedInformation/Diffs.md")
(defn pod [{:keys [id path open? diff? sort?] :as pod-info}]
(let [ambiance @(rf/subscribe [::settings.subs/ambiance])
render-diff? (and open? diff?)
app-db-after (rf/subscribe [::app-db.subs/current-epoch-app-db-after])
data (tools.coll/get-in-with-lists-and-sets @app-db-after path)]
[rc/v-box
:children
[[pod-header pod-info data]
[rc/v-box
:class (when open? (styles/pod-border ambiance))
:children
[(when open?
[rc/v-box
:class (styles/pod-data ambiance)
:style {:margin (css-join pod-padding pod-padding "0px" pod-padding)
:overflow-x "auto"
:overflow-y "hidden"}
:children
[[cljs-devtools/simple-render-with-path-annotations
data
["app-db-path" path]
{:path-id id
:update-path-fn [::app-db.events/update-path id]
:sort? sort?
:object @app-db-after}]]])
(when render-diff?
(let [app-db-before (rf/subscribe [::app-db.subs/current-epoch-app-db-before])
[diff-before diff-after _] (when render-diff?
(clojure.data/diff (get-in @app-db-before path)
(get-in @app-db-after path)))]
[rc/v-box
:children
[[rc/v-box
:class (styles/app-db-inspector-link ambiance)
:justify :end
:children
[[rc/hyperlink-href
:label "ONLY BEFORE"
:style {:margin-left styles/gs-7s}
:attr {:rel "noopener noreferrer"}
:target "_blank"
:href diff-url]]]
[rc/v-box
:style {:overflow-x "auto"
:overflow-y "hidden"}
:children
[[cljs-devtools/simple-render
diff-before
["app-db-diff" path]]]]
[rc/v-box
:class (styles/app-db-inspector-link ambiance)
:justify :end
:children
[[rc/hyperlink-href
:label "ONLY AFTER"
:style {:margin-left styles/gs-7s}
:attr {:rel "noopener noreferrer"}
:target "_blank"
:href diff-url]]]
[rc/v-box
:style {:overflow-x "auto"
:overflow-y "hidden"}
:children
[[cljs-devtools/simple-render
diff-after
["app-db-diff" path]]]]]]))
(when open?
[rc/gap-f :size pod-padding])]]]]))
(defn no-pods []
[rc/h-box
:margin (css-join styles/gs-19s " 0px 0px 50px")
:gap styles/gs-12s
:align :start
:align-self :start
:children
[[svgs/round-arrow]
[rc/label
:style {:width "160px"
:margin-top "22px"}
:label "see the values in app-db by adding one or more inspectors"]]])
(defn pod-header-column-titles
[]
[rc/h-box
:height styles/gs-19s
:align :center
:children
[[rc/gap-f :size styles/gs-31s]
[rc/box
:size "1"
:height "31px"
:child ""]
[rc/box
:justify :center
:child [rc/label :style {:font-size "9px"} :label "DIFFS"]]
[rc/box
:justify :center
:child [rc/label :style {:font-size "9px"} :label "SORT"]]
[rc/box
:justify :center
:child [rc/label :style {:font-size "9px"} :label "EXPAND"]]
[rc/box
:justify :center
:child [rc/label :style {:font-size "9px"} :label "DELETE"]]
[rc/box
:justify :center
:child [rc/label :style {:font-size "9px"} :label ""]]
[rc/gap-f :size styles/gs-2s]
(defn pod-section []
(let [pods @(rf/subscribe [::app-db.subs/paths])]
[rc/v-box
:size "1"
:children
(into
[(if (empty? pods)
[no-pods]
[pod-header-column-titles])]
(for [p pods]
[:<>
[pod p]
[rc/gap-f :size styles/gs-12s]]))]))
(defclass panel-style
[]
{:margin-right styles/gs-5
:overflow :auto})
(defn panel [_]
[rc/v-box
:class (panel-style)
:size "1"
:children
[[data-path-annotations]
[rc/gap-f :size styles/gs-19s]
[panel-header]
[pod-section]
[rc/gap-f :size styles/gs-19s]]])
|
fe09c44893e41fabd0f6d30d579231f6db1ce89a980e1854221269c550b8f829 | spechub/Hets | UndoRedo.hs | |
Module : ./CMDL / UndoRedo.hs
Description : description of undo and redo functions
Copyright : uni - bremen and DFKI
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
contains the implementation of the undo and redo commads
Module : ./CMDL/UndoRedo.hs
Description : description of undo and redo functions
Copyright : uni-bremen and DFKI
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
CMDL.UnDoRedo contains the implementation of the undo and redo commads
-}
module CMDL.UndoRedo
( cUndo
, cRedo
) where
import Interfaces.History (redoOneStep, undoOneStep)
import Interfaces.Command (showCmd)
import Interfaces.DataTypes
import CMDL.DataTypesUtils (genMessage)
import CMDL.DataTypes (CmdlState (intState))
-- | Undoes the last command entered
cUndo :: CmdlState -> IO CmdlState
cUndo = cdo True
-- | Redoes the last undo command
cRedo :: CmdlState -> IO CmdlState
cRedo = cdo False
cdo :: Bool -> CmdlState -> IO CmdlState
cdo isUndo state =
let msg = (if isUndo then "un" else "re") ++ "do"
in case (if isUndo then undoList else redoList) . i_hist $ intState state of
[] -> return $ genMessage [] ("Nothing to " ++ msg) state
action : _ ->
do
nwIntState <- (if isUndo then undoOneStep else redoOneStep)
$ intState state
return . genMessage [] ("Action '" ++ showCmd (command action)
++ "' is now " ++ msg ++ "ne")
$ state { intState = nwIntState }
| null | https://raw.githubusercontent.com/spechub/Hets/af7b628a75aab0d510b8ae7f067a5c9bc48d0f9e/CMDL/UndoRedo.hs | haskell | | Undoes the last command entered
| Redoes the last undo command | |
Module : ./CMDL / UndoRedo.hs
Description : description of undo and redo functions
Copyright : uni - bremen and DFKI
License : GPLv2 or higher , see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
contains the implementation of the undo and redo commads
Module : ./CMDL/UndoRedo.hs
Description : description of undo and redo functions
Copyright : uni-bremen and DFKI
License : GPLv2 or higher, see LICENSE.txt
Maintainer :
Stability : provisional
Portability : portable
CMDL.UnDoRedo contains the implementation of the undo and redo commads
-}
module CMDL.UndoRedo
( cUndo
, cRedo
) where
import Interfaces.History (redoOneStep, undoOneStep)
import Interfaces.Command (showCmd)
import Interfaces.DataTypes
import CMDL.DataTypesUtils (genMessage)
import CMDL.DataTypes (CmdlState (intState))
cUndo :: CmdlState -> IO CmdlState
cUndo = cdo True
cRedo :: CmdlState -> IO CmdlState
cRedo = cdo False
cdo :: Bool -> CmdlState -> IO CmdlState
cdo isUndo state =
let msg = (if isUndo then "un" else "re") ++ "do"
in case (if isUndo then undoList else redoList) . i_hist $ intState state of
[] -> return $ genMessage [] ("Nothing to " ++ msg) state
action : _ ->
do
nwIntState <- (if isUndo then undoOneStep else redoOneStep)
$ intState state
return . genMessage [] ("Action '" ++ showCmd (command action)
++ "' is now " ++ msg ++ "ne")
$ state { intState = nwIntState }
|
a1504b87c5d92386e8e26493a195b4b25c833a9e49b1ff423dfbf43555976e95 | fakedata-haskell/fakedata | CoffeeSpec.hs | {-# LANGUAGE OverloadedStrings #-}
# LANGUAGE ScopedTypeVariables #
module CoffeeSpec where
import Control.Monad.Catch
import Control.Monad.IO.Class
import qualified Data.Map as M
import Data.Text hiding (all, map)
import qualified Data.Text as T
import Data.Vector (Vector)
import qualified Data.Vector as V
import Faker hiding (defaultFakerSettings)
import Faker.Book.Dune
import Faker.Coffee
import Faker.Commerce
import Faker.Educator
import Faker.Game.Dota
import Faker.Internal
import Faker . Provider . Coffee
import qualified Faker.TvShow.DumbAndDumber as DD
import Test.Hspec
import TestImport
spec :: Spec
spec = do
describe "Coffee" $ do
-- it "Nested field" $ do
ctries < - coffeeRegionsBrazilProvider defaultFakerSettings
( V.toList ctries ) ` shouldBe ` [ " Sul Minas " , " " , " Cerrado " ]
it " Nested field ( via TH ) " $ do
-- ctries <- coffeeRegionsColombiaProvider defaultFakerSettings
( ctries ) ` shouldSatisfy ` ( \x - > V.length x > 3 )
it "random region" $ do
ctries <- generate regionsColombia
ctries `shouldBeOneOf` ["Santander", "Antioquia"]
it "brazil region (via TH)" $ do
ctries <- generate regionsBrazil
ctries `shouldBe` "Cerrado"
it "India region (via TH)" $ do
ctries <- generate regionsIndia
ctries `shouldBeOneOf` ["Sheveroys", "Travancore"]
describe "Commerce" $ do
it "Nested field" $ do
ctries <- generate productNameAdjective
ctries `shouldBeOneOf` ["Rustic", "Fantastic"]
describe "Dota" $ do
it "Nested field" $ do
ctries <- generate spiritBreakerQuote
ctries `shouldSatisfy` (\x -> T.length x > 5)
describe "Dune" $ do
it "Nested field" $ do
ctries <- generate quotesJessica
ctries `shouldSatisfy` (\x -> T.length x > 5)
describe "DumbAndDumber" $ do
it "Nested field" $ do
ctries <- generate DD.actors
ctries `shouldSatisfy` (\x -> T.length x > 5)
| null | https://raw.githubusercontent.com/fakedata-haskell/fakedata/4182ff14bb0aa8513ac30f5860506b3bb96482a0/test/CoffeeSpec.hs | haskell | # LANGUAGE OverloadedStrings #
it "Nested field" $ do
ctries <- coffeeRegionsColombiaProvider defaultFakerSettings | # LANGUAGE ScopedTypeVariables #
module CoffeeSpec where
import Control.Monad.Catch
import Control.Monad.IO.Class
import qualified Data.Map as M
import Data.Text hiding (all, map)
import qualified Data.Text as T
import Data.Vector (Vector)
import qualified Data.Vector as V
import Faker hiding (defaultFakerSettings)
import Faker.Book.Dune
import Faker.Coffee
import Faker.Commerce
import Faker.Educator
import Faker.Game.Dota
import Faker.Internal
import Faker . Provider . Coffee
import qualified Faker.TvShow.DumbAndDumber as DD
import Test.Hspec
import TestImport
spec :: Spec
spec = do
describe "Coffee" $ do
ctries < - coffeeRegionsBrazilProvider defaultFakerSettings
( V.toList ctries ) ` shouldBe ` [ " Sul Minas " , " " , " Cerrado " ]
it " Nested field ( via TH ) " $ do
( ctries ) ` shouldSatisfy ` ( \x - > V.length x > 3 )
it "random region" $ do
ctries <- generate regionsColombia
ctries `shouldBeOneOf` ["Santander", "Antioquia"]
it "brazil region (via TH)" $ do
ctries <- generate regionsBrazil
ctries `shouldBe` "Cerrado"
it "India region (via TH)" $ do
ctries <- generate regionsIndia
ctries `shouldBeOneOf` ["Sheveroys", "Travancore"]
describe "Commerce" $ do
it "Nested field" $ do
ctries <- generate productNameAdjective
ctries `shouldBeOneOf` ["Rustic", "Fantastic"]
describe "Dota" $ do
it "Nested field" $ do
ctries <- generate spiritBreakerQuote
ctries `shouldSatisfy` (\x -> T.length x > 5)
describe "Dune" $ do
it "Nested field" $ do
ctries <- generate quotesJessica
ctries `shouldSatisfy` (\x -> T.length x > 5)
describe "DumbAndDumber" $ do
it "Nested field" $ do
ctries <- generate DD.actors
ctries `shouldSatisfy` (\x -> T.length x > 5)
|
56b7a29995e7f910372912acd893d3bbe8255a57d7c5deae446781f26685df2e | jdsandifer/AutoLISP | PCO_COUNT.lsp |
;;;;;;;[ Post Call Out Counting ];;;;;;;;;;;;;;;
;; ;;
;; Counts post call-outs within a selected ;;
area based on 2 hard - coded block names . ; ;
;; ;;
;;::::::::::::::::::::::::::::::::::::::::::::::;;
;; ;;
Author : ( Copyright 2015 ) ; ;
;; Written: 10/28/2015 ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; ;;
;; 04/12/2016 - JD ;;
;; - Added cable tag text counting. ;;
;; - Both methods are in the main function ;;
;; right now. Comment the new one out if ;;
;; desired. ;;
;; ;;
;; 04/05/2016 - JD ;;
;; - Added cable tag counting (new block). ;;
;; - Changed name of print function so it ;;
;; could be used to neaten the results. ;;
;; - Moved sorting into the count function ;;
( for now ) . May move out later . ; ;
;; - Added a multiplier for cable runs to the ;;
;; print function (for now). ;;
;; - Added local variables to list. ;;
;; ;;
01/19/2016 - JD ; ;
;; - Removed shared helper functions. ;;
;; ;;
12/02/2015 - JD ; ;
;; - Added back "POST-DRILLED CALL-OUT" for ;;
;; residential demo. ;;
;; ;;
;; 11/17/2015 ;;
;; - Added option to choose block names. ;;
;; ;;
11/09/2015 ; ;
;; - Fixed ssget to use postCallOut ;;
;; correctly. ;;
- Changed ssget to use two block names - ; ;
postCallOut & postCallOut2 . ; ;
;; ;;
;; Todo: ;;
;; - Add options for names of blocks to ;;
;; count? ;;
;; ;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun c:pcocount (/ resultList postCallOut postCallOut2 postCallOut3
cableMultiplier layer1)
(setvar "cmdecho" 0) ; Turn off command line output
; Set block & layer names
(setq postCallOut "POST-DRILLED CALL-OUT")
(setq postCallOut2 "PICKET PANEL CALL-OUT")
(setq postCallOut3 "CABLE TAG")
(setq layer1 "Cable")
(setq cableMultiplier 13)
(DisplayCountTable (CountPostCallOuts))
(DisplayCountTable (CountCableTextLabels))
(setvar "cmdecho" 1) ; Command line back on
(princ) ) ; Hide last return value (clean exit)
CountPostCallOuts - Counts post call - out blocks within a user selection and returns an association list of ( labels . quantities ) .
;; no arguments - just local variables
(defun CountPostCallOuts (/ postList i blockSelSet key)
(setq blockSelSet (ssget (list '(0 . "INSERT")
'(-4 . "<or")
(cons 2 postCallOut)
(cons 2 postCallOut2)
(cons 2 postCallOut3)
'(-4 . "or>"))))
(setq i 0)
(while (< i (sslength blockSelSet))
(progn
(setq key (cdr (assoc 1 (entget (entnext (ssname blockSelSet i))) )) )
(setq postList (assoc++ key postList))
(setq i (1+ i)) ))
;this returns the list (after sorting it)
(OrderListAscending postList) )
CountPostCallOuts - Counts post call - out blocks within a user selection and returns an association list of ( labels . quantities ) .
;; no arguments - just local variables
(defun CountCableTextLabels ( / cableList index textSelSet key)
(setq textSelSet
(ssget
(list '(0 . "TEXT")
'(8 . "Cable"))))
(setq index 0)
(while (< index (sslength textSelSet))
(progn
(setq key
(cdr
(assoc 1
(entget
(ssname textSelSet index)))))
(setq cableList
(assoc++ key cableList))
(setq index
(1+ index))))
;this returns the list (after sorting it)
(OrderListAscending cableList))
;; DisplayCountTable - Displays the count list as a table: label then quantity
;; result - [association list] Labels paired with quantities.
(defun DisplayCountTable (result)
(princ "\n=#===Qty=\n")
(foreach item result
(progn
(princ " ")
(princ (car item))
(princ " . ")
(if (= (substr (car item) 1 3) "RUN")
(princ (* cableMultiplier (cdr item)))
(princ (cdr item)))
(princ "\n") ))
(princ "=========\n") )
(princ) ; Clean load
| null | https://raw.githubusercontent.com/jdsandifer/AutoLISP/054c8400fae84c223c3113e049a1ab87d374ba37/Old/PCO_COUNT.lsp | lisp | [ Post Call Out Counting ];;;;;;;;;;;;;;;
;;
Counts post call-outs within a selected ;;
;
;;
::::::::::::::::::::::::::::::::::::::::::::::;;
;;
;
Written: 10/28/2015 ;;
;;
;;
04/12/2016 - JD ;;
- Added cable tag text counting. ;;
- Both methods are in the main function ;;
right now. Comment the new one out if ;;
desired. ;;
;;
04/05/2016 - JD ;;
- Added cable tag counting (new block). ;;
- Changed name of print function so it ;;
could be used to neaten the results. ;;
- Moved sorting into the count function ;;
;
- Added a multiplier for cable runs to the ;;
print function (for now). ;;
- Added local variables to list. ;;
;;
;
- Removed shared helper functions. ;;
;;
;
- Added back "POST-DRILLED CALL-OUT" for ;;
residential demo. ;;
;;
11/17/2015 ;;
- Added option to choose block names. ;;
;;
;
- Fixed ssget to use postCallOut ;;
correctly. ;;
;
;
;;
Todo: ;;
- Add options for names of blocks to ;;
count? ;;
;;
Turn off command line output
Set block & layer names
Command line back on
Hide last return value (clean exit)
no arguments - just local variables
this returns the list (after sorting it)
no arguments - just local variables
this returns the list (after sorting it)
DisplayCountTable - Displays the count list as a table: label then quantity
result - [association list] Labels paired with quantities.
Clean load |
(defun c:pcocount (/ resultList postCallOut postCallOut2 postCallOut3
cableMultiplier layer1)
(setq postCallOut "POST-DRILLED CALL-OUT")
(setq postCallOut2 "PICKET PANEL CALL-OUT")
(setq postCallOut3 "CABLE TAG")
(setq layer1 "Cable")
(setq cableMultiplier 13)
(DisplayCountTable (CountPostCallOuts))
(DisplayCountTable (CountCableTextLabels))
CountPostCallOuts - Counts post call - out blocks within a user selection and returns an association list of ( labels . quantities ) .
(defun CountPostCallOuts (/ postList i blockSelSet key)
(setq blockSelSet (ssget (list '(0 . "INSERT")
'(-4 . "<or")
(cons 2 postCallOut)
(cons 2 postCallOut2)
(cons 2 postCallOut3)
'(-4 . "or>"))))
(setq i 0)
(while (< i (sslength blockSelSet))
(progn
(setq key (cdr (assoc 1 (entget (entnext (ssname blockSelSet i))) )) )
(setq postList (assoc++ key postList))
(setq i (1+ i)) ))
(OrderListAscending postList) )
CountPostCallOuts - Counts post call - out blocks within a user selection and returns an association list of ( labels . quantities ) .
(defun CountCableTextLabels ( / cableList index textSelSet key)
(setq textSelSet
(ssget
(list '(0 . "TEXT")
'(8 . "Cable"))))
(setq index 0)
(while (< index (sslength textSelSet))
(progn
(setq key
(cdr
(assoc 1
(entget
(ssname textSelSet index)))))
(setq cableList
(assoc++ key cableList))
(setq index
(1+ index))))
(OrderListAscending cableList))
(defun DisplayCountTable (result)
(princ "\n=#===Qty=\n")
(foreach item result
(progn
(princ " ")
(princ (car item))
(princ " . ")
(if (= (substr (car item) 1 3) "RUN")
(princ (* cableMultiplier (cdr item)))
(princ (cdr item)))
(princ "\n") ))
(princ "=========\n") )
|
977022b8b592cc91fa7f77598d2b14d83826368b80add5be98029eeb699e0142 | bobeff/playground | 009.rkt | Exercise 9 . Add the following line to the definitions area of :
;
; (define in ...)
;
; Then create an expression that converts the value of in to a non negative
; number.
- For a String , it determines how long the is .
; - For an Image, it uses the area.
; - For a Number, it takes its absolute value.
- For # true it uses 1 and for # false 0 .
#lang racket
(require 2htdp/image)
(include "../data/cat-image.rkt")
(define (abs-complex complex-number)
(sqrt (+ (sqr (real-part complex-number)) (sqr (imag-part complex-number)))))
(define (to-non-negative-number in)
(cond
((string? in) (string-length in))
((image? in) (* (image-width in) (image-height in)))
((number? in) (if (complex? in) (abs-complex in) (abs in)))
((boolean? in) (if in 1 0))))
(to-non-negative-number "")
(to-non-negative-number "Hello Dr. Racket.")
(to-non-negative-number cat)
(to-non-negative-number -13)
(to-non-negative-number 0)
(to-non-negative-number 42)
(to-non-negative-number 3+4i)
(to-non-negative-number #false)
(to-non-negative-number #true)
| null | https://raw.githubusercontent.com/bobeff/playground/7072dbd7e0acd690749abe1498dd5f247cc21637/htdp-second-edition/exercises/009.rkt | racket |
(define in ...)
Then create an expression that converts the value of in to a non negative
number.
- For an Image, it uses the area.
- For a Number, it takes its absolute value. | Exercise 9 . Add the following line to the definitions area of :
- For a String , it determines how long the is .
- For # true it uses 1 and for # false 0 .
#lang racket
(require 2htdp/image)
(include "../data/cat-image.rkt")
(define (abs-complex complex-number)
(sqrt (+ (sqr (real-part complex-number)) (sqr (imag-part complex-number)))))
(define (to-non-negative-number in)
(cond
((string? in) (string-length in))
((image? in) (* (image-width in) (image-height in)))
((number? in) (if (complex? in) (abs-complex in) (abs in)))
((boolean? in) (if in 1 0))))
(to-non-negative-number "")
(to-non-negative-number "Hello Dr. Racket.")
(to-non-negative-number cat)
(to-non-negative-number -13)
(to-non-negative-number 0)
(to-non-negative-number 42)
(to-non-negative-number 3+4i)
(to-non-negative-number #false)
(to-non-negative-number #true)
|
8f3d7ec3586ababf0154123ab72c57517b1cc6ca57a935d90f137b526d2f6bfd | haskell-suite/base | Base.hs | # LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude , MagicHash #
#ifdef __GLASGOW_HASKELL__
{-# LANGUAGE DeriveDataTypeable, StandaloneDeriving #-}
#endif
#include "Typeable.h"
-----------------------------------------------------------------------------
-- |
-- Module : Control.Exception.Base
Copyright : ( c ) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer :
-- Stability : experimental
-- Portability : non-portable (extended exceptions)
--
-- Extensible exceptions, except for multiple handlers.
--
-----------------------------------------------------------------------------
module Control.Exception.Base (
-- * The Exception type
#ifdef __HUGS__
SomeException,
#else
SomeException(..),
#endif
Exception(..),
IOException,
ArithException(..),
ArrayException(..),
AssertionFailed(..),
SomeAsyncException(..), AsyncException(..),
asyncExceptionToException, asyncExceptionFromException,
#if __GLASGOW_HASKELL__ || __HUGS__
NonTermination(..),
NestedAtomically(..),
#endif
BlockedIndefinitelyOnMVar(..),
BlockedIndefinitelyOnSTM(..),
Deadlock(..),
NoMethodError(..),
PatternMatchFail(..),
RecConError(..),
RecSelError(..),
RecUpdError(..),
ErrorCall(..),
-- * Throwing exceptions
throwIO,
throw,
ioError,
#ifdef __GLASGOW_HASKELL__
throwTo,
#endif
-- * Catching Exceptions
-- ** The @catch@ functions
catch,
catchJust,
-- ** The @handle@ functions
handle,
handleJust,
-- ** The @try@ functions
try,
tryJust,
onException,
-- ** The @evaluate@ function
evaluate,
-- ** The @mapException@ function
mapException,
-- * Asynchronous Exceptions
-- ** Asynchronous exception control
mask,
mask_,
uninterruptibleMask,
uninterruptibleMask_,
MaskingState(..),
getMaskingState,
-- ** (deprecated) Asynchronous exception control
block,
unblock,
blocked,
-- * Assertions
assert,
-- * Utilities
bracket,
bracket_,
bracketOnError,
finally,
#ifdef __GLASGOW_HASKELL__
* Calls for GHC runtime
recSelError, recConError, irrefutPatError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError,
nonTermination, nestedAtomically,
#endif
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.IO hiding (bracket,finally,onException)
import GHC.IO.Exception
import GHC.Exception
import GHC.Show
import GHC.Exception hiding ( Exception )
import GHC.Conc.Sync
#endif
#ifdef __HUGS__
import Prelude hiding (catch)
import Hugs.Prelude (ExitCode(..))
import Hugs.IOExts (unsafePerformIO)
import Hugs.Exception (SomeException(DynamicException, IOException,
ArithException, ArrayException, ExitException),
evaluate, IOException, ArithException, ArrayException)
import qualified Hugs.Exception
#endif
import Data.Dynamic
import Data.Either
import Data.Maybe
#ifdef __HUGS__
class (Typeable e, Show e) => Exception e where
toException :: e -> SomeException
fromException :: SomeException -> Maybe e
toException e = DynamicException (toDyn e) (flip showsPrec e)
fromException (DynamicException dyn _) = fromDynamic dyn
fromException _ = Nothing
INSTANCE_TYPEABLE0(SomeException,someExceptionTc,"SomeException")
INSTANCE_TYPEABLE0(IOException,iOExceptionTc,"IOException")
INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
INSTANCE_TYPEABLE0(ExitCode,exitCodeTc,"ExitCode")
INSTANCE_TYPEABLE0(ErrorCall,errorCallTc,"ErrorCall")
INSTANCE_TYPEABLE0(AssertionFailed,assertionFailedTc,"AssertionFailed")
INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
INSTANCE_TYPEABLE0(BlockedIndefinitelyOnMVar,blockedIndefinitelyOnMVarTc,"BlockedIndefinitelyOnMVar")
INSTANCE_TYPEABLE0(BlockedIndefinitelyOnSTM,blockedIndefinitelyOnSTM,"BlockedIndefinitelyOnSTM")
INSTANCE_TYPEABLE0(Deadlock,deadlockTc,"Deadlock")
instance Exception SomeException where
toException se = se
fromException = Just
instance Exception IOException where
toException = IOException
fromException (IOException e) = Just e
fromException _ = Nothing
instance Exception ArrayException where
toException = ArrayException
fromException (ArrayException e) = Just e
fromException _ = Nothing
instance Exception ArithException where
toException = ArithException
fromException (ArithException e) = Just e
fromException _ = Nothing
instance Exception ExitCode where
toException = ExitException
fromException (ExitException e) = Just e
fromException _ = Nothing
data ErrorCall = ErrorCall String
instance Show ErrorCall where
showsPrec _ (ErrorCall err) = showString err
instance Exception ErrorCall where
toException (ErrorCall s) = Hugs.Exception.ErrorCall s
fromException (Hugs.Exception.ErrorCall s) = Just (ErrorCall s)
fromException _ = Nothing
data BlockedIndefinitelyOnMVar = BlockedIndefinitelyOnMVar
data BlockedIndefinitelyOnSTM = BlockedIndefinitelyOnSTM
data Deadlock = Deadlock
data AssertionFailed = AssertionFailed String
data AsyncException
= StackOverflow
| HeapOverflow
| ThreadKilled
| UserInterrupt
deriving (Eq, Ord)
instance Show BlockedIndefinitelyOnMVar where
showsPrec _ BlockedIndefinitelyOnMVar = showString "thread blocked indefinitely"
instance Show BlockedIndefinitely where
showsPrec _ BlockedIndefinitely = showString "thread blocked indefinitely"
instance Show Deadlock where
showsPrec _ Deadlock = showString "<<deadlock>>"
instance Show AssertionFailed where
showsPrec _ (AssertionFailed err) = showString err
instance Show AsyncException where
showsPrec _ StackOverflow = showString "stack overflow"
showsPrec _ HeapOverflow = showString "heap overflow"
showsPrec _ ThreadKilled = showString "thread killed"
showsPrec _ UserInterrupt = showString "user interrupt"
instance Exception BlockedOnDeadMVar
instance Exception BlockedIndefinitely
instance Exception Deadlock
instance Exception AssertionFailed
instance Exception AsyncException
throw :: Exception e => e -> a
throw e = Hugs.Exception.throw (toException e)
throwIO :: Exception e => e -> IO a
throwIO e = Hugs.Exception.throwIO (toException e)
#endif
#ifndef __GLASGOW_HASKELL__
-- Dummy definitions for implementations lacking asynchonous exceptions
block :: IO a -> IO a
block = id
unblock :: IO a -> IO a
unblock = id
blocked :: IO Bool
blocked = return False
#endif
-----------------------------------------------------------------------------
-- Catching exceptions
-- |This is the simplest of the exception-catching functions. It
-- takes a single argument, runs it, and if an exception is raised
-- the \"handler\" is executed, with the value of the exception passed as an
-- argument. Otherwise, the result is returned as normal. For example:
--
-- > catch (readFile f)
-- > (\e -> do let err = show (e :: IOException)
-- > hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
-- > return "")
--
Note that we have to give a type signature to , or the program
will not as the type is ambiguous . While it is possible
-- to catch exceptions of any type, see the section \"Catching all
-- exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.
--
-- For catching exceptions in pure (non-'IO') expressions, see the
-- function 'evaluate'.
--
Note that due to Haskell\ 's unspecified evaluation order , an
expression may throw one of several possible exceptions : consider
the expression @(error \"urk\ " ) + ( 1 ` 0)@. Does
-- the expression throw
-- @ErrorCall \"urk\"@, or @DivideByZero@?
--
-- The answer is \"it might throw either\"; the choice is
-- non-deterministic. If you are catching any type of exception then you
-- might catch either. If you are calling @catch@ with type
-- @IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may
-- get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@
-- exception may be propogated further up. If you call it again, you
-- might get a the opposite behaviour. This is ok, because 'catch' is an
-- 'IO' computation.
--
catch :: Exception e
=> IO a -- ^ The computation to run
-> (e -> IO a) -- ^ Handler to invoke if an exception is raised
-> IO a
#if __GLASGOW_HASKELL__
catch = catchException
#elif __HUGS__
catch m h = Hugs.Exception.catchException m h'
where h' e = case fromException e of
Just e' -> h e'
Nothing -> throwIO e
#endif
-- | The function 'catchJust' is like 'catch', but it takes an extra
-- argument which is an /exception predicate/, a function which
-- selects which type of exceptions we\'re interested in.
--
-- > catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
-- > (readFile f)
-- > (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
-- > return "")
--
-- Any other exceptions which are not matched by the predicate
-- are re-raised, and may be caught by an enclosing
-- 'catch', 'catchJust', etc.
catchJust
:: Exception e
=> (e -> Maybe b) -- ^ Predicate to select exceptions
-> IO a -- ^ Computation to run
-> (b -> IO a) -- ^ Handler
-> IO a
catchJust p a handler = catch a handler'
where handler' e = case p e of
Nothing -> throwIO e
Just b -> handler b
-- | A version of 'catch' with the arguments swapped around; useful in
-- situations where the code for the handler is shorter. For example:
--
> do handle ( \NonTermination - > exitWith ( ExitFailure 1 ) ) $
-- > ...
handle :: Exception e => (e -> IO a) -> IO a -> IO a
handle = flip catch
-- | A version of 'catchJust' with the arguments swapped around (see
-- 'handle').
handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
handleJust p = flip (catchJust p)
-----------------------------------------------------------------------------
' mapException '
| This function maps one exception into another as proposed in the
-- paper \"A semantics for imprecise exceptions\".
-- Notice that the usage of 'unsafePerformIO' is safe here.
mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
mapException f v = unsafePerformIO (catch (evaluate v)
(\x -> throwIO (f x)))
-----------------------------------------------------------------------------
-- 'try' and variations.
-- | Similar to 'catch', but returns an 'Either' result which is
' a)@ if no exception of type was raised , or @('Left ' ex)@
if an exception of type was raised and its value is @ex@.
-- If any other type of exception is raised than it will be propogated
-- up to the next enclosing exception handler.
--
-- > try a = catch (Right `liftM` a) (return . Left)
try :: Exception e => IO a -> IO (Either e a)
try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
-- | A variant of 'try' that takes an exception predicate to select
which exceptions are caught ( c.f . ' catchJust ' ) . If the exception
-- does not match the predicate, it is re-thrown.
tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
tryJust p a = do
r <- try a
case r of
Right v -> return (Right v)
Left e -> case p e of
Nothing -> throwIO e
Just b -> return (Left b)
-- | Like 'finally', but only performs the final action if there was an
-- exception raised by the computation.
onException :: IO a -> IO b -> IO a
onException io what = io `catch` \e -> do _ <- what
throwIO (e :: SomeException)
-----------------------------------------------------------------------------
-- Some Useful Functions
-- | When you want to acquire a resource, do some work with it, and
-- then release the resource, it is a good idea to use 'bracket',
-- because 'bracket' will install the necessary exception handler to
-- release the resource in the event that an exception is raised
-- during the computation. If an exception is raised, then 'bracket' will
-- re-raise the exception (after performing the release).
--
-- A common example is opening a file:
--
-- > bracket
-- > (openFile "filename" ReadMode)
> ( )
-- > (\fileHandle -> do { ... })
--
-- The arguments to 'bracket' are in this order so that we can partially apply
-- it, e.g.:
--
-- > withFile name mode = bracket (openFile name mode) hClose
--
bracket
^ computation to run first ( \"acquire resource\ " )
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracket before after thing =
mask $ \restore -> do
a <- before
r <- restore (thing a) `onException` after a
_ <- after a
return r
-- | A specialised variant of 'bracket' with just a computation to run
-- afterward.
--
^ computation to run first
-> IO b -- ^ computation to run afterward (even if an exception
-- was raised)
returns the value from the first computation
a `finally` sequel =
mask $ \restore -> do
r <- restore a `onException` sequel
_ <- sequel
return r
| A variant of ' bracket ' where the return value from the first computation
-- is not required.
bracket_ :: IO a -> IO b -> IO c -> IO c
bracket_ before after thing = bracket before (const after) (const thing)
-- | Like 'bracket', but only performs the final action if there was an
-- exception raised by the in-between computation.
bracketOnError
^ computation to run first ( \"acquire resource\ " )
-> (a -> IO b) -- ^ computation to run last (\"release resource\")
-> (a -> IO c) -- ^ computation to run in-between
-> IO c -- returns the value from the in-between computation
bracketOnError before after thing =
mask $ \restore -> do
a <- before
restore (thing a) `onException` after a
#if !__GLASGOW_HASKELL__
assert :: Bool -> a -> a
assert True x = x
assert False _ = throw (AssertionFailed "")
#endif
-----
#if __GLASGOW_HASKELL__ || __HUGS__
-- |A pattern match failed. The @String@ gives information about the
-- source location of the pattern.
data PatternMatchFail = PatternMatchFail String
INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
instance Show PatternMatchFail where
showsPrec _ (PatternMatchFail err) = showString err
#ifdef __HUGS__
instance Exception PatternMatchFail where
toException (PatternMatchFail err) = Hugs.Exception.PatternMatchFail err
fromException (Hugs.Exception.PatternMatchFail err) = Just (PatternMatchFail err)
fromException _ = Nothing
#else
instance Exception PatternMatchFail
#endif
-----
-- |A record selector was applied to a constructor without the
-- appropriate field. This can only happen with a datatype with
multiple constructors , where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record selector.
data RecSelError = RecSelError String
INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
instance Show RecSelError where
showsPrec _ (RecSelError err) = showString err
#ifdef __HUGS__
instance Exception RecSelError where
toException (RecSelError err) = Hugs.Exception.RecSelError err
fromException (Hugs.Exception.RecSelError err) = Just (RecSelError err)
fromException _ = Nothing
#else
instance Exception RecSelError
#endif
-----
|An uninitialised record field was used . The @String@ gives
-- information about the source location where the record was
-- constructed.
data RecConError = RecConError String
INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
instance Show RecConError where
showsPrec _ (RecConError err) = showString err
#ifdef __HUGS__
instance Exception RecConError where
toException (RecConError err) = Hugs.Exception.RecConError err
fromException (Hugs.Exception.RecConError err) = Just (RecConError err)
fromException _ = Nothing
#else
instance Exception RecConError
#endif
-----
-- |A record update was performed on a constructor without the
-- appropriate field. This can only happen with a datatype with
multiple constructors , where some fields are in one constructor
-- but not another. The @String@ gives information about the source
-- location of the record update.
data RecUpdError = RecUpdError String
INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
instance Show RecUpdError where
showsPrec _ (RecUpdError err) = showString err
#ifdef __HUGS__
instance Exception RecUpdError where
toException (RecUpdError err) = Hugs.Exception.RecUpdError err
fromException (Hugs.Exception.RecUpdError err) = Just (RecUpdError err)
fromException _ = Nothing
#else
instance Exception RecUpdError
#endif
-----
-- |A class method without a definition (neither a default definition,
-- nor a definition in the appropriate instance) was called. The
-- @String@ gives information about which method it was.
data NoMethodError = NoMethodError String
INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
instance Show NoMethodError where
showsPrec _ (NoMethodError err) = showString err
#ifdef __HUGS__
instance Exception NoMethodError where
toException (NoMethodError err) = Hugs.Exception.NoMethodError err
fromException (Hugs.Exception.NoMethodError err) = Just (NoMethodError err)
fromException _ = Nothing
#else
instance Exception NoMethodError
#endif
-----
-- |Thrown when the runtime system detects that the computation is
-- guaranteed not to terminate. Note that there is no guarantee that
-- the runtime system will notice whether any given computation is
-- guaranteed to terminate or not.
data NonTermination = NonTermination
INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
instance Show NonTermination where
showsPrec _ NonTermination = showString "<<loop>>"
#ifdef __HUGS__
instance Exception NonTermination where
toException NonTermination = Hugs.Exception.NonTermination
fromException Hugs.Exception.NonTermination = Just NonTermination
fromException _ = Nothing
#else
instance Exception NonTermination
#endif
-----
-- |Thrown when the program attempts to call @atomically@, from the @stm@
package , inside another call to @atomically@.
data NestedAtomically = NestedAtomically
INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
instance Show NestedAtomically where
showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
instance Exception NestedAtomically
-----
#endif /* __GLASGOW_HASKELL__ || __HUGS__ */
#ifdef __GLASGOW_HASKELL__
recSelError, recConError, irrefutPatError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError
:: Addr# -> a -- All take a UTF8-encoded C string
recSelError s = throw (RecSelError ("No match in record selector "
++ unpackCStringUtf8# s)) -- No location info unfortunately
runtimeError s = error (unpackCStringUtf8# s) -- No location info unfortunately
absentError s = error ("Oops! Entered absent arg " ++ unpackCStringUtf8# s)
nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
recConError s = throw (RecConError (untangle s "Missing field in record construction"))
noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
GHC 's RTS calls this
nonTermination :: SomeException
nonTermination = toException NonTermination
GHC 's RTS calls this
nestedAtomically :: SomeException
nestedAtomically = toException NestedAtomically
#endif
| null | https://raw.githubusercontent.com/haskell-suite/base/1ee14681910c76d0a5a436c33ecf3289443e65ed/Control/Exception/Base.hs | haskell | # LANGUAGE DeriveDataTypeable, StandaloneDeriving #
---------------------------------------------------------------------------
|
Module : Control.Exception.Base
License : BSD-style (see the file libraries/base/LICENSE)
Maintainer :
Stability : experimental
Portability : non-portable (extended exceptions)
Extensible exceptions, except for multiple handlers.
---------------------------------------------------------------------------
* The Exception type
* Throwing exceptions
* Catching Exceptions
** The @catch@ functions
** The @handle@ functions
** The @try@ functions
** The @evaluate@ function
** The @mapException@ function
* Asynchronous Exceptions
** Asynchronous exception control
** (deprecated) Asynchronous exception control
* Assertions
* Utilities
Dummy definitions for implementations lacking asynchonous exceptions
---------------------------------------------------------------------------
Catching exceptions
|This is the simplest of the exception-catching functions. It
takes a single argument, runs it, and if an exception is raised
the \"handler\" is executed, with the value of the exception passed as an
argument. Otherwise, the result is returned as normal. For example:
> catch (readFile f)
> (\e -> do let err = show (e :: IOException)
> hPutStr stderr ("Warning: Couldn't open " ++ f ++ ": " ++ err)
> return "")
to catch exceptions of any type, see the section \"Catching all
exceptions\" (in "Control.Exception") for an explanation of the problems with doing so.
For catching exceptions in pure (non-'IO') expressions, see the
function 'evaluate'.
the expression throw
@ErrorCall \"urk\"@, or @DivideByZero@?
The answer is \"it might throw either\"; the choice is
non-deterministic. If you are catching any type of exception then you
might catch either. If you are calling @catch@ with type
@IO Int -> (ArithException -> IO Int) -> IO Int@ then the handler may
get run with @DivideByZero@ as an argument, or an @ErrorCall \"urk\"@
exception may be propogated further up. If you call it again, you
might get a the opposite behaviour. This is ok, because 'catch' is an
'IO' computation.
^ The computation to run
^ Handler to invoke if an exception is raised
| The function 'catchJust' is like 'catch', but it takes an extra
argument which is an /exception predicate/, a function which
selects which type of exceptions we\'re interested in.
> catchJust (\e -> if isDoesNotExistErrorType (ioeGetErrorType e) then Just () else Nothing)
> (readFile f)
> (\_ -> do hPutStrLn stderr ("No such file: " ++ show f)
> return "")
Any other exceptions which are not matched by the predicate
are re-raised, and may be caught by an enclosing
'catch', 'catchJust', etc.
^ Predicate to select exceptions
^ Computation to run
^ Handler
| A version of 'catch' with the arguments swapped around; useful in
situations where the code for the handler is shorter. For example:
> ...
| A version of 'catchJust' with the arguments swapped around (see
'handle').
---------------------------------------------------------------------------
paper \"A semantics for imprecise exceptions\".
Notice that the usage of 'unsafePerformIO' is safe here.
---------------------------------------------------------------------------
'try' and variations.
| Similar to 'catch', but returns an 'Either' result which is
If any other type of exception is raised than it will be propogated
up to the next enclosing exception handler.
> try a = catch (Right `liftM` a) (return . Left)
| A variant of 'try' that takes an exception predicate to select
does not match the predicate, it is re-thrown.
| Like 'finally', but only performs the final action if there was an
exception raised by the computation.
---------------------------------------------------------------------------
Some Useful Functions
| When you want to acquire a resource, do some work with it, and
then release the resource, it is a good idea to use 'bracket',
because 'bracket' will install the necessary exception handler to
release the resource in the event that an exception is raised
during the computation. If an exception is raised, then 'bracket' will
re-raise the exception (after performing the release).
A common example is opening a file:
> bracket
> (openFile "filename" ReadMode)
> (\fileHandle -> do { ... })
The arguments to 'bracket' are in this order so that we can partially apply
it, e.g.:
> withFile name mode = bracket (openFile name mode) hClose
^ computation to run last (\"release resource\")
^ computation to run in-between
returns the value from the in-between computation
| A specialised variant of 'bracket' with just a computation to run
afterward.
^ computation to run afterward (even if an exception
was raised)
is not required.
| Like 'bracket', but only performs the final action if there was an
exception raised by the in-between computation.
^ computation to run last (\"release resource\")
^ computation to run in-between
returns the value from the in-between computation
---
|A pattern match failed. The @String@ gives information about the
source location of the pattern.
---
|A record selector was applied to a constructor without the
appropriate field. This can only happen with a datatype with
but not another. The @String@ gives information about the source
location of the record selector.
---
information about the source location where the record was
constructed.
---
|A record update was performed on a constructor without the
appropriate field. This can only happen with a datatype with
but not another. The @String@ gives information about the source
location of the record update.
---
|A class method without a definition (neither a default definition,
nor a definition in the appropriate instance) was called. The
@String@ gives information about which method it was.
---
|Thrown when the runtime system detects that the computation is
guaranteed not to terminate. Note that there is no guarantee that
the runtime system will notice whether any given computation is
guaranteed to terminate or not.
---
|Thrown when the program attempts to call @atomically@, from the @stm@
---
All take a UTF8-encoded C string
No location info unfortunately
No location info unfortunately | # LANGUAGE Trustworthy #
# LANGUAGE CPP , NoImplicitPrelude , MagicHash #
#ifdef __GLASGOW_HASKELL__
#endif
#include "Typeable.h"
Copyright : ( c ) The University of Glasgow 2001
module Control.Exception.Base (
#ifdef __HUGS__
SomeException,
#else
SomeException(..),
#endif
Exception(..),
IOException,
ArithException(..),
ArrayException(..),
AssertionFailed(..),
SomeAsyncException(..), AsyncException(..),
asyncExceptionToException, asyncExceptionFromException,
#if __GLASGOW_HASKELL__ || __HUGS__
NonTermination(..),
NestedAtomically(..),
#endif
BlockedIndefinitelyOnMVar(..),
BlockedIndefinitelyOnSTM(..),
Deadlock(..),
NoMethodError(..),
PatternMatchFail(..),
RecConError(..),
RecSelError(..),
RecUpdError(..),
ErrorCall(..),
throwIO,
throw,
ioError,
#ifdef __GLASGOW_HASKELL__
throwTo,
#endif
catch,
catchJust,
handle,
handleJust,
try,
tryJust,
onException,
evaluate,
mapException,
mask,
mask_,
uninterruptibleMask,
uninterruptibleMask_,
MaskingState(..),
getMaskingState,
block,
unblock,
blocked,
assert,
bracket,
bracket_,
bracketOnError,
finally,
#ifdef __GLASGOW_HASKELL__
* Calls for GHC runtime
recSelError, recConError, irrefutPatError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError,
nonTermination, nestedAtomically,
#endif
) where
#ifdef __GLASGOW_HASKELL__
import GHC.Base
import GHC.IO hiding (bracket,finally,onException)
import GHC.IO.Exception
import GHC.Exception
import GHC.Show
import GHC.Exception hiding ( Exception )
import GHC.Conc.Sync
#endif
#ifdef __HUGS__
import Prelude hiding (catch)
import Hugs.Prelude (ExitCode(..))
import Hugs.IOExts (unsafePerformIO)
import Hugs.Exception (SomeException(DynamicException, IOException,
ArithException, ArrayException, ExitException),
evaluate, IOException, ArithException, ArrayException)
import qualified Hugs.Exception
#endif
import Data.Dynamic
import Data.Either
import Data.Maybe
#ifdef __HUGS__
class (Typeable e, Show e) => Exception e where
toException :: e -> SomeException
fromException :: SomeException -> Maybe e
toException e = DynamicException (toDyn e) (flip showsPrec e)
fromException (DynamicException dyn _) = fromDynamic dyn
fromException _ = Nothing
INSTANCE_TYPEABLE0(SomeException,someExceptionTc,"SomeException")
INSTANCE_TYPEABLE0(IOException,iOExceptionTc,"IOException")
INSTANCE_TYPEABLE0(ArithException,arithExceptionTc,"ArithException")
INSTANCE_TYPEABLE0(ArrayException,arrayExceptionTc,"ArrayException")
INSTANCE_TYPEABLE0(ExitCode,exitCodeTc,"ExitCode")
INSTANCE_TYPEABLE0(ErrorCall,errorCallTc,"ErrorCall")
INSTANCE_TYPEABLE0(AssertionFailed,assertionFailedTc,"AssertionFailed")
INSTANCE_TYPEABLE0(AsyncException,asyncExceptionTc,"AsyncException")
INSTANCE_TYPEABLE0(BlockedIndefinitelyOnMVar,blockedIndefinitelyOnMVarTc,"BlockedIndefinitelyOnMVar")
INSTANCE_TYPEABLE0(BlockedIndefinitelyOnSTM,blockedIndefinitelyOnSTM,"BlockedIndefinitelyOnSTM")
INSTANCE_TYPEABLE0(Deadlock,deadlockTc,"Deadlock")
instance Exception SomeException where
toException se = se
fromException = Just
instance Exception IOException where
toException = IOException
fromException (IOException e) = Just e
fromException _ = Nothing
instance Exception ArrayException where
toException = ArrayException
fromException (ArrayException e) = Just e
fromException _ = Nothing
instance Exception ArithException where
toException = ArithException
fromException (ArithException e) = Just e
fromException _ = Nothing
instance Exception ExitCode where
toException = ExitException
fromException (ExitException e) = Just e
fromException _ = Nothing
data ErrorCall = ErrorCall String
instance Show ErrorCall where
showsPrec _ (ErrorCall err) = showString err
instance Exception ErrorCall where
toException (ErrorCall s) = Hugs.Exception.ErrorCall s
fromException (Hugs.Exception.ErrorCall s) = Just (ErrorCall s)
fromException _ = Nothing
data BlockedIndefinitelyOnMVar = BlockedIndefinitelyOnMVar
data BlockedIndefinitelyOnSTM = BlockedIndefinitelyOnSTM
data Deadlock = Deadlock
data AssertionFailed = AssertionFailed String
data AsyncException
= StackOverflow
| HeapOverflow
| ThreadKilled
| UserInterrupt
deriving (Eq, Ord)
instance Show BlockedIndefinitelyOnMVar where
showsPrec _ BlockedIndefinitelyOnMVar = showString "thread blocked indefinitely"
instance Show BlockedIndefinitely where
showsPrec _ BlockedIndefinitely = showString "thread blocked indefinitely"
instance Show Deadlock where
showsPrec _ Deadlock = showString "<<deadlock>>"
instance Show AssertionFailed where
showsPrec _ (AssertionFailed err) = showString err
instance Show AsyncException where
showsPrec _ StackOverflow = showString "stack overflow"
showsPrec _ HeapOverflow = showString "heap overflow"
showsPrec _ ThreadKilled = showString "thread killed"
showsPrec _ UserInterrupt = showString "user interrupt"
instance Exception BlockedOnDeadMVar
instance Exception BlockedIndefinitely
instance Exception Deadlock
instance Exception AssertionFailed
instance Exception AsyncException
throw :: Exception e => e -> a
throw e = Hugs.Exception.throw (toException e)
throwIO :: Exception e => e -> IO a
throwIO e = Hugs.Exception.throwIO (toException e)
#endif
#ifndef __GLASGOW_HASKELL__
block :: IO a -> IO a
block = id
unblock :: IO a -> IO a
unblock = id
blocked :: IO Bool
blocked = return False
#endif
Note that we have to give a type signature to , or the program
will not as the type is ambiguous . While it is possible
Note that due to Haskell\ 's unspecified evaluation order , an
expression may throw one of several possible exceptions : consider
the expression @(error \"urk\ " ) + ( 1 ` 0)@. Does
catch :: Exception e
-> IO a
#if __GLASGOW_HASKELL__
catch = catchException
#elif __HUGS__
catch m h = Hugs.Exception.catchException m h'
where h' e = case fromException e of
Just e' -> h e'
Nothing -> throwIO e
#endif
catchJust
:: Exception e
-> IO a
catchJust p a handler = catch a handler'
where handler' e = case p e of
Nothing -> throwIO e
Just b -> handler b
> do handle ( \NonTermination - > exitWith ( ExitFailure 1 ) ) $
handle :: Exception e => (e -> IO a) -> IO a -> IO a
handle = flip catch
handleJust :: Exception e => (e -> Maybe b) -> (b -> IO a) -> IO a -> IO a
handleJust p = flip (catchJust p)
' mapException '
| This function maps one exception into another as proposed in the
mapException :: (Exception e1, Exception e2) => (e1 -> e2) -> a -> a
mapException f v = unsafePerformIO (catch (evaluate v)
(\x -> throwIO (f x)))
' a)@ if no exception of type was raised , or @('Left ' ex)@
if an exception of type was raised and its value is @ex@.
try :: Exception e => IO a -> IO (Either e a)
try a = catch (a >>= \ v -> return (Right v)) (\e -> return (Left e))
which exceptions are caught ( c.f . ' catchJust ' ) . If the exception
tryJust :: Exception e => (e -> Maybe b) -> IO a -> IO (Either b a)
tryJust p a = do
r <- try a
case r of
Right v -> return (Right v)
Left e -> case p e of
Nothing -> throwIO e
Just b -> return (Left b)
onException :: IO a -> IO b -> IO a
onException io what = io `catch` \e -> do _ <- what
throwIO (e :: SomeException)
> ( )
bracket
^ computation to run first ( \"acquire resource\ " )
bracket before after thing =
mask $ \restore -> do
a <- before
r <- restore (thing a) `onException` after a
_ <- after a
return r
^ computation to run first
returns the value from the first computation
a `finally` sequel =
mask $ \restore -> do
r <- restore a `onException` sequel
_ <- sequel
return r
| A variant of ' bracket ' where the return value from the first computation
bracket_ :: IO a -> IO b -> IO c -> IO c
bracket_ before after thing = bracket before (const after) (const thing)
bracketOnError
^ computation to run first ( \"acquire resource\ " )
bracketOnError before after thing =
mask $ \restore -> do
a <- before
restore (thing a) `onException` after a
#if !__GLASGOW_HASKELL__
assert :: Bool -> a -> a
assert True x = x
assert False _ = throw (AssertionFailed "")
#endif
#if __GLASGOW_HASKELL__ || __HUGS__
data PatternMatchFail = PatternMatchFail String
INSTANCE_TYPEABLE0(PatternMatchFail,patternMatchFailTc,"PatternMatchFail")
instance Show PatternMatchFail where
showsPrec _ (PatternMatchFail err) = showString err
#ifdef __HUGS__
instance Exception PatternMatchFail where
toException (PatternMatchFail err) = Hugs.Exception.PatternMatchFail err
fromException (Hugs.Exception.PatternMatchFail err) = Just (PatternMatchFail err)
fromException _ = Nothing
#else
instance Exception PatternMatchFail
#endif
multiple constructors , where some fields are in one constructor
data RecSelError = RecSelError String
INSTANCE_TYPEABLE0(RecSelError,recSelErrorTc,"RecSelError")
instance Show RecSelError where
showsPrec _ (RecSelError err) = showString err
#ifdef __HUGS__
instance Exception RecSelError where
toException (RecSelError err) = Hugs.Exception.RecSelError err
fromException (Hugs.Exception.RecSelError err) = Just (RecSelError err)
fromException _ = Nothing
#else
instance Exception RecSelError
#endif
|An uninitialised record field was used . The @String@ gives
data RecConError = RecConError String
INSTANCE_TYPEABLE0(RecConError,recConErrorTc,"RecConError")
instance Show RecConError where
showsPrec _ (RecConError err) = showString err
#ifdef __HUGS__
instance Exception RecConError where
toException (RecConError err) = Hugs.Exception.RecConError err
fromException (Hugs.Exception.RecConError err) = Just (RecConError err)
fromException _ = Nothing
#else
instance Exception RecConError
#endif
multiple constructors , where some fields are in one constructor
data RecUpdError = RecUpdError String
INSTANCE_TYPEABLE0(RecUpdError,recUpdErrorTc,"RecUpdError")
instance Show RecUpdError where
showsPrec _ (RecUpdError err) = showString err
#ifdef __HUGS__
instance Exception RecUpdError where
toException (RecUpdError err) = Hugs.Exception.RecUpdError err
fromException (Hugs.Exception.RecUpdError err) = Just (RecUpdError err)
fromException _ = Nothing
#else
instance Exception RecUpdError
#endif
data NoMethodError = NoMethodError String
INSTANCE_TYPEABLE0(NoMethodError,noMethodErrorTc,"NoMethodError")
instance Show NoMethodError where
showsPrec _ (NoMethodError err) = showString err
#ifdef __HUGS__
instance Exception NoMethodError where
toException (NoMethodError err) = Hugs.Exception.NoMethodError err
fromException (Hugs.Exception.NoMethodError err) = Just (NoMethodError err)
fromException _ = Nothing
#else
instance Exception NoMethodError
#endif
data NonTermination = NonTermination
INSTANCE_TYPEABLE0(NonTermination,nonTerminationTc,"NonTermination")
instance Show NonTermination where
showsPrec _ NonTermination = showString "<<loop>>"
#ifdef __HUGS__
instance Exception NonTermination where
toException NonTermination = Hugs.Exception.NonTermination
fromException Hugs.Exception.NonTermination = Just NonTermination
fromException _ = Nothing
#else
instance Exception NonTermination
#endif
package , inside another call to @atomically@.
data NestedAtomically = NestedAtomically
INSTANCE_TYPEABLE0(NestedAtomically,nestedAtomicallyTc,"NestedAtomically")
instance Show NestedAtomically where
showsPrec _ NestedAtomically = showString "Control.Concurrent.STM.atomically was nested"
instance Exception NestedAtomically
#endif /* __GLASGOW_HASKELL__ || __HUGS__ */
#ifdef __GLASGOW_HASKELL__
recSelError, recConError, irrefutPatError, runtimeError,
nonExhaustiveGuardsError, patError, noMethodBindingError,
absentError
recSelError s = throw (RecSelError ("No match in record selector "
absentError s = error ("Oops! Entered absent arg " ++ unpackCStringUtf8# s)
nonExhaustiveGuardsError s = throw (PatternMatchFail (untangle s "Non-exhaustive guards in"))
irrefutPatError s = throw (PatternMatchFail (untangle s "Irrefutable pattern failed for pattern"))
recConError s = throw (RecConError (untangle s "Missing field in record construction"))
noMethodBindingError s = throw (NoMethodError (untangle s "No instance nor default method for class operation"))
patError s = throw (PatternMatchFail (untangle s "Non-exhaustive patterns in"))
GHC 's RTS calls this
nonTermination :: SomeException
nonTermination = toException NonTermination
GHC 's RTS calls this
nestedAtomically :: SomeException
nestedAtomically = toException NestedAtomically
#endif
|
2e499948de0cf76d0eb8f9c492e63642c9e9dd5b9457851b1bacf01079d77e7d | xtdb/core2 | align.clj | (ns core2.align
(:require [core2.vector.indirect :as iv]
[core2.vector :as vec])
(:import (core2.vector IIndirectRelation IIndirectVector)
[java.util HashMap LinkedList List Map]
java.util.function.BiFunction
java.util.stream.IntStream
org.roaringbitmap.longlong.Roaring64Bitmap))
(set! *unchecked-math* :warn-on-boxed)
(defn ->row-id-bitmap
(^org.roaringbitmap.longlong.Roaring64Bitmap [^IIndirectVector row-id-col]
(->row-id-bitmap nil row-id-col))
(^org.roaringbitmap.longlong.Roaring64Bitmap [^ints idxs ^IIndirectVector row-id-col]
(let [res (Roaring64Bitmap.)
row-id-rdr (.monoReader row-id-col :i64)]
(if idxs
(dotimes [idx (alength idxs)]
(.addLong res (.readLong row-id-rdr (aget idxs idx))))
(dotimes [idx (.getValueCount row-id-col)]
(.addLong res (.readLong row-id-rdr idx))))
res)))
(defn- ->row-id->repeat-count ^java.util.Map [^IIndirectVector row-id-col]
(let [res (HashMap.)
row-id-rdr (.monoReader row-id-col :i64)]
(dotimes [idx (.getValueCount row-id-col)]
(let [row-id (.readLong row-id-rdr idx)]
(.compute res row-id (reify BiFunction
(apply [_ _k v]
(if v
(inc (long v))
1))))))
res))
(defn- align-vector ^core2.vector.IIndirectVector [^IIndirectRelation content-rel, ^Map row-id->repeat-count]
(let [[^IIndirectVector row-id-col, ^IIndirectVector content-col] (vec content-rel)
row-id-rdr (.monoReader row-id-col :i64)
res (IntStream/builder)]
(dotimes [idx (.getValueCount row-id-col)]
(let [row-id (.readLong row-id-rdr idx)]
(when-let [ns (.get row-id->repeat-count row-id)]
(dotimes [_ ns]
(.add res idx)))))
(.select content-col (.toArray (.build res)))))
(defn align-vectors ^core2.vector.IIndirectRelation [^List content-rels, ^IIndirectRelation temporal-rel]
;; assumption: temporal-rel is sorted by row-id
(let [read-cols (LinkedList. (seq temporal-rel))
temporal-row-id-col (.vectorForName temporal-rel "_row-id")]
(assert temporal-row-id-col)
(let [row-id->repeat-count (->row-id->repeat-count temporal-row-id-col)]
(doseq [^IIndirectRelation content-rel content-rels]
(.add read-cols (align-vector content-rel row-id->repeat-count))))
(iv/->indirect-rel read-cols)))
| null | https://raw.githubusercontent.com/xtdb/core2/3adeb391ca4dd73a3f79faba8024289376597d23/core/src/main/clojure/core2/align.clj | clojure | assumption: temporal-rel is sorted by row-id | (ns core2.align
(:require [core2.vector.indirect :as iv]
[core2.vector :as vec])
(:import (core2.vector IIndirectRelation IIndirectVector)
[java.util HashMap LinkedList List Map]
java.util.function.BiFunction
java.util.stream.IntStream
org.roaringbitmap.longlong.Roaring64Bitmap))
(set! *unchecked-math* :warn-on-boxed)
(defn ->row-id-bitmap
(^org.roaringbitmap.longlong.Roaring64Bitmap [^IIndirectVector row-id-col]
(->row-id-bitmap nil row-id-col))
(^org.roaringbitmap.longlong.Roaring64Bitmap [^ints idxs ^IIndirectVector row-id-col]
(let [res (Roaring64Bitmap.)
row-id-rdr (.monoReader row-id-col :i64)]
(if idxs
(dotimes [idx (alength idxs)]
(.addLong res (.readLong row-id-rdr (aget idxs idx))))
(dotimes [idx (.getValueCount row-id-col)]
(.addLong res (.readLong row-id-rdr idx))))
res)))
(defn- ->row-id->repeat-count ^java.util.Map [^IIndirectVector row-id-col]
(let [res (HashMap.)
row-id-rdr (.monoReader row-id-col :i64)]
(dotimes [idx (.getValueCount row-id-col)]
(let [row-id (.readLong row-id-rdr idx)]
(.compute res row-id (reify BiFunction
(apply [_ _k v]
(if v
(inc (long v))
1))))))
res))
(defn- align-vector ^core2.vector.IIndirectVector [^IIndirectRelation content-rel, ^Map row-id->repeat-count]
(let [[^IIndirectVector row-id-col, ^IIndirectVector content-col] (vec content-rel)
row-id-rdr (.monoReader row-id-col :i64)
res (IntStream/builder)]
(dotimes [idx (.getValueCount row-id-col)]
(let [row-id (.readLong row-id-rdr idx)]
(when-let [ns (.get row-id->repeat-count row-id)]
(dotimes [_ ns]
(.add res idx)))))
(.select content-col (.toArray (.build res)))))
(defn align-vectors ^core2.vector.IIndirectRelation [^List content-rels, ^IIndirectRelation temporal-rel]
(let [read-cols (LinkedList. (seq temporal-rel))
temporal-row-id-col (.vectorForName temporal-rel "_row-id")]
(assert temporal-row-id-col)
(let [row-id->repeat-count (->row-id->repeat-count temporal-row-id-col)]
(doseq [^IIndirectRelation content-rel content-rels]
(.add read-cols (align-vector content-rel row-id->repeat-count))))
(iv/->indirect-rel read-cols)))
|
ea89b6e350ec63854fc14abe8521faaf802459147bdeaed5d656a1e175c80a98 | AndrasKovacs/ELTE-func-lang | Interpreter.hs | # LANGUAGE RecordWildCards #
module Interpreter where
import Control.Monad.Identity
import Control.Monad.Trans.State
import Control.Monad.Trans.Except
import Control.Monad.Error.Class
import Data.Map (Map(..))
import qualified Data.Map as Map
import Syntax
newtype RTVal = RTLit Lit
deriving (Eq, Ord, Show)
type VarMapping = Map Var RTVal
type Eval a = StateT VarMapping (ExceptT String Identity) a
runEval :: Eval a -> VarMapping -> Either String (a, VarMapping)
runEval m s = runExcept (runStateT m s)
evalEval :: Eval a -> VarMapping -> Either String a
evalEval m s = fst <$> runEval m s
evalLit :: Lit -> Eval RTVal
evalLit lit = return $ RTLit lit
evalVar :: Var -> Eval RTVal
evalVar v = do
vars <- get
let mVal = Map.lookup v vars
case mVal of
Just val -> return val
Nothing -> throwError $ "Undefined variable: " ++ show v
evalBinOp :: (Expr -> Eval a) ->
(Expr -> Eval b) ->
(c -> RTVal) ->
(a -> b -> c) ->
(Expr -> Expr -> Eval RTVal)
evalBinOp evalLhs evalRhs mkRetVal op lhs rhs = do
lhs' <- evalLhs lhs
rhs' <- evalRhs rhs
let result = lhs' `op` rhs'
return $ mkRetVal result
evalInt :: Expr -> Eval Int
evalInt e = do
e' <- evalExpr e
case e' of
RTLit (LInt n) -> return n
_ -> throwError $ show e ++ " does not evaluate to an Integer"
evalBool :: Expr -> Eval Bool
evalBool e = do
e' <- evalExpr e
case e' of
RTLit (LBool b) -> return b
_ -> throwError $ show e ++ " does not evaluate to a Boolean"
mkRTInt :: Int -> RTVal
mkRTInt = RTLit . LInt
mkRTBool :: Bool -> RTVal
mkRTBool = RTLit . LBool
evalUnaryOp :: (Expr -> Eval a) ->
(b -> RTVal) ->
(a -> b) ->
(Expr -> Eval RTVal)
evalUnaryOp evalArg mkRetVal op arg =
evalBinOp evalArg evalArg mkRetVal (const <$> op) arg arg
const < $ > op is similar to : rhs - > op lhs
evalExpr :: Expr -> Eval RTVal
evalExpr (ELit l) = evalLit l
evalExpr (EVar v) = evalVar v
evalExpr (Plus lhs rhs) = evalBinOp evalInt evalInt mkRTInt (+) lhs rhs
evalExpr (Minus lhs rhs) = evalBinOp evalInt evalInt mkRTInt (-) lhs rhs
evalExpr (Mul lhs rhs) = evalBinOp evalInt evalInt mkRTInt (*) lhs rhs
evalExpr (And lhs rhs) = evalBinOp evalBool evalBool mkRTBool (&&) lhs rhs
evalExpr (LEq lhs rhs) = evalBinOp evalInt evalInt mkRTBool (<=) lhs rhs
evalExpr (Not arg) = evalUnaryOp evalBool mkRTBool (not) arg
| null | https://raw.githubusercontent.com/AndrasKovacs/ELTE-func-lang/88d41930999d6056bdd7bfaa85761a527cce4113/2019-20-1/jan6-pre/Interpreter.hs | haskell | # LANGUAGE RecordWildCards #
module Interpreter where
import Control.Monad.Identity
import Control.Monad.Trans.State
import Control.Monad.Trans.Except
import Control.Monad.Error.Class
import Data.Map (Map(..))
import qualified Data.Map as Map
import Syntax
newtype RTVal = RTLit Lit
deriving (Eq, Ord, Show)
type VarMapping = Map Var RTVal
type Eval a = StateT VarMapping (ExceptT String Identity) a
runEval :: Eval a -> VarMapping -> Either String (a, VarMapping)
runEval m s = runExcept (runStateT m s)
evalEval :: Eval a -> VarMapping -> Either String a
evalEval m s = fst <$> runEval m s
evalLit :: Lit -> Eval RTVal
evalLit lit = return $ RTLit lit
evalVar :: Var -> Eval RTVal
evalVar v = do
vars <- get
let mVal = Map.lookup v vars
case mVal of
Just val -> return val
Nothing -> throwError $ "Undefined variable: " ++ show v
evalBinOp :: (Expr -> Eval a) ->
(Expr -> Eval b) ->
(c -> RTVal) ->
(a -> b -> c) ->
(Expr -> Expr -> Eval RTVal)
evalBinOp evalLhs evalRhs mkRetVal op lhs rhs = do
lhs' <- evalLhs lhs
rhs' <- evalRhs rhs
let result = lhs' `op` rhs'
return $ mkRetVal result
evalInt :: Expr -> Eval Int
evalInt e = do
e' <- evalExpr e
case e' of
RTLit (LInt n) -> return n
_ -> throwError $ show e ++ " does not evaluate to an Integer"
evalBool :: Expr -> Eval Bool
evalBool e = do
e' <- evalExpr e
case e' of
RTLit (LBool b) -> return b
_ -> throwError $ show e ++ " does not evaluate to a Boolean"
mkRTInt :: Int -> RTVal
mkRTInt = RTLit . LInt
mkRTBool :: Bool -> RTVal
mkRTBool = RTLit . LBool
evalUnaryOp :: (Expr -> Eval a) ->
(b -> RTVal) ->
(a -> b) ->
(Expr -> Eval RTVal)
evalUnaryOp evalArg mkRetVal op arg =
evalBinOp evalArg evalArg mkRetVal (const <$> op) arg arg
const < $ > op is similar to : rhs - > op lhs
evalExpr :: Expr -> Eval RTVal
evalExpr (ELit l) = evalLit l
evalExpr (EVar v) = evalVar v
evalExpr (Plus lhs rhs) = evalBinOp evalInt evalInt mkRTInt (+) lhs rhs
evalExpr (Minus lhs rhs) = evalBinOp evalInt evalInt mkRTInt (-) lhs rhs
evalExpr (Mul lhs rhs) = evalBinOp evalInt evalInt mkRTInt (*) lhs rhs
evalExpr (And lhs rhs) = evalBinOp evalBool evalBool mkRTBool (&&) lhs rhs
evalExpr (LEq lhs rhs) = evalBinOp evalInt evalInt mkRTBool (<=) lhs rhs
evalExpr (Not arg) = evalUnaryOp evalBool mkRTBool (not) arg
| |
63163fb69593b8e17b91c6ad4be8253c4a834bb7064bd8b14f278a1eb420cc00 | ds-wizard/engine-backend | List_GET.hs | module Wizard.Specs.API.Info.List_GET (
list_get,
) where
import Data.Aeson (encode)
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import Test.Hspec.Wai.Matcher
import Shared.Api.Resource.Info.InfoJM ()
import Shared.Database.Migration.Development.Info.Data.Infos
import qualified Wizard.Database.Migration.Development.Component.ComponentMigration as CMP_Migration
import Wizard.Model.Context.AppContext
import SharedTest.Specs.API.Common
import Wizard.Specs.Common
-- ------------------------------------------------------------------------
-- GET /
-- ------------------------------------------------------------------------
list_get :: AppContext -> SpecWith ((), Application)
list_get appContext = describe "GET /" $ test_200 appContext
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
reqMethod = methodGet
reqUrl = "/"
reqHeaders = []
reqBody = ""
-- ----------------------------------------------------
-- ----------------------------------------------------
-- ----------------------------------------------------
test_200 appContext =
it "HTTP 200 OK" $
-- GIVEN: Prepare expectation
do
let expStatus = 200
let expHeaders = resCtHeader : resCorsHeaders
let expDto = appInfo
let expBody = encode expDto
-- AND: Prepare DB
runInContextIO CMP_Migration.runMigration appContext
-- WHEN: Call API
response <- request reqMethod reqUrl reqHeaders reqBody
-- THEN: Compare response with expectation
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
| null | https://raw.githubusercontent.com/ds-wizard/engine-backend/b87f6d481205dd7f0f00fd770145f8ee5c4be193/engine-wizard/test/Wizard/Specs/API/Info/List_GET.hs | haskell | ------------------------------------------------------------------------
GET /
------------------------------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
----------------------------------------------------
GIVEN: Prepare expectation
AND: Prepare DB
WHEN: Call API
THEN: Compare response with expectation | module Wizard.Specs.API.Info.List_GET (
list_get,
) where
import Data.Aeson (encode)
import Network.HTTP.Types
import Network.Wai (Application)
import Test.Hspec
import Test.Hspec.Wai hiding (shouldRespondWith)
import Test.Hspec.Wai.Matcher
import Shared.Api.Resource.Info.InfoJM ()
import Shared.Database.Migration.Development.Info.Data.Infos
import qualified Wizard.Database.Migration.Development.Component.ComponentMigration as CMP_Migration
import Wizard.Model.Context.AppContext
import SharedTest.Specs.API.Common
import Wizard.Specs.Common
list_get :: AppContext -> SpecWith ((), Application)
list_get appContext = describe "GET /" $ test_200 appContext
reqMethod = methodGet
reqUrl = "/"
reqHeaders = []
reqBody = ""
test_200 appContext =
it "HTTP 200 OK" $
do
let expStatus = 200
let expHeaders = resCtHeader : resCorsHeaders
let expDto = appInfo
let expBody = encode expDto
runInContextIO CMP_Migration.runMigration appContext
response <- request reqMethod reqUrl reqHeaders reqBody
let responseMatcher =
ResponseMatcher {matchHeaders = expHeaders, matchStatus = expStatus, matchBody = bodyEquals expBody}
response `shouldRespondWith` responseMatcher
|
bdbce2390f88094d1dbda443e58afdaa7cc537da4572bf81f51696c0520edd61 | tweag/ormolu | fancy-forall-1-out.hs | magnify ::
forall outertag innertag t outer inner m a.
( forall x. Coercible (t m x) (m x),
forall m'.
(HasReader outertag outer m') =>
HasReader innertag inner (t m'),
HasReader outertag outer m
) =>
(forall m'. (HasReader innertag inner m') => m' a) ->
m a
| null | https://raw.githubusercontent.com/tweag/ormolu/a4a9f4500b6c25f104cfbde82d9c16c6875b6d1e/data/examples/declaration/value/function/fancy-forall-1-out.hs | haskell | magnify ::
forall outertag innertag t outer inner m a.
( forall x. Coercible (t m x) (m x),
forall m'.
(HasReader outertag outer m') =>
HasReader innertag inner (t m'),
HasReader outertag outer m
) =>
(forall m'. (HasReader innertag inner m') => m' a) ->
m a
| |
3c3790b414eb483e001ffaa92b5f1c0b578d04d2a3eb145dd82665d6dc7c132e | bmeurer/ocaml-arm | command_line.ml | (***********************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
OCaml port by and
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
(* *)
(***********************************************************************)
$ Id$
(************************ Reading and executing commands ***************)
open Int64ops
open Format
open Misc
open Instruct
open Unix
open Debugger_config
open Types
open Primitives
open Unix_tools
open Parser
open Parser_aux
open Lexer
open Input_handling
open Question
open Debugcom
open Program_loading
open Program_management
open Lexing
open Parameters
open Show_source
open Show_information
open Time_travel
open Events
open Symbols
open Source
open Breakpoints
open Checkpoints
open Frames
open Printval
(** Instructions, variables and infos lists. **)
type dbg_instruction =
{ instr_name: string; (* Name of command *)
instr_prio: bool; (* Has priority *)
instr_action: formatter -> lexbuf -> unit;
(* What to do *)
instr_repeat: bool; (* Can be repeated *)
instr_help: string } (* Help message *)
let instruction_list = ref ([] : dbg_instruction list)
type dbg_variable =
{ var_name: string; (* Name of variable *)
var_action: (lexbuf -> unit) * (formatter -> unit);
Reading , writing fns
var_help: string } (* Help message *)
let variable_list = ref ([] : dbg_variable list)
type dbg_info =
{ info_name: string; (* Name of info *)
info_action: lexbuf -> unit; (* What to do *)
info_help: string } (* Help message *)
let info_list = ref ([] : dbg_info list)
(** Utilities. **)
let error text =
eprintf "%s@." text;
raise Toplevel
let check_not_windows feature =
match Sys.os_type with
| "Win32" ->
error ("'"^feature^"' feature not supported on Windows")
| _ ->
()
let eol =
end_of_line Lexer.lexeme
let matching_elements list name instr =
List.filter (function a -> isprefix instr (name a)) !list
let all_matching_instructions =
matching_elements instruction_list (fun i -> i.instr_name)
itz 04 - 21 - 96 do n't do priority completion in emacs mode
XL 25 - 02 - 97 why ? I find it very confusing .
let matching_instructions instr =
let all = all_matching_instructions instr in
let prio = List.filter (fun i -> i.instr_prio) all in
if prio = [] then all else prio
let matching_variables =
matching_elements variable_list (fun v -> v.var_name)
let matching_infos =
matching_elements info_list (fun i -> i.info_name)
let find_ident name matcher action alternative ppf lexbuf =
match identifier_or_eol Lexer.lexeme lexbuf with
| None -> alternative ppf
| Some ident ->
match matcher ident with
| [] -> error ("Unknown " ^ name ^ ".")
| [a] -> action a ppf lexbuf
| _ -> error ("Ambiguous " ^ name ^ ".")
let find_variable action alternative ppf lexbuf =
find_ident "variable name" matching_variables action alternative ppf lexbuf
let find_info action alternative ppf lexbuf =
find_ident "info command" matching_infos action alternative ppf lexbuf
let add_breakpoint_at_pc pc =
try
new_breakpoint (any_event_at_pc pc)
with
| Not_found ->
eprintf "Can't add breakpoint at pc %i : no event there.@." pc;
raise Toplevel
let add_breakpoint_after_pc pc =
let rec try_add n =
if n < 3 then begin
try
new_breakpoint (any_event_at_pc (pc + n * 4))
with
| Not_found ->
try_add (n+1)
end else begin
error
"Can't add breakpoint at beginning of function: no event there"
end
in try_add 0
let module_of_longident id =
match id with
| Some x -> Some (String.concat "." (Longident.flatten x))
| None -> None
let convert_module mdle =
match mdle with
| Some m ->
Strip .ml extension if any , and capitalize
String.capitalize(if Filename.check_suffix m ".ml"
then Filename.chop_suffix m ".ml"
else m)
| None ->
try
(get_current_event ()).ev_module
with
| Not_found ->
error "Not in a module."
* Toplevel . *
let current_line = ref ""
let interprete_line ppf line =
current_line := line;
let lexbuf = Lexing.from_string line in
try
match identifier_or_eol Lexer.lexeme lexbuf with
| Some x ->
begin match matching_instructions x with
| [] ->
error "Unknown command."
| [i] ->
i.instr_action ppf lexbuf;
resume_user_input ();
i.instr_repeat
| l ->
error "Ambiguous command."
end
| None ->
resume_user_input ();
false
with
| Parsing.Parse_error ->
error "Syntax error."
let line_loop ppf line_buffer =
resume_user_input ();
let previous_line = ref "" in
try
while true do
if !loaded then
History.add_current_time ();
let new_line = string_trim (line line_buffer) in
let line =
if new_line <> "" then
new_line
else
!previous_line
in
previous_line := "";
if interprete_line ppf line then
previous_line := line
done
with
| Exit ->
stop_user_input ()
| s - >
error ( " System error : " ^ s )
error ("System error : " ^ s) *)
(** Instructions. **)
let instr_cd ppf lexbuf =
let dir = argument_eol argument lexbuf in
if ask_kill_program () then
try
Sys.chdir (expand_path dir)
with
| Sys_error s ->
error s
let instr_shell ppf lexbuf =
let cmdarg = argument_list_eol argument lexbuf in
let cmd = String.concat " " cmdarg in
perhaps we should use $ SHELL -c ?
let err = Sys.command cmd in
if (err != 0) then
eprintf "Shell command %S failed with exit code %d\n%!" cmd err
let instr_env ppf lexbuf =
let cmdarg = argument_list_eol argument lexbuf in
let cmdarg = string_trim (String.concat " " cmdarg) in
if cmdarg <> "" then
try
if (String.index cmdarg '=') > 0 then
Debugger_config.environment := cmdarg :: !Debugger_config.environment
else
eprintf "Environment variables should not have an empty name\n%!"
with Not_found ->
eprintf "Environment variables should have the \"name=value\" format\n%!"
else
List.iter
(printf "%s\n%!")
(List.rev !Debugger_config.environment)
let instr_pwd ppf lexbuf =
eol lexbuf;
fprintf ppf "%s@." (Sys.getcwd ())
let instr_dir ppf lexbuf =
let new_directory = argument_list_eol argument lexbuf in
if new_directory = [] then begin
if yes_or_no "Reinitialize directory list" then begin
Config.load_path := !default_load_path;
Envaux.reset_cache ();
Hashtbl.clear Debugger_config.load_path_for;
flush_buffer_list ()
end
end
else begin
let new_directory' = List.rev new_directory in
match new_directory' with
| mdl :: for_keyw :: tl when (String.lowercase for_keyw) = "for" && (List.length tl) > 0 ->
List.iter (function x -> add_path_for mdl (expand_path x)) tl
| _ ->
List.iter (function x -> add_path (expand_path x)) new_directory'
end;
let print_dirs ppf l = List.iter (function x -> fprintf ppf "@ %s" x) l in
fprintf ppf "@[<2>Directories :%a@]@." print_dirs !Config.load_path;
Hashtbl.iter
(fun mdl dirs ->
fprintf ppf "@[<2>Source directories for %s :%a@]@." mdl print_dirs dirs)
Debugger_config.load_path_for
let instr_kill ppf lexbuf =
eol lexbuf;
if not !loaded then error "The program is not being run.";
if (yes_or_no "Kill the program being debugged") then begin
kill_program ();
show_no_point()
end
let instr_run ppf lexbuf =
eol lexbuf;
ensure_loaded ();
reset_named_values ();
run ();
show_current_event ppf;;
let instr_reverse ppf lexbuf =
eol lexbuf;
check_not_windows "reverse";
ensure_loaded ();
reset_named_values();
back_run ();
show_current_event ppf
let instr_step ppf lexbuf =
let step_count =
match opt_signed_int64_eol Lexer.lexeme lexbuf with
| None -> _1
| Some x -> x
in
ensure_loaded ();
reset_named_values();
step step_count;
show_current_event ppf
let instr_back ppf lexbuf =
let step_count =
match opt_signed_int64_eol Lexer.lexeme lexbuf with
| None -> _1
| Some x -> x
in
check_not_windows "backstep";
ensure_loaded ();
reset_named_values();
step (_0 -- step_count);
show_current_event ppf
let instr_finish ppf lexbuf =
eol lexbuf;
ensure_loaded ();
reset_named_values();
finish ();
show_current_event ppf
let instr_next ppf lexbuf =
let step_count =
match opt_integer_eol Lexer.lexeme lexbuf with
| None -> 1
| Some x -> x
in
ensure_loaded ();
reset_named_values();
next step_count;
show_current_event ppf
let instr_start ppf lexbuf =
eol lexbuf;
check_not_windows "start";
ensure_loaded ();
reset_named_values();
start ();
show_current_event ppf
let instr_previous ppf lexbuf =
let step_count =
match opt_integer_eol Lexer.lexeme lexbuf with
| None -> 1
| Some x -> x
in
check_not_windows "previous";
ensure_loaded ();
reset_named_values();
previous step_count;
show_current_event ppf
let instr_goto ppf lexbuf =
let time = int64_eol Lexer.lexeme lexbuf in
ensure_loaded ();
reset_named_values();
go_to time;
show_current_event ppf
let instr_quit _ =
raise Exit
let print_variable_list ppf =
let pr_vars ppf = List.iter (fun v -> fprintf ppf "%s@ " v.var_name) in
fprintf ppf "List of variables :%a@." pr_vars !variable_list
let print_info_list ppf =
let pr_infos ppf = List.iter (fun i -> fprintf ppf "%s@ " i.info_name) in
fprintf ppf "List of info commands :%a@." pr_infos !info_list
let instr_complete ppf lexbuf =
let ppf = Format.err_formatter in
let rec print_list l =
try
eol lexbuf;
List.iter (function i -> fprintf ppf "%s@." i) l
with _ ->
remove_file !user_channel
and match_list lexbuf =
match identifier_or_eol Lexer.lexeme lexbuf with
| None ->
List.map (fun i -> i.instr_name) !instruction_list
| Some x ->
match matching_instructions x with
| [ {instr_name = ("set" | "show" as i_full)} ] ->
if x = i_full then begin
match identifier_or_eol Lexer.lexeme lexbuf with
| Some ident ->
begin match matching_variables ident with
| [v] -> if v.var_name = ident then [] else [v.var_name]
| l -> List.map (fun v -> v.var_name) l
end
| None ->
List.map (fun v -> v.var_name) !variable_list
end
else [i_full]
| [ {instr_name = "info"} ] ->
if x = "info" then begin
match identifier_or_eol Lexer.lexeme lexbuf with
| Some ident ->
begin match matching_infos ident with
| [i] -> if i.info_name = ident then [] else [i.info_name]
| l -> List.map (fun i -> i.info_name) l
end
| None ->
List.map (fun i -> i.info_name) !info_list
end
else ["info"]
| [ {instr_name = "help"} ] ->
if x = "help" then match_list lexbuf else ["help"]
| [ i ] ->
if x = i.instr_name then [] else [i.instr_name]
| l ->
List.map (fun i -> i.instr_name) l
in
print_list(match_list lexbuf)
let instr_help ppf lexbuf =
let pr_instrs ppf =
List.iter (fun i -> fprintf ppf "%s@ " i.instr_name) in
match identifier_or_eol Lexer.lexeme lexbuf with
| Some x ->
let print_help nm hlp =
eol lexbuf;
fprintf ppf "%s : %s@." nm hlp in
begin match matching_instructions x with
| [] ->
eol lexbuf;
fprintf ppf "No matching command.@."
| [ {instr_name = "set"} ] ->
find_variable
(fun v _ _ ->
print_help ("set " ^ v.var_name) ("set " ^ v.var_help))
(fun ppf ->
print_help "set" "set debugger variable.";
print_variable_list ppf)
ppf
lexbuf
| [ {instr_name = "show"} ] ->
find_variable
(fun v _ _ ->
print_help ("show " ^ v.var_name) ("show " ^ v.var_help))
(fun v ->
print_help "show" "display debugger variable.";
print_variable_list ppf)
ppf
lexbuf
| [ {instr_name = "info"} ] ->
find_info
(fun i _ _ -> print_help ("info " ^ i.info_name) i.info_help)
(fun ppf ->
print_help "info"
"display infos about the program being debugged.";
print_info_list ppf)
ppf
lexbuf
| [i] ->
print_help i.instr_name i.instr_help
| l ->
eol lexbuf;
fprintf ppf "Ambiguous command \"%s\" : %a@." x pr_instrs l
end
| None ->
fprintf ppf "List of commands : %a@." pr_instrs !instruction_list
(* Printing values *)
let print_expr depth ev env ppf expr =
try
let (v, ty) = Eval.expression ev env expr in
print_named_value depth expr env v ppf ty
with
| Eval.Error msg ->
Eval.report_error ppf msg;
raise Toplevel
let print_command depth ppf lexbuf =
let exprs = expression_list_eol Lexer.lexeme lexbuf in
ensure_loaded ();
let env =
try
Envaux.env_of_event !selected_event
with
| Envaux.Error msg ->
Envaux.report_error ppf msg;
raise Toplevel
in
List.iter (print_expr depth !selected_event env ppf) exprs
let instr_print ppf lexbuf = print_command !max_printer_depth ppf lexbuf
let instr_display ppf lexbuf = print_command 1 ppf lexbuf
(* Loading of command files *)
let extract_filename arg =
(* Allow enclosing filename in quotes *)
let l = String.length arg in
let pos1 = if l > 0 && arg.[0] = '"' then 1 else 0 in
let pos2 = if l > 0 && arg.[l-1] = '"' then l-1 else l in
String.sub arg pos1 (pos2 - pos1)
let instr_source ppf lexbuf =
let file = extract_filename(argument_eol argument lexbuf)
and old_state = !interactif
and old_channel = !user_channel in
let io_chan =
try
io_channel_of_descr
(openfile (find_in_path !Config.load_path (expand_path file))
[O_RDONLY] 0)
with
| Not_found -> error "Source file not found."
| (Unix_error _) as x -> Unix_tools.report_error x; raise Toplevel
in
try
interactif := false;
user_channel := io_chan;
line_loop ppf (Lexing.from_function read_user_input);
close_io io_chan;
interactif := old_state;
user_channel := old_channel
with
| x ->
stop_user_input ();
close_io io_chan;
interactif := old_state;
user_channel := old_channel;
raise x
let instr_set =
find_variable
(fun {var_action = (funct, _)} ppf lexbuf -> funct lexbuf)
(function ppf -> error "Argument required.")
let instr_show =
find_variable
(fun {var_action = (_, funct)} ppf lexbuf -> eol lexbuf; funct ppf)
(function ppf ->
List.iter
(function {var_name = nm; var_action = (_, funct)} ->
fprintf ppf "%s : " nm;
funct ppf)
!variable_list)
let instr_info =
find_info
(fun i ppf lexbuf -> i.info_action lexbuf)
(function ppf ->
error "\"info\" must be followed by the name of an info command.")
let instr_break ppf lexbuf =
let argument = break_argument_eol Lexer.lexeme lexbuf in
ensure_loaded ();
match argument with
| BA_none -> (* break *)
(match !selected_event with
| Some ev ->
new_breakpoint ev
| None ->
error "Can't add breakpoint at this point.")
| BA_pc pc -> (* break PC *)
add_breakpoint_at_pc pc
| BA_function expr -> (* break FUNCTION *)
let env =
try
Envaux.env_of_event !selected_event
with
| Envaux.Error msg ->
Envaux.report_error ppf msg;
raise Toplevel
in
begin try
let (v, ty) = Eval.expression !selected_event env expr in
match (Ctype.repr ty).desc with
| Tarrow _ ->
add_breakpoint_after_pc (Remote_value.closure_code v)
| _ ->
eprintf "Not a function.@.";
raise Toplevel
with
| Eval.Error msg ->
Eval.report_error ppf msg;
raise Toplevel
end
| BA_pos1 (mdle, line, column) -> (* break @ [MODULE] LINE [COL] *)
let module_name = convert_module (module_of_longident mdle) in
new_breakpoint
(try
let buffer =
try get_buffer Lexing.dummy_pos module_name with
| Not_found ->
eprintf "No source file for %s.@." module_name;
raise Toplevel
in
match column with
| None ->
event_at_pos module_name (fst (pos_of_line buffer line))
| Some col ->
event_near_pos module_name (point_of_coord buffer line col)
with
| Not_found -> (* event_at_pos / event_near pos *)
eprintf "Can't find any event there.@.";
raise Toplevel
| Out_of_range -> (* pos_of_line / point_of_coord *)
eprintf "Position out of range.@.";
raise Toplevel)
| BA_pos2 (mdle, position) -> (* break @ [MODULE] # POSITION *)
try
new_breakpoint (event_near_pos (convert_module (module_of_longident mdle)) position)
with
| Not_found ->
eprintf "Can't find any event there.@."
let instr_delete ppf lexbuf =
match integer_list_eol Lexer.lexeme lexbuf with
| [] ->
if breakpoints_count () <> 0 && yes_or_no "Delete all breakpoints"
then remove_all_breakpoints ()
| breakpoints ->
List.iter
(function x -> try remove_breakpoint x with | Not_found -> ())
breakpoints
let instr_frame ppf lexbuf =
let frame_number =
match opt_integer_eol Lexer.lexeme lexbuf with
| None -> !current_frame
| Some x -> x
in
ensure_loaded ();
try
select_frame frame_number;
show_current_frame ppf true
with
| Not_found ->
error ("No frame number " ^ string_of_int frame_number ^ ".")
let instr_backtrace ppf lexbuf =
let number =
match opt_signed_integer_eol Lexer.lexeme lexbuf with
| None -> 0
| Some x -> x in
ensure_loaded ();
match current_report() with
| None | Some {rep_type = Exited | Uncaught_exc} -> ()
| Some _ ->
let frame_counter = ref 0 in
let print_frame first_frame last_frame = function
| None ->
fprintf ppf
"(Encountered a function with no debugging information)@.";
false
| Some event ->
if !frame_counter >= first_frame then
show_one_frame !frame_counter ppf event;
incr frame_counter;
if !frame_counter >= last_frame then begin
fprintf ppf "(More frames follow)@."
end;
!frame_counter < last_frame in
fprintf ppf "Backtrace:@.";
if number = 0 then
do_backtrace (print_frame 0 max_int)
else if number > 0 then
do_backtrace (print_frame 0 number)
else begin
let num_frames = stack_depth() in
if num_frames < 0 then
fprintf ppf
"(Encountered a function with no debugging information)@."
else
do_backtrace (print_frame (num_frames + number) max_int)
end
let instr_up ppf lexbuf =
let offset =
match opt_signed_integer_eol Lexer.lexeme lexbuf with
| None -> 1
| Some x -> x
in
ensure_loaded ();
try
select_frame (!current_frame + offset);
show_current_frame ppf true
with
| Not_found -> error "No such frame."
let instr_down ppf lexbuf =
let offset =
match opt_signed_integer_eol Lexer.lexeme lexbuf with
| None -> 1
| Some x -> x
in
ensure_loaded ();
try
select_frame (!current_frame - offset);
show_current_frame ppf true
with
| Not_found -> error "No such frame."
let instr_last ppf lexbuf =
let count =
match opt_signed_int64_eol Lexer.lexeme lexbuf with
| None -> _1
| Some x -> x
in
check_not_windows "last";
reset_named_values();
go_to (History.previous_time count);
show_current_event ppf
let instr_list ppf lexbuf =
let (mo, beg, e) = list_arguments_eol Lexer.lexeme lexbuf in
let (curr_mod, line, column) =
try
selected_point ()
with
| Not_found ->
("", -1, -1)
in
let mdle = convert_module (module_of_longident mo) in
let pos = Lexing.dummy_pos in
let buffer =
try get_buffer pos mdle with
| Not_found -> error ("No source file for " ^ mdle ^ ".") in
let point =
if column <> -1 then
(point_of_coord buffer line 1) + column
else
-1 in
let beginning =
match beg with
| None when (mo <> None) || (line = -1) ->
1
| None ->
begin try
max 1 (line - 10)
with Out_of_range ->
1
end
| Some x -> x
in
let en =
match e with
| None -> beginning + 20
| Some x -> x
in
if mdle = curr_mod then
show_listing pos mdle beginning en point
(current_event_is_before ())
else
show_listing pos mdle beginning en (-1) true
(** Variables. **)
let raw_variable kill name =
(function lexbuf ->
let argument = argument_eol argument lexbuf in
if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%s@." !name
let raw_line_variable kill name =
(function lexbuf ->
let argument = argument_eol line_argument lexbuf in
if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%s@." !name
let integer_variable kill min msg name =
(function lexbuf ->
let argument = integer_eol Lexer.lexeme lexbuf in
if argument < min then print_endline msg
else if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%i@." !name
let int64_variable kill min msg name =
(function lexbuf ->
let argument = int64_eol Lexer.lexeme lexbuf in
if argument < min then print_endline msg
else if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%Li@." !name
let boolean_variable kill name =
(function lexbuf ->
let argument =
match identifier_eol Lexer.lexeme lexbuf with
| "on" -> true
| "of" | "off" -> false
| _ -> error "Syntax error."
in
if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%s@." (if !name then "on" else "off")
let path_variable kill name =
(function lexbuf ->
let argument = argument_eol argument lexbuf in
if (not kill) || ask_kill_program () then
name := make_absolute (expand_path argument)),
function ppf -> fprintf ppf "%s@." !name
let loading_mode_variable ppf =
(find_ident
"loading mode"
(matching_elements (ref loading_modes) fst)
(fun (_, mode) ppf lexbuf ->
eol lexbuf; set_launching_function mode)
(function ppf -> error "Syntax error.")
ppf),
function ppf ->
let rec find = function
| [] -> ()
| (name, funct) :: l ->
if funct == !launching_func then fprintf ppf "%s" name else find l
in
find loading_modes;
fprintf ppf "@."
let follow_fork_variable =
(function lexbuf ->
let mode =
match identifier_eol Lexer.lexeme lexbuf with
| "child" -> Fork_child
| "parent" -> Fork_parent
| _ -> error "Syntax error."
in
fork_mode := mode;
if !loaded then update_follow_fork_mode ()),
function ppf ->
fprintf ppf "%s@."
(match !fork_mode with
Fork_child -> "child"
| Fork_parent -> "parent")
(** Infos. **)
let pr_modules ppf mods =
let pr_mods ppf = List.iter (function x -> fprintf ppf "%s@ " x) in
fprintf ppf "Used modules :@.%a@?" pr_mods mods
let info_modules ppf lexbuf =
eol lexbuf;
ensure_loaded ();
pr_modules ppf !modules
(********
print_endline "Opened modules :";
if !opened_modules_names = [] then
print_endline "(no module opened)."
else
(List.iter (function x -> print_string x; print_space) !opened_modules_names;
print_newline ())
*********)
let info_checkpoints ppf lexbuf =
eol lexbuf;
if !checkpoints = [] then fprintf ppf "No checkpoint.@."
else
(if !debug_breakpoints then
(prerr_endline " Time Pid Version";
List.iter
(function
{c_time = time; c_pid = pid; c_breakpoint_version = version} ->
Printf.printf "%19Ld %5d %d\n" time pid version)
!checkpoints)
else
(print_endline " Time Pid";
List.iter
(function
{c_time = time; c_pid = pid} ->
Printf.printf "%19Ld %5d\n" time pid)
!checkpoints))
let info_one_breakpoint ppf (num, ev) =
fprintf ppf "%3d %10d %s@." num ev.ev_pos (Pos.get_desc ev);
;;
let info_breakpoints ppf lexbuf =
eol lexbuf;
if !breakpoints = [] then fprintf ppf "No breakpoints.@."
else begin
fprintf ppf "Num Address Where@.";
List.iter (info_one_breakpoint ppf) (List.rev !breakpoints);
end
;;
let info_events ppf lexbuf =
ensure_loaded ();
let mdle = convert_module (module_of_longident (opt_longident_eol Lexer.lexeme lexbuf)) in
print_endline ("Module : " ^ mdle);
print_endline " Address Characters Kind Repr.";
List.iter
(function ev ->
let start_char, end_char =
try
let buffer = get_buffer (Events.get_pos ev) ev.ev_module in
(snd (start_and_cnum buffer ev.ev_loc.Location.loc_start)),
(snd (start_and_cnum buffer ev.ev_loc.Location.loc_end))
with _ ->
ev.ev_loc.Location.loc_start.Lexing.pos_cnum,
ev.ev_loc.Location.loc_end.Lexing.pos_cnum in
Printf.printf
"%10d %6d-%-6d %10s %10s\n"
ev.ev_pos
start_char
end_char
((match ev.ev_kind with
Event_before -> "before"
| Event_after _ -> "after"
| Event_pseudo -> "pseudo")
^
(match ev.ev_info with
Event_function -> "/fun"
| Event_return _ -> "/ret"
| Event_other -> ""))
(match ev.ev_repr with
Event_none -> ""
| Event_parent _ -> "(repr)"
| Event_child repr -> string_of_int !repr))
(events_in_module mdle)
(** User-defined printers **)
let instr_load_printer ppf lexbuf =
let filename = extract_filename(argument_eol argument lexbuf) in
try
Loadprinter.loadfile ppf filename
with Loadprinter.Error e ->
Loadprinter.report_error ppf e; raise Toplevel
let instr_install_printer ppf lexbuf =
let lid = longident_eol Lexer.lexeme lexbuf in
try
Loadprinter.install_printer ppf lid
with Loadprinter.Error e ->
Loadprinter.report_error ppf e; raise Toplevel
let instr_remove_printer ppf lexbuf =
let lid = longident_eol Lexer.lexeme lexbuf in
try
Loadprinter.remove_printer lid
with Loadprinter.Error e ->
Loadprinter.report_error ppf e; raise Toplevel
(** Initialization. **)
let init ppf =
instruction_list := [
{ instr_name = "cd"; instr_prio = false;
instr_action = instr_cd; instr_repeat = true; instr_help =
"set working directory to DIR for debugger and program being debugged." };
{ instr_name = "complete"; instr_prio = false;
instr_action = instr_complete; instr_repeat = false; instr_help =
"complete word at cursor according to context. Useful for Emacs." };
{ instr_name = "pwd"; instr_prio = false;
instr_action = instr_pwd; instr_repeat = true; instr_help =
"print working directory." };
{ instr_name = "directory"; instr_prio = false;
instr_action = instr_dir; instr_repeat = false; instr_help =
"add directory DIR to beginning of search path for source and\n\
interface files.\n\
Forget cached info on source file locations and line positions.\n\
With no argument, reset the search path." };
{ instr_name = "kill"; instr_prio = false;
instr_action = instr_kill; instr_repeat = true; instr_help =
"kill the program being debugged." };
{ instr_name = "help"; instr_prio = false;
instr_action = instr_help; instr_repeat = true; instr_help =
"print list of commands." };
{ instr_name = "quit"; instr_prio = false;
instr_action = instr_quit; instr_repeat = false; instr_help =
"exit the debugger." };
{ instr_name = "shell"; instr_prio = false;
instr_action = instr_shell; instr_repeat = true; instr_help =
"Execute a given COMMAND thru the system shell." };
{ instr_name = "environment"; instr_prio = false;
instr_action = instr_env; instr_repeat = false; instr_help =
"environment variable to give to program being debugged when it is started." };
(* Displacements *)
{ instr_name = "run"; instr_prio = true;
instr_action = instr_run; instr_repeat = true; instr_help =
"run the program from current position." };
{ instr_name = "reverse"; instr_prio = false;
instr_action = instr_reverse; instr_repeat = true; instr_help =
"run the program backward from current position." };
{ instr_name = "step"; instr_prio = true;
instr_action = instr_step; instr_repeat = true; instr_help =
"step program until it reaches the next event.\n\
Argument N means do this N times (or till program stops for another reason)." };
{ instr_name = "backstep"; instr_prio = true;
instr_action = instr_back; instr_repeat = true; instr_help =
"step program backward until it reaches the previous event.\n\
Argument N means do this N times (or till program stops for another reason)." };
{ instr_name = "goto"; instr_prio = false;
instr_action = instr_goto; instr_repeat = true; instr_help =
"go to the given time." };
{ instr_name = "finish"; instr_prio = true;
instr_action = instr_finish; instr_repeat = true; instr_help =
"execute until topmost stack frame returns." };
{ instr_name = "next"; instr_prio = true;
instr_action = instr_next; instr_repeat = true; instr_help =
"step program until it reaches the next event.\n\
Skip over function calls.\n\
Argument N means do this N times (or till program stops for another reason)." };
{ instr_name = "start"; instr_prio = false;
instr_action = instr_start; instr_repeat = true; instr_help =
"execute backward until the current function is exited." };
{ instr_name = "previous"; instr_prio = false;
instr_action = instr_previous; instr_repeat = true; instr_help =
"step program until it reaches the previous event.\n\
Skip over function calls.\n\
Argument N means do this N times (or till program stops for another reason)." };
{ instr_name = "print"; instr_prio = true;
instr_action = instr_print; instr_repeat = true; instr_help =
"print value of expressions (deep printing)." };
{ instr_name = "display"; instr_prio = true;
instr_action = instr_display; instr_repeat = true; instr_help =
"print value of expressions (shallow printing)." };
{ instr_name = "source"; instr_prio = false;
instr_action = instr_source; instr_repeat = true; instr_help =
"read command from file FILE." };
Breakpoints
{ instr_name = "break"; instr_prio = false;
instr_action = instr_break; instr_repeat = false; instr_help =
"Set breakpoint at specified line or function.\
\nSyntax: break function-name\
\n break @ [module] linenum\
\n break @ [module] # characternum" };
{ instr_name = "delete"; instr_prio = false;
instr_action = instr_delete; instr_repeat = false; instr_help =
"delete some breakpoints.\n\
Arguments are breakpoint numbers with spaces in between.\n\
To delete all breakpoints, give no argument." };
{ instr_name = "set"; instr_prio = false;
instr_action = instr_set; instr_repeat = false; instr_help =
"--unused--" };
{ instr_name = "show"; instr_prio = false;
instr_action = instr_show; instr_repeat = true; instr_help =
"--unused--" };
{ instr_name = "info"; instr_prio = false;
instr_action = instr_info; instr_repeat = true; instr_help =
"--unused--" };
(* Frames *)
{ instr_name = "frame"; instr_prio = false;
instr_action = instr_frame; instr_repeat = true; instr_help =
"select and print a stack frame.\n\
With no argument, print the selected stack frame.\n\
An argument specifies the frame to select." };
{ instr_name = "backtrace"; instr_prio = false;
instr_action = instr_backtrace; instr_repeat = true; instr_help =
"print backtrace of all stack frames, or innermost COUNT frames.\n\
With a negative argument, print outermost -COUNT frames." };
{ instr_name = "bt"; instr_prio = false;
instr_action = instr_backtrace; instr_repeat = true; instr_help =
"print backtrace of all stack frames, or innermost COUNT frames.\n\
With a negative argument, print outermost -COUNT frames." };
{ instr_name = "up"; instr_prio = false;
instr_action = instr_up; instr_repeat = true; instr_help =
"select and print stack frame that called this one.\n\
An argument says how many frames up to go." };
{ instr_name = "down"; instr_prio = false;
instr_action = instr_down; instr_repeat = true; instr_help =
"select and print stack frame called by this one.\n\
An argument says how many frames down to go." };
{ instr_name = "last"; instr_prio = true;
instr_action = instr_last; instr_repeat = true; instr_help =
"go back to previous time." };
{ instr_name = "list"; instr_prio = false;
instr_action = instr_list; instr_repeat = true; instr_help =
"list the source code." };
(* User-defined printers *)
{ instr_name = "load_printer"; instr_prio = false;
instr_action = instr_load_printer; instr_repeat = false; instr_help =
"load in the debugger a .cmo or .cma file containing printing functions." };
{ instr_name = "install_printer"; instr_prio = false;
instr_action = instr_install_printer; instr_repeat = false; instr_help =
"use the given function for printing values of its input type.\n\
The code for the function must have previously been loaded in the debugger\n\
using \"load_printer\"." };
{ instr_name = "remove_printer"; instr_prio = false;
instr_action = instr_remove_printer; instr_repeat = false; instr_help =
"stop using the given function for printing values of its input type." }
];
variable_list := [
(* variable name, (writing, reading), help reading, help writing *)
{ var_name = "arguments";
var_action = raw_line_variable true arguments;
var_help =
"arguments to give program being debugged when it is started." };
{ var_name = "program";
var_action = path_variable true program_name;
var_help =
"name of program to be debugged." };
{ var_name = "loadingmode";
var_action = loading_mode_variable ppf;
var_help =
"mode of loading.\n\
It can be either :\n\
direct : the program is directly called by the debugger.\n\
runtime : the debugger execute `ocamlrun programname arguments'.\n\
manual : the program is not launched by the debugger,\n\
but manually by the user." };
{ var_name = "processcount";
var_action = integer_variable false 1 "Must be >= 1."
checkpoint_max_count;
var_help =
"maximum number of process to keep." };
{ var_name = "checkpoints";
var_action = boolean_variable false make_checkpoints;
var_help =
"whether to make checkpoints or not." };
{ var_name = "bigstep";
var_action = int64_variable false _1 "Must be >= 1."
checkpoint_big_step;
var_help =
"step between checkpoints during long displacements." };
{ var_name = "smallstep";
var_action = int64_variable false _1 "Must be >= 1."
checkpoint_small_step;
var_help =
"step between checkpoints during small displacements." };
{ var_name = "socket";
var_action = raw_variable true socket_name;
var_help =
"name of the socket used by communications debugger-runtime." };
{ var_name = "history";
var_action = integer_variable false 0 "" history_size;
var_help =
"history size." };
{ var_name = "print_depth";
var_action = integer_variable false 1 "Must be at least 1"
max_printer_depth;
var_help =
"maximal depth for printing of values." };
{ var_name = "print_length";
var_action = integer_variable false 1 "Must be at least 1"
max_printer_steps;
var_help =
"maximal number of value nodes printed." };
{ var_name = "follow_fork_mode";
var_action = follow_fork_variable;
var_help =
"process to follow after forking.\n\
It can be either :
child : the newly created process.\n\
parent : the process that called fork.\n" }];
info_list :=
(* info name, function, help *)
[{ info_name = "modules";
info_action = info_modules ppf;
info_help = "list opened modules." };
{ info_name = "checkpoints";
info_action = info_checkpoints ppf;
info_help = "list checkpoints." };
{ info_name = "breakpoints";
info_action = info_breakpoints ppf;
info_help = "list breakpoints." };
{ info_name = "events";
info_action = info_events ppf;
info_help = "list events in MODULE (default is current module)." }]
let _ = init std_formatter
| null | https://raw.githubusercontent.com/bmeurer/ocaml-arm/43f7689c76a349febe3d06ae7a4fc1d52984fd8b/debugger/command_line.ml | ocaml | *********************************************************************
OCaml
*********************************************************************
*********************** Reading and executing commands **************
* Instructions, variables and infos lists. *
Name of command
Has priority
What to do
Can be repeated
Help message
Name of variable
Help message
Name of info
What to do
Help message
* Utilities. *
* Instructions. *
Printing values
Loading of command files
Allow enclosing filename in quotes
break
break PC
break FUNCTION
break @ [MODULE] LINE [COL]
event_at_pos / event_near pos
pos_of_line / point_of_coord
break @ [MODULE] # POSITION
* Variables. *
* Infos. *
*******
print_endline "Opened modules :";
if !opened_modules_names = [] then
print_endline "(no module opened)."
else
(List.iter (function x -> print_string x; print_space) !opened_modules_names;
print_newline ())
********
* User-defined printers *
* Initialization. *
Displacements
Frames
User-defined printers
variable name, (writing, reading), help reading, help writing
info name, function, help | , projet Cristal , INRIA Rocquencourt
OCaml port by and
Copyright 1996 Institut National de Recherche en Informatique et
en Automatique . All rights reserved . This file is distributed
under the terms of the Q Public License version 1.0 .
$ Id$
open Int64ops
open Format
open Misc
open Instruct
open Unix
open Debugger_config
open Types
open Primitives
open Unix_tools
open Parser
open Parser_aux
open Lexer
open Input_handling
open Question
open Debugcom
open Program_loading
open Program_management
open Lexing
open Parameters
open Show_source
open Show_information
open Time_travel
open Events
open Symbols
open Source
open Breakpoints
open Checkpoints
open Frames
open Printval
type dbg_instruction =
instr_action: formatter -> lexbuf -> unit;
let instruction_list = ref ([] : dbg_instruction list)
type dbg_variable =
var_action: (lexbuf -> unit) * (formatter -> unit);
Reading , writing fns
let variable_list = ref ([] : dbg_variable list)
type dbg_info =
let info_list = ref ([] : dbg_info list)
let error text =
eprintf "%s@." text;
raise Toplevel
let check_not_windows feature =
match Sys.os_type with
| "Win32" ->
error ("'"^feature^"' feature not supported on Windows")
| _ ->
()
let eol =
end_of_line Lexer.lexeme
let matching_elements list name instr =
List.filter (function a -> isprefix instr (name a)) !list
let all_matching_instructions =
matching_elements instruction_list (fun i -> i.instr_name)
itz 04 - 21 - 96 do n't do priority completion in emacs mode
XL 25 - 02 - 97 why ? I find it very confusing .
let matching_instructions instr =
let all = all_matching_instructions instr in
let prio = List.filter (fun i -> i.instr_prio) all in
if prio = [] then all else prio
let matching_variables =
matching_elements variable_list (fun v -> v.var_name)
let matching_infos =
matching_elements info_list (fun i -> i.info_name)
let find_ident name matcher action alternative ppf lexbuf =
match identifier_or_eol Lexer.lexeme lexbuf with
| None -> alternative ppf
| Some ident ->
match matcher ident with
| [] -> error ("Unknown " ^ name ^ ".")
| [a] -> action a ppf lexbuf
| _ -> error ("Ambiguous " ^ name ^ ".")
let find_variable action alternative ppf lexbuf =
find_ident "variable name" matching_variables action alternative ppf lexbuf
let find_info action alternative ppf lexbuf =
find_ident "info command" matching_infos action alternative ppf lexbuf
let add_breakpoint_at_pc pc =
try
new_breakpoint (any_event_at_pc pc)
with
| Not_found ->
eprintf "Can't add breakpoint at pc %i : no event there.@." pc;
raise Toplevel
let add_breakpoint_after_pc pc =
let rec try_add n =
if n < 3 then begin
try
new_breakpoint (any_event_at_pc (pc + n * 4))
with
| Not_found ->
try_add (n+1)
end else begin
error
"Can't add breakpoint at beginning of function: no event there"
end
in try_add 0
let module_of_longident id =
match id with
| Some x -> Some (String.concat "." (Longident.flatten x))
| None -> None
let convert_module mdle =
match mdle with
| Some m ->
Strip .ml extension if any , and capitalize
String.capitalize(if Filename.check_suffix m ".ml"
then Filename.chop_suffix m ".ml"
else m)
| None ->
try
(get_current_event ()).ev_module
with
| Not_found ->
error "Not in a module."
* Toplevel . *
let current_line = ref ""
let interprete_line ppf line =
current_line := line;
let lexbuf = Lexing.from_string line in
try
match identifier_or_eol Lexer.lexeme lexbuf with
| Some x ->
begin match matching_instructions x with
| [] ->
error "Unknown command."
| [i] ->
i.instr_action ppf lexbuf;
resume_user_input ();
i.instr_repeat
| l ->
error "Ambiguous command."
end
| None ->
resume_user_input ();
false
with
| Parsing.Parse_error ->
error "Syntax error."
let line_loop ppf line_buffer =
resume_user_input ();
let previous_line = ref "" in
try
while true do
if !loaded then
History.add_current_time ();
let new_line = string_trim (line line_buffer) in
let line =
if new_line <> "" then
new_line
else
!previous_line
in
previous_line := "";
if interprete_line ppf line then
previous_line := line
done
with
| Exit ->
stop_user_input ()
| s - >
error ( " System error : " ^ s )
error ("System error : " ^ s) *)
let instr_cd ppf lexbuf =
let dir = argument_eol argument lexbuf in
if ask_kill_program () then
try
Sys.chdir (expand_path dir)
with
| Sys_error s ->
error s
let instr_shell ppf lexbuf =
let cmdarg = argument_list_eol argument lexbuf in
let cmd = String.concat " " cmdarg in
perhaps we should use $ SHELL -c ?
let err = Sys.command cmd in
if (err != 0) then
eprintf "Shell command %S failed with exit code %d\n%!" cmd err
let instr_env ppf lexbuf =
let cmdarg = argument_list_eol argument lexbuf in
let cmdarg = string_trim (String.concat " " cmdarg) in
if cmdarg <> "" then
try
if (String.index cmdarg '=') > 0 then
Debugger_config.environment := cmdarg :: !Debugger_config.environment
else
eprintf "Environment variables should not have an empty name\n%!"
with Not_found ->
eprintf "Environment variables should have the \"name=value\" format\n%!"
else
List.iter
(printf "%s\n%!")
(List.rev !Debugger_config.environment)
let instr_pwd ppf lexbuf =
eol lexbuf;
fprintf ppf "%s@." (Sys.getcwd ())
let instr_dir ppf lexbuf =
let new_directory = argument_list_eol argument lexbuf in
if new_directory = [] then begin
if yes_or_no "Reinitialize directory list" then begin
Config.load_path := !default_load_path;
Envaux.reset_cache ();
Hashtbl.clear Debugger_config.load_path_for;
flush_buffer_list ()
end
end
else begin
let new_directory' = List.rev new_directory in
match new_directory' with
| mdl :: for_keyw :: tl when (String.lowercase for_keyw) = "for" && (List.length tl) > 0 ->
List.iter (function x -> add_path_for mdl (expand_path x)) tl
| _ ->
List.iter (function x -> add_path (expand_path x)) new_directory'
end;
let print_dirs ppf l = List.iter (function x -> fprintf ppf "@ %s" x) l in
fprintf ppf "@[<2>Directories :%a@]@." print_dirs !Config.load_path;
Hashtbl.iter
(fun mdl dirs ->
fprintf ppf "@[<2>Source directories for %s :%a@]@." mdl print_dirs dirs)
Debugger_config.load_path_for
let instr_kill ppf lexbuf =
eol lexbuf;
if not !loaded then error "The program is not being run.";
if (yes_or_no "Kill the program being debugged") then begin
kill_program ();
show_no_point()
end
let instr_run ppf lexbuf =
eol lexbuf;
ensure_loaded ();
reset_named_values ();
run ();
show_current_event ppf;;
let instr_reverse ppf lexbuf =
eol lexbuf;
check_not_windows "reverse";
ensure_loaded ();
reset_named_values();
back_run ();
show_current_event ppf
let instr_step ppf lexbuf =
let step_count =
match opt_signed_int64_eol Lexer.lexeme lexbuf with
| None -> _1
| Some x -> x
in
ensure_loaded ();
reset_named_values();
step step_count;
show_current_event ppf
let instr_back ppf lexbuf =
let step_count =
match opt_signed_int64_eol Lexer.lexeme lexbuf with
| None -> _1
| Some x -> x
in
check_not_windows "backstep";
ensure_loaded ();
reset_named_values();
step (_0 -- step_count);
show_current_event ppf
let instr_finish ppf lexbuf =
eol lexbuf;
ensure_loaded ();
reset_named_values();
finish ();
show_current_event ppf
let instr_next ppf lexbuf =
let step_count =
match opt_integer_eol Lexer.lexeme lexbuf with
| None -> 1
| Some x -> x
in
ensure_loaded ();
reset_named_values();
next step_count;
show_current_event ppf
let instr_start ppf lexbuf =
eol lexbuf;
check_not_windows "start";
ensure_loaded ();
reset_named_values();
start ();
show_current_event ppf
let instr_previous ppf lexbuf =
let step_count =
match opt_integer_eol Lexer.lexeme lexbuf with
| None -> 1
| Some x -> x
in
check_not_windows "previous";
ensure_loaded ();
reset_named_values();
previous step_count;
show_current_event ppf
let instr_goto ppf lexbuf =
let time = int64_eol Lexer.lexeme lexbuf in
ensure_loaded ();
reset_named_values();
go_to time;
show_current_event ppf
let instr_quit _ =
raise Exit
let print_variable_list ppf =
let pr_vars ppf = List.iter (fun v -> fprintf ppf "%s@ " v.var_name) in
fprintf ppf "List of variables :%a@." pr_vars !variable_list
let print_info_list ppf =
let pr_infos ppf = List.iter (fun i -> fprintf ppf "%s@ " i.info_name) in
fprintf ppf "List of info commands :%a@." pr_infos !info_list
let instr_complete ppf lexbuf =
let ppf = Format.err_formatter in
let rec print_list l =
try
eol lexbuf;
List.iter (function i -> fprintf ppf "%s@." i) l
with _ ->
remove_file !user_channel
and match_list lexbuf =
match identifier_or_eol Lexer.lexeme lexbuf with
| None ->
List.map (fun i -> i.instr_name) !instruction_list
| Some x ->
match matching_instructions x with
| [ {instr_name = ("set" | "show" as i_full)} ] ->
if x = i_full then begin
match identifier_or_eol Lexer.lexeme lexbuf with
| Some ident ->
begin match matching_variables ident with
| [v] -> if v.var_name = ident then [] else [v.var_name]
| l -> List.map (fun v -> v.var_name) l
end
| None ->
List.map (fun v -> v.var_name) !variable_list
end
else [i_full]
| [ {instr_name = "info"} ] ->
if x = "info" then begin
match identifier_or_eol Lexer.lexeme lexbuf with
| Some ident ->
begin match matching_infos ident with
| [i] -> if i.info_name = ident then [] else [i.info_name]
| l -> List.map (fun i -> i.info_name) l
end
| None ->
List.map (fun i -> i.info_name) !info_list
end
else ["info"]
| [ {instr_name = "help"} ] ->
if x = "help" then match_list lexbuf else ["help"]
| [ i ] ->
if x = i.instr_name then [] else [i.instr_name]
| l ->
List.map (fun i -> i.instr_name) l
in
print_list(match_list lexbuf)
let instr_help ppf lexbuf =
let pr_instrs ppf =
List.iter (fun i -> fprintf ppf "%s@ " i.instr_name) in
match identifier_or_eol Lexer.lexeme lexbuf with
| Some x ->
let print_help nm hlp =
eol lexbuf;
fprintf ppf "%s : %s@." nm hlp in
begin match matching_instructions x with
| [] ->
eol lexbuf;
fprintf ppf "No matching command.@."
| [ {instr_name = "set"} ] ->
find_variable
(fun v _ _ ->
print_help ("set " ^ v.var_name) ("set " ^ v.var_help))
(fun ppf ->
print_help "set" "set debugger variable.";
print_variable_list ppf)
ppf
lexbuf
| [ {instr_name = "show"} ] ->
find_variable
(fun v _ _ ->
print_help ("show " ^ v.var_name) ("show " ^ v.var_help))
(fun v ->
print_help "show" "display debugger variable.";
print_variable_list ppf)
ppf
lexbuf
| [ {instr_name = "info"} ] ->
find_info
(fun i _ _ -> print_help ("info " ^ i.info_name) i.info_help)
(fun ppf ->
print_help "info"
"display infos about the program being debugged.";
print_info_list ppf)
ppf
lexbuf
| [i] ->
print_help i.instr_name i.instr_help
| l ->
eol lexbuf;
fprintf ppf "Ambiguous command \"%s\" : %a@." x pr_instrs l
end
| None ->
fprintf ppf "List of commands : %a@." pr_instrs !instruction_list
let print_expr depth ev env ppf expr =
try
let (v, ty) = Eval.expression ev env expr in
print_named_value depth expr env v ppf ty
with
| Eval.Error msg ->
Eval.report_error ppf msg;
raise Toplevel
let print_command depth ppf lexbuf =
let exprs = expression_list_eol Lexer.lexeme lexbuf in
ensure_loaded ();
let env =
try
Envaux.env_of_event !selected_event
with
| Envaux.Error msg ->
Envaux.report_error ppf msg;
raise Toplevel
in
List.iter (print_expr depth !selected_event env ppf) exprs
let instr_print ppf lexbuf = print_command !max_printer_depth ppf lexbuf
let instr_display ppf lexbuf = print_command 1 ppf lexbuf
let extract_filename arg =
let l = String.length arg in
let pos1 = if l > 0 && arg.[0] = '"' then 1 else 0 in
let pos2 = if l > 0 && arg.[l-1] = '"' then l-1 else l in
String.sub arg pos1 (pos2 - pos1)
let instr_source ppf lexbuf =
let file = extract_filename(argument_eol argument lexbuf)
and old_state = !interactif
and old_channel = !user_channel in
let io_chan =
try
io_channel_of_descr
(openfile (find_in_path !Config.load_path (expand_path file))
[O_RDONLY] 0)
with
| Not_found -> error "Source file not found."
| (Unix_error _) as x -> Unix_tools.report_error x; raise Toplevel
in
try
interactif := false;
user_channel := io_chan;
line_loop ppf (Lexing.from_function read_user_input);
close_io io_chan;
interactif := old_state;
user_channel := old_channel
with
| x ->
stop_user_input ();
close_io io_chan;
interactif := old_state;
user_channel := old_channel;
raise x
let instr_set =
find_variable
(fun {var_action = (funct, _)} ppf lexbuf -> funct lexbuf)
(function ppf -> error "Argument required.")
let instr_show =
find_variable
(fun {var_action = (_, funct)} ppf lexbuf -> eol lexbuf; funct ppf)
(function ppf ->
List.iter
(function {var_name = nm; var_action = (_, funct)} ->
fprintf ppf "%s : " nm;
funct ppf)
!variable_list)
let instr_info =
find_info
(fun i ppf lexbuf -> i.info_action lexbuf)
(function ppf ->
error "\"info\" must be followed by the name of an info command.")
let instr_break ppf lexbuf =
let argument = break_argument_eol Lexer.lexeme lexbuf in
ensure_loaded ();
match argument with
(match !selected_event with
| Some ev ->
new_breakpoint ev
| None ->
error "Can't add breakpoint at this point.")
add_breakpoint_at_pc pc
let env =
try
Envaux.env_of_event !selected_event
with
| Envaux.Error msg ->
Envaux.report_error ppf msg;
raise Toplevel
in
begin try
let (v, ty) = Eval.expression !selected_event env expr in
match (Ctype.repr ty).desc with
| Tarrow _ ->
add_breakpoint_after_pc (Remote_value.closure_code v)
| _ ->
eprintf "Not a function.@.";
raise Toplevel
with
| Eval.Error msg ->
Eval.report_error ppf msg;
raise Toplevel
end
let module_name = convert_module (module_of_longident mdle) in
new_breakpoint
(try
let buffer =
try get_buffer Lexing.dummy_pos module_name with
| Not_found ->
eprintf "No source file for %s.@." module_name;
raise Toplevel
in
match column with
| None ->
event_at_pos module_name (fst (pos_of_line buffer line))
| Some col ->
event_near_pos module_name (point_of_coord buffer line col)
with
eprintf "Can't find any event there.@.";
raise Toplevel
eprintf "Position out of range.@.";
raise Toplevel)
try
new_breakpoint (event_near_pos (convert_module (module_of_longident mdle)) position)
with
| Not_found ->
eprintf "Can't find any event there.@."
let instr_delete ppf lexbuf =
match integer_list_eol Lexer.lexeme lexbuf with
| [] ->
if breakpoints_count () <> 0 && yes_or_no "Delete all breakpoints"
then remove_all_breakpoints ()
| breakpoints ->
List.iter
(function x -> try remove_breakpoint x with | Not_found -> ())
breakpoints
let instr_frame ppf lexbuf =
let frame_number =
match opt_integer_eol Lexer.lexeme lexbuf with
| None -> !current_frame
| Some x -> x
in
ensure_loaded ();
try
select_frame frame_number;
show_current_frame ppf true
with
| Not_found ->
error ("No frame number " ^ string_of_int frame_number ^ ".")
let instr_backtrace ppf lexbuf =
let number =
match opt_signed_integer_eol Lexer.lexeme lexbuf with
| None -> 0
| Some x -> x in
ensure_loaded ();
match current_report() with
| None | Some {rep_type = Exited | Uncaught_exc} -> ()
| Some _ ->
let frame_counter = ref 0 in
let print_frame first_frame last_frame = function
| None ->
fprintf ppf
"(Encountered a function with no debugging information)@.";
false
| Some event ->
if !frame_counter >= first_frame then
show_one_frame !frame_counter ppf event;
incr frame_counter;
if !frame_counter >= last_frame then begin
fprintf ppf "(More frames follow)@."
end;
!frame_counter < last_frame in
fprintf ppf "Backtrace:@.";
if number = 0 then
do_backtrace (print_frame 0 max_int)
else if number > 0 then
do_backtrace (print_frame 0 number)
else begin
let num_frames = stack_depth() in
if num_frames < 0 then
fprintf ppf
"(Encountered a function with no debugging information)@."
else
do_backtrace (print_frame (num_frames + number) max_int)
end
let instr_up ppf lexbuf =
let offset =
match opt_signed_integer_eol Lexer.lexeme lexbuf with
| None -> 1
| Some x -> x
in
ensure_loaded ();
try
select_frame (!current_frame + offset);
show_current_frame ppf true
with
| Not_found -> error "No such frame."
let instr_down ppf lexbuf =
let offset =
match opt_signed_integer_eol Lexer.lexeme lexbuf with
| None -> 1
| Some x -> x
in
ensure_loaded ();
try
select_frame (!current_frame - offset);
show_current_frame ppf true
with
| Not_found -> error "No such frame."
let instr_last ppf lexbuf =
let count =
match opt_signed_int64_eol Lexer.lexeme lexbuf with
| None -> _1
| Some x -> x
in
check_not_windows "last";
reset_named_values();
go_to (History.previous_time count);
show_current_event ppf
let instr_list ppf lexbuf =
let (mo, beg, e) = list_arguments_eol Lexer.lexeme lexbuf in
let (curr_mod, line, column) =
try
selected_point ()
with
| Not_found ->
("", -1, -1)
in
let mdle = convert_module (module_of_longident mo) in
let pos = Lexing.dummy_pos in
let buffer =
try get_buffer pos mdle with
| Not_found -> error ("No source file for " ^ mdle ^ ".") in
let point =
if column <> -1 then
(point_of_coord buffer line 1) + column
else
-1 in
let beginning =
match beg with
| None when (mo <> None) || (line = -1) ->
1
| None ->
begin try
max 1 (line - 10)
with Out_of_range ->
1
end
| Some x -> x
in
let en =
match e with
| None -> beginning + 20
| Some x -> x
in
if mdle = curr_mod then
show_listing pos mdle beginning en point
(current_event_is_before ())
else
show_listing pos mdle beginning en (-1) true
let raw_variable kill name =
(function lexbuf ->
let argument = argument_eol argument lexbuf in
if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%s@." !name
let raw_line_variable kill name =
(function lexbuf ->
let argument = argument_eol line_argument lexbuf in
if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%s@." !name
let integer_variable kill min msg name =
(function lexbuf ->
let argument = integer_eol Lexer.lexeme lexbuf in
if argument < min then print_endline msg
else if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%i@." !name
let int64_variable kill min msg name =
(function lexbuf ->
let argument = int64_eol Lexer.lexeme lexbuf in
if argument < min then print_endline msg
else if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%Li@." !name
let boolean_variable kill name =
(function lexbuf ->
let argument =
match identifier_eol Lexer.lexeme lexbuf with
| "on" -> true
| "of" | "off" -> false
| _ -> error "Syntax error."
in
if (not kill) || ask_kill_program () then name := argument),
function ppf -> fprintf ppf "%s@." (if !name then "on" else "off")
let path_variable kill name =
(function lexbuf ->
let argument = argument_eol argument lexbuf in
if (not kill) || ask_kill_program () then
name := make_absolute (expand_path argument)),
function ppf -> fprintf ppf "%s@." !name
let loading_mode_variable ppf =
(find_ident
"loading mode"
(matching_elements (ref loading_modes) fst)
(fun (_, mode) ppf lexbuf ->
eol lexbuf; set_launching_function mode)
(function ppf -> error "Syntax error.")
ppf),
function ppf ->
let rec find = function
| [] -> ()
| (name, funct) :: l ->
if funct == !launching_func then fprintf ppf "%s" name else find l
in
find loading_modes;
fprintf ppf "@."
let follow_fork_variable =
(function lexbuf ->
let mode =
match identifier_eol Lexer.lexeme lexbuf with
| "child" -> Fork_child
| "parent" -> Fork_parent
| _ -> error "Syntax error."
in
fork_mode := mode;
if !loaded then update_follow_fork_mode ()),
function ppf ->
fprintf ppf "%s@."
(match !fork_mode with
Fork_child -> "child"
| Fork_parent -> "parent")
let pr_modules ppf mods =
let pr_mods ppf = List.iter (function x -> fprintf ppf "%s@ " x) in
fprintf ppf "Used modules :@.%a@?" pr_mods mods
let info_modules ppf lexbuf =
eol lexbuf;
ensure_loaded ();
pr_modules ppf !modules
let info_checkpoints ppf lexbuf =
eol lexbuf;
if !checkpoints = [] then fprintf ppf "No checkpoint.@."
else
(if !debug_breakpoints then
(prerr_endline " Time Pid Version";
List.iter
(function
{c_time = time; c_pid = pid; c_breakpoint_version = version} ->
Printf.printf "%19Ld %5d %d\n" time pid version)
!checkpoints)
else
(print_endline " Time Pid";
List.iter
(function
{c_time = time; c_pid = pid} ->
Printf.printf "%19Ld %5d\n" time pid)
!checkpoints))
let info_one_breakpoint ppf (num, ev) =
fprintf ppf "%3d %10d %s@." num ev.ev_pos (Pos.get_desc ev);
;;
let info_breakpoints ppf lexbuf =
eol lexbuf;
if !breakpoints = [] then fprintf ppf "No breakpoints.@."
else begin
fprintf ppf "Num Address Where@.";
List.iter (info_one_breakpoint ppf) (List.rev !breakpoints);
end
;;
let info_events ppf lexbuf =
ensure_loaded ();
let mdle = convert_module (module_of_longident (opt_longident_eol Lexer.lexeme lexbuf)) in
print_endline ("Module : " ^ mdle);
print_endline " Address Characters Kind Repr.";
List.iter
(function ev ->
let start_char, end_char =
try
let buffer = get_buffer (Events.get_pos ev) ev.ev_module in
(snd (start_and_cnum buffer ev.ev_loc.Location.loc_start)),
(snd (start_and_cnum buffer ev.ev_loc.Location.loc_end))
with _ ->
ev.ev_loc.Location.loc_start.Lexing.pos_cnum,
ev.ev_loc.Location.loc_end.Lexing.pos_cnum in
Printf.printf
"%10d %6d-%-6d %10s %10s\n"
ev.ev_pos
start_char
end_char
((match ev.ev_kind with
Event_before -> "before"
| Event_after _ -> "after"
| Event_pseudo -> "pseudo")
^
(match ev.ev_info with
Event_function -> "/fun"
| Event_return _ -> "/ret"
| Event_other -> ""))
(match ev.ev_repr with
Event_none -> ""
| Event_parent _ -> "(repr)"
| Event_child repr -> string_of_int !repr))
(events_in_module mdle)
let instr_load_printer ppf lexbuf =
let filename = extract_filename(argument_eol argument lexbuf) in
try
Loadprinter.loadfile ppf filename
with Loadprinter.Error e ->
Loadprinter.report_error ppf e; raise Toplevel
let instr_install_printer ppf lexbuf =
let lid = longident_eol Lexer.lexeme lexbuf in
try
Loadprinter.install_printer ppf lid
with Loadprinter.Error e ->
Loadprinter.report_error ppf e; raise Toplevel
let instr_remove_printer ppf lexbuf =
let lid = longident_eol Lexer.lexeme lexbuf in
try
Loadprinter.remove_printer lid
with Loadprinter.Error e ->
Loadprinter.report_error ppf e; raise Toplevel
let init ppf =
instruction_list := [
{ instr_name = "cd"; instr_prio = false;
instr_action = instr_cd; instr_repeat = true; instr_help =
"set working directory to DIR for debugger and program being debugged." };
{ instr_name = "complete"; instr_prio = false;
instr_action = instr_complete; instr_repeat = false; instr_help =
"complete word at cursor according to context. Useful for Emacs." };
{ instr_name = "pwd"; instr_prio = false;
instr_action = instr_pwd; instr_repeat = true; instr_help =
"print working directory." };
{ instr_name = "directory"; instr_prio = false;
instr_action = instr_dir; instr_repeat = false; instr_help =
"add directory DIR to beginning of search path for source and\n\
interface files.\n\
Forget cached info on source file locations and line positions.\n\
With no argument, reset the search path." };
{ instr_name = "kill"; instr_prio = false;
instr_action = instr_kill; instr_repeat = true; instr_help =
"kill the program being debugged." };
{ instr_name = "help"; instr_prio = false;
instr_action = instr_help; instr_repeat = true; instr_help =
"print list of commands." };
{ instr_name = "quit"; instr_prio = false;
instr_action = instr_quit; instr_repeat = false; instr_help =
"exit the debugger." };
{ instr_name = "shell"; instr_prio = false;
instr_action = instr_shell; instr_repeat = true; instr_help =
"Execute a given COMMAND thru the system shell." };
{ instr_name = "environment"; instr_prio = false;
instr_action = instr_env; instr_repeat = false; instr_help =
"environment variable to give to program being debugged when it is started." };
{ instr_name = "run"; instr_prio = true;
instr_action = instr_run; instr_repeat = true; instr_help =
"run the program from current position." };
{ instr_name = "reverse"; instr_prio = false;
instr_action = instr_reverse; instr_repeat = true; instr_help =
"run the program backward from current position." };
{ instr_name = "step"; instr_prio = true;
instr_action = instr_step; instr_repeat = true; instr_help =
"step program until it reaches the next event.\n\
Argument N means do this N times (or till program stops for another reason)." };
{ instr_name = "backstep"; instr_prio = true;
instr_action = instr_back; instr_repeat = true; instr_help =
"step program backward until it reaches the previous event.\n\
Argument N means do this N times (or till program stops for another reason)." };
{ instr_name = "goto"; instr_prio = false;
instr_action = instr_goto; instr_repeat = true; instr_help =
"go to the given time." };
{ instr_name = "finish"; instr_prio = true;
instr_action = instr_finish; instr_repeat = true; instr_help =
"execute until topmost stack frame returns." };
{ instr_name = "next"; instr_prio = true;
instr_action = instr_next; instr_repeat = true; instr_help =
"step program until it reaches the next event.\n\
Skip over function calls.\n\
Argument N means do this N times (or till program stops for another reason)." };
{ instr_name = "start"; instr_prio = false;
instr_action = instr_start; instr_repeat = true; instr_help =
"execute backward until the current function is exited." };
{ instr_name = "previous"; instr_prio = false;
instr_action = instr_previous; instr_repeat = true; instr_help =
"step program until it reaches the previous event.\n\
Skip over function calls.\n\
Argument N means do this N times (or till program stops for another reason)." };
{ instr_name = "print"; instr_prio = true;
instr_action = instr_print; instr_repeat = true; instr_help =
"print value of expressions (deep printing)." };
{ instr_name = "display"; instr_prio = true;
instr_action = instr_display; instr_repeat = true; instr_help =
"print value of expressions (shallow printing)." };
{ instr_name = "source"; instr_prio = false;
instr_action = instr_source; instr_repeat = true; instr_help =
"read command from file FILE." };
Breakpoints
{ instr_name = "break"; instr_prio = false;
instr_action = instr_break; instr_repeat = false; instr_help =
"Set breakpoint at specified line or function.\
\nSyntax: break function-name\
\n break @ [module] linenum\
\n break @ [module] # characternum" };
{ instr_name = "delete"; instr_prio = false;
instr_action = instr_delete; instr_repeat = false; instr_help =
"delete some breakpoints.\n\
Arguments are breakpoint numbers with spaces in between.\n\
To delete all breakpoints, give no argument." };
{ instr_name = "set"; instr_prio = false;
instr_action = instr_set; instr_repeat = false; instr_help =
"--unused--" };
{ instr_name = "show"; instr_prio = false;
instr_action = instr_show; instr_repeat = true; instr_help =
"--unused--" };
{ instr_name = "info"; instr_prio = false;
instr_action = instr_info; instr_repeat = true; instr_help =
"--unused--" };
{ instr_name = "frame"; instr_prio = false;
instr_action = instr_frame; instr_repeat = true; instr_help =
"select and print a stack frame.\n\
With no argument, print the selected stack frame.\n\
An argument specifies the frame to select." };
{ instr_name = "backtrace"; instr_prio = false;
instr_action = instr_backtrace; instr_repeat = true; instr_help =
"print backtrace of all stack frames, or innermost COUNT frames.\n\
With a negative argument, print outermost -COUNT frames." };
{ instr_name = "bt"; instr_prio = false;
instr_action = instr_backtrace; instr_repeat = true; instr_help =
"print backtrace of all stack frames, or innermost COUNT frames.\n\
With a negative argument, print outermost -COUNT frames." };
{ instr_name = "up"; instr_prio = false;
instr_action = instr_up; instr_repeat = true; instr_help =
"select and print stack frame that called this one.\n\
An argument says how many frames up to go." };
{ instr_name = "down"; instr_prio = false;
instr_action = instr_down; instr_repeat = true; instr_help =
"select and print stack frame called by this one.\n\
An argument says how many frames down to go." };
{ instr_name = "last"; instr_prio = true;
instr_action = instr_last; instr_repeat = true; instr_help =
"go back to previous time." };
{ instr_name = "list"; instr_prio = false;
instr_action = instr_list; instr_repeat = true; instr_help =
"list the source code." };
{ instr_name = "load_printer"; instr_prio = false;
instr_action = instr_load_printer; instr_repeat = false; instr_help =
"load in the debugger a .cmo or .cma file containing printing functions." };
{ instr_name = "install_printer"; instr_prio = false;
instr_action = instr_install_printer; instr_repeat = false; instr_help =
"use the given function for printing values of its input type.\n\
The code for the function must have previously been loaded in the debugger\n\
using \"load_printer\"." };
{ instr_name = "remove_printer"; instr_prio = false;
instr_action = instr_remove_printer; instr_repeat = false; instr_help =
"stop using the given function for printing values of its input type." }
];
variable_list := [
{ var_name = "arguments";
var_action = raw_line_variable true arguments;
var_help =
"arguments to give program being debugged when it is started." };
{ var_name = "program";
var_action = path_variable true program_name;
var_help =
"name of program to be debugged." };
{ var_name = "loadingmode";
var_action = loading_mode_variable ppf;
var_help =
"mode of loading.\n\
It can be either :\n\
direct : the program is directly called by the debugger.\n\
runtime : the debugger execute `ocamlrun programname arguments'.\n\
manual : the program is not launched by the debugger,\n\
but manually by the user." };
{ var_name = "processcount";
var_action = integer_variable false 1 "Must be >= 1."
checkpoint_max_count;
var_help =
"maximum number of process to keep." };
{ var_name = "checkpoints";
var_action = boolean_variable false make_checkpoints;
var_help =
"whether to make checkpoints or not." };
{ var_name = "bigstep";
var_action = int64_variable false _1 "Must be >= 1."
checkpoint_big_step;
var_help =
"step between checkpoints during long displacements." };
{ var_name = "smallstep";
var_action = int64_variable false _1 "Must be >= 1."
checkpoint_small_step;
var_help =
"step between checkpoints during small displacements." };
{ var_name = "socket";
var_action = raw_variable true socket_name;
var_help =
"name of the socket used by communications debugger-runtime." };
{ var_name = "history";
var_action = integer_variable false 0 "" history_size;
var_help =
"history size." };
{ var_name = "print_depth";
var_action = integer_variable false 1 "Must be at least 1"
max_printer_depth;
var_help =
"maximal depth for printing of values." };
{ var_name = "print_length";
var_action = integer_variable false 1 "Must be at least 1"
max_printer_steps;
var_help =
"maximal number of value nodes printed." };
{ var_name = "follow_fork_mode";
var_action = follow_fork_variable;
var_help =
"process to follow after forking.\n\
It can be either :
child : the newly created process.\n\
parent : the process that called fork.\n" }];
info_list :=
[{ info_name = "modules";
info_action = info_modules ppf;
info_help = "list opened modules." };
{ info_name = "checkpoints";
info_action = info_checkpoints ppf;
info_help = "list checkpoints." };
{ info_name = "breakpoints";
info_action = info_breakpoints ppf;
info_help = "list breakpoints." };
{ info_name = "events";
info_action = info_events ppf;
info_help = "list events in MODULE (default is current module)." }]
let _ = init std_formatter
|
ae59504c18a84c1bdf5fbb6245aa6c705c6979d7d3e48eea1bbbfc19eb7c1f4f | melhadad/fuf | copypath.lisp | ;;; -*- Mode:Lisp; Syntax:Common-Lisp; Package: FUG5 -*-
;;; -----------------------------------------------------------------------
;;; File: copypath.l
Description : 's copying path instead of conflating
Author :
Created : 23 Feb 1993
;;; Modified:
Package : FUG5
;;; -----------------------------------------------------------------------
;;;
FUF - a functional unification - based text generation system . ( . 5.4 )
;;;
Copyright ( c ) 1987 - 2014 by . all rights reserved .
;;;
;;; Permission to use, copy, and/or distribute for any purpose and
;;; without fee is hereby granted, provided that both the above copyright
;;; notice and this permission notice appear in all copies and derived works.
;;; Fees for distribution or use of this software or derived works may only
;;; be charged with express written permission of the copyright holder.
THIS SOFTWARE IS PROVIDED ` ` AS IS '' WITHOUT EXPRESS OR IMPLIED WARRANTY .
;;; -----------------------------------------------------------------------
(in-package "FUG5")
;; Use as (att #{path})
Semantics : copy sub - fd pointed to by path at level att .
;; This is not a conflation - only what's currently at path
;; will get copied - and there won't be equality afterwards.
(set-dispatch-macro-character #\# #\{
#'(lambda (stream char arg)
(declare (ignore char arg))
(vector
'external
`(lambda (path)
(declare (special *input*))
(copy-tree
(relocate *input*
(absolute-path
,(make-path :l (normalize-path
(read-delimited-list #\} stream t)))
path)))))))
| null | https://raw.githubusercontent.com/melhadad/fuf/57bd0e31afc6aaa03b85f45f4c7195af701508b8/src/copypath.lisp | lisp | -*- Mode:Lisp; Syntax:Common-Lisp; Package: FUG5 -*-
-----------------------------------------------------------------------
File: copypath.l
Modified:
-----------------------------------------------------------------------
Permission to use, copy, and/or distribute for any purpose and
without fee is hereby granted, provided that both the above copyright
notice and this permission notice appear in all copies and derived works.
Fees for distribution or use of this software or derived works may only
be charged with express written permission of the copyright holder.
-----------------------------------------------------------------------
Use as (att #{path})
This is not a conflation - only what's currently at path
will get copied - and there won't be equality afterwards. | Description : 's copying path instead of conflating
Author :
Created : 23 Feb 1993
Package : FUG5
FUF - a functional unification - based text generation system . ( . 5.4 )
Copyright ( c ) 1987 - 2014 by . all rights reserved .
THIS SOFTWARE IS PROVIDED ` ` AS IS '' WITHOUT EXPRESS OR IMPLIED WARRANTY .
(in-package "FUG5")
Semantics : copy sub - fd pointed to by path at level att .
(set-dispatch-macro-character #\# #\{
#'(lambda (stream char arg)
(declare (ignore char arg))
(vector
'external
`(lambda (path)
(declare (special *input*))
(copy-tree
(relocate *input*
(absolute-path
,(make-path :l (normalize-path
(read-delimited-list #\} stream t)))
path)))))))
|
ce2833d1d62175f6e568f427278bf113086c30aea1008871bc39e084a0a65e31 | finnishtransportagency/harja | tieluvat_kartalla.cljs | (ns harja.tiedot.tieluvat.tieluvat-kartalla
(:require [harja.domain.tielupa :as tielupa]
[harja.ui.kartta.esitettavat-asiat :refer [kartalla-esitettavaan-muotoon]]
[harja.tiedot.tieluvat.tielupa-tiedot :as tiedot]
[clojure.set :as set])
(:require-macros [reagent.ratom :refer [reaction]]))
(defonce karttataso-tieluvat (atom false))
(defn hajota-tieluvat
"Koska yhteen tielupaan voi kuulua monta sijaintia, pitää yksi lupa hajoittaa moneksi objektiksi
kartalle piirrettäessa."
[luvat]
(mapcat
(fn [tielupa]
on monta sijaintitietoa
Yksi sijaintitieto sisältää tr - osoitetiedot , ja : : geometria avaimen takana geometriatiedot
Kartalle piirrettäessa " rikotaan osiin " , eli lisätään : sijainti - avain ,
jonka taakse geometriatieto . " objektia " .
Valitun asian , koska se tehdään id : n perusteella ,
eli i d on , korostetaan ne kaikki .
tämä , koska emme halua , että
toistuvat ( jos esim sijaintietoja on korkealla zoom - tasolla päällekkäin ) , tai että monta riviä
avataan samaan aikaan ( id : n perusteella ) . ilmoitusta
avattaessa pitää varmistaa , että aukaistaan varmasti " oikea ilmoitus " , jotain
väliaikaista objektia , vain .
(keep
(fn [sijainti]
(when-let [geo (::tielupa/geometria sijainti)]
(when (not-empty geo)
(assoc tielupa :sijainti geo))))
(::tielupa/sijainnit tielupa)))
luvat))
(defonce tieluvat-kartalla
(reaction
(let [tila @tiedot/tila]
(when @karttataso-tieluvat
(kartalla-esitettavaan-muotoon
(hajota-tieluvat (:haetut-tieluvat tila))
#(= (get-in tila [:valittu-tielupa ::tielupa/id]) (::tielupa/id %))
(comp
(map #(assoc % :tyyppi-kartalla :tielupa))))))))
| null | https://raw.githubusercontent.com/finnishtransportagency/harja/110c979dc11526dcde966445e82d326b4ee05991/src/cljs/harja/tiedot/tieluvat/tieluvat_kartalla.cljs | clojure | (ns harja.tiedot.tieluvat.tieluvat-kartalla
(:require [harja.domain.tielupa :as tielupa]
[harja.ui.kartta.esitettavat-asiat :refer [kartalla-esitettavaan-muotoon]]
[harja.tiedot.tieluvat.tielupa-tiedot :as tiedot]
[clojure.set :as set])
(:require-macros [reagent.ratom :refer [reaction]]))
(defonce karttataso-tieluvat (atom false))
(defn hajota-tieluvat
"Koska yhteen tielupaan voi kuulua monta sijaintia, pitää yksi lupa hajoittaa moneksi objektiksi
kartalle piirrettäessa."
[luvat]
(mapcat
(fn [tielupa]
on monta sijaintitietoa
Yksi sijaintitieto sisältää tr - osoitetiedot , ja : : geometria avaimen takana geometriatiedot
Kartalle piirrettäessa " rikotaan osiin " , eli lisätään : sijainti - avain ,
jonka taakse geometriatieto . " objektia " .
Valitun asian , koska se tehdään id : n perusteella ,
eli i d on , korostetaan ne kaikki .
tämä , koska emme halua , että
toistuvat ( jos esim sijaintietoja on korkealla zoom - tasolla päällekkäin ) , tai että monta riviä
avataan samaan aikaan ( id : n perusteella ) . ilmoitusta
avattaessa pitää varmistaa , että aukaistaan varmasti " oikea ilmoitus " , jotain
väliaikaista objektia , vain .
(keep
(fn [sijainti]
(when-let [geo (::tielupa/geometria sijainti)]
(when (not-empty geo)
(assoc tielupa :sijainti geo))))
(::tielupa/sijainnit tielupa)))
luvat))
(defonce tieluvat-kartalla
(reaction
(let [tila @tiedot/tila]
(when @karttataso-tieluvat
(kartalla-esitettavaan-muotoon
(hajota-tieluvat (:haetut-tieluvat tila))
#(= (get-in tila [:valittu-tielupa ::tielupa/id]) (::tielupa/id %))
(comp
(map #(assoc % :tyyppi-kartalla :tielupa))))))))
| |
005404be11fa89e9bf00912926b6fe9c89d6e0fae58c6bfda168f9f3c5b3f321 | compiling-to-categories/concat | NatArr.hs | # LANGUAGE CPP #
# LANGUAGE ViewPatterns #
# LANGUAGE UndecidableInstances #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeOperators #
# LANGUAGE TupleSections #
# LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
# LANGUAGE ExistentialQuantification #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE TypeApplications #
# LANGUAGE StandaloneDeriving #
# OPTIONS_GHC -Wall #
# OPTIONS_GHC -fno - warn - unused - imports #
-- Needed for HasCard instances
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
{-# OPTIONS -Wno-orphans #-}
#include "AbsTy.inc"
AbsTyPragmas
-- | Experiments with statically sized arrays
module ConCat.NatArr where
import Prelude hiding (Enum(..))
import Control.Arrow ((|||))
import Control.Applicative (liftA2)
import Data.Void (Void,absurd)
import Data.Monoid ((<>),Sum(..))
import GHC.TypeLits
import Data.Array (Array,(!))
import qualified Data.Array as Arr
import Data.Proxy (Proxy(..))
import GHC.Generics ((:*:)(..),(:.:)(..))
import Control.Newtype.Generics (Newtype(..))
import ConCat.Misc ((:*),(:+))
import ConCat.AltCat (Arr,array,arrAt,at,natV,divModC)
import ConCat.Rep (HasRep(..))
AbsTyImports
{--------------------------------------------------------------------
Domain-typed arrays
--------------------------------------------------------------------}
-- Type cardinality.
class (Enum a, KnownNat (Card a)) => HasCard a where
type Card a :: Nat
instance HasCard Void where type Card Void = 0
instance HasCard () where type Card () = 1
instance HasCard Bool where type Card Bool = 2
instance (HasCard a, HasCard b) => HasCard (a :+ b) where
type Card (a :+ b) = Card a + Card b
-- • Illegal nested type family application ‘Card a + Card b’
-- (Use UndecidableInstances to permit this)
instance (HasCard a, HasCard b) => HasCard (a :* b) where
type Card (a :* b) = Card a * Card b
Without . KnownNat . Solver ( from ghc - typelits - knownnat ):
--
• Could not deduce ( KnownNat ( Card a + Card b ) )
arising from the superclasses of an instance declaration
-- from the context: (HasCard a, HasCard b)
--
• Could not deduce ( KnownNat ( Card a * Card b ) )
arising from the superclasses of an instance declaration
-- from the context: (HasCard a, HasCard b)
data DArr a b = DArr { unDarr :: Arr (Card a) b }
instance HasCard a => Newtype (DArr a b) where
type O (DArr a b) = Arr (Card a) b
pack = DArr
unpack = unDarr
# INLINE pack #
# INLINE unpack #
instance HasCard a => HasRep (DArr a b) where
type Rep (DArr a b) = Arr (Card a) b
abst = pack
repr = unpack
AbsTy(DArr a b)
deriving instance HasCard a => Functor (DArr a)
-- deriving instance Foldable (DArr a)
instance HasCard i => Applicative (DArr i) where
pure x = DArr (pure x)
DArr fs <*> DArr xs = DArr (fs <*> xs)
# INLINE pure #
{-# INLINE (<*>) #-}
atd :: HasCard a => DArr a b -> a -> b
atd (DArr bs) a = arrAt (bs,fromEnum a)
-- bs `at` fromEnum a
# INLINE atd #
darr :: HasCard a => (a -> b) -> DArr a b
darr f = DArr (array (f . toEnum))
# INLINE darr #
instance Foldable (DArr Void) where
foldMap _f _h = mempty
{-# INLINE foldMap #-}
instance Foldable (DArr ()) where
foldMap f (atd -> h) = f (h ())
{-# INLINE foldMap #-}
sum = getSum . foldMap Sum -- experiment
# INLINE sum #
instance Foldable (DArr Bool) where
foldMap f (atd -> h) = f (h False) <> f (h True)
{-# INLINE foldMap #-}
sum = getSum . foldMap Sum -- experiment
# INLINE sum #
splitDSum :: (HasCard a, HasCard b) => DArr (a :+ b) z -> (DArr a :*: DArr b) z
splitDSum (atd -> h) = darr (h . Left) :*: darr (h . Right)
# INLINE splitDSum #
instance (HasCard a, HasCard b , Foldable (DArr a), Foldable (DArr b))
=> Foldable (DArr (a :+ b)) where
-- foldMap f (atd -> h) =
foldMap f ( ( h . Left ) ) < > foldMap f ( ( h . Right ) )
foldMap f = foldMap f . splitDSum
{-# INLINE foldMap #-}
sum = getSum . foldMap Sum -- experiment
# INLINE sum #
factorDProd :: (HasCard a, HasCard b) => DArr (a :* b) z -> (DArr a :.: DArr b) z
factorDProd = Comp1 . darr . fmap darr . curry . atd
# INLINE factorDProd #
-- atd :: DArr (a :* b) z -> (a :* b -> z)
-- curry :: (a :* b -> z) -> (a -> b -> z)
fmap darr : : ( a - > b - > z ) - > ( a - > DArr b z )
-- darr :: (a -> DArr b z) -> DArr a (DArr b z)
-- Comp1 :: DArr a (DArr b z) -> (DArr a :.: DArr b) z
instance ( HasCard a, HasCard b, Enum a, Enum b
, Foldable (DArr a), Foldable (DArr b) )
=> Foldable (DArr (a :* b)) where
foldMap f = foldMap f . factorDProd
{-# INLINE foldMap #-}
sum = getSum . foldMap Sum -- experiment
# INLINE sum #
-------------------------------------------------------------------
-------------------------------------------------------------------
Enum
--------------------------------------------------------------------}
-- Custom Enum class using *total* definitions of toEnum.
class Enum a where
fromEnum' :: a -> Int
toEnum' :: Int -> a
fromEnum :: Enum a => a -> Int
fromEnum = fromEnum'
{-# INLINE [0] fromEnum #-}
toEnum :: Enum a => Int -> a
toEnum = toEnum'
{-# INLINE [0] toEnum #-}
{-# RULES
-- "toEnum . fromEnum" forall a . toEnum (fromEnum a) = a
-- "fromEnum . toEnum" forall n . fromEnum (toEnum n) = n -- true in our context
#-}
instance Enum Void where
fromEnum' = absurd
toEnum' _ = error "toEnum on void"
instance Enum () where
fromEnum' () = 0
toEnum' _ = ()
instance Enum Bool where
fromEnum' False = 0
fromEnum' True = 1
toEnum' 0 = False
toEnum' 1 = True
-- toEnum' = (> 0)
card :: forall a. HasCard a => Int
card = natV @(Card a)
instance (Enum a, HasCard a, Enum b) => Enum (a :+ b) where
-- fromEnum (Left a) = fromEnum a
-- fromEnum (Right b) = card @a + fromEnum b
fromEnum' = fromEnum ||| (card @a +) . fromEnum
toEnum' i | i < na = Left (toEnum i)
| otherwise = Right (toEnum (i - na))
where
na = card @a
{-# INLINE fromEnum' #-}
{-# INLINE toEnum' #-}
instance (Enum a, HasCard b, Enum b) => Enum (a :* b) where
fromEnum' (a,b) = fromEnum a * card @b + fromEnum b
toEnum' i = (toEnum d, toEnum m)
where
(d,m) = divModC (i,card @b)
{-# INLINE fromEnum' #-}
{-# INLINE toEnum' #-}
The categorical divMod avoids method inlining .
| null | https://raw.githubusercontent.com/compiling-to-categories/concat/49e554856576245f583dfd2484e5f7c19f688028/examples/src/ConCat/NatArr.hs | haskell | # LANGUAGE DeriveAnyClass #
Needed for HasCard instances
# OPTIONS -Wno-orphans #
| Experiments with statically sized arrays
-------------------------------------------------------------------
Domain-typed arrays
-------------------------------------------------------------------
Type cardinality.
• Illegal nested type family application ‘Card a + Card b’
(Use UndecidableInstances to permit this)
from the context: (HasCard a, HasCard b)
from the context: (HasCard a, HasCard b)
deriving instance Foldable (DArr a)
# INLINE (<*>) #
bs `at` fromEnum a
# INLINE foldMap #
# INLINE foldMap #
experiment
# INLINE foldMap #
experiment
foldMap f (atd -> h) =
# INLINE foldMap #
experiment
atd :: DArr (a :* b) z -> (a :* b -> z)
curry :: (a :* b -> z) -> (a -> b -> z)
darr :: (a -> DArr b z) -> DArr a (DArr b z)
Comp1 :: DArr a (DArr b z) -> (DArr a :.: DArr b) z
# INLINE foldMap #
experiment
-----------------------------------------------------------------
-----------------------------------------------------------------
------------------------------------------------------------------}
Custom Enum class using *total* definitions of toEnum.
# INLINE [0] fromEnum #
# INLINE [0] toEnum #
# RULES
-- "toEnum . fromEnum" forall a . toEnum (fromEnum a) = a
-- "fromEnum . toEnum" forall n . fromEnum (toEnum n) = n -- true in our context
#
toEnum' = (> 0)
fromEnum (Left a) = fromEnum a
fromEnum (Right b) = card @a + fromEnum b
# INLINE fromEnum' #
# INLINE toEnum' #
# INLINE fromEnum' #
# INLINE toEnum' # | # LANGUAGE CPP #
# LANGUAGE ViewPatterns #
# LANGUAGE UndecidableInstances #
# LANGUAGE DeriveFoldable #
# LANGUAGE DeriveFunctor #
# LANGUAGE FlexibleContexts #
# LANGUAGE TypeFamilies #
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE TypeOperators #
# LANGUAGE TupleSections #
# LANGUAGE DataKinds #
# LANGUAGE KindSignatures #
# LANGUAGE ExistentialQuantification #
# LANGUAGE PolyKinds #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE AllowAmbiguousTypes #
# LANGUAGE TypeApplications #
# LANGUAGE StandaloneDeriving #
# OPTIONS_GHC -Wall #
# OPTIONS_GHC -fno - warn - unused - imports #
# OPTIONS_GHC -fplugin GHC.TypeLits . KnownNat . Solver #
#include "AbsTy.inc"
AbsTyPragmas
module ConCat.NatArr where
import Prelude hiding (Enum(..))
import Control.Arrow ((|||))
import Control.Applicative (liftA2)
import Data.Void (Void,absurd)
import Data.Monoid ((<>),Sum(..))
import GHC.TypeLits
import Data.Array (Array,(!))
import qualified Data.Array as Arr
import Data.Proxy (Proxy(..))
import GHC.Generics ((:*:)(..),(:.:)(..))
import Control.Newtype.Generics (Newtype(..))
import ConCat.Misc ((:*),(:+))
import ConCat.AltCat (Arr,array,arrAt,at,natV,divModC)
import ConCat.Rep (HasRep(..))
AbsTyImports
class (Enum a, KnownNat (Card a)) => HasCard a where
type Card a :: Nat
instance HasCard Void where type Card Void = 0
instance HasCard () where type Card () = 1
instance HasCard Bool where type Card Bool = 2
instance (HasCard a, HasCard b) => HasCard (a :+ b) where
type Card (a :+ b) = Card a + Card b
instance (HasCard a, HasCard b) => HasCard (a :* b) where
type Card (a :* b) = Card a * Card b
Without . KnownNat . Solver ( from ghc - typelits - knownnat ):
• Could not deduce ( KnownNat ( Card a + Card b ) )
arising from the superclasses of an instance declaration
• Could not deduce ( KnownNat ( Card a * Card b ) )
arising from the superclasses of an instance declaration
data DArr a b = DArr { unDarr :: Arr (Card a) b }
instance HasCard a => Newtype (DArr a b) where
type O (DArr a b) = Arr (Card a) b
pack = DArr
unpack = unDarr
# INLINE pack #
# INLINE unpack #
instance HasCard a => HasRep (DArr a b) where
type Rep (DArr a b) = Arr (Card a) b
abst = pack
repr = unpack
AbsTy(DArr a b)
deriving instance HasCard a => Functor (DArr a)
instance HasCard i => Applicative (DArr i) where
pure x = DArr (pure x)
DArr fs <*> DArr xs = DArr (fs <*> xs)
# INLINE pure #
atd :: HasCard a => DArr a b -> a -> b
atd (DArr bs) a = arrAt (bs,fromEnum a)
# INLINE atd #
darr :: HasCard a => (a -> b) -> DArr a b
darr f = DArr (array (f . toEnum))
# INLINE darr #
instance Foldable (DArr Void) where
foldMap _f _h = mempty
instance Foldable (DArr ()) where
foldMap f (atd -> h) = f (h ())
# INLINE sum #
instance Foldable (DArr Bool) where
foldMap f (atd -> h) = f (h False) <> f (h True)
# INLINE sum #
splitDSum :: (HasCard a, HasCard b) => DArr (a :+ b) z -> (DArr a :*: DArr b) z
splitDSum (atd -> h) = darr (h . Left) :*: darr (h . Right)
# INLINE splitDSum #
instance (HasCard a, HasCard b , Foldable (DArr a), Foldable (DArr b))
=> Foldable (DArr (a :+ b)) where
foldMap f ( ( h . Left ) ) < > foldMap f ( ( h . Right ) )
foldMap f = foldMap f . splitDSum
# INLINE sum #
factorDProd :: (HasCard a, HasCard b) => DArr (a :* b) z -> (DArr a :.: DArr b) z
factorDProd = Comp1 . darr . fmap darr . curry . atd
# INLINE factorDProd #
fmap darr : : ( a - > b - > z ) - > ( a - > DArr b z )
instance ( HasCard a, HasCard b, Enum a, Enum b
, Foldable (DArr a), Foldable (DArr b) )
=> Foldable (DArr (a :* b)) where
foldMap f = foldMap f . factorDProd
# INLINE sum #
Enum
class Enum a where
fromEnum' :: a -> Int
toEnum' :: Int -> a
fromEnum :: Enum a => a -> Int
fromEnum = fromEnum'
toEnum :: Enum a => Int -> a
toEnum = toEnum'
instance Enum Void where
fromEnum' = absurd
toEnum' _ = error "toEnum on void"
instance Enum () where
fromEnum' () = 0
toEnum' _ = ()
instance Enum Bool where
fromEnum' False = 0
fromEnum' True = 1
toEnum' 0 = False
toEnum' 1 = True
card :: forall a. HasCard a => Int
card = natV @(Card a)
instance (Enum a, HasCard a, Enum b) => Enum (a :+ b) where
fromEnum' = fromEnum ||| (card @a +) . fromEnum
toEnum' i | i < na = Left (toEnum i)
| otherwise = Right (toEnum (i - na))
where
na = card @a
instance (Enum a, HasCard b, Enum b) => Enum (a :* b) where
fromEnum' (a,b) = fromEnum a * card @b + fromEnum b
toEnum' i = (toEnum d, toEnum m)
where
(d,m) = divModC (i,card @b)
The categorical divMod avoids method inlining .
|
84daf2447d338802bd4473f13a084424624ea64c05906ae42ae61776c2698bf9 | talex5/ocaml-wayland | connection.ml | open Lwt.Syntax
open Internal
type 'a t = 'a Internal.connection
(* Dispatch all complete messages in [recv_buffer]. *)
let rec process_recv_buffer t recv_buffer =
let* () = t.paused in
match Msg.parse ~fds:t.incoming_fds (Recv_buffer.data recv_buffer) with
| None -> Lwt.return_unit
| Some msg ->
begin
let obj = Msg.obj msg in
match Objects.find_opt obj t.objects with
| None -> Fmt.failwith "No such object %lu (op=%d)" obj (Msg.op msg);
| Some (Generic proxy) ->
let msg = Msg.cast msg in
t.trace.inbound proxy msg;
if proxy.can_recv then (
try
proxy.handler#dispatch proxy msg
with ex ->
let bt = Printexc.get_raw_backtrace () in
Log.err (fun f -> f "Uncaught exception handling incoming message for %a:@,%a"
pp_proxy proxy Fmt.exn_backtrace (ex, bt))
) else (
Fmt.failwith "Received message for %a, which was shut down!" pp_proxy proxy
)
end;
Recv_buffer.update_consumer recv_buffer (Msg.length msg);
Unix.sleepf 0.001 ;
Fmt.pr " Buffer after dispatch : % a@. " Recv_buffer.dump recv_buffer ;
process_recv_buffer t recv_buffer
let listen t =
let recv_buffer = Recv_buffer.create 4096 in
let rec aux () =
let* (got, fds) = t.transport#recv (Recv_buffer.free_buffer recv_buffer) in
if Lwt.is_sleeping t.closed then (
List.iter (fun fd -> Queue.add fd t.incoming_fds) fds;
if got = 0 then (
Log.info (fun f -> f "Got end-of-file on wayland connection");
Lwt.return_unit
) else (
Recv_buffer.update_producer recv_buffer got;
Log.debug (fun f -> f "Ring after adding %d bytes: %a" got Recv_buffer.dump recv_buffer);
let* () = process_recv_buffer t recv_buffer in
aux ()
)
) else (
List.iter Unix.close fds;
failwith "Connection is closed"
)
in
Lwt.try_bind aux
(fun () ->
if Lwt.is_sleeping t.closed then Lwt.wakeup t.set_closed (Ok ());
Queue.iter Unix.close t.incoming_fds;
Lwt.return_unit;
)
(fun ex ->
if Lwt.is_sleeping t.closed then
Lwt.wakeup t.set_closed (Error ex)
else
Log.debug (fun f -> f "Listen error (but connection already closed): %a" Fmt.exn ex);
Queue.iter Unix.close t.incoming_fds;
Lwt.return_unit;
)
let clean_up t =
t.objects |> Objects.iter (fun _ (Generic obj) ->
obj.on_delete |> Queue.iter (fun f ->
try f ()
with ex ->
Log.warn (fun f -> f "Error from %a's on_delete handler called at end-of-connection: %a"
pp_proxy obj
Fmt.exn ex)
);
Queue.clear obj.on_delete
);
Lwt.return_unit
let connect ~trace role transport handler =
let closed, set_closed = Lwt.wait () in
let t = {
transport = (transport :> S.transport);
paused = Lwt.return_unit;
unpause = ignore;
role;
objects = Objects.empty;
free_ids = [];
next_id = (match role with `Client -> 2l | `Server -> 0xff000000l);
incoming_fds = Queue.create ();
outbox = Queue.create ();
closed;
set_closed;
trace = Proxy.trace trace;
} in
let display_proxy = Proxy.add_root t (handler :> _ Proxy.Handler.t) in
Lwt.async (fun () ->
Lwt.finalize
(fun () -> listen t)
(fun () -> clean_up t)
);
(t, display_proxy)
let closed t = t.closed
let set_paused t = function
| false ->
if Lwt.is_sleeping t.paused then t.unpause ()
| true ->
if not (Lwt.is_sleeping t.paused) then (
let paused, set_paused = Lwt.wait () in
t.paused <- paused;
t.unpause <- Lwt.wakeup set_paused
)
let dump f t =
let pp_item f (_id, Generic proxy) = pp_proxy f proxy in
Fmt.pf f "@[<v2>Connection on %t with %d objects:@,%a@]"
t.transport#pp
(Objects.cardinal t.objects)
(Fmt.Dump.list pp_item) (Objects.bindings t.objects)
| null | https://raw.githubusercontent.com/talex5/ocaml-wayland/1513420d35f3edb6ad2d9e1db0227e3cd9b9b76c/lib/connection.ml | ocaml | Dispatch all complete messages in [recv_buffer]. | open Lwt.Syntax
open Internal
type 'a t = 'a Internal.connection
let rec process_recv_buffer t recv_buffer =
let* () = t.paused in
match Msg.parse ~fds:t.incoming_fds (Recv_buffer.data recv_buffer) with
| None -> Lwt.return_unit
| Some msg ->
begin
let obj = Msg.obj msg in
match Objects.find_opt obj t.objects with
| None -> Fmt.failwith "No such object %lu (op=%d)" obj (Msg.op msg);
| Some (Generic proxy) ->
let msg = Msg.cast msg in
t.trace.inbound proxy msg;
if proxy.can_recv then (
try
proxy.handler#dispatch proxy msg
with ex ->
let bt = Printexc.get_raw_backtrace () in
Log.err (fun f -> f "Uncaught exception handling incoming message for %a:@,%a"
pp_proxy proxy Fmt.exn_backtrace (ex, bt))
) else (
Fmt.failwith "Received message for %a, which was shut down!" pp_proxy proxy
)
end;
Recv_buffer.update_consumer recv_buffer (Msg.length msg);
Unix.sleepf 0.001 ;
Fmt.pr " Buffer after dispatch : % a@. " Recv_buffer.dump recv_buffer ;
process_recv_buffer t recv_buffer
let listen t =
let recv_buffer = Recv_buffer.create 4096 in
let rec aux () =
let* (got, fds) = t.transport#recv (Recv_buffer.free_buffer recv_buffer) in
if Lwt.is_sleeping t.closed then (
List.iter (fun fd -> Queue.add fd t.incoming_fds) fds;
if got = 0 then (
Log.info (fun f -> f "Got end-of-file on wayland connection");
Lwt.return_unit
) else (
Recv_buffer.update_producer recv_buffer got;
Log.debug (fun f -> f "Ring after adding %d bytes: %a" got Recv_buffer.dump recv_buffer);
let* () = process_recv_buffer t recv_buffer in
aux ()
)
) else (
List.iter Unix.close fds;
failwith "Connection is closed"
)
in
Lwt.try_bind aux
(fun () ->
if Lwt.is_sleeping t.closed then Lwt.wakeup t.set_closed (Ok ());
Queue.iter Unix.close t.incoming_fds;
Lwt.return_unit;
)
(fun ex ->
if Lwt.is_sleeping t.closed then
Lwt.wakeup t.set_closed (Error ex)
else
Log.debug (fun f -> f "Listen error (but connection already closed): %a" Fmt.exn ex);
Queue.iter Unix.close t.incoming_fds;
Lwt.return_unit;
)
let clean_up t =
t.objects |> Objects.iter (fun _ (Generic obj) ->
obj.on_delete |> Queue.iter (fun f ->
try f ()
with ex ->
Log.warn (fun f -> f "Error from %a's on_delete handler called at end-of-connection: %a"
pp_proxy obj
Fmt.exn ex)
);
Queue.clear obj.on_delete
);
Lwt.return_unit
let connect ~trace role transport handler =
let closed, set_closed = Lwt.wait () in
let t = {
transport = (transport :> S.transport);
paused = Lwt.return_unit;
unpause = ignore;
role;
objects = Objects.empty;
free_ids = [];
next_id = (match role with `Client -> 2l | `Server -> 0xff000000l);
incoming_fds = Queue.create ();
outbox = Queue.create ();
closed;
set_closed;
trace = Proxy.trace trace;
} in
let display_proxy = Proxy.add_root t (handler :> _ Proxy.Handler.t) in
Lwt.async (fun () ->
Lwt.finalize
(fun () -> listen t)
(fun () -> clean_up t)
);
(t, display_proxy)
let closed t = t.closed
let set_paused t = function
| false ->
if Lwt.is_sleeping t.paused then t.unpause ()
| true ->
if not (Lwt.is_sleeping t.paused) then (
let paused, set_paused = Lwt.wait () in
t.paused <- paused;
t.unpause <- Lwt.wakeup set_paused
)
let dump f t =
let pp_item f (_id, Generic proxy) = pp_proxy f proxy in
Fmt.pf f "@[<v2>Connection on %t with %d objects:@,%a@]"
t.transport#pp
(Objects.cardinal t.objects)
(Fmt.Dump.list pp_item) (Objects.bindings t.objects)
|
f626c2e6f70ab3966f956bc19545e7b7cc06e2b8dd660618fd742c85c4971a52 | fragnix/fragnix | GHC.Char.hs | {-# LINE 1 "GHC.Char.hs" #-}
# LANGUAGE Trustworthy #
# LANGUAGE NoImplicitPrelude , MagicHash #
module GHC.Char
( -- * Utilities
chr
* equality operators
-- | See GHC.Classes#matching_overloaded_methods_in_rules
, eqChar, neChar
) where
import GHC.Base
import GHC.Show
| The ' Prelude.toEnum ' method restricted to the type ' Data . . ' .
chr :: Int -> Char
chr i@(I# i#)
| isTrue# (int2Word# i# `leWord#` 0x10FFFF##) = C# (chr# i#)
| otherwise
= errorWithoutStackTrace ("Prelude.chr: bad argument: " ++ showSignedInt (I# 9#) i "")
| null | https://raw.githubusercontent.com/fragnix/fragnix/b9969e9c6366e2917a782f3ac4e77cce0835448b/builtins/base/GHC.Char.hs | haskell | # LINE 1 "GHC.Char.hs" #
* Utilities
| See GHC.Classes#matching_overloaded_methods_in_rules | # LANGUAGE Trustworthy #
# LANGUAGE NoImplicitPrelude , MagicHash #
module GHC.Char
chr
* equality operators
, eqChar, neChar
) where
import GHC.Base
import GHC.Show
| The ' Prelude.toEnum ' method restricted to the type ' Data . . ' .
chr :: Int -> Char
chr i@(I# i#)
| isTrue# (int2Word# i# `leWord#` 0x10FFFF##) = C# (chr# i#)
| otherwise
= errorWithoutStackTrace ("Prelude.chr: bad argument: " ++ showSignedInt (I# 9#) i "")
|
f6e85c0151d67c19242d87c9ee1b8cf5d2db797c9749f38caf99912c65d102ed | alpmestan/probable | simple.hs | module Main where
import Control.Applicative
import Control.Monad
import Math.Probable
import qualified Data.Vector.Unboxed as VU
data Person = Person
{ age :: Int
, weight :: Double
, salary :: Int
} deriving (Eq, Show)
person :: RandT IO Person
person =
Person <$> uniformIn (1, 100)
<*> uniformIn (2, 130)
<*> uniformIn (500, 10000)
randomPersons :: Int -> IO [Person]
randomPersons n = mwc $ listOf n person
randomDoubles :: Int -> IO (VU.Vector Double)
randomDoubles n = mwc $ vectorOf n double
main :: IO ()
main = do
randomPersons 10 >>= mapM_ print
randomDoubles 10 >>= VU.mapM_ print | null | https://raw.githubusercontent.com/alpmestan/probable/36b339bb54ddaf13b674d6ee0dee8bdcb53a721d/examples/simple.hs | haskell | module Main where
import Control.Applicative
import Control.Monad
import Math.Probable
import qualified Data.Vector.Unboxed as VU
data Person = Person
{ age :: Int
, weight :: Double
, salary :: Int
} deriving (Eq, Show)
person :: RandT IO Person
person =
Person <$> uniformIn (1, 100)
<*> uniformIn (2, 130)
<*> uniformIn (500, 10000)
randomPersons :: Int -> IO [Person]
randomPersons n = mwc $ listOf n person
randomDoubles :: Int -> IO (VU.Vector Double)
randomDoubles n = mwc $ vectorOf n double
main :: IO ()
main = do
randomPersons 10 >>= mapM_ print
randomDoubles 10 >>= VU.mapM_ print | |
8d2f79d06c56b0de230fdc8b7e70b8ff1d664cd2ddce08a718467f80e06fba61 | appleshan/cl-http | tcp-stream.lisp | ;;; -*- Mode: lisp; Package: IPC; -*-
;;;
LispWorks 4 interface to TCP / IP streams
;;;
Copyright ( C ) 1997 - 2000 Xanalys Inc. All rights reserved .
;;;
Enhancements Copyright ( C ) 2003 , 2006 , . All rights reserved .
;;;
(in-package :IPC)
Added SSL support conditionalized by # + CL - HTTP - SSL -- JCMa 3/24/2006
Some optimization declarations conditionalized by # + CL - HTTP - Debugging have
been changed to # + CL - HTTP - Untested in order to increase safety in the
;; released system pending investigation of a memory corruption bug. 12/17/2003 -- JCMa.
SSL condition hierarchy introduced by LispWorks 4.4
;;;
;;; ssl-condition
;;; ssl-closed - The condition class ssl-closed corresponds to SSL_ERROR_ZERO_RETURN . It means the underlying socket is dead.
;;; ssl-error - The condition class ssl-error corresponds to SSL_ERROR_SYSCALL . It means that something got broken.
ssl - failure - The condition class ssl - failure corresponds to SSL_ERROR_SSL . This means a failure in processing the input ,
;;; typically due to a mismatch between the client and the server. You get this error when trying to use a SSL
;;; connection to a non-secure peer.
ssl - x509 - lookup - The condition class ssl - x509 - lookup corresponds to SSL_ERROR_WANT_X509_LOOKUP . It happens when a certificate
;;; is rejected by a user callback.
This is the condition hierarchy , based on the one .
;;; network-error
;;; domain-resolver-error
;;; local-network-error
;;; network-resources-exhausted
;;; unknown-address
;;; unknown-host-name
;;; remote-network-error
;;; bad-connection-state
;;; connection-closed
;;; connection-lost
;;; host-stopped-responding
;;; connection-error
;;; connection-refused
;;; host-not-responding
;;; protocol-timeout
;;; network-parse-error
(defparameter *tcp-stream-safe-abort-states*
'("Waiting for socket input"
"Waiting for socket output")
"Process whostates from which it is safe to abort HTTP connnections.")
(define-condition www-utils:network-error (simple-error)
()
(:report (lambda (condition stream)
(let ((control (simple-condition-format-control condition)))
(if control
(apply #'format stream control (simple-condition-format-arguments condition))
(format stream "A network error of type ~S occurred." (type-of condition))))))
(:default-initargs
:format-control nil
:format-arguments nil))
(define-condition www-utils:domain-resolver-error (www-utils:network-error)
((address :initarg :address))
(:report (lambda (condition stream)
(if (slot-boundp condition 'address)
(format stream "Cannot resolve IP address ~A" (ip-address-string (slot-value condition 'address)))
(format stream "Cannot find current domainname")))))
(define-condition www-utils:local-network-error (www-utils:network-error)
())
(define-condition www-utils:unknown-host-name (www-utils:local-network-error)
((hostname :initarg :hostname))
(:report (lambda (condition stream)
(format stream "Unknown host name ~A" (slot-value condition 'hostname)))))
#+comment ; MJS 07Oct97: not used
(define-condition www-utils:unknown-address (www-utils:local-network-error)
((address :initarg :address))
(:report (lambda (condition stream)
(let ((address (slot-value condition 'address)))
(format stream "Unknown address ~A" (ip-address-string address))))))
(define-condition www-utils:remote-network-error (www-utils:network-error) ())
#+CL-HTTP-SSL
(define-condition www-utils:ssl-certificate-rejected (www-utils:network-error comm:ssl-x509-lookup) ())
(define-condition www-utils:bad-connection-state (www-utils:remote-network-error) ())
(define-condition www-utils:connection-closed (www-utils:bad-connection-state) ())
#+CL-HTTP-SSL
(define-condition www-utils:ssl-connection-closed (www-utils:connection-closed comm:ssl-closed) ())
(define-condition www-utils:connection-lost (www-utils:bad-connection-state) ())
(define-condition www-utils:host-stopped-responding (www-utils:bad-connection-state) ())
(define-condition www-utils:connection-error (www-utils:remote-network-error) ())
#+CL-HTTP-SSL
(define-condition www-utils:ssl-connection-error (www-utils:connection-error comm:ssl-error) ())
(define-condition www-utils:connection-refused (www-utils:connection-error) ())
#+CL-HTTP-SSL
(define-condition www-utils:ssl-connection-refused (www-utils:connection-refused comm:ssl-failure) ())
(define-condition www-utils:host-not-responding (www-utils:remote-network-error) ())
(define-condition www-utils:protocol-timeout (www-utils:remote-network-error) ())
(define-condition www-utils:network-error-mixin
(www-utils:network-error)
()
(:documentation "Mixin to allow ports to inherit instance variables and methods to network conditions
defined at the portable code level."))
(define-condition connection-timed-out (www-utils:protocol-timeout www-utils:bad-connection-state)
()
(:report (lambda (condition stream)
(declare (ignore condition))
(format stream "Connection timed out."))))
;;; ----------------------------------------------------------------------------------
;;; NETWORK ADDRESS CODE
;;;
;; Turn internet address into string format
(defun ip-address-string (address)
(comm:ip-address-string address))
;; Turn internet string address format into IP number
(defun string-ip-address (address-string)
(let ((address (comm:string-ip-address address-string)))
#+LispWorks4.0
(when (eql address #xffffffff)
(setq address nil))
address))
(defun internet-address (name)
(or (comm:get-host-entry name :fields '(:address))
(error 'www-utils:unknown-host-name :hostname name)))
(defun internet-addresses (name)
(or (comm:get-host-entry name :fields '(:addresses))
(error 'www-utils:unknown-host-name :hostname name)))
#+UNIX
(fli:define-foreign-function (c-getdomainname getdomainname)
((name :pointer)
(namelen :int))
:result-type :int)
(defvar *domainname* nil)
There are more than one strategies you can use
;;; based on what OS you are using. Instead of providing
;;; each one we try one.
;;;
(defun getdomainname (&optional (where "/etc/defaultdomain"))
(or *domainname*
#+UNIX
(fli:with-dynamic-foreign-objects ((buffer (:ef-mb-string :external-format :ascii :limit 256)))
(and (eql (c-getdomainname buffer 256) 0)
(setq *domainname* (fli:convert-from-foreign-string buffer))))
Try using DNS name lookup : on some machines this
(let* ((self-name (comm:get-host-entry (machine-instance) :fields '(:name)))
(dot (and self-name (position #\. self-name))))
(and dot (subseq self-name (1+ dot))))
(when (probe-file where)
(with-open-file (stream where :direction :input)
(setq *domainname* (read-line stream))))
(error 'www-utils:domain-resolver-error)))
(defun get-host-name-by-address (address)
(or (comm:get-host-entry address :fields '(:name))
(error 'www-utils:domain-resolver-error :address address)))
;;; ----------------------------------------------------------------------------------
;;; STREAM CODE
(defclass chunk-transfer-encoding-output-stream (stream:buffered-stream)
((chunk-start-index)
(chunk-function)
(chunks-transmitted :initform nil)))
(defclass chunk-transfer-decoding-input-stream (stream:buffered-stream)
((chunk-length-received)
(chunk-remaining-bytes :initform nil)
(chunk-real-buffer-limit)))
; local-protocol returns URL scheme protocol for stream, eg :http, :https -- JCMa 3/22/2006
(defclass extended-socket-stream (comm:socket-stream)
((local-host :initarg :local-host :accessor local-host)
(local-port :initarg :local-port :accessor www-utils:local-port)
(foreign-host :initarg :foreign-host :accessor www-utils:foreign-host)
(foreign-port :initarg :foreign-port :accessor www-utils:foreign-port)
(bytes-received :initform 0 :accessor www-utils:bytes-received)
(bytes-transmitted :initform 0 :accessor www-utils:bytes-transmitted)
(local-protocol :initform :http :initarg :local-protocol :accessor www-utils:local-protocol)
#+CL-HTTP-X509
(peer-certificate :initarg :peer-certificate :accessor %peer-certificate)))
(defclass cl-http-chunk-transfer-socket-stream
(chunk-transfer-encoding-output-stream
chunk-transfer-decoding-input-stream
extended-socket-stream)
())
(defmethod print-object ((socket-stream extended-socket-stream) stream)
(with-slots (local-protocol local-host local-port foreign-host foreign-port) socket-stream
(flet ((ip-address (thing)
(etypecase thing
(integer (ip-address-string thing))
(string thing)))
(local-host ()
(ip-address-string (internet-address (machine-instance)))))
(declare (inline local-host))
(print-unreadable-object (socket-stream stream :type t :identity t)
(when (and (slot-boundp socket-stream 'foreign-host)
(slot-boundp socket-stream 'foreign-port))
(format stream "~A: ~A:~A <-> ~A:~D" local-protocol (ip-address local-host)
(if (slot-boundp socket-stream 'local-port) local-port "loopback")
(ip-address foreign-host) foreign-port))))))
;;;-------------------------------------------------------------------
;;;
;;; X.509 STREAM INTERFACE
;;;
#+CL-HTTP-X509
(declaim (inline %ssl-peer-certificate-verified-p))
#+CL-HTTP-X509
(defun %ssl-peer-certificate-verified-p (ssl)
(zerop (comm::ssl-get-verify-result ssl)))
#+CL-HTTP-X509
(defgeneric www-utils:peer-certificate-verified-p (extended-socket-stream)
(:documentation "Returns non-null when peer certificate has been verified for the SSL EXTENDED-SOCKET-STREAM.
If the stream is not in SSL mode or peer certificates are not required this returns NIL."))
#+CL-HTTP-X509
(defmethod www-utils:peer-certificate-verified-p ((stream extended-socket-stream))
(let ((ssl (comm:socket-stream-ssl stream)))
(when ssl
(%ssl-peer-certificate-verified-p ssl))))
#+CL-HTTP-X509
(declaim (function (http::allocate-x509-certificate (x509-pointer))))
#+CL-HTTP-X509
(defmethod www-utils:peer-certificate ((stream extended-socket-stream))
(flet ((get-peer-certificate (stream)
(let ((ssl (comm:socket-stream-ssl stream)))
(when (and ssl (%ssl-peer-certificate-verified-p ssl))
(let ((x509-pointer (comm::ssl-get-peer-certificate ssl)))
(when (and (not (fli:null-pointer-p x509-pointer)) ;not valid if null
(comm::x509-pointer-p x509-pointer))
(http::allocate-x509-certificate x509-pointer)))))))
(declare (inline get-peer-certificate))
(cond ((slot-boundp stream 'peer-certificate)
(%peer-certificate stream))
(t (setf (%peer-certificate stream) (get-peer-certificate stream))))))
;;;-------------------------------------------------------------------
;;;
;;; STREAM INTERFACE
;;;
(defmethod stream:stream-read-buffer ((stream extended-socket-stream)
buffer start end)
(declare (ignore buffer start end))
(with-slots (bytes-received) stream
(let ((len (call-next-method)))
(declare (fixnum len))
(when (> len 0)
(incf bytes-received len))
len)))
(defmethod stream:stream-write-buffer :after ((stream extended-socket-stream)
buffer start end)
(declare (ignore buffer)
(fixnum start end))
(with-slots (bytes-transmitted) stream
(incf bytes-transmitted (the fixnum (- end start)))))
(declaim (inline make-tcp-stream))
Why not resource the stream objects and save some consing ? -- JCMa 10/9/2003
(defun make-tcp-stream (socket-handle local-port read-timeout)
(multiple-value-bind (foreign-host foreign-port)
(comm:get-socket-peer-address socket-handle)
(if foreign-host
(multiple-value-bind (local-host local-port*)
(comm:get-socket-address socket-handle)
(declare (ignore local-port*))
(make-instance 'cl-http-chunk-transfer-socket-stream
:socket socket-handle
:direction :io
:element-type 'base-char
:local-host local-host
:local-port local-port
:foreign-host foreign-host
:foreign-port foreign-port
:read-timeout read-timeout
:local-protocol :http))
(error 'www-utils:network-error))))
(defun lispworks-accept-connection (fd port read-timeout function)
(declare (optimize (speed 3)))
(handler-case
(let ((stream (make-tcp-stream fd port read-timeout)))
(funcall function stream port))
(error (c) (abort c)))) ;announce
(defun %listen-for-connections (address port backlog read-timeout function)
(declare (optimize (speed 3)))
(let ((fctn-spec `(lispworks-accept-connection ,port ,read-timeout ,function)))
(declare (dynamic-extent fctn-spec))
(comm::listen-and-attach-stream fctn-spec port nil backlog address)))
#+CL-HTTP-SSL
(declaim (inline make-ssl-tcp-stream))
#+CL-HTTP-SSL
(defun make-ssl-tcp-stream (socket-handle local-port read-timeout ssl-ctx)
(multiple-value-bind (foreign-host foreign-port)
(comm:get-socket-peer-address socket-handle)
(if foreign-host
(multiple-value-bind (local-host local-port*)
(comm:get-socket-address socket-handle)
(declare (ignore local-port*))
(make-instance 'cl-http-chunk-transfer-socket-stream
:socket socket-handle
:direction :io
:element-type 'base-char
:local-host local-host
:local-port local-port
:foreign-host foreign-host
:foreign-port foreign-port
:read-timeout read-timeout
:local-protocol :https
:ssl-ctx ssl-ctx
:ssl-side :server))
(error 'www-utils:network-error))))
#+CL-HTTP-SSL
(defun lispworks-accept-ssl-connection (fd port read-timeout ssl-ctx function)
(handler-case
(let ((stream (make-ssl-tcp-stream fd port read-timeout ssl-ctx)))
(funcall function stream port))
(error (c) (abort c)))) ;announce
#+CL-HTTP-SSL
(defun %listen-for-ssl-connections (address port backlog read-timeout ssl-ctx function)
(declare (optimize (speed 3)))
(let ((fctn-spec `(lispworks-accept-ssl-connection ,port ,read-timeout ,ssl-ctx ,function)))
(declare (dynamic-extent fctn-spec))
(comm::listen-and-attach-stream fctn-spec port nil backlog address)))
#-CL-HTTP-SSL
(defun http::%open-http-stream-to-host (host port timeout)
(declare (optimize (speed 3)))
(let ((socket-handle nil))
(unwind-protect
(progn
(setq socket-handle (comm:connect-to-tcp-server host port :errorp nil :timeout timeout))
(if socket-handle
(multiple-value-bind (local-host local-port)
(comm:get-socket-address socket-handle)
(make-instance 'cl-http-chunk-transfer-socket-stream
:socket (shiftf socket-handle nil)
:direction :io
:element-type 'base-char
:local-host local-host
:local-port local-port
:foreign-host host
:foreign-port port
:read-timeout timeout))
(error 'www-utils:connection-error)))
(when socket-handle
(comm::close-socket socket-handle)))))
;; Added SSL client streams. -- JCMa 3/22/2006
#+CL-HTTP-SSL
(defun http::%open-http-stream-to-host (host port timeout &optional ssl-ctx)
(declare (optimize (speed 3)))
(let ((socket-handle nil))
(unwind-protect
(cond ((setq socket-handle (comm:connect-to-tcp-server host port :errorp nil :timeout timeout))
(multiple-value-bind (local-host local-port)
(comm:get-socket-address socket-handle)
(make-instance 'cl-http-chunk-transfer-socket-stream
:socket (shiftf socket-handle nil)
:direction :io
:element-type 'base-char
:local-host local-host
:local-port local-port
:foreign-host host
:foreign-port port
:read-timeout timeout
:ssl-ctx ssl-ctx
:ssl-side :client)))
(ssl-ctx
(error 'www-utils:ssl-connection-error))
(t (error 'www-utils:connection-error)))
(when socket-handle
(comm::close-socket socket-handle)))))
(defclass smtp-stream (extended-socket-stream)
((newline-p :initform t)
(body-p :initform nil)))
When LW does not know them , add assigned protocol ports here .
(defvar *tcp-service-port-alist* '(("finger" . 79)))
(defun tcp-service-port-number-aux (service-name error-p)
(let ((port (or (comm::get-port-for-service service-name "tcp")
(cdr (assoc service-name *tcp-service-port-alist* :test #'string-equal)))))
(cond (port (comm::ntohs port))
(error-p (error "Unknown TCP service name ~S" service-name)))))
(defun www-utils:tcp-service-port-number (protocol &optional error-p)
"Returns the service port number for the TCP protocol denoted by protocol.
PROTOCOL is a keyword,, but integer and string are also supported."
(etypecase protocol
(integer protocol)
(keyword
(let ((string (string-downcase protocol)))
(declare (dynamic-extent string))
(tcp-service-port-number-aux string error-p)))
(string (tcp-service-port-number-aux protocol error-p))))
(declaim (inline smtp::%open-mailer-stream))
(defun smtp::%open-mailer-stream (host port args)
(let ((socket-handle nil))
(unwind-protect
(progn
(setq socket-handle (comm:connect-to-tcp-server host port :errorp nil))
(if socket-handle
(apply 'make-instance 'smtp-stream
:socket (shiftf socket-handle nil)
:direction :io
:element-type 'base-char
:foreign-host host
:foreign-port port
args)
(error 'www-utils:connection-error)))
(when socket-handle
(comm::close-socket socket-handle)))))
redfines to not apply to lispworks4
(defmacro smtp::with-message-body-encoding ((stream output-stream) &body body)
`(let ((,stream ,output-stream))
(unwind-protect
(progn
(setf (slot-value ,stream 'body-p) t)
. ,body)
(setf (slot-value ,stream 'body-p) nil))))
(defmethod stream:stream-write-char ((stream smtp-stream) char)
(with-slots (newline-p body-p) stream
;; Convert dot at line start to dot dot.
(when (and newline-p body-p (eql char #\.))
(call-next-method stream #\.))
Convert newline to CRLF .
(when (setf newline-p (eql char #\Newline))
(call-next-method stream #\Return))
(call-next-method)))
(defmethod stream:stream-write-string ((stream smtp-stream) string &optional (start 0) end)
(with-slots (newline-p) stream
(loop (let ((break (position-if #'(lambda (char)
(or (eql char #\Newline)
(eql char #\.)))
string
:start start
:end end)))
(unless break
(setf newline-p nil)
(return (call-next-method stream string start end)))
(when (> break start)
(setf newline-p nil))
(call-next-method stream string start break)
(stream:stream-write-char stream (char string break))
(setq start (1+ break))))))
#+MSWindows
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant WSAENETRESET 10052)
(defconstant WSAECONNABORTED 10053)
(defconstant WSAECONNRESET 10054)
(defconstant WSAETIMEDOUT 10060)
(defconstant WSAECONNREFUSED 10061)
(defconstant WSAEHOSTDOWN 10064)
)
#+unix
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant EPIPE 32)
(defparameter ENETRESET
(cond ((sys:featurep :sunos4) 52)
((sys:featurep :svr4) 129)
((sys:featurep :aix) 71)
((sys:featurep :hp-ux) 230)
((sys:featurep :osf1) 52)
((sys:featurep :linux) 102)
((sys:featurep :darwin) 52)
((sys:featurep :freebsd) 52)
))
(defparameter ECONNABORTED
(cond ((sys:featurep :sunos4) 53)
((sys:featurep :svr4) 130)
((sys:featurep :aix) 72)
((sys:featurep :hp-ux) 231)
((sys:featurep :osf1) 53)
((sys:featurep :linux) 103)
((sys:featurep :darwin) 53)
((sys:featurep :freebsd) 53)
))
(defparameter ECONNRESET
(cond ((sys:featurep :sunos4) 54)
((sys:featurep :svr4) 131)
((sys:featurep :aix) 73)
((sys:featurep :hp-ux) 232)
((sys:featurep :osf1) 54)
((sys:featurep :linux) 104)
((sys:featurep :darwin) 54)
((sys:featurep :freebsd) 54)
))
(defparameter ETIMEDOUT
(cond ((sys:featurep :sunos4) 60)
((sys:featurep :svr4) 145)
((sys:featurep :aix) 78)
((sys:featurep :hp-ux) 238)
((sys:featurep :osf1) 60)
((sys:featurep :linux) 110)
((sys:featurep :darwin) 60)
((sys:featurep :freebsd) 60)
))
(defparameter ECONNREFUSED
(cond ((sys:featurep :sunos4) 61)
((sys:featurep :svr4) 146)
((sys:featurep :aix) 79)
((sys:featurep :hp-ux) 239)
((sys:featurep :osf1) 61)
((sys:featurep :linux) 111)
((sys:featurep :darwin) 61)
((sys:featurep :freebsd) 61)
))
(defparameter EHOSTDOWN
(cond ((sys:featurep :sunos4) 64)
((sys:featurep :svr4) 147)
((sys:featurep :aix) 80)
((sys:featurep :hp-ux) 241)
((sys:featurep :osf1) 64)
((sys:featurep :linux) 112)
((sys:featurep :darwin) 64)
((sys:featurep :freebsd) 64)
)))
;; Hook into error signaling
(defmethod comm::socket-error ((stream extended-socket-stream) error-code format-control &rest format-arguments)
(let ((class #+MSWindows
(case error-code
((#.WSAECONNABORTED #.WSAECONNRESET)
'www-utils:connection-closed)
((#.WSAETIMEDOUT)
'connection-timed-out)
((#.WSAENETRESET)
'www-utils:connection-lost)
((#.WSAECONNREFUSED)
'www-utils:connection-refused)
((#.WSAEHOSTDOWN)
'www-utils:host-not-responding)
(t 'www-utils:network-error))
#+unix
(cond ((or (eql error-code EPIPE)
(eql error-code ECONNABORTED)
(eql error-code ECONNRESET))
'www-utils:connection-closed)
((eql error-code ETIMEDOUT)
'connection-timed-out)
((eql error-code ENETRESET)
'www-utils:connection-lost)
((eql error-code ECONNREFUSED)
'www-utils:connection-refused)
((eql error-code ECONNREFUSED)
'www-utils:host-not-responding)
(t 'www-utils:network-error))))
(error class :format-control "~A during socket operation: ~?" :format-arguments (list class format-control format-arguments))))
(define-condition www-utils:end-of-chunk-transfer-decoding (end-of-file)
()
(:documentation "Condition signalled when a complete HTTP resource has been successfully transferred.")
(:report (lambda (condition stream)
(format stream "End of chunk tranfer decoding on stream ~S"
(stream-error-stream condition)))))
(define-condition end-of-file-while-copying (end-of-file)
((bytes :initarg :bytes))
(:report (lambda (condition stream)
(with-slots (bytes) condition
(format stream "End of stream before n-bytes ~D copied."
bytes)))))
(defmethod http:stream-copy-until-eof ((from-stream stream) (to-stream stream) &optional copy-mode)
(declare (optimize (speed 3))
(ignore copy-mode))
(%stream-copy-bytes from-stream to-stream nil))
(defmethod http::stream-copy-bytes ((from-stream stream) (to-stream stream) n-bytes &optional (copy-mode :binary))
(declare (optimize (speed 3))
(ignore copy-mode))
(%stream-copy-bytes from-stream to-stream n-bytes))
(defmethod http::stream-copy-byte-range ((from-stream stream) (to-stream stream) start last)
(cond ((file-position from-stream start)
(%stream-copy-bytes from-stream to-stream (- last start)))
(t (error "Unable to set file position for byte range copy."))))
(defun %copy-buffer (output-buffer input-buffer output-index input-index new-output-limit)
(declare (fixnum output-index input-index new-output-limit)
#-CL-HTTP-Debugging (optimize (safety 0)))
#+LispWorks4.0
(do ((input-index input-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (schar output-buffer output-index)
(schar input-buffer input-index)))
post 4.0 , replace is more than 2 times faster
(replace output-buffer input-buffer
:start1 output-index
:start2 input-index
:end1 new-output-limit))
(defun %binary-copy-buffer (output-buffer input-buffer output-index input-index new-output-limit)
(declare (fixnum output-index input-index new-output-limit)
#-CL-HTTP-Debugging (optimize (safety 0)))
#+LispWorks4.0
(do ((input-index input-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (aref output-buffer output-index)
(aref input-buffer input-index)))
post 4.0 , replace is more than 2 times faster
(replace output-buffer input-buffer
:start1 output-index
:start2 input-index
:end1 new-output-limit))
(defmacro loop-over-stream-input-buffer ((input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
&body body)
(rebinding (from-stream n-bytes)
`(loop (when (eql ,n-bytes 0)
(return))
(stream:with-stream-input-buffer (,input-buffer ,input-index ,input-limit)
,from-stream
(if (>= ,input-index ,input-limit)
(unless (handler-case (stream:stream-fill-buffer ,from-stream)
(www-utils:end-of-chunk-transfer-decoding
()
nil))
(if ,n-bytes
(error 'end-of-file-while-copying
:stream ,from-stream
:bytes ,n-bytes)
(return)))
(let* ((input-length (- ,input-limit ,input-index))
(,input-bytes (if (or (null ,n-bytes) (> ,n-bytes input-length))
input-length
,n-bytes)))
(declare (fixnum input-length ,input-bytes))
,@body
(when ,n-bytes
(decf ,n-bytes ,input-bytes))))))))
(defmethod %stream-copy-bytes ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream) n-bytes)
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(let ((remaining-input-bytes input-bytes))
(loop (stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(if (>= output-index output-limit)
(stream:stream-flush-buffer to-stream)
(let* ((test-output-limit (+ output-index remaining-input-bytes))
(new-output-limit (if (> test-output-limit output-limit)
output-limit
test-output-limit))
(output-length (- new-output-limit output-index)))
(%copy-buffer output-buffer input-buffer
output-index input-index
new-output-limit)
(incf input-index output-length)
(setf output-index new-output-limit)
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(decf remaining-input-bytes output-length)
(when (eql remaining-input-bytes 0)
(return))))))))
nil)
(defmethod %stream-copy-bytes ((from-stream stream:buffered-stream) (to-stream stream) n-bytes)
(declare (optimize (speed 3)))
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(let ((input-end (+ input-index input-bytes)))
(declare (fixnum input-end)
#+CL-HTTP-Untested (optimize (safety 0)))
(loop for index fixnum from input-index below input-end
do (write-byte (char-code (schar input-buffer index)) to-stream))
(setf input-index input-end)))
nil)
#+comment ;; untested
(defmethod %stream-copy-bytes ((from-stream stream) (to-stream stream:buffered-stream) n-bytes)
(let ((remaining-input-bytes n-bytes))
(loop (when (eql remaining-input-bytes 0)
(return))
(loop (stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(if (>= output-index output-limit)
(stream:stream-flush-buffer to-stream)
(let* ((test-output-limit (if remaining-input-bytes
(+ output-index remaining-input-bytes)
output-limit))
(new-output-limit (if (> test-output-limit output-limit)
output-limit
test-output-limit))
(output-length (- new-output-limit output-index)))
(loop for index from output-index to new-output-limit
for byte = (read-byte from-stream n-bytes nil)
when (null byte)
do (progn
(setq new-output-limit index)
(setq output-length (- new-output-limit output-index))
(setq remaining-input-bytes 0)
(return))
do (setf (schar output-buffer index)
(code-char byte)))
(setf output-index new-output-limit)
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(when remaining-input-bytes
(decf remaining-input-bytes output-length))
(when (eql remaining-input-bytes 0)
(return))))))))
nil)
post 4.0 , file - stream is a stream : buffered - stream
(defmethod %stream-copy-bytes ((from-stream file-stream)
(to-stream stream:buffered-stream)
n-bytes)
(multiple-value-bind (existing-buffer existing-index existing-limit)
(stream-grab-existing-input-buffer from-stream n-bytes)
(loop (when (eql n-bytes 0)
(return))
(stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(if (>= output-index output-limit)
(stream:stream-flush-buffer to-stream)
(let ((output-length
(if (> existing-limit existing-index)
(let* ((remaining-input-bytes (- existing-limit existing-index))
(test-output-limit (+ output-index remaining-input-bytes))
(new-output-limit (if (> test-output-limit output-limit)
output-limit
test-output-limit))
(output-length (- new-output-limit output-index)))
(do ((input-index existing-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (schar output-buffer output-index)
(char existing-buffer input-index)))
(incf existing-index output-length)
(setf output-index new-output-limit)
output-length)
(let ((output-length (sys::read-binary-bytes from-stream output-buffer
(- output-limit output-index)
output-index)))
(when (eql output-length 0)
(if n-bytes
(error 'end-of-file-while-copying
:strean from-stream
:bytes n-bytes)
(return)))
(incf output-index output-length)
output-length))))
(when n-bytes
(decf n-bytes output-length)))))))
nil)
post 4.0 , file - stream is a stream : buffered - stream
(defmethod %stream-copy-bytes ((from-stream stream:buffered-stream)
(to-stream file-stream)
n-bytes)
(force-output to-stream) ; serialize, to allow unbuffered output
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(sys::write-binary-bytes to-stream input-buffer input-bytes input-index)
(incf input-index input-bytes))
nil)
#+CAPI
(defmethod http:stream-copy-until-eof ((from-stream stream:buffered-stream) (to-stream editor::rubber-stream) &optional (copy-mode :text))
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream nil)
(let ((input-end (+ input-index input-bytes)))
(declare (fixnum input-end)
#+CL-HTTP-Untested (optimize (safety 0)))
(loop for index fixnum from input-index below input-end
for char = (schar input-buffer index)
do (cond ((member char '(#\return #\linefeed))
(when (eql char #\newline)
(terpri to-stream)))
(t (write-char char to-stream))))
(setf input-index input-end))))
post 4.0 , file - stream is a stream : buffered - stream
(defmethod stream-grab-existing-input-buffer ((stream file-stream)
n-bytes)
(let* ((buffer (io::file-stream-buffer stream))
(index (io::file-stream-index stream))
(limit (length buffer))
(new-index (if n-bytes
(min limit (the fixnum (+ index (the fixnum n-bytes))))
limit)))
(declare (fixnum index limit new-index))
(setf (io::file-stream-index stream) new-index)
(values buffer
index
new-index)))
#-(or LispWorks3.2 LispWorks4)
(defmethod http::input-available-on-streams-p ((streams cons) wait-reason timeout)
(sys::wait-for-input-streams-returning-first streams :wait-reason wait-reason :timeout timeout))
(defmethod http::stream-copy-input-buffer ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream))
(loop (stream:with-stream-input-buffer
(input-buffer input-index input-limit)
from-stream
(if (>= input-index input-limit)
(stream:stream-fill-buffer from-stream)
(let ((remaining-input-bytes (- input-limit input-index)))
(loop (stream:with-stream-output-buffer
(output-buffer output-index output-limit)
to-stream
(if (>= output-index output-limit)
(stream:stream-flush-buffer to-stream)
(let* ((test-output-limit (+ output-index remaining-input-bytes))
(new-output-limit (if (> test-output-limit output-limit) output-limit test-output-limit))
(output-length (- new-output-limit output-index)))
(%copy-buffer output-buffer input-buffer output-index input-index new-output-limit)
(incf input-index output-length)
(setf output-index new-output-limit)
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(decf remaining-input-bytes output-length)
(when (eql remaining-input-bytes 0)
(return))))))
(return))))))
(defmethod http::advance-input-buffer ((stream stream:buffered-stream) &optional delta)
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(stream delta)
input-buffer ; ignore this way because a declare ignore does not work here
(incf input-index input-bytes)))
(defmacro element-type-ecase (stream &body body)
`(let ((element-type (stream-element-type ,stream)))
(cond ,.(loop for (elt-type . forms) in body
for test = (etypecase elt-type (symbol 'eq) (cons 'equal))
collect `((,test element-type ',elt-type) ,@forms))
(t (error "Unknown element type, ~S, for the stream, ~S." element-type ,stream)))))
(defun %binary-to-8bit-char-copy-buffers (output-buffer input-buffer output-index input-index new-output-limit)
(declare (fixnum output-index input-index new-output-limit)
(type (simple-base-string) output-buffer)
(type (array (unsigned-byte 8) (*)) input-buffer) ; not simple-array
#-CL-HTTP-Debugging (optimize (safety 0)))
(do ((input-index input-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (schar output-buffer output-index) (code-char (aref input-buffer input-index)))))
(defmethod 8-bit-buffer-input-function ((stream stream:buffered-stream))
(element-type-ecase stream
((unsigned-byte 8) #'%binary-to-8bit-char-copy-buffers)
(base-char #'%binary-to-8bit-char-copy-buffers)
(lw:simple-char (error "Multi-byte characters are not implmented yet."))))
(defmethod 8-bit-buffer-input-function ((stream comm:socket-stream))
(element-type-ecase stream
(base-char #'%binary-to-8bit-char-copy-buffers)
((unsigned-byte 8) #'%binary-copy-buffer)))
(defmethod http::binary-stream-copy-from-8-bit-array (from-array (to-stream stream:buffered-stream) &optional (start 0) end)
(let* ((input-index start)
(input-limit (or end (length from-array)))
(remaining-input-bytes (- input-limit input-index))
(copy-buffer-function (8-bit-buffer-input-function to-stream)))
(declare (fixnum input-index input-limit remaining-input-bytes))
(loop doing (stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(declare (fixnum output-index output-limit))
(cond ((>= output-index output-limit) (stream:stream-flush-buffer to-stream))
(t (let* ((output-length (min (- output-limit output-index) remaining-input-bytes))
(new-output-limit (+ output-index output-length)))
(declare (fixnum output-length new-output-limit))
(funcall copy-buffer-function output-buffer from-array output-index input-index new-output-limit)
(incf input-index output-length)
(setf output-index new-output-limit)
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(decf remaining-input-bytes output-length)
(when (eql remaining-input-bytes 0)
(return)))))))))
(defun %8bit-char-to-binary-copy-buffer (output-buffer input-buffer output-index input-index new-output-limit)
(declare (fixnum output-index input-index new-output-limit)
#-CL-HTTP-Debugging (optimize (safety 0)))
(do ((input-index input-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (aref output-buffer output-index) (char-code (schar input-buffer input-index)))))
(defmethod 8-bit-buffer-output-function ((stream stream:buffered-stream))
(element-type-ecase stream
(character #'%8bit-char-to-binary-copy-buffer)
((unsigned-byte 8) #'%8bit-char-to-binary-copy-buffer)
(lw:simple-char (error "Multi-byte characters are not implmented yet for ~S streams." (type-of stream)))))
(defmethod 8-bit-buffer-output-function ((stream comm:socket-stream))
(element-type-ecase stream
(base-char #'%8bit-char-to-binary-copy-buffer)
((unsigned-byte 8) #'%binary-copy-buffer)))
(defmacro handler-case-if (condition form &body clauses)
`(flet ((execute-form () ,form))
(declare (inline execute-form))
(cond (,condition
(handler-case (execute-form) ,@clauses))
(t (execute-form)))))
(defmethod http::binary-stream-copy-into-8-bit-array ((from-stream stream:buffered-stream) n-bytes &optional (start 0) 8-bit-array
&aux (size 0))
(declare (fixnum start size))
(flet ((make-the-array (size fill-pointer)
(make-array size :fill-pointer fill-pointer :adjustable t :element-type '(unsigned-byte 8)))
(adjust-the-array (array size fill-pointer)
(let ((new-array (adjust-array array size :fill-pointer fill-pointer :element-type '(unsigned-byte 8))))
#+testing(unless (eq new-array array) (format t "New array in adjustment."))
new-array))
(new-size (size)
(cond ((< size 64000) (* 2 size))
(t (truncate (* size 1.2))))))
(declare (inline make-the-array adjust-the-array new-size))
(multiple-value-bind (copy-buffer-function)
(8-bit-buffer-output-function from-stream)
(cond (n-bytes
(locally
(declare (fixnum n-bytes))
(setq size (+ n-bytes start))
(cond ((null 8-bit-array)
(setq 8-bit-array (make-the-array size start)))
((< (array-total-size 8-bit-array) size)
(setq 8-bit-array (adjust-the-array 8-bit-array size start))))
(let ((fill-pointer start)
output-limit)
(declare (fixnum fill-pointer))
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(setq output-limit (+ fill-pointer input-bytes))
(funcall copy-buffer-function 8-bit-array input-buffer fill-pointer input-index output-limit)
(setf input-index (+ input-index input-bytes)
fill-pointer output-limit)))
(values 8-bit-array (setf (fill-pointer 8-bit-array) (+ start n-bytes)))))
;; the size and growth issues are open to experimentation and better
;; algorithms that do less work. 7/26/95 -- JCMa.
(t (cond ((null 8-bit-array)
(setq size (+ 1000 start)
8-bit-array (make-the-array size start)))
(t (setq size (array-total-size 8-bit-array))))
(let ((fill-pointer start)
output-limit)
(declare (fixnum fill-pointer))
(loop with chunking-p = (chunked-transfer-decoding-p from-stream)
doing (stream:with-stream-input-buffer (input-buffer input-index input-limit)
from-stream
(cond ((>= input-index input-limit)
(unless (handler-case-if chunking-p
(stream:stream-fill-buffer from-stream) ;advance input buffer
(www-utils:end-of-chunk-transfer-decoding () nil)) ;catch end of chunk transfer decoding
(return)))
(t (setq output-limit (+ fill-pointer (the fixnum (- input-limit input-index))))
(when (> output-limit size)
(setq 8-bit-array (adjust-the-array 8-bit-array (setq size (new-size size)) fill-pointer)))
(funcall copy-buffer-function 8-bit-array input-buffer fill-pointer input-index output-limit)
(setf input-index input-limit
fill-pointer output-limit)))))
(values 8-bit-array (setf (fill-pointer 8-bit-array) fill-pointer))))))))
;; Primitive for reading delimited lines which does not reset the fill-pointer
(defun www-utils::%buffered-stream-read-delimited-line (stream delimiters eof buffer)
(declare (optimize (speed 3)))
(flet ((do-it (stream delimiters eof buffer)
(declare (type string buffer)
(type stream:buffered-stream stream)
(type cons delimiters))
(let* ((size (array-total-size buffer))
(start (fill-pointer buffer))
(fill-pointer start)
eof-p delimiter)
(declare (fixnum size start fill-pointer))
(loop named buffer-feed
with chunking-p = (chunked-transfer-decoding-p stream)
doing (stream:with-stream-input-buffer (input-buffer input-index input-limit)
stream
(cond ((>= input-index input-limit)
(unless (handler-case-if chunking-p
(stream:stream-fill-buffer stream) ;advance input buffer
(www-utils:end-of-chunk-transfer-decoding () nil)) ;catch end of chunk transfer decoding
line is good if we found the first delimiter
(return-from buffer-feed)))
(t (locally
#+CL-HTTP-Untested (declare (optimize (safety 0)))
(loop named fill-buffer
for input-idx fixnum upfrom input-index below input-limit
for char = (schar input-buffer input-idx)
do (cond (delimiter
(if (and (member char delimiters) (not (eql delimiter char)))
(setf input-index (1+ input-idx)) ;advance buffer index
(setf input-index input-idx));set buffer index to current char
(return-from buffer-feed))
((member char delimiters) ;set delimiter flag
(setq delimiter char))
(t (unless (< fill-pointer size) ;grow the copy buffer
(setq size (floor (* (the fixnum size) 1.2))
buffer (adjust-array buffer size :element-type (array-element-type buffer))))
(setf (aref buffer fill-pointer) char) ;fill copy buffer
(incf fill-pointer)))
finally (setf input-index input-limit))))))) ;advance buffer index
(if (= start fill-pointer) ; no data read
(values (if eof-p eof buffer) eof-p delimiter (fill-pointer buffer))
(values buffer eof-p delimiter (setf (fill-pointer buffer) fill-pointer))))))
(cond (buffer
(do-it stream delimiters eof buffer))
(t (resources:using-resource (line-buffer http::line-buffer http::*line-buffer-size*)
(multiple-value-bind (buf eof-p delim length)
(do-it stream delimiters eof line-buffer)
(values (if eof-p eof (subseq buf 0 length)) eof-p delim length)))))))
(defmethod www-utils:read-delimited-line ((stream stream:buffered-stream) &optional (delimiters '(#\Return #\Linefeed)) eof buffer)
callers depend on zero - based start
(www-utils::%buffered-stream-read-delimited-line stream delimiters eof buffer))
(defmethod http::crlf-stream-copy-into-string ((stream stream:buffered-stream) &optional n-bytes (start 0) string)
(flet ((make-the-string (size fill-pointer)
(make-array size :fill-pointer fill-pointer :adjustable t :element-type http::*standard-character-type*))
(adjust-the-string (string size fill-pointer)
(adjust-array string size :fill-pointer fill-pointer :element-type (array-element-type string)))
(new-size (size)
(cond ((< size 64000) (* 2 size))
(t (truncate (* size 1.2))))))
(declare (inline make-the-string adjust-the-string new-size))
(macrolet ((push-char (char string index delimiter)
`(cond ((member ,char '(#\return #\linefeed))
(cond ((and ,delimiter (not (eql ,char ,delimiter)))
(setq ,delimiter nil))
(t (setq ,delimiter ,char) ;update new delimiter
ANSI CL line terminator
(incf ,index))))
(t (setf (aref ,string ,index) ,char)
(incf ,index)))))
(let ((fill-pointer start)
(size 0)
delimiter)
(declare (fixnum fill-pointer size))
(cond (n-bytes
(setq size (+ n-bytes start))
(cond ((null string)
(setq string (make-the-string size start)))
((< (array-total-size string) size)
(setq string (adjust-the-string string size fill-pointer))))
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(stream n-bytes)
(let ((input-end (+ input-index input-bytes)))
(declare (fixnum input-end)
#+CL-HTTP-Untested (optimize (safety 0)))
(loop for index fixnum from input-index below input-end
for char = (schar input-buffer index)
do (push-char char string fill-pointer delimiter))
(setf input-index input-end))))
;; the size and growth issues are open to experimentation and better
;; algorithms that do less work. 7/26/95 -- JCMa.
(t (cond ((null string)
(setq size (+ 1000 start)
string (make-the-string size start)))
(t (setq size (array-total-size string))))
(loop with chunking-p = (chunked-transfer-decoding-p stream)
doing (stream:with-stream-input-buffer (input-buffer input-index input-limit)
stream
(declare (fixnum input-index input-limit))
(cond ((>= input-index input-limit)
(unless (handler-case-if chunking-p
(stream:stream-fill-buffer stream) ;advance input buffer
(www-utils:end-of-chunk-transfer-decoding () nil))
(return)))
(t (locally
#+CL-HTTP-Untested (declare (optimize (safety 0)))
(loop for index fixnum upfrom input-index below input-limit
for char = (schar input-buffer index)
do (when (= size fill-pointer)
(setq string (adjust-the-string string (setq size (new-size size)) fill-pointer)))
do (push-char char string fill-pointer delimiter)))
(setf input-index input-limit)))))))
;; return the string and actual fill pointer
(values string (setf (fill-pointer string) fill-pointer))))))
;; convenient abstraction
(defun %stream-standardize-line-breaks (from-stream to-stream line-break-char &optional n-bytes &aux delimiter)
(declare (type stream:buffered-stream from-stream)
(type stream:buffered-stream to-stream))
(macrolet ((push-char (char string index delimiter)
`(cond ((member ,char '(#\return #\linefeed))
(cond ((and ,delimiter (not (eql ,char ,delimiter)))
(setq ,delimiter nil))
(t (setq ,delimiter ,char) ;update new delimiter
(setf (aref ,string ,index) line-break-char) ;insert the line break character
(incf ,index))))
(t (setf (aref ,string ,index) ,char)
(incf ,index)))))
(ipc::loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(loop with remaining-input-bytes fixnum = input-bytes
doing (stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(cond ((>= output-index output-limit) (stream:stream-flush-buffer to-stream))
(t (locally
#+CL-HTTP-Untested (declare (optimize (safety 0)))
(loop with output-idx fixnum = output-index
with input-size fixnum = (min (- output-limit output-index) remaining-input-bytes)
with input-end fixnum = (+ input-index input-size)
for index fixnum from input-index below input-end
for char = (schar input-buffer index)
do (push-char char output-buffer output-idx delimiter)
finally (progn
(decf remaining-input-bytes input-size)
(setf input-index input-end
output-index output-idx))))
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(when (eql remaining-input-bytes 0)
(return)))))))))
(defmethod http::stream-decode-crlf-bytes ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream) n-bytes)
ANSI CL line terminator
(defmethod http::stream-decode-crlf-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream))
ANSI CL line terminator
(defmethod http::stream-standardize-line-breaks-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream)
(line-break (eql :cr)))
(%stream-standardize-line-breaks from-stream to-stream #\return nil))
(defmethod http::stream-standardize-line-breaks-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream)
(line-break (eql :lf)))
(%stream-standardize-line-breaks from-stream to-stream #\linefeed nil))
(defmethod http::stream-standardize-line-breaks-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream)
(line-break (eql :crlf)))
(http::stream-encode-crlf-until-eof from-stream to-stream))
;; This should produce a correct CRLF when the input is a CRLF stream!
Version by
(defun %buffered-stream-write-string (stream string start end)
(declare (type string string)
(type stream:buffered-stream stream)
(fixnum start end))
(macrolet ((%push-char (char buffer index)
`(prog2 (setf (aref ,buffer ,index) ,char)
(incf ,index)))
(push-char (char buffer index limit at-cr-p) ; Even when receiving CRLF input, make this transmit a CRLF stream.
`(cond ((member ,char '(#\return #\linefeed))
(%push-char #\Return ,buffer ,index)
(cond ((< ,index ,limit)
(%push-char #\Linefeed ,buffer ,index))
(t (setq ,at-cr-p t) ;end of output buffer
nil)))
(t (%push-char ,char ,buffer ,index)))))
(let ((input-index start)
at-cr-p)
(declare (fixnum input-index))
(loop (stream:with-stream-output-buffer (output-buffer output-index output-limit)
stream
(cond ((>= output-index output-limit)
(stream:stream-flush-buffer stream))
(t (let ((output-idx output-index)
(index input-index))
(loop (let ((char (schar string index)))
(incf index)
(unless (push-char char output-buffer output-idx output-limit at-cr-p)
(return))
(when (or (>= index end)
(>= output-idx output-limit))
(return))))
(setf input-index index
output-index output-idx))
(when (>= output-index output-limit)
(stream:stream-flush-buffer stream)))))
(when at-cr-p
(stream:with-stream-output-buffer (output-buffer output-index output-limit)
stream
ignore ? What about zero length buffers ?
(%push-char #\Linefeed output-buffer output-index)
(setq at-cr-p nil)))
(when (>= input-index end)
(return)))
(values input-index))))
(defmethod http::stream-encode-crlf-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream))
#+later(declare (optimize (safety 0)))
(loop with chunking-p = (chunked-transfer-decoding-p from-stream)
doing (stream:with-stream-input-buffer (input-buffer input-index input-limit)
from-stream
(declare (fixnum input-index input-limit))
(cond ((>= input-index input-limit)
(unless (handler-case-if chunking-p
(stream:stream-fill-buffer from-stream) ;advance input buffer
(www-utils:end-of-chunk-transfer-decoding () nil))
(return)))
(t (let ((new-index (%buffered-stream-write-string to-stream input-buffer input-index input-limit)))
(declare (fixnum new-index))
(setf input-index new-index)))))))
(defmethod http::write-vector ((stream chunk-transfer-encoding-output-stream) (vector string) &optional (start 0) (end (length vector)))
(%buffered-stream-write-string stream vector start end)
vector)
(defmethod http::write-vector ((stream stream:buffered-stream) (vector vector) &optional (start 0) (end (length vector)))
(cond ((equal `(unsigned-byte 8)(array-element-type vector))
(http::binary-stream-copy-from-8-bit-array vector stream start end)
vector) ;return the vector
(t (call-next-method))))
;;;-----------------------------------------------------------------------------------
;;;
;;;
(defun www-utils:process-wait-for-stream (wait-reason stream &optional wait-function timeout)
(declare (optimize (speed 3)))
(mp::process-wait-for-input-stream stream
:wait-function wait-function
:wait-reason wait-reason
:timeout timeout))
(defmethod http::http-input-data-available-p ((stream cl-http-chunk-transfer-socket-stream) &optional timeout-seconds)
"Returns non-null when input data is available on the HTTP STREAM within
TIMEOUT-SECONDS. When timeout-seconds is null, data must be immediately
available. A dead HTTP connection means no data is available.
Ports can specialize this as necessary for their stream and process implementations."
(labels ((data-available-p (stream)
(loop for char = (when (listen stream)
(peek-char nil stream nil))
clear any dangling White Space due to buggy clients .
when (member char '(#\return #\linefeed #\space #\tab) :test #'eql)
do (read-char stream t)
else
return t ;something still there.
finally (return nil)))
(continue-p (stream)
(or (not (www-utils:live-connection-p stream)) ;connection went dead
(data-available-p stream)))) ;data available
(declare (inline data-available-p))
(cond ((not (www-utils:live-connection-p stream)) nil)
((data-available-p stream) t)
#-LispWorks
((and timeout-seconds (not (zerop timeout-seconds)))
;; Block until there is reason to take action
(process-wait-with-timeout
"HTTP Request Wait" timeout-seconds #'continue-p stream)
;; Determine whether input data was available without consing.
(and (www-utils:live-connection-p stream)
(listen stream)))
#+LispWorks
((and timeout-seconds (not (zerop timeout-seconds)))
;; Block until there is reason to take action
(loop (unless (www-utils:live-connection-p stream)
(return nil))
(when (data-available-p stream)
(return t))
(unless (www-utils:process-wait-for-stream
"HTTP Request Wait" stream
nil timeout-seconds)
Timeout expired
(return nil))))
(t nil))))
(defmacro www-utils:with-binary-stream ((stream direction) &body body)
"Turns STREAM into a binary stream within the scope of BODY.
direction can be :OUTPUT, :INPUT, or :BOTH."
(declare (ignore stream direction))
`(progn ,@body))
(defmacro www-utils:with-text-stream ((stream direction) &body body)
"Turns STREAM into a text stream within the scope of BODY.
direction can be :OUTPUT, :INPUT, or :BOTH."
(declare (ignore stream direction))
`(progn ,@body))
(defmacro www-utils:with-crlf-stream ((stream direction) &body body)
"Turns STREAM into a CRLF stream within the scope of BODY.
direction can be :OUTPUT, :INPUT, or :BOTH."
(declare (ignore stream direction))
`(progn ,@body))
(defun www-utils:live-connection-p (http-stream)
"Returns non-null if the TCP/IP connection over HTTP-STREAM remains alive
in that the remote host continue to respond at the TCP/IP level."
(and (open-stream-p http-stream)
(not (stream:stream-check-eof-no-hang http-stream))))
(declaim (inline www-utils:abort-http-stream))
(defun www-utils:abort-http-stream (http-stream)
"Closes http-stream in abort mode.
This will push any output in the transmit buffer and catch any network errors.
Takes care to clean up any dangling pointers."
(handler-case
(close http-stream :abort t)
(www-utils:network-error ())))
;;; ----------------------------------------------------------------------------------
;;; Server side chunking
;;;
(eval-when (:compile-toplevel :execute)
(defmacro fixed-crlf-string (count &key prefix)
`(load-time-value
(coerce ',(append prefix
(loop repeat count
append '(#\Return #\Linefeed)))
'string)))
)
(defmethod www-utils:chunk-transfer-encoding-mode ((stream chunk-transfer-encoding-output-stream)
&optional function)
(with-slots (chunk-function) stream
(check-type function (or null function))
(setf chunk-function function)))
(defmethod www-utils:note-first-chunk ((stream chunk-transfer-encoding-output-stream))
(with-slots (chunk-start-index chunks-transmitted) stream
(unless chunks-transmitted
;; write anything not part of the chunk
(force-output stream)
(stream:with-stream-output-buffer (buffer index limit) stream
;; Insert the CRLF part of the chunk prefix.
(%buffer-insert-crlf buffer (the fixnum (+ index 4)))
;; Advance the buffer past the chunk prefix.
(incf index 6)
;; Leave space in the buffer for the CRLF chunk suffix.
(decf limit 2)
(setf chunk-start-index index)
;; turn on chunking
(setf chunks-transmitted 0)))))
(defmethod www-utils:note-last-chunk ((stream chunk-transfer-encoding-output-stream)
&optional footers-plist)
(with-slots (chunks-transmitted) stream
(when chunks-transmitted
;; write the last chunk
(force-output stream)
;; Restore index and limit.
(stream:with-stream-output-buffer (buffer index limit) stream
buffer ;ignore
(decf index 6)
(incf limit 2))
turn off chunking and write the Chunked - Body terminator ( assumes
;; that :transfer-encoding :chunked was written by caller)
(setf chunks-transmitted nil)
(write-string (fixed-crlf-string 1 :prefix (#\0))
stream)
(http::write-headers stream footers-plist t))))
;; Make note-last-chunk do nothing in future calls e.g. unwinding.
(defmethod close :after ((stream chunk-transfer-encoding-output-stream) &key abort)
(declare (ignore abort))
(with-slots (chunks-transmitted) stream
(setf chunks-transmitted nil)))
(defmethod stream:stream-flush-buffer ((stream chunk-transfer-encoding-output-stream))
(with-slots (chunks-transmitted chunk-start-index) stream
(if chunks-transmitted ; Are we chunking?
(stream:with-stream-output-buffer (buffer index limit) stream
(cond ((or (< index chunk-start-index) ; sanity check
(> index limit)) ; e.g. closed stream
(let ((bad-index index)
(bad-limit limit))
try to get system error first
(error "Output buffer too full to insert chunk size marker ~S index ~D limit ~D chunk-start-index ~D."
stream bad-index bad-limit chunk-start-index)))
((> index chunk-start-index) ; non-empty chunk
(let ((start (%buffer-insert-chunk-size buffer chunk-start-index index)))
(%buffer-insert-crlf buffer index)
(stream:stream-write-buffer stream buffer start (+ index 2)))
(incf chunks-transmitted)
(setf index chunk-start-index))))
(call-next-method))))
(defun %buffer-insert-crlf (buffer index)
(declare (fixnum index))
(setf (schar buffer index) (code-char 13))
(setf (schar buffer (the fixnum (1+ index))) (code-char 10)))
(defun %buffer-insert-chunk-size (buffer start end)
(declare (fixnum start end))
(let* ((size (- end start))
(index (- start 2)))
(declare (fixnum size index))
(loop (decf index)
(let ((digit (logand size 15)))
(setf (schar buffer index)
(if (> digit 9)
(code-char (+ digit (- (char-code #\A) 10)))
(code-char (+ digit (char-code #\0))))))
(setq size (ash size -4))
(when (eql size 0)
(return)))
index))
;;; ----------------------------------------------------------------------------------
CLIENT SIDE CHUNKING
;;;
(defvar *debug-client-chunking* nil)
(defmethod www-utils:chunk-transfer-decoding-mode ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-length-received chunk-remaining-bytes chunk-real-buffer-limit) stream
(setf chunk-length-received 0
chunk-real-buffer-limit nil
chunk-remaining-bytes 0) ;ensure we enter stream:stream-fill-buffer on next read
(%set-buffer-chunk-limit stream)))
(defmethod www-utils:chunk-transfer-decoding-mode-end ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-remaining-bytes chunk-real-buffer-limit) stream
;; Restore the buffer limit in case more real data follows.
(when chunk-real-buffer-limit
(stream:with-stream-input-buffer (buffer index limit) stream
buffer index ;ignore
(setf limit chunk-real-buffer-limit
chunk-real-buffer-limit nil)))
(setq chunk-remaining-bytes nil)))
(defmethod www-utils:chunk-transfer-content-length ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-remaining-bytes chunk-length-received) stream
(if chunk-remaining-bytes
chunk-length-received
(error "~S is not in chunked transfer decoding mode." stream))))
Returns non - null when the stream is decoding chunked input -- JCMa 9/10/2003
(defmethod chunked-transfer-decoding-p ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-remaining-bytes) stream
(not (null chunk-remaining-bytes))))
(defmethod chunked-transfer-decoding-p (stream)
(declare (ignore stream))
nil)
(defmethod stream:stream-fill-buffer ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-length-received chunk-remaining-bytes chunk-real-buffer-limit) stream
(if chunk-remaining-bytes ; Are we chunking?
(when (if (eq chunk-remaining-bytes :eof) ; end of sequence of chunks?
;; Continue to signal eoc until chunk-transfer-decoding-mode-end.
(signal 'www-utils:end-of-chunk-transfer-decoding :stream stream)
(if (eql chunk-remaining-bytes 0) ; end of chunk?
(progn
;; Restore the buffer limit in case more chunk data follows.
(when chunk-real-buffer-limit
(stream:with-stream-input-buffer (buffer index limit) stream
buffer index ;ignore
(setf limit chunk-real-buffer-limit)))
;; Assume another one follows. Condition will be signaled if not.
(%parse-chunk-header stream
#'(lambda (stream)
(declare (ignore stream))
(call-next-method))
(not (eql chunk-length-received 0))))
(call-next-method)))
(%set-buffer-chunk-limit stream)
t)
(call-next-method))))
(defun %set-buffer-chunk-limit (stream)
(declare (type chunk-transfer-decoding-input-stream stream))
(with-slots (chunk-remaining-bytes chunk-real-buffer-limit) stream
(stream:with-stream-input-buffer (buffer index limit) stream
buffer ;ignore
(let ((chunk-end-index (+ index chunk-remaining-bytes)))
(if (< chunk-end-index limit)
;; Chunk ends within the buffer, so record the
;; real limit and put an artificial limit in the
;; stream so stream:stream-fill-buffer is called
;; again at the end of the chunk.
(setf chunk-real-buffer-limit limit
limit chunk-end-index
chunk-remaining-bytes 0)
;; Chunk ends after the limit so allow the whole
;; buffer to be consumed.
(setf chunk-real-buffer-limit nil
chunk-remaining-bytes (- chunk-remaining-bytes (- limit index))))
(when *debug-client-chunking*
(format t "~&;; Client chunk section ~D~%" (- limit index)))))))
#+comment ;MJS 19Jun98: a more pernickety version
(defun %parse-chunk-header-size (stream buffer-fill-function skip-first-crlf)
;; The next bytes in the stream are supposed to be a chunk header.
(declare (type chunk-transfer-decoding-input-stream stream))
(macrolet ((want-char (want)
`(unless (char= ch ,want)
(error "Chunk decoding error: wanted ~S, got ~S in ~S ~S ~S"
,want ch want-cr want-lf parsing-size)))
(adjust-size (baseline)
`(setq size (+ (ash size 4)
(- (char-code ch) ,baseline)))))
(let ((size 0)
(want-char (and skip-first-crlf #\Return)))
(block found-size
(loop (block refill-buffer
(stream:with-stream-input-buffer (buffer index limit) stream
(loop (when (>= index limit)
(return-from refill-buffer))
(let ((ch (schar buffer index)))
(declare (character ch))
(incf index)
(cond ((eql ch want-char)
(cond ((char= ch #\Return)
(setq want-char #\Newline))
must have been # \Newline
(if skip-first-crlf
(setq skip-first-crlf nil
want-char nil)
(return-from found-size)))))
(want-char
(error "Chunk decoding error: wanted ~S, got ~S"
want-char ch))
(t
(cond ((char<= #\0 ch #\9)
(adjust-size (char-code #\0)))
((char<= #\A ch #\Z)
(adjust-size (- (char-code #\A) 10)))
((char<= #\a ch #\z)
(adjust-size (- (char-code #\a) 10)))
((char= ch #\Return)
(setq want-char #\Newline))
((char= ch #\Space)
;; Skip space, which some servers add erroneously
)
(t (error "Chunk decoding error: wanted size, got ~S"
ch)))))))))
(unless (funcall buffer-fill-function stream)
(return-from %parse-chunk-header-size nil))))
size)))
(defun %parse-chunk-header-size (stream buffer-fill-function skip-first-crlf)
;; The next bytes in the stream are supposed to be a chunk header.
(declare (type chunk-transfer-decoding-input-stream stream))
(let ((size 0))
(block found-size
(loop (block refill-buffer
(stream:with-stream-input-buffer (buffer index limit) stream
(loop (when (>= index limit)
(return-from refill-buffer))
(let ((ch (schar buffer index)))
(declare (character ch))
(incf index)
(cond ((char<= #\0 ch #\9)
(setq size (+ (ash size 4)
(- (char-code ch) (char-code #\0)))))
((char<= #\A ch #\Z)
(setq size (+ (ash size 4)
(- (char-code ch) (- (char-code #\A) 10)))))
((char<= #\a ch #\z)
(setq size (+ (ash size 4)
(- (char-code ch) (- (char-code #\a) 10)))))
((char= ch #\Return)
;; Skip return, assumed to be part of CRLF.
)
((char= ch #\Newline)
(if skip-first-crlf
(setq skip-first-crlf nil)
(return-from found-size)))
((char= ch #\Space)
;; Skip space, which some servers add erroneously
)
(t
(error "Chunk decoding error got ~S"
ch)))))))
(unless (funcall buffer-fill-function stream)
(return-from %parse-chunk-header-size nil))))
size))
(defun %parse-chunk-header (stream buffer-fill-function skip-first-crlf)
;; The next bytes in the stream are supposed to be a chunk header.
(declare (type chunk-transfer-decoding-input-stream stream))
(let ((size (%parse-chunk-header-size stream buffer-fill-function skip-first-crlf)))
(when size
(when *debug-client-chunking*
(format t "~&;; New client chunk ~D~%" size))
(if (eql (the fixnum size) 0) ; end of sequence of chunks?
(stream:with-stream-input-buffer (buffer index limit) stream
buffer ;ignore
(with-slots (chunk-remaining-bytes chunk-real-buffer-limit) stream
;; Put an artificial limit in the
;; stream so stream:stream-fill-buffer is called
;; again for each read.
(setf chunk-real-buffer-limit limit
limit index
chunk-remaining-bytes :eof)
(signal 'www-utils:end-of-chunk-transfer-decoding :stream stream)))
(with-slots (chunk-length-received chunk-remaining-bytes) stream
(setf chunk-remaining-bytes size)
(incf chunk-length-received size)))
t)))
| null | https://raw.githubusercontent.com/appleshan/cl-http/a7ec6bf51e260e9bb69d8e180a103daf49aa0ac2/lw/server/tcp-stream.lisp | lisp | -*- Mode: lisp; Package: IPC; -*-
released system pending investigation of a memory corruption bug. 12/17/2003 -- JCMa.
ssl-condition
ssl-closed - The condition class ssl-closed corresponds to SSL_ERROR_ZERO_RETURN . It means the underlying socket is dead.
ssl-error - The condition class ssl-error corresponds to SSL_ERROR_SYSCALL . It means that something got broken.
typically due to a mismatch between the client and the server. You get this error when trying to use a SSL
connection to a non-secure peer.
is rejected by a user callback.
network-error
domain-resolver-error
local-network-error
network-resources-exhausted
unknown-address
unknown-host-name
remote-network-error
bad-connection-state
connection-closed
connection-lost
host-stopped-responding
connection-error
connection-refused
host-not-responding
protocol-timeout
network-parse-error
MJS 07Oct97: not used
----------------------------------------------------------------------------------
NETWORK ADDRESS CODE
Turn internet address into string format
Turn internet string address format into IP number
based on what OS you are using. Instead of providing
each one we try one.
----------------------------------------------------------------------------------
STREAM CODE
local-protocol returns URL scheme protocol for stream, eg :http, :https -- JCMa 3/22/2006
-------------------------------------------------------------------
X.509 STREAM INTERFACE
not valid if null
-------------------------------------------------------------------
STREAM INTERFACE
announce
announce
Added SSL client streams. -- JCMa 3/22/2006
Convert dot at line start to dot dot.
Hook into error signaling
untested
serialize, to allow unbuffered output
ignore this way because a declare ignore does not work here
not simple-array
the size and growth issues are open to experimentation and better
algorithms that do less work. 7/26/95 -- JCMa.
advance input buffer
catch end of chunk transfer decoding
Primitive for reading delimited lines which does not reset the fill-pointer
advance input buffer
catch end of chunk transfer decoding
advance buffer index
set buffer index to current char
set delimiter flag
grow the copy buffer
fill copy buffer
advance buffer index
no data read
update new delimiter
the size and growth issues are open to experimentation and better
algorithms that do less work. 7/26/95 -- JCMa.
advance input buffer
return the string and actual fill pointer
convenient abstraction
update new delimiter
insert the line break character
This should produce a correct CRLF when the input is a CRLF stream!
Even when receiving CRLF input, make this transmit a CRLF stream.
end of output buffer
advance input buffer
return the vector
-----------------------------------------------------------------------------------
something still there.
connection went dead
data available
Block until there is reason to take action
Determine whether input data was available without consing.
Block until there is reason to take action
----------------------------------------------------------------------------------
Server side chunking
write anything not part of the chunk
Insert the CRLF part of the chunk prefix.
Advance the buffer past the chunk prefix.
Leave space in the buffer for the CRLF chunk suffix.
turn on chunking
write the last chunk
Restore index and limit.
ignore
that :transfer-encoding :chunked was written by caller)
Make note-last-chunk do nothing in future calls e.g. unwinding.
Are we chunking?
sanity check
e.g. closed stream
non-empty chunk
----------------------------------------------------------------------------------
ensure we enter stream:stream-fill-buffer on next read
Restore the buffer limit in case more real data follows.
ignore
Are we chunking?
end of sequence of chunks?
Continue to signal eoc until chunk-transfer-decoding-mode-end.
end of chunk?
Restore the buffer limit in case more chunk data follows.
ignore
Assume another one follows. Condition will be signaled if not.
ignore
Chunk ends within the buffer, so record the
real limit and put an artificial limit in the
stream so stream:stream-fill-buffer is called
again at the end of the chunk.
Chunk ends after the limit so allow the whole
buffer to be consumed.
MJS 19Jun98: a more pernickety version
The next bytes in the stream are supposed to be a chunk header.
Skip space, which some servers add erroneously
The next bytes in the stream are supposed to be a chunk header.
Skip return, assumed to be part of CRLF.
Skip space, which some servers add erroneously
The next bytes in the stream are supposed to be a chunk header.
end of sequence of chunks?
ignore
Put an artificial limit in the
stream so stream:stream-fill-buffer is called
again for each read. | LispWorks 4 interface to TCP / IP streams
Copyright ( C ) 1997 - 2000 Xanalys Inc. All rights reserved .
Enhancements Copyright ( C ) 2003 , 2006 , . All rights reserved .
(in-package :IPC)
Added SSL support conditionalized by # + CL - HTTP - SSL -- JCMa 3/24/2006
Some optimization declarations conditionalized by # + CL - HTTP - Debugging have
been changed to # + CL - HTTP - Untested in order to increase safety in the
SSL condition hierarchy introduced by LispWorks 4.4
ssl - failure - The condition class ssl - failure corresponds to SSL_ERROR_SSL . This means a failure in processing the input ,
ssl - x509 - lookup - The condition class ssl - x509 - lookup corresponds to SSL_ERROR_WANT_X509_LOOKUP . It happens when a certificate
This is the condition hierarchy , based on the one .
(defparameter *tcp-stream-safe-abort-states*
'("Waiting for socket input"
"Waiting for socket output")
"Process whostates from which it is safe to abort HTTP connnections.")
(define-condition www-utils:network-error (simple-error)
()
(:report (lambda (condition stream)
(let ((control (simple-condition-format-control condition)))
(if control
(apply #'format stream control (simple-condition-format-arguments condition))
(format stream "A network error of type ~S occurred." (type-of condition))))))
(:default-initargs
:format-control nil
:format-arguments nil))
(define-condition www-utils:domain-resolver-error (www-utils:network-error)
((address :initarg :address))
(:report (lambda (condition stream)
(if (slot-boundp condition 'address)
(format stream "Cannot resolve IP address ~A" (ip-address-string (slot-value condition 'address)))
(format stream "Cannot find current domainname")))))
(define-condition www-utils:local-network-error (www-utils:network-error)
())
(define-condition www-utils:unknown-host-name (www-utils:local-network-error)
((hostname :initarg :hostname))
(:report (lambda (condition stream)
(format stream "Unknown host name ~A" (slot-value condition 'hostname)))))
(define-condition www-utils:unknown-address (www-utils:local-network-error)
((address :initarg :address))
(:report (lambda (condition stream)
(let ((address (slot-value condition 'address)))
(format stream "Unknown address ~A" (ip-address-string address))))))
(define-condition www-utils:remote-network-error (www-utils:network-error) ())
#+CL-HTTP-SSL
(define-condition www-utils:ssl-certificate-rejected (www-utils:network-error comm:ssl-x509-lookup) ())
(define-condition www-utils:bad-connection-state (www-utils:remote-network-error) ())
(define-condition www-utils:connection-closed (www-utils:bad-connection-state) ())
#+CL-HTTP-SSL
(define-condition www-utils:ssl-connection-closed (www-utils:connection-closed comm:ssl-closed) ())
(define-condition www-utils:connection-lost (www-utils:bad-connection-state) ())
(define-condition www-utils:host-stopped-responding (www-utils:bad-connection-state) ())
(define-condition www-utils:connection-error (www-utils:remote-network-error) ())
#+CL-HTTP-SSL
(define-condition www-utils:ssl-connection-error (www-utils:connection-error comm:ssl-error) ())
(define-condition www-utils:connection-refused (www-utils:connection-error) ())
#+CL-HTTP-SSL
(define-condition www-utils:ssl-connection-refused (www-utils:connection-refused comm:ssl-failure) ())
(define-condition www-utils:host-not-responding (www-utils:remote-network-error) ())
(define-condition www-utils:protocol-timeout (www-utils:remote-network-error) ())
(define-condition www-utils:network-error-mixin
(www-utils:network-error)
()
(:documentation "Mixin to allow ports to inherit instance variables and methods to network conditions
defined at the portable code level."))
(define-condition connection-timed-out (www-utils:protocol-timeout www-utils:bad-connection-state)
()
(:report (lambda (condition stream)
(declare (ignore condition))
(format stream "Connection timed out."))))
(defun ip-address-string (address)
(comm:ip-address-string address))
(defun string-ip-address (address-string)
(let ((address (comm:string-ip-address address-string)))
#+LispWorks4.0
(when (eql address #xffffffff)
(setq address nil))
address))
(defun internet-address (name)
(or (comm:get-host-entry name :fields '(:address))
(error 'www-utils:unknown-host-name :hostname name)))
(defun internet-addresses (name)
(or (comm:get-host-entry name :fields '(:addresses))
(error 'www-utils:unknown-host-name :hostname name)))
#+UNIX
(fli:define-foreign-function (c-getdomainname getdomainname)
((name :pointer)
(namelen :int))
:result-type :int)
(defvar *domainname* nil)
There are more than one strategies you can use
(defun getdomainname (&optional (where "/etc/defaultdomain"))
(or *domainname*
#+UNIX
(fli:with-dynamic-foreign-objects ((buffer (:ef-mb-string :external-format :ascii :limit 256)))
(and (eql (c-getdomainname buffer 256) 0)
(setq *domainname* (fli:convert-from-foreign-string buffer))))
Try using DNS name lookup : on some machines this
(let* ((self-name (comm:get-host-entry (machine-instance) :fields '(:name)))
(dot (and self-name (position #\. self-name))))
(and dot (subseq self-name (1+ dot))))
(when (probe-file where)
(with-open-file (stream where :direction :input)
(setq *domainname* (read-line stream))))
(error 'www-utils:domain-resolver-error)))
(defun get-host-name-by-address (address)
(or (comm:get-host-entry address :fields '(:name))
(error 'www-utils:domain-resolver-error :address address)))
(defclass chunk-transfer-encoding-output-stream (stream:buffered-stream)
((chunk-start-index)
(chunk-function)
(chunks-transmitted :initform nil)))
(defclass chunk-transfer-decoding-input-stream (stream:buffered-stream)
((chunk-length-received)
(chunk-remaining-bytes :initform nil)
(chunk-real-buffer-limit)))
(defclass extended-socket-stream (comm:socket-stream)
((local-host :initarg :local-host :accessor local-host)
(local-port :initarg :local-port :accessor www-utils:local-port)
(foreign-host :initarg :foreign-host :accessor www-utils:foreign-host)
(foreign-port :initarg :foreign-port :accessor www-utils:foreign-port)
(bytes-received :initform 0 :accessor www-utils:bytes-received)
(bytes-transmitted :initform 0 :accessor www-utils:bytes-transmitted)
(local-protocol :initform :http :initarg :local-protocol :accessor www-utils:local-protocol)
#+CL-HTTP-X509
(peer-certificate :initarg :peer-certificate :accessor %peer-certificate)))
(defclass cl-http-chunk-transfer-socket-stream
(chunk-transfer-encoding-output-stream
chunk-transfer-decoding-input-stream
extended-socket-stream)
())
(defmethod print-object ((socket-stream extended-socket-stream) stream)
(with-slots (local-protocol local-host local-port foreign-host foreign-port) socket-stream
(flet ((ip-address (thing)
(etypecase thing
(integer (ip-address-string thing))
(string thing)))
(local-host ()
(ip-address-string (internet-address (machine-instance)))))
(declare (inline local-host))
(print-unreadable-object (socket-stream stream :type t :identity t)
(when (and (slot-boundp socket-stream 'foreign-host)
(slot-boundp socket-stream 'foreign-port))
(format stream "~A: ~A:~A <-> ~A:~D" local-protocol (ip-address local-host)
(if (slot-boundp socket-stream 'local-port) local-port "loopback")
(ip-address foreign-host) foreign-port))))))
#+CL-HTTP-X509
(declaim (inline %ssl-peer-certificate-verified-p))
#+CL-HTTP-X509
(defun %ssl-peer-certificate-verified-p (ssl)
(zerop (comm::ssl-get-verify-result ssl)))
#+CL-HTTP-X509
(defgeneric www-utils:peer-certificate-verified-p (extended-socket-stream)
(:documentation "Returns non-null when peer certificate has been verified for the SSL EXTENDED-SOCKET-STREAM.
If the stream is not in SSL mode or peer certificates are not required this returns NIL."))
#+CL-HTTP-X509
(defmethod www-utils:peer-certificate-verified-p ((stream extended-socket-stream))
(let ((ssl (comm:socket-stream-ssl stream)))
(when ssl
(%ssl-peer-certificate-verified-p ssl))))
#+CL-HTTP-X509
(declaim (function (http::allocate-x509-certificate (x509-pointer))))
#+CL-HTTP-X509
(defmethod www-utils:peer-certificate ((stream extended-socket-stream))
(flet ((get-peer-certificate (stream)
(let ((ssl (comm:socket-stream-ssl stream)))
(when (and ssl (%ssl-peer-certificate-verified-p ssl))
(let ((x509-pointer (comm::ssl-get-peer-certificate ssl)))
(comm::x509-pointer-p x509-pointer))
(http::allocate-x509-certificate x509-pointer)))))))
(declare (inline get-peer-certificate))
(cond ((slot-boundp stream 'peer-certificate)
(%peer-certificate stream))
(t (setf (%peer-certificate stream) (get-peer-certificate stream))))))
(defmethod stream:stream-read-buffer ((stream extended-socket-stream)
buffer start end)
(declare (ignore buffer start end))
(with-slots (bytes-received) stream
(let ((len (call-next-method)))
(declare (fixnum len))
(when (> len 0)
(incf bytes-received len))
len)))
(defmethod stream:stream-write-buffer :after ((stream extended-socket-stream)
buffer start end)
(declare (ignore buffer)
(fixnum start end))
(with-slots (bytes-transmitted) stream
(incf bytes-transmitted (the fixnum (- end start)))))
(declaim (inline make-tcp-stream))
Why not resource the stream objects and save some consing ? -- JCMa 10/9/2003
(defun make-tcp-stream (socket-handle local-port read-timeout)
(multiple-value-bind (foreign-host foreign-port)
(comm:get-socket-peer-address socket-handle)
(if foreign-host
(multiple-value-bind (local-host local-port*)
(comm:get-socket-address socket-handle)
(declare (ignore local-port*))
(make-instance 'cl-http-chunk-transfer-socket-stream
:socket socket-handle
:direction :io
:element-type 'base-char
:local-host local-host
:local-port local-port
:foreign-host foreign-host
:foreign-port foreign-port
:read-timeout read-timeout
:local-protocol :http))
(error 'www-utils:network-error))))
(defun lispworks-accept-connection (fd port read-timeout function)
(declare (optimize (speed 3)))
(handler-case
(let ((stream (make-tcp-stream fd port read-timeout)))
(funcall function stream port))
(defun %listen-for-connections (address port backlog read-timeout function)
(declare (optimize (speed 3)))
(let ((fctn-spec `(lispworks-accept-connection ,port ,read-timeout ,function)))
(declare (dynamic-extent fctn-spec))
(comm::listen-and-attach-stream fctn-spec port nil backlog address)))
#+CL-HTTP-SSL
(declaim (inline make-ssl-tcp-stream))
#+CL-HTTP-SSL
(defun make-ssl-tcp-stream (socket-handle local-port read-timeout ssl-ctx)
(multiple-value-bind (foreign-host foreign-port)
(comm:get-socket-peer-address socket-handle)
(if foreign-host
(multiple-value-bind (local-host local-port*)
(comm:get-socket-address socket-handle)
(declare (ignore local-port*))
(make-instance 'cl-http-chunk-transfer-socket-stream
:socket socket-handle
:direction :io
:element-type 'base-char
:local-host local-host
:local-port local-port
:foreign-host foreign-host
:foreign-port foreign-port
:read-timeout read-timeout
:local-protocol :https
:ssl-ctx ssl-ctx
:ssl-side :server))
(error 'www-utils:network-error))))
#+CL-HTTP-SSL
(defun lispworks-accept-ssl-connection (fd port read-timeout ssl-ctx function)
(handler-case
(let ((stream (make-ssl-tcp-stream fd port read-timeout ssl-ctx)))
(funcall function stream port))
#+CL-HTTP-SSL
(defun %listen-for-ssl-connections (address port backlog read-timeout ssl-ctx function)
(declare (optimize (speed 3)))
(let ((fctn-spec `(lispworks-accept-ssl-connection ,port ,read-timeout ,ssl-ctx ,function)))
(declare (dynamic-extent fctn-spec))
(comm::listen-and-attach-stream fctn-spec port nil backlog address)))
#-CL-HTTP-SSL
(defun http::%open-http-stream-to-host (host port timeout)
(declare (optimize (speed 3)))
(let ((socket-handle nil))
(unwind-protect
(progn
(setq socket-handle (comm:connect-to-tcp-server host port :errorp nil :timeout timeout))
(if socket-handle
(multiple-value-bind (local-host local-port)
(comm:get-socket-address socket-handle)
(make-instance 'cl-http-chunk-transfer-socket-stream
:socket (shiftf socket-handle nil)
:direction :io
:element-type 'base-char
:local-host local-host
:local-port local-port
:foreign-host host
:foreign-port port
:read-timeout timeout))
(error 'www-utils:connection-error)))
(when socket-handle
(comm::close-socket socket-handle)))))
#+CL-HTTP-SSL
(defun http::%open-http-stream-to-host (host port timeout &optional ssl-ctx)
(declare (optimize (speed 3)))
(let ((socket-handle nil))
(unwind-protect
(cond ((setq socket-handle (comm:connect-to-tcp-server host port :errorp nil :timeout timeout))
(multiple-value-bind (local-host local-port)
(comm:get-socket-address socket-handle)
(make-instance 'cl-http-chunk-transfer-socket-stream
:socket (shiftf socket-handle nil)
:direction :io
:element-type 'base-char
:local-host local-host
:local-port local-port
:foreign-host host
:foreign-port port
:read-timeout timeout
:ssl-ctx ssl-ctx
:ssl-side :client)))
(ssl-ctx
(error 'www-utils:ssl-connection-error))
(t (error 'www-utils:connection-error)))
(when socket-handle
(comm::close-socket socket-handle)))))
(defclass smtp-stream (extended-socket-stream)
((newline-p :initform t)
(body-p :initform nil)))
When LW does not know them , add assigned protocol ports here .
(defvar *tcp-service-port-alist* '(("finger" . 79)))
(defun tcp-service-port-number-aux (service-name error-p)
(let ((port (or (comm::get-port-for-service service-name "tcp")
(cdr (assoc service-name *tcp-service-port-alist* :test #'string-equal)))))
(cond (port (comm::ntohs port))
(error-p (error "Unknown TCP service name ~S" service-name)))))
(defun www-utils:tcp-service-port-number (protocol &optional error-p)
"Returns the service port number for the TCP protocol denoted by protocol.
PROTOCOL is a keyword,, but integer and string are also supported."
(etypecase protocol
(integer protocol)
(keyword
(let ((string (string-downcase protocol)))
(declare (dynamic-extent string))
(tcp-service-port-number-aux string error-p)))
(string (tcp-service-port-number-aux protocol error-p))))
(declaim (inline smtp::%open-mailer-stream))
(defun smtp::%open-mailer-stream (host port args)
(let ((socket-handle nil))
(unwind-protect
(progn
(setq socket-handle (comm:connect-to-tcp-server host port :errorp nil))
(if socket-handle
(apply 'make-instance 'smtp-stream
:socket (shiftf socket-handle nil)
:direction :io
:element-type 'base-char
:foreign-host host
:foreign-port port
args)
(error 'www-utils:connection-error)))
(when socket-handle
(comm::close-socket socket-handle)))))
redfines to not apply to lispworks4
(defmacro smtp::with-message-body-encoding ((stream output-stream) &body body)
`(let ((,stream ,output-stream))
(unwind-protect
(progn
(setf (slot-value ,stream 'body-p) t)
. ,body)
(setf (slot-value ,stream 'body-p) nil))))
(defmethod stream:stream-write-char ((stream smtp-stream) char)
(with-slots (newline-p body-p) stream
(when (and newline-p body-p (eql char #\.))
(call-next-method stream #\.))
Convert newline to CRLF .
(when (setf newline-p (eql char #\Newline))
(call-next-method stream #\Return))
(call-next-method)))
(defmethod stream:stream-write-string ((stream smtp-stream) string &optional (start 0) end)
(with-slots (newline-p) stream
(loop (let ((break (position-if #'(lambda (char)
(or (eql char #\Newline)
(eql char #\.)))
string
:start start
:end end)))
(unless break
(setf newline-p nil)
(return (call-next-method stream string start end)))
(when (> break start)
(setf newline-p nil))
(call-next-method stream string start break)
(stream:stream-write-char stream (char string break))
(setq start (1+ break))))))
#+MSWindows
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant WSAENETRESET 10052)
(defconstant WSAECONNABORTED 10053)
(defconstant WSAECONNRESET 10054)
(defconstant WSAETIMEDOUT 10060)
(defconstant WSAECONNREFUSED 10061)
(defconstant WSAEHOSTDOWN 10064)
)
#+unix
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant EPIPE 32)
(defparameter ENETRESET
(cond ((sys:featurep :sunos4) 52)
((sys:featurep :svr4) 129)
((sys:featurep :aix) 71)
((sys:featurep :hp-ux) 230)
((sys:featurep :osf1) 52)
((sys:featurep :linux) 102)
((sys:featurep :darwin) 52)
((sys:featurep :freebsd) 52)
))
(defparameter ECONNABORTED
(cond ((sys:featurep :sunos4) 53)
((sys:featurep :svr4) 130)
((sys:featurep :aix) 72)
((sys:featurep :hp-ux) 231)
((sys:featurep :osf1) 53)
((sys:featurep :linux) 103)
((sys:featurep :darwin) 53)
((sys:featurep :freebsd) 53)
))
(defparameter ECONNRESET
(cond ((sys:featurep :sunos4) 54)
((sys:featurep :svr4) 131)
((sys:featurep :aix) 73)
((sys:featurep :hp-ux) 232)
((sys:featurep :osf1) 54)
((sys:featurep :linux) 104)
((sys:featurep :darwin) 54)
((sys:featurep :freebsd) 54)
))
(defparameter ETIMEDOUT
(cond ((sys:featurep :sunos4) 60)
((sys:featurep :svr4) 145)
((sys:featurep :aix) 78)
((sys:featurep :hp-ux) 238)
((sys:featurep :osf1) 60)
((sys:featurep :linux) 110)
((sys:featurep :darwin) 60)
((sys:featurep :freebsd) 60)
))
(defparameter ECONNREFUSED
(cond ((sys:featurep :sunos4) 61)
((sys:featurep :svr4) 146)
((sys:featurep :aix) 79)
((sys:featurep :hp-ux) 239)
((sys:featurep :osf1) 61)
((sys:featurep :linux) 111)
((sys:featurep :darwin) 61)
((sys:featurep :freebsd) 61)
))
(defparameter EHOSTDOWN
(cond ((sys:featurep :sunos4) 64)
((sys:featurep :svr4) 147)
((sys:featurep :aix) 80)
((sys:featurep :hp-ux) 241)
((sys:featurep :osf1) 64)
((sys:featurep :linux) 112)
((sys:featurep :darwin) 64)
((sys:featurep :freebsd) 64)
)))
(defmethod comm::socket-error ((stream extended-socket-stream) error-code format-control &rest format-arguments)
(let ((class #+MSWindows
(case error-code
((#.WSAECONNABORTED #.WSAECONNRESET)
'www-utils:connection-closed)
((#.WSAETIMEDOUT)
'connection-timed-out)
((#.WSAENETRESET)
'www-utils:connection-lost)
((#.WSAECONNREFUSED)
'www-utils:connection-refused)
((#.WSAEHOSTDOWN)
'www-utils:host-not-responding)
(t 'www-utils:network-error))
#+unix
(cond ((or (eql error-code EPIPE)
(eql error-code ECONNABORTED)
(eql error-code ECONNRESET))
'www-utils:connection-closed)
((eql error-code ETIMEDOUT)
'connection-timed-out)
((eql error-code ENETRESET)
'www-utils:connection-lost)
((eql error-code ECONNREFUSED)
'www-utils:connection-refused)
((eql error-code ECONNREFUSED)
'www-utils:host-not-responding)
(t 'www-utils:network-error))))
(error class :format-control "~A during socket operation: ~?" :format-arguments (list class format-control format-arguments))))
(define-condition www-utils:end-of-chunk-transfer-decoding (end-of-file)
()
(:documentation "Condition signalled when a complete HTTP resource has been successfully transferred.")
(:report (lambda (condition stream)
(format stream "End of chunk tranfer decoding on stream ~S"
(stream-error-stream condition)))))
(define-condition end-of-file-while-copying (end-of-file)
((bytes :initarg :bytes))
(:report (lambda (condition stream)
(with-slots (bytes) condition
(format stream "End of stream before n-bytes ~D copied."
bytes)))))
(defmethod http:stream-copy-until-eof ((from-stream stream) (to-stream stream) &optional copy-mode)
(declare (optimize (speed 3))
(ignore copy-mode))
(%stream-copy-bytes from-stream to-stream nil))
(defmethod http::stream-copy-bytes ((from-stream stream) (to-stream stream) n-bytes &optional (copy-mode :binary))
(declare (optimize (speed 3))
(ignore copy-mode))
(%stream-copy-bytes from-stream to-stream n-bytes))
(defmethod http::stream-copy-byte-range ((from-stream stream) (to-stream stream) start last)
(cond ((file-position from-stream start)
(%stream-copy-bytes from-stream to-stream (- last start)))
(t (error "Unable to set file position for byte range copy."))))
(defun %copy-buffer (output-buffer input-buffer output-index input-index new-output-limit)
(declare (fixnum output-index input-index new-output-limit)
#-CL-HTTP-Debugging (optimize (safety 0)))
#+LispWorks4.0
(do ((input-index input-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (schar output-buffer output-index)
(schar input-buffer input-index)))
post 4.0 , replace is more than 2 times faster
(replace output-buffer input-buffer
:start1 output-index
:start2 input-index
:end1 new-output-limit))
(defun %binary-copy-buffer (output-buffer input-buffer output-index input-index new-output-limit)
(declare (fixnum output-index input-index new-output-limit)
#-CL-HTTP-Debugging (optimize (safety 0)))
#+LispWorks4.0
(do ((input-index input-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (aref output-buffer output-index)
(aref input-buffer input-index)))
post 4.0 , replace is more than 2 times faster
(replace output-buffer input-buffer
:start1 output-index
:start2 input-index
:end1 new-output-limit))
(defmacro loop-over-stream-input-buffer ((input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
&body body)
(rebinding (from-stream n-bytes)
`(loop (when (eql ,n-bytes 0)
(return))
(stream:with-stream-input-buffer (,input-buffer ,input-index ,input-limit)
,from-stream
(if (>= ,input-index ,input-limit)
(unless (handler-case (stream:stream-fill-buffer ,from-stream)
(www-utils:end-of-chunk-transfer-decoding
()
nil))
(if ,n-bytes
(error 'end-of-file-while-copying
:stream ,from-stream
:bytes ,n-bytes)
(return)))
(let* ((input-length (- ,input-limit ,input-index))
(,input-bytes (if (or (null ,n-bytes) (> ,n-bytes input-length))
input-length
,n-bytes)))
(declare (fixnum input-length ,input-bytes))
,@body
(when ,n-bytes
(decf ,n-bytes ,input-bytes))))))))
(defmethod %stream-copy-bytes ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream) n-bytes)
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(let ((remaining-input-bytes input-bytes))
(loop (stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(if (>= output-index output-limit)
(stream:stream-flush-buffer to-stream)
(let* ((test-output-limit (+ output-index remaining-input-bytes))
(new-output-limit (if (> test-output-limit output-limit)
output-limit
test-output-limit))
(output-length (- new-output-limit output-index)))
(%copy-buffer output-buffer input-buffer
output-index input-index
new-output-limit)
(incf input-index output-length)
(setf output-index new-output-limit)
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(decf remaining-input-bytes output-length)
(when (eql remaining-input-bytes 0)
(return))))))))
nil)
(defmethod %stream-copy-bytes ((from-stream stream:buffered-stream) (to-stream stream) n-bytes)
(declare (optimize (speed 3)))
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(let ((input-end (+ input-index input-bytes)))
(declare (fixnum input-end)
#+CL-HTTP-Untested (optimize (safety 0)))
(loop for index fixnum from input-index below input-end
do (write-byte (char-code (schar input-buffer index)) to-stream))
(setf input-index input-end)))
nil)
(defmethod %stream-copy-bytes ((from-stream stream) (to-stream stream:buffered-stream) n-bytes)
(let ((remaining-input-bytes n-bytes))
(loop (when (eql remaining-input-bytes 0)
(return))
(loop (stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(if (>= output-index output-limit)
(stream:stream-flush-buffer to-stream)
(let* ((test-output-limit (if remaining-input-bytes
(+ output-index remaining-input-bytes)
output-limit))
(new-output-limit (if (> test-output-limit output-limit)
output-limit
test-output-limit))
(output-length (- new-output-limit output-index)))
(loop for index from output-index to new-output-limit
for byte = (read-byte from-stream n-bytes nil)
when (null byte)
do (progn
(setq new-output-limit index)
(setq output-length (- new-output-limit output-index))
(setq remaining-input-bytes 0)
(return))
do (setf (schar output-buffer index)
(code-char byte)))
(setf output-index new-output-limit)
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(when remaining-input-bytes
(decf remaining-input-bytes output-length))
(when (eql remaining-input-bytes 0)
(return))))))))
nil)
post 4.0 , file - stream is a stream : buffered - stream
(defmethod %stream-copy-bytes ((from-stream file-stream)
(to-stream stream:buffered-stream)
n-bytes)
(multiple-value-bind (existing-buffer existing-index existing-limit)
(stream-grab-existing-input-buffer from-stream n-bytes)
(loop (when (eql n-bytes 0)
(return))
(stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(if (>= output-index output-limit)
(stream:stream-flush-buffer to-stream)
(let ((output-length
(if (> existing-limit existing-index)
(let* ((remaining-input-bytes (- existing-limit existing-index))
(test-output-limit (+ output-index remaining-input-bytes))
(new-output-limit (if (> test-output-limit output-limit)
output-limit
test-output-limit))
(output-length (- new-output-limit output-index)))
(do ((input-index existing-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (schar output-buffer output-index)
(char existing-buffer input-index)))
(incf existing-index output-length)
(setf output-index new-output-limit)
output-length)
(let ((output-length (sys::read-binary-bytes from-stream output-buffer
(- output-limit output-index)
output-index)))
(when (eql output-length 0)
(if n-bytes
(error 'end-of-file-while-copying
:strean from-stream
:bytes n-bytes)
(return)))
(incf output-index output-length)
output-length))))
(when n-bytes
(decf n-bytes output-length)))))))
nil)
post 4.0 , file - stream is a stream : buffered - stream
(defmethod %stream-copy-bytes ((from-stream stream:buffered-stream)
(to-stream file-stream)
n-bytes)
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(sys::write-binary-bytes to-stream input-buffer input-bytes input-index)
(incf input-index input-bytes))
nil)
#+CAPI
(defmethod http:stream-copy-until-eof ((from-stream stream:buffered-stream) (to-stream editor::rubber-stream) &optional (copy-mode :text))
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream nil)
(let ((input-end (+ input-index input-bytes)))
(declare (fixnum input-end)
#+CL-HTTP-Untested (optimize (safety 0)))
(loop for index fixnum from input-index below input-end
for char = (schar input-buffer index)
do (cond ((member char '(#\return #\linefeed))
(when (eql char #\newline)
(terpri to-stream)))
(t (write-char char to-stream))))
(setf input-index input-end))))
post 4.0 , file - stream is a stream : buffered - stream
(defmethod stream-grab-existing-input-buffer ((stream file-stream)
n-bytes)
(let* ((buffer (io::file-stream-buffer stream))
(index (io::file-stream-index stream))
(limit (length buffer))
(new-index (if n-bytes
(min limit (the fixnum (+ index (the fixnum n-bytes))))
limit)))
(declare (fixnum index limit new-index))
(setf (io::file-stream-index stream) new-index)
(values buffer
index
new-index)))
#-(or LispWorks3.2 LispWorks4)
(defmethod http::input-available-on-streams-p ((streams cons) wait-reason timeout)
(sys::wait-for-input-streams-returning-first streams :wait-reason wait-reason :timeout timeout))
(defmethod http::stream-copy-input-buffer ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream))
(loop (stream:with-stream-input-buffer
(input-buffer input-index input-limit)
from-stream
(if (>= input-index input-limit)
(stream:stream-fill-buffer from-stream)
(let ((remaining-input-bytes (- input-limit input-index)))
(loop (stream:with-stream-output-buffer
(output-buffer output-index output-limit)
to-stream
(if (>= output-index output-limit)
(stream:stream-flush-buffer to-stream)
(let* ((test-output-limit (+ output-index remaining-input-bytes))
(new-output-limit (if (> test-output-limit output-limit) output-limit test-output-limit))
(output-length (- new-output-limit output-index)))
(%copy-buffer output-buffer input-buffer output-index input-index new-output-limit)
(incf input-index output-length)
(setf output-index new-output-limit)
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(decf remaining-input-bytes output-length)
(when (eql remaining-input-bytes 0)
(return))))))
(return))))))
(defmethod http::advance-input-buffer ((stream stream:buffered-stream) &optional delta)
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(stream delta)
(incf input-index input-bytes)))
(defmacro element-type-ecase (stream &body body)
`(let ((element-type (stream-element-type ,stream)))
(cond ,.(loop for (elt-type . forms) in body
for test = (etypecase elt-type (symbol 'eq) (cons 'equal))
collect `((,test element-type ',elt-type) ,@forms))
(t (error "Unknown element type, ~S, for the stream, ~S." element-type ,stream)))))
(defun %binary-to-8bit-char-copy-buffers (output-buffer input-buffer output-index input-index new-output-limit)
(declare (fixnum output-index input-index new-output-limit)
(type (simple-base-string) output-buffer)
#-CL-HTTP-Debugging (optimize (safety 0)))
(do ((input-index input-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (schar output-buffer output-index) (code-char (aref input-buffer input-index)))))
(defmethod 8-bit-buffer-input-function ((stream stream:buffered-stream))
(element-type-ecase stream
((unsigned-byte 8) #'%binary-to-8bit-char-copy-buffers)
(base-char #'%binary-to-8bit-char-copy-buffers)
(lw:simple-char (error "Multi-byte characters are not implmented yet."))))
(defmethod 8-bit-buffer-input-function ((stream comm:socket-stream))
(element-type-ecase stream
(base-char #'%binary-to-8bit-char-copy-buffers)
((unsigned-byte 8) #'%binary-copy-buffer)))
(defmethod http::binary-stream-copy-from-8-bit-array (from-array (to-stream stream:buffered-stream) &optional (start 0) end)
(let* ((input-index start)
(input-limit (or end (length from-array)))
(remaining-input-bytes (- input-limit input-index))
(copy-buffer-function (8-bit-buffer-input-function to-stream)))
(declare (fixnum input-index input-limit remaining-input-bytes))
(loop doing (stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(declare (fixnum output-index output-limit))
(cond ((>= output-index output-limit) (stream:stream-flush-buffer to-stream))
(t (let* ((output-length (min (- output-limit output-index) remaining-input-bytes))
(new-output-limit (+ output-index output-length)))
(declare (fixnum output-length new-output-limit))
(funcall copy-buffer-function output-buffer from-array output-index input-index new-output-limit)
(incf input-index output-length)
(setf output-index new-output-limit)
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(decf remaining-input-bytes output-length)
(when (eql remaining-input-bytes 0)
(return)))))))))
(defun %8bit-char-to-binary-copy-buffer (output-buffer input-buffer output-index input-index new-output-limit)
(declare (fixnum output-index input-index new-output-limit)
#-CL-HTTP-Debugging (optimize (safety 0)))
(do ((input-index input-index (1+ input-index))
(output-index output-index (1+ output-index)))
((eql output-index new-output-limit))
(setf (aref output-buffer output-index) (char-code (schar input-buffer input-index)))))
(defmethod 8-bit-buffer-output-function ((stream stream:buffered-stream))
(element-type-ecase stream
(character #'%8bit-char-to-binary-copy-buffer)
((unsigned-byte 8) #'%8bit-char-to-binary-copy-buffer)
(lw:simple-char (error "Multi-byte characters are not implmented yet for ~S streams." (type-of stream)))))
(defmethod 8-bit-buffer-output-function ((stream comm:socket-stream))
(element-type-ecase stream
(base-char #'%8bit-char-to-binary-copy-buffer)
((unsigned-byte 8) #'%binary-copy-buffer)))
(defmacro handler-case-if (condition form &body clauses)
`(flet ((execute-form () ,form))
(declare (inline execute-form))
(cond (,condition
(handler-case (execute-form) ,@clauses))
(t (execute-form)))))
(defmethod http::binary-stream-copy-into-8-bit-array ((from-stream stream:buffered-stream) n-bytes &optional (start 0) 8-bit-array
&aux (size 0))
(declare (fixnum start size))
(flet ((make-the-array (size fill-pointer)
(make-array size :fill-pointer fill-pointer :adjustable t :element-type '(unsigned-byte 8)))
(adjust-the-array (array size fill-pointer)
(let ((new-array (adjust-array array size :fill-pointer fill-pointer :element-type '(unsigned-byte 8))))
#+testing(unless (eq new-array array) (format t "New array in adjustment."))
new-array))
(new-size (size)
(cond ((< size 64000) (* 2 size))
(t (truncate (* size 1.2))))))
(declare (inline make-the-array adjust-the-array new-size))
(multiple-value-bind (copy-buffer-function)
(8-bit-buffer-output-function from-stream)
(cond (n-bytes
(locally
(declare (fixnum n-bytes))
(setq size (+ n-bytes start))
(cond ((null 8-bit-array)
(setq 8-bit-array (make-the-array size start)))
((< (array-total-size 8-bit-array) size)
(setq 8-bit-array (adjust-the-array 8-bit-array size start))))
(let ((fill-pointer start)
output-limit)
(declare (fixnum fill-pointer))
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(setq output-limit (+ fill-pointer input-bytes))
(funcall copy-buffer-function 8-bit-array input-buffer fill-pointer input-index output-limit)
(setf input-index (+ input-index input-bytes)
fill-pointer output-limit)))
(values 8-bit-array (setf (fill-pointer 8-bit-array) (+ start n-bytes)))))
(t (cond ((null 8-bit-array)
(setq size (+ 1000 start)
8-bit-array (make-the-array size start)))
(t (setq size (array-total-size 8-bit-array))))
(let ((fill-pointer start)
output-limit)
(declare (fixnum fill-pointer))
(loop with chunking-p = (chunked-transfer-decoding-p from-stream)
doing (stream:with-stream-input-buffer (input-buffer input-index input-limit)
from-stream
(cond ((>= input-index input-limit)
(unless (handler-case-if chunking-p
(return)))
(t (setq output-limit (+ fill-pointer (the fixnum (- input-limit input-index))))
(when (> output-limit size)
(setq 8-bit-array (adjust-the-array 8-bit-array (setq size (new-size size)) fill-pointer)))
(funcall copy-buffer-function 8-bit-array input-buffer fill-pointer input-index output-limit)
(setf input-index input-limit
fill-pointer output-limit)))))
(values 8-bit-array (setf (fill-pointer 8-bit-array) fill-pointer))))))))
(defun www-utils::%buffered-stream-read-delimited-line (stream delimiters eof buffer)
(declare (optimize (speed 3)))
(flet ((do-it (stream delimiters eof buffer)
(declare (type string buffer)
(type stream:buffered-stream stream)
(type cons delimiters))
(let* ((size (array-total-size buffer))
(start (fill-pointer buffer))
(fill-pointer start)
eof-p delimiter)
(declare (fixnum size start fill-pointer))
(loop named buffer-feed
with chunking-p = (chunked-transfer-decoding-p stream)
doing (stream:with-stream-input-buffer (input-buffer input-index input-limit)
stream
(cond ((>= input-index input-limit)
(unless (handler-case-if chunking-p
line is good if we found the first delimiter
(return-from buffer-feed)))
(t (locally
#+CL-HTTP-Untested (declare (optimize (safety 0)))
(loop named fill-buffer
for input-idx fixnum upfrom input-index below input-limit
for char = (schar input-buffer input-idx)
do (cond (delimiter
(if (and (member char delimiters) (not (eql delimiter char)))
(return-from buffer-feed))
(setq delimiter char))
(setq size (floor (* (the fixnum size) 1.2))
buffer (adjust-array buffer size :element-type (array-element-type buffer))))
(incf fill-pointer)))
(values (if eof-p eof buffer) eof-p delimiter (fill-pointer buffer))
(values buffer eof-p delimiter (setf (fill-pointer buffer) fill-pointer))))))
(cond (buffer
(do-it stream delimiters eof buffer))
(t (resources:using-resource (line-buffer http::line-buffer http::*line-buffer-size*)
(multiple-value-bind (buf eof-p delim length)
(do-it stream delimiters eof line-buffer)
(values (if eof-p eof (subseq buf 0 length)) eof-p delim length)))))))
(defmethod www-utils:read-delimited-line ((stream stream:buffered-stream) &optional (delimiters '(#\Return #\Linefeed)) eof buffer)
callers depend on zero - based start
(www-utils::%buffered-stream-read-delimited-line stream delimiters eof buffer))
(defmethod http::crlf-stream-copy-into-string ((stream stream:buffered-stream) &optional n-bytes (start 0) string)
(flet ((make-the-string (size fill-pointer)
(make-array size :fill-pointer fill-pointer :adjustable t :element-type http::*standard-character-type*))
(adjust-the-string (string size fill-pointer)
(adjust-array string size :fill-pointer fill-pointer :element-type (array-element-type string)))
(new-size (size)
(cond ((< size 64000) (* 2 size))
(t (truncate (* size 1.2))))))
(declare (inline make-the-string adjust-the-string new-size))
(macrolet ((push-char (char string index delimiter)
`(cond ((member ,char '(#\return #\linefeed))
(cond ((and ,delimiter (not (eql ,char ,delimiter)))
(setq ,delimiter nil))
ANSI CL line terminator
(incf ,index))))
(t (setf (aref ,string ,index) ,char)
(incf ,index)))))
(let ((fill-pointer start)
(size 0)
delimiter)
(declare (fixnum fill-pointer size))
(cond (n-bytes
(setq size (+ n-bytes start))
(cond ((null string)
(setq string (make-the-string size start)))
((< (array-total-size string) size)
(setq string (adjust-the-string string size fill-pointer))))
(loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(stream n-bytes)
(let ((input-end (+ input-index input-bytes)))
(declare (fixnum input-end)
#+CL-HTTP-Untested (optimize (safety 0)))
(loop for index fixnum from input-index below input-end
for char = (schar input-buffer index)
do (push-char char string fill-pointer delimiter))
(setf input-index input-end))))
(t (cond ((null string)
(setq size (+ 1000 start)
string (make-the-string size start)))
(t (setq size (array-total-size string))))
(loop with chunking-p = (chunked-transfer-decoding-p stream)
doing (stream:with-stream-input-buffer (input-buffer input-index input-limit)
stream
(declare (fixnum input-index input-limit))
(cond ((>= input-index input-limit)
(unless (handler-case-if chunking-p
(www-utils:end-of-chunk-transfer-decoding () nil))
(return)))
(t (locally
#+CL-HTTP-Untested (declare (optimize (safety 0)))
(loop for index fixnum upfrom input-index below input-limit
for char = (schar input-buffer index)
do (when (= size fill-pointer)
(setq string (adjust-the-string string (setq size (new-size size)) fill-pointer)))
do (push-char char string fill-pointer delimiter)))
(setf input-index input-limit)))))))
(values string (setf (fill-pointer string) fill-pointer))))))
(defun %stream-standardize-line-breaks (from-stream to-stream line-break-char &optional n-bytes &aux delimiter)
(declare (type stream:buffered-stream from-stream)
(type stream:buffered-stream to-stream))
(macrolet ((push-char (char string index delimiter)
`(cond ((member ,char '(#\return #\linefeed))
(cond ((and ,delimiter (not (eql ,char ,delimiter)))
(setq ,delimiter nil))
(incf ,index))))
(t (setf (aref ,string ,index) ,char)
(incf ,index)))))
(ipc::loop-over-stream-input-buffer (input-buffer input-index input-limit input-bytes)
(from-stream n-bytes)
(loop with remaining-input-bytes fixnum = input-bytes
doing (stream:with-stream-output-buffer (output-buffer output-index output-limit)
to-stream
(cond ((>= output-index output-limit) (stream:stream-flush-buffer to-stream))
(t (locally
#+CL-HTTP-Untested (declare (optimize (safety 0)))
(loop with output-idx fixnum = output-index
with input-size fixnum = (min (- output-limit output-index) remaining-input-bytes)
with input-end fixnum = (+ input-index input-size)
for index fixnum from input-index below input-end
for char = (schar input-buffer index)
do (push-char char output-buffer output-idx delimiter)
finally (progn
(decf remaining-input-bytes input-size)
(setf input-index input-end
output-index output-idx))))
(when (>= output-index output-limit)
(stream:stream-flush-buffer to-stream))
(when (eql remaining-input-bytes 0)
(return)))))))))
(defmethod http::stream-decode-crlf-bytes ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream) n-bytes)
ANSI CL line terminator
(defmethod http::stream-decode-crlf-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream))
ANSI CL line terminator
(defmethod http::stream-standardize-line-breaks-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream)
(line-break (eql :cr)))
(%stream-standardize-line-breaks from-stream to-stream #\return nil))
(defmethod http::stream-standardize-line-breaks-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream)
(line-break (eql :lf)))
(%stream-standardize-line-breaks from-stream to-stream #\linefeed nil))
(defmethod http::stream-standardize-line-breaks-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream)
(line-break (eql :crlf)))
(http::stream-encode-crlf-until-eof from-stream to-stream))
Version by
(defun %buffered-stream-write-string (stream string start end)
(declare (type string string)
(type stream:buffered-stream stream)
(fixnum start end))
(macrolet ((%push-char (char buffer index)
`(prog2 (setf (aref ,buffer ,index) ,char)
(incf ,index)))
`(cond ((member ,char '(#\return #\linefeed))
(%push-char #\Return ,buffer ,index)
(cond ((< ,index ,limit)
(%push-char #\Linefeed ,buffer ,index))
nil)))
(t (%push-char ,char ,buffer ,index)))))
(let ((input-index start)
at-cr-p)
(declare (fixnum input-index))
(loop (stream:with-stream-output-buffer (output-buffer output-index output-limit)
stream
(cond ((>= output-index output-limit)
(stream:stream-flush-buffer stream))
(t (let ((output-idx output-index)
(index input-index))
(loop (let ((char (schar string index)))
(incf index)
(unless (push-char char output-buffer output-idx output-limit at-cr-p)
(return))
(when (or (>= index end)
(>= output-idx output-limit))
(return))))
(setf input-index index
output-index output-idx))
(when (>= output-index output-limit)
(stream:stream-flush-buffer stream)))))
(when at-cr-p
(stream:with-stream-output-buffer (output-buffer output-index output-limit)
stream
ignore ? What about zero length buffers ?
(%push-char #\Linefeed output-buffer output-index)
(setq at-cr-p nil)))
(when (>= input-index end)
(return)))
(values input-index))))
(defmethod http::stream-encode-crlf-until-eof ((from-stream stream:buffered-stream) (to-stream stream:buffered-stream))
#+later(declare (optimize (safety 0)))
(loop with chunking-p = (chunked-transfer-decoding-p from-stream)
doing (stream:with-stream-input-buffer (input-buffer input-index input-limit)
from-stream
(declare (fixnum input-index input-limit))
(cond ((>= input-index input-limit)
(unless (handler-case-if chunking-p
(www-utils:end-of-chunk-transfer-decoding () nil))
(return)))
(t (let ((new-index (%buffered-stream-write-string to-stream input-buffer input-index input-limit)))
(declare (fixnum new-index))
(setf input-index new-index)))))))
(defmethod http::write-vector ((stream chunk-transfer-encoding-output-stream) (vector string) &optional (start 0) (end (length vector)))
(%buffered-stream-write-string stream vector start end)
vector)
(defmethod http::write-vector ((stream stream:buffered-stream) (vector vector) &optional (start 0) (end (length vector)))
(cond ((equal `(unsigned-byte 8)(array-element-type vector))
(http::binary-stream-copy-from-8-bit-array vector stream start end)
(t (call-next-method))))
(defun www-utils:process-wait-for-stream (wait-reason stream &optional wait-function timeout)
(declare (optimize (speed 3)))
(mp::process-wait-for-input-stream stream
:wait-function wait-function
:wait-reason wait-reason
:timeout timeout))
(defmethod http::http-input-data-available-p ((stream cl-http-chunk-transfer-socket-stream) &optional timeout-seconds)
"Returns non-null when input data is available on the HTTP STREAM within
TIMEOUT-SECONDS. When timeout-seconds is null, data must be immediately
available. A dead HTTP connection means no data is available.
Ports can specialize this as necessary for their stream and process implementations."
(labels ((data-available-p (stream)
(loop for char = (when (listen stream)
(peek-char nil stream nil))
clear any dangling White Space due to buggy clients .
when (member char '(#\return #\linefeed #\space #\tab) :test #'eql)
do (read-char stream t)
else
finally (return nil)))
(continue-p (stream)
(declare (inline data-available-p))
(cond ((not (www-utils:live-connection-p stream)) nil)
((data-available-p stream) t)
#-LispWorks
((and timeout-seconds (not (zerop timeout-seconds)))
(process-wait-with-timeout
"HTTP Request Wait" timeout-seconds #'continue-p stream)
(and (www-utils:live-connection-p stream)
(listen stream)))
#+LispWorks
((and timeout-seconds (not (zerop timeout-seconds)))
(loop (unless (www-utils:live-connection-p stream)
(return nil))
(when (data-available-p stream)
(return t))
(unless (www-utils:process-wait-for-stream
"HTTP Request Wait" stream
nil timeout-seconds)
Timeout expired
(return nil))))
(t nil))))
(defmacro www-utils:with-binary-stream ((stream direction) &body body)
"Turns STREAM into a binary stream within the scope of BODY.
direction can be :OUTPUT, :INPUT, or :BOTH."
(declare (ignore stream direction))
`(progn ,@body))
(defmacro www-utils:with-text-stream ((stream direction) &body body)
"Turns STREAM into a text stream within the scope of BODY.
direction can be :OUTPUT, :INPUT, or :BOTH."
(declare (ignore stream direction))
`(progn ,@body))
(defmacro www-utils:with-crlf-stream ((stream direction) &body body)
"Turns STREAM into a CRLF stream within the scope of BODY.
direction can be :OUTPUT, :INPUT, or :BOTH."
(declare (ignore stream direction))
`(progn ,@body))
(defun www-utils:live-connection-p (http-stream)
"Returns non-null if the TCP/IP connection over HTTP-STREAM remains alive
in that the remote host continue to respond at the TCP/IP level."
(and (open-stream-p http-stream)
(not (stream:stream-check-eof-no-hang http-stream))))
(declaim (inline www-utils:abort-http-stream))
(defun www-utils:abort-http-stream (http-stream)
"Closes http-stream in abort mode.
This will push any output in the transmit buffer and catch any network errors.
Takes care to clean up any dangling pointers."
(handler-case
(close http-stream :abort t)
(www-utils:network-error ())))
(eval-when (:compile-toplevel :execute)
(defmacro fixed-crlf-string (count &key prefix)
`(load-time-value
(coerce ',(append prefix
(loop repeat count
append '(#\Return #\Linefeed)))
'string)))
)
(defmethod www-utils:chunk-transfer-encoding-mode ((stream chunk-transfer-encoding-output-stream)
&optional function)
(with-slots (chunk-function) stream
(check-type function (or null function))
(setf chunk-function function)))
(defmethod www-utils:note-first-chunk ((stream chunk-transfer-encoding-output-stream))
(with-slots (chunk-start-index chunks-transmitted) stream
(unless chunks-transmitted
(force-output stream)
(stream:with-stream-output-buffer (buffer index limit) stream
(%buffer-insert-crlf buffer (the fixnum (+ index 4)))
(incf index 6)
(decf limit 2)
(setf chunk-start-index index)
(setf chunks-transmitted 0)))))
(defmethod www-utils:note-last-chunk ((stream chunk-transfer-encoding-output-stream)
&optional footers-plist)
(with-slots (chunks-transmitted) stream
(when chunks-transmitted
(force-output stream)
(stream:with-stream-output-buffer (buffer index limit) stream
(decf index 6)
(incf limit 2))
turn off chunking and write the Chunked - Body terminator ( assumes
(setf chunks-transmitted nil)
(write-string (fixed-crlf-string 1 :prefix (#\0))
stream)
(http::write-headers stream footers-plist t))))
(defmethod close :after ((stream chunk-transfer-encoding-output-stream) &key abort)
(declare (ignore abort))
(with-slots (chunks-transmitted) stream
(setf chunks-transmitted nil)))
(defmethod stream:stream-flush-buffer ((stream chunk-transfer-encoding-output-stream))
(with-slots (chunks-transmitted chunk-start-index) stream
(stream:with-stream-output-buffer (buffer index limit) stream
(let ((bad-index index)
(bad-limit limit))
try to get system error first
(error "Output buffer too full to insert chunk size marker ~S index ~D limit ~D chunk-start-index ~D."
stream bad-index bad-limit chunk-start-index)))
(let ((start (%buffer-insert-chunk-size buffer chunk-start-index index)))
(%buffer-insert-crlf buffer index)
(stream:stream-write-buffer stream buffer start (+ index 2)))
(incf chunks-transmitted)
(setf index chunk-start-index))))
(call-next-method))))
(defun %buffer-insert-crlf (buffer index)
(declare (fixnum index))
(setf (schar buffer index) (code-char 13))
(setf (schar buffer (the fixnum (1+ index))) (code-char 10)))
(defun %buffer-insert-chunk-size (buffer start end)
(declare (fixnum start end))
(let* ((size (- end start))
(index (- start 2)))
(declare (fixnum size index))
(loop (decf index)
(let ((digit (logand size 15)))
(setf (schar buffer index)
(if (> digit 9)
(code-char (+ digit (- (char-code #\A) 10)))
(code-char (+ digit (char-code #\0))))))
(setq size (ash size -4))
(when (eql size 0)
(return)))
index))
CLIENT SIDE CHUNKING
(defvar *debug-client-chunking* nil)
(defmethod www-utils:chunk-transfer-decoding-mode ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-length-received chunk-remaining-bytes chunk-real-buffer-limit) stream
(setf chunk-length-received 0
chunk-real-buffer-limit nil
(%set-buffer-chunk-limit stream)))
(defmethod www-utils:chunk-transfer-decoding-mode-end ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-remaining-bytes chunk-real-buffer-limit) stream
(when chunk-real-buffer-limit
(stream:with-stream-input-buffer (buffer index limit) stream
(setf limit chunk-real-buffer-limit
chunk-real-buffer-limit nil)))
(setq chunk-remaining-bytes nil)))
(defmethod www-utils:chunk-transfer-content-length ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-remaining-bytes chunk-length-received) stream
(if chunk-remaining-bytes
chunk-length-received
(error "~S is not in chunked transfer decoding mode." stream))))
Returns non - null when the stream is decoding chunked input -- JCMa 9/10/2003
(defmethod chunked-transfer-decoding-p ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-remaining-bytes) stream
(not (null chunk-remaining-bytes))))
(defmethod chunked-transfer-decoding-p (stream)
(declare (ignore stream))
nil)
(defmethod stream:stream-fill-buffer ((stream chunk-transfer-decoding-input-stream))
(with-slots (chunk-length-received chunk-remaining-bytes chunk-real-buffer-limit) stream
(signal 'www-utils:end-of-chunk-transfer-decoding :stream stream)
(progn
(when chunk-real-buffer-limit
(stream:with-stream-input-buffer (buffer index limit) stream
(setf limit chunk-real-buffer-limit)))
(%parse-chunk-header stream
#'(lambda (stream)
(declare (ignore stream))
(call-next-method))
(not (eql chunk-length-received 0))))
(call-next-method)))
(%set-buffer-chunk-limit stream)
t)
(call-next-method))))
(defun %set-buffer-chunk-limit (stream)
(declare (type chunk-transfer-decoding-input-stream stream))
(with-slots (chunk-remaining-bytes chunk-real-buffer-limit) stream
(stream:with-stream-input-buffer (buffer index limit) stream
(let ((chunk-end-index (+ index chunk-remaining-bytes)))
(if (< chunk-end-index limit)
(setf chunk-real-buffer-limit limit
limit chunk-end-index
chunk-remaining-bytes 0)
(setf chunk-real-buffer-limit nil
chunk-remaining-bytes (- chunk-remaining-bytes (- limit index))))
(when *debug-client-chunking*
(format t "~&;; Client chunk section ~D~%" (- limit index)))))))
(defun %parse-chunk-header-size (stream buffer-fill-function skip-first-crlf)
(declare (type chunk-transfer-decoding-input-stream stream))
(macrolet ((want-char (want)
`(unless (char= ch ,want)
(error "Chunk decoding error: wanted ~S, got ~S in ~S ~S ~S"
,want ch want-cr want-lf parsing-size)))
(adjust-size (baseline)
`(setq size (+ (ash size 4)
(- (char-code ch) ,baseline)))))
(let ((size 0)
(want-char (and skip-first-crlf #\Return)))
(block found-size
(loop (block refill-buffer
(stream:with-stream-input-buffer (buffer index limit) stream
(loop (when (>= index limit)
(return-from refill-buffer))
(let ((ch (schar buffer index)))
(declare (character ch))
(incf index)
(cond ((eql ch want-char)
(cond ((char= ch #\Return)
(setq want-char #\Newline))
must have been # \Newline
(if skip-first-crlf
(setq skip-first-crlf nil
want-char nil)
(return-from found-size)))))
(want-char
(error "Chunk decoding error: wanted ~S, got ~S"
want-char ch))
(t
(cond ((char<= #\0 ch #\9)
(adjust-size (char-code #\0)))
((char<= #\A ch #\Z)
(adjust-size (- (char-code #\A) 10)))
((char<= #\a ch #\z)
(adjust-size (- (char-code #\a) 10)))
((char= ch #\Return)
(setq want-char #\Newline))
((char= ch #\Space)
)
(t (error "Chunk decoding error: wanted size, got ~S"
ch)))))))))
(unless (funcall buffer-fill-function stream)
(return-from %parse-chunk-header-size nil))))
size)))
(defun %parse-chunk-header-size (stream buffer-fill-function skip-first-crlf)
(declare (type chunk-transfer-decoding-input-stream stream))
(let ((size 0))
(block found-size
(loop (block refill-buffer
(stream:with-stream-input-buffer (buffer index limit) stream
(loop (when (>= index limit)
(return-from refill-buffer))
(let ((ch (schar buffer index)))
(declare (character ch))
(incf index)
(cond ((char<= #\0 ch #\9)
(setq size (+ (ash size 4)
(- (char-code ch) (char-code #\0)))))
((char<= #\A ch #\Z)
(setq size (+ (ash size 4)
(- (char-code ch) (- (char-code #\A) 10)))))
((char<= #\a ch #\z)
(setq size (+ (ash size 4)
(- (char-code ch) (- (char-code #\a) 10)))))
((char= ch #\Return)
)
((char= ch #\Newline)
(if skip-first-crlf
(setq skip-first-crlf nil)
(return-from found-size)))
((char= ch #\Space)
)
(t
(error "Chunk decoding error got ~S"
ch)))))))
(unless (funcall buffer-fill-function stream)
(return-from %parse-chunk-header-size nil))))
size))
(defun %parse-chunk-header (stream buffer-fill-function skip-first-crlf)
(declare (type chunk-transfer-decoding-input-stream stream))
(let ((size (%parse-chunk-header-size stream buffer-fill-function skip-first-crlf)))
(when size
(when *debug-client-chunking*
(format t "~&;; New client chunk ~D~%" size))
(stream:with-stream-input-buffer (buffer index limit) stream
(with-slots (chunk-remaining-bytes chunk-real-buffer-limit) stream
(setf chunk-real-buffer-limit limit
limit index
chunk-remaining-bytes :eof)
(signal 'www-utils:end-of-chunk-transfer-decoding :stream stream)))
(with-slots (chunk-length-received chunk-remaining-bytes) stream
(setf chunk-remaining-bytes size)
(incf chunk-length-received size)))
t)))
|
5cab4f4975d6c3fdd35fe1fb9e42522ed1731ee4e14bfda9e83b36583e410144 | tpapp/cl-random | continuous-time.lisp | -*- Mode : Lisp ; Syntax : ANSI - Common - Lisp ; Coding : utf-8 -*-
(in-package #:cl-random)
(define-rv r-uniformized-markov-jump (rates &key transition-rate keys no-change)
(:documentation "Define a random variable for uniformized markov jumps,
which returns two values: the time spent in the state, and the index of the
next state (or the corresponding element in KEYS, which is a vector of the
same length). TRANSITION-RATES defaults to the sum of keys, however, it can
be specified to be larger, in which case the markov chain may remain in the
same state and return NO-CHANGE as the second value. Defines features
DURATION and JUMP, which return the two underlying random variables.")
((duration :reader duration)
(jump :reader jump)
no-change
(n :type fixnum :documentation "Number of states.")
(keys :type (or null vector)))
(let+ ((rates (as-float-vector rates))
(keys (when keys (coerce keys 'vector)))
(n (length rates))
(total-rate (clnu:sum rates))
((&values transition-rate probabilities)
(if transition-rate
(let ((no-change-rate (- transition-rate total-rate)))
(assert (<= 0 no-change-rate) ()
"Transition rate has to be >= the sum of rates.")
(values
transition-rate
(concatenate 'float-vector rates (vector no-change-rate))))
(values
total-rate
rates))))
;; (assert (every #'plusp rates) () "Rates need to be positive.")
(make :duration (r-exponential transition-rate)
:jump (r-discrete probabilities)
:no-change no-change
:keys keys
:n n))
(draw (&key)
(values (draw duration)
(let ((j (draw jump)))
(cond
((= j n) no-change)
(keys (aref keys j))
(t j))))))
| null | https://raw.githubusercontent.com/tpapp/cl-random/5bb65911037f95a4260bd29a594a09df3849f4ea/src/continuous-time.lisp | lisp | Syntax : ANSI - Common - Lisp ; Coding : utf-8 -*-
(assert (every #'plusp rates) () "Rates need to be positive.") |
(in-package #:cl-random)
(define-rv r-uniformized-markov-jump (rates &key transition-rate keys no-change)
(:documentation "Define a random variable for uniformized markov jumps,
which returns two values: the time spent in the state, and the index of the
next state (or the corresponding element in KEYS, which is a vector of the
same length). TRANSITION-RATES defaults to the sum of keys, however, it can
be specified to be larger, in which case the markov chain may remain in the
same state and return NO-CHANGE as the second value. Defines features
DURATION and JUMP, which return the two underlying random variables.")
((duration :reader duration)
(jump :reader jump)
no-change
(n :type fixnum :documentation "Number of states.")
(keys :type (or null vector)))
(let+ ((rates (as-float-vector rates))
(keys (when keys (coerce keys 'vector)))
(n (length rates))
(total-rate (clnu:sum rates))
((&values transition-rate probabilities)
(if transition-rate
(let ((no-change-rate (- transition-rate total-rate)))
(assert (<= 0 no-change-rate) ()
"Transition rate has to be >= the sum of rates.")
(values
transition-rate
(concatenate 'float-vector rates (vector no-change-rate))))
(values
total-rate
rates))))
(make :duration (r-exponential transition-rate)
:jump (r-discrete probabilities)
:no-change no-change
:keys keys
:n n))
(draw (&key)
(values (draw duration)
(let ((j (draw jump)))
(cond
((= j n) no-change)
(keys (aref keys j))
(t j))))))
|
1af35fa348e4736c30e7c9f6c58c3f241693af28b42a4522ab3691bb18195252 | heraldry/heraldicon | highlight.cljs | (ns heraldicon.frontend.highlight)
(def ^:private pattern-id
"selected-pattern")
(def fill-url
(str "url(#" pattern-id ")"))
(defn defs [& {:keys [scale]
:or {scale 1}}]
[:defs
(let [size (* 2 scale)
r (* 0.25 scale)]
[:pattern {:id pattern-id
:width size
:height size
:pattern-units "userSpaceOnUse"}
[:g.area-highlighted
[:circle {:cx 0
:cy 0
:r r}]
[:circle {:cx size
:cy 0
:r r}]
[:circle {:cx 0
:cy size
:r r}]
[:circle {:cx size
:cy size
:r r}]
[:circle {:cx (/ size 2)
:cy (/ size 2)
:r r}]]])])
| null | https://raw.githubusercontent.com/heraldry/heraldicon/c1d5afdc61919f9eccd2c274cb46274467d39768/src/heraldicon/frontend/highlight.cljs | clojure | (ns heraldicon.frontend.highlight)
(def ^:private pattern-id
"selected-pattern")
(def fill-url
(str "url(#" pattern-id ")"))
(defn defs [& {:keys [scale]
:or {scale 1}}]
[:defs
(let [size (* 2 scale)
r (* 0.25 scale)]
[:pattern {:id pattern-id
:width size
:height size
:pattern-units "userSpaceOnUse"}
[:g.area-highlighted
[:circle {:cx 0
:cy 0
:r r}]
[:circle {:cx size
:cy 0
:r r}]
[:circle {:cx 0
:cy size
:r r}]
[:circle {:cx size
:cy size
:r r}]
[:circle {:cx (/ size 2)
:cy (/ size 2)
:r r}]]])])
| |
3b58f5fdefd2af77b3b76e2249a0dd45aff36a382f02050fdfbc9ea254bcc41a | erlang/otp | systools_make.erl | %%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2022 . All Rights Reserved .
%%
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
%%
%% -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.
%%
%% %CopyrightEnd%
%%
-module(systools_make).
Purpose : Create start script . RelName.rel -- > RelName.{script , boot } .
%% and create a tar file of a release (RelName.tar.gz)
-export([make_script/1, make_script/2, make_script/3,
make_tar/1, make_tar/2]).
-export([format_error/1, format_warning/1]).
-export([read_release/2, get_release/2, get_release/3, pack_app/1]).
-export([read_application/4]).
-export([make_hybrid_boot/4]).
-export([preloaded/0]). % Exported just for testing
-import(lists, [filter/2, keysort/2, keysearch/3, map/2, reverse/1,
append/1, foldl/3, member/2, foreach/2]).
-include("systools.hrl").
-include_lib("kernel/include/file.hrl").
-define(XREF_SERVER, systools_make).
-compile({inline,[{badarg,2}]}).
-define(ESOCK_MODS, [prim_net,prim_socket,socket_registry]).
%%-----------------------------------------------------------------
%% Create a boot script from a release file.
%% Options is a list of {path, Path} | silent | local
| warnings_as_errors
%% where path sets the search path, silent suppresses error message
%% printing on console, local generates a script with references
%% to the directories there the applications are found,
and warnings_as_errors treats warnings as errors .
%%
%% New options: {path,Path} can contain wildcards
%% src_tests
{ variables,[{Name , } ] }
%% exref | {exref, [AppName]}
%% no_warn_sasl
%%-----------------------------------------------------------------
make_script(RelName) when is_list(RelName) ->
make_script(RelName, []);
make_script(RelName) ->
badarg(RelName,[RelName]).
make_script(RelName, Flags) when is_list(RelName), is_list(Flags) ->
ScriptName = get_script_name(RelName, Flags),
case get_outdir(Flags) of
"" ->
make_script(RelName, ScriptName, Flags);
OutDir ->
%% To maintain backwards compatibility for make_script/3,
%% the boot script file name is constructed here, before
%% checking the validity of OutDir
( is done in check_args_script/1 )
Output = filename:join(OutDir, filename:basename(ScriptName)),
make_script(RelName, Output, Flags)
end.
make_script(RelName, Output, Flags) when is_list(RelName),
is_list(Output),
is_list(Flags) ->
case check_args_script(Flags) of
[] ->
Path0 = get_path(Flags),
Path1 = mk_path(Path0), % expand wildcards etc.
Path = make_set(Path1 ++ code:get_path()),
ModTestP = {member(src_tests, Flags),xref_p(Flags)},
case get_release(RelName, Path, ModTestP) of
{ok, Release, Appls, Warnings0} ->
Warnings = wsasl(Flags, Warnings0),
case systools_lib:werror(Flags, Warnings) of
true ->
Warnings1 = [W || {warning,W}<-Warnings],
return({error,?MODULE,
{warnings_treated_as_errors,Warnings1}},
Warnings,
Flags);
false ->
case generate_script(Output,Release,Appls,Flags) of
ok ->
return(ok,Warnings,Flags);
Error ->
return(Error,Warnings,Flags)
end
end;
Error ->
return(Error,[],Flags)
end;
ErrorVars ->
badarg(ErrorVars, [RelName, Flags])
end;
make_script(RelName, _Output, Flags) when is_list(Flags) ->
badarg(RelName,[RelName, Flags]);
make_script(RelName, _Output, Flags) ->
badarg(Flags,[RelName, Flags]).
wsasl(Options, Warnings) ->
case lists:member(no_warn_sasl,Options) of
true -> lists:delete({warning,missing_sasl},Warnings);
false -> Warnings
end.
badarg(BadArg, Args) ->
erlang:error({badarg,BadArg}, Args).
get_script_name(RelName, Flags) ->
case get_flag(script_name,Flags) of
{script_name,ScriptName} when is_list(ScriptName) -> ScriptName;
_ -> RelName
end.
get_path(Flags) ->
case get_flag(path,Flags) of
{path,Path} when is_list(Path) -> Path;
_ -> []
end.
get_outdir(Flags) ->
case get_flag(outdir,Flags) of
{outdir,OutDir} when is_list(OutDir) ->
OutDir;
_ -> % false | {outdir, Badarg}
""
end.
return(ok,Warnings,Flags) ->
case member(silent,Flags) of
true ->
{ok,?MODULE,Warnings};
_ ->
io:format("~ts",[format_warning(Warnings)]),
ok
end;
return({error,Mod,Error},_,Flags) ->
case member(silent,Flags) of
true ->
{error,Mod,Error};
_ ->
io:format("~ts",[Mod:format_error(Error)]),
error
end.
%%-----------------------------------------------------------------
%% Make hybrid boot file for upgrading emulator. The resulting boot
file is a combination of the two input files , where kernel , stdlib
and sasl versions are taken from the second file ( the boot file of
the new release ) , and all other application versions from the first
%% file (the boot file of the old release).
%%
%% The most important thing that can fail here is that the input boot
files do not contain all three base applications - kernel , stdlib
%% and sasl.
%%
TmpVsn = string ( ) ,
%% Returns {ok,Boot} | {error,Reason}
Boot1 = Boot2 = Boot = binary ( )
%% Reason = {app_not_found,App} | {app_not_replaced,App}
App = stdlib | sasl
make_hybrid_boot(TmpVsn, Boot1, Boot2, Args) ->
catch do_make_hybrid_boot(TmpVsn, Boot1, Boot2, Args).
do_make_hybrid_boot(TmpVsn, OldBoot, NewBoot, Args) ->
{script,{_RelName1,_RelVsn1},OldScript} = binary_to_term(OldBoot),
{script,{NewRelName,_RelVsn2},NewScript} = binary_to_term(NewBoot),
%% Everything up to kernel_load_completed must come from the new script
Fun1 = fun({progress,kernel_load_completed}) -> false;
(_) -> true
end,
{_OldKernelLoad,OldRest1} = lists:splitwith(Fun1,OldScript),
{NewKernelLoad,NewRest1} = lists:splitwith(Fun1,NewScript),
Fun2 = fun({progress,modules_loaded}) -> false;
(_) -> true
end,
{OldModLoad,OldRest2} = lists:splitwith(Fun2,OldRest1),
{NewModLoad,NewRest2} = lists:splitwith(Fun2,NewRest1),
Fun3 = fun({kernelProcess,_,_}) -> false;
(_) -> true
end,
{OldPaths,OldRest3} = lists:splitwith(Fun3,OldRest2),
{NewPaths,NewRest3} = lists:splitwith(Fun3,NewRest2),
Fun4 = fun({progress,init_kernel_started}) -> false;
(_) -> true
end,
{_OldKernelProcs,OldApps} = lists:splitwith(Fun4,OldRest3),
{NewKernelProcs,NewApps} = lists:splitwith(Fun4,NewRest3),
%% Then comes all module load, which for each app consist of:
%% {path,[AppPath]},
{ primLoad , ModuleList }
%% Replace kernel, stdlib and sasl here
MatchPaths = get_regexp_path(),
ModLoad = replace_module_load(OldModLoad,NewModLoad,MatchPaths),
Paths = replace_paths(OldPaths,NewPaths,MatchPaths),
{Stdlib,Sasl} = get_apps(NewApps,undefined,undefined),
Apps0 = replace_apps(OldApps,Stdlib,Sasl),
Apps = add_apply_upgrade(Apps0,Args),
Script = NewKernelLoad++ModLoad++Paths++NewKernelProcs++Apps,
Boot = term_to_binary({script,{NewRelName,TmpVsn},Script}),
{ok,Boot}.
%% For each app, compile a regexp that can be used for finding its path
get_regexp_path() ->
{ok,KernelMP} = re:compile("kernel-[0-9\.]+",[unicode]),
{ok,StdlibMP} = re:compile("stdlib-[0-9\.]+",[unicode]),
{ok,SaslMP} = re:compile("sasl-[0-9\.]+",[unicode]),
[KernelMP,StdlibMP,SaslMP].
replace_module_load(Old,New,[MP|MatchPaths]) ->
replace_module_load(do_replace_module_load(Old,New,MP),New,MatchPaths);
replace_module_load(Script,_,[]) ->
Script.
do_replace_module_load([{path,[OldAppPath]},{primLoad,OldMods}|OldRest],New,MP) ->
case re:run(OldAppPath,MP,[{capture,none}]) of
nomatch ->
[{path,[OldAppPath]},{primLoad,OldMods}|
do_replace_module_load(OldRest,New,MP)];
match ->
get_module_load(New,MP) ++ OldRest
end;
do_replace_module_load([Other|Rest],New,MP) ->
[Other|do_replace_module_load(Rest,New,MP)];
do_replace_module_load([],_,_) ->
[].
get_module_load([{path,[AppPath]},{primLoad,Mods}|Rest],MP) ->
case re:run(AppPath,MP,[{capture,none}]) of
nomatch ->
get_module_load(Rest,MP);
match ->
[{path,[AppPath]},{primLoad,Mods}]
end;
get_module_load([_|Rest],MP) ->
get_module_load(Rest,MP);
get_module_load([],_) ->
[].
replace_paths([{path,OldPaths}|Old],New,MatchPaths) ->
{path,NewPath} = lists:keyfind(path,1,New),
[{path,do_replace_paths(OldPaths,NewPath,MatchPaths)}|Old];
replace_paths([Other|Old],New,MatchPaths) ->
[Other|replace_paths(Old,New,MatchPaths)].
do_replace_paths(Old,New,[MP|MatchPaths]) ->
do_replace_paths(do_replace_paths1(Old,New,MP),New,MatchPaths);
do_replace_paths(Paths,_,[]) ->
Paths.
do_replace_paths1([P|Ps],New,MP) ->
case re:run(P,MP,[{capture,none}]) of
nomatch ->
[P|do_replace_paths1(Ps,New,MP)];
match ->
get_path(New,MP) ++ Ps
end;
do_replace_paths1([],_,_) ->
[].
get_path([P|Ps],MP) ->
case re:run(P,MP,[{capture,none}]) of
nomatch ->
get_path(Ps,MP);
match ->
[P]
end;
get_path([],_) ->
[].
%% Return the entries for loading stdlib and sasl
get_apps([{apply,{application,load,[{application,stdlib,_}]}}=Stdlib|Script],
_,Sasl) ->
get_apps(Script,Stdlib,Sasl);
get_apps([{apply,{application,load,[{application,sasl,_}]}}=Sasl|_Script],
Stdlib,_) ->
{Stdlib,Sasl};
get_apps([_|Script],Stdlib,Sasl) ->
get_apps(Script,Stdlib,Sasl);
get_apps([],undefined,_) ->
throw({error,{app_not_found,stdlib}});
get_apps([],_,undefined) ->
throw({error,{app_not_found,sasl}}).
%% Replace the entries for loading the stdlib and sasl
replace_apps([{apply,{application,load,[{application,stdlib,_}]}}|Script],
Stdlib,Sasl) ->
[Stdlib|replace_apps(Script,undefined,Sasl)];
replace_apps([{apply,{application,load,[{application,sasl,_}]}}|Script],
_Stdlib,Sasl) ->
[Sasl|Script];
replace_apps([Stuff|Script],Stdlib,Sasl) ->
[Stuff|replace_apps(Script,Stdlib,Sasl)];
replace_apps([],undefined,_) ->
throw({error,{app_not_replaced,sasl}});
replace_apps([],_,_) ->
throw({error,{app_not_replaced,stdlib}}).
%% Finally add an apply of release_handler:new_emulator_upgrade - which will
complete the execution of the upgrade script ( relup ) .
add_apply_upgrade(Script,Args) ->
[{progress, started} | RevScript] = lists:reverse(Script),
lists:reverse([{progress,started},
{apply,{release_handler,new_emulator_upgrade,Args}} |
RevScript]).
%%-----------------------------------------------------------------
%% Create a release package from a release file.
%% Options is a list of {path, Path} | silent |
, [ src , include , examples , .. ] } | { erts , ErtsDir } where path
%% sets the search path, silent suppresses error message printing,
%% dirs includes the specified directories (per application) in the
%% release package and erts specifies that the erts-Vsn/bin directory
%% should be included in the release package and there it can be found.
%%
%% New options: {path,Path} can contain wildcards
%% src_tests
%% exref | {exref, [AppName]}
{ variables,[{Name , } ] }
{ var_tar , include | ownfile | omit }
%% no_warn_sasl
warnings_as_errors
%%
%% The tar file contains:
%% lib/App-Vsn/ebin
%% /priv
%% [/src]
%% [/include]
%% [/doc]
%% [/examples]
%% [/...]
Variable1.tar.gz
%% ...
VariableN.tar.gz
%% releases/RelName.rel
%% RelVsn/start.boot
relup
%% sys.config
%% sys.config.src
%% erts-EVsn[/bin]
%%-----------------------------------------------------------------
make_tar(RelName) when is_list(RelName) ->
make_tar(RelName, []);
make_tar(RelName) ->
badarg(RelName,[RelName]).
make_tar(RelName, Flags) when is_list(RelName), is_list(Flags) ->
case check_args_tar(Flags) of
[] ->
Path0 = get_path(Flags),
Path1 = mk_path(Path0),
Path = make_set(Path1 ++ code:get_path()),
ModTestP = {member(src_tests, Flags),xref_p(Flags)},
case get_release(RelName, Path, ModTestP) of
{ok, Release, Appls, Warnings0} ->
Warnings = wsasl(Flags, Warnings0),
case systools_lib:werror(Flags, Warnings) of
true ->
Warnings1 = [W || {warning,W}<-Warnings],
return({error,?MODULE,
{warnings_treated_as_errors,Warnings1}},
Warnings,
Flags);
false ->
case catch mk_tar(RelName, Release, Appls, Flags, Path1) of
ok ->
return(ok,Warnings,Flags);
Error ->
return(Error,Warnings,Flags)
end
end;
Error ->
return(Error,[],Flags)
end;
ErrorVars ->
badarg(ErrorVars, [RelName, Flags])
end;
make_tar(RelName, Flags) when is_list(Flags) ->
badarg(RelName,[RelName, Flags]);
make_tar(RelName, Flags) ->
badarg(Flags,[RelName, Flags]).
%%______________________________________________________________________
%% get_release(File, Path) ->
get_release(File , Path , ) - >
%% {ok, #release, [{{Name,Vsn},#application}], Warnings} | {error, What}
get_release(File, Path) ->
get_release(File, Path, {false,false}).
get_release(File, Path, ModTestP) ->
case catch get_release1(File, Path, ModTestP) of
{error, Error} ->
{error, ?MODULE, Error};
{'EXIT', Why} ->
{error, ?MODULE, {'EXIT',Why}};
Answer ->
Answer
end.
get_release1(File, Path, ModTestP) ->
{ok, Release, Warnings1} = read_release(File, Path),
{ok, Appls0} = collect_applications(Release, Path),
{ok, Appls1} = check_applications(Appls0),
OTP-4121 , OTP-9984
{ok, Warnings2} = check_modules(Appls2, Path, ModTestP),
{ok, Appls} = sort_appls(Appls2),
{ok, Release, Appls, Warnings1 ++ Warnings2}.
%%______________________________________________________________________
%% read_release(File, Path) -> {ok, #release} | throw({error, What})
read_release(File, Path) ->
case read_file(File ++ ".rel", ["."|Path]) of
{ok, Release, _FullName} ->
check_rel(Release);
{error,Error} ->
throw({error,?MODULE,Error})
end.
check_rel(Release) ->
case catch check_rel1(Release) of
{ok, {Name,Vsn,Evsn,Appl,Incl}, Ws} ->
{ok, #release{name=Name, vsn=Vsn,
erts_vsn=Evsn,
applications=Appl,
incl_apps=Incl},
Ws};
{error, Error} ->
throw({error,?MODULE,Error});
Error ->
throw({error,?MODULE,Error})
end.
check_rel1({release,{Name,Vsn},{erts,EVsn},Appl}) when is_list(Appl) ->
Name = check_name(Name),
Vsn = check_vsn(Vsn),
EVsn = check_evsn(EVsn),
{{Appls,Incls},Ws} = check_appl(Appl),
{ok, {Name,Vsn,EVsn,Appls,Incls},Ws};
check_rel1(_) ->
{error, badly_formatted_release}.
check_name(Name) ->
case string_p(Name) of
true ->
Name;
_ ->
throw({error,{illegal_name, Name}})
end.
check_vsn(Vsn) ->
case string_p(Vsn) of
true ->
Vsn;
_ ->
throw({error,{illegal_form, Vsn}})
end.
check_evsn(Vsn) ->
case string_p(Vsn) of
true ->
Vsn;
_ ->
throw({error,{illegal_form, {erts,Vsn}}})
end.
check_appl(Appl) ->
case filter(fun({App,Vsn}) when is_atom(App) ->
not string_p(Vsn);
({App,Vsn,Incl}) when is_atom(App), is_list(Incl) ->
case {string_p(Vsn), a_list_p(Incl)} of
{true, true} -> false;
_ -> true
end;
({App,Vsn,Type}) when is_atom(App), is_atom(Type) ->
case {string_p(Vsn), is_app_type(Type)} of
{true, true} -> false;
_ -> true
end;
({App,Vsn,Type,Incl}) when is_atom(App),
is_atom(Type),
is_list(Incl) ->
case {string_p(Vsn),is_app_type(Type),a_list_p(Incl)} of
{true, true, true} -> false;
_ -> true
end;
(_) ->
true
end,
Appl) of
[] ->
{ApplsNoIncls,Incls} = split_app_incl(Appl),
{ok,Ws} = mandatory_applications(ApplsNoIncls,undefined,
undefined,undefined),
{{ApplsNoIncls,Incls},Ws};
Illegal ->
throw({error, {illegal_applications,Illegal}})
end.
mandatory_applications([{kernel,_,Type}|Apps],undefined,Stdlib,Sasl) ->
mandatory_applications(Apps,Type,Stdlib,Sasl);
mandatory_applications([{stdlib,_,Type}|Apps],Kernel,undefined,Sasl) ->
mandatory_applications(Apps,Kernel,Type,Sasl);
mandatory_applications([{sasl,_,Type}|Apps],Kernel,Stdlib,undefined) ->
mandatory_applications(Apps,Kernel,Stdlib,Type);
mandatory_applications([_|Apps],Kernel,Stdlib,Sasl) ->
mandatory_applications(Apps,Kernel,Stdlib,Sasl);
mandatory_applications([],Type,_,_) when Type=/=permanent ->
error_mandatory_application(kernel,Type);
mandatory_applications([],_,Type,_) when Type=/=permanent ->
error_mandatory_application(stdlib,Type);
mandatory_applications([],_,_,undefined) ->
{ok, [{warning,missing_sasl}]};
mandatory_applications([],_,_,_) ->
{ok,[]}.
error_mandatory_application(App,undefined) ->
throw({error, {missing_mandatory_app, App}});
error_mandatory_application(App,Type) ->
throw({error, {mandatory_app, App, Type}}).
split_app_incl(Appl) -> split_app_incl(Appl, [], []).
split_app_incl([{App,Vsn}|Appls], Apps, Incls) ->
split_app_incl(Appls, [{App,Vsn,permanent}|Apps], Incls);
split_app_incl([{App,Vsn,Incl}|Appls], Apps,Incls) when is_list(Incl) ->
split_app_incl(Appls, [{App,Vsn,permanent}|Apps], [{App,Incl}|Incls]);
split_app_incl([{App,Vsn,Type}|Appls], Apps, Incls) ->
split_app_incl(Appls, [{App,Vsn,Type}|Apps], Incls);
split_app_incl([{App,Vsn,Type,Incl}|Appls], Apps, Incls) when is_list(Incl) ->
split_app_incl(Appls, [{App,Vsn,Type}|Apps], [{App,Incl}|Incls]);
split_app_incl([], Apps, Incls) ->
{reverse(Apps),reverse(Incls)}.
%%______________________________________________________________________
%% collect_applications(#release, Path) ->
%% {ok,[{{Name,Vsn},#application}]} |
%% throw({error, What})
%% Read all the application files specified in the release descriptor
collect_applications(Release, Path) ->
Appls = Release#release.applications,
Incls = Release#release.incl_apps,
X = foldl(fun({Name,Vsn,Type}, {Ok, Errs}) ->
case read_application(to_list(Name), Vsn, Path, Incls) of
{ok, A} ->
case {A#application.name,A#application.vsn} of
{Name,Vsn} ->
{[{{Name,Vsn}, A#application{type=Type}} | Ok],
Errs};
E ->
{Ok, [{bad_application_name, {Name, E}} | Errs]}
end;
{error, What} ->
{Ok, [{error_reading, {Name, What}} | Errs]}
end
end, {[],[]}, Appls),
case X of
{A, []} ->
{ok, reverse(A)};
{_, Errs} ->
throw({error, Errs})
end.
%%______________________________________________________________________
read_application(Name , Vsn , Path , Incls ) - > { ok , # release } | { error , What }
read_application(Name, Vsn, Path, Incls) ->
read_application(Name, Vsn, Path, Incls, false, no_fault).
read_application(Name, Vsn, [Dir|Path], Incls, Found, FirstError) ->
case read_file(Name ++ ".app", [Dir]) of
{ok, Term, FullName} ->
case parse_application(Term, FullName, Vsn, Incls) of
{error, {no_valid_version, {Vsn, OtherVsn}}} when FirstError == no_fault ->
NFE = {no_valid_version, {{"should be", Vsn},
{"found file", filename:join(Dir, Name++".app"),
OtherVsn}}},
read_application(Name, Vsn, Path, Incls, true, NFE);
{error, {no_valid_version, {Vsn, _OtherVsn}}} ->
read_application(Name, Vsn, Path, Incls, true, FirstError);
Res ->
Res
end;
{error, {parse, _File, {Line, _Mod, Err}}} when FirstError == no_fault ->
read_application(Name, Vsn, Path, Incls, Found,
{parse_error, {filename:join(Dir, Name++".app"), Line, Err}});
{error, {parse, _File, _Err}} ->
read_application(Name, Vsn, Path, Incls, Found, FirstError);
{error, _Err} -> %% Not found
read_application(Name, Vsn, Path, Incls, Found, FirstError)
end;
read_application(Name, Vsn, [], _, true, no_fault) ->
{error, {application_vsn, {Name,Vsn}}};
read_application(_Name, _Vsn, [], _, true, FirstError) ->
{error, FirstError};
read_application(Name, _, [], _, _, no_fault) ->
{error, {not_found, Name ++ ".app"}};
read_application(_Name, _, [], _, _, FirstError) ->
{error, FirstError}.
parse_application({application, Name, Dict}, File, Vsn, Incls)
when is_atom(Name),
is_list(Dict) ->
Items = [vsn,id,description,modules,registered,applications,
optional_applications,included_applications,mod,start_phases,env,maxT,maxP],
case catch get_items(Items, Dict) of
[Vsn,Id,Desc,Mods,Regs,Apps,Opts,Incs0,Mod,Phases,Env,MaxT,MaxP] ->
case override_include(Name, Incs0, Incls) of
{ok, Incs} ->
{ok, #application{name=Name,
vsn=Vsn,
id=Id,
description=Desc,
modules=Mods,
uses=Apps,
optional=Opts,
includes=Incs,
regs=Regs,
mod=Mod,
start_phases=Phases,
env=Env,
maxT=MaxT,
maxP=MaxP,
dir=filename:dirname(File)}};
{error, IncApps} ->
{error, {override_include, IncApps}}
end;
[OtherVsn,_,_,_,_,_,_,_,_,_,_,_,_] ->
{error, {no_valid_version, {Vsn, OtherVsn}}};
Err ->
{error, {Err, {application, Name, Dict}}}
end;
parse_application(Other, _, _, _) ->
{error, {badly_formatted_application, Other}}.
%% Test if all included applications specified in the .rel file
%% exists in the {included_applications,Incs} specified in the
%% .app file.
override_include(Name, Incs, Incls) ->
case keysearch(Name, 1, Incls) of
{value, {Name, I}} ->
case specified(I, Incs) of
[] ->
{ok, I};
NotSpec ->
{error, NotSpec}
end;
_ ->
{ok, Incs}
end.
specified([App|Incls], Spec) ->
case member(App, Spec) of
true ->
specified(Incls, Spec);
_ ->
[App|specified(Incls, Spec)]
end;
specified([], _) ->
[].
get_items([H|T], Dict) ->
Item = case check_item(keysearch(H, 1, Dict),H) of
[Atom|_]=Atoms when is_atom(Atom), is_list(Atoms) ->
%% Check for duplicate entries in lists
case Atoms =/= lists:uniq(Atoms) of
true -> throw({dupl_entry, H, lists:subtract(Atoms, lists:uniq(Atoms))});
false -> Atoms
end;
X -> X
end,
[Item|get_items(T, Dict)];
get_items([], _Dict) ->
[].
check_item({_,{mod,{M,A}}},_) when is_atom(M) ->
{M,A};
check_item({_,{mod,[]}},_) -> % default mod is [], so accept as entry
[];
check_item({_,{vsn,Vsn}},I) ->
case string_p(Vsn) of
true -> Vsn;
_ -> throw({bad_param, I})
end;
check_item({_,{id,Id}},I) ->
case string_p(Id) of
true -> Id;
_ -> throw({bad_param, I})
end;
check_item({_,{description,Desc}},I) ->
case string_p(Desc) of
true -> Desc;
_ -> throw({bad_param, I})
end;
check_item({_,{applications,Apps}},I) ->
case a_list_p(Apps) of
true -> Apps;
_ -> throw({bad_param, I})
end;
check_item({_,{optional_applications,Apps}},I) ->
case a_list_p(Apps) of
true -> Apps;
_ -> throw({bad_param, I})
end;
check_item({_,{included_applications,Apps}},I) ->
case a_list_p(Apps) of
true -> Apps;
_ -> throw({bad_param, I})
end;
check_item({_,{registered,Regs}},I) ->
case a_list_p(Regs) of
true -> Regs;
_ -> throw({bad_param, I})
end;
check_item({_,{modules,Mods}},I) ->
case a_list_p(Mods) of
true -> Mods;
_ -> throw({bad_param, I})
end;
check_item({_,{start_phases,undefined}},_) -> % default start_phase is undefined,
undefined; % so accept as entry
check_item({_,{start_phases,Phase}},I) ->
case t_list_p(Phase) of
true -> Phase;
_ -> throw({bad_param, I})
end;
check_item({_,{env,Env}},I) ->
case t_list_p(Env) of
true -> Env;
_ -> throw({bad_param, I})
end;
check_item({_,{maxT,MaxT}},I) ->
case MaxT of
MaxT when is_integer(MaxT), MaxT > 0 -> MaxT;
infinity -> infinity;
_ -> throw({bad_param, I})
end;
check_item({_,{maxP,MaxP}},I) ->
case MaxP of
MaxP when is_integer(MaxP), MaxP > 0 -> MaxP;
infinity -> infinity;
_ -> throw({bad_param, I})
end;
check_item(false, optional_applications) -> % optional !
[];
check_item(false, included_applications) -> % optional !
[];
check_item(false, mod) -> % mod is optional !
[];
check_item(false, env) -> % env is optional !
[];
check_item(false, id) -> % id is optional !
[];
check_item(false, start_phases) -> % start_phases is optional !
undefined;
check_item(false, maxT) -> % maxT is optional !
infinity;
check_item(false, maxP) -> % maxP is optional !
infinity;
check_item(_, Item) ->
throw({missing_param, Item}).
%%______________________________________________________________________
%% check_applications([{{Name,Vsn},#application}]) ->
ok | throw({error , Error } )
%% check that all referenced applications exists and that no
%% application register processes with the same name.
%% Check that included_applications are not specified as used
%% in another application.
check_applications(Appls) ->
undef_appls(Appls),
dupl_regs(Appls),
Make a list Incs = [ { Name , App , AppVsn , Dir } ]
Incs = [{IncApp,App,Appv,A#application.dir} ||
{{App,Appv},A} <- Appls,
IncApp <- A#application.includes],
dupl_incls(Incs),
Res = add_top_apps_to_uses(Incs, Appls, []),
{ok, Res}.
undef_appls(Appls) ->
case undefined_applications(Appls) of
[] ->
ok;
L ->
throw({error, {undefined_applications, make_set(L)}})
end.
dupl_regs(Appls) ->
Make a list = [ { Name , App , AppVsn , Dir } ]
Regs = [{Name,App,Appv,A#application.dir} ||
{{App,Appv},A} <- Appls,
Name <- A#application.regs],
case duplicates(Regs) of
[] ->
ok;
Dups ->
throw({error, {duplicate_register, Dups}})
end.
dupl_incls(Incs) ->
case duplicates(Incs) of
[] ->
ok;
Dups ->
throw({error, {duplicate_include, Dups}})
end.
%% If an application uses another application which is included in yet
%% another application, e.g. X uses A, A is included in T; then the A
application in the X applications uses - variable is changed to the T
%% application's top application to ensure the start order.
%% Exception: if both X and A have the same top, then it is not
%% added to avoid circular dependencies.
%%
%% add_top_apps_to_uses( list of all included applications in
%% the system,
%% list of all applications in the system,
%% temporary result)
%% -> new list of all applications
add_top_apps_to_uses(_InclApps, [], Res) ->
InclApps = [ { IncApp , App , AppVsn , Dir } ]
Res;
add_top_apps_to_uses(InclApps, [{Name,Appl} | Appls], Res) ->
MyTop = find_top_app(Appl#application.name, InclApps),
F = fun(UsedApp, AccIn) when UsedApp == MyTop ->
%% UW980513 This is a special case: The included app
%% uses its own top app. We'll allow it, but must
%% remove the top app from the uses list.
AccIn -- [MyTop];
(UsedApp, AccIn) ->
case lists:keysearch(UsedApp, 1, InclApps) of
false ->
AccIn;
{value, {_,DependApp,_,_}} ->
UsedAppTop = find_top_app(DependApp, InclApps),
case {lists:member(UsedAppTop, AccIn), MyTop} of
{true, _} ->
%% the top app is already in the uses
list , remove UsedApp
AccIn -- [UsedApp];
{_, UsedAppTop} ->
%% both are included in the same app
AccIn;
_ ->
%% change the used app to the used app's
%% top application
AccIn1 = AccIn -- [UsedApp],
AccIn1 ++ [UsedAppTop]
end
end
end,
NewUses = foldl(F, Appl#application.uses, Appl#application.uses),
add_top_apps_to_uses(InclApps, Appls,
Res++[{Name, Appl#application{uses = NewUses}}]).
find_top_app(App, InclApps) ->
case lists:keysearch(App, 1, InclApps) of
false ->
App;
{value, {_,TopApp,_,_}} ->
find_top_app(TopApp, InclApps)
end.
%%______________________________________________________________________
%% undefined_applications([{{Name,Vsn},#application}]) ->
%% [Name] list of applications that were declared in
%% use declarations but are not contained in the release descriptor
undefined_applications(Appls) ->
Uses = append(map(fun({_,A}) ->
(A#application.uses -- A#application.optional) ++
A#application.includes
end, Appls)),
Defined = map(fun({{X,_},_}) -> X end, Appls),
filter(fun(X) -> not member(X, Defined) end, Uses).
%%______________________________________________________________________
%% sort_used_and_incl_appls(Applications, Release) -> Applications
%% Applications = [{{Name,Vsn},#application}]
%% Release = #release{}
%%
OTP-4121 , OTP-9984
%% Check that used and included applications are given in the same
%% order as in the release resource file (.rel). Otherwise load and
%% start instructions in the boot script, and consequently release
upgrade instructions in relup , may end up in the wrong order .
sort_used_and_incl_appls(Applications, Release) when is_tuple(Release) ->
{ok,
sort_used_and_incl_appls(Applications, Release#release.applications)};
sort_used_and_incl_appls([{Tuple,Appl}|Appls], OrderedAppls) ->
Incls2 =
case Appl#application.includes of
Incls when length(Incls)>1 ->
sort_appl_list(Incls, OrderedAppls);
Incls ->
Incls
end,
Uses2 =
case Appl#application.uses of
Uses when length(Uses)>1 ->
sort_appl_list(Uses, OrderedAppls);
Uses ->
Uses
end,
Appl2 = Appl#application{includes=Incls2, uses=Uses2},
[{Tuple,Appl2}|sort_used_and_incl_appls(Appls, OrderedAppls)];
sort_used_and_incl_appls([], _OrderedAppls) ->
[].
sort_appl_list(List, Order) ->
IndexedList = find_pos(List, Order),
SortedIndexedList = lists:keysort(1, IndexedList),
lists:map(fun({_Index,Name}) -> Name end, SortedIndexedList).
find_pos([Name|Incs], OrderedAppls) ->
[find_pos(1, Name, OrderedAppls)|find_pos(Incs, OrderedAppls)];
find_pos([], _OrderedAppls) ->
[].
find_pos(N, Name, [{Name,_Vsn,_Type}|_OrderedAppls]) ->
{N, Name};
find_pos(N, Name, [_OtherAppl|OrderedAppls]) ->
find_pos(N+1, Name, OrderedAppls);
find_pos(_N, Name, []) ->
{optional, Name}.
%%______________________________________________________________________
%% check_modules(Appls, Path, TestP) ->
%% {ok, Warnings} | throw({error, What})
where = [ { App , , # application } ]
%% performs logical checking that we can find all the modules
%% etc.
check_modules(Appls, Path, TestP) ->
first check that all the module names are unique
Make a list M1 = [ { Mod , App , Dir } ]
M1 = [{Mod,App,A#application.dir} ||
{{App,_Appv},A} <- Appls,
Mod <- A#application.modules],
case duplicates(M1) of
[] ->
case check_mods(M1, Appls, Path, TestP) of
{error, Errors} ->
throw({error, {modules, Errors}});
Return ->
Return
end;
Dups ->
% io:format("** ERROR Duplicate modules: ~p\n", [Dups]),
throw({error, {duplicate_modules, Dups}})
end.
%%______________________________________________________________________
%% Check that all modules exists.
%% Use the module extension of the running machine as extension for
%% the checked modules.
check_mods(Modules, Appls, Path, {SrcTestP, XrefP}) ->
SrcTestRes = check_src(Modules, Appls, Path, SrcTestP),
XrefRes = check_xref(Appls, Path, XrefP),
Res = SrcTestRes ++ XrefRes,
case filter(fun({error, _}) -> true;
(_) -> false
end,
Res) of
[] ->
{ok, filter(fun({warning, _}) -> true;
(_) -> false
end,
Res)};
Errors ->
{error, Errors}
end.
check_src(Modules, Appls, Path, true) ->
Ext = code:objfile_extension(),
IncPath = create_include_path(Appls, Path),
append(map(fun(ModT) ->
{Mod,App,Dir} = ModT,
case check_mod(Mod,App,Dir,Ext,IncPath) of
ok ->
[];
{error, Error} ->
[{error,{Error, ModT}}];
{warning, Warn} ->
[{warning,{Warn,ModT}}]
end
end,
Modules));
check_src(_, _, _, _) ->
[].
check_xref(_Appls, _Path, false) ->
[];
check_xref(Appls, Path, XrefP) ->
AppDirsL = [{App,A#application.dir} || {{App,_Appv},A} <- Appls],
AppDirs0 = sofs:relation(AppDirsL),
AppDirs = case XrefP of
true ->
AppDirs0;
{true, Apps} ->
sofs:restriction(AppDirs0, sofs:set(Apps))
end,
XrefArgs = [{xref_mode, modules}],
case catch xref:start(?XREF_SERVER, XrefArgs) of
{ok, _Pid} ->
ok;
{error, {already_started, _Pid}} ->
xref:stop(?XREF_SERVER), %% Clear out any previous data
{ok,_} = xref:start(?XREF_SERVER, XrefArgs),
ok
end,
{ok, _} = xref:set_default(?XREF_SERVER, verbose, false),
LibPath = case Path == code:get_path() of
true -> code_path; % often faster
false -> Path
end,
ok = xref:set_library_path(?XREF_SERVER, LibPath),
check_xref(sofs:to_external(AppDirs)).
check_xref([{App,AppDir} | Appls]) ->
case xref:add_application(?XREF_SERVER, AppDir, {name,App}) of
{ok, _App} ->
check_xref(Appls);
Error ->
xref:stop(?XREF_SERVER),
[{error, Error}]
end;
check_xref([]) ->
R = case xref:analyze(?XREF_SERVER, undefined_functions) of
{ok, []} ->
[];
{ok, Undefined} ->
[{warning, {exref_undef, Undefined}}];
Error ->
[{error, Error}]
end,
xref:stop(?XREF_SERVER),
R.
%% Perform cross reference checks between all modules specified
%% in .app files.
%%
xref_p(Flags) ->
case member(exref, Flags) of
true ->
exists_xref(true);
_ ->
case get_flag(exref, Flags) of
{exref, Appls} when is_list(Appls) ->
case a_list_p(Appls) of
true -> exists_xref({true, Appls});
_ -> false
end;
_ ->
false
end
end.
exists_xref(Flag) ->
case code:ensure_loaded(xref) of
{error, _} -> false;
_ -> Flag
end.
check_mod(Mod,App,Dir,Ext,IncPath) ->
ObjFile = mod_to_filename(Dir, Mod, Ext),
case file:read_file_info(ObjFile) of
{ok,FileInfo} ->
LastModTime = FileInfo#file_info.mtime,
check_module(Mod, Dir, LastModTime, IncPath);
_ ->
{error, {module_not_found, App, Mod}}
end.
mod_to_filename(Dir, Mod, Ext) ->
filename:join(Dir, atom_to_list(Mod) ++ Ext).
check_module(Mod, Dir, ObjModTime, IncPath) ->
{SrcDirs,_IncDirs}= smart_guess(Dir,IncPath),
case locate_src(Mod,SrcDirs) of
{ok,_FDir,_File,LastModTime} ->
if
LastModTime > ObjModTime ->
{warning, obj_out_of_date};
true ->
ok
end;
_ ->
{warning, source_not_found}
end.
locate_src(Mod,[Dir|Dirs]) ->
File = mod_to_filename(Dir, Mod, ".erl"),
case file:read_file_info(File) of
{ok,FileInfo} ->
LastModTime = FileInfo#file_info.mtime,
{ok,Dir,File,LastModTime};
_ ->
locate_src(Mod,Dirs)
end;
locate_src(_,[]) ->
false.
%%______________________________________________________________________
smart_guess(Mod , , IncludePath ) - > { [ Dirs],[IncDirs ] }
%% Guess the src code and include directory. If dir contains .../ebin
%% src-dir should be one of .../src or .../src/e_src
If dir does not contain ... /ebin set to the same directory .
smart_guess(Dir,IncPath) ->
case reverse(filename:split(Dir)) of
["ebin"|D] ->
D1 = reverse(D),
Dirs = [filename:join(D1 ++ ["src"]),
filename:join(D1 ++ ["src", "e_src"])],
RecurseDirs = add_subdirs(Dirs),
{RecurseDirs,RecurseDirs ++ IncPath};
_ ->
{[Dir],[Dir] ++ IncPath}
end.
%%______________________________________________________________________
] ) - > [ Dirs ]
%% Take the directories that were used for a guess, and search them
%% recursively. This is required for applications relying on varying
nested directories . One example within OTP is the ` wx ' application ,
%% which has auto-generated modules in `src/gen/' and then fail any
%% systools check.
add_subdirs([]) ->
[];
add_subdirs([Dir|Dirs]) ->
case filelib:is_dir(Dir) of
false ->
%% Keep the bad guess, but put it last in the search order
%% since we won't find anything there. Handling of errors
%% for unfound file is done in `locate_src/2'
add_subdirs(Dirs) ++ [Dir];
true ->
SubDirs = [File || File <- filelib:wildcard(filename:join(Dir, "**")),
filelib:is_dir(File)],
[Dir|SubDirs] ++ add_subdirs(Dirs)
end.
%%______________________________________________________________________
%% generate_script(#release,
%% [{{Name,Vsn},#application}], Flags) ->
%% ok | {error, Error}
%% Writes a script (a la magnus) to the file File.script
%% and a bootfile to File.boot.
generate_script(Output, Release, Appls, Flags) ->
PathFlag = path_flag(Flags),
Variables = get_variables(Flags),
Preloaded = preloaded(),
Mandatory = mandatory_modules(),
Script = {script, {Release#release.name,Release#release.vsn},
[{preLoaded, Preloaded},
{progress, preloaded},
{path, create_mandatory_path(Appls, PathFlag, Variables)},
{primLoad, Mandatory},
{kernel_load_completed},
{progress, kernel_load_completed}] ++
load_appl_mods(Appls, Mandatory ++ Preloaded,
PathFlag, Variables) ++
[{path, create_path(Appls, PathFlag, Variables)}] ++
create_kernel_procs(Appls) ++
create_load_appls(Appls) ++
create_start_appls(Appls) ++
script_end(lists:member(no_dot_erlang, Flags))
},
ScriptFile = Output ++ ".script",
case file:open(ScriptFile, [write,{encoding,utf8}]) of
{ok, Fd} ->
io:format(Fd, "%% ~s\n~tp.\n",
[epp:encoding_to_string(utf8), Script]),
case file:close(Fd) of
ok ->
BootFile = Output ++ ".boot",
case file:write_file(BootFile, term_to_binary(Script)) of
ok ->
ok;
{error, Reason} ->
{error, ?MODULE, {open,BootFile,Reason}}
end;
{error, Reason} ->
{error, ?MODULE, {close,ScriptFile,Reason}}
end;
{error, Reason} ->
{error, ?MODULE, {open,ScriptFile,Reason}}
end.
path_flag(Flags) ->
case {member(local,Flags), member(otp_build, Flags)} of
{true, _} -> local;
{_, true} -> otp_build;
{_, _} -> true
end.
get_variables(Flags) ->
case get_flag(variables, Flags) of
{variables, Variables} when is_list(Variables) ->
valid_variables(Variables);
_ ->
[]
end.
valid_variables([{Var,Path}|Variables]) when is_list(Var), is_list(Path) ->
[{Var,rm_tlsl(Path)}|valid_variables(Variables)];
valid_variables([{Var,Path}|Variables]) when is_atom(Var), is_list(Path) ->
[{to_list(Var),rm_tlsl(Path)}|valid_variables(Variables)];
valid_variables([_|Variables]) ->
valid_variables(Variables);
valid_variables(_) ->
[].
rm_tlsl(P) -> rm_tlsl1(reverse(P)).
rm_tlsl1([$/|P]) -> rm_tlsl1(P);
rm_tlsl1(P) -> reverse(P).
%%______________________________________________________________________
%% Start all applications.
%% Do not start applications that are included applications !
create_start_appls(Appls) ->
Included = append(map(fun({_,A}) ->
A#application.includes
end, Appls)),
create_start_appls(Appls, Included).
create_start_appls([{_,A}|T], Incl) ->
App = A#application.name,
case lists:member(App, Incl) of
false when A#application.type == none ->
create_start_appls(T, Incl);
false when A#application.type == load ->
create_start_appls(T, Incl);
false ->
[{apply, {application, start_boot, [App,A#application.type]}} |
create_start_appls(T, Incl)];
_ ->
create_start_appls(T, Incl)
end;
create_start_appls([], _) ->
[].
%%______________________________________________________________________
%% Load all applications.
create_load_appls([{{kernel,_},_}|T]) -> %Already added !!
create_load_appls(T);
create_load_appls([{_,A}|T]) when A#application.type == none ->
create_load_appls(T);
create_load_appls([{_,A}|T]) ->
[{apply, {application, load, [pack_app(A)]}} |
create_load_appls(T)];
create_load_appls([]) ->
[{progress, applications_loaded}].
%%______________________________________________________________________
%% The final part of the script.
script_end(false) -> %% Do not skip loading of $HOME/.erlang
[{apply, {c, erlangrc, []}},
{progress, started}];
script_end(true) -> %% Ignore loading of $HOME/.erlang
[{progress, started}].
%%-----------------------------------------------------------------
Function : sort_appls(Appls ) - > { ok , ' } | throw({error , Error } )
Types : Appls = { { Name , , # application } ]
%% Purpose: Sort applications according to dependencies among
%% applications. If order doesn't matter, use the same
%% order as in the original list.
Alg . written by ( )
Mod . by mbj
%%-----------------------------------------------------------------
sort_appls(Appls) -> {ok, sort_appls(Appls, [], [], [])}.
sort_appls([{N, A}|T], Missing, Circular, Visited) ->
{Name,_Vsn} = N,
{Uses, T1, NotFnd1} = find_all(Name, lists:reverse(A#application.uses),
T, Visited, [], []),
{Incs, T2, NotFnd2} = find_all(Name, lists:reverse(A#application.includes),
T1, Visited, [], []),
Missing1 = (NotFnd1 -- A#application.optional) ++ NotFnd2 ++ Missing,
case Uses ++ Incs of
[] ->
%% No more app that must be started before this one is
%% found; they are all already taken care of (and present
%% in Visited list)
[{N, A}|sort_appls(T, Missing1, Circular, [N|Visited])];
L ->
%% The apps in L must be started before the app.
Check if we have already taken care of some app in L ,
%% in that case we have a circular dependency.
NewCircular = [N1 || {N1, _} <- L, N2 <- Visited, N1 == N2],
Circular1 = case NewCircular of
[] -> Circular;
_ -> [N | NewCircular] ++ Circular
end,
%% L must be started before N, try again, with all apps
in L added before N.
Apps = del_apps(NewCircular, L ++ [{N, A}|T2]),
sort_appls(Apps, Missing1, Circular1, [N|Visited])
end;
sort_appls([], [], [], _) ->
[];
sort_appls([], Missing, [], _) ->
%% this has already been checked before, but as we have the info...
throw({error, {undefined_applications, make_set(Missing)}});
sort_appls([], [], Circular, _) ->
throw({error, {circular_dependencies, make_set(Circular)}});
sort_appls([], Missing, Circular, _) ->
throw({error, {apps, [{circular_dependencies, make_set(Circular)},
{undefined_applications, make_set(Missing)}]}}).
find_all(CheckingApp, [Name|T], L, Visited, Found, NotFound) ->
case find_app(Name, L) of
{value, App} ->
{_A,R} = App,
%% It is OK to have a dependency like
X includes Y , Y uses X.
case lists:member(CheckingApp, R#application.includes) of
true ->
case lists:keymember(Name, 1, Visited) of
true ->
find_all(CheckingApp, T, L, Visited, Found, NotFound);
false ->
find_all(CheckingApp, T, L, Visited, Found, [Name|NotFound])
end;
false ->
find_all(CheckingApp, T, L -- [App], Visited, [App|Found], NotFound)
end;
false ->
case lists:keymember(Name, 1, Visited) of
true ->
find_all(CheckingApp, T, L, Visited, Found, NotFound);
false ->
find_all(CheckingApp, T, L, Visited, Found, [Name|NotFound])
end
end;
find_all(_CheckingApp, [], L, _Visited, Found, NotFound) ->
{Found, L, NotFound}.
find_app(Name, [{{Name,Vsn}, Application}|_]) ->
{value, {{Name,Vsn},Application}};
find_app(Name, [_|T]) ->
find_app(Name, T);
find_app(_Name, []) ->
false.
del_apps([Name|T], L) ->
del_apps(T, lists:keydelete(Name, 1, L));
del_apps([], L) ->
L.
%%______________________________________________________________________
%% Create the load path used in the generated script.
If PathFlag is true a script intended to be used as a complete
%% system (e.g. in an embedded system), i.e. all applications are
%% located under $ROOT/lib.
%% Otherwise all paths are set according to dir per application.
%% Create the complete path.
create_path(Appls, PathFlag, Variables) ->
make_set(map(fun({{Name,Vsn},App}) ->
cr_path(Name, Vsn, App, PathFlag, Variables)
end,
Appls)).
%% Create the path to a specific application.
( The otp_build flag is only used for OTP internal system make )
cr_path(Name, Vsn, _, true, []) ->
filename:join(["$ROOT", "lib", to_list(Name) ++ "-" ++ Vsn, "ebin"]);
cr_path(Name, Vsn, App, true, Variables) ->
Dir = App#application.dir,
N = to_list(Name),
Tail = [N ++ "-" ++ Vsn, "ebin"],
case variable_dir(Dir, N, Vsn, Variables) of
{ok, VarDir} ->
filename:join([VarDir] ++ Tail);
_ ->
filename:join(["$ROOT", "lib"] ++ Tail)
end;
cr_path(Name, _, _, otp_build, _) ->
filename:join(["$ROOT", "lib", to_list(Name), "ebin"]);
cr_path(_, _, App, _, _) ->
filename:absname(App#application.dir).
variable_dir(Dir, Name, Vsn, [{Var,Path}|Variables]) ->
case lists:prefix(Path,Dir) of
true ->
D0 = strip_prefix(Path, Dir),
case strip_name_ebin(D0, Name, Vsn) of
{ok, D} ->
{ok, filename:join(["\$" ++ Var] ++ D)};
_ ->
%% We know at least that we are located
%% under the variable dir.
{ok, filename:join(["\$" ++ Var] ++ D0)}
end;
_ ->
variable_dir(Dir, Name, Vsn, Variables)
end;
variable_dir(_Dir, _, _, []) ->
false.
strip_prefix(Path, Dir) ->
L = length(filename:split(Path)),
lists:nthtail(L, filename:split(Dir)).
strip_name_ebin(Dir, Name, Vsn) ->
FullName = Name ++ "-" ++ Vsn,
case reverse(Dir) of
["ebin",Name|D] -> {ok, reverse(D)};
["ebin",FullName|D] -> {ok, reverse(D)};
_ -> false
end.
%% Create the path to the kernel and stdlib applications.
create_mandatory_path(Appls, PathFlag, Variables) ->
Dirs = [kernel, stdlib],
make_set(map(fun({{Name,Vsn}, A}) ->
case lists:member(Name, Dirs) of
true ->
cr_path(Name, Vsn, A, PathFlag, Variables);
_ ->
""
end
end,
Appls)).
%%______________________________________________________________________
%% Load all modules, except those in Mandatory_modules.
load_appl_mods([{{Name,Vsn},A}|Appls], Mand, PathFlag, Variables) ->
Mods = A#application.modules,
load_commands(filter(fun(Mod) -> not member(Mod, Mand) end, Mods),
cr_path(Name, Vsn, A, PathFlag, Variables)) ++
load_appl_mods(Appls, Mand, PathFlag, Variables);
[ { path , [ cr_path(Name , , A , PathFlag , Variables ) ] } ,
{ primLoad , filter(fun(Mod ) - > not member(Mod , ) end , Mods ) } |
load_appl_mods(Appls , , PathFlag , Variables ) ] ;
load_appl_mods([], _, _, _) ->
[{progress, modules_loaded}].
load_commands(Mods, Path) ->
[{path, [filename:join([Path])]},
{primLoad,lists:sort(Mods)}].
%%______________________________________________________________________
%% Pack an application to an application term.
pack_app(#application{name=Name,vsn=V,id=Id,description=D,modules=M,
uses=App,optional=Opts,includes=Incs,regs=Regs,mod=Mod,start_phases=SF,
env=Env,maxT=MaxT,maxP=MaxP}) ->
{application, Name,
[{description,D},
{vsn,V},
{id,Id},
{modules, M},
{registered, Regs},
{applications, App},
{optional_applications, Opts},
{included_applications, Incs},
{env, Env},
{maxT, MaxT},
{maxP, MaxP} |
behave([{start_phases,SF},{mod,Mod}])]}.
behave([{mod,[]}|T]) ->
behave(T);
behave([{start_phases,undefined}|T]) ->
behave(T);
behave([H|T]) ->
[H|behave(T)];
behave([]) ->
[].
mandatory_modules() ->
[error_handler, %Truly mandatory.
%% Modules that are almost always needed. Listing them here
%% helps the init module to load them faster. Modules not
%% listed here will be loaded by the error_handler module.
%%
%% Keep this list sorted.
application,
application_controller,
application_master,
code,
code_server,
erl_eval,
erl_lint,
erl_parse,
error_logger,
ets,
file,
filename,
file_server,
file_io_server,
gen,
gen_event,
gen_server,
heart,
kernel,
logger,
logger_filters,
logger_server,
logger_backend,
logger_config,
logger_simple_h,
lists,
proc_lib,
supervisor
].
%%______________________________________________________________________
This is the modules that are preloaded into the Erlang system .
preloaded() ->
lists:sort(
?ESOCK_MODS ++
[atomics,counters,erl_init,erl_prim_loader,erl_tracer,erlang,
erts_code_purger,erts_dirty_process_signal_handler,
erts_internal,erts_literal_area_collector,
init,persistent_term,prim_buffer,prim_eval,prim_file,
prim_inet,prim_zip,zlib]).
%%______________________________________________________________________
This is the erts binaries that should * not * be part of a systool : make_tar package
erts_binary_filter() ->
Cmds = ["typer", "dialyzer", "ct_run", "yielding_c_fun", "erlc"],
case os:type() of
{unix,_} -> Cmds;
{win32,_} -> [ [Cmd, ".exe"] || Cmd <- Cmds]
end.
%%______________________________________________________________________
%% Kernel processes; processes that are specially treated by the init
%% process. If a kernel process terminates the whole system terminates.
kernel_processes ( ) - > [ { Name , Mod , Func , } ]
where is a term or a fun taking the list of applications as arg .
kernel_processes() ->
[{heart, heart, start, []},
{logger, logger_server, start_link, []},
{application_controller, application_controller, start,
fun(Appls) ->
[{_,App}] = filter(fun({{kernel,_},_App}) -> true;
(_) -> false
end,
Appls),
[pack_app(App)]
end}
].
%%______________________________________________________________________
%% Create the kernel processes.
create_kernel_procs(Appls) ->
map(fun({Name,Mod,Func,Args}) when is_function(Args) ->
{kernelProcess, Name, {Mod, Func, Args(Appls)}};
({Name,Mod,Func,Args}) ->
{kernelProcess, Name, {Mod, Func, Args}}
end,
kernel_processes()) ++
[{progress, init_kernel_started}].
%%______________________________________________________________________
%% Make a tar file of the release.
%% The tar file contains:
%% lib/App-Vsn/ebin
%% /priv
%% [/src]
%% [/include]
%% [/doc]
%% [/examples]
%% [/...]
Variable1.tar.gz
%% ...
VariableN.tar.gz
%% releases/RelName.rel
%% RelVsn/start.boot
relup
%% sys.config
%% sys.config.src
%% erts-EVsn[/bin]
%%
The VariableN.tar.gz files can also be stored as own files not
%% included in the main tar file or they can be omitted using
%% the var_tar option.
mk_tar(RelName, Release, Appls, Flags, Path1) ->
TarName = case get_outdir(Flags) of
"" ->
RelName ++ ".tar.gz";
OutDir ->
filename:join(OutDir, filename:basename(RelName))
++ ".tar.gz"
end,
Tar = open_main_tar(TarName),
case catch mk_tar(Tar, RelName, Release, Appls, Flags, Path1) of
{error,Error} ->
_ = del_tar(Tar, TarName),
{error,?MODULE,Error};
{'EXIT',Reason} ->
_ = del_tar(Tar, TarName),
{error,?MODULE,Reason};
_ ->
case erl_tar:close(Tar) of
ok -> ok;
{error,Reason} -> {error,?MODULE,{close,TarName,Reason}}
end
end.
open_main_tar(TarName) ->
case catch open_tar(TarName) of
{error, Error} ->
throw({error,?MODULE,Error});
Tar ->
Tar
end.
mk_tar(Tar, RelName, Release, Appls, Flags, Path1) ->
Variables = get_variables(Flags),
add_applications(Appls, Tar, Variables, Flags, false),
add_variable_tars(Variables, Appls, Tar, Flags),
add_system_files(Tar, RelName, Release, Path1),
add_erts_bin(Tar, Release, Flags),
add_additional_files(Tar, Flags).
add_additional_files(Tar, Flags) ->
case get_flag(extra_files, Flags) of
{extra_files, ToAdd} ->
[add_to_tar(Tar, From, To) || {From, To} <- ToAdd];
_ ->
ok
end.
add_applications(Appls, Tar, Variables, Flags, Var) ->
Res = foldl(fun({{Name,Vsn},App}, Errs) ->
case catch add_appl(to_list(Name), Vsn, App,
Tar, Variables, Flags, Var) of
ok ->
Errs;
{error, What} ->
[{error_add_appl, {Name,What}}|Errs]
end
end, [], Appls),
case Res of
[] ->
ok;
Errors ->
throw({error, Errors})
end.
%%______________________________________________________________________
%% Create a tar file for each Variable directory.
%% Deletes the temporary tar file.
add_variable_tars([Variable|Variables], Appls, Tar, Flags) ->
add_variable_tar(Variable, Appls, Tar, Flags),
add_variable_tars(Variables, Appls, Tar, Flags);
add_variable_tars([], _, _, _) ->
ok.
add_variable_tar({Variable,P}, Appls, Tar, Flags) ->
case var_tar_flag(Flags) of
omit ->
ok;
Flag ->
TarName = Variable ++ ".tar.gz",
VarTar = open_tar(TarName),
case catch add_applications(Appls, VarTar, [{Variable,P}],
Flags, Variable) of
ok when Flag == include ->
close_tar(VarTar,TarName),
add_to_tar(Tar, TarName, TarName),
del_file(TarName);
ok when Flag == ownfile ->
close_tar(VarTar,TarName);
Error ->
_ = del_tar(VarTar, TarName),
throw(Error)
end
end.
var_tar_flag(Flags) ->
case get_flag(var_tar, Flags) of
{var_tar, Flag} ->
case member(Flag, [include, ownfile, omit]) of
true -> Flag;
_ -> include
end;
_ ->
include
end.
%%______________________________________________________________________
Add all " other " files to Dir / releases / Svsn
%% add_system_files(Tar,Name,release#,Flags) ->
%% ok | throw({error,Error})
add_system_files(Tar, RelName, Release, Path1) ->
SVsn = Release#release.vsn,
RelName0 = filename:basename(RelName),
RelVsnDir = filename:join("releases", SVsn),
%% OTP-9746: store rel file in releases/<vsn>
%% Adding rel file to
1 ) releases directory - so it can be easily extracted
%% separately (see release_handler:unpack_release)
2 ) releases/<vsn > - so the file must not be explicitly moved
%% after unpack.
add_to_tar(Tar, RelName ++ ".rel",
filename:join("releases", RelName0 ++ ".rel")),
add_to_tar(Tar, RelName ++ ".rel",
filename:join(RelVsnDir, RelName0 ++ ".rel")),
OTP-6226 Look for the system files not only in cwd
%% --
%% (well, actually the boot file was looked for in the same
directory as RelName , which is not necessarily the same as cwd )
%% --
but also in the path specified as an option to systools : make_tar
( but make sure to search the RelName directory and cwd first )
Path = case filename:dirname(RelName) of
"." ->
["."|Path1];
RelDir ->
[RelDir, "."|Path1]
end,
case lookup_file("start.boot", Path) of
false ->
case lookup_file(RelName0 ++ ".boot", Path) of
false ->
throw({error, {tar_error, {add, boot, RelName, enoent}}});
Boot ->
add_to_tar(Tar, Boot, filename:join(RelVsnDir, "start.boot"))
end;
Boot ->
add_to_tar(Tar, Boot, filename:join(RelVsnDir, "start.boot"))
end,
case lookup_file("relup", Path) of
false ->
ignore;
Relup ->
check_relup(Relup),
add_to_tar(Tar, Relup, filename:join(RelVsnDir, "relup"))
end,
case lookup_file("sys.config.src", Path) of
false ->
case lookup_file("sys.config", Path) of
false ->
ignore;
Sys ->
check_sys_config(Sys),
add_to_tar(Tar, Sys, filename:join(RelVsnDir, "sys.config"))
end;
SysSrc ->
add_to_tar(Tar, SysSrc, filename:join(RelVsnDir, "sys.config.src"))
end,
ok.
lookup_file(Name, [Dir|Path]) ->
File = filename:join(Dir, Name),
case filelib:is_file(File) of
true ->
File;
false ->
lookup_file(Name, Path)
end;
lookup_file(_Name, []) ->
false.
Check that relup can be parsed and has expected format
check_relup(File) ->
case file:consult(File) of
{ok,[{Vsn,UpFrom,DownTo}]} when is_list(Vsn), is_integer(hd(Vsn)),
is_list(UpFrom), is_list(DownTo) ->
ok;
{ok,_} ->
throw({error,{tar_error,{add,"relup",[invalid_format]}}});
Other ->
throw({error,{tar_error,{add,"relup",[Other]}}})
end.
%% Check that sys.config can be parsed and has expected format
check_sys_config(File) ->
case file:consult(File) of
{ok,[SysConfig]} ->
case lists:all(fun({App,KeyVals}) when is_atom(App),
is_list(KeyVals)->
true;
(OtherConfig) when is_list(OtherConfig),
is_integer(hd(OtherConfig)) ->
true;
(_) ->
false
end,
SysConfig) of
true ->
ok;
false ->
throw({error,{tar_error,
{add,"sys.config",[invalid_format]}}})
end;
{ok,_} ->
throw({error,{tar_error,{add,"sys.config",[invalid_format]}}});
Other ->
throw({error,{tar_error,{add,"sys.config",[Other]}}})
end.
%%______________________________________________________________________
%% Add either a application located under a variable dir or all other
%% applications to a tar file.
add_appl(Name , , application#,Tar , Variables , Flags , Var ) - >
%% ok | {error,Error}
add_appl(Name, Vsn, App, Tar, Variables, Flags, Var) ->
AppDir = App#application.dir,
case add_to(AppDir,Name,Vsn,Variables,Var) of
false ->
ok;
{ok, ToDir} ->
ADir = appDir(AppDir),
add_priv(ADir, ToDir, Tar),
case get_flag(dirs,Flags) of
{dirs,Dirs} ->
add_dirs(ADir, Dirs, ToDir, Tar);
_ ->
ok
end,
BinDir = filename:join(ToDir, "ebin"),
add_to_tar(Tar,
filename:join(AppDir, Name ++ ".app"),
filename:join(BinDir, Name ++ ".app")),
add_modules(map(fun(Mod) -> to_list(Mod) end,
App#application.modules),
Tar,
AppDir,
BinDir,
code:objfile_extension())
end.
%%______________________________________________________________________
%% If an application directory contains a Variable (in AppDir) the
%% application will be placed in the tar file (if it is this Variable
%% we corrently is actually storing).
add_to(AppDir,Name,Vsn,Variables,Variable) ->
case var_dir(AppDir,Name,Vsn,Variables) of
{ok, Variable, RestPath} ->
{ok, filename:join(RestPath ++ [Name ++ "-" ++ Vsn])};
{ok, _, _} ->
false;
_ when Variable == false ->
{ok, filename:join("lib", Name ++ "-" ++ Vsn)};
_ ->
false
end.
var_dir(Dir, Name, Vsn, [{Var,Path}|Variables]) ->
case lists:prefix(Path,Dir) of
true ->
D0 = strip_prefix(Path, Dir),
case strip_name_ebin(D0, Name, Vsn) of
{ok, D} ->
{ok, Var, D};
_ ->
false
end;
_ ->
var_dir(Dir, Name, Vsn, Variables)
end;
var_dir(_Dir, _, _, []) ->
false.
appDir(AppDir) ->
case filename:basename(AppDir) of
"ebin" -> filename:dirname(AppDir);
_ -> AppDir
end.
add_modules(Modules, Tar, AppDir, ToDir, Ext) ->
foreach(fun(Mod) ->
add_to_tar(Tar,
filename:join(AppDir, Mod ++ Ext),
filename:join(ToDir, Mod ++ Ext))
end, Modules).
%%
%% Add own specified directories to include in the release.
%% If not found, skip it.
%%
add_dirs(AppDir, Dirs, ToDir, Tar) ->
foreach(fun(Dir) -> catch add_dir(AppDir, to_list(Dir), ToDir, Tar) end,
Dirs).
add_dir(TopDir, Dir, ToDir, Tar) ->
FromD = filename:join(TopDir, Dir),
case dirp(FromD) of
true ->
add_to_tar(Tar, FromD, filename:join(ToDir, Dir));
_ ->
ok
end.
%%
%% Add the priv dir if it exists.
add_priv(ADir, ToDir, Tar) ->
Priv = filename:join(ADir, "priv"),
case dirp(Priv) of
true ->
add_to_tar(Tar, Priv, filename:join(ToDir, "priv"));
_ ->
ok
end.
add_erts_bin(Tar, Release, Flags) ->
case {get_flag(erts,Flags),member(erts_all,Flags)} of
{{erts,ErtsDir},true} ->
add_erts_bin(Tar, Release, ErtsDir, []);
{{erts,ErtsDir},false} ->
add_erts_bin(Tar, Release, ErtsDir, erts_binary_filter());
_ ->
ok
end.
add_erts_bin(Tar, Release, ErtsDir, Filters) ->
FlattenedFilters = [filename:flatten(Filter) || Filter <- Filters],
EVsn = Release#release.erts_vsn,
FromDir = filename:join([to_list(ErtsDir),
"erts-" ++ EVsn, "bin"]),
ToDir = filename:join("erts-" ++ EVsn, "bin"),
{ok, Bins} = file:list_dir(FromDir),
[add_to_tar(Tar, filename:join(FromDir,Bin), filename:join(ToDir,Bin))
|| Bin <- Bins, not lists:member(Bin, FlattenedFilters)],
ok.
%%______________________________________________________________________
%% Tar functions.
open_tar(TarName) ->
case erl_tar:open(TarName, [write, compressed]) of
{ok, Tar} ->
Tar;
{error, Error} ->
throw({error,{tar_error, {open, TarName, Error}}})
end.
close_tar(Tar,File) ->
case erl_tar:close(Tar) of
ok -> ok;
{error,Reason} -> throw({error,{close,File,Reason}})
end.
del_tar(Tar, TarName) ->
_ = erl_tar:close(Tar),
file:delete(TarName).
add_to_tar(Tar, FromFile, ToFile) ->
case catch erl_tar:add(Tar, FromFile, ToFile, [compressed, dereference]) of
ok -> ok;
{'EXIT', Reason} ->
throw({error, {tar_error, {add, FromFile, Reason}}});
{error, Error} ->
throw({error, {tar_error, {add, FromFile, Error}}})
end.
%%______________________________________________________________________
%%______________________________________________________________________
%% utilities!
make_set([]) -> [];
make_set([""|T]) -> % Ignore empty items.
make_set(T);
make_set([H|T]) ->
[H | [ Y || Y<- make_set(T),
Y =/= H]].
to_list(A) when is_atom(A) -> atom_to_list(A);
to_list(L) -> L.
mk_path(Path0) ->
Path1 = map(fun(Dir) when is_atom(Dir) -> atom_to_list(Dir);
(Dir) -> Dir
end, Path0),
systools_lib:get_path(Path1).
%% duplicates([Tuple]) -> List of pairs where
%% element(1, T1) == element(1, T2) and where T1 and T2 are
%% taken from [Tuple]
duplicates(X) -> duplicates(keysort(1,X), []).
duplicates([H1,H2|T], L) ->
case {element(1,H1),element(1,H2)} of
{X,X} -> duplicates([H2|T],[{H1,H2}|L]);
_ -> duplicates([H2|T],L)
end;
duplicates(_, L) -> L.
%% read_file(File, Path) -> {ok, Term, FullName} | {error, Error}
%% read a file and check the syntax, i.e. that it contains a correct
Erlang term .
read_file(File, Path) ->
case file:path_open(Path, File, [read]) of
{ok, Stream, FullName} ->
Return = case systools_lib:read_term_from_stream(Stream, File) of
{ok, Term} ->
{ok, Term, FullName};
Other ->
Other
end,
case file:close(Stream) of
ok -> Return;
{error, Error} -> {error, {close,File,Error}}
end;
_Other ->
{error, {not_found, File}}
end.
del_file(File) ->
case file:delete(File) of
ok -> ok;
{error, Error} ->
throw({error, {delete, File, Error}})
end.
dirp(Dir) ->
case file:read_file_info(Dir) of
{ok, FileInfo} -> FileInfo#file_info.type == directory;
_ -> false
end.
%% Create the include path. Assumptions about the code path is done
%% and an include directory is added.
Add the official include dir for each found application first in
%% path !!
%% If .../ebin exists in a path an .../include directory is assumed to
%% exist at the same level. If .../ebin is not existing the .../include
%% directory is assumed anyhow.
%% Local includes are added for each application later on.
create_include_path(Appls, Path) ->
FoundAppDirs = map(fun({_,A}) -> A#application.dir end, Appls),
map(fun(Dir) ->
case reverse(filename:split(Dir)) of
["ebin"|D] ->
filename:join(reverse(D) ++ ["include"]);
_ ->
filename:join(Dir, "include")
end
end,
FoundAppDirs ++ no_dupl(Path, FoundAppDirs)).
no_dupl([Dir|Path], FoundAppDirs) ->
case member(Dir, FoundAppDirs) of
true ->
no_dupl(Path, FoundAppDirs);
_ ->
[Dir|no_dupl(Path, FoundAppDirs)]
end;
no_dupl([], _) ->
[].
is_app_type(permanent) -> true;
is_app_type(transient) -> true;
is_app_type(temporary) -> true;
is_app_type(none) -> true;
is_app_type(load) -> true;
is_app_type(_) -> false.
% check if a term is a string.
string_p(S) ->
case unicode:characters_to_list(S) of
S -> true;
_ -> false
end.
check if a term is a list of two tuples with the first
% element as an atom.
t_list_p([{A,_}|T]) when is_atom(A) -> t_list_p(T);
t_list_p([]) -> true;
t_list_p(_) -> false.
% check if a term is a list of atoms.
a_list_p([A|T]) when is_atom(A) -> a_list_p(T);
a_list_p([]) -> true;
a_list_p(_) -> false.
%% Get a key-value tuple flag from a list.
get_flag(F,[{F,D}|_]) -> {F,D};
get_flag(F,[_|Fs]) -> get_flag(F,Fs);
get_flag(_,_) -> false.
%% Check Options for make_script
check_args_script(Args) ->
cas(Args, []).
cas([], X) ->
X;
%%% path ---------------------------------------------------------------
cas([{path, P} | Args], X) when is_list(P) ->
case check_path(P) of
ok ->
cas(Args, X);
error ->
cas(Args, X++[{path,P}])
end;
%%% silent -------------------------------------------------------------
cas([silent | Args], X) ->
cas(Args, X);
%%% local --------------------------------------------------------------
cas([local | Args], X) ->
cas(Args, X);
%%% src_tests -------------------------------------------------------
cas([src_tests | Args], X) ->
cas(Args, X);
%%% variables ----------------------------------------------------------
cas([{variables, V} | Args], X) when is_list(V) ->
case check_vars(V) of
ok ->
cas(Args, X);
error ->
cas(Args, X++[{variables, V}])
end;
%%% exref --------------------------------------------------------------
cas([exref | Args], X) ->
cas(Args, X);
%%% exref Apps ---------------------------------------------------------
cas([{exref, Apps} | Args], X) when is_list(Apps) ->
case check_apps(Apps) of
ok ->
cas(Args, X);
error ->
cas(Args, X++[{exref, Apps}])
end;
%%% outdir Dir ---------------------------------------------------------
cas([{outdir, Dir} | Args], X) when is_list(Dir) ->
cas(Args, X);
%%% otp_build (secret, not documented) ---------------------------------
cas([otp_build | Args], X) ->
cas(Args, X);
%%% warnings_as_errors -------------------------------------------------
cas([warnings_as_errors | Args], X) ->
cas(Args, X);
%%% no_warn_sasl -------------------------------------------------------
cas([no_warn_sasl | Args], X) ->
cas(Args, X);
%%% no_module_tests (kept for backwards compatibility, but ignored) ----
cas([no_module_tests | Args], X) ->
cas(Args, X);
cas([no_dot_erlang | Args], X) ->
cas(Args, X);
%% set the name of the script and boot file to create
cas([{script_name, Name} | Args], X) when is_list(Name) ->
cas(Args, X);
%%% ERROR --------------------------------------------------------------
cas([Y | Args], X) ->
cas(Args, X++[Y]).
Check Options for make_tar
check_args_tar(Args) ->
cat(Args, []).
cat([], X) ->
X;
%%% path ---------------------------------------------------------------
cat([{path, P} | Args], X) when is_list(P) ->
case check_path(P) of
ok ->
cat(Args, X);
error ->
cat(Args, X++[{path,P}])
end;
%%% silent -------------------------------------------------------------
cat([silent | Args], X) ->
cat(Args, X);
%%% dirs ---------------------------------------------------------------
cat([{dirs, D} | Args], X) ->
case check_dirs(D) of
ok ->
cat(Args, X);
error ->
cat(Args, X++[{dirs, D}])
end;
%%% erts ---------------------------------------------------------------
cat([{erts, E} | Args], X) when is_list(E)->
cat(Args, X);
cat([erts_all | Args], X) ->
cat(Args, X);
%%% src_tests ----------------------------------------------------
cat([src_tests | Args], X) ->
cat(Args, X);
%%% variables ----------------------------------------------------------
cat([{variables, V} | Args], X) when is_list(V) ->
case check_vars(V) of
ok ->
cat(Args, X);
error ->
cat(Args, X++[{variables, V}])
end;
%%% var_tar ------------------------------------------------------------
cat([{var_tar, VT} | Args], X) when VT == include;
VT == ownfile;
VT == omit ->
cat(Args, X);
%%% exref --------------------------------------------------------------
cat([exref | Args], X) ->
cat(Args, X);
%%% exref Apps ---------------------------------------------------------
cat([{exref, Apps} | Args], X) when is_list(Apps) ->
case check_apps(Apps) of
ok ->
cat(Args, X);
error ->
cat(Args, X++[{exref, Apps}])
end;
%%% outdir Dir ---------------------------------------------------------
cat([{outdir, Dir} | Args], X) when is_list(Dir) ->
cat(Args, X);
%%% otp_build (secret, not documented) ---------------------------------
cat([otp_build | Args], X) ->
cat(Args, X);
%%% warnings_as_errors ----
cat([warnings_as_errors | Args], X) ->
cat(Args, X);
%%% no_warn_sasl ----
cat([no_warn_sasl | Args], X) ->
cat(Args, X);
%%% no_module_tests (kept for backwards compatibility, but ignored) ----
cat([no_module_tests | Args], X) ->
cat(Args, X);
cat([{extra_files, ExtraFiles} | Args], X) when is_list(ExtraFiles) ->
cat(Args, X);
%%% ERROR --------------------------------------------------------------
cat([Y | Args], X) ->
cat(Args, X++[Y]).
check_path([]) ->
ok;
check_path([H|T]) when is_list(H) ->
check_path(T);
check_path([_H|_T]) ->
error.
check_dirs([]) ->
ok;
check_dirs([H|T]) when is_atom(H) ->
check_dirs(T);
check_dirs([_H|_T]) ->
error.
check_vars([]) ->
ok;
check_vars([{Name, Dir} | T]) ->
if
is_atom(Name), is_list(Dir) ->
check_vars(T);
is_list(Name), is_list(Dir) ->
check_vars(T);
true ->
error
end;
check_vars(_) ->
error.
check_apps([]) ->
ok;
check_apps([H|T]) when is_atom(H) ->
check_apps(T);
check_apps(_) ->
error.
%% Format error
format_error(badly_formatted_release) ->
io_lib:format("Syntax error in the release file~n",[]);
format_error({illegal_name, Name}) ->
io_lib:format("Illegal name (~tp) in the release file~n",[Name]);
format_error({illegal_form, Form}) ->
io_lib:format("Illegal tag in the release file: ~tp~n",[Form]);
format_error({missing_parameter,Par}) ->
io_lib:format("Missing parameter (~p) in the release file~n",[Par]);
format_error({illegal_applications,Names}) ->
io_lib:format("Illegal applications in the release file: ~p~n",
[Names]);
format_error({missing_mandatory_app,Name}) ->
io_lib:format("Mandatory application ~w must be specified in the release file~n",
[Name]);
format_error({mandatory_app,Name,Type}) ->
io_lib:format("Mandatory application ~w must be of type 'permanent' in the release file. Is '~p'.~n",
[Name,Type]);
format_error({duplicate_register,Dups}) ->
io_lib:format("Duplicated register names: ~n~ts",
[map(fun({{Reg,App1,_,_},{Reg,App2,_,_}}) ->
io_lib:format("\t~tw registered in ~w and ~w~n",
[Reg,App1,App2])
end, Dups)]);
format_error({undefined_applications,Apps}) ->
io_lib:format("Undefined applications: ~p~n",[Apps]);
format_error({duplicate_modules,Dups}) ->
io_lib:format("Duplicated modules: ~n~ts",
[map(fun({{Mod,App1,_},{Mod,App2,_}}) ->
io_lib:format("\t~w specified in ~w and ~w~n",
[Mod,App1,App2])
end, Dups)]);
format_error({included_and_used, Dups}) ->
io_lib:format("Applications both used and included: ~p~n",[Dups]);
format_error({duplicate_include, Dups}) ->
io_lib:format("Duplicated application included: ~n~ts",
[map(fun({{Name,App1,_,_},{Name,App2,_,_}}) ->
io_lib:format("\t~w included in ~w and ~w~n",
[Name,App1,App2])
end, Dups)]);
format_error({modules,ModErrs}) ->
format_errors(ModErrs);
format_error({circular_dependencies,Apps}) ->
io_lib:format("Circular dependencies among applications: ~p~n",[Apps]);
format_error({not_found,File}) ->
io_lib:format("File not found: ~tp~n",[File]);
format_error({parse,File,{Line,Mod,What}}) ->
Str = Mod:format_error(What),
io_lib:format("~ts:~w: ~ts\n",[File, Line, Str]);
format_error({read,File}) ->
io_lib:format("Cannot read ~tp~n",[File]);
format_error({open,File,Error}) ->
io_lib:format("Cannot open ~tp - ~ts~n",
[File,file:format_error(Error)]);
format_error({close,File,Error}) ->
io_lib:format("Cannot close ~tp - ~ts~n",
[File,file:format_error(Error)]);
format_error({delete,File,Error}) ->
io_lib:format("Cannot delete ~tp - ~ts~n",
[File,file:format_error(Error)]);
format_error({tar_error,What}) ->
form_tar_err(What);
format_error({warnings_treated_as_errors,Warnings}) ->
io_lib:format("Warnings being treated as errors:~n~ts",
[map(fun(W) -> form_warn("",W) end, Warnings)]);
format_error(ListOfErrors) when is_list(ListOfErrors) ->
format_errors(ListOfErrors);
format_error(E) -> io_lib:format("~tp~n",[E]).
format_errors(ListOfErrors) ->
map(fun({error,E}) -> form_err(E);
(E) -> form_err(E)
end, ListOfErrors).
form_err({bad_application_name,{Name,Found}}) ->
io_lib:format("~p: Mismatched application id: ~p~n",[Name,Found]);
form_err({error_reading, {Name, What}}) ->
io_lib:format("~p: ~ts~n",[Name,form_reading(What)]);
form_err({module_not_found,App,Mod}) ->
io_lib:format("~w: Module (~w) not found~n",[App,Mod]);
form_err({error_add_appl, {Name, {tar_error, What}}}) ->
io_lib:format("~p: ~ts~n",[Name,form_tar_err(What)]);
form_err(E) ->
io_lib:format("~tp~n",[E]).
form_reading({not_found,File}) ->
io_lib:format("File not found: ~tp~n",[File]);
form_reading({application_vsn, {Name,Vsn}}) ->
io_lib:format("Application ~ts with version ~tp not found~n",[Name, Vsn]);
form_reading({parse,File,{Line,Mod,What}}) ->
Str = Mod:format_error(What),
io_lib:format("~ts:~w: ~ts\n",[File, Line, Str]);
form_reading({read,File}) ->
io_lib:format("Cannot read ~tp~n",[File]);
form_reading({{bad_param, P},_}) ->
io_lib:format("Bad parameter in .app file: ~tp~n",[P]);
form_reading({{dupl_entry, P, DE},_}) ->
io_lib:format("~tp parameter contains duplicates of: ~tp~n", [P, DE]);
form_reading({{missing_param,P},_}) ->
io_lib:format("Missing parameter in .app file: ~p~n",[P]);
form_reading({badly_formatted_application,_}) ->
io_lib:format("Syntax error in .app file~n",[]);
form_reading({override_include,Apps}) ->
io_lib:format("Tried to include not (in .app file) specified applications: ~p~n",
[Apps]);
form_reading({no_valid_version, {{_, SVsn}, {_, File, FVsn}}}) ->
io_lib:format("No valid version (~tp) of .app file found. Found file ~tp with version ~tp~n",
[SVsn, File, FVsn]);
form_reading({parse_error, {File, Line, Error}}) ->
io_lib:format("Parse error in file: ~tp. Line: ~w Error: ~tp; ~n", [File, Line, Error]);
form_reading(W) ->
io_lib:format("~tp~n",[W]).
form_tar_err({open, File, Error}) ->
io_lib:format("Cannot open tar file ~ts - ~ts~n",
[File, erl_tar:format_error(Error)]);
form_tar_err({add, boot, RelName, enoent}) ->
io_lib:format("Cannot find file start.boot or ~ts to add to tar file - ~ts~n",
[RelName, erl_tar:format_error(enoent)]);
form_tar_err({add, File, Error}) ->
io_lib:format("Cannot add file ~ts to tar file - ~ts~n",
[File, erl_tar:format_error(Error)]).
%% Format warning
format_warning(Warnings) ->
map(fun({warning,W}) -> form_warn("*WARNING* ", W) end, Warnings).
form_warn(Prefix, {source_not_found,{Mod,App,_}}) ->
io_lib:format("~ts~w: Source code not found: ~w.erl~n",
[Prefix,App,Mod]);
form_warn(Prefix, {{parse_error, File},{_,_,App,_,_}}) ->
io_lib:format("~ts~w: Parse error: ~tp~n",
[Prefix,App,File]);
form_warn(Prefix, {obj_out_of_date,{Mod,App,_}}) ->
io_lib:format("~ts~w: Object code (~w) out of date~n",
[Prefix,App,Mod]);
form_warn(Prefix, {exref_undef, Undef}) ->
F = fun({M,F,A}) ->
io_lib:format("~tsUndefined function ~w:~tw/~w~n",
[Prefix,M,F,A])
end,
map(F, Undef);
form_warn(Prefix, missing_sasl) ->
io_lib:format("~tsMissing application sasl. "
"Can not upgrade with this release~n",
[Prefix]);
form_warn(Prefix, What) ->
io_lib:format("~ts~tp~n", [Prefix,What]).
| null | https://raw.githubusercontent.com/erlang/otp/c696ab8951f3a02dd588e686bd041c6259bede7f/lib/sasl/src/systools_make.erl | erlang |
%CopyrightBegin%
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
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.
%CopyrightEnd%
and create a tar file of a release (RelName.tar.gz)
Exported just for testing
-----------------------------------------------------------------
Create a boot script from a release file.
Options is a list of {path, Path} | silent | local
where path sets the search path, silent suppresses error message
printing on console, local generates a script with references
to the directories there the applications are found,
New options: {path,Path} can contain wildcards
src_tests
exref | {exref, [AppName]}
no_warn_sasl
-----------------------------------------------------------------
To maintain backwards compatibility for make_script/3,
the boot script file name is constructed here, before
checking the validity of OutDir
expand wildcards etc.
false | {outdir, Badarg}
-----------------------------------------------------------------
Make hybrid boot file for upgrading emulator. The resulting boot
file (the boot file of the old release).
The most important thing that can fail here is that the input boot
and sasl.
Returns {ok,Boot} | {error,Reason}
Reason = {app_not_found,App} | {app_not_replaced,App}
Everything up to kernel_load_completed must come from the new script
Then comes all module load, which for each app consist of:
{path,[AppPath]},
Replace kernel, stdlib and sasl here
For each app, compile a regexp that can be used for finding its path
Return the entries for loading stdlib and sasl
Replace the entries for loading the stdlib and sasl
Finally add an apply of release_handler:new_emulator_upgrade - which will
-----------------------------------------------------------------
Create a release package from a release file.
Options is a list of {path, Path} | silent |
sets the search path, silent suppresses error message printing,
dirs includes the specified directories (per application) in the
release package and erts specifies that the erts-Vsn/bin directory
should be included in the release package and there it can be found.
New options: {path,Path} can contain wildcards
src_tests
exref | {exref, [AppName]}
no_warn_sasl
The tar file contains:
lib/App-Vsn/ebin
/priv
[/src]
[/include]
[/doc]
[/examples]
[/...]
...
releases/RelName.rel
RelVsn/start.boot
sys.config
sys.config.src
erts-EVsn[/bin]
-----------------------------------------------------------------
______________________________________________________________________
get_release(File, Path) ->
{ok, #release, [{{Name,Vsn},#application}], Warnings} | {error, What}
______________________________________________________________________
read_release(File, Path) -> {ok, #release} | throw({error, What})
______________________________________________________________________
collect_applications(#release, Path) ->
{ok,[{{Name,Vsn},#application}]} |
throw({error, What})
Read all the application files specified in the release descriptor
______________________________________________________________________
Not found
Test if all included applications specified in the .rel file
exists in the {included_applications,Incs} specified in the
.app file.
Check for duplicate entries in lists
default mod is [], so accept as entry
default start_phase is undefined,
so accept as entry
optional !
optional !
mod is optional !
env is optional !
id is optional !
start_phases is optional !
maxT is optional !
maxP is optional !
______________________________________________________________________
check_applications([{{Name,Vsn},#application}]) ->
check that all referenced applications exists and that no
application register processes with the same name.
Check that included_applications are not specified as used
in another application.
If an application uses another application which is included in yet
another application, e.g. X uses A, A is included in T; then the A
application's top application to ensure the start order.
Exception: if both X and A have the same top, then it is not
added to avoid circular dependencies.
add_top_apps_to_uses( list of all included applications in
the system,
list of all applications in the system,
temporary result)
-> new list of all applications
UW980513 This is a special case: The included app
uses its own top app. We'll allow it, but must
remove the top app from the uses list.
the top app is already in the uses
both are included in the same app
change the used app to the used app's
top application
______________________________________________________________________
undefined_applications([{{Name,Vsn},#application}]) ->
[Name] list of applications that were declared in
use declarations but are not contained in the release descriptor
______________________________________________________________________
sort_used_and_incl_appls(Applications, Release) -> Applications
Applications = [{{Name,Vsn},#application}]
Release = #release{}
Check that used and included applications are given in the same
order as in the release resource file (.rel). Otherwise load and
start instructions in the boot script, and consequently release
______________________________________________________________________
check_modules(Appls, Path, TestP) ->
{ok, Warnings} | throw({error, What})
performs logical checking that we can find all the modules
etc.
io:format("** ERROR Duplicate modules: ~p\n", [Dups]),
______________________________________________________________________
Check that all modules exists.
Use the module extension of the running machine as extension for
the checked modules.
Clear out any previous data
often faster
Perform cross reference checks between all modules specified
in .app files.
______________________________________________________________________
Guess the src code and include directory. If dir contains .../ebin
src-dir should be one of .../src or .../src/e_src
______________________________________________________________________
Take the directories that were used for a guess, and search them
recursively. This is required for applications relying on varying
which has auto-generated modules in `src/gen/' and then fail any
systools check.
Keep the bad guess, but put it last in the search order
since we won't find anything there. Handling of errors
for unfound file is done in `locate_src/2'
______________________________________________________________________
generate_script(#release,
[{{Name,Vsn},#application}], Flags) ->
ok | {error, Error}
Writes a script (a la magnus) to the file File.script
and a bootfile to File.boot.
______________________________________________________________________
Start all applications.
Do not start applications that are included applications !
______________________________________________________________________
Load all applications.
Already added !!
______________________________________________________________________
The final part of the script.
Do not skip loading of $HOME/.erlang
Ignore loading of $HOME/.erlang
-----------------------------------------------------------------
Purpose: Sort applications according to dependencies among
applications. If order doesn't matter, use the same
order as in the original list.
-----------------------------------------------------------------
No more app that must be started before this one is
found; they are all already taken care of (and present
in Visited list)
The apps in L must be started before the app.
in that case we have a circular dependency.
L must be started before N, try again, with all apps
this has already been checked before, but as we have the info...
It is OK to have a dependency like
______________________________________________________________________
Create the load path used in the generated script.
system (e.g. in an embedded system), i.e. all applications are
located under $ROOT/lib.
Otherwise all paths are set according to dir per application.
Create the complete path.
Create the path to a specific application.
We know at least that we are located
under the variable dir.
Create the path to the kernel and stdlib applications.
______________________________________________________________________
Load all modules, except those in Mandatory_modules.
______________________________________________________________________
Pack an application to an application term.
Truly mandatory.
Modules that are almost always needed. Listing them here
helps the init module to load them faster. Modules not
listed here will be loaded by the error_handler module.
Keep this list sorted.
______________________________________________________________________
______________________________________________________________________
______________________________________________________________________
Kernel processes; processes that are specially treated by the init
process. If a kernel process terminates the whole system terminates.
______________________________________________________________________
Create the kernel processes.
______________________________________________________________________
Make a tar file of the release.
The tar file contains:
lib/App-Vsn/ebin
/priv
[/src]
[/include]
[/doc]
[/examples]
[/...]
...
releases/RelName.rel
RelVsn/start.boot
sys.config
sys.config.src
erts-EVsn[/bin]
included in the main tar file or they can be omitted using
the var_tar option.
______________________________________________________________________
Create a tar file for each Variable directory.
Deletes the temporary tar file.
______________________________________________________________________
add_system_files(Tar,Name,release#,Flags) ->
ok | throw({error,Error})
OTP-9746: store rel file in releases/<vsn>
Adding rel file to
separately (see release_handler:unpack_release)
after unpack.
--
(well, actually the boot file was looked for in the same
--
Check that sys.config can be parsed and has expected format
______________________________________________________________________
Add either a application located under a variable dir or all other
applications to a tar file.
ok | {error,Error}
______________________________________________________________________
If an application directory contains a Variable (in AppDir) the
application will be placed in the tar file (if it is this Variable
we corrently is actually storing).
Add own specified directories to include in the release.
If not found, skip it.
Add the priv dir if it exists.
______________________________________________________________________
Tar functions.
______________________________________________________________________
______________________________________________________________________
utilities!
Ignore empty items.
duplicates([Tuple]) -> List of pairs where
element(1, T1) == element(1, T2) and where T1 and T2 are
taken from [Tuple]
read_file(File, Path) -> {ok, Term, FullName} | {error, Error}
read a file and check the syntax, i.e. that it contains a correct
Create the include path. Assumptions about the code path is done
and an include directory is added.
path !!
If .../ebin exists in a path an .../include directory is assumed to
exist at the same level. If .../ebin is not existing the .../include
directory is assumed anyhow.
Local includes are added for each application later on.
check if a term is a string.
element as an atom.
check if a term is a list of atoms.
Get a key-value tuple flag from a list.
Check Options for make_script
path ---------------------------------------------------------------
silent -------------------------------------------------------------
local --------------------------------------------------------------
src_tests -------------------------------------------------------
variables ----------------------------------------------------------
exref --------------------------------------------------------------
exref Apps ---------------------------------------------------------
outdir Dir ---------------------------------------------------------
otp_build (secret, not documented) ---------------------------------
warnings_as_errors -------------------------------------------------
no_warn_sasl -------------------------------------------------------
no_module_tests (kept for backwards compatibility, but ignored) ----
set the name of the script and boot file to create
ERROR --------------------------------------------------------------
path ---------------------------------------------------------------
silent -------------------------------------------------------------
dirs ---------------------------------------------------------------
erts ---------------------------------------------------------------
src_tests ----------------------------------------------------
variables ----------------------------------------------------------
var_tar ------------------------------------------------------------
exref --------------------------------------------------------------
exref Apps ---------------------------------------------------------
outdir Dir ---------------------------------------------------------
otp_build (secret, not documented) ---------------------------------
warnings_as_errors ----
no_warn_sasl ----
no_module_tests (kept for backwards compatibility, but ignored) ----
ERROR --------------------------------------------------------------
Format error
Format warning | Copyright Ericsson AB 1996 - 2022 . All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(systools_make).
Purpose : Create start script . RelName.rel -- > RelName.{script , boot } .
-export([make_script/1, make_script/2, make_script/3,
make_tar/1, make_tar/2]).
-export([format_error/1, format_warning/1]).
-export([read_release/2, get_release/2, get_release/3, pack_app/1]).
-export([read_application/4]).
-export([make_hybrid_boot/4]).
-import(lists, [filter/2, keysort/2, keysearch/3, map/2, reverse/1,
append/1, foldl/3, member/2, foreach/2]).
-include("systools.hrl").
-include_lib("kernel/include/file.hrl").
-define(XREF_SERVER, systools_make).
-compile({inline,[{badarg,2}]}).
-define(ESOCK_MODS, [prim_net,prim_socket,socket_registry]).
| warnings_as_errors
and warnings_as_errors treats warnings as errors .
{ variables,[{Name , } ] }
make_script(RelName) when is_list(RelName) ->
make_script(RelName, []);
make_script(RelName) ->
badarg(RelName,[RelName]).
make_script(RelName, Flags) when is_list(RelName), is_list(Flags) ->
ScriptName = get_script_name(RelName, Flags),
case get_outdir(Flags) of
"" ->
make_script(RelName, ScriptName, Flags);
OutDir ->
( is done in check_args_script/1 )
Output = filename:join(OutDir, filename:basename(ScriptName)),
make_script(RelName, Output, Flags)
end.
make_script(RelName, Output, Flags) when is_list(RelName),
is_list(Output),
is_list(Flags) ->
case check_args_script(Flags) of
[] ->
Path0 = get_path(Flags),
Path = make_set(Path1 ++ code:get_path()),
ModTestP = {member(src_tests, Flags),xref_p(Flags)},
case get_release(RelName, Path, ModTestP) of
{ok, Release, Appls, Warnings0} ->
Warnings = wsasl(Flags, Warnings0),
case systools_lib:werror(Flags, Warnings) of
true ->
Warnings1 = [W || {warning,W}<-Warnings],
return({error,?MODULE,
{warnings_treated_as_errors,Warnings1}},
Warnings,
Flags);
false ->
case generate_script(Output,Release,Appls,Flags) of
ok ->
return(ok,Warnings,Flags);
Error ->
return(Error,Warnings,Flags)
end
end;
Error ->
return(Error,[],Flags)
end;
ErrorVars ->
badarg(ErrorVars, [RelName, Flags])
end;
make_script(RelName, _Output, Flags) when is_list(Flags) ->
badarg(RelName,[RelName, Flags]);
make_script(RelName, _Output, Flags) ->
badarg(Flags,[RelName, Flags]).
wsasl(Options, Warnings) ->
case lists:member(no_warn_sasl,Options) of
true -> lists:delete({warning,missing_sasl},Warnings);
false -> Warnings
end.
badarg(BadArg, Args) ->
erlang:error({badarg,BadArg}, Args).
get_script_name(RelName, Flags) ->
case get_flag(script_name,Flags) of
{script_name,ScriptName} when is_list(ScriptName) -> ScriptName;
_ -> RelName
end.
get_path(Flags) ->
case get_flag(path,Flags) of
{path,Path} when is_list(Path) -> Path;
_ -> []
end.
get_outdir(Flags) ->
case get_flag(outdir,Flags) of
{outdir,OutDir} when is_list(OutDir) ->
OutDir;
""
end.
return(ok,Warnings,Flags) ->
case member(silent,Flags) of
true ->
{ok,?MODULE,Warnings};
_ ->
io:format("~ts",[format_warning(Warnings)]),
ok
end;
return({error,Mod,Error},_,Flags) ->
case member(silent,Flags) of
true ->
{error,Mod,Error};
_ ->
io:format("~ts",[Mod:format_error(Error)]),
error
end.
file is a combination of the two input files , where kernel , stdlib
and sasl versions are taken from the second file ( the boot file of
the new release ) , and all other application versions from the first
files do not contain all three base applications - kernel , stdlib
TmpVsn = string ( ) ,
Boot1 = Boot2 = Boot = binary ( )
App = stdlib | sasl
make_hybrid_boot(TmpVsn, Boot1, Boot2, Args) ->
catch do_make_hybrid_boot(TmpVsn, Boot1, Boot2, Args).
do_make_hybrid_boot(TmpVsn, OldBoot, NewBoot, Args) ->
{script,{_RelName1,_RelVsn1},OldScript} = binary_to_term(OldBoot),
{script,{NewRelName,_RelVsn2},NewScript} = binary_to_term(NewBoot),
Fun1 = fun({progress,kernel_load_completed}) -> false;
(_) -> true
end,
{_OldKernelLoad,OldRest1} = lists:splitwith(Fun1,OldScript),
{NewKernelLoad,NewRest1} = lists:splitwith(Fun1,NewScript),
Fun2 = fun({progress,modules_loaded}) -> false;
(_) -> true
end,
{OldModLoad,OldRest2} = lists:splitwith(Fun2,OldRest1),
{NewModLoad,NewRest2} = lists:splitwith(Fun2,NewRest1),
Fun3 = fun({kernelProcess,_,_}) -> false;
(_) -> true
end,
{OldPaths,OldRest3} = lists:splitwith(Fun3,OldRest2),
{NewPaths,NewRest3} = lists:splitwith(Fun3,NewRest2),
Fun4 = fun({progress,init_kernel_started}) -> false;
(_) -> true
end,
{_OldKernelProcs,OldApps} = lists:splitwith(Fun4,OldRest3),
{NewKernelProcs,NewApps} = lists:splitwith(Fun4,NewRest3),
{ primLoad , ModuleList }
MatchPaths = get_regexp_path(),
ModLoad = replace_module_load(OldModLoad,NewModLoad,MatchPaths),
Paths = replace_paths(OldPaths,NewPaths,MatchPaths),
{Stdlib,Sasl} = get_apps(NewApps,undefined,undefined),
Apps0 = replace_apps(OldApps,Stdlib,Sasl),
Apps = add_apply_upgrade(Apps0,Args),
Script = NewKernelLoad++ModLoad++Paths++NewKernelProcs++Apps,
Boot = term_to_binary({script,{NewRelName,TmpVsn},Script}),
{ok,Boot}.
get_regexp_path() ->
{ok,KernelMP} = re:compile("kernel-[0-9\.]+",[unicode]),
{ok,StdlibMP} = re:compile("stdlib-[0-9\.]+",[unicode]),
{ok,SaslMP} = re:compile("sasl-[0-9\.]+",[unicode]),
[KernelMP,StdlibMP,SaslMP].
replace_module_load(Old,New,[MP|MatchPaths]) ->
replace_module_load(do_replace_module_load(Old,New,MP),New,MatchPaths);
replace_module_load(Script,_,[]) ->
Script.
do_replace_module_load([{path,[OldAppPath]},{primLoad,OldMods}|OldRest],New,MP) ->
case re:run(OldAppPath,MP,[{capture,none}]) of
nomatch ->
[{path,[OldAppPath]},{primLoad,OldMods}|
do_replace_module_load(OldRest,New,MP)];
match ->
get_module_load(New,MP) ++ OldRest
end;
do_replace_module_load([Other|Rest],New,MP) ->
[Other|do_replace_module_load(Rest,New,MP)];
do_replace_module_load([],_,_) ->
[].
get_module_load([{path,[AppPath]},{primLoad,Mods}|Rest],MP) ->
case re:run(AppPath,MP,[{capture,none}]) of
nomatch ->
get_module_load(Rest,MP);
match ->
[{path,[AppPath]},{primLoad,Mods}]
end;
get_module_load([_|Rest],MP) ->
get_module_load(Rest,MP);
get_module_load([],_) ->
[].
replace_paths([{path,OldPaths}|Old],New,MatchPaths) ->
{path,NewPath} = lists:keyfind(path,1,New),
[{path,do_replace_paths(OldPaths,NewPath,MatchPaths)}|Old];
replace_paths([Other|Old],New,MatchPaths) ->
[Other|replace_paths(Old,New,MatchPaths)].
do_replace_paths(Old,New,[MP|MatchPaths]) ->
do_replace_paths(do_replace_paths1(Old,New,MP),New,MatchPaths);
do_replace_paths(Paths,_,[]) ->
Paths.
do_replace_paths1([P|Ps],New,MP) ->
case re:run(P,MP,[{capture,none}]) of
nomatch ->
[P|do_replace_paths1(Ps,New,MP)];
match ->
get_path(New,MP) ++ Ps
end;
do_replace_paths1([],_,_) ->
[].
get_path([P|Ps],MP) ->
case re:run(P,MP,[{capture,none}]) of
nomatch ->
get_path(Ps,MP);
match ->
[P]
end;
get_path([],_) ->
[].
get_apps([{apply,{application,load,[{application,stdlib,_}]}}=Stdlib|Script],
_,Sasl) ->
get_apps(Script,Stdlib,Sasl);
get_apps([{apply,{application,load,[{application,sasl,_}]}}=Sasl|_Script],
Stdlib,_) ->
{Stdlib,Sasl};
get_apps([_|Script],Stdlib,Sasl) ->
get_apps(Script,Stdlib,Sasl);
get_apps([],undefined,_) ->
throw({error,{app_not_found,stdlib}});
get_apps([],_,undefined) ->
throw({error,{app_not_found,sasl}}).
replace_apps([{apply,{application,load,[{application,stdlib,_}]}}|Script],
Stdlib,Sasl) ->
[Stdlib|replace_apps(Script,undefined,Sasl)];
replace_apps([{apply,{application,load,[{application,sasl,_}]}}|Script],
_Stdlib,Sasl) ->
[Sasl|Script];
replace_apps([Stuff|Script],Stdlib,Sasl) ->
[Stuff|replace_apps(Script,Stdlib,Sasl)];
replace_apps([],undefined,_) ->
throw({error,{app_not_replaced,sasl}});
replace_apps([],_,_) ->
throw({error,{app_not_replaced,stdlib}}).
complete the execution of the upgrade script ( relup ) .
add_apply_upgrade(Script,Args) ->
[{progress, started} | RevScript] = lists:reverse(Script),
lists:reverse([{progress,started},
{apply,{release_handler,new_emulator_upgrade,Args}} |
RevScript]).
, [ src , include , examples , .. ] } | { erts , ErtsDir } where path
{ variables,[{Name , } ] }
{ var_tar , include | ownfile | omit }
warnings_as_errors
Variable1.tar.gz
VariableN.tar.gz
relup
make_tar(RelName) when is_list(RelName) ->
make_tar(RelName, []);
make_tar(RelName) ->
badarg(RelName,[RelName]).
make_tar(RelName, Flags) when is_list(RelName), is_list(Flags) ->
case check_args_tar(Flags) of
[] ->
Path0 = get_path(Flags),
Path1 = mk_path(Path0),
Path = make_set(Path1 ++ code:get_path()),
ModTestP = {member(src_tests, Flags),xref_p(Flags)},
case get_release(RelName, Path, ModTestP) of
{ok, Release, Appls, Warnings0} ->
Warnings = wsasl(Flags, Warnings0),
case systools_lib:werror(Flags, Warnings) of
true ->
Warnings1 = [W || {warning,W}<-Warnings],
return({error,?MODULE,
{warnings_treated_as_errors,Warnings1}},
Warnings,
Flags);
false ->
case catch mk_tar(RelName, Release, Appls, Flags, Path1) of
ok ->
return(ok,Warnings,Flags);
Error ->
return(Error,Warnings,Flags)
end
end;
Error ->
return(Error,[],Flags)
end;
ErrorVars ->
badarg(ErrorVars, [RelName, Flags])
end;
make_tar(RelName, Flags) when is_list(Flags) ->
badarg(RelName,[RelName, Flags]);
make_tar(RelName, Flags) ->
badarg(Flags,[RelName, Flags]).
get_release(File , Path , ) - >
get_release(File, Path) ->
get_release(File, Path, {false,false}).
get_release(File, Path, ModTestP) ->
case catch get_release1(File, Path, ModTestP) of
{error, Error} ->
{error, ?MODULE, Error};
{'EXIT', Why} ->
{error, ?MODULE, {'EXIT',Why}};
Answer ->
Answer
end.
get_release1(File, Path, ModTestP) ->
{ok, Release, Warnings1} = read_release(File, Path),
{ok, Appls0} = collect_applications(Release, Path),
{ok, Appls1} = check_applications(Appls0),
OTP-4121 , OTP-9984
{ok, Warnings2} = check_modules(Appls2, Path, ModTestP),
{ok, Appls} = sort_appls(Appls2),
{ok, Release, Appls, Warnings1 ++ Warnings2}.
read_release(File, Path) ->
case read_file(File ++ ".rel", ["."|Path]) of
{ok, Release, _FullName} ->
check_rel(Release);
{error,Error} ->
throw({error,?MODULE,Error})
end.
check_rel(Release) ->
case catch check_rel1(Release) of
{ok, {Name,Vsn,Evsn,Appl,Incl}, Ws} ->
{ok, #release{name=Name, vsn=Vsn,
erts_vsn=Evsn,
applications=Appl,
incl_apps=Incl},
Ws};
{error, Error} ->
throw({error,?MODULE,Error});
Error ->
throw({error,?MODULE,Error})
end.
check_rel1({release,{Name,Vsn},{erts,EVsn},Appl}) when is_list(Appl) ->
Name = check_name(Name),
Vsn = check_vsn(Vsn),
EVsn = check_evsn(EVsn),
{{Appls,Incls},Ws} = check_appl(Appl),
{ok, {Name,Vsn,EVsn,Appls,Incls},Ws};
check_rel1(_) ->
{error, badly_formatted_release}.
check_name(Name) ->
case string_p(Name) of
true ->
Name;
_ ->
throw({error,{illegal_name, Name}})
end.
check_vsn(Vsn) ->
case string_p(Vsn) of
true ->
Vsn;
_ ->
throw({error,{illegal_form, Vsn}})
end.
check_evsn(Vsn) ->
case string_p(Vsn) of
true ->
Vsn;
_ ->
throw({error,{illegal_form, {erts,Vsn}}})
end.
check_appl(Appl) ->
case filter(fun({App,Vsn}) when is_atom(App) ->
not string_p(Vsn);
({App,Vsn,Incl}) when is_atom(App), is_list(Incl) ->
case {string_p(Vsn), a_list_p(Incl)} of
{true, true} -> false;
_ -> true
end;
({App,Vsn,Type}) when is_atom(App), is_atom(Type) ->
case {string_p(Vsn), is_app_type(Type)} of
{true, true} -> false;
_ -> true
end;
({App,Vsn,Type,Incl}) when is_atom(App),
is_atom(Type),
is_list(Incl) ->
case {string_p(Vsn),is_app_type(Type),a_list_p(Incl)} of
{true, true, true} -> false;
_ -> true
end;
(_) ->
true
end,
Appl) of
[] ->
{ApplsNoIncls,Incls} = split_app_incl(Appl),
{ok,Ws} = mandatory_applications(ApplsNoIncls,undefined,
undefined,undefined),
{{ApplsNoIncls,Incls},Ws};
Illegal ->
throw({error, {illegal_applications,Illegal}})
end.
mandatory_applications([{kernel,_,Type}|Apps],undefined,Stdlib,Sasl) ->
mandatory_applications(Apps,Type,Stdlib,Sasl);
mandatory_applications([{stdlib,_,Type}|Apps],Kernel,undefined,Sasl) ->
mandatory_applications(Apps,Kernel,Type,Sasl);
mandatory_applications([{sasl,_,Type}|Apps],Kernel,Stdlib,undefined) ->
mandatory_applications(Apps,Kernel,Stdlib,Type);
mandatory_applications([_|Apps],Kernel,Stdlib,Sasl) ->
mandatory_applications(Apps,Kernel,Stdlib,Sasl);
mandatory_applications([],Type,_,_) when Type=/=permanent ->
error_mandatory_application(kernel,Type);
mandatory_applications([],_,Type,_) when Type=/=permanent ->
error_mandatory_application(stdlib,Type);
mandatory_applications([],_,_,undefined) ->
{ok, [{warning,missing_sasl}]};
mandatory_applications([],_,_,_) ->
{ok,[]}.
error_mandatory_application(App,undefined) ->
throw({error, {missing_mandatory_app, App}});
error_mandatory_application(App,Type) ->
throw({error, {mandatory_app, App, Type}}).
split_app_incl(Appl) -> split_app_incl(Appl, [], []).
split_app_incl([{App,Vsn}|Appls], Apps, Incls) ->
split_app_incl(Appls, [{App,Vsn,permanent}|Apps], Incls);
split_app_incl([{App,Vsn,Incl}|Appls], Apps,Incls) when is_list(Incl) ->
split_app_incl(Appls, [{App,Vsn,permanent}|Apps], [{App,Incl}|Incls]);
split_app_incl([{App,Vsn,Type}|Appls], Apps, Incls) ->
split_app_incl(Appls, [{App,Vsn,Type}|Apps], Incls);
split_app_incl([{App,Vsn,Type,Incl}|Appls], Apps, Incls) when is_list(Incl) ->
split_app_incl(Appls, [{App,Vsn,Type}|Apps], [{App,Incl}|Incls]);
split_app_incl([], Apps, Incls) ->
{reverse(Apps),reverse(Incls)}.
collect_applications(Release, Path) ->
Appls = Release#release.applications,
Incls = Release#release.incl_apps,
X = foldl(fun({Name,Vsn,Type}, {Ok, Errs}) ->
case read_application(to_list(Name), Vsn, Path, Incls) of
{ok, A} ->
case {A#application.name,A#application.vsn} of
{Name,Vsn} ->
{[{{Name,Vsn}, A#application{type=Type}} | Ok],
Errs};
E ->
{Ok, [{bad_application_name, {Name, E}} | Errs]}
end;
{error, What} ->
{Ok, [{error_reading, {Name, What}} | Errs]}
end
end, {[],[]}, Appls),
case X of
{A, []} ->
{ok, reverse(A)};
{_, Errs} ->
throw({error, Errs})
end.
read_application(Name , Vsn , Path , Incls ) - > { ok , # release } | { error , What }
read_application(Name, Vsn, Path, Incls) ->
read_application(Name, Vsn, Path, Incls, false, no_fault).
read_application(Name, Vsn, [Dir|Path], Incls, Found, FirstError) ->
case read_file(Name ++ ".app", [Dir]) of
{ok, Term, FullName} ->
case parse_application(Term, FullName, Vsn, Incls) of
{error, {no_valid_version, {Vsn, OtherVsn}}} when FirstError == no_fault ->
NFE = {no_valid_version, {{"should be", Vsn},
{"found file", filename:join(Dir, Name++".app"),
OtherVsn}}},
read_application(Name, Vsn, Path, Incls, true, NFE);
{error, {no_valid_version, {Vsn, _OtherVsn}}} ->
read_application(Name, Vsn, Path, Incls, true, FirstError);
Res ->
Res
end;
{error, {parse, _File, {Line, _Mod, Err}}} when FirstError == no_fault ->
read_application(Name, Vsn, Path, Incls, Found,
{parse_error, {filename:join(Dir, Name++".app"), Line, Err}});
{error, {parse, _File, _Err}} ->
read_application(Name, Vsn, Path, Incls, Found, FirstError);
read_application(Name, Vsn, Path, Incls, Found, FirstError)
end;
read_application(Name, Vsn, [], _, true, no_fault) ->
{error, {application_vsn, {Name,Vsn}}};
read_application(_Name, _Vsn, [], _, true, FirstError) ->
{error, FirstError};
read_application(Name, _, [], _, _, no_fault) ->
{error, {not_found, Name ++ ".app"}};
read_application(_Name, _, [], _, _, FirstError) ->
{error, FirstError}.
parse_application({application, Name, Dict}, File, Vsn, Incls)
when is_atom(Name),
is_list(Dict) ->
Items = [vsn,id,description,modules,registered,applications,
optional_applications,included_applications,mod,start_phases,env,maxT,maxP],
case catch get_items(Items, Dict) of
[Vsn,Id,Desc,Mods,Regs,Apps,Opts,Incs0,Mod,Phases,Env,MaxT,MaxP] ->
case override_include(Name, Incs0, Incls) of
{ok, Incs} ->
{ok, #application{name=Name,
vsn=Vsn,
id=Id,
description=Desc,
modules=Mods,
uses=Apps,
optional=Opts,
includes=Incs,
regs=Regs,
mod=Mod,
start_phases=Phases,
env=Env,
maxT=MaxT,
maxP=MaxP,
dir=filename:dirname(File)}};
{error, IncApps} ->
{error, {override_include, IncApps}}
end;
[OtherVsn,_,_,_,_,_,_,_,_,_,_,_,_] ->
{error, {no_valid_version, {Vsn, OtherVsn}}};
Err ->
{error, {Err, {application, Name, Dict}}}
end;
parse_application(Other, _, _, _) ->
{error, {badly_formatted_application, Other}}.
override_include(Name, Incs, Incls) ->
case keysearch(Name, 1, Incls) of
{value, {Name, I}} ->
case specified(I, Incs) of
[] ->
{ok, I};
NotSpec ->
{error, NotSpec}
end;
_ ->
{ok, Incs}
end.
specified([App|Incls], Spec) ->
case member(App, Spec) of
true ->
specified(Incls, Spec);
_ ->
[App|specified(Incls, Spec)]
end;
specified([], _) ->
[].
get_items([H|T], Dict) ->
Item = case check_item(keysearch(H, 1, Dict),H) of
[Atom|_]=Atoms when is_atom(Atom), is_list(Atoms) ->
case Atoms =/= lists:uniq(Atoms) of
true -> throw({dupl_entry, H, lists:subtract(Atoms, lists:uniq(Atoms))});
false -> Atoms
end;
X -> X
end,
[Item|get_items(T, Dict)];
get_items([], _Dict) ->
[].
check_item({_,{mod,{M,A}}},_) when is_atom(M) ->
{M,A};
[];
check_item({_,{vsn,Vsn}},I) ->
case string_p(Vsn) of
true -> Vsn;
_ -> throw({bad_param, I})
end;
check_item({_,{id,Id}},I) ->
case string_p(Id) of
true -> Id;
_ -> throw({bad_param, I})
end;
check_item({_,{description,Desc}},I) ->
case string_p(Desc) of
true -> Desc;
_ -> throw({bad_param, I})
end;
check_item({_,{applications,Apps}},I) ->
case a_list_p(Apps) of
true -> Apps;
_ -> throw({bad_param, I})
end;
check_item({_,{optional_applications,Apps}},I) ->
case a_list_p(Apps) of
true -> Apps;
_ -> throw({bad_param, I})
end;
check_item({_,{included_applications,Apps}},I) ->
case a_list_p(Apps) of
true -> Apps;
_ -> throw({bad_param, I})
end;
check_item({_,{registered,Regs}},I) ->
case a_list_p(Regs) of
true -> Regs;
_ -> throw({bad_param, I})
end;
check_item({_,{modules,Mods}},I) ->
case a_list_p(Mods) of
true -> Mods;
_ -> throw({bad_param, I})
end;
check_item({_,{start_phases,Phase}},I) ->
case t_list_p(Phase) of
true -> Phase;
_ -> throw({bad_param, I})
end;
check_item({_,{env,Env}},I) ->
case t_list_p(Env) of
true -> Env;
_ -> throw({bad_param, I})
end;
check_item({_,{maxT,MaxT}},I) ->
case MaxT of
MaxT when is_integer(MaxT), MaxT > 0 -> MaxT;
infinity -> infinity;
_ -> throw({bad_param, I})
end;
check_item({_,{maxP,MaxP}},I) ->
case MaxP of
MaxP when is_integer(MaxP), MaxP > 0 -> MaxP;
infinity -> infinity;
_ -> throw({bad_param, I})
end;
[];
[];
[];
[];
[];
undefined;
infinity;
infinity;
check_item(_, Item) ->
throw({missing_param, Item}).
ok | throw({error , Error } )
check_applications(Appls) ->
undef_appls(Appls),
dupl_regs(Appls),
Make a list Incs = [ { Name , App , AppVsn , Dir } ]
Incs = [{IncApp,App,Appv,A#application.dir} ||
{{App,Appv},A} <- Appls,
IncApp <- A#application.includes],
dupl_incls(Incs),
Res = add_top_apps_to_uses(Incs, Appls, []),
{ok, Res}.
undef_appls(Appls) ->
case undefined_applications(Appls) of
[] ->
ok;
L ->
throw({error, {undefined_applications, make_set(L)}})
end.
dupl_regs(Appls) ->
Make a list = [ { Name , App , AppVsn , Dir } ]
Regs = [{Name,App,Appv,A#application.dir} ||
{{App,Appv},A} <- Appls,
Name <- A#application.regs],
case duplicates(Regs) of
[] ->
ok;
Dups ->
throw({error, {duplicate_register, Dups}})
end.
dupl_incls(Incs) ->
case duplicates(Incs) of
[] ->
ok;
Dups ->
throw({error, {duplicate_include, Dups}})
end.
application in the X applications uses - variable is changed to the T
add_top_apps_to_uses(_InclApps, [], Res) ->
InclApps = [ { IncApp , App , AppVsn , Dir } ]
Res;
add_top_apps_to_uses(InclApps, [{Name,Appl} | Appls], Res) ->
MyTop = find_top_app(Appl#application.name, InclApps),
F = fun(UsedApp, AccIn) when UsedApp == MyTop ->
AccIn -- [MyTop];
(UsedApp, AccIn) ->
case lists:keysearch(UsedApp, 1, InclApps) of
false ->
AccIn;
{value, {_,DependApp,_,_}} ->
UsedAppTop = find_top_app(DependApp, InclApps),
case {lists:member(UsedAppTop, AccIn), MyTop} of
{true, _} ->
list , remove UsedApp
AccIn -- [UsedApp];
{_, UsedAppTop} ->
AccIn;
_ ->
AccIn1 = AccIn -- [UsedApp],
AccIn1 ++ [UsedAppTop]
end
end
end,
NewUses = foldl(F, Appl#application.uses, Appl#application.uses),
add_top_apps_to_uses(InclApps, Appls,
Res++[{Name, Appl#application{uses = NewUses}}]).
find_top_app(App, InclApps) ->
case lists:keysearch(App, 1, InclApps) of
false ->
App;
{value, {_,TopApp,_,_}} ->
find_top_app(TopApp, InclApps)
end.
undefined_applications(Appls) ->
Uses = append(map(fun({_,A}) ->
(A#application.uses -- A#application.optional) ++
A#application.includes
end, Appls)),
Defined = map(fun({{X,_},_}) -> X end, Appls),
filter(fun(X) -> not member(X, Defined) end, Uses).
OTP-4121 , OTP-9984
upgrade instructions in relup , may end up in the wrong order .
sort_used_and_incl_appls(Applications, Release) when is_tuple(Release) ->
{ok,
sort_used_and_incl_appls(Applications, Release#release.applications)};
sort_used_and_incl_appls([{Tuple,Appl}|Appls], OrderedAppls) ->
Incls2 =
case Appl#application.includes of
Incls when length(Incls)>1 ->
sort_appl_list(Incls, OrderedAppls);
Incls ->
Incls
end,
Uses2 =
case Appl#application.uses of
Uses when length(Uses)>1 ->
sort_appl_list(Uses, OrderedAppls);
Uses ->
Uses
end,
Appl2 = Appl#application{includes=Incls2, uses=Uses2},
[{Tuple,Appl2}|sort_used_and_incl_appls(Appls, OrderedAppls)];
sort_used_and_incl_appls([], _OrderedAppls) ->
[].
sort_appl_list(List, Order) ->
IndexedList = find_pos(List, Order),
SortedIndexedList = lists:keysort(1, IndexedList),
lists:map(fun({_Index,Name}) -> Name end, SortedIndexedList).
find_pos([Name|Incs], OrderedAppls) ->
[find_pos(1, Name, OrderedAppls)|find_pos(Incs, OrderedAppls)];
find_pos([], _OrderedAppls) ->
[].
find_pos(N, Name, [{Name,_Vsn,_Type}|_OrderedAppls]) ->
{N, Name};
find_pos(N, Name, [_OtherAppl|OrderedAppls]) ->
find_pos(N+1, Name, OrderedAppls);
find_pos(_N, Name, []) ->
{optional, Name}.
where = [ { App , , # application } ]
check_modules(Appls, Path, TestP) ->
first check that all the module names are unique
Make a list M1 = [ { Mod , App , Dir } ]
M1 = [{Mod,App,A#application.dir} ||
{{App,_Appv},A} <- Appls,
Mod <- A#application.modules],
case duplicates(M1) of
[] ->
case check_mods(M1, Appls, Path, TestP) of
{error, Errors} ->
throw({error, {modules, Errors}});
Return ->
Return
end;
Dups ->
throw({error, {duplicate_modules, Dups}})
end.
check_mods(Modules, Appls, Path, {SrcTestP, XrefP}) ->
SrcTestRes = check_src(Modules, Appls, Path, SrcTestP),
XrefRes = check_xref(Appls, Path, XrefP),
Res = SrcTestRes ++ XrefRes,
case filter(fun({error, _}) -> true;
(_) -> false
end,
Res) of
[] ->
{ok, filter(fun({warning, _}) -> true;
(_) -> false
end,
Res)};
Errors ->
{error, Errors}
end.
check_src(Modules, Appls, Path, true) ->
Ext = code:objfile_extension(),
IncPath = create_include_path(Appls, Path),
append(map(fun(ModT) ->
{Mod,App,Dir} = ModT,
case check_mod(Mod,App,Dir,Ext,IncPath) of
ok ->
[];
{error, Error} ->
[{error,{Error, ModT}}];
{warning, Warn} ->
[{warning,{Warn,ModT}}]
end
end,
Modules));
check_src(_, _, _, _) ->
[].
check_xref(_Appls, _Path, false) ->
[];
check_xref(Appls, Path, XrefP) ->
AppDirsL = [{App,A#application.dir} || {{App,_Appv},A} <- Appls],
AppDirs0 = sofs:relation(AppDirsL),
AppDirs = case XrefP of
true ->
AppDirs0;
{true, Apps} ->
sofs:restriction(AppDirs0, sofs:set(Apps))
end,
XrefArgs = [{xref_mode, modules}],
case catch xref:start(?XREF_SERVER, XrefArgs) of
{ok, _Pid} ->
ok;
{error, {already_started, _Pid}} ->
{ok,_} = xref:start(?XREF_SERVER, XrefArgs),
ok
end,
{ok, _} = xref:set_default(?XREF_SERVER, verbose, false),
LibPath = case Path == code:get_path() of
false -> Path
end,
ok = xref:set_library_path(?XREF_SERVER, LibPath),
check_xref(sofs:to_external(AppDirs)).
check_xref([{App,AppDir} | Appls]) ->
case xref:add_application(?XREF_SERVER, AppDir, {name,App}) of
{ok, _App} ->
check_xref(Appls);
Error ->
xref:stop(?XREF_SERVER),
[{error, Error}]
end;
check_xref([]) ->
R = case xref:analyze(?XREF_SERVER, undefined_functions) of
{ok, []} ->
[];
{ok, Undefined} ->
[{warning, {exref_undef, Undefined}}];
Error ->
[{error, Error}]
end,
xref:stop(?XREF_SERVER),
R.
xref_p(Flags) ->
case member(exref, Flags) of
true ->
exists_xref(true);
_ ->
case get_flag(exref, Flags) of
{exref, Appls} when is_list(Appls) ->
case a_list_p(Appls) of
true -> exists_xref({true, Appls});
_ -> false
end;
_ ->
false
end
end.
exists_xref(Flag) ->
case code:ensure_loaded(xref) of
{error, _} -> false;
_ -> Flag
end.
check_mod(Mod,App,Dir,Ext,IncPath) ->
ObjFile = mod_to_filename(Dir, Mod, Ext),
case file:read_file_info(ObjFile) of
{ok,FileInfo} ->
LastModTime = FileInfo#file_info.mtime,
check_module(Mod, Dir, LastModTime, IncPath);
_ ->
{error, {module_not_found, App, Mod}}
end.
mod_to_filename(Dir, Mod, Ext) ->
filename:join(Dir, atom_to_list(Mod) ++ Ext).
check_module(Mod, Dir, ObjModTime, IncPath) ->
{SrcDirs,_IncDirs}= smart_guess(Dir,IncPath),
case locate_src(Mod,SrcDirs) of
{ok,_FDir,_File,LastModTime} ->
if
LastModTime > ObjModTime ->
{warning, obj_out_of_date};
true ->
ok
end;
_ ->
{warning, source_not_found}
end.
locate_src(Mod,[Dir|Dirs]) ->
File = mod_to_filename(Dir, Mod, ".erl"),
case file:read_file_info(File) of
{ok,FileInfo} ->
LastModTime = FileInfo#file_info.mtime,
{ok,Dir,File,LastModTime};
_ ->
locate_src(Mod,Dirs)
end;
locate_src(_,[]) ->
false.
smart_guess(Mod , , IncludePath ) - > { [ Dirs],[IncDirs ] }
If dir does not contain ... /ebin set to the same directory .
smart_guess(Dir,IncPath) ->
case reverse(filename:split(Dir)) of
["ebin"|D] ->
D1 = reverse(D),
Dirs = [filename:join(D1 ++ ["src"]),
filename:join(D1 ++ ["src", "e_src"])],
RecurseDirs = add_subdirs(Dirs),
{RecurseDirs,RecurseDirs ++ IncPath};
_ ->
{[Dir],[Dir] ++ IncPath}
end.
] ) - > [ Dirs ]
nested directories . One example within OTP is the ` wx ' application ,
add_subdirs([]) ->
[];
add_subdirs([Dir|Dirs]) ->
case filelib:is_dir(Dir) of
false ->
add_subdirs(Dirs) ++ [Dir];
true ->
SubDirs = [File || File <- filelib:wildcard(filename:join(Dir, "**")),
filelib:is_dir(File)],
[Dir|SubDirs] ++ add_subdirs(Dirs)
end.
generate_script(Output, Release, Appls, Flags) ->
PathFlag = path_flag(Flags),
Variables = get_variables(Flags),
Preloaded = preloaded(),
Mandatory = mandatory_modules(),
Script = {script, {Release#release.name,Release#release.vsn},
[{preLoaded, Preloaded},
{progress, preloaded},
{path, create_mandatory_path(Appls, PathFlag, Variables)},
{primLoad, Mandatory},
{kernel_load_completed},
{progress, kernel_load_completed}] ++
load_appl_mods(Appls, Mandatory ++ Preloaded,
PathFlag, Variables) ++
[{path, create_path(Appls, PathFlag, Variables)}] ++
create_kernel_procs(Appls) ++
create_load_appls(Appls) ++
create_start_appls(Appls) ++
script_end(lists:member(no_dot_erlang, Flags))
},
ScriptFile = Output ++ ".script",
case file:open(ScriptFile, [write,{encoding,utf8}]) of
{ok, Fd} ->
io:format(Fd, "%% ~s\n~tp.\n",
[epp:encoding_to_string(utf8), Script]),
case file:close(Fd) of
ok ->
BootFile = Output ++ ".boot",
case file:write_file(BootFile, term_to_binary(Script)) of
ok ->
ok;
{error, Reason} ->
{error, ?MODULE, {open,BootFile,Reason}}
end;
{error, Reason} ->
{error, ?MODULE, {close,ScriptFile,Reason}}
end;
{error, Reason} ->
{error, ?MODULE, {open,ScriptFile,Reason}}
end.
path_flag(Flags) ->
case {member(local,Flags), member(otp_build, Flags)} of
{true, _} -> local;
{_, true} -> otp_build;
{_, _} -> true
end.
get_variables(Flags) ->
case get_flag(variables, Flags) of
{variables, Variables} when is_list(Variables) ->
valid_variables(Variables);
_ ->
[]
end.
valid_variables([{Var,Path}|Variables]) when is_list(Var), is_list(Path) ->
[{Var,rm_tlsl(Path)}|valid_variables(Variables)];
valid_variables([{Var,Path}|Variables]) when is_atom(Var), is_list(Path) ->
[{to_list(Var),rm_tlsl(Path)}|valid_variables(Variables)];
valid_variables([_|Variables]) ->
valid_variables(Variables);
valid_variables(_) ->
[].
rm_tlsl(P) -> rm_tlsl1(reverse(P)).
rm_tlsl1([$/|P]) -> rm_tlsl1(P);
rm_tlsl1(P) -> reverse(P).
create_start_appls(Appls) ->
Included = append(map(fun({_,A}) ->
A#application.includes
end, Appls)),
create_start_appls(Appls, Included).
create_start_appls([{_,A}|T], Incl) ->
App = A#application.name,
case lists:member(App, Incl) of
false when A#application.type == none ->
create_start_appls(T, Incl);
false when A#application.type == load ->
create_start_appls(T, Incl);
false ->
[{apply, {application, start_boot, [App,A#application.type]}} |
create_start_appls(T, Incl)];
_ ->
create_start_appls(T, Incl)
end;
create_start_appls([], _) ->
[].
create_load_appls(T);
create_load_appls([{_,A}|T]) when A#application.type == none ->
create_load_appls(T);
create_load_appls([{_,A}|T]) ->
[{apply, {application, load, [pack_app(A)]}} |
create_load_appls(T)];
create_load_appls([]) ->
[{progress, applications_loaded}].
[{apply, {c, erlangrc, []}},
{progress, started}];
[{progress, started}].
Function : sort_appls(Appls ) - > { ok , ' } | throw({error , Error } )
Types : Appls = { { Name , , # application } ]
Alg . written by ( )
Mod . by mbj
sort_appls(Appls) -> {ok, sort_appls(Appls, [], [], [])}.
sort_appls([{N, A}|T], Missing, Circular, Visited) ->
{Name,_Vsn} = N,
{Uses, T1, NotFnd1} = find_all(Name, lists:reverse(A#application.uses),
T, Visited, [], []),
{Incs, T2, NotFnd2} = find_all(Name, lists:reverse(A#application.includes),
T1, Visited, [], []),
Missing1 = (NotFnd1 -- A#application.optional) ++ NotFnd2 ++ Missing,
case Uses ++ Incs of
[] ->
[{N, A}|sort_appls(T, Missing1, Circular, [N|Visited])];
L ->
Check if we have already taken care of some app in L ,
NewCircular = [N1 || {N1, _} <- L, N2 <- Visited, N1 == N2],
Circular1 = case NewCircular of
[] -> Circular;
_ -> [N | NewCircular] ++ Circular
end,
in L added before N.
Apps = del_apps(NewCircular, L ++ [{N, A}|T2]),
sort_appls(Apps, Missing1, Circular1, [N|Visited])
end;
sort_appls([], [], [], _) ->
[];
sort_appls([], Missing, [], _) ->
throw({error, {undefined_applications, make_set(Missing)}});
sort_appls([], [], Circular, _) ->
throw({error, {circular_dependencies, make_set(Circular)}});
sort_appls([], Missing, Circular, _) ->
throw({error, {apps, [{circular_dependencies, make_set(Circular)},
{undefined_applications, make_set(Missing)}]}}).
find_all(CheckingApp, [Name|T], L, Visited, Found, NotFound) ->
case find_app(Name, L) of
{value, App} ->
{_A,R} = App,
X includes Y , Y uses X.
case lists:member(CheckingApp, R#application.includes) of
true ->
case lists:keymember(Name, 1, Visited) of
true ->
find_all(CheckingApp, T, L, Visited, Found, NotFound);
false ->
find_all(CheckingApp, T, L, Visited, Found, [Name|NotFound])
end;
false ->
find_all(CheckingApp, T, L -- [App], Visited, [App|Found], NotFound)
end;
false ->
case lists:keymember(Name, 1, Visited) of
true ->
find_all(CheckingApp, T, L, Visited, Found, NotFound);
false ->
find_all(CheckingApp, T, L, Visited, Found, [Name|NotFound])
end
end;
find_all(_CheckingApp, [], L, _Visited, Found, NotFound) ->
{Found, L, NotFound}.
find_app(Name, [{{Name,Vsn}, Application}|_]) ->
{value, {{Name,Vsn},Application}};
find_app(Name, [_|T]) ->
find_app(Name, T);
find_app(_Name, []) ->
false.
del_apps([Name|T], L) ->
del_apps(T, lists:keydelete(Name, 1, L));
del_apps([], L) ->
L.
If PathFlag is true a script intended to be used as a complete
create_path(Appls, PathFlag, Variables) ->
make_set(map(fun({{Name,Vsn},App}) ->
cr_path(Name, Vsn, App, PathFlag, Variables)
end,
Appls)).
( The otp_build flag is only used for OTP internal system make )
cr_path(Name, Vsn, _, true, []) ->
filename:join(["$ROOT", "lib", to_list(Name) ++ "-" ++ Vsn, "ebin"]);
cr_path(Name, Vsn, App, true, Variables) ->
Dir = App#application.dir,
N = to_list(Name),
Tail = [N ++ "-" ++ Vsn, "ebin"],
case variable_dir(Dir, N, Vsn, Variables) of
{ok, VarDir} ->
filename:join([VarDir] ++ Tail);
_ ->
filename:join(["$ROOT", "lib"] ++ Tail)
end;
cr_path(Name, _, _, otp_build, _) ->
filename:join(["$ROOT", "lib", to_list(Name), "ebin"]);
cr_path(_, _, App, _, _) ->
filename:absname(App#application.dir).
variable_dir(Dir, Name, Vsn, [{Var,Path}|Variables]) ->
case lists:prefix(Path,Dir) of
true ->
D0 = strip_prefix(Path, Dir),
case strip_name_ebin(D0, Name, Vsn) of
{ok, D} ->
{ok, filename:join(["\$" ++ Var] ++ D)};
_ ->
{ok, filename:join(["\$" ++ Var] ++ D0)}
end;
_ ->
variable_dir(Dir, Name, Vsn, Variables)
end;
variable_dir(_Dir, _, _, []) ->
false.
strip_prefix(Path, Dir) ->
L = length(filename:split(Path)),
lists:nthtail(L, filename:split(Dir)).
strip_name_ebin(Dir, Name, Vsn) ->
FullName = Name ++ "-" ++ Vsn,
case reverse(Dir) of
["ebin",Name|D] -> {ok, reverse(D)};
["ebin",FullName|D] -> {ok, reverse(D)};
_ -> false
end.
create_mandatory_path(Appls, PathFlag, Variables) ->
Dirs = [kernel, stdlib],
make_set(map(fun({{Name,Vsn}, A}) ->
case lists:member(Name, Dirs) of
true ->
cr_path(Name, Vsn, A, PathFlag, Variables);
_ ->
""
end
end,
Appls)).
load_appl_mods([{{Name,Vsn},A}|Appls], Mand, PathFlag, Variables) ->
Mods = A#application.modules,
load_commands(filter(fun(Mod) -> not member(Mod, Mand) end, Mods),
cr_path(Name, Vsn, A, PathFlag, Variables)) ++
load_appl_mods(Appls, Mand, PathFlag, Variables);
[ { path , [ cr_path(Name , , A , PathFlag , Variables ) ] } ,
{ primLoad , filter(fun(Mod ) - > not member(Mod , ) end , Mods ) } |
load_appl_mods(Appls , , PathFlag , Variables ) ] ;
load_appl_mods([], _, _, _) ->
[{progress, modules_loaded}].
load_commands(Mods, Path) ->
[{path, [filename:join([Path])]},
{primLoad,lists:sort(Mods)}].
pack_app(#application{name=Name,vsn=V,id=Id,description=D,modules=M,
uses=App,optional=Opts,includes=Incs,regs=Regs,mod=Mod,start_phases=SF,
env=Env,maxT=MaxT,maxP=MaxP}) ->
{application, Name,
[{description,D},
{vsn,V},
{id,Id},
{modules, M},
{registered, Regs},
{applications, App},
{optional_applications, Opts},
{included_applications, Incs},
{env, Env},
{maxT, MaxT},
{maxP, MaxP} |
behave([{start_phases,SF},{mod,Mod}])]}.
behave([{mod,[]}|T]) ->
behave(T);
behave([{start_phases,undefined}|T]) ->
behave(T);
behave([H|T]) ->
[H|behave(T)];
behave([]) ->
[].
mandatory_modules() ->
application,
application_controller,
application_master,
code,
code_server,
erl_eval,
erl_lint,
erl_parse,
error_logger,
ets,
file,
filename,
file_server,
file_io_server,
gen,
gen_event,
gen_server,
heart,
kernel,
logger,
logger_filters,
logger_server,
logger_backend,
logger_config,
logger_simple_h,
lists,
proc_lib,
supervisor
].
This is the modules that are preloaded into the Erlang system .
preloaded() ->
lists:sort(
?ESOCK_MODS ++
[atomics,counters,erl_init,erl_prim_loader,erl_tracer,erlang,
erts_code_purger,erts_dirty_process_signal_handler,
erts_internal,erts_literal_area_collector,
init,persistent_term,prim_buffer,prim_eval,prim_file,
prim_inet,prim_zip,zlib]).
This is the erts binaries that should * not * be part of a systool : make_tar package
erts_binary_filter() ->
Cmds = ["typer", "dialyzer", "ct_run", "yielding_c_fun", "erlc"],
case os:type() of
{unix,_} -> Cmds;
{win32,_} -> [ [Cmd, ".exe"] || Cmd <- Cmds]
end.
kernel_processes ( ) - > [ { Name , Mod , Func , } ]
where is a term or a fun taking the list of applications as arg .
kernel_processes() ->
[{heart, heart, start, []},
{logger, logger_server, start_link, []},
{application_controller, application_controller, start,
fun(Appls) ->
[{_,App}] = filter(fun({{kernel,_},_App}) -> true;
(_) -> false
end,
Appls),
[pack_app(App)]
end}
].
create_kernel_procs(Appls) ->
map(fun({Name,Mod,Func,Args}) when is_function(Args) ->
{kernelProcess, Name, {Mod, Func, Args(Appls)}};
({Name,Mod,Func,Args}) ->
{kernelProcess, Name, {Mod, Func, Args}}
end,
kernel_processes()) ++
[{progress, init_kernel_started}].
Variable1.tar.gz
VariableN.tar.gz
relup
The VariableN.tar.gz files can also be stored as own files not
mk_tar(RelName, Release, Appls, Flags, Path1) ->
TarName = case get_outdir(Flags) of
"" ->
RelName ++ ".tar.gz";
OutDir ->
filename:join(OutDir, filename:basename(RelName))
++ ".tar.gz"
end,
Tar = open_main_tar(TarName),
case catch mk_tar(Tar, RelName, Release, Appls, Flags, Path1) of
{error,Error} ->
_ = del_tar(Tar, TarName),
{error,?MODULE,Error};
{'EXIT',Reason} ->
_ = del_tar(Tar, TarName),
{error,?MODULE,Reason};
_ ->
case erl_tar:close(Tar) of
ok -> ok;
{error,Reason} -> {error,?MODULE,{close,TarName,Reason}}
end
end.
open_main_tar(TarName) ->
case catch open_tar(TarName) of
{error, Error} ->
throw({error,?MODULE,Error});
Tar ->
Tar
end.
mk_tar(Tar, RelName, Release, Appls, Flags, Path1) ->
Variables = get_variables(Flags),
add_applications(Appls, Tar, Variables, Flags, false),
add_variable_tars(Variables, Appls, Tar, Flags),
add_system_files(Tar, RelName, Release, Path1),
add_erts_bin(Tar, Release, Flags),
add_additional_files(Tar, Flags).
add_additional_files(Tar, Flags) ->
case get_flag(extra_files, Flags) of
{extra_files, ToAdd} ->
[add_to_tar(Tar, From, To) || {From, To} <- ToAdd];
_ ->
ok
end.
add_applications(Appls, Tar, Variables, Flags, Var) ->
Res = foldl(fun({{Name,Vsn},App}, Errs) ->
case catch add_appl(to_list(Name), Vsn, App,
Tar, Variables, Flags, Var) of
ok ->
Errs;
{error, What} ->
[{error_add_appl, {Name,What}}|Errs]
end
end, [], Appls),
case Res of
[] ->
ok;
Errors ->
throw({error, Errors})
end.
add_variable_tars([Variable|Variables], Appls, Tar, Flags) ->
add_variable_tar(Variable, Appls, Tar, Flags),
add_variable_tars(Variables, Appls, Tar, Flags);
add_variable_tars([], _, _, _) ->
ok.
add_variable_tar({Variable,P}, Appls, Tar, Flags) ->
case var_tar_flag(Flags) of
omit ->
ok;
Flag ->
TarName = Variable ++ ".tar.gz",
VarTar = open_tar(TarName),
case catch add_applications(Appls, VarTar, [{Variable,P}],
Flags, Variable) of
ok when Flag == include ->
close_tar(VarTar,TarName),
add_to_tar(Tar, TarName, TarName),
del_file(TarName);
ok when Flag == ownfile ->
close_tar(VarTar,TarName);
Error ->
_ = del_tar(VarTar, TarName),
throw(Error)
end
end.
var_tar_flag(Flags) ->
case get_flag(var_tar, Flags) of
{var_tar, Flag} ->
case member(Flag, [include, ownfile, omit]) of
true -> Flag;
_ -> include
end;
_ ->
include
end.
Add all " other " files to Dir / releases / Svsn
add_system_files(Tar, RelName, Release, Path1) ->
SVsn = Release#release.vsn,
RelName0 = filename:basename(RelName),
RelVsnDir = filename:join("releases", SVsn),
1 ) releases directory - so it can be easily extracted
2 ) releases/<vsn > - so the file must not be explicitly moved
add_to_tar(Tar, RelName ++ ".rel",
filename:join("releases", RelName0 ++ ".rel")),
add_to_tar(Tar, RelName ++ ".rel",
filename:join(RelVsnDir, RelName0 ++ ".rel")),
OTP-6226 Look for the system files not only in cwd
directory as RelName , which is not necessarily the same as cwd )
but also in the path specified as an option to systools : make_tar
( but make sure to search the RelName directory and cwd first )
Path = case filename:dirname(RelName) of
"." ->
["."|Path1];
RelDir ->
[RelDir, "."|Path1]
end,
case lookup_file("start.boot", Path) of
false ->
case lookup_file(RelName0 ++ ".boot", Path) of
false ->
throw({error, {tar_error, {add, boot, RelName, enoent}}});
Boot ->
add_to_tar(Tar, Boot, filename:join(RelVsnDir, "start.boot"))
end;
Boot ->
add_to_tar(Tar, Boot, filename:join(RelVsnDir, "start.boot"))
end,
case lookup_file("relup", Path) of
false ->
ignore;
Relup ->
check_relup(Relup),
add_to_tar(Tar, Relup, filename:join(RelVsnDir, "relup"))
end,
case lookup_file("sys.config.src", Path) of
false ->
case lookup_file("sys.config", Path) of
false ->
ignore;
Sys ->
check_sys_config(Sys),
add_to_tar(Tar, Sys, filename:join(RelVsnDir, "sys.config"))
end;
SysSrc ->
add_to_tar(Tar, SysSrc, filename:join(RelVsnDir, "sys.config.src"))
end,
ok.
lookup_file(Name, [Dir|Path]) ->
File = filename:join(Dir, Name),
case filelib:is_file(File) of
true ->
File;
false ->
lookup_file(Name, Path)
end;
lookup_file(_Name, []) ->
false.
Check that relup can be parsed and has expected format
check_relup(File) ->
case file:consult(File) of
{ok,[{Vsn,UpFrom,DownTo}]} when is_list(Vsn), is_integer(hd(Vsn)),
is_list(UpFrom), is_list(DownTo) ->
ok;
{ok,_} ->
throw({error,{tar_error,{add,"relup",[invalid_format]}}});
Other ->
throw({error,{tar_error,{add,"relup",[Other]}}})
end.
check_sys_config(File) ->
case file:consult(File) of
{ok,[SysConfig]} ->
case lists:all(fun({App,KeyVals}) when is_atom(App),
is_list(KeyVals)->
true;
(OtherConfig) when is_list(OtherConfig),
is_integer(hd(OtherConfig)) ->
true;
(_) ->
false
end,
SysConfig) of
true ->
ok;
false ->
throw({error,{tar_error,
{add,"sys.config",[invalid_format]}}})
end;
{ok,_} ->
throw({error,{tar_error,{add,"sys.config",[invalid_format]}}});
Other ->
throw({error,{tar_error,{add,"sys.config",[Other]}}})
end.
add_appl(Name , , application#,Tar , Variables , Flags , Var ) - >
add_appl(Name, Vsn, App, Tar, Variables, Flags, Var) ->
AppDir = App#application.dir,
case add_to(AppDir,Name,Vsn,Variables,Var) of
false ->
ok;
{ok, ToDir} ->
ADir = appDir(AppDir),
add_priv(ADir, ToDir, Tar),
case get_flag(dirs,Flags) of
{dirs,Dirs} ->
add_dirs(ADir, Dirs, ToDir, Tar);
_ ->
ok
end,
BinDir = filename:join(ToDir, "ebin"),
add_to_tar(Tar,
filename:join(AppDir, Name ++ ".app"),
filename:join(BinDir, Name ++ ".app")),
add_modules(map(fun(Mod) -> to_list(Mod) end,
App#application.modules),
Tar,
AppDir,
BinDir,
code:objfile_extension())
end.
add_to(AppDir,Name,Vsn,Variables,Variable) ->
case var_dir(AppDir,Name,Vsn,Variables) of
{ok, Variable, RestPath} ->
{ok, filename:join(RestPath ++ [Name ++ "-" ++ Vsn])};
{ok, _, _} ->
false;
_ when Variable == false ->
{ok, filename:join("lib", Name ++ "-" ++ Vsn)};
_ ->
false
end.
var_dir(Dir, Name, Vsn, [{Var,Path}|Variables]) ->
case lists:prefix(Path,Dir) of
true ->
D0 = strip_prefix(Path, Dir),
case strip_name_ebin(D0, Name, Vsn) of
{ok, D} ->
{ok, Var, D};
_ ->
false
end;
_ ->
var_dir(Dir, Name, Vsn, Variables)
end;
var_dir(_Dir, _, _, []) ->
false.
appDir(AppDir) ->
case filename:basename(AppDir) of
"ebin" -> filename:dirname(AppDir);
_ -> AppDir
end.
add_modules(Modules, Tar, AppDir, ToDir, Ext) ->
foreach(fun(Mod) ->
add_to_tar(Tar,
filename:join(AppDir, Mod ++ Ext),
filename:join(ToDir, Mod ++ Ext))
end, Modules).
add_dirs(AppDir, Dirs, ToDir, Tar) ->
foreach(fun(Dir) -> catch add_dir(AppDir, to_list(Dir), ToDir, Tar) end,
Dirs).
add_dir(TopDir, Dir, ToDir, Tar) ->
FromD = filename:join(TopDir, Dir),
case dirp(FromD) of
true ->
add_to_tar(Tar, FromD, filename:join(ToDir, Dir));
_ ->
ok
end.
add_priv(ADir, ToDir, Tar) ->
Priv = filename:join(ADir, "priv"),
case dirp(Priv) of
true ->
add_to_tar(Tar, Priv, filename:join(ToDir, "priv"));
_ ->
ok
end.
add_erts_bin(Tar, Release, Flags) ->
case {get_flag(erts,Flags),member(erts_all,Flags)} of
{{erts,ErtsDir},true} ->
add_erts_bin(Tar, Release, ErtsDir, []);
{{erts,ErtsDir},false} ->
add_erts_bin(Tar, Release, ErtsDir, erts_binary_filter());
_ ->
ok
end.
add_erts_bin(Tar, Release, ErtsDir, Filters) ->
FlattenedFilters = [filename:flatten(Filter) || Filter <- Filters],
EVsn = Release#release.erts_vsn,
FromDir = filename:join([to_list(ErtsDir),
"erts-" ++ EVsn, "bin"]),
ToDir = filename:join("erts-" ++ EVsn, "bin"),
{ok, Bins} = file:list_dir(FromDir),
[add_to_tar(Tar, filename:join(FromDir,Bin), filename:join(ToDir,Bin))
|| Bin <- Bins, not lists:member(Bin, FlattenedFilters)],
ok.
open_tar(TarName) ->
case erl_tar:open(TarName, [write, compressed]) of
{ok, Tar} ->
Tar;
{error, Error} ->
throw({error,{tar_error, {open, TarName, Error}}})
end.
close_tar(Tar,File) ->
case erl_tar:close(Tar) of
ok -> ok;
{error,Reason} -> throw({error,{close,File,Reason}})
end.
del_tar(Tar, TarName) ->
_ = erl_tar:close(Tar),
file:delete(TarName).
add_to_tar(Tar, FromFile, ToFile) ->
case catch erl_tar:add(Tar, FromFile, ToFile, [compressed, dereference]) of
ok -> ok;
{'EXIT', Reason} ->
throw({error, {tar_error, {add, FromFile, Reason}}});
{error, Error} ->
throw({error, {tar_error, {add, FromFile, Error}}})
end.
make_set([]) -> [];
make_set(T);
make_set([H|T]) ->
[H | [ Y || Y<- make_set(T),
Y =/= H]].
to_list(A) when is_atom(A) -> atom_to_list(A);
to_list(L) -> L.
mk_path(Path0) ->
Path1 = map(fun(Dir) when is_atom(Dir) -> atom_to_list(Dir);
(Dir) -> Dir
end, Path0),
systools_lib:get_path(Path1).
duplicates(X) -> duplicates(keysort(1,X), []).
duplicates([H1,H2|T], L) ->
case {element(1,H1),element(1,H2)} of
{X,X} -> duplicates([H2|T],[{H1,H2}|L]);
_ -> duplicates([H2|T],L)
end;
duplicates(_, L) -> L.
Erlang term .
read_file(File, Path) ->
case file:path_open(Path, File, [read]) of
{ok, Stream, FullName} ->
Return = case systools_lib:read_term_from_stream(Stream, File) of
{ok, Term} ->
{ok, Term, FullName};
Other ->
Other
end,
case file:close(Stream) of
ok -> Return;
{error, Error} -> {error, {close,File,Error}}
end;
_Other ->
{error, {not_found, File}}
end.
del_file(File) ->
case file:delete(File) of
ok -> ok;
{error, Error} ->
throw({error, {delete, File, Error}})
end.
dirp(Dir) ->
case file:read_file_info(Dir) of
{ok, FileInfo} -> FileInfo#file_info.type == directory;
_ -> false
end.
Add the official include dir for each found application first in
create_include_path(Appls, Path) ->
FoundAppDirs = map(fun({_,A}) -> A#application.dir end, Appls),
map(fun(Dir) ->
case reverse(filename:split(Dir)) of
["ebin"|D] ->
filename:join(reverse(D) ++ ["include"]);
_ ->
filename:join(Dir, "include")
end
end,
FoundAppDirs ++ no_dupl(Path, FoundAppDirs)).
no_dupl([Dir|Path], FoundAppDirs) ->
case member(Dir, FoundAppDirs) of
true ->
no_dupl(Path, FoundAppDirs);
_ ->
[Dir|no_dupl(Path, FoundAppDirs)]
end;
no_dupl([], _) ->
[].
is_app_type(permanent) -> true;
is_app_type(transient) -> true;
is_app_type(temporary) -> true;
is_app_type(none) -> true;
is_app_type(load) -> true;
is_app_type(_) -> false.
string_p(S) ->
case unicode:characters_to_list(S) of
S -> true;
_ -> false
end.
check if a term is a list of two tuples with the first
t_list_p([{A,_}|T]) when is_atom(A) -> t_list_p(T);
t_list_p([]) -> true;
t_list_p(_) -> false.
a_list_p([A|T]) when is_atom(A) -> a_list_p(T);
a_list_p([]) -> true;
a_list_p(_) -> false.
get_flag(F,[{F,D}|_]) -> {F,D};
get_flag(F,[_|Fs]) -> get_flag(F,Fs);
get_flag(_,_) -> false.
check_args_script(Args) ->
cas(Args, []).
cas([], X) ->
X;
cas([{path, P} | Args], X) when is_list(P) ->
case check_path(P) of
ok ->
cas(Args, X);
error ->
cas(Args, X++[{path,P}])
end;
cas([silent | Args], X) ->
cas(Args, X);
cas([local | Args], X) ->
cas(Args, X);
cas([src_tests | Args], X) ->
cas(Args, X);
cas([{variables, V} | Args], X) when is_list(V) ->
case check_vars(V) of
ok ->
cas(Args, X);
error ->
cas(Args, X++[{variables, V}])
end;
cas([exref | Args], X) ->
cas(Args, X);
cas([{exref, Apps} | Args], X) when is_list(Apps) ->
case check_apps(Apps) of
ok ->
cas(Args, X);
error ->
cas(Args, X++[{exref, Apps}])
end;
cas([{outdir, Dir} | Args], X) when is_list(Dir) ->
cas(Args, X);
cas([otp_build | Args], X) ->
cas(Args, X);
cas([warnings_as_errors | Args], X) ->
cas(Args, X);
cas([no_warn_sasl | Args], X) ->
cas(Args, X);
cas([no_module_tests | Args], X) ->
cas(Args, X);
cas([no_dot_erlang | Args], X) ->
cas(Args, X);
cas([{script_name, Name} | Args], X) when is_list(Name) ->
cas(Args, X);
cas([Y | Args], X) ->
cas(Args, X++[Y]).
Check Options for make_tar
check_args_tar(Args) ->
cat(Args, []).
cat([], X) ->
X;
cat([{path, P} | Args], X) when is_list(P) ->
case check_path(P) of
ok ->
cat(Args, X);
error ->
cat(Args, X++[{path,P}])
end;
cat([silent | Args], X) ->
cat(Args, X);
cat([{dirs, D} | Args], X) ->
case check_dirs(D) of
ok ->
cat(Args, X);
error ->
cat(Args, X++[{dirs, D}])
end;
cat([{erts, E} | Args], X) when is_list(E)->
cat(Args, X);
cat([erts_all | Args], X) ->
cat(Args, X);
cat([src_tests | Args], X) ->
cat(Args, X);
cat([{variables, V} | Args], X) when is_list(V) ->
case check_vars(V) of
ok ->
cat(Args, X);
error ->
cat(Args, X++[{variables, V}])
end;
cat([{var_tar, VT} | Args], X) when VT == include;
VT == ownfile;
VT == omit ->
cat(Args, X);
cat([exref | Args], X) ->
cat(Args, X);
cat([{exref, Apps} | Args], X) when is_list(Apps) ->
case check_apps(Apps) of
ok ->
cat(Args, X);
error ->
cat(Args, X++[{exref, Apps}])
end;
cat([{outdir, Dir} | Args], X) when is_list(Dir) ->
cat(Args, X);
cat([otp_build | Args], X) ->
cat(Args, X);
cat([warnings_as_errors | Args], X) ->
cat(Args, X);
cat([no_warn_sasl | Args], X) ->
cat(Args, X);
cat([no_module_tests | Args], X) ->
cat(Args, X);
cat([{extra_files, ExtraFiles} | Args], X) when is_list(ExtraFiles) ->
cat(Args, X);
cat([Y | Args], X) ->
cat(Args, X++[Y]).
check_path([]) ->
ok;
check_path([H|T]) when is_list(H) ->
check_path(T);
check_path([_H|_T]) ->
error.
check_dirs([]) ->
ok;
check_dirs([H|T]) when is_atom(H) ->
check_dirs(T);
check_dirs([_H|_T]) ->
error.
check_vars([]) ->
ok;
check_vars([{Name, Dir} | T]) ->
if
is_atom(Name), is_list(Dir) ->
check_vars(T);
is_list(Name), is_list(Dir) ->
check_vars(T);
true ->
error
end;
check_vars(_) ->
error.
check_apps([]) ->
ok;
check_apps([H|T]) when is_atom(H) ->
check_apps(T);
check_apps(_) ->
error.
format_error(badly_formatted_release) ->
io_lib:format("Syntax error in the release file~n",[]);
format_error({illegal_name, Name}) ->
io_lib:format("Illegal name (~tp) in the release file~n",[Name]);
format_error({illegal_form, Form}) ->
io_lib:format("Illegal tag in the release file: ~tp~n",[Form]);
format_error({missing_parameter,Par}) ->
io_lib:format("Missing parameter (~p) in the release file~n",[Par]);
format_error({illegal_applications,Names}) ->
io_lib:format("Illegal applications in the release file: ~p~n",
[Names]);
format_error({missing_mandatory_app,Name}) ->
io_lib:format("Mandatory application ~w must be specified in the release file~n",
[Name]);
format_error({mandatory_app,Name,Type}) ->
io_lib:format("Mandatory application ~w must be of type 'permanent' in the release file. Is '~p'.~n",
[Name,Type]);
format_error({duplicate_register,Dups}) ->
io_lib:format("Duplicated register names: ~n~ts",
[map(fun({{Reg,App1,_,_},{Reg,App2,_,_}}) ->
io_lib:format("\t~tw registered in ~w and ~w~n",
[Reg,App1,App2])
end, Dups)]);
format_error({undefined_applications,Apps}) ->
io_lib:format("Undefined applications: ~p~n",[Apps]);
format_error({duplicate_modules,Dups}) ->
io_lib:format("Duplicated modules: ~n~ts",
[map(fun({{Mod,App1,_},{Mod,App2,_}}) ->
io_lib:format("\t~w specified in ~w and ~w~n",
[Mod,App1,App2])
end, Dups)]);
format_error({included_and_used, Dups}) ->
io_lib:format("Applications both used and included: ~p~n",[Dups]);
format_error({duplicate_include, Dups}) ->
io_lib:format("Duplicated application included: ~n~ts",
[map(fun({{Name,App1,_,_},{Name,App2,_,_}}) ->
io_lib:format("\t~w included in ~w and ~w~n",
[Name,App1,App2])
end, Dups)]);
format_error({modules,ModErrs}) ->
format_errors(ModErrs);
format_error({circular_dependencies,Apps}) ->
io_lib:format("Circular dependencies among applications: ~p~n",[Apps]);
format_error({not_found,File}) ->
io_lib:format("File not found: ~tp~n",[File]);
format_error({parse,File,{Line,Mod,What}}) ->
Str = Mod:format_error(What),
io_lib:format("~ts:~w: ~ts\n",[File, Line, Str]);
format_error({read,File}) ->
io_lib:format("Cannot read ~tp~n",[File]);
format_error({open,File,Error}) ->
io_lib:format("Cannot open ~tp - ~ts~n",
[File,file:format_error(Error)]);
format_error({close,File,Error}) ->
io_lib:format("Cannot close ~tp - ~ts~n",
[File,file:format_error(Error)]);
format_error({delete,File,Error}) ->
io_lib:format("Cannot delete ~tp - ~ts~n",
[File,file:format_error(Error)]);
format_error({tar_error,What}) ->
form_tar_err(What);
format_error({warnings_treated_as_errors,Warnings}) ->
io_lib:format("Warnings being treated as errors:~n~ts",
[map(fun(W) -> form_warn("",W) end, Warnings)]);
format_error(ListOfErrors) when is_list(ListOfErrors) ->
format_errors(ListOfErrors);
format_error(E) -> io_lib:format("~tp~n",[E]).
format_errors(ListOfErrors) ->
map(fun({error,E}) -> form_err(E);
(E) -> form_err(E)
end, ListOfErrors).
form_err({bad_application_name,{Name,Found}}) ->
io_lib:format("~p: Mismatched application id: ~p~n",[Name,Found]);
form_err({error_reading, {Name, What}}) ->
io_lib:format("~p: ~ts~n",[Name,form_reading(What)]);
form_err({module_not_found,App,Mod}) ->
io_lib:format("~w: Module (~w) not found~n",[App,Mod]);
form_err({error_add_appl, {Name, {tar_error, What}}}) ->
io_lib:format("~p: ~ts~n",[Name,form_tar_err(What)]);
form_err(E) ->
io_lib:format("~tp~n",[E]).
form_reading({not_found,File}) ->
io_lib:format("File not found: ~tp~n",[File]);
form_reading({application_vsn, {Name,Vsn}}) ->
io_lib:format("Application ~ts with version ~tp not found~n",[Name, Vsn]);
form_reading({parse,File,{Line,Mod,What}}) ->
Str = Mod:format_error(What),
io_lib:format("~ts:~w: ~ts\n",[File, Line, Str]);
form_reading({read,File}) ->
io_lib:format("Cannot read ~tp~n",[File]);
form_reading({{bad_param, P},_}) ->
io_lib:format("Bad parameter in .app file: ~tp~n",[P]);
form_reading({{dupl_entry, P, DE},_}) ->
io_lib:format("~tp parameter contains duplicates of: ~tp~n", [P, DE]);
form_reading({{missing_param,P},_}) ->
io_lib:format("Missing parameter in .app file: ~p~n",[P]);
form_reading({badly_formatted_application,_}) ->
io_lib:format("Syntax error in .app file~n",[]);
form_reading({override_include,Apps}) ->
io_lib:format("Tried to include not (in .app file) specified applications: ~p~n",
[Apps]);
form_reading({no_valid_version, {{_, SVsn}, {_, File, FVsn}}}) ->
io_lib:format("No valid version (~tp) of .app file found. Found file ~tp with version ~tp~n",
[SVsn, File, FVsn]);
form_reading({parse_error, {File, Line, Error}}) ->
io_lib:format("Parse error in file: ~tp. Line: ~w Error: ~tp; ~n", [File, Line, Error]);
form_reading(W) ->
io_lib:format("~tp~n",[W]).
form_tar_err({open, File, Error}) ->
io_lib:format("Cannot open tar file ~ts - ~ts~n",
[File, erl_tar:format_error(Error)]);
form_tar_err({add, boot, RelName, enoent}) ->
io_lib:format("Cannot find file start.boot or ~ts to add to tar file - ~ts~n",
[RelName, erl_tar:format_error(enoent)]);
form_tar_err({add, File, Error}) ->
io_lib:format("Cannot add file ~ts to tar file - ~ts~n",
[File, erl_tar:format_error(Error)]).
format_warning(Warnings) ->
map(fun({warning,W}) -> form_warn("*WARNING* ", W) end, Warnings).
form_warn(Prefix, {source_not_found,{Mod,App,_}}) ->
io_lib:format("~ts~w: Source code not found: ~w.erl~n",
[Prefix,App,Mod]);
form_warn(Prefix, {{parse_error, File},{_,_,App,_,_}}) ->
io_lib:format("~ts~w: Parse error: ~tp~n",
[Prefix,App,File]);
form_warn(Prefix, {obj_out_of_date,{Mod,App,_}}) ->
io_lib:format("~ts~w: Object code (~w) out of date~n",
[Prefix,App,Mod]);
form_warn(Prefix, {exref_undef, Undef}) ->
F = fun({M,F,A}) ->
io_lib:format("~tsUndefined function ~w:~tw/~w~n",
[Prefix,M,F,A])
end,
map(F, Undef);
form_warn(Prefix, missing_sasl) ->
io_lib:format("~tsMissing application sasl. "
"Can not upgrade with this release~n",
[Prefix]);
form_warn(Prefix, What) ->
io_lib:format("~ts~tp~n", [Prefix,What]).
|
1d0de20a3126cd722f5a3102d23514985a2028648435e776e0fa78f656a6a150 | aigarashi/copl-tools | pp.ml | open Format
open Core
let g = "MLi"
let pr = fprintf
(* generic functions to generate parens depending on precedence *)
let with_paren lt ppf_e e_up ppf e =
let (<) = lt in
if e < e_up then pr ppf "(%a)" ppf_e e else pr ppf "%a" ppf_e e
(* precedence for expressions *)
let rec is_last_longexp = function
BinOp(_,_,e) -> is_last_longexp e
| If(_,_,_) -> true
| _ -> false
(* if e is the left operand of e_up, do you need parentheses for e? *)
let (<) e e_up = match e, e_up with
(* mult associates stronger than plus or minus *)
BinOp((Plus | Minus | Lt), _, _), BinOp(Mult, _, _)
| BinOp(Lt, _, _), BinOp((Plus | Minus), _, _)
-> true
| e, BinOp(_, _, _) when is_last_longexp e
-> true
| _ -> false
(* if e is the right operand of e_up, do you need parentheses for e? *)
let (>) e_up e = match e_up, e with
(* mult associates stronger than plus or minus,
and bin ops are left-associative *)
BinOp(Mult, _, _), BinOp(_, _, _)
| BinOp((Plus | Minus), _, _), BinOp((Plus | Minus | Lt), _, _)
-> true
| _ -> false
let rec print_exp ppf e =
let with_paren_L = with_paren (<)
and with_paren_R = with_paren (fun e_up e -> e > e_up) in
match e with
Exp_of_int i -> pr ppf "%d" i
| Exp_of_bool b -> pp_print_string ppf (string_of_bool b)
| BinOp(p, e1, e2) ->
let op =
match p with Plus -> "+" | Minus -> "-" | Mult -> "*" | Lt -> "<" in
pr ppf "%a %s %a"
(with_paren_L print_exp e) e1
op
(with_paren_R print_exp e) e2
| If(e1, e2, e3) ->
pr ppf "if %a then %a else %a"
print_exp e1
print_exp e2
print_exp e3
let print_val ppf = function
Value_of_int i -> pr ppf "%d" i
| Value_of_bool b -> pp_print_string ppf (string_of_bool b)
let print_judgment ppf = function
EvalTo (e, v) -> pr ppf "@[@[%a@]@ evalto %a@]" print_exp e print_val v
| AppBOp (Lt, v1, v2, Value_of_bool true) ->
pr ppf "@[%a is less than %a@]" print_val v1 print_val v2
| AppBOp (Lt, v1, v2, Value_of_bool false) ->
pr ppf "@[%a is not less than %a@]" print_val v1 print_val v2
| AppBOp (p, v1, v2, v3) ->
let op = match p with Plus -> "plus" | Minus -> "minus" | Mult -> "times"
in pr ppf "@[%a %s %a is %a@]" print_val v1 op print_val v2 print_val v3
let print_pjudgment ppf = function
In_EvalTo e -> pr ppf "@[@[%a@]@ evalto ?@]" print_exp e
| In_AppBOp (Lt, v1, v2) ->
pr ppf "@[%a is less than %a ?@]" print_val v1 print_val v2
| In_AppBOp (p, v1, v2) ->
let op = match p with Plus -> "plus" | Minus -> "minus" | Mult -> "times"
in pr ppf "@[%a %s %a is ?@]" print_val v1 op print_val v2
let rec tex_exp ppf e =
let with_paren_L = with_paren (<)
and with_paren_R = with_paren (fun e_up e -> e > e_up) in
match e with
Exp_of_int i -> pr ppf "%d" i
| Exp_of_bool b -> pp_print_string ppf (string_of_bool b)
| BinOp(p, e1, e2) ->
let op =
match p with Plus -> "+" | Minus -> "-" | Mult -> "*" | Lt -> "<" in
pr ppf "\\%sBinOpTerm{%a}{%s}{%a}" g
(with_paren_L tex_exp e) e1
op
(with_paren_R tex_exp e) e2
| If(e1, e2, e3) ->
pr ppf "\\%sIfTerm{%a}{%a}{%a}" g
tex_exp e1
tex_exp e2
tex_exp e3
let tex_val ppf = function
Value_of_int i -> pr ppf "%d" i
| Value_of_bool b -> pp_print_string ppf (string_of_bool b)
let tex_judgment ppf = function
EvalTo (e, v) -> pr ppf "\\%sEvalTo{%a}{%a}" g tex_exp e tex_val v
| AppBOp (p, v1, v2, v3) ->
let op = "\\" ^ g ^ match p with
Plus -> "PlusTerm" | Minus -> "MinusTerm"
| Mult -> "MultTerm" | Lt -> "LTTerm"
in pr ppf "\\%sAppBOp{%a}{%s}{%a}{%a}"
g tex_val v1 op tex_val v2 tex_val v3
| null | https://raw.githubusercontent.com/aigarashi/copl-tools/3c4da117083a0870334c8eef270206b11060514e/checker/EvalML1/pp.ml | ocaml | generic functions to generate parens depending on precedence
precedence for expressions
if e is the left operand of e_up, do you need parentheses for e?
mult associates stronger than plus or minus
if e is the right operand of e_up, do you need parentheses for e?
mult associates stronger than plus or minus,
and bin ops are left-associative | open Format
open Core
let g = "MLi"
let pr = fprintf
let with_paren lt ppf_e e_up ppf e =
let (<) = lt in
if e < e_up then pr ppf "(%a)" ppf_e e else pr ppf "%a" ppf_e e
let rec is_last_longexp = function
BinOp(_,_,e) -> is_last_longexp e
| If(_,_,_) -> true
| _ -> false
let (<) e e_up = match e, e_up with
BinOp((Plus | Minus | Lt), _, _), BinOp(Mult, _, _)
| BinOp(Lt, _, _), BinOp((Plus | Minus), _, _)
-> true
| e, BinOp(_, _, _) when is_last_longexp e
-> true
| _ -> false
let (>) e_up e = match e_up, e with
BinOp(Mult, _, _), BinOp(_, _, _)
| BinOp((Plus | Minus), _, _), BinOp((Plus | Minus | Lt), _, _)
-> true
| _ -> false
let rec print_exp ppf e =
let with_paren_L = with_paren (<)
and with_paren_R = with_paren (fun e_up e -> e > e_up) in
match e with
Exp_of_int i -> pr ppf "%d" i
| Exp_of_bool b -> pp_print_string ppf (string_of_bool b)
| BinOp(p, e1, e2) ->
let op =
match p with Plus -> "+" | Minus -> "-" | Mult -> "*" | Lt -> "<" in
pr ppf "%a %s %a"
(with_paren_L print_exp e) e1
op
(with_paren_R print_exp e) e2
| If(e1, e2, e3) ->
pr ppf "if %a then %a else %a"
print_exp e1
print_exp e2
print_exp e3
let print_val ppf = function
Value_of_int i -> pr ppf "%d" i
| Value_of_bool b -> pp_print_string ppf (string_of_bool b)
let print_judgment ppf = function
EvalTo (e, v) -> pr ppf "@[@[%a@]@ evalto %a@]" print_exp e print_val v
| AppBOp (Lt, v1, v2, Value_of_bool true) ->
pr ppf "@[%a is less than %a@]" print_val v1 print_val v2
| AppBOp (Lt, v1, v2, Value_of_bool false) ->
pr ppf "@[%a is not less than %a@]" print_val v1 print_val v2
| AppBOp (p, v1, v2, v3) ->
let op = match p with Plus -> "plus" | Minus -> "minus" | Mult -> "times"
in pr ppf "@[%a %s %a is %a@]" print_val v1 op print_val v2 print_val v3
let print_pjudgment ppf = function
In_EvalTo e -> pr ppf "@[@[%a@]@ evalto ?@]" print_exp e
| In_AppBOp (Lt, v1, v2) ->
pr ppf "@[%a is less than %a ?@]" print_val v1 print_val v2
| In_AppBOp (p, v1, v2) ->
let op = match p with Plus -> "plus" | Minus -> "minus" | Mult -> "times"
in pr ppf "@[%a %s %a is ?@]" print_val v1 op print_val v2
let rec tex_exp ppf e =
let with_paren_L = with_paren (<)
and with_paren_R = with_paren (fun e_up e -> e > e_up) in
match e with
Exp_of_int i -> pr ppf "%d" i
| Exp_of_bool b -> pp_print_string ppf (string_of_bool b)
| BinOp(p, e1, e2) ->
let op =
match p with Plus -> "+" | Minus -> "-" | Mult -> "*" | Lt -> "<" in
pr ppf "\\%sBinOpTerm{%a}{%s}{%a}" g
(with_paren_L tex_exp e) e1
op
(with_paren_R tex_exp e) e2
| If(e1, e2, e3) ->
pr ppf "\\%sIfTerm{%a}{%a}{%a}" g
tex_exp e1
tex_exp e2
tex_exp e3
let tex_val ppf = function
Value_of_int i -> pr ppf "%d" i
| Value_of_bool b -> pp_print_string ppf (string_of_bool b)
let tex_judgment ppf = function
EvalTo (e, v) -> pr ppf "\\%sEvalTo{%a}{%a}" g tex_exp e tex_val v
| AppBOp (p, v1, v2, v3) ->
let op = "\\" ^ g ^ match p with
Plus -> "PlusTerm" | Minus -> "MinusTerm"
| Mult -> "MultTerm" | Lt -> "LTTerm"
in pr ppf "\\%sAppBOp{%a}{%s}{%a}{%a}"
g tex_val v1 op tex_val v2 tex_val v3
|
df1795440d0c37729db3327d69419ed29df1c8dbcfc6e415051bc0c6cf031e92 | kidpollo/jackdaw-literate-examples | exception.clj | (ns prod-app.exception
(:require [prod-app.log :as log]
[honeybadger.core :as honeybadger]
[integrant.core :as ig]))
(def magic-keys
"The keys that honeybadger treats special in its metadata."
[:tags :component :action :context :request])
(defn with-app-meta
[app raw-metadata]
(assoc-in raw-metadata [:context :app] app))
(defn groom-meta
"Cleans up the metadata for honeybadger so we see the data
we expect in the places we expect.
Pulls out the magic keys, merges the rest under :context where anything
goes."
[raw-metadata]
(let [;; all the special keys are in this map
predefined (select-keys raw-metadata magic-keys)
added-context (apply dissoc raw-metadata magic-keys)]
(update predefined :context merge added-context)))
(defn hb-notify
"Notifies Honeybadger of the error.
`error` can be a string or exception object.
`metadata` has a specific set of keys supported by honeybadger, others are ignored,
see the select-keys call, and #metadata"
[config error raw-metadata]
(let [metadata (->> raw-metadata
(groom-meta)
(with-app-meta (:app config)))]
(log/error {:error error
:metadata raw-metadata}
"Notifying HoneyBadger")
@(honeybadger/notify config error metadata)))
(defn terminate
"Stop the JVM and exit with an error code."
[]
(shutdown-agents) ; this may be a no-op
(System/exit 1))
(defmethod ig/init-key ::honeybadger [_ {:keys [config]}]
(let [hb-report (partial hb-notify (:honeybadger config))
handler (reify Thread$UncaughtExceptionHandler
(uncaughtException [this thread error]
(try
(hb-report error {})
(catch Throwable t
(log/error {:uncaught-exception error
:uncaught-exception-handler-error t}
"UncaughtExceptionHandler fn threw Exception"))
(finally (terminate)))))]
(Thread/setDefaultUncaughtExceptionHandler handler)
{:report hb-report
:handler handler}))
| null | https://raw.githubusercontent.com/kidpollo/jackdaw-literate-examples/9f3eca7415c0c4d460ab114eca675901a6c32114/prod-app/src/prod_app/exception.clj | clojure | all the special keys are in this map
this may be a no-op | (ns prod-app.exception
(:require [prod-app.log :as log]
[honeybadger.core :as honeybadger]
[integrant.core :as ig]))
(def magic-keys
"The keys that honeybadger treats special in its metadata."
[:tags :component :action :context :request])
(defn with-app-meta
[app raw-metadata]
(assoc-in raw-metadata [:context :app] app))
(defn groom-meta
"Cleans up the metadata for honeybadger so we see the data
we expect in the places we expect.
Pulls out the magic keys, merges the rest under :context where anything
goes."
[raw-metadata]
predefined (select-keys raw-metadata magic-keys)
added-context (apply dissoc raw-metadata magic-keys)]
(update predefined :context merge added-context)))
(defn hb-notify
"Notifies Honeybadger of the error.
`error` can be a string or exception object.
`metadata` has a specific set of keys supported by honeybadger, others are ignored,
see the select-keys call, and #metadata"
[config error raw-metadata]
(let [metadata (->> raw-metadata
(groom-meta)
(with-app-meta (:app config)))]
(log/error {:error error
:metadata raw-metadata}
"Notifying HoneyBadger")
@(honeybadger/notify config error metadata)))
(defn terminate
"Stop the JVM and exit with an error code."
[]
(System/exit 1))
(defmethod ig/init-key ::honeybadger [_ {:keys [config]}]
(let [hb-report (partial hb-notify (:honeybadger config))
handler (reify Thread$UncaughtExceptionHandler
(uncaughtException [this thread error]
(try
(hb-report error {})
(catch Throwable t
(log/error {:uncaught-exception error
:uncaught-exception-handler-error t}
"UncaughtExceptionHandler fn threw Exception"))
(finally (terminate)))))]
(Thread/setDefaultUncaughtExceptionHandler handler)
{:report hb-report
:handler handler}))
|
53bfd5bb34cad1a43222d834dea7171239e9c0933f8bdeb79613b24e1955ec36 | intermine/bluegenes | events.cljs | (ns bluegenes.components.tools.events
(:require [re-frame.core :as re-frame :refer [reg-event-db reg-event-fx reg-fx dispatch subscribe]]
[bluegenes.effects :as fx]
[bluegenes.crud.tools :as crud]))
(reg-event-fx
::fetch-tools
(fn [{db :db} [evt]]
{:db db
::fx/http {:method :get
:uri "/api/tools/all"
:on-success [::success-fetch-tools]
:on-unauthorised [::error-fetch-tools evt]
:on-failure [::error-fetch-tools evt]}}))
(reg-event-db
::success-fetch-tools
(fn [db [_ {:keys [tools]}]]
(crud/update-installed-tools db tools)))
(reg-event-fx
::error-fetch-tools
(fn [{db :db} [_ evt res]]
(let [text (case evt
::fetch-tools "Failed to fetch BlueGenes Tools - visualizations may not show. This indicates a problem with the BlueGenes backend. "
"Error occurred when communicating with the BlueGenes Tool backend. ")]
{:dispatch [:messages/add
{:markup [:span text
(when-let [err (get-in res [:body :error])]
[:code err])]
:style "warning"
:timeout 0}]})))
(reg-event-fx
::fetch-npm-tools
(fn [_ [evt]]
{::fx/http {:method :get
:uri (str ""
"?q=keywords:bluegenes-intermine-tool")
:on-success [::success-fetch-npm-tools]
:on-unauthorised [::error-fetch-tools evt]
:on-failure [::error-fetch-tools evt]}}))
(reg-event-db
::success-fetch-npm-tools
(fn [db [_ {:keys [results]}]]
(assoc-in db [:tools :available] results)))
(reg-event-fx
::navigate-query
(fn [{db :db} [_ query source]]
(let [source (or source (:current-mine db))
set-current-mine [:set-current-mine source]
history+ [:results/history+ {:source source
:type :query
:intent :tool
:value query}]
new-source? (not= source (:current-mine db))]
{:dispatch (if new-source? set-current-mine history+)
;; Use :dispatch-after-boot since [:results :queries] is cleared when switching mines.
:db (cond-> db
new-source? (update :dispatch-after-boot (fnil conj []) history+))})))
(reg-event-fx
::fetch-tool-path
(fn [_ [evt]]
{::fx/http {:method :get
:uri "/api/tools/path"
:on-success [::success-fetch-tool-path]
:on-unauthorised [::error-fetch-tools evt]
:on-failure [::error-fetch-tools evt]}}))
(reg-event-db
::success-fetch-tool-path
(fn [db [_ {:keys [path]}]]
(assoc-in db [:tools :path] path)))
(reg-event-fx
::init-tool
(fn [{db :db} [_ tool-details tool-id]]
(let [mine (get-in db [:mines (:current-mine db)])
service (get mine :service)]
{:load-tool {:tool tool-details
:tool-id tool-id
:service service}})))
(reg-event-db
::collapse-tool
(fn [db [_ tool-name-cljs]]
(update-in db [:tools :collapsed] (fnil conj #{}) tool-name-cljs)))
(reg-event-db
::expand-tool
(fn [db [_ tool-name-cljs]]
(update-in db [:tools :collapsed] (fnil disj #{}) tool-name-cljs)))
| null | https://raw.githubusercontent.com/intermine/bluegenes/77d3d011b2c8436633d1f711e70c4ec943d9b46d/src/cljs/bluegenes/components/tools/events.cljs | clojure | Use :dispatch-after-boot since [:results :queries] is cleared when switching mines. | (ns bluegenes.components.tools.events
(:require [re-frame.core :as re-frame :refer [reg-event-db reg-event-fx reg-fx dispatch subscribe]]
[bluegenes.effects :as fx]
[bluegenes.crud.tools :as crud]))
(reg-event-fx
::fetch-tools
(fn [{db :db} [evt]]
{:db db
::fx/http {:method :get
:uri "/api/tools/all"
:on-success [::success-fetch-tools]
:on-unauthorised [::error-fetch-tools evt]
:on-failure [::error-fetch-tools evt]}}))
(reg-event-db
::success-fetch-tools
(fn [db [_ {:keys [tools]}]]
(crud/update-installed-tools db tools)))
(reg-event-fx
::error-fetch-tools
(fn [{db :db} [_ evt res]]
(let [text (case evt
::fetch-tools "Failed to fetch BlueGenes Tools - visualizations may not show. This indicates a problem with the BlueGenes backend. "
"Error occurred when communicating with the BlueGenes Tool backend. ")]
{:dispatch [:messages/add
{:markup [:span text
(when-let [err (get-in res [:body :error])]
[:code err])]
:style "warning"
:timeout 0}]})))
(reg-event-fx
::fetch-npm-tools
(fn [_ [evt]]
{::fx/http {:method :get
:uri (str ""
"?q=keywords:bluegenes-intermine-tool")
:on-success [::success-fetch-npm-tools]
:on-unauthorised [::error-fetch-tools evt]
:on-failure [::error-fetch-tools evt]}}))
(reg-event-db
::success-fetch-npm-tools
(fn [db [_ {:keys [results]}]]
(assoc-in db [:tools :available] results)))
(reg-event-fx
::navigate-query
(fn [{db :db} [_ query source]]
(let [source (or source (:current-mine db))
set-current-mine [:set-current-mine source]
history+ [:results/history+ {:source source
:type :query
:intent :tool
:value query}]
new-source? (not= source (:current-mine db))]
{:dispatch (if new-source? set-current-mine history+)
:db (cond-> db
new-source? (update :dispatch-after-boot (fnil conj []) history+))})))
(reg-event-fx
::fetch-tool-path
(fn [_ [evt]]
{::fx/http {:method :get
:uri "/api/tools/path"
:on-success [::success-fetch-tool-path]
:on-unauthorised [::error-fetch-tools evt]
:on-failure [::error-fetch-tools evt]}}))
(reg-event-db
::success-fetch-tool-path
(fn [db [_ {:keys [path]}]]
(assoc-in db [:tools :path] path)))
(reg-event-fx
::init-tool
(fn [{db :db} [_ tool-details tool-id]]
(let [mine (get-in db [:mines (:current-mine db)])
service (get mine :service)]
{:load-tool {:tool tool-details
:tool-id tool-id
:service service}})))
(reg-event-db
::collapse-tool
(fn [db [_ tool-name-cljs]]
(update-in db [:tools :collapsed] (fnil conj #{}) tool-name-cljs)))
(reg-event-db
::expand-tool
(fn [db [_ tool-name-cljs]]
(update-in db [:tools :collapsed] (fnil disj #{}) tool-name-cljs)))
|
cf9ad79fe3f1fb41918969f00ea45134089f6d75a9e7c10244a4b20c95294b60 | samth/gcstats | info.rkt | #lang setup/infotab
(define collection 'multi)
(define deps '("base"))
| null | https://raw.githubusercontent.com/samth/gcstats/c1112a07155f2a8e8a8ad999c9980d544d56b970/info.rkt | racket | #lang setup/infotab
(define collection 'multi)
(define deps '("base"))
| |
9d29a32dfc6730cf4092c2552ec5222dad7547d8556f2187681464a53980df66 | Kalimehtar/gtk-cffi | table.lisp | (in-package :gtk-cffi)
(defclass table (container)
())
(defcfun gtk-table-new :pointer
(rows :uint) (columns :uint) (homogeneous :boolean))
(defmethod gconstructor ((table table)
&key homogeneous (rows 1) (columns 1)
&allow-other-keys)
(gtk-table-new rows columns homogeneous))
(defbitfield attach-options
:expand :shrink :fill)
(defcfun gtk-table-attach-defaults :void
(table pobject) (widget pobject)
(left-attach :uint) (right-attach :uint)
(top-attach :uint) (bottom-attach :uint))
(defcfun gtk-table-attach :void
(table pobject) (widget pobject)
(left-attach :uint) (right-attach :uint)
(top-attach :uint) (bottom-attach :uint)
(xoptions attach-options) (yoptions attach-options)
(xpadding :uint) (ypadding :uint))
(defgeneric attach (table widget &key)
(:method ((table table) (widget widget)
&key (left 0) (right 1) (top 0) (bottom 1)
(xoptions '(:expand :fill) xoptions-p)
(yoptions '(:expand :fill) yoptions-p)
(xpadding 0) (ypadding 0))
(if (and (null xoptions-p)
(null yoptions-p)
(eq xpadding 0)
(eq ypadding 0))
(gtk-table-attach-defaults table widget left right top bottom)
(gtk-table-attach table widget left right top bottom
xoptions yoptions xpadding ypadding))))
(defcfun gtk-table-get-size :void
(table pobject) (rows (:pointer :int)) (columns (:pointer :int)))
(defgeneric table-size (table)
(:method ((table table))
(with-foreign-outs-list ((rows :int) (columns :int)) :ignore
(gtk-table-get-size table rows columns))))
(defcfun gtk-table-resize :void
(table pobject) (rows :uint) (columns :uint))
(defgeneric (setf table-size) (new-size table)
(:method ((new-size list) (table table))
(destructuring-bind (rows columns) new-size
(gtk-table-resize table rows columns))))
(defgeneric resize (table &key)
(:method ((table table) &key rows columns)
(unless (and rows columns)
(destructuring-bind (cur-rows cur-columns) (table-size table)
(unless rows (setf rows cur-rows))
(unless columns (setf columns cur-columns))))
(gtk-table-resize table rows columns)))
(defmethod pack ((table table) (list list) &rest rest)
"Table should have list of widgets to add"
(declare (ignore rest))
(let ((rows (+ (first (table-size table)) 1))
(width 1))
(loop
:for i :from 0
:for widget :in list
:do (cond
((numberp widget) (setf width widget) (incf i -1))
((not (null widget))
(attach table widget
:left i :right (+ i width)
:top (- rows 1) :bottom rows))))))
| null | https://raw.githubusercontent.com/Kalimehtar/gtk-cffi/fbd8a40a2bbda29f81b1a95ed2530debfe2afe9b/gtk/table.lisp | lisp | (in-package :gtk-cffi)
(defclass table (container)
())
(defcfun gtk-table-new :pointer
(rows :uint) (columns :uint) (homogeneous :boolean))
(defmethod gconstructor ((table table)
&key homogeneous (rows 1) (columns 1)
&allow-other-keys)
(gtk-table-new rows columns homogeneous))
(defbitfield attach-options
:expand :shrink :fill)
(defcfun gtk-table-attach-defaults :void
(table pobject) (widget pobject)
(left-attach :uint) (right-attach :uint)
(top-attach :uint) (bottom-attach :uint))
(defcfun gtk-table-attach :void
(table pobject) (widget pobject)
(left-attach :uint) (right-attach :uint)
(top-attach :uint) (bottom-attach :uint)
(xoptions attach-options) (yoptions attach-options)
(xpadding :uint) (ypadding :uint))
(defgeneric attach (table widget &key)
(:method ((table table) (widget widget)
&key (left 0) (right 1) (top 0) (bottom 1)
(xoptions '(:expand :fill) xoptions-p)
(yoptions '(:expand :fill) yoptions-p)
(xpadding 0) (ypadding 0))
(if (and (null xoptions-p)
(null yoptions-p)
(eq xpadding 0)
(eq ypadding 0))
(gtk-table-attach-defaults table widget left right top bottom)
(gtk-table-attach table widget left right top bottom
xoptions yoptions xpadding ypadding))))
(defcfun gtk-table-get-size :void
(table pobject) (rows (:pointer :int)) (columns (:pointer :int)))
(defgeneric table-size (table)
(:method ((table table))
(with-foreign-outs-list ((rows :int) (columns :int)) :ignore
(gtk-table-get-size table rows columns))))
(defcfun gtk-table-resize :void
(table pobject) (rows :uint) (columns :uint))
(defgeneric (setf table-size) (new-size table)
(:method ((new-size list) (table table))
(destructuring-bind (rows columns) new-size
(gtk-table-resize table rows columns))))
(defgeneric resize (table &key)
(:method ((table table) &key rows columns)
(unless (and rows columns)
(destructuring-bind (cur-rows cur-columns) (table-size table)
(unless rows (setf rows cur-rows))
(unless columns (setf columns cur-columns))))
(gtk-table-resize table rows columns)))
(defmethod pack ((table table) (list list) &rest rest)
"Table should have list of widgets to add"
(declare (ignore rest))
(let ((rows (+ (first (table-size table)) 1))
(width 1))
(loop
:for i :from 0
:for widget :in list
:do (cond
((numberp widget) (setf width widget) (incf i -1))
((not (null widget))
(attach table widget
:left i :right (+ i width)
:top (- rows 1) :bottom rows))))))
| |
b06b1930050af1c4d64155c6b62cd2ba06bbbae63aa4ec11c0328ef35bf41ede | theiceshelf/trunk | components.cljs | (ns app.renderer.components
(:require
[app.renderer.events :as events :refer [|>]]
[app.renderer.subs :as subs :refer [<|]]
[app.shared.ipc-events :refer [s-ev]]
[app.shared.util :as u]
[reagent.core :as r]
[re-frame.core :as rf]))
(defn input-label
[label-text]
[:label.flex.mb-2.text-xs.italic {:for label-text} label-text])
(defn input
[props]
(let [touched? (r/atom false)]
(fn [{:keys [valid? value label default-value on-change] :as props}]
(let [valid? (if (fn? valid?) (valid? value) valid?)
base-styles "w-full p-1.5 text-gray-700 dark:text-gray-50 border rounded-sm focus:outline-none text-sm dark:bg-gray-900 dark:border-gray-500 dark:text-white"
input-stz (if (nil? valid?)
base-styles
(str base-styles
(when @touched?
(if valid? " border-green-500 dark:border-green-500" " border-red-500 dark:border-red-500"))))
;; patch on-change to alter the internal state to show the field has been touched
props (assoc props :on-change (fn [e]
(when-not @touched? (reset! touched? true))
(on-change e)))]
(if label
[:div
[input-label label]
[:input
(merge {:class input-stz :id label} (dissoc props :label :valid?))]]
[:input
(merge {:class input-stz} (dissoc props props :label :valid?))])))))
(defn textarea
[props]
(let [input-stz "w-full p-2 text-gray-700 dark:text-gray-50 border focus:outline-none text-sm mb-4 dark:bg-gray-900 dark:border-gray-500 dark:text-white"
label (props :label)]
(if label
[:div [input-label label] [:textarea (merge {:class input-stz :id label} props)]]
[:textarea (merge {:class input-stz} props)])))
(defn select
[props options]
(let [styles "flex border w-64 py-1.5 rounded-sm dark:bg-gray-900 dark:text-white outline-none "
label (props :label)]
(if label
[:div
[input-label label]
[:select (merge {:class styles :id label} props) options]]
[:select (merge {:class styles} props) options])))
(defn loading-wheel
"Bottom right absolute position loading wheel."
[]
(let [loading? (rf/subscribe [::subs/loading?])
div-stz "transition duration-500 flex bg-gray-50 dark:bg-gray-800 text-xs shadow fixed bottom-0 right-0 p-2 m-2 rounded-md align-center items-center"
div-stz (if-not @loading? (str "-bottom-16 " div-stz) (str "bottom-0 " div-stz))]
(when @loading?
[:div {:class div-stz}
[:svg {:class "animate-spin text-blue-600 dark:text-blue-400", :style {:width "24px" :height "24px"} :xmlns "", :fill "none", :viewBox "0 0 24 24"}
[:circle {:class "opacity-25", :cx "12", :cy "12", :r "10", :stroke "currentColor", :stroke-width "4"}]
[:path {:class "opacity-75", :fill "currentColor", :d "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"}]]])))
(defn toast
[{:keys [type msg]}]
(let [classes (str "px-4 h-full flex items-center "
(case type :confirmation "text-green-600" :error "text-red-500" ""))]
(when-not (empty? msg)
[:div {:class (str classes)} msg])))
(defn container
"This needs to have it's react-keys resolved."
[children]
[:div {:class "flex flex-col p-8 w-full md:w-10/12 lg:w-8/12 mx-auto max-w-screen-xl dark:bg-gray-900"}
children])
(def icons
{:chevron-up "chevron-up.svg"
:chevron-down "chevron-down.svg"
:check "check.svg"})
(defn icon
""
[{:keys [size icon on-click]}]
[:img {:class (if on-click "cursor-pointer" "")
:src (str "img/icons/" (get icons icon))
:on-click on-click
:style {:width (or size 32)
:height (or size 32)}}])
(defn card
[{:keys [header toggleable? starts-closed?]} body]
(let [open? (r/atom (if starts-closed? false true))]
(fn [{:keys [header toggleable? starts-closed?]} body]
[:div.bg-white.border.shadow-sm
{:class (u/twld "bg-white border" "bg-gray-800 border-gray-700")
:key header}
(when header
[:div.border-b.px-4.py-2.text-sm.font-bold.dark:border-gray-700
{:class (when toggleable? " cursor-pointer")
:on-click #(if toggleable?
(reset! open? (not @open?))
nil)}
[:div.flex.flex-1.justify-between.items-center
[:span header]
(when toggleable?
(if @open?
[icon {:icon :chevron-down :size 12}]
[icon {:icon :chevron-up :size 12}]))]])
(if toggleable?
(when @open?
[:div.p-4 body])
[:div.p-4 body])])))
(defn loading-intercept
[msg]
[:div.h-screen.w-100.flex.items-center.justify-center.text-sm.text-gray.600 msg])
(defn ext-link
[{:keys [link text]}]
(let [handle-click (fn [e]
(.preventDefault e)
(.openExternal (.-shell (js/require "electron")) link))]
[:a.text-blue-600.dark:text-blue-400.cursor-pointer {:on-click handle-click} text]))
(defn button
[props]
(let [dbl-check-count (r/atom 0)]
(fn [{:keys [on-click text icon-name icon-size disabled? style dbl-check]
:or {disabled? false style ""}}]
(let [style (if disabled? "disabled" style)
style (case style
"primary" "bg-blue-500 hover:bg-blue-600 text-gray-50 border-none"
"disabled" "border border-opacity-0 dark:border-opacity-100 cursor-not-allowed text-gray-700 dark:text-gray-50 dark:bg-gray-800 dark:border-gray-500 dark:border dark:hover:bg-gray-800 bg-gray-200"
"caution" "bg-red-500 hover:bg-red-600 text-gray-50 border-none"
"" "bg-white text-gray-800 hover:bg-gray-100 dark:text-white dark:bg-gray-700 dark:hover:bg-gray-600 border border-gray-400 ")
styles (str style " self-start text-xs py-1 px-2 rounded shadow ")
curr-text (if dbl-check (if (> @dbl-check-count 0) dbl-check text) text)
handle-click (if dbl-check
(if (> @dbl-check-count 0)
(do #(reset! dbl-check-count 0) on-click)
#(swap! dbl-check-count inc))
on-click)]
[:button {:class styles :on-click handle-click :disabled disabled?}
(if icon-name
[:span [icon {:icon icon-name :size (or icon-size 18)}]
[:span curr-text]]
curr-text)]))))
(defn trunk-logo
[{:keys [width]}]
[:img {:src "img/temp_logo.png"
:style {:width (or width 64) :height (or width 64)}}])
(defn empty-state
[children]
[:div.flex.flex-col.h-screen.justify-center.items-center
[trunk-logo {:width 64}]
[:div.mt-4 children]])
(defn empty-state-with-msg
[{:keys [top-line bottom-line]
:or {top-line "You haven't created any texts yet."
bottom-line "Click \"Create Text\" above to get started."}}]
[empty-state
[:div.text-center.text-gray-400
[:div top-line]
[:div bottom-line]]])
(defn nav-link
[{:keys [on-click text id current-view]}]
(let [active? (= id current-view)]
[:button.bg-transparent.border-b.border-opacity-0.hover:border-opacity-75.font-bold.pt-3.pb-2.px-3.mr-4
{:class (if active? "border-blue-400 border-opacity-100" "")
:on-click on-click} text]))
(defn nav
"Display the navigation bar in app."
[{:keys [current-view]}]
(let [nav! (fn [route] (|> [::events/navigate route]))
;; current-article (<| [::subs/current-article])
toast-msg (<| [::subs/toast])
links [{:text "Read" :id "article-list"}
{:text "Create Text" :id "article-create"}
{:text "Words" :id "words"}
{:text "Settings" :id "settings"}
;; NOTE: show the currently reading article in the nav:
;; not sure I want this as part of the ux so I'm commenting out for now.
{ : text ( u / trunc - ellipse ( get current - article : name ) 25 ) : i d " article " }
]]
[:nav.bg-white.w-full.text-xs.dark:bg-gray-800.dark:text-gray-50.border-b.dark:border-b-gray-900
[:div.flex.items-center {:style {:height "35px"}}
[:div.flex.flex-1.items-center
[:div.pl-4 [trunk-logo {:width 24}]]
[:div.flex.ml-8
(for [l links :when l]
^{:key (l :id)}
[nav-link {:on-click #(nav! (l :id))
:text (l :text)
:current-view current-view
:id (l :id)}])]]
[toast toast-msg]]]))
(defn page-heading
[text]
[:div.text-center.mb-8 [:h2.text-2xl text]])
(defn article-word
"how single words are styled based on their familiarity/comfort."
[{:keys [word current-word index current-word-idx on-click current-phrase-idxs lang-word-regex]}]
(let [{:keys [name comfort is_not_a_word _translation]} word
base-styles "border-b border-transparent px-0.5 py-px mr-1 cursor-pointer bg-opacity-25 hover:bg-opacity-50
dark:bg-opacity-50 dark:text-gray-300"
stz (str (u/get-comfort-bg-col comfort) " "
base-styles)
is-in-current-phrase (not (nil? (some #{index} current-phrase-idxs)))
is-current-word (or (and (= (dissoc word :comfort) (dissoc current-word :comfort))
(= index current-word-idx))
is-in-current-phrase)
stz (if is-current-word (str " border-black dark:border-b-gray-300 " stz) (str " " stz))]
(cond
;; newlines that are just from textarea...
(= name "\n")
[:div.w-full {:style {:height "0px"}}]
(= name "\n\n")
[:div.w-full [:br]]
;; it's a phrase
(and (word :first_word_slug)
(not (u/word? name lang-word-regex)))
[:span.relative {:on-click on-click}
[:span {:class stz} (str " " (word :name) " ")]]
(= is_not_a_word 1) ; ie - it's punctuation.
[:span.mr-1 (str "" (word :name) " ")]
:else
[:span.relative {:on-click on-click}
[:span {:class stz} (str " " (word :name) " ")]])))
(defn google-translate-view
[{:keys [t-win-open? word-or-phrase]}]
(let [stz "absolute bottom-0 left-0 p-2 w-full text-center italic text-xs bg-white
hover:bg-gray-100 text-gray-800 border-t border-gray-300
dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700 dark:text-white"
button-height 44
iframe-height 368
window-width js/window.innerWidth
window-height js/window.innerHeight]
;; only enable rendering google translate view when there is enough room
TODO : checking of window heighto only happens on render ,
;; so handle for user resize of window.
(when (and (> window-width 1000)
(> window-height (+ iframe-height button-height 128)))
[:div
(if t-win-open?
[:div
[:div.border-b.absolute.left-0.w-full {:style {:bottom (str (+ iframe-height button-height) "px")}}]
[:button {:class stz
:style {:height (- button-height 1)}
:on-click #(|> [(s-ev :t-win-close)])}
"Close Translations"]]
[:button {:class stz
:style {:height (- button-height 1)}
:on-click #(|> [(s-ev :t-win-open)
{:width window-width
:word-or-phrase word-or-phrase
:height window-height
:button-height button-height
:containerHeight iframe-height
:containerWidth (- (* 0.4 js/window.innerWidth) 1)}])}
"Open Translations"])])))
(defn view-current-word
"Displays the currently clicked on word/phrase for user editing. "
[{:keys [current-word form]}]
(let [t-win-open? (<| [::subs/t-win-open?])
currently-selected-phrase (<| [::subs/current-phrase]) ; current phrase as in, the one being underlined and is yet to be made a word.
word-or-phrase (or currently-selected-phrase current-word)
word-or-phrase-text (or (get word-or-phrase :name) (<| [::subs/current-phrase-text]))
is-phrase (or currently-selected-phrase
(u/is-phrase word-or-phrase))
handle-submit (fn [e]
(.preventDefault e)
(if is-phrase
(|> [(s-ev :phrase-update) @form])
(|> [(s-ev :word-update) @form])))]
[:div {:class "bg-gray-50 w-full border-t md:border-t-0 md:flex md:w-2/5 md:relative border-l dark:border-gray-900 dark:bg-gray-800 dark:border-gray-700"}
(when word-or-phrase
[:div {:class "dark:bg-gray-800 w-full p-8 flex flex-col mx-auto"}
[:div.static
;; current word or title text:
[:div.h-16.flex.items-center
[:div {:class (str "mb-8 w-full" (when-not is-phrase " text-xl"))} word-or-phrase-text]]
[:form {:class "w-full" :on-submit handle-submit}
[input {:placeholder "Add Translation..."
:default-value (get word-or-phrase :translation "")
:value (@form :translation)
:on-change (fn [e] (swap! form assoc :translation (-> e .-target .-value)))}]
;; radio button
[:div.my-2.flex.md:flex-col.lg:flex-row.xl:justify-between.flex-wrap.pt-2
(doall ;; needed for deref (@) in lazy for loop.
(for [[comfort-int comfort-data] u/comfort-text-and-col
:let [{:keys [name text-col help-text]} comfort-data]]
[:span {:class "flex items-center lg:w-1/2 xl:w-1/3"
:key comfort-int}
[:input {:id name
:type "radio"
:value comfort-int
:name "group-1"
:checked (= (@form :comfort) comfort-int)
:on-change (fn [e] (swap! form assoc :comfort (-> e .-target .-value int)))}]
[:label {:for name
:title help-text
:class (str "text-sm p-0.5 pl-1 pr-2 " text-col)} (str name "(" (+ 1 comfort-int) ")")]]))]
;; submit update
[:div.mt-4 [button {:type "submit"
:style "primary"
:text (if is-phrase
(if currently-selected-phrase "Add phrase" "Update phrase")
"Update word")}]]]]
[google-translate-view
{:t-win-open? t-win-open?
:word-or-phrase (word-or-phrase :name)}]])]))
| null | https://raw.githubusercontent.com/theiceshelf/trunk/d6e275bcfb7ae6cc23b5f9e3e2f39186a74544ec/src/app/renderer/components.cljs | clojure | patch on-change to alter the internal state to show the field has been touched
current-article (<| [::subs/current-article])
NOTE: show the currently reading article in the nav:
not sure I want this as part of the ux so I'm commenting out for now.
newlines that are just from textarea...
it's a phrase
ie - it's punctuation.
only enable rendering google translate view when there is enough room
so handle for user resize of window.
current phrase as in, the one being underlined and is yet to be made a word.
current word or title text:
radio button
needed for deref (@) in lazy for loop.
submit update | (ns app.renderer.components
(:require
[app.renderer.events :as events :refer [|>]]
[app.renderer.subs :as subs :refer [<|]]
[app.shared.ipc-events :refer [s-ev]]
[app.shared.util :as u]
[reagent.core :as r]
[re-frame.core :as rf]))
(defn input-label
[label-text]
[:label.flex.mb-2.text-xs.italic {:for label-text} label-text])
(defn input
[props]
(let [touched? (r/atom false)]
(fn [{:keys [valid? value label default-value on-change] :as props}]
(let [valid? (if (fn? valid?) (valid? value) valid?)
base-styles "w-full p-1.5 text-gray-700 dark:text-gray-50 border rounded-sm focus:outline-none text-sm dark:bg-gray-900 dark:border-gray-500 dark:text-white"
input-stz (if (nil? valid?)
base-styles
(str base-styles
(when @touched?
(if valid? " border-green-500 dark:border-green-500" " border-red-500 dark:border-red-500"))))
props (assoc props :on-change (fn [e]
(when-not @touched? (reset! touched? true))
(on-change e)))]
(if label
[:div
[input-label label]
[:input
(merge {:class input-stz :id label} (dissoc props :label :valid?))]]
[:input
(merge {:class input-stz} (dissoc props props :label :valid?))])))))
(defn textarea
[props]
(let [input-stz "w-full p-2 text-gray-700 dark:text-gray-50 border focus:outline-none text-sm mb-4 dark:bg-gray-900 dark:border-gray-500 dark:text-white"
label (props :label)]
(if label
[:div [input-label label] [:textarea (merge {:class input-stz :id label} props)]]
[:textarea (merge {:class input-stz} props)])))
(defn select
[props options]
(let [styles "flex border w-64 py-1.5 rounded-sm dark:bg-gray-900 dark:text-white outline-none "
label (props :label)]
(if label
[:div
[input-label label]
[:select (merge {:class styles :id label} props) options]]
[:select (merge {:class styles} props) options])))
(defn loading-wheel
"Bottom right absolute position loading wheel."
[]
(let [loading? (rf/subscribe [::subs/loading?])
div-stz "transition duration-500 flex bg-gray-50 dark:bg-gray-800 text-xs shadow fixed bottom-0 right-0 p-2 m-2 rounded-md align-center items-center"
div-stz (if-not @loading? (str "-bottom-16 " div-stz) (str "bottom-0 " div-stz))]
(when @loading?
[:div {:class div-stz}
[:svg {:class "animate-spin text-blue-600 dark:text-blue-400", :style {:width "24px" :height "24px"} :xmlns "", :fill "none", :viewBox "0 0 24 24"}
[:circle {:class "opacity-25", :cx "12", :cy "12", :r "10", :stroke "currentColor", :stroke-width "4"}]
[:path {:class "opacity-75", :fill "currentColor", :d "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"}]]])))
(defn toast
[{:keys [type msg]}]
(let [classes (str "px-4 h-full flex items-center "
(case type :confirmation "text-green-600" :error "text-red-500" ""))]
(when-not (empty? msg)
[:div {:class (str classes)} msg])))
(defn container
"This needs to have it's react-keys resolved."
[children]
[:div {:class "flex flex-col p-8 w-full md:w-10/12 lg:w-8/12 mx-auto max-w-screen-xl dark:bg-gray-900"}
children])
(def icons
{:chevron-up "chevron-up.svg"
:chevron-down "chevron-down.svg"
:check "check.svg"})
(defn icon
""
[{:keys [size icon on-click]}]
[:img {:class (if on-click "cursor-pointer" "")
:src (str "img/icons/" (get icons icon))
:on-click on-click
:style {:width (or size 32)
:height (or size 32)}}])
(defn card
[{:keys [header toggleable? starts-closed?]} body]
(let [open? (r/atom (if starts-closed? false true))]
(fn [{:keys [header toggleable? starts-closed?]} body]
[:div.bg-white.border.shadow-sm
{:class (u/twld "bg-white border" "bg-gray-800 border-gray-700")
:key header}
(when header
[:div.border-b.px-4.py-2.text-sm.font-bold.dark:border-gray-700
{:class (when toggleable? " cursor-pointer")
:on-click #(if toggleable?
(reset! open? (not @open?))
nil)}
[:div.flex.flex-1.justify-between.items-center
[:span header]
(when toggleable?
(if @open?
[icon {:icon :chevron-down :size 12}]
[icon {:icon :chevron-up :size 12}]))]])
(if toggleable?
(when @open?
[:div.p-4 body])
[:div.p-4 body])])))
(defn loading-intercept
[msg]
[:div.h-screen.w-100.flex.items-center.justify-center.text-sm.text-gray.600 msg])
(defn ext-link
[{:keys [link text]}]
(let [handle-click (fn [e]
(.preventDefault e)
(.openExternal (.-shell (js/require "electron")) link))]
[:a.text-blue-600.dark:text-blue-400.cursor-pointer {:on-click handle-click} text]))
(defn button
[props]
(let [dbl-check-count (r/atom 0)]
(fn [{:keys [on-click text icon-name icon-size disabled? style dbl-check]
:or {disabled? false style ""}}]
(let [style (if disabled? "disabled" style)
style (case style
"primary" "bg-blue-500 hover:bg-blue-600 text-gray-50 border-none"
"disabled" "border border-opacity-0 dark:border-opacity-100 cursor-not-allowed text-gray-700 dark:text-gray-50 dark:bg-gray-800 dark:border-gray-500 dark:border dark:hover:bg-gray-800 bg-gray-200"
"caution" "bg-red-500 hover:bg-red-600 text-gray-50 border-none"
"" "bg-white text-gray-800 hover:bg-gray-100 dark:text-white dark:bg-gray-700 dark:hover:bg-gray-600 border border-gray-400 ")
styles (str style " self-start text-xs py-1 px-2 rounded shadow ")
curr-text (if dbl-check (if (> @dbl-check-count 0) dbl-check text) text)
handle-click (if dbl-check
(if (> @dbl-check-count 0)
(do #(reset! dbl-check-count 0) on-click)
#(swap! dbl-check-count inc))
on-click)]
[:button {:class styles :on-click handle-click :disabled disabled?}
(if icon-name
[:span [icon {:icon icon-name :size (or icon-size 18)}]
[:span curr-text]]
curr-text)]))))
(defn trunk-logo
[{:keys [width]}]
[:img {:src "img/temp_logo.png"
:style {:width (or width 64) :height (or width 64)}}])
(defn empty-state
[children]
[:div.flex.flex-col.h-screen.justify-center.items-center
[trunk-logo {:width 64}]
[:div.mt-4 children]])
(defn empty-state-with-msg
[{:keys [top-line bottom-line]
:or {top-line "You haven't created any texts yet."
bottom-line "Click \"Create Text\" above to get started."}}]
[empty-state
[:div.text-center.text-gray-400
[:div top-line]
[:div bottom-line]]])
(defn nav-link
[{:keys [on-click text id current-view]}]
(let [active? (= id current-view)]
[:button.bg-transparent.border-b.border-opacity-0.hover:border-opacity-75.font-bold.pt-3.pb-2.px-3.mr-4
{:class (if active? "border-blue-400 border-opacity-100" "")
:on-click on-click} text]))
(defn nav
"Display the navigation bar in app."
[{:keys [current-view]}]
(let [nav! (fn [route] (|> [::events/navigate route]))
toast-msg (<| [::subs/toast])
links [{:text "Read" :id "article-list"}
{:text "Create Text" :id "article-create"}
{:text "Words" :id "words"}
{:text "Settings" :id "settings"}
{ : text ( u / trunc - ellipse ( get current - article : name ) 25 ) : i d " article " }
]]
[:nav.bg-white.w-full.text-xs.dark:bg-gray-800.dark:text-gray-50.border-b.dark:border-b-gray-900
[:div.flex.items-center {:style {:height "35px"}}
[:div.flex.flex-1.items-center
[:div.pl-4 [trunk-logo {:width 24}]]
[:div.flex.ml-8
(for [l links :when l]
^{:key (l :id)}
[nav-link {:on-click #(nav! (l :id))
:text (l :text)
:current-view current-view
:id (l :id)}])]]
[toast toast-msg]]]))
(defn page-heading
[text]
[:div.text-center.mb-8 [:h2.text-2xl text]])
(defn article-word
"how single words are styled based on their familiarity/comfort."
[{:keys [word current-word index current-word-idx on-click current-phrase-idxs lang-word-regex]}]
(let [{:keys [name comfort is_not_a_word _translation]} word
base-styles "border-b border-transparent px-0.5 py-px mr-1 cursor-pointer bg-opacity-25 hover:bg-opacity-50
dark:bg-opacity-50 dark:text-gray-300"
stz (str (u/get-comfort-bg-col comfort) " "
base-styles)
is-in-current-phrase (not (nil? (some #{index} current-phrase-idxs)))
is-current-word (or (and (= (dissoc word :comfort) (dissoc current-word :comfort))
(= index current-word-idx))
is-in-current-phrase)
stz (if is-current-word (str " border-black dark:border-b-gray-300 " stz) (str " " stz))]
(cond
(= name "\n")
[:div.w-full {:style {:height "0px"}}]
(= name "\n\n")
[:div.w-full [:br]]
(and (word :first_word_slug)
(not (u/word? name lang-word-regex)))
[:span.relative {:on-click on-click}
[:span {:class stz} (str " " (word :name) " ")]]
[:span.mr-1 (str "" (word :name) " ")]
:else
[:span.relative {:on-click on-click}
[:span {:class stz} (str " " (word :name) " ")]])))
(defn google-translate-view
[{:keys [t-win-open? word-or-phrase]}]
(let [stz "absolute bottom-0 left-0 p-2 w-full text-center italic text-xs bg-white
hover:bg-gray-100 text-gray-800 border-t border-gray-300
dark:bg-gray-800 dark:border-gray-700 dark:hover:bg-gray-700 dark:text-white"
button-height 44
iframe-height 368
window-width js/window.innerWidth
window-height js/window.innerHeight]
TODO : checking of window heighto only happens on render ,
(when (and (> window-width 1000)
(> window-height (+ iframe-height button-height 128)))
[:div
(if t-win-open?
[:div
[:div.border-b.absolute.left-0.w-full {:style {:bottom (str (+ iframe-height button-height) "px")}}]
[:button {:class stz
:style {:height (- button-height 1)}
:on-click #(|> [(s-ev :t-win-close)])}
"Close Translations"]]
[:button {:class stz
:style {:height (- button-height 1)}
:on-click #(|> [(s-ev :t-win-open)
{:width window-width
:word-or-phrase word-or-phrase
:height window-height
:button-height button-height
:containerHeight iframe-height
:containerWidth (- (* 0.4 js/window.innerWidth) 1)}])}
"Open Translations"])])))
(defn view-current-word
"Displays the currently clicked on word/phrase for user editing. "
[{:keys [current-word form]}]
(let [t-win-open? (<| [::subs/t-win-open?])
word-or-phrase (or currently-selected-phrase current-word)
word-or-phrase-text (or (get word-or-phrase :name) (<| [::subs/current-phrase-text]))
is-phrase (or currently-selected-phrase
(u/is-phrase word-or-phrase))
handle-submit (fn [e]
(.preventDefault e)
(if is-phrase
(|> [(s-ev :phrase-update) @form])
(|> [(s-ev :word-update) @form])))]
[:div {:class "bg-gray-50 w-full border-t md:border-t-0 md:flex md:w-2/5 md:relative border-l dark:border-gray-900 dark:bg-gray-800 dark:border-gray-700"}
(when word-or-phrase
[:div {:class "dark:bg-gray-800 w-full p-8 flex flex-col mx-auto"}
[:div.static
[:div.h-16.flex.items-center
[:div {:class (str "mb-8 w-full" (when-not is-phrase " text-xl"))} word-or-phrase-text]]
[:form {:class "w-full" :on-submit handle-submit}
[input {:placeholder "Add Translation..."
:default-value (get word-or-phrase :translation "")
:value (@form :translation)
:on-change (fn [e] (swap! form assoc :translation (-> e .-target .-value)))}]
[:div.my-2.flex.md:flex-col.lg:flex-row.xl:justify-between.flex-wrap.pt-2
(for [[comfort-int comfort-data] u/comfort-text-and-col
:let [{:keys [name text-col help-text]} comfort-data]]
[:span {:class "flex items-center lg:w-1/2 xl:w-1/3"
:key comfort-int}
[:input {:id name
:type "radio"
:value comfort-int
:name "group-1"
:checked (= (@form :comfort) comfort-int)
:on-change (fn [e] (swap! form assoc :comfort (-> e .-target .-value int)))}]
[:label {:for name
:title help-text
:class (str "text-sm p-0.5 pl-1 pr-2 " text-col)} (str name "(" (+ 1 comfort-int) ")")]]))]
[:div.mt-4 [button {:type "submit"
:style "primary"
:text (if is-phrase
(if currently-selected-phrase "Add phrase" "Update phrase")
"Update word")}]]]]
[google-translate-view
{:t-win-open? t-win-open?
:word-or-phrase (word-or-phrase :name)}]])]))
|
4f7b37dc8acd8de343734f89de89581492057a219788b9e79caea2d3120aab91 | denisidoro/rosebud | config.clj | (ns quark.beta.server.protocols.config
"Store and retrieve the last error for debugging purposes.")
(defprotocol Config
"Runtime configuration"
(get! [component config-path] "Get an item based on a [:path :to :item], or raise an exception if not found.")
(get-env-var [component name fallback])
(get-optional [component config-path] "Get an optional item based on a [:path :to :item]. Returns nil if not found"))
| null | https://raw.githubusercontent.com/denisidoro/rosebud/90385528d9a75a0e17803df487a4f6cfb87e981c/server/src/quark/beta/server/protocols/config.clj | clojure | (ns quark.beta.server.protocols.config
"Store and retrieve the last error for debugging purposes.")
(defprotocol Config
"Runtime configuration"
(get! [component config-path] "Get an item based on a [:path :to :item], or raise an exception if not found.")
(get-env-var [component name fallback])
(get-optional [component config-path] "Get an optional item based on a [:path :to :item]. Returns nil if not found"))
| |
c34c3ed24dc6cba16ab55cbbbb2f81094ae5ea4afbe640d7c1343e4d2bc93f2e | ksseono/the-joy-of-clojure | externs_for_cljs.clj | (ns joy.externs-for-cljs
(:require [cljs.compiler :as comp]
[cljs.analyzer :as ana]
[clojure.walk :refer [prewalk]]
[clojure.pprint :refer [pprint]]
[clojure.java.io :as io])
(:import (clojure.lang LineNumberingPushbackReader)))
(def code-string "(defn hello [x] (js/alert (pr-str 'greetings x)))")
(def code-data (read-string code-string))
(def ast (ana/analyze (ana/empty-env) code-data))
;;
Listing 13.3
;;
(defn print-ast [ast]
(pprint
(prewalk
(fn [x]
(if (map? x)
(select-keys x [:op :form :name :children])
x))
ast)))
(comment
(print-ast ast)
;; {:op :def,
;; :form
( def hello ( cljs.core/fn ( [ x ] ( js / alert ( pr - str ' greetings x ) ) ) ) ) ,
;; :name cljs.user/hello,
;; :children
;; [{:op :fn,
;; :form (fn* ([x] (js/alert (pr-str 'greetings x)))),
;; :name {:name hello},
;; :children
;; [{:op :do,
;; :form (do (js/alert (pr-str 'greetings x))),
;; :children
;; [{:op :invoke,
;; :form (js/alert (pr-str 'greetings x)),
;; :children
;; [{:op :var, :form js/alert}
;; {:op :invoke,
;; :form (pr-str 'greetings x),
;; :children
;; [{:op :var, :form pr-str}
;; {:op :constant, :form greetings}
;; {:op :var, :form x}]}]}]}]}]}
(comp/emit ast)
;; cljs.user.hello = (function cljs$user$hello(x){
;; return alert(cljs.user.pr_str.call(null,
new cljs.core . Symbol(null,"greetings","greetings " ,
;; -547008995,null),x));
;; });
;;=> nil
)
;;
Listing 13.8
;;
(defn read-file
"Read the contents of filename as a sequence of Clojure values."
[filename]
(let [eof (Object.)]
(with-open [reader (LineNumberingPushbackReader.
(io/reader filename))]
(doall
(take-while #(not= % eof)
(repeatedly #(read reader false eof)))))))
(defn file-ast
"Return the ClojureScript AST for the contents of filename. Tends to be large
and to contain cycles -- be careful printing at the REPL."
[filename]
(binding [ana/*cljs-ns* 'cljs.user
ana/*cljs-file* filename]
(mapv #(ana/analyze (ana/empty-env) %)
(read-file filename))))
(comment
(count (file-ast "src/cljs/joy/music.cljs"))
= > 13
(first (file-ast "src/cljs/joy/music.cljs"))
;;=> {:use-macros nil, :excludes #{}, :name joy.music, ...}
)
(defn flatten-ast [ast]
(mapcat #(tree-seq :children :children %) ast))
(def flat-ast (flatten-ast (file-ast "src/cljs/joy/music.cljs")))
(comment
(count flat-ast)
= > 557
)
(defn get-interop-used
"Return a set of symbols representing the method and field names
used in interop forms in the given sequence of AST nodes."
[flat-ast]
(set (keep #(some % [:method :field]) flat-ast)))
(comment
(get-interop-used flat-ast)
;;=> #{destination createDynamicsCompressor createOscillator createGain
;; linearRampToValueAtTime connect value frequency start
;; cljs$core$ISeq$ AudioContext currentTime stop
;; cljs$lang$protocol_mask$partition0$ detune gain webkitAudioContext}
)
(defn externs-for-interop [syms]
(apply str
"var DummyClass={};\n"
(map #(str "DummyClass." % "=function(){};\n")
syms)))
| null | https://raw.githubusercontent.com/ksseono/the-joy-of-clojure/4fee3fb2750236b85b59ae9d7a83e0929040e4f0/src/clj/ch13/joy/externs_for_cljs.clj | clojure |
{:op :def,
:form
:name cljs.user/hello,
:children
[{:op :fn,
:form (fn* ([x] (js/alert (pr-str 'greetings x)))),
:name {:name hello},
:children
[{:op :do,
:form (do (js/alert (pr-str 'greetings x))),
:children
[{:op :invoke,
:form (js/alert (pr-str 'greetings x)),
:children
[{:op :var, :form js/alert}
{:op :invoke,
:form (pr-str 'greetings x),
:children
[{:op :var, :form pr-str}
{:op :constant, :form greetings}
{:op :var, :form x}]}]}]}]}]}
cljs.user.hello = (function cljs$user$hello(x){
return alert(cljs.user.pr_str.call(null,
-547008995,null),x));
});
=> nil
=> {:use-macros nil, :excludes #{}, :name joy.music, ...}
=> #{destination createDynamicsCompressor createOscillator createGain
linearRampToValueAtTime connect value frequency start
cljs$core$ISeq$ AudioContext currentTime stop
cljs$lang$protocol_mask$partition0$ detune gain webkitAudioContext} | (ns joy.externs-for-cljs
(:require [cljs.compiler :as comp]
[cljs.analyzer :as ana]
[clojure.walk :refer [prewalk]]
[clojure.pprint :refer [pprint]]
[clojure.java.io :as io])
(:import (clojure.lang LineNumberingPushbackReader)))
(def code-string "(defn hello [x] (js/alert (pr-str 'greetings x)))")
(def code-data (read-string code-string))
(def ast (ana/analyze (ana/empty-env) code-data))
Listing 13.3
(defn print-ast [ast]
(pprint
(prewalk
(fn [x]
(if (map? x)
(select-keys x [:op :form :name :children])
x))
ast)))
(comment
(print-ast ast)
( def hello ( cljs.core/fn ( [ x ] ( js / alert ( pr - str ' greetings x ) ) ) ) ) ,
(comp/emit ast)
new cljs.core . Symbol(null,"greetings","greetings " ,
)
Listing 13.8
(defn read-file
"Read the contents of filename as a sequence of Clojure values."
[filename]
(let [eof (Object.)]
(with-open [reader (LineNumberingPushbackReader.
(io/reader filename))]
(doall
(take-while #(not= % eof)
(repeatedly #(read reader false eof)))))))
(defn file-ast
"Return the ClojureScript AST for the contents of filename. Tends to be large
and to contain cycles -- be careful printing at the REPL."
[filename]
(binding [ana/*cljs-ns* 'cljs.user
ana/*cljs-file* filename]
(mapv #(ana/analyze (ana/empty-env) %)
(read-file filename))))
(comment
(count (file-ast "src/cljs/joy/music.cljs"))
= > 13
(first (file-ast "src/cljs/joy/music.cljs"))
)
(defn flatten-ast [ast]
(mapcat #(tree-seq :children :children %) ast))
(def flat-ast (flatten-ast (file-ast "src/cljs/joy/music.cljs")))
(comment
(count flat-ast)
= > 557
)
(defn get-interop-used
"Return a set of symbols representing the method and field names
used in interop forms in the given sequence of AST nodes."
[flat-ast]
(set (keep #(some % [:method :field]) flat-ast)))
(comment
(get-interop-used flat-ast)
)
(defn externs-for-interop [syms]
(apply str
"var DummyClass={};\n"
(map #(str "DummyClass." % "=function(){};\n")
syms)))
|
24da67a52f326324e0bdd9ed2e08b5e5569dee75e6a7da181e59c24468a47566 | typedclojure/typedclojure | reify.clj | Copyright ( c ) , contributors .
;; The use and distribution terms for this software are covered by the
;; Eclipse Public License 1.0 (-1.0.php)
;; which can be found in the file epl-v10.html at the root of this distribution.
;; By using this software in any fashion, you are agreeing to be bound by
;; the terms of this license.
;; You must not remove this notice, or any other, from this software.
TODO share with typed.clj.checker.check.deftype
(ns typed.clj.checker.check.reify
(:require [clojure.core.typed.errors :as err]
[typed.cljc.checker.type-ctors :as c]
[typed.cljc.checker.type-rep :as r]
[clojure.core.typed.util-vars :as vs]
[typed.cljc.checker.filter-ops :as fo]
[typed.cljc.analyzer :as ana2]
[typed.cljc.checker.utils :as u]
[typed.cljc.checker.check-below :as below]
[typed.clj.ext.clojure.core__reify :as reify]
[typed.clj.analyzer.utils :as ju]
[typed.clj.checker.method-override-env :as mth-override]
[typed.cljc.checker.check.recur-utils :as recur-u]
[typed.cljc.checker.check.fn-methods :as fn-methods]
[typed.cljc.checker.check.utils :as cu]
[typed.clj.checker.parse-unparse :as prs]))
(defn IFn-invoke-method-t [this-t t]
(let [t (c/fully-resolve-type t)]
(cond
(r/FnIntersection? t) (apply r/make-FnIntersection
(map (fn [{:keys [dom rng rest drest prest pdot kws] :as t}]
(cond
(or rest drest prest pdot kws) (assert nil "TODO IFn-invoke-method-t (or rest drest prest pdot kws)")
:else (update t :dom #(cons this-t %))))
(:types t)))
(and (r/RClass? t)
(= 'clojure.lang.IFn (:the-class t))) (r/TopFunction-maker)
:else (assert nil (str "TODO: " `IFn-invoke-method-t " " (class t))))))
(defn check-inst-fn-methods [inst-methods {:keys [kind expected-ifn] :as _opts}]
{:pre [(#{:reify :deftype} kind)
(every? (comp #{:method} :op) inst-methods)]
:post [(every? (comp #{:method} :op) %)]}
(:methods
(fn-methods/check-fn-methods
inst-methods
expected-ifn
{:check-recur-fn (fn [& args] (err/int-error (format "%s method cannot have rest parameter" (name kind))))
:recur-target-fn
(fn [{:keys [dom] :as f}]
{:pre [(r/Function? f)]
:post [(recur-u/RecurTarget? %)]}
(recur-u/RecurTarget-maker (rest dom) nil nil nil))
:validate-expected-fn
(fn [fin]
{:pre [(r/FnIntersection? fin)]}
(when (some #{:rest :drest :kws} (:types fin))
(err/int-error
(str "Cannot provide rest arguments to " (name kind) " method: "
(prs/unparse-type fin)))))})))
(defn check-reify
[expr expected]
(let [{original-reify-form :form :as original-reify-expr} (-> expr :form first meta ::reify/original-reify-expr)
_ (assert original-reify-form)
class->info (into {}
(comp (partition-all 2)
(drop-while (every-pred #(= 2 (count %))
(comp keyword? first)))
(mapcat identity)
(remove seq?)
(map (fn [prot+class-syn]
(let [v (let [v (resolve prot+class-syn)]
(when (var? v)
v))
cls (ju/maybe-class
(if v
(:on @v)
prot+class-syn))
_ (assert (class? cls) (pr-str cls))]
(when-not (#{Object clojure.lang.IObj} cls)
[cls (cond-> {:prot+interface-syntax prot+class-syn
:static-type (or (when-some [[_ t] (-> prot+class-syn meta (find :typed.clojure/replace))]
(prs/parse-type t))
(when v
(c/Protocol-of (symbol v)))
(c/RClass-of cls))}
v (assoc :protocol v))])))))
(next original-reify-form))
class->info (-> class->info
(assoc clojure.lang.IObj {:static-type (c/RClass-of clojure.lang.IObj)}
Object {:static-type (c/RClass-of Object)}))
this-t (apply c/In (map (comp :static-type val) class->info))]
(binding [vs/*current-expr* original-reify-expr]
(-> expr
(update :methods (fn [methods]
(let [methods (map #(into % (select-keys (ana2/run-passes %) [:methods])) methods)]
(doseq [[method-name methods] (group-by :name methods)
:let [inst-methods (mapcat :methods methods)
declaring-class (-> inst-methods first :declaring-class)
_ (assert (simple-symbol? declaring-class) (vec inst-methods))
_ (assert (apply = declaring-class (map :declaring-class inst-methods))
(vec inst-methods))
msym (symbol (str declaring-class) (name method-name))
{:keys [static-type] :as info} (get class->info (ju/maybe-class declaring-class))
_ (assert info)
override-t (or (mth-override/get-method-override msym)
(cond
(= msym 'clojure.lang.IFn/invoke) (IFn-invoke-method-t this-t (:static-type info))
(:protocol info) (let [static-type (c/fully-resolve-type static-type)
_ (assert (r/Protocol? static-type))
mtype (get-in static-type [:methods method-name])]
(assert mtype (format "Missing annotation for method %s on protocol %s"
method-name
(symbol (:protocol info))))
mtype)))]]
(if override-t
(check-inst-fn-methods
methods
{:kind :reify
:expected-ifn override-t})
(doseq [method methods
:let [_ (assert (= 1 (count (:methods method))))
m (first (:methods method))
_ (prn m)
rfin-type (cu/extend-method-expected this-t (cu/instance-method->Function m))]]
(check-inst-fn-methods
[method]
{:kind :reify
:expected-ifn rfin-type})))))
methods))
(assoc u/expr-type (below/maybe-check-below
(r/ret this-t
(fo/-true-filter))
expected))))))
| null | https://raw.githubusercontent.com/typedclojure/typedclojure/668ee1ef3953eb37f2c748209a6ad25bbfb6165c/typed/clj.checker/src/typed/clj/checker/check/reify.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) , contributors .
TODO share with typed.clj.checker.check.deftype
(ns typed.clj.checker.check.reify
(:require [clojure.core.typed.errors :as err]
[typed.cljc.checker.type-ctors :as c]
[typed.cljc.checker.type-rep :as r]
[clojure.core.typed.util-vars :as vs]
[typed.cljc.checker.filter-ops :as fo]
[typed.cljc.analyzer :as ana2]
[typed.cljc.checker.utils :as u]
[typed.cljc.checker.check-below :as below]
[typed.clj.ext.clojure.core__reify :as reify]
[typed.clj.analyzer.utils :as ju]
[typed.clj.checker.method-override-env :as mth-override]
[typed.cljc.checker.check.recur-utils :as recur-u]
[typed.cljc.checker.check.fn-methods :as fn-methods]
[typed.cljc.checker.check.utils :as cu]
[typed.clj.checker.parse-unparse :as prs]))
(defn IFn-invoke-method-t [this-t t]
(let [t (c/fully-resolve-type t)]
(cond
(r/FnIntersection? t) (apply r/make-FnIntersection
(map (fn [{:keys [dom rng rest drest prest pdot kws] :as t}]
(cond
(or rest drest prest pdot kws) (assert nil "TODO IFn-invoke-method-t (or rest drest prest pdot kws)")
:else (update t :dom #(cons this-t %))))
(:types t)))
(and (r/RClass? t)
(= 'clojure.lang.IFn (:the-class t))) (r/TopFunction-maker)
:else (assert nil (str "TODO: " `IFn-invoke-method-t " " (class t))))))
(defn check-inst-fn-methods [inst-methods {:keys [kind expected-ifn] :as _opts}]
{:pre [(#{:reify :deftype} kind)
(every? (comp #{:method} :op) inst-methods)]
:post [(every? (comp #{:method} :op) %)]}
(:methods
(fn-methods/check-fn-methods
inst-methods
expected-ifn
{:check-recur-fn (fn [& args] (err/int-error (format "%s method cannot have rest parameter" (name kind))))
:recur-target-fn
(fn [{:keys [dom] :as f}]
{:pre [(r/Function? f)]
:post [(recur-u/RecurTarget? %)]}
(recur-u/RecurTarget-maker (rest dom) nil nil nil))
:validate-expected-fn
(fn [fin]
{:pre [(r/FnIntersection? fin)]}
(when (some #{:rest :drest :kws} (:types fin))
(err/int-error
(str "Cannot provide rest arguments to " (name kind) " method: "
(prs/unparse-type fin)))))})))
(defn check-reify
[expr expected]
(let [{original-reify-form :form :as original-reify-expr} (-> expr :form first meta ::reify/original-reify-expr)
_ (assert original-reify-form)
class->info (into {}
(comp (partition-all 2)
(drop-while (every-pred #(= 2 (count %))
(comp keyword? first)))
(mapcat identity)
(remove seq?)
(map (fn [prot+class-syn]
(let [v (let [v (resolve prot+class-syn)]
(when (var? v)
v))
cls (ju/maybe-class
(if v
(:on @v)
prot+class-syn))
_ (assert (class? cls) (pr-str cls))]
(when-not (#{Object clojure.lang.IObj} cls)
[cls (cond-> {:prot+interface-syntax prot+class-syn
:static-type (or (when-some [[_ t] (-> prot+class-syn meta (find :typed.clojure/replace))]
(prs/parse-type t))
(when v
(c/Protocol-of (symbol v)))
(c/RClass-of cls))}
v (assoc :protocol v))])))))
(next original-reify-form))
class->info (-> class->info
(assoc clojure.lang.IObj {:static-type (c/RClass-of clojure.lang.IObj)}
Object {:static-type (c/RClass-of Object)}))
this-t (apply c/In (map (comp :static-type val) class->info))]
(binding [vs/*current-expr* original-reify-expr]
(-> expr
(update :methods (fn [methods]
(let [methods (map #(into % (select-keys (ana2/run-passes %) [:methods])) methods)]
(doseq [[method-name methods] (group-by :name methods)
:let [inst-methods (mapcat :methods methods)
declaring-class (-> inst-methods first :declaring-class)
_ (assert (simple-symbol? declaring-class) (vec inst-methods))
_ (assert (apply = declaring-class (map :declaring-class inst-methods))
(vec inst-methods))
msym (symbol (str declaring-class) (name method-name))
{:keys [static-type] :as info} (get class->info (ju/maybe-class declaring-class))
_ (assert info)
override-t (or (mth-override/get-method-override msym)
(cond
(= msym 'clojure.lang.IFn/invoke) (IFn-invoke-method-t this-t (:static-type info))
(:protocol info) (let [static-type (c/fully-resolve-type static-type)
_ (assert (r/Protocol? static-type))
mtype (get-in static-type [:methods method-name])]
(assert mtype (format "Missing annotation for method %s on protocol %s"
method-name
(symbol (:protocol info))))
mtype)))]]
(if override-t
(check-inst-fn-methods
methods
{:kind :reify
:expected-ifn override-t})
(doseq [method methods
:let [_ (assert (= 1 (count (:methods method))))
m (first (:methods method))
_ (prn m)
rfin-type (cu/extend-method-expected this-t (cu/instance-method->Function m))]]
(check-inst-fn-methods
[method]
{:kind :reify
:expected-ifn rfin-type})))))
methods))
(assoc u/expr-type (below/maybe-check-below
(r/ret this-t
(fo/-true-filter))
expected))))))
|
8b5a208d91486173d07a8432507cb190b448e01096d84edf641901f2c71d5f68 | lambdageek/centrinel | Env.hs | -- | Defines the environment type for the naked pointer analysis
module Centrinel.NakedPointer.Env where
import Centrinel.Data.CodePosition (NPEPosn)
-- | The environment for the naked pointer analysis
data AnalysisEnv = AnalysisEnv
{
_analysisPosn :: NPEPosn -- ^ position to report if analysis finds a problem
, _analysisSuppress :: Bool -- ^ 'True' if analysis is suppressed by a local pragma
}
analysisPosn :: Functor f => (NPEPosn -> f NPEPosn) -> AnalysisEnv -> f AnalysisEnv
analysisPosn inj (AnalysisEnv p s) = flip AnalysisEnv s <$> inj p
# INLINE analysisPosn #
analysisSuppress :: Functor f => (Bool -> f Bool) -> AnalysisEnv -> f AnalysisEnv
analysisSuppress inj (AnalysisEnv p s) = AnalysisEnv p <$> inj s
# INLINE analysisSuppress #
| null | https://raw.githubusercontent.com/lambdageek/centrinel/412b620b77c6cb569811fec845b89d04585c1332/src/Centrinel/NakedPointer/Env.hs | haskell | | Defines the environment type for the naked pointer analysis
| The environment for the naked pointer analysis
^ position to report if analysis finds a problem
^ 'True' if analysis is suppressed by a local pragma | module Centrinel.NakedPointer.Env where
import Centrinel.Data.CodePosition (NPEPosn)
data AnalysisEnv = AnalysisEnv
{
}
analysisPosn :: Functor f => (NPEPosn -> f NPEPosn) -> AnalysisEnv -> f AnalysisEnv
analysisPosn inj (AnalysisEnv p s) = flip AnalysisEnv s <$> inj p
# INLINE analysisPosn #
analysisSuppress :: Functor f => (Bool -> f Bool) -> AnalysisEnv -> f AnalysisEnv
analysisSuppress inj (AnalysisEnv p s) = AnalysisEnv p <$> inj s
# INLINE analysisSuppress #
|
b974fcb9d2f1fd2407192d23359da240a4ae5aae42fceb4a7a1798955ff2e8eb | modular-macros/ocaml-macros | parse.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Entry points in the parser *)
(* Skip tokens to the end of the phrase *)
let rec skip_phrase lexbuf =
try
match Lexer.token lexbuf with
Parser.SEMISEMI | Parser.EOF -> ()
| _ -> skip_phrase lexbuf
with
| Lexer.Error (Lexer.Unterminated_comment _, _)
| Lexer.Error (Lexer.Unterminated_string, _)
| Lexer.Error (Lexer.Unterminated_string_in_comment _, _)
| Lexer.Error (Lexer.Illegal_character _, _) -> skip_phrase lexbuf
;;
let maybe_skip_phrase lexbuf =
if Parsing.is_current_lookahead Parser.SEMISEMI
|| Parsing.is_current_lookahead Parser.EOF
then ()
else skip_phrase lexbuf
let wrap parsing_fun lexbuf =
try
Docstrings.init ();
Lexer.init ();
let ast = parsing_fun Lexer.token lexbuf in
Parsing.clear_parser();
Docstrings.warn_bad_docstrings ();
ast
with
| Lexer.Error(Lexer.Illegal_character _, _) as err
when !Location.input_name = "//toplevel//"->
skip_phrase lexbuf;
raise err
| Syntaxerr.Error _ as err
when !Location.input_name = "//toplevel//" ->
maybe_skip_phrase lexbuf;
raise err
| Parsing.Parse_error | Syntaxerr.Escape_error ->
let loc = Location.curr lexbuf in
if !Location.input_name = "//toplevel//"
then maybe_skip_phrase lexbuf;
raise(Syntaxerr.Error(Syntaxerr.Other loc))
let implementation = wrap Parser.implementation
and interface = wrap Parser.interface
and toplevel_phrase = wrap Parser.toplevel_phrase
and use_file = wrap Parser.use_file
and core_type = wrap Parser.parse_core_type
and expression = wrap Parser.parse_expression
and pattern = wrap Parser.parse_pattern
| null | https://raw.githubusercontent.com/modular-macros/ocaml-macros/05372c7248b5a7b1aa507b3c581f710380f17fcd/parsing/parse.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Entry points in the parser
Skip tokens to the end of the phrase | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
let rec skip_phrase lexbuf =
try
match Lexer.token lexbuf with
Parser.SEMISEMI | Parser.EOF -> ()
| _ -> skip_phrase lexbuf
with
| Lexer.Error (Lexer.Unterminated_comment _, _)
| Lexer.Error (Lexer.Unterminated_string, _)
| Lexer.Error (Lexer.Unterminated_string_in_comment _, _)
| Lexer.Error (Lexer.Illegal_character _, _) -> skip_phrase lexbuf
;;
let maybe_skip_phrase lexbuf =
if Parsing.is_current_lookahead Parser.SEMISEMI
|| Parsing.is_current_lookahead Parser.EOF
then ()
else skip_phrase lexbuf
let wrap parsing_fun lexbuf =
try
Docstrings.init ();
Lexer.init ();
let ast = parsing_fun Lexer.token lexbuf in
Parsing.clear_parser();
Docstrings.warn_bad_docstrings ();
ast
with
| Lexer.Error(Lexer.Illegal_character _, _) as err
when !Location.input_name = "//toplevel//"->
skip_phrase lexbuf;
raise err
| Syntaxerr.Error _ as err
when !Location.input_name = "//toplevel//" ->
maybe_skip_phrase lexbuf;
raise err
| Parsing.Parse_error | Syntaxerr.Escape_error ->
let loc = Location.curr lexbuf in
if !Location.input_name = "//toplevel//"
then maybe_skip_phrase lexbuf;
raise(Syntaxerr.Error(Syntaxerr.Other loc))
let implementation = wrap Parser.implementation
and interface = wrap Parser.interface
and toplevel_phrase = wrap Parser.toplevel_phrase
and use_file = wrap Parser.use_file
and core_type = wrap Parser.parse_core_type
and expression = wrap Parser.parse_expression
and pattern = wrap Parser.parse_pattern
|
3a7365abf73090e989bafa240abc866801d63b50cf4c5440cd4955ed7e218e17 | ghcjs/jsaddle-dom | SVGTests.hs | # LANGUAGE PatternSynonyms #
-- For HasCallStack compatibility
{-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-}
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.SVGTests
(hasExtension, hasExtension_, getRequiredFeatures,
getRequiredExtensions, getSystemLanguage, SVGTests(..),
gTypeSVGTests, IsSVGTests, toSVGTests)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
-- | <-US/docs/Web/API/SVGTests.hasExtension Mozilla SVGTests.hasExtension documentation>
hasExtension ::
(MonadDOM m, IsSVGTests self, ToJSString extension) =>
self -> Maybe extension -> m Bool
hasExtension self extension
= liftDOM
(((toSVGTests self) ^. jsf "hasExtension" [toJSVal extension]) >>=
valToBool)
-- | <-US/docs/Web/API/SVGTests.hasExtension Mozilla SVGTests.hasExtension documentation>
hasExtension_ ::
(MonadDOM m, IsSVGTests self, ToJSString extension) =>
self -> Maybe extension -> m ()
hasExtension_ self extension
= liftDOM
(void
((toSVGTests self) ^. jsf "hasExtension" [toJSVal extension]))
-- | <-US/docs/Web/API/SVGTests.requiredFeatures Mozilla SVGTests.requiredFeatures documentation>
getRequiredFeatures ::
(MonadDOM m, IsSVGTests self) => self -> m SVGStringList
getRequiredFeatures self
= liftDOM
(((toSVGTests self) ^. js "requiredFeatures") >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTests.requiredExtensions Mozilla SVGTests.requiredExtensions documentation >
getRequiredExtensions ::
(MonadDOM m, IsSVGTests self) => self -> m SVGStringList
getRequiredExtensions self
= liftDOM
(((toSVGTests self) ^. js "requiredExtensions") >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTests.systemLanguage Mozilla SVGTests.systemLanguage documentation >
getSystemLanguage ::
(MonadDOM m, IsSVGTests self) => self -> m SVGStringList
getSystemLanguage self
= liftDOM
(((toSVGTests self) ^. js "systemLanguage") >>= fromJSValUnchecked)
| null | https://raw.githubusercontent.com/ghcjs/jsaddle-dom/5f5094277d4b11f3dc3e2df6bb437b75712d268f/src/JSDOM/Generated/SVGTests.hs | haskell | For HasCallStack compatibility
# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #
| <-US/docs/Web/API/SVGTests.hasExtension Mozilla SVGTests.hasExtension documentation>
| <-US/docs/Web/API/SVGTests.hasExtension Mozilla SVGTests.hasExtension documentation>
| <-US/docs/Web/API/SVGTests.requiredFeatures Mozilla SVGTests.requiredFeatures documentation> | # LANGUAGE PatternSynonyms #
# OPTIONS_GHC -fno - warn - unused - imports #
module JSDOM.Generated.SVGTests
(hasExtension, hasExtension_, getRequiredFeatures,
getRequiredExtensions, getSystemLanguage, SVGTests(..),
gTypeSVGTests, IsSVGTests, toSVGTests)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..))
import qualified Prelude (error)
import Data.Typeable (Typeable)
import Data.Traversable (mapM)
import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import JSDOM.Types
import Control.Applicative ((<$>))
import Control.Monad (void)
import Control.Lens.Operators ((^.))
import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync)
import JSDOM.Enums
hasExtension ::
(MonadDOM m, IsSVGTests self, ToJSString extension) =>
self -> Maybe extension -> m Bool
hasExtension self extension
= liftDOM
(((toSVGTests self) ^. jsf "hasExtension" [toJSVal extension]) >>=
valToBool)
hasExtension_ ::
(MonadDOM m, IsSVGTests self, ToJSString extension) =>
self -> Maybe extension -> m ()
hasExtension_ self extension
= liftDOM
(void
((toSVGTests self) ^. jsf "hasExtension" [toJSVal extension]))
getRequiredFeatures ::
(MonadDOM m, IsSVGTests self) => self -> m SVGStringList
getRequiredFeatures self
= liftDOM
(((toSVGTests self) ^. js "requiredFeatures") >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTests.requiredExtensions Mozilla SVGTests.requiredExtensions documentation >
getRequiredExtensions ::
(MonadDOM m, IsSVGTests self) => self -> m SVGStringList
getRequiredExtensions self
= liftDOM
(((toSVGTests self) ^. js "requiredExtensions") >>=
fromJSValUnchecked)
| < -US/docs/Web/API/SVGTests.systemLanguage Mozilla SVGTests.systemLanguage documentation >
getSystemLanguage ::
(MonadDOM m, IsSVGTests self) => self -> m SVGStringList
getSystemLanguage self
= liftDOM
(((toSVGTests self) ^. js "systemLanguage") >>= fromJSValUnchecked)
|
0269a295927fb12f2b24944f24fa58bf35770d9ab0cdb01e73907d09d3220342 | moss/haskell-roguelike-challenge | rfk.hs | module RobotFindsKitten where
import Control.Monad
import Data.List
import System.Console.ANSI
import System.IO
import System.Random
type Position = (Int, Int)
data GameState = Playing Position
| FoundKitten
| FoundNKI
| Over deriving (Eq)
data Command = MoveLeft
| MoveDown
| MoveUp
| MoveRight
| Quit
| Unknown
deriving (Eq)
data Item = Kitten { representation :: Char, position :: Position }
| NKI { representation :: Char, position :: Position }
deriving (Eq)
type Level = [Item]
parseInput :: [Char] -> [Command]
parseInput chars = map parseCommand chars
parseCommand :: Char -> Command
parseCommand 'q' = Quit
parseCommand 'h' = MoveLeft
parseCommand 'j' = MoveDown
parseCommand 'k' = MoveUp
parseCommand 'l' = MoveRight
parseCommand _ = Unknown
itemAt :: Position -> [Item] -> Maybe Item
itemAt pos = find (\ item -> (position item) == pos)
moveRobot :: Level -> (Int, Int) -> GameState -> [GameState]
moveRobot level (rowDelta, colDelta) (Playing (row, col)) =
let newR = (row + rowDelta, col + colDelta) in
let itemInTheWay = itemAt newR in
case itemAt newR level of
Just (Kitten _ _) -> [FoundKitten]
Just (NKI _ _) -> [FoundNKI, Playing (row, col)]
Nothing -> [Playing newR]
positions :: [Item] -> [Position]
positions = map position
advance :: Level -> GameState -> Command -> [GameState]
advance level state MoveLeft = moveRobot level (0, -1) state
advance level state MoveUp = moveRobot level (-1, 0) state
advance level state MoveDown = moveRobot level (1, 0) state
advance level state MoveRight = moveRobot level (0, 1) state
advance _ _ Quit = [Over]
advance _ state _ = [state]
|like scanl , but one trip through the function can produce multiple
-- >>> chunkyscanl (\ latest new -> [latest + new]) 0 [1,2,3]
-- [0,1,3,6]
> > > chunkyscanl ( \ latest new - > [ 9 , latest + new ] ) 0 [ 1,2,3 ]
[ 0,9,1,9,3,9,6 ]
chunkyscanl :: (a -> b -> [a]) -> a -> [b] -> [a]
chunkyscanl f q ls = q : (case ls of
[] -> []
x:xs -> let nextchunk = f q x in
(init nextchunk) ++ chunkyscanl f (last nextchunk) xs)
-- |Show a simple representation of a series of gameplay states
diagram :: [GameState] -> String
diagram = intercalate " -> " . map (\ state -> case state of
Playing robot -> show robot
FoundKitten -> "Kitten"
FoundNKI -> "NKI"
Over -> "Over"
)
-- |Play a game
> > > diagram $ playGame [ Kitten ' k ' ( 5,5 ) ] [ ' h ' , ' q ' ] ( Playing ( 2,2 ) )
" ( 2,2 ) - > ( 2,1 ) - > Over "
--
> > > diagram $ playGame [ Kitten ' k ' ( 2,1 ) ] [ ' h ' , ' l ' ] ( Playing ( 2,2 ) )
" ( 2,2 ) - > Kitten "
--
> > > diagram $ playGame [ NKI 's ' ( 2,1 ) ] [ ' h ' , ' l ' ] ( Playing ( 2,2 ) )
" ( 2,2 ) - > NKI - > ( 2,2 ) - > ( 2,3 ) "
playGame :: Level -> [Char] -> GameState -> [GameState]
playGame level userInput initState = takeThrough (flip elem [Over, FoundKitten]) $
chunkyscanl (advance level) initState $
parseInput userInput
-- |takeThrough, applied to a predicate @p@ and a list @xs@, returns the
prefix ( possibly empty ) of @xs@ up through the first that satisfies :
> > > takeThrough (= = 3 ) [ 1,2,3,4,5 ]
-- [1,2,3]
> > > takeThrough (= = 700 ) [ 1,2,3,4,5 ]
[ 1,2,3,4,5 ]
takeThrough :: (a -> Bool) -> [a] -> [a]
takeThrough _ [] = []
takeThrough p (x:xs)
| not (p x) = x : takeThrough p xs
| otherwise = [x]
transitions :: [a] -> [(a, a)]
transitions list = zip ([head list] ++ list) list
Here be IO Monad dragons
initScreen level (Playing robot) = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
hSetEcho stdin False
clearScreen
drawR robot
mapM_ drawItem level
drawItem (Kitten representation position) = draw representation position
drawItem (NKI representation position) = draw representation position
draw char (row, col) = do
setCursorPosition row col
putChar char
setCursorPosition 26 0
drawR = draw '#'
drawK = draw 'k'
drawS = draw 's'
clear = draw ' '
updateScreen (_, Over) = do putStrLn "Goodbye!"
updateScreen (_, FoundKitten) = do putStrLn "Aww! You found a kitten!"
updateScreen (_, FoundNKI) = do putStr "Just a useless gray rock."
updateScreen (FoundNKI, _) = do return ()
updateScreen (Playing oldState, Playing newState) = do
clear oldState
drawR newState
takeRandom count range = do
g <- newStdGen
return $ take count $ randomRs range g
generateLevel = do
[kittenChar, stoneChar, otherStoneChar] <- takeRandom 3 ('A', 'z')
randomRows <- takeRandom 2 (0, 25)
randomCols <- takeRandom 2 (0, 80)
let [kittenPos, stonePos] = zip randomRows randomCols
return [ Kitten kittenChar kittenPos
, NKI stoneChar stonePos
, NKI otherStoneChar (6, 42)
]
main :: IO ()
main = do
level <- generateLevel
let gameState = Playing (12, 40)
initScreen level gameState
userInput <- getContents
forM_ (transitions $ playGame level userInput gameState) updateScreen
| null | https://raw.githubusercontent.com/moss/haskell-roguelike-challenge/2163c3aa6f14051bc2360de0d7a1694b54ef73a3/6-robot-finds-kitten/rfk.hs | haskell | >>> chunkyscanl (\ latest new -> [latest + new]) 0 [1,2,3]
[0,1,3,6]
|Show a simple representation of a series of gameplay states
|Play a game
|takeThrough, applied to a predicate @p@ and a list @xs@, returns the
[1,2,3] | module RobotFindsKitten where
import Control.Monad
import Data.List
import System.Console.ANSI
import System.IO
import System.Random
type Position = (Int, Int)
data GameState = Playing Position
| FoundKitten
| FoundNKI
| Over deriving (Eq)
data Command = MoveLeft
| MoveDown
| MoveUp
| MoveRight
| Quit
| Unknown
deriving (Eq)
data Item = Kitten { representation :: Char, position :: Position }
| NKI { representation :: Char, position :: Position }
deriving (Eq)
type Level = [Item]
parseInput :: [Char] -> [Command]
parseInput chars = map parseCommand chars
parseCommand :: Char -> Command
parseCommand 'q' = Quit
parseCommand 'h' = MoveLeft
parseCommand 'j' = MoveDown
parseCommand 'k' = MoveUp
parseCommand 'l' = MoveRight
parseCommand _ = Unknown
itemAt :: Position -> [Item] -> Maybe Item
itemAt pos = find (\ item -> (position item) == pos)
moveRobot :: Level -> (Int, Int) -> GameState -> [GameState]
moveRobot level (rowDelta, colDelta) (Playing (row, col)) =
let newR = (row + rowDelta, col + colDelta) in
let itemInTheWay = itemAt newR in
case itemAt newR level of
Just (Kitten _ _) -> [FoundKitten]
Just (NKI _ _) -> [FoundNKI, Playing (row, col)]
Nothing -> [Playing newR]
positions :: [Item] -> [Position]
positions = map position
advance :: Level -> GameState -> Command -> [GameState]
advance level state MoveLeft = moveRobot level (0, -1) state
advance level state MoveUp = moveRobot level (-1, 0) state
advance level state MoveDown = moveRobot level (1, 0) state
advance level state MoveRight = moveRobot level (0, 1) state
advance _ _ Quit = [Over]
advance _ state _ = [state]
|like scanl , but one trip through the function can produce multiple
> > > chunkyscanl ( \ latest new - > [ 9 , latest + new ] ) 0 [ 1,2,3 ]
[ 0,9,1,9,3,9,6 ]
chunkyscanl :: (a -> b -> [a]) -> a -> [b] -> [a]
chunkyscanl f q ls = q : (case ls of
[] -> []
x:xs -> let nextchunk = f q x in
(init nextchunk) ++ chunkyscanl f (last nextchunk) xs)
diagram :: [GameState] -> String
diagram = intercalate " -> " . map (\ state -> case state of
Playing robot -> show robot
FoundKitten -> "Kitten"
FoundNKI -> "NKI"
Over -> "Over"
)
> > > diagram $ playGame [ Kitten ' k ' ( 5,5 ) ] [ ' h ' , ' q ' ] ( Playing ( 2,2 ) )
" ( 2,2 ) - > ( 2,1 ) - > Over "
> > > diagram $ playGame [ Kitten ' k ' ( 2,1 ) ] [ ' h ' , ' l ' ] ( Playing ( 2,2 ) )
" ( 2,2 ) - > Kitten "
> > > diagram $ playGame [ NKI 's ' ( 2,1 ) ] [ ' h ' , ' l ' ] ( Playing ( 2,2 ) )
" ( 2,2 ) - > NKI - > ( 2,2 ) - > ( 2,3 ) "
playGame :: Level -> [Char] -> GameState -> [GameState]
playGame level userInput initState = takeThrough (flip elem [Over, FoundKitten]) $
chunkyscanl (advance level) initState $
parseInput userInput
prefix ( possibly empty ) of @xs@ up through the first that satisfies :
> > > takeThrough (= = 3 ) [ 1,2,3,4,5 ]
> > > takeThrough (= = 700 ) [ 1,2,3,4,5 ]
[ 1,2,3,4,5 ]
takeThrough :: (a -> Bool) -> [a] -> [a]
takeThrough _ [] = []
takeThrough p (x:xs)
| not (p x) = x : takeThrough p xs
| otherwise = [x]
transitions :: [a] -> [(a, a)]
transitions list = zip ([head list] ++ list) list
Here be IO Monad dragons
initScreen level (Playing robot) = do
hSetBuffering stdin NoBuffering
hSetBuffering stdout NoBuffering
hSetEcho stdin False
clearScreen
drawR robot
mapM_ drawItem level
drawItem (Kitten representation position) = draw representation position
drawItem (NKI representation position) = draw representation position
draw char (row, col) = do
setCursorPosition row col
putChar char
setCursorPosition 26 0
drawR = draw '#'
drawK = draw 'k'
drawS = draw 's'
clear = draw ' '
updateScreen (_, Over) = do putStrLn "Goodbye!"
updateScreen (_, FoundKitten) = do putStrLn "Aww! You found a kitten!"
updateScreen (_, FoundNKI) = do putStr "Just a useless gray rock."
updateScreen (FoundNKI, _) = do return ()
updateScreen (Playing oldState, Playing newState) = do
clear oldState
drawR newState
takeRandom count range = do
g <- newStdGen
return $ take count $ randomRs range g
generateLevel = do
[kittenChar, stoneChar, otherStoneChar] <- takeRandom 3 ('A', 'z')
randomRows <- takeRandom 2 (0, 25)
randomCols <- takeRandom 2 (0, 80)
let [kittenPos, stonePos] = zip randomRows randomCols
return [ Kitten kittenChar kittenPos
, NKI stoneChar stonePos
, NKI otherStoneChar (6, 42)
]
main :: IO ()
main = do
level <- generateLevel
let gameState = Playing (12, 40)
initScreen level gameState
userInput <- getContents
forM_ (transitions $ playGame level userInput gameState) updateScreen
|
b29368d23c871a064a82a44dd386103fdcfb2ed29d16690b02a63d5e3db7bcd3 | commsor/titanoboa | api.clj | Copyright ( c ) Commsor Inc. All rights reserved .
; The use and distribution terms for this software are covered by the
; GNU Affero General Public License v3.0 (/#AGPL)
; which can be found in the LICENSE at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns titanoboa.api
(:require [com.stuartsierra.component :as component]
[clojure.tools.logging :as log]
[clojure.core.async :as async :refer [>!! <!! chan]]
[titanoboa.system :as system]
[titanoboa.util :as util]
[titanoboa.processor]))
(defn get-jobs-states []
"Retrievs job state snapshot from all running core systems.
Since core systems are not flagged and any system can be a 'core' system,
the functions simply takes all systems that are running and have referencable :job-state attribute.
Returns map of job state maps where keys are names of the systems."
(->> @system/systems-state
(filter (fn [[k v]] (and (:job-state (:system v))
(instance? clojure.lang.IDeref (:job-state (:system v)))
(= :running (:state v)))))
(map (fn [[k v]] [k (deref (:job-state (:system v)))]))
(into {})))
| null | https://raw.githubusercontent.com/commsor/titanoboa/ffe3e1e58f89169092d7b6a3a45e1707a0ecc9ee/src/clj/titanoboa/api.clj | clojure | The use and distribution terms for this software are covered by the
GNU Affero General Public License v3.0 (/#AGPL)
which can be found in the LICENSE at the root of this distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) Commsor Inc. All rights reserved .
(ns titanoboa.api
(:require [com.stuartsierra.component :as component]
[clojure.tools.logging :as log]
[clojure.core.async :as async :refer [>!! <!! chan]]
[titanoboa.system :as system]
[titanoboa.util :as util]
[titanoboa.processor]))
(defn get-jobs-states []
"Retrievs job state snapshot from all running core systems.
Since core systems are not flagged and any system can be a 'core' system,
the functions simply takes all systems that are running and have referencable :job-state attribute.
Returns map of job state maps where keys are names of the systems."
(->> @system/systems-state
(filter (fn [[k v]] (and (:job-state (:system v))
(instance? clojure.lang.IDeref (:job-state (:system v)))
(= :running (:state v)))))
(map (fn [[k v]] [k (deref (:job-state (:system v)))]))
(into {})))
|
7f512b5a9b25c08a2cd4ab701942ca6558d74f12a496190c2cc72354b67a9791 | Perry961002/SICP | exa2.1.1-rational-number.scm | (load "Chap1\\example\\exa1.2.5-GCD.scm")
返回一个有理数 ,
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
取得分子
(define (number x)
(car x))
;取得分母
(define (denom x)
(cdr x))
;打印一个有理数
(define (print-rat x)
(newline)
(display (number x))
(display "/")
(display (denom x)))
;两个有理数相加
(define (add-rat x y)
(make-rat (+ (* (number x) (denom y))
(* (number y) (denom x)))
(* (denom x) (denom y))))
;减法
(define (sub-rat x y)
(make-rat (- (* (number x) (denom y))
(* (number y) (denom x)))
(* (denom x) (denom y))))
;乘法
(define (mul-rat x y)
(make-rat (* (number x) (number y))
(* (denom x) (denom y))))
;除法
(define (div-rat x y)
(make-rat (* (number x) (denom y))
(* (denom x) (number y))))
;判断相等
(define (equal-rat? x y)
(= (* (number x) (denom y))
(* (number y) (denom x)))) | null | https://raw.githubusercontent.com/Perry961002/SICP/89d539e600a73bec42d350592f0ac626e041bf16/Chap2/example/exa2.1.1-rational-number.scm | scheme | 取得分母
打印一个有理数
两个有理数相加
减法
乘法
除法
判断相等 | (load "Chap1\\example\\exa1.2.5-GCD.scm")
返回一个有理数 ,
(define (make-rat n d)
(let ((g (gcd n d)))
(cons (/ n g) (/ d g))))
取得分子
(define (number x)
(car x))
(define (denom x)
(cdr x))
(define (print-rat x)
(newline)
(display (number x))
(display "/")
(display (denom x)))
(define (add-rat x y)
(make-rat (+ (* (number x) (denom y))
(* (number y) (denom x)))
(* (denom x) (denom y))))
(define (sub-rat x y)
(make-rat (- (* (number x) (denom y))
(* (number y) (denom x)))
(* (denom x) (denom y))))
(define (mul-rat x y)
(make-rat (* (number x) (number y))
(* (denom x) (denom y))))
(define (div-rat x y)
(make-rat (* (number x) (denom y))
(* (denom x) (number y))))
(define (equal-rat? x y)
(= (* (number x) (denom y))
(* (number y) (denom x)))) |
e8a6804a09e8a07feadc5761273be768fe0be1684eeee313a43e05377881bcdc | emqx/minirest | minirest_json_encoder.erl | Copyright ( c ) 2013 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
%%
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
%%
%% -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.
-module(minirest_json_encoder).
-include("minirest_http.hrl").
-export([encode/1]).
encode(Body) ->
case jsx:is_term(Body) of
true ->
{ok, ?DEFAULT_RESPONSE_HEADERS, jsx:encode(Body)};
false ->
Response = {
?RESPONSE_CODE_INTERNAL_SERVER_ERROR,
#{<<"content-type">> => <<"text/plain">>},
list_to_binary(io_lib:format("invalid json term: ~p", [Body]))
},
{response, Response}
end.
| null | https://raw.githubusercontent.com/emqx/minirest/e08265f8d5a2ce157912614e7c6293c7c1528ab1/src/body_encoder/minirest_json_encoder.erl | erlang |
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
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. | Copyright ( c ) 2013 - 2022 EMQ Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(minirest_json_encoder).
-include("minirest_http.hrl").
-export([encode/1]).
encode(Body) ->
case jsx:is_term(Body) of
true ->
{ok, ?DEFAULT_RESPONSE_HEADERS, jsx:encode(Body)};
false ->
Response = {
?RESPONSE_CODE_INTERNAL_SERVER_ERROR,
#{<<"content-type">> => <<"text/plain">>},
list_to_binary(io_lib:format("invalid json term: ~p", [Body]))
},
{response, Response}
end.
|
0fd26dda9c29f76c0c87da09512c78f42870a5dfeeb6c62cbc9fa65dc0fbf98e | haroldcarr/learn-haskell-coq-ml-etc | Lec4HS.hs | module Lec4HS where
import System.IO
mainLoop :: s -> (s -> Bool -> ([Bool], Maybe s)) -> IO ()
mainLoop s f = do
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
hSetEcho stdin False
innerLoop s
where
getBit = do
c <- getChar
case c of
'0' -> return False
'1' -> return True
_ -> getBit
innerLoop s = do
b <- getBit
let (os, ms) = f s b
mapM_ (\ b -> if b then putChar '1' else putChar '0') os
case ms of
Just s -> innerLoop s
Nothing -> return ()
mainOutIn :: s -> (s -> ([Bool], Maybe (Bool -> s))) -> IO ()
mainOutIn s f = do
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
hSetEcho stdin False
innerLoop s
where
getBit = do
c <- getChar
case c of
'0' -> return False
'1' -> return True
_ -> getBit
innerLoop s = do
let (os, mk) = f s
mapM_ (\ b -> if b then putChar '1' else putChar '0') os
case mk of
Just k -> do
b <- getBit
innerLoop (k b)
Nothing -> return ()
| null | https://raw.githubusercontent.com/haroldcarr/learn-haskell-coq-ml-etc/56093b549c1b715ee76581fb65e2c371dba3f455/agda/course/2017-conor_mcbride_cs410/CS410-17-master/lectures/Lec4HS.hs | haskell | module Lec4HS where
import System.IO
mainLoop :: s -> (s -> Bool -> ([Bool], Maybe s)) -> IO ()
mainLoop s f = do
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
hSetEcho stdin False
innerLoop s
where
getBit = do
c <- getChar
case c of
'0' -> return False
'1' -> return True
_ -> getBit
innerLoop s = do
b <- getBit
let (os, ms) = f s b
mapM_ (\ b -> if b then putChar '1' else putChar '0') os
case ms of
Just s -> innerLoop s
Nothing -> return ()
mainOutIn :: s -> (s -> ([Bool], Maybe (Bool -> s))) -> IO ()
mainOutIn s f = do
hSetBuffering stdout NoBuffering
hSetBuffering stdin NoBuffering
hSetEcho stdin False
innerLoop s
where
getBit = do
c <- getChar
case c of
'0' -> return False
'1' -> return True
_ -> getBit
innerLoop s = do
let (os, mk) = f s
mapM_ (\ b -> if b then putChar '1' else putChar '0') os
case mk of
Just k -> do
b <- getBit
innerLoop (k b)
Nothing -> return ()
| |
8724edf7d706f3fa35e38380d4bc5957a15c77e3818be5980eb96ca0320e38f1 | pablomarx/Thomas | common.scm | * Copyright 1992 Digital Equipment Corporation
;* All Rights Reserved
;*
;* Permission to use, copy, and modify this software and its documentation is
;* hereby granted only under the following terms and conditions. Both the
;* above copyright notice and this permission notice must appear in all copies
;* of the software, derivative works or modified versions, and any portions
;* thereof, and both notices must appear in supporting documentation.
;*
;* Users of this software agree to the terms and conditions set forth herein,
* and hereby grant back to Digital a non - exclusive , unrestricted , royalty - free
;* right and license under any changes, enhancements or extensions made to the
;* core functions of the software, including but not limited to those affording
;* compatibility with other hardware or software environments, but excluding
;* applications which incorporate this software. Users further agree to use
* their best efforts to return to Digital any such changes , enhancements or
* extensions that they make and inform Digital of noteworthy uses of this
* software . Correspondence should be provided to Digital at :
;*
* Director , Cambridge Research Lab
* Digital Equipment Corp
* One Kendall Square , Bldg 700
;* Cambridge MA 02139
;*
;* This software may be distributed (but not offered for sale or transferred
* for compensation ) to third parties , provided such third parties agree to
;* abide by the terms and conditions of this notice.
;*
* THE SOFTWARE IS PROVIDED " AS IS " AND DIGITAL EQUIPMENT CORP . DISCLAIMS ALL
;* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
;* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
;* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
;* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
;* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
;* SOFTWARE.
$ I d : common.scm , v 1.3 1992/09/09 23:06:25 birkholz Exp $
(dylan::load "support")
| null | https://raw.githubusercontent.com/pablomarx/Thomas/c8ab3f6fa92a9a39667fe37dfe060b651affb18e/src/common.scm | scheme | * All Rights Reserved
*
* Permission to use, copy, and modify this software and its documentation is
* hereby granted only under the following terms and conditions. Both the
* above copyright notice and this permission notice must appear in all copies
* of the software, derivative works or modified versions, and any portions
* thereof, and both notices must appear in supporting documentation.
*
* Users of this software agree to the terms and conditions set forth herein,
* right and license under any changes, enhancements or extensions made to the
* core functions of the software, including but not limited to those affording
* compatibility with other hardware or software environments, but excluding
* applications which incorporate this software. Users further agree to use
*
* Cambridge MA 02139
*
* This software may be distributed (but not offered for sale or transferred
* abide by the terms and conditions of this notice.
*
* WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL DIGITAL EQUIPMENT
* CORPORATION BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE. | * Copyright 1992 Digital Equipment Corporation
* and hereby grant back to Digital a non - exclusive , unrestricted , royalty - free
* their best efforts to return to Digital any such changes , enhancements or
* extensions that they make and inform Digital of noteworthy uses of this
* software . Correspondence should be provided to Digital at :
* Director , Cambridge Research Lab
* Digital Equipment Corp
* One Kendall Square , Bldg 700
* for compensation ) to third parties , provided such third parties agree to
* THE SOFTWARE IS PROVIDED " AS IS " AND DIGITAL EQUIPMENT CORP . DISCLAIMS ALL
* PROFITS , WHETHER IN AN ACTION OF CONTRACT , NEGLIGENCE OR OTHER
$ I d : common.scm , v 1.3 1992/09/09 23:06:25 birkholz Exp $
(dylan::load "support")
|
ff3326cc3d0f3c32387f76a42cebc0c4b9172bacaf8aa153712dc4fb573ba9aa | melhadad/fuf | generator.lisp | ;;; -*- Mode:Lisp; Syntax:Common-Lisp; Package:FUG5 -*-
;;; -----------------------------------------------------------------------
;;; File : GENERATOR.L
;;; Description: Generator manipulation functions
Author :
Created : 22 - Jul-87
;;; Modified : 02-Nov-87
17 May 90 : moved macros to macros.l
17 Dec 91 : renamed first to gen - first
;;; Tag file: TAGS
Package : FUG5
Macros : empty , freeze , cons - gen
;;; -----------------------------------------------------------------------
;;;
FUF - a functional unification - based text generation system . ( . 5.4 )
;;;
Copyright ( c ) 1987 - 2014 by . all rights reserved .
;;;
;;; Permission to use, copy, and/or distribute for any purpose and
;;; without fee is hereby granted, provided that both the above copyright
;;; notice and this permission notice appear in all copies and derived works.
;;; Fees for distribution or use of this software or derived works may only
;;; be charged with express written permission of the copyright holder.
THIS SOFTWARE IS PROVIDED ` ` AS IS '' WITHOUT EXPRESS OR IMPLIED WARRANTY .
;;; -----------------------------------------------------------------------
(in-package "FUG5")
(format t "Generator...~%")
; --------------------------------------------------------------------------
; Comments :
; --------------------------------------------------------------------------
A generator is a pair : ( VALUE . ) or nil .
; nil is the empty generator.
where VALUE is any lisp object , and CONTINUATION is a closure
; CONT. should require no argument (something like #'(lambda () ...))
; (that is what Scheme calls a thunk).
; The value of CONT. must be a new generator.
; Patterned after SCHEME streams.
; --------------------------------------------------------------------------
(defvar *the-empty-generator* nil "Used by module GEN")
(defvar *no-first* '*no-first* "Used by module GEN for first-if and filter")
(defun displace (l1 l2)
(when (consp l1)
(rplaca l1 (car l2))
(rplacd l1 (cdr l2))))
(defun force (thunk)
"Forces the evaluation of a frozen expression (by FREEZE)
Implements memoization"
(let ((result (funcall thunk)))
(displace thunk `(lambda () ',result))
result))
(defun list->gen (list)
"Converts a list to an equivalent generator.
Inverse function is gen->list (or exhaust)"
(if (null list)
*the-empty-generator*
; cons-gen
(cons (car list) #'(lambda nil (list->gen (cdr list))))))
(defun gen-first (generator)
"Returns the first value of a generator"
(if (empty generator)
;; (format t "generator exhausted")
nil
(car generator)))
(defun next (generator)
"Returns a new generator which starts with the next value"
(if (empty generator)
(format t "generator exhausted")
(force (cdr generator))))
(defun first-if (pred generator)
(if (empty generator)
*no-first*
(if (funcall pred (gen-first generator))
(gen-first generator)
(first-if pred (next generator)))))
(defun next-if (pred generator)
(cond ((empty generator) *the-empty-generator*)
((funcall pred (gen-first generator)) (next generator))
(t (next-if pred (next generator)))))
(defun filter (pred generator)
(if (empty generator)
generator
(let ((first (first-if pred generator)))
(if (eq first *no-first*)
*the-empty-generator*
(cons-gen (first-if pred generator)
(filter pred (next-if pred generator)))))))
(defun exhaust (generator)
"Returns a list of all the values of a generator.
May run forever if generator is an implicit infinite computation"
(do ((g generator (next g))
(result nil (cons (gen-first g) result)))
((empty g) (reverse result))))
(defun set-of (generator)
"Returns all the values generated by a generator with no repetition"
(do ((g generator (next g))
(result nil (pushnew (gen-first g) result)))
((empty g) result)))
(defun mapgen (f gen)
"Returns a generator whose values are those of gen modified by the
application of f"
(if (empty gen)
gen
(cons (funcall f (gen-first gen))
#'(lambda nil (mapgen f (next gen))))))
(defun concatgen (gen1 gen2)
"Returns a generator generating all the values of gen1, then all the
values of gen2. Gen2 must be frozen."
(if (empty gen1)
(force gen2)
(cons (gen-first gen1)
#'(lambda nil (concatgen (next gen1) gen2)))))
(defun multiplygen (f gen1 gen2)
"Generic function to combine generators. Returns a generator creating
all the elements of the form f(ei1,ej2), for ei1 generated by gen1,
and ej2 generated by gen2. f must be a function of 2 arguments.
The order of traversal of the 2 generators is j varying the faster."
(if (or (empty gen1) (empty gen2))
*the-empty-generator*
(concatgen
(mapgen #'(lambda (first2) (funcall f (gen-first gen1) first2)) gen2)
#'(lambda () (multiplygen f (next gen1) gen2)))))
(defun appendgen (gen1 gen2)
(multiplygen #'append gen1 gen2))
; --------------------------------------------------------------------------
; Some examples of streams
; --------------------------------------------------------------------------
; This one is infinite
(defun integers (i)
(cons i #'(lambda () (integers (1+ i)))))
; This one is useful
(defun powerset (set)
"Returns a generator producing all 2^n subsets of a set"
(if (null set)
(cons-gen set *the-empty-generator*)
(concatgen
(mapgen #'(lambda (e) (cons (car set) e)) (powerset (cdr set)))
(freeze (powerset (cdr set))))))
;; -----------------------------------------------------------------------
(provide "$fug5/generator")
;; -----------------------------------------------------------------------
| null | https://raw.githubusercontent.com/melhadad/fuf/57bd0e31afc6aaa03b85f45f4c7195af701508b8/src/generator.lisp | lisp | -*- Mode:Lisp; Syntax:Common-Lisp; Package:FUG5 -*-
-----------------------------------------------------------------------
File : GENERATOR.L
Description: Generator manipulation functions
Modified : 02-Nov-87
Tag file: TAGS
-----------------------------------------------------------------------
Permission to use, copy, and/or distribute for any purpose and
without fee is hereby granted, provided that both the above copyright
notice and this permission notice appear in all copies and derived works.
Fees for distribution or use of this software or derived works may only
be charged with express written permission of the copyright holder.
-----------------------------------------------------------------------
--------------------------------------------------------------------------
Comments :
--------------------------------------------------------------------------
nil is the empty generator.
CONT. should require no argument (something like #'(lambda () ...))
(that is what Scheme calls a thunk).
The value of CONT. must be a new generator.
Patterned after SCHEME streams.
--------------------------------------------------------------------------
cons-gen
(format t "generator exhausted")
--------------------------------------------------------------------------
Some examples of streams
--------------------------------------------------------------------------
This one is infinite
This one is useful
-----------------------------------------------------------------------
----------------------------------------------------------------------- | Author :
Created : 22 - Jul-87
17 May 90 : moved macros to macros.l
17 Dec 91 : renamed first to gen - first
Package : FUG5
Macros : empty , freeze , cons - gen
FUF - a functional unification - based text generation system . ( . 5.4 )
Copyright ( c ) 1987 - 2014 by . all rights reserved .
THIS SOFTWARE IS PROVIDED ` ` AS IS '' WITHOUT EXPRESS OR IMPLIED WARRANTY .
(in-package "FUG5")
(format t "Generator...~%")
A generator is a pair : ( VALUE . ) or nil .
where VALUE is any lisp object , and CONTINUATION is a closure
(defvar *the-empty-generator* nil "Used by module GEN")
(defvar *no-first* '*no-first* "Used by module GEN for first-if and filter")
(defun displace (l1 l2)
(when (consp l1)
(rplaca l1 (car l2))
(rplacd l1 (cdr l2))))
(defun force (thunk)
"Forces the evaluation of a frozen expression (by FREEZE)
Implements memoization"
(let ((result (funcall thunk)))
(displace thunk `(lambda () ',result))
result))
(defun list->gen (list)
"Converts a list to an equivalent generator.
Inverse function is gen->list (or exhaust)"
(if (null list)
*the-empty-generator*
(cons (car list) #'(lambda nil (list->gen (cdr list))))))
(defun gen-first (generator)
"Returns the first value of a generator"
(if (empty generator)
nil
(car generator)))
(defun next (generator)
"Returns a new generator which starts with the next value"
(if (empty generator)
(format t "generator exhausted")
(force (cdr generator))))
(defun first-if (pred generator)
(if (empty generator)
*no-first*
(if (funcall pred (gen-first generator))
(gen-first generator)
(first-if pred (next generator)))))
(defun next-if (pred generator)
(cond ((empty generator) *the-empty-generator*)
((funcall pred (gen-first generator)) (next generator))
(t (next-if pred (next generator)))))
(defun filter (pred generator)
(if (empty generator)
generator
(let ((first (first-if pred generator)))
(if (eq first *no-first*)
*the-empty-generator*
(cons-gen (first-if pred generator)
(filter pred (next-if pred generator)))))))
(defun exhaust (generator)
"Returns a list of all the values of a generator.
May run forever if generator is an implicit infinite computation"
(do ((g generator (next g))
(result nil (cons (gen-first g) result)))
((empty g) (reverse result))))
(defun set-of (generator)
"Returns all the values generated by a generator with no repetition"
(do ((g generator (next g))
(result nil (pushnew (gen-first g) result)))
((empty g) result)))
(defun mapgen (f gen)
"Returns a generator whose values are those of gen modified by the
application of f"
(if (empty gen)
gen
(cons (funcall f (gen-first gen))
#'(lambda nil (mapgen f (next gen))))))
(defun concatgen (gen1 gen2)
"Returns a generator generating all the values of gen1, then all the
values of gen2. Gen2 must be frozen."
(if (empty gen1)
(force gen2)
(cons (gen-first gen1)
#'(lambda nil (concatgen (next gen1) gen2)))))
(defun multiplygen (f gen1 gen2)
"Generic function to combine generators. Returns a generator creating
all the elements of the form f(ei1,ej2), for ei1 generated by gen1,
and ej2 generated by gen2. f must be a function of 2 arguments.
The order of traversal of the 2 generators is j varying the faster."
(if (or (empty gen1) (empty gen2))
*the-empty-generator*
(concatgen
(mapgen #'(lambda (first2) (funcall f (gen-first gen1) first2)) gen2)
#'(lambda () (multiplygen f (next gen1) gen2)))))
(defun appendgen (gen1 gen2)
(multiplygen #'append gen1 gen2))
(defun integers (i)
(cons i #'(lambda () (integers (1+ i)))))
(defun powerset (set)
"Returns a generator producing all 2^n subsets of a set"
(if (null set)
(cons-gen set *the-empty-generator*)
(concatgen
(mapgen #'(lambda (e) (cons (car set) e)) (powerset (cdr set)))
(freeze (powerset (cdr set))))))
(provide "$fug5/generator")
|
b8e6ab6dfeb036c3803ddfdbaa6b82a1e8b1a863d5c517aa856d725f71c3aea3 | pink-gorilla/notebook | services.clj | (ns pinkgorilla.notebook-ui.app.services
(:require
[taoensso.timbre :refer [info warn]]
; webly
[webly.config :refer [get-in-config]]
[webly.web.handler :refer [add-ring-handler]]
; explorer
[pinkgorilla.explore.handler :refer [explore-directories-start]]
[pinkgorilla.explorer.default-config] ; side-effects
[pinkgorilla.explorer.handler] ; side-effects
; nrepl relay
[picasso.default-config]
[pinkgorilla.nrepl.relay.jetty :as relay]
[pinkgorilla.nrepl.server.nrepl-server :refer [run-nrepl-server]]
; notebook app
referred to in config.edn
[pinkgorilla.notebook-ui.app.routes]
[pinkgorilla.notebook-ui.sniffer.dump]
; goldly
[goldly.app]))
(defn nrepl-relay-start []
; relay: see resources/config.edn :jetty-ws
(let [{:keys [server relay enabled]} (get-in-config [:nrepl])
nrepl-ws-handler (relay/ws-handler relay)]
(if enabled
(do
(run-nrepl-server server)
(add-ring-handler :ws/nrepl nrepl-ws-handler))
(warn "nrepl-relay is disabed!"))))
(defn explorer-start []
(let [config-explorer-server (get-in-config [:explorer :server])]
(explore-directories-start config-explorer-server)))
(defn run-notebook-services! []
(nrepl-relay-start)
(explorer-start))
| null | https://raw.githubusercontent.com/pink-gorilla/notebook/e25bfb57a9ad4595e34175a57eb65a767206c260/src/pinkgorilla/notebook_ui/app/services.clj | clojure | webly
explorer
side-effects
side-effects
nrepl relay
notebook app
goldly
relay: see resources/config.edn :jetty-ws | (ns pinkgorilla.notebook-ui.app.services
(:require
[taoensso.timbre :refer [info warn]]
[webly.config :refer [get-in-config]]
[webly.web.handler :refer [add-ring-handler]]
[pinkgorilla.explore.handler :refer [explore-directories-start]]
[picasso.default-config]
[pinkgorilla.nrepl.relay.jetty :as relay]
[pinkgorilla.nrepl.server.nrepl-server :refer [run-nrepl-server]]
referred to in config.edn
[pinkgorilla.notebook-ui.app.routes]
[pinkgorilla.notebook-ui.sniffer.dump]
[goldly.app]))
(defn nrepl-relay-start []
(let [{:keys [server relay enabled]} (get-in-config [:nrepl])
nrepl-ws-handler (relay/ws-handler relay)]
(if enabled
(do
(run-nrepl-server server)
(add-ring-handler :ws/nrepl nrepl-ws-handler))
(warn "nrepl-relay is disabed!"))))
(defn explorer-start []
(let [config-explorer-server (get-in-config [:explorer :server])]
(explore-directories-start config-explorer-server)))
(defn run-notebook-services! []
(nrepl-relay-start)
(explorer-start))
|
4504e17082e4249e526b87d36934e936d718d89e14d3de8f67621416d39c0ff4 | dyzsr/ocaml-selectml | ccomp.ml | (**************************************************************************)
(* *)
(* OCaml *)
(* *)
, projet Cristal , INRIA Rocquencourt
(* *)
Copyright 1996 Institut National de Recherche en Informatique et
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
the GNU Lesser General Public License version 2.1 , with the
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Compiling C files and building C libraries *)
let command cmdline =
if !Clflags.verbose then begin
prerr_string "+ ";
prerr_string cmdline;
prerr_newline()
end;
let res = Sys.command cmdline in
if res = 127 then raise (Sys_error cmdline);
res
let run_command cmdline = ignore(command cmdline)
Build @responsefile to work around OS limitations on
command - line length .
Under Windows , the length is 8187 minus the length of the
COMSPEC variable ( or 7 if it 's not set ) . To be on the safe side ,
we 'll use a response file if we need to pass 4096 or more bytes of
arguments .
For Unix - like systems , the threshold is 2 ^ 16 ( 64 KiB ) , which is
within the lowest observed limits ( 2 ^ 17 per argument under Linux ;
between 70000 and 80000 for macOS ) .
command-line length.
Under Windows, the max length is 8187 minus the length of the
COMSPEC variable (or 7 if it's not set). To be on the safe side,
we'll use a response file if we need to pass 4096 or more bytes of
arguments.
For Unix-like systems, the threshold is 2^16 (64 KiB), which is
within the lowest observed limits (2^17 per argument under Linux;
between 70000 and 80000 for macOS).
*)
let build_diversion lst =
let (responsefile, oc) = Filename.open_temp_file "camlresp" "" in
List.iter (fun f -> Printf.fprintf oc "%s\n" f) lst;
close_out oc;
at_exit (fun () -> Misc.remove_file responsefile);
"@" ^ responsefile
let quote_files lst =
let lst = List.filter (fun f -> f <> "") lst in
let quoted = List.map Filename.quote lst in
let s = String.concat " " quoted in
if String.length s >= 65536
|| (String.length s >= 4096 && Sys.os_type = "Win32")
then build_diversion quoted
else s
let quote_prefixed pr lst =
let lst = List.filter (fun f -> f <> "") lst in
let lst = List.map (fun f -> pr ^ f) lst in
quote_files lst
let quote_optfile = function
| None -> ""
| Some f -> Filename.quote f
let display_msvc_output file name =
let c = open_in file in
try
let first = input_line c in
if first <> Filename.basename name then
print_endline first;
while true do
print_endline (input_line c)
done
with _ ->
close_in c;
Sys.remove file
let compile_file ?output ?(opt="") ?stable_name name =
let (pipe, file) =
if Config.ccomp_type = "msvc" && not !Clflags.verbose then
try
let (t, c) = Filename.open_temp_file "msvc" "stdout" in
close_out c;
(Printf.sprintf " > %s" (Filename.quote t), t)
with _ ->
("", "")
else
("", "") in
let debug_prefix_map =
match stable_name with
| Some stable when Config.c_has_debug_prefix_map ->
Printf.sprintf " -fdebug-prefix-map=%s=%s" name stable
| Some _ | None -> "" in
let exit =
command
(Printf.sprintf
"%s%s %s %s -c %s %s %s %s %s%s"
(match !Clflags.c_compiler with
| Some cc -> cc
| None ->
(* #7678: ocamlopt only calls the C compiler to process .c files
from the command line, and the behaviour between
ocamlc/ocamlopt should be identical. *)
(String.concat " " [Config.c_compiler;
Config.ocamlc_cflags;
Config.ocamlc_cppflags]))
debug_prefix_map
(match output with
| None -> ""
| Some o -> Printf.sprintf "%s%s" Config.c_output_obj o)
opt
(if !Clflags.debug && Config.ccomp_type <> "msvc" then "-g" else "")
(String.concat " " (List.rev !Clflags.all_ccopts))
(quote_prefixed "-I"
(List.map (Misc.expand_directory Config.standard_library)
(List.rev !Clflags.include_dirs)))
(Clflags.std_include_flag "-I")
(Filename.quote name)
cl tediously includes the name of the C file as the first thing it
outputs ( in fairness , the tedious thing is that there 's no switch to
disable this behaviour ) . In the absence of the Unix module , use
a temporary file to filter the output ( can not pipe the output to a
filter because this removes the exit status of cl , which is wanted .
outputs (in fairness, the tedious thing is that there's no switch to
disable this behaviour). In the absence of the Unix module, use
a temporary file to filter the output (cannot pipe the output to a
filter because this removes the exit status of cl, which is wanted.
*)
pipe) in
if pipe <> ""
then display_msvc_output file name;
exit
let create_archive archive file_list =
Misc.remove_file archive;
let quoted_archive = Filename.quote archive in
if file_list = [] then
Do n't call the archiver : # 6550/#1094/#9011
else
match Config.ccomp_type with
"msvc" ->
command(Printf.sprintf "link /lib /nologo /out:%s %s"
quoted_archive (quote_files file_list))
| _ ->
assert(String.length Config.ar > 0);
let r1 =
command(Printf.sprintf "%s rc %s %s"
Config.ar quoted_archive (quote_files file_list)) in
if r1 <> 0 || String.length Config.ranlib = 0
then r1
else command(Config.ranlib ^ " " ^ quoted_archive)
let expand_libname cclibs =
cclibs |> List.map (fun cclib ->
if String.starts_with ~prefix:"-l" cclib then
let libname =
"lib" ^ String.sub cclib 2 (String.length cclib - 2) ^ Config.ext_lib in
try
Load_path.find libname
with Not_found ->
libname
else cclib)
type link_mode =
| Exe
| Dll
| MainDll
| Partial
let remove_Wl cclibs =
cclibs |> List.map (fun cclib ->
-Wl,-foo , bar - > -foo bar
if String.length cclib >= 4 && "-Wl," = String.sub cclib 0 4 then
String.map (function ',' -> ' ' | c -> c)
(String.sub cclib 4 (String.length cclib - 4))
else cclib)
let call_linker mode output_name files extra =
Profile.record_call "c-linker" (fun () ->
let cmd =
if mode = Partial then
let (l_prefix, files) =
match Config.ccomp_type with
| "msvc" -> ("/libpath:", expand_libname files)
| _ -> ("-L", files)
in
Printf.sprintf "%s%s %s %s %s"
Config.native_pack_linker
(Filename.quote output_name)
(quote_prefixed l_prefix (Load_path.get_paths ()))
(quote_files (remove_Wl files))
extra
else
Printf.sprintf "%s -o %s %s %s %s %s %s"
(match !Clflags.c_compiler, mode with
| Some cc, _ -> cc
| None, Exe -> Config.mkexe
| None, Dll -> Config.mkdll
| None, MainDll -> Config.mkmaindll
| None, Partial -> assert false
)
(Filename.quote output_name)
( Clflags.std_include_flag " -I " )
(quote_prefixed "-L" (Load_path.get_paths ()))
(String.concat " " (List.rev !Clflags.all_ccopts))
(quote_files files)
extra
in
command cmd
)
let linker_is_flexlink =
Config.mkexe , Config.mkdll and Config.mkmaindll are all flexlink
invocations for the native Windows ports and for , if shared library
support is enabled .
invocations for the native Windows ports and for Cygwin, if shared library
support is enabled. *)
Sys.win32 || Config.supports_shared_libraries && Sys.cygwin
| null | https://raw.githubusercontent.com/dyzsr/ocaml-selectml/875544110abb3350e9fb5ec9bbadffa332c270d2/utils/ccomp.ml | ocaml | ************************************************************************
OCaml
en Automatique.
All rights reserved. This file is distributed under the terms of
special exception on linking described in the file LICENSE.
************************************************************************
Compiling C files and building C libraries
#7678: ocamlopt only calls the C compiler to process .c files
from the command line, and the behaviour between
ocamlc/ocamlopt should be identical. | , projet Cristal , INRIA Rocquencourt
Copyright 1996 Institut National de Recherche en Informatique et
the GNU Lesser General Public License version 2.1 , with the
let command cmdline =
if !Clflags.verbose then begin
prerr_string "+ ";
prerr_string cmdline;
prerr_newline()
end;
let res = Sys.command cmdline in
if res = 127 then raise (Sys_error cmdline);
res
let run_command cmdline = ignore(command cmdline)
Build @responsefile to work around OS limitations on
command - line length .
Under Windows , the length is 8187 minus the length of the
COMSPEC variable ( or 7 if it 's not set ) . To be on the safe side ,
we 'll use a response file if we need to pass 4096 or more bytes of
arguments .
For Unix - like systems , the threshold is 2 ^ 16 ( 64 KiB ) , which is
within the lowest observed limits ( 2 ^ 17 per argument under Linux ;
between 70000 and 80000 for macOS ) .
command-line length.
Under Windows, the max length is 8187 minus the length of the
COMSPEC variable (or 7 if it's not set). To be on the safe side,
we'll use a response file if we need to pass 4096 or more bytes of
arguments.
For Unix-like systems, the threshold is 2^16 (64 KiB), which is
within the lowest observed limits (2^17 per argument under Linux;
between 70000 and 80000 for macOS).
*)
let build_diversion lst =
let (responsefile, oc) = Filename.open_temp_file "camlresp" "" in
List.iter (fun f -> Printf.fprintf oc "%s\n" f) lst;
close_out oc;
at_exit (fun () -> Misc.remove_file responsefile);
"@" ^ responsefile
let quote_files lst =
let lst = List.filter (fun f -> f <> "") lst in
let quoted = List.map Filename.quote lst in
let s = String.concat " " quoted in
if String.length s >= 65536
|| (String.length s >= 4096 && Sys.os_type = "Win32")
then build_diversion quoted
else s
let quote_prefixed pr lst =
let lst = List.filter (fun f -> f <> "") lst in
let lst = List.map (fun f -> pr ^ f) lst in
quote_files lst
let quote_optfile = function
| None -> ""
| Some f -> Filename.quote f
let display_msvc_output file name =
let c = open_in file in
try
let first = input_line c in
if first <> Filename.basename name then
print_endline first;
while true do
print_endline (input_line c)
done
with _ ->
close_in c;
Sys.remove file
let compile_file ?output ?(opt="") ?stable_name name =
let (pipe, file) =
if Config.ccomp_type = "msvc" && not !Clflags.verbose then
try
let (t, c) = Filename.open_temp_file "msvc" "stdout" in
close_out c;
(Printf.sprintf " > %s" (Filename.quote t), t)
with _ ->
("", "")
else
("", "") in
let debug_prefix_map =
match stable_name with
| Some stable when Config.c_has_debug_prefix_map ->
Printf.sprintf " -fdebug-prefix-map=%s=%s" name stable
| Some _ | None -> "" in
let exit =
command
(Printf.sprintf
"%s%s %s %s -c %s %s %s %s %s%s"
(match !Clflags.c_compiler with
| Some cc -> cc
| None ->
(String.concat " " [Config.c_compiler;
Config.ocamlc_cflags;
Config.ocamlc_cppflags]))
debug_prefix_map
(match output with
| None -> ""
| Some o -> Printf.sprintf "%s%s" Config.c_output_obj o)
opt
(if !Clflags.debug && Config.ccomp_type <> "msvc" then "-g" else "")
(String.concat " " (List.rev !Clflags.all_ccopts))
(quote_prefixed "-I"
(List.map (Misc.expand_directory Config.standard_library)
(List.rev !Clflags.include_dirs)))
(Clflags.std_include_flag "-I")
(Filename.quote name)
cl tediously includes the name of the C file as the first thing it
outputs ( in fairness , the tedious thing is that there 's no switch to
disable this behaviour ) . In the absence of the Unix module , use
a temporary file to filter the output ( can not pipe the output to a
filter because this removes the exit status of cl , which is wanted .
outputs (in fairness, the tedious thing is that there's no switch to
disable this behaviour). In the absence of the Unix module, use
a temporary file to filter the output (cannot pipe the output to a
filter because this removes the exit status of cl, which is wanted.
*)
pipe) in
if pipe <> ""
then display_msvc_output file name;
exit
let create_archive archive file_list =
Misc.remove_file archive;
let quoted_archive = Filename.quote archive in
if file_list = [] then
Do n't call the archiver : # 6550/#1094/#9011
else
match Config.ccomp_type with
"msvc" ->
command(Printf.sprintf "link /lib /nologo /out:%s %s"
quoted_archive (quote_files file_list))
| _ ->
assert(String.length Config.ar > 0);
let r1 =
command(Printf.sprintf "%s rc %s %s"
Config.ar quoted_archive (quote_files file_list)) in
if r1 <> 0 || String.length Config.ranlib = 0
then r1
else command(Config.ranlib ^ " " ^ quoted_archive)
let expand_libname cclibs =
cclibs |> List.map (fun cclib ->
if String.starts_with ~prefix:"-l" cclib then
let libname =
"lib" ^ String.sub cclib 2 (String.length cclib - 2) ^ Config.ext_lib in
try
Load_path.find libname
with Not_found ->
libname
else cclib)
type link_mode =
| Exe
| Dll
| MainDll
| Partial
let remove_Wl cclibs =
cclibs |> List.map (fun cclib ->
-Wl,-foo , bar - > -foo bar
if String.length cclib >= 4 && "-Wl," = String.sub cclib 0 4 then
String.map (function ',' -> ' ' | c -> c)
(String.sub cclib 4 (String.length cclib - 4))
else cclib)
let call_linker mode output_name files extra =
Profile.record_call "c-linker" (fun () ->
let cmd =
if mode = Partial then
let (l_prefix, files) =
match Config.ccomp_type with
| "msvc" -> ("/libpath:", expand_libname files)
| _ -> ("-L", files)
in
Printf.sprintf "%s%s %s %s %s"
Config.native_pack_linker
(Filename.quote output_name)
(quote_prefixed l_prefix (Load_path.get_paths ()))
(quote_files (remove_Wl files))
extra
else
Printf.sprintf "%s -o %s %s %s %s %s %s"
(match !Clflags.c_compiler, mode with
| Some cc, _ -> cc
| None, Exe -> Config.mkexe
| None, Dll -> Config.mkdll
| None, MainDll -> Config.mkmaindll
| None, Partial -> assert false
)
(Filename.quote output_name)
( Clflags.std_include_flag " -I " )
(quote_prefixed "-L" (Load_path.get_paths ()))
(String.concat " " (List.rev !Clflags.all_ccopts))
(quote_files files)
extra
in
command cmd
)
let linker_is_flexlink =
Config.mkexe , Config.mkdll and Config.mkmaindll are all flexlink
invocations for the native Windows ports and for , if shared library
support is enabled .
invocations for the native Windows ports and for Cygwin, if shared library
support is enabled. *)
Sys.win32 || Config.supports_shared_libraries && Sys.cygwin
|
74aefca17204dd2c3eec33eeb3aa5eaf62481982c3127f593dc54ac1ed25d8a4 | noinia/hgeometry | IntersectionSpec.hs | # LANGUAGE UnicodeSyntax #
module Geometry.IntersectionSpec where
import Data.Ext
import Geometry.Line
import Geometry.LineSegment
import Geometry.Point
import Geometry.Polygon
import Data.Intersection
import Data.Proxy
import Data.RealNumber.Rational
import Data.Vinyl
import Paths_hgeometry
import Test.Hspec
import Test.QuickCheck
--------------------------------------------------------------------------------
type R = RealNumber 5
-- |
spec :: Spec
spec = do
it ("intersects agrees with intersect: Geometry.Line ") $
property (propIntersectionsAgree @(Line 2 R) @(Line 2 R))
it ("intersects agrees with intersect: Geometry.LineSegment ") $
property (propIntersectionsAgree @(LineSegment 2 () R) @(LineSegment 2 () R))
it ("intersects agrees with intersect: Geometry.LineSegment x Line ") $
property (propIntersectionsAgree @(LineSegment 2 () R) @(Line 2 R))
propIntersectionsAgree :: forall a b. ( IsIntersectableWith a b
, NoIntersection ∈ IntersectionOf a b
, RecApplicative (IntersectionOf a b)
)
=> a -> b -> Expectation
propIntersectionsAgree a b = (a `intersects` b)
`shouldBe`
(defaultNonEmptyIntersection (Proxy @a) (Proxy @b) $ a `intersect` b)
| null | https://raw.githubusercontent.com/noinia/hgeometry/89cd3d3109ec68f877bf8e34dc34b6df337a4ec1/hgeometry/test/src/Geometry/IntersectionSpec.hs | haskell | ------------------------------------------------------------------------------
| | # LANGUAGE UnicodeSyntax #
module Geometry.IntersectionSpec where
import Data.Ext
import Geometry.Line
import Geometry.LineSegment
import Geometry.Point
import Geometry.Polygon
import Data.Intersection
import Data.Proxy
import Data.RealNumber.Rational
import Data.Vinyl
import Paths_hgeometry
import Test.Hspec
import Test.QuickCheck
type R = RealNumber 5
spec :: Spec
spec = do
it ("intersects agrees with intersect: Geometry.Line ") $
property (propIntersectionsAgree @(Line 2 R) @(Line 2 R))
it ("intersects agrees with intersect: Geometry.LineSegment ") $
property (propIntersectionsAgree @(LineSegment 2 () R) @(LineSegment 2 () R))
it ("intersects agrees with intersect: Geometry.LineSegment x Line ") $
property (propIntersectionsAgree @(LineSegment 2 () R) @(Line 2 R))
propIntersectionsAgree :: forall a b. ( IsIntersectableWith a b
, NoIntersection ∈ IntersectionOf a b
, RecApplicative (IntersectionOf a b)
)
=> a -> b -> Expectation
propIntersectionsAgree a b = (a `intersects` b)
`shouldBe`
(defaultNonEmptyIntersection (Proxy @a) (Proxy @b) $ a `intersect` b)
|
9f94f90c82455e0082d8d2058c160ea7e00006ae4eaf6ab9c3c87a00f62cfd3f | serras/hinc | Main.hs | # language NamedFieldPuns #
{-# language OverloadedStrings #-}
# language RecordWildCards #
module Main where
import Data.List (intercalate)
import Hinc.Parser
import Language.Haskell.Exts.Pretty (Pretty, prettyPrint)
import Miso
import Miso.String (JSString, fromMisoString, toMisoString)
import Text.Megaparsec
main :: IO ()
main = startApp App {..}
where
initialAction = Translate
model = Model (toMisoString initialCode) ""
update = updateModel
view = viewModel
events = defaultEvents
subs = []
mountPoint = Nothing
logLevel = Off
initialCode = unlines [
"data Maybe<a> {"
, " Nothing,"
, " Just(value: a)"
, "} : Show, Eq"
, ""
, "let f(xs: List<Int>, p: (Int) => Bool): List<a>"
, " = effect {"
, " let x = await xs"
, " guard(p(x))"
, " x.add(1).pure"
, " }"
]
data Model = Model {
currentText :: JSString
, translated :: JSString
} deriving (Show, Eq)
data Action
= ChangeCurrentText JSString
| Translate
deriving (Show, Eq)
updateModel :: Action -> Model -> Effect Action Model
updateModel (ChangeCurrentText t) m
= noEff (m { currentText = t })
updateModel Translate m
= let s = fromMisoString $ currentText m
in case map prettyPrint <$> Text.Megaparsec.parse declsP "test" s of
Left e -> noEff (m { translated = toMisoString (show e) })
Right s -> noEff (m { translated = toMisoString (intercalate "\n\n" s) })
| Constructs a virtual DOM from a model
viewModel :: Model -> View Action
viewModel Model { currentText, translated }
= div_ [ class_ "jumbotron vh-100"] [
h1_ [ class_ "display-4" ] [ text "Haskell In New Clothes" ]
, p_ [ class_ "lead" ]
[ text "Braces-and-parens syntax for your favorite language "
, a_ [ href_ "" ] [ text "Why?" ] ]
, div_ [ class_ "row" ] [
div_ [ class_ "col" ] [
textarea_ [ class_ "form-control text-monospace"
, onChange ChangeCurrentText
, rows_ "10" ]
[ text currentText ]
]
, div_ [ class_ "col-1" ] [
button_ [ class_ "btn btn-primary"
, onClick Translate ]
[ text "->" ]
]
, div_ [ class_ "col" ] [
textarea_ [ class_ "form-control text-monospace"
, rows_ "10"
, readonly_ True ]
[ text translated ]
]
]
, div_ [ class_ "text-muted" ]
[ text "Proudly \129322 developed by "
, a_ [ href_ "" ] [ text "@trupill" ]
, text " using "
, a_ [ href_ "-miso.org/" ] [ text "Miso 🍲" ]
, text " and hosted in "
, a_ [ href_ "" ] [ text "GitHub" ]
]
, link_ [ rel_ "stylesheet"
, href_ "" ]
]
| null | https://raw.githubusercontent.com/serras/hinc/219b9b15050d9684d7d55cb7edd3191c49f23835/web/Main.hs | haskell | # language OverloadedStrings # | # language NamedFieldPuns #
# language RecordWildCards #
module Main where
import Data.List (intercalate)
import Hinc.Parser
import Language.Haskell.Exts.Pretty (Pretty, prettyPrint)
import Miso
import Miso.String (JSString, fromMisoString, toMisoString)
import Text.Megaparsec
main :: IO ()
main = startApp App {..}
where
initialAction = Translate
model = Model (toMisoString initialCode) ""
update = updateModel
view = viewModel
events = defaultEvents
subs = []
mountPoint = Nothing
logLevel = Off
initialCode = unlines [
"data Maybe<a> {"
, " Nothing,"
, " Just(value: a)"
, "} : Show, Eq"
, ""
, "let f(xs: List<Int>, p: (Int) => Bool): List<a>"
, " = effect {"
, " let x = await xs"
, " guard(p(x))"
, " x.add(1).pure"
, " }"
]
data Model = Model {
currentText :: JSString
, translated :: JSString
} deriving (Show, Eq)
data Action
= ChangeCurrentText JSString
| Translate
deriving (Show, Eq)
updateModel :: Action -> Model -> Effect Action Model
updateModel (ChangeCurrentText t) m
= noEff (m { currentText = t })
updateModel Translate m
= let s = fromMisoString $ currentText m
in case map prettyPrint <$> Text.Megaparsec.parse declsP "test" s of
Left e -> noEff (m { translated = toMisoString (show e) })
Right s -> noEff (m { translated = toMisoString (intercalate "\n\n" s) })
| Constructs a virtual DOM from a model
viewModel :: Model -> View Action
viewModel Model { currentText, translated }
= div_ [ class_ "jumbotron vh-100"] [
h1_ [ class_ "display-4" ] [ text "Haskell In New Clothes" ]
, p_ [ class_ "lead" ]
[ text "Braces-and-parens syntax for your favorite language "
, a_ [ href_ "" ] [ text "Why?" ] ]
, div_ [ class_ "row" ] [
div_ [ class_ "col" ] [
textarea_ [ class_ "form-control text-monospace"
, onChange ChangeCurrentText
, rows_ "10" ]
[ text currentText ]
]
, div_ [ class_ "col-1" ] [
button_ [ class_ "btn btn-primary"
, onClick Translate ]
[ text "->" ]
]
, div_ [ class_ "col" ] [
textarea_ [ class_ "form-control text-monospace"
, rows_ "10"
, readonly_ True ]
[ text translated ]
]
]
, div_ [ class_ "text-muted" ]
[ text "Proudly \129322 developed by "
, a_ [ href_ "" ] [ text "@trupill" ]
, text " using "
, a_ [ href_ "-miso.org/" ] [ text "Miso 🍲" ]
, text " and hosted in "
, a_ [ href_ "" ] [ text "GitHub" ]
]
, link_ [ rel_ "stylesheet"
, href_ "" ]
]
|
f2a904c3a89ad4c99c6ca0761faf547f7a94fded79266e6f30364b2d439be906 | haskell-unordered-containers/unordered-containers | HashMapStrict.hs | # LANGUAGE CPP #
#define STRICT
#include "HashMapLazy.hs"
| null | https://raw.githubusercontent.com/haskell-unordered-containers/unordered-containers/c48237994d8a2476c5029e494feb052a7354e29a/tests/Properties/HashMapStrict.hs | haskell | # LANGUAGE CPP #
#define STRICT
#include "HashMapLazy.hs"
| |
a494691c5b694dd088f456c1885ec1a56c6d9e55ec8e05905dd1df84da9e64d6 | dgiot/dgiot | dgiot_udp_channel.erl | %%--------------------------------------------------------------------
Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved .
%%
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
%%
%% -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.
%%--------------------------------------------------------------------
-module(dgiot_udp_channel).
-behavior(dgiot_channelx).
-include_lib("dgiot/include/logger.hrl").
-include("dgiot_bridge.hrl").
-define(TYPE, <<"UDP">>).
-author("kenneth").
-record(state, {id, ip, port, transport, env, product, log}).
%% API
-export([start/2]).
-export([init/3, handle_init/1, handle_event/3, handle_message/2, stop/3]).
-define(SOCKOPTS, [binary, {reuseaddr, true}]).
注册通道类型
-channel_type(#{
cType => ?TYPE,
type => ?PROTOCOL_CHL,
title => #{
zh => <<"UDP采集通道"/utf8>>
},
description => #{
zh => <<"UDP采集通道"/utf8>>
}
}).
%% 注册通道参数
-params(#{
<<"port">> => #{
order => 1,
type => integer,
required => true,
default => 3456,
title => #{
zh => <<"端口"/utf8>>
},
description => #{
zh => <<"侦听端口"/utf8>>
}
},
<<"ico">> => #{
order => 102,
type => string,
required => false,
default => <<"/dgiot_file/shuwa_tech/zh/product/dgiot/channel/UdpIcon.png">>,
title => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
},
description => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
}
}
}).
start(ChannelId, ChannelArgs) ->
ok = esockd:start(),
dgiot_channelx:add(?TYPE, ChannelId, ?MODULE, ChannelArgs).
通道初始化
init(?TYPE, ChannelId, #{<<"port">> := Port} = _ChannelArgs) ->
case dgiot_bridge:get_products(ChannelId) of
{ok, ?TYPE, ProductIds} ->
State = #state{
id = ChannelId,
env = #{},
product = ProductIds
},
Name : , ChannelId ) ,
= { ? MODULE , start_link , [ State ] } ,
ChildSpec = esockd : udp_child_spec(binary_to_atom(Name , utf8 ) , Port , [ { udp_options , ? SOCKOPTS } ] , ) ,
ChildSpec = dgiot_udp_worker:child_spec(Port, State),
{ok, State, ChildSpec};
{error, not_find} ->
{stop, not_find_product}
end;
init(?TYPE, _ChannelId, _Args) ->
io:format("~s ~p _Args: ~p~n", [?FILE, ?LINE, _Args]),
{ok, #{}, #{}}.
handle_init(State) ->
{ok, State}.
通道消息处理 ,
handle_event(_EventId, _Event, State) ->
{ok, State}.
handle_message(Message, #state{id = ChannelId, product = ProductId} = State) ->
?LOG(info, "Channel ~p, Product ~p, handle_message ~p", [ChannelId, ProductId, Message]),
do_product(handle_info, [Message], State).
stop(ChannelType, ChannelId, _) ->
?LOG(info, "channel stop ~p,~p", [ChannelType, ChannelId]),
ok.
do_product(Fun, Args, #state{id = ChannelId, env = Env, product = ProductIds} = State) ->
case dgiot_bridge:apply_channel(ChannelId, ProductIds, Fun, Args, Env) of
{ok, NewEnv} ->
{ok, update_state(NewEnv, State)};
{stop, Reason, NewEnv} ->
{stop, Reason, update_state(NewEnv, State)};
{reply, ProductId, Reply, NewEnv} ->
{reply, ProductId, Reply, update_state(NewEnv, State)}
end.
update_state(Env, State) ->
State#state{env = maps:without([<<"send">>], Env)}.
| null | https://raw.githubusercontent.com/dgiot/dgiot/a6b816a094b1c9bd024ce40b8142375a0f0289d8/apps/dgiot_bridge/src/channel/dgiot_udp_channel.erl | erlang | --------------------------------------------------------------------
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing, software
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.
--------------------------------------------------------------------
API
注册通道参数 | Copyright ( c ) 2020 - 2021 DGIOT Technologies Co. , Ltd. All Rights Reserved .
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(dgiot_udp_channel).
-behavior(dgiot_channelx).
-include_lib("dgiot/include/logger.hrl").
-include("dgiot_bridge.hrl").
-define(TYPE, <<"UDP">>).
-author("kenneth").
-record(state, {id, ip, port, transport, env, product, log}).
-export([start/2]).
-export([init/3, handle_init/1, handle_event/3, handle_message/2, stop/3]).
-define(SOCKOPTS, [binary, {reuseaddr, true}]).
注册通道类型
-channel_type(#{
cType => ?TYPE,
type => ?PROTOCOL_CHL,
title => #{
zh => <<"UDP采集通道"/utf8>>
},
description => #{
zh => <<"UDP采集通道"/utf8>>
}
}).
-params(#{
<<"port">> => #{
order => 1,
type => integer,
required => true,
default => 3456,
title => #{
zh => <<"端口"/utf8>>
},
description => #{
zh => <<"侦听端口"/utf8>>
}
},
<<"ico">> => #{
order => 102,
type => string,
required => false,
default => <<"/dgiot_file/shuwa_tech/zh/product/dgiot/channel/UdpIcon.png">>,
title => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
},
description => #{
en => <<"channel ICO">>,
zh => <<"通道ICO"/utf8>>
}
}
}).
start(ChannelId, ChannelArgs) ->
ok = esockd:start(),
dgiot_channelx:add(?TYPE, ChannelId, ?MODULE, ChannelArgs).
通道初始化
init(?TYPE, ChannelId, #{<<"port">> := Port} = _ChannelArgs) ->
case dgiot_bridge:get_products(ChannelId) of
{ok, ?TYPE, ProductIds} ->
State = #state{
id = ChannelId,
env = #{},
product = ProductIds
},
Name : , ChannelId ) ,
= { ? MODULE , start_link , [ State ] } ,
ChildSpec = esockd : udp_child_spec(binary_to_atom(Name , utf8 ) , Port , [ { udp_options , ? SOCKOPTS } ] , ) ,
ChildSpec = dgiot_udp_worker:child_spec(Port, State),
{ok, State, ChildSpec};
{error, not_find} ->
{stop, not_find_product}
end;
init(?TYPE, _ChannelId, _Args) ->
io:format("~s ~p _Args: ~p~n", [?FILE, ?LINE, _Args]),
{ok, #{}, #{}}.
handle_init(State) ->
{ok, State}.
通道消息处理 ,
handle_event(_EventId, _Event, State) ->
{ok, State}.
handle_message(Message, #state{id = ChannelId, product = ProductId} = State) ->
?LOG(info, "Channel ~p, Product ~p, handle_message ~p", [ChannelId, ProductId, Message]),
do_product(handle_info, [Message], State).
stop(ChannelType, ChannelId, _) ->
?LOG(info, "channel stop ~p,~p", [ChannelType, ChannelId]),
ok.
do_product(Fun, Args, #state{id = ChannelId, env = Env, product = ProductIds} = State) ->
case dgiot_bridge:apply_channel(ChannelId, ProductIds, Fun, Args, Env) of
{ok, NewEnv} ->
{ok, update_state(NewEnv, State)};
{stop, Reason, NewEnv} ->
{stop, Reason, update_state(NewEnv, State)};
{reply, ProductId, Reply, NewEnv} ->
{reply, ProductId, Reply, update_state(NewEnv, State)}
end.
update_state(Env, State) ->
State#state{env = maps:without([<<"send">>], Env)}.
|
90a464357bd05325cdb4fd0218ca63e22c78f75f9b296d82355653114d5def09 | pezipink/Pisemble | info.rkt | #lang info
(define collection "pisemble")
(define version "0.1.0")
(define deps
'("base"))
(define build-deps
'("scribble-lib"
"racket-doc"))
(define pkg-desc "ARM assembler")
(define pkg-authors '(""))
(define scribblings '(("pisemble/pisemble.scrbl" ())))
| null | https://raw.githubusercontent.com/pezipink/Pisemble/ee6bf264bc8f9fb2b0d5b51c9a76503e3e80f768/info.rkt | racket | #lang info
(define collection "pisemble")
(define version "0.1.0")
(define deps
'("base"))
(define build-deps
'("scribble-lib"
"racket-doc"))
(define pkg-desc "ARM assembler")
(define pkg-authors '(""))
(define scribblings '(("pisemble/pisemble.scrbl" ())))
| |
453a84496721224d43c650c29ced4fbeffbc0922c6f7e60ff2d1cdde42e7e5a2 | dradtke/Lisp-Text-Editor | font.lisp | (in-package :cl-cairo2)
;;;; TODO:
;;;;
;;;; - text clusters (maybe)
;;;;
;;;; NOT TODO:
;;;;
;;;; - cairo_scaled_font_text_to_glyphs: this seems to be essentially
identical to the toy interface , and neither Quartz nor
;;;; backends even seem to implement this, and there doesn't seem to
;;;; be a way to tell. I'm not sure what the point is.
;; Types
;;;; These are mostly for specialization; specific implementations are
needed to get a useful instance ( FreeType , etc ) .
(defclass font-face (cairo-object) ())
(defclass scaled-font (cairo-object)
((font-face :initarg :font-face :initform nil
:accessor scaled-font-face)))
(defclass font-options (cairo-object) ())
;; Generic Functions
(defgeneric create-font (source-face &key &allow-other-keys)
(:documentation "Create a FONT-FACE (cairo_font_t) from SOURCE-FACE"))
(defgeneric set-font (font-face &optional context)
(:documentation "Set the current font to FONT-FACE"))
;; Methods
(defmethod set-font ((font-face font-face) &optional (context *context*))
(set-font-face font-face context))
(defmethod set-font ((font-face scaled-font) &optional (context *context*))
(set-scaled-font font-face context))
(defmethod lowlevel-destroy ((object font-face))
(cairo_font_face_destroy (get-pointer object)))
(defmethod lowlevel-destroy ((object scaled-font))
(cairo_scaled_font_destroy (get-pointer object)))
(defmethod lowlevel-destroy ((object font-options))
(cairo_font_options_destroy (get-pointer object)))
(defmethod lowlevel-status ((object font-face))
(cairo_font_face_status (get-pointer object)))
(defmethod lowlevel-status ((object scaled-font))
(cairo_scaled_font_status (get-pointer object)))
(defmethod lowlevel-status ((object font-options))
(cairo_font_options_status (get-pointer object)))
;; cairo_font_face_t functions
(defun font-face-get-type (font)
(cairo_font_face_get_type (get-pointer font)))
;; cairo_scaled_font_t functions
(defun create-scaled-font (font font-matrix matrix options)
(with-alive-object (font f-ptr)
(with-alive-object (options o-ptr)
(let ((fm-ptr (foreign-alloc 'cairo_matrix_t))
(m-ptr (foreign-alloc 'cairo_matrix_t)))
(trans-matrix-copy-in fm-ptr font-matrix)
(trans-matrix-copy-in m-ptr matrix)
(let* ((s-ptr (cairo_scaled_font_create f-ptr fm-ptr m-ptr o-ptr))
(scaled-font (make-instance 'scaled-font
:pointer s-ptr
:font-face font)))
(tg:cancel-finalization options)
(tg:finalize scaled-font
(lambda ()
(cairo_scaled_font_destroy s-ptr)
(foreign-free fm-ptr)
(foreign-free m-ptr)
(cairo_font_options_destroy o-ptr)))
scaled-font)))))
(defun scaled-font-extents (scaled-font)
(with-alive-object (scaled-font font-pointer)
(with-font-extents-t-out extents-pointer
(cairo_scaled_font_extents font-pointer extents-pointer))))
(defun scaled-font-text-extents (scaled-font string)
(with-alive-object (scaled-font font-pointer)
(with-font-extents-t-out extents-pointer
(with-foreign-string (cstr string)
(cairo_scaled_font_text_extents font-pointer cstr extents-pointer)))))
(defun scaled-font-glyph-extents (scaled-font glyphs)
(with-alive-object (scaled-font font-pointer)
(with-font-extents-t-out extents-pointer
(with-foreign-object (arr :int (length glyphs))
(loop for g across glyphs
for i from 0
do (setf (mem-aref arr :int i) (aref glyphs i)))
(cairo_scaled_font_glyph_extents font-pointer arr (length glyphs)
extents-pointer)))))
;; *_get_font_face is covered by scaled-font-face
* _ get_font_options
* _
;; *_get_ctm
;; *_get_scale_matrix
(defun scaled-font-get-type (scaled-font)
(with-alive-object (scaled-font font-pointer)
(cairo_scaled_font_get_type font-pointer)))
cairo_font_options_t functions
(defun create-font-options ()
(let* ((pointer (cairo_font_options_create))
(options (make-instance 'font-options :pointer pointer)))
(tg:finalize options (lambda () (cairo_font_options_destroy pointer)))
options))
(defun font-options-copy (font-options)
(with-alive-object (font-options src)
(let* ((dest (cairo_font_options_copy src))
(options (make-instance 'font-options :pointer dest)))
(tg:finalize options (lambda () (cairo_font_options_destroy dest)))
options)))
(defun font-options-merge (fo1 fo2)
(with-alive-object (fo1 ptr1)
(with-alive-object (fo2 ptr2)
(cairo_font_options_merge fo1 fo2))))
(defun font-options-hash (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_hash ptr)))
(defun font-options-equal (fo1 fo2)
(with-alive-object (fo1 ptr1)
(with-alive-object (fo2 ptr2)
(cairo_font_options_equal fo1 fo2))))
(defun font-options-set-antialias (font-options antialias-type)
(with-alive-object (font-options ptr)
(cairo_font_options_set_antialias ptr antialias-type)))
(defun font-options-get-antialias (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_get_antialias ptr)))
(defun font-options-set-subpixel-order (font-options subpixel-order)
(with-alive-object (font-options ptr)
(cairo_font_options_set_subpixel_order ptr subpixel-order)))
(defun font-options-get-subpixel-order (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_get_subpixel_order ptr)))
(defun font-options-set-hint-style (font-options hint-style)
(with-alive-object (font-options ptr)
(cairo_font_options_set_hint_style ptr hint-style)))
(defun font-options-get-hint-style (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_get_hint_style ptr)))
(defun font-options-set-hint-metrics (font-options hint-metrics)
(with-alive-object (font-options ptr)
(cairo_font_options_set_hint_metrics ptr hint-metrics)))
(defun font-options-get-hint-metrics (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_get_hint_metrics ptr)))
| null | https://raw.githubusercontent.com/dradtke/Lisp-Text-Editor/b0947828eda82d7edd0df8ec2595e7491a633580/quicklisp/dists/quicklisp/software/cl-cairo2-20120208-git/src/font.lisp | lisp | TODO:
- text clusters (maybe)
NOT TODO:
- cairo_scaled_font_text_to_glyphs: this seems to be essentially
backends even seem to implement this, and there doesn't seem to
be a way to tell. I'm not sure what the point is.
Types
These are mostly for specialization; specific implementations are
Generic Functions
Methods
cairo_font_face_t functions
cairo_scaled_font_t functions
*_get_font_face is covered by scaled-font-face
*_get_ctm
*_get_scale_matrix | (in-package :cl-cairo2)
identical to the toy interface , and neither Quartz nor
needed to get a useful instance ( FreeType , etc ) .
(defclass font-face (cairo-object) ())
(defclass scaled-font (cairo-object)
((font-face :initarg :font-face :initform nil
:accessor scaled-font-face)))
(defclass font-options (cairo-object) ())
(defgeneric create-font (source-face &key &allow-other-keys)
(:documentation "Create a FONT-FACE (cairo_font_t) from SOURCE-FACE"))
(defgeneric set-font (font-face &optional context)
(:documentation "Set the current font to FONT-FACE"))
(defmethod set-font ((font-face font-face) &optional (context *context*))
(set-font-face font-face context))
(defmethod set-font ((font-face scaled-font) &optional (context *context*))
(set-scaled-font font-face context))
(defmethod lowlevel-destroy ((object font-face))
(cairo_font_face_destroy (get-pointer object)))
(defmethod lowlevel-destroy ((object scaled-font))
(cairo_scaled_font_destroy (get-pointer object)))
(defmethod lowlevel-destroy ((object font-options))
(cairo_font_options_destroy (get-pointer object)))
(defmethod lowlevel-status ((object font-face))
(cairo_font_face_status (get-pointer object)))
(defmethod lowlevel-status ((object scaled-font))
(cairo_scaled_font_status (get-pointer object)))
(defmethod lowlevel-status ((object font-options))
(cairo_font_options_status (get-pointer object)))
(defun font-face-get-type (font)
(cairo_font_face_get_type (get-pointer font)))
(defun create-scaled-font (font font-matrix matrix options)
(with-alive-object (font f-ptr)
(with-alive-object (options o-ptr)
(let ((fm-ptr (foreign-alloc 'cairo_matrix_t))
(m-ptr (foreign-alloc 'cairo_matrix_t)))
(trans-matrix-copy-in fm-ptr font-matrix)
(trans-matrix-copy-in m-ptr matrix)
(let* ((s-ptr (cairo_scaled_font_create f-ptr fm-ptr m-ptr o-ptr))
(scaled-font (make-instance 'scaled-font
:pointer s-ptr
:font-face font)))
(tg:cancel-finalization options)
(tg:finalize scaled-font
(lambda ()
(cairo_scaled_font_destroy s-ptr)
(foreign-free fm-ptr)
(foreign-free m-ptr)
(cairo_font_options_destroy o-ptr)))
scaled-font)))))
(defun scaled-font-extents (scaled-font)
(with-alive-object (scaled-font font-pointer)
(with-font-extents-t-out extents-pointer
(cairo_scaled_font_extents font-pointer extents-pointer))))
(defun scaled-font-text-extents (scaled-font string)
(with-alive-object (scaled-font font-pointer)
(with-font-extents-t-out extents-pointer
(with-foreign-string (cstr string)
(cairo_scaled_font_text_extents font-pointer cstr extents-pointer)))))
(defun scaled-font-glyph-extents (scaled-font glyphs)
(with-alive-object (scaled-font font-pointer)
(with-font-extents-t-out extents-pointer
(with-foreign-object (arr :int (length glyphs))
(loop for g across glyphs
for i from 0
do (setf (mem-aref arr :int i) (aref glyphs i)))
(cairo_scaled_font_glyph_extents font-pointer arr (length glyphs)
extents-pointer)))))
* _ get_font_options
* _
(defun scaled-font-get-type (scaled-font)
(with-alive-object (scaled-font font-pointer)
(cairo_scaled_font_get_type font-pointer)))
cairo_font_options_t functions
(defun create-font-options ()
(let* ((pointer (cairo_font_options_create))
(options (make-instance 'font-options :pointer pointer)))
(tg:finalize options (lambda () (cairo_font_options_destroy pointer)))
options))
(defun font-options-copy (font-options)
(with-alive-object (font-options src)
(let* ((dest (cairo_font_options_copy src))
(options (make-instance 'font-options :pointer dest)))
(tg:finalize options (lambda () (cairo_font_options_destroy dest)))
options)))
(defun font-options-merge (fo1 fo2)
(with-alive-object (fo1 ptr1)
(with-alive-object (fo2 ptr2)
(cairo_font_options_merge fo1 fo2))))
(defun font-options-hash (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_hash ptr)))
(defun font-options-equal (fo1 fo2)
(with-alive-object (fo1 ptr1)
(with-alive-object (fo2 ptr2)
(cairo_font_options_equal fo1 fo2))))
(defun font-options-set-antialias (font-options antialias-type)
(with-alive-object (font-options ptr)
(cairo_font_options_set_antialias ptr antialias-type)))
(defun font-options-get-antialias (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_get_antialias ptr)))
(defun font-options-set-subpixel-order (font-options subpixel-order)
(with-alive-object (font-options ptr)
(cairo_font_options_set_subpixel_order ptr subpixel-order)))
(defun font-options-get-subpixel-order (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_get_subpixel_order ptr)))
(defun font-options-set-hint-style (font-options hint-style)
(with-alive-object (font-options ptr)
(cairo_font_options_set_hint_style ptr hint-style)))
(defun font-options-get-hint-style (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_get_hint_style ptr)))
(defun font-options-set-hint-metrics (font-options hint-metrics)
(with-alive-object (font-options ptr)
(cairo_font_options_set_hint_metrics ptr hint-metrics)))
(defun font-options-get-hint-metrics (font-options)
(with-alive-object (font-options ptr)
(cairo_font_options_get_hint_metrics ptr)))
|
7c8c6683ebacfeb8f67469b2baf0557b6e56d11675df0cd4dee0df42a9286426 | MinaProtocol/mina | mina_net2.mli | * An interface to limited libp2p functionality for Coda to use .
A subprocess is spawned to run the go - libp2p code . This module communicates
with that subprocess over an ad - hoc RPC protocol .
TODO : separate internal helper errors from underlying libp2p errors .
In general , functions in this module return [ ' a Deferred . ] . Unless
otherwise mentioned , the deferred is resolved immediately once the RPC action
to the libp2p helper is finished . Unless otherwise mentioned , everything can
throw an exception due to an internal helper error . These indicate a bug in
this module / the helper , and not misuse .
Some errors can arise from calling certain functions before [ configure ] has been
called . In general , anything that returns an [ Or_error ] can fail in this manner .
A [ Mina_net2.t ] has the following lifecycle :
- Fresh : the result of [ Mina_net2.create ] . This spawns the helper process but
does not connect to any network . Few operations can be done on fresh nets ,
only [ Keypair.random ] for now .
- Configured : after calling [ Mina_net2.configure ] . Configure creates the libp2p
objects and can start listening on network sockets . This does n't join any DHT
or attempt peer connections . Configured networks can do everything but any
pubsub messages may have very limited reach without being in the DHT .
- Active : after calling [ Mina_net2.begin_advertising ] . This joins the DHT ,
announcing our existence to our peers and initiating local mDNS discovery .
- Closed : after calling [ Mina_net2.shutdown ] . This flushes all the pending RPC
TODO : consider encoding the network state in the types .
A note about connection limits :
In the original coda_net , connection limits were enforced synchronously on
every received connection . Right now with mina_net2 , connection management is
asynchronous and post - hoc . In the background , once per minute it checks the
connection count . If it is above the " high water mark " , it will close
( " trim " ) eligible connections until it reaches the " low water mark " . All
connections start with a " grace period " where they wo n't be closed . Peer IDs
can be marked as " protected " which prevents them being trimmed . Ember believes this
is vulnerable to resource exhaustion by opening many new connections .
A subprocess is spawned to run the go-libp2p code. This module communicates
with that subprocess over an ad-hoc RPC protocol.
TODO: separate internal helper errors from underlying libp2p errors.
In general, functions in this module return ['a Deferred.Or_error.t]. Unless
otherwise mentioned, the deferred is resolved immediately once the RPC action
to the libp2p helper is finished. Unless otherwise mentioned, everything can
throw an exception due to an internal helper error. These indicate a bug in
this module/the helper, and not misuse.
Some errors can arise from calling certain functions before [configure] has been
called. In general, anything that returns an [Or_error] can fail in this manner.
A [Mina_net2.t] has the following lifecycle:
- Fresh: the result of [Mina_net2.create]. This spawns the helper process but
does not connect to any network. Few operations can be done on fresh nets,
only [Keypair.random] for now.
- Configured: after calling [Mina_net2.configure]. Configure creates the libp2p
objects and can start listening on network sockets. This doesn't join any DHT
or attempt peer connections. Configured networks can do everything but any
pubsub messages may have very limited reach without being in the DHT.
- Active: after calling [Mina_net2.begin_advertising]. This joins the DHT,
announcing our existence to our peers and initiating local mDNS discovery.
- Closed: after calling [Mina_net2.shutdown]. This flushes all the pending RPC
TODO: consider encoding the network state in the types.
A note about connection limits:
In the original coda_net, connection limits were enforced synchronously on
every received connection. Right now with mina_net2, connection management is
asynchronous and post-hoc. In the background, once per minute it checks the
connection count. If it is above the "high water mark", it will close
("trim") eligible connections until it reaches the "low water mark". All
connections start with a "grace period" where they won't be closed. Peer IDs
can be marked as "protected" which prevents them being trimmed. Ember believes this
is vulnerable to resource exhaustion by opening many new connections.
*)
open Core
open Async
open Network_peer
exception Libp2p_helper_died_unexpectedly
(** Handle to all network functionality. *)
type t
* A " multiaddr " is libp2p 's extensible encoding for network addresses .
They generally look like paths , and are read left - to - right . Each protocol
type defines how to decode its address format , and everything leftover is
encapsulated inside that protocol .
Some example :
- [ /p2p / QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC ]
- [ /ip4/127.0.0.1 / tcp/1234 / p2p / QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC ]
- [ /ip6/2601:9:4f81:9700:803e : ca65:66e8 : c21 ]
They generally look like paths, and are read left-to-right. Each protocol
type defines how to decode its address format, and everything leftover is
encapsulated inside that protocol.
Some example multiaddrs:
- [/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC]
- [/ip4/127.0.0.1/tcp/1234/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC]
- [/ip6/2601:9:4f81:9700:803e:ca65:66e8:c21]
*)
module Multiaddr : sig
type t [@@deriving compare, bin_io]
val to_string : t -> string
val of_string : string -> t
val to_peer : t -> Network_peer.Peer.t option
val of_peer : Network_peer.Peer.t -> t
* can a multiaddr plausibly be used as a Peer.t ?
a syntactic check only ; a return value of
true does not guarantee that the multiaddress can
be used as a peer by libp2p
a syntactic check only; a return value of
true does not guarantee that the multiaddress can
be used as a peer by libp2p
*)
val valid_as_peer : t -> bool
val of_file_contents : string -> t list
end
module Keypair : sig
[%%versioned:
module Stable : sig
module V1 : sig
type t
end
end]
(** Formats this keypair to a comma-separated list of public key, secret key, and peer_id. *)
val to_string : t -> string
(** Undo [to_string t].
Only fails if the string has the wrong format, not if the embedded
keypair data is corrupt. *)
val of_string : string -> t Or_error.t
val to_peer_id : t -> Peer.Id.t
val secret : t -> string
end
module Validation_callback = Validation_callback
module Sink = Sink
module For_tests : sig
module Helper = Libp2p_helper
val generate_random_keypair : Helper.t -> Keypair.t Deferred.t
val multiaddr_to_libp2p_ipc : Multiaddr.t -> Libp2p_ipc.multiaddr
val empty_libp2p_ipc_gating_config : Libp2p_ipc.gating_config
end
(** [create ~logger ~conf_dir] starts a new [net] storing its state in [conf_dir]
*
* The optional [allow_multiple_instances] defaults to `false`. A `true` value
* allows spawning multiple subprocesses, which can be useful for tests.
*
* The new [net] isn't connected to any network until [configure] is called.
*
* This can fail for a variety of reasons related to spawning the subprocess.
*)
val create :
?allow_multiple_instances:bool
-> all_peers_seen_metric:bool
-> logger:Logger.t
-> pids:Child_processes.Termination.t
-> conf_dir:string
-> on_peer_connected:(Peer.Id.t -> unit)
-> on_peer_disconnected:(Peer.Id.t -> unit)
-> unit
-> t Deferred.Or_error.t
(** State for the connection gateway. It will disallow connections from IPs
or peer IDs in [banned_peers], except for those listed in [trusted_peers]. If
[isolate] is true, only connections to [trusted_peers] are allowed. *)
type connection_gating =
{ banned_peers : Peer.t list; trusted_peers : Peer.t list; isolate : bool }
* Configure the network connection .
*
* Listens on each address in [ maddrs ] .
*
* This will only connect to peers that share the same [ network_id ] . [ on_new_peer ] , if present ,
* will be called for each peer we connect to . [ unsafe_no_trust_ip ] , if true , will not attempt to
* report trust actions for the IPs of observed connections .
*
* Whenever the connection list gets too small , [ seed_peers ] will be
* candidates for reconnection for peer discovery .
*
* This fails if initializing libp2p fails for any reason .
*
* Listens on each address in [maddrs].
*
* This will only connect to peers that share the same [network_id]. [on_new_peer], if present,
* will be called for each peer we connect to. [unsafe_no_trust_ip], if true, will not attempt to
* report trust actions for the IPs of observed connections.
*
* Whenever the connection list gets too small, [seed_peers] will be
* candidates for reconnection for peer discovery.
*
* This fails if initializing libp2p fails for any reason.
*)
val configure :
t
-> me:Keypair.t
-> external_maddr:Multiaddr.t
-> maddrs:Multiaddr.t list
-> network_id:string
-> metrics_port:int option
-> unsafe_no_trust_ip:bool
-> flooding:bool
-> direct_peers:Multiaddr.t list
-> peer_exchange:bool
-> peer_protection_ratio:float
-> seed_peers:Multiaddr.t list
-> initial_gating_config:connection_gating
-> min_connections:int
-> max_connections:int
-> validation_queue_size:int
-> known_private_ip_nets:Core.Unix.Cidr.t list
-> topic_config:string list list
-> unit Deferred.Or_error.t
(** The keypair the network was configured with.
*
* Resolved once configuration succeeds.
*)
val me : t -> Keypair.t Deferred.t
(** List of all peers we know about. *)
val peers : t -> Peer.t list Deferred.t
val bandwidth_info :
t
-> ([ `Input of float ] * [ `Output of float ] * [ `Cpu_usage of float ])
Deferred.Or_error.t
(** Set node status to be served to peers requesting node status. *)
val set_node_status : t -> string -> unit Deferred.Or_error.t
(** Get node status from given peer. *)
val get_peer_node_status : t -> Multiaddr.t -> string Deferred.Or_error.t
val generate_random_keypair : t -> Keypair.t Deferred.t
module Pubsub : sig
type 'a subscription
* Subscribe to a pubsub topic .
*
* Fails if already subscribed . If it succeeds , incoming messages for that
* topic will be written to the [ Subscription.message_pipe t ] . Returned deferred
* is resolved with [ Ok sub ] as soon as the subscription is enqueued .
*
* [ should_forward_message ] will be called once per new message , and will
* not be called again until the deferred it returns is resolved . The helper
* process waits 5 seconds for the result of [ should_forward_message ] to be
* reported , otherwise it will not forward it .
*
* Fails if already subscribed. If it succeeds, incoming messages for that
* topic will be written to the [Subscription.message_pipe t]. Returned deferred
* is resolved with [Ok sub] as soon as the subscription is enqueued.
*
* [should_forward_message] will be called once per new message, and will
* not be called again until the deferred it returns is resolved. The helper
* process waits 5 seconds for the result of [should_forward_message] to be
* reported, otherwise it will not forward it.
*)
val subscribe :
t
-> string
-> handle_and_validate_incoming_message:
(string Envelope.Incoming.t -> Validation_callback.t -> unit Deferred.t)
-> string subscription Deferred.Or_error.t
* Like [ subscribe ] , but knows how to stringify / destringify
*
* Fails if already subscribed . If it succeeds , incoming messages for that
* topic will be written to the [ Subscription.message_pipe t ] . Returned deferred
* is resolved with [ Ok sub ] as soon as the subscription is enqueued .
*
* [ should_forward_message ] will be called once per new message , and will
* not be called again until the deferred it returns is resolved . The helper
* process waits 5 seconds for the result of [ should_forward_message ] to be
* reported , otherwise it will not forward it .
*
* Fails if already subscribed. If it succeeds, incoming messages for that
* topic will be written to the [Subscription.message_pipe t]. Returned deferred
* is resolved with [Ok sub] as soon as the subscription is enqueued.
*
* [should_forward_message] will be called once per new message, and will
* not be called again until the deferred it returns is resolved. The helper
* process waits 5 seconds for the result of [should_forward_message] to be
* reported, otherwise it will not forward it.
*)
val subscribe_encode :
t
-> string
-> handle_and_validate_incoming_message:
('a Envelope.Incoming.t -> Validation_callback.t -> unit Deferred.t)
-> bin_prot:'a Bin_prot.Type_class.t
-> on_decode_failure:
[ `Ignore | `Call of string Envelope.Incoming.t -> Error.t -> unit ]
-> 'a subscription Deferred.Or_error.t
(** Unsubscribe from this topic, closing the write pipe.
*
* Returned deferred is resolved once the unsubscription is complete.
* This can fail if already unsubscribed. *)
val unsubscribe : t -> _ subscription -> unit Deferred.Or_error.t
(** Publish a message to this pubsub topic.
*
* Returned deferred is resolved once the publish is enqueued locally.
* This function continues to work even if [unsubscribe t] has been called.
* It is exactly [Pubsub.publish] with the topic this subscription was
* created for, and fails in the same way. *)
val publish : t -> 'a subscription -> 'a -> unit Deferred.t
(** Publish a message to a topic described buy a string.
*
* Returned deferred is resolved once the publish is enqueued locally.
* This function continues to work even if [unsubscribe t] has been called.
* This function allows to publish to the topic to which we are
* not necessarily subscribed.
*)
val publish_raw : t -> topic:string -> string -> unit Deferred.t
end
* An open stream .
Close the write pipe when you are done . This wo n't close the reading end .
The reading end will be closed when the remote peer closes their writing
end . Once both write ends are closed , the stream ends .
Long - lived connections are likely to get closed by the remote peer if
they reach their connection limit . See the module - level notes about
connection limiting .
IMPORTANT NOTE : A single write to the stream will not necessarily result
in a single read on the other side . libp2p may fragment messages arbitrarily .
Close the write pipe when you are done. This won't close the reading end.
The reading end will be closed when the remote peer closes their writing
end. Once both write ends are closed, the stream ends.
Long-lived connections are likely to get closed by the remote peer if
they reach their connection limit. See the module-level notes about
connection limiting.
IMPORTANT NOTE: A single write to the stream will not necessarily result
in a single read on the other side. libp2p may fragment messages arbitrarily.
*)
module Libp2p_stream : sig
type t
* [ pipes t ] returns the reader / writer pipe for our half of the stream .
val pipes : t -> string Pipe.Reader.t * string Pipe.Writer.t
val remote_peer : t -> Peer.t
end
(** Opens a stream with a peer on a particular protocol.
Close the write pipe when you are done. This won't close the reading end.
The reading end will be closed when the remote peer closes their writing
end. Once both write ends are closed, the connection terminates.
This can fail if the peer isn't reachable, doesn't implement the requested
protocol, and probably for other reasons.
*)
val open_stream :
t -> protocol:string -> peer:Peer.Id.t -> Libp2p_stream.t Deferred.Or_error.t
* [ reset_stream t ] informs the other peer to close the stream .
The returned [ Deferred . ] is fulfilled with [ Ok ( ) ] immediately
once the reset is performed . It does not wait for the other host to
acknowledge .
The returned [Deferred.Or_error.t] is fulfilled with [Ok ()] immediately
once the reset is performed. It does not wait for the other host to
acknowledge.
*)
val reset_stream : t -> Libp2p_stream.t -> unit Deferred.Or_error.t
(** Handle incoming streams for a protocol.
[on_handler_error] determines what happens if the handler throws an
exception. If an exception is raised by [on_handler_error] (either explicitly
via [`Raise], or in the function passed via [`Call]), [Protocol_handler.close] will
be called.
The function in `Call will be passed the stream that faulted.
*)
val open_protocol :
t
-> on_handler_error:
[ `Raise | `Ignore | `Call of Libp2p_stream.t -> exn -> unit ]
-> protocol:string
-> (Libp2p_stream.t -> unit Deferred.t)
-> unit Deferred.Or_error.t
(** Stop handling new streams on this protocol.
[reset_existing_streams] controls whether open streams for this protocol
will be reset, and defaults to [false].
*)
val close_protocol :
?reset_existing_streams:bool -> t -> protocol:string -> unit Deferred.t
(** Try listening on a multiaddr.
*
* If successful, returns the list of all addresses this net is listening on
* For example, if listening on ["/ip4/127.0.0.1/tcp/0"], it might return
* ["/ip4/127.0.0.1/tcp/35647"] after the OS selects an available listening
* port.
*
* This can be called many times.
*)
val listen_on : t -> Multiaddr.t -> Multiaddr.t list Deferred.Or_error.t
(** The list of addresses this net is listening on.
This returns the same thing that [listen_on] does, without listening
on an address.
*)
val listening_addrs : t -> Multiaddr.t list Deferred.Or_error.t
(** Connect to a peer, ensuring it enters our peerbook and DHT.
This can fail if the connection fails. *)
val add_peer : t -> Multiaddr.t -> is_seed:bool -> unit Deferred.Or_error.t
(** Join the DHT and announce our existence.
Call this after using [add_peer] to add any bootstrap peers. *)
val begin_advertising : t -> unit Deferred.Or_error.t
(** Stop listening, close all connections and subscription pipes, and kill the subprocess. *)
val shutdown : t -> unit Deferred.t
(** Configure the connection gateway.
This will fail if any of the trusted or banned peers are on IPv6. *)
val set_connection_gating_config :
t -> connection_gating -> connection_gating Deferred.t
val connection_gating_config : t -> connection_gating
(** List of currently banned IPs. *)
val banned_ips : t -> Unix.Inet_addr.t list
val send_heartbeat : t -> Peer.Id.t -> unit
| null | https://raw.githubusercontent.com/MinaProtocol/mina/a1185fc7b207cfec2a652ef7f3fdc3d9b2e202ea/src/lib/mina_net2/mina_net2.mli | ocaml | * Handle to all network functionality.
* Formats this keypair to a comma-separated list of public key, secret key, and peer_id.
* Undo [to_string t].
Only fails if the string has the wrong format, not if the embedded
keypair data is corrupt.
* [create ~logger ~conf_dir] starts a new [net] storing its state in [conf_dir]
*
* The optional [allow_multiple_instances] defaults to `false`. A `true` value
* allows spawning multiple subprocesses, which can be useful for tests.
*
* The new [net] isn't connected to any network until [configure] is called.
*
* This can fail for a variety of reasons related to spawning the subprocess.
* State for the connection gateway. It will disallow connections from IPs
or peer IDs in [banned_peers], except for those listed in [trusted_peers]. If
[isolate] is true, only connections to [trusted_peers] are allowed.
* The keypair the network was configured with.
*
* Resolved once configuration succeeds.
* List of all peers we know about.
* Set node status to be served to peers requesting node status.
* Get node status from given peer.
* Unsubscribe from this topic, closing the write pipe.
*
* Returned deferred is resolved once the unsubscription is complete.
* This can fail if already unsubscribed.
* Publish a message to this pubsub topic.
*
* Returned deferred is resolved once the publish is enqueued locally.
* This function continues to work even if [unsubscribe t] has been called.
* It is exactly [Pubsub.publish] with the topic this subscription was
* created for, and fails in the same way.
* Publish a message to a topic described buy a string.
*
* Returned deferred is resolved once the publish is enqueued locally.
* This function continues to work even if [unsubscribe t] has been called.
* This function allows to publish to the topic to which we are
* not necessarily subscribed.
* Opens a stream with a peer on a particular protocol.
Close the write pipe when you are done. This won't close the reading end.
The reading end will be closed when the remote peer closes their writing
end. Once both write ends are closed, the connection terminates.
This can fail if the peer isn't reachable, doesn't implement the requested
protocol, and probably for other reasons.
* Handle incoming streams for a protocol.
[on_handler_error] determines what happens if the handler throws an
exception. If an exception is raised by [on_handler_error] (either explicitly
via [`Raise], or in the function passed via [`Call]), [Protocol_handler.close] will
be called.
The function in `Call will be passed the stream that faulted.
* Stop handling new streams on this protocol.
[reset_existing_streams] controls whether open streams for this protocol
will be reset, and defaults to [false].
* Try listening on a multiaddr.
*
* If successful, returns the list of all addresses this net is listening on
* For example, if listening on ["/ip4/127.0.0.1/tcp/0"], it might return
* ["/ip4/127.0.0.1/tcp/35647"] after the OS selects an available listening
* port.
*
* This can be called many times.
* The list of addresses this net is listening on.
This returns the same thing that [listen_on] does, without listening
on an address.
* Connect to a peer, ensuring it enters our peerbook and DHT.
This can fail if the connection fails.
* Join the DHT and announce our existence.
Call this after using [add_peer] to add any bootstrap peers.
* Stop listening, close all connections and subscription pipes, and kill the subprocess.
* Configure the connection gateway.
This will fail if any of the trusted or banned peers are on IPv6.
* List of currently banned IPs. | * An interface to limited libp2p functionality for Coda to use .
A subprocess is spawned to run the go - libp2p code . This module communicates
with that subprocess over an ad - hoc RPC protocol .
TODO : separate internal helper errors from underlying libp2p errors .
In general , functions in this module return [ ' a Deferred . ] . Unless
otherwise mentioned , the deferred is resolved immediately once the RPC action
to the libp2p helper is finished . Unless otherwise mentioned , everything can
throw an exception due to an internal helper error . These indicate a bug in
this module / the helper , and not misuse .
Some errors can arise from calling certain functions before [ configure ] has been
called . In general , anything that returns an [ Or_error ] can fail in this manner .
A [ Mina_net2.t ] has the following lifecycle :
- Fresh : the result of [ Mina_net2.create ] . This spawns the helper process but
does not connect to any network . Few operations can be done on fresh nets ,
only [ Keypair.random ] for now .
- Configured : after calling [ Mina_net2.configure ] . Configure creates the libp2p
objects and can start listening on network sockets . This does n't join any DHT
or attempt peer connections . Configured networks can do everything but any
pubsub messages may have very limited reach without being in the DHT .
- Active : after calling [ Mina_net2.begin_advertising ] . This joins the DHT ,
announcing our existence to our peers and initiating local mDNS discovery .
- Closed : after calling [ Mina_net2.shutdown ] . This flushes all the pending RPC
TODO : consider encoding the network state in the types .
A note about connection limits :
In the original coda_net , connection limits were enforced synchronously on
every received connection . Right now with mina_net2 , connection management is
asynchronous and post - hoc . In the background , once per minute it checks the
connection count . If it is above the " high water mark " , it will close
( " trim " ) eligible connections until it reaches the " low water mark " . All
connections start with a " grace period " where they wo n't be closed . Peer IDs
can be marked as " protected " which prevents them being trimmed . Ember believes this
is vulnerable to resource exhaustion by opening many new connections .
A subprocess is spawned to run the go-libp2p code. This module communicates
with that subprocess over an ad-hoc RPC protocol.
TODO: separate internal helper errors from underlying libp2p errors.
In general, functions in this module return ['a Deferred.Or_error.t]. Unless
otherwise mentioned, the deferred is resolved immediately once the RPC action
to the libp2p helper is finished. Unless otherwise mentioned, everything can
throw an exception due to an internal helper error. These indicate a bug in
this module/the helper, and not misuse.
Some errors can arise from calling certain functions before [configure] has been
called. In general, anything that returns an [Or_error] can fail in this manner.
A [Mina_net2.t] has the following lifecycle:
- Fresh: the result of [Mina_net2.create]. This spawns the helper process but
does not connect to any network. Few operations can be done on fresh nets,
only [Keypair.random] for now.
- Configured: after calling [Mina_net2.configure]. Configure creates the libp2p
objects and can start listening on network sockets. This doesn't join any DHT
or attempt peer connections. Configured networks can do everything but any
pubsub messages may have very limited reach without being in the DHT.
- Active: after calling [Mina_net2.begin_advertising]. This joins the DHT,
announcing our existence to our peers and initiating local mDNS discovery.
- Closed: after calling [Mina_net2.shutdown]. This flushes all the pending RPC
TODO: consider encoding the network state in the types.
A note about connection limits:
In the original coda_net, connection limits were enforced synchronously on
every received connection. Right now with mina_net2, connection management is
asynchronous and post-hoc. In the background, once per minute it checks the
connection count. If it is above the "high water mark", it will close
("trim") eligible connections until it reaches the "low water mark". All
connections start with a "grace period" where they won't be closed. Peer IDs
can be marked as "protected" which prevents them being trimmed. Ember believes this
is vulnerable to resource exhaustion by opening many new connections.
*)
open Core
open Async
open Network_peer
exception Libp2p_helper_died_unexpectedly
type t
* A " multiaddr " is libp2p 's extensible encoding for network addresses .
They generally look like paths , and are read left - to - right . Each protocol
type defines how to decode its address format , and everything leftover is
encapsulated inside that protocol .
Some example :
- [ /p2p / QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC ]
- [ /ip4/127.0.0.1 / tcp/1234 / p2p / QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC ]
- [ /ip6/2601:9:4f81:9700:803e : ca65:66e8 : c21 ]
They generally look like paths, and are read left-to-right. Each protocol
type defines how to decode its address format, and everything leftover is
encapsulated inside that protocol.
Some example multiaddrs:
- [/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC]
- [/ip4/127.0.0.1/tcp/1234/p2p/QmcgpsyWgH8Y8ajJz1Cu72KnS5uo2Aa2LpzU7kinSupNKC]
- [/ip6/2601:9:4f81:9700:803e:ca65:66e8:c21]
*)
module Multiaddr : sig
type t [@@deriving compare, bin_io]
val to_string : t -> string
val of_string : string -> t
val to_peer : t -> Network_peer.Peer.t option
val of_peer : Network_peer.Peer.t -> t
* can a multiaddr plausibly be used as a Peer.t ?
a syntactic check only ; a return value of
true does not guarantee that the multiaddress can
be used as a peer by libp2p
a syntactic check only; a return value of
true does not guarantee that the multiaddress can
be used as a peer by libp2p
*)
val valid_as_peer : t -> bool
val of_file_contents : string -> t list
end
module Keypair : sig
[%%versioned:
module Stable : sig
module V1 : sig
type t
end
end]
val to_string : t -> string
val of_string : string -> t Or_error.t
val to_peer_id : t -> Peer.Id.t
val secret : t -> string
end
module Validation_callback = Validation_callback
module Sink = Sink
module For_tests : sig
module Helper = Libp2p_helper
val generate_random_keypair : Helper.t -> Keypair.t Deferred.t
val multiaddr_to_libp2p_ipc : Multiaddr.t -> Libp2p_ipc.multiaddr
val empty_libp2p_ipc_gating_config : Libp2p_ipc.gating_config
end
val create :
?allow_multiple_instances:bool
-> all_peers_seen_metric:bool
-> logger:Logger.t
-> pids:Child_processes.Termination.t
-> conf_dir:string
-> on_peer_connected:(Peer.Id.t -> unit)
-> on_peer_disconnected:(Peer.Id.t -> unit)
-> unit
-> t Deferred.Or_error.t
type connection_gating =
{ banned_peers : Peer.t list; trusted_peers : Peer.t list; isolate : bool }
* Configure the network connection .
*
* Listens on each address in [ maddrs ] .
*
* This will only connect to peers that share the same [ network_id ] . [ on_new_peer ] , if present ,
* will be called for each peer we connect to . [ unsafe_no_trust_ip ] , if true , will not attempt to
* report trust actions for the IPs of observed connections .
*
* Whenever the connection list gets too small , [ seed_peers ] will be
* candidates for reconnection for peer discovery .
*
* This fails if initializing libp2p fails for any reason .
*
* Listens on each address in [maddrs].
*
* This will only connect to peers that share the same [network_id]. [on_new_peer], if present,
* will be called for each peer we connect to. [unsafe_no_trust_ip], if true, will not attempt to
* report trust actions for the IPs of observed connections.
*
* Whenever the connection list gets too small, [seed_peers] will be
* candidates for reconnection for peer discovery.
*
* This fails if initializing libp2p fails for any reason.
*)
val configure :
t
-> me:Keypair.t
-> external_maddr:Multiaddr.t
-> maddrs:Multiaddr.t list
-> network_id:string
-> metrics_port:int option
-> unsafe_no_trust_ip:bool
-> flooding:bool
-> direct_peers:Multiaddr.t list
-> peer_exchange:bool
-> peer_protection_ratio:float
-> seed_peers:Multiaddr.t list
-> initial_gating_config:connection_gating
-> min_connections:int
-> max_connections:int
-> validation_queue_size:int
-> known_private_ip_nets:Core.Unix.Cidr.t list
-> topic_config:string list list
-> unit Deferred.Or_error.t
val me : t -> Keypair.t Deferred.t
val peers : t -> Peer.t list Deferred.t
val bandwidth_info :
t
-> ([ `Input of float ] * [ `Output of float ] * [ `Cpu_usage of float ])
Deferred.Or_error.t
val set_node_status : t -> string -> unit Deferred.Or_error.t
val get_peer_node_status : t -> Multiaddr.t -> string Deferred.Or_error.t
val generate_random_keypair : t -> Keypair.t Deferred.t
module Pubsub : sig
type 'a subscription
* Subscribe to a pubsub topic .
*
* Fails if already subscribed . If it succeeds , incoming messages for that
* topic will be written to the [ Subscription.message_pipe t ] . Returned deferred
* is resolved with [ Ok sub ] as soon as the subscription is enqueued .
*
* [ should_forward_message ] will be called once per new message , and will
* not be called again until the deferred it returns is resolved . The helper
* process waits 5 seconds for the result of [ should_forward_message ] to be
* reported , otherwise it will not forward it .
*
* Fails if already subscribed. If it succeeds, incoming messages for that
* topic will be written to the [Subscription.message_pipe t]. Returned deferred
* is resolved with [Ok sub] as soon as the subscription is enqueued.
*
* [should_forward_message] will be called once per new message, and will
* not be called again until the deferred it returns is resolved. The helper
* process waits 5 seconds for the result of [should_forward_message] to be
* reported, otherwise it will not forward it.
*)
val subscribe :
t
-> string
-> handle_and_validate_incoming_message:
(string Envelope.Incoming.t -> Validation_callback.t -> unit Deferred.t)
-> string subscription Deferred.Or_error.t
* Like [ subscribe ] , but knows how to stringify / destringify
*
* Fails if already subscribed . If it succeeds , incoming messages for that
* topic will be written to the [ Subscription.message_pipe t ] . Returned deferred
* is resolved with [ Ok sub ] as soon as the subscription is enqueued .
*
* [ should_forward_message ] will be called once per new message , and will
* not be called again until the deferred it returns is resolved . The helper
* process waits 5 seconds for the result of [ should_forward_message ] to be
* reported , otherwise it will not forward it .
*
* Fails if already subscribed. If it succeeds, incoming messages for that
* topic will be written to the [Subscription.message_pipe t]. Returned deferred
* is resolved with [Ok sub] as soon as the subscription is enqueued.
*
* [should_forward_message] will be called once per new message, and will
* not be called again until the deferred it returns is resolved. The helper
* process waits 5 seconds for the result of [should_forward_message] to be
* reported, otherwise it will not forward it.
*)
val subscribe_encode :
t
-> string
-> handle_and_validate_incoming_message:
('a Envelope.Incoming.t -> Validation_callback.t -> unit Deferred.t)
-> bin_prot:'a Bin_prot.Type_class.t
-> on_decode_failure:
[ `Ignore | `Call of string Envelope.Incoming.t -> Error.t -> unit ]
-> 'a subscription Deferred.Or_error.t
val unsubscribe : t -> _ subscription -> unit Deferred.Or_error.t
val publish : t -> 'a subscription -> 'a -> unit Deferred.t
val publish_raw : t -> topic:string -> string -> unit Deferred.t
end
* An open stream .
Close the write pipe when you are done . This wo n't close the reading end .
The reading end will be closed when the remote peer closes their writing
end . Once both write ends are closed , the stream ends .
Long - lived connections are likely to get closed by the remote peer if
they reach their connection limit . See the module - level notes about
connection limiting .
IMPORTANT NOTE : A single write to the stream will not necessarily result
in a single read on the other side . libp2p may fragment messages arbitrarily .
Close the write pipe when you are done. This won't close the reading end.
The reading end will be closed when the remote peer closes their writing
end. Once both write ends are closed, the stream ends.
Long-lived connections are likely to get closed by the remote peer if
they reach their connection limit. See the module-level notes about
connection limiting.
IMPORTANT NOTE: A single write to the stream will not necessarily result
in a single read on the other side. libp2p may fragment messages arbitrarily.
*)
module Libp2p_stream : sig
type t
* [ pipes t ] returns the reader / writer pipe for our half of the stream .
val pipes : t -> string Pipe.Reader.t * string Pipe.Writer.t
val remote_peer : t -> Peer.t
end
val open_stream :
t -> protocol:string -> peer:Peer.Id.t -> Libp2p_stream.t Deferred.Or_error.t
* [ reset_stream t ] informs the other peer to close the stream .
The returned [ Deferred . ] is fulfilled with [ Ok ( ) ] immediately
once the reset is performed . It does not wait for the other host to
acknowledge .
The returned [Deferred.Or_error.t] is fulfilled with [Ok ()] immediately
once the reset is performed. It does not wait for the other host to
acknowledge.
*)
val reset_stream : t -> Libp2p_stream.t -> unit Deferred.Or_error.t
val open_protocol :
t
-> on_handler_error:
[ `Raise | `Ignore | `Call of Libp2p_stream.t -> exn -> unit ]
-> protocol:string
-> (Libp2p_stream.t -> unit Deferred.t)
-> unit Deferred.Or_error.t
val close_protocol :
?reset_existing_streams:bool -> t -> protocol:string -> unit Deferred.t
val listen_on : t -> Multiaddr.t -> Multiaddr.t list Deferred.Or_error.t
val listening_addrs : t -> Multiaddr.t list Deferred.Or_error.t
val add_peer : t -> Multiaddr.t -> is_seed:bool -> unit Deferred.Or_error.t
val begin_advertising : t -> unit Deferred.Or_error.t
val shutdown : t -> unit Deferred.t
val set_connection_gating_config :
t -> connection_gating -> connection_gating Deferred.t
val connection_gating_config : t -> connection_gating
val banned_ips : t -> Unix.Inet_addr.t list
val send_heartbeat : t -> Peer.Id.t -> unit
|
20cba054265a58936ee5c0ddd3ef30059f708165bffa01562896fda46153b923 | philnguyen/json-type-provider | read.rkt | #lang typed/racket/base
;; Originally copied and modified from `json` package
(provide
JSNum
Reader
read-number
read-integer
read-float
read-a-string
read-bool
read-true
read-false
read-null
read-fold
read-list
read-list-rest
read-empty-list
skip-json
make-sequence-reader
skip-whitespace
bad-input
err
)
(require racket/match
(only-in racket/sequence empty-sequence sequence-append))
(require/typed syntax/readerr
[raise-read-error
(String Any (Option Natural) (Option Natural) (Option Natural) (Option Natural)
→ Nothing)])
(require/typed json
[read-json (Input-Port → Any)])
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; Readers for base types
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define-type (Reader X) (∀ (Y)
(case->
[Input-Port → X]
[Input-Port (Input-Port → Y) → (U X Y)])))
(define-type JSNum (U Integer Float))
(define-type Sign (U -1 1))
(: read-number (Reader JSNum))
(define (read-number i [default bad-input])
(: digit-byte? : (U EOF Byte) → Boolean : #:+ Byte)
(define (digit-byte? c)
(and (not (eof-object? c))
(<= (char->integer #\0) c (char->integer #\9))))
(define (to-number [c : Byte]) (- c (char->integer #\0)))
(define (maybe-bytes [c : (U EOF Byte)]) (if (eof-object? c) #"" (bytes c)))
(: n->string : Integer Integer → Bytes)
(define (n->string n exp)
(define s (number->string n))
(string->bytes/utf-8
(cond
[(zero? exp) s]
[else
(define m (+ (string-length s) exp))
(string-append (substring s 0 m) "." (substring s m))])))
(: read-integer : Sign → JSNum)
(define (read-integer sgn)
(define c (read-byte i))
(cond
[(digit-byte? c)
(read-integer-rest sgn (to-number c)
#:more-digits? (not (eqv? c (char->integer #\0))))]
[else (bad-input i (bytes-append (if (sgn . < . 0) #"-" #"")
(maybe-bytes c))
#:eof? (eof-object? c))]))
(: read-integer-rest : Sign Integer #:more-digits? Boolean → JSNum)
(define (read-integer-rest sgn n #:more-digits? more-digits?)
(define c (peek-byte i))
(cond
[(and more-digits? (digit-byte? c))
(read-byte i)
(read-integer-rest sgn (+ (* n 10) (to-number c)) #:more-digits? #t)]
[(eqv? c (char->integer #\.))
(read-byte i)
(read-fraction sgn n)]
[(or (eqv? c (char->integer #\e))
(eqv? c (char->integer #\E)))
(read-byte i)
(read-exponent (* sgn n) (assert c byte?) 0)]
[else (* sgn n)]))
(: read-fraction : Sign Integer → Float)
(define (read-fraction sgn n)
(define c (read-byte i))
(cond
[(digit-byte? c)
(read-fraction-rest sgn (+ (* n 10) (to-number c)) -1)]
[else (bad-input i (bytes-append (string->bytes/utf-8 (format "~a." (* sgn n)))
(maybe-bytes c))
#:eof? (eof-object? c))]))
(: read-fraction-rest : Sign Integer Integer → Float)
(define (read-fraction-rest sgn n exp)
(define c (peek-byte i))
(cond
[(digit-byte? c)
(read-byte i)
(read-fraction-rest sgn (+ (* n 10) (to-number c)) (sub1 exp))]
[(or (eqv? c (char->integer #\e))
(eqv? c (char->integer #\E)))
(read-byte i)
(read-exponent (* sgn n) (assert c byte?) exp)]
[else (exact->inexact (* sgn n (expt 10 exp)))]))
(: read-exponent : Integer Byte Integer → Float)
(define (read-exponent n mark exp)
(define c (read-byte i))
(cond
[(digit-byte? c)
(read-exponent-rest n exp (to-number c) 1)]
[(eqv? c (char->integer #\+))
(read-exponent-more n mark #"+" exp 1)]
[(eqv? c (char->integer #\-))
(read-exponent-more n mark #"-" exp -1)]
[else (bad-input i (bytes-append (n->string n exp)
(bytes mark)
(maybe-bytes c))
#:eof? (eof-object? c))]))
(: read-exponent-more : Integer Byte Bytes Integer Integer → Float)
(define (read-exponent-more n mark mark2 exp sgn)
(define c (read-byte i))
(cond
[(digit-byte? c)
(read-exponent-rest n exp (to-number c) sgn)]
[else (bad-input i (bytes-append (n->string n exp)
(bytes mark)
mark2
(maybe-bytes c))
#:eof? (eof-object? c))]))
(: read-exponent-rest : Integer Integer Integer Integer → Float)
(define (read-exponent-rest n exp exp2 sgn)
(define c (peek-byte i))
(cond
[(digit-byte? c)
(read-byte i)
(read-exponent-rest n exp (+ (* 10 exp2) (to-number c)) sgn)]
[else (exact->inexact (* n (expt 10 (+ exp (* sgn exp2)))))]))
(let ([ch (skip-whitespace i)])
(cond [(eof-object? ch) (bad-input i)]
[(eqv? ch #\-) (read-byte i)
(read-integer -1)]
[(<= (char->integer #\0) (char->integer ch) (char->integer #\9))
(read-integer 1)]
[else (default i)])))
(: read-integer : (Reader Integer))
(define (read-integer i [default bad-input])
(define n (read-number i default))
(cond [(exact-integer? n) n]
[(integer? n) (assert (inexact->exact n) exact-integer?)]
[else (err i "expect integer, got ~a" n)]))
(: read-float : (Reader Float))
(define (read-float i [default bad-input])
(define n (read-number i default))
(if (exact-integer? n) (exact->inexact n) n))
(: read-a-string (Reader String))
(define (read-a-string i [default bad-input])
(define (byte-char=? [b : Byte] [ch : Char]) (eqv? b (char->integer ch)))
(: keep-char : Char String Integer (Option Bytes-Converter) → String)
(define (keep-char c old-result pos converter)
(define result
(if (= pos (string-length old-result))
(let ([new (make-string (* pos 2))])
(string-copy! new 0 old-result 0 pos)
new)
old-result))
(string-set! result pos c)
(loop result (add1 pos) converter))
(: loop : String Integer (Option Bytes-Converter) → String)
(define (loop result pos converter)
(define c (read-byte i))
(cond
[(eof-object? c) (err i "unterminated string")]
[(byte-char=? c #\") (substring result 0 pos)]
[(byte-char=? c #\\) (read-escape (read-char i) result pos converter)]
[(c . < . 128) (keep-char (integer->char c) result pos converter)]
[else
need to decode , but we ca n't un - read the byte , and
;; also we want to report decoding errors
(define cvtr (or converter ID-CONVERTER))
(define buf (make-bytes 6 c))
(let utf8-loop ([start : Natural 0] [end : Natural 1])
(define-values (wrote-n read-n state) (bytes-convert cvtr buf start end buf 0 6))
(case state
[(complete)
(keep-char (bytes-utf-8-ref buf 0) result pos cvtr)]
[(error)
(err i "UTF-8 decoding error at ~e" (subbytes buf 0 end))]
[(aborts)
(define c (read-byte i))
(cond
[(eof-object? c)
(err i "unexpected end-of-file")]
[else
(bytes-set! buf end c)
(utf8-loop (+ start read-n) (add1 end))])]
[else (error 'utf8-loop "internal")]))]))
(: read-escape : (U EOF Char) String Integer (Option Bytes-Converter) → String)
(define (read-escape esc result pos converter)
(cond
[(case esc
[(#\b) "\b"]
[(#\n) "\n"]
[(#\r) "\r"]
[(#\f) "\f"]
[(#\t) "\t"]
[(#\\) "\\"]
[(#\") "\""]
[(#\/) "/"]
[else #f])
=> (λ (s) (keep-char (string-ref s 0) result pos converter))]
[(eqv? esc #\u)
(define (get-hex)
(define (read-next) : Byte
(define c (read-byte i))
(when (eof-object? c) (error "unexpected end-of-file"))
c)
(define c1 (read-next))
(define c2 (read-next))
(define c3 (read-next))
(define c4 (read-next))
(define (hex-convert [c : Byte])
(cond
[(<= (char->integer #\0) c (char->integer #\9))
(- c (char->integer #\0))]
[(<= (char->integer #\a) c (char->integer #\f))
(- c (- (char->integer #\a) 10))]
[(<= (char->integer #\A) c (char->integer #\F))
(- c (- (char->integer #\A) 10))]
[else (err i "bad \\u escape ~e" (bytes c1 c2 c3 c4))]))
(+ (arithmetic-shift (hex-convert c1) 12)
(arithmetic-shift (hex-convert c2) 8)
(arithmetic-shift (hex-convert c3) 4)
(hex-convert c4)))
(define e (get-hex))
(define e*
(cond
[(<= #xD800 e #xDFFF)
(define (err-missing)
(err i "bad string \\u escape, missing second half of a UTF-16 pair"))
(unless (eqv? (read-byte i) (char->integer #\\)) (err-missing))
(unless (eqv? (read-byte i) (char->integer #\u)) (err-missing))
(define e2 (get-hex))
(cond
[(<= #xDC00 e2 #xDFFF)
(+ (arithmetic-shift (- e #xD800) 10) (- e2 #xDC00) #x10000)]
[else
(err i "bad string \\u escape, bad second half of a UTF-16 pair")])]
[else e]))
(keep-char (integer->char e*) result pos converter)]
[else (err i "bad string escape: \"~a\"" esc)]))
(match (skip-whitespace i)
[(== #\" eqv?) (read-byte i)
(loop (make-string 16) 0 #f)]
[_ (default i)]))
(: read-bool (Reader Boolean))
(define (read-bool i [default bad-input])
(match (skip-whitespace i)
[(== #\t eqv?) (consume-literal i #"true") #t]
[(== #\f eqv?) (consume-literal i #"false") #f]
[_ (default i)]))
(: read-const (∀ (X) (Bytes X → (Reader X))))
(define (read-const lit c)
(define l0 (integer->char (bytes-ref lit 0)))
(λ (i [default bad-input])
(if (eqv? (skip-whitespace i) l0)
(begin (consume-literal i lit) c)
(default i))))
(define read-true (read-const #"true" #t))
(define read-false (read-const #"false" #f))
(define (read-null) (read-const #"null" 'null))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; Combinators for reading lists and objects
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(: read-fold (∀ (X A) A (X A → A) (Input-Port → X) → (Reader A)))
(define ((read-fold a f read-one) i [default bad-input])
(let ([ch (skip-whitespace i)])
(cond [(eqv? ch #\[) (read-byte i)
((read-fold-rest a f read-one) i)]
[else (default i)])))
(: read-fold-rest (∀ (X A) A (X A → A) (Input-Port → X) → Input-Port → A))
(define ((read-fold-rest a f read-one) i)
(define ch (skip-whitespace i))
(cond
[(eqv? ch #\]) (read-byte i)
a]
[else
(let loop : A ([a : A (f (read-one i) a)])
(define ch (skip-whitespace i))
(cond
[(eqv? ch #\]) (read-byte i)
a]
[(eqv? ch #\,) (read-byte i)
(loop (f (read-one i) a))]
[else (err i "error while parsing a list")]))]))
(: read-list (∀ (A) (Input-Port → A) → (Reader (Listof A))))
(define ((read-list read-one) i [default bad-input])
(let ([ch (skip-whitespace i)])
(cond [(eqv? ch #\[) (read-byte i)
((read-list-rest read-one) i)]
[else (default i)])))
(: read-list-rest (∀ (A) (Input-Port → A) → Input-Port → (Listof A)))
(define ((read-list-rest read-one) i)
(reverse (((inst read-fold-rest A (Listof A)) '() cons read-one) i)))
(: read-empty-list (Reader Null))
(define (read-empty-list i [default bad-input])
(match (skip-whitespace i)
[(== #\[ eqv?) (read-byte i)
(match (skip-whitespace i)
[(== #\] eqv?) (read-byte i)
'()]
[_ (bad-input i)])]
[_ (default i)]))
(: make-sequence-reader (∀ (X) (Input-Port → X) → Input-Port → (Sequenceof X)))
(define ((make-sequence-reader read-one) i)
(let ([ch (skip-whitespace i)])
(cond [(eqv? ch #\[)
(read-byte i)
(let ([ch (skip-whitespace i)])
(cond
[(eqv? ch #\]) (read-byte i) empty-sequence]
[else
(sequence-append
(in-value (read-one i))
((inst make-do-sequence (U Char EOF) X)
(λ ()
(values (λ _ (read-one i))
(λ _ (skip-whitespace i))
(skip-whitespace i)
(λ (ch)
(cond
[(eqv? ch #\,) (read-byte i) #t]
[(eqv? ch #\]) (read-byte i) #f]
[else (err i "error white parsing a list")]))
#f
#f))))]))]
[else (err i "error while parsing a list")])))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;;; Helpers
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(define ID-CONVERTER (assert (bytes-open-converter "UTF-8" "UTF-8")))
(: skip-json : Input-Port → Void)
(define (skip-json i) (void (read-json i)))
(: consume-literal : Input-Port Bytes → Void)
(define (consume-literal i bstr)
(define len (bytes-length bstr))
(read-byte i)
(for ([j (in-range 1 len)])
(define c (assert (read-byte i) byte?))
(unless (eqv? c (bytes-ref bstr j))
(bad-input i (bytes-append (subbytes bstr 0 j) (bytes c)))))
;; Check for delimiter, defined for our purposes as matching #rx"\\b":
(define b (peek-byte i))
(unless (eof-object? b)
(when (or (<= (char->integer #\a) b (char->integer #\z))
(<= (char->integer #\A) b (char->integer #\Z))
(<= (char->integer #\0) b (char->integer #\9))
(eqv? b (char->integer #\_)))
(bad-input i bstr))))
(: skip-whitespace : Input-Port → (U Char EOF))
(define (skip-whitespace i)
(match (peek-char i)
[(and (? char?) (? char-whitespace?))
(read-char i)
(skip-whitespace i)]
[ch ch]))
Follows the specification ( eg , at json.org ) -- no extensions .
(: err : Input-Port String Any * → Nothing)
(define (err i fmt . args)
(define-values (l c p) (port-next-location i))
(raise-read-error (apply format fmt args)
(object-name i) l c p #f))
(: bad-input (->* [Input-Port] [Bytes #:eof? (U Bytes #t #f)] Nothing))
(define (bad-input i [prefix #""] #:eof? [eof? #f])
(define bstr (peek-bytes (assert (sub1 (error-print-width)) index?) 0 i))
(if (or (and (eof-object? bstr) (equal? prefix #""))
eof?)
(err i (string-append "unexpected end-of-file"
(if (equal? prefix #"")
""
(format "after ~e" prefix))))
(err i (format "bad input starting ~e" (bytes-append prefix (if (eof-object? bstr)
#""
bstr))))))
| null | https://raw.githubusercontent.com/philnguyen/json-type-provider/f96d3f212519f4ff2aef828e7b891971b82babb8/json-type-provider/read.rkt | racket | Originally copied and modified from `json` package
Readers for base types
also we want to report decoding errors
Combinators for reading lists and objects
Helpers
Check for delimiter, defined for our purposes as matching #rx"\\b": | #lang typed/racket/base
(provide
JSNum
Reader
read-number
read-integer
read-float
read-a-string
read-bool
read-true
read-false
read-null
read-fold
read-list
read-list-rest
read-empty-list
skip-json
make-sequence-reader
skip-whitespace
bad-input
err
)
(require racket/match
(only-in racket/sequence empty-sequence sequence-append))
(require/typed syntax/readerr
[raise-read-error
(String Any (Option Natural) (Option Natural) (Option Natural) (Option Natural)
→ Nothing)])
(require/typed json
[read-json (Input-Port → Any)])
(define-type (Reader X) (∀ (Y)
(case->
[Input-Port → X]
[Input-Port (Input-Port → Y) → (U X Y)])))
(define-type JSNum (U Integer Float))
(define-type Sign (U -1 1))
(: read-number (Reader JSNum))
(define (read-number i [default bad-input])
(: digit-byte? : (U EOF Byte) → Boolean : #:+ Byte)
(define (digit-byte? c)
(and (not (eof-object? c))
(<= (char->integer #\0) c (char->integer #\9))))
(define (to-number [c : Byte]) (- c (char->integer #\0)))
(define (maybe-bytes [c : (U EOF Byte)]) (if (eof-object? c) #"" (bytes c)))
(: n->string : Integer Integer → Bytes)
(define (n->string n exp)
(define s (number->string n))
(string->bytes/utf-8
(cond
[(zero? exp) s]
[else
(define m (+ (string-length s) exp))
(string-append (substring s 0 m) "." (substring s m))])))
(: read-integer : Sign → JSNum)
(define (read-integer sgn)
(define c (read-byte i))
(cond
[(digit-byte? c)
(read-integer-rest sgn (to-number c)
#:more-digits? (not (eqv? c (char->integer #\0))))]
[else (bad-input i (bytes-append (if (sgn . < . 0) #"-" #"")
(maybe-bytes c))
#:eof? (eof-object? c))]))
(: read-integer-rest : Sign Integer #:more-digits? Boolean → JSNum)
(define (read-integer-rest sgn n #:more-digits? more-digits?)
(define c (peek-byte i))
(cond
[(and more-digits? (digit-byte? c))
(read-byte i)
(read-integer-rest sgn (+ (* n 10) (to-number c)) #:more-digits? #t)]
[(eqv? c (char->integer #\.))
(read-byte i)
(read-fraction sgn n)]
[(or (eqv? c (char->integer #\e))
(eqv? c (char->integer #\E)))
(read-byte i)
(read-exponent (* sgn n) (assert c byte?) 0)]
[else (* sgn n)]))
(: read-fraction : Sign Integer → Float)
(define (read-fraction sgn n)
(define c (read-byte i))
(cond
[(digit-byte? c)
(read-fraction-rest sgn (+ (* n 10) (to-number c)) -1)]
[else (bad-input i (bytes-append (string->bytes/utf-8 (format "~a." (* sgn n)))
(maybe-bytes c))
#:eof? (eof-object? c))]))
(: read-fraction-rest : Sign Integer Integer → Float)
(define (read-fraction-rest sgn n exp)
(define c (peek-byte i))
(cond
[(digit-byte? c)
(read-byte i)
(read-fraction-rest sgn (+ (* n 10) (to-number c)) (sub1 exp))]
[(or (eqv? c (char->integer #\e))
(eqv? c (char->integer #\E)))
(read-byte i)
(read-exponent (* sgn n) (assert c byte?) exp)]
[else (exact->inexact (* sgn n (expt 10 exp)))]))
(: read-exponent : Integer Byte Integer → Float)
(define (read-exponent n mark exp)
(define c (read-byte i))
(cond
[(digit-byte? c)
(read-exponent-rest n exp (to-number c) 1)]
[(eqv? c (char->integer #\+))
(read-exponent-more n mark #"+" exp 1)]
[(eqv? c (char->integer #\-))
(read-exponent-more n mark #"-" exp -1)]
[else (bad-input i (bytes-append (n->string n exp)
(bytes mark)
(maybe-bytes c))
#:eof? (eof-object? c))]))
(: read-exponent-more : Integer Byte Bytes Integer Integer → Float)
(define (read-exponent-more n mark mark2 exp sgn)
(define c (read-byte i))
(cond
[(digit-byte? c)
(read-exponent-rest n exp (to-number c) sgn)]
[else (bad-input i (bytes-append (n->string n exp)
(bytes mark)
mark2
(maybe-bytes c))
#:eof? (eof-object? c))]))
(: read-exponent-rest : Integer Integer Integer Integer → Float)
(define (read-exponent-rest n exp exp2 sgn)
(define c (peek-byte i))
(cond
[(digit-byte? c)
(read-byte i)
(read-exponent-rest n exp (+ (* 10 exp2) (to-number c)) sgn)]
[else (exact->inexact (* n (expt 10 (+ exp (* sgn exp2)))))]))
(let ([ch (skip-whitespace i)])
(cond [(eof-object? ch) (bad-input i)]
[(eqv? ch #\-) (read-byte i)
(read-integer -1)]
[(<= (char->integer #\0) (char->integer ch) (char->integer #\9))
(read-integer 1)]
[else (default i)])))
(: read-integer : (Reader Integer))
(define (read-integer i [default bad-input])
(define n (read-number i default))
(cond [(exact-integer? n) n]
[(integer? n) (assert (inexact->exact n) exact-integer?)]
[else (err i "expect integer, got ~a" n)]))
(: read-float : (Reader Float))
(define (read-float i [default bad-input])
(define n (read-number i default))
(if (exact-integer? n) (exact->inexact n) n))
(: read-a-string (Reader String))
(define (read-a-string i [default bad-input])
(define (byte-char=? [b : Byte] [ch : Char]) (eqv? b (char->integer ch)))
(: keep-char : Char String Integer (Option Bytes-Converter) → String)
(define (keep-char c old-result pos converter)
(define result
(if (= pos (string-length old-result))
(let ([new (make-string (* pos 2))])
(string-copy! new 0 old-result 0 pos)
new)
old-result))
(string-set! result pos c)
(loop result (add1 pos) converter))
(: loop : String Integer (Option Bytes-Converter) → String)
(define (loop result pos converter)
(define c (read-byte i))
(cond
[(eof-object? c) (err i "unterminated string")]
[(byte-char=? c #\") (substring result 0 pos)]
[(byte-char=? c #\\) (read-escape (read-char i) result pos converter)]
[(c . < . 128) (keep-char (integer->char c) result pos converter)]
[else
need to decode , but we ca n't un - read the byte , and
(define cvtr (or converter ID-CONVERTER))
(define buf (make-bytes 6 c))
(let utf8-loop ([start : Natural 0] [end : Natural 1])
(define-values (wrote-n read-n state) (bytes-convert cvtr buf start end buf 0 6))
(case state
[(complete)
(keep-char (bytes-utf-8-ref buf 0) result pos cvtr)]
[(error)
(err i "UTF-8 decoding error at ~e" (subbytes buf 0 end))]
[(aborts)
(define c (read-byte i))
(cond
[(eof-object? c)
(err i "unexpected end-of-file")]
[else
(bytes-set! buf end c)
(utf8-loop (+ start read-n) (add1 end))])]
[else (error 'utf8-loop "internal")]))]))
(: read-escape : (U EOF Char) String Integer (Option Bytes-Converter) → String)
(define (read-escape esc result pos converter)
(cond
[(case esc
[(#\b) "\b"]
[(#\n) "\n"]
[(#\r) "\r"]
[(#\f) "\f"]
[(#\t) "\t"]
[(#\\) "\\"]
[(#\") "\""]
[(#\/) "/"]
[else #f])
=> (λ (s) (keep-char (string-ref s 0) result pos converter))]
[(eqv? esc #\u)
(define (get-hex)
(define (read-next) : Byte
(define c (read-byte i))
(when (eof-object? c) (error "unexpected end-of-file"))
c)
(define c1 (read-next))
(define c2 (read-next))
(define c3 (read-next))
(define c4 (read-next))
(define (hex-convert [c : Byte])
(cond
[(<= (char->integer #\0) c (char->integer #\9))
(- c (char->integer #\0))]
[(<= (char->integer #\a) c (char->integer #\f))
(- c (- (char->integer #\a) 10))]
[(<= (char->integer #\A) c (char->integer #\F))
(- c (- (char->integer #\A) 10))]
[else (err i "bad \\u escape ~e" (bytes c1 c2 c3 c4))]))
(+ (arithmetic-shift (hex-convert c1) 12)
(arithmetic-shift (hex-convert c2) 8)
(arithmetic-shift (hex-convert c3) 4)
(hex-convert c4)))
(define e (get-hex))
(define e*
(cond
[(<= #xD800 e #xDFFF)
(define (err-missing)
(err i "bad string \\u escape, missing second half of a UTF-16 pair"))
(unless (eqv? (read-byte i) (char->integer #\\)) (err-missing))
(unless (eqv? (read-byte i) (char->integer #\u)) (err-missing))
(define e2 (get-hex))
(cond
[(<= #xDC00 e2 #xDFFF)
(+ (arithmetic-shift (- e #xD800) 10) (- e2 #xDC00) #x10000)]
[else
(err i "bad string \\u escape, bad second half of a UTF-16 pair")])]
[else e]))
(keep-char (integer->char e*) result pos converter)]
[else (err i "bad string escape: \"~a\"" esc)]))
(match (skip-whitespace i)
[(== #\" eqv?) (read-byte i)
(loop (make-string 16) 0 #f)]
[_ (default i)]))
(: read-bool (Reader Boolean))
(define (read-bool i [default bad-input])
(match (skip-whitespace i)
[(== #\t eqv?) (consume-literal i #"true") #t]
[(== #\f eqv?) (consume-literal i #"false") #f]
[_ (default i)]))
(: read-const (∀ (X) (Bytes X → (Reader X))))
(define (read-const lit c)
(define l0 (integer->char (bytes-ref lit 0)))
(λ (i [default bad-input])
(if (eqv? (skip-whitespace i) l0)
(begin (consume-literal i lit) c)
(default i))))
(define read-true (read-const #"true" #t))
(define read-false (read-const #"false" #f))
(define (read-null) (read-const #"null" 'null))
(: read-fold (∀ (X A) A (X A → A) (Input-Port → X) → (Reader A)))
(define ((read-fold a f read-one) i [default bad-input])
(let ([ch (skip-whitespace i)])
(cond [(eqv? ch #\[) (read-byte i)
((read-fold-rest a f read-one) i)]
[else (default i)])))
(: read-fold-rest (∀ (X A) A (X A → A) (Input-Port → X) → Input-Port → A))
(define ((read-fold-rest a f read-one) i)
(define ch (skip-whitespace i))
(cond
[(eqv? ch #\]) (read-byte i)
a]
[else
(let loop : A ([a : A (f (read-one i) a)])
(define ch (skip-whitespace i))
(cond
[(eqv? ch #\]) (read-byte i)
a]
[(eqv? ch #\,) (read-byte i)
(loop (f (read-one i) a))]
[else (err i "error while parsing a list")]))]))
(: read-list (∀ (A) (Input-Port → A) → (Reader (Listof A))))
(define ((read-list read-one) i [default bad-input])
(let ([ch (skip-whitespace i)])
(cond [(eqv? ch #\[) (read-byte i)
((read-list-rest read-one) i)]
[else (default i)])))
(: read-list-rest (∀ (A) (Input-Port → A) → Input-Port → (Listof A)))
(define ((read-list-rest read-one) i)
(reverse (((inst read-fold-rest A (Listof A)) '() cons read-one) i)))
(: read-empty-list (Reader Null))
(define (read-empty-list i [default bad-input])
(match (skip-whitespace i)
[(== #\[ eqv?) (read-byte i)
(match (skip-whitespace i)
[(== #\] eqv?) (read-byte i)
'()]
[_ (bad-input i)])]
[_ (default i)]))
(: make-sequence-reader (∀ (X) (Input-Port → X) → Input-Port → (Sequenceof X)))
(define ((make-sequence-reader read-one) i)
(let ([ch (skip-whitespace i)])
(cond [(eqv? ch #\[)
(read-byte i)
(let ([ch (skip-whitespace i)])
(cond
[(eqv? ch #\]) (read-byte i) empty-sequence]
[else
(sequence-append
(in-value (read-one i))
((inst make-do-sequence (U Char EOF) X)
(λ ()
(values (λ _ (read-one i))
(λ _ (skip-whitespace i))
(skip-whitespace i)
(λ (ch)
(cond
[(eqv? ch #\,) (read-byte i) #t]
[(eqv? ch #\]) (read-byte i) #f]
[else (err i "error white parsing a list")]))
#f
#f))))]))]
[else (err i "error while parsing a list")])))
(define ID-CONVERTER (assert (bytes-open-converter "UTF-8" "UTF-8")))
(: skip-json : Input-Port → Void)
(define (skip-json i) (void (read-json i)))
(: consume-literal : Input-Port Bytes → Void)
(define (consume-literal i bstr)
(define len (bytes-length bstr))
(read-byte i)
(for ([j (in-range 1 len)])
(define c (assert (read-byte i) byte?))
(unless (eqv? c (bytes-ref bstr j))
(bad-input i (bytes-append (subbytes bstr 0 j) (bytes c)))))
(define b (peek-byte i))
(unless (eof-object? b)
(when (or (<= (char->integer #\a) b (char->integer #\z))
(<= (char->integer #\A) b (char->integer #\Z))
(<= (char->integer #\0) b (char->integer #\9))
(eqv? b (char->integer #\_)))
(bad-input i bstr))))
(: skip-whitespace : Input-Port → (U Char EOF))
(define (skip-whitespace i)
(match (peek-char i)
[(and (? char?) (? char-whitespace?))
(read-char i)
(skip-whitespace i)]
[ch ch]))
Follows the specification ( eg , at json.org ) -- no extensions .
(: err : Input-Port String Any * → Nothing)
(define (err i fmt . args)
(define-values (l c p) (port-next-location i))
(raise-read-error (apply format fmt args)
(object-name i) l c p #f))
(: bad-input (->* [Input-Port] [Bytes #:eof? (U Bytes #t #f)] Nothing))
(define (bad-input i [prefix #""] #:eof? [eof? #f])
(define bstr (peek-bytes (assert (sub1 (error-print-width)) index?) 0 i))
(if (or (and (eof-object? bstr) (equal? prefix #""))
eof?)
(err i (string-append "unexpected end-of-file"
(if (equal? prefix #"")
""
(format "after ~e" prefix))))
(err i (format "bad input starting ~e" (bytes-append prefix (if (eof-object? bstr)
#""
bstr))))))
|
2c989d12752b01dfc4846786746a8e0769e0e16cbbbedd9d51bdbb82a865bb91 | circuithub/rel8 | Information.hs | # language GADTs #
# language NamedFieldPuns #
# language StandaloneKindSignatures #
module Rel8.Type.Information
( TypeInformation(..)
, mapTypeInformation
, parseTypeInformation
)
where
-- base
import Data.Bifunctor ( first )
import Data.Kind ( Type )
import Prelude
-- hasql
import qualified Hasql.Decoders as Hasql
-- opaleye
import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
-- text
import qualified Data.Text as Text
| @TypeInformation@ describes how to encode and decode a type to and
-- from database queries. The @typeName@ is the name of the type in the
-- database, which is used to accurately type literals.
type TypeInformation :: Type -> Type
data TypeInformation a = TypeInformation
{ encode :: a -> Opaleye.PrimExpr
^ How to encode a single Haskell value as a SQL expression .
, decode :: Hasql.Value a
^ How to deserialize a single result back to Haskell .
, typeName :: String
-- ^ The name of the SQL type.
}
-- | Simultaneously map over how a type is both encoded and decoded, while
-- retaining the name of the type. This operation is useful if you want to
-- essentially @newtype@ another 'Rel8.DBType'.
--
-- The mapping is required to be total. If you have a partial mapping, see
-- 'parseTypeInformation'.
mapTypeInformation :: ()
=> (a -> b) -> (b -> a)
-> TypeInformation a -> TypeInformation b
mapTypeInformation = parseTypeInformation . fmap pure
| Apply a parser to ' TypeInformation ' .
--
-- This can be used if the data stored in the database should only be subset of
a given ' TypeInformation ' . The parser is applied when deserializing rows
-- returned - the encoder assumes that the input data is already in the
-- appropriate form.
parseTypeInformation :: ()
=> (a -> Either String b) -> (b -> a)
-> TypeInformation a -> TypeInformation b
parseTypeInformation to from TypeInformation {encode, decode, typeName} =
TypeInformation
{ encode = encode . from
, decode = Hasql.refine (first Text.pack . to) decode
, typeName
}
| null | https://raw.githubusercontent.com/circuithub/rel8/93638f8bdf98023fb5ac2d9b38867af51561a063/src/Rel8/Type/Information.hs | haskell | base
hasql
opaleye
text
from database queries. The @typeName@ is the name of the type in the
database, which is used to accurately type literals.
^ The name of the SQL type.
| Simultaneously map over how a type is both encoded and decoded, while
retaining the name of the type. This operation is useful if you want to
essentially @newtype@ another 'Rel8.DBType'.
The mapping is required to be total. If you have a partial mapping, see
'parseTypeInformation'.
This can be used if the data stored in the database should only be subset of
returned - the encoder assumes that the input data is already in the
appropriate form. | # language GADTs #
# language NamedFieldPuns #
# language StandaloneKindSignatures #
module Rel8.Type.Information
( TypeInformation(..)
, mapTypeInformation
, parseTypeInformation
)
where
import Data.Bifunctor ( first )
import Data.Kind ( Type )
import Prelude
import qualified Hasql.Decoders as Hasql
import qualified Opaleye.Internal.HaskellDB.PrimQuery as Opaleye
import qualified Data.Text as Text
| @TypeInformation@ describes how to encode and decode a type to and
type TypeInformation :: Type -> Type
data TypeInformation a = TypeInformation
{ encode :: a -> Opaleye.PrimExpr
^ How to encode a single Haskell value as a SQL expression .
, decode :: Hasql.Value a
^ How to deserialize a single result back to Haskell .
, typeName :: String
}
mapTypeInformation :: ()
=> (a -> b) -> (b -> a)
-> TypeInformation a -> TypeInformation b
mapTypeInformation = parseTypeInformation . fmap pure
| Apply a parser to ' TypeInformation ' .
a given ' TypeInformation ' . The parser is applied when deserializing rows
parseTypeInformation :: ()
=> (a -> Either String b) -> (b -> a)
-> TypeInformation a -> TypeInformation b
parseTypeInformation to from TypeInformation {encode, decode, typeName} =
TypeInformation
{ encode = encode . from
, decode = Hasql.refine (first Text.pack . to) decode
, typeName
}
|
32ce1c42bad96120da387e21cf0eb00ea4d0d05e7c682eed62f9f110b85f3021 | ml-in-barcelona/server-reason-react | belt_Array.ml | external length : 'a array -> int = "%array_length"
external size : 'a array -> int = "%array_length"
external getUnsafe : 'a array -> int -> 'a = "%array_unsafe_get"
external setUnsafe : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
let getUndefined arr i =
try Js.fromOpt (Some arr.(i)) with Invalid_argument _ -> Js.fromOpt None
external get : 'a array -> int -> 'a = "%array_safe_get"
let get arr i =
if i >= 0 && i < length arr then Some (getUnsafe arr i) else None
let getExn arr i =
if Stdlib.not (i >= 0 && i < length arr) then
Js.Exn.raiseError "File \"\", line 37, characters 6-12";
getUnsafe arr i
let set arr i v =
if i >= 0 && i < length arr then (
setUnsafe arr i v;
true)
else false
let setExn arr i v =
if Stdlib.not (i >= 0 && i < length arr) then
Js.Exn.raiseError "File \"\", line 43, characters 4-10";
setUnsafe arr i v
let makeUninitialized len = Array.make len Js.undefined
let makeUninitializedUnsafe len defaultVal = Array.make len defaultVal
let truncateToLengthUnsafe arr len = Array.sub arr 0 len
let copy a =
let l = length a in
let v = if l > 0 then Array.make l (getUnsafe a 0) else [||] in
for i = 0 to l - 1 do
setUnsafe v i (getUnsafe a i)
done;
v
let swapUnsafe xs i j =
let tmp = getUnsafe xs i in
setUnsafe xs i (getUnsafe xs j);
setUnsafe xs j tmp
let shuffleInPlace xs =
let len = length xs in
for i = 0 to len - 1 do
swapUnsafe xs i (Js_math.random_int i len)
done
let shuffle xs =
let result = copy xs in
shuffleInPlace result;
result
let reverseAux xs ofs len =
for i = 0 to (len / 2) - 1 do
swapUnsafe xs (ofs + i) (ofs + len - i - 1)
done
let reverseInPlace xs =
let len = length xs in
reverseAux xs 0 len
let make l f =
if l <= 0 then [||]
else
let res = Array.make l f in
res
let reverse xs =
let len = length xs in
let result =
if len > 0 then makeUninitializedUnsafe len (getUnsafe xs 0) else [||]
in
for i = 0 to len - 1 do
setUnsafe result i (getUnsafe xs (len - 1 - i))
done;
result
let makeByU l f =
if l <= 0 then [||]
else
let res = if l > 0 then makeUninitializedUnsafe l (f 0) else [||] in
for i = 0 to l - 1 do
setUnsafe res i (f i)
done;
res
let makeBy l f = makeByU l (fun a -> f a)
let makeByAndShuffleU l f =
let u = makeByU l f in
shuffleInPlace u;
u
let makeByAndShuffle l f = makeByAndShuffleU l (fun a -> f a)
let range start finish =
let cut = finish - start in
if cut < 0 then [||]
else
let arr = makeUninitializedUnsafe (cut + 1) 0 in
for i = 0 to cut do
setUnsafe arr i (start + i)
done;
arr
let rangeBy start finish ~step =
let cut = finish - start in
if cut < 0 || step <= 0 then [||]
else
let nb = (cut / step) + 1 in
let arr = makeUninitializedUnsafe nb 0 in
let cur = ref start in
for i = 0 to nb - 1 do
setUnsafe arr i !cur;
cur := !cur + step
done;
arr
let zip xs ys =
let lenx, leny = (length xs, length ys) in
let len = Stdlib.min lenx leny in
let s =
if len > 0 then makeUninitializedUnsafe len (getUnsafe xs 0, getUnsafe ys 0)
else [||]
in
for i = 0 to len - 1 do
setUnsafe s i (getUnsafe xs i, getUnsafe ys i)
done;
s
let zipByU xs ys f =
let lenx, leny = (length xs, length ys) in
let len = Stdlib.min lenx leny in
let s =
if len > 0 then
makeUninitializedUnsafe len (f (getUnsafe xs 0) (getUnsafe ys 0))
else [||]
in
for i = 0 to len - 1 do
setUnsafe s i (f (getUnsafe xs i) (getUnsafe ys i))
done;
s
let zipBy xs ys f = zipByU xs ys (fun a b -> f a b)
let concat a1 a2 =
let l1 = length a1 in
let l2 = length a2 in
let a1a2 =
if l1 > 0 then makeUninitializedUnsafe (l1 + l2) (getUnsafe a1 0) else [||]
in
for i = 0 to l1 - 1 do
setUnsafe a1a2 i (getUnsafe a1 i)
done;
for i = 0 to l2 - 1 do
setUnsafe a1a2 (l1 + i) (getUnsafe a2 i)
done;
a1a2
let concatMany arrs =
let lenArrs = length arrs in
let totalLen = ref 0 in
let firstArrWithLengthMoreThanZero = ref None in
for i = 0 to lenArrs - 1 do
let len = length (getUnsafe arrs i) in
totalLen := !totalLen + len;
if len > 0 && !firstArrWithLengthMoreThanZero = None then
firstArrWithLengthMoreThanZero := Some (getUnsafe arrs i)
done;
match !firstArrWithLengthMoreThanZero with
| None -> [||]
| Some firstArr ->
let result = makeUninitializedUnsafe !totalLen (getUnsafe firstArr 0) in
totalLen := 0;
for j = 0 to lenArrs - 1 do
let cur = getUnsafe arrs j in
for k = 0 to length cur - 1 do
setUnsafe result !totalLen (getUnsafe cur k);
incr totalLen
done
done;
result
let slice a ~offset ~len =
if len <= 0 then [||]
else
let lena = length a in
let ofs = if offset < 0 then max (lena + offset) 0 else offset in
let hasLen = lena - ofs in
let copyLength = min hasLen len in
if copyLength <= 0 then [||]
else
let result =
if lena > 0 then makeUninitializedUnsafe copyLength (getUnsafe a 0)
else [||]
in
for i = 0 to copyLength - 1 do
setUnsafe result i (getUnsafe a (ofs + i))
done;
result
let fill a ~offset ~len v =
if len > 0 then
let lena = length a in
let ofs = if offset < 0 then max (lena + offset) 0 else offset in
let hasLen = lena - ofs in
let fillLength = min hasLen len in
if fillLength > 0 then
for i = ofs to ofs + fillLength - 1 do
setUnsafe a i v
done
let blitUnsafe
~src:a1
~srcOffset:srcofs1
~dst:a2
~dstOffset:srcofs2
~len:blitLength =
if srcofs2 <= srcofs1 then
for j = 0 to blitLength - 1 do
setUnsafe a2 (j + srcofs2) (getUnsafe a1 (j + srcofs1))
done
else
for j = blitLength - 1 downto 0 do
setUnsafe a2 (j + srcofs2) (getUnsafe a1 (j + srcofs1))
done
let blit ~src:a1 ~srcOffset:ofs1 ~dst:a2 ~dstOffset:ofs2 ~len =
let lena1 = length a1 in
let lena2 = length a2 in
let srcofs1 = if ofs1 < 0 then max (lena1 + ofs1) 0 else ofs1 in
let srcofs2 = if ofs2 < 0 then max (lena2 + ofs2) 0 else ofs2 in
let blitLength = min len (min (lena1 - srcofs1) (lena2 - srcofs2)) in
if srcofs2 <= srcofs1 then
for j = 0 to blitLength - 1 do
setUnsafe a2 (j + srcofs2) (getUnsafe a1 (j + srcofs1))
done
else
for j = blitLength - 1 downto 0 do
setUnsafe a2 (j + srcofs2) (getUnsafe a1 (j + srcofs1))
done
let forEachU a f =
for i = 0 to length a - 1 do
f (getUnsafe a i)
done
let forEach a f = forEachU a (fun a -> f a)
let mapU a f =
let l = length a in
let r =
if l > 0 then makeUninitializedUnsafe l (f (getUnsafe a 0)) else [||]
in
for i = 0 to l - 1 do
setUnsafe r i (f (getUnsafe a i))
done;
r
let map a f = mapU a (fun a -> f a)
let keepU a f =
let l = length a in
let r = if l > 0 then makeUninitializedUnsafe l (getUnsafe a 0) else [||] in
let j = ref 0 in
for i = 0 to l - 1 do
let v = getUnsafe a i in
if f v then (
setUnsafe r !j v;
incr j)
done;
truncateToLengthUnsafe r !j
let keep a f = keepU a (fun a -> f a)
let keepMapU a f =
let l = length a in
let r = ref None in
let j = ref 0 in
for i = 0 to l - 1 do
let v = getUnsafe a i in
match f v with
| None -> ()
| Some v ->
let r =
match !r with
| None ->
let newr = makeUninitializedUnsafe l v in
r := Some newr;
newr
| Some r -> r
in
setUnsafe r !j v;
incr j
done;
match !r with None -> [||] | Some r -> truncateToLengthUnsafe r !j
let keepMap a f = keepMapU a (fun a -> f a)
let forEachWithIndexU a f =
for i = 0 to length a - 1 do
f i (getUnsafe a i)
done
let forEachWithIndex a f = forEachWithIndexU a (fun a b -> f a b)
let mapWithIndexU a f =
let l = length a in
let r =
if l > 0 then makeUninitializedUnsafe l (f 0 (getUnsafe a 0)) else [||]
in
for i = 0 to l - 1 do
setUnsafe r i (f i (getUnsafe a i))
done;
r
let mapWithIndex a f = mapWithIndexU a (fun a b -> f a b)
let reduceU a x f =
let r = ref x in
for i = 0 to length a - 1 do
r := f !r (getUnsafe a i)
done;
!r
let reduce a x f = reduceU a x (fun a b -> f a b)
let reduceReverseU a x f =
let r = ref x in
for i = length a - 1 downto 0 do
r := f !r (getUnsafe a i)
done;
!r
let reduceReverse a x f = reduceReverseU a x (fun a b -> f a b)
let reduceReverse2U a b x f =
let r = ref x in
let len = min (length a) (length b) in
for i = len - 1 downto 0 do
r := f !r (getUnsafe a i) (getUnsafe b i)
done;
!r
let reduceReverse2 a b x f = reduceReverse2U a b x (fun a b c -> f a b c)
let rec everyAux arr i b len =
if i = len then true
else if b (getUnsafe arr i) then everyAux arr (i + 1) b len
else false
let rec someAux arr i b len =
if i = len then false
else if b (getUnsafe arr i) then true
else someAux arr (i + 1) b len
let everyU arr b =
let len = length arr in
everyAux arr 0 b len
let every arr f = everyU arr (fun b -> f b)
let someU arr b =
let len = length arr in
someAux arr 0 b len
let some arr f = someU arr (fun b -> f b)
let rec everyAux2 arr1 arr2 i b len =
if i = len then true
else if b (getUnsafe arr1 i) (getUnsafe arr2 i) then
everyAux2 arr1 arr2 (i + 1) b len
else false
let rec someAux2 arr1 arr2 i b len =
if i = len then false
else if b (getUnsafe arr1 i) (getUnsafe arr2 i) then true
else someAux2 arr1 arr2 (i + 1) b len
let every2U a b p = everyAux2 a b 0 p (min (length a) (length b))
let every2 a b p = every2U a b (fun a b -> p a b)
let some2U a b p = someAux2 a b 0 p (min (length a) (length b))
let some2 a b p = some2U a b (fun a b -> p a b)
let eqU a b p =
let lena = length a in
let lenb = length b in
if lena = lenb then everyAux2 a b 0 p lena else false
let eq a b p = eqU a b (fun a b -> p a b)
let rec everyCmpAux2 arr1 arr2 i b len =
if i = len then 0
else
let c = b (getUnsafe arr1 i) (getUnsafe arr2 i) in
if c = 0 then everyCmpAux2 arr1 arr2 (i + 1) b len else c
let cmpU a b p =
let lena = length a in
let lenb = length b in
if lena > lenb then 1
else if lena < lenb then -1
else everyCmpAux2 a b 0 p lena
let cmp a b p = cmpU a b (fun a b -> p a b)
let partitionU a f =
let l = length a in
let i = ref 0 in
let j = ref 0 in
let a1 = if l > 0 then makeUninitializedUnsafe l (getUnsafe a 0) else [||] in
let a2 = if l > 0 then makeUninitializedUnsafe l (getUnsafe a 0) else [||] in
for ii = 0 to l - 1 do
let v = getUnsafe a ii in
if f v then (
setUnsafe a1 !i v;
incr i)
else (
setUnsafe a2 !j v;
incr j)
done;
(truncateToLengthUnsafe a1 !i, truncateToLengthUnsafe a2 !j)
let partition a f = partitionU a (fun x -> f x)
let unzip a =
let l = length a in
let a1, a2 =
if l > 0 then
let v1, v2 = getUnsafe a 0 in
(makeUninitializedUnsafe l v1, makeUninitializedUnsafe l v2)
else ([||], [||])
in
for i = 0 to l - 1 do
let v1, v2 = getUnsafe a i in
setUnsafe a1 i v1;
setUnsafe a2 i v2
done;
(a1, a2)
| null | https://raw.githubusercontent.com/ml-in-barcelona/server-reason-react/a5d22907eb2633bcb8e77808f6c677802062953a/lib/belt/belt_Array.ml | ocaml | external length : 'a array -> int = "%array_length"
external size : 'a array -> int = "%array_length"
external getUnsafe : 'a array -> int -> 'a = "%array_unsafe_get"
external setUnsafe : 'a array -> int -> 'a -> unit = "%array_unsafe_set"
let getUndefined arr i =
try Js.fromOpt (Some arr.(i)) with Invalid_argument _ -> Js.fromOpt None
external get : 'a array -> int -> 'a = "%array_safe_get"
let get arr i =
if i >= 0 && i < length arr then Some (getUnsafe arr i) else None
let getExn arr i =
if Stdlib.not (i >= 0 && i < length arr) then
Js.Exn.raiseError "File \"\", line 37, characters 6-12";
getUnsafe arr i
let set arr i v =
if i >= 0 && i < length arr then (
setUnsafe arr i v;
true)
else false
let setExn arr i v =
if Stdlib.not (i >= 0 && i < length arr) then
Js.Exn.raiseError "File \"\", line 43, characters 4-10";
setUnsafe arr i v
let makeUninitialized len = Array.make len Js.undefined
let makeUninitializedUnsafe len defaultVal = Array.make len defaultVal
let truncateToLengthUnsafe arr len = Array.sub arr 0 len
let copy a =
let l = length a in
let v = if l > 0 then Array.make l (getUnsafe a 0) else [||] in
for i = 0 to l - 1 do
setUnsafe v i (getUnsafe a i)
done;
v
let swapUnsafe xs i j =
let tmp = getUnsafe xs i in
setUnsafe xs i (getUnsafe xs j);
setUnsafe xs j tmp
let shuffleInPlace xs =
let len = length xs in
for i = 0 to len - 1 do
swapUnsafe xs i (Js_math.random_int i len)
done
let shuffle xs =
let result = copy xs in
shuffleInPlace result;
result
let reverseAux xs ofs len =
for i = 0 to (len / 2) - 1 do
swapUnsafe xs (ofs + i) (ofs + len - i - 1)
done
let reverseInPlace xs =
let len = length xs in
reverseAux xs 0 len
let make l f =
if l <= 0 then [||]
else
let res = Array.make l f in
res
let reverse xs =
let len = length xs in
let result =
if len > 0 then makeUninitializedUnsafe len (getUnsafe xs 0) else [||]
in
for i = 0 to len - 1 do
setUnsafe result i (getUnsafe xs (len - 1 - i))
done;
result
let makeByU l f =
if l <= 0 then [||]
else
let res = if l > 0 then makeUninitializedUnsafe l (f 0) else [||] in
for i = 0 to l - 1 do
setUnsafe res i (f i)
done;
res
let makeBy l f = makeByU l (fun a -> f a)
let makeByAndShuffleU l f =
let u = makeByU l f in
shuffleInPlace u;
u
let makeByAndShuffle l f = makeByAndShuffleU l (fun a -> f a)
let range start finish =
let cut = finish - start in
if cut < 0 then [||]
else
let arr = makeUninitializedUnsafe (cut + 1) 0 in
for i = 0 to cut do
setUnsafe arr i (start + i)
done;
arr
let rangeBy start finish ~step =
let cut = finish - start in
if cut < 0 || step <= 0 then [||]
else
let nb = (cut / step) + 1 in
let arr = makeUninitializedUnsafe nb 0 in
let cur = ref start in
for i = 0 to nb - 1 do
setUnsafe arr i !cur;
cur := !cur + step
done;
arr
let zip xs ys =
let lenx, leny = (length xs, length ys) in
let len = Stdlib.min lenx leny in
let s =
if len > 0 then makeUninitializedUnsafe len (getUnsafe xs 0, getUnsafe ys 0)
else [||]
in
for i = 0 to len - 1 do
setUnsafe s i (getUnsafe xs i, getUnsafe ys i)
done;
s
let zipByU xs ys f =
let lenx, leny = (length xs, length ys) in
let len = Stdlib.min lenx leny in
let s =
if len > 0 then
makeUninitializedUnsafe len (f (getUnsafe xs 0) (getUnsafe ys 0))
else [||]
in
for i = 0 to len - 1 do
setUnsafe s i (f (getUnsafe xs i) (getUnsafe ys i))
done;
s
let zipBy xs ys f = zipByU xs ys (fun a b -> f a b)
let concat a1 a2 =
let l1 = length a1 in
let l2 = length a2 in
let a1a2 =
if l1 > 0 then makeUninitializedUnsafe (l1 + l2) (getUnsafe a1 0) else [||]
in
for i = 0 to l1 - 1 do
setUnsafe a1a2 i (getUnsafe a1 i)
done;
for i = 0 to l2 - 1 do
setUnsafe a1a2 (l1 + i) (getUnsafe a2 i)
done;
a1a2
let concatMany arrs =
let lenArrs = length arrs in
let totalLen = ref 0 in
let firstArrWithLengthMoreThanZero = ref None in
for i = 0 to lenArrs - 1 do
let len = length (getUnsafe arrs i) in
totalLen := !totalLen + len;
if len > 0 && !firstArrWithLengthMoreThanZero = None then
firstArrWithLengthMoreThanZero := Some (getUnsafe arrs i)
done;
match !firstArrWithLengthMoreThanZero with
| None -> [||]
| Some firstArr ->
let result = makeUninitializedUnsafe !totalLen (getUnsafe firstArr 0) in
totalLen := 0;
for j = 0 to lenArrs - 1 do
let cur = getUnsafe arrs j in
for k = 0 to length cur - 1 do
setUnsafe result !totalLen (getUnsafe cur k);
incr totalLen
done
done;
result
let slice a ~offset ~len =
if len <= 0 then [||]
else
let lena = length a in
let ofs = if offset < 0 then max (lena + offset) 0 else offset in
let hasLen = lena - ofs in
let copyLength = min hasLen len in
if copyLength <= 0 then [||]
else
let result =
if lena > 0 then makeUninitializedUnsafe copyLength (getUnsafe a 0)
else [||]
in
for i = 0 to copyLength - 1 do
setUnsafe result i (getUnsafe a (ofs + i))
done;
result
let fill a ~offset ~len v =
if len > 0 then
let lena = length a in
let ofs = if offset < 0 then max (lena + offset) 0 else offset in
let hasLen = lena - ofs in
let fillLength = min hasLen len in
if fillLength > 0 then
for i = ofs to ofs + fillLength - 1 do
setUnsafe a i v
done
let blitUnsafe
~src:a1
~srcOffset:srcofs1
~dst:a2
~dstOffset:srcofs2
~len:blitLength =
if srcofs2 <= srcofs1 then
for j = 0 to blitLength - 1 do
setUnsafe a2 (j + srcofs2) (getUnsafe a1 (j + srcofs1))
done
else
for j = blitLength - 1 downto 0 do
setUnsafe a2 (j + srcofs2) (getUnsafe a1 (j + srcofs1))
done
let blit ~src:a1 ~srcOffset:ofs1 ~dst:a2 ~dstOffset:ofs2 ~len =
let lena1 = length a1 in
let lena2 = length a2 in
let srcofs1 = if ofs1 < 0 then max (lena1 + ofs1) 0 else ofs1 in
let srcofs2 = if ofs2 < 0 then max (lena2 + ofs2) 0 else ofs2 in
let blitLength = min len (min (lena1 - srcofs1) (lena2 - srcofs2)) in
if srcofs2 <= srcofs1 then
for j = 0 to blitLength - 1 do
setUnsafe a2 (j + srcofs2) (getUnsafe a1 (j + srcofs1))
done
else
for j = blitLength - 1 downto 0 do
setUnsafe a2 (j + srcofs2) (getUnsafe a1 (j + srcofs1))
done
let forEachU a f =
for i = 0 to length a - 1 do
f (getUnsafe a i)
done
let forEach a f = forEachU a (fun a -> f a)
let mapU a f =
let l = length a in
let r =
if l > 0 then makeUninitializedUnsafe l (f (getUnsafe a 0)) else [||]
in
for i = 0 to l - 1 do
setUnsafe r i (f (getUnsafe a i))
done;
r
let map a f = mapU a (fun a -> f a)
let keepU a f =
let l = length a in
let r = if l > 0 then makeUninitializedUnsafe l (getUnsafe a 0) else [||] in
let j = ref 0 in
for i = 0 to l - 1 do
let v = getUnsafe a i in
if f v then (
setUnsafe r !j v;
incr j)
done;
truncateToLengthUnsafe r !j
let keep a f = keepU a (fun a -> f a)
let keepMapU a f =
let l = length a in
let r = ref None in
let j = ref 0 in
for i = 0 to l - 1 do
let v = getUnsafe a i in
match f v with
| None -> ()
| Some v ->
let r =
match !r with
| None ->
let newr = makeUninitializedUnsafe l v in
r := Some newr;
newr
| Some r -> r
in
setUnsafe r !j v;
incr j
done;
match !r with None -> [||] | Some r -> truncateToLengthUnsafe r !j
let keepMap a f = keepMapU a (fun a -> f a)
let forEachWithIndexU a f =
for i = 0 to length a - 1 do
f i (getUnsafe a i)
done
let forEachWithIndex a f = forEachWithIndexU a (fun a b -> f a b)
let mapWithIndexU a f =
let l = length a in
let r =
if l > 0 then makeUninitializedUnsafe l (f 0 (getUnsafe a 0)) else [||]
in
for i = 0 to l - 1 do
setUnsafe r i (f i (getUnsafe a i))
done;
r
let mapWithIndex a f = mapWithIndexU a (fun a b -> f a b)
let reduceU a x f =
let r = ref x in
for i = 0 to length a - 1 do
r := f !r (getUnsafe a i)
done;
!r
let reduce a x f = reduceU a x (fun a b -> f a b)
let reduceReverseU a x f =
let r = ref x in
for i = length a - 1 downto 0 do
r := f !r (getUnsafe a i)
done;
!r
let reduceReverse a x f = reduceReverseU a x (fun a b -> f a b)
let reduceReverse2U a b x f =
let r = ref x in
let len = min (length a) (length b) in
for i = len - 1 downto 0 do
r := f !r (getUnsafe a i) (getUnsafe b i)
done;
!r
let reduceReverse2 a b x f = reduceReverse2U a b x (fun a b c -> f a b c)
let rec everyAux arr i b len =
if i = len then true
else if b (getUnsafe arr i) then everyAux arr (i + 1) b len
else false
let rec someAux arr i b len =
if i = len then false
else if b (getUnsafe arr i) then true
else someAux arr (i + 1) b len
let everyU arr b =
let len = length arr in
everyAux arr 0 b len
let every arr f = everyU arr (fun b -> f b)
let someU arr b =
let len = length arr in
someAux arr 0 b len
let some arr f = someU arr (fun b -> f b)
let rec everyAux2 arr1 arr2 i b len =
if i = len then true
else if b (getUnsafe arr1 i) (getUnsafe arr2 i) then
everyAux2 arr1 arr2 (i + 1) b len
else false
let rec someAux2 arr1 arr2 i b len =
if i = len then false
else if b (getUnsafe arr1 i) (getUnsafe arr2 i) then true
else someAux2 arr1 arr2 (i + 1) b len
let every2U a b p = everyAux2 a b 0 p (min (length a) (length b))
let every2 a b p = every2U a b (fun a b -> p a b)
let some2U a b p = someAux2 a b 0 p (min (length a) (length b))
let some2 a b p = some2U a b (fun a b -> p a b)
let eqU a b p =
let lena = length a in
let lenb = length b in
if lena = lenb then everyAux2 a b 0 p lena else false
let eq a b p = eqU a b (fun a b -> p a b)
let rec everyCmpAux2 arr1 arr2 i b len =
if i = len then 0
else
let c = b (getUnsafe arr1 i) (getUnsafe arr2 i) in
if c = 0 then everyCmpAux2 arr1 arr2 (i + 1) b len else c
let cmpU a b p =
let lena = length a in
let lenb = length b in
if lena > lenb then 1
else if lena < lenb then -1
else everyCmpAux2 a b 0 p lena
let cmp a b p = cmpU a b (fun a b -> p a b)
let partitionU a f =
let l = length a in
let i = ref 0 in
let j = ref 0 in
let a1 = if l > 0 then makeUninitializedUnsafe l (getUnsafe a 0) else [||] in
let a2 = if l > 0 then makeUninitializedUnsafe l (getUnsafe a 0) else [||] in
for ii = 0 to l - 1 do
let v = getUnsafe a ii in
if f v then (
setUnsafe a1 !i v;
incr i)
else (
setUnsafe a2 !j v;
incr j)
done;
(truncateToLengthUnsafe a1 !i, truncateToLengthUnsafe a2 !j)
let partition a f = partitionU a (fun x -> f x)
let unzip a =
let l = length a in
let a1, a2 =
if l > 0 then
let v1, v2 = getUnsafe a 0 in
(makeUninitializedUnsafe l v1, makeUninitializedUnsafe l v2)
else ([||], [||])
in
for i = 0 to l - 1 do
let v1, v2 = getUnsafe a i in
setUnsafe a1 i v1;
setUnsafe a2 i v2
done;
(a1, a2)
| |
93f1548d8f34cedc0d3869d39d0566c37cef6a8de390dae61f497320031b95cf | MyDataFlow/ttalk-server | eunit_SUITE.erl | Copyright ( c ) 2013 - 2014 , < >
%%
%% Permission to use, copy, modify, and/or distribute this software for any
%% purpose with or without fee is hereby granted, provided that the above
%% copyright notice and this permission notice appear in all copies.
%%
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
%% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
%% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
%% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
%% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-module(eunit_SUITE).
-compile(export_all).
all() ->
[eunit].
eunit(_) ->
ok = eunit:test({application, cowboy}).
| null | https://raw.githubusercontent.com/MyDataFlow/ttalk-server/07a60d5d74cd86aedd1f19c922d9d3abf2ebf28d/deps/cowboy/test/eunit_SUITE.erl | erlang |
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. | Copyright ( c ) 2013 - 2014 , < >
THE SOFTWARE IS PROVIDED " AS IS " AND THE AUTHOR DISCLAIMS ALL WARRANTIES
ANY SPECIAL , DIRECT , INDIRECT , OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE , DATA OR PROFITS , WHETHER IN AN
-module(eunit_SUITE).
-compile(export_all).
all() ->
[eunit].
eunit(_) ->
ok = eunit:test({application, cowboy}).
|
0a0b677573f142ae8ebc96664f1752990f864436bcdef11d82ea9117cb16f391 | ubf/ubf-redis | ruf_driver.erl | %%% -*- mode: erlang -*-
%%%
%%% The MIT License
%%%
Copyright ( C ) 2012 - 2016 by < >
%%%
%%% Permission is hereby granted, free of charge, to any person obtaining a copy
%%% of this software and associated documentation files (the "Software"), to deal
in the Software without restriction , including without limitation the rights
%%% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software , and to permit persons to whom the Software is
%%% furnished to do so, subject to the following conditions:
%%%
%%% The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software .
%%%
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
%%% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
%%% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
%%% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
%%% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
%%% THE SOFTWARE.
%%%
@doc Protocol driver process for RUF ( Redis Binary Format )
%%% protocol sessions.
-module(ruf_driver).
-behaviour(contract_driver).
-export([start/1, start/2, init/1, init/2, encode/3, decode/4]).
%%%=========================================================================
%%% Records, Types, Macros
%%%=========================================================================
-define(VSN_1, "2.4.15.0").
%%%=========================================================================
%%% API
%%%=========================================================================
%% -----------------------------------------------------------------
%%
%% -----------------------------------------------------------------
start(Contract) ->
start(Contract, []).
start(Contract, Options) ->
proc_utils:spawn_link_debug(fun() -> contract_driver:start(?MODULE, Contract, Options) end, ruf_client_driver).
%% -----------------------------------------------------------------
%%
%% -----------------------------------------------------------------
init(Contract) ->
init(Contract, []).
init(_Contract, Options) ->
Safe = safe(Options),
{Safe, ruf:decode_init(Safe)}.
%% -----------------------------------------------------------------
%%
%% -----------------------------------------------------------------
encode(Contract, _Safe, Term) ->
VSN = case get(?MODULE) of undefined -> ?VSN_1; V -> V end,
ruf:encode(ruf_term:decode(Term, Contract, VSN), Contract, VSN).
%% -----------------------------------------------------------------
%%
%% -----------------------------------------------------------------
decode(Contract, Safe, {init, Rest, VSN}, Binary) ->
put(?MODULE, VSN),
Cont = ruf:decode_init(Safe, Rest),
decode(Contract, Safe, Cont, Binary);
decode(Contract, Safe, Cont, Binary) ->
case ruf:decode(Binary, Contract, Cont) of
{done, Term, Rest1, VSN1} ->
Term1 = ruf_term:encode(Term, Contract, VSN1, Safe),
{done, Term1, Rest1, VSN1};
Else ->
Else
end.
%%%========================================================================
Internal functions
%%%========================================================================
%% -----------------------------------------------------------------
%%
%% -----------------------------------------------------------------
safe(Options) ->
proplists:get_bool(safe, Options).
| null | https://raw.githubusercontent.com/ubf/ubf-redis/737c3c47ebeae76ab8d3758bed7b4f3eb22b13ea/src/ruf_driver.erl | erlang | -*- mode: erlang -*-
The MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
protocol sessions.
=========================================================================
Records, Types, Macros
=========================================================================
=========================================================================
API
=========================================================================
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
-----------------------------------------------------------------
========================================================================
========================================================================
-----------------------------------------------------------------
----------------------------------------------------------------- | Copyright ( C ) 2012 - 2016 by < >
in the Software without restriction , including without limitation the rights
copies of the Software , and to permit persons to whom the Software is
all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND , EXPRESS OR
LIABILITY , WHETHER IN AN ACTION OF CONTRACT , TORT OR OTHERWISE , ARISING FROM ,
@doc Protocol driver process for RUF ( Redis Binary Format )
-module(ruf_driver).
-behaviour(contract_driver).
-export([start/1, start/2, init/1, init/2, encode/3, decode/4]).
-define(VSN_1, "2.4.15.0").
start(Contract) ->
start(Contract, []).
start(Contract, Options) ->
proc_utils:spawn_link_debug(fun() -> contract_driver:start(?MODULE, Contract, Options) end, ruf_client_driver).
init(Contract) ->
init(Contract, []).
init(_Contract, Options) ->
Safe = safe(Options),
{Safe, ruf:decode_init(Safe)}.
encode(Contract, _Safe, Term) ->
VSN = case get(?MODULE) of undefined -> ?VSN_1; V -> V end,
ruf:encode(ruf_term:decode(Term, Contract, VSN), Contract, VSN).
decode(Contract, Safe, {init, Rest, VSN}, Binary) ->
put(?MODULE, VSN),
Cont = ruf:decode_init(Safe, Rest),
decode(Contract, Safe, Cont, Binary);
decode(Contract, Safe, Cont, Binary) ->
case ruf:decode(Binary, Contract, Cont) of
{done, Term, Rest1, VSN1} ->
Term1 = ruf_term:encode(Term, Contract, VSN1, Safe),
{done, Term1, Rest1, VSN1};
Else ->
Else
end.
Internal functions
safe(Options) ->
proplists:get_bool(safe, Options).
|
c20549797ac6e9ac3a50e6b491482b2b0c96b09cb4338082dd44f1ddefdf20e2 | wdhowe/telegrambot-lib | games.clj | (ns telegrambot-lib.api.games
"Telegram Bot API Games - function implementations.
- <#games>
Most functions are multi-arity with the following options:
- Send all parameters in a 'content' map.
- Send only the required parameters as simple values.
- Send the required paraemters as simple values and then 'optional' parameters in a map."
(:gen-class)
(:require [telegrambot-lib.http :as http]))
(defn send-game
"Use this method to send a game.
On success, the sent Message is returned.
Required
- this ; a bot instance
- chat_id ; target chat id
- game_short_name ; serves as unique id for the game
Optional
- message_thread_id ; id of the target thread of the forum.
- disable_notification ; send message silently
- protect_content ; protect content from forwarding/saving
- reply_to_message_id ; id of original message
- allow_sending_without_reply ; true to send message even if replied-to message is not found
- reply_markup ; inline keyboard markup"
([this content]
(http/request this "sendGame" content))
([this chat_id game_short_name]
(let [content {:chat_id chat_id
:game_short_name game_short_name}]
(send-game this content)))
([this chat_id game_short_name & optional]
(let [content (merge (first optional)
{:chat_id chat_id
:game_short_name game_short_name})]
(send-game this content))))
(defn set-game-score
"Use this method to set the score of the specified user in a game.
On success, if the message was sent by the bot, returns the edited Message,
otherwise returns True. Returns an error, if the new score is not greater
than the user's current score in the chat and force is False.
Required
- this ; a bot instance
- chat_id ; id of target chat
- message_id ; id of the sent message
- user_id ; user identifier
- score ; new score, non-negative
Optional
- force ; true if high score is allowed to decrease
- disable_edit_message ; true if game msg should not be auto edited to include the scoreboard"
([this content]
(http/request this "setGameScore" content))
([this chat_id message_id user_id score]
(let [content {:chat_id chat_id
:message_id message_id
:user_id user_id
:score score}]
(set-game-score this content)))
([this chat_id message_id user_id score & optional]
(let [content (merge (first optional)
{:chat_id chat_id
:message_id message_id
:user_id user_id
:score score})]
(set-game-score this content))))
(defn set-game-score-inline
"Use this method to set the inline score of the specified user in a game.
On success, if the message was sent by the bot, returns the edited Message,
otherwise returns True. Returns an error, if the new score is not greater
than the user's current score in the chat and force is False.
Required
- this ; a bot instance
- inline_message_id ; id of the inline message
- user_id ; user identifier
- score ; new score, non-negative
Optional
- force ; true if high score is allowed to decrease
- disable_edit_message ; true if game msg should not be auto edited to include the scoreboard"
([this content]
(http/request this "setGameScore" content))
([this inline_message_id user_id score]
(let [content {:inline_message_id inline_message_id
:user_id user_id
:score score}]
(set-game-score-inline this content)))
([this inline_message_id user_id score & optional]
(let [content (merge (first optional)
{:inline_message_id inline_message_id
:user_id user_id
:score score})]
(set-game-score-inline this content))))
(defn get-game-high-scores
"Use this method to get data for high score tables.
Will return the score of the specified user and several of their neighbors in a game.
On success, returns an Array of GameHighScore objects.
Required
- this ; a bot instance
- chat_id ; id of the target chat
- message_id ; id of the sent message
- user_id ; target user"
([this content]
(http/request this "getGameHighScores" content))
([this chat_id message_id user_id]
(let [content {:chat_id chat_id
:message_id message_id
:user_id user_id}]
(get-game-high-scores this content))))
(defn get-game-high-scores-inline
"Use this method to get data for inline high score tables.
Will return the score of the specified user and several of their neighbors in a game.
On success, returns an Array of GameHighScore objects.
Required
- this ; a bot instance
- inline_message_id ; id of the sent message
- user_id ; target user"
([this content]
(http/request this "getGameHighScores" content))
([this inline_message_id user_id]
(let [content {:inline_message_id inline_message_id
:user_id user_id}]
(get-game-high-scores-inline this content))))
| null | https://raw.githubusercontent.com/wdhowe/telegrambot-lib/590ed016f0dca394559f29ade8bb7ddddaeffa1a/src/telegrambot_lib/api/games.clj | clojure | a bot instance
target chat id
serves as unique id for the game
id of the target thread of the forum.
send message silently
protect content from forwarding/saving
id of original message
true to send message even if replied-to message is not found
inline keyboard markup"
a bot instance
id of target chat
id of the sent message
user identifier
new score, non-negative
true if high score is allowed to decrease
true if game msg should not be auto edited to include the scoreboard"
a bot instance
id of the inline message
user identifier
new score, non-negative
true if high score is allowed to decrease
true if game msg should not be auto edited to include the scoreboard"
a bot instance
id of the target chat
id of the sent message
target user"
a bot instance
id of the sent message
target user" | (ns telegrambot-lib.api.games
"Telegram Bot API Games - function implementations.
- <#games>
Most functions are multi-arity with the following options:
- Send all parameters in a 'content' map.
- Send only the required parameters as simple values.
- Send the required paraemters as simple values and then 'optional' parameters in a map."
(:gen-class)
(:require [telegrambot-lib.http :as http]))
(defn send-game
"Use this method to send a game.
On success, the sent Message is returned.
Required
Optional
([this content]
(http/request this "sendGame" content))
([this chat_id game_short_name]
(let [content {:chat_id chat_id
:game_short_name game_short_name}]
(send-game this content)))
([this chat_id game_short_name & optional]
(let [content (merge (first optional)
{:chat_id chat_id
:game_short_name game_short_name})]
(send-game this content))))
(defn set-game-score
"Use this method to set the score of the specified user in a game.
On success, if the message was sent by the bot, returns the edited Message,
otherwise returns True. Returns an error, if the new score is not greater
than the user's current score in the chat and force is False.
Required
Optional
([this content]
(http/request this "setGameScore" content))
([this chat_id message_id user_id score]
(let [content {:chat_id chat_id
:message_id message_id
:user_id user_id
:score score}]
(set-game-score this content)))
([this chat_id message_id user_id score & optional]
(let [content (merge (first optional)
{:chat_id chat_id
:message_id message_id
:user_id user_id
:score score})]
(set-game-score this content))))
(defn set-game-score-inline
"Use this method to set the inline score of the specified user in a game.
On success, if the message was sent by the bot, returns the edited Message,
otherwise returns True. Returns an error, if the new score is not greater
than the user's current score in the chat and force is False.
Required
Optional
([this content]
(http/request this "setGameScore" content))
([this inline_message_id user_id score]
(let [content {:inline_message_id inline_message_id
:user_id user_id
:score score}]
(set-game-score-inline this content)))
([this inline_message_id user_id score & optional]
(let [content (merge (first optional)
{:inline_message_id inline_message_id
:user_id user_id
:score score})]
(set-game-score-inline this content))))
(defn get-game-high-scores
"Use this method to get data for high score tables.
Will return the score of the specified user and several of their neighbors in a game.
On success, returns an Array of GameHighScore objects.
Required
([this content]
(http/request this "getGameHighScores" content))
([this chat_id message_id user_id]
(let [content {:chat_id chat_id
:message_id message_id
:user_id user_id}]
(get-game-high-scores this content))))
(defn get-game-high-scores-inline
"Use this method to get data for inline high score tables.
Will return the score of the specified user and several of their neighbors in a game.
On success, returns an Array of GameHighScore objects.
Required
([this content]
(http/request this "getGameHighScores" content))
([this inline_message_id user_id]
(let [content {:inline_message_id inline_message_id
:user_id user_id}]
(get-game-high-scores-inline this content))))
|
d317a46f3ba0aa26e68334bb56f9e22ce7f70c0369da7899ccd108e39b9b3972 | lpeterse/koka | Newtypes.hs | ------------------------------------------------------------------------------
Copyright 2012 Microsoft Corporation .
--
-- This is free software; you can redistribute it and/or modify it under the
terms of the Apache License , Version 2.0 . A copy of the License can be
found in the file " license.txt " at the root of this distribution .
-----------------------------------------------------------------------------
{-
Map type names to type definition schemes.
-}
-----------------------------------------------------------------------------
module Kind.Newtypes( -- * Type newtypes
Newtypes, DataInfo(..)
, newtypesEmpty, newtypesExtend, newtypesLookup, newtypesFind
, newtypesNew, newtypesCompose
, newtypesIsEmpty
, newtypesTypeDefs
, extractNewtypes
-- * Pretty
-- , ppNewtypes
) where
import qualified Common.NameMap as M
import Common.Failure( failure )
import Common.Name
import Common.Syntax ( Visibility(..))
import Type.Type
import Type.Pretty
import Lib.PPrint
import qualified Data.List as L
import qualified Core.Core as Core
-------------------------------------------------------------------------
Newtype map
-------------------------------------------------------------------------
Newtype map
--------------------------------------------------------------------------}
-- | Newtypes: a map from newtype names to newtype information
newtype Newtypes = Newtypes (M.NameMap DataInfo)
newtypesEmpty :: Newtypes
newtypesEmpty
= Newtypes M.empty
newtypesIsEmpty :: Newtypes -> Bool
newtypesIsEmpty (Newtypes m)
= M.null m
newtypesNew :: [DataInfo] -> Newtypes
newtypesNew infos
= Newtypes (M.fromList [(dataInfoName info, info) | info <- infos])
newtypesCompose :: Newtypes -> Newtypes -> Newtypes
newtypesCompose (Newtypes m1) (Newtypes m2)
= Newtypes (M.union m2 m1) -- ASSUME: left-biased union
newtypesTypeDefs :: Newtypes -> M.NameMap DataInfo
newtypesTypeDefs (Newtypes m)
= m
newtypesExtend :: Name -> DataInfo -> Newtypes -> Newtypes
newtypesExtend name info (Newtypes m)
= Newtypes (M.insert name info m)
newtypesLookup :: Name -> Newtypes -> Maybe DataInfo
newtypesLookup name (Newtypes m)
= M.lookup name m
newtypesFind :: Name -> Newtypes -> DataInfo
newtypesFind name syn
= case newtypesLookup name syn of
Nothing -> failure ("Kind.Newtypes.newtypesFind: unknown newtype: " ++ show name)
Just x -> x
-- | Extract data infos from core
extractNewtypes :: Core.Core -> Newtypes
extractNewtypes core
= newtypesNew (concatMap extractTypeDefGroup (Core.coreProgTypeDefs core))
extractTypeDefGroup (Core.TypeDefGroup tdefs)
= concatMap extractTypeDef tdefs
extractTypeDef :: Core.TypeDef -> [DataInfo]
extractTypeDef tdef
= case tdef of
Core.Data dataInfo Public conViss
-> [dataInfo]
_ -> []
-------------------------------------------------------------------------
Pretty printing
TODO : redo
-------------------------------------------------------------------------
Pretty printing
TODO: redo
--------------------------------------------------------------------------}
instance Show Newtypes where
show = show . pretty
instance Pretty Newtypes where
pretty syns
= ppNewtypes Type.Pretty.defaultEnv syns
ppNewtypes showOptions (Newtypes m)
= vcat [fill 8 (pretty name) <> colon <+>
-- text "rank" <+> pretty rank <> colon <+>
ppDataInfo defaultEnv True dataInfo
| (name,dataInfo) <- L.sortBy (\(n1,_) (n2,_) -> compare (show n1) (show n2)) $ M.toList m]
| null | https://raw.githubusercontent.com/lpeterse/koka/43feefed258b9a533f07967d3f8867b02384df0e/src/Kind/Newtypes.hs | haskell | ----------------------------------------------------------------------------
This is free software; you can redistribute it and/or modify it under the
---------------------------------------------------------------------------
Map type names to type definition schemes.
---------------------------------------------------------------------------
* Type newtypes
* Pretty
, ppNewtypes
-----------------------------------------------------------------------
-----------------------------------------------------------------------
------------------------------------------------------------------------}
| Newtypes: a map from newtype names to newtype information
ASSUME: left-biased union
| Extract data infos from core
-----------------------------------------------------------------------
-----------------------------------------------------------------------
------------------------------------------------------------------------}
text "rank" <+> pretty rank <> colon <+> | Copyright 2012 Microsoft Corporation .
terms of the Apache License , Version 2.0 . A copy of the License can be
found in the file " license.txt " at the root of this distribution .
Newtypes, DataInfo(..)
, newtypesEmpty, newtypesExtend, newtypesLookup, newtypesFind
, newtypesNew, newtypesCompose
, newtypesIsEmpty
, newtypesTypeDefs
, extractNewtypes
) where
import qualified Common.NameMap as M
import Common.Failure( failure )
import Common.Name
import Common.Syntax ( Visibility(..))
import Type.Type
import Type.Pretty
import Lib.PPrint
import qualified Data.List as L
import qualified Core.Core as Core
Newtype map
Newtype map
newtype Newtypes = Newtypes (M.NameMap DataInfo)
newtypesEmpty :: Newtypes
newtypesEmpty
= Newtypes M.empty
newtypesIsEmpty :: Newtypes -> Bool
newtypesIsEmpty (Newtypes m)
= M.null m
newtypesNew :: [DataInfo] -> Newtypes
newtypesNew infos
= Newtypes (M.fromList [(dataInfoName info, info) | info <- infos])
newtypesCompose :: Newtypes -> Newtypes -> Newtypes
newtypesCompose (Newtypes m1) (Newtypes m2)
newtypesTypeDefs :: Newtypes -> M.NameMap DataInfo
newtypesTypeDefs (Newtypes m)
= m
newtypesExtend :: Name -> DataInfo -> Newtypes -> Newtypes
newtypesExtend name info (Newtypes m)
= Newtypes (M.insert name info m)
newtypesLookup :: Name -> Newtypes -> Maybe DataInfo
newtypesLookup name (Newtypes m)
= M.lookup name m
newtypesFind :: Name -> Newtypes -> DataInfo
newtypesFind name syn
= case newtypesLookup name syn of
Nothing -> failure ("Kind.Newtypes.newtypesFind: unknown newtype: " ++ show name)
Just x -> x
extractNewtypes :: Core.Core -> Newtypes
extractNewtypes core
= newtypesNew (concatMap extractTypeDefGroup (Core.coreProgTypeDefs core))
extractTypeDefGroup (Core.TypeDefGroup tdefs)
= concatMap extractTypeDef tdefs
extractTypeDef :: Core.TypeDef -> [DataInfo]
extractTypeDef tdef
= case tdef of
Core.Data dataInfo Public conViss
-> [dataInfo]
_ -> []
Pretty printing
TODO : redo
Pretty printing
TODO: redo
instance Show Newtypes where
show = show . pretty
instance Pretty Newtypes where
pretty syns
= ppNewtypes Type.Pretty.defaultEnv syns
ppNewtypes showOptions (Newtypes m)
= vcat [fill 8 (pretty name) <> colon <+>
ppDataInfo defaultEnv True dataInfo
| (name,dataInfo) <- L.sortBy (\(n1,_) (n2,_) -> compare (show n1) (show n2)) $ M.toList m]
|
eb08000e04a1477f271cfd42fb34a324f5d64c213729c63a5434f44e1a97f802 | quil/quil | calculation.cljc | (ns quil.snippets.math.calculation
(:require #?(:clj [quil.snippets.macro :refer [defsnippet]])
[quil.core :as q :include-macros true]
quil.snippets.all-snippets-internal)
#?(:cljs
(:use-macros [quil.snippets.macro :only [defsnippet]])))
(defsnippet abs
"abs"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/abs -1) = " (q/abs -1)) 10 20)
(q/text (str "(q/abs -0.5) = " (q/abs -0.5)) 10 40))
(defsnippet ceil
"ceil"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/ceil 9.03) = " (q/ceil 9.03)) 10 20))
(defsnippet constrain
"constrain"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/constrain 4 10 20) = " (q/constrain 4 10 20)) 10 20)
(q/text (str "(q/constrain 4.5 1.5 3.9) = " (q/constrain 4.5 1.5 3.9)) 10 40))
(defsnippet dist
"dist"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/dist 0 0 3 4) = " (q/dist 0 0 3 4)) 10 20)
(q/text (str "(q/dist 0 0 0 5 5 5) = " (q/dist 0 0 0 5 5 5)) 10 40))
(defsnippet exp
"exp"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/exp 2) = " (q/exp 2)) 10 20))
(defsnippet floor
"floor"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/floor 9.03) = " (q/floor 9.03)) 10 20))
(defsnippet lerp
"lerp"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/lerp 2 5 0.5) = " (q/lerp 2 5 0.5)) 10 20))
(defsnippet log
"log"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/log Math/E) = " (q/log Math/E)) 10 20))
(defsnippet mag
"mag"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/mag 3 4) = " (q/mag 3 4)) 10 20)
#?(:clj (q/text (str "(q/mag 3 4 5) = " (q/mag 3 4 5)) 10 40)))
(defsnippet map-range
"map-range"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/map-range 2 0 5 10 20) = " (q/map-range 2 0 5 10 20)) 10 20))
(defsnippet norm
"norm"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/norm 20 0 50) = " (q/norm 20 0 50)) 10 20))
(defsnippet pow
"pow"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/pow 2 10) = " (q/pow 2 10)) 10 20))
(defsnippet round
"round"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/round 9.2) = " (q/round 9.2)) 10 20))
(defsnippet sq
"sq"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/sq 5) = " (q/sq 5)) 10 20))
(defsnippet sqrt
"sqrt"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/sqrt 25) = " (q/sqrt 25)) 10 20))
| null | https://raw.githubusercontent.com/quil/quil/1f214e712d834ede311fdc652eafe9cc0232c96e/src/cljc/quil/snippets/math/calculation.cljc | clojure | (ns quil.snippets.math.calculation
(:require #?(:clj [quil.snippets.macro :refer [defsnippet]])
[quil.core :as q :include-macros true]
quil.snippets.all-snippets-internal)
#?(:cljs
(:use-macros [quil.snippets.macro :only [defsnippet]])))
(defsnippet abs
"abs"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/abs -1) = " (q/abs -1)) 10 20)
(q/text (str "(q/abs -0.5) = " (q/abs -0.5)) 10 40))
(defsnippet ceil
"ceil"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/ceil 9.03) = " (q/ceil 9.03)) 10 20))
(defsnippet constrain
"constrain"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/constrain 4 10 20) = " (q/constrain 4 10 20)) 10 20)
(q/text (str "(q/constrain 4.5 1.5 3.9) = " (q/constrain 4.5 1.5 3.9)) 10 40))
(defsnippet dist
"dist"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/dist 0 0 3 4) = " (q/dist 0 0 3 4)) 10 20)
(q/text (str "(q/dist 0 0 0 5 5 5) = " (q/dist 0 0 0 5 5 5)) 10 40))
(defsnippet exp
"exp"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/exp 2) = " (q/exp 2)) 10 20))
(defsnippet floor
"floor"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/floor 9.03) = " (q/floor 9.03)) 10 20))
(defsnippet lerp
"lerp"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/lerp 2 5 0.5) = " (q/lerp 2 5 0.5)) 10 20))
(defsnippet log
"log"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/log Math/E) = " (q/log Math/E)) 10 20))
(defsnippet mag
"mag"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/mag 3 4) = " (q/mag 3 4)) 10 20)
#?(:clj (q/text (str "(q/mag 3 4 5) = " (q/mag 3 4 5)) 10 40)))
(defsnippet map-range
"map-range"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/map-range 2 0 5 10 20) = " (q/map-range 2 0 5 10 20)) 10 20))
(defsnippet norm
"norm"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/norm 20 0 50) = " (q/norm 20 0 50)) 10 20))
(defsnippet pow
"pow"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/pow 2 10) = " (q/pow 2 10)) 10 20))
(defsnippet round
"round"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/round 9.2) = " (q/round 9.2)) 10 20))
(defsnippet sq
"sq"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/sq 5) = " (q/sq 5)) 10 20))
(defsnippet sqrt
"sqrt"
{}
(q/background 255)
(q/fill 0)
(q/text (str "(q/sqrt 25) = " (q/sqrt 25)) 10 20))
| |
7e8462846bcc692c4aafd31168afafaf536c09ad7784edfe72ef6e1bef064210 | tonyg/kali-scheme | type.scm | Copyright ( c ) 1994 . See file COPYING .
(define-record-type base-type
(name
uid ; an integer
)
())
(define-record-discloser type/base-type
(lambda (base-type)
(list (base-type-name base-type)
(base-type-uid base-type))))
(define *next-base-type-uid* 0)
(define (next-base-type-uid)
(let ((x *next-base-type-uid*))
(set! *next-base-type-uid* (+ x 1))
x))
(define base-type-table (make-table))
(define (make-base-type name)
(let ((type (base-type-maker name (next-base-type-uid))))
(table-set! base-type-table name type)
type))
(define (lookup-type id)
(cond ((table-ref base-type-table id)
=> identity)
(else #f)))
(define type/integer (make-base-type 'integer))
(define type/float (make-base-type 'float))
(define type/null (make-base-type 'null)) ; no value
(define type/unit (make-base-type 'unit)) ; single value
(define type/boolean (make-base-type 'boolean))
(define type/undetermined (make-base-type '?))
(define type/input-port (make-base-type 'input-port))
(define type/output-port (make-base-type 'output-port))
(define type/address (make-base-type 'address))
(define type/char (make-base-type 'char))
(define (make-atomic-type name)
(base-type-maker name (next-base-type-uid)))
(define type/unknown type/undetermined) ; an alias
(define (type-name type)
(if (base-type? type)
(base-type-name type)
(error "type has no name ~S" type)))
(define (make-base-type-table)
(let ((elts (make-vector *next-base-type-uid* #f)))
(values (lambda (type)
(vector-ref elts (base-type-uid type)))
(lambda (type value)
(vector-set! elts (base-type-uid type) value)))))
;--------------------------------------------------
; This won't terminate on recursive types.
(define (type-eq? type1 type2)
(let ((type1 (maybe-follow-uvar type1))
(type2 (maybe-follow-uvar type2)))
(or (eq? type1 type2)
(and (other-type? type1)
(other-type? type2)
(eq? (other-type-kind type1)
(other-type-kind type2))
(let loop ((l1 (other-type-subtypes type1))
(l2 (other-type-subtypes type2)))
(cond ((null? l1) (null? l2))
((null? l2) #f)
((type-eq? (car l1) (car l2))
(loop (cdr l1) (cdr l2)))
(else #f)))))))
;--------------------------------------------------
Arrow and pointer types ( and perhaps others later )
; All done together to simplify the type walking
(define-record-type other-type
(
kind
(subtypes) ; set when finalized
)
(
(finalized? #f)
))
(define make-other-type other-type-maker)
(define-record-discloser type/other-type
(lambda (type)
(case (other-type-kind type)
((arrow)
(list 'arrow-type
(arrow-type-args type)
(arrow-type-result type)))
(else
(cons (other-type-kind type)
(other-type-subtypes type))))))
(define (make-other-type-predicate kind)
(lambda (x)
(and (other-type? x)
(eq? kind (other-type-kind x)))))
Arrow
(define (make-arrow-type args result)
(other-type-maker 'arrow (cons result args)))
(define arrow-type? (make-other-type-predicate 'arrow))
(define (arrow-type-args type)
(cdr (other-type-subtypes type)))
(define (arrow-type-result type)
(car (other-type-subtypes type)))
; Pointer
(define (make-pointer-type type)
(other-type-maker 'pointer (list type)))
(define pointer-type? (make-other-type-predicate 'pointer))
(define (pointer-type-to pointer-type)
(car (other-type-subtypes pointer-type)))
(define type/string (make-pointer-type type/char))
; Tuple (used for arguments and returning multiple values)
(define (make-tuple-type types)
(if (and (not (null? types))
(null? (cdr types)))
(car types)
(other-type-maker 'tuple types)))
(define tuple-type? (make-other-type-predicate 'tuple))
(define (tuple-type-types type)
(other-type-subtypes type))
;--------------------------------------------------
(define (finalize-type type)
(let ((type (maybe-follow-uvar type)))
(cond ((and (other-type? type)
(not (other-type-finalized? type)))
(let ((subs (other-type-subtypes type)))
(set-other-type-finalized?! type #t)
(set-other-type-subtypes! type (map finalize-type subs))))
((and (uvar? type)
(uvar-tuple-okay? type)) ; unused return value
(bind-uvar! type type/unit)))
type))
;--------------------------------------------------
(define (expand-type-spec spec)
(cond ((pair? spec)
(case (car spec)
((=>)
(make-arrow-type (map expand-type-spec (cadr spec))
(make-tuple-type (map expand-type-spec
(cddr spec)))))
((^)
(make-pointer-type (expand-type-spec (cadr spec))))
((tuple)
(make-tuple-type (map expand-type-spec (cdr spec))))
(else
(error "unknown type syntax ~S" spec))))
((not (symbol? spec))
(error "unknown type syntax ~S" spec))
((lookup-type spec)
=> identity)
((lookup-record-type spec)
=> make-pointer-type)
(else
(error "unknown type name ~S" spec))))
;--------------------------------------------------
(define (display-type type port)
(define (do-list list)
(write-char #\( port)
(cond ((not (null? list))
(do-type (car list))
(for-each (lambda (type)
(write-char #\space port)
(do-type type))
(cdr list))))
(write-char #\) port))
(define (do-type type)
(let ((type (maybe-follow-uvar type)))
(cond ((base-type? type)
(display (base-type-name type) port))
((record-type? type)
(display (record-type-name type) port))
((arrow-type? type)
(write-char #\( port)
(do-list (arrow-type-args type))
(display " -> " port)
(do-type (arrow-type-result type))
(write-char #\) port))
((pointer-type? type)
(write-char #\* port)
(do-type (pointer-type-to type)))
((uvar? type)
(write-char #\T port)
(display (uvar-id type) port))
((type-scheme? type)
(display "(for-all " port)
(do-list (type-scheme-free-uvars type))
(display " " port)
(do-type (type-scheme-type type))
(display ")" port))
((tuple-type? type)
(display "(tuple " port)
(do-list (tuple-type-types type))
(display ")" port))
(else
(bug "don't know how to display type ~S" type)))))
(do-type type)) | null | https://raw.githubusercontent.com/tonyg/kali-scheme/79bf76b4964729b63fce99c4d2149b32cb067ac0/ps-compiler/prescheme/type.scm | scheme | an integer
no value
single value
an alias
--------------------------------------------------
This won't terminate on recursive types.
--------------------------------------------------
All done together to simplify the type walking
set when finalized
Pointer
Tuple (used for arguments and returning multiple values)
--------------------------------------------------
unused return value
--------------------------------------------------
-------------------------------------------------- | Copyright ( c ) 1994 . See file COPYING .
(define-record-type base-type
(name
)
())
(define-record-discloser type/base-type
(lambda (base-type)
(list (base-type-name base-type)
(base-type-uid base-type))))
(define *next-base-type-uid* 0)
(define (next-base-type-uid)
(let ((x *next-base-type-uid*))
(set! *next-base-type-uid* (+ x 1))
x))
(define base-type-table (make-table))
(define (make-base-type name)
(let ((type (base-type-maker name (next-base-type-uid))))
(table-set! base-type-table name type)
type))
(define (lookup-type id)
(cond ((table-ref base-type-table id)
=> identity)
(else #f)))
(define type/integer (make-base-type 'integer))
(define type/float (make-base-type 'float))
(define type/boolean (make-base-type 'boolean))
(define type/undetermined (make-base-type '?))
(define type/input-port (make-base-type 'input-port))
(define type/output-port (make-base-type 'output-port))
(define type/address (make-base-type 'address))
(define type/char (make-base-type 'char))
(define (make-atomic-type name)
(base-type-maker name (next-base-type-uid)))
(define (type-name type)
(if (base-type? type)
(base-type-name type)
(error "type has no name ~S" type)))
(define (make-base-type-table)
(let ((elts (make-vector *next-base-type-uid* #f)))
(values (lambda (type)
(vector-ref elts (base-type-uid type)))
(lambda (type value)
(vector-set! elts (base-type-uid type) value)))))
(define (type-eq? type1 type2)
(let ((type1 (maybe-follow-uvar type1))
(type2 (maybe-follow-uvar type2)))
(or (eq? type1 type2)
(and (other-type? type1)
(other-type? type2)
(eq? (other-type-kind type1)
(other-type-kind type2))
(let loop ((l1 (other-type-subtypes type1))
(l2 (other-type-subtypes type2)))
(cond ((null? l1) (null? l2))
((null? l2) #f)
((type-eq? (car l1) (car l2))
(loop (cdr l1) (cdr l2)))
(else #f)))))))
Arrow and pointer types ( and perhaps others later )
(define-record-type other-type
(
kind
)
(
(finalized? #f)
))
(define make-other-type other-type-maker)
(define-record-discloser type/other-type
(lambda (type)
(case (other-type-kind type)
((arrow)
(list 'arrow-type
(arrow-type-args type)
(arrow-type-result type)))
(else
(cons (other-type-kind type)
(other-type-subtypes type))))))
(define (make-other-type-predicate kind)
(lambda (x)
(and (other-type? x)
(eq? kind (other-type-kind x)))))
Arrow
(define (make-arrow-type args result)
(other-type-maker 'arrow (cons result args)))
(define arrow-type? (make-other-type-predicate 'arrow))
(define (arrow-type-args type)
(cdr (other-type-subtypes type)))
(define (arrow-type-result type)
(car (other-type-subtypes type)))
(define (make-pointer-type type)
(other-type-maker 'pointer (list type)))
(define pointer-type? (make-other-type-predicate 'pointer))
(define (pointer-type-to pointer-type)
(car (other-type-subtypes pointer-type)))
(define type/string (make-pointer-type type/char))
(define (make-tuple-type types)
(if (and (not (null? types))
(null? (cdr types)))
(car types)
(other-type-maker 'tuple types)))
(define tuple-type? (make-other-type-predicate 'tuple))
(define (tuple-type-types type)
(other-type-subtypes type))
(define (finalize-type type)
(let ((type (maybe-follow-uvar type)))
(cond ((and (other-type? type)
(not (other-type-finalized? type)))
(let ((subs (other-type-subtypes type)))
(set-other-type-finalized?! type #t)
(set-other-type-subtypes! type (map finalize-type subs))))
((and (uvar? type)
(bind-uvar! type type/unit)))
type))
(define (expand-type-spec spec)
(cond ((pair? spec)
(case (car spec)
((=>)
(make-arrow-type (map expand-type-spec (cadr spec))
(make-tuple-type (map expand-type-spec
(cddr spec)))))
((^)
(make-pointer-type (expand-type-spec (cadr spec))))
((tuple)
(make-tuple-type (map expand-type-spec (cdr spec))))
(else
(error "unknown type syntax ~S" spec))))
((not (symbol? spec))
(error "unknown type syntax ~S" spec))
((lookup-type spec)
=> identity)
((lookup-record-type spec)
=> make-pointer-type)
(else
(error "unknown type name ~S" spec))))
(define (display-type type port)
(define (do-list list)
(write-char #\( port)
(cond ((not (null? list))
(do-type (car list))
(for-each (lambda (type)
(write-char #\space port)
(do-type type))
(cdr list))))
(write-char #\) port))
(define (do-type type)
(let ((type (maybe-follow-uvar type)))
(cond ((base-type? type)
(display (base-type-name type) port))
((record-type? type)
(display (record-type-name type) port))
((arrow-type? type)
(write-char #\( port)
(do-list (arrow-type-args type))
(display " -> " port)
(do-type (arrow-type-result type))
(write-char #\) port))
((pointer-type? type)
(write-char #\* port)
(do-type (pointer-type-to type)))
((uvar? type)
(write-char #\T port)
(display (uvar-id type) port))
((type-scheme? type)
(display "(for-all " port)
(do-list (type-scheme-free-uvars type))
(display " " port)
(do-type (type-scheme-type type))
(display ")" port))
((tuple-type? type)
(display "(tuple " port)
(do-list (tuple-type-types type))
(display ")" port))
(else
(bug "don't know how to display type ~S" type)))))
(do-type type)) |
dea09d352762167c881e4fa4f5e80a901a8c669de9a6392f8453a9987916344e | aws-beam/aws-erlang | aws_mobile_analytics.erl | %% WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
See -beam/aws-codegen for more details .
@doc Amazon Mobile Analytics is a service for collecting , visualizing , and
%% understanding app usage data at scale.
-module(aws_mobile_analytics).
-export([put_events/2,
put_events/3]).
-include_lib("hackney/include/hackney_lib.hrl").
%%====================================================================
%% API
%%====================================================================
@doc The PutEvents operation records one or more events .
%%
You can have up to 1,500 unique custom events per app , any combination of
up to 40 attributes and metrics per custom event , and any number of
%% attribute or metric values.
put_events(Client, Input) ->
put_events(Client, Input, []).
put_events(Client, Input0, Options0) ->
Method = post,
Path = ["/2014-06-05/events"],
SuccessStatusCode = 202,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
HeadersMapping = [
{<<"x-amz-Client-Context">>, <<"clientContext">>},
{<<"x-amz-Client-Context-Encoding">>, <<"clientContextEncoding">>}
],
{Headers, Input1} = aws_request:build_headers(HeadersMapping, Input0),
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
%%====================================================================
Internal functions
%%====================================================================
-spec request(aws_client:aws_client(), atom(), iolist(), list(),
list(), map() | undefined, list(), pos_integer() | undefined) ->
{ok, {integer(), list()}} |
{ok, Result, {integer(), list(), hackney:client()}} |
{error, Error, {integer(), list(), hackney:client()}} |
{error, term()} when
Result :: map(),
Error :: map().
request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) ->
RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end,
aws_request:request(RequestFun, Options).
do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) ->
Client1 = Client#{service => <<"mobileanalytics">>},
Host = build_host(<<"mobileanalytics">>, Client1),
URL0 = build_url(Host, Path, Client1),
URL = aws_request:add_query(URL0, Query),
AdditionalHeaders1 = [ {<<"Host">>, Host}
, {<<"Content-Type">>, <<"application/x-amz-json-1.1">>}
],
Payload =
case proplists:get_value(send_body_as_binary, Options) of
true ->
maps:get(<<"Body">>, Input, <<"">>);
false ->
encode_payload(Input)
end,
AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of
true ->
add_checksum_hash_header(AdditionalHeaders1, Payload);
false ->
AdditionalHeaders1
end,
Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0),
MethodBin = aws_request:method_to_binary(Method),
SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload),
Response = hackney:request(Method, URL, SignedHeaders, Payload, Options),
DecodeBody = not proplists:get_value(receive_body_as_binary, Options),
handle_response(Response, SuccessStatusCode, DecodeBody).
add_checksum_hash_header(Headers, Body) ->
[ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))}
| Headers
].
handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody)
when StatusCode =:= 200;
StatusCode =:= 202;
StatusCode =:= 204;
StatusCode =:= 206;
StatusCode =:= SuccessStatusCode ->
{ok, {StatusCode, ResponseHeaders}};
handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) ->
{error, {StatusCode, ResponseHeaders}};
handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody)
when StatusCode =:= 200;
StatusCode =:= 202;
StatusCode =:= 204;
StatusCode =:= 206;
StatusCode =:= SuccessStatusCode ->
case hackney:body(Client) of
{ok, <<>>} when StatusCode =:= 200;
StatusCode =:= SuccessStatusCode ->
{ok, #{}, {StatusCode, ResponseHeaders, Client}};
{ok, Body} ->
Result = case DecodeBody of
true ->
try
jsx:decode(Body)
catch
Error:Reason:Stack ->
erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack)
end;
false -> #{<<"Body">> => Body}
end,
{ok, Result, {StatusCode, ResponseHeaders, Client}}
end;
handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody)
when StatusCode =:= 503 ->
Retriable error if retries are enabled
{error, service_unavailable};
handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) ->
{ok, Body} = hackney:body(Client),
try
DecodedError = jsx:decode(Body),
{error, DecodedError, {StatusCode, ResponseHeaders, Client}}
catch
Error:Reason:Stack ->
erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack)
end;
handle_response({error, Reason}, _, _DecodeBody) ->
{error, Reason}.
build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) ->
Endpoint;
build_host(_EndpointPrefix, #{region := <<"local">>}) ->
<<"localhost">>;
build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) ->
aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>).
build_url(Host, Path0, Client) ->
Proto = aws_client:proto(Client),
Path = erlang:iolist_to_binary(Path0),
Port = aws_client:port(Client),
aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>).
-spec encode_payload(undefined | map()) -> binary().
encode_payload(undefined) ->
<<>>;
encode_payload(Input) ->
jsx:encode(Input).
| null | https://raw.githubusercontent.com/aws-beam/aws-erlang/699287cee7dfc9dc8c08ced5f090dcc192c9cba8/src/aws_mobile_analytics.erl | erlang | WARNING: DO NOT EDIT, AUTO-GENERATED CODE!
understanding app usage data at scale.
====================================================================
API
====================================================================
attribute or metric values.
====================================================================
==================================================================== | See -beam/aws-codegen for more details .
@doc Amazon Mobile Analytics is a service for collecting , visualizing , and
-module(aws_mobile_analytics).
-export([put_events/2,
put_events/3]).
-include_lib("hackney/include/hackney_lib.hrl").
@doc The PutEvents operation records one or more events .
You can have up to 1,500 unique custom events per app , any combination of
up to 40 attributes and metrics per custom event , and any number of
put_events(Client, Input) ->
put_events(Client, Input, []).
put_events(Client, Input0, Options0) ->
Method = post,
Path = ["/2014-06-05/events"],
SuccessStatusCode = 202,
Options = [{send_body_as_binary, false},
{receive_body_as_binary, false},
{append_sha256_content_hash, false}
| Options0],
HeadersMapping = [
{<<"x-amz-Client-Context">>, <<"clientContext">>},
{<<"x-amz-Client-Context-Encoding">>, <<"clientContextEncoding">>}
],
{Headers, Input1} = aws_request:build_headers(HeadersMapping, Input0),
CustomHeaders = [],
Input2 = Input1,
Query_ = [],
Input = Input2,
request(Client, Method, Path, Query_, CustomHeaders ++ Headers, Input, Options, SuccessStatusCode).
Internal functions
-spec request(aws_client:aws_client(), atom(), iolist(), list(),
list(), map() | undefined, list(), pos_integer() | undefined) ->
{ok, {integer(), list()}} |
{ok, Result, {integer(), list(), hackney:client()}} |
{error, Error, {integer(), list(), hackney:client()}} |
{error, term()} when
Result :: map(),
Error :: map().
request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) ->
RequestFun = fun() -> do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) end,
aws_request:request(RequestFun, Options).
do_request(Client, Method, Path, Query, Headers0, Input, Options, SuccessStatusCode) ->
Client1 = Client#{service => <<"mobileanalytics">>},
Host = build_host(<<"mobileanalytics">>, Client1),
URL0 = build_url(Host, Path, Client1),
URL = aws_request:add_query(URL0, Query),
AdditionalHeaders1 = [ {<<"Host">>, Host}
, {<<"Content-Type">>, <<"application/x-amz-json-1.1">>}
],
Payload =
case proplists:get_value(send_body_as_binary, Options) of
true ->
maps:get(<<"Body">>, Input, <<"">>);
false ->
encode_payload(Input)
end,
AdditionalHeaders = case proplists:get_value(append_sha256_content_hash, Options, false) of
true ->
add_checksum_hash_header(AdditionalHeaders1, Payload);
false ->
AdditionalHeaders1
end,
Headers1 = aws_request:add_headers(AdditionalHeaders, Headers0),
MethodBin = aws_request:method_to_binary(Method),
SignedHeaders = aws_request:sign_request(Client1, MethodBin, URL, Headers1, Payload),
Response = hackney:request(Method, URL, SignedHeaders, Payload, Options),
DecodeBody = not proplists:get_value(receive_body_as_binary, Options),
handle_response(Response, SuccessStatusCode, DecodeBody).
add_checksum_hash_header(Headers, Body) ->
[ {<<"X-Amz-CheckSum-SHA256">>, base64:encode(crypto:hash(sha256, Body))}
| Headers
].
handle_response({ok, StatusCode, ResponseHeaders}, SuccessStatusCode, _DecodeBody)
when StatusCode =:= 200;
StatusCode =:= 202;
StatusCode =:= 204;
StatusCode =:= 206;
StatusCode =:= SuccessStatusCode ->
{ok, {StatusCode, ResponseHeaders}};
handle_response({ok, StatusCode, ResponseHeaders}, _, _DecodeBody) ->
{error, {StatusCode, ResponseHeaders}};
handle_response({ok, StatusCode, ResponseHeaders, Client}, SuccessStatusCode, DecodeBody)
when StatusCode =:= 200;
StatusCode =:= 202;
StatusCode =:= 204;
StatusCode =:= 206;
StatusCode =:= SuccessStatusCode ->
case hackney:body(Client) of
{ok, <<>>} when StatusCode =:= 200;
StatusCode =:= SuccessStatusCode ->
{ok, #{}, {StatusCode, ResponseHeaders, Client}};
{ok, Body} ->
Result = case DecodeBody of
true ->
try
jsx:decode(Body)
catch
Error:Reason:Stack ->
erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack)
end;
false -> #{<<"Body">> => Body}
end,
{ok, Result, {StatusCode, ResponseHeaders, Client}}
end;
handle_response({ok, StatusCode, _ResponseHeaders, _Client}, _, _DecodeBody)
when StatusCode =:= 503 ->
Retriable error if retries are enabled
{error, service_unavailable};
handle_response({ok, StatusCode, ResponseHeaders, Client}, _, _DecodeBody) ->
{ok, Body} = hackney:body(Client),
try
DecodedError = jsx:decode(Body),
{error, DecodedError, {StatusCode, ResponseHeaders, Client}}
catch
Error:Reason:Stack ->
erlang:raise(error, {body_decode_failed, Error, Reason, StatusCode, Body}, Stack)
end;
handle_response({error, Reason}, _, _DecodeBody) ->
{error, Reason}.
build_host(_EndpointPrefix, #{region := <<"local">>, endpoint := Endpoint}) ->
Endpoint;
build_host(_EndpointPrefix, #{region := <<"local">>}) ->
<<"localhost">>;
build_host(EndpointPrefix, #{region := Region, endpoint := Endpoint}) ->
aws_util:binary_join([EndpointPrefix, Region, Endpoint], <<".">>).
build_url(Host, Path0, Client) ->
Proto = aws_client:proto(Client),
Path = erlang:iolist_to_binary(Path0),
Port = aws_client:port(Client),
aws_util:binary_join([Proto, <<"://">>, Host, <<":">>, Port, Path], <<"">>).
-spec encode_payload(undefined | map()) -> binary().
encode_payload(undefined) ->
<<>>;
encode_payload(Input) ->
jsx:encode(Input).
|
309acc0d1565e55d78a1bec26a9b7440afc46f1ca8698c5ba1e9b3f804758573 | haskell-servant/servant | StreamSpec.hs | {-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
{-# LANGUAGE GADTs #-}
# LANGUAGE MultiParamTypeClasses #
{-# LANGUAGE OverloadedStrings #-}
# LANGUAGE PolyKinds #
# LANGUAGE RecordWildCards #
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -freduction - depth=100 #
# OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_GHC -fno - warn - name - shadowing #
module Servant.StreamSpec (spec) where
import Control.Monad
(when)
import Control.Monad.Codensity
(Codensity (..))
import Control.Monad.IO.Class
(MonadIO (..))
import Control.Monad.Trans.Except
import qualified Data.ByteString as BS
import Data.Proxy
import qualified Data.TDigest as TD
import qualified Network.HTTP.Client as C
import Prelude ()
import Prelude.Compat
import Servant.API
((:<|>) ((:<|>)), (:>), JSON, NetstringFraming, StreamBody,
NewlineFraming, NoFraming, OctetStream, SourceIO, StreamGet,
)
import Servant.Client.Streaming
import Servant.Server
import Servant.Test.ComprehensiveAPI
import Servant.Types.SourceT
import System.Entropy
(getEntropy, getHardwareEntropy)
import System.IO.Unsafe
(unsafePerformIO)
import System.Mem
(performGC)
import Test.Hspec
import Servant.ClientTestUtils (Person(..))
import qualified Servant.ClientTestUtils as CT
#if MIN_VERSION_base(4,10,0)
import GHC.Stats
(gc, gcdetails_live_bytes, getRTSStats)
#else
import GHC.Stats
(currentBytesUsed, getGCStats)
#endif
-- This declaration simply checks that all instances are in place.
-- Note: this is streaming client
_ = client comprehensiveAPI
spec :: Spec
spec = describe "Servant.Client.Streaming" $ do
streamSpec
type StreamApi =
"streamGetNewline" :> StreamGet NewlineFraming JSON (SourceIO Person)
:<|> "streamGetNetstring" :> StreamGet NetstringFraming JSON (SourceIO Person)
:<|> "streamALot" :> StreamGet NoFraming OctetStream (SourceIO BS.ByteString)
:<|> "streamBody" :> StreamBody NoFraming OctetStream (SourceIO BS.ByteString) :> StreamGet NoFraming OctetStream (SourceIO BS.ByteString)
api :: Proxy StreamApi
api = Proxy
getGetNL, getGetNS :: ClientM (SourceIO Person)
getGetALot :: ClientM (SourceIO BS.ByteString)
getStreamBody :: SourceT IO BS.ByteString -> ClientM (SourceIO BS.ByteString)
getGetNL :<|> getGetNS :<|> getGetALot :<|> getStreamBody = client api
alice :: Person
alice = Person "Alice" 42
bob :: Person
bob = Person "Bob" 25
server :: Application
server = serve api
$ return (source [alice, bob, alice])
:<|> return (source [alice, bob, alice])
2 ^ ( 18 + 10 ) = 256 M
:<|> return (SourceT ($ lots (powerOfTwo 18)))
:<|> return
where
lots n
| n < 0 = Stop
| otherwise = Effect $ do
let size = powerOfTwo 10
mbs <- getHardwareEntropy size
bs <- maybe (getEntropy size) pure mbs
return (Yield bs (lots (n - 1)))
powerOfTwo :: Int -> Int
powerOfTwo = (2 ^)
# NOINLINE manager ' #
manager' :: C.Manager
manager' = unsafePerformIO $ C.newManager C.defaultManagerSettings
withClient :: ClientM a -> BaseUrl -> (Either ClientError a -> IO r) -> IO r
withClient x baseUrl' = withClientM x (mkClientEnv manager' baseUrl')
testRunSourceIO :: SourceIO a
-> IO (Either String [a])
testRunSourceIO = runExceptT . runSourceT
streamSpec :: Spec
streamSpec = beforeAll (CT.startWaiApp server) $ afterAll CT.endWaiApp $ do
it "works with Servant.API.StreamGet.Newline" $ \(_, baseUrl) -> do
withClient getGetNL baseUrl $ \(Right res) ->
testRunSourceIO res `shouldReturn` Right [alice, bob, alice]
it "works with Servant.API.StreamGet.Netstring" $ \(_, baseUrl) -> do
withClient getGetNS baseUrl $ \(Right res) ->
testRunSourceIO res `shouldReturn` Right [alice, bob, alice]
it "works with Servant.API.StreamBody" $ \(_, baseUrl) -> do
withClient (getStreamBody (source input)) baseUrl $ \(Right res) ->
testRunSourceIO res `shouldReturn` Right output
where
input = ["foo", "", "bar"]
output = ["foo", "bar"]
it " streams in constant memory " $ \ ( _ , baseUrl ) - > do
Right rs < - runClient getGetALot baseUrl
performGC
--
-- putStrLn $ " Start : " + + show
tdigest < - memoryUsage $ joinCodensitySourceT rs
-- putStrLn $ " Median : " + + show ( TD.median tdigest )
-- putStrLn $ " Mean : " + + show ( TD.mean tdigest )
-- putStrLn $ " : " + + show ( TD.stddev tdigest )
-- forM _ [ 0.01 , 0.1 , 0.2 , 0.5 , 0.8 , 0.9 , 0.99 ] $ \q - >
-- putStrLn $ " q " + + show q + + " : " + + show ( TD.quantile q tdigest )
let Just stddev = TD.stddev tdigest
-- standard deviation of 100k is ok , we generate 256 M of data after all .
-- On my machine deviation is 40k-50k
stddev ` shouldSatisfy ` ( < 100000 )
memoryUsage : : SourceT IO BS.ByteString - > IO ( TD.TDigest 25 )
memoryUsage src = unSourceT src $ loop mempty ( 0 : : Int )
where
loop ! acc ! _ Stop = return acc
loop ! _ ! _ ( Error err ) = fail err -- !
loop ! acc ! n ( Skip s ) = loop acc n s
loop ! acc ! n ( Effect ms ) = ms > > = loop acc n
loop ! acc ! n ( Yield _ bs s ) = do
usage < - liftIO getUsage
-- We perform GC in between as we generate garbage .
when ( n ` mod ` 1024 = = 0 ) $ liftIO performGC
loop ( TD.insert usage acc ) ( n + 1 ) s
getUsage : : IO Double
getUsage = fromIntegral .
# if MIN_VERSION_base(4,10,0 )
gcdetails_live_bytes . gc < $ > getRTSStats
# else
currentBytesUsed < $ > getGCStats
# endif
memUsed ` shouldSatisfy ` ( < megabytes 22 )
megabytes : : a = > a - > a
megabytes n = n * ( 1000 ^ ( 2 : : Int ) )
it "streams in constant memory" $ \(_, baseUrl) -> do
Right rs <- runClient getGetALot baseUrl
performGC
-- usage0 <- getUsage
-- putStrLn $ "Start: " ++ show usage0
tdigest <- memoryUsage $ joinCodensitySourceT rs
-- putStrLn $ "Median: " ++ show (TD.median tdigest)
-- putStrLn $ "Mean: " ++ show (TD.mean tdigest)
-- putStrLn $ "Stddev: " ++ show (TD.stddev tdigest)
-- forM_ [0.01, 0.1, 0.2, 0.5, 0.8, 0.9, 0.99] $ \q ->
-- putStrLn $ "q" ++ show q ++ ": " ++ show (TD.quantile q tdigest)
let Just stddev = TD.stddev tdigest
-- standard deviation of 100k is ok, we generate 256M of data after all.
-- On my machine deviation is 40k-50k
stddev `shouldSatisfy` (< 100000)
memoryUsage :: SourceT IO BS.ByteString -> IO (TD.TDigest 25)
memoryUsage src = unSourceT src $ loop mempty (0 :: Int)
where
loop !acc !_ Stop = return acc
loop !_ !_ (Error err) = fail err -- !
loop !acc !n (Skip s) = loop acc n s
loop !acc !n (Effect ms) = ms >>= loop acc n
loop !acc !n (Yield _bs s) = do
usage <- liftIO getUsage
-- We perform GC in between as we generate garbage.
when (n `mod` 1024 == 0) $ liftIO performGC
loop (TD.insert usage acc) (n + 1) s
getUsage :: IO Double
getUsage = fromIntegral .
#if MIN_VERSION_base(4,10,0)
gcdetails_live_bytes . gc <$> getRTSStats
#else
currentBytesUsed <$> getGCStats
#endif
memUsed `shouldSatisfy` (< megabytes 22)
megabytes :: Num a => a -> a
megabytes n = n * (1000 ^ (2 :: Int))
-}
| null | https://raw.githubusercontent.com/haskell-servant/servant/d06b65c4e6116f992debbac2eeeb83eafb960321/servant-client/test/Servant/StreamSpec.hs | haskell | # LANGUAGE CPP #
# LANGUAGE ConstraintKinds #
# LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE StandaloneDeriving #
# LANGUAGE TypeFamilies #
# LANGUAGE TypeOperators #
This declaration simply checks that all instances are in place.
Note: this is streaming client
putStrLn $ " Start : " + + show
putStrLn $ " Median : " + + show ( TD.median tdigest )
putStrLn $ " Mean : " + + show ( TD.mean tdigest )
putStrLn $ " : " + + show ( TD.stddev tdigest )
forM _ [ 0.01 , 0.1 , 0.2 , 0.5 , 0.8 , 0.9 , 0.99 ] $ \q - >
putStrLn $ " q " + + show q + + " : " + + show ( TD.quantile q tdigest )
standard deviation of 100k is ok , we generate 256 M of data after all .
On my machine deviation is 40k-50k
!
We perform GC in between as we generate garbage .
usage0 <- getUsage
putStrLn $ "Start: " ++ show usage0
putStrLn $ "Median: " ++ show (TD.median tdigest)
putStrLn $ "Mean: " ++ show (TD.mean tdigest)
putStrLn $ "Stddev: " ++ show (TD.stddev tdigest)
forM_ [0.01, 0.1, 0.2, 0.5, 0.8, 0.9, 0.99] $ \q ->
putStrLn $ "q" ++ show q ++ ": " ++ show (TD.quantile q tdigest)
standard deviation of 100k is ok, we generate 256M of data after all.
On my machine deviation is 40k-50k
!
We perform GC in between as we generate garbage. | # LANGUAGE FlexibleInstances #
# LANGUAGE FunctionalDependencies #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE PolyKinds #
# LANGUAGE RecordWildCards #
# LANGUAGE UndecidableInstances #
# OPTIONS_GHC -freduction - depth=100 #
# OPTIONS_GHC -fno - warn - orphans #
# OPTIONS_GHC -fno - warn - name - shadowing #
module Servant.StreamSpec (spec) where
import Control.Monad
(when)
import Control.Monad.Codensity
(Codensity (..))
import Control.Monad.IO.Class
(MonadIO (..))
import Control.Monad.Trans.Except
import qualified Data.ByteString as BS
import Data.Proxy
import qualified Data.TDigest as TD
import qualified Network.HTTP.Client as C
import Prelude ()
import Prelude.Compat
import Servant.API
((:<|>) ((:<|>)), (:>), JSON, NetstringFraming, StreamBody,
NewlineFraming, NoFraming, OctetStream, SourceIO, StreamGet,
)
import Servant.Client.Streaming
import Servant.Server
import Servant.Test.ComprehensiveAPI
import Servant.Types.SourceT
import System.Entropy
(getEntropy, getHardwareEntropy)
import System.IO.Unsafe
(unsafePerformIO)
import System.Mem
(performGC)
import Test.Hspec
import Servant.ClientTestUtils (Person(..))
import qualified Servant.ClientTestUtils as CT
#if MIN_VERSION_base(4,10,0)
import GHC.Stats
(gc, gcdetails_live_bytes, getRTSStats)
#else
import GHC.Stats
(currentBytesUsed, getGCStats)
#endif
_ = client comprehensiveAPI
spec :: Spec
spec = describe "Servant.Client.Streaming" $ do
streamSpec
type StreamApi =
"streamGetNewline" :> StreamGet NewlineFraming JSON (SourceIO Person)
:<|> "streamGetNetstring" :> StreamGet NetstringFraming JSON (SourceIO Person)
:<|> "streamALot" :> StreamGet NoFraming OctetStream (SourceIO BS.ByteString)
:<|> "streamBody" :> StreamBody NoFraming OctetStream (SourceIO BS.ByteString) :> StreamGet NoFraming OctetStream (SourceIO BS.ByteString)
api :: Proxy StreamApi
api = Proxy
getGetNL, getGetNS :: ClientM (SourceIO Person)
getGetALot :: ClientM (SourceIO BS.ByteString)
getStreamBody :: SourceT IO BS.ByteString -> ClientM (SourceIO BS.ByteString)
getGetNL :<|> getGetNS :<|> getGetALot :<|> getStreamBody = client api
alice :: Person
alice = Person "Alice" 42
bob :: Person
bob = Person "Bob" 25
server :: Application
server = serve api
$ return (source [alice, bob, alice])
:<|> return (source [alice, bob, alice])
2 ^ ( 18 + 10 ) = 256 M
:<|> return (SourceT ($ lots (powerOfTwo 18)))
:<|> return
where
lots n
| n < 0 = Stop
| otherwise = Effect $ do
let size = powerOfTwo 10
mbs <- getHardwareEntropy size
bs <- maybe (getEntropy size) pure mbs
return (Yield bs (lots (n - 1)))
powerOfTwo :: Int -> Int
powerOfTwo = (2 ^)
# NOINLINE manager ' #
manager' :: C.Manager
manager' = unsafePerformIO $ C.newManager C.defaultManagerSettings
withClient :: ClientM a -> BaseUrl -> (Either ClientError a -> IO r) -> IO r
withClient x baseUrl' = withClientM x (mkClientEnv manager' baseUrl')
testRunSourceIO :: SourceIO a
-> IO (Either String [a])
testRunSourceIO = runExceptT . runSourceT
streamSpec :: Spec
streamSpec = beforeAll (CT.startWaiApp server) $ afterAll CT.endWaiApp $ do
it "works with Servant.API.StreamGet.Newline" $ \(_, baseUrl) -> do
withClient getGetNL baseUrl $ \(Right res) ->
testRunSourceIO res `shouldReturn` Right [alice, bob, alice]
it "works with Servant.API.StreamGet.Netstring" $ \(_, baseUrl) -> do
withClient getGetNS baseUrl $ \(Right res) ->
testRunSourceIO res `shouldReturn` Right [alice, bob, alice]
it "works with Servant.API.StreamBody" $ \(_, baseUrl) -> do
withClient (getStreamBody (source input)) baseUrl $ \(Right res) ->
testRunSourceIO res `shouldReturn` Right output
where
input = ["foo", "", "bar"]
output = ["foo", "bar"]
it " streams in constant memory " $ \ ( _ , baseUrl ) - > do
Right rs < - runClient getGetALot baseUrl
performGC
tdigest < - memoryUsage $ joinCodensitySourceT rs
let Just stddev = TD.stddev tdigest
stddev ` shouldSatisfy ` ( < 100000 )
memoryUsage : : SourceT IO BS.ByteString - > IO ( TD.TDigest 25 )
memoryUsage src = unSourceT src $ loop mempty ( 0 : : Int )
where
loop ! acc ! _ Stop = return acc
loop ! acc ! n ( Skip s ) = loop acc n s
loop ! acc ! n ( Effect ms ) = ms > > = loop acc n
loop ! acc ! n ( Yield _ bs s ) = do
usage < - liftIO getUsage
when ( n ` mod ` 1024 = = 0 ) $ liftIO performGC
loop ( TD.insert usage acc ) ( n + 1 ) s
getUsage : : IO Double
getUsage = fromIntegral .
# if MIN_VERSION_base(4,10,0 )
gcdetails_live_bytes . gc < $ > getRTSStats
# else
currentBytesUsed < $ > getGCStats
# endif
memUsed ` shouldSatisfy ` ( < megabytes 22 )
megabytes : : a = > a - > a
megabytes n = n * ( 1000 ^ ( 2 : : Int ) )
it "streams in constant memory" $ \(_, baseUrl) -> do
Right rs <- runClient getGetALot baseUrl
performGC
tdigest <- memoryUsage $ joinCodensitySourceT rs
let Just stddev = TD.stddev tdigest
stddev `shouldSatisfy` (< 100000)
memoryUsage :: SourceT IO BS.ByteString -> IO (TD.TDigest 25)
memoryUsage src = unSourceT src $ loop mempty (0 :: Int)
where
loop !acc !_ Stop = return acc
loop !acc !n (Skip s) = loop acc n s
loop !acc !n (Effect ms) = ms >>= loop acc n
loop !acc !n (Yield _bs s) = do
usage <- liftIO getUsage
when (n `mod` 1024 == 0) $ liftIO performGC
loop (TD.insert usage acc) (n + 1) s
getUsage :: IO Double
getUsage = fromIntegral .
#if MIN_VERSION_base(4,10,0)
gcdetails_live_bytes . gc <$> getRTSStats
#else
currentBytesUsed <$> getGCStats
#endif
memUsed `shouldSatisfy` (< megabytes 22)
megabytes :: Num a => a -> a
megabytes n = n * (1000 ^ (2 :: Int))
-}
|
a00cd4786b0cbf55d1b9ff23be49a1149a0c02d6321819a91ef74340659af3bf | Lovesan/doors | dlls.lisp | ;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
Copyright ( C ) 2010 - 2011 , < >
;;; Permission is hereby granted, free of charge, to any person
;;; obtaining a copy of this software and associated documentation
files ( the " Software " ) , to deal in the Software without
;;; restriction, including without limitation the rights to use, copy,
;;; modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software , and to permit persons to whom the Software is
;;; furnished to do so, subject to the following conditions:
;;; The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
;;; HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
;;; WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
;;; OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
;;; DEALINGS IN THE SOFTWARE
(in-package #:doors)
(define-external-function
("DisableThreadLibraryCalls" (:camel-case))
(:stdcall kernel32)
((last-error bool))
(module handle))
(define-external-function
("FreeLibrary" (:camel-case))
(:stdcall kernel32)
((last-error bool))
"Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count."
(module handle))
(define-external-function
("FreeLibraryAndExitThread" (:camel-case))
(:stdcall kernel32)
(void)
"Decrements the reference count of a loaded dynamic-link library (DLL) by one, then calls ExitThread to terminate the calling thread. The function does not return."
(module handle)
(exit-code dword :optional 0))
#-win2000
(define-external-function
(#+doors.unicode "GetDllDirectoryW"
#-doors.unicode "GetDllDirectoryA"
dll-directory)
(:stdcall kernel32)
(dword rv (if (zerop rv)
(invoke-last-error)
(subseq buffer 0 rv)))
"Retrieves the application-specific portion of the search path used to locate DLLs for the application."
(buffer-length dword :optional 256)
(buffer (& tstring :out) :aux (make-string buffer-length)))
#-win2000
(define-symbol-macro dll-directory (dll-directory))
(define-external-function
(#+doors.unicode "GetModuleFileNameW"
#-doors.unicode "GetModuleFileNameA"
module-file-name)
(:stdcall kernel32)
(dword rv (if (and (zerop rv) (not (zerop buffer-size)))
(invoke-last-error)
(subseq buffer 0 rv)))
"Retrieves the fully-qualified path for the file that contains the specified module."
(module handle :optional nil)
(buffer (& tstring :out) :aux (make-string buffer-size))
(buffer-size dword :optional 256))
(define-symbol-macro module-file-name (module-file-name))
(define-external-function
(#+doors.unicode "GetModuleHandleW"
#-doors.unicode "GetModuleHandleA"
module-handle)
(:stdcall kernel32)
((last-error handle))
"Retrieves a module handle for the specified module. The module must have been loaded by the calling process."
(module-name (& tstring :in t) :optional void))
(define-symbol-macro module-handle (module-handle))
(define-enum (module-handle-flags
(:base-type dword)
(:list t)
(:conc-name module-handle-flag-))
(:inc-refcount #x00000000)
(:from-address #x00000004)
(:pin #x00000001)
(:unchanged-refcount #x00000002))
#-win2000
(define-external-function
(#+doors.unicode "GetModuleHandleExW"
#-doors.unicode "GetModuleHandleExA"
module-handle*)
(:stdcall kernel32)
((last-error bool) rv module)
"Retrieves a module handle for the specified module. The module must have been loaded by the calling process."
(flags module-handle-flags)
(module-name (union ()
(ptr pointer)
(name (& tstring :in t)))
:optional void)
(module (& handle :out) :aux))
#-win2000
(define-symbol-macro module-handle* (module-handle*))
(define-external-function
("GetProcAddress" proc-address)
(:stdcall kernel32)
((last-error pointer &?))
"Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL)."
(module handle)
(proc-name (union ()
(number size-t)
(name (& astring)))))
(define-external-function
(#+doors.unicode "LoadLibraryW"
#-doors.unicode "LoadLibraryA"
load-library)
(:stdcall kernel32)
((last-error handle))
"Loads the specified module into the address space of the calling process."
(filename (& tstring)))
(define-enum (load-library-flags
(:base-type dword)
(:list t)
(:conc-name load-library-))
(:dont-resolve-dll-references #x00000001)
(:ignore-code-authz-level #x00000010)
(:as-datafile #x00000002)
(:as-datafile-exclusive #x00000040)
(:as-image-resource #x00000020)
(:with-altered-search-path #x00000008))
(define-external-function
(#+doors.unicode "LoadLibraryExW"
#-doors.unicode "LoadLibraryExA"
load-library*)
(:stdcall kernel32)
((last-error handle))
"Loads the specified module into the address space of the calling process. The specified module may cause other modules to be loaded."
(filename (& tstring))
(hfile handle :aux nil)
(flags load-library-flags))
(define-struct (load-params
(:constructor make-load-params)
(:constructor
load-params (cmd-line &optional cmd-show env-address)))
(env-address (& astring :in t) :initform void)
(cmd-line (& pascal-string))
(cmd-show (& dword) :initform #x00000002)
(reserved dword :initform 0))
(define-external-function
("LoadModule" (:camel-case))
(:stdcall kernel32)
(dword rv (if (> rv 31)
t
(error 'windows-error
:code (if (zerop rv)
error-out-of-memory
(hresult-from-win32 rv)))))
"Loads and executes an application or creates a new instance of an existing application."
(module-name (& astring))
(parameter-block (& load-params)))
#-win2000
(define-external-function
(#+doors.unicode "SetDllDirectoryW"
#-doors.unicode "SetDllDirectoryA"
(setf dll-directory))
(:stdcall kernel32)
((last-error bool) rv pathname)
"Adds a directory to the search path used to locate DLLs for the application."
(pathname (& tstring :in t)))
| null | https://raw.githubusercontent.com/Lovesan/doors/12a2fe2fd8d6c42ae314bd6d02a1d2332f12499e/system/dlls.lisp | lisp | -*- Mode: lisp; indent-tabs-mode: nil -*-
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE |
Copyright ( C ) 2010 - 2011 , < >
files ( the " Software " ) , to deal in the Software without
of the Software , and to permit persons to whom the Software is
included in all copies or substantial portions of the Software .
THE SOFTWARE IS PROVIDED " AS IS " , WITHOUT WARRANTY OF ANY KIND ,
(in-package #:doors)
(define-external-function
("DisableThreadLibraryCalls" (:camel-case))
(:stdcall kernel32)
((last-error bool))
(module handle))
(define-external-function
("FreeLibrary" (:camel-case))
(:stdcall kernel32)
((last-error bool))
"Frees the loaded dynamic-link library (DLL) module and, if necessary, decrements its reference count."
(module handle))
(define-external-function
("FreeLibraryAndExitThread" (:camel-case))
(:stdcall kernel32)
(void)
"Decrements the reference count of a loaded dynamic-link library (DLL) by one, then calls ExitThread to terminate the calling thread. The function does not return."
(module handle)
(exit-code dword :optional 0))
#-win2000
(define-external-function
(#+doors.unicode "GetDllDirectoryW"
#-doors.unicode "GetDllDirectoryA"
dll-directory)
(:stdcall kernel32)
(dword rv (if (zerop rv)
(invoke-last-error)
(subseq buffer 0 rv)))
"Retrieves the application-specific portion of the search path used to locate DLLs for the application."
(buffer-length dword :optional 256)
(buffer (& tstring :out) :aux (make-string buffer-length)))
#-win2000
(define-symbol-macro dll-directory (dll-directory))
(define-external-function
(#+doors.unicode "GetModuleFileNameW"
#-doors.unicode "GetModuleFileNameA"
module-file-name)
(:stdcall kernel32)
(dword rv (if (and (zerop rv) (not (zerop buffer-size)))
(invoke-last-error)
(subseq buffer 0 rv)))
"Retrieves the fully-qualified path for the file that contains the specified module."
(module handle :optional nil)
(buffer (& tstring :out) :aux (make-string buffer-size))
(buffer-size dword :optional 256))
(define-symbol-macro module-file-name (module-file-name))
(define-external-function
(#+doors.unicode "GetModuleHandleW"
#-doors.unicode "GetModuleHandleA"
module-handle)
(:stdcall kernel32)
((last-error handle))
"Retrieves a module handle for the specified module. The module must have been loaded by the calling process."
(module-name (& tstring :in t) :optional void))
(define-symbol-macro module-handle (module-handle))
(define-enum (module-handle-flags
(:base-type dword)
(:list t)
(:conc-name module-handle-flag-))
(:inc-refcount #x00000000)
(:from-address #x00000004)
(:pin #x00000001)
(:unchanged-refcount #x00000002))
#-win2000
(define-external-function
(#+doors.unicode "GetModuleHandleExW"
#-doors.unicode "GetModuleHandleExA"
module-handle*)
(:stdcall kernel32)
((last-error bool) rv module)
"Retrieves a module handle for the specified module. The module must have been loaded by the calling process."
(flags module-handle-flags)
(module-name (union ()
(ptr pointer)
(name (& tstring :in t)))
:optional void)
(module (& handle :out) :aux))
#-win2000
(define-symbol-macro module-handle* (module-handle*))
(define-external-function
("GetProcAddress" proc-address)
(:stdcall kernel32)
((last-error pointer &?))
"Retrieves the address of an exported function or variable from the specified dynamic-link library (DLL)."
(module handle)
(proc-name (union ()
(number size-t)
(name (& astring)))))
(define-external-function
(#+doors.unicode "LoadLibraryW"
#-doors.unicode "LoadLibraryA"
load-library)
(:stdcall kernel32)
((last-error handle))
"Loads the specified module into the address space of the calling process."
(filename (& tstring)))
(define-enum (load-library-flags
(:base-type dword)
(:list t)
(:conc-name load-library-))
(:dont-resolve-dll-references #x00000001)
(:ignore-code-authz-level #x00000010)
(:as-datafile #x00000002)
(:as-datafile-exclusive #x00000040)
(:as-image-resource #x00000020)
(:with-altered-search-path #x00000008))
(define-external-function
(#+doors.unicode "LoadLibraryExW"
#-doors.unicode "LoadLibraryExA"
load-library*)
(:stdcall kernel32)
((last-error handle))
"Loads the specified module into the address space of the calling process. The specified module may cause other modules to be loaded."
(filename (& tstring))
(hfile handle :aux nil)
(flags load-library-flags))
(define-struct (load-params
(:constructor make-load-params)
(:constructor
load-params (cmd-line &optional cmd-show env-address)))
(env-address (& astring :in t) :initform void)
(cmd-line (& pascal-string))
(cmd-show (& dword) :initform #x00000002)
(reserved dword :initform 0))
(define-external-function
("LoadModule" (:camel-case))
(:stdcall kernel32)
(dword rv (if (> rv 31)
t
(error 'windows-error
:code (if (zerop rv)
error-out-of-memory
(hresult-from-win32 rv)))))
"Loads and executes an application or creates a new instance of an existing application."
(module-name (& astring))
(parameter-block (& load-params)))
#-win2000
(define-external-function
(#+doors.unicode "SetDllDirectoryW"
#-doors.unicode "SetDllDirectoryA"
(setf dll-directory))
(:stdcall kernel32)
((last-error bool) rv pathname)
"Adds a directory to the search path used to locate DLLs for the application."
(pathname (& tstring :in t)))
|
fd20c8b8f7c32ec3c2f1ff4da185fd8ff6c6eb757ee76ebafec40d612fc95300 | zyrolasting/racket-vulkan | txexpr.rkt | #lang racket/base
;; Tagged X-expression procedures adapted to this project.
(provide (all-defined-out)
(all-from-out txexpr))
(require (only-in racket/string string-trim string-join)
txexpr)
(define (with-attr name L)
(filter (λ (x) (attrs-have-key? x name)) L))
(define (tag=? t tx)
(and (txexpr? tx)
(equal? (get-tag tx) t)))
(define (category=? c tx)
(and (txexpr? tx)
(equal? (attr-ref tx 'category #f) c)))
(define (find-all-by-tag t tx)
(or (findf*-txexpr tx (λ (x) (tag=? t x)))
'()))
(define (find-first-by-tag t tx)
(findf-txexpr tx (λ (x) (tag=? t x))))
(define (get-tagged-children tx)
(filter txexpr? (get-elements tx)))
(define (get-types-by-category cat types)
(filter (λ (x) (equal? (attr-ref x 'category "") cat))
types))
(define (shrink-wrap-cdata x)
(string-trim (string-join (filter string? (get-elements x)) "")))
(define (get-text-in-tagged-child t tx)
(shrink-wrap-cdata (find-first-by-tag t tx)))
(define (get-all-cdata x)
(foldl (λ (kid str)
(string-append str
(if (string? kid)
kid
(get-all-cdata kid))))
""
(get-elements x)))
(define (snatch-cdata t tx #:children-only? [kidsonly #f])
(shrink-wrap-cdata (find-first-by-tag t (if kidsonly (cons (gensym) (cdr tx))
tx))))
(define (get-elements-of-tag t tx)
(filter (λ (x) (tag=? t x))
(get-elements tx)))
| null | https://raw.githubusercontent.com/zyrolasting/racket-vulkan/4f743b4b2933173ee4f141e5ae94739895c54b67/private/txexpr.rkt | racket | Tagged X-expression procedures adapted to this project. | #lang racket/base
(provide (all-defined-out)
(all-from-out txexpr))
(require (only-in racket/string string-trim string-join)
txexpr)
(define (with-attr name L)
(filter (λ (x) (attrs-have-key? x name)) L))
(define (tag=? t tx)
(and (txexpr? tx)
(equal? (get-tag tx) t)))
(define (category=? c tx)
(and (txexpr? tx)
(equal? (attr-ref tx 'category #f) c)))
(define (find-all-by-tag t tx)
(or (findf*-txexpr tx (λ (x) (tag=? t x)))
'()))
(define (find-first-by-tag t tx)
(findf-txexpr tx (λ (x) (tag=? t x))))
(define (get-tagged-children tx)
(filter txexpr? (get-elements tx)))
(define (get-types-by-category cat types)
(filter (λ (x) (equal? (attr-ref x 'category "") cat))
types))
(define (shrink-wrap-cdata x)
(string-trim (string-join (filter string? (get-elements x)) "")))
(define (get-text-in-tagged-child t tx)
(shrink-wrap-cdata (find-first-by-tag t tx)))
(define (get-all-cdata x)
(foldl (λ (kid str)
(string-append str
(if (string? kid)
kid
(get-all-cdata kid))))
""
(get-elements x)))
(define (snatch-cdata t tx #:children-only? [kidsonly #f])
(shrink-wrap-cdata (find-first-by-tag t (if kidsonly (cons (gensym) (cdr tx))
tx))))
(define (get-elements-of-tag t tx)
(filter (λ (x) (tag=? t x))
(get-elements tx)))
|
7e273dbf401bc495f401802dc0e648bcdbbb8d4ec8ada23493343562533dc2e0 | lpeterse/koka | Pretty.hs | -----------------------------------------------------------------------------
Copyright 2012 Microsoft Corporation .
--
-- This is free software; you can redistribute it and/or modify it under the
terms of the Apache License , Version 2.0 . A copy of the License can be
found in the file " license.txt " at the root of this distribution .
-----------------------------------------------------------------------------
module Type.Pretty (-- * Pretty
ppType, ppScheme, ppTypeVar, ppDataInfo, ppSynInfo
,prettyDataInfo, prettyConInfo
,ppSchemeEffect, ppDeclType, ppPred
,niceTypeInitial, niceTypeExtend, niceTypeExtendVars
,precTop, precArrow, precApp, precAtom, pparens
,Env(..), defaultEnv
,niceList, niceTypes, niceType, niceEnv
,typeColon, niceTypeVars, ppName
, canonical, minCanonical
, prettyComment
) where
import Data.Char( isSpace )
import qualified Data.Map as M
import Platform.Config( programName )
import Data.List( partition )
import Lib.PPrint
import Common.Name
import Common.NamePrim( isNameTuple, nameTpOptional, nameEffectExtend, nameTpTotal, nameEffectEmpty, nameTpDelay, nameSystemCore )
import Common.ColorScheme
import Common.IdNice
import Common.Syntax
import Kind.Kind
import Kind.Pretty
import Kind.ImportMap
import Type.Type
import Type.TypeVar
import Type.Kind
typeColon colors
= color (colorSep colors) (text ":")
minCanonical tp
= compress (show (minimalForm tp))
canonical tp
= compress (show (canonicalForm tp))
compress cs
= case cs of
[] -> []
(c:cc) ->
if (c=='\n')
then compress (dropWhile isSpace cc)
else if (isSpace c)
then ' ' : compress (dropWhile isSpace cc)
else c : compress cc
{--------------------------------------------------------------------------
--------------------------------------------------------------------------}
niceType :: Env -> Type -> Doc
niceType env tp
-- ppType env tp
= head (niceTypes env [tp])
niceTypes :: Env -> [Type] -> [Doc]
niceTypes = niceList (\env tp -> color (colorType (colors env)) (ppType env tp))
niceList :: (HasTypeVar a) => (Env -> a -> Doc) -> Env -> [a] -> [Doc]
niceList printer env schemes
= let env' = niceEnv env (tvsList (ftv schemes))
in map (printer env') schemes
niceEnv :: Env -> [TypeVar] -> Env
niceEnv env typevars
= env{ nice = niceTypeExtendVars typevars (nice env) }
keyword env s
= color (colorTypeKeyword (colors env)) (text s)
tab
= id
{--------------------------------------------------------------------------
Show
--------------------------------------------------------------------------}
instance Pretty Type where
ppScheme defaultEnv
instance Pretty TypeVar where
pretty = ppTypeVar defaultEnv
instance Pretty TypeCon where
pretty = ppTypeCon defaultEnv
instance Pretty TypeSyn where
pretty = ppTypeSyn defaultEnv
{--------------------------------------------------------------------------
Pretty print type schemes
This is somewhat complicated as we want to expand type variables
into type schemes when they (a) occur once, and (b) the variance
of the type variable matches the bound. This makes type schemes
much more readable than the plain mlF variant.
Furthermore, we want to hide type schemes that are hidden under
a type synonym (see test/correct/kind/poly3). So, we have to
determine if variables are used uniquely, or if they are dead,
where we do not look under type synonyms if the option
"--expand-synonyms" is not given.
Even more complications: we want to return a big map with single
use and dead variables but that is only possible if no name-capture
is possible. So, we run "uniquefy" before doing the analysis to make
all bound variables unique relative to each other.
--------------------------------------------------------------------------}
type TvScheme = M.Map TypeVar (Prec -> Doc)
-- | Pretty print environment for types.
data Env = Env{ showKinds :: Bool
, expandSynonyms :: Bool
, colors :: ColorScheme
, nice :: Nice
, prec :: Prec
, ranked :: TvScheme
, context :: Name -- ^ module in which we pretty print
, importsMap :: ImportMap -- ^ import aliases
, fullNames :: Bool
should not really belong here . Contains link bases for documentation generation ( see Syntax . Colorize )
, htmlBases :: [(String,String)]
, htmlCss :: String
, htmlJs :: String
-- should not be here either: Signifies whether we output core for an interface or not
, coreIface :: Bool
-- should not be here either: was the verbose flag set?
, verbose :: Int
}
-- | Default pretty print environment
defaultEnv :: Env
defaultEnv
= Env False False defaultColorScheme niceEmpty (precTop-1) M.empty (newName "Main") (importsEmpty) False
[]
[ ( " System . ","file:/users / / dev / koka / out / lib/ " ) ]
("scripts/" ++ programName ++ "-highlight.js")
False -- coreIface
0 -- verbose
-- | Pretty print a type.
ppScheme :: Env -> Scheme -> Doc
ppScheme env scheme
= niceType env scheme
ppSchemeEffect :: Env -> Scheme -> Doc
ppSchemeEffect env tp@(TFun [] effect result)
= ppSchemeEffect env (TForall [] [] tp)
ppSchemeEffect env (TForall vars preds (TFun [] effect result))
= color (colorType (colors env)) $
let env' = env{ nice = niceTypeExtend vars (nice env), prec = precTop } in
pparens (prec env) precQuant $ tab $
(if null vars then empty else (keyword env' "forall" <> angled (map (ppTypeVar env') vars) <> dot <> space))
<> (if null preds then empty else ((commaSep (map (ppPred env') preds)) <+> text "=> " ))
<> (if isTypeTotal effect then empty else (ppType env'{prec = precArrow-1} effect) <> space)
<> ppType env' result
ppSchemeEffect env tp
= niceType env tp
ppDeclType :: Env -> Scheme -> (Maybe [(Name,Doc)],Doc)
ppDeclType env tp
= case tp of
TForall vars preds rho
-> let env' = niceEnv env vars
(args,res) = ppDeclType env' rho
in (args, res <> ppPredicates env' preds)
TFun params effect rho
ppFun env ( text " : " ) rho
let pparams = [(name, ppType env tp) | (name,tp) <- params]
in (Just pparams, (if (isTypeTotal effect) then empty else (ppType env{prec=precArrow} effect <> space)) <> ppType env{prec=precArrow} rho)
_ -> -- ppType env tp
(Nothing,ppType env tp)
{--------------------------------------------------------------------------
Pretty printing of type information
TODO: properly implement these
--------------------------------------------------------------------------}
instance Show DataInfo where
show = show . pretty
instance Pretty DataInfo where
pretty = ppDataInfo Type.Pretty.defaultEnv True
ppDataInfo env showBody dataInfo
= prettyDataInfo env showBody False dataInfo Private (repeat Private)
commaSep = hsep . punctuate comma
prettyDataInfo env0 showBody publicOnly info@(DataInfo datakind name kind args cons range isRec doc) vis conViss
= if (publicOnly && isPrivate vis) then empty else
(prettyComment env0 doc $
(if publicOnly then empty else ppVis env0 vis) <>
let env = env0{ nice = niceTypeExtendVars (args) (nice env0) } in
(case datakind of
Inductive -> keyword env "type"
CoInductive -> keyword env "cotype"
Retractive -> keyword env "rectype") <+>
(if isRec then keyword env "rec " else empty) <>
-- ppVis env vis <+>
ppName env name <>
(if null args then empty else space <> angled (map (ppTypeVar env) args)) <>
(if kind /= kindStar then text " ::" <+> ppKind (colors env) 0 kind else empty) <+>
(if (showBody && not (null cons))
then (text "{" <$>
indent 2 (vcat (map (prettyConInfo env publicOnly) (zip conViss cons))) <$> text "}")
else empty))
prettyConInfo env publicOnly (vis,ConInfo conName ntname exists fields scheme sort range paramRanges singleton doc)
= if (publicOnly && isPrivate vis) then empty else
(prettyComment env doc $
(if publicOnly then empty else ppVis env vis) <>
keyword env "con" <+>
ppName env conName <>
(if null exists then empty else (angled (map (ppTypeVar env) exists))) <>
(if null fields
then empty
else parens (commaSep (map (ppField env) fields)))
<+> text ":" <+> ppType env scheme <> semi)
where
ppField env (name,tp)
= (if isFieldName name then empty else (ppName env name <> text ": ")) <> ppType env tp
prettyComment env comment doc
= if null comment then doc
else let cmt = if last comment == '\n' then init comment else comment
in color (colorComment (colors env)) (text cmt) <$> doc
ppVis env vis
= case vis of
Private -> keyword env "private "
Public -> keyword env "public "
{--------------------------------------------------------------------------
Synonym Info
--------------------------------------------------------------------------}
instance Pretty SynInfo where
pretty info = ppSynInfo Type.Pretty.defaultEnv False True info Public
ppSynInfo env publicOnly showBody (SynInfo name kind params scheme rank range doc) vis
= if (publicOnly && isPrivate vis) then empty else
(prettyComment env doc $
(if publicOnly then empty else ppVis env vis) <>
keyword env "alias" <+> ppName env name <> -- <+> (ppSynInfo env True synInfo)
let docs = niceTypes env (map TVar params ++ [scheme])
in (if null params then empty else angled (init docs))
<> (if kind /= kindStar then text " ::" <+> ppKind (colors env) precTop kind else empty)
<+> (if not showBody then empty else keyword env "=" <+> last docs))
<+> text "=" <+> pretty rank
{--------------------------------------------------------------------------
Pretty printing
--------------------------------------------------------------------------}
-- | Precedence
type Prec = Int
precTop,precQuant,precArrow,precApp :: Prec
precTopTop = -1 -- most outer level: used to suppress 'forall'
precTop = 0
precQuant = 1
precArrow = 2
precApp = 3
precAtom = 4
precPred = 5
pparens :: Prec -> Prec -> Doc -> Doc
pparens context prec doc
| context >= prec = parens doc
| otherwise = doc
ppType :: Env -> Type -> Doc
ppType env tp
= color (colorType (colors env)) $
case tp of
TForall vars preds t
-> let env' = env{ nice = niceTypeExtend vars (nice env), prec = precTop } in
pparens (prec env) precQuant $ tab $
(if (null vars {- prec env == precTopTop-}) then empty
else (keyword env' "forall" <> angled (map (ppTypeVar env') vars) <> space))
<> ppType env' t
<> ppPredicates env' preds
TFun args effect result
-> ppFun env (text "->") args effect result
TVar tv@(TypeVar id kind Bound)
-> case M.lookup tv (ranked env) of
( nice env ) i d
Just f -> f (prec env)
TVar tv -> ppTypeVar env tv
TCon cv -> if (typeConName cv == nameEffectEmpty && not (coreIface env))
then ppNameEx env nameTpTotal
else ppTypeCon env cv
TApp (TCon con) [_,_] | typeConName con == nameEffectExtend
-> let (ls,tl) = shallowExtractEffectExtend tp
tldoc = if (tl == effectEmpty)
then empty
else text "|" <> ppType env{prec=precTop} tl
in color (colorEffect (colors env)) $
case ls of
[] | tl == effectEmpty && not (coreIface env) -> ppNameEx env nameTpTotal
[l] | tl == effectEmpty && not (coreIface env) -> ppType env{prec=precAtom} l
_ -> text "<" <> hcat (punctuate comma (map (ppType env{prec=precTop}) ls)) <> tldoc <> text ">"
TApp (TCon con) [eff,res]
| typeConName con == nameTpDelay
-> text "$" <+>
(if (isTypeTotal eff) then empty else (ppType env{prec = precArrow} eff <> space)) <>
ppType env{prec=precArrow} res
TApp (TCon con) [arg]
| typeConName con == nameTpOptional
-> text "?" <> ppType env{prec=precTop} arg
TApp (TCon (TypeCon name _)) args | isNameTuple (name)
-> parens (commaSep (map (ppType env{prec = precTop}) args))
TApp f args -> pparens (prec env) precApp $
ppType env{ prec = precAtom } f <>
(case args of
[] -> empty
(arg:rest)
-> (if null rest then colorByKind env (getKind arg) id else id) $
angled (map (ppType env{ prec = precTop }) args))
TSyn syn args tp
-> ppSynonym env syn args (ppType env{ prec = precTop } tp)
ppPredicates env preds
= (if null preds then empty else (keyword env " with") <+> (align (hcat (map (ppPred env) preds))))
ppFun env arrow args effect result
= pparens (prec env) precArrow $
parens (hsep (punctuate comma (map (ppParam env{prec = precTop}) args))) <+>
(if (isTypeTotal effect) then arrow else (arrow <+> ppType env{prec = precArrow} effect)) <+>
ppType env{prec=precArrow} result
ppParam :: Env -> (Name,Type) -> Doc
ppParam env (name,tp)
= (if (not (nameIsNil name || isFieldName name)) then (color (colorParameter (colors env)) (ppNameEx env name <> text " : ")) else empty)
<> ppType env tp
ppName :: Env -> Name -> Doc
ppName env name
= color (colorSource (colors env)) $ ppNameEx env name
ppTypeName :: Env -> Name -> Doc
ppTypeName env name
= color (colorType (colors env)) $ ppNameEx env name
ppNameEx env name
= if (fullNames env)
then pretty name
else if (context env == qualifier name || (qualifier name == nameSystemCore && not (coreIface env)) || isNameTuple name)
then pretty (unqualify name)
else -- if coreIface env
-- then pretty name
-- else
pretty (importsAlias name (importsMap env))
---------------------------------------------------------------------------
-- Predicates
---------------------------------------------------------------------------
ppPred :: Env -> Pred -> Doc
ppPred env pred
= pparens (prec env) precPred $
case pred of
PredSub tp1 tp2
-> ppType (env{prec = precPred}) tp1 <+> text "<=" <+> ppType (env{prec=precPred}) tp2
PredIFace name args
-> ppTypeName env name <> angled (map (ppType env{prec=precTop}) args)
ppSynonym :: Env -> TypeSyn -> [Tau] -> Doc -> Doc
ppSynonym env (TypeSyn name kind rank _) args tpdoc
= (if (expandSynonyms env)
then parens
else if (null args)
then id
else pparens (prec env) precApp) $
ppType env{prec=precTop} (TApp (TCon (TypeCon name kind)) args) <>
if (expandSynonyms env) then text " == " <> pretty rank <+> tpdoc else empty
ppTypeVar :: Env -> TypeVar -> Doc
ppTypeVar env (TypeVar id kind flavour)
= colorByKindDef env kind colorTypeVar $
wrapKind (showKinds env) env kind $
(case flavour of
Meta -> text "_"
Skolem -> text "$"
_ -> empty) <> nicePretty (nice env) id
ppTypeCon :: Env -> TypeCon -> Doc
ppTypeCon env (TypeCon name kind)
= colorByKindDef env kind colorTypeCon $
(if name == nameEffectEmpty then id else wrapKind (showKinds env) env kind) $
ppNameEx env name
ppTypeSyn :: Env -> TypeSyn -> Doc
ppTypeSyn env (TypeSyn name kind rank _)
= colorByKindDef env kind colorTypeCon $
wrapKind (showKinds env) env kind (ppNameEx env name)
colorByKindDef env kind defcolor doc
= colorByKind env kind (color (defcolor (colors env))) doc
colorByKind env kind defcolor doc
= case colorForKind env kind of
Just c -> color c doc
Nothing -> defcolor doc
colorForKind env kind
= if (kind == kindEffect || kind == kindLabel || kind == kindFun kindHeap kindLabel)
then Just (colorEffect (colors env))
else if (kind == kindHeap)
then Just (colorEffect (colors env))
else Nothing
wrapKind :: Bool -> Env -> Kind -> Doc -> Doc
wrapKind showKinds env kind doc
= if (showKinds && kind /= kindStar )
then color (colorKind (colors env)) $
parens (color (colorType (colors env)) doc <+> text "::" <+>
ppKind (colors env) precTop kind)
else doc
niceTypeInitial :: [TypeVar] -> Nice
niceTypeInitial ts
= niceTypeExtendVars ts niceEmpty
niceTypeExtend :: [TypeVar] -> Nice -> Nice
niceTypeExtend tvars nice
= niceTypeExtendVars tvars nice
niceTypeExtendVars ts nice
= let (es,ws) = partition (\(TypeVar id kind flavour) -> kind == kindEffect) ts
(hs,vs) = partition (\(TypeVar id kind flavour) -> kind == kindHeap) ws
nice1 = niceExtend (map typeVarId vs) niceTypeVars nice
nice2 = niceExtend (map typeVarId es) niceEffectVars nice1
nice3 = niceExtend (map typeVarId hs) niceHeapVars nice2
in nice3
niceTypeVars :: [String]
niceTypeVars
= [ [x] | x <- letters ] ++
[ ([x] ++ show i) | i <- [1..], x <- letters]
where
letters = ['a'..'d']
niceEffectVars :: [String]
niceEffectVars
= [ "e" ] ++
[ (['e'] ++ show i) | i <- [1..]]
niceHeapVars :: [String]
niceHeapVars
= [ "h" ] ++
[ (['h'] ++ show i) | i <- [1..]]
| null | https://raw.githubusercontent.com/lpeterse/koka/43feefed258b9a533f07967d3f8867b02384df0e/src/Type/Pretty.hs | haskell | ---------------------------------------------------------------------------
This is free software; you can redistribute it and/or modify it under the
---------------------------------------------------------------------------
* Pretty
-------------------------------------------------------------------------
-------------------------------------------------------------------------
ppType env tp
-------------------------------------------------------------------------
Show
-------------------------------------------------------------------------
-------------------------------------------------------------------------
Pretty print type schemes
This is somewhat complicated as we want to expand type variables
into type schemes when they (a) occur once, and (b) the variance
of the type variable matches the bound. This makes type schemes
much more readable than the plain mlF variant.
Furthermore, we want to hide type schemes that are hidden under
a type synonym (see test/correct/kind/poly3). So, we have to
determine if variables are used uniquely, or if they are dead,
where we do not look under type synonyms if the option
"--expand-synonyms" is not given.
Even more complications: we want to return a big map with single
use and dead variables but that is only possible if no name-capture
is possible. So, we run "uniquefy" before doing the analysis to make
all bound variables unique relative to each other.
-------------------------------------------------------------------------
| Pretty print environment for types.
^ module in which we pretty print
^ import aliases
should not be here either: Signifies whether we output core for an interface or not
should not be here either: was the verbose flag set?
| Default pretty print environment
coreIface
verbose
| Pretty print a type.
ppType env tp
-------------------------------------------------------------------------
Pretty printing of type information
TODO: properly implement these
-------------------------------------------------------------------------
ppVis env vis <+>
-------------------------------------------------------------------------
Synonym Info
-------------------------------------------------------------------------
<+> (ppSynInfo env True synInfo)
-------------------------------------------------------------------------
Pretty printing
-------------------------------------------------------------------------
| Precedence
most outer level: used to suppress 'forall'
prec env == precTopTop
if coreIface env
then pretty name
else
-------------------------------------------------------------------------
Predicates
------------------------------------------------------------------------- | Copyright 2012 Microsoft Corporation .
terms of the Apache License , Version 2.0 . A copy of the License can be
found in the file " license.txt " at the root of this distribution .
ppType, ppScheme, ppTypeVar, ppDataInfo, ppSynInfo
,prettyDataInfo, prettyConInfo
,ppSchemeEffect, ppDeclType, ppPred
,niceTypeInitial, niceTypeExtend, niceTypeExtendVars
,precTop, precArrow, precApp, precAtom, pparens
,Env(..), defaultEnv
,niceList, niceTypes, niceType, niceEnv
,typeColon, niceTypeVars, ppName
, canonical, minCanonical
, prettyComment
) where
import Data.Char( isSpace )
import qualified Data.Map as M
import Platform.Config( programName )
import Data.List( partition )
import Lib.PPrint
import Common.Name
import Common.NamePrim( isNameTuple, nameTpOptional, nameEffectExtend, nameTpTotal, nameEffectEmpty, nameTpDelay, nameSystemCore )
import Common.ColorScheme
import Common.IdNice
import Common.Syntax
import Kind.Kind
import Kind.Pretty
import Kind.ImportMap
import Type.Type
import Type.TypeVar
import Type.Kind
typeColon colors
= color (colorSep colors) (text ":")
minCanonical tp
= compress (show (minimalForm tp))
canonical tp
= compress (show (canonicalForm tp))
compress cs
= case cs of
[] -> []
(c:cc) ->
if (c=='\n')
then compress (dropWhile isSpace cc)
else if (isSpace c)
then ' ' : compress (dropWhile isSpace cc)
else c : compress cc
niceType :: Env -> Type -> Doc
niceType env tp
= head (niceTypes env [tp])
niceTypes :: Env -> [Type] -> [Doc]
niceTypes = niceList (\env tp -> color (colorType (colors env)) (ppType env tp))
niceList :: (HasTypeVar a) => (Env -> a -> Doc) -> Env -> [a] -> [Doc]
niceList printer env schemes
= let env' = niceEnv env (tvsList (ftv schemes))
in map (printer env') schemes
niceEnv :: Env -> [TypeVar] -> Env
niceEnv env typevars
= env{ nice = niceTypeExtendVars typevars (nice env) }
keyword env s
= color (colorTypeKeyword (colors env)) (text s)
tab
= id
instance Pretty Type where
ppScheme defaultEnv
instance Pretty TypeVar where
pretty = ppTypeVar defaultEnv
instance Pretty TypeCon where
pretty = ppTypeCon defaultEnv
instance Pretty TypeSyn where
pretty = ppTypeSyn defaultEnv
type TvScheme = M.Map TypeVar (Prec -> Doc)
data Env = Env{ showKinds :: Bool
, expandSynonyms :: Bool
, colors :: ColorScheme
, nice :: Nice
, prec :: Prec
, ranked :: TvScheme
, fullNames :: Bool
should not really belong here . Contains link bases for documentation generation ( see Syntax . Colorize )
, htmlBases :: [(String,String)]
, htmlCss :: String
, htmlJs :: String
, coreIface :: Bool
, verbose :: Int
}
defaultEnv :: Env
defaultEnv
= Env False False defaultColorScheme niceEmpty (precTop-1) M.empty (newName "Main") (importsEmpty) False
[]
[ ( " System . ","file:/users / / dev / koka / out / lib/ " ) ]
("scripts/" ++ programName ++ "-highlight.js")
ppScheme :: Env -> Scheme -> Doc
ppScheme env scheme
= niceType env scheme
ppSchemeEffect :: Env -> Scheme -> Doc
ppSchemeEffect env tp@(TFun [] effect result)
= ppSchemeEffect env (TForall [] [] tp)
ppSchemeEffect env (TForall vars preds (TFun [] effect result))
= color (colorType (colors env)) $
let env' = env{ nice = niceTypeExtend vars (nice env), prec = precTop } in
pparens (prec env) precQuant $ tab $
(if null vars then empty else (keyword env' "forall" <> angled (map (ppTypeVar env') vars) <> dot <> space))
<> (if null preds then empty else ((commaSep (map (ppPred env') preds)) <+> text "=> " ))
<> (if isTypeTotal effect then empty else (ppType env'{prec = precArrow-1} effect) <> space)
<> ppType env' result
ppSchemeEffect env tp
= niceType env tp
ppDeclType :: Env -> Scheme -> (Maybe [(Name,Doc)],Doc)
ppDeclType env tp
= case tp of
TForall vars preds rho
-> let env' = niceEnv env vars
(args,res) = ppDeclType env' rho
in (args, res <> ppPredicates env' preds)
TFun params effect rho
ppFun env ( text " : " ) rho
let pparams = [(name, ppType env tp) | (name,tp) <- params]
in (Just pparams, (if (isTypeTotal effect) then empty else (ppType env{prec=precArrow} effect <> space)) <> ppType env{prec=precArrow} rho)
(Nothing,ppType env tp)
instance Show DataInfo where
show = show . pretty
instance Pretty DataInfo where
pretty = ppDataInfo Type.Pretty.defaultEnv True
ppDataInfo env showBody dataInfo
= prettyDataInfo env showBody False dataInfo Private (repeat Private)
commaSep = hsep . punctuate comma
prettyDataInfo env0 showBody publicOnly info@(DataInfo datakind name kind args cons range isRec doc) vis conViss
= if (publicOnly && isPrivate vis) then empty else
(prettyComment env0 doc $
(if publicOnly then empty else ppVis env0 vis) <>
let env = env0{ nice = niceTypeExtendVars (args) (nice env0) } in
(case datakind of
Inductive -> keyword env "type"
CoInductive -> keyword env "cotype"
Retractive -> keyword env "rectype") <+>
(if isRec then keyword env "rec " else empty) <>
ppName env name <>
(if null args then empty else space <> angled (map (ppTypeVar env) args)) <>
(if kind /= kindStar then text " ::" <+> ppKind (colors env) 0 kind else empty) <+>
(if (showBody && not (null cons))
then (text "{" <$>
indent 2 (vcat (map (prettyConInfo env publicOnly) (zip conViss cons))) <$> text "}")
else empty))
prettyConInfo env publicOnly (vis,ConInfo conName ntname exists fields scheme sort range paramRanges singleton doc)
= if (publicOnly && isPrivate vis) then empty else
(prettyComment env doc $
(if publicOnly then empty else ppVis env vis) <>
keyword env "con" <+>
ppName env conName <>
(if null exists then empty else (angled (map (ppTypeVar env) exists))) <>
(if null fields
then empty
else parens (commaSep (map (ppField env) fields)))
<+> text ":" <+> ppType env scheme <> semi)
where
ppField env (name,tp)
= (if isFieldName name then empty else (ppName env name <> text ": ")) <> ppType env tp
prettyComment env comment doc
= if null comment then doc
else let cmt = if last comment == '\n' then init comment else comment
in color (colorComment (colors env)) (text cmt) <$> doc
ppVis env vis
= case vis of
Private -> keyword env "private "
Public -> keyword env "public "
instance Pretty SynInfo where
pretty info = ppSynInfo Type.Pretty.defaultEnv False True info Public
ppSynInfo env publicOnly showBody (SynInfo name kind params scheme rank range doc) vis
= if (publicOnly && isPrivate vis) then empty else
(prettyComment env doc $
(if publicOnly then empty else ppVis env vis) <>
let docs = niceTypes env (map TVar params ++ [scheme])
in (if null params then empty else angled (init docs))
<> (if kind /= kindStar then text " ::" <+> ppKind (colors env) precTop kind else empty)
<+> (if not showBody then empty else keyword env "=" <+> last docs))
<+> text "=" <+> pretty rank
type Prec = Int
precTop,precQuant,precArrow,precApp :: Prec
precTop = 0
precQuant = 1
precArrow = 2
precApp = 3
precAtom = 4
precPred = 5
pparens :: Prec -> Prec -> Doc -> Doc
pparens context prec doc
| context >= prec = parens doc
| otherwise = doc
ppType :: Env -> Type -> Doc
ppType env tp
= color (colorType (colors env)) $
case tp of
TForall vars preds t
-> let env' = env{ nice = niceTypeExtend vars (nice env), prec = precTop } in
pparens (prec env) precQuant $ tab $
else (keyword env' "forall" <> angled (map (ppTypeVar env') vars) <> space))
<> ppType env' t
<> ppPredicates env' preds
TFun args effect result
-> ppFun env (text "->") args effect result
TVar tv@(TypeVar id kind Bound)
-> case M.lookup tv (ranked env) of
( nice env ) i d
Just f -> f (prec env)
TVar tv -> ppTypeVar env tv
TCon cv -> if (typeConName cv == nameEffectEmpty && not (coreIface env))
then ppNameEx env nameTpTotal
else ppTypeCon env cv
TApp (TCon con) [_,_] | typeConName con == nameEffectExtend
-> let (ls,tl) = shallowExtractEffectExtend tp
tldoc = if (tl == effectEmpty)
then empty
else text "|" <> ppType env{prec=precTop} tl
in color (colorEffect (colors env)) $
case ls of
[] | tl == effectEmpty && not (coreIface env) -> ppNameEx env nameTpTotal
[l] | tl == effectEmpty && not (coreIface env) -> ppType env{prec=precAtom} l
_ -> text "<" <> hcat (punctuate comma (map (ppType env{prec=precTop}) ls)) <> tldoc <> text ">"
TApp (TCon con) [eff,res]
| typeConName con == nameTpDelay
-> text "$" <+>
(if (isTypeTotal eff) then empty else (ppType env{prec = precArrow} eff <> space)) <>
ppType env{prec=precArrow} res
TApp (TCon con) [arg]
| typeConName con == nameTpOptional
-> text "?" <> ppType env{prec=precTop} arg
TApp (TCon (TypeCon name _)) args | isNameTuple (name)
-> parens (commaSep (map (ppType env{prec = precTop}) args))
TApp f args -> pparens (prec env) precApp $
ppType env{ prec = precAtom } f <>
(case args of
[] -> empty
(arg:rest)
-> (if null rest then colorByKind env (getKind arg) id else id) $
angled (map (ppType env{ prec = precTop }) args))
TSyn syn args tp
-> ppSynonym env syn args (ppType env{ prec = precTop } tp)
ppPredicates env preds
= (if null preds then empty else (keyword env " with") <+> (align (hcat (map (ppPred env) preds))))
ppFun env arrow args effect result
= pparens (prec env) precArrow $
parens (hsep (punctuate comma (map (ppParam env{prec = precTop}) args))) <+>
(if (isTypeTotal effect) then arrow else (arrow <+> ppType env{prec = precArrow} effect)) <+>
ppType env{prec=precArrow} result
ppParam :: Env -> (Name,Type) -> Doc
ppParam env (name,tp)
= (if (not (nameIsNil name || isFieldName name)) then (color (colorParameter (colors env)) (ppNameEx env name <> text " : ")) else empty)
<> ppType env tp
ppName :: Env -> Name -> Doc
ppName env name
= color (colorSource (colors env)) $ ppNameEx env name
ppTypeName :: Env -> Name -> Doc
ppTypeName env name
= color (colorType (colors env)) $ ppNameEx env name
ppNameEx env name
= if (fullNames env)
then pretty name
else if (context env == qualifier name || (qualifier name == nameSystemCore && not (coreIface env)) || isNameTuple name)
then pretty (unqualify name)
pretty (importsAlias name (importsMap env))
ppPred :: Env -> Pred -> Doc
ppPred env pred
= pparens (prec env) precPred $
case pred of
PredSub tp1 tp2
-> ppType (env{prec = precPred}) tp1 <+> text "<=" <+> ppType (env{prec=precPred}) tp2
PredIFace name args
-> ppTypeName env name <> angled (map (ppType env{prec=precTop}) args)
ppSynonym :: Env -> TypeSyn -> [Tau] -> Doc -> Doc
ppSynonym env (TypeSyn name kind rank _) args tpdoc
= (if (expandSynonyms env)
then parens
else if (null args)
then id
else pparens (prec env) precApp) $
ppType env{prec=precTop} (TApp (TCon (TypeCon name kind)) args) <>
if (expandSynonyms env) then text " == " <> pretty rank <+> tpdoc else empty
ppTypeVar :: Env -> TypeVar -> Doc
ppTypeVar env (TypeVar id kind flavour)
= colorByKindDef env kind colorTypeVar $
wrapKind (showKinds env) env kind $
(case flavour of
Meta -> text "_"
Skolem -> text "$"
_ -> empty) <> nicePretty (nice env) id
ppTypeCon :: Env -> TypeCon -> Doc
ppTypeCon env (TypeCon name kind)
= colorByKindDef env kind colorTypeCon $
(if name == nameEffectEmpty then id else wrapKind (showKinds env) env kind) $
ppNameEx env name
ppTypeSyn :: Env -> TypeSyn -> Doc
ppTypeSyn env (TypeSyn name kind rank _)
= colorByKindDef env kind colorTypeCon $
wrapKind (showKinds env) env kind (ppNameEx env name)
colorByKindDef env kind defcolor doc
= colorByKind env kind (color (defcolor (colors env))) doc
colorByKind env kind defcolor doc
= case colorForKind env kind of
Just c -> color c doc
Nothing -> defcolor doc
colorForKind env kind
= if (kind == kindEffect || kind == kindLabel || kind == kindFun kindHeap kindLabel)
then Just (colorEffect (colors env))
else if (kind == kindHeap)
then Just (colorEffect (colors env))
else Nothing
wrapKind :: Bool -> Env -> Kind -> Doc -> Doc
wrapKind showKinds env kind doc
= if (showKinds && kind /= kindStar )
then color (colorKind (colors env)) $
parens (color (colorType (colors env)) doc <+> text "::" <+>
ppKind (colors env) precTop kind)
else doc
niceTypeInitial :: [TypeVar] -> Nice
niceTypeInitial ts
= niceTypeExtendVars ts niceEmpty
niceTypeExtend :: [TypeVar] -> Nice -> Nice
niceTypeExtend tvars nice
= niceTypeExtendVars tvars nice
niceTypeExtendVars ts nice
= let (es,ws) = partition (\(TypeVar id kind flavour) -> kind == kindEffect) ts
(hs,vs) = partition (\(TypeVar id kind flavour) -> kind == kindHeap) ws
nice1 = niceExtend (map typeVarId vs) niceTypeVars nice
nice2 = niceExtend (map typeVarId es) niceEffectVars nice1
nice3 = niceExtend (map typeVarId hs) niceHeapVars nice2
in nice3
niceTypeVars :: [String]
niceTypeVars
= [ [x] | x <- letters ] ++
[ ([x] ++ show i) | i <- [1..], x <- letters]
where
letters = ['a'..'d']
niceEffectVars :: [String]
niceEffectVars
= [ "e" ] ++
[ (['e'] ++ show i) | i <- [1..]]
niceHeapVars :: [String]
niceHeapVars
= [ "h" ] ++
[ (['h'] ++ show i) | i <- [1..]]
|
461aec6a1da9866c16865cf89955990039aa578978d89efc9a3352eeb7a8e1a2 | basho/riak_test | post_generate_key.erl | %% -------------------------------------------------------------------
%%
Copyright ( c ) 2012 Basho Technologies , Inc.
%%
This file is provided to you 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
%%
%% -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.
%%
%% -------------------------------------------------------------------
%% @doc Verify that POSTing to a bucket URL generates a key for an
%% object correctly.
-module(post_generate_key).
-behavior(riak_test).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
confirm() ->
Nodes = rt:build_cluster(1),
?assertEqual(ok, rt:wait_until_nodes_ready(Nodes)),
[Base|_] = rt:http_url(Nodes),
Bucket = "post_generate_key",
OldPostUrl = old_url(Base, Bucket),
NewPostUrl = new_url(Base, Bucket),
OldPostResult = post(OldPostUrl),
NewPostResult = post(NewPostUrl),
?assert(post_was_successful(OldPostResult)),
?assert(post_was_successful(NewPostResult)),
OldLocation = location_header(OldPostResult),
NewLocation = location_header(NewPostResult),
?assert(is_old_url(OldLocation)),
?assert(is_new_url(NewLocation)),
OldGetResult = get_url(Base++OldLocation),
NewGetResult = get_url(Base++NewLocation),
?assert(get_was_successful(OldGetResult)),
?assert(get_was_successful(NewGetResult)),
pass.
old_url(Base, Bucket) ->
Base++"/riak/"++Bucket.
new_url(Base, Bucket) ->
Base++"/buckets/"++Bucket++"/keys".
post(Url) ->
ibrowse:send_req(Url, [{"content-type", "text/plain"}],
post, "foobar").
get_url(Url) ->
ibrowse:send_req(Url, [{"accept", "text/plain"}], get).
post_was_successful({ok, "201", _, _}) -> true;
post_was_successful(Other) ->
lager:warning("That's not a 201: ~p", [Other]),
false.
location_header({ok, _, Headers, _}) ->
proplists:get_value("Location", Headers).
is_old_url(Url) ->
case re:run(Url, "^/riak/") of
{match, _} ->
true;
nomatch ->
lager:warning("That's not an old url: ~s", [Url]),
false
end.
is_new_url(Url) ->
case re:run(Url, "^/buckets/.*/keys/") of
{match, _} ->
true;
nomatch ->
lager:warning("That's not a new url: ~s", [Url]),
false
end.
get_was_successful({ok, "200", _, _}) -> true;
get_was_successful(Other) ->
lager:warning("That's not a 200: ~p", [Other]),
false.
| null | https://raw.githubusercontent.com/basho/riak_test/8170137b283061ba94bc85bf42575021e26c929d/tests/post_generate_key.erl | erlang | -------------------------------------------------------------------
Version 2.0 (the "License"); you may not use this file
a copy of the License at
-2.0
Unless required by applicable law or agreed to in writing,
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-------------------------------------------------------------------
@doc Verify that POSTing to a bucket URL generates a key for an
object correctly. | Copyright ( c ) 2012 Basho Technologies , Inc.
This file is provided to you under the Apache License ,
except in compliance with the License . You may obtain
software distributed under the License is distributed on an
" AS IS " BASIS , WITHOUT WARRANTIES OR CONDITIONS OF ANY
-module(post_generate_key).
-behavior(riak_test).
-export([confirm/0]).
-include_lib("eunit/include/eunit.hrl").
confirm() ->
Nodes = rt:build_cluster(1),
?assertEqual(ok, rt:wait_until_nodes_ready(Nodes)),
[Base|_] = rt:http_url(Nodes),
Bucket = "post_generate_key",
OldPostUrl = old_url(Base, Bucket),
NewPostUrl = new_url(Base, Bucket),
OldPostResult = post(OldPostUrl),
NewPostResult = post(NewPostUrl),
?assert(post_was_successful(OldPostResult)),
?assert(post_was_successful(NewPostResult)),
OldLocation = location_header(OldPostResult),
NewLocation = location_header(NewPostResult),
?assert(is_old_url(OldLocation)),
?assert(is_new_url(NewLocation)),
OldGetResult = get_url(Base++OldLocation),
NewGetResult = get_url(Base++NewLocation),
?assert(get_was_successful(OldGetResult)),
?assert(get_was_successful(NewGetResult)),
pass.
old_url(Base, Bucket) ->
Base++"/riak/"++Bucket.
new_url(Base, Bucket) ->
Base++"/buckets/"++Bucket++"/keys".
post(Url) ->
ibrowse:send_req(Url, [{"content-type", "text/plain"}],
post, "foobar").
get_url(Url) ->
ibrowse:send_req(Url, [{"accept", "text/plain"}], get).
post_was_successful({ok, "201", _, _}) -> true;
post_was_successful(Other) ->
lager:warning("That's not a 201: ~p", [Other]),
false.
location_header({ok, _, Headers, _}) ->
proplists:get_value("Location", Headers).
is_old_url(Url) ->
case re:run(Url, "^/riak/") of
{match, _} ->
true;
nomatch ->
lager:warning("That's not an old url: ~s", [Url]),
false
end.
is_new_url(Url) ->
case re:run(Url, "^/buckets/.*/keys/") of
{match, _} ->
true;
nomatch ->
lager:warning("That's not a new url: ~s", [Url]),
false
end.
get_was_successful({ok, "200", _, _}) -> true;
get_was_successful(Other) ->
lager:warning("That's not a 200: ~p", [Other]),
false.
|
72f06d6ca3eb07ad9a76d59f228ab0331c447cf393d3d973b4b57a93a3cfb269 | cj1128/sicp-review | euclid-algorithm.scm | Using Euclid 's Algorithm to computer GCD
(define (gcd a b)
(if (= b 0)
a
(gcd b (remainder a b))))
(display (gcd 3 8))
| null | https://raw.githubusercontent.com/cj1128/sicp-review/efaa2f863b7f03c51641c22d701bac97e398a050/chapter-1/1.2/euclid-algorithm.scm | scheme | Using Euclid 's Algorithm to computer GCD
(define (gcd a b)
(if (= b 0)
a
(gcd b (remainder a b))))
(display (gcd 3 8))
| |
5a107cb8c32e3b3558027d5f443c5ef17c32dc94b3eb7448ff048a473265a1c4 | dalaing/little-languages | Gen.hs | module Type.Gen where
import Text.Trifecta.Rendering (Span)
import Test.QuickCheck (Gen, Arbitrary(..), elements)
import Loc
import Type
genType :: Gen (Type l)
genType = elements [TyBool, TyNat]
genNotType :: Type l -> Gen (Type l)
genNotType TyBool = return TyNat
genNotType TyNat = return TyBool
genNotType (TyLoc _ t) = genNotType t
shrinkType :: Type l -> [Type l]
shrinkType = const []
newtype AnyType = AnyType { getAnyType :: Type Span }
deriving (Show)
instance Eq AnyType where
AnyType x == AnyType y =
stripLoc x == stripLoc y
instance Ord AnyType where
compare (AnyType x) (AnyType y) =
compare (stripLoc x) (stripLoc y)
instance Arbitrary AnyType where
arbitrary = AnyType <$> genType
shrink = fmap AnyType . shrinkType . getAnyType
| null | https://raw.githubusercontent.com/dalaing/little-languages/9f089f646a5344b8f7178700455a36a755d29b1f/code/old/multityped/nb-srcloc/src/Type/Gen.hs | haskell | module Type.Gen where
import Text.Trifecta.Rendering (Span)
import Test.QuickCheck (Gen, Arbitrary(..), elements)
import Loc
import Type
genType :: Gen (Type l)
genType = elements [TyBool, TyNat]
genNotType :: Type l -> Gen (Type l)
genNotType TyBool = return TyNat
genNotType TyNat = return TyBool
genNotType (TyLoc _ t) = genNotType t
shrinkType :: Type l -> [Type l]
shrinkType = const []
newtype AnyType = AnyType { getAnyType :: Type Span }
deriving (Show)
instance Eq AnyType where
AnyType x == AnyType y =
stripLoc x == stripLoc y
instance Ord AnyType where
compare (AnyType x) (AnyType y) =
compare (stripLoc x) (stripLoc y)
instance Arbitrary AnyType where
arbitrary = AnyType <$> genType
shrink = fmap AnyType . shrinkType . getAnyType
| |
3bf9141641a3a268110ea7e0c760f518ee7c73e0919e83ff25bc277217c57f8e | Clojure2D/clojure2d-examples | material.clj | (ns rt4.in-one-weekend.ch13.material
(:require [rt4.common :as common]
[rt4.in-one-weekend.ch13.ray :as ray]
[fastmath.vector :as v]
[fastmath.core :as m]
[fastmath.random :as r]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol MaterialProto
(scatter [material ray-in rec]))
(defrecord MaterialData [attenuation scattered])
(defrecord Lambertian [albedo]
MaterialProto
(scatter [_ _ray-in rec]
(let [scatter-direction (v/add (:normal rec) (common/random-unit-vector))]
(if (v/is-near-zero? scatter-direction)
(->MaterialData albedo (ray/ray (:p rec) (:normal rec)))
(->MaterialData albedo (ray/ray (:p rec) scatter-direction))))))
(defn lambertian [albedo] (->Lambertian albedo))
(defrecord Metal [albedo ^double fuzz]
MaterialProto
(scatter [_ ray-in rec]
(let [reflected (v/add (common/reflect (v/normalize (:direction ray-in)) (:normal rec))
(v/mult (common/random-in-unit-sphere) fuzz))]
(when (pos? (v/dot reflected (:normal rec)))
(->MaterialData albedo (ray/ray (:p rec) reflected))))))
(defn metal [albedo ^double fuzz]
(->Metal albedo (min fuzz 1.0)))
(def one (v/vec3 1.0 1.0 1.0))
(defn- reflectance
^double [^double cosine ^double ref-idx]
(let [r0 (m/sq (/ (- 1.0 ref-idx) (inc ref-idx)))]
(+ r0 (* (- 1.0 r0) (m/pow (- 1.0 cosine) 5.0)))))
(defrecord Dielectric [^double ir]
MaterialProto
(scatter [_ ray-in rec]
(let [refraction-ratio (if (:front-face? rec) (/ ir) ir)
unit-direction (v/normalize (:direction ray-in))
cos-theta (min (v/dot (v/sub unit-direction) (:normal rec)) 1.0)
sin-theta (m/sqrt (- 1.0 (* cos-theta cos-theta)))
cannot-refract? (pos? (dec (* refraction-ratio sin-theta)))
direction (if (or cannot-refract?
(> (reflectance cos-theta refraction-ratio) (r/drand)))
(common/reflect unit-direction (:normal rec))
(common/refract unit-direction (:normal rec) refraction-ratio))]
(->MaterialData one (ray/ray (:p rec) direction)))))
(defn dielectric [ir]
(->Dielectric ir))
| null | https://raw.githubusercontent.com/Clojure2D/clojure2d-examples/ead92d6f17744b91070e6308157364ad4eab8a1b/src/rt4/in_one_weekend/ch13/material.clj | clojure | (ns rt4.in-one-weekend.ch13.material
(:require [rt4.common :as common]
[rt4.in-one-weekend.ch13.ray :as ray]
[fastmath.vector :as v]
[fastmath.core :as m]
[fastmath.random :as r]))
(set! *warn-on-reflection* true)
(set! *unchecked-math* :warn-on-boxed)
(m/use-primitive-operators)
(defprotocol MaterialProto
(scatter [material ray-in rec]))
(defrecord MaterialData [attenuation scattered])
(defrecord Lambertian [albedo]
MaterialProto
(scatter [_ _ray-in rec]
(let [scatter-direction (v/add (:normal rec) (common/random-unit-vector))]
(if (v/is-near-zero? scatter-direction)
(->MaterialData albedo (ray/ray (:p rec) (:normal rec)))
(->MaterialData albedo (ray/ray (:p rec) scatter-direction))))))
(defn lambertian [albedo] (->Lambertian albedo))
(defrecord Metal [albedo ^double fuzz]
MaterialProto
(scatter [_ ray-in rec]
(let [reflected (v/add (common/reflect (v/normalize (:direction ray-in)) (:normal rec))
(v/mult (common/random-in-unit-sphere) fuzz))]
(when (pos? (v/dot reflected (:normal rec)))
(->MaterialData albedo (ray/ray (:p rec) reflected))))))
(defn metal [albedo ^double fuzz]
(->Metal albedo (min fuzz 1.0)))
(def one (v/vec3 1.0 1.0 1.0))
(defn- reflectance
^double [^double cosine ^double ref-idx]
(let [r0 (m/sq (/ (- 1.0 ref-idx) (inc ref-idx)))]
(+ r0 (* (- 1.0 r0) (m/pow (- 1.0 cosine) 5.0)))))
(defrecord Dielectric [^double ir]
MaterialProto
(scatter [_ ray-in rec]
(let [refraction-ratio (if (:front-face? rec) (/ ir) ir)
unit-direction (v/normalize (:direction ray-in))
cos-theta (min (v/dot (v/sub unit-direction) (:normal rec)) 1.0)
sin-theta (m/sqrt (- 1.0 (* cos-theta cos-theta)))
cannot-refract? (pos? (dec (* refraction-ratio sin-theta)))
direction (if (or cannot-refract?
(> (reflectance cos-theta refraction-ratio) (r/drand)))
(common/reflect unit-direction (:normal rec))
(common/refract unit-direction (:normal rec) refraction-ratio))]
(->MaterialData one (ray/ray (:p rec) direction)))))
(defn dielectric [ir]
(->Dielectric ir))
| |
55c68ba1837ae1d2cf57e919307d8b4b7ff480ba58688340a9dd9251d9969b44 | SamB/coq | command.mli | (************************************************************************)
v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
(* // * This file is distributed under the terms of the *)
(* * GNU Lesser General Public License Version 2.1 *)
(************************************************************************)
(*i $Id$ i*)
(*i*)
open Util
open Names
open Term
open Nametab
open Declare
open Library
open Libnames
open Nametab
open Tacexpr
open Vernacexpr
open Rawterm
open Topconstr
open Decl_kinds
open Redexpr
(*i*)
(*s Declaration functions. The following functions take ASTs,
transform them into [constr] and then call the corresponding
functions of [Declare]; they return an absolute reference to the
defined object *)
val get_declare_definition_hook : unit -> (Entries.definition_entry -> unit)
val set_declare_definition_hook : (Entries.definition_entry -> unit) -> unit
val definition_message : identifier -> unit
val assumption_message : identifier -> unit
val declare_definition : identifier -> definition_kind ->
local_binder list -> red_expr option -> constr_expr ->
constr_expr option -> declaration_hook -> unit
val syntax_definition : identifier -> identifier list * constr_expr ->
bool -> bool -> unit
val declare_one_assumption : coercion_flag -> assumption_kind -> Term.types ->
Impargs.manual_explicitation list ->
bool (* implicit *) -> bool (* keep *) -> bool (* inline *) -> Names.variable located -> unit
val set_declare_assumption_hook : (types -> unit) -> unit
val declare_assumption : identifier located list ->
coercion_flag -> assumption_kind -> local_binder list -> constr_expr ->
bool -> bool -> bool -> unit
val declare_interning_data : 'a * Constrintern.implicits_env ->
string * Topconstr.constr_expr * Topconstr.scope_name option -> unit
val compute_interning_datas : Environ.env ->
'a list ->
'b list ->
Term.types list ->
Impargs.manual_explicitation list list ->
'a list *
('b *
(Names.identifier list * Impargs.implicits_list *
Topconstr.scope_name option list))
list
val build_mutual : (inductive_expr * decl_notation) list -> bool -> unit
val declare_mutual_with_eliminations :
bool -> Entries.mutual_inductive_entry ->
(Impargs.manual_explicitation list *
Impargs.manual_explicitation list list) list ->
mutual_inductive
type fixpoint_kind =
| IsFixpoint of (identifier located option * recursion_order_expr) list
| IsCoFixpoint
type fixpoint_expr = {
fix_name : identifier;
fix_binders : local_binder list;
fix_body : constr_expr;
fix_type : constr_expr
}
val recursive_message : Decl_kinds.definition_object_kind ->
int array option -> Names.identifier list -> Pp.std_ppcmds
val declare_fix : bool -> Decl_kinds.definition_object_kind -> identifier ->
constr -> types -> Impargs.manual_explicitation list -> global_reference
val build_recursive : (Topconstr.fixpoint_expr * decl_notation) list -> bool -> unit
val build_corecursive : (Topconstr.cofixpoint_expr * decl_notation) list -> bool -> unit
val build_scheme : (identifier located option * scheme ) list -> unit
val build_combined_scheme : identifier located -> identifier located list -> unit
val generalize_constr_expr : constr_expr -> local_binder list -> constr_expr
val abstract_constr_expr : constr_expr -> local_binder list -> constr_expr
(* A hook start_proof calls on the type of the definition being started *)
val set_start_hook : (types -> unit) -> unit
val start_proof : identifier -> goal_kind -> types ->
?init_tac:Proof_type.tactic -> declaration_hook -> unit
val start_proof_com : goal_kind ->
(lident option * (local_binder list * constr_expr)) list ->
declaration_hook -> unit
A hook the next three functions pass to cook_proof
val set_save_hook : (Refiner.pftreestate -> unit) -> unit
(*s [save_named b] saves the current completed proof under the name it
was started; boolean [b] tells if the theorem is declared opaque; it
fails if the proof is not completed *)
val save_named : bool -> unit
(* [save_anonymous b name] behaves as [save_named] but declares the theorem
under the name [name] and respects the strength of the declaration *)
val save_anonymous : bool -> identifier -> unit
(* [save_anonymous_with_strength s b name] behaves as [save_anonymous] but
declares the theorem under the name [name] and gives it the
strength [strength] *)
val save_anonymous_with_strength : theorem_kind -> bool -> identifier -> unit
(* [admit ()] aborts the current goal and save it as an assmumption *)
val admit : unit -> unit
(* [get_current_context ()] returns the evar context and env of the
current open proof if any, otherwise returns the empty evar context
and the current global env *)
val get_current_context : unit -> Evd.evar_map * Environ.env
| null | https://raw.githubusercontent.com/SamB/coq/8f84aba9ae83a4dc43ea6e804227ae8cae8086b1/toplevel/command.mli | ocaml | **********************************************************************
// * This file is distributed under the terms of the
* GNU Lesser General Public License Version 2.1
**********************************************************************
i $Id$ i
i
i
s Declaration functions. The following functions take ASTs,
transform them into [constr] and then call the corresponding
functions of [Declare]; they return an absolute reference to the
defined object
implicit
keep
inline
A hook start_proof calls on the type of the definition being started
s [save_named b] saves the current completed proof under the name it
was started; boolean [b] tells if the theorem is declared opaque; it
fails if the proof is not completed
[save_anonymous b name] behaves as [save_named] but declares the theorem
under the name [name] and respects the strength of the declaration
[save_anonymous_with_strength s b name] behaves as [save_anonymous] but
declares the theorem under the name [name] and gives it the
strength [strength]
[admit ()] aborts the current goal and save it as an assmumption
[get_current_context ()] returns the evar context and env of the
current open proof if any, otherwise returns the empty evar context
and the current global env | v * The Coq Proof Assistant / The Coq Development Team
< O _ _ _ , , * CNRS - Ecole Polytechnique - INRIA Futurs - Universite Paris Sud
\VV/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
open Util
open Names
open Term
open Nametab
open Declare
open Library
open Libnames
open Nametab
open Tacexpr
open Vernacexpr
open Rawterm
open Topconstr
open Decl_kinds
open Redexpr
val get_declare_definition_hook : unit -> (Entries.definition_entry -> unit)
val set_declare_definition_hook : (Entries.definition_entry -> unit) -> unit
val definition_message : identifier -> unit
val assumption_message : identifier -> unit
val declare_definition : identifier -> definition_kind ->
local_binder list -> red_expr option -> constr_expr ->
constr_expr option -> declaration_hook -> unit
val syntax_definition : identifier -> identifier list * constr_expr ->
bool -> bool -> unit
val declare_one_assumption : coercion_flag -> assumption_kind -> Term.types ->
Impargs.manual_explicitation list ->
val set_declare_assumption_hook : (types -> unit) -> unit
val declare_assumption : identifier located list ->
coercion_flag -> assumption_kind -> local_binder list -> constr_expr ->
bool -> bool -> bool -> unit
val declare_interning_data : 'a * Constrintern.implicits_env ->
string * Topconstr.constr_expr * Topconstr.scope_name option -> unit
val compute_interning_datas : Environ.env ->
'a list ->
'b list ->
Term.types list ->
Impargs.manual_explicitation list list ->
'a list *
('b *
(Names.identifier list * Impargs.implicits_list *
Topconstr.scope_name option list))
list
val build_mutual : (inductive_expr * decl_notation) list -> bool -> unit
val declare_mutual_with_eliminations :
bool -> Entries.mutual_inductive_entry ->
(Impargs.manual_explicitation list *
Impargs.manual_explicitation list list) list ->
mutual_inductive
type fixpoint_kind =
| IsFixpoint of (identifier located option * recursion_order_expr) list
| IsCoFixpoint
type fixpoint_expr = {
fix_name : identifier;
fix_binders : local_binder list;
fix_body : constr_expr;
fix_type : constr_expr
}
val recursive_message : Decl_kinds.definition_object_kind ->
int array option -> Names.identifier list -> Pp.std_ppcmds
val declare_fix : bool -> Decl_kinds.definition_object_kind -> identifier ->
constr -> types -> Impargs.manual_explicitation list -> global_reference
val build_recursive : (Topconstr.fixpoint_expr * decl_notation) list -> bool -> unit
val build_corecursive : (Topconstr.cofixpoint_expr * decl_notation) list -> bool -> unit
val build_scheme : (identifier located option * scheme ) list -> unit
val build_combined_scheme : identifier located -> identifier located list -> unit
val generalize_constr_expr : constr_expr -> local_binder list -> constr_expr
val abstract_constr_expr : constr_expr -> local_binder list -> constr_expr
val set_start_hook : (types -> unit) -> unit
val start_proof : identifier -> goal_kind -> types ->
?init_tac:Proof_type.tactic -> declaration_hook -> unit
val start_proof_com : goal_kind ->
(lident option * (local_binder list * constr_expr)) list ->
declaration_hook -> unit
A hook the next three functions pass to cook_proof
val set_save_hook : (Refiner.pftreestate -> unit) -> unit
val save_named : bool -> unit
val save_anonymous : bool -> identifier -> unit
val save_anonymous_with_strength : theorem_kind -> bool -> identifier -> unit
val admit : unit -> unit
val get_current_context : unit -> Evd.evar_map * Environ.env
|
b4a24f1e6dc1ca10ef9ed483d5a490ee250183b28339d00368a07ecdf895f244 | metareflection/poof | enumitem.rkt | #lang racket/base
(provide enumparenalph)
(require racket/runtime-path
(only-in scribble/core style)
(only-in scribble/latex-properties tex-addition))
(define-runtime-path enumitem.tex "../tex/enumitem.tex")
(define enumparenalph
(style "enumparenalph" `(,(tex-addition enumitem.tex))))
| null | https://raw.githubusercontent.com/metareflection/poof/72fe1b4bce02acb86ff5f6b30274e44ac1f34296/util/enumitem.rkt | racket | #lang racket/base
(provide enumparenalph)
(require racket/runtime-path
(only-in scribble/core style)
(only-in scribble/latex-properties tex-addition))
(define-runtime-path enumitem.tex "../tex/enumitem.tex")
(define enumparenalph
(style "enumparenalph" `(,(tex-addition enumitem.tex))))
| |
c5c183297322630978ab80ab975c06dda1cd15466980216f627d2fbee68dd341 | clj-commons/seesaw | icon.clj | Copyright ( c ) , 2011 . All rights reserved .
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (-1.0.php)
; which can be found in the file epl-v10.html at the root of this
; distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.
(ns seesaw.test.icon
(:use seesaw.icon)
(:require [seesaw.graphics :as g]
[clojure.java.io :as jio])
(:use [lazytest.describe :only (describe it testing)]
[lazytest.expect :only (expect)]))
(describe icon
(it "returns nil given nil"
(nil? (icon nil)))
(it "returns its input given an Icon"
(let [i (javax.swing.ImageIcon.)]
(expect (= i (icon i)))))
(it "returns an icon given an image"
(let [image (g/buffered-image 16 16)
i (icon image)]
(expect (instance? javax.swing.ImageIcon i))
(expect (= image (.getImage i)))))
(it "returns an icon given a URL"
(let [i (icon (jio/resource "seesaw/test/examples/rss.gif"))]
(expect (instance? javax.swing.ImageIcon i))))
(it "returns an icon given a path to an icon on the classpath"
(let [i (icon "seesaw/test/examples/rss.gif")]
(expect (instance? javax.swing.ImageIcon i))))
(it "returns an icon given a File"
(let [i (icon (java.io.File. "test/seesaw/test/examples/rss.gif"))]
(expect (instance? javax.swing.ImageIcon i))))
(it "returns an icon given a i18n keyword"
(let [i (icon ::test-icon)]
(expect (instance? javax.swing.ImageIcon i)))))
| null | https://raw.githubusercontent.com/clj-commons/seesaw/4ca89d0dcdf0557d99d5fa84202b7cc6e2e92263/test/seesaw/test/icon.clj | clojure | The use and distribution terms for this software are covered by the
Eclipse Public License 1.0 (-1.0.php)
which can be found in the file epl-v10.html at the root of this
distribution.
By using this software in any fashion, you are agreeing to be bound by
the terms of this license.
You must not remove this notice, or any other, from this software. | Copyright ( c ) , 2011 . All rights reserved .
(ns seesaw.test.icon
(:use seesaw.icon)
(:require [seesaw.graphics :as g]
[clojure.java.io :as jio])
(:use [lazytest.describe :only (describe it testing)]
[lazytest.expect :only (expect)]))
(describe icon
(it "returns nil given nil"
(nil? (icon nil)))
(it "returns its input given an Icon"
(let [i (javax.swing.ImageIcon.)]
(expect (= i (icon i)))))
(it "returns an icon given an image"
(let [image (g/buffered-image 16 16)
i (icon image)]
(expect (instance? javax.swing.ImageIcon i))
(expect (= image (.getImage i)))))
(it "returns an icon given a URL"
(let [i (icon (jio/resource "seesaw/test/examples/rss.gif"))]
(expect (instance? javax.swing.ImageIcon i))))
(it "returns an icon given a path to an icon on the classpath"
(let [i (icon "seesaw/test/examples/rss.gif")]
(expect (instance? javax.swing.ImageIcon i))))
(it "returns an icon given a File"
(let [i (icon (java.io.File. "test/seesaw/test/examples/rss.gif"))]
(expect (instance? javax.swing.ImageIcon i))))
(it "returns an icon given a i18n keyword"
(let [i (icon ::test-icon)]
(expect (instance? javax.swing.ImageIcon i)))))
|
068a4b6f1c87682139e3025ba1fd805448708f3d599d5f5035e60d2b414baf60 | MaybeJustJames/zephyr | Main.hs | # LANGUAGE CPP #
module Main (main) where
import System.IO (hSetEncoding, stderr, stdout, utf8)
import qualified Test.CoreFn
import qualified Test.Eval
import Test.Hspec
import qualified Test.Lib
#ifdef TEST_CORE_LIBS
import qualified Test.CoreLib
#endif
main :: IO ()
main = do
hSetEncoding stdout utf8
hSetEncoding stderr utf8
hspec Test.CoreFn.spec
hspec Test.Eval.spec
hspec Test.Lib.spec
-- Tree shaking of core libraries is disabled by default because it's not
-- reliable.
#ifdef TEST_CORE_LIBS
hspec Test.CoreLib.spec
#endif
| null | https://raw.githubusercontent.com/MaybeJustJames/zephyr/30b6d25813592123dd4dadc34b4df4eb0d150a0b/test/Main.hs | haskell | Tree shaking of core libraries is disabled by default because it's not
reliable. | # LANGUAGE CPP #
module Main (main) where
import System.IO (hSetEncoding, stderr, stdout, utf8)
import qualified Test.CoreFn
import qualified Test.Eval
import Test.Hspec
import qualified Test.Lib
#ifdef TEST_CORE_LIBS
import qualified Test.CoreLib
#endif
main :: IO ()
main = do
hSetEncoding stdout utf8
hSetEncoding stderr utf8
hspec Test.CoreFn.spec
hspec Test.Eval.spec
hspec Test.Lib.spec
#ifdef TEST_CORE_LIBS
hspec Test.CoreLib.spec
#endif
|
38e9d2bb14d299a3009b530f4e8c34f75e5fc3ed2288e5a43feb1e11890b3bdf | Bogdanp/koyo | koyo.rkt | #lang racket/base
(require (for-label koyo
racket/base)
(for-syntax racket/base)
racket/runtime-path
racket/sandbox
scribble/example
scribble/manual)
(provide (all-from-out scribble/example
scribble/manual)
media-path
sandbox)
(define-runtime-path media-path
(build-path 'up "media"))
(define sandbox
(call-with-trusted-sandbox-configuration
(lambda ()
(parameterize ([sandbox-output 'string]
[sandbox-error-output 'string]
[sandbox-memory-limit 256])
(make-evaluator 'racket/base)))))
(void (examples #:eval sandbox (require component koyo)))
(provide
haml-form
haml-splicing-syntax-example)
(define haml-form
(defform
#:literals (unquote-splicing unless when)
(haml element ...+)
#:grammar
[(element (selector maybe-attributes element ...)
(unless cond-expr e0 e ...)
(when cond-expr e0 e ...)
&html-entity-name
,@expr
expr)
(selector :tag-name
.class-name
.class-name-1.class-name-2.class-name-n#id
:tag-name.class-name
:tag-name.class-name#id)
(maybe-attributes (code:line)
([:attribute-name maybe-expr] ...))]
"Produces an x-expression."))
(define haml-splicing-syntax-example
(examples
#:eval sandbox
#:label #f
(haml
(.content
(:ul.items
,@(for/list ([it '("a" "b" "c")])
`(li ,it)))))))
| null | https://raw.githubusercontent.com/Bogdanp/koyo/2dd096940da875085855124ef04421657f9c4581/koyo-doc/scribblings/koyo.rkt | racket | #lang racket/base
(require (for-label koyo
racket/base)
(for-syntax racket/base)
racket/runtime-path
racket/sandbox
scribble/example
scribble/manual)
(provide (all-from-out scribble/example
scribble/manual)
media-path
sandbox)
(define-runtime-path media-path
(build-path 'up "media"))
(define sandbox
(call-with-trusted-sandbox-configuration
(lambda ()
(parameterize ([sandbox-output 'string]
[sandbox-error-output 'string]
[sandbox-memory-limit 256])
(make-evaluator 'racket/base)))))
(void (examples #:eval sandbox (require component koyo)))
(provide
haml-form
haml-splicing-syntax-example)
(define haml-form
(defform
#:literals (unquote-splicing unless when)
(haml element ...+)
#:grammar
[(element (selector maybe-attributes element ...)
(unless cond-expr e0 e ...)
(when cond-expr e0 e ...)
&html-entity-name
,@expr
expr)
(selector :tag-name
.class-name
.class-name-1.class-name-2.class-name-n#id
:tag-name.class-name
:tag-name.class-name#id)
(maybe-attributes (code:line)
([:attribute-name maybe-expr] ...))]
"Produces an x-expression."))
(define haml-splicing-syntax-example
(examples
#:eval sandbox
#:label #f
(haml
(.content
(:ul.items
,@(for/list ([it '("a" "b" "c")])
`(li ,it)))))))
| |
ede380ce64dabd4b4d8721184f0f39edf77bfc25140536e8fdbbcf51a13c33de | open-company/open-company-web | label.cljs | (ns oc.web.utils.label
(:require [oc.lib.hateoas :as hateoas]
[oc.web.dispatcher :as dis]
[clojure.set :as clj-set]
[oc.web.local-settings :as ls]))
;; Labels comparison
(defn label-compare-set [label deep-check?]
(set (remove nil?
[(:slug label)
(:uuid label)
(when deep-check?
(:name label))])))
(defn compare-label
([label-a label-b] (compare-label label-a label-b false))
([label-a label-b deep-check?] (seq (clj-set/intersection (label-compare-set label-a deep-check?) (label-compare-set label-b deep-check?)))))
(defn compare-labels
([labels label] (compare-labels labels label false))
([labels label deep-check?]
(let [list-values-set (set (mapcat #(label-compare-set % deep-check?) labels))]
(seq (clj-set/intersection (label-compare-set label deep-check?) list-values-set)))))
;; Data parse
(def default-label-slug "-empty-label-slug")
(defn new-label-data
([] (new-label-data "" (:uuid (dis/org-data))))
([label-name] (new-label-data label-name (:uuid (dis/org-data))))
([label-name org-uuid]
{:name (or label-name "")
:slug default-label-slug
:org-uuid org-uuid
:uuid ""}))
(defn parse-label [label-map]
(-> label-map
(assoc :can-edit? (hateoas/link-for (:links label-map) "partial-update"))
(assoc :can-delete? (hateoas/link-for (:links label-map) "delete"))))
(defn parse-labels [labels-resp]
(->> labels-resp
:collection
:items
(mapv parse-label)))
(defn parse-entry-label [label-map]
(identity label-map))
(defn parse-entry-labels [entry-labels-data]
(mapv parse-entry-label entry-labels-data))
;; Clean
(defn clean-entry-label [label-data]
(select-keys label-data [:uuid :slug :name]))
(defn clean-entry-labels [entry-data]
(update entry-data :labels #(mapv clean-entry-label %)))
(defn clean-label [label-data]
(select-keys label-data [:uuid :slug :name :org-uuid]))
(defn clean-labels [labels-data]
(mapv clean-label labels-data))
(defn can-add-label? [labels]
(< (count labels) ls/max-entry-labels)) | null | https://raw.githubusercontent.com/open-company/open-company-web/700f751b8284d287432ba73007b104f26669be91/src/main/oc/web/utils/label.cljs | clojure | Labels comparison
Data parse
Clean | (ns oc.web.utils.label
(:require [oc.lib.hateoas :as hateoas]
[oc.web.dispatcher :as dis]
[clojure.set :as clj-set]
[oc.web.local-settings :as ls]))
(defn label-compare-set [label deep-check?]
(set (remove nil?
[(:slug label)
(:uuid label)
(when deep-check?
(:name label))])))
(defn compare-label
([label-a label-b] (compare-label label-a label-b false))
([label-a label-b deep-check?] (seq (clj-set/intersection (label-compare-set label-a deep-check?) (label-compare-set label-b deep-check?)))))
(defn compare-labels
([labels label] (compare-labels labels label false))
([labels label deep-check?]
(let [list-values-set (set (mapcat #(label-compare-set % deep-check?) labels))]
(seq (clj-set/intersection (label-compare-set label deep-check?) list-values-set)))))
(def default-label-slug "-empty-label-slug")
(defn new-label-data
([] (new-label-data "" (:uuid (dis/org-data))))
([label-name] (new-label-data label-name (:uuid (dis/org-data))))
([label-name org-uuid]
{:name (or label-name "")
:slug default-label-slug
:org-uuid org-uuid
:uuid ""}))
(defn parse-label [label-map]
(-> label-map
(assoc :can-edit? (hateoas/link-for (:links label-map) "partial-update"))
(assoc :can-delete? (hateoas/link-for (:links label-map) "delete"))))
(defn parse-labels [labels-resp]
(->> labels-resp
:collection
:items
(mapv parse-label)))
(defn parse-entry-label [label-map]
(identity label-map))
(defn parse-entry-labels [entry-labels-data]
(mapv parse-entry-label entry-labels-data))
(defn clean-entry-label [label-data]
(select-keys label-data [:uuid :slug :name]))
(defn clean-entry-labels [entry-data]
(update entry-data :labels #(mapv clean-entry-label %)))
(defn clean-label [label-data]
(select-keys label-data [:uuid :slug :name :org-uuid]))
(defn clean-labels [labels-data]
(mapv clean-label labels-data))
(defn can-add-label? [labels]
(< (count labels) ls/max-entry-labels)) |
026a07d0a9d6e2aae6b3781fc834ba9a7c3ebeebdd22d8db67d3cbfa6cffccd2 | eta-lang/eta-prelude | Alternative.hs | module Eta.Classes.Alternative
( Alternative(..) )
where
import Control.Applicative
| null | https://raw.githubusercontent.com/eta-lang/eta-prelude/e25e9aa42093e090a86d2728b0cac288a25bc52e/src/Eta/Classes/Alternative.hs | haskell | module Eta.Classes.Alternative
( Alternative(..) )
where
import Control.Applicative
| |
5f7f6b727c5faf4e5a64a8383f37ff379271d810516d3277b7e9915f4ae1aa05 | reflex-frp/reflex-native | Layout.hs | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
|Functionality for applying " Reflex . Native " layouts to views .
module Reflex.UIKit.Layout
( applyLayout
) where
import CoreGraphics (CGPoint(..), CGRect(..), CGSize(..))
import ObjC (ObjPtr, SafeObjCoerce)
import Reflex.Native (Point(..), Rect(..), Size(..), ViewLayout(..))
import UIKit.Types (MainThread, UIViewType)
import qualified UIKit.UIView as UIView
|Apply a ' ViewLayout ' to the given view . Used for both initial layout and later updates .
# INLINABLE applyLayout #
applyLayout :: SafeObjCoerce v UIViewType => ObjPtr v -> ViewLayout -> MainThread ()
applyLayout view = \ case
ViewLayout_Fixed (Rect (Point {..}) (Size {..})) -> do
UIView.setFrame view (CGRect (CGPoint _point_x _point_y) (CGSize _size_width _size_height))
| null | https://raw.githubusercontent.com/reflex-frp/reflex-native/5fb6a07845e4f7c51f97e9c8ce1a48009f341246/reflex-native-uikit/src/Reflex/UIKit/Layout.hs | haskell | # LANGUAGE FlexibleContexts #
# LANGUAGE LambdaCase #
# LANGUAGE RecordWildCards #
|Functionality for applying " Reflex . Native " layouts to views .
module Reflex.UIKit.Layout
( applyLayout
) where
import CoreGraphics (CGPoint(..), CGRect(..), CGSize(..))
import ObjC (ObjPtr, SafeObjCoerce)
import Reflex.Native (Point(..), Rect(..), Size(..), ViewLayout(..))
import UIKit.Types (MainThread, UIViewType)
import qualified UIKit.UIView as UIView
|Apply a ' ViewLayout ' to the given view . Used for both initial layout and later updates .
# INLINABLE applyLayout #
applyLayout :: SafeObjCoerce v UIViewType => ObjPtr v -> ViewLayout -> MainThread ()
applyLayout view = \ case
ViewLayout_Fixed (Rect (Point {..}) (Size {..})) -> do
UIView.setFrame view (CGRect (CGPoint _point_x _point_y) (CGSize _size_width _size_height))
| |
e81d0a68c76d2ec235ee32fd2588c4ae174c691802bf0699918331d273b4d59e | jacekschae/learn-reitit-course-files | db.clj | (ns cheffy.recipe.db
(:require [next.jdbc.sql :as sql]
[next.jdbc :as jdbc]
[clojure.string :as str]))
(defn find-all-recipes
[db uid]
(with-open [conn (jdbc/get-connection db)]
(let [public (sql/find-by-keys conn :recipe {:public true})]
(if uid
(let [drafts (sql/find-by-keys conn :recipe {:public false :uid uid})]
{:public public
:drafts drafts})
{:public public}))))
(defn insert-recipe!
[db recipe]
(sql/insert! db :recipe (assoc recipe :public false
:favorite-count 0)))
(defn find-recipe-by-id
[db recipe-id]
(with-open [conn (jdbc/get-connection db)]
(let [[recipe] (sql/find-by-keys conn :recipe {:recipe_id recipe-id})
steps (sql/find-by-keys conn :step {:recipe_id recipe-id})
ingredeints (sql/find-by-keys conn :ingredient {:recipe_id recipe-id})]
(when (seq recipe)
(assoc recipe
:recipe/steps steps
:recipe/ingredients ingredeints)))))
(defn update-recipe!
[db recipe]
(-> (sql/update! db :recipe recipe (select-keys recipe [:recipe-id]))
:next.jdbc/update-count
(pos?)))
(defn delete-recipe!
[db recipe]
(-> (sql/delete! db :recipe recipe)
:next.jdbc/update-count
(pos?)))
(defn insert-step!
[db step]
(sql/insert! db :step step))
(defn update-step!
[db step]
(-> (sql/update! db :step step (select-keys step [:step-id]))
:next.jdbc/update-count
(pos?)))
(defn delete-step!
[db step]
(-> (sql/delete! db :step step)
:next.jdbc/update-count
(pos?)))
(defn favorite-recipe!
[db {:keys [recipe-id] :as data}]
(jdbc/with-transaction [tx db]
(sql/insert! tx :recipe-favorite data (:options db))
(jdbc/execute-one! tx ["UPDATE recipe
SET favorite_count = favorite_count + 1
WHERE recipe_id = ?" recipe-id])))
(defn unfavorite-recipe!
[db {:keys [recipe-id] :as data}]
(-> (jdbc/with-transaction [tx db]
(sql/delete! tx :recipe-favorite data (:options db))
(jdbc/execute-one! tx ["UPDATE recipe
SET favorite_count = favorite_count - 1
WHERE recipe_id = ?" recipe-id]))
:next.jdbc/update-count
(pos?))) | null | https://raw.githubusercontent.com/jacekschae/learn-reitit-course-files/c13a8eb622a371ad719d3d9023f1b4eff9392e4c/increments/37-step-tests/src/cheffy/recipe/db.clj | clojure | (ns cheffy.recipe.db
(:require [next.jdbc.sql :as sql]
[next.jdbc :as jdbc]
[clojure.string :as str]))
(defn find-all-recipes
[db uid]
(with-open [conn (jdbc/get-connection db)]
(let [public (sql/find-by-keys conn :recipe {:public true})]
(if uid
(let [drafts (sql/find-by-keys conn :recipe {:public false :uid uid})]
{:public public
:drafts drafts})
{:public public}))))
(defn insert-recipe!
[db recipe]
(sql/insert! db :recipe (assoc recipe :public false
:favorite-count 0)))
(defn find-recipe-by-id
[db recipe-id]
(with-open [conn (jdbc/get-connection db)]
(let [[recipe] (sql/find-by-keys conn :recipe {:recipe_id recipe-id})
steps (sql/find-by-keys conn :step {:recipe_id recipe-id})
ingredeints (sql/find-by-keys conn :ingredient {:recipe_id recipe-id})]
(when (seq recipe)
(assoc recipe
:recipe/steps steps
:recipe/ingredients ingredeints)))))
(defn update-recipe!
[db recipe]
(-> (sql/update! db :recipe recipe (select-keys recipe [:recipe-id]))
:next.jdbc/update-count
(pos?)))
(defn delete-recipe!
[db recipe]
(-> (sql/delete! db :recipe recipe)
:next.jdbc/update-count
(pos?)))
(defn insert-step!
[db step]
(sql/insert! db :step step))
(defn update-step!
[db step]
(-> (sql/update! db :step step (select-keys step [:step-id]))
:next.jdbc/update-count
(pos?)))
(defn delete-step!
[db step]
(-> (sql/delete! db :step step)
:next.jdbc/update-count
(pos?)))
(defn favorite-recipe!
[db {:keys [recipe-id] :as data}]
(jdbc/with-transaction [tx db]
(sql/insert! tx :recipe-favorite data (:options db))
(jdbc/execute-one! tx ["UPDATE recipe
SET favorite_count = favorite_count + 1
WHERE recipe_id = ?" recipe-id])))
(defn unfavorite-recipe!
[db {:keys [recipe-id] :as data}]
(-> (jdbc/with-transaction [tx db]
(sql/delete! tx :recipe-favorite data (:options db))
(jdbc/execute-one! tx ["UPDATE recipe
SET favorite_count = favorite_count - 1
WHERE recipe_id = ?" recipe-id]))
:next.jdbc/update-count
(pos?))) | |
388034a1b7293031d294384afab20d2f33b15d1032511bd280b193d2429c6f7d | wattlebirdaz/rclref | http_api_SUITE.erl | -module(http_api_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-export([all/0, init_per_suite/1, end_per_suite/1]).
-export([http_api_test/1]).
all() ->
[http_api_test].
init_per_suite(Config) ->
application:ensure_all_started(rclref),
Names = [node1],
Ports = [30200],
Nodes = node_utils:set_up_nodes(Names, Ports, [{module, ?MODULE}]),
[{module, ?MODULE}, {names, Names}, {nodes, Nodes}, {ports, Ports} | Config].
end_per_suite(Config) ->
Nodes = ?config(nodes, Config),
node_utils:kill_nodes(Nodes),
Config.
http_api_test(Config) ->
[_Node] = ?config(nodes, Config),
[Port] = ?config(ports, Config),
HttpPort = Port + 1,
Keys = ["key--" ++ integer_to_list(Num) || Num <- lists:seq(1, 20)],
Values = ["value--" ++ integer_to_list(Num) || Num <- lists:seq(1, 20)],
URLs = [list_to_binary(":" ++ integer_to_list(HttpPort) ++ "/rclref/" ++ Key) || Key <- Keys],
% check not_found
lists:foreach(fun(URL) ->
{ok, 404, _, ClientRef} = hackney:request(get, URL, [], <<>>, []),
{ok, Response} = hackney:body(ClientRef),
404 = maps:get(<<"code">>, maps:get(<<"error">>, jsx:decode(Response))),
<<"not_found">> = maps:get(<<"reason">>, maps:get(<<"error">>, jsx:decode(Response)))
end, URLs),
% put values
lists:foreach(fun({URL, Value}) ->
{ok, 200, _, ClientRef} = hackney:request(post, URL, [], Value, []),
{ok, Response} = hackney:body(ClientRef),
200 = maps:get(<<"code">>, maps:get(<<"ok">>, jsx:decode(Response)))
end, lists:zip(URLs, Values)),
% confirm values
lists:foreach(fun({URL, Value}) ->
{ok, 200, _, ClientRef} = hackney:request(get, URL, [], <<>>, []),
{ok, Response} = hackney:body(ClientRef),
200 = maps:get(<<"code">>, maps:get(<<"ok">>, jsx:decode(Response))),
GotValues = maps:get(<<"values">>, maps:get(<<"ok">>, jsx:decode(Response))),
true = lists:all(fun(GotValue) -> list_to_binary(Value) =:= GotValue end, GotValues)
end, lists:zip(URLs, Values)),
% delete values
lists:foreach(fun(URL) ->
{ok, 200, _, ClientRef} = hackney:request(delete, URL, [], <<>>, []),
{ok, Response} = hackney:body(ClientRef),
200 = maps:get(<<"code">>, maps:get(<<"ok">>, jsx:decode(Response)))
end, URLs),
% confirm not_found
lists:foreach(fun(URL) ->
{ok, 404, _, ClientRef} = hackney:request(get, URL, [], <<>>, []),
{ok, Response} = hackney:body(ClientRef),
404 = maps:get(<<"code">>, maps:get(<<"error">>, jsx:decode(Response))),
<<"not_found">> = maps:get(<<"reason">>, maps:get(<<"error">>, jsx:decode(Response)))
end, URLs),
ok.
| null | https://raw.githubusercontent.com/wattlebirdaz/rclref/0e31857de43e3930f69d4063f79a518fe9fdbb79/test/single_node/http_api_SUITE.erl | erlang | check not_found
put values
confirm values
delete values
confirm not_found | -module(http_api_SUITE).
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-export([all/0, init_per_suite/1, end_per_suite/1]).
-export([http_api_test/1]).
all() ->
[http_api_test].
init_per_suite(Config) ->
application:ensure_all_started(rclref),
Names = [node1],
Ports = [30200],
Nodes = node_utils:set_up_nodes(Names, Ports, [{module, ?MODULE}]),
[{module, ?MODULE}, {names, Names}, {nodes, Nodes}, {ports, Ports} | Config].
end_per_suite(Config) ->
Nodes = ?config(nodes, Config),
node_utils:kill_nodes(Nodes),
Config.
http_api_test(Config) ->
[_Node] = ?config(nodes, Config),
[Port] = ?config(ports, Config),
HttpPort = Port + 1,
Keys = ["key--" ++ integer_to_list(Num) || Num <- lists:seq(1, 20)],
Values = ["value--" ++ integer_to_list(Num) || Num <- lists:seq(1, 20)],
URLs = [list_to_binary(":" ++ integer_to_list(HttpPort) ++ "/rclref/" ++ Key) || Key <- Keys],
lists:foreach(fun(URL) ->
{ok, 404, _, ClientRef} = hackney:request(get, URL, [], <<>>, []),
{ok, Response} = hackney:body(ClientRef),
404 = maps:get(<<"code">>, maps:get(<<"error">>, jsx:decode(Response))),
<<"not_found">> = maps:get(<<"reason">>, maps:get(<<"error">>, jsx:decode(Response)))
end, URLs),
lists:foreach(fun({URL, Value}) ->
{ok, 200, _, ClientRef} = hackney:request(post, URL, [], Value, []),
{ok, Response} = hackney:body(ClientRef),
200 = maps:get(<<"code">>, maps:get(<<"ok">>, jsx:decode(Response)))
end, lists:zip(URLs, Values)),
lists:foreach(fun({URL, Value}) ->
{ok, 200, _, ClientRef} = hackney:request(get, URL, [], <<>>, []),
{ok, Response} = hackney:body(ClientRef),
200 = maps:get(<<"code">>, maps:get(<<"ok">>, jsx:decode(Response))),
GotValues = maps:get(<<"values">>, maps:get(<<"ok">>, jsx:decode(Response))),
true = lists:all(fun(GotValue) -> list_to_binary(Value) =:= GotValue end, GotValues)
end, lists:zip(URLs, Values)),
lists:foreach(fun(URL) ->
{ok, 200, _, ClientRef} = hackney:request(delete, URL, [], <<>>, []),
{ok, Response} = hackney:body(ClientRef),
200 = maps:get(<<"code">>, maps:get(<<"ok">>, jsx:decode(Response)))
end, URLs),
lists:foreach(fun(URL) ->
{ok, 404, _, ClientRef} = hackney:request(get, URL, [], <<>>, []),
{ok, Response} = hackney:body(ClientRef),
404 = maps:get(<<"code">>, maps:get(<<"error">>, jsx:decode(Response))),
<<"not_found">> = maps:get(<<"reason">>, maps:get(<<"error">>, jsx:decode(Response)))
end, URLs),
ok.
|
56997210e9803842b572b1fe048cf24546a6cc5ca474011a08fa08a8913585cf | fare/lisp-interface-library | encoded-key-map.lisp | ;;;;; Functional mapping where key is encoded.
(uiop:define-package :lil/pure/encoded-key-map
(:use :closer-common-lisp
:lil/core
:lil/interface/base)
(:use-reexport
:lil/pure/map)
(:export
#:<encoded-key-map> #:<parametric-encoded-key-map>))
(in-package :lil/pure/encoded-key-map)
(define-interface <encoded-key-map>
(<encoded-key-collection> <map-foldable-from-*> <map-singleton-from-insert> <map>) ()
(:abstract))
(define-interface <parametric-encoded-key-map> (<parametric-encoded-key-collection> <encoded-key-map>) ()
(:parametric (&key base-interface key-encoder key-decoder
key-interface value-interface)
(make-interface
:base-interface base-interface
:key-interface key-interface
:value-interface value-interface
:key-encoder key-encoder
:key-decoder key-decoder)))
| null | https://raw.githubusercontent.com/fare/lisp-interface-library/ac2e0063dc65feb805f0c57715d52fda28d4dcd8/pure/encoded-key-map.lisp | lisp | Functional mapping where key is encoded. | (uiop:define-package :lil/pure/encoded-key-map
(:use :closer-common-lisp
:lil/core
:lil/interface/base)
(:use-reexport
:lil/pure/map)
(:export
#:<encoded-key-map> #:<parametric-encoded-key-map>))
(in-package :lil/pure/encoded-key-map)
(define-interface <encoded-key-map>
(<encoded-key-collection> <map-foldable-from-*> <map-singleton-from-insert> <map>) ()
(:abstract))
(define-interface <parametric-encoded-key-map> (<parametric-encoded-key-collection> <encoded-key-map>) ()
(:parametric (&key base-interface key-encoder key-decoder
key-interface value-interface)
(make-interface
:base-interface base-interface
:key-interface key-interface
:value-interface value-interface
:key-encoder key-encoder
:key-decoder key-decoder)))
|
0943c66c886c04b4cf6a4059f99ec1a518727c12381ff3e596f01efb57839a4f | rixed/ramen | RamenOrc.ml | ORC types and mapping with Ramen types .
*
* No comprehensive doc for ORC but see :
* -data-types-examples/
*
* Note : in all this private fields are not taken into account .
* This is because it is easier to deal with them in the ocaml code than the
* C++ code ( especially reading them back as ` any cheap value ` ) . This must
* therefore be wrapped in an OCaml generated code that remove / add them .
*
* No comprehensive doc for ORC but see:
* -data-types-examples/
*
* Note: in all this private fields are not taken into account.
* This is because it is easier to deal with them in the ocaml code than the
* C++ code (especially reading them back as `any cheap value`). This must
* therefore be wrapped in an OCaml generated code that remove/add them.
*)
open Batteries
open RamenHelpersNoLog
module T = RamenTypes
module DT = DessserTypes
module N = RamenName
let debug = false
$ inject
module T = RamenTypes
module T = RamenTypes
*)
type t =
| Boolean
8 bits , signed
16 bits , signed
32 bits , signed
64 bits , signed
| Float
| Double
| TimeStamp
| Date
| String
| Binary
(* It seems that precision is the number of digits and scale the number of
* those after the fractional dot: *)
| Decimal of { precision : int ; scale : int }
| VarChar of int (* max length *)
also
(* Compound types: *)
| Array of t
| UnionType of t array
| Struct of (string * t) array
| Map of (t * t)
Orc types string format use colon as a separator , and liborc accepts only
* alphanums and underscores , then optionally a dot followed by some
* alphabetic ( no nums ) . Otherwise it will throw :
* std::logic_error : Unrecognized character .
* Better replace everything that 's not alphanum by an underscore :
* alphanums and underscores, then optionally a dot followed by some
* alphabetic (no nums). Otherwise it will throw:
* std::logic_error: Unrecognized character.
* Better replace everything that's not alphanum by an underscore: *)
let print_label oc str =
String.map (fun c -> if is_alphanum c then c else '_') str |>
String.print oc
Output the schema of the type .
* Similar to * in a more civilised language .
* Similar to #L157
* in a more civilised language. *)
let rec print oc = function
| Boolean -> String.print oc "boolean"
| TinyInt -> String.print oc "tinyint"
| SmallInt -> String.print oc "smallint"
| Int -> String.print oc "int"
| BigInt -> String.print oc "bigint"
| Double -> String.print oc "double"
| Float -> String.print oc "float"
| TimeStamp -> String.print oc "timestamp"
| Date -> String.print oc "date"
| String -> String.print oc "string"
| Binary -> String.print oc "binary"
| Decimal { precision ; scale } ->
Printf.fprintf oc "decimal(%d,%d)" precision scale
| VarChar len ->
Printf.fprintf oc "varchar(%d)" len
| Char len ->
Printf.fprintf oc "char(%d)" len
| Array t ->
Printf.fprintf oc "array<%a>" print t
| UnionType ts ->
Printf.fprintf oc "uniontype<%a>"
(Array.print ~first:"" ~last:"" ~sep:"," print) ts
| Struct kts ->
Printf.fprintf oc "struct<%a>"
(Array.print ~first:"" ~last:"" ~sep:","
(fun oc (l, v) -> Printf.fprintf oc "%a:%a" print_label l print v)) kts
| Map (k, v) ->
Printf.fprintf oc "map<%a,%a>" print k print v
$ = print & ~printer : BatPervasives.identity
" double " ( BatIO.to_string print Double )
" struct < a_map : map < smallint , char(5)>,a_list : array < decimal(3,1 ) > > " \
( BatIO.to_string print \
( Struct [ | " a_map " , Map ( , Char 5 ) ; \
" a_list " , Array ( Decimal { precision=3 ; } ) | ] ) )
"double" (BatIO.to_string print Double)
"struct<a_map:map<smallint,char(5)>,a_list:array<decimal(3,1)>>" \
(BatIO.to_string print \
(Struct [| "a_map", Map (SmallInt, Char 5); \
"a_list", Array (Decimal { precision=3; scale=1 }) |]))
*)
Generate the ORC type corresponding to a Ramen type . Note that for ORC
* every value can be NULL so there is no nullability in the type .
* In the other way around that is not a conversion but a cast .
* ORC has no unsigned integer types . We could upgrade all unsigned types
* to the next bigger signed type , but that would not be very efficient for
* storing values . Also , we could not do this for uint128 as the largest
* Decimal supported must fit an int128 .
* Therefore , we encode unsigned as signed . This is no problem when Ramen
* read them back , as it always know the exact type , but could cause some
* issues when importing the files in Hive etc .
* every value can be NULL so there is no nullability in the type.
* In the other way around that is not a conversion but a cast.
* ORC has no unsigned integer types. We could upgrade all unsigned types
* to the next bigger signed type, but that would not be very efficient for
* storing values. Also, we could not do this for uint128 as the largest
* Decimal supported must fit an int128.
* Therefore, we encode unsigned as signed. This is no problem when Ramen
* read them back, as it always know the exact type, but could cause some
* issues when importing the files in Hive etc. *)
let rec of_value_type vt =
match DT.develop vt with
| DT.TChar -> TinyInt
| TFloat -> Double
| TString -> String
| TBool -> Boolean
| TI8 | TU8 -> TinyInt
| TI16 | TU16 -> SmallInt
| TI24 | TU24 | TI32 | TU32 -> Int
| TI40 | TU40 | TI48 | TU48 | TI56 | TU56 | TI64 | TU64 -> BigInt
128 bits would be 39 digits , but liborc would fail on 39 .
* It will happily store 128 bits inside its 128 bits value though .
* Not all other ORC readers might perform that well unfortunately .
* It will happily store 128 bits inside its 128 bits value though.
* Not all other ORC readers might perform that well unfortunately. *)
| TI128 | TU128 -> Decimal { precision = 38 ; scale = 0 }
| TTup ts ->
There are no tuple in ORC so we use a Struct :
Struct (
Array.mapi (fun i t ->
string_of_int i, of_value_type t.DT.typ) ts)
| TVec (_, t) | TArr t | TSet (Simple, t) ->
Array (of_value_type t.DT.typ)
| TSet _ ->
todo "RamenOrc.of_value_type for non-simple sets"
| TRec kts ->
(* Keep the order of definition but ignore private fields
* that are going to be skipped over when serializing.
* (TODO: also ignore shadowed fields): *)
Struct (
Array.filter_map (fun (k, t) ->
if N.(is_private (field k)) then None else
Some (k, of_value_type t.DT.typ)
) kts)
| TSum mns ->
UnionType (
Array.map (fun (_, mn) ->
of_value_type mn.DT.typ
) mns)
| TMap _ -> assert false (* No values of that type *)
| TUsr _ -> assert false (* Should have been developed *)
| _ -> assert false
$ = of_value_type & ~printer : BatPervasives.identity
" struct < ip : int , mask : tinyint > " \
( BatIO.to_string print ( of_value_type T.cidrv4 ) )
" struct < pas_glop : int > " \
( BatIO.to_string print ( of_value_type \
( DT.TRec [ | " pas : glop " , DT.required ( TI32 ) | ] ) ) )
"struct<ip:int,mask:tinyint>" \
(BatIO.to_string print (of_value_type T.cidrv4))
"struct<pas_glop:int>" \
(BatIO.to_string print (of_value_type \
(DT.TRec [| "pas:glop", DT.required (TI32) |])))
*)
(* Check the outmost type is not nullable: *)
let of_type mn =
assert (not mn.DT.nullable) ;
of_value_type mn.typ
Map ORC types into the C++ class used to batch this type :
let batch_type_of = function
| Boolean | TinyInt | SmallInt | Int | BigInt | Date -> "LongVectorBatch"
| Float | Double -> "DoubleVectorBatch"
| TimeStamp -> "TimestampVectorBatch"
| String | Binary | VarChar _ | Char _ -> "StringVectorBatch"
| Decimal { precision ; _ } ->
if precision <= 18 then "Decimal64VectorBatch"
else "Decimal128VectorBatch"
| Struct _ -> "StructVectorBatch"
| Array _ -> "ListVectorBatch"
| UnionType _ -> "UnionVectorBatch"
| Map _ -> "MapVectorBatch"
let batch_type_of_value_type = batch_type_of % of_value_type
let make_valid_cpp = DessserBackEndCLike.valid_identifier
let gensym =
let seq = ref 0 in
fun pref ->
incr seq ;
make_valid_cpp pref ^"_"^ string_of_int !seq
* Writing ORC files
* Writing ORC files
*)
Convert from OCaml value to a corresponding C++ value suitable for ORC :
let emit_conv_of_ocaml vt val_var oc =
let p fmt = Printf.fprintf oc fmt in
let scaled_int s =
(* Signed small integers are shifted all the way to the left: *)
p "(((intnat)Long_val(%s)) >> \
(CHAR_BIT * sizeof(intnat) - %d - 1))"
val_var s in
match DT.develop vt with
| DT.TBool ->
p "Bool_val(%s)" val_var
| TChar ->
p "Long_val(%s)" val_var
| TU8 | TU16 | TU24 ->
p "Long_val(%s)" val_var (* FIXME: should be Unsigned_long_val? *)
| TU32 ->
(* Assuming the custom val is suitably aligned: *)
p "(*(uint32_t*)Data_custom_val(%s))" val_var
| TU40 ->
p "((*(uint64_t*)Data_custom_val(%s)) >> 24)" val_var
| TU48 ->
p "((*(uint64_t*)Data_custom_val(%s)) >> 16)" val_var
| TU56 ->
p "((*(uint64_t*)Data_custom_val(%s)) >> 8)" val_var
| TU64 ->
p "(*(uint64_t*)Data_custom_val(%s))" val_var
| TU128 ->
p "(*(uint128_t*)Data_custom_val(%s))" val_var
| TI8 ->
scaled_int 8
| TI16 ->
scaled_int 16
| TI24 ->
scaled_int 24
| TI32 ->
p "(*(int32_t*)Data_custom_val(%s))" val_var
| TI40 ->
p "((*(int64_t*)Data_custom_val(%s)) >> 24)" val_var
| TI48 ->
p "((*(int64_t*)Data_custom_val(%s)) >> 16)" val_var
| TI56 ->
p "((*(int64_t*)Data_custom_val(%s)) >> 8)" val_var
| TI64 ->
p "(*(int64_t*)Data_custom_val(%s))" val_var
| TI128 ->
p "(*(int128_t*)Data_custom_val(%s))" val_var
| TFloat ->
p "Double_val(%s)" val_var
| TString ->
(* String_val return a pointer to the string, that the StringVectorBatch
* will store. Obviously, we want it to store a non-relocatable copy and
* then free it... FIXME *)
(* Note: we pass the OCaml string length. the string might be actually
* nul terminated before that, but that's not supposed to happen and
* would not cause problems other than the string appear shorter. *)
p "handler->keep_string(String_val(%s), caml_string_length(%s))"
val_var val_var
| TTup _ | TVec _ | TArr _ | TSet _ | TRec _ | TMap _ ->
(* Compound types have no values of their own *)
()
| TSum _ ->
todo "emit_conv_of_ocaml for sum types"
| TUsr _ ->
(* Should have been developed already *)
assert false
| _ ->
assert false
Convert from OCaml value to a corresponding C++ value suitable for ORC
* and write it in the vector buffer :
* and write it in the vector buffer: *)
let rec emit_store_data indent vb_var i_var vt val_var oc =
let p fmt = emit oc indent fmt in
match DT.develop vt with
| DT.TVoid -> ()
| TUsr _ -> assert false (* must have been developed *)
(* Never called on recursive types (dealt with iter_struct): *)
| TTup _ | TVec _ | TArr _ | TSet _ | TRec _ | TMap _ | TSum _ ->
assert false
| TBool | TFloat | TChar | TI8 | TU8 | TI16 | TU16 | TI24 | TU24 |
TI32 | TU32 | TI40 | TU40 | TI48 | TU48 | TI56 | TU56 | TI64 | TU64 ->
(* Most of the time we just store a single value in an array: *)
p "%s->data[%s] = %t;" vb_var i_var (emit_conv_of_ocaml vt val_var)
| TI128 ->
ORC Int128 is a custom thing which constructor will accept only a
* int16_t for the low bits , or two int64_t for high and low bits .
* Initializing from an int128_t will /silently/ cast it to a single
* int64_t and initialize the Int128 with garbage .
* int16_t for the low bits, or two int64_t for high and low bits.
* Initializing from an int128_t will /silently/ cast it to a single
* int64_t and initialize the Int128 with garbage. *)
let tmp_var = gensym "i128" in
p "int128_t const %s = %t;" tmp_var (emit_conv_of_ocaml vt val_var) ;
p "%s->values[%s] = Int128((int64_t)(%s >> 64), (int64_t)%s);"
vb_var i_var tmp_var tmp_var
| TU128 ->
let tmp_var = gensym "u128" in
p "uint128_t const %s = %t;" tmp_var (emit_conv_of_ocaml vt val_var) ;
p "%s->values[%s] = Int128((int64_t)(%s >> 64U), (int64_t)%s);"
vb_var i_var tmp_var tmp_var
| TString ->
p "assert(String_tag == Tag_val(%s));" val_var ;
p "%s->data[%s] = %t;" vb_var i_var (emit_conv_of_ocaml vt val_var) ;
p "%s->length[%s] = caml_string_length(%s);" vb_var i_var val_var
| _ -> assert false
From the writers we need only two functions :
*
* The first one to " register interest " in a ORC files writer for a given
* ORC type . That one only need to return a handle with all appropriate
* information but must not perform any file opening or anything , as we
* do not know yet if anything will actually be ever written .
*
* And the second function required by the worker is one to write a single
* message . That one must create the file when required , flush a batch when
* required , close the file etc , in addition to actually converting the
* ocaml representation of the output tuple into an ORC value and write it
* in the many involved vector batches .
*
* The first one to "register interest" in a ORC files writer for a given
* ORC type. That one only need to return a handle with all appropriate
* information but must not perform any file opening or anything, as we
* do not know yet if anything will actually be ever written.
*
* And the second function required by the worker is one to write a single
* message. That one must create the file when required, flush a batch when
* required, close the file etc, in addition to actually converting the
* ocaml representation of the output tuple into an ORC value and write it
* in the many involved vector batches. *)
(* Cast [batch_var] into a vector for the given type, named vb: *)
let emit_get_vb indent vb_var rtyp batch_var oc =
let p fmt = emit oc indent fmt in
let btyp = batch_type_of_value_type rtyp.DT.typ in
p "%s *%s = dynamic_cast<%s *>(%s);" btyp vb_var btyp batch_var
Write a single OCaml value [ val_var ] of the given RamenType [ rtyp ] into the
* ColumnVectorBatch [ batch_var ] .
* Note : [ field_name ] is for debug print only .
* ColumnVectorBatch [batch_var].
* Note: [field_name] is for debug print only. *)
let rec emit_add_value_to_batch
indent depth val_var batch_var i_var rtyp field_name oc =
let p fmt = Printf.fprintf oc ("%s"^^fmt^^"\n") (indent_of indent) in
let add_to_batch indent rtyp val_var =
let p fmt = Printf.fprintf oc ("%s"^^fmt^^"\n") (indent_of indent) in
let iter_struct tuple_with_1_element kts =
Enum.fold (fun (oi, xi) (k, t) ->
(* Skip over private fields.
* TODO: also skip over shadowed fields! *)
if N.(is_private (field k)) then
oi, xi + 1
else (
p "{ /* Structure/Tuple item %s */" k ;
let btyp = batch_type_of_value_type t.DT.typ in
let arr_item = gensym "arr_item" in
p " %s *%s = dynamic_cast<%s *>(%s->fields[%d]);"
btyp arr_item btyp batch_var oi ;
let val_var =
Option.map (fun v ->
(* OCaml has no such tuples. Value is then unboxed. *)
if tuple_with_1_element then v
else Printf.sprintf "Field(%s, %d)" v xi
) val_var
and field_name =
if field_name = "" then k else field_name ^"."^ k
and i_var =
Printf.sprintf "%s->numElements" arr_item in
emit_add_value_to_batch
(indent + 1) (depth + 1) val_var arr_item i_var t field_name oc ;
p "}" ;
oi + 1, xi + 1
)
) (0, 0) kts |> ignore
in
match DT.develop rtyp.DT.typ with
| DT.TVoid ->
p "/* Skip unit value */"
| TBool | TChar | TFloat | TString |
TU8 | TU16 | TU24 | TU32 | TU40 | TU48 | TU56 | TU64 | TU128 |
TI8 | TI16 | TI24 | TI32 | TI40 | TI48 | TI56 | TI64 | TI128 ->
Option.may (fun v ->
p "/* Write the value for %s (of type %a) */"
(if field_name <> "" then field_name else "root value")
DT.print_mn rtyp ;
emit_store_data
indent batch_var i_var rtyp.DT.typ v oc
) val_var
| TTup ts ->
Array.enum ts |>
Enum.mapi (fun i t -> string_of_int i, t) |>
iter_struct (Array.length ts = 1)
| TRec kts ->
Array.enum kts |>
iter_struct (Array.length kts = 1)
| TArr t | TSet (_, t) | TVec (_, t) ->
Regardless of [ t ] , we treat a list as a " scalar " because
* that 's how it looks like for ORC : each new list value is
* added to the [ offsets ] vector , while the list items are on
* the side pushed to the global [ elements ] vector - batch .
* that's how it looks like for ORC: each new list value is
* added to the [offsets] vector, while the list items are on
* the side pushed to the global [elements] vector-batch. *)
Option.may (fun v ->
p "/* Write the values for %s (of type %a) */"
(if field_name <> "" then field_name else "root value")
DT.print_mn t ;
let vb = gensym "vb" in
emit_get_vb
indent vb t (batch_var ^"->elements.get()") oc ;
let bi_lst = gensym "bi_lst" in
p "uint64_t const %s = %s->numElements;" bi_lst vb ;
(* FIXME: handle arrays of unboxed values *)
let idx_var = gensym "idx" in
p "unsigned %s;" idx_var ;
p "for (%s = 0; %s < Wosize_val(%s); %s++) {"
idx_var idx_var v idx_var ;
let v_lst = gensym "v_lst" in
p " value %s = Field(%s, %s);" v_lst v idx_var ;
emit_add_value_to_batch
(indent + 1) 0 (Some v_lst) vb (bi_lst ^"+"^ idx_var) t
(field_name ^".elmt") oc ;
p "}"
) val_var ;
(* Regardless of the value being NULL or not, when we have a
* list we must initialize the offsets value. *)
let nb_vals =
match val_var with
| None -> "0"
| Some v -> Printf.sprintf "Wosize_val(%s)" v in
p "%s->offsets[%s + 1] = %s->offsets[%s] + %s;"
batch_var i_var batch_var i_var nb_vals ;
if debug then (
p "cerr << \"%s.offsets[\" << %s << \"+1]=\"" field_name i_var ;
p " << %s->offsets[%s + 1] << \"\\n\";" batch_var i_var)
| TSum mns ->
Unions : we have many children and we have to fill them independently .
* Then in the union itself the [ tags ] array that we must fill with the
* tag for that row , as well as the [ offsets ] array where to put the
* offset in the children of the current row because liborc is a bit
* lazy .
* Then in the union itself the [tags] array that we must fill with the
* tag for that row, as well as the [offsets] array where to put the
* offset in the children of the current row because liborc is a bit
* lazy. *)
Option.may (fun v ->
p "switch (Tag_val(%s)) {" v ;
Array.iteri (fun i (cstr_name, mn) ->
p "case %d: { /* %s */" i cstr_name ;
let vbtyp = batch_type_of_value_type mn.DT.typ in
let vbs = gensym cstr_name in
p " %s *%s = dynamic_cast<%s *>(%s->children[%d]);"
vbtyp vbs vbtyp batch_var i ;
p " %s->tags[%s] = %d;" batch_var i_var i ;
p " %s->offsets[%s] = %s->numElements;" batch_var i_var vbs ;
let i_var = Printf.sprintf "%s->numElements" vbs in
let v_cstr = gensym "v_cstr" in
p " value %s = Field(%s, 0);" v_cstr v ;
emit_add_value_to_batch
(indent + 1) (depth + 1) (Some v_cstr) vbs i_var mn
(field_name ^"."^ cstr_name) oc ;
p " break;" ;
p "}"
) mns ;
p "default: assert(false);" ;
p "}"
) val_var
| TMap _ -> assert false (* No values of that type *)
| _ -> assert false
in
(match val_var with
| Some v when rtyp.DT.nullable ->
(* Only generate that code in the "not null" branches: *)
p "if (Is_block(%s)) { /* Not null */" v ;
The first non const constructor is " NotNull of ... " :
let non_null = gensym "non_null" in
p " value %s = Field(%s, 0);" non_null v ;
let rtyp' = { rtyp with nullable = false } in
add_to_batch (indent + 1) rtyp' (Some non_null) ;
p "} else { /* Null */" ;
liborc initializes hasNulls to false and notNull to all ones :
if debug then
p " cerr << \"%s[\" << %s << \"] is null\\n\";"
field_name i_var ;
p " %s->hasNulls = true;" batch_var ;
p " %s->notNull[%s] = 0;" batch_var i_var ;
add_to_batch (indent + 1) rtyp None ;
p "}"
| _ ->
if val_var = None then (
(* A field above us was null. We have to set all subfields to null. *)
if debug then
p "cerr << \"%s[\" << %s << \"] is null\\n\";"
field_name i_var ;
p "%s->hasNulls = true;" batch_var ;
p "%s->notNull[%s] = 0;" batch_var i_var
) ;
add_to_batch indent rtyp val_var
) ;
Also increase :
p "%s->numElements++;" batch_var ;
if debug then
p "cerr << \"%s->numElements=\" << %s->numElements << \"\\n\";"
field_name batch_var
Generate an OCaml callable function named [ func_name ] that receives a
* " handler " and an OCaml value of a given type [ rtyp ] and batch it .
* Notice that we want the handler created with the fname and type , but
* without creating a file nor a batch before values are actually added .
* "handler" and an OCaml value of a given type [rtyp] and batch it.
* Notice that we want the handler created with the fname and type, but
* without creating a file nor a batch before values are actually added. *)
let emit_write_value func_name rtyp oc =
let p fmt = emit oc 0 fmt in
p "extern \"C\" CAMLprim value %s(" func_name ;
p " value hder_, value v_, value start_, value stop_)" ;
p "{" ;
p " CAMLparam4(hder_, v_, start_, stop_);" ;
p " OrcHandler *handler = Handler_val(hder_);" ;
p " if (! handler->writer) handler->start_write();" ;
emit_get_vb 1 "root" rtyp "handler->batch.get()" oc ;
emit_add_value_to_batch
1 0 (Some "v_") "root" "root->numElements" rtyp "" oc ;
p " if (root->numElements >= root->capacity) {" ;
p " handler->flush_batch(true);" ; (* might destroy the writer... *)
p " root->numElements = 0;" ; (* ... but not the batch! *)
p " }" ;
p " // Since we survived, update this file timestamps:" ;
p " double start = Double_val(start_);" ;
p " double stop = Double_val(stop_);" ;
p " if (start < handler->start) handler->start = start;" ;
p " if (stop > handler->stop) handler->stop = stop;" ;
p " CAMLreturn(Val_unit);" ;
p "}"
(* ...where flush_batch check for handle->num_batches and close the file and
* reset handler->ri when the limit is reached. *)
* Reading ORC files
* Reading ORC files
*)
Emits the code to read row [ row_var ] ( an uint64_t ) from [ batch_var ] ( a
* pointer to a ColumnVectorBatch ) , that 's of RamenTypes.t [ rtyp ] .
* The result must be set in the ( uninitialized ) value [ res_var ] .
* [ depth ] is the recursion depth ( ie . indent + const ) that gives us the
* name of the OCaml temp value we can use .
* pointer to a ColumnVectorBatch), that's of RamenTypes.t [rtyp].
* The result must be set in the (uninitialized) value [res_var].
* [depth] is the recursion depth (ie. indent + const) that gives us the
* name of the OCaml temp value we can use. *)
let rec emit_read_value_from_batch
indent depth orig_batch_var row_var res_var rtyp oc =
let p fmt = emit oc indent fmt in
let tmp_var = "tmp" ^ string_of_int depth in
(* Start with casting the batch to the proper type corresponding to [rtyp]
* structure: *)
let batch_var = gensym "batch" in
emit_get_vb indent batch_var rtyp orig_batch_var oc ;
let emit_read_nonnull indent =
let p fmt = emit oc indent fmt in
let emit_read_array t len_var =
p "%s = caml_alloc(%s, 0);" res_var len_var ;
let idx_var = gensym "idx" in
p "for (uint64_t %s = 0; %s < %s; %s++) {"
idx_var idx_var len_var idx_var ;
let elmts_var = batch_var ^"->elements.get()" in
let elmt_idx_var = gensym "row" in
p " uint64_t %s = %s->offsets[%s] + %s;"
elmt_idx_var batch_var row_var idx_var ;
emit_read_value_from_batch
(indent + 1) (depth + 1) elmts_var elmt_idx_var tmp_var t oc ;
p " caml_modify(&Field(%s, %s), %s);" res_var idx_var tmp_var ;
p "}"
and emit_read_boxed ops custom_sz =
(* See READ_BOXED in ringbuf/wrapper.c *)
p "%s = caml_alloc_custom(&%s, %d, 0, 1);" res_var ops custom_sz ;
p "memcpy(Data_custom_val(%s), &%s->data[%s], %d);"
res_var batch_var row_var custom_sz
and emit_read_boxed64_signed width =
Makes a signed integer between 32 and 64 bits wide from a scaled
* down int64_t ( stored in a LongVectorBatch as an int64_t already ):
* down int64_t (stored in a LongVectorBatch as an int64_t already): *)
p "%s = caml_alloc_custom(&caml_int64_ops, 8, 0, 1);" res_var ;
p "*(int64_t *)Data_custom_val(%s) = %s->data[%s] << %d;"
res_var batch_var row_var (64 - width)
and emit_read_boxed64_unsigned width =
(* Same as above, with unsigned ints: *)
p "%s = caml_alloc_custom(&uint64_ops, 8, 0, 1);" res_var ;
p "*(uint64_t *)Data_custom_val(%s) = ((uint64_t)%s->data[%s]) << %d;"
res_var batch_var row_var (64 - width)
and emit_read_unboxed_signed shift =
See in ringbuf / wrapper.c , remembering than i8 and
* i16 are normal ints shifted all the way to the left .
* i16 are normal ints shifted all the way to the left. *)
p "%s = Val_long((intnat)%s->data[%s] << \
(CHAR_BIT * sizeof(intnat) - %d - 1));"
res_var batch_var row_var shift
and emit_read_unboxed_unsigned typ_name =
Same as above , but we have to take care that liborc extended the sign
* of our unsigned value :
* of our unsigned value: *)
p "%s = Val_long((%s)%s->data[%s]);" res_var typ_name batch_var row_var
and emit_read_struct tuple_with_1_element kts =
For structs , we build an OCaml tuple in the same order
* as that of the ORC fields ; unless that 's a tuple with onle 1
* element , in which case we return directly the unboxed var .
* as that of the ORC fields; unless that's a tuple with onle 1
* element, in which case we return directly the unboxed var. *)
if not tuple_with_1_element then
p "%s = caml_alloc_tuple(%s->fields.size());" res_var batch_var ;
Enum.iteri (fun i (k, t) ->
p "/* Field %s */" k ;
if debug then p "cerr << \"Field %s\" << endl;" k ;
(* Use our tmp var to store the result of reading the i-th field: *)
let field_var = gensym "field" in
let field_batch_var =
Printf.sprintf "%s->fields[%d]" batch_var i in
emit_get_vb indent field_var t field_batch_var oc ;
emit_read_value_from_batch
indent (depth + 1) field_var row_var tmp_var t oc ;
if tuple_with_1_element then
p "%s = %s; // Single element tuple is unboxed" res_var tmp_var
else
p "Store_field(%s, %d, %s);" res_var i tmp_var
) kts
and emit_case tag cstr_name vt =
let iptyp = DT.required vt in
p " case %d: /* %s : %a */" tag cstr_name DT.print vt ;
p " {" ;
let val_var = gensym (make_valid_cpp cstr_name) in
let chld_var = Printf.sprintf "%s->children[%d]" batch_var tag in
emit_get_vb (indent + 3) val_var iptyp chld_var oc ;
let offs_var = Printf.sprintf "%s->offsets[%s]" batch_var row_var in
emit_read_value_from_batch
(indent + 3) (depth + 1) val_var offs_var tmp_var iptyp oc ;
p " %s = caml_alloc_small(1, %d);" res_var tag ;
p " Field(%s, 0) = %s;" res_var tmp_var ;
p " break;" ;
p " }"
and emit_default typ_name =
p " default: /* Invalid */" ;
p " {" ;
p " cerr << \"Invalid tag for %s: \" << %s->tags[%s] << \"\\n\";"
typ_name batch_var row_var ;
p " assert(false);" ; (* TODO: raise an OCaml exception *)
p " break;" ;
p " }"
and emit_read_i128 signed =
p "%s = caml_alloc_custom(&%s, 16, 0, 1);"
res_var (if signed then "int128_ops" else "uint128_ops") ;
let i128_var = gensym "i128" and i_var = gensym "i128" in
p "Int128 *%s = &%s->values[%s];" i128_var batch_var row_var ;
let std_typ = if signed then "int128_t" else "uint128_t" in
p "%s const %s =" std_typ i_var ;
p " ((%s)%s->getHighBits() << 64%s) | (%s->getLowBits());"
std_typ i128_var (if signed then "U" else "") i128_var ;
p "memcpy(Data_custom_val(%s), &%s, 16);" res_var i_var
in
match DT.develop rtyp.DT.typ with
| DT.TVoid -> ()
| TI8 -> emit_read_unboxed_signed 8
| TI16 -> emit_read_unboxed_signed 16
| TI24 -> emit_read_unboxed_signed 24
| TI32 -> emit_read_boxed "caml_int32_ops" 4
| TI40 -> emit_read_boxed64_signed 40
| TI48 -> emit_read_boxed64_signed 48
| TI56 -> emit_read_boxed64_signed 56
| TI64 -> emit_read_boxed "caml_int64_ops" 8
| TU8 -> emit_read_unboxed_unsigned "uint8_t"
| TU16 -> emit_read_unboxed_unsigned "uint16_t"
| TU24 -> emit_read_unboxed_unsigned "uint32_t"
| TU32 -> emit_read_boxed "uint32_ops" 4
| TU40 -> emit_read_boxed64_unsigned 40
| TU48 -> emit_read_boxed64_unsigned 48
| TU56 -> emit_read_boxed64_unsigned 56
| TU64 -> emit_read_boxed "uint64_ops" 8
| TI128 -> emit_read_i128 true
| TU128 -> emit_read_i128 false
| TBool ->
p "%s = Val_bool(%s->data[%s]);" res_var batch_var row_var
| TChar -> emit_read_unboxed_unsigned "uint8_t"
| TFloat ->
p "%s = caml_copy_double(%s->data[%s]);" res_var batch_var row_var
| TString ->
p "%s = caml_alloc_initialized_string(%s->length[%s], %s->data[%s]);"
res_var batch_var row_var batch_var row_var
| TSum mns as typ ->
(* Cf. emit_store_data for a description of the encoding *)
p "switch (%s->tags[%s]) {" batch_var row_var ;
Array.iteri (fun i (cstr_name, mn) ->
let vt = DT.develop mn.DT.typ in
emit_case i cstr_name vt
) mns ;
emit_default (DT.to_string typ) ;
p "}"
| TArr t ->
(* The [elements] field will have all list items concatenated and
* the [offsets] data buffer at row [row_var] will have the row
* number of the starting element.
* We can therefore get the size of that list, alloc an array for
* [res_var] and then read each of the value into it (recursing). *)
let len_var = gensym "len" in
(* It seems that the offsets of the last+1 element is set to the
* end of the elements, so this works also for the last element: *)
p "int64_t %s =" len_var ;
p " %s->offsets[%s + 1] - %s->offsets[%s];"
batch_var row_var batch_var row_var ;
p "if (%s < 0) {" len_var ;
p " cerr << \"Invalid list of \" << %s << \" entries at row \" << %s"
len_var row_var ;
p " << \"(offsets are \" << %s->offsets[%s]"
batch_var row_var ;
p " << \" and then \" << %s->offsets[%s + 1] << \")\\n\";"
batch_var row_var ;
(* TODO: raise an OCaml exception instead *)
p " assert(false);" ;
p "}" ;
emit_read_array t ("((uint64_t)"^ len_var ^")") ;
| TVec (d, t) ->
emit_read_array t (string_of_int d)
| TTup ts ->
Array.enum ts |>
Enum.mapi (fun i t -> string_of_int i, t) |>
emit_read_struct (Array.length ts = 1)
| TRec kts ->
Array.enum kts //
(fun (k, _) -> not N.(is_private (field k))) |>
emit_read_struct (Array.length kts = 1)
| TMap _ -> assert false (* No values of that type *)
| TSet _ -> assert false (* No values of that type *)
| _ -> assert false
in
(* If the type is nullable, check the null column (we can do this even
* before getting the proper column vector. Convention: if we have no
* notNull buffer then that means we have no nulls (it is assumed that
* NULLs are rare in the wild): *)
if rtyp.DT.nullable then (
p "if (%s->hasNulls && !%s->notNull[%s]) {"
orig_batch_var orig_batch_var row_var ;
p " %s = Val_long(0); /* Null */" res_var ;
p "} else {" ;
emit_read_nonnull (indent + 1) ;
We must wrap res into a NotNull block ( tag 0 ) . Since we are back
* from emit_read_nonnull we are free to reuse our tmp value :
* from emit_read_nonnull we are free to reuse our tmp value: *)
p " %s = caml_alloc_small(1, 0);" tmp_var ;
p " Field(%s, 0) = %s;" tmp_var res_var ;
p " %s = %s;" res_var tmp_var ;
p "}"
) else (
(* Value is not nullable *)
emit_read_nonnull indent
)
(* Generate an OCaml callable function named [func_name] that receive a
* file name, a batch size and an OCaml callback and read that file, calling
* back OCaml code with each row as an OCaml value: *)
let emit_read_values func_name rtyp oc =
let p fmt = emit oc 0 fmt in
According to dessser , depth 0 is flat scalars :
let max_depth = DT.(depth ~opaque_user_type:false rtyp.typ) + 1 in
p "extern \"C\" value %s(value path_, value batch_sz_, value cb_)" func_name ;
p "{" ;
p " CAMLparam3(path_, batch_sz_, cb_);" ;
p " CAMLlocal1(res);" ;
let rec localN n =
if n < max_depth then
let c = min 5 (max_depth - n) in
p " CAMLlocal%d(%a);" c
(Enum.print ~sep:", " (fun oc n -> Printf.fprintf oc "tmp%d" n))
(Enum.range n ~until:(n + c - 1)) ;
localN (n + c) in
localN 0 ;
p " char const *path = String_val(path_);" ;
p " unsigned batch_sz = Long_val(batch_sz_);" ;
p " unique_ptr<InputStream> in_file = readLocalFile(path);" ;
p " ReaderOptions options;" ;
p " unique_ptr<Reader> reader = createReader(move(in_file), options);" ;
p " RowReaderOptions row_options;" ;
p " unique_ptr<RowReader> row_reader =" ;
p " reader->createRowReader(row_options);" ;
p " unique_ptr<ColumnVectorBatch> batch =" ;
p " row_reader->createRowBatch(batch_sz);" ;
p " unsigned num_lines = 0;" ;
p " unsigned num_errors = 0;" ;
p " while (row_reader->next(*batch)) {" ;
p " for (uint64_t row = 0; row < batch->numElements; row++) {" ;
emit_read_value_from_batch 3 0 "batch.get()" "row" "res" rtyp oc ;
p " res = caml_callback_exn(cb_, res);" ;
p " if (Is_exception_result(res)) {" ;
p " res = Extract_exception(res);" ;
p " // Print only the first 10 such exceptions:" ;
p " if (num_errors++ < 10) {" ;
p " cerr << \"Exception while reading ORC file \" << path" ;
p " << \": to_be_printed\\n\";" ;
p " }" ;
p " }" ;
p " num_lines++;" ;
p " }" ;
p " }" ;
p " // Return the number of lines and errors:" ;
p " res = caml_alloc(2, 0);" ;
p " Store_field(res, 0, Val_long(num_lines));" ;
p " Store_field(res, 1, Val_long(num_errors));" ;
p " CAMLreturn(res);" ;
p "}"
let emit_intro oc =
let p fmt = emit oc 0 fmt in
p "/* This code is automatically generated. Edition is futile. */" ;
p "#include <cassert>" ;
p "#include <orc/OrcFile.hh>" ;
p "extern \"C\" {" ;
p "# include <limits.h> /* CHAR_BIT */" ;
p "# include <caml/mlvalues.h>" ;
p "# include <caml/memory.h>" ;
p "# include <caml/alloc.h>" ;
p "# include <caml/custom.h>" ;
p "# include <caml/callback.h>" ;
p "extern struct custom_operations uint128_ops;" ;
p "extern struct custom_operations uint64_ops;" ;
p "extern struct custom_operations uint32_ops;" ;
p "extern struct custom_operations int128_ops;" ;
p "extern struct custom_operations caml_int64_ops;" ;
p "extern struct custom_operations caml_int32_ops;" ;
p "}" ;
p "typedef __int128_t int128_t;" ;
p "typedef __uint128_t uint128_t;" ;
p "using namespace std;" ;
p "using namespace orc;" ;
p "" ;
p "class OrcHandler {" ;
p " unique_ptr<Type> type;" ;
p " string fname;" ;
p " bool const with_index;" ;
p " unsigned const batch_size;" ;
p " unsigned const max_batches;" ;
p " unsigned num_batches;" ;
p " bool archive;" ;
p " std::vector<char> strs;" ;
p " public:" ;
p " OrcHandler(string schema, string fn, bool with_index, unsigned bsz, unsigned mb, bool arc);" ;
p " ~OrcHandler();" ;
p " void start_write();" ;
p " void flush_batch(bool);" ;
p " char *keep_string(char const *, size_t);" ;
p " unique_ptr<OutputStream> outStream;" ;
p " unique_ptr<Writer> writer;" ;
p " unique_ptr<ColumnVectorBatch> batch;" ;
p " double start, stop;" ;
p "};" ;
p "" ;
p "#define Handler_val(v) (*((class OrcHandler **)Data_custom_val(v)))" ;
p ""
let emit_outro oc =
ignore oc
| null | https://raw.githubusercontent.com/rixed/ramen/e9f94e4f4d0935844fc7f6df63a75462c295d9e9/src/RamenOrc.ml | ocaml | It seems that precision is the number of digits and scale the number of
* those after the fractional dot:
max length
Compound types:
Keep the order of definition but ignore private fields
* that are going to be skipped over when serializing.
* (TODO: also ignore shadowed fields):
No values of that type
Should have been developed
Check the outmost type is not nullable:
Signed small integers are shifted all the way to the left:
FIXME: should be Unsigned_long_val?
Assuming the custom val is suitably aligned:
String_val return a pointer to the string, that the StringVectorBatch
* will store. Obviously, we want it to store a non-relocatable copy and
* then free it... FIXME
Note: we pass the OCaml string length. the string might be actually
* nul terminated before that, but that's not supposed to happen and
* would not cause problems other than the string appear shorter.
Compound types have no values of their own
Should have been developed already
must have been developed
Never called on recursive types (dealt with iter_struct):
Most of the time we just store a single value in an array:
Cast [batch_var] into a vector for the given type, named vb:
Skip over private fields.
* TODO: also skip over shadowed fields!
OCaml has no such tuples. Value is then unboxed.
FIXME: handle arrays of unboxed values
Regardless of the value being NULL or not, when we have a
* list we must initialize the offsets value.
No values of that type
Only generate that code in the "not null" branches:
A field above us was null. We have to set all subfields to null.
might destroy the writer...
... but not the batch!
...where flush_batch check for handle->num_batches and close the file and
* reset handler->ri when the limit is reached.
Start with casting the batch to the proper type corresponding to [rtyp]
* structure:
See READ_BOXED in ringbuf/wrapper.c
Same as above, with unsigned ints:
Use our tmp var to store the result of reading the i-th field:
TODO: raise an OCaml exception
Cf. emit_store_data for a description of the encoding
The [elements] field will have all list items concatenated and
* the [offsets] data buffer at row [row_var] will have the row
* number of the starting element.
* We can therefore get the size of that list, alloc an array for
* [res_var] and then read each of the value into it (recursing).
It seems that the offsets of the last+1 element is set to the
* end of the elements, so this works also for the last element:
TODO: raise an OCaml exception instead
No values of that type
No values of that type
If the type is nullable, check the null column (we can do this even
* before getting the proper column vector. Convention: if we have no
* notNull buffer then that means we have no nulls (it is assumed that
* NULLs are rare in the wild):
Value is not nullable
Generate an OCaml callable function named [func_name] that receive a
* file name, a batch size and an OCaml callback and read that file, calling
* back OCaml code with each row as an OCaml value: | ORC types and mapping with Ramen types .
*
* No comprehensive doc for ORC but see :
* -data-types-examples/
*
* Note : in all this private fields are not taken into account .
* This is because it is easier to deal with them in the ocaml code than the
* C++ code ( especially reading them back as ` any cheap value ` ) . This must
* therefore be wrapped in an OCaml generated code that remove / add them .
*
* No comprehensive doc for ORC but see:
* -data-types-examples/
*
* Note: in all this private fields are not taken into account.
* This is because it is easier to deal with them in the ocaml code than the
* C++ code (especially reading them back as `any cheap value`). This must
* therefore be wrapped in an OCaml generated code that remove/add them.
*)
open Batteries
open RamenHelpersNoLog
module T = RamenTypes
module DT = DessserTypes
module N = RamenName
let debug = false
$ inject
module T = RamenTypes
module T = RamenTypes
*)
type t =
| Boolean
8 bits , signed
16 bits , signed
32 bits , signed
64 bits , signed
| Float
| Double
| TimeStamp
| Date
| String
| Binary
| Decimal of { precision : int ; scale : int }
also
| Array of t
| UnionType of t array
| Struct of (string * t) array
| Map of (t * t)
Orc types string format use colon as a separator , and liborc accepts only
* alphanums and underscores , then optionally a dot followed by some
* alphabetic ( no nums ) . Otherwise it will throw :
* std::logic_error : Unrecognized character .
* Better replace everything that 's not alphanum by an underscore :
* alphanums and underscores, then optionally a dot followed by some
* alphabetic (no nums). Otherwise it will throw:
* std::logic_error: Unrecognized character.
* Better replace everything that's not alphanum by an underscore: *)
let print_label oc str =
String.map (fun c -> if is_alphanum c then c else '_') str |>
String.print oc
Output the schema of the type .
* Similar to * in a more civilised language .
* Similar to #L157
* in a more civilised language. *)
let rec print oc = function
| Boolean -> String.print oc "boolean"
| TinyInt -> String.print oc "tinyint"
| SmallInt -> String.print oc "smallint"
| Int -> String.print oc "int"
| BigInt -> String.print oc "bigint"
| Double -> String.print oc "double"
| Float -> String.print oc "float"
| TimeStamp -> String.print oc "timestamp"
| Date -> String.print oc "date"
| String -> String.print oc "string"
| Binary -> String.print oc "binary"
| Decimal { precision ; scale } ->
Printf.fprintf oc "decimal(%d,%d)" precision scale
| VarChar len ->
Printf.fprintf oc "varchar(%d)" len
| Char len ->
Printf.fprintf oc "char(%d)" len
| Array t ->
Printf.fprintf oc "array<%a>" print t
| UnionType ts ->
Printf.fprintf oc "uniontype<%a>"
(Array.print ~first:"" ~last:"" ~sep:"," print) ts
| Struct kts ->
Printf.fprintf oc "struct<%a>"
(Array.print ~first:"" ~last:"" ~sep:","
(fun oc (l, v) -> Printf.fprintf oc "%a:%a" print_label l print v)) kts
| Map (k, v) ->
Printf.fprintf oc "map<%a,%a>" print k print v
$ = print & ~printer : BatPervasives.identity
" double " ( BatIO.to_string print Double )
" struct < a_map : map < smallint , char(5)>,a_list : array < decimal(3,1 ) > > " \
( BatIO.to_string print \
( Struct [ | " a_map " , Map ( , Char 5 ) ; \
" a_list " , Array ( Decimal { precision=3 ; } ) | ] ) )
"double" (BatIO.to_string print Double)
"struct<a_map:map<smallint,char(5)>,a_list:array<decimal(3,1)>>" \
(BatIO.to_string print \
(Struct [| "a_map", Map (SmallInt, Char 5); \
"a_list", Array (Decimal { precision=3; scale=1 }) |]))
*)
Generate the ORC type corresponding to a Ramen type . Note that for ORC
* every value can be NULL so there is no nullability in the type .
* In the other way around that is not a conversion but a cast .
* ORC has no unsigned integer types . We could upgrade all unsigned types
* to the next bigger signed type , but that would not be very efficient for
* storing values . Also , we could not do this for uint128 as the largest
* Decimal supported must fit an int128 .
* Therefore , we encode unsigned as signed . This is no problem when Ramen
* read them back , as it always know the exact type , but could cause some
* issues when importing the files in Hive etc .
* every value can be NULL so there is no nullability in the type.
* In the other way around that is not a conversion but a cast.
* ORC has no unsigned integer types. We could upgrade all unsigned types
* to the next bigger signed type, but that would not be very efficient for
* storing values. Also, we could not do this for uint128 as the largest
* Decimal supported must fit an int128.
* Therefore, we encode unsigned as signed. This is no problem when Ramen
* read them back, as it always know the exact type, but could cause some
* issues when importing the files in Hive etc. *)
let rec of_value_type vt =
match DT.develop vt with
| DT.TChar -> TinyInt
| TFloat -> Double
| TString -> String
| TBool -> Boolean
| TI8 | TU8 -> TinyInt
| TI16 | TU16 -> SmallInt
| TI24 | TU24 | TI32 | TU32 -> Int
| TI40 | TU40 | TI48 | TU48 | TI56 | TU56 | TI64 | TU64 -> BigInt
128 bits would be 39 digits , but liborc would fail on 39 .
* It will happily store 128 bits inside its 128 bits value though .
* Not all other ORC readers might perform that well unfortunately .
* It will happily store 128 bits inside its 128 bits value though.
* Not all other ORC readers might perform that well unfortunately. *)
| TI128 | TU128 -> Decimal { precision = 38 ; scale = 0 }
| TTup ts ->
There are no tuple in ORC so we use a Struct :
Struct (
Array.mapi (fun i t ->
string_of_int i, of_value_type t.DT.typ) ts)
| TVec (_, t) | TArr t | TSet (Simple, t) ->
Array (of_value_type t.DT.typ)
| TSet _ ->
todo "RamenOrc.of_value_type for non-simple sets"
| TRec kts ->
Struct (
Array.filter_map (fun (k, t) ->
if N.(is_private (field k)) then None else
Some (k, of_value_type t.DT.typ)
) kts)
| TSum mns ->
UnionType (
Array.map (fun (_, mn) ->
of_value_type mn.DT.typ
) mns)
| _ -> assert false
$ = of_value_type & ~printer : BatPervasives.identity
" struct < ip : int , mask : tinyint > " \
( BatIO.to_string print ( of_value_type T.cidrv4 ) )
" struct < pas_glop : int > " \
( BatIO.to_string print ( of_value_type \
( DT.TRec [ | " pas : glop " , DT.required ( TI32 ) | ] ) ) )
"struct<ip:int,mask:tinyint>" \
(BatIO.to_string print (of_value_type T.cidrv4))
"struct<pas_glop:int>" \
(BatIO.to_string print (of_value_type \
(DT.TRec [| "pas:glop", DT.required (TI32) |])))
*)
let of_type mn =
assert (not mn.DT.nullable) ;
of_value_type mn.typ
Map ORC types into the C++ class used to batch this type :
let batch_type_of = function
| Boolean | TinyInt | SmallInt | Int | BigInt | Date -> "LongVectorBatch"
| Float | Double -> "DoubleVectorBatch"
| TimeStamp -> "TimestampVectorBatch"
| String | Binary | VarChar _ | Char _ -> "StringVectorBatch"
| Decimal { precision ; _ } ->
if precision <= 18 then "Decimal64VectorBatch"
else "Decimal128VectorBatch"
| Struct _ -> "StructVectorBatch"
| Array _ -> "ListVectorBatch"
| UnionType _ -> "UnionVectorBatch"
| Map _ -> "MapVectorBatch"
let batch_type_of_value_type = batch_type_of % of_value_type
let make_valid_cpp = DessserBackEndCLike.valid_identifier
let gensym =
let seq = ref 0 in
fun pref ->
incr seq ;
make_valid_cpp pref ^"_"^ string_of_int !seq
* Writing ORC files
* Writing ORC files
*)
Convert from OCaml value to a corresponding C++ value suitable for ORC :
let emit_conv_of_ocaml vt val_var oc =
let p fmt = Printf.fprintf oc fmt in
let scaled_int s =
p "(((intnat)Long_val(%s)) >> \
(CHAR_BIT * sizeof(intnat) - %d - 1))"
val_var s in
match DT.develop vt with
| DT.TBool ->
p "Bool_val(%s)" val_var
| TChar ->
p "Long_val(%s)" val_var
| TU8 | TU16 | TU24 ->
| TU32 ->
p "(*(uint32_t*)Data_custom_val(%s))" val_var
| TU40 ->
p "((*(uint64_t*)Data_custom_val(%s)) >> 24)" val_var
| TU48 ->
p "((*(uint64_t*)Data_custom_val(%s)) >> 16)" val_var
| TU56 ->
p "((*(uint64_t*)Data_custom_val(%s)) >> 8)" val_var
| TU64 ->
p "(*(uint64_t*)Data_custom_val(%s))" val_var
| TU128 ->
p "(*(uint128_t*)Data_custom_val(%s))" val_var
| TI8 ->
scaled_int 8
| TI16 ->
scaled_int 16
| TI24 ->
scaled_int 24
| TI32 ->
p "(*(int32_t*)Data_custom_val(%s))" val_var
| TI40 ->
p "((*(int64_t*)Data_custom_val(%s)) >> 24)" val_var
| TI48 ->
p "((*(int64_t*)Data_custom_val(%s)) >> 16)" val_var
| TI56 ->
p "((*(int64_t*)Data_custom_val(%s)) >> 8)" val_var
| TI64 ->
p "(*(int64_t*)Data_custom_val(%s))" val_var
| TI128 ->
p "(*(int128_t*)Data_custom_val(%s))" val_var
| TFloat ->
p "Double_val(%s)" val_var
| TString ->
p "handler->keep_string(String_val(%s), caml_string_length(%s))"
val_var val_var
| TTup _ | TVec _ | TArr _ | TSet _ | TRec _ | TMap _ ->
()
| TSum _ ->
todo "emit_conv_of_ocaml for sum types"
| TUsr _ ->
assert false
| _ ->
assert false
Convert from OCaml value to a corresponding C++ value suitable for ORC
* and write it in the vector buffer :
* and write it in the vector buffer: *)
let rec emit_store_data indent vb_var i_var vt val_var oc =
let p fmt = emit oc indent fmt in
match DT.develop vt with
| DT.TVoid -> ()
| TTup _ | TVec _ | TArr _ | TSet _ | TRec _ | TMap _ | TSum _ ->
assert false
| TBool | TFloat | TChar | TI8 | TU8 | TI16 | TU16 | TI24 | TU24 |
TI32 | TU32 | TI40 | TU40 | TI48 | TU48 | TI56 | TU56 | TI64 | TU64 ->
p "%s->data[%s] = %t;" vb_var i_var (emit_conv_of_ocaml vt val_var)
| TI128 ->
ORC Int128 is a custom thing which constructor will accept only a
* int16_t for the low bits , or two int64_t for high and low bits .
* Initializing from an int128_t will /silently/ cast it to a single
* int64_t and initialize the Int128 with garbage .
* int16_t for the low bits, or two int64_t for high and low bits.
* Initializing from an int128_t will /silently/ cast it to a single
* int64_t and initialize the Int128 with garbage. *)
let tmp_var = gensym "i128" in
p "int128_t const %s = %t;" tmp_var (emit_conv_of_ocaml vt val_var) ;
p "%s->values[%s] = Int128((int64_t)(%s >> 64), (int64_t)%s);"
vb_var i_var tmp_var tmp_var
| TU128 ->
let tmp_var = gensym "u128" in
p "uint128_t const %s = %t;" tmp_var (emit_conv_of_ocaml vt val_var) ;
p "%s->values[%s] = Int128((int64_t)(%s >> 64U), (int64_t)%s);"
vb_var i_var tmp_var tmp_var
| TString ->
p "assert(String_tag == Tag_val(%s));" val_var ;
p "%s->data[%s] = %t;" vb_var i_var (emit_conv_of_ocaml vt val_var) ;
p "%s->length[%s] = caml_string_length(%s);" vb_var i_var val_var
| _ -> assert false
From the writers we need only two functions :
*
* The first one to " register interest " in a ORC files writer for a given
* ORC type . That one only need to return a handle with all appropriate
* information but must not perform any file opening or anything , as we
* do not know yet if anything will actually be ever written .
*
* And the second function required by the worker is one to write a single
* message . That one must create the file when required , flush a batch when
* required , close the file etc , in addition to actually converting the
* ocaml representation of the output tuple into an ORC value and write it
* in the many involved vector batches .
*
* The first one to "register interest" in a ORC files writer for a given
* ORC type. That one only need to return a handle with all appropriate
* information but must not perform any file opening or anything, as we
* do not know yet if anything will actually be ever written.
*
* And the second function required by the worker is one to write a single
* message. That one must create the file when required, flush a batch when
* required, close the file etc, in addition to actually converting the
* ocaml representation of the output tuple into an ORC value and write it
* in the many involved vector batches. *)
let emit_get_vb indent vb_var rtyp batch_var oc =
let p fmt = emit oc indent fmt in
let btyp = batch_type_of_value_type rtyp.DT.typ in
p "%s *%s = dynamic_cast<%s *>(%s);" btyp vb_var btyp batch_var
Write a single OCaml value [ val_var ] of the given RamenType [ rtyp ] into the
* ColumnVectorBatch [ batch_var ] .
* Note : [ field_name ] is for debug print only .
* ColumnVectorBatch [batch_var].
* Note: [field_name] is for debug print only. *)
let rec emit_add_value_to_batch
indent depth val_var batch_var i_var rtyp field_name oc =
let p fmt = Printf.fprintf oc ("%s"^^fmt^^"\n") (indent_of indent) in
let add_to_batch indent rtyp val_var =
let p fmt = Printf.fprintf oc ("%s"^^fmt^^"\n") (indent_of indent) in
let iter_struct tuple_with_1_element kts =
Enum.fold (fun (oi, xi) (k, t) ->
if N.(is_private (field k)) then
oi, xi + 1
else (
p "{ /* Structure/Tuple item %s */" k ;
let btyp = batch_type_of_value_type t.DT.typ in
let arr_item = gensym "arr_item" in
p " %s *%s = dynamic_cast<%s *>(%s->fields[%d]);"
btyp arr_item btyp batch_var oi ;
let val_var =
Option.map (fun v ->
if tuple_with_1_element then v
else Printf.sprintf "Field(%s, %d)" v xi
) val_var
and field_name =
if field_name = "" then k else field_name ^"."^ k
and i_var =
Printf.sprintf "%s->numElements" arr_item in
emit_add_value_to_batch
(indent + 1) (depth + 1) val_var arr_item i_var t field_name oc ;
p "}" ;
oi + 1, xi + 1
)
) (0, 0) kts |> ignore
in
match DT.develop rtyp.DT.typ with
| DT.TVoid ->
p "/* Skip unit value */"
| TBool | TChar | TFloat | TString |
TU8 | TU16 | TU24 | TU32 | TU40 | TU48 | TU56 | TU64 | TU128 |
TI8 | TI16 | TI24 | TI32 | TI40 | TI48 | TI56 | TI64 | TI128 ->
Option.may (fun v ->
p "/* Write the value for %s (of type %a) */"
(if field_name <> "" then field_name else "root value")
DT.print_mn rtyp ;
emit_store_data
indent batch_var i_var rtyp.DT.typ v oc
) val_var
| TTup ts ->
Array.enum ts |>
Enum.mapi (fun i t -> string_of_int i, t) |>
iter_struct (Array.length ts = 1)
| TRec kts ->
Array.enum kts |>
iter_struct (Array.length kts = 1)
| TArr t | TSet (_, t) | TVec (_, t) ->
Regardless of [ t ] , we treat a list as a " scalar " because
* that 's how it looks like for ORC : each new list value is
* added to the [ offsets ] vector , while the list items are on
* the side pushed to the global [ elements ] vector - batch .
* that's how it looks like for ORC: each new list value is
* added to the [offsets] vector, while the list items are on
* the side pushed to the global [elements] vector-batch. *)
Option.may (fun v ->
p "/* Write the values for %s (of type %a) */"
(if field_name <> "" then field_name else "root value")
DT.print_mn t ;
let vb = gensym "vb" in
emit_get_vb
indent vb t (batch_var ^"->elements.get()") oc ;
let bi_lst = gensym "bi_lst" in
p "uint64_t const %s = %s->numElements;" bi_lst vb ;
let idx_var = gensym "idx" in
p "unsigned %s;" idx_var ;
p "for (%s = 0; %s < Wosize_val(%s); %s++) {"
idx_var idx_var v idx_var ;
let v_lst = gensym "v_lst" in
p " value %s = Field(%s, %s);" v_lst v idx_var ;
emit_add_value_to_batch
(indent + 1) 0 (Some v_lst) vb (bi_lst ^"+"^ idx_var) t
(field_name ^".elmt") oc ;
p "}"
) val_var ;
let nb_vals =
match val_var with
| None -> "0"
| Some v -> Printf.sprintf "Wosize_val(%s)" v in
p "%s->offsets[%s + 1] = %s->offsets[%s] + %s;"
batch_var i_var batch_var i_var nb_vals ;
if debug then (
p "cerr << \"%s.offsets[\" << %s << \"+1]=\"" field_name i_var ;
p " << %s->offsets[%s + 1] << \"\\n\";" batch_var i_var)
| TSum mns ->
Unions : we have many children and we have to fill them independently .
* Then in the union itself the [ tags ] array that we must fill with the
* tag for that row , as well as the [ offsets ] array where to put the
* offset in the children of the current row because liborc is a bit
* lazy .
* Then in the union itself the [tags] array that we must fill with the
* tag for that row, as well as the [offsets] array where to put the
* offset in the children of the current row because liborc is a bit
* lazy. *)
Option.may (fun v ->
p "switch (Tag_val(%s)) {" v ;
Array.iteri (fun i (cstr_name, mn) ->
p "case %d: { /* %s */" i cstr_name ;
let vbtyp = batch_type_of_value_type mn.DT.typ in
let vbs = gensym cstr_name in
p " %s *%s = dynamic_cast<%s *>(%s->children[%d]);"
vbtyp vbs vbtyp batch_var i ;
p " %s->tags[%s] = %d;" batch_var i_var i ;
p " %s->offsets[%s] = %s->numElements;" batch_var i_var vbs ;
let i_var = Printf.sprintf "%s->numElements" vbs in
let v_cstr = gensym "v_cstr" in
p " value %s = Field(%s, 0);" v_cstr v ;
emit_add_value_to_batch
(indent + 1) (depth + 1) (Some v_cstr) vbs i_var mn
(field_name ^"."^ cstr_name) oc ;
p " break;" ;
p "}"
) mns ;
p "default: assert(false);" ;
p "}"
) val_var
| _ -> assert false
in
(match val_var with
| Some v when rtyp.DT.nullable ->
p "if (Is_block(%s)) { /* Not null */" v ;
The first non const constructor is " NotNull of ... " :
let non_null = gensym "non_null" in
p " value %s = Field(%s, 0);" non_null v ;
let rtyp' = { rtyp with nullable = false } in
add_to_batch (indent + 1) rtyp' (Some non_null) ;
p "} else { /* Null */" ;
liborc initializes hasNulls to false and notNull to all ones :
if debug then
p " cerr << \"%s[\" << %s << \"] is null\\n\";"
field_name i_var ;
p " %s->hasNulls = true;" batch_var ;
p " %s->notNull[%s] = 0;" batch_var i_var ;
add_to_batch (indent + 1) rtyp None ;
p "}"
| _ ->
if val_var = None then (
if debug then
p "cerr << \"%s[\" << %s << \"] is null\\n\";"
field_name i_var ;
p "%s->hasNulls = true;" batch_var ;
p "%s->notNull[%s] = 0;" batch_var i_var
) ;
add_to_batch indent rtyp val_var
) ;
Also increase :
p "%s->numElements++;" batch_var ;
if debug then
p "cerr << \"%s->numElements=\" << %s->numElements << \"\\n\";"
field_name batch_var
Generate an OCaml callable function named [ func_name ] that receives a
* " handler " and an OCaml value of a given type [ rtyp ] and batch it .
* Notice that we want the handler created with the fname and type , but
* without creating a file nor a batch before values are actually added .
* "handler" and an OCaml value of a given type [rtyp] and batch it.
* Notice that we want the handler created with the fname and type, but
* without creating a file nor a batch before values are actually added. *)
let emit_write_value func_name rtyp oc =
let p fmt = emit oc 0 fmt in
p "extern \"C\" CAMLprim value %s(" func_name ;
p " value hder_, value v_, value start_, value stop_)" ;
p "{" ;
p " CAMLparam4(hder_, v_, start_, stop_);" ;
p " OrcHandler *handler = Handler_val(hder_);" ;
p " if (! handler->writer) handler->start_write();" ;
emit_get_vb 1 "root" rtyp "handler->batch.get()" oc ;
emit_add_value_to_batch
1 0 (Some "v_") "root" "root->numElements" rtyp "" oc ;
p " if (root->numElements >= root->capacity) {" ;
p " }" ;
p " // Since we survived, update this file timestamps:" ;
p " double start = Double_val(start_);" ;
p " double stop = Double_val(stop_);" ;
p " if (start < handler->start) handler->start = start;" ;
p " if (stop > handler->stop) handler->stop = stop;" ;
p " CAMLreturn(Val_unit);" ;
p "}"
* Reading ORC files
* Reading ORC files
*)
Emits the code to read row [ row_var ] ( an uint64_t ) from [ batch_var ] ( a
* pointer to a ColumnVectorBatch ) , that 's of RamenTypes.t [ rtyp ] .
* The result must be set in the ( uninitialized ) value [ res_var ] .
* [ depth ] is the recursion depth ( ie . indent + const ) that gives us the
* name of the OCaml temp value we can use .
* pointer to a ColumnVectorBatch), that's of RamenTypes.t [rtyp].
* The result must be set in the (uninitialized) value [res_var].
* [depth] is the recursion depth (ie. indent + const) that gives us the
* name of the OCaml temp value we can use. *)
let rec emit_read_value_from_batch
indent depth orig_batch_var row_var res_var rtyp oc =
let p fmt = emit oc indent fmt in
let tmp_var = "tmp" ^ string_of_int depth in
let batch_var = gensym "batch" in
emit_get_vb indent batch_var rtyp orig_batch_var oc ;
let emit_read_nonnull indent =
let p fmt = emit oc indent fmt in
let emit_read_array t len_var =
p "%s = caml_alloc(%s, 0);" res_var len_var ;
let idx_var = gensym "idx" in
p "for (uint64_t %s = 0; %s < %s; %s++) {"
idx_var idx_var len_var idx_var ;
let elmts_var = batch_var ^"->elements.get()" in
let elmt_idx_var = gensym "row" in
p " uint64_t %s = %s->offsets[%s] + %s;"
elmt_idx_var batch_var row_var idx_var ;
emit_read_value_from_batch
(indent + 1) (depth + 1) elmts_var elmt_idx_var tmp_var t oc ;
p " caml_modify(&Field(%s, %s), %s);" res_var idx_var tmp_var ;
p "}"
and emit_read_boxed ops custom_sz =
p "%s = caml_alloc_custom(&%s, %d, 0, 1);" res_var ops custom_sz ;
p "memcpy(Data_custom_val(%s), &%s->data[%s], %d);"
res_var batch_var row_var custom_sz
and emit_read_boxed64_signed width =
Makes a signed integer between 32 and 64 bits wide from a scaled
* down int64_t ( stored in a LongVectorBatch as an int64_t already ):
* down int64_t (stored in a LongVectorBatch as an int64_t already): *)
p "%s = caml_alloc_custom(&caml_int64_ops, 8, 0, 1);" res_var ;
p "*(int64_t *)Data_custom_val(%s) = %s->data[%s] << %d;"
res_var batch_var row_var (64 - width)
and emit_read_boxed64_unsigned width =
p "%s = caml_alloc_custom(&uint64_ops, 8, 0, 1);" res_var ;
p "*(uint64_t *)Data_custom_val(%s) = ((uint64_t)%s->data[%s]) << %d;"
res_var batch_var row_var (64 - width)
and emit_read_unboxed_signed shift =
See in ringbuf / wrapper.c , remembering than i8 and
* i16 are normal ints shifted all the way to the left .
* i16 are normal ints shifted all the way to the left. *)
p "%s = Val_long((intnat)%s->data[%s] << \
(CHAR_BIT * sizeof(intnat) - %d - 1));"
res_var batch_var row_var shift
and emit_read_unboxed_unsigned typ_name =
Same as above , but we have to take care that liborc extended the sign
* of our unsigned value :
* of our unsigned value: *)
p "%s = Val_long((%s)%s->data[%s]);" res_var typ_name batch_var row_var
and emit_read_struct tuple_with_1_element kts =
For structs , we build an OCaml tuple in the same order
* as that of the ORC fields ; unless that 's a tuple with onle 1
* element , in which case we return directly the unboxed var .
* as that of the ORC fields; unless that's a tuple with onle 1
* element, in which case we return directly the unboxed var. *)
if not tuple_with_1_element then
p "%s = caml_alloc_tuple(%s->fields.size());" res_var batch_var ;
Enum.iteri (fun i (k, t) ->
p "/* Field %s */" k ;
if debug then p "cerr << \"Field %s\" << endl;" k ;
let field_var = gensym "field" in
let field_batch_var =
Printf.sprintf "%s->fields[%d]" batch_var i in
emit_get_vb indent field_var t field_batch_var oc ;
emit_read_value_from_batch
indent (depth + 1) field_var row_var tmp_var t oc ;
if tuple_with_1_element then
p "%s = %s; // Single element tuple is unboxed" res_var tmp_var
else
p "Store_field(%s, %d, %s);" res_var i tmp_var
) kts
and emit_case tag cstr_name vt =
let iptyp = DT.required vt in
p " case %d: /* %s : %a */" tag cstr_name DT.print vt ;
p " {" ;
let val_var = gensym (make_valid_cpp cstr_name) in
let chld_var = Printf.sprintf "%s->children[%d]" batch_var tag in
emit_get_vb (indent + 3) val_var iptyp chld_var oc ;
let offs_var = Printf.sprintf "%s->offsets[%s]" batch_var row_var in
emit_read_value_from_batch
(indent + 3) (depth + 1) val_var offs_var tmp_var iptyp oc ;
p " %s = caml_alloc_small(1, %d);" res_var tag ;
p " Field(%s, 0) = %s;" res_var tmp_var ;
p " break;" ;
p " }"
and emit_default typ_name =
p " default: /* Invalid */" ;
p " {" ;
p " cerr << \"Invalid tag for %s: \" << %s->tags[%s] << \"\\n\";"
typ_name batch_var row_var ;
p " break;" ;
p " }"
and emit_read_i128 signed =
p "%s = caml_alloc_custom(&%s, 16, 0, 1);"
res_var (if signed then "int128_ops" else "uint128_ops") ;
let i128_var = gensym "i128" and i_var = gensym "i128" in
p "Int128 *%s = &%s->values[%s];" i128_var batch_var row_var ;
let std_typ = if signed then "int128_t" else "uint128_t" in
p "%s const %s =" std_typ i_var ;
p " ((%s)%s->getHighBits() << 64%s) | (%s->getLowBits());"
std_typ i128_var (if signed then "U" else "") i128_var ;
p "memcpy(Data_custom_val(%s), &%s, 16);" res_var i_var
in
match DT.develop rtyp.DT.typ with
| DT.TVoid -> ()
| TI8 -> emit_read_unboxed_signed 8
| TI16 -> emit_read_unboxed_signed 16
| TI24 -> emit_read_unboxed_signed 24
| TI32 -> emit_read_boxed "caml_int32_ops" 4
| TI40 -> emit_read_boxed64_signed 40
| TI48 -> emit_read_boxed64_signed 48
| TI56 -> emit_read_boxed64_signed 56
| TI64 -> emit_read_boxed "caml_int64_ops" 8
| TU8 -> emit_read_unboxed_unsigned "uint8_t"
| TU16 -> emit_read_unboxed_unsigned "uint16_t"
| TU24 -> emit_read_unboxed_unsigned "uint32_t"
| TU32 -> emit_read_boxed "uint32_ops" 4
| TU40 -> emit_read_boxed64_unsigned 40
| TU48 -> emit_read_boxed64_unsigned 48
| TU56 -> emit_read_boxed64_unsigned 56
| TU64 -> emit_read_boxed "uint64_ops" 8
| TI128 -> emit_read_i128 true
| TU128 -> emit_read_i128 false
| TBool ->
p "%s = Val_bool(%s->data[%s]);" res_var batch_var row_var
| TChar -> emit_read_unboxed_unsigned "uint8_t"
| TFloat ->
p "%s = caml_copy_double(%s->data[%s]);" res_var batch_var row_var
| TString ->
p "%s = caml_alloc_initialized_string(%s->length[%s], %s->data[%s]);"
res_var batch_var row_var batch_var row_var
| TSum mns as typ ->
p "switch (%s->tags[%s]) {" batch_var row_var ;
Array.iteri (fun i (cstr_name, mn) ->
let vt = DT.develop mn.DT.typ in
emit_case i cstr_name vt
) mns ;
emit_default (DT.to_string typ) ;
p "}"
| TArr t ->
let len_var = gensym "len" in
p "int64_t %s =" len_var ;
p " %s->offsets[%s + 1] - %s->offsets[%s];"
batch_var row_var batch_var row_var ;
p "if (%s < 0) {" len_var ;
p " cerr << \"Invalid list of \" << %s << \" entries at row \" << %s"
len_var row_var ;
p " << \"(offsets are \" << %s->offsets[%s]"
batch_var row_var ;
p " << \" and then \" << %s->offsets[%s + 1] << \")\\n\";"
batch_var row_var ;
p " assert(false);" ;
p "}" ;
emit_read_array t ("((uint64_t)"^ len_var ^")") ;
| TVec (d, t) ->
emit_read_array t (string_of_int d)
| TTup ts ->
Array.enum ts |>
Enum.mapi (fun i t -> string_of_int i, t) |>
emit_read_struct (Array.length ts = 1)
| TRec kts ->
Array.enum kts //
(fun (k, _) -> not N.(is_private (field k))) |>
emit_read_struct (Array.length kts = 1)
| _ -> assert false
in
if rtyp.DT.nullable then (
p "if (%s->hasNulls && !%s->notNull[%s]) {"
orig_batch_var orig_batch_var row_var ;
p " %s = Val_long(0); /* Null */" res_var ;
p "} else {" ;
emit_read_nonnull (indent + 1) ;
We must wrap res into a NotNull block ( tag 0 ) . Since we are back
* from emit_read_nonnull we are free to reuse our tmp value :
* from emit_read_nonnull we are free to reuse our tmp value: *)
p " %s = caml_alloc_small(1, 0);" tmp_var ;
p " Field(%s, 0) = %s;" tmp_var res_var ;
p " %s = %s;" res_var tmp_var ;
p "}"
) else (
emit_read_nonnull indent
)
let emit_read_values func_name rtyp oc =
let p fmt = emit oc 0 fmt in
According to dessser , depth 0 is flat scalars :
let max_depth = DT.(depth ~opaque_user_type:false rtyp.typ) + 1 in
p "extern \"C\" value %s(value path_, value batch_sz_, value cb_)" func_name ;
p "{" ;
p " CAMLparam3(path_, batch_sz_, cb_);" ;
p " CAMLlocal1(res);" ;
let rec localN n =
if n < max_depth then
let c = min 5 (max_depth - n) in
p " CAMLlocal%d(%a);" c
(Enum.print ~sep:", " (fun oc n -> Printf.fprintf oc "tmp%d" n))
(Enum.range n ~until:(n + c - 1)) ;
localN (n + c) in
localN 0 ;
p " char const *path = String_val(path_);" ;
p " unsigned batch_sz = Long_val(batch_sz_);" ;
p " unique_ptr<InputStream> in_file = readLocalFile(path);" ;
p " ReaderOptions options;" ;
p " unique_ptr<Reader> reader = createReader(move(in_file), options);" ;
p " RowReaderOptions row_options;" ;
p " unique_ptr<RowReader> row_reader =" ;
p " reader->createRowReader(row_options);" ;
p " unique_ptr<ColumnVectorBatch> batch =" ;
p " row_reader->createRowBatch(batch_sz);" ;
p " unsigned num_lines = 0;" ;
p " unsigned num_errors = 0;" ;
p " while (row_reader->next(*batch)) {" ;
p " for (uint64_t row = 0; row < batch->numElements; row++) {" ;
emit_read_value_from_batch 3 0 "batch.get()" "row" "res" rtyp oc ;
p " res = caml_callback_exn(cb_, res);" ;
p " if (Is_exception_result(res)) {" ;
p " res = Extract_exception(res);" ;
p " // Print only the first 10 such exceptions:" ;
p " if (num_errors++ < 10) {" ;
p " cerr << \"Exception while reading ORC file \" << path" ;
p " << \": to_be_printed\\n\";" ;
p " }" ;
p " }" ;
p " num_lines++;" ;
p " }" ;
p " }" ;
p " // Return the number of lines and errors:" ;
p " res = caml_alloc(2, 0);" ;
p " Store_field(res, 0, Val_long(num_lines));" ;
p " Store_field(res, 1, Val_long(num_errors));" ;
p " CAMLreturn(res);" ;
p "}"
let emit_intro oc =
let p fmt = emit oc 0 fmt in
p "/* This code is automatically generated. Edition is futile. */" ;
p "#include <cassert>" ;
p "#include <orc/OrcFile.hh>" ;
p "extern \"C\" {" ;
p "# include <limits.h> /* CHAR_BIT */" ;
p "# include <caml/mlvalues.h>" ;
p "# include <caml/memory.h>" ;
p "# include <caml/alloc.h>" ;
p "# include <caml/custom.h>" ;
p "# include <caml/callback.h>" ;
p "extern struct custom_operations uint128_ops;" ;
p "extern struct custom_operations uint64_ops;" ;
p "extern struct custom_operations uint32_ops;" ;
p "extern struct custom_operations int128_ops;" ;
p "extern struct custom_operations caml_int64_ops;" ;
p "extern struct custom_operations caml_int32_ops;" ;
p "}" ;
p "typedef __int128_t int128_t;" ;
p "typedef __uint128_t uint128_t;" ;
p "using namespace std;" ;
p "using namespace orc;" ;
p "" ;
p "class OrcHandler {" ;
p " unique_ptr<Type> type;" ;
p " string fname;" ;
p " bool const with_index;" ;
p " unsigned const batch_size;" ;
p " unsigned const max_batches;" ;
p " unsigned num_batches;" ;
p " bool archive;" ;
p " std::vector<char> strs;" ;
p " public:" ;
p " OrcHandler(string schema, string fn, bool with_index, unsigned bsz, unsigned mb, bool arc);" ;
p " ~OrcHandler();" ;
p " void start_write();" ;
p " void flush_batch(bool);" ;
p " char *keep_string(char const *, size_t);" ;
p " unique_ptr<OutputStream> outStream;" ;
p " unique_ptr<Writer> writer;" ;
p " unique_ptr<ColumnVectorBatch> batch;" ;
p " double start, stop;" ;
p "};" ;
p "" ;
p "#define Handler_val(v) (*((class OrcHandler **)Data_custom_val(v)))" ;
p ""
let emit_outro oc =
ignore oc
|
e4b45eed1c0ded0d03fff9dea95f95f632d9c46a3345361a78441cdec0d12625 | nasa/Common-Metadata-Repository | core.clj | (ns cmr.exchange.common.results.core
(:require
[clojusc.results.core :as core]))
(defrecord CollectionResults
[;; The number of results returned
hits
;; Number of milleseconds elapsed from start to end of call
took
;; Search-after header
search-after
;; The actual items in the result set
items
;; The randomly generated request-id string
request-id
;; Any non-error messages that need to be returned
warnings])
(defn create
[results & {:keys [request-id elapsed sa-header hits-header warnings]}]
(map->CollectionResults
(merge {
:hits hits-header
:took elapsed
:search-after sa-header
:request-id request-id
:items results}
warnings)))
(def elided #'core/elided)
(def remaining-items #'core/remaining-items)
| null | https://raw.githubusercontent.com/nasa/Common-Metadata-Repository/3215ee6945cb1fa82499c3c3d74841c3284eec6e/other/cmr-exchange/exchange-common/src/cmr/exchange/common/results/core.clj | clojure | The number of results returned
Number of milleseconds elapsed from start to end of call
Search-after header
The actual items in the result set
The randomly generated request-id string
Any non-error messages that need to be returned | (ns cmr.exchange.common.results.core
(:require
[clojusc.results.core :as core]))
(defrecord CollectionResults
hits
took
search-after
items
request-id
warnings])
(defn create
[results & {:keys [request-id elapsed sa-header hits-header warnings]}]
(map->CollectionResults
(merge {
:hits hits-header
:took elapsed
:search-after sa-header
:request-id request-id
:items results}
warnings)))
(def elided #'core/elided)
(def remaining-items #'core/remaining-items)
|
c1f6f1ccc48e801fb6bbd9051b0620e7f462428c0265f2cec66989c9315a7fea | huangz1990/SICP-answers | 44-up-split.scm | ;;; 44-up-split.scm
(define (up-split painter n)
(if (= n 0)
painter
(let ((smaller (up-split painter (- n 1))))
(below painter
(beside smaller smaller)))))
| null | https://raw.githubusercontent.com/huangz1990/SICP-answers/15e3475003ef10eb738cf93c1932277bc56bacbe/chp2/code/44-up-split.scm | scheme | 44-up-split.scm |
(define (up-split painter n)
(if (= n 0)
painter
(let ((smaller (up-split painter (- n 1))))
(below painter
(beside smaller smaller)))))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.