_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
|
---|---|---|---|---|---|---|---|---|
a38722afa65fcf780cb03ce6ca70c20c603c6aa841ecc36002ad643adc6cfbc0
|
runtimeverification/haskell-backend
|
Imports.hs
|
module Test.Kore.Validate.DefinitionVerifier.Imports (
test_imports,
) where
import Kore.Attribute.Symbol qualified as Attribute
import Kore.Error
import Kore.IndexedModule.Error (
noSort,
)
import Kore.Internal.Alias qualified as Internal
import Kore.Internal.ApplicationSorts
import Kore.Internal.Symbol qualified as Internal
import Kore.Internal.TermLike hiding (
Alias,
Symbol,
)
import Kore.Syntax.Definition
import Prelude.Kore
import Test.Kore
import Test.Kore.Builtin.External
import Test.Kore.Validate.DefinitionVerifier
import Test.Tasty (
TestTree,
testGroup,
)
test_imports :: [TestTree]
test_imports =
[ importTests
, nameVisibilityTests
, nameDuplicationTests
]
importTests :: TestTree
importTests =
testGroup
"Module imports"
[ expectSuccess
"Simplest definition"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Two modules"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = []
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Two modules with import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = [importSentence (ModuleName "M2")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Three modules with chain import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = [importSentence (ModuleName "M2")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Three modules with dag import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[ importSentence (ModuleName "M2")
, importSentence (ModuleName "M3")
]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectFailureWithError
"Circular import"
( Error
["module 'M1'", "module 'M2'", "module 'M3'", "module 'M2'"]
"Circular module import dependency."
)
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = [importSentence (ModuleName "M2")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences = [importSentence (ModuleName "M2")]
, moduleAttributes = Attributes []
}
]
}
]
nameVisibilityTests :: TestTree
nameVisibilityTests =
testGroup
"Name visibility though module imports"
( sortVisibilityTests
++ symbolVisibilityTests
++ aliasVisibilityTests
)
sortVisibilityTests :: [TestTree]
sortVisibilityTests =
[ nameReferenceTests
"Sort visibility in sorts"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\top (<test data>)"
, "sort 'sort2' (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSortSentence)
(SupportingSentences sortReferenceInSortSupportingSentences)
, nameReferenceTests
"Sort visibility in top pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\top (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInTopPatternSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in exists pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\exists 'var' (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInExistsPatternSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in and pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\and (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInAndPatternSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in next pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\next (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInNextPatternSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in pattern in pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\next (<test data>)"
, "\\equals (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInPatternInPatternSentence)
( SupportingSentences
sortReferenceInPatternInPatternSupportingSentences
)
, nameReferenceTests
"Sort visibility in symbol declaration - return sort"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "symbol 'symbol1' declaration (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSentenceSymbolResultSortSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in symbol declaration - operand sort"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "symbol 'symbol1' declaration (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSentenceSymbolSortsSentence)
( SupportingSentences
sortReferenceInSentenceSymbolSortsSupportSentences
)
, nameReferenceTests
"Sort visibility in alias declaration - return sort"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "alias 'alias1' declaration (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSentenceAliasResultSortSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in alias declaration - operand sort"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "alias 'alias1' declaration (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSentenceAliasSortsSentence)
( SupportingSentences
sortReferenceInSentenceAliasSortsSupportSentences
)
, nameReferenceTests
"Sort visibility in application patterns"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'symbol2' (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSymbolOrAliasSentence)
(SupportingSentences sortReferenceInSymbolOrAliasSupportSentences)
, testGroup
"Meta sort visibility in top pattern"
( nameReferenceSuccessTests
-- N.B., this is not related to the used sort.
(DeclaringSentence sortDeclaration)
(UsingSentence metaSortReferenceInTopPatternSentence)
(SupportingSentences [])
)
]
where
sort =
SortActualSort
SortActual
{ sortActualName = testId "sort1"
, sortActualSorts = []
}
sortDeclaration =
asSentence
SentenceSort
{ sentenceSortName = testId "sort1"
, sentenceSortParameters = []
, sentenceSortAttributes = Attributes []
}
anotherSort =
SortActualSort
SortActual
{ sortActualName = testId "sort3"
, sortActualSorts = []
}
anotherSortDeclaration =
asSentence
SentenceSort
{ sentenceSortName = testId "sort3"
, sentenceSortParameters = []
, sentenceSortAttributes = Attributes []
}
topSortPattern = mkTop sort
metaTopSortPattern = mkTop stringMetaSort
sortReferenceInSort =
SortActualSort
SortActual
{ sortActualName = testId "sort2"
, sortActualSorts = [sort]
}
sortReferenceInSortSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkTop sortReferenceInSort
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInSortSupportingSentences =
[ asSentence
SentenceSort
{ sentenceSortName = testId "sort2"
, sentenceSortParameters = [SortVariable (testId "x")]
, sentenceSortAttributes = Attributes []
}
]
sortReferenceInTopPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize topSortPattern
, sentenceAxiomAttributes = Attributes []
}
metaSortReferenceInTopPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize metaTopSortPattern
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInExistsPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkExists existsVariable (mkElemVar existsVariable)
, sentenceAxiomAttributes = Attributes []
}
where
existsVariable = mkElementVariable (testId "var") sort
sortReferenceInAndPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkAnd (mkTop sort) (mkTop sort)
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInNextPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkNext (mkTop sort)
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInPatternInPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkNext $
mkEquals
anotherSort
(mkTop sort)
(mkTop sort)
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInPatternInPatternSupportingSentences =
[anotherSortDeclaration]
sortReferenceInSentenceSymbolResultSortSentence =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol1"
, symbolParams = []
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort = sort
, sentenceSymbolAttributes = Attributes []
}
sortReferenceInSentenceSymbolSortsSentence =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol1"
, symbolParams = []
}
, sentenceSymbolSorts = [sort]
, sentenceSymbolResultSort = anotherSort
, sentenceSymbolAttributes = Attributes []
}
sortReferenceInSentenceSymbolSortsSupportSentences =
[anotherSortDeclaration]
sortReferenceInSentenceAliasResultSortSentence =
asSentence
SentenceAlias
{ sentenceAliasAlias =
Alias
{ aliasConstructor = testId "alias1"
, aliasParams = []
}
, sentenceAliasSorts = []
, sentenceAliasResultSort = sort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = testId "alias1"
, symbolOrAliasParams = []
}
, applicationChildren = []
}
, sentenceAliasRightPattern =
externalize $ mkTop sort :: ParsedPattern
, sentenceAliasAttributes = Attributes []
}
sortReferenceInSentenceAliasSortsSentence =
asSentence
SentenceAlias
{ sentenceAliasAlias =
Alias
{ aliasConstructor = testId "alias1"
, aliasParams = []
}
, sentenceAliasSorts = [sort]
, sentenceAliasResultSort = anotherSort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = testId "alias1"
, symbolOrAliasParams = []
}
, applicationChildren =
[ mkSomeVariable $ mkElementVariable (testId "x") sort
]
}
, sentenceAliasRightPattern =
externalize $ mkTop anotherSort :: ParsedPattern
, sentenceAliasAttributes = Attributes []
}
sortReferenceInSentenceAliasSortsSupportSentences =
[anotherSortDeclaration]
sortReferenceInSymbolOrAliasSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkApplySymbol
Internal.Symbol
{ symbolConstructor = testId "symbol2"
, symbolParams = [sort]
, symbolAttributes = Attribute.defaultSymbolAttributes
, symbolSorts = applicationSorts [] sort
}
[]
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInSymbolOrAliasSupportSentences =
[ asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol2"
, symbolParams = [SortVariable (testId "sv1")]
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "sv1"))
, sentenceSymbolAttributes = Attributes []
}
]
symbolVisibilityTests :: [TestTree]
symbolVisibilityTests =
[ nameReferenceTests
"Symbol visibility in axioms"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInAxiomSentence)
(SupportingSentences defaultSymbolSupportSentences)
, nameReferenceTests
"Symbol visibility in and pattern"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\and (<test data>)"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInAndPatternSentence)
(SupportingSentences defaultSymbolSupportSentences)
, nameReferenceTests
"Symbol visibility in exists pattern"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\exists 'var' (<test data>)"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInExistsPatternSentence)
(SupportingSentences defaultSymbolSupportSentences)
, nameReferenceTests
"Symbol visibility in next pattern"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\next (<test data>)"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInNextPatternSentence)
(SupportingSentences defaultSymbolSupportSentences)
, nameReferenceTests
"Symbol visibility in application pattern"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'symbol2' (<test data>)"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInSymbolOrAliasSentence)
(SupportingSentences symbolReferenceInSymbolOrAliasSupportSentences)
, nameReferenceTests
"Meta symbol visibility in axioms"
(ExpectedErrorMessage "Head '#symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias '#symbol1' (<test data>)"
]
)
(DeclaringSentence metaSymbolDeclaration)
(UsingSentence metaSymbolReferenceInAxiomSentence)
(SupportingSentences [])
]
where
symbolPattern =
mkApplySymbol
Internal.Symbol
{ symbolConstructor = testId "symbol1"
, symbolParams = [defaultSort]
, symbolAttributes = Attribute.defaultSymbolAttributes
, symbolSorts = applicationSorts [] defaultSort
}
[]
symbolDeclaration =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol1"
, symbolParams = [SortVariable (testId "sv1")]
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "sv1"))
, sentenceSymbolAttributes = Attributes []
}
defaultSymbolSupportSentences = [defaultSortDeclaration]
metaSymbolPattern =
mkApplySymbol
Internal.Symbol
{ symbolConstructor = testId "#symbol1"
, symbolParams = [stringMetaSort]
, symbolAttributes = Attribute.defaultSymbolAttributes
, symbolSorts = applicationSorts [] stringMetaSort
}
[]
metaSymbolDeclaration =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "#symbol1"
, symbolParams = [SortVariable (testId "#sv1")]
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "#sv1"))
, sentenceSymbolAttributes = Attributes []
}
symbolReferenceInAxiomSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize symbolPattern
, sentenceAxiomAttributes = Attributes []
}
metaSymbolReferenceInAxiomSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize metaSymbolPattern
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInAndPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
mkAnd symbolPattern (mkTop $ termLikeSort symbolPattern)
& externalize
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInExistsPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
mkExists
(mkElementVariable (testId "var") defaultSort)
symbolPattern
& externalize
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInNextPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkNext symbolPattern
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInSymbolOrAliasSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkApplySymbol
Internal.Symbol
{ symbolConstructor = testId "symbol2"
, symbolParams = [defaultSort]
, symbolAttributes = Attribute.defaultSymbolAttributes
, symbolSorts =
applicationSorts
[termLikeSort symbolPattern]
defaultSort
}
[symbolPattern]
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInSymbolOrAliasSupportSentences =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol2"
, symbolParams = [SortVariable (testId "sv1")]
}
, sentenceSymbolSorts =
[SortVariableSort (SortVariable (testId "sv1"))]
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "sv1"))
, sentenceSymbolAttributes = Attributes []
} :
defaultSymbolSupportSentences
aliasVisibilityTests :: [TestTree]
aliasVisibilityTests =
[ nameReferenceTests
"Alias visibility in axioms"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInAxiomSentence)
(SupportingSentences defaultAliasSupportSentences)
, nameReferenceTests
"Alias visibility in and pattern"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\and (<test data>)"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInAndPatternSentence)
(SupportingSentences defaultAliasSupportSentences)
, nameReferenceTests
"Alias visibility in exists pattern"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\exists 'var' (<test data>)"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInExistsPatternSentence)
(SupportingSentences defaultAliasSupportSentences)
, nameReferenceTests
"Alias visibility in next pattern"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\next (<test data>)"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInNextPatternSentence)
(SupportingSentences defaultAliasSupportSentences)
, nameReferenceTests
"Alias visibility in application pattern"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'alias2' (<test data>)"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInAliasOrAliasSentence)
(SupportingSentences aliasReferenceInAliasOrAliasSupportSentences)
, nameReferenceTests
"Meta alias visibility in axioms"
(ExpectedErrorMessage "Head '#alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias '#alias1' (<test data>)"
]
)
(DeclaringSentence metaAliasDeclaration)
(UsingSentence metaAliasReferenceInAxiomSentence)
(SupportingSentences [])
]
where
aliasPattern =
mkApplyAlias
Internal.Alias
{ aliasConstructor = testId "alias1"
, aliasParams = [defaultSort]
, aliasSorts = applicationSorts [] defaultSort
, aliasLeft = []
, aliasRight = mkTop defaultSort
}
[]
aliasDeclaration =
let aliasConstructor = testId "alias1"
aliasParams = [SortVariable (testId "sv1")]
sentenceAliasResultSort :: Sort
sentenceAliasResultSort =
SortVariableSort (SortVariable (testId "sv1"))
in SentenceAliasSentence
SentenceAlias
{ sentenceAliasAlias = Alias{aliasConstructor, aliasParams}
, sentenceAliasSorts = []
, sentenceAliasResultSort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = aliasConstructor
, symbolOrAliasParams =
SortVariableSort <$> aliasParams
}
, applicationChildren = []
}
, sentenceAliasRightPattern =
externalize $ mkTop sentenceAliasResultSort
, sentenceAliasAttributes = Attributes []
}
defaultAliasSupportSentences = [defaultSortDeclaration]
metaAliasPattern =
mkApplyAlias
Internal.Alias
{ aliasConstructor = testId "#alias1"
, aliasParams = [stringMetaSort]
, aliasSorts = applicationSorts [] stringMetaSort
, aliasLeft = []
, aliasRight = mkTop stringMetaSort
}
[]
metaAliasDeclaration =
let aliasConstructor = testId "#alias1"
aliasParams = [SortVariable (testId "#sv1")]
symbolOrAliasParams = SortVariableSort <$> aliasParams
sentenceAliasResultSort :: Sort
sentenceAliasResultSort =
SortVariableSort (SortVariable (testId "#sv1"))
in SentenceAliasSentence
SentenceAlias
{ sentenceAliasAlias = Alias{aliasConstructor, aliasParams}
, sentenceAliasSorts = []
, sentenceAliasResultSort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = aliasConstructor
, symbolOrAliasParams
}
, applicationChildren = []
}
, sentenceAliasRightPattern =
externalize $ mkTop sentenceAliasResultSort
, sentenceAliasAttributes = Attributes []
}
aliasReferenceInAxiomSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize aliasPattern
, sentenceAxiomAttributes = Attributes []
}
metaAliasReferenceInAxiomSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize metaAliasPattern
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInAndPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
mkAnd aliasPattern (mkTop $ termLikeSort aliasPattern)
& externalize
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInExistsPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
mkExists
(mkElementVariable (testId "var") defaultSort)
aliasPattern
& externalize
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInNextPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkNext aliasPattern
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInAliasOrAliasSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkApplyAlias
Internal.Alias
{ aliasConstructor = testId "alias2"
, aliasParams = [defaultSort]
, aliasSorts =
applicationSorts
[termLikeSort aliasPattern]
defaultSort
, aliasLeft = []
, aliasRight =
mkTop $ termLikeSort aliasPattern
}
[aliasPattern]
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInAliasOrAliasSupportSentences :: [ParsedSentence]
aliasReferenceInAliasOrAliasSupportSentences =
let aliasConstructor :: Id
aliasConstructor = testId "alias2" :: Id
aliasParams = [SortVariable (testId "sv1")]
sentenceAliasResultSort :: Sort
sentenceAliasResultSort =
SortVariableSort (SortVariable (testId "sv1"))
in SentenceAliasSentence
SentenceAlias
{ sentenceAliasAlias = Alias{aliasConstructor, aliasParams}
, sentenceAliasSorts =
[SortVariableSort (SortVariable (testId "sv1"))]
, sentenceAliasResultSort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = testId "alias2"
, symbolOrAliasParams =
[ SortVariableSort
(SortVariable (testId "sv1"))
]
}
, applicationChildren =
[ mkSomeVariable $
mkSetVariable (testId "@x") $
SortVariableSort (SortVariable (testId "sv1"))
]
}
, sentenceAliasRightPattern =
externalize $ mkTop sentenceAliasResultSort
, sentenceAliasAttributes = Attributes []
} :
defaultAliasSupportSentences
defaultSort :: Sort
defaultSort =
SortActualSort
SortActual
{ sortActualName = testId "sort1"
, sortActualSorts = []
}
defaultSortDeclaration :: ParsedSentence
defaultSortDeclaration =
asSentence
SentenceSort
{ sentenceSortName = testId "sort1"
, sentenceSortParameters = []
, sentenceSortAttributes = Attributes []
}
newtype DeclaringSentence = DeclaringSentence ParsedSentence
newtype UsingSentence = UsingSentence ParsedSentence
newtype SupportingSentences = SupportingSentences [ParsedSentence]
nameReferenceTests ::
HasCallStack =>
String ->
ExpectedErrorMessage ->
ErrorStack ->
DeclaringSentence ->
UsingSentence ->
SupportingSentences ->
TestTree
nameReferenceTests
description
expectedErrorMessage
additionalErrorStack
declaringSentence
usingSentence
supportingSentences =
testGroup
description
( nameReferenceSuccessTests
declaringSentence
usingSentence
supportingSentences
++ nameReferenceFailureTests
expectedErrorMessage
additionalErrorStack
declaringSentence
usingSentence
supportingSentences
)
nameReferenceSuccessTests ::
HasCallStack =>
DeclaringSentence ->
UsingSentence ->
SupportingSentences ->
[TestTree]
nameReferenceSuccessTests
(DeclaringSentence declaringSentence)
(UsingSentence usingSentence)
(SupportingSentences supportingSentences) =
[ expectSuccess
"Successful reference: one module"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
usingSentence :
declaringSentence :
supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Successful reference: two modules with import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[importSentence (ModuleName "M2"), usingSentence]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences =
declaringSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Successful reference: three modules with chain import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[importSentence (ModuleName "M2"), usingSentence]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences =
declaringSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Successful reference: three modules with tree import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[ importSentence (ModuleName "M2")
, importSentence (ModuleName "M3")
, usingSentence
]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = []
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences =
declaringSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Successful reference: three modules with dag import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[ importSentence (ModuleName "M2")
, importSentence (ModuleName "M3")
, usingSentence
]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences =
declaringSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
]
nameReferenceFailureTests ::
HasCallStack =>
ExpectedErrorMessage ->
ErrorStack ->
DeclaringSentence ->
UsingSentence ->
SupportingSentences ->
[TestTree]
nameReferenceFailureTests
(ExpectedErrorMessage expectedErrorMessage)
(ErrorStack additionalErrorStack)
(DeclaringSentence declaringSentence)
(UsingSentence usingSentence)
(SupportingSentences supportingSentences) =
[ expectFailureWithError
"Failed reference: One module without declaration"
Error
{ errorContext = "module 'M1'" : additionalErrorStack
, errorError = expectedErrorMessage
}
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = usingSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectFailureWithError
"Failed reference: two modules without import"
Error
{ errorContext = "module 'M1'" : additionalErrorStack
, errorError = expectedErrorMessage
}
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = usingSentence : supportingSentences
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [declaringSentence]
, moduleAttributes = Attributes []
}
]
}
, expectFailureWithError
"Failed reference: two modules with reverse import"
Error
{ errorContext = "module 'M2'" : additionalErrorStack
, errorError = expectedErrorMessage
}
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[ importSentence (ModuleName "M2")
, declaringSentence
]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = usingSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
]
nameDuplicationTests :: TestTree
nameDuplicationTests =
testGroup
"Name duplication accross modules"
[ duplicatedNameFailureTest
"Two sorts with the same name"
"s1"
(sortDeclarationModule (ModuleName "M1") (SortName "s1"))
(sortDeclarationModule (ModuleName "M2") (SortName "s1"))
, duplicatedNameFailureTest
"Sort with the same name as symbol"
"name"
(sortDeclarationModule (ModuleName "M1") (SortName "name"))
(symbolDeclarationModule (ModuleName "M2") (SymbolName "name"))
, duplicatedNameFailureTest
"Sort with the same name as symbol"
"name"
(symbolDeclarationModule (ModuleName "M1") (SymbolName "name"))
(sortDeclarationModule (ModuleName "M2") (SortName "name"))
, duplicatedNameFailureTest
"Sort with the same name as alias"
"name"
(sortDeclarationModule (ModuleName "M1") (SortName "name"))
(aliasDeclarationModule (ModuleName "M2") (AliasName "name"))
, duplicatedNameFailureTest
"Sort with the same name as alias"
"name"
(aliasDeclarationModule (ModuleName "M1") (AliasName "name"))
(sortDeclarationModule (ModuleName "M2") (SortName "name"))
, duplicatedNameFailureTest
"Two symbols with the same name"
"name"
(symbolDeclarationModule (ModuleName "M1") (SymbolName "name"))
(symbolDeclarationModule (ModuleName "M2") (SymbolName "name"))
, duplicatedNameFailureTest
"Symbol with the same name as alias"
"name"
(aliasDeclarationModule (ModuleName "M1") (AliasName "name"))
(aliasDeclarationModule (ModuleName "M2") (AliasName "name"))
, duplicatedNameFailureTest
"Symbol with the same name as alias"
"name"
(aliasDeclarationModule (ModuleName "M1") (AliasName "name"))
(symbolDeclarationModule (ModuleName "M2") (SymbolName "name"))
, duplicatedNameFailureTest
"Two aliases with the same name"
"name"
(aliasDeclarationModule (ModuleName "M1") (AliasName "name"))
(aliasDeclarationModule (ModuleName "M2") (AliasName "name"))
]
where
sortDeclarationModule modName (SortName sortName) =
Module
{ moduleName = modName
, moduleSentences =
[ asSentence
SentenceSort
{ sentenceSortName = testId sortName
, sentenceSortParameters = []
, sentenceSortAttributes = Attributes []
}
]
, moduleAttributes = Attributes []
}
symbolDeclarationModule modName (SymbolName symbolName) =
Module
{ moduleName = modName
, moduleSentences =
[ asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId symbolName
, symbolParams = [SortVariable (testId "sv1")]
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "sv1"))
, sentenceSymbolAttributes = Attributes []
}
]
, moduleAttributes = Attributes []
}
aliasDeclarationModule modName (AliasName aliasName) =
let sv1 = SortVariable (testId "sv1") :: SortVariable
aliasConstructor = testId aliasName :: Id
in Module
{ moduleName = modName
, moduleSentences =
[ SentenceAliasSentence
SentenceAlias
{ sentenceAliasAlias =
Alias
{ aliasConstructor
, aliasParams = [sv1]
}
, sentenceAliasSorts = []
, sentenceAliasResultSort = SortVariableSort sv1
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor =
aliasConstructor
, symbolOrAliasParams =
[SortVariableSort sv1]
}
, applicationChildren = []
}
, sentenceAliasRightPattern =
externalize $
mkTop (SortVariableSort sv1)
, sentenceAliasAttributes = Attributes []
}
]
, moduleAttributes = Attributes []
}
duplicatedNameFailureTest ::
String ->
String ->
Module ParsedSentence ->
Module ParsedSentence ->
TestTree
duplicatedNameFailureTest message duplicatedName module1 module2 =
expectFailureWithError
message
Error
{ errorContext = ["module 'M2'", "(<test data>, <test data>)"]
, errorError = "Duplicated name: " ++ duplicatedName ++ "."
}
Definition
{ definitionAttributes = Attributes []
, definitionModules = [module1, module2]
}
| null |
https://raw.githubusercontent.com/runtimeverification/haskell-backend/b06757e252ee01fdd5ab8f07de2910711997d845/kore/test/Test/Kore/Validate/DefinitionVerifier/Imports.hs
|
haskell
|
N.B., this is not related to the used sort.
|
module Test.Kore.Validate.DefinitionVerifier.Imports (
test_imports,
) where
import Kore.Attribute.Symbol qualified as Attribute
import Kore.Error
import Kore.IndexedModule.Error (
noSort,
)
import Kore.Internal.Alias qualified as Internal
import Kore.Internal.ApplicationSorts
import Kore.Internal.Symbol qualified as Internal
import Kore.Internal.TermLike hiding (
Alias,
Symbol,
)
import Kore.Syntax.Definition
import Prelude.Kore
import Test.Kore
import Test.Kore.Builtin.External
import Test.Kore.Validate.DefinitionVerifier
import Test.Tasty (
TestTree,
testGroup,
)
test_imports :: [TestTree]
test_imports =
[ importTests
, nameVisibilityTests
, nameDuplicationTests
]
importTests :: TestTree
importTests =
testGroup
"Module imports"
[ expectSuccess
"Simplest definition"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Two modules"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = []
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Two modules with import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = [importSentence (ModuleName "M2")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Three modules with chain import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = [importSentence (ModuleName "M2")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Three modules with dag import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[ importSentence (ModuleName "M2")
, importSentence (ModuleName "M3")
]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences = []
, moduleAttributes = Attributes []
}
]
}
, expectFailureWithError
"Circular import"
( Error
["module 'M1'", "module 'M2'", "module 'M3'", "module 'M2'"]
"Circular module import dependency."
)
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = [importSentence (ModuleName "M2")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences = [importSentence (ModuleName "M2")]
, moduleAttributes = Attributes []
}
]
}
]
nameVisibilityTests :: TestTree
nameVisibilityTests =
testGroup
"Name visibility though module imports"
( sortVisibilityTests
++ symbolVisibilityTests
++ aliasVisibilityTests
)
sortVisibilityTests :: [TestTree]
sortVisibilityTests =
[ nameReferenceTests
"Sort visibility in sorts"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\top (<test data>)"
, "sort 'sort2' (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSortSentence)
(SupportingSentences sortReferenceInSortSupportingSentences)
, nameReferenceTests
"Sort visibility in top pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\top (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInTopPatternSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in exists pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\exists 'var' (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInExistsPatternSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in and pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\and (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInAndPatternSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in next pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\next (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInNextPatternSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in pattern in pattern"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "\\next (<test data>)"
, "\\equals (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInPatternInPatternSentence)
( SupportingSentences
sortReferenceInPatternInPatternSupportingSentences
)
, nameReferenceTests
"Sort visibility in symbol declaration - return sort"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "symbol 'symbol1' declaration (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSentenceSymbolResultSortSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in symbol declaration - operand sort"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "symbol 'symbol1' declaration (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSentenceSymbolSortsSentence)
( SupportingSentences
sortReferenceInSentenceSymbolSortsSupportSentences
)
, nameReferenceTests
"Sort visibility in alias declaration - return sort"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "alias 'alias1' declaration (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSentenceAliasResultSortSentence)
(SupportingSentences [])
, nameReferenceTests
"Sort visibility in alias declaration - operand sort"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "alias 'alias1' declaration (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSentenceAliasSortsSentence)
( SupportingSentences
sortReferenceInSentenceAliasSortsSupportSentences
)
, nameReferenceTests
"Sort visibility in application patterns"
(ExpectedErrorMessage $ noSort "sort1")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'symbol2' (<test data>)"
, "sort 'sort1' (<test data>)"
, "(<test data>)"
]
)
(DeclaringSentence sortDeclaration)
(UsingSentence sortReferenceInSymbolOrAliasSentence)
(SupportingSentences sortReferenceInSymbolOrAliasSupportSentences)
, testGroup
"Meta sort visibility in top pattern"
( nameReferenceSuccessTests
(DeclaringSentence sortDeclaration)
(UsingSentence metaSortReferenceInTopPatternSentence)
(SupportingSentences [])
)
]
where
sort =
SortActualSort
SortActual
{ sortActualName = testId "sort1"
, sortActualSorts = []
}
sortDeclaration =
asSentence
SentenceSort
{ sentenceSortName = testId "sort1"
, sentenceSortParameters = []
, sentenceSortAttributes = Attributes []
}
anotherSort =
SortActualSort
SortActual
{ sortActualName = testId "sort3"
, sortActualSorts = []
}
anotherSortDeclaration =
asSentence
SentenceSort
{ sentenceSortName = testId "sort3"
, sentenceSortParameters = []
, sentenceSortAttributes = Attributes []
}
topSortPattern = mkTop sort
metaTopSortPattern = mkTop stringMetaSort
sortReferenceInSort =
SortActualSort
SortActual
{ sortActualName = testId "sort2"
, sortActualSorts = [sort]
}
sortReferenceInSortSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkTop sortReferenceInSort
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInSortSupportingSentences =
[ asSentence
SentenceSort
{ sentenceSortName = testId "sort2"
, sentenceSortParameters = [SortVariable (testId "x")]
, sentenceSortAttributes = Attributes []
}
]
sortReferenceInTopPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize topSortPattern
, sentenceAxiomAttributes = Attributes []
}
metaSortReferenceInTopPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize metaTopSortPattern
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInExistsPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkExists existsVariable (mkElemVar existsVariable)
, sentenceAxiomAttributes = Attributes []
}
where
existsVariable = mkElementVariable (testId "var") sort
sortReferenceInAndPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkAnd (mkTop sort) (mkTop sort)
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInNextPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkNext (mkTop sort)
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInPatternInPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkNext $
mkEquals
anotherSort
(mkTop sort)
(mkTop sort)
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInPatternInPatternSupportingSentences =
[anotherSortDeclaration]
sortReferenceInSentenceSymbolResultSortSentence =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol1"
, symbolParams = []
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort = sort
, sentenceSymbolAttributes = Attributes []
}
sortReferenceInSentenceSymbolSortsSentence =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol1"
, symbolParams = []
}
, sentenceSymbolSorts = [sort]
, sentenceSymbolResultSort = anotherSort
, sentenceSymbolAttributes = Attributes []
}
sortReferenceInSentenceSymbolSortsSupportSentences =
[anotherSortDeclaration]
sortReferenceInSentenceAliasResultSortSentence =
asSentence
SentenceAlias
{ sentenceAliasAlias =
Alias
{ aliasConstructor = testId "alias1"
, aliasParams = []
}
, sentenceAliasSorts = []
, sentenceAliasResultSort = sort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = testId "alias1"
, symbolOrAliasParams = []
}
, applicationChildren = []
}
, sentenceAliasRightPattern =
externalize $ mkTop sort :: ParsedPattern
, sentenceAliasAttributes = Attributes []
}
sortReferenceInSentenceAliasSortsSentence =
asSentence
SentenceAlias
{ sentenceAliasAlias =
Alias
{ aliasConstructor = testId "alias1"
, aliasParams = []
}
, sentenceAliasSorts = [sort]
, sentenceAliasResultSort = anotherSort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = testId "alias1"
, symbolOrAliasParams = []
}
, applicationChildren =
[ mkSomeVariable $ mkElementVariable (testId "x") sort
]
}
, sentenceAliasRightPattern =
externalize $ mkTop anotherSort :: ParsedPattern
, sentenceAliasAttributes = Attributes []
}
sortReferenceInSentenceAliasSortsSupportSentences =
[anotherSortDeclaration]
sortReferenceInSymbolOrAliasSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkApplySymbol
Internal.Symbol
{ symbolConstructor = testId "symbol2"
, symbolParams = [sort]
, symbolAttributes = Attribute.defaultSymbolAttributes
, symbolSorts = applicationSorts [] sort
}
[]
, sentenceAxiomAttributes = Attributes []
}
sortReferenceInSymbolOrAliasSupportSentences =
[ asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol2"
, symbolParams = [SortVariable (testId "sv1")]
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "sv1"))
, sentenceSymbolAttributes = Attributes []
}
]
symbolVisibilityTests :: [TestTree]
symbolVisibilityTests =
[ nameReferenceTests
"Symbol visibility in axioms"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInAxiomSentence)
(SupportingSentences defaultSymbolSupportSentences)
, nameReferenceTests
"Symbol visibility in and pattern"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\and (<test data>)"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInAndPatternSentence)
(SupportingSentences defaultSymbolSupportSentences)
, nameReferenceTests
"Symbol visibility in exists pattern"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\exists 'var' (<test data>)"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInExistsPatternSentence)
(SupportingSentences defaultSymbolSupportSentences)
, nameReferenceTests
"Symbol visibility in next pattern"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\next (<test data>)"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInNextPatternSentence)
(SupportingSentences defaultSymbolSupportSentences)
, nameReferenceTests
"Symbol visibility in application pattern"
(ExpectedErrorMessage "Head 'symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'symbol2' (<test data>)"
, "symbol or alias 'symbol1' (<test data>)"
]
)
(DeclaringSentence symbolDeclaration)
(UsingSentence symbolReferenceInSymbolOrAliasSentence)
(SupportingSentences symbolReferenceInSymbolOrAliasSupportSentences)
, nameReferenceTests
"Meta symbol visibility in axioms"
(ExpectedErrorMessage "Head '#symbol1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias '#symbol1' (<test data>)"
]
)
(DeclaringSentence metaSymbolDeclaration)
(UsingSentence metaSymbolReferenceInAxiomSentence)
(SupportingSentences [])
]
where
symbolPattern =
mkApplySymbol
Internal.Symbol
{ symbolConstructor = testId "symbol1"
, symbolParams = [defaultSort]
, symbolAttributes = Attribute.defaultSymbolAttributes
, symbolSorts = applicationSorts [] defaultSort
}
[]
symbolDeclaration =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol1"
, symbolParams = [SortVariable (testId "sv1")]
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "sv1"))
, sentenceSymbolAttributes = Attributes []
}
defaultSymbolSupportSentences = [defaultSortDeclaration]
metaSymbolPattern =
mkApplySymbol
Internal.Symbol
{ symbolConstructor = testId "#symbol1"
, symbolParams = [stringMetaSort]
, symbolAttributes = Attribute.defaultSymbolAttributes
, symbolSorts = applicationSorts [] stringMetaSort
}
[]
metaSymbolDeclaration =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "#symbol1"
, symbolParams = [SortVariable (testId "#sv1")]
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "#sv1"))
, sentenceSymbolAttributes = Attributes []
}
symbolReferenceInAxiomSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize symbolPattern
, sentenceAxiomAttributes = Attributes []
}
metaSymbolReferenceInAxiomSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize metaSymbolPattern
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInAndPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
mkAnd symbolPattern (mkTop $ termLikeSort symbolPattern)
& externalize
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInExistsPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
mkExists
(mkElementVariable (testId "var") defaultSort)
symbolPattern
& externalize
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInNextPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkNext symbolPattern
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInSymbolOrAliasSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkApplySymbol
Internal.Symbol
{ symbolConstructor = testId "symbol2"
, symbolParams = [defaultSort]
, symbolAttributes = Attribute.defaultSymbolAttributes
, symbolSorts =
applicationSorts
[termLikeSort symbolPattern]
defaultSort
}
[symbolPattern]
, sentenceAxiomAttributes = Attributes []
}
symbolReferenceInSymbolOrAliasSupportSentences =
asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId "symbol2"
, symbolParams = [SortVariable (testId "sv1")]
}
, sentenceSymbolSorts =
[SortVariableSort (SortVariable (testId "sv1"))]
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "sv1"))
, sentenceSymbolAttributes = Attributes []
} :
defaultSymbolSupportSentences
aliasVisibilityTests :: [TestTree]
aliasVisibilityTests =
[ nameReferenceTests
"Alias visibility in axioms"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInAxiomSentence)
(SupportingSentences defaultAliasSupportSentences)
, nameReferenceTests
"Alias visibility in and pattern"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\and (<test data>)"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInAndPatternSentence)
(SupportingSentences defaultAliasSupportSentences)
, nameReferenceTests
"Alias visibility in exists pattern"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\exists 'var' (<test data>)"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInExistsPatternSentence)
(SupportingSentences defaultAliasSupportSentences)
, nameReferenceTests
"Alias visibility in next pattern"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "\\next (<test data>)"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInNextPatternSentence)
(SupportingSentences defaultAliasSupportSentences)
, nameReferenceTests
"Alias visibility in application pattern"
(ExpectedErrorMessage "Head 'alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias 'alias2' (<test data>)"
, "symbol or alias 'alias1' (<test data>)"
]
)
(DeclaringSentence aliasDeclaration)
(UsingSentence aliasReferenceInAliasOrAliasSentence)
(SupportingSentences aliasReferenceInAliasOrAliasSupportSentences)
, nameReferenceTests
"Meta alias visibility in axioms"
(ExpectedErrorMessage "Head '#alias1' not defined.")
( ErrorStack
[ "axiom declaration"
, "symbol or alias '#alias1' (<test data>)"
]
)
(DeclaringSentence metaAliasDeclaration)
(UsingSentence metaAliasReferenceInAxiomSentence)
(SupportingSentences [])
]
where
aliasPattern =
mkApplyAlias
Internal.Alias
{ aliasConstructor = testId "alias1"
, aliasParams = [defaultSort]
, aliasSorts = applicationSorts [] defaultSort
, aliasLeft = []
, aliasRight = mkTop defaultSort
}
[]
aliasDeclaration =
let aliasConstructor = testId "alias1"
aliasParams = [SortVariable (testId "sv1")]
sentenceAliasResultSort :: Sort
sentenceAliasResultSort =
SortVariableSort (SortVariable (testId "sv1"))
in SentenceAliasSentence
SentenceAlias
{ sentenceAliasAlias = Alias{aliasConstructor, aliasParams}
, sentenceAliasSorts = []
, sentenceAliasResultSort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = aliasConstructor
, symbolOrAliasParams =
SortVariableSort <$> aliasParams
}
, applicationChildren = []
}
, sentenceAliasRightPattern =
externalize $ mkTop sentenceAliasResultSort
, sentenceAliasAttributes = Attributes []
}
defaultAliasSupportSentences = [defaultSortDeclaration]
metaAliasPattern =
mkApplyAlias
Internal.Alias
{ aliasConstructor = testId "#alias1"
, aliasParams = [stringMetaSort]
, aliasSorts = applicationSorts [] stringMetaSort
, aliasLeft = []
, aliasRight = mkTop stringMetaSort
}
[]
metaAliasDeclaration =
let aliasConstructor = testId "#alias1"
aliasParams = [SortVariable (testId "#sv1")]
symbolOrAliasParams = SortVariableSort <$> aliasParams
sentenceAliasResultSort :: Sort
sentenceAliasResultSort =
SortVariableSort (SortVariable (testId "#sv1"))
in SentenceAliasSentence
SentenceAlias
{ sentenceAliasAlias = Alias{aliasConstructor, aliasParams}
, sentenceAliasSorts = []
, sentenceAliasResultSort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = aliasConstructor
, symbolOrAliasParams
}
, applicationChildren = []
}
, sentenceAliasRightPattern =
externalize $ mkTop sentenceAliasResultSort
, sentenceAliasAttributes = Attributes []
}
aliasReferenceInAxiomSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize aliasPattern
, sentenceAxiomAttributes = Attributes []
}
metaAliasReferenceInAxiomSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize metaAliasPattern
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInAndPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
mkAnd aliasPattern (mkTop $ termLikeSort aliasPattern)
& externalize
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInExistsPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
mkExists
(mkElementVariable (testId "var") defaultSort)
aliasPattern
& externalize
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInNextPatternSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $ mkNext aliasPattern
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInAliasOrAliasSentence =
SentenceAxiomSentence
SentenceAxiom
{ sentenceAxiomParameters = []
, sentenceAxiomPattern =
externalize $
mkApplyAlias
Internal.Alias
{ aliasConstructor = testId "alias2"
, aliasParams = [defaultSort]
, aliasSorts =
applicationSorts
[termLikeSort aliasPattern]
defaultSort
, aliasLeft = []
, aliasRight =
mkTop $ termLikeSort aliasPattern
}
[aliasPattern]
, sentenceAxiomAttributes = Attributes []
}
aliasReferenceInAliasOrAliasSupportSentences :: [ParsedSentence]
aliasReferenceInAliasOrAliasSupportSentences =
let aliasConstructor :: Id
aliasConstructor = testId "alias2" :: Id
aliasParams = [SortVariable (testId "sv1")]
sentenceAliasResultSort :: Sort
sentenceAliasResultSort =
SortVariableSort (SortVariable (testId "sv1"))
in SentenceAliasSentence
SentenceAlias
{ sentenceAliasAlias = Alias{aliasConstructor, aliasParams}
, sentenceAliasSorts =
[SortVariableSort (SortVariable (testId "sv1"))]
, sentenceAliasResultSort
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor = testId "alias2"
, symbolOrAliasParams =
[ SortVariableSort
(SortVariable (testId "sv1"))
]
}
, applicationChildren =
[ mkSomeVariable $
mkSetVariable (testId "@x") $
SortVariableSort (SortVariable (testId "sv1"))
]
}
, sentenceAliasRightPattern =
externalize $ mkTop sentenceAliasResultSort
, sentenceAliasAttributes = Attributes []
} :
defaultAliasSupportSentences
defaultSort :: Sort
defaultSort =
SortActualSort
SortActual
{ sortActualName = testId "sort1"
, sortActualSorts = []
}
defaultSortDeclaration :: ParsedSentence
defaultSortDeclaration =
asSentence
SentenceSort
{ sentenceSortName = testId "sort1"
, sentenceSortParameters = []
, sentenceSortAttributes = Attributes []
}
newtype DeclaringSentence = DeclaringSentence ParsedSentence
newtype UsingSentence = UsingSentence ParsedSentence
newtype SupportingSentences = SupportingSentences [ParsedSentence]
nameReferenceTests ::
HasCallStack =>
String ->
ExpectedErrorMessage ->
ErrorStack ->
DeclaringSentence ->
UsingSentence ->
SupportingSentences ->
TestTree
nameReferenceTests
description
expectedErrorMessage
additionalErrorStack
declaringSentence
usingSentence
supportingSentences =
testGroup
description
( nameReferenceSuccessTests
declaringSentence
usingSentence
supportingSentences
++ nameReferenceFailureTests
expectedErrorMessage
additionalErrorStack
declaringSentence
usingSentence
supportingSentences
)
nameReferenceSuccessTests ::
HasCallStack =>
DeclaringSentence ->
UsingSentence ->
SupportingSentences ->
[TestTree]
nameReferenceSuccessTests
(DeclaringSentence declaringSentence)
(UsingSentence usingSentence)
(SupportingSentences supportingSentences) =
[ expectSuccess
"Successful reference: one module"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
usingSentence :
declaringSentence :
supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Successful reference: two modules with import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[importSentence (ModuleName "M2"), usingSentence]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences =
declaringSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Successful reference: three modules with chain import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[importSentence (ModuleName "M2"), usingSentence]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences =
declaringSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Successful reference: three modules with tree import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[ importSentence (ModuleName "M2")
, importSentence (ModuleName "M3")
, usingSentence
]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = []
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences =
declaringSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectSuccess
"Successful reference: three modules with dag import"
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[ importSentence (ModuleName "M2")
, importSentence (ModuleName "M3")
, usingSentence
]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [importSentence (ModuleName "M3")]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M3"
, moduleSentences =
declaringSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
]
nameReferenceFailureTests ::
HasCallStack =>
ExpectedErrorMessage ->
ErrorStack ->
DeclaringSentence ->
UsingSentence ->
SupportingSentences ->
[TestTree]
nameReferenceFailureTests
(ExpectedErrorMessage expectedErrorMessage)
(ErrorStack additionalErrorStack)
(DeclaringSentence declaringSentence)
(UsingSentence usingSentence)
(SupportingSentences supportingSentences) =
[ expectFailureWithError
"Failed reference: One module without declaration"
Error
{ errorContext = "module 'M1'" : additionalErrorStack
, errorError = expectedErrorMessage
}
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = usingSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
, expectFailureWithError
"Failed reference: two modules without import"
Error
{ errorContext = "module 'M1'" : additionalErrorStack
, errorError = expectedErrorMessage
}
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences = usingSentence : supportingSentences
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = [declaringSentence]
, moduleAttributes = Attributes []
}
]
}
, expectFailureWithError
"Failed reference: two modules with reverse import"
Error
{ errorContext = "module 'M2'" : additionalErrorStack
, errorError = expectedErrorMessage
}
Definition
{ definitionAttributes = Attributes []
, definitionModules =
[ Module
{ moduleName = ModuleName "M1"
, moduleSentences =
[ importSentence (ModuleName "M2")
, declaringSentence
]
, moduleAttributes = Attributes []
}
, Module
{ moduleName = ModuleName "M2"
, moduleSentences = usingSentence : supportingSentences
, moduleAttributes = Attributes []
}
]
}
]
nameDuplicationTests :: TestTree
nameDuplicationTests =
testGroup
"Name duplication accross modules"
[ duplicatedNameFailureTest
"Two sorts with the same name"
"s1"
(sortDeclarationModule (ModuleName "M1") (SortName "s1"))
(sortDeclarationModule (ModuleName "M2") (SortName "s1"))
, duplicatedNameFailureTest
"Sort with the same name as symbol"
"name"
(sortDeclarationModule (ModuleName "M1") (SortName "name"))
(symbolDeclarationModule (ModuleName "M2") (SymbolName "name"))
, duplicatedNameFailureTest
"Sort with the same name as symbol"
"name"
(symbolDeclarationModule (ModuleName "M1") (SymbolName "name"))
(sortDeclarationModule (ModuleName "M2") (SortName "name"))
, duplicatedNameFailureTest
"Sort with the same name as alias"
"name"
(sortDeclarationModule (ModuleName "M1") (SortName "name"))
(aliasDeclarationModule (ModuleName "M2") (AliasName "name"))
, duplicatedNameFailureTest
"Sort with the same name as alias"
"name"
(aliasDeclarationModule (ModuleName "M1") (AliasName "name"))
(sortDeclarationModule (ModuleName "M2") (SortName "name"))
, duplicatedNameFailureTest
"Two symbols with the same name"
"name"
(symbolDeclarationModule (ModuleName "M1") (SymbolName "name"))
(symbolDeclarationModule (ModuleName "M2") (SymbolName "name"))
, duplicatedNameFailureTest
"Symbol with the same name as alias"
"name"
(aliasDeclarationModule (ModuleName "M1") (AliasName "name"))
(aliasDeclarationModule (ModuleName "M2") (AliasName "name"))
, duplicatedNameFailureTest
"Symbol with the same name as alias"
"name"
(aliasDeclarationModule (ModuleName "M1") (AliasName "name"))
(symbolDeclarationModule (ModuleName "M2") (SymbolName "name"))
, duplicatedNameFailureTest
"Two aliases with the same name"
"name"
(aliasDeclarationModule (ModuleName "M1") (AliasName "name"))
(aliasDeclarationModule (ModuleName "M2") (AliasName "name"))
]
where
sortDeclarationModule modName (SortName sortName) =
Module
{ moduleName = modName
, moduleSentences =
[ asSentence
SentenceSort
{ sentenceSortName = testId sortName
, sentenceSortParameters = []
, sentenceSortAttributes = Attributes []
}
]
, moduleAttributes = Attributes []
}
symbolDeclarationModule modName (SymbolName symbolName) =
Module
{ moduleName = modName
, moduleSentences =
[ asSentence
SentenceSymbol
{ sentenceSymbolSymbol =
Symbol
{ symbolConstructor = testId symbolName
, symbolParams = [SortVariable (testId "sv1")]
}
, sentenceSymbolSorts = []
, sentenceSymbolResultSort =
SortVariableSort (SortVariable (testId "sv1"))
, sentenceSymbolAttributes = Attributes []
}
]
, moduleAttributes = Attributes []
}
aliasDeclarationModule modName (AliasName aliasName) =
let sv1 = SortVariable (testId "sv1") :: SortVariable
aliasConstructor = testId aliasName :: Id
in Module
{ moduleName = modName
, moduleSentences =
[ SentenceAliasSentence
SentenceAlias
{ sentenceAliasAlias =
Alias
{ aliasConstructor
, aliasParams = [sv1]
}
, sentenceAliasSorts = []
, sentenceAliasResultSort = SortVariableSort sv1
, sentenceAliasLeftPattern =
Application
{ applicationSymbolOrAlias =
SymbolOrAlias
{ symbolOrAliasConstructor =
aliasConstructor
, symbolOrAliasParams =
[SortVariableSort sv1]
}
, applicationChildren = []
}
, sentenceAliasRightPattern =
externalize $
mkTop (SortVariableSort sv1)
, sentenceAliasAttributes = Attributes []
}
]
, moduleAttributes = Attributes []
}
duplicatedNameFailureTest ::
String ->
String ->
Module ParsedSentence ->
Module ParsedSentence ->
TestTree
duplicatedNameFailureTest message duplicatedName module1 module2 =
expectFailureWithError
message
Error
{ errorContext = ["module 'M2'", "(<test data>, <test data>)"]
, errorError = "Duplicated name: " ++ duplicatedName ++ "."
}
Definition
{ definitionAttributes = Attributes []
, definitionModules = [module1, module2]
}
|
285cbb52cfd2ab537ab0d4acf18a8ab67e572ecee8ee5518bc9b5ba375c4db9c
|
didierverna/clon
|
context.lisp
|
;;; context.lisp --- Context management
Copyright ( C ) 2010 - 2012 , 2015 , 2017 , 2020 , 2021
Author : < >
This file is part of .
;; Permission to use, copy, modify, and 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.
THIS 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.
;;; Commentary:
Contents management by FCM version 0.1 .
;;; Code:
(in-package :net.didierverna.clon)
(in-readtable :net.didierverna.clon)
(defvar *context* nil "The current context.")
;; ==========================================================================
;; Command-line error management (not regarding known options)
;; ==========================================================================
(define-condition invalid-short-equal-syntax (cmdline-error)
()
(:report (lambda (error stream)
(format stream "Invalid = syntax in short call: ~S."
(item error))))
(:documentation "An error related to a short-equal syntax."))
(define-condition invalid-negated-equal-syntax (cmdline-error)
()
(:report (lambda (error stream)
(format stream "Invalid = syntax in negated call: ~S."
(item error))))
(:documentation "An error related to a negated-equal syntax."))
(define-condition cmdline-junk-error (cmdline-error)
inherited from the CMDLINE - ERROR condition
:documentation "The piece of junk appearing on the command-line."
:initarg :junk
:reader junk))
(:report (lambda (error stream)
(format stream "Junk on the command-line: ~S." (junk error))))
(:documentation "An error related to a command-line piece of junk."))
(defun restartable-cmdline-junk-error (junk)
(restart-case (error 'cmdline-junk-error :junk junk)
(discard ()
:report "Discard junk."
nil)))
(define-condition unrecognized-short-call-error (cmdline-error)
inherited from the CMDLINE - ERROR condition
:documentation "The unrecognized short call on the command-line."
:initarg :short-call
:reader short-call))
(:report (lambda (error stream)
(format stream "Unrecognized option or short pack: ~S."
(short-call error))))
(:documentation "An error related to an unrecognized short call."))
(define-condition unrecognized-negated-call-error (cmdline-error)
inherited from the CMDLINE - ERROR condition
:documentation "The unrecognized negated call on the command-line."
:initarg :negated-call
:reader negated-call))
(:report (lambda (error stream)
(format stream "Unrecognized option or negated pack: ~S."
(negated-call error))))
(:documentation "An error related to an unrecognized negated call."))
(define-condition unknown-cmdline-option-error (cmdline-error)
inherited from the CMDLINE - ERROR condition
:documentation "The option's name as it appears on the command-line."
:initarg :name
:reader name)
(argument :documentation "The option's command-line argument."
:initarg :argument
:reader argument))
(:report (lambda (error stream)
(format stream "Unknown command-line option ~
~S~@[ with argument ~S~]."
(name error)
(argument error))))
(:documentation "An error related to an unknown command-line option."))
(defun print-error (error
&optional interactivep
&aux (stream (if interactivep *query-io* *error-output*))
*print-escape*)
"Print ERROR on *ERROR-OUTPUT*.
When INTERACTIVEP, print on *QUERY-IO* instead."
(print-object error stream)
(terpri stream))
(defun exit-abnormally (error)
"Print ERROR on *ERROR-OUTPUT* and exit with status code 1."
(print-error error)
(uiop:quit 1))
Adapted from the Hyperspec
(defun restart-on-error (error)
"Print ERROR and offer available restarts on *QUERY-IO*."
(print-error error :interactive)
(format *query-io* "Available options:~%")
(let ((restarts (compute-restarts)))
(do ((i 0 (+ i 1)) (r restarts (cdr r))) ((null r))
(format *query-io* "~&~D: ~A~%" i (car r)))
(loop :with k := (length restarts) :and n := nil
:until (and (typep n 'integer) (>= n 0) (< n k))
:do (progn (format *query-io* "~&Option [0-~A]: " (1- k))
(finish-output *query-io*)
(setq n (read *query-io*))
(fresh-line *query-io*))
:finally (invoke-restart-interactively (nth n restarts)))))
# # # # NOTE : this macro used to bind only for errors , but other kinds of
;; errors may actually occur, for instance when retreiving a lispobj option's
;; value.
(defmacro with-context-error-handler (context &body body)
"Execute BODY with CONTEXT's error handler bound for CONDITION."
(let ((the-context (gensym "context")))
`(let ((,the-context ,context))
(handler-bind
((error
(lambda (error)
(ecase (error-handler ,the-context)
(:interactive
(restart-on-error error))
(:help
(print-error error)
# # # # NOTE : there are two special cases below .
1 . For an unknown command - line option error , we print
the help rather than the application one if the
;; unknown option looks like a Clon one (i.e., it starts
;; with "clon"-.
2 . For an error related to a known option , there 's no
;; point in printing a full help anyway, so we just fall
;; back to the behavior of :quit.
(cond ((and (typep error 'unknown-cmdline-option-error)
(>= (length (item error)) 5)
(string= "clon-" (subseq (item error) 0 5)))
(help :context ,the-context
:item (clon-options-group context)))
((typep error 'option-error)) ;; do nothing
(t
(help :context ,the-context)))
(uiop:quit 1))
(:quit
(exit-abnormally error))
(:none)))))
,@body))))
;; ==========================================================================
;; The Context Class
;; ==========================================================================
(defstruct cmdline-option
the option 's name as used on the cmdline
option ;; the corresponding option object
value ;; the converted option's cmdline value
source ;; the value source
)
(defclass context ()
((synopsis :documentation "The program synopsis."
:type synopsis
:initarg :synopsis
:reader synopsis
:initform *synopsis*)
(progname :documentation ~"The program name "
~"as it appears on the command-line."
:type string) ;; see below for reader
(cmdline-options :documentation "The options from the command-line."
:type list ;; of cmdline-option objects
:initform nil ;; for bootstrapping the context
:accessor cmdline-options)
(remainder :documentation "The non-Clon part of the command-line."
:type list) ;; see below for reader
(search-path :documentation "The search path for Clon files."
:reader search-path)
(theme :documentation "The theme filename."
:reader theme)
(line-width :documentation "The line width for help display."
:reader line-width)
(highlight :documentation "Clon's output highlight mode."
:reader highlight)
(error-handler :documentation ~"The behavior to adopt "
~"on option retrieval errors."
:type symbol
:initform :quit ;; see the warning in initialize-instance
:reader error-handler))
(:default-initargs
:cmdline (cmdline))
(:documentation "The CONTEXT class.
This class represents the associatiion of a synopsis and a set of command-line
options based on it."))
(defun progname (&key (context *context*))
"Return CONTEXT's program name."
(slot-value context 'progname))
(defun remainder (&key (context *context*))
"Return CONTEXT's remainder."
(slot-value context 'remainder))
(defun cmdline-options-p (&key (context *context*))
"Return T if CONTEXT has any unprocessed options left."
(if (cmdline-options context) t nil))
(defun cmdline-p (&key (context *context*))
"Return T if CONTEXT has anything on its command-line."
(or (cmdline-options-p :context context)
(remainder :context context)))
;; --------------------------------------------
;; Convenience wrappers around context synopsis
;; --------------------------------------------
(defmethod postfix ((context context))
"Return the postfix of CONTEXT's synopsis."
(postfix (synopsis context)))
(defmethod short-pack ((context context))
"Return the short pack of CONTEXT's synopsis."
(short-pack (synopsis context)))
(defmethod negated-pack ((context context))
"Return the negated pack of CONTEXT's synopsis."
(negated-pack (synopsis context)))
(defmethod clon-options-group ((context context))
"Return the Clon options group of CONTEXT's synopsis."
(clon-options-group (synopsis context)))
(defmethod potential-pack-p (pack (context context))
"Return t if PACK (a string) is a potential pack in CONTEXT."
(potential-pack-p pack (synopsis context)))
# # # # WARNING : the two wrappers below are here to make the DO - OPTIONS macro
;; work directly on contexts. Beware that both of them are needed.
(defmethod mapoptions (func (context context))
"Map FUNC over all options in CONTEXT synopsis."
(mapoptions func (synopsis context)))
(defmethod untraverse ((context context))
"Untraverse CONTEXT synopsis."
(untraverse (synopsis context)))
;; =========================================================================
The Help Protocol
;; =========================================================================
# # # # NOTE : all help related parameters but OUTPUT - STREAM have a
;; corresponding slot in contexts that act as a default value. The idea is
;; that users can in turn specify their preferences in the corresponding
;; environment variables. I don't think it would make much sense to provide an
;; option for OUTPUT-STREAM. At the end-user level, you can redirect to a file
;; from the shell.
(defun help (&key (context *context*)
(item (synopsis context))
(output-stream *standard-output*)
(search-path (search-path context))
(theme (theme context))
(line-width (line-width context))
(highlight (highlight context)))
"Print CONTEXT's help."
(let ((sheet (make-sheet :output-stream output-stream
:search-path search-path
:theme theme
:line-width line-width
:highlight highlight)))
(print-help sheet
(help-spec item
:program (pathname-name (progname :context context))
:unhide t))
(flush-sheet sheet)))
;; =========================================================================
The Option Search Protocol
;; =========================================================================
(defun search-option-by-name (context &rest keys &key short-name long-name)
"Search for option with either SHORT-NAME or LONG-NAME in CONTEXT.
When such an option exists, return two values:
- the option itself,
- the name that matched."
(declare (ignore short-name long-name))
(do-options (option context)
(let ((name (apply #'match-option option keys)))
(when name
(return-from search-option-by-name (values option name))))))
(defun search-option-by-abbreviation (context partial-name)
"Search for option abbreviated with PARTIAL-NAME in CONTEXT.
When such an option exists, return two values:
- the option itself,
- the completed name."
(let ((shortest-distance most-positive-fixnum)
closest-option)
(do-options (option context)
(let ((distance (option-abbreviation-distance option partial-name)))
(when (< distance shortest-distance)
(setq shortest-distance distance)
(setq closest-option option))))
(when closest-option
(values closest-option
;; When long names are abbreviated (for instance --he instead of
;; --help), we register the command-line name like this: he(lp).
;; In case of error report, this will help the user spot where
;; he did something wrong.
(complete-string partial-name (long-name closest-option))))))
#i(search-option 1)
(defun search-option
(context &rest keys &key short-name long-name partial-name)
"Search for an option in CONTEXT.
The search is done with SHORT-NAME, LONG-NAME, or PARTIAL-NAME.
In case of a PARTIAL-NAME search, look for an option the long name of which
begins with it.
In case of multiple matches by PARTIAL-NAME, the longest match is selected.
When such an option exists, return wo values:
- the option itself,
- the name used to find the option, possibly completed if partial."
(econd ((or short-name long-name)
(apply #'search-option-by-name context keys))
(partial-name
(search-option-by-abbreviation context partial-name))))
(defun search-sticky-option (context namearg)
"Search for a sticky option in CONTEXT, matching NAMEARG.
NAMEARG is the concatenation of the option's short name and its argument.
In case of multiple matches, the option with the longest name is selected.
When such an option exists, return two values:
- the option itself,
- the argument part of NAMEARG."
(let ((longest-distance 0)
closest-option)
(do-options (option context)
(let ((distance (option-sticky-distance option namearg)))
(when (> distance longest-distance)
(setq longest-distance distance)
(setq closest-option option))))
(when closest-option
(values closest-option (subseq namearg longest-distance)))))
;; ==========================================================================
The Option Retrieval Protocol
;; ==========================================================================
(defun getopt (&rest keys
&key (context *context*) short-name long-name option)
"Get an option's value in CONTEXT.
The option can be specified either by SHORT-NAME, LONG-NAME, or directly via
an OPTION object.
Return two values:
- the retrieved value,
- the value's source."
(unless option
(setq option
(apply #'search-option context (remove-keys keys :context))))
(unless option
(error "Getting option ~S from synopsis ~A in context ~A: unknown option."
(or short-name long-name)
(synopsis context)
context))
;; Try the command-line:
(let ((cmdline-options (list)))
(do ((cmdline-option
(pop (cmdline-options context))
(pop (cmdline-options context))))
((null cmdline-option))
(cond ((eq (cmdline-option-option cmdline-option) option)
(setf (cmdline-options context)
Actually , I * do * have a use for nreconc ;-)
(nreconc cmdline-options (cmdline-options context)))
(return-from getopt
(values (cmdline-option-value cmdline-option)
(list (cmdline-option-source cmdline-option)
(cmdline-option-name cmdline-option)))))
(t
(push cmdline-option cmdline-options))))
(setf (cmdline-options context) (nreverse cmdline-options)))
;; Try an environment variable:
(with-context-error-handler context
(let* ((env-var (env-var option))
(env-val (getenv env-var)))
(when env-val
(return-from getopt
(values (retrieve-from-environment option env-val)
(list :environement env-var))))))
;; Try a default value:
(when (and (typep option 'valued-option)
(slot-boundp option 'default-value))
(values (default-value option) :default)))
(defun getopt-cmdline (&key (context *context*))
"Get the next command-line option in CONTEXT.
When there is no next command-line option, return nil.
Otherwise, return four values:
- the option object,
- the option's name used on the command-line,
- the retrieved value,
- the value source."
(let ((cmdline-option (pop (cmdline-options context))))
(when cmdline-option
(values (cmdline-option-option cmdline-option)
(cmdline-option-name cmdline-option)
(cmdline-option-value cmdline-option)
(cmdline-option-source cmdline-option)))))
(defmacro multiple-value-getopt-cmdline
((option name value source &key context) &body body)
"Get the next command-line option in CONTEXT. and evaluate BODY.
OPTION, NAME and VALUE are bound to the values returned by GETOPT-CMDLINE.
BODY is executed only if there is a next command-line option."
`(multiple-value-bind (,option ,name ,value ,source)
(getopt-cmdline :context (or ,context *context*))
(when ,option
,@body)))
(defmacro do-cmdline-options
((option name value source &key context) &body body)
"Evaluate BODY over all command-line options in CONTEXT.
OPTION, NAME and VALUE are bound to each option's object, name used on the
command-line and retrieved value."
(let ((ctx (gensym "context")))
`(let ((,ctx (or ,context *context*)))
(do () ((null (cmdline-options ,ctx)))
(multiple-value-getopt-cmdline
(,option ,name ,value ,source :context ,ctx)
,@body)))))
;; ==========================================================================
;; Context Instance Creation
;; ==========================================================================
(defun read-long-name ()
"Read an option's long name from standard input."
(format t "Please type in the correct option's long name:~%")
(let (line)
(loop (setq line (read-line))
(if (position #\= line)
(format t "Option names can't contain equal signs. Try again:~%")
(return (list line))))))
(defun read-call (&optional negated)
"Read an option's call or pack from standard input.
If NEGATED, read a negated call or pack. Otherwise, read a short call or pack."
(format t "Please type in the correct ~
~:[short~;negated~] call or pack:~%"
negated)
(list (read-line)))
#i(push-cmdline-option 1)
#i(push-retrieved-option 3)
(defmethod initialize-instance :after ((context context) &key cmdline progname)
"Parse CMDLINE."
(setf (slot-value context 'progname) (pop cmdline))
(when progname
# # # # NOTE : we are more tolerant with empty strings coming from the
;; environment (discarded) than we are on programmatic ones. That's
;; because we are less sure about who's responsible.
# # # # FIXME : see about better error / warning handling here .
(econd ((and (stringp progname) (not (zerop (length progname))))
(setf (slot-value context 'progname) progname))
((eq progname :environment)
(let ((progname (getenv "__CL_ARGV0")))
(when (and progname (not (zerop (length progname))))
(setf (slot-value context 'progname) progname))))))
# # # # WARNING : we have several bootstrapping problems related to error
handling here . First of all , the error handler is set up by the
;; --clon-error-handler option, but in order to retrieve this option, we
;; need to parse the command-line, which might trigger some errors. Next, if
the : help error handler is selected , we also need four other values
;; (search-path, theme, highlight, and line-width), all of which also being
;; set up by options likely to trigger errors. Fortunately, there is a way
;; out of this. The general idea is to set up all that information as soon
;; as possible, while always making sure that we are in a consistent state.
;; More specifically, this is how it works.
1 . A very early error handler value of : quit is provided in the class
definition , thanks to an : initform . This handler does n't require
;; anything particular to work out the box (in fact, it is also the
default one ) .
2 . Before doing anything else , we try to get the four other values from
;; the environment. As a matter of fact, user settings are much likely to
;; be found there anyway, than on the actual command-line. This is in
;; fact very simple to do: we can already use our context, eventhough it
;; is not completely initialized yet. The only ;; thing we need is a nil
CMDLINE - OPTIONS slot , so that GETOPT directly goes to environment
;; retrieval. If there's an error during this process, the handler is
;; :quit, which is ok.
(setf (slot-value context 'search-path)
(getopt :context context :long-name "clon-search-path"))
(setf (slot-value context 'theme)
(getopt :context context :long-name "clon-theme"))
(setf (slot-value context 'line-width)
(getopt :context context :long-name "clon-line-width"))
(setf (slot-value context 'highlight)
(getopt :context context :long-name "clon-highlight"))
3 . If everything goes well , we finally try to get another error handler
;; from the environment as well. At that point, it would be ok to find
;; :help. If nothing is found in the environment, the default value is
;; retrieved, which is also :quit.
(setf (slot-value context 'error-handler)
(getopt :long-name "clon-error-handler" :context context))
4 . Finally , during command - line parsing , we systematically check if we
got one of those five particular options , and handle them immediately
;; instead of waiting for the end of the process.
;; Step one: parse the command-line =======================================
(let ((cmdline-options (list))
(remainder (list)))
(macrolet ((push-cmdline-option (place &rest body)
"Push a new CMDLINE-OPTION created with BODY onto PLACE."
`(push (make-cmdline-option ,@body) ,place))
(push-retrieved-option (place func option
&optional cmdline-value cmdline)
"Retrieve OPTION from a FUNC call and push it onto PLACE.
- FUNC must be either :short or :negated,
- CMDLINE-VALUE is a potentially already parsed option argument,
- CMDILNE is where to find a potentially required argument."
(let* ((value (gensym "value"))
(source (gensym "source"))
(vars (list source value))
(call (list option
(find-symbol
(concatenate 'string
# # # # NOTE : case portability
(string :retrieve-from-)
(symbol-name func)
(string :-call))
:net.didierverna.clon)))
new-cmdline)
(when cmdline-value
(push cmdline-value call))
(when cmdline
(setq new-cmdline (gensym "new-cmdline"))
(push new-cmdline vars)
(unless cmdline-value
(push nil call))
(push cmdline call))
`(multiple-value-bind ,(reverse vars) ,(reverse call)
,(when cmdline `(setq ,cmdline ,new-cmdline))
(push-cmdline-option ,place
:name (short-name ,option)
:option ,option
:value ,value
:source ,source))))
(do-pack ((option pack context) &body body)
"Evaluate BODY with OPTION bound to each option from PACK.
CONTEXT is where to look for the options."
(let ((char (gensym "char"))
(name (gensym "name")))
`(loop :for ,char :across ,pack
:do (let* ((,name (make-string 1
:initial-element ,char))
(,option (search-option ,context
:short-name ,name)))
(assert ,option)
,@body)))))
(with-context-error-handler context
(do ((arg (pop cmdline) (pop cmdline)))
((null arg))
(cond ((string= arg "--")
The separator .
(setq remainder cmdline)
(setq cmdline nil))
((beginning-of-string-p "--" arg)
;; A long call.
(let* ((value-start (position #\= arg :start 2))
(cmdline-name (subseq arg 2 value-start))
(cmdline-value (when value-start
(subseq arg (1+ value-start))))
option-name option)
(tagbody find-option
(setq option-name cmdline-name)
(setq option
(search-option context :long-name cmdline-name))
(unless option
(multiple-value-setq (option option-name)
(search-option context :partial-name cmdline-name)))
(if option
(multiple-value-bind (value source new-cmdline)
(retrieve-from-long-call option
option-name
cmdline-value
cmdline)
(setq cmdline new-cmdline)
# # # # NOTE : see comment at the top of this
;; function about the bootstrapping problems.
(cond ((string= (long-name option)
"clon-search-path")
(setf (slot-value context 'search-path)
value))
((string= (long-name option)
"clon-theme")
(setf (slot-value context 'theme)
value))
((string= (long-name option)
"clon-line-width")
(setf (slot-value context 'line-width)
value))
((string= (long-name option)
"clon-highlight")
(setf (slot-value context 'highlight)
value))
((string= (long-name option)
"clon-error-handler")
(setf (slot-value context 'error-handler)
value))
(t
(push-cmdline-option cmdline-options
:name option-name
:option option
:value value
:source source))))
(restart-case (error 'unknown-cmdline-option-error
:name cmdline-name
:argument cmdline-value)
(discard ()
:report "Discard unknown option."
nil)
(fix-option-name (new-cmdline-name)
:report "Fix the option's long name."
:interactive read-long-name
(setq cmdline-name new-cmdline-name)
(go find-option)))))))
;; A short call, or a short pack.
((beginning-of-string-p "-" arg)
(tagbody figure-this-short-call
(let* ((value-start (position #\= arg :start 2))
(cmdline-name (subseq arg 1 value-start))
(cmdline-value (when value-start
(subseq arg (1+ value-start))))
option)
(when cmdline-value
(restart-case
(error 'invalid-short-equal-syntax :item arg)
(discard-argument ()
:report "Discard the argument."
(setq cmdline-value nil))
(stick-argument ()
:report "Stick argument to option name."
(setq cmdline-name
(concatenate 'string
cmdline-name cmdline-value))
(setq cmdline-value nil))
(separate-argument ()
:report "Separate option from its argument."
(push cmdline-value cmdline)
(setq cmdline-value nil))))
(setq option
(search-option context :short-name cmdline-name))
(unless option
(multiple-value-setq (option cmdline-value)
(search-sticky-option context cmdline-name)))
(cond (option
(push-retrieved-option cmdline-options :short
option cmdline-value
cmdline))
((potential-pack-p cmdline-name context)
# # # # NOTE : When parsing a short pack , only the
;; last option gets a cmdline argument because
;; only the last one is allowed to retrieve an
;; argument from there.
(do-pack (option
(subseq cmdline-name 0
(1- (length cmdline-name)))
context)
(push-retrieved-option cmdline-options :short
option))
(let* ((name (subseq cmdline-name
(1- (length cmdline-name))))
(option (search-option context
:short-name name)))
(assert option)
(push-retrieved-option
cmdline-options :short option nil cmdline)))
(t
(restart-case
(error 'unrecognized-short-call-error
:short-call cmdline-name)
(discard ()
:report "Discard this short call."
nil)
(fix-short-call (new-cmdline-name)
:report "Fix this short call."
:interactive (lambda () (read-call))
(setq arg (concatenate 'string
"-" new-cmdline-name))
(go figure-this-short-call))))))))
;; A negated call or pack.
((beginning-of-string-p "+" arg)
(block processing-negated-call
(tagbody figure-this-negated-call
(let* ((value-start (position #\= arg :start 2))
(cmdline-name (subseq arg 1 value-start))
(cmdline-value (when value-start
(subseq arg (1+ value-start))))
option)
(when cmdline-value
(restart-case
(error 'invalid-negated-equal-syntax :item arg)
(discard-argument ()
:report "Discard the argument."
(setq cmdline-value nil))
(convert-to-short-and-stick ()
:report
"Convert to short call and stick argument."
(push (concatenate 'string
"-" cmdline-name cmdline-value)
cmdline)
(return-from processing-negated-call))
(convert-to-short-and-split ()
:report
"Convert to short call and split argument."
(push cmdline-value cmdline)
(push (concatenate 'string "-" cmdline-name)
cmdline)
(return-from processing-negated-call))))
# # # # NOTE : in theory , we could allow partial
;; matches on short names when they're used with the
;; negated syntax, because there's no sticky argument
;; or whatever. But we don't. That's all. Short names
;; are not meant to be long (otherwise, that would be
;; long names right?), so they're not meant to be
;; abbreviated.
(setq option
(search-option context :short-name cmdline-name))
(cond (option
(push-retrieved-option cmdline-options :negated
option))
((potential-pack-p cmdline-name context)
(do-pack (option cmdline-name context)
(push-retrieved-option cmdline-options
:negated option)))
(t
(restart-case
(error 'unrecognized-negated-call-error
:negated-call cmdline-name)
(discard ()
:report "Discard this negated call."
nil)
(fix-negated-call (new-cmdline-name)
:report "Fix this negated call."
:interactive (lambda ()
(read-call :negated))
(setq arg (concatenate 'string
"+" new-cmdline-name))
(go figure-this-negated-call)))))))))
(t
;; Not an option call. Consider this as an implicit remainder
;; if one is expected. Contrary to the case of an explicit
;; one however (separated from the rest of the cmdline by
;; --), trigger an error if a remainder is not expected.
(cond ((null (postfix context))
(setq arg (cons arg cmdline))
(setq cmdline nil)
;; Note that here, the whole remainder of the
;; cmdline might be discraded at once.
(restartable-cmdline-junk-error arg))
(t
(setq remainder (cons arg cmdline))
(setq cmdline nil)))))))
(setf (cmdline-options context) (nreverse cmdline-options))
(setf (slot-value context 'remainder) remainder)))
Step two : handle internal options = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(when (getopt :context context :long-name "clon-banner")
(format t "~A's command-line is powered by Clon,
the Command-Line Options Nuker library, version ~A,
written by Didier Verna <>.
Copyright (C) ~A Didier Verna
Clon is released under the terms of the BSD license.
See -license for more information.
Clon is provided with NO warranty; not even for MERCHANTABILITY
or FITNESS FOR A PARTICULAR PURPOSE.~%"
(pathname-name (progname :context context))
(version :long)
*copyright-years*)
(uiop:quit))
(let ((version-format (getopt :context context :long-name "clon-version")))
(when version-format
(format t "~A~%" (version version-format))
(uiop:quit)))
(when (getopt :context context :long-name "clon-lisp-information")
(format t "~A ~A~%"
(lisp-implementation-type)
(lisp-implementation-version))
(uiop:quit))
(when (getopt :context context :long-name "clon-help")
(help :context context :item (clon-options-group context))
(uiop:quit)))
(defun make-context
(&rest keys &key synopsis cmdline progname (make-current t))
"Make a new context.
- SYNOPSIS is the program synopsis to use in that context.
It defaults to *SYNOPSIS*.
- CMDLINE is the argument list (strings) to process.
It defaults to a POSIX conformant argv.
- PROGNAME is an alternate value for argv[0].
It defaults to NIL, in which case the actual argv[0] is used.
Otherwise, it can be a non-empty string, standing for itself,
or :environment meaning to retrieve the value of the __CL_ARGV0 environment
variable (ignored if it's empty).
value.
- If MAKE-CURRENT, make the new context current. This is the default."
(declare (ignore synopsis cmdline progname))
(let ((context (apply #'make-instance 'context
(remove-keys keys :make-current))))
(when make-current
(setq *context* context))
context))
;; ==========================================================================
Context Manipulation Utilities
;; ==========================================================================
(defmacro with-context (context &body body)
"Execute BODY with *context* bound to CONTEXT."
`(let ((*context* ,context))
,@body))
context.lisp ends here
| null |
https://raw.githubusercontent.com/didierverna/clon/dc4b0e2c4f654d5c99c1140b4d3cabb9c15e769c/core/src/context.lisp
|
lisp
|
context.lisp --- Context management
Permission to use, copy, modify, and 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.
Commentary:
Code:
==========================================================================
Command-line error management (not regarding known options)
==========================================================================
errors may actually occur, for instance when retreiving a lispobj option's
value.
unknown option looks like a Clon one (i.e., it starts
with "clon"-.
point in printing a full help anyway, so we just fall
back to the behavior of :quit.
do nothing
==========================================================================
The Context Class
==========================================================================
the corresponding option object
the converted option's cmdline value
the value source
see below for reader
of cmdline-option objects
for bootstrapping the context
see below for reader
see the warning in initialize-instance
--------------------------------------------
Convenience wrappers around context synopsis
--------------------------------------------
work directly on contexts. Beware that both of them are needed.
=========================================================================
=========================================================================
corresponding slot in contexts that act as a default value. The idea is
that users can in turn specify their preferences in the corresponding
environment variables. I don't think it would make much sense to provide an
option for OUTPUT-STREAM. At the end-user level, you can redirect to a file
from the shell.
=========================================================================
=========================================================================
When long names are abbreviated (for instance --he instead of
--help), we register the command-line name like this: he(lp).
In case of error report, this will help the user spot where
he did something wrong.
==========================================================================
==========================================================================
Try the command-line:
-)
Try an environment variable:
Try a default value:
==========================================================================
Context Instance Creation
==========================================================================
negated~] call or pack:~%"
environment (discarded) than we are on programmatic ones. That's
because we are less sure about who's responsible.
--clon-error-handler option, but in order to retrieve this option, we
need to parse the command-line, which might trigger some errors. Next, if
(search-path, theme, highlight, and line-width), all of which also being
set up by options likely to trigger errors. Fortunately, there is a way
out of this. The general idea is to set up all that information as soon
as possible, while always making sure that we are in a consistent state.
More specifically, this is how it works.
anything particular to work out the box (in fact, it is also the
the environment. As a matter of fact, user settings are much likely to
be found there anyway, than on the actual command-line. This is in
fact very simple to do: we can already use our context, eventhough it
is not completely initialized yet. The only ;; thing we need is a nil
retrieval. If there's an error during this process, the handler is
:quit, which is ok.
from the environment as well. At that point, it would be ok to find
:help. If nothing is found in the environment, the default value is
retrieved, which is also :quit.
instead of waiting for the end of the process.
Step one: parse the command-line =======================================
A long call.
function about the bootstrapping problems.
A short call, or a short pack.
last option gets a cmdline argument because
only the last one is allowed to retrieve an
argument from there.
A negated call or pack.
matches on short names when they're used with the
negated syntax, because there's no sticky argument
or whatever. But we don't. That's all. Short names
are not meant to be long (otherwise, that would be
long names right?), so they're not meant to be
abbreviated.
Not an option call. Consider this as an implicit remainder
if one is expected. Contrary to the case of an explicit
one however (separated from the rest of the cmdline by
--), trigger an error if a remainder is not expected.
Note that here, the whole remainder of the
cmdline might be discraded at once.
not even for MERCHANTABILITY
==========================================================================
==========================================================================
|
Copyright ( C ) 2010 - 2012 , 2015 , 2017 , 2020 , 2021
Author : < >
This file is part of .
THIS 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
Contents management by FCM version 0.1 .
(in-package :net.didierverna.clon)
(in-readtable :net.didierverna.clon)
(defvar *context* nil "The current context.")
(define-condition invalid-short-equal-syntax (cmdline-error)
()
(:report (lambda (error stream)
(format stream "Invalid = syntax in short call: ~S."
(item error))))
(:documentation "An error related to a short-equal syntax."))
(define-condition invalid-negated-equal-syntax (cmdline-error)
()
(:report (lambda (error stream)
(format stream "Invalid = syntax in negated call: ~S."
(item error))))
(:documentation "An error related to a negated-equal syntax."))
(define-condition cmdline-junk-error (cmdline-error)
inherited from the CMDLINE - ERROR condition
:documentation "The piece of junk appearing on the command-line."
:initarg :junk
:reader junk))
(:report (lambda (error stream)
(format stream "Junk on the command-line: ~S." (junk error))))
(:documentation "An error related to a command-line piece of junk."))
(defun restartable-cmdline-junk-error (junk)
(restart-case (error 'cmdline-junk-error :junk junk)
(discard ()
:report "Discard junk."
nil)))
(define-condition unrecognized-short-call-error (cmdline-error)
inherited from the CMDLINE - ERROR condition
:documentation "The unrecognized short call on the command-line."
:initarg :short-call
:reader short-call))
(:report (lambda (error stream)
(format stream "Unrecognized option or short pack: ~S."
(short-call error))))
(:documentation "An error related to an unrecognized short call."))
(define-condition unrecognized-negated-call-error (cmdline-error)
inherited from the CMDLINE - ERROR condition
:documentation "The unrecognized negated call on the command-line."
:initarg :negated-call
:reader negated-call))
(:report (lambda (error stream)
(format stream "Unrecognized option or negated pack: ~S."
(negated-call error))))
(:documentation "An error related to an unrecognized negated call."))
(define-condition unknown-cmdline-option-error (cmdline-error)
inherited from the CMDLINE - ERROR condition
:documentation "The option's name as it appears on the command-line."
:initarg :name
:reader name)
(argument :documentation "The option's command-line argument."
:initarg :argument
:reader argument))
(:report (lambda (error stream)
(format stream "Unknown command-line option ~
~S~@[ with argument ~S~]."
(name error)
(argument error))))
(:documentation "An error related to an unknown command-line option."))
(defun print-error (error
&optional interactivep
&aux (stream (if interactivep *query-io* *error-output*))
*print-escape*)
"Print ERROR on *ERROR-OUTPUT*.
When INTERACTIVEP, print on *QUERY-IO* instead."
(print-object error stream)
(terpri stream))
(defun exit-abnormally (error)
"Print ERROR on *ERROR-OUTPUT* and exit with status code 1."
(print-error error)
(uiop:quit 1))
Adapted from the Hyperspec
(defun restart-on-error (error)
"Print ERROR and offer available restarts on *QUERY-IO*."
(print-error error :interactive)
(format *query-io* "Available options:~%")
(let ((restarts (compute-restarts)))
(do ((i 0 (+ i 1)) (r restarts (cdr r))) ((null r))
(format *query-io* "~&~D: ~A~%" i (car r)))
(loop :with k := (length restarts) :and n := nil
:until (and (typep n 'integer) (>= n 0) (< n k))
:do (progn (format *query-io* "~&Option [0-~A]: " (1- k))
(finish-output *query-io*)
(setq n (read *query-io*))
(fresh-line *query-io*))
:finally (invoke-restart-interactively (nth n restarts)))))
# # # # NOTE : this macro used to bind only for errors , but other kinds of
(defmacro with-context-error-handler (context &body body)
"Execute BODY with CONTEXT's error handler bound for CONDITION."
(let ((the-context (gensym "context")))
`(let ((,the-context ,context))
(handler-bind
((error
(lambda (error)
(ecase (error-handler ,the-context)
(:interactive
(restart-on-error error))
(:help
(print-error error)
# # # # NOTE : there are two special cases below .
1 . For an unknown command - line option error , we print
the help rather than the application one if the
2 . For an error related to a known option , there 's no
(cond ((and (typep error 'unknown-cmdline-option-error)
(>= (length (item error)) 5)
(string= "clon-" (subseq (item error) 0 5)))
(help :context ,the-context
:item (clon-options-group context)))
(t
(help :context ,the-context)))
(uiop:quit 1))
(:quit
(exit-abnormally error))
(:none)))))
,@body))))
(defstruct cmdline-option
the option 's name as used on the cmdline
)
(defclass context ()
((synopsis :documentation "The program synopsis."
:type synopsis
:initarg :synopsis
:reader synopsis
:initform *synopsis*)
(progname :documentation ~"The program name "
~"as it appears on the command-line."
(cmdline-options :documentation "The options from the command-line."
:accessor cmdline-options)
(remainder :documentation "The non-Clon part of the command-line."
(search-path :documentation "The search path for Clon files."
:reader search-path)
(theme :documentation "The theme filename."
:reader theme)
(line-width :documentation "The line width for help display."
:reader line-width)
(highlight :documentation "Clon's output highlight mode."
:reader highlight)
(error-handler :documentation ~"The behavior to adopt "
~"on option retrieval errors."
:type symbol
:reader error-handler))
(:default-initargs
:cmdline (cmdline))
(:documentation "The CONTEXT class.
This class represents the associatiion of a synopsis and a set of command-line
options based on it."))
(defun progname (&key (context *context*))
"Return CONTEXT's program name."
(slot-value context 'progname))
(defun remainder (&key (context *context*))
"Return CONTEXT's remainder."
(slot-value context 'remainder))
(defun cmdline-options-p (&key (context *context*))
"Return T if CONTEXT has any unprocessed options left."
(if (cmdline-options context) t nil))
(defun cmdline-p (&key (context *context*))
"Return T if CONTEXT has anything on its command-line."
(or (cmdline-options-p :context context)
(remainder :context context)))
(defmethod postfix ((context context))
"Return the postfix of CONTEXT's synopsis."
(postfix (synopsis context)))
(defmethod short-pack ((context context))
"Return the short pack of CONTEXT's synopsis."
(short-pack (synopsis context)))
(defmethod negated-pack ((context context))
"Return the negated pack of CONTEXT's synopsis."
(negated-pack (synopsis context)))
(defmethod clon-options-group ((context context))
"Return the Clon options group of CONTEXT's synopsis."
(clon-options-group (synopsis context)))
(defmethod potential-pack-p (pack (context context))
"Return t if PACK (a string) is a potential pack in CONTEXT."
(potential-pack-p pack (synopsis context)))
# # # # WARNING : the two wrappers below are here to make the DO - OPTIONS macro
(defmethod mapoptions (func (context context))
"Map FUNC over all options in CONTEXT synopsis."
(mapoptions func (synopsis context)))
(defmethod untraverse ((context context))
"Untraverse CONTEXT synopsis."
(untraverse (synopsis context)))
The Help Protocol
# # # # NOTE : all help related parameters but OUTPUT - STREAM have a
(defun help (&key (context *context*)
(item (synopsis context))
(output-stream *standard-output*)
(search-path (search-path context))
(theme (theme context))
(line-width (line-width context))
(highlight (highlight context)))
"Print CONTEXT's help."
(let ((sheet (make-sheet :output-stream output-stream
:search-path search-path
:theme theme
:line-width line-width
:highlight highlight)))
(print-help sheet
(help-spec item
:program (pathname-name (progname :context context))
:unhide t))
(flush-sheet sheet)))
The Option Search Protocol
(defun search-option-by-name (context &rest keys &key short-name long-name)
"Search for option with either SHORT-NAME or LONG-NAME in CONTEXT.
When such an option exists, return two values:
- the option itself,
- the name that matched."
(declare (ignore short-name long-name))
(do-options (option context)
(let ((name (apply #'match-option option keys)))
(when name
(return-from search-option-by-name (values option name))))))
(defun search-option-by-abbreviation (context partial-name)
"Search for option abbreviated with PARTIAL-NAME in CONTEXT.
When such an option exists, return two values:
- the option itself,
- the completed name."
(let ((shortest-distance most-positive-fixnum)
closest-option)
(do-options (option context)
(let ((distance (option-abbreviation-distance option partial-name)))
(when (< distance shortest-distance)
(setq shortest-distance distance)
(setq closest-option option))))
(when closest-option
(values closest-option
(complete-string partial-name (long-name closest-option))))))
#i(search-option 1)
(defun search-option
(context &rest keys &key short-name long-name partial-name)
"Search for an option in CONTEXT.
The search is done with SHORT-NAME, LONG-NAME, or PARTIAL-NAME.
In case of a PARTIAL-NAME search, look for an option the long name of which
begins with it.
In case of multiple matches by PARTIAL-NAME, the longest match is selected.
When such an option exists, return wo values:
- the option itself,
- the name used to find the option, possibly completed if partial."
(econd ((or short-name long-name)
(apply #'search-option-by-name context keys))
(partial-name
(search-option-by-abbreviation context partial-name))))
(defun search-sticky-option (context namearg)
"Search for a sticky option in CONTEXT, matching NAMEARG.
NAMEARG is the concatenation of the option's short name and its argument.
In case of multiple matches, the option with the longest name is selected.
When such an option exists, return two values:
- the option itself,
- the argument part of NAMEARG."
(let ((longest-distance 0)
closest-option)
(do-options (option context)
(let ((distance (option-sticky-distance option namearg)))
(when (> distance longest-distance)
(setq longest-distance distance)
(setq closest-option option))))
(when closest-option
(values closest-option (subseq namearg longest-distance)))))
The Option Retrieval Protocol
(defun getopt (&rest keys
&key (context *context*) short-name long-name option)
"Get an option's value in CONTEXT.
The option can be specified either by SHORT-NAME, LONG-NAME, or directly via
an OPTION object.
Return two values:
- the retrieved value,
- the value's source."
(unless option
(setq option
(apply #'search-option context (remove-keys keys :context))))
(unless option
(error "Getting option ~S from synopsis ~A in context ~A: unknown option."
(or short-name long-name)
(synopsis context)
context))
(let ((cmdline-options (list)))
(do ((cmdline-option
(pop (cmdline-options context))
(pop (cmdline-options context))))
((null cmdline-option))
(cond ((eq (cmdline-option-option cmdline-option) option)
(setf (cmdline-options context)
(nreconc cmdline-options (cmdline-options context)))
(return-from getopt
(values (cmdline-option-value cmdline-option)
(list (cmdline-option-source cmdline-option)
(cmdline-option-name cmdline-option)))))
(t
(push cmdline-option cmdline-options))))
(setf (cmdline-options context) (nreverse cmdline-options)))
(with-context-error-handler context
(let* ((env-var (env-var option))
(env-val (getenv env-var)))
(when env-val
(return-from getopt
(values (retrieve-from-environment option env-val)
(list :environement env-var))))))
(when (and (typep option 'valued-option)
(slot-boundp option 'default-value))
(values (default-value option) :default)))
(defun getopt-cmdline (&key (context *context*))
"Get the next command-line option in CONTEXT.
When there is no next command-line option, return nil.
Otherwise, return four values:
- the option object,
- the option's name used on the command-line,
- the retrieved value,
- the value source."
(let ((cmdline-option (pop (cmdline-options context))))
(when cmdline-option
(values (cmdline-option-option cmdline-option)
(cmdline-option-name cmdline-option)
(cmdline-option-value cmdline-option)
(cmdline-option-source cmdline-option)))))
(defmacro multiple-value-getopt-cmdline
((option name value source &key context) &body body)
"Get the next command-line option in CONTEXT. and evaluate BODY.
OPTION, NAME and VALUE are bound to the values returned by GETOPT-CMDLINE.
BODY is executed only if there is a next command-line option."
`(multiple-value-bind (,option ,name ,value ,source)
(getopt-cmdline :context (or ,context *context*))
(when ,option
,@body)))
(defmacro do-cmdline-options
((option name value source &key context) &body body)
"Evaluate BODY over all command-line options in CONTEXT.
OPTION, NAME and VALUE are bound to each option's object, name used on the
command-line and retrieved value."
(let ((ctx (gensym "context")))
`(let ((,ctx (or ,context *context*)))
(do () ((null (cmdline-options ,ctx)))
(multiple-value-getopt-cmdline
(,option ,name ,value ,source :context ,ctx)
,@body)))))
(defun read-long-name ()
"Read an option's long name from standard input."
(format t "Please type in the correct option's long name:~%")
(let (line)
(loop (setq line (read-line))
(if (position #\= line)
(format t "Option names can't contain equal signs. Try again:~%")
(return (list line))))))
(defun read-call (&optional negated)
"Read an option's call or pack from standard input.
If NEGATED, read a negated call or pack. Otherwise, read a short call or pack."
(format t "Please type in the correct ~
negated)
(list (read-line)))
#i(push-cmdline-option 1)
#i(push-retrieved-option 3)
(defmethod initialize-instance :after ((context context) &key cmdline progname)
"Parse CMDLINE."
(setf (slot-value context 'progname) (pop cmdline))
(when progname
# # # # NOTE : we are more tolerant with empty strings coming from the
# # # # FIXME : see about better error / warning handling here .
(econd ((and (stringp progname) (not (zerop (length progname))))
(setf (slot-value context 'progname) progname))
((eq progname :environment)
(let ((progname (getenv "__CL_ARGV0")))
(when (and progname (not (zerop (length progname))))
(setf (slot-value context 'progname) progname))))))
# # # # WARNING : we have several bootstrapping problems related to error
handling here . First of all , the error handler is set up by the
the : help error handler is selected , we also need four other values
1 . A very early error handler value of : quit is provided in the class
definition , thanks to an : initform . This handler does n't require
default one ) .
2 . Before doing anything else , we try to get the four other values from
CMDLINE - OPTIONS slot , so that GETOPT directly goes to environment
(setf (slot-value context 'search-path)
(getopt :context context :long-name "clon-search-path"))
(setf (slot-value context 'theme)
(getopt :context context :long-name "clon-theme"))
(setf (slot-value context 'line-width)
(getopt :context context :long-name "clon-line-width"))
(setf (slot-value context 'highlight)
(getopt :context context :long-name "clon-highlight"))
3 . If everything goes well , we finally try to get another error handler
(setf (slot-value context 'error-handler)
(getopt :long-name "clon-error-handler" :context context))
4 . Finally , during command - line parsing , we systematically check if we
got one of those five particular options , and handle them immediately
(let ((cmdline-options (list))
(remainder (list)))
(macrolet ((push-cmdline-option (place &rest body)
"Push a new CMDLINE-OPTION created with BODY onto PLACE."
`(push (make-cmdline-option ,@body) ,place))
(push-retrieved-option (place func option
&optional cmdline-value cmdline)
"Retrieve OPTION from a FUNC call and push it onto PLACE.
- FUNC must be either :short or :negated,
- CMDLINE-VALUE is a potentially already parsed option argument,
- CMDILNE is where to find a potentially required argument."
(let* ((value (gensym "value"))
(source (gensym "source"))
(vars (list source value))
(call (list option
(find-symbol
(concatenate 'string
# # # # NOTE : case portability
(string :retrieve-from-)
(symbol-name func)
(string :-call))
:net.didierverna.clon)))
new-cmdline)
(when cmdline-value
(push cmdline-value call))
(when cmdline
(setq new-cmdline (gensym "new-cmdline"))
(push new-cmdline vars)
(unless cmdline-value
(push nil call))
(push cmdline call))
`(multiple-value-bind ,(reverse vars) ,(reverse call)
,(when cmdline `(setq ,cmdline ,new-cmdline))
(push-cmdline-option ,place
:name (short-name ,option)
:option ,option
:value ,value
:source ,source))))
(do-pack ((option pack context) &body body)
"Evaluate BODY with OPTION bound to each option from PACK.
CONTEXT is where to look for the options."
(let ((char (gensym "char"))
(name (gensym "name")))
`(loop :for ,char :across ,pack
:do (let* ((,name (make-string 1
:initial-element ,char))
(,option (search-option ,context
:short-name ,name)))
(assert ,option)
,@body)))))
(with-context-error-handler context
(do ((arg (pop cmdline) (pop cmdline)))
((null arg))
(cond ((string= arg "--")
The separator .
(setq remainder cmdline)
(setq cmdline nil))
((beginning-of-string-p "--" arg)
(let* ((value-start (position #\= arg :start 2))
(cmdline-name (subseq arg 2 value-start))
(cmdline-value (when value-start
(subseq arg (1+ value-start))))
option-name option)
(tagbody find-option
(setq option-name cmdline-name)
(setq option
(search-option context :long-name cmdline-name))
(unless option
(multiple-value-setq (option option-name)
(search-option context :partial-name cmdline-name)))
(if option
(multiple-value-bind (value source new-cmdline)
(retrieve-from-long-call option
option-name
cmdline-value
cmdline)
(setq cmdline new-cmdline)
# # # # NOTE : see comment at the top of this
(cond ((string= (long-name option)
"clon-search-path")
(setf (slot-value context 'search-path)
value))
((string= (long-name option)
"clon-theme")
(setf (slot-value context 'theme)
value))
((string= (long-name option)
"clon-line-width")
(setf (slot-value context 'line-width)
value))
((string= (long-name option)
"clon-highlight")
(setf (slot-value context 'highlight)
value))
((string= (long-name option)
"clon-error-handler")
(setf (slot-value context 'error-handler)
value))
(t
(push-cmdline-option cmdline-options
:name option-name
:option option
:value value
:source source))))
(restart-case (error 'unknown-cmdline-option-error
:name cmdline-name
:argument cmdline-value)
(discard ()
:report "Discard unknown option."
nil)
(fix-option-name (new-cmdline-name)
:report "Fix the option's long name."
:interactive read-long-name
(setq cmdline-name new-cmdline-name)
(go find-option)))))))
((beginning-of-string-p "-" arg)
(tagbody figure-this-short-call
(let* ((value-start (position #\= arg :start 2))
(cmdline-name (subseq arg 1 value-start))
(cmdline-value (when value-start
(subseq arg (1+ value-start))))
option)
(when cmdline-value
(restart-case
(error 'invalid-short-equal-syntax :item arg)
(discard-argument ()
:report "Discard the argument."
(setq cmdline-value nil))
(stick-argument ()
:report "Stick argument to option name."
(setq cmdline-name
(concatenate 'string
cmdline-name cmdline-value))
(setq cmdline-value nil))
(separate-argument ()
:report "Separate option from its argument."
(push cmdline-value cmdline)
(setq cmdline-value nil))))
(setq option
(search-option context :short-name cmdline-name))
(unless option
(multiple-value-setq (option cmdline-value)
(search-sticky-option context cmdline-name)))
(cond (option
(push-retrieved-option cmdline-options :short
option cmdline-value
cmdline))
((potential-pack-p cmdline-name context)
# # # # NOTE : When parsing a short pack , only the
(do-pack (option
(subseq cmdline-name 0
(1- (length cmdline-name)))
context)
(push-retrieved-option cmdline-options :short
option))
(let* ((name (subseq cmdline-name
(1- (length cmdline-name))))
(option (search-option context
:short-name name)))
(assert option)
(push-retrieved-option
cmdline-options :short option nil cmdline)))
(t
(restart-case
(error 'unrecognized-short-call-error
:short-call cmdline-name)
(discard ()
:report "Discard this short call."
nil)
(fix-short-call (new-cmdline-name)
:report "Fix this short call."
:interactive (lambda () (read-call))
(setq arg (concatenate 'string
"-" new-cmdline-name))
(go figure-this-short-call))))))))
((beginning-of-string-p "+" arg)
(block processing-negated-call
(tagbody figure-this-negated-call
(let* ((value-start (position #\= arg :start 2))
(cmdline-name (subseq arg 1 value-start))
(cmdline-value (when value-start
(subseq arg (1+ value-start))))
option)
(when cmdline-value
(restart-case
(error 'invalid-negated-equal-syntax :item arg)
(discard-argument ()
:report "Discard the argument."
(setq cmdline-value nil))
(convert-to-short-and-stick ()
:report
"Convert to short call and stick argument."
(push (concatenate 'string
"-" cmdline-name cmdline-value)
cmdline)
(return-from processing-negated-call))
(convert-to-short-and-split ()
:report
"Convert to short call and split argument."
(push cmdline-value cmdline)
(push (concatenate 'string "-" cmdline-name)
cmdline)
(return-from processing-negated-call))))
# # # # NOTE : in theory , we could allow partial
(setq option
(search-option context :short-name cmdline-name))
(cond (option
(push-retrieved-option cmdline-options :negated
option))
((potential-pack-p cmdline-name context)
(do-pack (option cmdline-name context)
(push-retrieved-option cmdline-options
:negated option)))
(t
(restart-case
(error 'unrecognized-negated-call-error
:negated-call cmdline-name)
(discard ()
:report "Discard this negated call."
nil)
(fix-negated-call (new-cmdline-name)
:report "Fix this negated call."
:interactive (lambda ()
(read-call :negated))
(setq arg (concatenate 'string
"+" new-cmdline-name))
(go figure-this-negated-call)))))))))
(t
(cond ((null (postfix context))
(setq arg (cons arg cmdline))
(setq cmdline nil)
(restartable-cmdline-junk-error arg))
(t
(setq remainder (cons arg cmdline))
(setq cmdline nil)))))))
(setf (cmdline-options context) (nreverse cmdline-options))
(setf (slot-value context 'remainder) remainder)))
Step two : handle internal options = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
(when (getopt :context context :long-name "clon-banner")
(format t "~A's command-line is powered by Clon,
the Command-Line Options Nuker library, version ~A,
written by Didier Verna <>.
Copyright (C) ~A Didier Verna
Clon is released under the terms of the BSD license.
See -license for more information.
or FITNESS FOR A PARTICULAR PURPOSE.~%"
(pathname-name (progname :context context))
(version :long)
*copyright-years*)
(uiop:quit))
(let ((version-format (getopt :context context :long-name "clon-version")))
(when version-format
(format t "~A~%" (version version-format))
(uiop:quit)))
(when (getopt :context context :long-name "clon-lisp-information")
(format t "~A ~A~%"
(lisp-implementation-type)
(lisp-implementation-version))
(uiop:quit))
(when (getopt :context context :long-name "clon-help")
(help :context context :item (clon-options-group context))
(uiop:quit)))
(defun make-context
(&rest keys &key synopsis cmdline progname (make-current t))
"Make a new context.
- SYNOPSIS is the program synopsis to use in that context.
It defaults to *SYNOPSIS*.
- CMDLINE is the argument list (strings) to process.
It defaults to a POSIX conformant argv.
- PROGNAME is an alternate value for argv[0].
It defaults to NIL, in which case the actual argv[0] is used.
Otherwise, it can be a non-empty string, standing for itself,
or :environment meaning to retrieve the value of the __CL_ARGV0 environment
variable (ignored if it's empty).
value.
- If MAKE-CURRENT, make the new context current. This is the default."
(declare (ignore synopsis cmdline progname))
(let ((context (apply #'make-instance 'context
(remove-keys keys :make-current))))
(when make-current
(setq *context* context))
context))
Context Manipulation Utilities
(defmacro with-context (context &body body)
"Execute BODY with *context* bound to CONTEXT."
`(let ((*context* ,context))
,@body))
context.lisp ends here
|
32a9332834dd42ae10d73e8cf7816742f1972555df731fe1b035f22d1d11e505
|
PEZ/rich4clojure
|
problem_143.clj
|
(ns rich4clojure.easy.problem-143
(:require [hyperfiddle.rcf :refer [tests]]))
;; = dot product =
;; By 4Clojure user: bloop
;; Difficulty: Easy
Tags : [ seqs math ]
;;
Create a function that computes the dot product of two
;; sequences. You may assume that the vectors will have
;; the same length.
(def __ :tests-will-fail)
(comment
)
(tests
0 := (__ [0 1 0] [1 0 0])
3 := (__ [1 1 1] [1 1 1])
32 := (__ [1 2 3] [4 5 6])
256 := (__ [2 5 6] [100 10 1]))
;; Share your solution, and/or check how others did it:
;;
| null |
https://raw.githubusercontent.com/PEZ/rich4clojure/2ccfac041840e9b1550f0a69b9becbdb03f9525b/src/rich4clojure/easy/problem_143.clj
|
clojure
|
= dot product =
By 4Clojure user: bloop
Difficulty: Easy
sequences. You may assume that the vectors will have
the same length.
Share your solution, and/or check how others did it:
|
(ns rich4clojure.easy.problem-143
(:require [hyperfiddle.rcf :refer [tests]]))
Tags : [ seqs math ]
Create a function that computes the dot product of two
(def __ :tests-will-fail)
(comment
)
(tests
0 := (__ [0 1 0] [1 0 0])
3 := (__ [1 1 1] [1 1 1])
32 := (__ [1 2 3] [4 5 6])
256 := (__ [2 5 6] [100 10 1]))
|
8baa34a7d6994b8022c3241da632c113e1ec8450a08898b21e8884df55ef160e
|
fdopen/ppx_cstubs
|
marshal_types.ml
|
This file is part of ppx_cstubs ( )
* Copyright ( c ) 2018 - 2019 fdopen
*
* 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) 2018-2019 fdopen
*
* 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 Mparsetree.Ast_cur
type fun_params = {
el : (arg_label * expression) list;
ret : expression;
release_runtime_lock : bool;
noalloc : bool;
is_inline : bool;
return_errno : bool;
remove_labels : bool;
c_name : string;
(* external xyz : .... = "c_name" *)
prim_name : string;
(* external prim_name : ..... *)
uniq_ref_id : Uniq_ref.t;
}
type id = int
type loc = Ast_helper.loc
type id_loc_param = id * loc
type expr = expression
type enum_type =
| E_normal of id
| E_bitmask of id
| E_normal_bitmask of id * id
type enum_entry = {
ee_int_id : int;
ee_type_check : int;
ee_loc : Location.t;
ee_expr : expr;
ee_cname : string;
}
type enum = {
enum_l : enum_entry list;
enum_name : string;
enum_is_typedef : bool;
enum_type_id : enum_type;
enum_is_int_bitmask : bool;
enum_loc : loc;
enum_unexpected : expr;
enum_unexpected_bits : expr;
}
type struct_record_params = {
sr_mod_path : string list;
sr_type_name : string;
sr_field_names : string list;
sr_locs : loc list;
}
type opaque_params = {
o_binding_name : string;
o_uniq_ref_id : Uniq_ref.t;
}
type ocaml_funptr = {
cb_mod_path : string list;
cb_binding_name : string;
cb_bottom : id;
cb_top_mod : string;
cb_acquire_runtime : bool;
cb_thread_registration : bool;
cb_user_fun : expression;
cb_init_fun : string;
}
| null |
https://raw.githubusercontent.com/fdopen/ppx_cstubs/5d5ce9b7cf45d87bb71c046a76d30c17ec6075e5/src/internal/marshal_types.ml
|
ocaml
|
external xyz : .... = "c_name"
external prim_name : .....
|
This file is part of ppx_cstubs ( )
* Copyright ( c ) 2018 - 2019 fdopen
*
* 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) 2018-2019 fdopen
*
* 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 Mparsetree.Ast_cur
type fun_params = {
el : (arg_label * expression) list;
ret : expression;
release_runtime_lock : bool;
noalloc : bool;
is_inline : bool;
return_errno : bool;
remove_labels : bool;
c_name : string;
prim_name : string;
uniq_ref_id : Uniq_ref.t;
}
type id = int
type loc = Ast_helper.loc
type id_loc_param = id * loc
type expr = expression
type enum_type =
| E_normal of id
| E_bitmask of id
| E_normal_bitmask of id * id
type enum_entry = {
ee_int_id : int;
ee_type_check : int;
ee_loc : Location.t;
ee_expr : expr;
ee_cname : string;
}
type enum = {
enum_l : enum_entry list;
enum_name : string;
enum_is_typedef : bool;
enum_type_id : enum_type;
enum_is_int_bitmask : bool;
enum_loc : loc;
enum_unexpected : expr;
enum_unexpected_bits : expr;
}
type struct_record_params = {
sr_mod_path : string list;
sr_type_name : string;
sr_field_names : string list;
sr_locs : loc list;
}
type opaque_params = {
o_binding_name : string;
o_uniq_ref_id : Uniq_ref.t;
}
type ocaml_funptr = {
cb_mod_path : string list;
cb_binding_name : string;
cb_bottom : id;
cb_top_mod : string;
cb_acquire_runtime : bool;
cb_thread_registration : bool;
cb_user_fun : expression;
cb_init_fun : string;
}
|
8b91411ef9a990ce41400f774a7e9e81c9ffec2da0991356283d5c6d42e21e37
|
sinasamavati/leptus
|
leptus_http2.erl
|
Copyright ( c ) 2013 - 2015 Sina Samavati < >
%%
%% 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.
-module(leptus_http2).
-compile({parse_transform, leptus_pt}).
leptus callbacks
-export([init/3]).
-export([is_authenticated/3]).
-export([get/3]).
-export([put/3]).
-export([post/3]).
-export([terminate/4]).
init(_Route, _Req, _State) ->
{ok, blah}.
is_authenticated("/users/:id", Req, State) ->
case cowboy_req:method(Req) of
<<"PUT">> ->
check_auth(Req, State);
<<"POST">> ->
case check_auth(Req, State) of
{false, _, _} ->
{false, #{<<"error">> => <<"unauthorized">>}, State};
Else ->
Else
end;
_ ->
{true, State}
end;
is_authenticated(_Route, _Req, State) ->
{true, State}.
get("/users/:id", Req, State) ->
Id = cowboy_req:binding(id, Req),
{["aha, this is ", Id], State};
get("/users/:id/interests", Req, State) ->
Id = cowboy_req:binding(id, Req),
case Id of
<<"s1n4">> ->
{200, <<"Erlang and a lotta things else">>, State};
<<"456">> ->
{"art, photography...", State};
_ ->
{404, <<"not found...">>, State}
end;
get("/users/:id/profile", Req, State) ->
Body = #{
<<"id">> => cowboy_req:binding(id, Req),
<<"bio">> => <<"Erlanger">>,
<<"github">> => cowboy_req:binding(id, Req)
},
{200, Body, State}.
put("/users/:id", _Req, State) ->
{200, <<"updated">>, State}.
post("/users/:id", _Req, State) ->
{200, <<"updated">>, State}.
%% internal
check_auth(Req, State) ->
case cowboy_req:parse_header(<<"authorization">>, Req) of
{basic, <<"sina">>, <<"wrote_me">>} ->
{true, State};
_ ->
{false, <<"unauthorized.">>, State}
end.
terminate(_Reason, _Route, _Req, State) ->
blah = State,
ok.
| null |
https://raw.githubusercontent.com/sinasamavati/leptus/e0d9bd2270dfa85bd5922e0a5c2d0289d2dc0ef9/test/leptus_http_SUITE_data/leptus_http2.erl
|
erlang
|
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.
internal
|
Copyright ( c ) 2013 - 2015 Sina Samavati < >
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 ,
-module(leptus_http2).
-compile({parse_transform, leptus_pt}).
leptus callbacks
-export([init/3]).
-export([is_authenticated/3]).
-export([get/3]).
-export([put/3]).
-export([post/3]).
-export([terminate/4]).
init(_Route, _Req, _State) ->
{ok, blah}.
is_authenticated("/users/:id", Req, State) ->
case cowboy_req:method(Req) of
<<"PUT">> ->
check_auth(Req, State);
<<"POST">> ->
case check_auth(Req, State) of
{false, _, _} ->
{false, #{<<"error">> => <<"unauthorized">>}, State};
Else ->
Else
end;
_ ->
{true, State}
end;
is_authenticated(_Route, _Req, State) ->
{true, State}.
get("/users/:id", Req, State) ->
Id = cowboy_req:binding(id, Req),
{["aha, this is ", Id], State};
get("/users/:id/interests", Req, State) ->
Id = cowboy_req:binding(id, Req),
case Id of
<<"s1n4">> ->
{200, <<"Erlang and a lotta things else">>, State};
<<"456">> ->
{"art, photography...", State};
_ ->
{404, <<"not found...">>, State}
end;
get("/users/:id/profile", Req, State) ->
Body = #{
<<"id">> => cowboy_req:binding(id, Req),
<<"bio">> => <<"Erlanger">>,
<<"github">> => cowboy_req:binding(id, Req)
},
{200, Body, State}.
put("/users/:id", _Req, State) ->
{200, <<"updated">>, State}.
post("/users/:id", _Req, State) ->
{200, <<"updated">>, State}.
check_auth(Req, State) ->
case cowboy_req:parse_header(<<"authorization">>, Req) of
{basic, <<"sina">>, <<"wrote_me">>} ->
{true, State};
_ ->
{false, <<"unauthorized.">>, State}
end.
terminate(_Reason, _Route, _Req, State) ->
blah = State,
ok.
|
f45b6d876f4a032633ebede33f939ac7af6eda81e3b51682b3a22ffae724d674
|
takikawa/racket-ppa
|
construct.rkt
|
Smart constructors and better names for markup
#lang racket/base
(require racket/contract
(only-in simple-tree-text-markup/data markup? record-dc-datum?))
(provide
(contract-out
(srcloc-markup (srcloc? markup? . -> . markup?))
(framed-markup (markup? . -> . markup?))
(image-markup (any/c markup? . -> . markup?))
(record-dc-datum (any/c natural-number/c natural-number/c . -> . record-dc-datum?))
(number (->* (number?) (#:exact-prefix (or/c 'always 'never 'when-necessary)
#:inexact-prefix (or/c 'always 'never 'when-necessary)
#:fraction-view (or/c #f 'mixed 'improper 'decimal))
markup?))
(empty-markup markup?)
(empty-line markup?)
(horizontal (markup? ... . -> . markup?))
(vertical (markup? ... . -> . markup?))
(markup-transform-image-data ((any/c . -> . any/c) markup? . -> . markup?))))
(require (rename-in simple-tree-text-markup/data
(empty-markup make-empty-markup)
(number-markup make-number-markup))
(only-in racket/list splitf-at append-map))
(define empty-markup (make-empty-markup))
(define empty-line (horizontal-markup '()))
(define (number number
#:exact-prefix [exact-prefix 'never] #:inexact-prefix [inexact-prefix 'never]
#:fraction-view [fraction-view #f])
(make-number-markup number exact-prefix inexact-prefix fraction-view))
; flatten out nested markup elements, merge adjacent strings
(define (normalize-horizontal markups)
(let ((flattened
(append-map (lambda (markup)
(cond
((empty-markup? markup) '())
((horizontal-markup? markup)
(horizontal-markup-markups markup))
(else
(list markup))))
markups)))
(merge-adjacent-strings flattened)))
(define (merge-adjacent-strings markups)
(call-with-values
(lambda () (splitf-at markups string?))
(lambda (strings after)
(let ((after-merged
(if (null? after)
'()
(cons (car after)
(merge-adjacent-strings (cdr after))))))
(if (null? strings)
after-merged
(cons (apply string-append strings)
after-merged))))))
(define (horizontal . markups)
(let ((markups (normalize-horizontal markups)))
(cond
((null? markups) empty-markup)
((null? (cdr markups))
(car markups))
(else (horizontal-markup (remove "" markups))))))
(define (flatten-vertical markups)
(append-map (lambda (markup)
(cond
((empty-markup? markup) '())
((vertical-markup? markup)
(vertical-markup-markups markup))
(else (list markup))))
markups))
(define (vertical . markups)
(let ((markups (flatten-vertical markups)))
(cond
((null? markups)
empty-markup)
((null? (cdr markups))
(car markups))
(else
(vertical-markup markups)))))
(define (markup-transform-image-data transform-image-data markup)
(transform-markup
`((,image-markup? . ,(lambda (data alt-markup)
(image-markup (transform-image-data data) alt-markup))))
markup))
| null |
https://raw.githubusercontent.com/takikawa/racket-ppa/d336bb10e3e0ec3a20020e9ade9e77d2f6f80b6d/share/pkgs/simple-tree-text-markup-lib/simple-tree-text-markup/construct.rkt
|
racket
|
flatten out nested markup elements, merge adjacent strings
|
Smart constructors and better names for markup
#lang racket/base
(require racket/contract
(only-in simple-tree-text-markup/data markup? record-dc-datum?))
(provide
(contract-out
(srcloc-markup (srcloc? markup? . -> . markup?))
(framed-markup (markup? . -> . markup?))
(image-markup (any/c markup? . -> . markup?))
(record-dc-datum (any/c natural-number/c natural-number/c . -> . record-dc-datum?))
(number (->* (number?) (#:exact-prefix (or/c 'always 'never 'when-necessary)
#:inexact-prefix (or/c 'always 'never 'when-necessary)
#:fraction-view (or/c #f 'mixed 'improper 'decimal))
markup?))
(empty-markup markup?)
(empty-line markup?)
(horizontal (markup? ... . -> . markup?))
(vertical (markup? ... . -> . markup?))
(markup-transform-image-data ((any/c . -> . any/c) markup? . -> . markup?))))
(require (rename-in simple-tree-text-markup/data
(empty-markup make-empty-markup)
(number-markup make-number-markup))
(only-in racket/list splitf-at append-map))
(define empty-markup (make-empty-markup))
(define empty-line (horizontal-markup '()))
(define (number number
#:exact-prefix [exact-prefix 'never] #:inexact-prefix [inexact-prefix 'never]
#:fraction-view [fraction-view #f])
(make-number-markup number exact-prefix inexact-prefix fraction-view))
(define (normalize-horizontal markups)
(let ((flattened
(append-map (lambda (markup)
(cond
((empty-markup? markup) '())
((horizontal-markup? markup)
(horizontal-markup-markups markup))
(else
(list markup))))
markups)))
(merge-adjacent-strings flattened)))
(define (merge-adjacent-strings markups)
(call-with-values
(lambda () (splitf-at markups string?))
(lambda (strings after)
(let ((after-merged
(if (null? after)
'()
(cons (car after)
(merge-adjacent-strings (cdr after))))))
(if (null? strings)
after-merged
(cons (apply string-append strings)
after-merged))))))
(define (horizontal . markups)
(let ((markups (normalize-horizontal markups)))
(cond
((null? markups) empty-markup)
((null? (cdr markups))
(car markups))
(else (horizontal-markup (remove "" markups))))))
(define (flatten-vertical markups)
(append-map (lambda (markup)
(cond
((empty-markup? markup) '())
((vertical-markup? markup)
(vertical-markup-markups markup))
(else (list markup))))
markups))
(define (vertical . markups)
(let ((markups (flatten-vertical markups)))
(cond
((null? markups)
empty-markup)
((null? (cdr markups))
(car markups))
(else
(vertical-markup markups)))))
(define (markup-transform-image-data transform-image-data markup)
(transform-markup
`((,image-markup? . ,(lambda (data alt-markup)
(image-markup (transform-image-data data) alt-markup))))
markup))
|
56ffd0fb9a6a83080999de1ef69017f663f0d4ea90d48d50cfba78e292849ab2
|
haskell/HTTP
|
Proxy.hs
|
# LANGUAGE CPP #
-----------------------------------------------------------------------------
-- |
Module : Network .
-- Copyright : See LICENSE file
License : BSD
--
-- Maintainer : Ganesh Sittampalam <>
-- Stability : experimental
-- Portability : non-portable (not tested)
--
-- Handling proxy server settings and their resolution.
--
-----------------------------------------------------------------------------
module Network.HTTP.Proxy
( Proxy(..)
, noProxy -- :: Proxy
, fetchProxy -- :: Bool -> IO Proxy
, parseProxy -- :: String -> Maybe Proxy
) where
# if ! defined(WIN32 ) & & defined(mingw32_HOST_OS )
# define WIN32 1
# endif
#if !defined(WIN32) && defined(mingw32_HOST_OS)
#define WIN32 1
#endif
-}
import Control.Monad ( when, mplus, join, liftM2 )
#if defined(WIN32)
import Network.HTTP.Base ( catchIO )
import Control.Monad ( liftM )
import Data.List ( isPrefixOf )
#endif
import Network.HTTP.Utils ( dropWhileTail, chopAtDelim )
import Network.HTTP.Auth
import Network.URI
( URI(..), URIAuth(..), parseAbsoluteURI, unEscapeString )
import System.IO ( hPutStrLn, stderr )
import System.Environment
# if ! defined(WIN32 ) & & defined(mingw32_HOST_OS )
# define WIN32 1
# endif
#if !defined(WIN32) && defined(mingw32_HOST_OS)
#define WIN32 1
#endif
-}
#if defined(WIN32)
import System.Win32.Types ( DWORD, HKEY )
import System.Win32.Registry( hKEY_CURRENT_USER, regOpenKey, regCloseKey, regQueryValueEx )
import Control.Exception ( bracket )
import Foreign ( toBool, Storable(peek, sizeOf), castPtr, alloca )
#if MIN_VERSION_Win32(2,8,0)
import System.Win32.Registry( regQueryDefaultValue )
#else
import System.Win32.Registry( regQueryValue )
#endif
#endif
-- | HTTP proxies (or not) are represented via 'Proxy', specifying if a
proxy should be used for the request ( see ' Network . Browser.setProxy ' )
data Proxy
= NoProxy -- ^ Don't use a proxy.
| Proxy String
(Maybe Authority) -- ^ Use the proxy given. Should be of the
-- form "http:\/\/host:port", "host", "host:port", or "http:\/\/host".
Additionally , an optional ' Authority ' for authentication with the proxy .
noProxy :: Proxy
noProxy = NoProxy
-- | @envProxyString@ locates proxy server settings by looking
-- up env variable @HTTP_PROXY@ (or its lower-case equivalent.)
If no mapping found , returns @Nothing@.
envProxyString :: IO (Maybe String)
envProxyString = do
env <- getEnvironment
return (lookup "http_proxy" env `mplus` lookup "HTTP_PROXY" env)
-- | @proxyString@ tries to locate the user's proxy server setting.
Consults environment variable , and in case of Windows , by querying
-- the Registry (cf. @registryProxyString@.)
proxyString :: IO (Maybe String)
proxyString = liftM2 mplus envProxyString windowsProxyString
windowsProxyString :: IO (Maybe String)
#if !defined(WIN32)
windowsProxyString = return Nothing
#else
windowsProxyString = liftM (>>= parseWindowsProxy) registryProxyString
registryProxyLoc :: (HKEY,String)
registryProxyLoc = (hive, path)
where
-- some sources say proxy settings should be at
-- HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows
-- \CurrentVersion\Internet Settings\ProxyServer
-- but if the user sets them with IE connection panel they seem to
-- end up in the following place:
hive = hKEY_CURRENT_USER
path = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
-- read proxy settings from the windows registry; this is just a best
-- effort and may not work on all setups.
registryProxyString :: IO (Maybe String)
registryProxyString = catchIO
(bracket (uncurry regOpenKey registryProxyLoc) regCloseKey $ \hkey -> do
enable <- fmap toBool $ regQueryValueDWORD hkey "ProxyEnable"
if enable
#if MIN_VERSION_Win32(2,8,0)
then fmap Just $ regQueryDefaultValue hkey "ProxyServer"
#elif MIN_VERSION_Win32(2,6,0)
then fmap Just $ regQueryValue hkey "ProxyServer"
#else
then fmap Just $ regQueryValue hkey (Just "ProxyServer")
#endif
else return Nothing)
(\_ -> return Nothing)
the proxy string is in the format " http = x.x.x.x : yyyy;https= ... ;ftp= ... ... "
-- even though the following article indicates otherwise
-- -us/kb/819961
--
-- to be sure, parse strings where each entry in the ';'-separated list above is
-- either in the format "protocol=..." or "protocol://..."
--
only return the first " http " of them , if it exists
parseWindowsProxy :: String -> Maybe String
parseWindowsProxy s =
case proxies of
x:_ -> Just x
_ -> Nothing
where
parts = split ';' s
pr x = case break (== '=') x of
(p, []) -> p -- might be in format http://
(p, u) -> p ++ "://" ++ drop 1 u
proxies = filter (isPrefixOf "http://") . map pr $ parts
split :: Eq a => a -> [a] -> [[a]]
split _ [] = []
split a xs = case break (a ==) xs of
(ys, []) -> [ys]
(ys, _:zs) -> ys:split a zs
#endif
-- | @fetchProxy flg@ gets the local proxy settings and parse the string
into a @Proxy@ value . If you want to be informed of ill - formed proxy
configuration strings , supply @True@ for @flg@.
-- Proxy settings are sourced from the @HTTP_PROXY@ environment variable,
and in the case of Windows platforms , by consulting IE / WinInet 's proxy
-- setting in the Registry.
fetchProxy :: Bool -> IO Proxy
fetchProxy warnIfIllformed = do
mstr <- proxyString
case mstr of
Nothing -> return NoProxy
Just str -> case parseProxy str of
Just p -> return p
Nothing -> do
when warnIfIllformed $ System.IO.hPutStrLn System.IO.stderr $ unlines
[ "invalid http proxy uri: " ++ show str
, "proxy uri must be http with a hostname"
, "ignoring http proxy, trying a direct connection"
]
return NoProxy
| @parseProxy str@ translates a proxy server string into a @Proxy@ value ;
-- returns @Nothing@ if not well-formed.
parseProxy :: String -> Maybe Proxy
parseProxy "" = Nothing
parseProxy str = join
. fmap uri2proxy
$ parseHttpURI str
`mplus` parseHttpURI ("http://" ++ str)
where
parseHttpURI str' =
case parseAbsoluteURI str' of
Just uri@URI{uriAuthority = Just{}} -> Just (fixUserInfo uri)
_ -> Nothing
Note : we need to be able to parse non - URIs like
which lack the @\"http://\"@ URI scheme . The problem is that
is in fact a valid URI but with scheme
-- @\"wwwcache.example.com:\"@, no authority part and a path of @\"80\"@.
--
So our strategy is to try parsing as normal uri first and if it lacks the
-- 'uriAuthority' then we try parsing again with a @\"http://\"@ prefix.
--
-- | tidy up user portion, don't want the trailing "\@".
fixUserInfo :: URI -> URI
fixUserInfo uri = uri{ uriAuthority = f `fmap` uriAuthority uri }
where
f a@URIAuth{uriUserInfo=s} = a{uriUserInfo=dropWhileTail (=='@') s}
--
uri2proxy :: URI -> Maybe Proxy
uri2proxy uri@URI{ uriScheme = "http:"
, uriAuthority = Just (URIAuth auth' hst prt)
} =
Just (Proxy (hst ++ prt) auth)
where
auth =
case auth' of
[] -> Nothing
as -> Just (AuthBasic "" (unEscapeString usr) (unEscapeString pwd) uri)
where
(usr,pwd) = chopAtDelim ':' as
uri2proxy _ = Nothing
-- utilities
#if defined(WIN32)
regQueryValueDWORD :: HKEY -> String -> IO DWORD
regQueryValueDWORD hkey name = alloca $ \ptr -> do
-- TODO: this throws away the key type returned by regQueryValueEx
-- we should check it's what we expect instead
_ <- regQueryValueEx hkey name (castPtr ptr) (sizeOf (undefined :: DWORD))
peek ptr
#endif
| null |
https://raw.githubusercontent.com/haskell/HTTP/3e9af54c867769275d7bf50c88bcd037cde6132a/Network/HTTP/Proxy.hs
|
haskell
|
---------------------------------------------------------------------------
|
Copyright : See LICENSE file
Maintainer : Ganesh Sittampalam <>
Stability : experimental
Portability : non-portable (not tested)
Handling proxy server settings and their resolution.
---------------------------------------------------------------------------
:: Proxy
:: Bool -> IO Proxy
:: String -> Maybe Proxy
| HTTP proxies (or not) are represented via 'Proxy', specifying if a
^ Don't use a proxy.
^ Use the proxy given. Should be of the
form "http:\/\/host:port", "host", "host:port", or "http:\/\/host".
| @envProxyString@ locates proxy server settings by looking
up env variable @HTTP_PROXY@ (or its lower-case equivalent.)
| @proxyString@ tries to locate the user's proxy server setting.
the Registry (cf. @registryProxyString@.)
some sources say proxy settings should be at
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows
\CurrentVersion\Internet Settings\ProxyServer
but if the user sets them with IE connection panel they seem to
end up in the following place:
read proxy settings from the windows registry; this is just a best
effort and may not work on all setups.
even though the following article indicates otherwise
-us/kb/819961
to be sure, parse strings where each entry in the ';'-separated list above is
either in the format "protocol=..." or "protocol://..."
might be in format http://
| @fetchProxy flg@ gets the local proxy settings and parse the string
Proxy settings are sourced from the @HTTP_PROXY@ environment variable,
setting in the Registry.
returns @Nothing@ if not well-formed.
@\"wwwcache.example.com:\"@, no authority part and a path of @\"80\"@.
'uriAuthority' then we try parsing again with a @\"http://\"@ prefix.
| tidy up user portion, don't want the trailing "\@".
utilities
TODO: this throws away the key type returned by regQueryValueEx
we should check it's what we expect instead
|
# LANGUAGE CPP #
Module : Network .
License : BSD
module Network.HTTP.Proxy
( Proxy(..)
) where
# if ! defined(WIN32 ) & & defined(mingw32_HOST_OS )
# define WIN32 1
# endif
#if !defined(WIN32) && defined(mingw32_HOST_OS)
#define WIN32 1
#endif
-}
import Control.Monad ( when, mplus, join, liftM2 )
#if defined(WIN32)
import Network.HTTP.Base ( catchIO )
import Control.Monad ( liftM )
import Data.List ( isPrefixOf )
#endif
import Network.HTTP.Utils ( dropWhileTail, chopAtDelim )
import Network.HTTP.Auth
import Network.URI
( URI(..), URIAuth(..), parseAbsoluteURI, unEscapeString )
import System.IO ( hPutStrLn, stderr )
import System.Environment
# if ! defined(WIN32 ) & & defined(mingw32_HOST_OS )
# define WIN32 1
# endif
#if !defined(WIN32) && defined(mingw32_HOST_OS)
#define WIN32 1
#endif
-}
#if defined(WIN32)
import System.Win32.Types ( DWORD, HKEY )
import System.Win32.Registry( hKEY_CURRENT_USER, regOpenKey, regCloseKey, regQueryValueEx )
import Control.Exception ( bracket )
import Foreign ( toBool, Storable(peek, sizeOf), castPtr, alloca )
#if MIN_VERSION_Win32(2,8,0)
import System.Win32.Registry( regQueryDefaultValue )
#else
import System.Win32.Registry( regQueryValue )
#endif
#endif
proxy should be used for the request ( see ' Network . Browser.setProxy ' )
data Proxy
| Proxy String
Additionally , an optional ' Authority ' for authentication with the proxy .
noProxy :: Proxy
noProxy = NoProxy
If no mapping found , returns @Nothing@.
envProxyString :: IO (Maybe String)
envProxyString = do
env <- getEnvironment
return (lookup "http_proxy" env `mplus` lookup "HTTP_PROXY" env)
Consults environment variable , and in case of Windows , by querying
proxyString :: IO (Maybe String)
proxyString = liftM2 mplus envProxyString windowsProxyString
windowsProxyString :: IO (Maybe String)
#if !defined(WIN32)
windowsProxyString = return Nothing
#else
windowsProxyString = liftM (>>= parseWindowsProxy) registryProxyString
registryProxyLoc :: (HKEY,String)
registryProxyLoc = (hive, path)
where
hive = hKEY_CURRENT_USER
path = "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"
registryProxyString :: IO (Maybe String)
registryProxyString = catchIO
(bracket (uncurry regOpenKey registryProxyLoc) regCloseKey $ \hkey -> do
enable <- fmap toBool $ regQueryValueDWORD hkey "ProxyEnable"
if enable
#if MIN_VERSION_Win32(2,8,0)
then fmap Just $ regQueryDefaultValue hkey "ProxyServer"
#elif MIN_VERSION_Win32(2,6,0)
then fmap Just $ regQueryValue hkey "ProxyServer"
#else
then fmap Just $ regQueryValue hkey (Just "ProxyServer")
#endif
else return Nothing)
(\_ -> return Nothing)
the proxy string is in the format " http = x.x.x.x : yyyy;https= ... ;ftp= ... ... "
only return the first " http " of them , if it exists
parseWindowsProxy :: String -> Maybe String
parseWindowsProxy s =
case proxies of
x:_ -> Just x
_ -> Nothing
where
parts = split ';' s
pr x = case break (== '=') x of
(p, u) -> p ++ "://" ++ drop 1 u
proxies = filter (isPrefixOf "http://") . map pr $ parts
split :: Eq a => a -> [a] -> [[a]]
split _ [] = []
split a xs = case break (a ==) xs of
(ys, []) -> [ys]
(ys, _:zs) -> ys:split a zs
#endif
into a @Proxy@ value . If you want to be informed of ill - formed proxy
configuration strings , supply @True@ for @flg@.
and in the case of Windows platforms , by consulting IE / WinInet 's proxy
fetchProxy :: Bool -> IO Proxy
fetchProxy warnIfIllformed = do
mstr <- proxyString
case mstr of
Nothing -> return NoProxy
Just str -> case parseProxy str of
Just p -> return p
Nothing -> do
when warnIfIllformed $ System.IO.hPutStrLn System.IO.stderr $ unlines
[ "invalid http proxy uri: " ++ show str
, "proxy uri must be http with a hostname"
, "ignoring http proxy, trying a direct connection"
]
return NoProxy
| @parseProxy str@ translates a proxy server string into a @Proxy@ value ;
parseProxy :: String -> Maybe Proxy
parseProxy "" = Nothing
parseProxy str = join
. fmap uri2proxy
$ parseHttpURI str
`mplus` parseHttpURI ("http://" ++ str)
where
parseHttpURI str' =
case parseAbsoluteURI str' of
Just uri@URI{uriAuthority = Just{}} -> Just (fixUserInfo uri)
_ -> Nothing
Note : we need to be able to parse non - URIs like
which lack the @\"http://\"@ URI scheme . The problem is that
is in fact a valid URI but with scheme
So our strategy is to try parsing as normal uri first and if it lacks the
fixUserInfo :: URI -> URI
fixUserInfo uri = uri{ uriAuthority = f `fmap` uriAuthority uri }
where
f a@URIAuth{uriUserInfo=s} = a{uriUserInfo=dropWhileTail (=='@') s}
uri2proxy :: URI -> Maybe Proxy
uri2proxy uri@URI{ uriScheme = "http:"
, uriAuthority = Just (URIAuth auth' hst prt)
} =
Just (Proxy (hst ++ prt) auth)
where
auth =
case auth' of
[] -> Nothing
as -> Just (AuthBasic "" (unEscapeString usr) (unEscapeString pwd) uri)
where
(usr,pwd) = chopAtDelim ':' as
uri2proxy _ = Nothing
#if defined(WIN32)
regQueryValueDWORD :: HKEY -> String -> IO DWORD
regQueryValueDWORD hkey name = alloca $ \ptr -> do
_ <- regQueryValueEx hkey name (castPtr ptr) (sizeOf (undefined :: DWORD))
peek ptr
#endif
|
015a488fde85742c3064fe3b04c45cbcb71ddedc5a376b6c3808bb1b871b09f6
|
seckcoder/course-compiler
|
r1a_4.rkt
|
(let ([a 1])
(let ([b 1])
(let ([c 1])
(let ([d 1])
(let ([e 1])
(let ([f 1])
(let ([g 1])
(let ([h 1])
(let ([i 1])
(let ([j 1])
(let ([k 1])
(let ([l 1])
(let ([m 1])
(let ([n 1])
(let ([o 1])
(let ([p 1])
(let ([q (read)])
(let ([r 1])
(let ([s 1])
(let ([t 1])
(let ([u 1])
(+ a
(+ b
(+ c
(+ d
(+ e
(+ f
(+ g
(+ h
(+ i
(+ j
(+ k
(+ l
(+ m
(+ n
(+ o
(+ p
(+ q
(+ r
(+ s
(+ t
(+ u 21))))))))))))))))))))))))))))))))))))))))))
| null |
https://raw.githubusercontent.com/seckcoder/course-compiler/4363e5b3e15eaa7553902c3850b6452de80b2ef6/tests/student-tests/r1a_4.rkt
|
racket
|
(let ([a 1])
(let ([b 1])
(let ([c 1])
(let ([d 1])
(let ([e 1])
(let ([f 1])
(let ([g 1])
(let ([h 1])
(let ([i 1])
(let ([j 1])
(let ([k 1])
(let ([l 1])
(let ([m 1])
(let ([n 1])
(let ([o 1])
(let ([p 1])
(let ([q (read)])
(let ([r 1])
(let ([s 1])
(let ([t 1])
(let ([u 1])
(+ a
(+ b
(+ c
(+ d
(+ e
(+ f
(+ g
(+ h
(+ i
(+ j
(+ k
(+ l
(+ m
(+ n
(+ o
(+ p
(+ q
(+ r
(+ s
(+ t
(+ u 21))))))))))))))))))))))))))))))))))))))))))
|
|
adfcad2d6f0a9e45a6337f896051cbc94a5a1f0ecc2e515af2be95539af473c0
|
realworldocaml/book
|
setup.defaults.ml
|
let library_path = []
let roots : string option Install.Section.Paths.Roots.t =
{ lib_root = None
; man = None
; doc_root = None
; etc_root = None
; share_root = None
; bin = None
; sbin = None
; libexec_root = None
}
| null |
https://raw.githubusercontent.com/realworldocaml/book/d822fd065f19dbb6324bf83e0143bc73fd77dbf9/duniverse/dune_/src/dune_rules/setup.defaults.ml
|
ocaml
|
let library_path = []
let roots : string option Install.Section.Paths.Roots.t =
{ lib_root = None
; man = None
; doc_root = None
; etc_root = None
; share_root = None
; bin = None
; sbin = None
; libexec_root = None
}
|
|
a891452c9e49aeab7008031848ceca0e1535532457281f7bc90f743311807cc8
|
SNePS/SNePS2
|
lexicon-2.lisp
|
-*- Mode : Lisp ; Syntax : Common - Lisp ; Package : USER ; Base : 10 -*-
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
;;; Version: $Id: lexicon-2.lisp,v
;;; This file is part of SNePS.
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Buffalo Public License Version 1.0 ( the " License " ) ; you may
;;; not use this file except in compliance with the License. You
;;; may obtain a copy of the License at
;;; . edu/sneps/Downloads/ubpl.pdf.
;;;
Software distributed under the License is distributed on an
" AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express
;;; or implied. See the License for the specific language gov
;;; erning rights and limitations under the License.
;;;
The Original Code is SNePS 2.8 .
;;;
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
;;;
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
("a" ((ctgy . det)))
("an" ((ctgy . det)))
("ant" ((ctgy . n)))
("animal" ((ctgy . n)))
("bat" ((ctgy . n)))
("be" ((ctgy . v)))
("believe" ((ctgy . v)(prop-att . t)))
("Bill" ((ctgy . npr)(gen . m)))
("car" ((ctgy . n)))
("Carol" ((ctgy . npr)(gen . f)))
("cat" ((ctgy . n)))
("dog" ((ctgy . n)))
("elk" ((ctgy . n)))
("fox" ((ctgy . n)))
("girl" ((ctgy . n)))
("gnu" ((ctgy . n)))
("Guatemalan" ((ctgy . adj)))
("he" ((ctgy . pron)))
("Hector" ((ctgy . npr)(gen . m)))
("hen" ((ctgy . n)))
("is" ((ctgy . v)(root . "be")(num . sing)(tense . pres)))
("it" ((ctgy . pron)))
("John" ((ctgy . npr)(gen . m)))
("Lucy" ((ctgy . npr)(gen . f)))
("man" ((ctgy . n)(plur . "men")))
("Mary" ((ctgy . npr)(gen . f)))
("men" ((ctgy . n)(root . "man")(num . plur)))
("mortal" ((ctgy . adj)))
("old" ((ctgy . adj)))
("owl" ((ctgy . n)))
("pear" ((ctgy . n)))
("pet" ((ctgy . n)))
("people" ((ctgy . n)(root . "person")(num . plur)))
("person" ((ctgy . n)(plur . "people")))
("philosophical" ((ctgy . adj)))
("pick" ((ctgy . v)))
("poor" ((ctgy . adj)))
("rat" ((ctgy . n)))
("rich" ((ctgy . adj)))
("saw" ((ctgy . n)(root . "saw1"))
((ctgy . v)(root . "see")(tense . past)))
("saw1" ((ctgy . n)(root . "saw")))
("see" ((ctgy . v)(past . "saw")(pastp . "seen")))
("seen" ((ctgy . v)(root . "see")(tense . pastp)(pprt . t)))
("she" ((ctgy . pron)))
("smart" ((ctgy . adj)))
("Socrates" ((ctgy . npr)(gen . m)))
("sow" ((ctgy . n)))
("Stu" ((ctgy . npr)(gen . m)))
("sweet" ((ctgy . adj)))
("tall" ((ctgy . adj)))
("that" ((ctgy . conj)))
("the" ((ctgy . det)))
("the-editor-of-Byte" ((ctgy . npr)(gen m f)))
("this" ((ctgy . demon)))
("what" ((ctgy . pron)))
("was" ((ctgy . v)(root . "be")(num . sing)(tense . past)))
("who" ((ctgy . pron)))
("wise" ((ctgy . adj)))
("yak" ((ctgy . n)))
("young" ((ctgy . adj)))
| null |
https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/nlint/lexicon-2.lisp
|
lisp
|
Syntax : Common - Lisp ; Package : USER ; Base : 10 -*-
Version: $Id: lexicon-2.lisp,v
This file is part of SNePS.
you may
not use this file except in compliance with the License. You
may obtain a copy of the License at
. edu/sneps/Downloads/ubpl.pdf.
or implied. See the License for the specific language gov
erning rights and limitations under the License.
|
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Software distributed under the License is distributed on an
" AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express
The Original Code is SNePS 2.8 .
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
("a" ((ctgy . det)))
("an" ((ctgy . det)))
("ant" ((ctgy . n)))
("animal" ((ctgy . n)))
("bat" ((ctgy . n)))
("be" ((ctgy . v)))
("believe" ((ctgy . v)(prop-att . t)))
("Bill" ((ctgy . npr)(gen . m)))
("car" ((ctgy . n)))
("Carol" ((ctgy . npr)(gen . f)))
("cat" ((ctgy . n)))
("dog" ((ctgy . n)))
("elk" ((ctgy . n)))
("fox" ((ctgy . n)))
("girl" ((ctgy . n)))
("gnu" ((ctgy . n)))
("Guatemalan" ((ctgy . adj)))
("he" ((ctgy . pron)))
("Hector" ((ctgy . npr)(gen . m)))
("hen" ((ctgy . n)))
("is" ((ctgy . v)(root . "be")(num . sing)(tense . pres)))
("it" ((ctgy . pron)))
("John" ((ctgy . npr)(gen . m)))
("Lucy" ((ctgy . npr)(gen . f)))
("man" ((ctgy . n)(plur . "men")))
("Mary" ((ctgy . npr)(gen . f)))
("men" ((ctgy . n)(root . "man")(num . plur)))
("mortal" ((ctgy . adj)))
("old" ((ctgy . adj)))
("owl" ((ctgy . n)))
("pear" ((ctgy . n)))
("pet" ((ctgy . n)))
("people" ((ctgy . n)(root . "person")(num . plur)))
("person" ((ctgy . n)(plur . "people")))
("philosophical" ((ctgy . adj)))
("pick" ((ctgy . v)))
("poor" ((ctgy . adj)))
("rat" ((ctgy . n)))
("rich" ((ctgy . adj)))
("saw" ((ctgy . n)(root . "saw1"))
((ctgy . v)(root . "see")(tense . past)))
("saw1" ((ctgy . n)(root . "saw")))
("see" ((ctgy . v)(past . "saw")(pastp . "seen")))
("seen" ((ctgy . v)(root . "see")(tense . pastp)(pprt . t)))
("she" ((ctgy . pron)))
("smart" ((ctgy . adj)))
("Socrates" ((ctgy . npr)(gen . m)))
("sow" ((ctgy . n)))
("Stu" ((ctgy . npr)(gen . m)))
("sweet" ((ctgy . adj)))
("tall" ((ctgy . adj)))
("that" ((ctgy . conj)))
("the" ((ctgy . det)))
("the-editor-of-Byte" ((ctgy . npr)(gen m f)))
("this" ((ctgy . demon)))
("what" ((ctgy . pron)))
("was" ((ctgy . v)(root . "be")(num . sing)(tense . past)))
("who" ((ctgy . pron)))
("wise" ((ctgy . adj)))
("yak" ((ctgy . n)))
("young" ((ctgy . adj)))
|
3a9bd6f3f006dc2e86a1456dab88ef5b1596d30d800725f32f5ccac600d9f4fd
|
jasonstolaruk/CurryMUD
|
Gods.hs
|
module Mud.Misc.Gods where
import Mud.Data.Misc
import Mud.Data.State.MudData
import Mud.Util.Misc
import qualified Data.Set as S (Set, filter, fromList, toList)
godSet :: S.Set God
godSet = S.fromList [ God Aule GodOfWealth . Just $ (Male, Dwarf ) -- Son of Drogo and Celoriel.
, God Caila GodOfHarvest . Just $ (Female, Human ) -- Daughter of Drogo and Celoriel.
, God Celoriel GodOfPsionics . Just $ (Female, Lagomorph) -- Wife of Drogo.
Daughter of Murgorhd and Iminye .
, God Drogo GodOfMoonAndMagic . Just $ (Male, Hobbit ) -- Husband of Celoriel.
, God Iminye GodOfArtAndEngineering . Just $ (Female, Elf ) -- Daughter of Drogo and Celoriel.
, God Itulvatar GodOfLight Nothing
, God Murgorhd GodOfDarkness Nothing
Son of Murgorhd and Iminye .
, God Rumialys GodOfNature . Just $ (Male, Nymph ) ]
getGodForGodName :: GodName -> Maybe God
getGodForGodName gn = safeHead . S.toList . S.filter (\(God gn' _ _) -> gn' == gn) $ godSet
| null |
https://raw.githubusercontent.com/jasonstolaruk/CurryMUD/f9775fb3ede08610f33f27bb1fb5fc0565e98266/lib/Mud/Misc/Gods.hs
|
haskell
|
Son of Drogo and Celoriel.
Daughter of Drogo and Celoriel.
Wife of Drogo.
Husband of Celoriel.
Daughter of Drogo and Celoriel.
|
module Mud.Misc.Gods where
import Mud.Data.Misc
import Mud.Data.State.MudData
import Mud.Util.Misc
import qualified Data.Set as S (Set, filter, fromList, toList)
godSet :: S.Set God
Daughter of Murgorhd and Iminye .
, God Itulvatar GodOfLight Nothing
, God Murgorhd GodOfDarkness Nothing
Son of Murgorhd and Iminye .
, God Rumialys GodOfNature . Just $ (Male, Nymph ) ]
getGodForGodName :: GodName -> Maybe God
getGodForGodName gn = safeHead . S.toList . S.filter (\(God gn' _ _) -> gn' == gn) $ godSet
|
76da1a51b701bf3261092113cbf4a29814a3a65507b69e7173f8046f7ae3e4b9
|
helpshift/gulfstream
|
project.clj
|
(defproject helpshift/gulfstream "0.2.1"
:description "graphing library wrapper built on top of graphstream"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
[garden "1.2.5"]
[net.sourceforge.cssparser/cssparser "0.9.16"]
[im.chit/hara.object "2.2.11"]
[im.chit/hara.data.diff "2.2.11"]
[org.graphstream/gs-ui "1.3"]]
:profiles {:dev {:dependencies [[midje "1.7.0"]
[helpshift/hydrox "0.1.3"]]
:plugins [[lein-midje "3.1.3"]]}}
:documentation {:site "gulfstream"
:output "docs"
:template {:path "template"
:copy ["assets"]
:defaults {:template "article.html"
:navbar [:file "partials/navbar.html"]
:dependencies [:file "partials/deps-web.html"]
:navigation :navigation
:article :article}}
:paths ["test/documentation"]
:files {"index"
{:input "test/documentation/gulfstream_guide.clj"
:title "gulfstream"
:subtitle "rapid graph visualizations"}}}
)
| null |
https://raw.githubusercontent.com/helpshift/gulfstream/f5e3f4159a9335bcf73ccbb750e0e6b17bde8773/project.clj
|
clojure
|
(defproject helpshift/gulfstream "0.2.1"
:description "graphing library wrapper built on top of graphstream"
:url ""
:license {:name "Eclipse Public License"
:url "-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
[garden "1.2.5"]
[net.sourceforge.cssparser/cssparser "0.9.16"]
[im.chit/hara.object "2.2.11"]
[im.chit/hara.data.diff "2.2.11"]
[org.graphstream/gs-ui "1.3"]]
:profiles {:dev {:dependencies [[midje "1.7.0"]
[helpshift/hydrox "0.1.3"]]
:plugins [[lein-midje "3.1.3"]]}}
:documentation {:site "gulfstream"
:output "docs"
:template {:path "template"
:copy ["assets"]
:defaults {:template "article.html"
:navbar [:file "partials/navbar.html"]
:dependencies [:file "partials/deps-web.html"]
:navigation :navigation
:article :article}}
:paths ["test/documentation"]
:files {"index"
{:input "test/documentation/gulfstream_guide.clj"
:title "gulfstream"
:subtitle "rapid graph visualizations"}}}
)
|
|
5d3aee03e78fc1b01f37bb447a9294dac5c604ff5aa3aae8b2db5eddf62b8872
|
v-kolesnikov/sicp
|
1_22_test.clj
|
(ns sicp.chapter01.1-22-test
(:require [clojure.test :refer :all]
[sicp.test-helper :refer :all]
[sicp.chapter01.1-22 :refer :all]
[sicp.common :refer [avg]]))
(deftest test-search-for-primes
(let [searched-primes
(map #(search-for-primes % 3) [1000 10000 100000 1000000 10000000])
avg-times (reduce #(conj %1 (avg (vals %2))) nil searched-primes)
avg-ratio (->> avg-times
(partition 2 1)
(reduce #(conj %1
(float (/ (first %2)
(second %2))))
nil)
(avg))]
(println "Average time:" (avg avg-times))
(println "Average times:" avg-times)
(println "Average ratio:" avg-ratio)))
| null |
https://raw.githubusercontent.com/v-kolesnikov/sicp/4298de6083440a75898e97aad658025a8cecb631/test/sicp/chapter01/1_22_test.clj
|
clojure
|
(ns sicp.chapter01.1-22-test
(:require [clojure.test :refer :all]
[sicp.test-helper :refer :all]
[sicp.chapter01.1-22 :refer :all]
[sicp.common :refer [avg]]))
(deftest test-search-for-primes
(let [searched-primes
(map #(search-for-primes % 3) [1000 10000 100000 1000000 10000000])
avg-times (reduce #(conj %1 (avg (vals %2))) nil searched-primes)
avg-ratio (->> avg-times
(partition 2 1)
(reduce #(conj %1
(float (/ (first %2)
(second %2))))
nil)
(avg))]
(println "Average time:" (avg avg-times))
(println "Average times:" avg-times)
(println "Average ratio:" avg-ratio)))
|
|
87559bab6ad7312c226e0adcd3d2229beb756c198a1da9fe29efee84e196e9ac
|
nyu-acsys/drift
|
a-copy-print.ml
|
(*
USED: PLDI2011 as a-cppr
USED: PEPM2013 as a-cppr
*)
let make_array n i = assert (0 <= i && i < n); 0
let update (i:int) (n:int) des x : int -> int =
des i;
let a j = if i=j then x else des j in a
let print_int (n:int) = ()
let f (m:int) src des =
let rec bcopy (m:int) src des i =
if i >= m then
des
else
let des = update i m des (src i) in
bcopy m src des (i+1)
in
let rec print_array m (array:int->int) i =
if i >= m then
()
else
(print_int (array i);
print_array m array (i + 1))
in
let array : int -> int = bcopy m src des 0 in
print_array m array 0
let main (n:int(*-:{v:Int|true}*)) =
let array1 = make_array n in
let array2 = make_array n in
if n > 0 then f n array1 array2
| null |
https://raw.githubusercontent.com/nyu-acsys/drift/51a3160d74b761626180da4f7dd0bb950cfe40c0/tests/benchmarks/r_type/high/a-copy-print.ml
|
ocaml
|
USED: PLDI2011 as a-cppr
USED: PEPM2013 as a-cppr
-:{v:Int|true}
|
let make_array n i = assert (0 <= i && i < n); 0
let update (i:int) (n:int) des x : int -> int =
des i;
let a j = if i=j then x else des j in a
let print_int (n:int) = ()
let f (m:int) src des =
let rec bcopy (m:int) src des i =
if i >= m then
des
else
let des = update i m des (src i) in
bcopy m src des (i+1)
in
let rec print_array m (array:int->int) i =
if i >= m then
()
else
(print_int (array i);
print_array m array (i + 1))
in
let array : int -> int = bcopy m src des 0 in
print_array m array 0
let array1 = make_array n in
let array2 = make_array n in
if n > 0 then f n array1 array2
|
f4a23f54c406d664b2b96f7f293a126c6c13a1f6a077a50367341694ae699099
|
geneweb/geneweb
|
name.ml
|
Copyright ( c ) 1998 - 2007 INRIA
(* La liste des caractères interdits *)
let forbidden_char = [ ':'; '@'; '#'; '='; '$' ]
Name.lower
let unaccent_utf_8 lower s i =
let fns =
if lower then fun n s -> (String.lowercase_ascii s, n) else fun n s -> (s, n)
in
let fnc =
if lower then fun n c -> (String.make 1 @@ Char.lowercase_ascii c, n)
else fun n c -> (String.make 1 c, n)
in
let s, n =
Unidecode.decode fns fnc
(fun n -> (String.sub s i (n - i), n))
s i (String.length s)
in
if lower then (String.lowercase_ascii s, n) else (s, n)
let next_chars_if_equiv s i t j =
if i >= String.length s || j >= String.length t then None
else
let s1, i1 = unaccent_utf_8 true s i in
let t1, j1 = unaccent_utf_8 true t j in
if s1 = t1 then Some (i1, j1) else None
Name.lower :
- uppercase - > lowercase
- no accents
- chars no letters and no numbers ( except ' . ' ) = > spaces ( stripped )
Key comparison ( first name , surname , number ) applies " lower " equality
on first names and surnames
- uppercase -> lowercase
- no accents
- chars no letters and no numbers (except '.') => spaces (stripped)
Key comparison (first name, surname, number) applies "lower" equality
on first names and surnames *)
let lower s =
let rec copy special i len =
if i = String.length s then Buff.get len
else if Char.code s.[i] < 0x80 then
match s.[i] with
| ('a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '.') as c ->
let len = if special then Buff.store len ' ' else len in
let c = Char.lowercase_ascii c in
copy false (i + 1) (Buff.store len c)
| _ -> copy (len <> 0) (i + 1) len
else
let len = if special then Buff.store len ' ' else len in
let t, j = unaccent_utf_8 true s i in
copy false j (Buff.mstore len t)
in
copy false 0 0
let title s =
let t = ref true in
let cmap u =
let r = if !t then Uucp.Case.Map.to_upper u else Uucp.Case.Map.to_lower u in
t := not (Uucp.Alpha.is_alphabetic u);
r
in
Utf8.cmap_utf_8 cmap s
(* Name.abbrev *)
(* List of abbreviations. If abbreviation is mapped to [Some s] should be remplaced by
[s]. If mapped to None, it should be removed from name. *)
let abbrev_list =
[
("a", None);
("af", None);
("d", None);
("de", None);
("di", None);
("ier", Some "i");
("of", None);
("saint", Some "st");
("sainte", Some "ste");
("van", None);
("von", None);
("zu", None);
("zur", None);
]
(* Checks if the word starting at [i] in [s] is [p]. *)
let is_word s i p =
let rec is_word s i p ip =
if ip = String.length p then
if i = String.length s then true else if s.[i] = ' ' then true else false
else if i = String.length s then false
else if s.[i] = p.[ip] then is_word s (i + 1) p (ip + 1)
else false
in
is_word s i p 0
Checks if word that starts at position [ i ] in [ s ] is one of abbreviation
let rec search_abbrev s i = function
| (w, a) :: pl ->
if is_word s i w then Some (String.length w, a) else search_abbrev s i pl
| [] -> None
(* Name.abbrev: suppress lowercase particles, shorten "saint" into "st" *)
let abbrev s =
let rec copy can_start_abbrev i len =
if i >= String.length s then Buff.get len
else
match s.[i] with
| ' ' -> copy true (i + 1) (Buff.store len ' ')
| c ->
if can_start_abbrev then
match search_abbrev s i abbrev_list with
| None -> copy false (i + 1) (Buff.store len c)
| Some (n, Some a) -> copy false (i + n) (Buff.mstore len a)
| Some (n, None) -> copy true (i + n + 1) len
else copy false (i + 1) (Buff.store len c)
in
copy true 0 0
Name.strip
(* Name.strip_c = name without the charater c given as parameter *)
let strip_c s c =
let rec copy i len =
if i = String.length s then Buff.get len
else if s.[i] = c then copy (i + 1) len
else copy (i + 1) (Buff.store len s.[i])
in
copy 0 0
let strip s = strip_c s ' '
String without any forbidden caracters defined in forbidden_char
(* ******************************************************************** *)
[ Fonc ] purge : string - > string
(* ******************************************************************** *)
* [ Description ] : interdits ( défini par
forbidden_char ) présents dans la chaine passée en
argument .
[ ] :
- s : string que ] :
- string : retourne la chaîne délestée des caractères interdits
[ Rem ] : en clair hors de ce module .
forbidden_char) présents dans la chaine passée en
argument.
[Args] :
- s : string que l'on veut purger
[Retour] :
- string : retourne la chaîne délestée des caractères interdits
[Rem] : Exporté en clair hors de ce module. *)
let purge s = List.fold_left strip_c s forbidden_char
(* Name.crush *)
(* If string starting from [i] contains roman number then returns the next position,
else returns None. *)
let roman_number s i =
let rec loop i =
if i = String.length s then Some i
else if s.[i] = ' ' then Some i
else match s.[i] with 'i' | 'v' | 'x' | 'l' -> loop (i + 1) | _ -> None
in
if i = 0 || s.[i - 1] = ' ' then loop i else None
(* Name.crush, a custom sonnex/soundex-like phonetic algorithm:
- no spaces
- roman numbers are keeped
- vowels are suppressed, except in words starting with a vowel,
where this vowel is converted into "e"
- "k" and "q" replaced by "c"
- "y" replaced by "i"
- "z" replaced by "s"
- "ph" replaced by "f"
- others "h" deleted
- s at end of words are deleted
- no double lowercase consons *)
let crush s =
let rec copy i len first_vowel =
if i = String.length s then Buff.get len
else if s.[i] = ' ' then copy (i + 1) len true
else
match roman_number s i with
| Some j ->
let rec loop i len =
if i = j then copy j len true
else loop (i + 1) (Buff.store len s.[i])
in
loop i len
| _ -> (
match s.[i] with
| 'a' | 'e' | 'i' | 'o' | 'u' | 'y' ->
let len = if first_vowel then Buff.store len 'e' else len in
copy (i + 1) len false
| 'h' ->
let len =
if i > 0 && s.[i - 1] = 'p' then Buff.store (len - 1) 'f'
else len
in
copy (i + 1) len first_vowel
| ('s' | 'z') when i = String.length s - 1 || s.[i + 1] = ' ' ->
let len =
let rec loop i len =
if
i > 0 && len > 0
&& s.[i] = Bytes.get !Buff.buff len
&& (s.[i] = 's' || s.[i] = 'z')
then loop (i - 1) (len - 1)
else len + 1
in
loop (i - 1) (len - 1)
in
copy (i + 1) len false
| 's' when i = String.length s - 1 || s.[i + 1] = ' ' ->
copy (i + 1) len false
| c ->
if i > 0 && s.[i - 1] = c then copy (i + 1) len false
else
let c = match c with 'k' | 'q' -> 'c' | 'z' -> 's' | c -> c in
copy (i + 1) (Buff.store len c) false)
in
copy 0 0 true
(* strip_lower *)
strip_lower = strip o lower , as first comparison of names .
First names and Surnames comparison is strip_lower equality .
First names and Surnames comparison is strip_lower equality. *)
let strip_lower s = strip (lower s)
(* crush_lower *)
crush_lower = crush o abbrev o lower , as second comparison of names .
In index by names , the " names " are crush_lowers
In index by names, the "names" are crush_lowers *)
let crush_lower s = crush (abbrev (lower s))
concat two strings using Bytes module
let concat_aux fn l1 sn l2 =
let b = Bytes.create (l1 + l2 + 1) in
Bytes.blit_string fn 0 b 0 l1;
Bytes.blit_string sn 0 b (l1 + 1) l2;
Bytes.unsafe_set b l1 ' ';
Bytes.unsafe_to_string b
let concat fn sn = concat_aux fn (String.length fn) sn (String.length sn)
let contains_forbidden_char s = List.exists (String.contains s) forbidden_char
(* Copy/paste from String.split_on_char adapted to our needs *)
let split_sname_callback fn s =
let open String in
let j = ref (length s) in
for i = length s - 1 downto 0 do
if match unsafe_get s i with ' ' | '-' -> true | _ -> false then (
fn (i + 1) (!j - i - 1);
j := i)
done;
fn 0 !j
(* Copy/paste from String.split_on_char adapted to our needs *)
let split_fname_callback fn s =
let open String in
let j = ref (length s) in
for i = length s - 1 downto 0 do
if unsafe_get s i = ' ' then (
fn (i + 1) (!j - i - 1);
j := i)
done;
fn 0 !j
let split_sname s =
let r = ref [] in
split_sname_callback (fun i j -> r := String.sub s i j :: !r) s;
!r
let split_fname s =
let r = ref [] in
split_fname_callback (fun i j -> r := String.sub s i j :: !r) s;
!r
| null |
https://raw.githubusercontent.com/geneweb/geneweb/747f43da396a706bd1da60d34c04493a190edf0f/lib/util/name.ml
|
ocaml
|
La liste des caractères interdits
Name.abbrev
List of abbreviations. If abbreviation is mapped to [Some s] should be remplaced by
[s]. If mapped to None, it should be removed from name.
Checks if the word starting at [i] in [s] is [p].
Name.abbrev: suppress lowercase particles, shorten "saint" into "st"
Name.strip_c = name without the charater c given as parameter
********************************************************************
********************************************************************
Name.crush
If string starting from [i] contains roman number then returns the next position,
else returns None.
Name.crush, a custom sonnex/soundex-like phonetic algorithm:
- no spaces
- roman numbers are keeped
- vowels are suppressed, except in words starting with a vowel,
where this vowel is converted into "e"
- "k" and "q" replaced by "c"
- "y" replaced by "i"
- "z" replaced by "s"
- "ph" replaced by "f"
- others "h" deleted
- s at end of words are deleted
- no double lowercase consons
strip_lower
crush_lower
Copy/paste from String.split_on_char adapted to our needs
Copy/paste from String.split_on_char adapted to our needs
|
Copyright ( c ) 1998 - 2007 INRIA
let forbidden_char = [ ':'; '@'; '#'; '='; '$' ]
Name.lower
let unaccent_utf_8 lower s i =
let fns =
if lower then fun n s -> (String.lowercase_ascii s, n) else fun n s -> (s, n)
in
let fnc =
if lower then fun n c -> (String.make 1 @@ Char.lowercase_ascii c, n)
else fun n c -> (String.make 1 c, n)
in
let s, n =
Unidecode.decode fns fnc
(fun n -> (String.sub s i (n - i), n))
s i (String.length s)
in
if lower then (String.lowercase_ascii s, n) else (s, n)
let next_chars_if_equiv s i t j =
if i >= String.length s || j >= String.length t then None
else
let s1, i1 = unaccent_utf_8 true s i in
let t1, j1 = unaccent_utf_8 true t j in
if s1 = t1 then Some (i1, j1) else None
Name.lower :
- uppercase - > lowercase
- no accents
- chars no letters and no numbers ( except ' . ' ) = > spaces ( stripped )
Key comparison ( first name , surname , number ) applies " lower " equality
on first names and surnames
- uppercase -> lowercase
- no accents
- chars no letters and no numbers (except '.') => spaces (stripped)
Key comparison (first name, surname, number) applies "lower" equality
on first names and surnames *)
let lower s =
let rec copy special i len =
if i = String.length s then Buff.get len
else if Char.code s.[i] < 0x80 then
match s.[i] with
| ('a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '.') as c ->
let len = if special then Buff.store len ' ' else len in
let c = Char.lowercase_ascii c in
copy false (i + 1) (Buff.store len c)
| _ -> copy (len <> 0) (i + 1) len
else
let len = if special then Buff.store len ' ' else len in
let t, j = unaccent_utf_8 true s i in
copy false j (Buff.mstore len t)
in
copy false 0 0
let title s =
let t = ref true in
let cmap u =
let r = if !t then Uucp.Case.Map.to_upper u else Uucp.Case.Map.to_lower u in
t := not (Uucp.Alpha.is_alphabetic u);
r
in
Utf8.cmap_utf_8 cmap s
let abbrev_list =
[
("a", None);
("af", None);
("d", None);
("de", None);
("di", None);
("ier", Some "i");
("of", None);
("saint", Some "st");
("sainte", Some "ste");
("van", None);
("von", None);
("zu", None);
("zur", None);
]
let is_word s i p =
let rec is_word s i p ip =
if ip = String.length p then
if i = String.length s then true else if s.[i] = ' ' then true else false
else if i = String.length s then false
else if s.[i] = p.[ip] then is_word s (i + 1) p (ip + 1)
else false
in
is_word s i p 0
Checks if word that starts at position [ i ] in [ s ] is one of abbreviation
let rec search_abbrev s i = function
| (w, a) :: pl ->
if is_word s i w then Some (String.length w, a) else search_abbrev s i pl
| [] -> None
let abbrev s =
let rec copy can_start_abbrev i len =
if i >= String.length s then Buff.get len
else
match s.[i] with
| ' ' -> copy true (i + 1) (Buff.store len ' ')
| c ->
if can_start_abbrev then
match search_abbrev s i abbrev_list with
| None -> copy false (i + 1) (Buff.store len c)
| Some (n, Some a) -> copy false (i + n) (Buff.mstore len a)
| Some (n, None) -> copy true (i + n + 1) len
else copy false (i + 1) (Buff.store len c)
in
copy true 0 0
Name.strip
let strip_c s c =
let rec copy i len =
if i = String.length s then Buff.get len
else if s.[i] = c then copy (i + 1) len
else copy (i + 1) (Buff.store len s.[i])
in
copy 0 0
let strip s = strip_c s ' '
String without any forbidden caracters defined in forbidden_char
[ Fonc ] purge : string - > string
* [ Description ] : interdits ( défini par
forbidden_char ) présents dans la chaine passée en
argument .
[ ] :
- s : string que ] :
- string : retourne la chaîne délestée des caractères interdits
[ Rem ] : en clair hors de ce module .
forbidden_char) présents dans la chaine passée en
argument.
[Args] :
- s : string que l'on veut purger
[Retour] :
- string : retourne la chaîne délestée des caractères interdits
[Rem] : Exporté en clair hors de ce module. *)
let purge s = List.fold_left strip_c s forbidden_char
let roman_number s i =
let rec loop i =
if i = String.length s then Some i
else if s.[i] = ' ' then Some i
else match s.[i] with 'i' | 'v' | 'x' | 'l' -> loop (i + 1) | _ -> None
in
if i = 0 || s.[i - 1] = ' ' then loop i else None
let crush s =
let rec copy i len first_vowel =
if i = String.length s then Buff.get len
else if s.[i] = ' ' then copy (i + 1) len true
else
match roman_number s i with
| Some j ->
let rec loop i len =
if i = j then copy j len true
else loop (i + 1) (Buff.store len s.[i])
in
loop i len
| _ -> (
match s.[i] with
| 'a' | 'e' | 'i' | 'o' | 'u' | 'y' ->
let len = if first_vowel then Buff.store len 'e' else len in
copy (i + 1) len false
| 'h' ->
let len =
if i > 0 && s.[i - 1] = 'p' then Buff.store (len - 1) 'f'
else len
in
copy (i + 1) len first_vowel
| ('s' | 'z') when i = String.length s - 1 || s.[i + 1] = ' ' ->
let len =
let rec loop i len =
if
i > 0 && len > 0
&& s.[i] = Bytes.get !Buff.buff len
&& (s.[i] = 's' || s.[i] = 'z')
then loop (i - 1) (len - 1)
else len + 1
in
loop (i - 1) (len - 1)
in
copy (i + 1) len false
| 's' when i = String.length s - 1 || s.[i + 1] = ' ' ->
copy (i + 1) len false
| c ->
if i > 0 && s.[i - 1] = c then copy (i + 1) len false
else
let c = match c with 'k' | 'q' -> 'c' | 'z' -> 's' | c -> c in
copy (i + 1) (Buff.store len c) false)
in
copy 0 0 true
strip_lower = strip o lower , as first comparison of names .
First names and Surnames comparison is strip_lower equality .
First names and Surnames comparison is strip_lower equality. *)
let strip_lower s = strip (lower s)
crush_lower = crush o abbrev o lower , as second comparison of names .
In index by names , the " names " are crush_lowers
In index by names, the "names" are crush_lowers *)
let crush_lower s = crush (abbrev (lower s))
concat two strings using Bytes module
let concat_aux fn l1 sn l2 =
let b = Bytes.create (l1 + l2 + 1) in
Bytes.blit_string fn 0 b 0 l1;
Bytes.blit_string sn 0 b (l1 + 1) l2;
Bytes.unsafe_set b l1 ' ';
Bytes.unsafe_to_string b
let concat fn sn = concat_aux fn (String.length fn) sn (String.length sn)
let contains_forbidden_char s = List.exists (String.contains s) forbidden_char
let split_sname_callback fn s =
let open String in
let j = ref (length s) in
for i = length s - 1 downto 0 do
if match unsafe_get s i with ' ' | '-' -> true | _ -> false then (
fn (i + 1) (!j - i - 1);
j := i)
done;
fn 0 !j
let split_fname_callback fn s =
let open String in
let j = ref (length s) in
for i = length s - 1 downto 0 do
if unsafe_get s i = ' ' then (
fn (i + 1) (!j - i - 1);
j := i)
done;
fn 0 !j
let split_sname s =
let r = ref [] in
split_sname_callback (fun i j -> r := String.sub s i j :: !r) s;
!r
let split_fname s =
let r = ref [] in
split_fname_callback (fun i j -> r := String.sub s i j :: !r) s;
!r
|
17b6dd271b3f27d4a1cb5791d4c1e268891b5117845f8204cec4fbc3b133fd87
|
atzedijkstra/chr
|
Core.hs
|
# LANGUAGE ConstraintKinds , MultiParamTypeClasses , FlexibleInstances , FunctionalDependencies , UndecidableInstances , ExistentialQuantification , ScopedTypeVariables , StandaloneDeriving , GeneralizedNewtypeDeriving , TemplateHaskell , NoMonomorphismRestriction #
-------------------------------------------------------------------------------------------
--- Constraint Handling Rules
-------------------------------------------------------------------------------------------
module CHR.Types.Core
( IsConstraint(..)
, ConstraintSolvesVia(..)
, IsCHRConstraint(..)
, IsCHRGuard(..)
, IsCHRPrio(..)
, IsCHRBacktrackPrio(..)
, CHREmptySubstitution(..)
, CHRMatcherFailure(..)
, CHRMatcher
, chrmatcherRun'
, chrmatcherRun
, chrmatcherstateEnv
, chrmatcherstateVarLookup
, chrMatchResolveCompareAndContinue
, chrMatchSubst
, chrMatchBind
, chrMatchFail
, chrMatchFailNoBinding
, chrMatchSuccess
, chrMatchWait
, chrMatchSucces
, CHRMatchEnv(..)
, emptyCHRMatchEnv
, CHRMatchable(..)
, CHRMatchableKey
, CHRMatchHow(..)
, chrMatchAndWaitToM
, CHRWaitForVarSet
, CHRCheckable(..)
, Prio(..)
, CHRPrioEvaluatable(..)
, CHRPrioEvaluatableVal
, CHRTrOpt(..)
, IVar
, VarToNmMp
, emptyVarToNmMp
, NmToVarMp
, emptyNmToVarMp
)
where
import qualified Data.Map.Strict as Map
import qualified Data.HashMap.Strict as MapH
import qualified Data.IntMap.Strict as IntMap
import Data.Word
import Data.Monoid
import Data.Typeable
import Data.Function
import qualified Data.Set as Set
import Unsafe.Coerce
import Control.Monad
import Control.Monad.State -- .Strict
import Control.Monad.Except
import Control.Monad.Identity
import CHR.Pretty
import CHR.Data.VarMp
import CHR.Data.Lookup (Lookup, Stacked, LookupApply)
import qualified CHR.Data.Lookup as Lk
import qualified CHR.Data.Lookup.Stacked as Lk
import qualified CHR.Data.TreeTrie as TT
import CHR.Data.Lens
import CHR.Utils
import CHR.Data.Substitutable
-------------------------------------------------------------------------------------------
--- Name <-> Var mapping
-------------------------------------------------------------------------------------------
type IVar = IntMap.Key
type VarToNmMp = IntMap.IntMap String
type NmToVarMp = MapH.HashMap String IVar
emptyVarToNmMp :: VarToNmMp = IntMap.empty
emptyNmToVarMp :: NmToVarMp = MapH.empty
-------------------------------------------------------------------------------------------
--- CHRMatchHow
-------------------------------------------------------------------------------------------
-- | How to match, increasingly more binding is allowed
data CHRMatchHow
= CHRMatchHow_Check -- ^ equality check only
^ also allow one - directional ( left to right ) matching / binding of ( meta)vars
| CHRMatchHow_MatchAndWait -- ^ also allow giving back of global vars on which we wait
| CHRMatchHow_Unify -- ^ also allow bi-directional matching, i.e. unification
deriving (Ord, Eq)
-------------------------------------------------------------------------------------------
--- CHRMatchEnv
-------------------------------------------------------------------------------------------
-- | Context/environment required for matching itself
data CHRMatchEnv k
= CHRMatchEnv
{ {- chrmatchenvHow :: !CHRMatchHow
, -}
chrmatchenvMetaMayBind :: !(k -> Bool)
}
emptyCHRMatchEnv :: CHRMatchEnv x
emptyCHRMatchEnv = CHRMatchEnv {- CHRMatchHow_Check -} (const True)
-------------------------------------------------------------------------------------------
--- Wait for var
-------------------------------------------------------------------------------------------
type CHRWaitForVarSet s = Set.Set (VarLookupKey s)
-------------------------------------------------------------------------------------------
--- CHRMatcher, call back API used during matching
-------------------------------------------------------------------------------------------
data CHRMatcherState subst k
= CHRMatcherState
{ _ chrmatcherstateVarLookup : : ! ( subst )
, _ chrmatcherstateWaitForVarSet : : ! ( CHRWaitForVarSet subst )
, _ chrmatcherstateEnv : : ! ( CHRMatchEnv k )
}
deriving Typeable
data CHRMatcherState subst k
= CHRMatcherState
{ _chrmatcherstateVarLookup :: !(StackedVarLookup subst)
, _chrmatcherstateWaitForVarSet :: !(CHRWaitForVarSet subst)
, _chrmatcherstateEnv :: !(CHRMatchEnv k)
}
deriving Typeable
-}
type CHRMatcherState subst k = (StackedVarLookup subst, CHRWaitForVarSet (Lk.StackedElt (StackedVarLookup subst)), CHRMatchEnv k)
mkCHRMatcherState :: StackedVarLookup subst -> CHRWaitForVarSet (Lk.StackedElt (StackedVarLookup subst)) -> CHRMatchEnv k -> CHRMatcherState subst k
mkCHRMatcherState s w e = (s, w, e)
mkCHRMatcherState s w e = CHRMatcherState s w e
# INLINE mkCHRMatcherState #
unCHRMatcherState :: CHRMatcherState subst k -> (StackedVarLookup subst, CHRWaitForVarSet (Lk.StackedElt (StackedVarLookup subst)), CHRMatchEnv k)
unCHRMatcherState = id
-- unCHRMatcherState (CHRMatcherState s w e) = (s,w,e)
# INLINE unCHRMatcherState #
-- | Failure of CHRMatcher
data CHRMatcherFailure
= CHRMatcherFailure
| CHRMatcherFailure_NoBinding -- ^ absence of binding
-- | Matching monad, keeping a stacked (pair) of subst (local + global), and a set of global variables upon which the solver has to wait in order to (possibly) match further/again
type CHRMatcher subst = StateT ( StackedVarLookup subst , CHRWaitForVarSet subst ) ( Either ( ) )
type CHRMatcher subst = StateT (CHRMatcherState subst (VarLookupKey subst)) (Either CHRMatcherFailure)
instance ( k ~ VarLookupKey subst ) = > MonadState ( CHRMatcherState subst k ) ( CHRMatcher subst )
chrmatcherstateVarLookup = fst3l
chrmatcherstateWaitForVarSet = snd3l
chrmatcherstateEnv = trd3l
mkLabel '' CHRMatcherState
mkLabel ''CHRMatcherState
-}
-------------------------------------------------------------------------------------------
--- Common part w.r.t. variable lookup
-------------------------------------------------------------------------------------------
-- | Do the resolution part of a comparison, continuing with a function which can assume variable resolution has been done for the terms being compared
chrMatchResolveCompareAndContinue
:: forall s .
( Lookup s (VarLookupKey s) (VarLookupVal s)
, LookupApply s s
, Ord (VarLookupKey s)
, VarTerm (VarLookupVal s)
, ExtrValVarKey (VarLookupVal s) ~ VarLookupKey s
)
=> CHRMatchHow -- ^ how to do the resolution
-> (VarLookupVal s -> VarLookupVal s -> CHRMatcher s ()) -- ^ succeed with successful varlookup continuation
-> VarLookupVal s -- ^ left/fst val
-> VarLookupVal s -- ^ right/snd val
-> CHRMatcher s ()
chrMatchResolveCompareAndContinue how ok t1 t2
= cmp t1 t2
where cmp t1 t2 = do
menv <- getl chrmatcherstateEnv
case (varTermMbKey t1, varTermMbKey t2) of
(Just v1, Just v2) | v1 == v2 -> chrMatchSuccess
| how == CHRMatchHow_Check -> varContinue
(varContinue (waitv v1 >> waitv v2) (ok t1) v2)
(\t1 -> varContinue (waitt t1 >> waitv v2) (ok t1) v2)
v1
where waitv v = unless (chrmatchenvMetaMayBind menv v) $ chrMatchWait v
waitt = maybe (return ()) waitv . varTermMbKey
(Just v1, _ ) | how == CHRMatchHow_Check -> varContinue (if maybind then chrMatchFail else chrMatchWait v1) (flip ok t2) v1
| how >= CHRMatchHow_Match && maybind
-> varContinue (chrMatchBind v1 t2) (flip ok t2) v1
| otherwise -> varContinue chrMatchFail (flip ok t2) v1
where maybind = chrmatchenvMetaMayBind menv v1
(_ , Just v2) | how == CHRMatchHow_Check -> varContinue (if maybind then chrMatchFail else chrMatchWait v2) (ok t1) v2
| how == CHRMatchHow_MatchAndWait -> varContinue (chrMatchWait v2) (ok t1) v2
| how == CHRMatchHow_Unify && maybind
-> varContinue (chrMatchBind v2 t1) (ok t1) v2
| otherwise -> varContinue chrMatchFail (ok t1) v2
where maybind = chrmatchenvMetaMayBind menv v2
_ -> chrMatchFail -- ok t1 t2
varContinue = Lk.lookupResolveAndContinueM varTermMbKey chrMatchSubst
-------------------------------------------------------------------------------------------
--- CHRCheckable
-------------------------------------------------------------------------------------------
| A Checkable participates in the reduction process as a guard , to be checked .
-- Checking is allowed to find/return substitutions for meta variables (not for global variables).
class (CHREmptySubstitution subst, LookupApply subst subst) => CHRCheckable env x subst where
chrCheck :: env -> subst -> x -> Maybe subst
chrCheck e s x = chrmatcherUnlift (chrCheckM e x) emptyCHRMatchEnv s
chrCheckM :: env -> x -> CHRMatcher subst ()
chrCheckM e x = chrmatcherLift $ \sg -> chrCheck e sg x
-------------------------------------------------------------------------------------------
--- CHRPrioEvaluatable
-------------------------------------------------------------------------------------------
| The type of value a prio representation evaluates to , must be instance
type family CHRPrioEvaluatableVal p :: *
| A PrioEvaluatable participates in the reduction process to indicate the rule priority , higher prio takes precedence
class (Ord (CHRPrioEvaluatableVal x), Bounded (CHRPrioEvaluatableVal x)) => CHRPrioEvaluatable env x subst where
| Reduce to a prio representation
chrPrioEval :: env -> subst -> x -> CHRPrioEvaluatableVal x
chrPrioEval _ _ _ = minBound
-- | Compare priorities
chrPrioCompare :: env -> (subst,x) -> (subst,x) -> Ordering
chrPrioCompare e (s1,x1) (s2,x2) = chrPrioEval e s1 x1 `compare` chrPrioEval e s2 x2
| Lift into
chrPrioLift :: proxy env -> proxy subst -> CHRPrioEvaluatableVal x -> x
-------------------------------------------------------------------------------------------
--- Prio
-------------------------------------------------------------------------------------------
| Separate priority type , where represents lowest , and compare sorts from high to low ( i.e. high ` compare ` low = = LT )
newtype Prio = Prio {unPrio :: Word32}
deriving (Eq, Bounded, Num, Enum, Integral, Real)
instance Ord Prio where
compare = flip compare `on` unPrio
# INLINE compare #
-------------------------------------------------------------------------------------------
--- Constraint API
-------------------------------------------------------------------------------------------
-- | Alias API for constraint requirements
type IsCHRConstraint env c subst
= ( CHRMatchable env c subst
-- , CHRBuiltinSolvable env c subst
, VarExtractable c
, VarUpdatable c subst
, Typeable c
, Serialize c
, TTKeyable c
, TT.TreeTrieKeyable c
, IsConstraint c
, Ord c
, ( TTKey c )
, Ord (TT.TrTrKey c)
, PP c
, PP ( TTKey c )
, PP (TT.TrTrKey c)
)
-------------------------------------------------------------------------------------------
--- Guard API
-------------------------------------------------------------------------------------------
-- | Alias API for guard requirements
type IsCHRGuard env g subst
= ( CHRCheckable env g subst
, VarExtractable g
, VarUpdatable g subst
, Typeable g
,
, PP g
)
-------------------------------------------------------------------------------------------
--- Prio API
-------------------------------------------------------------------------------------------
-- | Alias API for priority requirements
type IsCHRPrio env p subst
= ( CHRPrioEvaluatable env p subst
, Typeable p
, Serialize p
, PP p
)
-- | Alias API for backtrack priority requirements
type IsCHRBacktrackPrio env bp subst
= ( IsCHRPrio env bp subst
, CHRMatchable env bp subst
, PP (CHRPrioEvaluatableVal bp)
-- , ( CHRPrioEvaluatableVal bp )
)
-------------------------------------------------------------------------------------------
--- What a constraint must be capable of
-------------------------------------------------------------------------------------------
-- | Different ways of solving
data ConstraintSolvesVia
^ rewrite / CHR rules apply
| ConstraintSolvesVia_Solve -- ^ solving involving finding of variable bindings (e.g. unification)
| ConstraintSolvesVia_Residual -- ^ a leftover, residue
| ConstraintSolvesVia_Fail -- ^ triggers explicit fail
| ConstraintSolvesVia_Succeed -- ^ triggers explicit succes
deriving (Show, Enum, Eq, Ord)
instance PP ConstraintSolvesVia where
pp = pp . show
-- | The things a constraints needs to be capable of in order to participate in solving
class IsConstraint c where
-- | Requires solving? Or is just a residue...
cnstrRequiresSolve :: c -> Bool
cnstrRequiresSolve c = case cnstrSolvesVia c of
ConstraintSolvesVia_Residual -> False
_ -> True
cnstrSolvesVia :: c -> ConstraintSolvesVia
cnstrSolvesVia c | cnstrRequiresSolve c = ConstraintSolvesVia_Rule
| otherwise = ConstraintSolvesVia_Residual
-------------------------------------------------------------------------------------------
- Tracing options , specific for CHR solvers
-------------------------------------------------------------------------------------------
data CHRTrOpt
= CHRTrOpt_Lookup -- ^ trie query
| CHRTrOpt_Stats -- ^ various stats
deriving (Eq, Ord, Show)
-------------------------------------------------------------------------------------------
--- CHREmptySubstitution
-------------------------------------------------------------------------------------------
-- | Capability to yield an empty substitution.
class CHREmptySubstitution subst where
chrEmptySubst :: subst
-------------------------------------------------------------------------------------------
--- CHRMatchable
-------------------------------------------------------------------------------------------
-- | The key of a substitution
type family CHRMatchableKey subst :: *
type instance CHRMatchableKey (StackedVarLookup subst) = CHRMatchableKey subst
-- | A Matchable participates in the reduction process as a reducable constraint.
-- Unification may be incorporated as well, allowing matching to be expressed in terms of unification.
-- This facilitates implementations of 'CHRBuiltinSolvable'.
class (CHREmptySubstitution subst, LookupApply subst subst, VarExtractable x, VarLookupKey subst ~ ExtrValVarKey x) => CHRMatchable env x subst where
| One - directional ( 1st to 2nd ' x ' ) unify
chrMatchTo :: env -> subst -> x -> x -> Maybe subst
chrMatchTo env s x1 x2 = chrUnify CHRMatchHow_Match (emptyCHRMatchEnv {chrmatchenvMetaMayBind = (`Set.member` varFreeSet x1)}) env s x1 x2
-- where free = varFreeSet x1
| One - directional ( 1st to 2nd ' x ' ) unify
chrUnify :: CHRMatchHow -> CHRMatchEnv (VarLookupKey subst) -> env -> subst -> x -> x -> Maybe subst
chrUnify how menv e s x1 x2 = chrmatcherUnlift (chrUnifyM how e x1 x2) menv s
| Match one - directional ( from 1st to 2nd arg ) , under a subst , yielding a subst for the metavars in the 1st arg , waiting for those in the 2nd
chrMatchToM :: env -> x -> x -> CHRMatcher subst ()
chrMatchToM e x1 x2 = chrUnifyM CHRMatchHow_Match e x1 x2
| Unify bi - directional or match one - directional ( from 1st to 2nd arg ) , under a subst , yielding a subst for the metavars in the 1st arg , waiting for those in the 2nd
chrUnifyM :: CHRMatchHow -> env -> x -> x -> CHRMatcher subst ()
chrUnifyM how e x1 x2 = getl chrmatcherstateEnv >>= \menv -> chrmatcherLift $ \sg -> chrUnify how menv e sg x1 x2
-- | Solve a constraint which is categorized as 'ConstraintSolvesVia_Solve'
chrBuiltinSolveM :: env -> x -> CHRMatcher subst ()
chrmatcherLift $ \sg - > chrBuiltinSolve e sg x
instance {-# OVERLAPPABLE #-} (CHRMatchable env x subst) => CHRMatchable env (Maybe x) subst where
chrUnifyM how e (Just x1) (Just x2) = chrUnifyM how e x1 x2
chrUnifyM how e Nothing Nothing = chrMatchSuccess
chrUnifyM how e _ _ = chrMatchFail
instance {-# OVERLAPPABLE #-} (CHRMatchable env x subst) => CHRMatchable env [x] subst where
chrUnifyM how e x1 x2 | length x1 == length x2 = sequence_ $ zipWith (chrUnifyM how e) x1 x2
chrUnifyM how e _ _ = chrMatchFail
-------------------------------------------------------------------------------------------
--- CHRMatcher API, part I
-------------------------------------------------------------------------------------------
| Unlift / observe ( or run ) a CHRMatcher
chrmatcherUnlift :: (CHREmptySubstitution subst) => CHRMatcher subst () -> CHRMatchEnv (VarLookupKey subst) -> (subst -> Maybe subst)
chrmatcherUnlift mtch menv s = do
(s,w) <- chrmatcherRun mtch menv s
if Set.null w then Just s else Nothing
-- | Lift into CHRMatcher
chrmatcherLift :: (LookupApply subst subst) => (subst -> Maybe subst) -> CHRMatcher subst ()
chrmatcherLift f = do
gets ( . _ chrmatcherstateVarLookup )
case Lk.unlifts stLk of
[sl,sg] -> maybe chrMatchFail (\snew -> chrmatcherstateVarLookup =$: (Lk.apply snew)) $ f sg
_ -> chrMatchFail
-- | Run a CHRMatcher
chrmatcherRun' :: (CHREmptySubstitution subst) => (CHRMatcherFailure -> r) -> (subst -> CHRWaitForVarSet subst -> x -> r) -> CHRMatcher subst x -> CHRMatchEnv (VarLookupKey subst) -> StackedVarLookup subst -> r
chrmatcherRun' fail succes mtch menv s = either
fail
((\(x,ms) -> let (s, w, _) = unCHRMatcherState ms in succes (Lk.top s) w x))
$ flip runStateT (mkCHRMatcherState s Set.empty menv)
$ mtch
-- | Run a CHRMatcher
chrmatcherRun :: (CHREmptySubstitution subst) => CHRMatcher subst () -> CHRMatchEnv (VarLookupKey subst) -> subst -> Maybe (subst, CHRWaitForVarSet subst)
( [ chrEmptySubst , s ] )
-------------------------------------------------------------------------------------------
- CHRMatcher API , part II
-------------------------------------------------------------------------------------------
chrMatchSubst :: CHRMatcher subst (StackedVarLookup subst)
chrMatchSubst = getl chrmatcherstateVarLookup
# INLINE chrMatchSubst #
chrMatchBind :: forall subst k v . (LookupApply subst subst, Lookup subst k v, k ~ VarLookupKey subst, v ~ VarLookupVal subst) => k -> v -> CHRMatcher subst ()
chrMatchBind k v = chrmatcherstateVarLookup =$: ((Lk.singleton k v :: subst) `Lk.apply`)
# INLINE chrMatchBind #
chrMatchWait :: (Ord k, k ~ VarLookupKey subst) => k -> CHRMatcher subst ()
chrMatchWait k = chrMatchModifyWait (Set.insert k)
# INLINE chrMatchWait #
chrMatchSuccess :: CHRMatcher subst ()
chrMatchSuccess = return ()
# INLINE chrMatchSuccess #
-- | Normal CHRMatcher failure
chrMatchFail :: CHRMatcher subst a
chrMatchFail = throwError CHRMatcherFailure
# INLINE chrMatchFail #
-- | CHRMatcher failure because a variable binding is missing
chrMatchFailNoBinding :: CHRMatcher subst a
chrMatchFailNoBinding = throwError CHRMatcherFailure_NoBinding
{-# INLINE chrMatchFailNoBinding #-}
chrMatchSucces :: CHRMatcher subst ()
chrMatchSucces = return ()
# INLINE chrMatchSucces #
chrMatchModifyWait :: (CHRWaitForVarSet subst -> CHRWaitForVarSet subst) -> CHRMatcher subst ()
chrMatchModifyWait f =
modify ( \st - > st { _ chrmatcherstateWaitForVarSet = f $ _ chrmatcherstateWaitForVarSet st } )
( chrmatcherstateWaitForVarSet = $ :)
modify (\(s,w,e) -> (s,f w,e))
# INLINE chrMatchModifyWait #
| Match one - directional ( from 1st to 2nd arg ) , under a subst , yielding a subst for the metavars in the 1st arg , waiting for those in the 2nd
chrMatchAndWaitToM :: CHRMatchable env x subst => Bool -> env -> x -> x -> CHRMatcher subst ()
chrMatchAndWaitToM wait env x1 x2 = chrUnifyM (if wait then CHRMatchHow_MatchAndWait else CHRMatchHow_Match) env x1 x2
-------------------------------------------------------------------------------------------
--- CHRMatchable: instances
-------------------------------------------------------------------------------------------
-- TBD: move to other file...
instance {-# OVERLAPPABLE #-} Ord (ExtrValVarKey ()) => VarExtractable () where
varFreeSet _ = Set.empty
instance {-# OVERLAPPABLE #-} (Ord (ExtrValVarKey ()), CHREmptySubstitution subst, LookupApply subst subst, VarLookupKey subst ~ ExtrValVarKey ()) => CHRMatchable env () subst where
chrUnifyM _ _ _ _ = chrMatchSuccess
-------------------------------------------------------------------------------------------
--- Prio: instances
-------------------------------------------------------------------------------------------
instance Show Prio where
show = show . unPrio
instance PP Prio where
pp = pp . unPrio
-------------------------------------------------------------------------------------------
--- CHRPrioEvaluatable: instances
-------------------------------------------------------------------------------------------
type instance CHRPrioEvaluatableVal () = Prio
| null |
https://raw.githubusercontent.com/atzedijkstra/chr/035027514f0956cbb2889c7fafb272160ba33b4d/chr-core/src/CHR/Types/Core.hs
|
haskell
|
-----------------------------------------------------------------------------------------
- Constraint Handling Rules
-----------------------------------------------------------------------------------------
.Strict
-----------------------------------------------------------------------------------------
- Name <-> Var mapping
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
- CHRMatchHow
-----------------------------------------------------------------------------------------
| How to match, increasingly more binding is allowed
^ equality check only
^ also allow giving back of global vars on which we wait
^ also allow bi-directional matching, i.e. unification
-----------------------------------------------------------------------------------------
- CHRMatchEnv
-----------------------------------------------------------------------------------------
| Context/environment required for matching itself
chrmatchenvHow :: !CHRMatchHow
,
CHRMatchHow_Check
-----------------------------------------------------------------------------------------
- Wait for var
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
- CHRMatcher, call back API used during matching
-----------------------------------------------------------------------------------------
unCHRMatcherState (CHRMatcherState s w e) = (s,w,e)
| Failure of CHRMatcher
^ absence of binding
| Matching monad, keeping a stacked (pair) of subst (local + global), and a set of global variables upon which the solver has to wait in order to (possibly) match further/again
-----------------------------------------------------------------------------------------
- Common part w.r.t. variable lookup
-----------------------------------------------------------------------------------------
| Do the resolution part of a comparison, continuing with a function which can assume variable resolution has been done for the terms being compared
^ how to do the resolution
^ succeed with successful varlookup continuation
^ left/fst val
^ right/snd val
ok t1 t2
-----------------------------------------------------------------------------------------
- CHRCheckable
-----------------------------------------------------------------------------------------
Checking is allowed to find/return substitutions for meta variables (not for global variables).
-----------------------------------------------------------------------------------------
- CHRPrioEvaluatable
-----------------------------------------------------------------------------------------
| Compare priorities
-----------------------------------------------------------------------------------------
- Prio
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
- Constraint API
-----------------------------------------------------------------------------------------
| Alias API for constraint requirements
, CHRBuiltinSolvable env c subst
-----------------------------------------------------------------------------------------
- Guard API
-----------------------------------------------------------------------------------------
| Alias API for guard requirements
-----------------------------------------------------------------------------------------
- Prio API
-----------------------------------------------------------------------------------------
| Alias API for priority requirements
| Alias API for backtrack priority requirements
, ( CHRPrioEvaluatableVal bp )
-----------------------------------------------------------------------------------------
- What a constraint must be capable of
-----------------------------------------------------------------------------------------
| Different ways of solving
^ solving involving finding of variable bindings (e.g. unification)
^ a leftover, residue
^ triggers explicit fail
^ triggers explicit succes
| The things a constraints needs to be capable of in order to participate in solving
| Requires solving? Or is just a residue...
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
^ trie query
^ various stats
-----------------------------------------------------------------------------------------
- CHREmptySubstitution
-----------------------------------------------------------------------------------------
| Capability to yield an empty substitution.
-----------------------------------------------------------------------------------------
- CHRMatchable
-----------------------------------------------------------------------------------------
| The key of a substitution
| A Matchable participates in the reduction process as a reducable constraint.
Unification may be incorporated as well, allowing matching to be expressed in terms of unification.
This facilitates implementations of 'CHRBuiltinSolvable'.
where free = varFreeSet x1
| Solve a constraint which is categorized as 'ConstraintSolvesVia_Solve'
# OVERLAPPABLE #
# OVERLAPPABLE #
-----------------------------------------------------------------------------------------
- CHRMatcher API, part I
-----------------------------------------------------------------------------------------
| Lift into CHRMatcher
| Run a CHRMatcher
| Run a CHRMatcher
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
| Normal CHRMatcher failure
| CHRMatcher failure because a variable binding is missing
# INLINE chrMatchFailNoBinding #
-----------------------------------------------------------------------------------------
- CHRMatchable: instances
-----------------------------------------------------------------------------------------
TBD: move to other file...
# OVERLAPPABLE #
# OVERLAPPABLE #
-----------------------------------------------------------------------------------------
- Prio: instances
-----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------
- CHRPrioEvaluatable: instances
-----------------------------------------------------------------------------------------
|
# LANGUAGE ConstraintKinds , MultiParamTypeClasses , FlexibleInstances , FunctionalDependencies , UndecidableInstances , ExistentialQuantification , ScopedTypeVariables , StandaloneDeriving , GeneralizedNewtypeDeriving , TemplateHaskell , NoMonomorphismRestriction #
module CHR.Types.Core
( IsConstraint(..)
, ConstraintSolvesVia(..)
, IsCHRConstraint(..)
, IsCHRGuard(..)
, IsCHRPrio(..)
, IsCHRBacktrackPrio(..)
, CHREmptySubstitution(..)
, CHRMatcherFailure(..)
, CHRMatcher
, chrmatcherRun'
, chrmatcherRun
, chrmatcherstateEnv
, chrmatcherstateVarLookup
, chrMatchResolveCompareAndContinue
, chrMatchSubst
, chrMatchBind
, chrMatchFail
, chrMatchFailNoBinding
, chrMatchSuccess
, chrMatchWait
, chrMatchSucces
, CHRMatchEnv(..)
, emptyCHRMatchEnv
, CHRMatchable(..)
, CHRMatchableKey
, CHRMatchHow(..)
, chrMatchAndWaitToM
, CHRWaitForVarSet
, CHRCheckable(..)
, Prio(..)
, CHRPrioEvaluatable(..)
, CHRPrioEvaluatableVal
, CHRTrOpt(..)
, IVar
, VarToNmMp
, emptyVarToNmMp
, NmToVarMp
, emptyNmToVarMp
)
where
import qualified Data.Map.Strict as Map
import qualified Data.HashMap.Strict as MapH
import qualified Data.IntMap.Strict as IntMap
import Data.Word
import Data.Monoid
import Data.Typeable
import Data.Function
import qualified Data.Set as Set
import Unsafe.Coerce
import Control.Monad
import Control.Monad.Except
import Control.Monad.Identity
import CHR.Pretty
import CHR.Data.VarMp
import CHR.Data.Lookup (Lookup, Stacked, LookupApply)
import qualified CHR.Data.Lookup as Lk
import qualified CHR.Data.Lookup.Stacked as Lk
import qualified CHR.Data.TreeTrie as TT
import CHR.Data.Lens
import CHR.Utils
import CHR.Data.Substitutable
type IVar = IntMap.Key
type VarToNmMp = IntMap.IntMap String
type NmToVarMp = MapH.HashMap String IVar
emptyVarToNmMp :: VarToNmMp = IntMap.empty
emptyNmToVarMp :: NmToVarMp = MapH.empty
data CHRMatchHow
^ also allow one - directional ( left to right ) matching / binding of ( meta)vars
deriving (Ord, Eq)
data CHRMatchEnv k
= CHRMatchEnv
chrmatchenvMetaMayBind :: !(k -> Bool)
}
emptyCHRMatchEnv :: CHRMatchEnv x
type CHRWaitForVarSet s = Set.Set (VarLookupKey s)
data CHRMatcherState subst k
= CHRMatcherState
{ _ chrmatcherstateVarLookup : : ! ( subst )
, _ chrmatcherstateWaitForVarSet : : ! ( CHRWaitForVarSet subst )
, _ chrmatcherstateEnv : : ! ( CHRMatchEnv k )
}
deriving Typeable
data CHRMatcherState subst k
= CHRMatcherState
{ _chrmatcherstateVarLookup :: !(StackedVarLookup subst)
, _chrmatcherstateWaitForVarSet :: !(CHRWaitForVarSet subst)
, _chrmatcherstateEnv :: !(CHRMatchEnv k)
}
deriving Typeable
-}
type CHRMatcherState subst k = (StackedVarLookup subst, CHRWaitForVarSet (Lk.StackedElt (StackedVarLookup subst)), CHRMatchEnv k)
mkCHRMatcherState :: StackedVarLookup subst -> CHRWaitForVarSet (Lk.StackedElt (StackedVarLookup subst)) -> CHRMatchEnv k -> CHRMatcherState subst k
mkCHRMatcherState s w e = (s, w, e)
mkCHRMatcherState s w e = CHRMatcherState s w e
# INLINE mkCHRMatcherState #
unCHRMatcherState :: CHRMatcherState subst k -> (StackedVarLookup subst, CHRWaitForVarSet (Lk.StackedElt (StackedVarLookup subst)), CHRMatchEnv k)
unCHRMatcherState = id
# INLINE unCHRMatcherState #
data CHRMatcherFailure
= CHRMatcherFailure
type CHRMatcher subst = StateT ( StackedVarLookup subst , CHRWaitForVarSet subst ) ( Either ( ) )
type CHRMatcher subst = StateT (CHRMatcherState subst (VarLookupKey subst)) (Either CHRMatcherFailure)
instance ( k ~ VarLookupKey subst ) = > MonadState ( CHRMatcherState subst k ) ( CHRMatcher subst )
chrmatcherstateVarLookup = fst3l
chrmatcherstateWaitForVarSet = snd3l
chrmatcherstateEnv = trd3l
mkLabel '' CHRMatcherState
mkLabel ''CHRMatcherState
-}
chrMatchResolveCompareAndContinue
:: forall s .
( Lookup s (VarLookupKey s) (VarLookupVal s)
, LookupApply s s
, Ord (VarLookupKey s)
, VarTerm (VarLookupVal s)
, ExtrValVarKey (VarLookupVal s) ~ VarLookupKey s
)
-> CHRMatcher s ()
chrMatchResolveCompareAndContinue how ok t1 t2
= cmp t1 t2
where cmp t1 t2 = do
menv <- getl chrmatcherstateEnv
case (varTermMbKey t1, varTermMbKey t2) of
(Just v1, Just v2) | v1 == v2 -> chrMatchSuccess
| how == CHRMatchHow_Check -> varContinue
(varContinue (waitv v1 >> waitv v2) (ok t1) v2)
(\t1 -> varContinue (waitt t1 >> waitv v2) (ok t1) v2)
v1
where waitv v = unless (chrmatchenvMetaMayBind menv v) $ chrMatchWait v
waitt = maybe (return ()) waitv . varTermMbKey
(Just v1, _ ) | how == CHRMatchHow_Check -> varContinue (if maybind then chrMatchFail else chrMatchWait v1) (flip ok t2) v1
| how >= CHRMatchHow_Match && maybind
-> varContinue (chrMatchBind v1 t2) (flip ok t2) v1
| otherwise -> varContinue chrMatchFail (flip ok t2) v1
where maybind = chrmatchenvMetaMayBind menv v1
(_ , Just v2) | how == CHRMatchHow_Check -> varContinue (if maybind then chrMatchFail else chrMatchWait v2) (ok t1) v2
| how == CHRMatchHow_MatchAndWait -> varContinue (chrMatchWait v2) (ok t1) v2
| how == CHRMatchHow_Unify && maybind
-> varContinue (chrMatchBind v2 t1) (ok t1) v2
| otherwise -> varContinue chrMatchFail (ok t1) v2
where maybind = chrmatchenvMetaMayBind menv v2
varContinue = Lk.lookupResolveAndContinueM varTermMbKey chrMatchSubst
| A Checkable participates in the reduction process as a guard , to be checked .
class (CHREmptySubstitution subst, LookupApply subst subst) => CHRCheckable env x subst where
chrCheck :: env -> subst -> x -> Maybe subst
chrCheck e s x = chrmatcherUnlift (chrCheckM e x) emptyCHRMatchEnv s
chrCheckM :: env -> x -> CHRMatcher subst ()
chrCheckM e x = chrmatcherLift $ \sg -> chrCheck e sg x
| The type of value a prio representation evaluates to , must be instance
type family CHRPrioEvaluatableVal p :: *
| A PrioEvaluatable participates in the reduction process to indicate the rule priority , higher prio takes precedence
class (Ord (CHRPrioEvaluatableVal x), Bounded (CHRPrioEvaluatableVal x)) => CHRPrioEvaluatable env x subst where
| Reduce to a prio representation
chrPrioEval :: env -> subst -> x -> CHRPrioEvaluatableVal x
chrPrioEval _ _ _ = minBound
chrPrioCompare :: env -> (subst,x) -> (subst,x) -> Ordering
chrPrioCompare e (s1,x1) (s2,x2) = chrPrioEval e s1 x1 `compare` chrPrioEval e s2 x2
| Lift into
chrPrioLift :: proxy env -> proxy subst -> CHRPrioEvaluatableVal x -> x
| Separate priority type , where represents lowest , and compare sorts from high to low ( i.e. high ` compare ` low = = LT )
newtype Prio = Prio {unPrio :: Word32}
deriving (Eq, Bounded, Num, Enum, Integral, Real)
instance Ord Prio where
compare = flip compare `on` unPrio
# INLINE compare #
type IsCHRConstraint env c subst
= ( CHRMatchable env c subst
, VarExtractable c
, VarUpdatable c subst
, Typeable c
, Serialize c
, TTKeyable c
, TT.TreeTrieKeyable c
, IsConstraint c
, Ord c
, ( TTKey c )
, Ord (TT.TrTrKey c)
, PP c
, PP ( TTKey c )
, PP (TT.TrTrKey c)
)
type IsCHRGuard env g subst
= ( CHRCheckable env g subst
, VarExtractable g
, VarUpdatable g subst
, Typeable g
,
, PP g
)
type IsCHRPrio env p subst
= ( CHRPrioEvaluatable env p subst
, Typeable p
, Serialize p
, PP p
)
type IsCHRBacktrackPrio env bp subst
= ( IsCHRPrio env bp subst
, CHRMatchable env bp subst
, PP (CHRPrioEvaluatableVal bp)
)
data ConstraintSolvesVia
^ rewrite / CHR rules apply
deriving (Show, Enum, Eq, Ord)
instance PP ConstraintSolvesVia where
pp = pp . show
class IsConstraint c where
cnstrRequiresSolve :: c -> Bool
cnstrRequiresSolve c = case cnstrSolvesVia c of
ConstraintSolvesVia_Residual -> False
_ -> True
cnstrSolvesVia :: c -> ConstraintSolvesVia
cnstrSolvesVia c | cnstrRequiresSolve c = ConstraintSolvesVia_Rule
| otherwise = ConstraintSolvesVia_Residual
- Tracing options , specific for CHR solvers
data CHRTrOpt
deriving (Eq, Ord, Show)
class CHREmptySubstitution subst where
chrEmptySubst :: subst
type family CHRMatchableKey subst :: *
type instance CHRMatchableKey (StackedVarLookup subst) = CHRMatchableKey subst
class (CHREmptySubstitution subst, LookupApply subst subst, VarExtractable x, VarLookupKey subst ~ ExtrValVarKey x) => CHRMatchable env x subst where
| One - directional ( 1st to 2nd ' x ' ) unify
chrMatchTo :: env -> subst -> x -> x -> Maybe subst
chrMatchTo env s x1 x2 = chrUnify CHRMatchHow_Match (emptyCHRMatchEnv {chrmatchenvMetaMayBind = (`Set.member` varFreeSet x1)}) env s x1 x2
| One - directional ( 1st to 2nd ' x ' ) unify
chrUnify :: CHRMatchHow -> CHRMatchEnv (VarLookupKey subst) -> env -> subst -> x -> x -> Maybe subst
chrUnify how menv e s x1 x2 = chrmatcherUnlift (chrUnifyM how e x1 x2) menv s
| Match one - directional ( from 1st to 2nd arg ) , under a subst , yielding a subst for the metavars in the 1st arg , waiting for those in the 2nd
chrMatchToM :: env -> x -> x -> CHRMatcher subst ()
chrMatchToM e x1 x2 = chrUnifyM CHRMatchHow_Match e x1 x2
| Unify bi - directional or match one - directional ( from 1st to 2nd arg ) , under a subst , yielding a subst for the metavars in the 1st arg , waiting for those in the 2nd
chrUnifyM :: CHRMatchHow -> env -> x -> x -> CHRMatcher subst ()
chrUnifyM how e x1 x2 = getl chrmatcherstateEnv >>= \menv -> chrmatcherLift $ \sg -> chrUnify how menv e sg x1 x2
chrBuiltinSolveM :: env -> x -> CHRMatcher subst ()
chrmatcherLift $ \sg - > chrBuiltinSolve e sg x
chrUnifyM how e (Just x1) (Just x2) = chrUnifyM how e x1 x2
chrUnifyM how e Nothing Nothing = chrMatchSuccess
chrUnifyM how e _ _ = chrMatchFail
chrUnifyM how e x1 x2 | length x1 == length x2 = sequence_ $ zipWith (chrUnifyM how e) x1 x2
chrUnifyM how e _ _ = chrMatchFail
| Unlift / observe ( or run ) a CHRMatcher
chrmatcherUnlift :: (CHREmptySubstitution subst) => CHRMatcher subst () -> CHRMatchEnv (VarLookupKey subst) -> (subst -> Maybe subst)
chrmatcherUnlift mtch menv s = do
(s,w) <- chrmatcherRun mtch menv s
if Set.null w then Just s else Nothing
chrmatcherLift :: (LookupApply subst subst) => (subst -> Maybe subst) -> CHRMatcher subst ()
chrmatcherLift f = do
gets ( . _ chrmatcherstateVarLookup )
case Lk.unlifts stLk of
[sl,sg] -> maybe chrMatchFail (\snew -> chrmatcherstateVarLookup =$: (Lk.apply snew)) $ f sg
_ -> chrMatchFail
chrmatcherRun' :: (CHREmptySubstitution subst) => (CHRMatcherFailure -> r) -> (subst -> CHRWaitForVarSet subst -> x -> r) -> CHRMatcher subst x -> CHRMatchEnv (VarLookupKey subst) -> StackedVarLookup subst -> r
chrmatcherRun' fail succes mtch menv s = either
fail
((\(x,ms) -> let (s, w, _) = unCHRMatcherState ms in succes (Lk.top s) w x))
$ flip runStateT (mkCHRMatcherState s Set.empty menv)
$ mtch
chrmatcherRun :: (CHREmptySubstitution subst) => CHRMatcher subst () -> CHRMatchEnv (VarLookupKey subst) -> subst -> Maybe (subst, CHRWaitForVarSet subst)
( [ chrEmptySubst , s ] )
- CHRMatcher API , part II
chrMatchSubst :: CHRMatcher subst (StackedVarLookup subst)
chrMatchSubst = getl chrmatcherstateVarLookup
# INLINE chrMatchSubst #
chrMatchBind :: forall subst k v . (LookupApply subst subst, Lookup subst k v, k ~ VarLookupKey subst, v ~ VarLookupVal subst) => k -> v -> CHRMatcher subst ()
chrMatchBind k v = chrmatcherstateVarLookup =$: ((Lk.singleton k v :: subst) `Lk.apply`)
# INLINE chrMatchBind #
chrMatchWait :: (Ord k, k ~ VarLookupKey subst) => k -> CHRMatcher subst ()
chrMatchWait k = chrMatchModifyWait (Set.insert k)
# INLINE chrMatchWait #
chrMatchSuccess :: CHRMatcher subst ()
chrMatchSuccess = return ()
# INLINE chrMatchSuccess #
chrMatchFail :: CHRMatcher subst a
chrMatchFail = throwError CHRMatcherFailure
# INLINE chrMatchFail #
chrMatchFailNoBinding :: CHRMatcher subst a
chrMatchFailNoBinding = throwError CHRMatcherFailure_NoBinding
chrMatchSucces :: CHRMatcher subst ()
chrMatchSucces = return ()
# INLINE chrMatchSucces #
chrMatchModifyWait :: (CHRWaitForVarSet subst -> CHRWaitForVarSet subst) -> CHRMatcher subst ()
chrMatchModifyWait f =
modify ( \st - > st { _ chrmatcherstateWaitForVarSet = f $ _ chrmatcherstateWaitForVarSet st } )
( chrmatcherstateWaitForVarSet = $ :)
modify (\(s,w,e) -> (s,f w,e))
# INLINE chrMatchModifyWait #
| Match one - directional ( from 1st to 2nd arg ) , under a subst , yielding a subst for the metavars in the 1st arg , waiting for those in the 2nd
chrMatchAndWaitToM :: CHRMatchable env x subst => Bool -> env -> x -> x -> CHRMatcher subst ()
chrMatchAndWaitToM wait env x1 x2 = chrUnifyM (if wait then CHRMatchHow_MatchAndWait else CHRMatchHow_Match) env x1 x2
varFreeSet _ = Set.empty
chrUnifyM _ _ _ _ = chrMatchSuccess
instance Show Prio where
show = show . unPrio
instance PP Prio where
pp = pp . unPrio
type instance CHRPrioEvaluatableVal () = Prio
|
d246c0f6a295e0e36256b2dbf493c2f4f3806de74699fdb1b7471c09282c2410
|
BranchTaken/Hemlock
|
test_conversion.ml
|
open! Basis.Rudiments
open! Basis
open I32
let test () =
let rec fn = function
| [] -> ()
| x :: xs' -> begin
let i = x in
let t = trunc_of_sint i in
let i' = extend_to_sint t in
let t' = trunc_of_sint i' in
File.Fmt.stdout
|> Fmt.fmt "trunc_of_sint "
|> Sint.fmt ~alt:true ~zpad:true ~width:16L ~radix:Radix.Hex ~pretty:true i
|> Fmt.fmt " -> extend_to_sint "
|> fmt ~alt:true ~zpad:true ~width:8L ~radix:Radix.Hex ~pretty:true t
|> Fmt.fmt " -> trunc_of_sint "
|> Sint.pp i'
|> Fmt.fmt " -> "
|> fmt ~alt:true ~zpad:true ~width:8L ~radix:Radix.Hex ~pretty:true t'
|> Fmt.fmt "\n"
|> ignore;
let t = trunc_of_uns (Uns.bits_of_sint i) in
let u = extend_to_uns t in
let t' = trunc_of_uns u in
File.Fmt.stdout
|> Fmt.fmt "trunc_of_uns "
|> Sint.fmt ~alt:true ~zpad:true ~width:16L ~radix:Radix.Hex ~pretty:true i
|> Fmt.fmt " -> extend_to_uns "
|> fmt ~alt:true ~zpad:true ~width:8L ~radix:Radix.Hex ~pretty:true t
|> Fmt.fmt " -> trunc_of_uns "
|> Uns.fmt ~alt:true ~zpad:true ~width:16L ~radix:Radix.Hex u
|> Fmt.fmt " -> "
|> fmt ~alt:true ~zpad:true ~width:8L ~radix:Radix.Hex ~pretty:true t'
|> Fmt.fmt "\n"
|> ignore;
fn xs'
end
in
fn [Uns.max_value; (-2L); (-1L); 0L; 1L; 2L; Uns.bits_of_sint Sint.max_value]
let _ = test ()
| null |
https://raw.githubusercontent.com/BranchTaken/Hemlock/a07e362d66319108c1478a4cbebab765c1808b1a/bootstrap/test/basis/i32/test_conversion.ml
|
ocaml
|
open! Basis.Rudiments
open! Basis
open I32
let test () =
let rec fn = function
| [] -> ()
| x :: xs' -> begin
let i = x in
let t = trunc_of_sint i in
let i' = extend_to_sint t in
let t' = trunc_of_sint i' in
File.Fmt.stdout
|> Fmt.fmt "trunc_of_sint "
|> Sint.fmt ~alt:true ~zpad:true ~width:16L ~radix:Radix.Hex ~pretty:true i
|> Fmt.fmt " -> extend_to_sint "
|> fmt ~alt:true ~zpad:true ~width:8L ~radix:Radix.Hex ~pretty:true t
|> Fmt.fmt " -> trunc_of_sint "
|> Sint.pp i'
|> Fmt.fmt " -> "
|> fmt ~alt:true ~zpad:true ~width:8L ~radix:Radix.Hex ~pretty:true t'
|> Fmt.fmt "\n"
|> ignore;
let t = trunc_of_uns (Uns.bits_of_sint i) in
let u = extend_to_uns t in
let t' = trunc_of_uns u in
File.Fmt.stdout
|> Fmt.fmt "trunc_of_uns "
|> Sint.fmt ~alt:true ~zpad:true ~width:16L ~radix:Radix.Hex ~pretty:true i
|> Fmt.fmt " -> extend_to_uns "
|> fmt ~alt:true ~zpad:true ~width:8L ~radix:Radix.Hex ~pretty:true t
|> Fmt.fmt " -> trunc_of_uns "
|> Uns.fmt ~alt:true ~zpad:true ~width:16L ~radix:Radix.Hex u
|> Fmt.fmt " -> "
|> fmt ~alt:true ~zpad:true ~width:8L ~radix:Radix.Hex ~pretty:true t'
|> Fmt.fmt "\n"
|> ignore;
fn xs'
end
in
fn [Uns.max_value; (-2L); (-1L); 0L; 1L; 2L; Uns.bits_of_sint Sint.max_value]
let _ = test ()
|
|
76fe8b4a818b37a06c771dfde94a35677198688c4cb66c7cb4be4347aeb79efe
|
opencog/pln
|
simple-implication.scm
|
;; Define simple implications to test implication instantiation rules
(ImplicationScopeLink (stv 1 1)
(TypedVariableLink
(VariableNode "$X")
(TypeNode "ConceptNode"))
(EvaluationLink (stv 0.2 0.9)
(PredicateNode "P")
(VariableNode "$X"))
(EvaluationLink
(PredicateNode "Q")
(VariableNode "$X")))
(EvaluationLink (stv 1 1)
(PredicateNode "P")
(ConceptNode "A"))
(ImplicationScopeLink (stv 1 1)
(VariableList
(TypedVariableLink
(VariableNode "$X")
(TypeNode "ConceptNode"))
(TypedVariableLink
(VariableNode "$Y")
(TypeNode "ConceptNode")))
(EvaluationLink (stv 0.04 0.6)
(PredicateNode "P")
(ListLink
(VariableNode "$X")
(VariableNode "$Y")))
(EvaluationLink
(PredicateNode "Q")
(ListLink
(VariableNode "$Y")
(VariableNode "$X"))))
(EvaluationLink (stv 1 1)
(PredicateNode "P")
(ListLink
(ConceptNode "A")
(ConceptNode "B")))
;; This one is to test the implication instantiation rule when the
;; precondition cannot be satisfied
(ImplicationScopeLink (stv 1 1)
(TypedVariableLink
(VariableNode "$X")
(TypeNode "ConceptNode"))
(EvaluationLink
(PredicateNode "dummy-implicant")
(VariableNode "$X"))
(EvaluationLink
(PredicateNode "dummy-implicand")
(VariableNode "$X")))
;; This one is to test implicant distribution
(ImplicationLink (stv 1 1)
(PredicateNode "P")
(PredicateNode "Q"))
| null |
https://raw.githubusercontent.com/opencog/pln/52dc099e21393892cf5529fef687a69682436b2d/tests/pln/rules/simple-implication.scm
|
scheme
|
Define simple implications to test implication instantiation rules
This one is to test the implication instantiation rule when the
precondition cannot be satisfied
This one is to test implicant distribution
|
(ImplicationScopeLink (stv 1 1)
(TypedVariableLink
(VariableNode "$X")
(TypeNode "ConceptNode"))
(EvaluationLink (stv 0.2 0.9)
(PredicateNode "P")
(VariableNode "$X"))
(EvaluationLink
(PredicateNode "Q")
(VariableNode "$X")))
(EvaluationLink (stv 1 1)
(PredicateNode "P")
(ConceptNode "A"))
(ImplicationScopeLink (stv 1 1)
(VariableList
(TypedVariableLink
(VariableNode "$X")
(TypeNode "ConceptNode"))
(TypedVariableLink
(VariableNode "$Y")
(TypeNode "ConceptNode")))
(EvaluationLink (stv 0.04 0.6)
(PredicateNode "P")
(ListLink
(VariableNode "$X")
(VariableNode "$Y")))
(EvaluationLink
(PredicateNode "Q")
(ListLink
(VariableNode "$Y")
(VariableNode "$X"))))
(EvaluationLink (stv 1 1)
(PredicateNode "P")
(ListLink
(ConceptNode "A")
(ConceptNode "B")))
(ImplicationScopeLink (stv 1 1)
(TypedVariableLink
(VariableNode "$X")
(TypeNode "ConceptNode"))
(EvaluationLink
(PredicateNode "dummy-implicant")
(VariableNode "$X"))
(EvaluationLink
(PredicateNode "dummy-implicand")
(VariableNode "$X")))
(ImplicationLink (stv 1 1)
(PredicateNode "P")
(PredicateNode "Q"))
|
800c6679a57e1fb84f5d406aa7fd503d4704fb87d7f16a5bc74ef64c69aa4839
|
fujita-y/ypsilon
|
takl.scm
|
TAKL -- The TAKeuchi function using lists as counters .
(define (listn n)
(if (= n 0)
'()
(cons n (listn (- n 1)))))
(define l18 (listn 18))
(define l12 (listn 12))
(define l6 (listn 6))
(define (mas x y z)
(if (not (shorterp y x))
z
(mas (mas (cdr x) y z)
(mas (cdr y) z x)
(mas (cdr z) x y))))
(define (shorterp x y)
(and (not (null? y))
(or (null? x)
(shorterp (cdr x)
(cdr y)))))
(define (main . args)
(run-benchmark
"takl"
takl-iters
(lambda (result) (equal? result '(7 6 5 4 3 2 1)))
(lambda (x y z) (lambda () (mas x y z)))
l18
l12
l6))
| null |
https://raw.githubusercontent.com/fujita-y/ypsilon/50f1fdc499d1cbd77879ab376d4a394adf347b76/bench/gambit-benchmarks/takl.scm
|
scheme
|
TAKL -- The TAKeuchi function using lists as counters .
(define (listn n)
(if (= n 0)
'()
(cons n (listn (- n 1)))))
(define l18 (listn 18))
(define l12 (listn 12))
(define l6 (listn 6))
(define (mas x y z)
(if (not (shorterp y x))
z
(mas (mas (cdr x) y z)
(mas (cdr y) z x)
(mas (cdr z) x y))))
(define (shorterp x y)
(and (not (null? y))
(or (null? x)
(shorterp (cdr x)
(cdr y)))))
(define (main . args)
(run-benchmark
"takl"
takl-iters
(lambda (result) (equal? result '(7 6 5 4 3 2 1)))
(lambda (x y z) (lambda () (mas x y z)))
l18
l12
l6))
|
|
82023e221119946bf39067fdba062fb6f47f062f9997cc18c8849ea588257b67
|
igorhvr/bedlam
|
scamacr.scm
|
;;; "scamacr.scm" syntax-case macros for Scheme constructs
Copyright ( C ) 1992
;;;
;;; Permission to copy this software, in whole or in part, to use this
;;; software for any lawful purpose, and to redistribute this software
;;; is granted subject to the restriction that all copies made of this
;;; software must include this copyright notice in full. This software
is provided AS IS , with NO WARRANTY , EITHER EXPRESS OR IMPLIED ,
;;; INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY
;;; OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE
;;; AUTHORS BE LIABLE FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES OF ANY
NATURE WHATSOEVER .
Written by
;;; This file was munged by a simple minded sed script since it left
;;; its original authors' hands. See syncase.sh for the horrid details.
;;; macro-defs.ss
92/06/18
(define-syntax with-syntax
(lambda (x)
(syntax-case x ()
((_ () e1 e2 ...)
(syntax (begin e1 e2 ...)))
((_ ((out in)) e1 e2 ...)
(syntax (syntax-case in () (out (begin e1 e2 ...)))))
((_ ((out in) ...) e1 e2 ...)
(syntax (syntax-case (list in ...) ()
((out ...) (begin e1 e2 ...))))))))
(define-syntax syntax-rules
(lambda (x)
(syntax-case x ()
((_ (k ...) ((keyword . pattern) template) ...)
(with-syntax (((dummy ...)
(generate-temporaries (syntax (keyword ...)))))
(syntax (lambda (x)
(syntax-case x (k ...)
((dummy . pattern) (syntax template))
...))))))))
(define-syntax or
(lambda (x)
(syntax-case x ()
((_) (syntax #f))
((_ e) (syntax e))
((_ e1 e2 e3 ...)
(syntax (let ((t e1)) (if t t (or e2 e3 ...))))))))
(define-syntax and
(lambda (x)
(syntax-case x ()
((_ e1 e2 e3 ...) (syntax (if e1 (and e2 e3 ...) #f)))
((_ e) (syntax e))
((_) (syntax #t)))))
(define-syntax cond
(lambda (x)
(syntax-case x (else =>)
((_ (else e1 e2 ...))
(syntax (begin e1 e2 ...)))
((_ (e0))
(syntax (let ((t e0)) (if t t))))
((_ (e0) c1 c2 ...)
(syntax (let ((t e0)) (if t t (cond c1 c2 ...)))))
((_ (e0 => e1)) (syntax (let ((t e0)) (if t (e1 t)))))
((_ (e0 => e1) c1 c2 ...)
(syntax (let ((t e0)) (if t (e1 t) (cond c1 c2 ...)))))
((_ (e0 e1 e2 ...)) (syntax (if e0 (begin e1 e2 ...))))
((_ (e0 e1 e2 ...) c1 c2 ...)
(syntax (if e0 (begin e1 e2 ...) (cond c1 c2 ...)))))))
(define-syntax let*
(lambda (x)
(syntax-case x ()
((let* () e1 e2 ...)
(syntax (let () e1 e2 ...)))
((let* ((x1 v1) (x2 v2) ...) e1 e2 ...)
(syncase:andmap identifier? (syntax (x1 x2 ...)))
(syntax (let ((x1 v1)) (let* ((x2 v2) ...) e1 e2 ...)))))))
(define-syntax case
(lambda (x)
(syntax-case x (else)
((_ v (else e1 e2 ...))
(syntax (begin v e1 e2 ...)))
((_ v ((k ...) e1 e2 ...))
(syntax (if (memv v '(k ...)) (begin e1 e2 ...))))
((_ v ((k ...) e1 e2 ...) c1 c2 ...)
(syntax (let ((x v))
(if (memv x '(k ...))
(begin e1 e2 ...)
(case x c1 c2 ...))))))))
(define-syntax do
(lambda (orig-x)
(syntax-case orig-x ()
((_ ((var init . step) ...) (e0 e1 ...) c ...)
(with-syntax (((step ...)
(map (lambda (v s)
(syntax-case s ()
(() v)
((e) (syntax e))
(_ (syntax-error orig-x))))
(syntax (var ...))
(syntax (step ...)))))
(syntax-case (syntax (e1 ...)) ()
(() (syntax (let doloop ((var init) ...)
(if (not e0)
(begin c ... (doloop step ...))))))
((e1 e2 ...)
(syntax (let doloop ((var init) ...)
(if e0
(begin e1 e2 ...)
(begin c ... (doloop step ...))))))))))))
(define-syntax quasiquote
(letrec
((gen-cons
(lambda (x y)
(syntax-case x (quote)
((quote x)
(syntax-case y (quote list)
((quote y) (syntax (quote (x . y))))
((list y ...) (syntax (list (quote x) y ...)))
(y (syntax (cons (quote x) y)))))
(x (syntax-case y (quote list)
((quote ()) (syntax (list x)))
((list y ...) (syntax (list x y ...)))
(y (syntax (cons x y))))))))
(gen-append
(lambda (x y)
(syntax-case x (quote list cons)
((quote (x1 x2 ...))
(syntax-case y (quote)
((quote y) (syntax (quote (x1 x2 ... . y))))
(y (syntax (append (quote (x1 x2 ...) y))))))
((quote ()) y)
((list x1 x2 ...)
(gen-cons (syntax x1) (gen-append (syntax (list x2 ...)) y)))
(x (syntax-case y (quote list)
((quote ()) (syntax x))
(y (syntax (append x y))))))))
(gen-vector
(lambda (x)
(syntax-case x (quote list)
((quote (x ...)) (syntax (quote #(x ...))))
((list x ...) (syntax (vector x ...)))
(x (syntax (list->vector x))))))
(gen
(lambda (p lev)
(syntax-case p (unquote unquote-splicing quasiquote)
((unquote p)
(if (= lev 0)
(syntax p)
(gen-cons (syntax (quote unquote))
(gen (syntax (p)) (- lev 1)))))
(((unquote-splicing p) . q)
(if (= lev 0)
(gen-append (syntax p) (gen (syntax q) lev))
(gen-cons (gen-cons (syntax (quote unquote-splicing))
(gen (syntax p) (- lev 1)))
(gen (syntax q) lev))))
((quasiquote p)
(gen-cons (syntax (quote quasiquote))
(gen (syntax (p)) (+ lev 1))))
((p . q)
(gen-cons (gen (syntax p) lev) (gen (syntax q) lev)))
(#(x ...) (gen-vector (gen (syntax (x ...)) lev)))
(p (syntax (quote p)))))))
(lambda (x)
(syntax-case x ()
((- e) (gen (syntax e) 0))))))
| null |
https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/iasylum/slib/3b2/scamacr.scm
|
scheme
|
"scamacr.scm" syntax-case macros for Scheme constructs
Permission to copy this software, in whole or in part, to use this
software for any lawful purpose, and to redistribute this software
is granted subject to the restriction that all copies made of this
software must include this copyright notice in full. This software
INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY
OR FITNESS FOR ANY PARTICULAR PURPOSE. IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES OF ANY
This file was munged by a simple minded sed script since it left
its original authors' hands. See syncase.sh for the horrid details.
macro-defs.ss
|
Copyright ( C ) 1992
is provided AS IS , with NO WARRANTY , EITHER EXPRESS OR IMPLIED ,
NATURE WHATSOEVER .
Written by
92/06/18
(define-syntax with-syntax
(lambda (x)
(syntax-case x ()
((_ () e1 e2 ...)
(syntax (begin e1 e2 ...)))
((_ ((out in)) e1 e2 ...)
(syntax (syntax-case in () (out (begin e1 e2 ...)))))
((_ ((out in) ...) e1 e2 ...)
(syntax (syntax-case (list in ...) ()
((out ...) (begin e1 e2 ...))))))))
(define-syntax syntax-rules
(lambda (x)
(syntax-case x ()
((_ (k ...) ((keyword . pattern) template) ...)
(with-syntax (((dummy ...)
(generate-temporaries (syntax (keyword ...)))))
(syntax (lambda (x)
(syntax-case x (k ...)
((dummy . pattern) (syntax template))
...))))))))
(define-syntax or
(lambda (x)
(syntax-case x ()
((_) (syntax #f))
((_ e) (syntax e))
((_ e1 e2 e3 ...)
(syntax (let ((t e1)) (if t t (or e2 e3 ...))))))))
(define-syntax and
(lambda (x)
(syntax-case x ()
((_ e1 e2 e3 ...) (syntax (if e1 (and e2 e3 ...) #f)))
((_ e) (syntax e))
((_) (syntax #t)))))
(define-syntax cond
(lambda (x)
(syntax-case x (else =>)
((_ (else e1 e2 ...))
(syntax (begin e1 e2 ...)))
((_ (e0))
(syntax (let ((t e0)) (if t t))))
((_ (e0) c1 c2 ...)
(syntax (let ((t e0)) (if t t (cond c1 c2 ...)))))
((_ (e0 => e1)) (syntax (let ((t e0)) (if t (e1 t)))))
((_ (e0 => e1) c1 c2 ...)
(syntax (let ((t e0)) (if t (e1 t) (cond c1 c2 ...)))))
((_ (e0 e1 e2 ...)) (syntax (if e0 (begin e1 e2 ...))))
((_ (e0 e1 e2 ...) c1 c2 ...)
(syntax (if e0 (begin e1 e2 ...) (cond c1 c2 ...)))))))
(define-syntax let*
(lambda (x)
(syntax-case x ()
((let* () e1 e2 ...)
(syntax (let () e1 e2 ...)))
((let* ((x1 v1) (x2 v2) ...) e1 e2 ...)
(syncase:andmap identifier? (syntax (x1 x2 ...)))
(syntax (let ((x1 v1)) (let* ((x2 v2) ...) e1 e2 ...)))))))
(define-syntax case
(lambda (x)
(syntax-case x (else)
((_ v (else e1 e2 ...))
(syntax (begin v e1 e2 ...)))
((_ v ((k ...) e1 e2 ...))
(syntax (if (memv v '(k ...)) (begin e1 e2 ...))))
((_ v ((k ...) e1 e2 ...) c1 c2 ...)
(syntax (let ((x v))
(if (memv x '(k ...))
(begin e1 e2 ...)
(case x c1 c2 ...))))))))
(define-syntax do
(lambda (orig-x)
(syntax-case orig-x ()
((_ ((var init . step) ...) (e0 e1 ...) c ...)
(with-syntax (((step ...)
(map (lambda (v s)
(syntax-case s ()
(() v)
((e) (syntax e))
(_ (syntax-error orig-x))))
(syntax (var ...))
(syntax (step ...)))))
(syntax-case (syntax (e1 ...)) ()
(() (syntax (let doloop ((var init) ...)
(if (not e0)
(begin c ... (doloop step ...))))))
((e1 e2 ...)
(syntax (let doloop ((var init) ...)
(if e0
(begin e1 e2 ...)
(begin c ... (doloop step ...))))))))))))
(define-syntax quasiquote
(letrec
((gen-cons
(lambda (x y)
(syntax-case x (quote)
((quote x)
(syntax-case y (quote list)
((quote y) (syntax (quote (x . y))))
((list y ...) (syntax (list (quote x) y ...)))
(y (syntax (cons (quote x) y)))))
(x (syntax-case y (quote list)
((quote ()) (syntax (list x)))
((list y ...) (syntax (list x y ...)))
(y (syntax (cons x y))))))))
(gen-append
(lambda (x y)
(syntax-case x (quote list cons)
((quote (x1 x2 ...))
(syntax-case y (quote)
((quote y) (syntax (quote (x1 x2 ... . y))))
(y (syntax (append (quote (x1 x2 ...) y))))))
((quote ()) y)
((list x1 x2 ...)
(gen-cons (syntax x1) (gen-append (syntax (list x2 ...)) y)))
(x (syntax-case y (quote list)
((quote ()) (syntax x))
(y (syntax (append x y))))))))
(gen-vector
(lambda (x)
(syntax-case x (quote list)
((quote (x ...)) (syntax (quote #(x ...))))
((list x ...) (syntax (vector x ...)))
(x (syntax (list->vector x))))))
(gen
(lambda (p lev)
(syntax-case p (unquote unquote-splicing quasiquote)
((unquote p)
(if (= lev 0)
(syntax p)
(gen-cons (syntax (quote unquote))
(gen (syntax (p)) (- lev 1)))))
(((unquote-splicing p) . q)
(if (= lev 0)
(gen-append (syntax p) (gen (syntax q) lev))
(gen-cons (gen-cons (syntax (quote unquote-splicing))
(gen (syntax p) (- lev 1)))
(gen (syntax q) lev))))
((quasiquote p)
(gen-cons (syntax (quote quasiquote))
(gen (syntax (p)) (+ lev 1))))
((p . q)
(gen-cons (gen (syntax p) lev) (gen (syntax q) lev)))
(#(x ...) (gen-vector (gen (syntax (x ...)) lev)))
(p (syntax (quote p)))))))
(lambda (x)
(syntax-case x ()
((- e) (gen (syntax e) 0))))))
|
3522b7fc0dbe1b457f2d1953c95f6908aa7a7fdbeb1f53efd9c3489e8083ec1c
|
basvandijk/threads
|
Thread.hs
|
# LANGUAGE CPP , NoImplicitPrelude , RankNTypes , ImpredicativeTypes #
#if __GLASGOW_HASKELL__ >= 701
# LANGUAGE Trustworthy #
#endif
--------------------------------------------------------------------------------
-- |
-- Module : Control.Concurrent.Thread
Copyright : ( c ) 2010 - 2012
-- License : BSD3 (see the file LICENSE)
Maintainer : < >
, < >
--
-- Standard threads extended with the ability to /wait/ for their return value.
--
This module exports equivalently named functions from @Control . Concurrent@
( and @GHC.Conc@ ) . Avoid ambiguities by importing this module qualified . May
-- we suggest:
--
-- @
-- import qualified Control.Concurrent.Thread as Thread ( ... )
-- @
--
-- The following is an example how to use this module:
--
-- @
--
import qualified Control . Concurrent . Thread as ( ' forkIO ' , ' result ' )
--
main = do ( tid , wait ) < - Thread . ' $ do x < - someExpensiveComputation
-- return x
-- doSomethingElse
x < - Thread . ' = < < ' wait '
-- doSomethingWithResult x
-- @
--
--------------------------------------------------------------------------------
module Control.Concurrent.Thread
( -- * Forking threads
forkIO
, forkOS
, forkOn
, forkIOWithUnmask
, forkOnWithUnmask
-- * Results
, Result
, result
) where
--------------------------------------------------------------------------------
-- Imports
--------------------------------------------------------------------------------
-- from base:
import qualified Control.Concurrent ( forkOS
, forkIOWithUnmask
, forkOnWithUnmask
)
import Control.Concurrent ( ThreadId )
import Control.Concurrent.MVar ( newEmptyMVar, putMVar, readMVar )
import Control.Exception ( SomeException, try, throwIO, mask )
import Control.Monad ( return, (>>=) )
import Data.Either ( Either(..), either )
import Data.Function ( (.), ($) )
import Data.Int ( Int )
import System.IO ( IO )
-- from threads:
import Control.Concurrent.Raw ( rawForkIO, rawForkOn )
--------------------------------------------------------------------------------
-- * Forking threads
--------------------------------------------------------------------------------
| Like @Control . Concurrent . 'Control . Concurrent.forkIO'@ but returns
-- a computation that when executed blocks until the thread terminates
-- then returns the final value of the thread.
forkIO :: IO a -> IO (ThreadId, IO (Result a))
forkIO = fork rawForkIO
| Like @Control . Concurrent . 'Control . Concurrent.forkOS'@ but returns
-- a computation that when executed blocks until the thread terminates
-- then returns the final value of the thread.
forkOS :: IO a -> IO (ThreadId, IO (Result a))
forkOS = fork Control.Concurrent.forkOS
| Like @Control . Concurrent . 'Control . Concurrent.forkOn'@ but returns
-- a computation that when executed blocks until the thread terminates
-- then returns the final value of the thread.
forkOn :: Int -> IO a -> IO (ThreadId, IO (Result a))
forkOn = fork . rawForkOn
| Like @Control . Concurrent . 'Control . Concurrent.forkIOWithUnmask'@ but returns
-- a computation that when executed blocks until the thread terminates
-- then returns the final value of the thread.
forkIOWithUnmask
:: ((forall b. IO b -> IO b) -> IO a) -> IO (ThreadId, IO (Result a))
forkIOWithUnmask = forkWithUnmask Control.Concurrent.forkIOWithUnmask
| Like @Control . Concurrent . 'Control . Concurrent.forkOnWithUnmask'@ but returns
-- a computation that when executed blocks until the thread terminates
-- then returns the final value of the thread.
forkOnWithUnmask
:: Int -> ((forall b. IO b -> IO b) -> IO a) -> IO (ThreadId, IO (Result a))
forkOnWithUnmask = forkWithUnmask . Control.Concurrent.forkOnWithUnmask
--------------------------------------------------------------------------------
Utils
--------------------------------------------------------------------------------
fork :: (IO () -> IO ThreadId) -> (IO a -> IO (ThreadId, IO (Result a)))
fork doFork = \a -> do
res <- newEmptyMVar
tid <- mask $ \restore -> doFork $ try (restore a) >>= putMVar res
return (tid, readMVar res)
forkWithUnmask
:: (((forall b. IO b -> IO b) -> IO ()) -> IO ThreadId)
-> ((forall b. IO b -> IO b) -> IO a) -> IO (ThreadId, IO (Result a))
forkWithUnmask doForkWithUnmask = \f -> do
res <- newEmptyMVar
tid <- mask $ \restore ->
doForkWithUnmask $ \unmask ->
try (restore $ f unmask) >>= putMVar res
return (tid, readMVar res)
--------------------------------------------------------------------------------
-- Results
--------------------------------------------------------------------------------
-- | A result of a thread is either some exception that was thrown in the thread
-- and wasn't catched or the actual value that was returned by the thread.
type Result a = Either SomeException a
-- | Retrieve the actual value from the result.
--
When the result is ' SomeException ' the exception is thrown .
result :: Result a -> IO a
result = either throwIO return
| null |
https://raw.githubusercontent.com/basvandijk/threads/b51a750a11fe568f5388993d53449ee9b9049e2c/Control/Concurrent/Thread.hs
|
haskell
|
------------------------------------------------------------------------------
|
Module : Control.Concurrent.Thread
License : BSD3 (see the file LICENSE)
Standard threads extended with the ability to /wait/ for their return value.
we suggest:
@
import qualified Control.Concurrent.Thread as Thread ( ... )
@
The following is an example how to use this module:
@
return x
doSomethingElse
doSomethingWithResult x
@
------------------------------------------------------------------------------
* Forking threads
* Results
------------------------------------------------------------------------------
Imports
------------------------------------------------------------------------------
from base:
from threads:
------------------------------------------------------------------------------
* Forking threads
------------------------------------------------------------------------------
a computation that when executed blocks until the thread terminates
then returns the final value of the thread.
a computation that when executed blocks until the thread terminates
then returns the final value of the thread.
a computation that when executed blocks until the thread terminates
then returns the final value of the thread.
a computation that when executed blocks until the thread terminates
then returns the final value of the thread.
a computation that when executed blocks until the thread terminates
then returns the final value of the thread.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Results
------------------------------------------------------------------------------
| A result of a thread is either some exception that was thrown in the thread
and wasn't catched or the actual value that was returned by the thread.
| Retrieve the actual value from the result.
|
# LANGUAGE CPP , NoImplicitPrelude , RankNTypes , ImpredicativeTypes #
#if __GLASGOW_HASKELL__ >= 701
# LANGUAGE Trustworthy #
#endif
Copyright : ( c ) 2010 - 2012
Maintainer : < >
, < >
This module exports equivalently named functions from @Control . Concurrent@
( and @GHC.Conc@ ) . Avoid ambiguities by importing this module qualified . May
import qualified Control . Concurrent . Thread as ( ' forkIO ' , ' result ' )
main = do ( tid , wait ) < - Thread . ' $ do x < - someExpensiveComputation
x < - Thread . ' = < < ' wait '
module Control.Concurrent.Thread
forkIO
, forkOS
, forkOn
, forkIOWithUnmask
, forkOnWithUnmask
, Result
, result
) where
import qualified Control.Concurrent ( forkOS
, forkIOWithUnmask
, forkOnWithUnmask
)
import Control.Concurrent ( ThreadId )
import Control.Concurrent.MVar ( newEmptyMVar, putMVar, readMVar )
import Control.Exception ( SomeException, try, throwIO, mask )
import Control.Monad ( return, (>>=) )
import Data.Either ( Either(..), either )
import Data.Function ( (.), ($) )
import Data.Int ( Int )
import System.IO ( IO )
import Control.Concurrent.Raw ( rawForkIO, rawForkOn )
| Like @Control . Concurrent . 'Control . Concurrent.forkIO'@ but returns
forkIO :: IO a -> IO (ThreadId, IO (Result a))
forkIO = fork rawForkIO
| Like @Control . Concurrent . 'Control . Concurrent.forkOS'@ but returns
forkOS :: IO a -> IO (ThreadId, IO (Result a))
forkOS = fork Control.Concurrent.forkOS
| Like @Control . Concurrent . 'Control . Concurrent.forkOn'@ but returns
forkOn :: Int -> IO a -> IO (ThreadId, IO (Result a))
forkOn = fork . rawForkOn
| Like @Control . Concurrent . 'Control . Concurrent.forkIOWithUnmask'@ but returns
forkIOWithUnmask
:: ((forall b. IO b -> IO b) -> IO a) -> IO (ThreadId, IO (Result a))
forkIOWithUnmask = forkWithUnmask Control.Concurrent.forkIOWithUnmask
| Like @Control . Concurrent . 'Control . Concurrent.forkOnWithUnmask'@ but returns
forkOnWithUnmask
:: Int -> ((forall b. IO b -> IO b) -> IO a) -> IO (ThreadId, IO (Result a))
forkOnWithUnmask = forkWithUnmask . Control.Concurrent.forkOnWithUnmask
Utils
fork :: (IO () -> IO ThreadId) -> (IO a -> IO (ThreadId, IO (Result a)))
fork doFork = \a -> do
res <- newEmptyMVar
tid <- mask $ \restore -> doFork $ try (restore a) >>= putMVar res
return (tid, readMVar res)
forkWithUnmask
:: (((forall b. IO b -> IO b) -> IO ()) -> IO ThreadId)
-> ((forall b. IO b -> IO b) -> IO a) -> IO (ThreadId, IO (Result a))
forkWithUnmask doForkWithUnmask = \f -> do
res <- newEmptyMVar
tid <- mask $ \restore ->
doForkWithUnmask $ \unmask ->
try (restore $ f unmask) >>= putMVar res
return (tid, readMVar res)
type Result a = Either SomeException a
When the result is ' SomeException ' the exception is thrown .
result :: Result a -> IO a
result = either throwIO return
|
36aeaac643a2e009195c8895176c8479453d35cd18737908d874968bf6b74953
|
alekras/erl.mqtt.server
|
session.erl
|
%%
Copyright ( C ) 2015 - 2022 by ( )
%%
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.
%%
%% @hidden
@since 2016 - 09 - 29
2015 - 2022
@author < > [ / ]
%% @version {@version}
%% @doc This module implements a tesing of MQTT session.
-module(session).
%%
%% Include files
%%
%% -include_lib("eunit/include/eunit.hrl").
-include_lib("stdlib/include/assert.hrl").
-include_lib("mqtt_common/include/mqtt.hrl").
-include("test.hrl").
-export([
session_1/2,
session_2/2
]).
-import(testing, [wait_all/1]).
%%
%% API Functions
%%
%% Publisher: skip send publish. Resend publish after reconnect and restore session.
session_1({1, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=1, publisher skips send publish.", timeout, 100, fun() ->
% ?debug_Fmt("::test:: session_1 : ~p ~p", [_X, _Conns]),
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
% ?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(1, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 1, F}]),
% ?debug_Fmt("::test:: subscribe returns: ~p",[R1_0]),
?assertEqual({suback,[1],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"Test Payload QoS = 1. annon. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R2_0 ] ) ,
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_send_publish}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"Test Payload QoS = 1. annon. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R3_0 ] ) ,
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","puback timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
%% Publisher: skip recieve publish ack. Resend publish after reconnect and restore session. Duplicate message.
session_1({2, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=1, publisher skips recieve puback.", timeout, 100, fun() ->
% ?debug_Fmt("::test:: session_1 : ~p ~p", [_X, _Conns]),
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
% ?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(1, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 1, F}]),
% ?debug_Fmt("::test:: subscribe returns: ~p",[R1_0]),
?assertEqual({suback,[1],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::1 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R2_0 ] ) ,
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_rcv_puback}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::2 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R3_0 ] ) ,
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","puback timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
%% Subscriber: skip recieve publish. Resend publish after reconnect and restore session. Duplicate message.
session_1({3, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=1, subscriber skips receive publish", timeout, 100, fun() ->
% ?debug_Fmt("::test:: session_1 : ~p ~p", [_X, _Conns]),
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(1, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 1, F}]),
% ?debug_Fmt("::test:: subscribe returns: ~p",[R1_0]),
?assertEqual({suback,[1],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::1 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R2_0 ] ) ,
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_rcv_publish}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::2 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R3_0 ] ) ,
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
{F},
[?TEST_CONN_TYPE]
),
% ?debug_Fmt("::test:: Subscriber with saved session : ~p", [Subscriber_2]),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::3 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R3_1 ] ) ,
?assertEqual(ok, R3_1),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end};
%% Subscriber: skip send publish ack. Resend publish after reconnect and restore session. Duplicate message.
session_1({4, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=1, subscriber skips send puback.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
% ?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(1, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 1, F}]),
?assertEqual({suback,[1],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::1 Test Payload QoS = 1. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_send_puback}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::2 Test Payload QoS = 1. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
timer:sleep(500),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::3 Test Payload QoS = 1. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(4),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end}.
%% Publisher: skip send publish. Resend publish after reconnect and restore session.
session_2({1, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, publisher skips send publish.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKTest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKTest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_send_publish}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","pubcomp timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
Publisher : skip receive pubrec . Resend publish after reconnect and restore session .
session_2({2, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, publisher skips receive pubrec.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKTest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKTest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"1) Test Payload QoS = 2. annon. function callback.">>),
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_rcv_pubrec}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"2) Test Payload QoS = 2. annon. function callback.">>),
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","pubcomp timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
%% Publisher: skip send pubrel. Resend pubrel after reconnect and restore session.
session_2({3, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, publisher skips send pubrel.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
% ?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(2, Q),
?assertEqual("AKTest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKTest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"1) Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_send_pubrel}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"2) Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","pubcomp timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
%% Publisher: skip receive pubcomp. Resend publish after reconnect and restore session.
session_2({4, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, publisher skips receive pubcomp.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
% ?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(2, Q),
?assertEqual("AKTest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKTest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"1) Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_rcv_pubcomp}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"2) Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","pubcomp timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
%% Subscriber: skip receive publish. Resend publish after reconnect and restore session.
session_2({5, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, subscriber skips receive publish.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
% ?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(2, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::1 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_rcv_publish}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::2 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::3 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end};
Subscriber : skip send pubrec . Resend publish after reconnect and restore session .
session_2({6, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, subscriber skips send pubrec.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
% ?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(2, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::1 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_send_pubrec}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::2 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::3 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(4),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end};
%% Subscriber: skip receive pubrel. Resend publish after reconnect and restore session.
session_2({7, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, subscriber skips receive pubrel.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
% ?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(2, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::1 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_rcv_pubrel}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::2 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::3 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end};
%% Subscriber: skip send pubcomp. Resend publish after reconnect and restore session.
session_2({8, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, subscriber skips send pubcomp.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
% ?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(2, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::1 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_send_pubcomp}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::2 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
timer:sleep(500),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::3 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end}.
| null |
https://raw.githubusercontent.com/alekras/erl.mqtt.server/d05919cfc7bfdb7a252eb97a58da67f6a3c48138/apps/mqtt_server/test/session.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.
@hidden
@version {@version}
@doc This module implements a tesing of MQTT session.
Include files
-include_lib("eunit/include/eunit.hrl").
API Functions
Publisher: skip send publish. Resend publish after reconnect and restore session.
?debug_Fmt("::test:: session_1 : ~p ~p", [_X, _Conns]),
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?debug_Fmt("::test:: subscribe returns: ~p",[R1_0]),
Publisher: skip recieve publish ack. Resend publish after reconnect and restore session. Duplicate message.
?debug_Fmt("::test:: session_1 : ~p ~p", [_X, _Conns]),
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?debug_Fmt("::test:: subscribe returns: ~p",[R1_0]),
Subscriber: skip recieve publish. Resend publish after reconnect and restore session. Duplicate message.
?debug_Fmt("::test:: session_1 : ~p ~p", [_X, _Conns]),
?debug_Fmt("::test:: subscribe returns: ~p",[R1_0]),
?debug_Fmt("::test:: Subscriber with saved session : ~p", [Subscriber_2]),
Subscriber: skip send publish ack. Resend publish after reconnect and restore session. Duplicate message.
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
Publisher: skip send publish. Resend publish after reconnect and restore session.
Publisher: skip send pubrel. Resend pubrel after reconnect and restore session.
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
Publisher: skip receive pubcomp. Resend publish after reconnect and restore session.
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
Subscriber: skip receive publish. Resend publish after reconnect and restore session.
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
Subscriber: skip receive pubrel. Resend publish after reconnect and restore session.
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
Subscriber: skip send pubcomp. Resend publish after reconnect and restore session.
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
|
Copyright ( C ) 2015 - 2022 by ( )
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
@since 2016 - 09 - 29
2015 - 2022
@author < > [ / ]
-module(session).
-include_lib("stdlib/include/assert.hrl").
-include_lib("mqtt_common/include/mqtt.hrl").
-include("test.hrl").
-export([
session_1/2,
session_2/2
]).
-import(testing, [wait_all/1]).
session_1({1, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=1, publisher skips send publish.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(1, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 1, F}]),
?assertEqual({suback,[1],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"Test Payload QoS = 1. annon. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R2_0 ] ) ,
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_send_publish}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"Test Payload QoS = 1. annon. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R3_0 ] ) ,
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","puback timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
session_1({2, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=1, publisher skips recieve puback.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(1, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 1, F}]),
?assertEqual({suback,[1],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::1 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R2_0 ] ) ,
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_rcv_puback}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::2 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R3_0 ] ) ,
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","puback timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
session_1({3, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=1, subscriber skips receive publish", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?debug_Fmt("::test:: fun callback: ~100p",[_Arg]),
?assertEqual(1, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 1, F}]),
?assertEqual({suback,[1],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::1 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R2_0 ] ) ,
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_rcv_publish}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::2 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R3_0 ] ) ,
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
{F},
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::3 Test Payload QoS = 1. function callback. ">>),
? debug_Fmt("::test : : publish ( QoS = 1 ) returns : ~120p",[R3_1 ] ) ,
?assertEqual(ok, R3_1),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end};
session_1({4, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=1, subscriber skips send puback.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(1, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 1, F}]),
?assertEqual({suback,[1],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::1 Test Payload QoS = 1. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_send_puback}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::2 Test Payload QoS = 1. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
timer:sleep(500),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 1}, <<"::3 Test Payload QoS = 1. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(4),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end}.
session_2({1, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, publisher skips send publish.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKTest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKTest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_send_publish}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","pubcomp timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
Publisher : skip receive pubrec . Resend publish after reconnect and restore session .
session_2({2, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, publisher skips receive pubrec.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKTest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKTest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"1) Test Payload QoS = 2. annon. function callback.">>),
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_rcv_pubrec}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"2) Test Payload QoS = 2. annon. function callback.">>),
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","pubcomp timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
session_2({3, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, publisher skips send pubrel.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKTest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKTest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"1) Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_send_pubrel}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"2) Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","pubcomp timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
session_2({4, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, publisher skips receive pubcomp.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKTest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKTest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"1) Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual(ok, R2_0),
gen_server:call(Publisher, {set_test_flag, skip_rcv_pubcomp}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKTest", qos = 2}, <<"2) Test Payload QoS = 2. annon. function callback. ">>),
?assertEqual({mqtt_client_error,publish,none,"mqtt_client:publish/2","pubcomp timeout"}, R3_0),
mqtt_client:disconnect(Publisher),
Publisher_2 = mqtt_client:connect(
publisher,
#connect{
client_id = "publisher",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 1000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
W = wait_all(2),
unregister(test_result),
mqtt_client:disconnect(Publisher_2),
?assert(W),
?PASSED
end};
session_2({5, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, subscriber skips receive publish.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::1 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_rcv_publish}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::2 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::3 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end};
Subscriber : skip send pubrec . Resend publish after reconnect and restore session .
session_2({6, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, subscriber skips send pubrec.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::1 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_send_pubrec}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::2 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::3 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(4),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end};
session_2({7, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, subscriber skips receive pubrel.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::1 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_rcv_pubrel}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::2 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::3 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end};
session_2({8, session} = _X, [Publisher, Subscriber] = _Conns) -> {"session QoS=2, subscriber skips send pubcomp.", timeout, 100, fun() ->
register(test_result, self()),
F = fun({Q, #publish{topic= Topic, qos=_QoS, dup=_Dup, retain=_Ret, payload= Msg}} = _Arg) ->
?assertEqual(2, Q),
?assertEqual("AKtest", Topic),
test_result ! done
end,
R1_0 = mqtt_client:subscribe(Subscriber, [{"AKtest", 2, F}]),
?assertEqual({suback,[2],[]}, R1_0),
R2_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::1 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R2_0),
allow subscriber to receive first message
gen_server:call(Subscriber, {set_test_flag, skip_send_pubcomp}),
R3_0 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::2 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_0),
allow subscriber to receive second message
mqtt_client:disconnect(Subscriber),
timer:sleep(500),
Subscriber_2 = mqtt_client:connect(
subscriber,
#connect{
client_id = "subscriber",
user_name = "guest", password = <<"guest">>,
clean_session = 0,
keep_alive = 60000,
version = ?TEST_PROTOCOL
},
"localhost", ?TEST_SERVER_PORT,
[?TEST_CONN_TYPE]
),
?assert(is_pid(Subscriber_2)),
R3_1 = mqtt_client:publish(Publisher, #publish{topic = "AKtest", qos = 2}, <<"::3 Test Payload QoS = 2. function callback. ">>),
?assertEqual(ok, R3_1),
W = wait_all(3),
unregister(test_result),
mqtt_client:disconnect(Subscriber_2),
?assert(W),
?PASSED
end}.
|
850353e560a3b3737d3c97cf5376f16a9cb75d1f5eb4a3bc830ebfa8f51df745
|
NorfairKing/tickler
|
PostLoginSpec.hs
|
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
module Tickler.Server.Handler.PostLoginSpec (spec) where
import Network.HTTP.Types as HTTP
import Servant.API (HList (..), Headers (..))
import TestImport hiding (HList (..))
import Tickler.Client
import Tickler.Server.TestUtils
spec :: Spec
spec = withTicklerServer $
describe "Login" $ do
it "does not crash" $ \cenv ->
forAllValid $ \registration ->
withNewUser cenv registration $ \_ -> do
let lf = LoginForm {loginFormUsername = registrationUsername registration, loginFormPassword = registrationPassword registration}
Headers NoContent (HCons _ HNil) <- runClientOrError cenv $ clientPostLogin lf
pure ()
it "returns 401 when using an invalid password" $ \cenv ->
forAllValid $ \registration ->
forAll (genValid `suchThat` (/= registrationPassword registration)) $ \otherPassword ->
withNewUser cenv registration $ \_ -> do
let lf = LoginForm {loginFormUsername = registrationUsername registration, loginFormPassword = otherPassword}
errOrResult <- runClient cenv $ clientPostLogin lf
case errOrResult of
Right _ -> expectationFailure "Should not have succeeded."
Left err ->
let snf = expectationFailure $ "Should not fail with error: " <> show err
in case err of
FailureResponse _ resp ->
if HTTP.statusCode (responseStatusCode resp) == 401
then pure ()
else snf
_ -> snf
it "returns 401 when the account does not exist" $ \cenv ->
forAllValid $ \registration -> do
let lf = LoginForm {loginFormUsername = registrationUsername registration, loginFormPassword = registrationPassword registration}
errOrResult <- runClient cenv $ clientPostLogin lf
case errOrResult of
Right _ -> expectationFailure "Should not have succeeded."
Left err ->
let snf = expectationFailure $ "Should not fail with error: " <> show err
in case err of
FailureResponse _ resp ->
if HTTP.statusCode (responseStatusCode resp) == 401
then pure ()
else snf
_ -> snf
| null |
https://raw.githubusercontent.com/NorfairKing/tickler/1b0c05dc1d32847596bd3ffe4f93d094e1f6382a/tickler-server-gen/test/Tickler/Server/Handler/PostLoginSpec.hs
|
haskell
|
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
|
# LANGUAGE DataKinds #
# LANGUAGE FlexibleContexts #
module Tickler.Server.Handler.PostLoginSpec (spec) where
import Network.HTTP.Types as HTTP
import Servant.API (HList (..), Headers (..))
import TestImport hiding (HList (..))
import Tickler.Client
import Tickler.Server.TestUtils
spec :: Spec
spec = withTicklerServer $
describe "Login" $ do
it "does not crash" $ \cenv ->
forAllValid $ \registration ->
withNewUser cenv registration $ \_ -> do
let lf = LoginForm {loginFormUsername = registrationUsername registration, loginFormPassword = registrationPassword registration}
Headers NoContent (HCons _ HNil) <- runClientOrError cenv $ clientPostLogin lf
pure ()
it "returns 401 when using an invalid password" $ \cenv ->
forAllValid $ \registration ->
forAll (genValid `suchThat` (/= registrationPassword registration)) $ \otherPassword ->
withNewUser cenv registration $ \_ -> do
let lf = LoginForm {loginFormUsername = registrationUsername registration, loginFormPassword = otherPassword}
errOrResult <- runClient cenv $ clientPostLogin lf
case errOrResult of
Right _ -> expectationFailure "Should not have succeeded."
Left err ->
let snf = expectationFailure $ "Should not fail with error: " <> show err
in case err of
FailureResponse _ resp ->
if HTTP.statusCode (responseStatusCode resp) == 401
then pure ()
else snf
_ -> snf
it "returns 401 when the account does not exist" $ \cenv ->
forAllValid $ \registration -> do
let lf = LoginForm {loginFormUsername = registrationUsername registration, loginFormPassword = registrationPassword registration}
errOrResult <- runClient cenv $ clientPostLogin lf
case errOrResult of
Right _ -> expectationFailure "Should not have succeeded."
Left err ->
let snf = expectationFailure $ "Should not fail with error: " <> show err
in case err of
FailureResponse _ resp ->
if HTTP.statusCode (responseStatusCode resp) == 401
then pure ()
else snf
_ -> snf
|
eb3be97fdb0cc44c793337492b0212ab4f94a12ff01258bd063ad5cb584d6849
|
dyoo/whalesong
|
parameters.rkt
|
#lang typed/racket/base
(require "compiler/expression-structs.rkt"
"compiler/lexical-structs.rkt"
"compiler/arity-structs.rkt"
"sets.rkt"
racket/path
racket/port)
(require/typed "logger.rkt"
[log-warning (String -> Void)])
(provide current-defined-name
current-module-path
current-root-path
current-warn-unimplemented-kernel-primitive
current-seen-unimplemented-kernel-primitives
current-primitive-identifier?
current-compress-javascript?
current-one-module-per-file?
current-with-cache?
current-with-legacy-ie-support?
current-header-scripts
current-report-port
current-timing-port
)
(: current-module-path (Parameterof (U False Path)))
(define current-module-path
(make-parameter (build-path (current-directory) "anonymous-module.rkt")))
(: current-root-path (Parameterof Path))
(define current-root-path
(make-parameter (normalize-path (current-directory))))
(: current-warn-unimplemented-kernel-primitive (Parameterof (Symbol -> Void)))
(define current-warn-unimplemented-kernel-primitive
(make-parameter
(lambda: ([id : Symbol])
(log-warning
(format "WARNING: Primitive Kernel Value ~s has not been implemented\n"
id)))))
(: current-primitive-identifier? (Parameterof (Symbol -> (U False Arity))))
(define current-primitive-identifier? (make-parameter (lambda: ([name : Symbol]) #f)))
(: current-compress-javascript? (Parameterof Boolean))
(define current-compress-javascript? (make-parameter #f))
;; Turn this one so that js-assembler/package generates a file per module, as
;; opposed to trying to bundle them all together.
(: current-one-module-per-file? (Parameterof Boolean))
(define current-one-module-per-file? (make-parameter #f))
;; Turns on caching of compiled programs, so that repeated compilations
;; will reuse existing work.
(: current-with-cache? (Parameterof Boolean))
(define current-with-cache? (make-parameter #f))
;; Turns on ie legacy support; includes excanvas and other helper libraries
;; to smooth out compatibility issues.
(: current-with-legacy-ie-support? (Parameterof Boolean))
(define current-with-legacy-ie-support? (make-parameter #t))
;; Keeps list of Javascript files to be included in the header.
(: current-header-scripts (Parameterof (Listof Path)))
(define current-header-scripts (make-parameter '()))
(: current-report-port (Parameterof Output-Port))
(define current-report-port (make-parameter (current-output-port)))
(: current-timing-port (Parameterof Output-Port))
(define current-timing-port (make-parameter (open-output-nowhere) ;(current-output-port)
))
;;; Do not touch the following parameters: they're used internally by package
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(: current-seen-unimplemented-kernel-primitives (Parameterof (Setof Symbol)))
(define current-seen-unimplemented-kernel-primitives
(make-parameter
((inst new-seteq Symbol))))
;;; These parameters below will probably go away soon.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Workaround for what appears to be a bug in 5.3.1 pre - release
(: UNKNOWN Symbol)
(define UNKNOWN 'unknown)
(: current-defined-name (Parameterof (U Symbol LamPositionalName)))
(define current-defined-name (make-parameter UNKNOWN))
| null |
https://raw.githubusercontent.com/dyoo/whalesong/636e0b4e399e4523136ab45ef4cd1f5a84e88cdc/whalesong/parameters.rkt
|
racket
|
Turn this one so that js-assembler/package generates a file per module, as
opposed to trying to bundle them all together.
Turns on caching of compiled programs, so that repeated compilations
will reuse existing work.
Turns on ie legacy support; includes excanvas and other helper libraries
to smooth out compatibility issues.
Keeps list of Javascript files to be included in the header.
(current-output-port)
Do not touch the following parameters: they're used internally by package
These parameters below will probably go away soon.
|
#lang typed/racket/base
(require "compiler/expression-structs.rkt"
"compiler/lexical-structs.rkt"
"compiler/arity-structs.rkt"
"sets.rkt"
racket/path
racket/port)
(require/typed "logger.rkt"
[log-warning (String -> Void)])
(provide current-defined-name
current-module-path
current-root-path
current-warn-unimplemented-kernel-primitive
current-seen-unimplemented-kernel-primitives
current-primitive-identifier?
current-compress-javascript?
current-one-module-per-file?
current-with-cache?
current-with-legacy-ie-support?
current-header-scripts
current-report-port
current-timing-port
)
(: current-module-path (Parameterof (U False Path)))
(define current-module-path
(make-parameter (build-path (current-directory) "anonymous-module.rkt")))
(: current-root-path (Parameterof Path))
(define current-root-path
(make-parameter (normalize-path (current-directory))))
(: current-warn-unimplemented-kernel-primitive (Parameterof (Symbol -> Void)))
(define current-warn-unimplemented-kernel-primitive
(make-parameter
(lambda: ([id : Symbol])
(log-warning
(format "WARNING: Primitive Kernel Value ~s has not been implemented\n"
id)))))
(: current-primitive-identifier? (Parameterof (Symbol -> (U False Arity))))
(define current-primitive-identifier? (make-parameter (lambda: ([name : Symbol]) #f)))
(: current-compress-javascript? (Parameterof Boolean))
(define current-compress-javascript? (make-parameter #f))
(: current-one-module-per-file? (Parameterof Boolean))
(define current-one-module-per-file? (make-parameter #f))
(: current-with-cache? (Parameterof Boolean))
(define current-with-cache? (make-parameter #f))
(: current-with-legacy-ie-support? (Parameterof Boolean))
(define current-with-legacy-ie-support? (make-parameter #t))
(: current-header-scripts (Parameterof (Listof Path)))
(define current-header-scripts (make-parameter '()))
(: current-report-port (Parameterof Output-Port))
(define current-report-port (make-parameter (current-output-port)))
(: current-timing-port (Parameterof Output-Port))
))
(: current-seen-unimplemented-kernel-primitives (Parameterof (Setof Symbol)))
(define current-seen-unimplemented-kernel-primitives
(make-parameter
((inst new-seteq Symbol))))
Workaround for what appears to be a bug in 5.3.1 pre - release
(: UNKNOWN Symbol)
(define UNKNOWN 'unknown)
(: current-defined-name (Parameterof (U Symbol LamPositionalName)))
(define current-defined-name (make-parameter UNKNOWN))
|
51bb1455f847d0d06dd0c40b8f93e875ca1bb88268fc5111e953e6d526706a80
|
teamwalnut/graphql-ppx
|
list_inputs.ml
|
open Test_shared
module MyQuery =
[%graphql
{|
query ($arg: ListsInput!) {
listsInput(arg: $arg)
}
|}]
type qt = MyQuery.t
let pp formatter (obj : qt) =
Format.fprintf formatter "< listsInput = @[%s@] >" obj.listsInput
let equal (a : qt) (b : qt) = a.listsInput = b.listsInput
let allows_none_in_lists_of_nullable () =
test_json_
(MyQuery.makeVariables
~arg:
{
nullableOfNullable = Some [| Some "x"; None; Some "y" |];
nullableOfNonNullable = None;
nonNullableOfNullable = [| Some "a"; None; Some "b" |];
nonNullableOfNonNullable = [| "1"; "2"; "3" |];
}
()
|> MyQuery.serializeVariables |> MyQuery.variablesToJson)
(Json.Read.from_string
{| {
"arg": {
"nullableOfNullable": ["x", null, "y"],
"nullableOfNonNullable": null,
"nonNullableOfNullable": ["a", null, "b"],
"nonNullableOfNonNullable": ["1", "2", "3"]
}
} |})
let tests =
[
("Allows None in lists of nullable types", allows_none_in_lists_of_nullable);
]
| null |
https://raw.githubusercontent.com/teamwalnut/graphql-ppx/8276452ebe8d89a748b6b267afc94161650ab620/tests_native/list_inputs.ml
|
ocaml
|
open Test_shared
module MyQuery =
[%graphql
{|
query ($arg: ListsInput!) {
listsInput(arg: $arg)
}
|}]
type qt = MyQuery.t
let pp formatter (obj : qt) =
Format.fprintf formatter "< listsInput = @[%s@] >" obj.listsInput
let equal (a : qt) (b : qt) = a.listsInput = b.listsInput
let allows_none_in_lists_of_nullable () =
test_json_
(MyQuery.makeVariables
~arg:
{
nullableOfNullable = Some [| Some "x"; None; Some "y" |];
nullableOfNonNullable = None;
nonNullableOfNullable = [| Some "a"; None; Some "b" |];
nonNullableOfNonNullable = [| "1"; "2"; "3" |];
}
()
|> MyQuery.serializeVariables |> MyQuery.variablesToJson)
(Json.Read.from_string
{| {
"arg": {
"nullableOfNullable": ["x", null, "y"],
"nullableOfNonNullable": null,
"nonNullableOfNullable": ["a", null, "b"],
"nonNullableOfNonNullable": ["1", "2", "3"]
}
} |})
let tests =
[
("Allows None in lists of nullable types", allows_none_in_lists_of_nullable);
]
|
|
a0269f457a64d0b25c80b6316475fa2077b0eff51177425b21644e01ab3cce56
|
ndmitchell/catch
|
Predicate2.hs
|
{- |
For details see </~ndm/projects/libraries.php>
The idea behind this library is that the simplification of the predicate is
handled automatically using the 'PredLit' instance.
-}
module Data.Predicate2(
-- * Core Type Declarations
Pred, Reduction(..), PredLit(..), PredLitNot(..),
-- * Predicate Creation
predTrue, predFalse, predLit, predAnd, predOr, predNot, predBool,
-- * Extract and Test
isFalse, isTrue,
-- * Show
showPred, showPredBy,
-- * Play
mapPredLit, allPredLit, mapPredLitM
) where
import Data.List
import Data.Maybe
import Control.Monad
import qualified Data.Map as Map
import qualified Data.IntSet as IntSet
import qualified Data.IntMap as IntMap
-- * Debugging options
-- only to be used for developing
disableSimplify :: Bool
disableSimplify = False
-- * Core Type
-- | The abstract data type of a predicate.
-- Most users will want the type variable to be a member of 'PredLit'
data Pred a = PredTrue
| PredFalse
| Pred (Map.Map a Int) [IntSet.IntSet]
deriving (Read, Show)
| How do two items combine to be reduced , for simplification rules .
^ These two items do not simplify
^ Two items collapse to one item , same as ' Priority ' infinite
^ Two items collapse to a boolean value
^ The items collapse , but with a given priority - higher gets done first
-- | A predicate that has simplifications on it, all methods are optional
class Ord a => PredLit a where
| the first item implies the second
(?=>) :: a -> a -> Bool
| how two items combine under or
(?\/) :: a -> a -> Reduction a
| how two items combine under and
(?/\) :: a -> a -> Reduction a
-- | can a single value be collapse to a boolean
simp :: a -> Maybe Bool
simp x = Nothing
x ?=> y = False
x ?\/ y = Same
x ?/\ y = Same
-- | A predicate that can also be negated, required for 'predNot' only
class PredLit a => PredLitNot a where
-- | the negation of a literal
litNot :: a -> Pred a
-- * Useful utilities
(??\/) :: PredLit a => a -> a -> Reduction a
a ??\/ b | disableSimplify = Same
| a == b = Single a
| a ?=> b = Single b
| otherwise = a ?\/ b
(??/\) :: PredLit a => a -> a -> Reduction a
a ??/\ b | disableSimplify = Same
| a == b = Single a
| a ?=> b = Single a
| otherwise = a ?/\ b
-- * Creators
-- | A constant True
predTrue :: Pred a
predTrue = PredTrue
-- | A constant False
predFalse :: Pred a
predFalse = PredFalse
-- | Create a predicate that is just a literal
predLit :: a -> Pred a
predLit x = Pred (Map.singleton x 0) [IntSet.singleton 0]
makeCompat :: PredLit a => [Pred a] -> (Map.Map a Int, [[IntSet.IntSet]])
makeCompat xs = (mp, map f xs)
where
mp = Map.fromAscList $ zip as [0..]
as = mergeList [map fst $ Map.toAscList a | Pred a b <- xs]
f (Pred a b) = map (IntSet.map g) b
where
mp2 = IntMap.fromList [(v, fromJust $ Map.lookup k mp) | (k,v) <- Map.toAscList a]
g x = fromJust $ IntMap.lookup x mp2
mergeList xs = foldr f [] xs
where
f (x:xs) (y:ys) =
case compare x y of
EQ -> x : f xs ys
LT -> x : f xs (y:ys)
GT -> y : f (x:xs) ys
f [] ys = ys
f xs [] = xs
-- | Combine a list of predicates with and
predAnd :: PredLit a => [Pred a] -> Pred a
case items of
[ x ] - > x
xs | any isFalse xs - > predFalse
| otherwise - > PredAnd xs
where
items = nub $ filter ( not . isTrue ) $ solveTerms ( ? ? /\ ) $ concatMap fromAnd xs
[x] -> x
xs | any isFalse xs -> predFalse
| otherwise -> PredAnd xs
where
items = nub $ filter (not . isTrue) $ solveTerms (??/\) $ concatMap fromAnd xs
-}
-- | Combine a list of predicates with or
predOr :: PredLit a => [Pred a] -> Pred a
case items of
[ x ] - > x
xs | any isTrue xs - > predTrue
| otherwise - > PredOr xs
where
items = nub $ filter ( not . isFalse ) $ solveTerms ( ? ? \/ ) $ concatMap fromOr xs
[x] -> x
xs | any isTrue xs -> predTrue
| otherwise -> PredOr xs
where
items = nub $ filter (not . isFalse) $ solveTerms (??\/) $ concatMap fromOr xs
-}
-- | Return True only if the predicate is definately False. Note that predFalse /is not/ not . predTrue
isFalse :: Pred a -> Bool
isFalse (PredFalse) = True
isFalse _ = False
-- | Return True only if the predicate is definately True
isTrue :: Pred a -> Bool
isTrue (PredTrue) = True
isTrue _ = False
-- | Create a predicate that matches the boolean value
predBool :: Bool -> Pred a
predBool True = predTrue
predBool False = predFalse
demandBool :: Pred a -> Bool
demandBool x | isTrue x = True
| isFalse x = False
| otherwise = error "demandBool, error"
-- | Negate a predicate
predNot :: PredLitNot a => Pred a -> Pred a
predNot x = undefined {- =
case x of
PredOr xs -> predAnd $ map predNot xs
PredAnd xs -> predOr $ map predNot xs
PredLit x -> litNot x-}
-- * Show
-- | Show a predicate nicely
showPred :: Show a => Pred a -> String
showPred x = showPredBy show x
-- | Show a predicate, with a special function for showing each element
showPredBy :: (a -> String) -> Pred a -> String
case x of
PredOr [ ] - > " False "
[ ] - > " True "
PredLit a - > f a
PredOr xs - > disp ' v ' xs
PredAnd xs - > disp ' ^ ' xs
where
disp sym xs = " ( " + + mid + + " ) "
where mid = concat $ intersperse [ ' ' , sym , ' ' ] $ map ( showPredBy f ) xs
case x of
PredOr [] -> "False"
PredAnd [] -> "True"
PredLit a -> f a
PredOr xs -> disp 'v' xs
PredAnd xs -> disp '^' xs
where
disp sym xs = "(" ++ mid ++ ")"
where mid = concat $ intersperse [' ',sym,' '] $ map (showPredBy f) xs -}
-- * Eq
instance Eq a => Eq (Pred a) where
( PredLit a ) = = ( PredLit b ) = a = = b
( PredAnd a ) = = ( b ) = sameSet a b
( PredOr a ) = = ( PredOr b ) = sameSet a b
_ = = _ = False
(PredLit a) == (PredLit b) = a == b
(PredAnd a) == (PredAnd b) = sameSet a b
(PredOr a) == (PredOr b) = sameSet a b
_ == _ = False -}
-- * Maps and traversals
-- | Convert a predicate to a boolean
mapPredBool :: (a -> Bool) -> Pred a -> Bool
mapPredBool f = undefined -- demandBool . mapPredLit (predBool . f)
-- | Perform a map over every literal
mapPredLit :: PredLit b => (a -> Pred b) -> Pred a -> Pred b
case x of
PredOr xs - > predOr $ fs xs
PredAnd xs - > predAnd $ fs xs
PredLit x - > f x
where
fs = map ( mapPredLit f )
case x of
PredOr xs -> predOr $ fs xs
PredAnd xs -> predAnd $ fs xs
PredLit x -> f x
where
fs = map (mapPredLit f) -}
| Perform a map over every literal ,
mapPredLitM :: (Monad m, PredLit b) => (a -> m (Pred b)) -> Pred a -> m (Pred b)
case x of
PredOr xs - > liftM predOr $ fs xs
PredAnd xs - > liftM predAnd $ fs xs
PredLit x - > f x
where
fs = mapM ( mapPredLitM f )
case x of
PredOr xs -> liftM predOr $ fs xs
PredAnd xs -> liftM predAnd $ fs xs
PredLit x -> f x
where
fs = mapM (mapPredLitM f) -}
-- | Get all literals in a predicate
allPredLit :: Pred a -> [a]
allPredLit x = undefined {-
case x of
PredOr xs -> fs xs
PredAnd xs -> fs xs
PredLit x -> [x]
where
fs = concatMap allPredLit -}
| null |
https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/proposition/Unused/Predicate2.hs
|
haskell
|
|
For details see </~ndm/projects/libraries.php>
The idea behind this library is that the simplification of the predicate is
handled automatically using the 'PredLit' instance.
* Core Type Declarations
* Predicate Creation
* Extract and Test
* Show
* Play
* Debugging options
only to be used for developing
* Core Type
| The abstract data type of a predicate.
Most users will want the type variable to be a member of 'PredLit'
| A predicate that has simplifications on it, all methods are optional
| can a single value be collapse to a boolean
| A predicate that can also be negated, required for 'predNot' only
| the negation of a literal
* Useful utilities
* Creators
| A constant True
| A constant False
| Create a predicate that is just a literal
| Combine a list of predicates with and
| Combine a list of predicates with or
| Return True only if the predicate is definately False. Note that predFalse /is not/ not . predTrue
| Return True only if the predicate is definately True
| Create a predicate that matches the boolean value
| Negate a predicate
=
case x of
PredOr xs -> predAnd $ map predNot xs
PredAnd xs -> predOr $ map predNot xs
PredLit x -> litNot x
* Show
| Show a predicate nicely
| Show a predicate, with a special function for showing each element
* Eq
* Maps and traversals
| Convert a predicate to a boolean
demandBool . mapPredLit (predBool . f)
| Perform a map over every literal
| Get all literals in a predicate
case x of
PredOr xs -> fs xs
PredAnd xs -> fs xs
PredLit x -> [x]
where
fs = concatMap allPredLit
|
module Data.Predicate2(
Pred, Reduction(..), PredLit(..), PredLitNot(..),
predTrue, predFalse, predLit, predAnd, predOr, predNot, predBool,
isFalse, isTrue,
showPred, showPredBy,
mapPredLit, allPredLit, mapPredLitM
) where
import Data.List
import Data.Maybe
import Control.Monad
import qualified Data.Map as Map
import qualified Data.IntSet as IntSet
import qualified Data.IntMap as IntMap
disableSimplify :: Bool
disableSimplify = False
data Pred a = PredTrue
| PredFalse
| Pred (Map.Map a Int) [IntSet.IntSet]
deriving (Read, Show)
| How do two items combine to be reduced , for simplification rules .
^ These two items do not simplify
^ Two items collapse to one item , same as ' Priority ' infinite
^ Two items collapse to a boolean value
^ The items collapse , but with a given priority - higher gets done first
class Ord a => PredLit a where
| the first item implies the second
(?=>) :: a -> a -> Bool
| how two items combine under or
(?\/) :: a -> a -> Reduction a
| how two items combine under and
(?/\) :: a -> a -> Reduction a
simp :: a -> Maybe Bool
simp x = Nothing
x ?=> y = False
x ?\/ y = Same
x ?/\ y = Same
class PredLit a => PredLitNot a where
litNot :: a -> Pred a
(??\/) :: PredLit a => a -> a -> Reduction a
a ??\/ b | disableSimplify = Same
| a == b = Single a
| a ?=> b = Single b
| otherwise = a ?\/ b
(??/\) :: PredLit a => a -> a -> Reduction a
a ??/\ b | disableSimplify = Same
| a == b = Single a
| a ?=> b = Single a
| otherwise = a ?/\ b
predTrue :: Pred a
predTrue = PredTrue
predFalse :: Pred a
predFalse = PredFalse
predLit :: a -> Pred a
predLit x = Pred (Map.singleton x 0) [IntSet.singleton 0]
makeCompat :: PredLit a => [Pred a] -> (Map.Map a Int, [[IntSet.IntSet]])
makeCompat xs = (mp, map f xs)
where
mp = Map.fromAscList $ zip as [0..]
as = mergeList [map fst $ Map.toAscList a | Pred a b <- xs]
f (Pred a b) = map (IntSet.map g) b
where
mp2 = IntMap.fromList [(v, fromJust $ Map.lookup k mp) | (k,v) <- Map.toAscList a]
g x = fromJust $ IntMap.lookup x mp2
mergeList xs = foldr f [] xs
where
f (x:xs) (y:ys) =
case compare x y of
EQ -> x : f xs ys
LT -> x : f xs (y:ys)
GT -> y : f (x:xs) ys
f [] ys = ys
f xs [] = xs
predAnd :: PredLit a => [Pred a] -> Pred a
case items of
[ x ] - > x
xs | any isFalse xs - > predFalse
| otherwise - > PredAnd xs
where
items = nub $ filter ( not . isTrue ) $ solveTerms ( ? ? /\ ) $ concatMap fromAnd xs
[x] -> x
xs | any isFalse xs -> predFalse
| otherwise -> PredAnd xs
where
items = nub $ filter (not . isTrue) $ solveTerms (??/\) $ concatMap fromAnd xs
-}
predOr :: PredLit a => [Pred a] -> Pred a
case items of
[ x ] - > x
xs | any isTrue xs - > predTrue
| otherwise - > PredOr xs
where
items = nub $ filter ( not . isFalse ) $ solveTerms ( ? ? \/ ) $ concatMap fromOr xs
[x] -> x
xs | any isTrue xs -> predTrue
| otherwise -> PredOr xs
where
items = nub $ filter (not . isFalse) $ solveTerms (??\/) $ concatMap fromOr xs
-}
isFalse :: Pred a -> Bool
isFalse (PredFalse) = True
isFalse _ = False
isTrue :: Pred a -> Bool
isTrue (PredTrue) = True
isTrue _ = False
predBool :: Bool -> Pred a
predBool True = predTrue
predBool False = predFalse
demandBool :: Pred a -> Bool
demandBool x | isTrue x = True
| isFalse x = False
| otherwise = error "demandBool, error"
predNot :: PredLitNot a => Pred a -> Pred a
showPred :: Show a => Pred a -> String
showPred x = showPredBy show x
showPredBy :: (a -> String) -> Pred a -> String
case x of
PredOr [ ] - > " False "
[ ] - > " True "
PredLit a - > f a
PredOr xs - > disp ' v ' xs
PredAnd xs - > disp ' ^ ' xs
where
disp sym xs = " ( " + + mid + + " ) "
where mid = concat $ intersperse [ ' ' , sym , ' ' ] $ map ( showPredBy f ) xs
case x of
PredOr [] -> "False"
PredAnd [] -> "True"
PredLit a -> f a
PredOr xs -> disp 'v' xs
PredAnd xs -> disp '^' xs
where
disp sym xs = "(" ++ mid ++ ")"
where mid = concat $ intersperse [' ',sym,' '] $ map (showPredBy f) xs -}
instance Eq a => Eq (Pred a) where
( PredLit a ) = = ( PredLit b ) = a = = b
( PredAnd a ) = = ( b ) = sameSet a b
( PredOr a ) = = ( PredOr b ) = sameSet a b
_ = = _ = False
(PredLit a) == (PredLit b) = a == b
(PredAnd a) == (PredAnd b) = sameSet a b
(PredOr a) == (PredOr b) = sameSet a b
_ == _ = False -}
mapPredBool :: (a -> Bool) -> Pred a -> Bool
mapPredLit :: PredLit b => (a -> Pred b) -> Pred a -> Pred b
case x of
PredOr xs - > predOr $ fs xs
PredAnd xs - > predAnd $ fs xs
PredLit x - > f x
where
fs = map ( mapPredLit f )
case x of
PredOr xs -> predOr $ fs xs
PredAnd xs -> predAnd $ fs xs
PredLit x -> f x
where
fs = map (mapPredLit f) -}
| Perform a map over every literal ,
mapPredLitM :: (Monad m, PredLit b) => (a -> m (Pred b)) -> Pred a -> m (Pred b)
case x of
PredOr xs - > liftM predOr $ fs xs
PredAnd xs - > liftM predAnd $ fs xs
PredLit x - > f x
where
fs = mapM ( mapPredLitM f )
case x of
PredOr xs -> liftM predOr $ fs xs
PredAnd xs -> liftM predAnd $ fs xs
PredLit x -> f x
where
fs = mapM (mapPredLitM f) -}
allPredLit :: Pred a -> [a]
|
5f7882913de715e1d1d7a72afd22db849ffa2bf8c0108d1e355d03b030f0d7a6
|
sbtourist/clamq
|
project.clj
|
(defproject clamq/clamq-rabbitmq "0.5-SNAPSHOT"
:description "Clojure APIs for Message Queues"
:dependencies [[clamq/clamq-core "0.5-SNAPSHOT"]
[org.slf4j/slf4j-api "1.6.1"]
[org.springframework.amqp/spring-rabbit "1.0.0.RELEASE"]]
:dev-dependencies [
[org.slf4j/slf4j-simple "1.6.1"]])
| null |
https://raw.githubusercontent.com/sbtourist/clamq/34a6bbcb7a2a431ea629aa5cfbc687ef31f860f2/clamq-rabbitmq/project.clj
|
clojure
|
(defproject clamq/clamq-rabbitmq "0.5-SNAPSHOT"
:description "Clojure APIs for Message Queues"
:dependencies [[clamq/clamq-core "0.5-SNAPSHOT"]
[org.slf4j/slf4j-api "1.6.1"]
[org.springframework.amqp/spring-rabbit "1.0.0.RELEASE"]]
:dev-dependencies [
[org.slf4j/slf4j-simple "1.6.1"]])
|
|
fa6699b99665db90c252e9b33ee6280dac4385e9ba4d54dbb8148323f70517ac
|
ktakashi/sagittarius-scheme
|
ecdh.scm
|
-*- mode : scheme ; coding : utf-8 ; -*-
;;;
;;; crypto/key/ecdh.scm - ECDH and ECCDH
;;;
Copyright ( c ) 2017 . All rights reserved .
;;;
;;; Redistribution and use in source and binary forms, with or without
;;; modification, are permitted provided that the following conditions
;;; are met:
;;;
1 . Redistributions of source code must retain the above copyright
;;; notice, this list of conditions and the following disclaimer.
;;;
2 . Redistributions in binary form must reproduce the above copyright
;;; notice, this list of conditions and the following disclaimer in the
;;; documentation and/or other materials provided with the distribution.
;;;
;;; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
;;; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
;;; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
TO , PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES ; LOSS OF USE , DATA , OR
;;; PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
;;; SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
;; reference:
;; - SEC1 v2
;; -v2.pdf
;; - 800-56A
;; -56Ar2.pdf
#!nounbound
(library (crypto ecdh)
(export ECDH
ecdh-calculate-agreement
ecdhc-calculate-agreement)
(import (rnrs)
(sagittarius)
(math ec)
(clos user)
(crypto key agreement)
(crypto ecdsa))
(define ECDH :ecdh)
SEC1 v2 , section 3.3.1
ec - param - a curve parameter
du - private key d from ec - priavate - key
Qv - public key Q from ec - public - key ( ec - point )
(define (ecdh-calculate-agreement ec-param du Qv)
(define curve (ec-parameter-curve ec-param))
(let ((P (ec-point-mul curve Qv du)))
(when (ec-point-infinity? P) (error 'ecdh-calculate-agreement "invalid"))
(ec-point-x P)))
SEC1 v2 , section 3.3.2
ec - param - a curve parameter
du - private key d from ec - priavate - key
Qv - public key Q from ec - public - key ( ec - point )
NB : prefix ECDEC is taken from cofactor agreement of bouncy castle
(define (ecdhc-calculate-agreement ec-param du Qv)
(define curve (ec-parameter-curve ec-param))
(define h (ec-parameter-h ec-param))
(define n (ec-parameter-n ec-param))
(let ((P (ec-point-mul curve Qv (mod (* du h) n))))
(when (ec-point-infinity? P) (error 'ecdh-calculate-agreement "invalid"))
(ec-point-x P)))
(define-method calculate-key-agreement ((m (eql ECDH))
(priv <ecdsa-private-key>)
(pub <ecdsa-public-key>))
(define param (ecdsa-private-key-parameter priv))
(unless (equal? (ec-parameter-curve param)
(ec-parameter-curve (ecdsa-public-key-parameter pub)))
(assertion-violation 'calculate-key-agreement
"Key type are not the same"))
;; it's rather weird to return integer as secret key
;; so convert it to bytevector.
;; NOTE: actual implementation return integer for whatever the reason
(integer->bytevector
(ecdhc-calculate-agreement param (ecdsa-private-key-d priv)
(ecdsa-public-key-Q pub))))
)
| null |
https://raw.githubusercontent.com/ktakashi/sagittarius-scheme/ec4aa18461cbbbf8fb13376cb85eaf01ce7fb998/ext/crypto/crypto/ecdh.scm
|
scheme
|
coding : utf-8 ; -*-
crypto/key/ecdh.scm - ECDH and ECCDH
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
notice, this list of conditions and the following disclaimer.
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
LOSS OF USE , DATA , OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
reference:
- SEC1 v2
-v2.pdf
- 800-56A
-56Ar2.pdf
it's rather weird to return integer as secret key
so convert it to bytevector.
NOTE: actual implementation return integer for whatever the reason
|
Copyright ( c ) 2017 . All rights reserved .
1 . Redistributions of source code must retain the above copyright
2 . Redistributions in binary form must reproduce the above copyright
" AS IS " AND ANY EXPRESS OR IMPLIED WARRANTIES , INCLUDING , BUT NOT
OWNER OR ANY DIRECT , INDIRECT , INCIDENTAL ,
SPECIAL , EXEMPLARY , OR CONSEQUENTIAL DAMAGES ( INCLUDING , BUT NOT LIMITED
LIABILITY , WHETHER IN CONTRACT , STRICT LIABILITY , OR TORT ( INCLUDING
NEGLIGENCE OR OTHERWISE ) ARISING IN ANY WAY OUT OF THE USE OF THIS
#!nounbound
(library (crypto ecdh)
(export ECDH
ecdh-calculate-agreement
ecdhc-calculate-agreement)
(import (rnrs)
(sagittarius)
(math ec)
(clos user)
(crypto key agreement)
(crypto ecdsa))
(define ECDH :ecdh)
SEC1 v2 , section 3.3.1
ec - param - a curve parameter
du - private key d from ec - priavate - key
Qv - public key Q from ec - public - key ( ec - point )
(define (ecdh-calculate-agreement ec-param du Qv)
(define curve (ec-parameter-curve ec-param))
(let ((P (ec-point-mul curve Qv du)))
(when (ec-point-infinity? P) (error 'ecdh-calculate-agreement "invalid"))
(ec-point-x P)))
SEC1 v2 , section 3.3.2
ec - param - a curve parameter
du - private key d from ec - priavate - key
Qv - public key Q from ec - public - key ( ec - point )
NB : prefix ECDEC is taken from cofactor agreement of bouncy castle
(define (ecdhc-calculate-agreement ec-param du Qv)
(define curve (ec-parameter-curve ec-param))
(define h (ec-parameter-h ec-param))
(define n (ec-parameter-n ec-param))
(let ((P (ec-point-mul curve Qv (mod (* du h) n))))
(when (ec-point-infinity? P) (error 'ecdh-calculate-agreement "invalid"))
(ec-point-x P)))
(define-method calculate-key-agreement ((m (eql ECDH))
(priv <ecdsa-private-key>)
(pub <ecdsa-public-key>))
(define param (ecdsa-private-key-parameter priv))
(unless (equal? (ec-parameter-curve param)
(ec-parameter-curve (ecdsa-public-key-parameter pub)))
(assertion-violation 'calculate-key-agreement
"Key type are not the same"))
(integer->bytevector
(ecdhc-calculate-agreement param (ecdsa-private-key-d priv)
(ecdsa-public-key-Q pub))))
)
|
34a8801352ccbd06f0ce2ae120ee4e5226546a6a82d4fd8a38009881225b1bf4
|
lasp-lang/lasp
|
lasp_client_server_advertisement_counter_SUITE.erl
|
%% -------------------------------------------------------------------
%%
Copyright ( c ) 2016 . All Rights Reserved .
%%
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.
%%
%% -------------------------------------------------------------------
%%
-module(lasp_client_server_advertisement_counter_SUITE).
-author("Christopher Meiklejohn <>").
%% common_test callbacks
-export([%% suite/0,
init_per_suite/1,
end_per_suite/1,
init_per_testcase/2,
end_per_testcase/2,
all/0]).
%% tests
-compile([export_all]).
-include("lasp.hrl").
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("kernel/include/inet.hrl").
%% ===================================================================
%% common_test callbacks
%% ===================================================================
init_per_suite(_Config) ->
_Config.
end_per_suite(_Config) ->
_Config.
init_per_testcase(Case, _Config) ->
ct:pal("Beginning test case ~p", [Case]),
_Config.
end_per_testcase(Case, _Config) ->
ct:pal("Ending test case ~p", [Case]),
_Config.
all() ->
[
client_server_state_based_test,
client_server_delta_based_test,
reactive_client_server_state_based_test,
reactive_client_server_delta_based_test
%%client_server_state_based_ps_test,
client_server_delta_based_ps_test
].
%% ===================================================================
%% tests
%% ===================================================================
default_test(_Config) ->
ok.
%% ===================================================================
%% client/server with local replica
%% ===================================================================
client_server_state_based_test(Config) ->
lasp_simulation_support:run(client_server_ad_counter_state_based_test,
Config,
[{mode, state_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, orset},
{broadcast, false},
{evaluation_identifier, client_server_state_based}]),
ok.
client_server_delta_based_test(Config) ->
lasp_simulation_support:run(client_server_ad_counter_delta_based_test,
Config,
[{mode, delta_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, orset},
{broadcast, false},
{evaluation_identifier, client_server_delta_based}]),
ok.
reactive_client_server_state_based_test(Config) ->
lasp_simulation_support:run(reactive_client_server_ad_counter_state_based_test,
Config,
[{mode, state_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, orset},
{broadcast, false},
{reactive_server, true},
{evaluation_identifier, reactive_client_server_state_based}]),
ok.
reactive_client_server_delta_based_test(Config) ->
lasp_simulation_support:run(reactive_client_server_ad_counter_delta_based_test,
Config,
[{mode, delta_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, orset},
{broadcast, false},
{reactive_server, true},
{evaluation_identifier, reactive_client_server_delta_based}]),
ok.
client_server_state_based_ps_test(Config) ->
lasp_simulation_support:run(client_server_ad_counter_state_based_ps_test,
Config,
[{mode, state_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, awset_ps},
{broadcast, false},
{evaluation_identifier, client_server_state_based_ps}]),
ok.
client_server_delta_based_ps_test(Config) ->
lasp_simulation_support:run(client_server_ad_counter_delta_based_ps_test,
Config,
[{mode, delta_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, awset_ps},
{broadcast, false},
{evaluation_identifier, client_server_delta_based_ps}]),
ok.
%% ===================================================================
Internal functions
%% ===================================================================
| null |
https://raw.githubusercontent.com/lasp-lang/lasp/1701c8af77e193738dfc4ef4a5a703d205da41a1/test/lasp_client_server_advertisement_counter_SUITE.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.
-------------------------------------------------------------------
common_test callbacks
suite/0,
tests
===================================================================
common_test callbacks
===================================================================
client_server_state_based_ps_test,
===================================================================
tests
===================================================================
===================================================================
client/server with local replica
===================================================================
===================================================================
===================================================================
|
Copyright ( c ) 2016 . All Rights Reserved .
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(lasp_client_server_advertisement_counter_SUITE).
-author("Christopher Meiklejohn <>").
init_per_suite/1,
end_per_suite/1,
init_per_testcase/2,
end_per_testcase/2,
all/0]).
-compile([export_all]).
-include("lasp.hrl").
-include_lib("common_test/include/ct.hrl").
-include_lib("eunit/include/eunit.hrl").
-include_lib("kernel/include/inet.hrl").
init_per_suite(_Config) ->
_Config.
end_per_suite(_Config) ->
_Config.
init_per_testcase(Case, _Config) ->
ct:pal("Beginning test case ~p", [Case]),
_Config.
end_per_testcase(Case, _Config) ->
ct:pal("Ending test case ~p", [Case]),
_Config.
all() ->
[
client_server_state_based_test,
client_server_delta_based_test,
reactive_client_server_state_based_test,
reactive_client_server_delta_based_test
client_server_delta_based_ps_test
].
default_test(_Config) ->
ok.
client_server_state_based_test(Config) ->
lasp_simulation_support:run(client_server_ad_counter_state_based_test,
Config,
[{mode, state_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, orset},
{broadcast, false},
{evaluation_identifier, client_server_state_based}]),
ok.
client_server_delta_based_test(Config) ->
lasp_simulation_support:run(client_server_ad_counter_delta_based_test,
Config,
[{mode, delta_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, orset},
{broadcast, false},
{evaluation_identifier, client_server_delta_based}]),
ok.
reactive_client_server_state_based_test(Config) ->
lasp_simulation_support:run(reactive_client_server_ad_counter_state_based_test,
Config,
[{mode, state_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, orset},
{broadcast, false},
{reactive_server, true},
{evaluation_identifier, reactive_client_server_state_based}]),
ok.
reactive_client_server_delta_based_test(Config) ->
lasp_simulation_support:run(reactive_client_server_ad_counter_delta_based_test,
Config,
[{mode, delta_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, orset},
{broadcast, false},
{reactive_server, true},
{evaluation_identifier, reactive_client_server_delta_based}]),
ok.
client_server_state_based_ps_test(Config) ->
lasp_simulation_support:run(client_server_ad_counter_state_based_ps_test,
Config,
[{mode, state_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, awset_ps},
{broadcast, false},
{evaluation_identifier, client_server_state_based_ps}]),
ok.
client_server_delta_based_ps_test(Config) ->
lasp_simulation_support:run(client_server_ad_counter_delta_based_ps_test,
Config,
[{mode, delta_based},
{simulation, ad_counter},
{partisan_peer_service_manager, partisan_client_server_peer_service_manager},
{set, awset_ps},
{broadcast, false},
{evaluation_identifier, client_server_delta_based_ps}]),
ok.
Internal functions
|
d4b9c98850e746f513a21db93f1ea3563da50fd4742c33c70051d7bd9c31327a
|
stuarthalloway/programming-clojure
|
expectorate.clj
|
(ns examples.expectorate
(:import (java.io FileOutputStream OutputStreamWriter BufferedWriter)))
(defn expectorate [dst content]
(with-open [writer (-> dst
FileOutputStream.
OutputStreamWriter.
BufferedWriter.)]
(.write writer (str content))))
| null |
https://raw.githubusercontent.com/stuarthalloway/programming-clojure/192e2f28d797fd70e50778aabd031b3ff55bd2b9/src/examples/expectorate.clj
|
clojure
|
(ns examples.expectorate
(:import (java.io FileOutputStream OutputStreamWriter BufferedWriter)))
(defn expectorate [dst content]
(with-open [writer (-> dst
FileOutputStream.
OutputStreamWriter.
BufferedWriter.)]
(.write writer (str content))))
|
|
443c1eca4f33b9a6a5949085bcbf9690d671029e409097bb423178d1246438cd
|
DKurilo/hackerrank
|
Main.hs
|
import Control.Monad
import Data.List (minimumBy)
import Debug.Trace (trace)
import System.IO
rocks :: Int
rocks = 30
letters :: Int
letters = 27
data Op = GoRight | GoLeft | Prev | Next | Take | Loop Program
instance Show Op where
show GoRight = ">"
show GoLeft = "<"
show Prev = "-"
show Next = "+"
show Take = "."
show (Loop prog) = "[" <> show prog <> "]"
newtype Program = Program {unProgram :: [Op]}
instance Semigroup Program where
p1 <> p2 = Program (unProgram p1 <> unProgram p2)
instance Monoid Program where
mempty = Program []
mconcat = Program . foldr ((<>) . unProgram) mempty
instance Show Program where
show = concatMap show . unProgram
data Machine = Machine {mProg :: Program, mRock :: Int, mRocks :: [Int]} deriving (Show)
charToMem :: Int -> Char
charToMem 1 = 'A'
charToMem 2 = 'B'
charToMem 3 = 'C'
charToMem 4 = 'D'
charToMem 5 = 'E'
charToMem 6 = 'F'
charToMem 7 = 'G'
charToMem 8 = 'H'
charToMem 9 = 'I'
charToMem 10 = 'J'
charToMem 11 = 'K'
charToMem 12 = 'L'
charToMem 13 = 'M'
charToMem 14 = 'N'
charToMem 15 = 'O'
charToMem 16 = 'P'
charToMem 17 = 'Q'
charToMem 18 = 'R'
charToMem 19 = 'S'
charToMem 20 = 'T'
charToMem 21 = 'U'
charToMem 22 = 'V'
charToMem 23 = 'W'
charToMem 24 = 'X'
charToMem 25 = 'Y'
charToMem 26 = 'Z'
charToMem _ = ' '
memToChar :: Char -> Int
memToChar 'A' = 1
memToChar 'B' = 2
memToChar 'C' = 3
memToChar 'D' = 4
memToChar 'E' = 5
memToChar 'F' = 6
memToChar 'G' = 7
memToChar 'H' = 8
memToChar 'I' = 9
memToChar 'J' = 10
memToChar 'K' = 11
memToChar 'L' = 12
memToChar 'M' = 13
memToChar 'N' = 14
memToChar 'O' = 15
memToChar 'P' = 16
memToChar 'Q' = 17
memToChar 'R' = 18
memToChar 'S' = 19
memToChar 'T' = 20
memToChar 'U' = 21
memToChar 'V' = 22
memToChar 'W' = 23
memToChar 'X' = 24
memToChar 'Y' = 25
memToChar 'Z' = 26
memToChar _ = 0
goToRock :: Int -> Machine -> Machine
goToRock to m
| from == to = m
| from > to =
m
{ mRock = to,
mProg =
mProg m
<> Program
( if from - to < rocks - from + to
then replicate (from - to) GoLeft
else replicate (rocks - from + to) GoRight
)
}
| otherwise =
m
{ mRock = to,
mProg =
mProg m
<> Program
( if to - from < rocks + from - to
then replicate (to - from) GoRight
else replicate (rocks + from - to) GoLeft
)
}
where
from = mRock m
takeLetter :: Int -> Machine -> Machine
takeLetter l m
| from == to = m {mProg = mProg m <> Program [Take]}
| from > to =
m
{ mRocks = newRocks,
mProg =
mProg m
<> Program
( if from - to < letters - from + to
then replicate (from - to) Prev
else replicate (letters - from + to) Next
)
<> Program [Take]
}
| otherwise =
m
{ mRocks = newRocks,
mProg =
mProg m
<> Program
( if to - from < letters + from - to
then replicate (to - from) Next
else replicate (letters + from - to) Prev
)
<> Program [Take]
}
where
from = mRocks m !! mRock m
to = l
currRocks = mRocks m
newRocks = take (mRock m) currRocks <> (l : drop (mRock m + 1) currRocks)
addLetter :: Int -> Machine -> Machine
addLetter l =
minimumBy (\m1 m2 -> compare (progLength m1) (progLength m2))
. zipWith (\i m -> takeLetter l . goToRock i $ m) [0 .. rocks - 1]
. repeat
where
progLength = length . unProgram . mProg
main :: IO ()
main = do
hSetBuffering stdout NoBuffering -- DO NOT REMOVE
-- Auto-generated code below aims at helping you parse
-- the standard input according to the problem statement.
magicphrase <- map memToChar <$> getLine
-- hPutStrLn stderr "Debug messages..."
-- Write action to stdout
print . mProg . foldl (flip addLetter) (Machine (Program []) 0 (replicate rocks 0)) $ magicphrase
return ()
| null |
https://raw.githubusercontent.com/DKurilo/hackerrank/bb6a69775a4a03c784fc678de54ded5ef6eb5d30/codingame/brain-fork/src/Main.hs
|
haskell
|
DO NOT REMOVE
Auto-generated code below aims at helping you parse
the standard input according to the problem statement.
hPutStrLn stderr "Debug messages..."
Write action to stdout
|
import Control.Monad
import Data.List (minimumBy)
import Debug.Trace (trace)
import System.IO
rocks :: Int
rocks = 30
letters :: Int
letters = 27
data Op = GoRight | GoLeft | Prev | Next | Take | Loop Program
instance Show Op where
show GoRight = ">"
show GoLeft = "<"
show Prev = "-"
show Next = "+"
show Take = "."
show (Loop prog) = "[" <> show prog <> "]"
newtype Program = Program {unProgram :: [Op]}
instance Semigroup Program where
p1 <> p2 = Program (unProgram p1 <> unProgram p2)
instance Monoid Program where
mempty = Program []
mconcat = Program . foldr ((<>) . unProgram) mempty
instance Show Program where
show = concatMap show . unProgram
data Machine = Machine {mProg :: Program, mRock :: Int, mRocks :: [Int]} deriving (Show)
charToMem :: Int -> Char
charToMem 1 = 'A'
charToMem 2 = 'B'
charToMem 3 = 'C'
charToMem 4 = 'D'
charToMem 5 = 'E'
charToMem 6 = 'F'
charToMem 7 = 'G'
charToMem 8 = 'H'
charToMem 9 = 'I'
charToMem 10 = 'J'
charToMem 11 = 'K'
charToMem 12 = 'L'
charToMem 13 = 'M'
charToMem 14 = 'N'
charToMem 15 = 'O'
charToMem 16 = 'P'
charToMem 17 = 'Q'
charToMem 18 = 'R'
charToMem 19 = 'S'
charToMem 20 = 'T'
charToMem 21 = 'U'
charToMem 22 = 'V'
charToMem 23 = 'W'
charToMem 24 = 'X'
charToMem 25 = 'Y'
charToMem 26 = 'Z'
charToMem _ = ' '
memToChar :: Char -> Int
memToChar 'A' = 1
memToChar 'B' = 2
memToChar 'C' = 3
memToChar 'D' = 4
memToChar 'E' = 5
memToChar 'F' = 6
memToChar 'G' = 7
memToChar 'H' = 8
memToChar 'I' = 9
memToChar 'J' = 10
memToChar 'K' = 11
memToChar 'L' = 12
memToChar 'M' = 13
memToChar 'N' = 14
memToChar 'O' = 15
memToChar 'P' = 16
memToChar 'Q' = 17
memToChar 'R' = 18
memToChar 'S' = 19
memToChar 'T' = 20
memToChar 'U' = 21
memToChar 'V' = 22
memToChar 'W' = 23
memToChar 'X' = 24
memToChar 'Y' = 25
memToChar 'Z' = 26
memToChar _ = 0
goToRock :: Int -> Machine -> Machine
goToRock to m
| from == to = m
| from > to =
m
{ mRock = to,
mProg =
mProg m
<> Program
( if from - to < rocks - from + to
then replicate (from - to) GoLeft
else replicate (rocks - from + to) GoRight
)
}
| otherwise =
m
{ mRock = to,
mProg =
mProg m
<> Program
( if to - from < rocks + from - to
then replicate (to - from) GoRight
else replicate (rocks + from - to) GoLeft
)
}
where
from = mRock m
takeLetter :: Int -> Machine -> Machine
takeLetter l m
| from == to = m {mProg = mProg m <> Program [Take]}
| from > to =
m
{ mRocks = newRocks,
mProg =
mProg m
<> Program
( if from - to < letters - from + to
then replicate (from - to) Prev
else replicate (letters - from + to) Next
)
<> Program [Take]
}
| otherwise =
m
{ mRocks = newRocks,
mProg =
mProg m
<> Program
( if to - from < letters + from - to
then replicate (to - from) Next
else replicate (letters + from - to) Prev
)
<> Program [Take]
}
where
from = mRocks m !! mRock m
to = l
currRocks = mRocks m
newRocks = take (mRock m) currRocks <> (l : drop (mRock m + 1) currRocks)
addLetter :: Int -> Machine -> Machine
addLetter l =
minimumBy (\m1 m2 -> compare (progLength m1) (progLength m2))
. zipWith (\i m -> takeLetter l . goToRock i $ m) [0 .. rocks - 1]
. repeat
where
progLength = length . unProgram . mProg
main :: IO ()
main = do
magicphrase <- map memToChar <$> getLine
print . mProg . foldl (flip addLetter) (Machine (Program []) 0 (replicate rocks 0)) $ magicphrase
return ()
|
bec481c971761e1da3bca75460a7dcfb77ceef7cdff7e226de3f695de47c92b9
|
databrary/databrary
|
ConfigTest.hs
|
{-# LANGUAGE OverloadedStrings #-}
module Store.ConfigTest
where
import Data.Aeson hiding (Value)
import qualified Data.ByteString as BS
import Data.Monoid ((<>))
import qualified Data.Text as T
-- import Test.Tasty
import Test.Tasty.HUnit
import Store.Config
-- example usage; TODO: replace guts with data.yaml
unit_Config_examples :: Assertion
unit_Config_examples = do
pathKey (Path ["k1", "k2"]) @?= "k1.k2"
encode ((mempty :: Config) <> mempty) @?= encode (mempty :: Config)
mempty ! "k1.k2" @?= (Nothing :: Maybe Value)
mempty ! "k1.k2" @?= (Nothing :: Maybe ConfigMap)
encode (mempty ! "k1.k2" :: Maybe Config) @?= encode (Nothing :: Maybe Config)
mempty ! "k1.k2" @?= (Nothing :: Maybe (Maybe Bool))
mempty ! "k1.k2" @?= (Nothing :: Maybe Integer)
mempty ! "k1.k2" @?= (Nothing :: Maybe BS.ByteString)
mempty ! "k1.k2" @?= (Nothing :: Maybe [Integer])
mempty ! "k1.k2" @?= (Nothing :: Maybe T.Text)
mempty ! "k1.k2" @?= (Nothing :: Maybe String)
mempty ! "k1.k2" @?= (Nothing :: Maybe Int)
| null |
https://raw.githubusercontent.com/databrary/databrary/685f3c625b960268f5d9b04e3d7c6146bea5afda/test/Store/ConfigTest.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
import Test.Tasty
example usage; TODO: replace guts with data.yaml
|
module Store.ConfigTest
where
import Data.Aeson hiding (Value)
import qualified Data.ByteString as BS
import Data.Monoid ((<>))
import qualified Data.Text as T
import Test.Tasty.HUnit
import Store.Config
unit_Config_examples :: Assertion
unit_Config_examples = do
pathKey (Path ["k1", "k2"]) @?= "k1.k2"
encode ((mempty :: Config) <> mempty) @?= encode (mempty :: Config)
mempty ! "k1.k2" @?= (Nothing :: Maybe Value)
mempty ! "k1.k2" @?= (Nothing :: Maybe ConfigMap)
encode (mempty ! "k1.k2" :: Maybe Config) @?= encode (Nothing :: Maybe Config)
mempty ! "k1.k2" @?= (Nothing :: Maybe (Maybe Bool))
mempty ! "k1.k2" @?= (Nothing :: Maybe Integer)
mempty ! "k1.k2" @?= (Nothing :: Maybe BS.ByteString)
mempty ! "k1.k2" @?= (Nothing :: Maybe [Integer])
mempty ! "k1.k2" @?= (Nothing :: Maybe T.Text)
mempty ! "k1.k2" @?= (Nothing :: Maybe String)
mempty ! "k1.k2" @?= (Nothing :: Maybe Int)
|
2d705487faa9bc6a04bc62c8cc0df1f00e5bdb1c0a0f21d70a9a361096b50321
|
basho/riak_shell
|
connection_EXT.erl
|
%% -------------------------------------------------------------------
%%
%% connection management extension for riak_shell
%%
Copyright ( c ) 2007 - 2016 Basho Technologies , Inc. All Rights Reserved .
%%
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.
%%
%% -------------------------------------------------------------------
-module(connection_EXT).
-include("riak_shell.hrl").
-export([
help/1
]).
-export([
connect/3,
connection_prompt/3,
ping/2,
ping/3,
reconnect/2,
show_connection/2,
show_cookie/2,
show_nodes/2
]).
-ignore_xref([
connect/3,
connection_prompt/3,
help/1,
ping/2,
ping/3,
reconnect/2,
show_connection/2,
show_cookie/2,
show_nodes/2
]).
help(show_nodes) ->
"Type `show_nodes;` to see which nodes riak-shell is connected to.";
help(show_cookie) ->
"Type `show_cookie;` to see what the Erlang cookie is for riak-shell.~n"
"The riak-shell needs to have the same cookie as the riak nodes you~n"
"are connecting to.";
help(ping) ->
"Typing `ping;` will ping all the nodes specified in the config file~n"
"and print the results. Typing `ping [email protected];` will ping~n"
"a particular node. You need to replace dev1 etc with your actual~n"
"node name";
help(reconnect) ->
"Typing `reconnect;` will try to connect you to one of the nodes~n"
"listed in your riak_shell.config. It will try each node until it~n"
"succeeds (or doesn't).~n~n"
"To connect to a specific node (or one not in your riak_shell.config)~n"
"please use the connect command.";
help(connect) ->
"You can connect to a specific node (whether in your riak_shell.config~n"
"or not) by typing `connect [email protected];` substituting your~n"
"node name for dev1.~n~n"
"You may need to change the Erlang cookie to do this.~n~n"
"See also the `reconnect` command.";
help(connection_prompt) ->
"Type `connection_prompt on;` to display the connection status in~n"
"the prompt, or `connection_prompt off;` to disable it.~n~n"
"Unicode support in your terminal is highly recommended.";
help(show_connection) ->
"This shows which riak node riak-shell is connected to".
show_nodes(Cmd, State) ->
Msg = io_lib:format("The connected nodes are: ~p", [lists:sort(nodes())]),
{Cmd#command{response = Msg}, State}.
show_cookie(Cmd, #state{cookie = Cookie} = State) ->
Msg = io_lib:format("Cookie is ~p [actual ~p]", [Cookie, erlang:get_cookie()]),
{Cmd#command{response = Msg}, State}.
ping(Cmd, #state{config = Config} = State) ->
Nodes = riak_shell:read_config(Config, nodes, []),
FoldFn = fun(Node, Msg) ->
Msg2 = ping_single_node(State, Node),
[Msg2] ++ Msg
end,
Msgs = lists:foldl(FoldFn, [], Nodes),
{Cmd#command{response = string:join(Msgs, "\n"),
log_this_cmd = false}, State}.
ping(Cmd, State, Node) when is_atom(Node) ->
{Cmd#command{response = ping_single_node(State, Node),
log_this_cmd = false}, State};
ping(Cmd, State, Node) when is_list(Node) ->
ping(Cmd, State, list_to_atom(Node));
ping(Cmd, State, Node) ->
Msg = io_lib:format("Error: node has to be a valid node name ~p", [Node]),
{Cmd#command{response = Msg,
cmd_error = true,
log_this_cmd = false}, State}.
ping_single_node(State, Node) ->
{Prefix1, Prefix2} = case State#state.show_connection_status of
true -> {?GREENTICK, ?REDCROSS};
false -> {"", ""}
end,
case net_adm:ping(Node) of
pong -> io_lib:format("~p: " ++ Prefix1 ++ " (connected)", [Node]);
pang -> io_lib:format("~p: " ++ Prefix2 ++ " (disconnected)", [Node])
end.
show_connection(Cmd, #state{has_connection = false} = State) ->
{Cmd#command{response = "riak-shell is not connected to riak"}, State};
show_connection(Cmd, #state{has_connection = true,
connection = {Node, Port}} = State) ->
Msg = io_lib:format("riak-shell is connected to: ~p on port ~p",
[Node, Port]),
{Cmd#command{response = Msg}, State}.
reconnect(Cmd, S) ->
case connection_srv:reconnect() of
{connected, {Node, Port}} ->
Msg = io_lib:format("Reconnected to ~p on port ~p", [Node, Port]),
{Cmd#command{response = Msg}, S#state{has_connection = true,
connection = {Node, Port}}};
disconnected ->
Msg = "Reconnection failed",
{Cmd#command{response = Msg}, S#state{has_connection = false,
connection = none}}
end.
connect(Cmd, S, Node) when is_atom(Node) ->
case connection_srv:connect([Node]) of
{connected, {N, Port}} ->
Msg = io_lib:format("Connected to ~p on port ~p", [N, Port]),
{Cmd#command{response = Msg}, S#state{has_connection = true,
connection = {Node, Port}}};
disconnected ->
Msg = io_lib:format("Connection to ~p failed", [Node]),
{Cmd#command{response = Msg}, S#state{has_connection = false,
connection = none}}
end;
connect(Cmd, S, Node) when is_list(Node) ->
connect(Cmd, S, list_to_atom(Node));
connect(Cmd, State, Node) ->
Msg = io_lib:format("Error: node has to be a valid node name ~p", [Node]),
{Cmd#command{response = Msg,
cmd_error = true}, State}.
connection_prompt(Cmd, State, on) ->
Msg = "Connection Prompt turned on",
{Cmd#command{response = Msg}, State#state{show_connection_status = true}};
connection_prompt(Cmd, State, off) ->
Msg = "Connection Prompt turned off",
{Cmd#command{response = Msg}, State#state{show_connection_status = false}};
connection_prompt(Cmd, State, Toggle) ->
ErrMsg = io_lib:format("Invalid parameter passed to connection_prompt ~p. Should be `off` or `on`.", [Toggle]),
{Cmd#command{response = ErrMsg,
cmd_error = true}, State}.
| null |
https://raw.githubusercontent.com/basho/riak_shell/afc4b7c04925f8accaa5b32ee0253d8c0ddc5000/src/connection_EXT.erl
|
erlang
|
-------------------------------------------------------------------
connection management extension for riak_shell
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.
-------------------------------------------------------------------
|
Copyright ( c ) 2007 - 2016 Basho Technologies , Inc. All Rights Reserved .
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(connection_EXT).
-include("riak_shell.hrl").
-export([
help/1
]).
-export([
connect/3,
connection_prompt/3,
ping/2,
ping/3,
reconnect/2,
show_connection/2,
show_cookie/2,
show_nodes/2
]).
-ignore_xref([
connect/3,
connection_prompt/3,
help/1,
ping/2,
ping/3,
reconnect/2,
show_connection/2,
show_cookie/2,
show_nodes/2
]).
help(show_nodes) ->
"Type `show_nodes;` to see which nodes riak-shell is connected to.";
help(show_cookie) ->
"Type `show_cookie;` to see what the Erlang cookie is for riak-shell.~n"
"The riak-shell needs to have the same cookie as the riak nodes you~n"
"are connecting to.";
help(ping) ->
"Typing `ping;` will ping all the nodes specified in the config file~n"
"and print the results. Typing `ping [email protected];` will ping~n"
"a particular node. You need to replace dev1 etc with your actual~n"
"node name";
help(reconnect) ->
"Typing `reconnect;` will try to connect you to one of the nodes~n"
"listed in your riak_shell.config. It will try each node until it~n"
"succeeds (or doesn't).~n~n"
"To connect to a specific node (or one not in your riak_shell.config)~n"
"please use the connect command.";
help(connect) ->
"You can connect to a specific node (whether in your riak_shell.config~n"
"or not) by typing `connect [email protected];` substituting your~n"
"node name for dev1.~n~n"
"You may need to change the Erlang cookie to do this.~n~n"
"See also the `reconnect` command.";
help(connection_prompt) ->
"Type `connection_prompt on;` to display the connection status in~n"
"the prompt, or `connection_prompt off;` to disable it.~n~n"
"Unicode support in your terminal is highly recommended.";
help(show_connection) ->
"This shows which riak node riak-shell is connected to".
show_nodes(Cmd, State) ->
Msg = io_lib:format("The connected nodes are: ~p", [lists:sort(nodes())]),
{Cmd#command{response = Msg}, State}.
show_cookie(Cmd, #state{cookie = Cookie} = State) ->
Msg = io_lib:format("Cookie is ~p [actual ~p]", [Cookie, erlang:get_cookie()]),
{Cmd#command{response = Msg}, State}.
ping(Cmd, #state{config = Config} = State) ->
Nodes = riak_shell:read_config(Config, nodes, []),
FoldFn = fun(Node, Msg) ->
Msg2 = ping_single_node(State, Node),
[Msg2] ++ Msg
end,
Msgs = lists:foldl(FoldFn, [], Nodes),
{Cmd#command{response = string:join(Msgs, "\n"),
log_this_cmd = false}, State}.
ping(Cmd, State, Node) when is_atom(Node) ->
{Cmd#command{response = ping_single_node(State, Node),
log_this_cmd = false}, State};
ping(Cmd, State, Node) when is_list(Node) ->
ping(Cmd, State, list_to_atom(Node));
ping(Cmd, State, Node) ->
Msg = io_lib:format("Error: node has to be a valid node name ~p", [Node]),
{Cmd#command{response = Msg,
cmd_error = true,
log_this_cmd = false}, State}.
ping_single_node(State, Node) ->
{Prefix1, Prefix2} = case State#state.show_connection_status of
true -> {?GREENTICK, ?REDCROSS};
false -> {"", ""}
end,
case net_adm:ping(Node) of
pong -> io_lib:format("~p: " ++ Prefix1 ++ " (connected)", [Node]);
pang -> io_lib:format("~p: " ++ Prefix2 ++ " (disconnected)", [Node])
end.
show_connection(Cmd, #state{has_connection = false} = State) ->
{Cmd#command{response = "riak-shell is not connected to riak"}, State};
show_connection(Cmd, #state{has_connection = true,
connection = {Node, Port}} = State) ->
Msg = io_lib:format("riak-shell is connected to: ~p on port ~p",
[Node, Port]),
{Cmd#command{response = Msg}, State}.
reconnect(Cmd, S) ->
case connection_srv:reconnect() of
{connected, {Node, Port}} ->
Msg = io_lib:format("Reconnected to ~p on port ~p", [Node, Port]),
{Cmd#command{response = Msg}, S#state{has_connection = true,
connection = {Node, Port}}};
disconnected ->
Msg = "Reconnection failed",
{Cmd#command{response = Msg}, S#state{has_connection = false,
connection = none}}
end.
connect(Cmd, S, Node) when is_atom(Node) ->
case connection_srv:connect([Node]) of
{connected, {N, Port}} ->
Msg = io_lib:format("Connected to ~p on port ~p", [N, Port]),
{Cmd#command{response = Msg}, S#state{has_connection = true,
connection = {Node, Port}}};
disconnected ->
Msg = io_lib:format("Connection to ~p failed", [Node]),
{Cmd#command{response = Msg}, S#state{has_connection = false,
connection = none}}
end;
connect(Cmd, S, Node) when is_list(Node) ->
connect(Cmd, S, list_to_atom(Node));
connect(Cmd, State, Node) ->
Msg = io_lib:format("Error: node has to be a valid node name ~p", [Node]),
{Cmd#command{response = Msg,
cmd_error = true}, State}.
connection_prompt(Cmd, State, on) ->
Msg = "Connection Prompt turned on",
{Cmd#command{response = Msg}, State#state{show_connection_status = true}};
connection_prompt(Cmd, State, off) ->
Msg = "Connection Prompt turned off",
{Cmd#command{response = Msg}, State#state{show_connection_status = false}};
connection_prompt(Cmd, State, Toggle) ->
ErrMsg = io_lib:format("Invalid parameter passed to connection_prompt ~p. Should be `off` or `on`.", [Toggle]),
{Cmd#command{response = ErrMsg,
cmd_error = true}, State}.
|
7d8c732fe5de98a027eaa994d65fe9820b6775f9671058c59d1c11eefa8a2f07
|
master/ejabberd
|
ejabberd_update.erl
|
%%%-------------------------------------------------------------------
File :
Author : < >
%%% Purpose : ejabberd code updater
Created : 27 Jan 2006 by < >
%%%
%%%
ejabberd , Copyright ( C ) 2002 - 2012 ProcessOne
%%%
%%% This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 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
%%% General Public License for more details.
%%%
You should have received a copy of the GNU General Public License
%%% along with this program; if not, write to the Free Software
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
%%%
%%%-------------------------------------------------------------------
-module(ejabberd_update).
-author('').
%% API
-export([update/0, update/1, update_info/0]).
-include("ejabberd.hrl").
%%====================================================================
%% API
%%====================================================================
%% Update all the modified modules
update() ->
case update_info() of
{ok, Dir, _UpdatedBeams, _Script, LowLevelScript, _Check} ->
Eval =
eval_script(
LowLevelScript, [],
[{ejabberd, "", filename:join(Dir, "..")}]),
?DEBUG("eval: ~p~n", [Eval]),
Eval;
{error, Reason} ->
{error, Reason}
end.
%% Update only the specified modules
update(ModulesToUpdate) ->
case update_info() of
{ok, Dir, UpdatedBeamsAll, _Script, _LowLevelScript, _Check} ->
UpdatedBeamsNow =
[A || A <- UpdatedBeamsAll, B <- ModulesToUpdate, A == B],
{_, LowLevelScript, _} = build_script(Dir, UpdatedBeamsNow),
Eval =
eval_script(
LowLevelScript, [],
[{ejabberd, "", filename:join(Dir, "..")}]),
?DEBUG("eval: ~p~n", [Eval]),
Eval;
{error, Reason} ->
{error, Reason}
end.
OTP R14B03 and older provided release_handler_1 : eval_script/3
But OTP R14B04 and newer provide release_handler_1 : eval_script/5
eval_script(Script, Apps, LibDirs) ->
case lists:member({eval_script, 5}, release_handler_1:module_info(exports)) of
true ->
release_handler_1:eval_script(Script, Apps, LibDirs, [], []);
false ->
release_handler_1:eval_script(Script, Apps, LibDirs)
end.
%% Get information about the modified modules
update_info() ->
Dir = filename:dirname(code:which(ejabberd)),
case file:list_dir(Dir) of
{ok, Files} ->
update_info(Dir, Files);
{error, Reason} ->
{error, Reason}
end.
%%--------------------------------------------------------------------
Internal functions
%%--------------------------------------------------------------------
update_info(Dir, Files) ->
Beams = lists:sort(get_beams(Files)),
UpdatedBeams = get_updated_beams(Beams),
?DEBUG("beam files: ~p~n", [UpdatedBeams]),
{Script, LowLevelScript, Check} = build_script(Dir, UpdatedBeams),
{ok, Dir, UpdatedBeams, Script, LowLevelScript, Check}.
get_beams(Files) ->
[list_to_atom(filename:rootname(FN))
|| FN <- Files, lists:suffix(".beam", FN)].
%% Return only the beams that have different version
get_updated_beams(Beams) ->
lists:filter(
fun(Module) ->
NewVsn = get_new_version(Module),
case code:is_loaded(Module) of
{file, _} ->
CurVsn = get_current_version(Module),
(NewVsn /= CurVsn
andalso NewVsn /= unknown_version);
false ->
false
end
end, Beams).
get_new_version(Module) ->
Path = code:which(Module),
VersionRes = beam_lib:version(Path),
case VersionRes of
{ok, {Module, NewVsn}} -> NewVsn;
%% If a m1.erl has -module("m2"):
_ -> unknown_version
end.
get_current_version(Module) ->
Attrs = Module:module_info(attributes),
case lists:keysearch(vsn, 1, Attrs) of
{value, {vsn, CurVsn}} -> CurVsn;
_ -> unknown_version
end.
%% @spec(Dir::string(), UpdatedBeams::[atom()]) -> {Script,LowLevelScript,Check}
build_script(Dir, UpdatedBeams) ->
Script = make_script(UpdatedBeams),
LowLevelScript = make_low_level_script(UpdatedBeams, Script),
Check =
release_handler_1:check_script(
LowLevelScript,
[{ejabberd, "", filename:join(Dir, "..")}]),
case Check of
ok ->
?DEBUG("script: ~p~n", [Script]),
?DEBUG("low level script: ~p~n", [LowLevelScript]),
?DEBUG("check: ~p~n", [Check]);
{ok, []} ->
?DEBUG("script: ~p~n", [Script]),
?DEBUG("low level script: ~p~n", [LowLevelScript]),
?DEBUG("check: ~p~n", [Check]);
_ ->
?ERROR_MSG("script: ~p~n", [Script]),
?ERROR_MSG("low level script: ~p~n", [LowLevelScript]),
?ERROR_MSG("check: ~p~n", [Check])
end,
{Script, LowLevelScript, Check}.
Copied from Erlang / OTP file : lib / sasl / src / systools.hrl
-record(application,
{name, %% Name of the application, atom().
type = permanent, %% Application start type, atom().
vsn = "", %% Version of the application, string().
id = "", %% Id of the application, string().
description = "", %% Description of application, string().
modules = [], %% [Module | {Module,Vsn}] of modules
%% incorporated in the application,
%% Module = atom(), Vsn = string().
uses = [], %% [Application] list of applications required
%% by the application, Application = atom().
includes = [], %% [Application] list of applications included
%% by the application, Application = atom().
regs = [], %% [RegNames] a list of registered process
names used by the application , RegNames =
%% atom().
env = [], %% [{Key,Value}] environment variable of
%% application, Key = Value = term().
time an application may exist ,
%% integer() | infinity.
number of processes in an application ,
%% integer() | infinity.
[ ] | { Mod , } , ( ) ,
= list ( ) .
start_phases = [], %% [] | {Phase, PhaseArgs}, Phase = atom(),
%% PhaseArgs = list().
dir = "" %% The directory where the .app file was
%% found (internal use).
}).
make_script(UpdatedBeams) ->
lists:map(
fun(Module) ->
{ok, {Module, [{attributes, NewAttrs}]}} =
beam_lib:chunks(code:which(Module), [attributes]),
CurAttrs = Module:module_info(attributes),
case lists:keysearch(update_info, 1, NewAttrs) of
{value, {_, [{update, _}]}} ->
case lists:keysearch(update_info, 1, CurAttrs) of
{value, {_, [{update, Extra}]}} ->
{update, Module, {advanced, Extra}};
false ->
{update, Module, {advanced, 0}}
end;
false ->
{load_module, Module}
end
end, UpdatedBeams).
make_low_level_script(UpdatedBeams, Script) ->
EJDApp = #application{name = ejabberd,
modules = UpdatedBeams},
{ok, LowLevelScript} =
systools_rc:translate_scripts([Script], [EJDApp], [EJDApp]),
LowLevelScript.
| null |
https://raw.githubusercontent.com/master/ejabberd/9c31874d5a9d1852ece1b8ae70dd4b7e5eef7cf7/src/ejabberd_update.erl
|
erlang
|
-------------------------------------------------------------------
Purpose : ejabberd code updater
This program is free software; you can redistribute it and/or
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
General Public License for more details.
along with this program; if not, write to the Free Software
-------------------------------------------------------------------
API
====================================================================
API
====================================================================
Update all the modified modules
Update only the specified modules
Get information about the modified modules
--------------------------------------------------------------------
--------------------------------------------------------------------
Return only the beams that have different version
If a m1.erl has -module("m2"):
@spec(Dir::string(), UpdatedBeams::[atom()]) -> {Script,LowLevelScript,Check}
Name of the application, atom().
Application start type, atom().
Version of the application, string().
Id of the application, string().
Description of application, string().
[Module | {Module,Vsn}] of modules
incorporated in the application,
Module = atom(), Vsn = string().
[Application] list of applications required
by the application, Application = atom().
[Application] list of applications included
by the application, Application = atom().
[RegNames] a list of registered process
atom().
[{Key,Value}] environment variable of
application, Key = Value = term().
integer() | infinity.
integer() | infinity.
[] | {Phase, PhaseArgs}, Phase = atom(),
PhaseArgs = list().
The directory where the .app file was
found (internal use).
|
File :
Author : < >
Created : 27 Jan 2006 by < >
ejabberd , Copyright ( C ) 2002 - 2012 ProcessOne
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation ; either version 2 of the
You should have received a copy of the GNU General Public License
Foundation , Inc. , 59 Temple Place , Suite 330 , Boston , MA
02111 - 1307 USA
-module(ejabberd_update).
-author('').
-export([update/0, update/1, update_info/0]).
-include("ejabberd.hrl").
update() ->
case update_info() of
{ok, Dir, _UpdatedBeams, _Script, LowLevelScript, _Check} ->
Eval =
eval_script(
LowLevelScript, [],
[{ejabberd, "", filename:join(Dir, "..")}]),
?DEBUG("eval: ~p~n", [Eval]),
Eval;
{error, Reason} ->
{error, Reason}
end.
update(ModulesToUpdate) ->
case update_info() of
{ok, Dir, UpdatedBeamsAll, _Script, _LowLevelScript, _Check} ->
UpdatedBeamsNow =
[A || A <- UpdatedBeamsAll, B <- ModulesToUpdate, A == B],
{_, LowLevelScript, _} = build_script(Dir, UpdatedBeamsNow),
Eval =
eval_script(
LowLevelScript, [],
[{ejabberd, "", filename:join(Dir, "..")}]),
?DEBUG("eval: ~p~n", [Eval]),
Eval;
{error, Reason} ->
{error, Reason}
end.
OTP R14B03 and older provided release_handler_1 : eval_script/3
But OTP R14B04 and newer provide release_handler_1 : eval_script/5
eval_script(Script, Apps, LibDirs) ->
case lists:member({eval_script, 5}, release_handler_1:module_info(exports)) of
true ->
release_handler_1:eval_script(Script, Apps, LibDirs, [], []);
false ->
release_handler_1:eval_script(Script, Apps, LibDirs)
end.
update_info() ->
Dir = filename:dirname(code:which(ejabberd)),
case file:list_dir(Dir) of
{ok, Files} ->
update_info(Dir, Files);
{error, Reason} ->
{error, Reason}
end.
Internal functions
update_info(Dir, Files) ->
Beams = lists:sort(get_beams(Files)),
UpdatedBeams = get_updated_beams(Beams),
?DEBUG("beam files: ~p~n", [UpdatedBeams]),
{Script, LowLevelScript, Check} = build_script(Dir, UpdatedBeams),
{ok, Dir, UpdatedBeams, Script, LowLevelScript, Check}.
get_beams(Files) ->
[list_to_atom(filename:rootname(FN))
|| FN <- Files, lists:suffix(".beam", FN)].
get_updated_beams(Beams) ->
lists:filter(
fun(Module) ->
NewVsn = get_new_version(Module),
case code:is_loaded(Module) of
{file, _} ->
CurVsn = get_current_version(Module),
(NewVsn /= CurVsn
andalso NewVsn /= unknown_version);
false ->
false
end
end, Beams).
get_new_version(Module) ->
Path = code:which(Module),
VersionRes = beam_lib:version(Path),
case VersionRes of
{ok, {Module, NewVsn}} -> NewVsn;
_ -> unknown_version
end.
get_current_version(Module) ->
Attrs = Module:module_info(attributes),
case lists:keysearch(vsn, 1, Attrs) of
{value, {vsn, CurVsn}} -> CurVsn;
_ -> unknown_version
end.
build_script(Dir, UpdatedBeams) ->
Script = make_script(UpdatedBeams),
LowLevelScript = make_low_level_script(UpdatedBeams, Script),
Check =
release_handler_1:check_script(
LowLevelScript,
[{ejabberd, "", filename:join(Dir, "..")}]),
case Check of
ok ->
?DEBUG("script: ~p~n", [Script]),
?DEBUG("low level script: ~p~n", [LowLevelScript]),
?DEBUG("check: ~p~n", [Check]);
{ok, []} ->
?DEBUG("script: ~p~n", [Script]),
?DEBUG("low level script: ~p~n", [LowLevelScript]),
?DEBUG("check: ~p~n", [Check]);
_ ->
?ERROR_MSG("script: ~p~n", [Script]),
?ERROR_MSG("low level script: ~p~n", [LowLevelScript]),
?ERROR_MSG("check: ~p~n", [Check])
end,
{Script, LowLevelScript, Check}.
Copied from Erlang / OTP file : lib / sasl / src / systools.hrl
-record(application,
names used by the application , RegNames =
time an application may exist ,
number of processes in an application ,
[ ] | { Mod , } , ( ) ,
= list ( ) .
}).
make_script(UpdatedBeams) ->
lists:map(
fun(Module) ->
{ok, {Module, [{attributes, NewAttrs}]}} =
beam_lib:chunks(code:which(Module), [attributes]),
CurAttrs = Module:module_info(attributes),
case lists:keysearch(update_info, 1, NewAttrs) of
{value, {_, [{update, _}]}} ->
case lists:keysearch(update_info, 1, CurAttrs) of
{value, {_, [{update, Extra}]}} ->
{update, Module, {advanced, Extra}};
false ->
{update, Module, {advanced, 0}}
end;
false ->
{load_module, Module}
end
end, UpdatedBeams).
make_low_level_script(UpdatedBeams, Script) ->
EJDApp = #application{name = ejabberd,
modules = UpdatedBeams},
{ok, LowLevelScript} =
systools_rc:translate_scripts([Script], [EJDApp], [EJDApp]),
LowLevelScript.
|
6d8b6c4b4a6d23902e9dda7ee49fa969c4f73d0d5eb213ff9ac948a2ded5e718
|
gowthamk/ocaml-irmin
|
iheap_leftlist.ml
|
open Printf
open Lwt.Infix
open Irmin_unix
module type Config =
sig val root : string val shared : string val init : unit -> unit end
let from_just op msg =
match op with
| Some x -> x
| None -> failwith @@ (msg ^ ": Expected Some. Got None.")
module MakeVersioned(Config:Config)(Atom:Heap_leftlist.ATOM) =
struct
module OM = Heap_leftlist.Make(Atom)
module HeapList = OM
open OM
module K = Irmin.Hash.SHA1
module G = Git_unix.Mem
type node = {
ra: int64 ;
d: Atom.t ;
l: K.t ;
r: K.t }
and madt =
| E
| T of node
module IrminConvert =
struct
let mknode t =
let open Irmin.Type in
(((((record "node"
(fun ra ->
fun d ->
fun l ->
fun r -> { ra; d; l; r }))
|+ (field "ra" int64 (fun t -> t.ra)))
|+ (field "d" Atom.t (fun t -> t.d)))
|+ (field "l" K.t (fun t -> t.l)))
|+ (field "r" K.t (fun t -> t.r)))
|> sealr
and mkmadt node =
let open Irmin.Type in
variant "t" (fun empty node -> function
| E -> empty
| T n -> node n)
|~ case0 "E" E
|~ case1 "T" node (fun x -> T x)
|> sealv
end
module IrminConvertTie =
struct
let () = ()
let () = ()
and (node, madt) =
let open Irmin.Type in
mu2
(fun node ->
fun madt ->
((IrminConvert.mknode madt),
(IrminConvert.mkmadt node)))
end
module AO_value : (Irmin.Contents.Conv with type t = madt) =
struct
type t = madt
let t = IrminConvertTie.madt
let pp = Irmin.Type.pp_json ~minify:false t
let of_string s =
let decoder = Jsonm.decoder (`String s) in
let res =
try Irmin.Type.decode_json t decoder
with
| Invalid_argument s ->
failwith @@
(Printf.sprintf
"AO_Value.of_string: Invalid_argument: %s" s) in
res
end
module AO_store =
struct
module S = Irmin_git.AO(G)(AO_value)
include S
let create config =
let level =
Irmin.Private.Conf.key ~doc:"The Zlib compression level."
"level" (let open Irmin.Private.Conf in some int) None in
let root =
Irmin.Private.Conf.get config Irmin.Private.Conf.root in
let level = Irmin.Private.Conf.get config level in
G.create ?root ?level ()
let create () = create @@ (Irmin_git.config Config.root)
let on_add = ref (fun k v -> (*printf "%s\n"
(Fmt.to_to_string K.pp k); *)
Lwt.return ())
let add t v =
(S.add t v) >>=
(fun k -> ((!on_add) k v) >>= (fun _ -> Lwt.return k))
module PHashtbl = Hashtbl.Make(struct
type t = OM.t
let equal x y = x == y
let hash x = Hashtbl.hash_param 2 10 x
end)
let (read_cache: (K.t, OM.t) Hashtbl.t) = Hashtbl.create 5051
let (write_cache: K.t PHashtbl.t) = PHashtbl.create 5051
let rec add_adt t (a:OM.t) : K.t Lwt.t =
try
Lwt.return @@ PHashtbl.find write_cache a
with Not_found -> begin
add t =<<
(match a with
| OM.E -> Lwt.return @@ E
| OM.T {ra;d;l;r} ->
(add_adt t l >>= fun l' ->
add_adt t r >>= fun r' ->
Lwt.return @@ T {ra; d;
l=l'; r=r'}))
end
let rec read_adt t (k:K.t) : OM.t Lwt.t =
try
Lwt.return @@ Hashtbl.find read_cache k
with Not_found -> begin
find t k >>= fun aop ->
let a = from_just aop "to_adt" in
match a with
| E -> Lwt.return @@ OM.E
| T {ra;d;l;r} ->
(read_adt t l >>= fun l' ->
read_adt t r >>= fun r' ->
Lwt.return @@ OM.T {OM.ra=ra; OM.d=d;
OM.l=l'; OM.r=r'})
end
let read t k =
find t k >>= fun vop ->
Lwt.return @@ from_just vop "AO_store.read"
end
module type IRMIN_STORE_VALUE =
sig
include Irmin.Contents.S
val of_adt : OM.t -> t Lwt.t
val to_adt : t -> OM.t Lwt.t
end
let merge_time = ref 0.0
let merge_count = ref 0
module BC_value =
(struct
include AO_value
let of_adt (a:OM.t) : t Lwt.t =
AO_store.create () >>= fun ao_store ->
let aostore_add adt =
AO_store.add_adt ao_store adt in
match a with
| OM.E -> Lwt.return @@ E
| OM.T {ra;d;l;r} ->
(aostore_add l >>= fun l' ->
aostore_add r >>= fun r' ->
Lwt.return @@ T {ra; d;
l=l'; r=r'})
let to_adt (t:t) : OM.t Lwt.t =
AO_store.create () >>= fun ao_store ->
let aostore_read k =
AO_store.read_adt ao_store k in
match t with
| E -> Lwt.return @@ OM.E
| T {ra;d;l;r} ->
(aostore_read l >>= fun l' ->
aostore_read r >>= fun r' ->
Lwt.return @@ OM.T {ra; d;
OM.l=l'; OM.r=r'})
let rec merge_keys k k1 k2 =
if k = k1 then Lwt.return k2
else if k = k2 then Lwt.return k1
else begin
AO_store.create () >>= fun ao_store ->
AO_store.read ao_store k >>= fun old ->
AO_store.read ao_store k1 >>= fun v1 ->
AO_store.read ao_store k2 >>= fun v2 ->
do_merge old v1 v2 >>= fun v ->
AO_store.add ao_store v
end
and do_merge old v1 v2 =
begin
to_adt old >>= fun old ->
to_adt v1 >>= fun v1 ->
to_adt v2 >>= fun v2 ->
let v = OM.merge3 old v1 v2 in
of_adt v >>= fun merged_k ->
Lwt.return @@ merged_k
end
let rec merge ~old:(old : t Irmin.Merge.promise) (v1 : t)
(v2 : t) =
let _ = Gc.full_major () in
let t1 = Sys.time () in
let res =
if v1 = v2 then Irmin.Merge.ok v1
else begin
let open Irmin.Merge.Infix in
old() >>=* fun old ->
do_merge (from_just old "merge.old")
v1 v2 >>= fun merged_v ->
Irmin.Merge.ok merged_v
end in
let t2 = Sys.time () in
let _ = merge_time := !merge_time +. (t2-.t1) in
let _ = merge_count := !merge_count + 1 in
res
let merge = let open Irmin.Merge in option (v t merge)
end : (IRMIN_STORE_VALUE with type t = madt))
module BC_store =
struct
module Store = (Irmin_unix.Git.Mem.KV)(BC_value)
module Sync = (Irmin.Sync)(Store)
module Head = Store.Head
type t = Store.t
type path = string list
let init ?root ?bare () =
let config = Irmin_git.config Config.root in
Store.Repo.v config
let master (repo : Store.repo) = Store.master repo
let clone t name = Store.clone t name
let get_branch r ~branch_name = Store.of_branch r branch_name
let merge s ~into = Store.merge s ~into
let read t (p : path) = Store.find t p
let string_of_path p = String.concat "/" p
let info s = Irmin_unix.info "[repo %s] %s" Config.root s;;
let rec update ?msg t (p : path) (v : BC_value.t) =
let msg =
match msg with
| Some s -> s
| None -> "Setting " ^ (string_of_path p) in
Store.set t p v ~info:(info msg)
let pp = Fmt.using Store.status Store.Status.pp
end
module Vpst :
sig
type 'a t
type branch
val return : 'a -> 'a t
val bind : 'a t -> ('a -> 'b t) -> 'b t
val with_init_version_do : HeapList.t -> 'a t -> 'a
val fork_version : ?parent:branch -> 'a t -> branch t
val set_parent: branch -> unit t
val get_latest_version : unit -> HeapList.t t
val sync_next_version : ?v:HeapList.t -> HeapList.t t
val liftLwt : 'a Lwt.t -> 'a t
val print_info: unit t
end =
struct
type branch = BC_store.t
type st =
{
master: branch;
parent: branch;
local: branch;
name: string ;
next_id: int }
type 'a t = st -> ('a * st) Lwt.t
let info s = Irmin_unix.info "[repo %s] %s" Config.root s
let path = ["state"]
let return (x : 'a) = (fun st -> Lwt.return (x, st) : 'a t)
let bind (m1 : 'a t) (f : 'a -> 'b t) =
(fun st -> (m1 st) >>= (fun (a, st') -> f a st') : 'b t)
let with_init_version_do (v : HeapList.t) (m : 'a t) =
Lwt_main.run
((BC_store.init ()) >>=
(fun repo ->
(BC_store.master repo) >>=
(fun m_br ->
(BC_value.of_adt v) >>=
(fun (v' : BC_value.t) ->
(BC_store.update ~msg:"initial version" m_br
path v')
>>=
(fun () ->
(BC_store.clone m_br "1_local") >>=
(fun t_br ->
let st =
{
master = m_br;
parent = m_br;
local = t_br;
name = "1";
next_id = 1
} in
(m st) >>=
(fun (a, _) -> Lwt.return a)))))))
let fork_version ?parent (m : 'a t) = fun (st : st) ->
let child_name =
st.name ^ ("_" ^ (string_of_int st.next_id)) in
let m_br = st.master in
BC_store.clone m_br (child_name ^ "_local") >>= fun t_br ->
let p_br = match parent with
| Some br -> br
| None -> st.local in
let new_st = { master = m_br; parent = p_br;
local = t_br; name = child_name;
next_id = 1} in
Lwt.async (fun () -> m new_st);
Lwt.return (t_br, { st with next_id = (st.next_id + 1) })
let get_latest_version () =
(fun (st : st) ->
(BC_store.read st.local path) >>=
(fun (vop : BC_value.t option) ->
let v = from_just vop "get_latest_version" in
(BC_value.to_adt v) >>= (fun td -> Lwt.return (td, st))) :
HeapList.t t)
let set_parent parent = fun (st:st) ->
Lwt.return ((), {st with parent=parent})
let sync_next_version ?v = fun (st:st) ->
try
1 . Commit to the local branch
(match v with
| None -> Lwt.return ()
| Some v ->
BC_value.of_adt v >>= fun v' ->
BC_store.update ~msg:"Committing local state"
st.local path v') >>= fun () ->
2 . Merge parent to the local branch
let cinfo = info "Merging parent into local" in
Lwt_unix.sleep @@ 0.1 *. (float @@ Random.int 20) >>= fun _ ->
BC_store.Head.find st.parent >>= fun commitop ->
let latest_commit = match commitop with
| Some p -> p
| None -> failwith "Parent has no commits!" in
BC_store.Head.merge latest_commit
~into:st.local ~info:cinfo >>= fun _ ->
get_latest_version () st
with _ -> failwith "Some error occured"
let liftLwt (m : 'a Lwt.t) =
(fun st -> m >>= (fun a -> Lwt.return (a, st)) : 'a t)
let print_info = fun (st:st) ->
let str = Fmt.to_to_string BC_store.pp st.local in
let pstr = Fmt.to_to_string BC_store.pp st.parent in
begin
Lwt_io.printf "I am: %s\n My parent: %s\n"
str pstr >>= fun () ->
Lwt.return ((),st)
end
end
end
| null |
https://raw.githubusercontent.com/gowthamk/ocaml-irmin/54775f6c3012e87d2d0308f37a2ec7b27477e887/heap_leftist/mem/iheap_leftlist.ml
|
ocaml
|
printf "%s\n"
(Fmt.to_to_string K.pp k);
|
open Printf
open Lwt.Infix
open Irmin_unix
module type Config =
sig val root : string val shared : string val init : unit -> unit end
let from_just op msg =
match op with
| Some x -> x
| None -> failwith @@ (msg ^ ": Expected Some. Got None.")
module MakeVersioned(Config:Config)(Atom:Heap_leftlist.ATOM) =
struct
module OM = Heap_leftlist.Make(Atom)
module HeapList = OM
open OM
module K = Irmin.Hash.SHA1
module G = Git_unix.Mem
type node = {
ra: int64 ;
d: Atom.t ;
l: K.t ;
r: K.t }
and madt =
| E
| T of node
module IrminConvert =
struct
let mknode t =
let open Irmin.Type in
(((((record "node"
(fun ra ->
fun d ->
fun l ->
fun r -> { ra; d; l; r }))
|+ (field "ra" int64 (fun t -> t.ra)))
|+ (field "d" Atom.t (fun t -> t.d)))
|+ (field "l" K.t (fun t -> t.l)))
|+ (field "r" K.t (fun t -> t.r)))
|> sealr
and mkmadt node =
let open Irmin.Type in
variant "t" (fun empty node -> function
| E -> empty
| T n -> node n)
|~ case0 "E" E
|~ case1 "T" node (fun x -> T x)
|> sealv
end
module IrminConvertTie =
struct
let () = ()
let () = ()
and (node, madt) =
let open Irmin.Type in
mu2
(fun node ->
fun madt ->
((IrminConvert.mknode madt),
(IrminConvert.mkmadt node)))
end
module AO_value : (Irmin.Contents.Conv with type t = madt) =
struct
type t = madt
let t = IrminConvertTie.madt
let pp = Irmin.Type.pp_json ~minify:false t
let of_string s =
let decoder = Jsonm.decoder (`String s) in
let res =
try Irmin.Type.decode_json t decoder
with
| Invalid_argument s ->
failwith @@
(Printf.sprintf
"AO_Value.of_string: Invalid_argument: %s" s) in
res
end
module AO_store =
struct
module S = Irmin_git.AO(G)(AO_value)
include S
let create config =
let level =
Irmin.Private.Conf.key ~doc:"The Zlib compression level."
"level" (let open Irmin.Private.Conf in some int) None in
let root =
Irmin.Private.Conf.get config Irmin.Private.Conf.root in
let level = Irmin.Private.Conf.get config level in
G.create ?root ?level ()
let create () = create @@ (Irmin_git.config Config.root)
Lwt.return ())
let add t v =
(S.add t v) >>=
(fun k -> ((!on_add) k v) >>= (fun _ -> Lwt.return k))
module PHashtbl = Hashtbl.Make(struct
type t = OM.t
let equal x y = x == y
let hash x = Hashtbl.hash_param 2 10 x
end)
let (read_cache: (K.t, OM.t) Hashtbl.t) = Hashtbl.create 5051
let (write_cache: K.t PHashtbl.t) = PHashtbl.create 5051
let rec add_adt t (a:OM.t) : K.t Lwt.t =
try
Lwt.return @@ PHashtbl.find write_cache a
with Not_found -> begin
add t =<<
(match a with
| OM.E -> Lwt.return @@ E
| OM.T {ra;d;l;r} ->
(add_adt t l >>= fun l' ->
add_adt t r >>= fun r' ->
Lwt.return @@ T {ra; d;
l=l'; r=r'}))
end
let rec read_adt t (k:K.t) : OM.t Lwt.t =
try
Lwt.return @@ Hashtbl.find read_cache k
with Not_found -> begin
find t k >>= fun aop ->
let a = from_just aop "to_adt" in
match a with
| E -> Lwt.return @@ OM.E
| T {ra;d;l;r} ->
(read_adt t l >>= fun l' ->
read_adt t r >>= fun r' ->
Lwt.return @@ OM.T {OM.ra=ra; OM.d=d;
OM.l=l'; OM.r=r'})
end
let read t k =
find t k >>= fun vop ->
Lwt.return @@ from_just vop "AO_store.read"
end
module type IRMIN_STORE_VALUE =
sig
include Irmin.Contents.S
val of_adt : OM.t -> t Lwt.t
val to_adt : t -> OM.t Lwt.t
end
let merge_time = ref 0.0
let merge_count = ref 0
module BC_value =
(struct
include AO_value
let of_adt (a:OM.t) : t Lwt.t =
AO_store.create () >>= fun ao_store ->
let aostore_add adt =
AO_store.add_adt ao_store adt in
match a with
| OM.E -> Lwt.return @@ E
| OM.T {ra;d;l;r} ->
(aostore_add l >>= fun l' ->
aostore_add r >>= fun r' ->
Lwt.return @@ T {ra; d;
l=l'; r=r'})
let to_adt (t:t) : OM.t Lwt.t =
AO_store.create () >>= fun ao_store ->
let aostore_read k =
AO_store.read_adt ao_store k in
match t with
| E -> Lwt.return @@ OM.E
| T {ra;d;l;r} ->
(aostore_read l >>= fun l' ->
aostore_read r >>= fun r' ->
Lwt.return @@ OM.T {ra; d;
OM.l=l'; OM.r=r'})
let rec merge_keys k k1 k2 =
if k = k1 then Lwt.return k2
else if k = k2 then Lwt.return k1
else begin
AO_store.create () >>= fun ao_store ->
AO_store.read ao_store k >>= fun old ->
AO_store.read ao_store k1 >>= fun v1 ->
AO_store.read ao_store k2 >>= fun v2 ->
do_merge old v1 v2 >>= fun v ->
AO_store.add ao_store v
end
and do_merge old v1 v2 =
begin
to_adt old >>= fun old ->
to_adt v1 >>= fun v1 ->
to_adt v2 >>= fun v2 ->
let v = OM.merge3 old v1 v2 in
of_adt v >>= fun merged_k ->
Lwt.return @@ merged_k
end
let rec merge ~old:(old : t Irmin.Merge.promise) (v1 : t)
(v2 : t) =
let _ = Gc.full_major () in
let t1 = Sys.time () in
let res =
if v1 = v2 then Irmin.Merge.ok v1
else begin
let open Irmin.Merge.Infix in
old() >>=* fun old ->
do_merge (from_just old "merge.old")
v1 v2 >>= fun merged_v ->
Irmin.Merge.ok merged_v
end in
let t2 = Sys.time () in
let _ = merge_time := !merge_time +. (t2-.t1) in
let _ = merge_count := !merge_count + 1 in
res
let merge = let open Irmin.Merge in option (v t merge)
end : (IRMIN_STORE_VALUE with type t = madt))
module BC_store =
struct
module Store = (Irmin_unix.Git.Mem.KV)(BC_value)
module Sync = (Irmin.Sync)(Store)
module Head = Store.Head
type t = Store.t
type path = string list
let init ?root ?bare () =
let config = Irmin_git.config Config.root in
Store.Repo.v config
let master (repo : Store.repo) = Store.master repo
let clone t name = Store.clone t name
let get_branch r ~branch_name = Store.of_branch r branch_name
let merge s ~into = Store.merge s ~into
let read t (p : path) = Store.find t p
let string_of_path p = String.concat "/" p
let info s = Irmin_unix.info "[repo %s] %s" Config.root s;;
let rec update ?msg t (p : path) (v : BC_value.t) =
let msg =
match msg with
| Some s -> s
| None -> "Setting " ^ (string_of_path p) in
Store.set t p v ~info:(info msg)
let pp = Fmt.using Store.status Store.Status.pp
end
module Vpst :
sig
type 'a t
type branch
val return : 'a -> 'a t
val bind : 'a t -> ('a -> 'b t) -> 'b t
val with_init_version_do : HeapList.t -> 'a t -> 'a
val fork_version : ?parent:branch -> 'a t -> branch t
val set_parent: branch -> unit t
val get_latest_version : unit -> HeapList.t t
val sync_next_version : ?v:HeapList.t -> HeapList.t t
val liftLwt : 'a Lwt.t -> 'a t
val print_info: unit t
end =
struct
type branch = BC_store.t
type st =
{
master: branch;
parent: branch;
local: branch;
name: string ;
next_id: int }
type 'a t = st -> ('a * st) Lwt.t
let info s = Irmin_unix.info "[repo %s] %s" Config.root s
let path = ["state"]
let return (x : 'a) = (fun st -> Lwt.return (x, st) : 'a t)
let bind (m1 : 'a t) (f : 'a -> 'b t) =
(fun st -> (m1 st) >>= (fun (a, st') -> f a st') : 'b t)
let with_init_version_do (v : HeapList.t) (m : 'a t) =
Lwt_main.run
((BC_store.init ()) >>=
(fun repo ->
(BC_store.master repo) >>=
(fun m_br ->
(BC_value.of_adt v) >>=
(fun (v' : BC_value.t) ->
(BC_store.update ~msg:"initial version" m_br
path v')
>>=
(fun () ->
(BC_store.clone m_br "1_local") >>=
(fun t_br ->
let st =
{
master = m_br;
parent = m_br;
local = t_br;
name = "1";
next_id = 1
} in
(m st) >>=
(fun (a, _) -> Lwt.return a)))))))
let fork_version ?parent (m : 'a t) = fun (st : st) ->
let child_name =
st.name ^ ("_" ^ (string_of_int st.next_id)) in
let m_br = st.master in
BC_store.clone m_br (child_name ^ "_local") >>= fun t_br ->
let p_br = match parent with
| Some br -> br
| None -> st.local in
let new_st = { master = m_br; parent = p_br;
local = t_br; name = child_name;
next_id = 1} in
Lwt.async (fun () -> m new_st);
Lwt.return (t_br, { st with next_id = (st.next_id + 1) })
let get_latest_version () =
(fun (st : st) ->
(BC_store.read st.local path) >>=
(fun (vop : BC_value.t option) ->
let v = from_just vop "get_latest_version" in
(BC_value.to_adt v) >>= (fun td -> Lwt.return (td, st))) :
HeapList.t t)
let set_parent parent = fun (st:st) ->
Lwt.return ((), {st with parent=parent})
let sync_next_version ?v = fun (st:st) ->
try
1 . Commit to the local branch
(match v with
| None -> Lwt.return ()
| Some v ->
BC_value.of_adt v >>= fun v' ->
BC_store.update ~msg:"Committing local state"
st.local path v') >>= fun () ->
2 . Merge parent to the local branch
let cinfo = info "Merging parent into local" in
Lwt_unix.sleep @@ 0.1 *. (float @@ Random.int 20) >>= fun _ ->
BC_store.Head.find st.parent >>= fun commitop ->
let latest_commit = match commitop with
| Some p -> p
| None -> failwith "Parent has no commits!" in
BC_store.Head.merge latest_commit
~into:st.local ~info:cinfo >>= fun _ ->
get_latest_version () st
with _ -> failwith "Some error occured"
let liftLwt (m : 'a Lwt.t) =
(fun st -> m >>= (fun a -> Lwt.return (a, st)) : 'a t)
let print_info = fun (st:st) ->
let str = Fmt.to_to_string BC_store.pp st.local in
let pstr = Fmt.to_to_string BC_store.pp st.parent in
begin
Lwt_io.printf "I am: %s\n My parent: %s\n"
str pstr >>= fun () ->
Lwt.return ((),st)
end
end
end
|
34236221cd1f26e96430bf92a2b09f61c13740dbfd1a330db519661d15e9eedd
|
Dexterminator/clj-templates
|
server.clj
|
(ns clj-templates.server
(:require [integrant.core :as ig]
[environ.core :refer [env]]
[ring.adapter.jetty :refer [run-jetty]]))
(defmethod ig/init-key :server/jetty [_ {:keys [handler opts]}]
(run-jetty handler (assoc opts :port (Integer/parseInt (env :port)))))
(defmethod ig/halt-key! :server/jetty [_ server]
(.stop server))
| null |
https://raw.githubusercontent.com/Dexterminator/clj-templates/705e652fece2455257e5008c12c712bb9f7802d1/src/clj/clj_templates/server.clj
|
clojure
|
(ns clj-templates.server
(:require [integrant.core :as ig]
[environ.core :refer [env]]
[ring.adapter.jetty :refer [run-jetty]]))
(defmethod ig/init-key :server/jetty [_ {:keys [handler opts]}]
(run-jetty handler (assoc opts :port (Integer/parseInt (env :port)))))
(defmethod ig/halt-key! :server/jetty [_ server]
(.stop server))
|
|
e3768e0cf6ff1c001597247cd23b08d5a02501486fd28fd2e694e3954a12987a
|
helmutkian/cl-react
|
example.lisp
|
(defun ajax (&key (type "GET") (cache t) url data success error)
(chain $
(ajax (create :url url
:type type
:cache cache
:data-type "json"
:data data
:success success
:error error))))
(define-class comment-box
(:load-comments-from-server
(lambda ()
(ajax :url (@ this props url)
:data-type "json"
:cache false
:success (bind-lambda (data) (set-state :data data))
:error (bind-lambda (xhr status err)
(chain console
(error (@ this props url)
status
(chain err (to-string))))))))
(:handle-comment-submit
(lambda (comment)
(let* ((comments (@ this state data))
(new-comments (append comments (array comment))))
(set-state :data new-comments)
(ajax :url (@ this props url)
:type "POST"
:data comment
:success (bind-lambda (data) (set-state :data data))
:error (bind-lambda (xhr status err)
(chain console
(error (@ this props url)
status
(chain err (to-string)))))))))
(:get-initial-state
(lambda ()
(create :data (array))))
(:component-did-mount
(lambda ()
(chain this (load-comments-from-server))
(set-interval (@ this load-comments-from-server)
(@ this props poll-interval))))
(:render
(lambda ()
(psx (:div :class "commentBox"
(:h1 "Comments")
(:comment-list :data (@ this state data))
(:comment-form :on-comment-submit (@ this handle-comment-submit)))))))
| null |
https://raw.githubusercontent.com/helmutkian/cl-react/f6c2af7cbd4ad70e3cba6c7e6f9ef789d73bca2b/example.lisp
|
lisp
|
(defun ajax (&key (type "GET") (cache t) url data success error)
(chain $
(ajax (create :url url
:type type
:cache cache
:data-type "json"
:data data
:success success
:error error))))
(define-class comment-box
(:load-comments-from-server
(lambda ()
(ajax :url (@ this props url)
:data-type "json"
:cache false
:success (bind-lambda (data) (set-state :data data))
:error (bind-lambda (xhr status err)
(chain console
(error (@ this props url)
status
(chain err (to-string))))))))
(:handle-comment-submit
(lambda (comment)
(let* ((comments (@ this state data))
(new-comments (append comments (array comment))))
(set-state :data new-comments)
(ajax :url (@ this props url)
:type "POST"
:data comment
:success (bind-lambda (data) (set-state :data data))
:error (bind-lambda (xhr status err)
(chain console
(error (@ this props url)
status
(chain err (to-string)))))))))
(:get-initial-state
(lambda ()
(create :data (array))))
(:component-did-mount
(lambda ()
(chain this (load-comments-from-server))
(set-interval (@ this load-comments-from-server)
(@ this props poll-interval))))
(:render
(lambda ()
(psx (:div :class "commentBox"
(:h1 "Comments")
(:comment-list :data (@ this state data))
(:comment-form :on-comment-submit (@ this handle-comment-submit)))))))
|
|
62eee70e523497c3035d13428fda2d74b55c3ed6c4eb74a7411648655b4a67a5
|
eamsden/Animas
|
AFRPTestsCOC.hs
|
$ I d : AFRPTestsCOC.hs , v 1.2 2003/11/10 21:28:58 antony Exp $
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* A F R P *
* *
* Module : AFRPTestsCOC *
* Purpose : Test cases for collection - oriented combinators *
* Authors : and *
* *
* Copyright ( c ) Yale University , 2003 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
******************************************************************************
* A F R P *
* *
* Module: AFRPTestsCOC *
* Purpose: Test cases for collection-oriented combinators *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module AFRPTestsCOC (coc_tr, coc_trs) where
import FRP.Yampa
import AFRPTestsCommon
------------------------------------------------------------------------------
-- Test cases for collection-oriented combinators
------------------------------------------------------------------------------
coc_inp1 = deltaEncode 0.1 [0.0, 0.5 ..]
coc_t0 :: [[Double]]
coc_t0 = take 20 $ embed (parB [constant 1.0, identity, integral]) coc_inp1
coc_t0r =
[[1.0, 0.0, 0.00],
[1.0, 0.5, 0.00],
[1.0, 1.0, 0.05],
[1.0, 1.5, 0.15],
[1.0, 2.0, 0.30],
[1.0, 2.5, 0.50],
[1.0, 3.0, 0.75],
[1.0, 3.5, 1.05],
[1.0, 4.0, 1.40],
[1.0, 4.5, 1.80],
[1.0, 5.0, 2.25],
[1.0, 5.5, 2.75],
[1.0, 6.0, 3.30],
[1.0, 6.5, 3.90],
[1.0, 7.0, 4.55],
[1.0, 7.5, 5.25],
[1.0, 8.0, 6.00],
[1.0, 8.5, 6.80],
[1.0, 9.0, 7.65],
[1.0, 9.5, 8.55]]
coc_trs =
[ coc_t0 ~= coc_t0r
]
coc_tr = and coc_trs
| null |
https://raw.githubusercontent.com/eamsden/Animas/2404d1de20982a337109fc6032cb77b022514f9d/tests/AFRPTestsCOC.hs
|
haskell
|
----------------------------------------------------------------------------
Test cases for collection-oriented combinators
----------------------------------------------------------------------------
|
$ I d : AFRPTestsCOC.hs , v 1.2 2003/11/10 21:28:58 antony Exp $
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* A F R P *
* *
* Module : AFRPTestsCOC *
* Purpose : Test cases for collection - oriented combinators *
* Authors : and *
* *
* Copyright ( c ) Yale University , 2003 *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
******************************************************************************
* A F R P *
* *
* Module: AFRPTestsCOC *
* Purpose: Test cases for collection-oriented combinators *
* Authors: Antony Courtney and Henrik Nilsson *
* *
* Copyright (c) Yale University, 2003 *
* *
******************************************************************************
-}
module AFRPTestsCOC (coc_tr, coc_trs) where
import FRP.Yampa
import AFRPTestsCommon
coc_inp1 = deltaEncode 0.1 [0.0, 0.5 ..]
coc_t0 :: [[Double]]
coc_t0 = take 20 $ embed (parB [constant 1.0, identity, integral]) coc_inp1
coc_t0r =
[[1.0, 0.0, 0.00],
[1.0, 0.5, 0.00],
[1.0, 1.0, 0.05],
[1.0, 1.5, 0.15],
[1.0, 2.0, 0.30],
[1.0, 2.5, 0.50],
[1.0, 3.0, 0.75],
[1.0, 3.5, 1.05],
[1.0, 4.0, 1.40],
[1.0, 4.5, 1.80],
[1.0, 5.0, 2.25],
[1.0, 5.5, 2.75],
[1.0, 6.0, 3.30],
[1.0, 6.5, 3.90],
[1.0, 7.0, 4.55],
[1.0, 7.5, 5.25],
[1.0, 8.0, 6.00],
[1.0, 8.5, 6.80],
[1.0, 9.0, 7.65],
[1.0, 9.5, 8.55]]
coc_trs =
[ coc_t0 ~= coc_t0r
]
coc_tr = and coc_trs
|
6ceeae22db451d99bb0e4717324895206f19fd73ce5f010b9797880ad0ed8dc6
|
spectrum-finance/cardano-dex-contracts
|
Deposit.hs
|
# LANGUAGE TemplateHaskell #
# LANGUAGE UndecidableInstances #
module ErgoDex.Contracts.Proxy.Deposit where
import PlutusLedgerApi.V1.Crypto (PubKeyHash)
import PlutusLedgerApi.V1.Value
import qualified PlutusTx
import PlutusTx.Builtins
data DepositConfig = DepositConfig
{ poolNft :: AssetClass
, tokenA :: AssetClass
, tokenB :: AssetClass
, tokenLp :: AssetClass
, exFee :: Integer
, rewardPkh :: PubKeyHash
, stakePkh :: Maybe PubKeyHash
, collateralAda :: Integer
}
deriving stock (Show)
PlutusTx.makeIsDataIndexed ''DepositConfig [('DepositConfig, 0)]
| null |
https://raw.githubusercontent.com/spectrum-finance/cardano-dex-contracts/87bdbc26dbe9ae5f6c59e608d728330f8166f19c/cardano-dex-contracts-onchain/ErgoDex/Contracts/Proxy/Deposit.hs
|
haskell
|
# LANGUAGE TemplateHaskell #
# LANGUAGE UndecidableInstances #
module ErgoDex.Contracts.Proxy.Deposit where
import PlutusLedgerApi.V1.Crypto (PubKeyHash)
import PlutusLedgerApi.V1.Value
import qualified PlutusTx
import PlutusTx.Builtins
data DepositConfig = DepositConfig
{ poolNft :: AssetClass
, tokenA :: AssetClass
, tokenB :: AssetClass
, tokenLp :: AssetClass
, exFee :: Integer
, rewardPkh :: PubKeyHash
, stakePkh :: Maybe PubKeyHash
, collateralAda :: Integer
}
deriving stock (Show)
PlutusTx.makeIsDataIndexed ''DepositConfig [('DepositConfig, 0)]
|
|
89ae75a2023ad45cd0a98a3102b62e642fc9843fd8ea2026b0a3d8696597d5d2
|
TomerAberbach/programming-in-haskell-exercises
|
2-and-3.hs
|
grid :: Int -> Int -> [(Int, Int)]
grid m n = [(x, y) | x <- [0..m], y <- [0..n]]
square :: Int -> [(Int, Int)]
square n = [(x, y) | (x, y) <- grid n n, x /= y]
| null |
https://raw.githubusercontent.com/TomerAberbach/programming-in-haskell-exercises/a66830529ebc9c4d84d0e4c6e0ad58041b46bc32/parts/1/chapters/5/2-and-3.hs
|
haskell
|
grid :: Int -> Int -> [(Int, Int)]
grid m n = [(x, y) | x <- [0..m], y <- [0..n]]
square :: Int -> [(Int, Int)]
square n = [(x, y) | (x, y) <- grid n n, x /= y]
|
|
a6af74469b93e383023bf828ba98be072991b179fbd70def8e635879dc1d5e33
|
kpblc2000/KpblcLispLib
|
_kpblc-get-objectid-for-field.lsp
|
(defun _kpblc-get-objectid-for-field (obj / str)
;|
* Ïîëó÷åíèå ñòðîêîâîãî ïðåäñòàâëåíèÿ îáúåêòà äëÿ èñïîëüçîâàíèÿ â ïîëÿõ. Ðàáîòàåò òîëüêî â òåêóùåì äîêóìåíòå
* Ïàðàìåòðû âûçîâà:
óêàçàòåëü íà
* Ïðèìåðû âûçîâà:
(_kpblc-get-objectid-for-field (car (entsel)))
|;
(if (and (setq obj (_kpblc-conv-ent-to-ename obj))
(setq str (cadr (_kpblc-conv-string-to-list (vl-princ-to-string obj) ":")))
) ;_ end of and
(vl-string-trim ":<>" str)
) ;_ end of if
) ;_ end of defun
| null |
https://raw.githubusercontent.com/kpblc2000/KpblcLispLib/49d1d9d29078b4167cc65dc881bea61b706c620d/lsp/get/objectid/_kpblc-get-objectid-for-field.lsp
|
lisp
|
|
_ end of and
_ end of if
_ end of defun
|
(defun _kpblc-get-objectid-for-field (obj / str)
* Ïîëó÷åíèå ñòðîêîâîãî ïðåäñòàâëåíèÿ îáúåêòà äëÿ èñïîëüçîâàíèÿ â ïîëÿõ. Ðàáîòàåò òîëüêî â òåêóùåì äîêóìåíòå
* Ïàðàìåòðû âûçîâà:
óêàçàòåëü íà
* Ïðèìåðû âûçîâà:
(_kpblc-get-objectid-for-field (car (entsel)))
(if (and (setq obj (_kpblc-conv-ent-to-ename obj))
(setq str (cadr (_kpblc-conv-string-to-list (vl-princ-to-string obj) ":")))
(vl-string-trim ":<>" str)
|
09b562795db2d10b802116eb39b1abe4c6cb1fc6207152b24c8c813ffe30c886
|
takeoutweight/clojure-scheme
|
keyword_other.cljs
|
(ns cljs.keyword-other)
(defn foo [a b]
(+ a b))
| null |
https://raw.githubusercontent.com/takeoutweight/clojure-scheme/6121de1690a6a52c7dbbe7fa722aaf3ddd4920dd/test/cljs/cljs/keyword_other.cljs
|
clojure
|
(ns cljs.keyword-other)
(defn foo [a b]
(+ a b))
|
|
9da2fbb6dbd4a9f577de5620a209c82aec202a343bbb95d1c479180c9c80ed51
|
buildsome/buildsome
|
ScanFileUpwards.hs
|
module Lib.ScanFileUpwards (scanFileUpwards) where
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Except
import Data.Foldable (traverse_)
import Lib.FilePath (FilePath, (</>))
import qualified Lib.FilePath as FilePath
import qualified System.Posix.ByteString as Posix
import Prelude.Compat hiding (FilePath)
scanFileUpwards :: FilePath -> IO (Maybe FilePath)
scanFileUpwards name = do
cwd <- Posix.getWorkingDirectory
let
-- NOTE: Excludes root (which is probably fine)
parents = takeWhile (/= "/") $ iterate FilePath.takeDirectory cwd
candidates = map (</> name) parents
-- Use EitherT with Left short-circuiting when found, and Right
-- falling through to the end of the loop:
res <- runExceptT $ traverse_ check candidates
case res of
Left found -> Just <$> FilePath.makeRelativeToCurrentDirectory found
Right () -> pure Nothing
where
check path = do
exists <- liftIO $ FilePath.exists path
when exists $ throwE path
| null |
https://raw.githubusercontent.com/buildsome/buildsome/479b92bb74a474a5f0c3292b79202cc850bd8653/src/Lib/ScanFileUpwards.hs
|
haskell
|
NOTE: Excludes root (which is probably fine)
Use EitherT with Left short-circuiting when found, and Right
falling through to the end of the loop:
|
module Lib.ScanFileUpwards (scanFileUpwards) where
import Control.Monad (when)
import Control.Monad.IO.Class (liftIO)
import Control.Monad.Trans.Except
import Data.Foldable (traverse_)
import Lib.FilePath (FilePath, (</>))
import qualified Lib.FilePath as FilePath
import qualified System.Posix.ByteString as Posix
import Prelude.Compat hiding (FilePath)
scanFileUpwards :: FilePath -> IO (Maybe FilePath)
scanFileUpwards name = do
cwd <- Posix.getWorkingDirectory
let
parents = takeWhile (/= "/") $ iterate FilePath.takeDirectory cwd
candidates = map (</> name) parents
res <- runExceptT $ traverse_ check candidates
case res of
Left found -> Just <$> FilePath.makeRelativeToCurrentDirectory found
Right () -> pure Nothing
where
check path = do
exists <- liftIO $ FilePath.exists path
when exists $ throwE path
|
cdd3ebc63ae30e3f41b288c497864dd83b91a089c429d67acd300d7c64e01a10
|
shentufoundation/deepsea
|
Integers.ml
|
open BinInt
open BinNums
open BinPos
open Coqlib
open Datatypes
open List0
open Specif
open Zpower
type comparison =
| Ceq
| Cne
| Clt
| Cle
| Cgt
| Cge
module type WORDSIZE =
sig
val wordsize : nat
end
module Make =
functor (WS:WORDSIZE) ->
struct
* val wordsize : *
let wordsize =
WS.wordsize
(** val zwordsize : coq_Z **)
let zwordsize =
Z.of_nat wordsize
(** val modulus : coq_Z **)
let modulus =
two_power_nat wordsize
* : coq_Z *
let half_modulus =
Z.div modulus (Zpos (Coq_xO Coq_xH))
(** val max_unsigned : coq_Z **)
let max_unsigned =
Z.sub modulus (Zpos Coq_xH)
(** val max_signed : coq_Z **)
let max_signed =
Z.sub half_modulus (Zpos Coq_xH)
(** val min_signed : coq_Z **)
let min_signed =
Z.opp half_modulus
type int = coq_Z
(* singleton inductive, whose constructor was mkint *)
* intval : int - > coq_Z *
let intval i =
i
(** val coq_P_mod_two_p : positive -> nat -> coq_Z **)
let rec coq_P_mod_two_p p = function
| O -> Z0
| S m ->
(match p with
| Coq_xI q -> Z.succ_double (coq_P_mod_two_p q m)
| Coq_xO q -> Z.double (coq_P_mod_two_p q m)
| Coq_xH -> Zpos Coq_xH)
(** val coq_Z_mod_modulus : coq_Z -> coq_Z **)
let coq_Z_mod_modulus = function
| Z0 -> Z0
| Zpos p -> coq_P_mod_two_p p wordsize
| Zneg p ->
let r = coq_P_mod_two_p p wordsize in
(match zeq r Z0 with
| Coq_left -> Z0
| Coq_right -> Z.sub modulus r)
* unsigned : int - > coq_Z *
let unsigned =
intval
* signed : int - > coq_Z *
let signed n =
let x = unsigned n in
(match zlt x half_modulus with
| Coq_left -> x
| Coq_right -> Z.sub x modulus)
* repr : coq_Z - > int *
let repr =
coq_Z_mod_modulus
* val zero : int *
let zero =
repr Z0
(** val one : int **)
let one =
repr (Zpos Coq_xH)
(** val mone : int **)
let mone =
repr (Zneg Coq_xH)
(** val iwordsize : int **)
let iwordsize =
repr zwordsize
(** val eq_dec : int -> int -> sumbool **)
let eq_dec =
zeq
* eq : int - > int - > bool *
let eq x y =
match zeq (unsigned x) (unsigned y) with
| Coq_left -> Coq_true
| Coq_right -> Coq_false
(** val lt : int -> int -> bool **)
let lt x y =
match zlt (signed x) (signed y) with
| Coq_left -> Coq_true
| Coq_right -> Coq_false
(** val ltu : int -> int -> bool **)
let ltu x y =
match zlt (unsigned x) (unsigned y) with
| Coq_left -> Coq_true
| Coq_right -> Coq_false
(** val neg : int -> int **)
let neg x =
repr (Z.opp (unsigned x))
* add : int - > int - > int *
let add x y =
repr (Z.add (unsigned x) (unsigned y))
(** val sub : int -> int -> int **)
let sub x y =
repr (Z.sub (unsigned x) (unsigned y))
* : int - > int - > int *
let mul x y =
repr (Z.mul (unsigned x) (unsigned y))
* : int - > int - > int *
let divs x y =
repr (Z.quot (signed x) (signed y))
(** val mods : int -> int -> int **)
let mods x y =
repr (Z.rem (signed x) (signed y))
* divu : int - > int - > int *
let divu x y =
repr (Z.div (unsigned x) (unsigned y))
(** val modu : int -> int -> int **)
let modu x y =
repr (Z.modulo (unsigned x) (unsigned y))
* coq_and : int - > int - > int *
let coq_and x y =
repr (Z.coq_land (unsigned x) (unsigned y))
* coq_or : int - > int - > int *
let coq_or x y =
repr (Z.coq_lor (unsigned x) (unsigned y))
(** val xor : int -> int -> int **)
let xor x y =
repr (Z.coq_lxor (unsigned x) (unsigned y))
(** val not : int -> int **)
let not x =
xor x mone
* : int - > int - > int *
let shl x y =
repr (Z.shiftl (unsigned x) (unsigned y))
* : int - > int - > int *
let shru x y =
repr (Z.shiftr (unsigned x) (unsigned y))
* : int - > int - > int *
let shr x y =
repr (Z.shiftr (signed x) (unsigned y))
* rol : int - > int - > int *
let rol x y =
let n = Z.modulo (unsigned y) zwordsize in
repr
(Z.coq_lor (Z.shiftl (unsigned x) n)
(Z.shiftr (unsigned x) (Z.sub zwordsize n)))
* : int - > int - > int *
let ror x y =
let n = Z.modulo (unsigned y) zwordsize in
repr
(Z.coq_lor (Z.shiftr (unsigned x) n)
(Z.shiftl (unsigned x) (Z.sub zwordsize n)))
(** val rolm : int -> int -> int -> int **)
let rolm x a m =
coq_and (rol x a) m
* shrx : int - > int - > int *
let shrx x y =
divs x (shl one y)
* : int - > int - > int *
let mulhu x y =
repr (Z.div (Z.mul (unsigned x) (unsigned y)) modulus)
(** val mulhs : int -> int -> int **)
let mulhs x y =
repr (Z.div (Z.mul (signed x) (signed y)) modulus)
(** val negative : int -> int **)
let negative x =
match lt x zero with
| Coq_true -> one
| Coq_false -> zero
* : int - > int - > int - > int *
let add_carry x y cin =
match zlt (Z.add (Z.add (unsigned x) (unsigned y)) (unsigned cin)) modulus with
| Coq_left -> zero
| Coq_right -> one
(** val add_overflow : int -> int -> int -> int **)
let add_overflow x y cin =
let s = Z.add (Z.add (signed x) (signed y)) (signed cin) in
(match match proj_sumbool (zle min_signed s) with
| Coq_true -> proj_sumbool (zle s max_signed)
| Coq_false -> Coq_false with
| Coq_true -> zero
| Coq_false -> one)
* sub_borrow : int - > int - > int - > int *
let sub_borrow x y bin =
match zlt (Z.sub (Z.sub (unsigned x) (unsigned y)) (unsigned bin)) Z0 with
| Coq_left -> one
| Coq_right -> zero
* : int - > int - > int - > int *
let sub_overflow x y bin =
let s = Z.sub (Z.sub (signed x) (signed y)) (signed bin) in
(match match proj_sumbool (zle min_signed s) with
| Coq_true -> proj_sumbool (zle s max_signed)
| Coq_false -> Coq_false with
| Coq_true -> zero
| Coq_false -> one)
* shr_carry : int - > int - > int *
let shr_carry x y =
match match lt x zero with
| Coq_true -> negb (eq (coq_and x (sub (shl one y) one)) zero)
| Coq_false -> Coq_false with
| Coq_true -> one
| Coq_false -> zero
(** val coq_Zshiftin : bool -> coq_Z -> coq_Z **)
let coq_Zshiftin b x =
match b with
| Coq_true -> Z.succ_double x
| Coq_false -> Z.double x
* coq_Zzero_ext : coq_Z - > coq_Z - > coq_Z *
let coq_Zzero_ext n x =
Z.iter n (fun rec0 x0 -> coq_Zshiftin (Z.odd x0) (rec0 (Z.div2 x0)))
(fun _ -> Z0) x
* coq_Zsign_ext : coq_Z - > coq_Z - > coq_Z *
let coq_Zsign_ext n x =
Z.iter (Z.pred n) (fun rec0 x0 ->
coq_Zshiftin (Z.odd x0) (rec0 (Z.div2 x0))) (fun x0 ->
match Z.odd x0 with
| Coq_true -> Zneg Coq_xH
| Coq_false -> Z0) x
(** val zero_ext : coq_Z -> int -> int **)
let zero_ext n x =
repr (coq_Zzero_ext n (unsigned x))
* sign_ext : coq_Z - > int - > int *
let sign_ext n x =
repr (coq_Zsign_ext n (unsigned x))
* coq_Z_one_bits : - > coq_Z - > coq_Z - > coq_Z list *
let rec coq_Z_one_bits n x i =
match n with
| O -> Coq_nil
| S m ->
(match Z.odd x with
| Coq_true ->
Coq_cons (i, (coq_Z_one_bits m (Z.div2 x) (Z.add i (Zpos Coq_xH))))
| Coq_false -> coq_Z_one_bits m (Z.div2 x) (Z.add i (Zpos Coq_xH)))
(** val one_bits : int -> int list **)
let one_bits x =
map repr (coq_Z_one_bits wordsize (unsigned x) Z0)
(** val is_power2 : int -> int option **)
let is_power2 x =
match coq_Z_one_bits wordsize (unsigned x) Z0 with
| Coq_nil -> None
| Coq_cons (i, l) ->
(match l with
| Coq_nil -> Some (repr i)
| Coq_cons (_, _) -> None)
* cmp : comparison - > int - > int - > bool *
let cmp c x y =
match c with
| Ceq -> eq x y
| Cne -> negb (eq x y)
| Clt -> lt x y
| Cle -> negb (lt y x)
| Cgt -> lt y x
| Cge -> negb (lt x y)
* : comparison - > int - > int - > bool *
let cmpu c x y =
match c with
| Ceq -> eq x y
| Cne -> negb (eq x y)
| Clt -> ltu x y
| Cle -> negb (ltu y x)
| Cgt -> ltu y x
| Cge -> negb (ltu x y)
* val : int - > int *
let notbool x =
match eq x zero with
| Coq_true -> one
| Coq_false -> zero
* : int - > int - > int - > ( int , int ) prod option *
let divmodu2 nhi nlo d =
match eq_dec d zero with
| Coq_left -> None
| Coq_right ->
let Coq_pair (q, r) =
Z.div_eucl (Z.add (Z.mul (unsigned nhi) modulus) (unsigned nlo))
(unsigned d)
in
(match zle q max_unsigned with
| Coq_left -> Some (Coq_pair ((repr q), (repr r)))
| Coq_right -> None)
(** val divmods2 : int -> int -> int -> (int, int) prod option **)
let divmods2 nhi nlo d =
match eq_dec d zero with
| Coq_left -> None
| Coq_right ->
let Coq_pair (q, r) =
Z.quotrem (Z.add (Z.mul (signed nhi) modulus) (unsigned nlo))
(signed d)
in
(match match proj_sumbool (zle min_signed q) with
| Coq_true -> proj_sumbool (zle q max_signed)
| Coq_false -> Coq_false with
| Coq_true -> Some (Coq_pair ((repr q), (repr r)))
| Coq_false -> None)
* : int - > coq_Z - > bool *
let testbit x i =
Z.testbit (unsigned x) i
* : coq_Z list - > coq_Z *
let rec powerserie = function
| Coq_nil -> Z0
| Coq_cons (x, xs) -> Z.add (two_p x) (powerserie xs)
* int_of_one_bits : int list - > int *
let rec int_of_one_bits = function
| Coq_nil -> zero
| Coq_cons (a, b) -> add (shl one a) (int_of_one_bits b)
* no_overlap : int - > coq_Z - > int - > coq_Z - > bool *
let no_overlap ofs1 sz1 ofs2 sz2 =
let x1 = unsigned ofs1 in
let x2 = unsigned ofs2 in
(match match proj_sumbool (zlt (Z.add x1 sz1) modulus) with
| Coq_true -> proj_sumbool (zlt (Z.add x2 sz2) modulus)
| Coq_false -> Coq_false with
| Coq_true ->
(match proj_sumbool (zle (Z.add x1 sz1) x2) with
| Coq_true -> Coq_true
| Coq_false -> proj_sumbool (zle (Z.add x2 sz2) x1))
| Coq_false -> Coq_false)
* coq_Zsize : coq_Z - > coq_Z *
let coq_Zsize = function
| Zpos p -> Zpos (Pos.size p)
| _ -> Z0
(** val size : int -> coq_Z **)
let size x =
coq_Zsize (unsigned x)
end
module Wordsize_32 =
struct
* val wordsize : *
let wordsize =
S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S O)))))))))))))))))))))))))))))))
end
module Int = Make(Wordsize_32)
module Wordsize_256 =
struct
* val wordsize : *
let wordsize =
S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
O)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
end
module Int256 = Make(Wordsize_256)
| null |
https://raw.githubusercontent.com/shentufoundation/deepsea/970576a97c8992655ed2f173f576502d73b827e1/src/backend/extraction/Integers.ml
|
ocaml
|
* val zwordsize : coq_Z *
* val modulus : coq_Z *
* val max_unsigned : coq_Z *
* val max_signed : coq_Z *
* val min_signed : coq_Z *
singleton inductive, whose constructor was mkint
* val coq_P_mod_two_p : positive -> nat -> coq_Z *
* val coq_Z_mod_modulus : coq_Z -> coq_Z *
* val one : int *
* val mone : int *
* val iwordsize : int *
* val eq_dec : int -> int -> sumbool *
* val lt : int -> int -> bool *
* val ltu : int -> int -> bool *
* val neg : int -> int *
* val sub : int -> int -> int *
* val mods : int -> int -> int *
* val modu : int -> int -> int *
* val xor : int -> int -> int *
* val not : int -> int *
* val rolm : int -> int -> int -> int *
* val mulhs : int -> int -> int *
* val negative : int -> int *
* val add_overflow : int -> int -> int -> int *
* val coq_Zshiftin : bool -> coq_Z -> coq_Z *
* val zero_ext : coq_Z -> int -> int *
* val one_bits : int -> int list *
* val is_power2 : int -> int option *
* val divmods2 : int -> int -> int -> (int, int) prod option *
* val size : int -> coq_Z *
|
open BinInt
open BinNums
open BinPos
open Coqlib
open Datatypes
open List0
open Specif
open Zpower
type comparison =
| Ceq
| Cne
| Clt
| Cle
| Cgt
| Cge
module type WORDSIZE =
sig
val wordsize : nat
end
module Make =
functor (WS:WORDSIZE) ->
struct
* val wordsize : *
let wordsize =
WS.wordsize
let zwordsize =
Z.of_nat wordsize
let modulus =
two_power_nat wordsize
* : coq_Z *
let half_modulus =
Z.div modulus (Zpos (Coq_xO Coq_xH))
let max_unsigned =
Z.sub modulus (Zpos Coq_xH)
let max_signed =
Z.sub half_modulus (Zpos Coq_xH)
let min_signed =
Z.opp half_modulus
type int = coq_Z
* intval : int - > coq_Z *
let intval i =
i
let rec coq_P_mod_two_p p = function
| O -> Z0
| S m ->
(match p with
| Coq_xI q -> Z.succ_double (coq_P_mod_two_p q m)
| Coq_xO q -> Z.double (coq_P_mod_two_p q m)
| Coq_xH -> Zpos Coq_xH)
let coq_Z_mod_modulus = function
| Z0 -> Z0
| Zpos p -> coq_P_mod_two_p p wordsize
| Zneg p ->
let r = coq_P_mod_two_p p wordsize in
(match zeq r Z0 with
| Coq_left -> Z0
| Coq_right -> Z.sub modulus r)
* unsigned : int - > coq_Z *
let unsigned =
intval
* signed : int - > coq_Z *
let signed n =
let x = unsigned n in
(match zlt x half_modulus with
| Coq_left -> x
| Coq_right -> Z.sub x modulus)
* repr : coq_Z - > int *
let repr =
coq_Z_mod_modulus
* val zero : int *
let zero =
repr Z0
let one =
repr (Zpos Coq_xH)
let mone =
repr (Zneg Coq_xH)
let iwordsize =
repr zwordsize
let eq_dec =
zeq
* eq : int - > int - > bool *
let eq x y =
match zeq (unsigned x) (unsigned y) with
| Coq_left -> Coq_true
| Coq_right -> Coq_false
let lt x y =
match zlt (signed x) (signed y) with
| Coq_left -> Coq_true
| Coq_right -> Coq_false
let ltu x y =
match zlt (unsigned x) (unsigned y) with
| Coq_left -> Coq_true
| Coq_right -> Coq_false
let neg x =
repr (Z.opp (unsigned x))
* add : int - > int - > int *
let add x y =
repr (Z.add (unsigned x) (unsigned y))
let sub x y =
repr (Z.sub (unsigned x) (unsigned y))
* : int - > int - > int *
let mul x y =
repr (Z.mul (unsigned x) (unsigned y))
* : int - > int - > int *
let divs x y =
repr (Z.quot (signed x) (signed y))
let mods x y =
repr (Z.rem (signed x) (signed y))
* divu : int - > int - > int *
let divu x y =
repr (Z.div (unsigned x) (unsigned y))
let modu x y =
repr (Z.modulo (unsigned x) (unsigned y))
* coq_and : int - > int - > int *
let coq_and x y =
repr (Z.coq_land (unsigned x) (unsigned y))
* coq_or : int - > int - > int *
let coq_or x y =
repr (Z.coq_lor (unsigned x) (unsigned y))
let xor x y =
repr (Z.coq_lxor (unsigned x) (unsigned y))
let not x =
xor x mone
* : int - > int - > int *
let shl x y =
repr (Z.shiftl (unsigned x) (unsigned y))
* : int - > int - > int *
let shru x y =
repr (Z.shiftr (unsigned x) (unsigned y))
* : int - > int - > int *
let shr x y =
repr (Z.shiftr (signed x) (unsigned y))
* rol : int - > int - > int *
let rol x y =
let n = Z.modulo (unsigned y) zwordsize in
repr
(Z.coq_lor (Z.shiftl (unsigned x) n)
(Z.shiftr (unsigned x) (Z.sub zwordsize n)))
* : int - > int - > int *
let ror x y =
let n = Z.modulo (unsigned y) zwordsize in
repr
(Z.coq_lor (Z.shiftr (unsigned x) n)
(Z.shiftl (unsigned x) (Z.sub zwordsize n)))
let rolm x a m =
coq_and (rol x a) m
* shrx : int - > int - > int *
let shrx x y =
divs x (shl one y)
* : int - > int - > int *
let mulhu x y =
repr (Z.div (Z.mul (unsigned x) (unsigned y)) modulus)
let mulhs x y =
repr (Z.div (Z.mul (signed x) (signed y)) modulus)
let negative x =
match lt x zero with
| Coq_true -> one
| Coq_false -> zero
* : int - > int - > int - > int *
let add_carry x y cin =
match zlt (Z.add (Z.add (unsigned x) (unsigned y)) (unsigned cin)) modulus with
| Coq_left -> zero
| Coq_right -> one
let add_overflow x y cin =
let s = Z.add (Z.add (signed x) (signed y)) (signed cin) in
(match match proj_sumbool (zle min_signed s) with
| Coq_true -> proj_sumbool (zle s max_signed)
| Coq_false -> Coq_false with
| Coq_true -> zero
| Coq_false -> one)
* sub_borrow : int - > int - > int - > int *
let sub_borrow x y bin =
match zlt (Z.sub (Z.sub (unsigned x) (unsigned y)) (unsigned bin)) Z0 with
| Coq_left -> one
| Coq_right -> zero
* : int - > int - > int - > int *
let sub_overflow x y bin =
let s = Z.sub (Z.sub (signed x) (signed y)) (signed bin) in
(match match proj_sumbool (zle min_signed s) with
| Coq_true -> proj_sumbool (zle s max_signed)
| Coq_false -> Coq_false with
| Coq_true -> zero
| Coq_false -> one)
* shr_carry : int - > int - > int *
let shr_carry x y =
match match lt x zero with
| Coq_true -> negb (eq (coq_and x (sub (shl one y) one)) zero)
| Coq_false -> Coq_false with
| Coq_true -> one
| Coq_false -> zero
let coq_Zshiftin b x =
match b with
| Coq_true -> Z.succ_double x
| Coq_false -> Z.double x
* coq_Zzero_ext : coq_Z - > coq_Z - > coq_Z *
let coq_Zzero_ext n x =
Z.iter n (fun rec0 x0 -> coq_Zshiftin (Z.odd x0) (rec0 (Z.div2 x0)))
(fun _ -> Z0) x
* coq_Zsign_ext : coq_Z - > coq_Z - > coq_Z *
let coq_Zsign_ext n x =
Z.iter (Z.pred n) (fun rec0 x0 ->
coq_Zshiftin (Z.odd x0) (rec0 (Z.div2 x0))) (fun x0 ->
match Z.odd x0 with
| Coq_true -> Zneg Coq_xH
| Coq_false -> Z0) x
let zero_ext n x =
repr (coq_Zzero_ext n (unsigned x))
* sign_ext : coq_Z - > int - > int *
let sign_ext n x =
repr (coq_Zsign_ext n (unsigned x))
* coq_Z_one_bits : - > coq_Z - > coq_Z - > coq_Z list *
let rec coq_Z_one_bits n x i =
match n with
| O -> Coq_nil
| S m ->
(match Z.odd x with
| Coq_true ->
Coq_cons (i, (coq_Z_one_bits m (Z.div2 x) (Z.add i (Zpos Coq_xH))))
| Coq_false -> coq_Z_one_bits m (Z.div2 x) (Z.add i (Zpos Coq_xH)))
let one_bits x =
map repr (coq_Z_one_bits wordsize (unsigned x) Z0)
let is_power2 x =
match coq_Z_one_bits wordsize (unsigned x) Z0 with
| Coq_nil -> None
| Coq_cons (i, l) ->
(match l with
| Coq_nil -> Some (repr i)
| Coq_cons (_, _) -> None)
* cmp : comparison - > int - > int - > bool *
let cmp c x y =
match c with
| Ceq -> eq x y
| Cne -> negb (eq x y)
| Clt -> lt x y
| Cle -> negb (lt y x)
| Cgt -> lt y x
| Cge -> negb (lt x y)
* : comparison - > int - > int - > bool *
let cmpu c x y =
match c with
| Ceq -> eq x y
| Cne -> negb (eq x y)
| Clt -> ltu x y
| Cle -> negb (ltu y x)
| Cgt -> ltu y x
| Cge -> negb (ltu x y)
* val : int - > int *
let notbool x =
match eq x zero with
| Coq_true -> one
| Coq_false -> zero
* : int - > int - > int - > ( int , int ) prod option *
let divmodu2 nhi nlo d =
match eq_dec d zero with
| Coq_left -> None
| Coq_right ->
let Coq_pair (q, r) =
Z.div_eucl (Z.add (Z.mul (unsigned nhi) modulus) (unsigned nlo))
(unsigned d)
in
(match zle q max_unsigned with
| Coq_left -> Some (Coq_pair ((repr q), (repr r)))
| Coq_right -> None)
let divmods2 nhi nlo d =
match eq_dec d zero with
| Coq_left -> None
| Coq_right ->
let Coq_pair (q, r) =
Z.quotrem (Z.add (Z.mul (signed nhi) modulus) (unsigned nlo))
(signed d)
in
(match match proj_sumbool (zle min_signed q) with
| Coq_true -> proj_sumbool (zle q max_signed)
| Coq_false -> Coq_false with
| Coq_true -> Some (Coq_pair ((repr q), (repr r)))
| Coq_false -> None)
* : int - > coq_Z - > bool *
let testbit x i =
Z.testbit (unsigned x) i
* : coq_Z list - > coq_Z *
let rec powerserie = function
| Coq_nil -> Z0
| Coq_cons (x, xs) -> Z.add (two_p x) (powerserie xs)
* int_of_one_bits : int list - > int *
let rec int_of_one_bits = function
| Coq_nil -> zero
| Coq_cons (a, b) -> add (shl one a) (int_of_one_bits b)
* no_overlap : int - > coq_Z - > int - > coq_Z - > bool *
let no_overlap ofs1 sz1 ofs2 sz2 =
let x1 = unsigned ofs1 in
let x2 = unsigned ofs2 in
(match match proj_sumbool (zlt (Z.add x1 sz1) modulus) with
| Coq_true -> proj_sumbool (zlt (Z.add x2 sz2) modulus)
| Coq_false -> Coq_false with
| Coq_true ->
(match proj_sumbool (zle (Z.add x1 sz1) x2) with
| Coq_true -> Coq_true
| Coq_false -> proj_sumbool (zle (Z.add x2 sz2) x1))
| Coq_false -> Coq_false)
* coq_Zsize : coq_Z - > coq_Z *
let coq_Zsize = function
| Zpos p -> Zpos (Pos.size p)
| _ -> Z0
let size x =
coq_Zsize (unsigned x)
end
module Wordsize_32 =
struct
* val wordsize : *
let wordsize =
S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S O)))))))))))))))))))))))))))))))
end
module Int = Make(Wordsize_32)
module Wordsize_256 =
struct
* val wordsize : *
let wordsize =
S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
(S (S (S (S (S (S (S (S (S (S (S (S (S (S (S
O)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))
end
module Int256 = Make(Wordsize_256)
|
7b48aa804201b2276a8b19a79144ea831c5a46895cacb26bb785d201ff2a3ec6
|
johnwhitington/ocamli
|
example03.ml
|
let rec take n l =
if n = 0 then [] else
match l with
h::t -> h :: take (n - 1) t
let rec drop n l =
if n = 0 then l else
match l with
h::t -> drop (n - 1) t
let rec length x =
match x with
[] -> 0
| _::t -> 1 + length t
let rec merge x y =
match x, y with
[], l -> l
| l, [] -> l
| hx::tx, hy::ty ->
if hx < hy
then hx :: merge tx (hy :: ty)
else hy :: merge (hx :: tx) ty
let rec msort l =
match l with
[] -> []
| [x] -> [x]
| _ ->
let left = take (length l / 2) l
and right = drop (length l / 2) l in
merge (msort left) (msort right)
| null |
https://raw.githubusercontent.com/johnwhitington/ocamli/28da5d87478a51583a6cb792bf3a8ee44b990e9f/OCaml%20from%20the%20Very%20Beginning/Chapter%205/example03.ml
|
ocaml
|
let rec take n l =
if n = 0 then [] else
match l with
h::t -> h :: take (n - 1) t
let rec drop n l =
if n = 0 then l else
match l with
h::t -> drop (n - 1) t
let rec length x =
match x with
[] -> 0
| _::t -> 1 + length t
let rec merge x y =
match x, y with
[], l -> l
| l, [] -> l
| hx::tx, hy::ty ->
if hx < hy
then hx :: merge tx (hy :: ty)
else hy :: merge (hx :: tx) ty
let rec msort l =
match l with
[] -> []
| [x] -> [x]
| _ ->
let left = take (length l / 2) l
and right = drop (length l / 2) l in
merge (msort left) (msort right)
|
|
f1bee4da49189d50af94075cb64916d7bd0e6c37eda45a461748cd8c0c8641f4
|
cyverse-archive/DiscoveryEnvironmentBackend
|
thread_context.clj
|
(ns service-logging.thread-context
(:import [org.slf4j MDC]))
(defn set-context!
"set-context! puts the data from the context-map into the current thread's
context."
[context-map]
(if (map? context-map)
(doall (map (fn [[k# v#]] (MDC/put (name k#) (str v#))) context-map))))
(defn clear-context!
"clear-context! clears out context map from the context. This should be
used when the thread is about to be either shut down or returned to a thread
pool."
[]
(MDC/clear))
(defn set-ext-svc-tag!
"Sets a value in the logging context which communicates the the operations in the current context
are from the designated external service.
It is suggested that this key only be set within the scope of a 'with-logging-context' call. This
is to ensure that the key will be automatically removed when the 'with-logging-context' macro
restores the original logging context."
[tag]
(MDC/put "ext_service" tag))
;; With thanks to -example-logback-integration/
(defmacro with-logging-context
"Use this to add a map to any logging wrapped in the macro. Macro can be nested.
(with-logging-context {:key \"value\"} (log/info \"yay\"))
"
[context & body]
`(let [wrapped-context# ~context
ctx# (MDC/getCopyOfContextMap)]
(try
(set-context! wrapped-context#)
~@body
(finally
(if ctx#
(MDC/setContextMap ctx#)
(clear-context!))))))
| null |
https://raw.githubusercontent.com/cyverse-archive/DiscoveryEnvironmentBackend/7f6177078c1a1cb6d11e62f12cfe2e22d669635b/libs/service-logging/src/service_logging/thread_context.clj
|
clojure
|
With thanks to -example-logback-integration/
|
(ns service-logging.thread-context
(:import [org.slf4j MDC]))
(defn set-context!
"set-context! puts the data from the context-map into the current thread's
context."
[context-map]
(if (map? context-map)
(doall (map (fn [[k# v#]] (MDC/put (name k#) (str v#))) context-map))))
(defn clear-context!
"clear-context! clears out context map from the context. This should be
used when the thread is about to be either shut down or returned to a thread
pool."
[]
(MDC/clear))
(defn set-ext-svc-tag!
"Sets a value in the logging context which communicates the the operations in the current context
are from the designated external service.
It is suggested that this key only be set within the scope of a 'with-logging-context' call. This
is to ensure that the key will be automatically removed when the 'with-logging-context' macro
restores the original logging context."
[tag]
(MDC/put "ext_service" tag))
(defmacro with-logging-context
"Use this to add a map to any logging wrapped in the macro. Macro can be nested.
(with-logging-context {:key \"value\"} (log/info \"yay\"))
"
[context & body]
`(let [wrapped-context# ~context
ctx# (MDC/getCopyOfContextMap)]
(try
(set-context! wrapped-context#)
~@body
(finally
(if ctx#
(MDC/setContextMap ctx#)
(clear-context!))))))
|
45c6f01e5e8601f2f5b848d02acb8ee07e4f6496b780460e343640c6d94250a3
|
boris-ci/boris
|
Arbitrary.hs
|
{-# LANGUAGE GADTs #-}
# LANGUAGE NoImplicitPrelude #
{-# LANGUAGE OverloadedStrings #-}
# OPTIONS_GHC -fno - warn - orphans #
module Test.Boris.Queue.Arbitrary where
import Boris.Core.Data
import Boris.Queue
import P
import Test.Boris.Core.Arbitrary ()
import Test.QuickCheck
import Test.QuickCheck.Instances ()
instance Arbitrary RequestBuild where
arbitrary =
RequestBuild
<$> arbitrary
<*> arbitrary
<*> (Repository <$> arbitrary)
<*> arbitrary
<*> oneof [fmap (Just . Ref) arbitrary, pure Nothing]
instance Arbitrary RequestDiscover where
arbitrary =
RequestDiscover
<$> arbitrary
<*> arbitrary
<*> (Repository <$> arbitrary)
instance Arbitrary Request where
arbitrary =
oneof [
RequestDiscover' <$> arbitrary
, RequestBuild' <$> arbitrary
]
| null |
https://raw.githubusercontent.com/boris-ci/boris/c321187490afc889bf281442ac4ef9398b77b200/boris-queue/test/Test/Boris/Queue/Arbitrary.hs
|
haskell
|
# LANGUAGE GADTs #
# LANGUAGE OverloadedStrings #
|
# LANGUAGE NoImplicitPrelude #
# OPTIONS_GHC -fno - warn - orphans #
module Test.Boris.Queue.Arbitrary where
import Boris.Core.Data
import Boris.Queue
import P
import Test.Boris.Core.Arbitrary ()
import Test.QuickCheck
import Test.QuickCheck.Instances ()
instance Arbitrary RequestBuild where
arbitrary =
RequestBuild
<$> arbitrary
<*> arbitrary
<*> (Repository <$> arbitrary)
<*> arbitrary
<*> oneof [fmap (Just . Ref) arbitrary, pure Nothing]
instance Arbitrary RequestDiscover where
arbitrary =
RequestDiscover
<$> arbitrary
<*> arbitrary
<*> (Repository <$> arbitrary)
instance Arbitrary Request where
arbitrary =
oneof [
RequestDiscover' <$> arbitrary
, RequestBuild' <$> arbitrary
]
|
efdcd0e2ce669498764d4c846dee653f5f485ee9b2b979cbf370052fdafb9fb6
|
vernemq/vernemq
|
vmq_storage_engine_leveldb.erl
|
Copyright 2019 Octavo Labs AG Zurich Switzerland ( )
%%
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(vmq_storage_engine_leveldb).
-export([open/2, close/1, write/2, read/2, fold/3, fold/4]).
-record(state, {
ref :: undefined | eleveldb:db_ref(),
data_root :: string(),
open_opts = [],
config :: config(),
read_opts = [],
write_opts = [],
fold_opts = [{fill_cache, false}]
}).
-type state() :: #state{}.
-type config() :: [{atom(), term()}].
-type key() :: binary().
-type value() :: binary().
-type write_op() :: {put, key(), value()} | {delete, key()}.
% API
open(DataRoot, Opts) ->
RetriesLeft = proplists:get_value(open_retries, Opts, 30),
State = init_state(DataRoot, Opts),
open_db(Opts, State, max(1, RetriesLeft), undefined).
-spec write(state(), [write_op()]) -> ok.
write(#state{ref=EngineRef, write_opts=WriteOpts}, WriteOps) ->
eleveldb:write(EngineRef, WriteOps, WriteOpts).
-spec read(state(), key()) -> {ok, value()} | not_found.
read(#state{ref=EngineRef, read_opts=ReadOpts}, Key) ->
eleveldb:get(EngineRef, Key, ReadOpts).
fold(#state{ref=EngineRef, fold_opts=FoldOpts}, Fun, Acc) ->
{ok, Itr} = eleveldb:iterator(EngineRef, FoldOpts),
fold_iterate(eleveldb:iterator_move(Itr, first), Itr, Fun, Acc).
fold(#state{ref=EngineRef, fold_opts=FoldOpts}, Fun, Acc, FirstKey) ->
{ok, Itr} = eleveldb:iterator(EngineRef, FoldOpts),
fold_iterate(eleveldb:iterator_move(Itr, FirstKey), Itr, Fun, Acc).
fold_iterate({error, _}, _Itr, _Fun, Acc) ->
%% no need to close the iterator
Acc;
fold_iterate({ok, Key, Value}, Itr, Fun, Acc0) ->
try Fun(Key, Value, Acc0) of
Acc1 ->
fold_iterate(eleveldb:iterator_move(Itr, prefetch), Itr, Fun, Acc1)
catch
throw:_Throw ->
eleveldb:iterator_close(Itr),
Acc0
end.
close(#state{ref=EngineRef}) ->
eleveldb:close(EngineRef).
Internal
init_state(DataRoot, Config) ->
%% Get the data root directory
filelib:ensure_dir(filename:join(DataRoot, "msg_store_dummy")),
%% Merge the proplist passed in from Config with any values specified by the
%% eleveldb app level; precedence is given to the Config.
MergedConfig = orddict:merge(fun(_K, VLocal, _VGlobal) -> VLocal end,
orddict:from_list(Config), % Local
orddict:from_list(application:get_all_env(eleveldb))), % Global
%% Use a variable write buffer size in order to reduce the number
%% of vnodes that try to kick off compaction at the same time
%% under heavy uniform load...
WriteBufferMin = config_value(write_buffer_size_min, MergedConfig, 30 * 1024 * 1024),
WriteBufferMax = config_value(write_buffer_size_max, MergedConfig, 60 * 1024 * 1024),
WriteBufferSize = WriteBufferMin + rand:uniform(1 + WriteBufferMax - WriteBufferMin),
%% Update the write buffer size in the merged config and make sure create_if_missing is set
%% to true
FinalConfig = orddict:store(write_buffer_size, WriteBufferSize,
orddict:store(create_if_missing, true, MergedConfig)),
Parse out the open / read / write options
{OpenOpts, _BadOpenOpts} = eleveldb:validate_options(open, FinalConfig),
{ReadOpts, _BadReadOpts} = eleveldb:validate_options(read, FinalConfig),
{WriteOpts, _BadWriteOpts} = eleveldb:validate_options(write, FinalConfig),
%% Use read options for folding, but FORCE fill_cache to false
FoldOpts = lists:keystore(fill_cache, 1, ReadOpts, {fill_cache, false}),
%% Warn if block_size is set
SSTBS = proplists:get_value(sst_block_size, OpenOpts, false),
BS = proplists:get_value(block_size, OpenOpts, false),
case BS /= false andalso SSTBS == false of
true ->
lager:warning("eleveldb block_size has been renamed sst_block_size "
"and the current setting of ~p is being ignored. "
"Changing sst_block_size is strongly cautioned "
"against unless you know what you are doing. Remove "
"block_size from app.config to get rid of this "
"message.\n", [BS]);
_ ->
ok
end,
%% Generate a debug message with the options we'll use for each operation
lager:debug("datadir ~s options for LevelDB: ~p\n",
[DataRoot, [{open, OpenOpts}, {read, ReadOpts}, {write, WriteOpts}, {fold, FoldOpts}]]),
#state { data_root = DataRoot,
open_opts = OpenOpts,
read_opts = ReadOpts,
write_opts = WriteOpts,
fold_opts = FoldOpts,
config = FinalConfig }.
config_value(Key, Config, Default) ->
case orddict:find(Key, Config) of
error ->
Default;
{ok, Value} ->
Value
end.
open_db(_Opts, _State0, 0, LastError) ->
{error, LastError};
open_db(Opts, State0, RetriesLeft, _) ->
DataRoot = State0#state.data_root,
case eleveldb:open(DataRoot, State0#state.open_opts) of
{ok, Ref} ->
lager:info("Opening LevelDB database at ~p~n", [DataRoot]),
{ok, State0#state { ref = Ref }};
%% Check specifically for lock error, this can be caused if
%% a crashed instance takes some time to flush leveldb information
out to disk . The process is gone , but the NIF resource cleanup
%% may not have completed.
{error, {db_open, OpenErr}=Reason} ->
case lists:prefix("Corruption: truncated record ", OpenErr) of
true ->
lager:info("VerneMQ LevelDB Message Store backend repair attempt for store ~p, after error ~s. LevelDB will put unusable .log and MANIFEST filest in 'lost' folder.\n",
[DataRoot, OpenErr]),
case eleveldb:repair(DataRoot, []) of
LevelDB will put unusable .log and MANIFEST files in ' lost ' folder .
open_db(Opts, State0, RetriesLeft - 1, Reason);
{error, Reason} -> {error, Reason}
end;
false ->
case lists:prefix("IO error: lock ", OpenErr) of
true ->
SleepFor = proplists:get_value(open_retry_delay, Opts, 2000),
lager:info("VerneMQ LevelDB Message Store backend retrying ~p in ~p ms after error ~s\n",
[DataRoot, SleepFor, OpenErr]),
timer:sleep(SleepFor),
open_db(Opts, State0, RetriesLeft - 1, Reason);
false ->
{error, Reason}
end
end;
{error, Reason} ->
{error, Reason}
end.
| null |
https://raw.githubusercontent.com/vernemq/vernemq/eb1a262035af47e90d9edf07f36c1b1503557c1f/apps/vmq_generic_msg_store/src/engines/vmq_storage_engine_leveldb.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
no need to close the iterator
Get the data root directory
Merge the proplist passed in from Config with any values specified by the
eleveldb app level; precedence is given to the Config.
Local
Global
Use a variable write buffer size in order to reduce the number
of vnodes that try to kick off compaction at the same time
under heavy uniform load...
Update the write buffer size in the merged config and make sure create_if_missing is set
to true
Use read options for folding, but FORCE fill_cache to false
Warn if block_size is set
Generate a debug message with the options we'll use for each operation
Check specifically for lock error, this can be caused if
a crashed instance takes some time to flush leveldb information
may not have completed.
|
Copyright 2019 Octavo Labs AG Zurich Switzerland ( )
Licensed under the Apache License , Version 2.0 ( the " License " ) ;
distributed under the License is distributed on an " AS IS " BASIS ,
-module(vmq_storage_engine_leveldb).
-export([open/2, close/1, write/2, read/2, fold/3, fold/4]).
-record(state, {
ref :: undefined | eleveldb:db_ref(),
data_root :: string(),
open_opts = [],
config :: config(),
read_opts = [],
write_opts = [],
fold_opts = [{fill_cache, false}]
}).
-type state() :: #state{}.
-type config() :: [{atom(), term()}].
-type key() :: binary().
-type value() :: binary().
-type write_op() :: {put, key(), value()} | {delete, key()}.
open(DataRoot, Opts) ->
RetriesLeft = proplists:get_value(open_retries, Opts, 30),
State = init_state(DataRoot, Opts),
open_db(Opts, State, max(1, RetriesLeft), undefined).
-spec write(state(), [write_op()]) -> ok.
write(#state{ref=EngineRef, write_opts=WriteOpts}, WriteOps) ->
eleveldb:write(EngineRef, WriteOps, WriteOpts).
-spec read(state(), key()) -> {ok, value()} | not_found.
read(#state{ref=EngineRef, read_opts=ReadOpts}, Key) ->
eleveldb:get(EngineRef, Key, ReadOpts).
fold(#state{ref=EngineRef, fold_opts=FoldOpts}, Fun, Acc) ->
{ok, Itr} = eleveldb:iterator(EngineRef, FoldOpts),
fold_iterate(eleveldb:iterator_move(Itr, first), Itr, Fun, Acc).
fold(#state{ref=EngineRef, fold_opts=FoldOpts}, Fun, Acc, FirstKey) ->
{ok, Itr} = eleveldb:iterator(EngineRef, FoldOpts),
fold_iterate(eleveldb:iterator_move(Itr, FirstKey), Itr, Fun, Acc).
fold_iterate({error, _}, _Itr, _Fun, Acc) ->
Acc;
fold_iterate({ok, Key, Value}, Itr, Fun, Acc0) ->
try Fun(Key, Value, Acc0) of
Acc1 ->
fold_iterate(eleveldb:iterator_move(Itr, prefetch), Itr, Fun, Acc1)
catch
throw:_Throw ->
eleveldb:iterator_close(Itr),
Acc0
end.
close(#state{ref=EngineRef}) ->
eleveldb:close(EngineRef).
Internal
init_state(DataRoot, Config) ->
filelib:ensure_dir(filename:join(DataRoot, "msg_store_dummy")),
MergedConfig = orddict:merge(fun(_K, VLocal, _VGlobal) -> VLocal end,
WriteBufferMin = config_value(write_buffer_size_min, MergedConfig, 30 * 1024 * 1024),
WriteBufferMax = config_value(write_buffer_size_max, MergedConfig, 60 * 1024 * 1024),
WriteBufferSize = WriteBufferMin + rand:uniform(1 + WriteBufferMax - WriteBufferMin),
FinalConfig = orddict:store(write_buffer_size, WriteBufferSize,
orddict:store(create_if_missing, true, MergedConfig)),
Parse out the open / read / write options
{OpenOpts, _BadOpenOpts} = eleveldb:validate_options(open, FinalConfig),
{ReadOpts, _BadReadOpts} = eleveldb:validate_options(read, FinalConfig),
{WriteOpts, _BadWriteOpts} = eleveldb:validate_options(write, FinalConfig),
FoldOpts = lists:keystore(fill_cache, 1, ReadOpts, {fill_cache, false}),
SSTBS = proplists:get_value(sst_block_size, OpenOpts, false),
BS = proplists:get_value(block_size, OpenOpts, false),
case BS /= false andalso SSTBS == false of
true ->
lager:warning("eleveldb block_size has been renamed sst_block_size "
"and the current setting of ~p is being ignored. "
"Changing sst_block_size is strongly cautioned "
"against unless you know what you are doing. Remove "
"block_size from app.config to get rid of this "
"message.\n", [BS]);
_ ->
ok
end,
lager:debug("datadir ~s options for LevelDB: ~p\n",
[DataRoot, [{open, OpenOpts}, {read, ReadOpts}, {write, WriteOpts}, {fold, FoldOpts}]]),
#state { data_root = DataRoot,
open_opts = OpenOpts,
read_opts = ReadOpts,
write_opts = WriteOpts,
fold_opts = FoldOpts,
config = FinalConfig }.
config_value(Key, Config, Default) ->
case orddict:find(Key, Config) of
error ->
Default;
{ok, Value} ->
Value
end.
open_db(_Opts, _State0, 0, LastError) ->
{error, LastError};
open_db(Opts, State0, RetriesLeft, _) ->
DataRoot = State0#state.data_root,
case eleveldb:open(DataRoot, State0#state.open_opts) of
{ok, Ref} ->
lager:info("Opening LevelDB database at ~p~n", [DataRoot]),
{ok, State0#state { ref = Ref }};
out to disk . The process is gone , but the NIF resource cleanup
{error, {db_open, OpenErr}=Reason} ->
case lists:prefix("Corruption: truncated record ", OpenErr) of
true ->
lager:info("VerneMQ LevelDB Message Store backend repair attempt for store ~p, after error ~s. LevelDB will put unusable .log and MANIFEST filest in 'lost' folder.\n",
[DataRoot, OpenErr]),
case eleveldb:repair(DataRoot, []) of
LevelDB will put unusable .log and MANIFEST files in ' lost ' folder .
open_db(Opts, State0, RetriesLeft - 1, Reason);
{error, Reason} -> {error, Reason}
end;
false ->
case lists:prefix("IO error: lock ", OpenErr) of
true ->
SleepFor = proplists:get_value(open_retry_delay, Opts, 2000),
lager:info("VerneMQ LevelDB Message Store backend retrying ~p in ~p ms after error ~s\n",
[DataRoot, SleepFor, OpenErr]),
timer:sleep(SleepFor),
open_db(Opts, State0, RetriesLeft - 1, Reason);
false ->
{error, Reason}
end
end;
{error, Reason} ->
{error, Reason}
end.
|
c3c8fe0d3667fec8d58c56c1b1efd9c328a3348f45589440d291e815fc9c5efe
|
sebashack/servantRestfulAPI
|
API.hs
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
{-# LANGUAGE ScopedTypeVariables #-}
# LANGUAGE TypeFamilies #
{-# LANGUAGE TypeOperators #-}
# LANGUAGE UndecidableInstances #
# LANGUAGE ScopedTypeVariables #
module Domains.BookingDomain.Reservation.API
(
ReservationAPI
) where
import Domains.BookingDomain.Reservation.DataTypes
import Servant.API
import qualified Data.Time as TM
import qualified Data.Text as T
type ReservId = Integer
type ReservCode = T.Text
type UserToken = T.Text
type BookableId = T.Text
type PropertyId = T.Text
type NotifId = Integer
type Message = T.Text
type ReservationAPI =
1 --
"reservation" :> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Get '[JSON] Reservation
2 --
:<|> "reservation" :> "pricingInfo"
:> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Get '[JSON] [PricingInfo]
3 --
:<|> "user" :> "reservation"
:> Header "Authorization" UserToken
:> ReqBody '[JSON] UserReservData
:> PostCreated '[JSON] Reservation
4 --
:<|> "admin" :> "reservation"
:> Header "Authorization" UserToken
:> ReqBody '[JSON] AdminReservData
:> PostCreated '[JSON] Reservation
5 --
:<|> "property" :> "reservations"
:> Capture "propertyId" PropertyId
:> QueryParam "state" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [Reservation]
6 --
:<|> "userReservs" :> QueryParam "state" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [Reservation]
7 --
:<|> "bookable" :> "reservationInfo"
:> Capture "bookableId" BookableId
:> QueryParam "state" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [PricingInfo]
8 --
:<|> "reservation" :> "accept"
:> Capture "reservationId" ReservId
:> ReqBody '[JSON] Acceptance
:> Header "Authorization" UserToken
:> PostCreated '[JSON] Notification
9 --
:<|> "reservation" :> "reject"
:> Capture "reservationId" ReservId
:> ReqBody '[JSON] Message
:> Header "Authorization" UserToken
:> PostCreated '[JSON] Notification
10 --
:<|> "reservation" :> "user"
:> "absent"
:> Capture "reservationId" ReservId
:> ReqBody '[JSON] Message
:> Header "Authorization" UserToken
:> PostCreated '[JSON] Notification
11 --
:<|> "reservation" :> "admin"
:> "absent"
:> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Put '[JSON] ()
12 --
:<|> "userNotifs" :> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [Notification]
13 --
:<|> "userNotif" :> Capture "notificationId" NotifId
:> Header "Authorization" UserToken
:> Get '[JSON] Notification
14 --
:<|> "reservation" :> ReqBody '[JSON] ReservCode
:> Header "Authorization" UserToken
:> Get '[JSON] Reservation
15 --
:<|> "reservation" :> "guestArrived"
:> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Put '[JSON] ()
16 --
:<|> "reservations" :> "validAbsent"
:> Capture "propertyId" PropertyId
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [Reservation]
17 --
:<|> "reservation" :> "availableRooms"
:> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Get '[JSON] [BookAvailability]
| null |
https://raw.githubusercontent.com/sebashack/servantRestfulAPI/e625535d196acefaff4f5bf03108816be668fe4d/libs/Domains/BookingDomain/Reservation/API.hs
|
haskell
|
# LANGUAGE DataKinds #
# LANGUAGE DeriveGeneric #
# LANGUAGE FlexibleContexts #
# LANGUAGE ScopedTypeVariables #
# LANGUAGE TypeOperators #
|
# LANGUAGE FlexibleInstances #
# LANGUAGE MultiParamTypeClasses #
# LANGUAGE OverloadedStrings #
# LANGUAGE TypeFamilies #
# LANGUAGE UndecidableInstances #
# LANGUAGE ScopedTypeVariables #
module Domains.BookingDomain.Reservation.API
(
ReservationAPI
) where
import Domains.BookingDomain.Reservation.DataTypes
import Servant.API
import qualified Data.Time as TM
import qualified Data.Text as T
type ReservId = Integer
type ReservCode = T.Text
type UserToken = T.Text
type BookableId = T.Text
type PropertyId = T.Text
type NotifId = Integer
type Message = T.Text
type ReservationAPI =
"reservation" :> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Get '[JSON] Reservation
:<|> "reservation" :> "pricingInfo"
:> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Get '[JSON] [PricingInfo]
:<|> "user" :> "reservation"
:> Header "Authorization" UserToken
:> ReqBody '[JSON] UserReservData
:> PostCreated '[JSON] Reservation
:<|> "admin" :> "reservation"
:> Header "Authorization" UserToken
:> ReqBody '[JSON] AdminReservData
:> PostCreated '[JSON] Reservation
:<|> "property" :> "reservations"
:> Capture "propertyId" PropertyId
:> QueryParam "state" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [Reservation]
:<|> "userReservs" :> QueryParam "state" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [Reservation]
:<|> "bookable" :> "reservationInfo"
:> Capture "bookableId" BookableId
:> QueryParam "state" T.Text
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [PricingInfo]
:<|> "reservation" :> "accept"
:> Capture "reservationId" ReservId
:> ReqBody '[JSON] Acceptance
:> Header "Authorization" UserToken
:> PostCreated '[JSON] Notification
:<|> "reservation" :> "reject"
:> Capture "reservationId" ReservId
:> ReqBody '[JSON] Message
:> Header "Authorization" UserToken
:> PostCreated '[JSON] Notification
:<|> "reservation" :> "user"
:> "absent"
:> Capture "reservationId" ReservId
:> ReqBody '[JSON] Message
:> Header "Authorization" UserToken
:> PostCreated '[JSON] Notification
:<|> "reservation" :> "admin"
:> "absent"
:> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Put '[JSON] ()
:<|> "userNotifs" :> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [Notification]
:<|> "userNotif" :> Capture "notificationId" NotifId
:> Header "Authorization" UserToken
:> Get '[JSON] Notification
:<|> "reservation" :> ReqBody '[JSON] ReservCode
:> Header "Authorization" UserToken
:> Get '[JSON] Reservation
:<|> "reservation" :> "guestArrived"
:> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Put '[JSON] ()
:<|> "reservations" :> "validAbsent"
:> Capture "propertyId" PropertyId
:> QueryParam "from" Int
:> QueryParam "size" Int
:> Header "Authorization" UserToken
:> Get '[JSON] [Reservation]
:<|> "reservation" :> "availableRooms"
:> Capture "reservationId" ReservId
:> Header "Authorization" UserToken
:> Get '[JSON] [BookAvailability]
|
298f123909b5fe9b18a8805d4aa1aa2ff67d98954066d72b30328eb2d9244710
|
well-typed/visualize-cbn
|
Main.hs
|
module Main (main) where
import Control.Monad
import CBN.Options
import CBN.Parser
import CBN.Trace
import CBN.Trace.HeapGraph as Trace.HeapGraph
import CBN.Trace.JavaScript as Trace.JavaScript
import CBN.Trace.Textual as Trace.Textual
import CBN.Trace.Graph as Trace.Graph
main :: IO ()
main = do
Options{..} <- getOptions
input <- parseIO optionsInput parseModule =<< readFile optionsInput
let trace = summarize optionsSummarize $ traceTerm optionsGC input
when optionsShowTrace $
Trace.Textual.renderIO trace
forM_ optionsJsOutput $ \file ->
writeFile file $ Trace.JavaScript.render optionsJsName optionsGraphOutput trace
forM_ optionsGraphOutput $ \file ->
writeFile file $ Trace.Graph.render trace
forM_ optionsGraphOutput $ toGraphFiles trace
| null |
https://raw.githubusercontent.com/well-typed/visualize-cbn/499a8bc806ce03ce6d1bc12df1ea6e6df7768817/src/Main.hs
|
haskell
|
module Main (main) where
import Control.Monad
import CBN.Options
import CBN.Parser
import CBN.Trace
import CBN.Trace.HeapGraph as Trace.HeapGraph
import CBN.Trace.JavaScript as Trace.JavaScript
import CBN.Trace.Textual as Trace.Textual
import CBN.Trace.Graph as Trace.Graph
main :: IO ()
main = do
Options{..} <- getOptions
input <- parseIO optionsInput parseModule =<< readFile optionsInput
let trace = summarize optionsSummarize $ traceTerm optionsGC input
when optionsShowTrace $
Trace.Textual.renderIO trace
forM_ optionsJsOutput $ \file ->
writeFile file $ Trace.JavaScript.render optionsJsName optionsGraphOutput trace
forM_ optionsGraphOutput $ \file ->
writeFile file $ Trace.Graph.render trace
forM_ optionsGraphOutput $ toGraphFiles trace
|
|
9b9bedf2002d7062a6d9d56523fe470bd0a14d12c30500d655dc5bf730681b17
|
byteally/dbrecord
|
Types.hs
|
# OPTIONS_GHC -Wno - orphans #
# LANGUAGE TypeFamilies , DataKinds , DeriveGeneric , FlexibleInstances , FlexibleContexts , ScopedTypeVariables , DeriveFunctor , GeneralizedNewtypeDeriving , MultiParamTypeClasses , UndecidableInstances #
module DBRecord.MSSQL.Internal.Types where
import qualified DBRecord.Internal.Types as Type
import DBRecord.Internal.DBTypes
import DBRecord.Internal.Schema
import Data.Text
import GHC.TypeLits
import GHC.Generics
import qualified DBRecord.Internal.PrimQuery as PQ
import DBRecord.Internal.Expr
import Data.String
import qualified Data.Text as T
import Data.ByteString (ByteString)
import Control.Monad.Reader
newtype MSSQLDBM m (db :: *) a = MSSQLDBM { runMSSQLDB :: ReaderT () m a}
deriving (Functor, Applicative, Monad, MonadIO)
newtype Sized (n :: Nat) a = Sized { getSized :: a }
deriving (Show, Eq, Generic)
newtype Varsized (n :: Nat) a = Varsized { getVarsized :: a }
deriving (Show, Eq, Generic)
type instance CustomDBTypeRep sc (Sized n Text) = 'Type.DBChar n
type instance CustomDBTypeRep sc (Varsized n Text) = 'Type.DBVarchar ('Right n)
instance EqExpr sc ByteString where
a .== b = binOp PQ.OpEq a b
instance EqExpr sc (Type.CustomType (Sized n Text)) where
a .== b = binOp PQ.OpEq a b
instance EqExpr sc (Type.CustomType (Varsized n Text)) where
a .== b = binOp PQ.OpEq a b
instance ( DBTypeCtx (GetDBTypeRep sc Text)
, Type.SingI (GetDBTypeRep sc Text)
) => IsString (Expr sc scopes (Sized n Text)) where
fromString = coerceExpr . annotateType . mssqltext . pack
instance ( DBTypeCtx (GetDBTypeRep sc Text)
, Type.SingI (GetDBTypeRep sc Text)
) => IsString (Expr sc scopes (Varsized n Text)) where
fromString = coerceExpr . annotateType . mssqltext . pack
instance (IsString (Expr sc scopes a)
) => IsString (Expr sc scopes (Type.CustomType a)) where
fromString = coerceExpr . (fromString :: String -> Expr sc scopes a)
mssqltext :: T.Text -> Expr sc scopes T.Text
mssqltext = Expr . PQ.ConstExpr . PQ.String
mssqlbyte :: ByteString -> Expr sc scopes ByteString
mssqlbyte = Expr . PQ.ConstExpr . PQ.Byte
| null |
https://raw.githubusercontent.com/byteally/dbrecord/991efe9a293532ee9242b3e9a26434cf16f5b2a0/dbrecord-mssql-odbc/src/DBRecord/MSSQL/Internal/Types.hs
|
haskell
|
# OPTIONS_GHC -Wno - orphans #
# LANGUAGE TypeFamilies , DataKinds , DeriveGeneric , FlexibleInstances , FlexibleContexts , ScopedTypeVariables , DeriveFunctor , GeneralizedNewtypeDeriving , MultiParamTypeClasses , UndecidableInstances #
module DBRecord.MSSQL.Internal.Types where
import qualified DBRecord.Internal.Types as Type
import DBRecord.Internal.DBTypes
import DBRecord.Internal.Schema
import Data.Text
import GHC.TypeLits
import GHC.Generics
import qualified DBRecord.Internal.PrimQuery as PQ
import DBRecord.Internal.Expr
import Data.String
import qualified Data.Text as T
import Data.ByteString (ByteString)
import Control.Monad.Reader
newtype MSSQLDBM m (db :: *) a = MSSQLDBM { runMSSQLDB :: ReaderT () m a}
deriving (Functor, Applicative, Monad, MonadIO)
newtype Sized (n :: Nat) a = Sized { getSized :: a }
deriving (Show, Eq, Generic)
newtype Varsized (n :: Nat) a = Varsized { getVarsized :: a }
deriving (Show, Eq, Generic)
type instance CustomDBTypeRep sc (Sized n Text) = 'Type.DBChar n
type instance CustomDBTypeRep sc (Varsized n Text) = 'Type.DBVarchar ('Right n)
instance EqExpr sc ByteString where
a .== b = binOp PQ.OpEq a b
instance EqExpr sc (Type.CustomType (Sized n Text)) where
a .== b = binOp PQ.OpEq a b
instance EqExpr sc (Type.CustomType (Varsized n Text)) where
a .== b = binOp PQ.OpEq a b
instance ( DBTypeCtx (GetDBTypeRep sc Text)
, Type.SingI (GetDBTypeRep sc Text)
) => IsString (Expr sc scopes (Sized n Text)) where
fromString = coerceExpr . annotateType . mssqltext . pack
instance ( DBTypeCtx (GetDBTypeRep sc Text)
, Type.SingI (GetDBTypeRep sc Text)
) => IsString (Expr sc scopes (Varsized n Text)) where
fromString = coerceExpr . annotateType . mssqltext . pack
instance (IsString (Expr sc scopes a)
) => IsString (Expr sc scopes (Type.CustomType a)) where
fromString = coerceExpr . (fromString :: String -> Expr sc scopes a)
mssqltext :: T.Text -> Expr sc scopes T.Text
mssqltext = Expr . PQ.ConstExpr . PQ.String
mssqlbyte :: ByteString -> Expr sc scopes ByteString
mssqlbyte = Expr . PQ.ConstExpr . PQ.Byte
|
|
8c388936c28b7f4ada40050b6fa14a7e6a37d0b77fe6736719aa7faeb94275f6
|
KaroshiBee/weevil
|
dap_raise_error_response_tests.ml
|
include Utilities.Testing_utils
module Js = Data_encoding.Json
module Res = Dap.Response
module Ev = Dap.Event
module TestState = Dap_state.T ()
module Raise_error =
Dap_handlers.Raise_error.Make
(struct
type enum = Dap_commands.error
type contents = Dap.Data.ErrorResponse_body.t
type presence = Dap.Data.Presence.req
type msg = (enum, contents, presence) Res.Message.t
type t = msg Res.t
let ctor = Res.errorResponse
let enc = Res.Message.enc Dap.Commands.error Dap.Data.ErrorResponse_body.enc
end)
(TestState)
let _reset state =
need to set the state as if messsages have already been exchanged
TestState.set_seqr state @@ Dap.Seqr.make ~seq:121 ~request_seq:120 ()
let%expect_test "Check sequencing raise response" =
let state = TestState.make () in
_reset state;
let handler =
Raise_error.make ~handler:(fun ~state:_ _ ->
Res.(
let msg = default_response_error "flux capacitor ran out of gigawatts" in
errorResponse msg
|> Dap_result.ok
)
)
in
let seqr = TestState.current_seqr state in
let request_seq = Dap.Seqr.request_seq seqr in
Printf.printf "request_seq %d" request_seq;
let%lwt () =
[%expect {| request_seq 120 |}]
in
let seq = Dap.Seqr.seq seqr in
Printf.printf "seq %d" seq;
let%lwt () =
[%expect {| seq 121 |}]
in
let%lwt s = handler ~state "" in
Printf.printf "%s" @@ Result.get_ok s ;
let%lwt () =
[%expect
{|
{ "seq": 122, "type": "response", "request_seq": 121, "success": false,
"command": "error", "message": "flux capacitor ran out of gigawatts",
"body":
{ "error":
{ "id": 61389606, "format": "{error}",
"variables": { "error": "flux capacitor ran out of gigawatts" } } } } |}]
in
let seqr = TestState.current_seqr state in
let request_seq = Dap.Seqr.request_seq seqr in
Printf.printf "request_seq %d" request_seq;
let%lwt () =
[%expect {| request_seq 121 |}]
in
let seq = Dap.Seqr.seq seqr in
Printf.printf "seq %d" seq;
[%expect {| seq 122 |}]
| null |
https://raw.githubusercontent.com/KaroshiBee/weevil/1b166ba053062498c1ec05c885e04fba4ae7d831/lib/dapper/tests/dap_expect_tests/dap_raise_error_response_tests.ml
|
ocaml
|
include Utilities.Testing_utils
module Js = Data_encoding.Json
module Res = Dap.Response
module Ev = Dap.Event
module TestState = Dap_state.T ()
module Raise_error =
Dap_handlers.Raise_error.Make
(struct
type enum = Dap_commands.error
type contents = Dap.Data.ErrorResponse_body.t
type presence = Dap.Data.Presence.req
type msg = (enum, contents, presence) Res.Message.t
type t = msg Res.t
let ctor = Res.errorResponse
let enc = Res.Message.enc Dap.Commands.error Dap.Data.ErrorResponse_body.enc
end)
(TestState)
let _reset state =
need to set the state as if messsages have already been exchanged
TestState.set_seqr state @@ Dap.Seqr.make ~seq:121 ~request_seq:120 ()
let%expect_test "Check sequencing raise response" =
let state = TestState.make () in
_reset state;
let handler =
Raise_error.make ~handler:(fun ~state:_ _ ->
Res.(
let msg = default_response_error "flux capacitor ran out of gigawatts" in
errorResponse msg
|> Dap_result.ok
)
)
in
let seqr = TestState.current_seqr state in
let request_seq = Dap.Seqr.request_seq seqr in
Printf.printf "request_seq %d" request_seq;
let%lwt () =
[%expect {| request_seq 120 |}]
in
let seq = Dap.Seqr.seq seqr in
Printf.printf "seq %d" seq;
let%lwt () =
[%expect {| seq 121 |}]
in
let%lwt s = handler ~state "" in
Printf.printf "%s" @@ Result.get_ok s ;
let%lwt () =
[%expect
{|
{ "seq": 122, "type": "response", "request_seq": 121, "success": false,
"command": "error", "message": "flux capacitor ran out of gigawatts",
"body":
{ "error":
{ "id": 61389606, "format": "{error}",
"variables": { "error": "flux capacitor ran out of gigawatts" } } } } |}]
in
let seqr = TestState.current_seqr state in
let request_seq = Dap.Seqr.request_seq seqr in
Printf.printf "request_seq %d" request_seq;
let%lwt () =
[%expect {| request_seq 121 |}]
in
let seq = Dap.Seqr.seq seqr in
Printf.printf "seq %d" seq;
[%expect {| seq 122 |}]
|
|
96f4ffdbbde3b5f941b2c3e458f66a6471f9fcac7997f05b61202f69294cd2d6
|
erlang/erlide_kernel
|
erlide_tools_app.erl
|
-module(erlide_tools_app).
-export([
init/0
]).
init() ->
io:format("Start tools app~n"),
ok.
| null |
https://raw.githubusercontent.com/erlang/erlide_kernel/763a7fe47213f374b59862fd5a17d5dcc2811c7b/common/apps/erlide_tools/src/erlide_tools_app.erl
|
erlang
|
-module(erlide_tools_app).
-export([
init/0
]).
init() ->
io:format("Start tools app~n"),
ok.
|
|
966cd5fff72f94f949c428756ab347b8836a2c094aafbe78fe72efca6b4f0169
|
TerrorJack/ghc-alter
|
num005.hs
|
-- Exercising Numeric.readSigned a bit
--
module Main(main) where
import Numeric
main =
let
ls = ["3489348394032498320438240938403","0","-1","1","34323","2L","012","0x23","3243ab"]
present str f ls =
sequence (map (\ v -> putStr ('\n':str ++
' ': v ++
" = " ++
(show (f v)))) ls)
in
do
present "(readDec::ReadS Integer)" (readDec::ReadS Integer) ls
present "(readDec::ReadS Int)" (readDec::ReadS Int) ls
present "(readOct::ReadS Integer)" (readOct::ReadS Integer) ls
present "(readOct::ReadS Int)" (readOct::ReadS Int) ls
present "(readHex::ReadS Integer)" (readHex::ReadS Integer) ls
present "(readHex::ReadS Int)" (readHex::ReadS Int) ls
putStrLn ""
| null |
https://raw.githubusercontent.com/TerrorJack/ghc-alter/db736f34095eef416b7e077f9b26fc03aa78c311/ghc-alter/boot-lib/base/tests/Numeric/num005.hs
|
haskell
|
Exercising Numeric.readSigned a bit
|
module Main(main) where
import Numeric
main =
let
ls = ["3489348394032498320438240938403","0","-1","1","34323","2L","012","0x23","3243ab"]
present str f ls =
sequence (map (\ v -> putStr ('\n':str ++
' ': v ++
" = " ++
(show (f v)))) ls)
in
do
present "(readDec::ReadS Integer)" (readDec::ReadS Integer) ls
present "(readDec::ReadS Int)" (readDec::ReadS Int) ls
present "(readOct::ReadS Integer)" (readOct::ReadS Integer) ls
present "(readOct::ReadS Int)" (readOct::ReadS Int) ls
present "(readHex::ReadS Integer)" (readHex::ReadS Integer) ls
present "(readHex::ReadS Int)" (readHex::ReadS Int) ls
putStrLn ""
|
9ed3d32b66abe88f6720e93908097d7e7f643338cf195ddae9bcc24bf1c2c612
|
onaio/hatti
|
macros.clj
|
(ns hatti.macros)
(defmacro read-file
"Takes a filename, and returns contents as string, at compile time. Used for
ClojureScript tests to read fixtures."
[filename]
(slurp filename))
| null |
https://raw.githubusercontent.com/onaio/hatti/7dc23c1c60b9fc46e1ff5b023eb6c794ebd04773/test/hatti/macros.clj
|
clojure
|
(ns hatti.macros)
(defmacro read-file
"Takes a filename, and returns contents as string, at compile time. Used for
ClojureScript tests to read fixtures."
[filename]
(slurp filename))
|
|
775f2494f1bc17a5aa2ee54ba276ebc657963b74e49f8ff4820016c75f57a634
|
bgusach/exercises-htdp2e
|
ex-184.rkt
|
#lang htdp/bsl+
(require test-engine/racket-tests)
(check-expect
(list (string=? "a" "b") #false)
(list #false #false)
)
(check-expect
(list (+ 10 20) (* 10 20) (/ 10 20))
(list 30 200 1/2)
)
(check-expect
(list "dana" "jane" "mary" "laura")
; ...??
(list "dana" "jane" "mary" "laura")
)
(test)
| null |
https://raw.githubusercontent.com/bgusach/exercises-htdp2e/c4fd33f28fb0427862a2777a1fde8bf6432a7690/2-arbitrarily-large-data/ex-184.rkt
|
racket
|
...??
|
#lang htdp/bsl+
(require test-engine/racket-tests)
(check-expect
(list (string=? "a" "b") #false)
(list #false #false)
)
(check-expect
(list (+ 10 20) (* 10 20) (/ 10 20))
(list 30 200 1/2)
)
(check-expect
(list "dana" "jane" "mary" "laura")
(list "dana" "jane" "mary" "laura")
)
(test)
|
e91082178ab2282dc8b7771bb2543993a1712294572734453690108feaa17aa8
|
pharaun/hsnsq
|
Parser.hs
|
{-# LANGUAGE OverloadedStrings #-}
|
Module : Network .
Description : Protocol Parser layer for the NSQ client library .
Module : Network.NSQ.Parser
Description : Protocol Parser layer for the NSQ client library.
-}
module Network.NSQ.Parser
( message
, decode
, encode
) where
import Data.Word
import Data.Monoid
import Control.Applicative
import Data.Attoparsec.Binary
import Data.Attoparsec.ByteString hiding (count)
import Data.Int
import Prelude hiding (take)
import qualified Data.List as DL
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Builder as BL
import qualified Data.Text.Encoding as T
import Network.NSQ.Types
import Network.NSQ.Identify
-- | Decode the 'ByteString' to an 'Message'
decode :: BS.ByteString -> Maybe Message
decode str = case parseOnly message str of
Left _ -> Nothing
Right r -> Just r
-- | Convert various nsq messages into useful 'Message' types
command :: BS.ByteString -> Message
command "_heartbeat_" = Heartbeat
command "OK" = OK
command "CLOSE_WAIT" = CloseWait
command x = CatchAllMessage (FTUnknown 99) x -- TODO: Better FrameType
| Convert various Error strings to ' ErrorType '
errorCasting :: BS.ByteString -> ErrorType
errorCasting "E_INVALID" = Invalid
errorCasting "E_BAD_BODY" = BadBody
errorCasting "E_BAD_TOPIC" = BadTopic
errorCasting "E_BAD_MESSAGE" = BadMessage
errorCasting "E_PUB_FAILED" = PubFailed
errorCasting "E_MPUB_FAILED" = MPubFailed
errorCasting "E_FIN_FAILED" = FinFailed
errorCasting "E_REQ_FAILED" = ReqFailed
errorCasting "E_TOUCH_FAILED" = TouchFailed
errorCasting x = Unknown x
| Frame types into ' FrameType '
frameType :: Int32 -> FrameType
frameType 0 = FTResponse
frameType 1 = FTError
frameType 2 = FTMessage
frameType x = FTUnknown x
-- TODO: do sanity check such as checking that the size is of a minimal
-- size, then parsing the frameType, then the remainder (fail "messg")
-- | Parse the low level message frames into a 'Message' type.
message :: Parser Message
message = do
size <- fromIntegral <$> anyWord32be
ft <- frameType <$> fromIntegral <$> anyWord32be
frame ft (size - 4) -- Taking in accord the frameType
-- | Parse in the frame (remaining portion) of the message in accordance of
the ' '
frame :: FrameType -> Int -> Parser Message
frame FTError size = Error <$> (errorCasting `fmap` take size)
frame FTResponse size = command <$> take size
frame FTMessage size = Message
<$> (fromIntegral <$> anyWord64be)
<*> anyWord16be
16 bytes message i d
<*> take 16
Taking in accord timestamp / attempts / msgid
<*> take (size - 26)
frame ft size = CatchAllMessage ft <$> take size
-- TODO: this won't work for streaming the data...
Should provide two api , one for in memory ( ie where we count up the length of the data manualy
-- And a "streaming" version in which we know the actual size before streaming (ie streaming from a file for ex)
-- | Primitive version for encoding the size of the data into the frame
-- content then encoding the remaining.
sizedData :: BS.ByteString -> BL.Builder
sizedData dat = BL.word32BE (fromIntegral $ BS.length dat) <> BL.byteString dat
-- Body of a foldl to build up a sequence of concat sized data
concatSizedData :: (Word32, Word32, BL.Builder) -> BS.ByteString -> (Word32, Word32, BL.Builder)
concatSizedData (totalSize, count, xs) dat = (
Add 4 to accord for message size
count + 1,
xs <> sizedData dat
)
| Encode a ' Command ' into raw ' ByteString ' to send to the network to the
-- nsqd daemon. There are a few gotchas here; You can only have one 'Sub'
( topic / channel ) per nsqld connection , any other will yield ' Invalid ' .
-- Also you can publish to any number of topic without limitation.
encode :: Command -> BS.ByteString
encode Protocol = " V2"
encode NOP = "NOP\n"
encode Cls = "CLS\n"
encode (Identify identify) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "IDENTIFY\n" <>
sizedData (BL.toStrict $ encodeMetadata identify)
)
encode (Sub topic channel ephemeral) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "SUB " <>
BL.byteString (T.encodeUtf8 topic) <>
BL.byteString " " <>
BL.byteString (T.encodeUtf8 channel) <>
BL.byteString (if ephemeral then "#ephemeral" else "") <>
BL.byteString "\n"
)
encode (Pub topic dat) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "PUB " <>
BL.byteString (T.encodeUtf8 topic) <>
BL.byteString "\n" <>
sizedData dat
)
encode (MPub topic dx) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "MPUB " <>
BL.byteString (T.encodeUtf8 topic) <>
BL.byteString "\n" <>
Accord for message count
BL.word32BE totalCount <>
content
)
where
(totalSize, totalCount, content) = DL.foldl' concatSizedData (0, 0, mempty) dx
encode (Rdy count) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "RDY " <>
BL.byteString (C8.pack $ show count) <>
BL.byteString "\n"
)
encode (Fin msg_id) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "FIN " <>
BL.byteString msg_id <>
BL.byteString "\n"
)
encode (Touch msg_id) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "TOUCH " <>
BL.byteString msg_id <>
BL.byteString "\n"
)
encode (Req msg_id timeout) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "REQ " <>
BL.byteString msg_id <>
BL.byteString " " <>
BL.byteString (C8.pack $ show timeout) <>
BL.byteString "\n"
)
encode (Command m) = m
| null |
https://raw.githubusercontent.com/pharaun/hsnsq/f0072e40382e3669a4ffae37354d9947077ccbd2/src/Network/NSQ/Parser.hs
|
haskell
|
# LANGUAGE OverloadedStrings #
| Decode the 'ByteString' to an 'Message'
| Convert various nsq messages into useful 'Message' types
TODO: Better FrameType
TODO: do sanity check such as checking that the size is of a minimal
size, then parsing the frameType, then the remainder (fail "messg")
| Parse the low level message frames into a 'Message' type.
Taking in accord the frameType
| Parse in the frame (remaining portion) of the message in accordance of
TODO: this won't work for streaming the data...
And a "streaming" version in which we know the actual size before streaming (ie streaming from a file for ex)
| Primitive version for encoding the size of the data into the frame
content then encoding the remaining.
Body of a foldl to build up a sequence of concat sized data
nsqd daemon. There are a few gotchas here; You can only have one 'Sub'
Also you can publish to any number of topic without limitation.
|
|
Module : Network .
Description : Protocol Parser layer for the NSQ client library .
Module : Network.NSQ.Parser
Description : Protocol Parser layer for the NSQ client library.
-}
module Network.NSQ.Parser
( message
, decode
, encode
) where
import Data.Word
import Data.Monoid
import Control.Applicative
import Data.Attoparsec.Binary
import Data.Attoparsec.ByteString hiding (count)
import Data.Int
import Prelude hiding (take)
import qualified Data.List as DL
import qualified Data.ByteString as BS
import qualified Data.ByteString.Char8 as C8
import qualified Data.ByteString.Lazy as BL
import qualified Data.ByteString.Lazy.Builder as BL
import qualified Data.Text.Encoding as T
import Network.NSQ.Types
import Network.NSQ.Identify
decode :: BS.ByteString -> Maybe Message
decode str = case parseOnly message str of
Left _ -> Nothing
Right r -> Just r
command :: BS.ByteString -> Message
command "_heartbeat_" = Heartbeat
command "OK" = OK
command "CLOSE_WAIT" = CloseWait
| Convert various Error strings to ' ErrorType '
errorCasting :: BS.ByteString -> ErrorType
errorCasting "E_INVALID" = Invalid
errorCasting "E_BAD_BODY" = BadBody
errorCasting "E_BAD_TOPIC" = BadTopic
errorCasting "E_BAD_MESSAGE" = BadMessage
errorCasting "E_PUB_FAILED" = PubFailed
errorCasting "E_MPUB_FAILED" = MPubFailed
errorCasting "E_FIN_FAILED" = FinFailed
errorCasting "E_REQ_FAILED" = ReqFailed
errorCasting "E_TOUCH_FAILED" = TouchFailed
errorCasting x = Unknown x
| Frame types into ' FrameType '
frameType :: Int32 -> FrameType
frameType 0 = FTResponse
frameType 1 = FTError
frameType 2 = FTMessage
frameType x = FTUnknown x
message :: Parser Message
message = do
size <- fromIntegral <$> anyWord32be
ft <- frameType <$> fromIntegral <$> anyWord32be
the ' '
frame :: FrameType -> Int -> Parser Message
frame FTError size = Error <$> (errorCasting `fmap` take size)
frame FTResponse size = command <$> take size
frame FTMessage size = Message
<$> (fromIntegral <$> anyWord64be)
<*> anyWord16be
16 bytes message i d
<*> take 16
Taking in accord timestamp / attempts / msgid
<*> take (size - 26)
frame ft size = CatchAllMessage ft <$> take size
Should provide two api , one for in memory ( ie where we count up the length of the data manualy
sizedData :: BS.ByteString -> BL.Builder
sizedData dat = BL.word32BE (fromIntegral $ BS.length dat) <> BL.byteString dat
concatSizedData :: (Word32, Word32, BL.Builder) -> BS.ByteString -> (Word32, Word32, BL.Builder)
concatSizedData (totalSize, count, xs) dat = (
Add 4 to accord for message size
count + 1,
xs <> sizedData dat
)
| Encode a ' Command ' into raw ' ByteString ' to send to the network to the
( topic / channel ) per nsqld connection , any other will yield ' Invalid ' .
encode :: Command -> BS.ByteString
encode Protocol = " V2"
encode NOP = "NOP\n"
encode Cls = "CLS\n"
encode (Identify identify) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "IDENTIFY\n" <>
sizedData (BL.toStrict $ encodeMetadata identify)
)
encode (Sub topic channel ephemeral) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "SUB " <>
BL.byteString (T.encodeUtf8 topic) <>
BL.byteString " " <>
BL.byteString (T.encodeUtf8 channel) <>
BL.byteString (if ephemeral then "#ephemeral" else "") <>
BL.byteString "\n"
)
encode (Pub topic dat) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "PUB " <>
BL.byteString (T.encodeUtf8 topic) <>
BL.byteString "\n" <>
sizedData dat
)
encode (MPub topic dx) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "MPUB " <>
BL.byteString (T.encodeUtf8 topic) <>
BL.byteString "\n" <>
Accord for message count
BL.word32BE totalCount <>
content
)
where
(totalSize, totalCount, content) = DL.foldl' concatSizedData (0, 0, mempty) dx
encode (Rdy count) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "RDY " <>
BL.byteString (C8.pack $ show count) <>
BL.byteString "\n"
)
encode (Fin msg_id) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "FIN " <>
BL.byteString msg_id <>
BL.byteString "\n"
)
encode (Touch msg_id) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "TOUCH " <>
BL.byteString msg_id <>
BL.byteString "\n"
)
encode (Req msg_id timeout) = BL.toStrict $ BL.toLazyByteString (
BL.byteString "REQ " <>
BL.byteString msg_id <>
BL.byteString " " <>
BL.byteString (C8.pack $ show timeout) <>
BL.byteString "\n"
)
encode (Command m) = m
|
82d44034f2d605dba3ca3bc96eb95182ad56f3dd27411c0aaa25ad71860fc322
|
callum-oakley/advent-of-code
|
02.clj
|
(ns aoc.2021.02
(:require
[clojure.test :refer [deftest is]]))
(defn parse [s]
(->> s (re-seq #"\w+") (map read-string) (partition 2)))
This covers parts 1 and 2 : for part-1 treat aim as depth and ignore dep
(defn dive [commands]
(reduce (fn [[hor aim dep] [op x]]
(case op
forward [(+ hor x) aim (+ (* aim x) dep)]
down [hor (+ aim x) dep]
up [hor (- aim x) dep]))
[0 0 0]
commands))
(defn part-1 [commands]
(let [[hor dep _] (dive commands)] (* hor dep)))
(defn part-2 [commands]
(let [[hor _ dep] (dive commands)] (* hor dep)))
(deftest test-example
(let [commands (parse "forward 5 down 5 forward 8 up 3 down 8 forward 2")]
(is (= [15 10 60] (dive commands)))))
| null |
https://raw.githubusercontent.com/callum-oakley/advent-of-code/3cf44bcb8c57693639630f95f29d4abf49a6f0e4/src/aoc/2021/02.clj
|
clojure
|
(ns aoc.2021.02
(:require
[clojure.test :refer [deftest is]]))
(defn parse [s]
(->> s (re-seq #"\w+") (map read-string) (partition 2)))
This covers parts 1 and 2 : for part-1 treat aim as depth and ignore dep
(defn dive [commands]
(reduce (fn [[hor aim dep] [op x]]
(case op
forward [(+ hor x) aim (+ (* aim x) dep)]
down [hor (+ aim x) dep]
up [hor (- aim x) dep]))
[0 0 0]
commands))
(defn part-1 [commands]
(let [[hor dep _] (dive commands)] (* hor dep)))
(defn part-2 [commands]
(let [[hor _ dep] (dive commands)] (* hor dep)))
(deftest test-example
(let [commands (parse "forward 5 down 5 forward 8 up 3 down 8 forward 2")]
(is (= [15 10 60] (dive commands)))))
|
|
f64398714b56b83e2476bc9e08c460d9f551b2b5ccbbdffd0c594fb3d02d09a1
|
mhuebert/maria
|
animation_quickstart.cljs
|
(ns maria.curriculum.animation-quickstart
{:description "Get a running start at making basic animations using the Shapes library."}
(:require [cells.api :refer :all]
[shapes.core :refer :all]))
;; # Animations Quick-Start
;; This is a quick-start guide for drawing animations. The goal of this document is to equip you with templates to give you a running start at making basic animations. From there you can do many fun and complex things.
;; For a full explanation of how the techniques in this guide work, see the [Cells]() lesson.
# # # ` cell ` and ` interval `
We use ` interval ` inside a ` cell ` to make animations that repeat . The interval , ` 250 ` , is in millisseconds , meaning this square gets colorized with a random item from ` palette ` every quarter - second :
(let [palette ["red" "orange" "yellow" "green" "blue" "indigo" "violet"]]
(cell (interval 250 #(colorize (rand-nth palette) (square 50)))))
;; That's the most basic template.
# # # ` defcell `
;; By naming cells with `defcell`, we can use them in multiple places:
(defcell clock (interval 10 inc))
;; We can then get the _current_ value of `clock` with the `@` symbol. (Why? Read [Cells]() for how it works.)
(cell (rotate @clock (square 100)))
;; Because `clock` has a name, we can use it in a totally separate sketch. Here we add a color variable with the `hsl` (Hue/Saturation/Lightness) and `mod` ("modulo" or remainder) functions:
(cell (colorize (hsl (mod @clock 360) 80 80)
(rotate @clock (square 100))))
;; We can also use multiple named cells in a single sketch.
First make a counter :
(defcell counter (interval 250 inc))
Second , define a random - color - name cell :
(defcell a-color (interval 250 #(rand-nth (map first color-names))))
;; Finally, put the counter and random-color-name cells together using sine and cosine:
(cell (->> (circle 25)
(position (+ 60 (* 20 (Math/sin @counter)))
(+ 60 (* 20 (Math/cos @counter))))
(colorize @a-color)))
;; Those are the basic tricks. Go forth and hack on some animated drawings, fellow programmer. For ideas, see the [Gallery]().
| null |
https://raw.githubusercontent.com/mhuebert/maria/9fc2e26ed7df16e82841e0127a56ae36fafa4e63/editor2/src/main/maria/curriculum/animation_quickstart.cljs
|
clojure
|
# Animations Quick-Start
This is a quick-start guide for drawing animations. The goal of this document is to equip you with templates to give you a running start at making basic animations. From there you can do many fun and complex things.
For a full explanation of how the techniques in this guide work, see the [Cells]() lesson.
That's the most basic template.
By naming cells with `defcell`, we can use them in multiple places:
We can then get the _current_ value of `clock` with the `@` symbol. (Why? Read [Cells]() for how it works.)
Because `clock` has a name, we can use it in a totally separate sketch. Here we add a color variable with the `hsl` (Hue/Saturation/Lightness) and `mod` ("modulo" or remainder) functions:
We can also use multiple named cells in a single sketch.
Finally, put the counter and random-color-name cells together using sine and cosine:
Those are the basic tricks. Go forth and hack on some animated drawings, fellow programmer. For ideas, see the [Gallery]().
|
(ns maria.curriculum.animation-quickstart
{:description "Get a running start at making basic animations using the Shapes library."}
(:require [cells.api :refer :all]
[shapes.core :refer :all]))
# # # ` cell ` and ` interval `
We use ` interval ` inside a ` cell ` to make animations that repeat . The interval , ` 250 ` , is in millisseconds , meaning this square gets colorized with a random item from ` palette ` every quarter - second :
(let [palette ["red" "orange" "yellow" "green" "blue" "indigo" "violet"]]
(cell (interval 250 #(colorize (rand-nth palette) (square 50)))))
# # # ` defcell `
(defcell clock (interval 10 inc))
(cell (rotate @clock (square 100)))
(cell (colorize (hsl (mod @clock 360) 80 80)
(rotate @clock (square 100))))
First make a counter :
(defcell counter (interval 250 inc))
Second , define a random - color - name cell :
(defcell a-color (interval 250 #(rand-nth (map first color-names))))
(cell (->> (circle 25)
(position (+ 60 (* 20 (Math/sin @counter)))
(+ 60 (* 20 (Math/cos @counter))))
(colorize @a-color)))
|
10ca3f2f6336f87bd87e665467ad90fbdf5d3d29e5ba8cb7fbb787d2d48d3f8b
|
erlangonrails/devdb
|
reloader.erl
|
2007 Mochi Media , Inc.
@author < >
%%
@doc Erlang module for automatically reloading modified modules
%% during development.
-module(reloader).
-author("Matthew Dempsky <>").
-include_lib("kernel/include/file.hrl").
-behaviour(gen_server).
-export([start/0, start_link/0]).
-export([stop/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {last, tref}).
%% External API
@spec start ( ) - > ServerRet
%% @doc Start the reloader.
start() ->
gen_server:start({local, ?MODULE}, ?MODULE, [], []).
( ) - > ServerRet
%% @doc Start the reloader.
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
stop ( ) - > ok
%% @doc Stop the reloader.
stop() ->
gen_server:call(?MODULE, stop).
%% gen_server callbacks
@spec init ( [ ] ) - > { ok , State }
%% @doc gen_server init, opens the server in an initial state.
init([]) ->
{ok, TRef} = timer:send_interval(timer:seconds(1), doit),
{ok, #state{last = stamp(), tref = TRef}}.
@spec handle_call(Args , From , State ) - > tuple ( )
%% @doc gen_server callback.
handle_call(stop, _From, State) ->
{stop, shutdown, stopped, State};
handle_call(_Req, _From, State) ->
{reply, {error, badrequest}, State}.
@spec handle_cast(Cast , State ) - > tuple ( )
%% @doc gen_server callback.
handle_cast(_Req, State) ->
{noreply, State}.
, State ) - > tuple ( )
%% @doc gen_server callback.
handle_info(doit, State) ->
Now = stamp(),
doit(State#state.last, Now),
{noreply, State#state{last = Now}};
handle_info(_Info, State) ->
{noreply, State}.
, State ) - > ok
%% @doc gen_server termination callback.
terminate(_Reason, State) ->
{ok, cancel} = timer:cancel(State#state.tref),
ok.
, State , _ Extra ) - > State
%% @doc gen_server code_change callback (trivial).
code_change(_Vsn, State, _Extra) ->
{ok, State}.
%% Internal API
doit(From, To) ->
[case file:read_file_info(Filename) of
{ok, #file_info{mtime = Mtime}} when Mtime >= From, Mtime < To ->
reload(Module);
{ok, _} ->
unmodified;
{error, enoent} ->
The Erlang compiler deletes existing .beam files if
%% recompiling fails. Maybe it's worth spitting out a
%% warning here, but I'd want to limit it to just once.
gone;
{error, Reason} ->
io:format("Error reading ~s's file info: ~p~n",
[Filename, Reason]),
error
end || {Module, Filename} <- code:all_loaded(), is_list(Filename)].
reload(Module) ->
io:format("Reloading ~p ...", [Module]),
code:purge(Module),
case code:load_file(Module) of
{module, Module} ->
io:format(" ok.~n"),
case erlang:function_exported(Module, test, 0) of
true ->
io:format(" - Calling ~p:test() ...", [Module]),
case catch Module:test() of
ok ->
io:format(" ok.~n"),
reload;
Reason ->
io:format(" fail: ~p.~n", [Reason]),
reload_but_test_failed
end;
false ->
reload
end;
{error, Reason} ->
io:format(" fail: ~p.~n", [Reason]),
error
end.
stamp() ->
erlang:localtime().
%%
%% Tests
%%
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
-endif.
| null |
https://raw.githubusercontent.com/erlangonrails/devdb/0e7eaa6bd810ec3892bfc3d933439560620d0941/dev/riak-0.11.0/deps/mochiweb/src/reloader.erl
|
erlang
|
during development.
External API
@doc Start the reloader.
@doc Start the reloader.
@doc Stop the reloader.
gen_server callbacks
@doc gen_server init, opens the server in an initial state.
@doc gen_server callback.
@doc gen_server callback.
@doc gen_server callback.
@doc gen_server termination callback.
@doc gen_server code_change callback (trivial).
Internal API
recompiling fails. Maybe it's worth spitting out a
warning here, but I'd want to limit it to just once.
Tests
|
2007 Mochi Media , Inc.
@author < >
@doc Erlang module for automatically reloading modified modules
-module(reloader).
-author("Matthew Dempsky <>").
-include_lib("kernel/include/file.hrl").
-behaviour(gen_server).
-export([start/0, start_link/0]).
-export([stop/0]).
-export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]).
-record(state, {last, tref}).
@spec start ( ) - > ServerRet
start() ->
gen_server:start({local, ?MODULE}, ?MODULE, [], []).
( ) - > ServerRet
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, [], []).
stop ( ) - > ok
stop() ->
gen_server:call(?MODULE, stop).
@spec init ( [ ] ) - > { ok , State }
init([]) ->
{ok, TRef} = timer:send_interval(timer:seconds(1), doit),
{ok, #state{last = stamp(), tref = TRef}}.
@spec handle_call(Args , From , State ) - > tuple ( )
handle_call(stop, _From, State) ->
{stop, shutdown, stopped, State};
handle_call(_Req, _From, State) ->
{reply, {error, badrequest}, State}.
@spec handle_cast(Cast , State ) - > tuple ( )
handle_cast(_Req, State) ->
{noreply, State}.
, State ) - > tuple ( )
handle_info(doit, State) ->
Now = stamp(),
doit(State#state.last, Now),
{noreply, State#state{last = Now}};
handle_info(_Info, State) ->
{noreply, State}.
, State ) - > ok
terminate(_Reason, State) ->
{ok, cancel} = timer:cancel(State#state.tref),
ok.
, State , _ Extra ) - > State
code_change(_Vsn, State, _Extra) ->
{ok, State}.
doit(From, To) ->
[case file:read_file_info(Filename) of
{ok, #file_info{mtime = Mtime}} when Mtime >= From, Mtime < To ->
reload(Module);
{ok, _} ->
unmodified;
{error, enoent} ->
The Erlang compiler deletes existing .beam files if
gone;
{error, Reason} ->
io:format("Error reading ~s's file info: ~p~n",
[Filename, Reason]),
error
end || {Module, Filename} <- code:all_loaded(), is_list(Filename)].
reload(Module) ->
io:format("Reloading ~p ...", [Module]),
code:purge(Module),
case code:load_file(Module) of
{module, Module} ->
io:format(" ok.~n"),
case erlang:function_exported(Module, test, 0) of
true ->
io:format(" - Calling ~p:test() ...", [Module]),
case catch Module:test() of
ok ->
io:format(" ok.~n"),
reload;
Reason ->
io:format(" fail: ~p.~n", [Reason]),
reload_but_test_failed
end;
false ->
reload
end;
{error, Reason} ->
io:format(" fail: ~p.~n", [Reason]),
error
end.
stamp() ->
erlang:localtime().
-include_lib("eunit/include/eunit.hrl").
-ifdef(TEST).
-endif.
|
73fdb7b3131b9f98cd50ae83c5b47e09b5a841d50a77542be53b5a3f5c721b29
|
zeromq/chumak
|
chumak_protocol.erl
|
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
%% @doc Parser of ZeroMQ protocol
%%
This module was created to make responsibility of decode and make a buffer of ZeroMQ wire protocol ,
%% the client of this module needs to announce that more bytes were been received by peer.
%%
-module(chumak_protocol).
-include("chumak.hrl").
-export_type([decoder/0]).
-export([build_greeting_frame/2,
build_hello_frame/1,
build_welcome_frame/1,
build_initiate_frame/2,
build_ready_frame/2,
new_decoder/1,
decoder_state/1, decoder_version/1, decoder_buffer/1,
decoder_mechanism/1, decoder_as_server/1,
decoder_security_data/1, set_decoder_security_data/2,
decode/2, continue_decode/1,
encode_old_subscribe/1, encode_old_cancel/1,
encode_command/1, encode_message_multipart/3,
encode_more_message/3, encode_last_message/3,
message_data/1, message_has_more/1
]).
-define(PROTOCOL_MAJOR, 3).
-define(PROTOCOL_MINOR, 1).
-define(SIGNATURE_SIZE, 11).
ENUM for frame type
-define(SMALL_LAST_MESSAGE, 0).
-define(SMALL_MORE_MESSAGE, 1).
-define(LARGE_LAST_MESSAGE, 2).
-define(LARGE_MORE_MESSAGE, 3).
-define(SMALL_COMMAND, 4).
-define(LARGE_COMMAND, 6).
-record(decoder, {
state=initial :: decoder_state(), %% the state of decoder
size=0 :: integer(),
buffer=nil :: nil | binary(),
next_state=nil :: nil | decoder_state(),
version_major=nil :: nil | {some, integer()}, %% number of the major version
version_minor=nil :: nil | {some, integer()}, %% number of the minor version
security_data=nil :: decoder_security_data(),
mechanism=nil :: nil | security_mechanism(),
as_server=false :: boolean()
}).
-record(message,{
frame :: binary(),
has_more :: true | false
}).
-type message() :: #message{}.
-type decoder() :: #decoder{}. %% the structure responsible to decode incoming bytes
-type decoder_state() :: 'initial' | 'waiting_minor_version' | 'waiting_mechanism' |
'waiting_as_server' | 'waiting_filler' | 'ready' |
'command_ready' | 'message_ready' | 'require_size'. %% the state of decoder
-type decoder_version() :: {MajorVersion::integer(), MinorVersion::integer()}.
-type decoder_security_data() :: #{} | chumak_curve:curve_data().
-type frame() :: binary(). %% the bytes received or sent
-type invalid_version() :: {invalid_version, Major::atom()}.
-type invalid_mechanism() :: {mechanism_not_supported_yet, Mechanism::atom()}.
-type bad_greeting_frame() :: {bad_greeting_frame, Frame::binary()}.
-type decode_reason() :: bad_greeting_frame() | invalid_version() | invalid_mechanism(). %% decode fail reason
-type decoder_ready() :: {ready, UpdatedDecoder::decoder()}. %% returned when decoder was finished greeting part.
-type decoder_ok() :: {ok, UpdatedDecoder::decoder()}. %% returned when decoder only decoded the frame.
returned when decoder was found one or more commands .
-type decoder_error() :: {error, Reason::decode_reason()}.
-type decoder_reply() :: decoder_ready() | decoder_ok() | decoder_cmds() | decoder_error(). %% reply of decoder command
%%
%% Public API
%%
%% @doc build_greeting_frame creates a new greeting frame done to send to peer.
-spec build_greeting_frame(AsServer::boolean(),
Mechanism::chumak:security_mechanism()) -> Frame::frame().
build_greeting_frame(AsServer, Mechanism) ->
Padding has size 8
Signature has size 10
MechanismBinary = encode_mechanism(Mechanism),
AsServerBinary = case AsServer of
false ->
<<8#0>>;
true ->
<<8#1>>
end,
Filler = binary:copy(<<8#0>>, 31),
<<Signature/binary, ?PROTOCOL_MAJOR, ?PROTOCOL_MINOR, MechanismBinary/binary,
AsServerBinary/binary, Filler/binary>>.
The HELLO Command
%%
The first command on a CurveZMQ connection is the HELLO command . The client
%% SHALL send a HELLO command after opening the stream connection. This command
SHALL be 200 octets long and have the following fields :
%%
The command ID , which is [ 5]"HELLO " .
%%
The CurveZMQ version number , which SHALL be the two octets 1 and 0 .
%%
An anti - amplification padding field . This SHALL be 70 octets , all zero . This
%% filler field ensures the HELLO command is larger than the WELCOME command,
%% so an attacker who spoofs a sender IP address cannot use the server to
overwhelm that innocent 3rd party with response data .
%%
The client 's public transient key C ' ( 32 octets ) . The client SHALL generate
%% a unique key pair for each connection it creates to a server. It SHALL
%% discard this key pair when it closes the connection, and it MUST NOT store
%% its secret key in permanent storage, nor share it in any way.
%%
A client short nonce ( 8 octets ) . The nonce SHALL be implicitly prefixed with
the 16 characters @@"CurveZMQHELLO---"@@ to form the 24 - octet nonce used to
%% encrypt and decrypt the signature box.
%%
The signature box ( 80 octets ) . This SHALL contain 64 zero octets , encrypted
%% from the client's transient key C' to the server's permanent key S.
%%
%% The server SHALL validate all fields and SHALL reject and disconnect clients
%% who send malformed HELLO commands.
%%
%% When the server gets a valid HELLO command, it SHALL generate a new
%% transient key pair, and encode both the public and secret key in a WELCOME
%% command, as explained below. The server SHALL not keep this transient key
%% pair and SHOULD keep minimal state for the client until the client responds
%% with a valid INITIATE command. This protects against denial-of-service
%% attacks where unauthenticated clients send many HELLO commands to consume
%% server resources.
%%
Note that the client uses an 8 octet " short nonce " in the HELLO , INITIATE ,
%% and MESSAGE commands. This nonce SHALL be an incrementing integer, and
%% unique to each command within a connection. The client SHALL NOT send more
than 2 ^ 64 - 1 commands in one connection . The server SHALL verify that a
%% client connection does use correctly incrementing short nonces, and SHALL
%% disconnect clients that reuse a short nonce.
%%
NOTE : the size of 70 for the padding is wrong , must be 72 .
HELLO command , 200 octets
%% hello = %d5 "HELLO" version padding hello-client hello-nonce hello-box
hello - version = % x1 % ; CurveZMQ major - minor version
%% hello-padding = 72%x00 ; Anti-amplification padding
%% hello-client = 32OCTET ; Client public transient key C'
hello - nonce = 8OCTET ; Short nonce , prefixed by " "
hello - box = 80OCTET ; Signature , Box [ 64 * % x0](C'->S )
NOTE : there is 1 additional byte for the size of the command name ,
so it adds up to 200 .
build_hello_frame(#{client_public_transient_key := ClientPublicTransientKey,
client_secret_transient_key := ClientSecretTransientKey,
curve_serverkey := ServerPermanentKey,
client_nonce := ClientShortNonce} = SecurityData) ->
CommandName = <<"HELLO">>,
CommandNameSize = <<5>>,
Version = <<1, 0>>,
Padding = <<0:72/integer-unit:8>>,
ClientShortNonceBinary = <<ClientShortNonce:8/integer-unit:8>>,
Nonce = <<"CurveZMQHELLO---", ClientShortNonceBinary/binary>>,
box(Msg , , Pk , Sk )
SignatureBox =
chumak_curve_if:box(<<0:64/integer-unit:8>>, Nonce, ServerPermanentKey,
ClientSecretTransientKey),
Command = <<CommandNameSize/binary, CommandName/binary, Version/binary,
Padding/binary, ClientPublicTransientKey/binary,
ClientShortNonceBinary/binary, SignatureBox/binary>>,
{encode_command(Command),
SecurityData#{client_nonce => ClientShortNonce + 1}}.
The WELCOME Command
%%
%% The server SHALL respond to a valid HELLO command with a WELCOME command.
This command SHALL be 168 octets long and have the following fields :
%%
%% The command ID, which is [7]"WELCOME".
%%
A server long nonce ( 16 octets ) . This nonce SHALL be implicitly prefixed by
the 8 characters " WELCOME- " to form a 24 - octet nonce used to encrypt and
%% decrypt the welcome box.
%%
A welcome box ( 144 octets ) that encrypts the server public transient key S '
( 32 octets ) and the server cookie ( 96 octets ) , from the server permanent key
%% S to the client's transient key C'.
%%
Note that the server uses a 16 - octet " long nonce " in the WELCOME command and
%% when creating a cookie. This nonce SHALL be unique for this server permanent
key . The recommended simplest strategy is to use 16 random octets from a
%% sufficiently good entropy source.
%%
The cookie consists of two fields :
%%
A server long nonce ( 16 octets ) . This nonce SHALL be implicitly prefixed by
the 8 characters @@"COOKIE--"@@ to form a 24 - octet nonce used to encrypt and
%% decrypt the cookie box.
%%
A cookie box ( 80 octets ) that holds the client public transient key C ' ( 32
octets ) and the server secret transient key s ' ( 32 octets ) , encrypted to and
%% from a secret short-term "cookie key". The server MUST discard from its
memory the cookie key after a short interval , for example 60 seconds , or as
%% soon as the client sends a valid INITIATE command.
%%
%% The server SHALL generate a new cookie for each WELCOME command it sends.
%%
%% The client SHALL validate all fields and SHALL disconnect from servers that
%% send malformed WELCOME commands.
%%
; WELCOME command , 168 octets
%% welcome = %d7 "WELCOME" welcome-nonce welcome-box
welcome - nonce = 16OCTET ; Long nonce , prefixed by " WELCOME- "
%% welcome-box = 144OCTET ; Box [S' + cookie](S->C')
%% ; This is the text sent encrypted in the box
%% ?? the Server public transient key ?? (bug in the spec).
%% cookie = cookie-nonce cookie-box
cookie - nonce = 16OCTET ; Long nonce , prefixed by " "
%% cookie-box = 80OCTET ; Box [C' + s'](K)
build_welcome_frame(#{server_public_transient_key := ServerPublicTransientKey,
server_secret_transient_key := ServerSecretTransientKey,
curve_secretkey := ServerSecretPermanentKey,
client_public_transient_key := ClientPublicTransientKey,
cookie_public_key := CookiePublicKey,
cookie_secret_key := CookieSecretKey} = CurveData) ->
LongNonce = chumak_curve_if:randombytes(16),
WelcomeBoxNonce = <<"WELCOME-", LongNonce/binary>>,
CookieBoxNonce = <<"COOKIE--", LongNonce/binary>>,
CookieBox =
chumak_curve_if:box(<<ClientPublicTransientKey/binary,
ServerSecretTransientKey/binary>>,
CookieBoxNonce, CookiePublicKey, CookieSecretKey),
Cookie = <<LongNonce/binary, CookieBox/binary>>,
WelcomeBox =
chumak_curve_if:box(<<ServerPublicTransientKey/binary, Cookie/binary>>,
WelcomeBoxNonce,
ClientPublicTransientKey, ServerSecretPermanentKey),
Welcome = <<7, <<"WELCOME">>/binary, LongNonce/binary, WelcomeBox/binary>>,
%% remove the transient keys (they will be returned by the client in the
%% initiate message).
NewCD = CurveData#{server_public_transient_key => <<>>,
server_secret_transient_key => <<>>,
client_public_transient_key => <<>>},
{encode_command(Welcome), NewCD}.
The INITIATE Command
%%
%% When the client receives a WELCOME command it can decrypt this to receive
%% the server's transient key S', and the cookie, which it must send back to
%% the server. The cookie is the only memory of the server's secret transient
%% key s'.
%%
%% The client SHALL respond to a valid WELCOME with an INITIATE command. This
command SHALL be at least 257 octets long and have the following fields :
%%
%% - The command ID, which is [8]"INITIATE".
%%
- The cookie provided by the server in the WELCOME command ( 96 octets ) .
%%
- A client short nonce ( 8 octets ) . The nonce SHALL be implicitly prefixed with
the 16 characters " CurveZMQINITIATE " to form the 24 - octet nonce used to
%% encrypt and decrypt the vouch box.
%%
- The initiate box ( 144 or more octets ) , by which the client securely sends
%% its permanent public key C to the server. The initiate box holds the client
permanent public key C ( 32 octets ) , the vouch ( 96 octets ) , and the metadata
%% (0 or more octets), encrypted from the client's transient key C' to the
%% server's transient key S'.
%%
The vouch itself consists of two fields :
%%
- A client long nonce ( 16 octets ) . This nonce SHALL be implicitly prefixed
with the 8 characters @@"VOUCH---"@@ to give a 24 - octet nonce , used to
%% encrypt and decrypt the vouch box. This nonce SHALL be unique for all
%% INITIATE commands from this client permanent key. A valid strategy is to use
16 random octets from a sufficiently good entropy source .
%%
- The vouch box ( 80 octets ) , that encrypts the client 's transient key C ' ( 32
octets ) and the server permanent key S ( 32 octets ) from the client permanent
%% key C to the server transient key S'.
%%
%% The metadata consists of a list of properties consisting of name and value
as size - specified strings . The name SHALL be 1 to 255 characters . Zero - sized
%% names are not valid. The case (upper or lower) of names SHALL NOT be
significant . The value SHALL be 0 to 2 ^ 31 - 1 octets of opaque binary data .
Zero - sized values are allowed . The semantics of the value depend on the
property . The value size field SHALL be four octets , in network order . Note
%% that this size field will mostly not be aligned in memory.
%%
%% The server SHALL validate all fields and SHALL reject and disconnect clients
%% who send malformed INITIATE commands.
%%
%% After decrypting the INITIATE command, the server MAY authenticate the
client based on its permanent public key C. If the client does not pass
%% authentication, the server SHALL not respond except by closing the
%% connection. If the client passes authentication the server SHALL send a
READY command and then immediately send MESSAGE commands .
; INITIATE command , 257 + octets
%% initiate = %d8 "INITIATE" cookie initiate-nonce initiate-box
%% initiate-cookie = cookie ; Server-provided cookie
%% initiate-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQINITIATE"
%% initiate-box = 144*OCTET ; Box [C + vouch + metadata](C'->S')
%% ; This is the text sent encrypted in the box
%% vouch = vouch-nonce vouch-box
%% vouch-nonce = 16OCTET ; Long nonce, prefixed by "VOUCH---"
%% vouch-box = 80OCTET ; Box [C',S](C->S')
%% metadata = *property
%% property = name value
%% name = OCTET *name-char
%% name-char = ALPHA | DIGIT | "-" | "_" | "." | "+"
%% value = value-size value-data
value - size = 4OCTET ; Size in network order
value - data = * OCTET ; 0 or more octets
build_initiate_frame(MetaData,
#{client_nonce := ClientShortNonce,
client_public_transient_key := ClientPublicTransientKey,
client_secret_transient_key := ClientSecretTransientKey,
curve_publickey := ClientPublicPermanentKey,
curve_secretkey := ClientSecretPermanentKey,
server_public_transient_key := ServerPublicTransientKey,
curve_serverkey := ServerPublicPermanentKey,
cookie := Cookie} = CurveData) ->
ClientShortNonceBinary = <<ClientShortNonce:8/integer-unit:8>>,
LongNonce = chumak_curve_if:randombytes(16),
VouchBoxNonce = <<"VOUCH---", LongNonce/binary>>,
InitiateBoxNonce = <<"CurveZMQINITIATE", ClientShortNonceBinary/binary>>,
The vouch box ( 80 octets ) , that encrypts the client 's transient key C '
( 32 octets ) and the server permanent key S ( 32 octets ) from the client
%% permanent key C to the server transient key S'.
VouchBox =
chumak_curve_if:box(<<ClientPublicTransientKey/binary,
ServerPublicPermanentKey/binary>>,
VouchBoxNonce,
ServerPublicTransientKey,
ClientSecretPermanentKey),
Vouch = <<LongNonce/binary, VouchBox/binary>>,
MetaDataBinary = chumak_command:encode_ready_properties(MetaData),
The initiate box holds the client permanent public key C ( 32 octets ) ,
the vouch ( 96 octets ) , and the metadata ( 0 or more octets ) , encrypted
%% from the client's transient key C' to the server's transient key S'.
InitiateBox =
chumak_curve_if:box(<<ClientPublicPermanentKey/binary, Vouch/binary,
MetaDataBinary/binary>>,
InitiateBoxNonce,
ServerPublicTransientKey,
ClientSecretTransientKey),
Initiate = <<8, <<"INITIATE">>/binary, Cookie/binary,
ClientShortNonceBinary/binary, InitiateBox/binary>>,
{encode_command(Initiate), CurveData#{client_nonce => ClientShortNonce + 1}}.
%% The READY Command
%%
%% The server SHALL respond to a valid INITIATE command with a READY command.
This command SHALL be at least 30 octets long and have the following fields :
%%
The command ID , which is [ 5]"READY " .
%%
A server short nonce ( 8 octets ) . The nonce SHALL be implicitly prefixed with
the 16 characters @@"CurveZMQREADY---"@@ to form the 24 - octet nonce used to
%% encrypt and decrypt the ready box.
%%
The ready box ( 16 or more octets ) . This shall contain metadata of the same
%% format as sent in the INITIATE command, encrypted from the server's
%% transient key S' to the client's transient key C'.
%%
%% The client SHALL validate all fields and SHALL disconnect from servers who
%% send malformed READY commands.
%%
The client MAY validate the meta - data . If the client accepts the meta - data ,
%% it SHALL then expect MESSAGE commands from the server.
%%
Note that the server uses an 8 octet " short nonce " in the HELLO , INITIATE ,
%% and MESSAGE commands. This nonce SHALL be an incrementing integer, and
%% unique to each command within a connection. The server SHALL NOT send more
than 2 ^ 64 - 1 commands in one connection . The client SHALL verify that a
%% server connection does use correctly incrementing short nonces, and SHALL
%% disconnect from servers that reuse a short nonce.
%%
%% NOTE: I am assuming that the list of commands above should be READY and
%% MESSAGE.
%%
; READY command , 30 + octets
%% ready = %d5 "READY" ready-nonce ready-box
%% ready-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQREADY---"
%% ready-box = 16*OCTET ; Box [metadata](S'->C')
build_ready_frame(MetaData,
#{client_public_transient_key := ClientPublicTransientKey,
server_secret_transient_key := ServerSecretTransientKey,
server_nonce := ServerShortNonce} = CurveData) ->
ServerShortNonceBinary = <<ServerShortNonce:8/integer-unit:8>>,
ReadyBoxNonce = <<"CurveZMQREADY---", ServerShortNonceBinary/binary>>,
MetaDataBinary = chumak_command:encode_ready_properties(MetaData),
The ready box ( 16 or more octets ) . This shall contain metadata of the
%% same format as sent in the INITIATE command, encrypted from the server's
%% transient key S' to the client's transient key C'.
ReadyBox =
chumak_curve_if:box(<<MetaDataBinary/binary>>,
ReadyBoxNonce, ClientPublicTransientKey,
ServerSecretTransientKey),
Ready = <<5, "READY", ServerShortNonceBinary/binary,
ReadyBox/binary>>,
{encode_command(Ready), CurveData#{server_nonce => ServerShortNonce + 1}}.
; MESSAGE command , 33 + octets
%% message = %d7 "MESSAGE" message_nonce message-box
%% message-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQMESSAGE-"
message - box = 17*OCTET ; Box [ payload](S'->C ' ) or ( C'->S ' )
%% ; This is the text sent encrypted in the box
%% payload = payload-flags payload-data
%% payload-flags = OCTET ; Explained below
payload - data = * octet ; 0 or more octets
build_message(Message,
curve,
#{role := client,
client_secret_transient_key := SecretKey,
server_public_transient_key := PublicKey,
client_nonce := ClientNonce} = SecurityData) ->
NonceBinary = <<ClientNonce:8/integer-unit:8>>,
Nonce = <<"CurveZMQMESSAGEC", NonceBinary/binary>>,
MessageBox =
chumak_curve_if:box(<<0, Message/binary>>,
Nonce, PublicKey, SecretKey),
{<<7, "MESSAGE", NonceBinary/binary, MessageBox/binary>>,
SecurityData#{client_nonce => ClientNonce + 1}};
build_message(Message,
curve,
#{role := server,
server_secret_transient_key := SecretKey,
client_public_transient_key := PublicKey,
server_nonce := ServerNonce} = SecurityData) ->
NonceBinary = <<ServerNonce:8/integer-unit:8>>,
Nonce = <<"CurveZMQMESSAGES", NonceBinary/binary>>,
MessageBox =
chumak_curve_if:box(<<0, Message/binary>>,
Nonce, PublicKey, SecretKey),
{<<7, "MESSAGE", NonceBinary/binary, MessageBox/binary>>,
SecurityData#{server_nonce => ServerNonce + 1}};
build_message(Message, _, SecurityData) ->
{Message, SecurityData}.
%% @doc new_decoder creates a new decoder waiting for greeting message
-spec new_decoder(SecurityData::decoder_security_data()) -> NewDecoder::decoder().
new_decoder(SecurityData) ->
#decoder{security_data = SecurityData}.
%% @doc decode reads incoming frame and generate an updated decoder
-spec decode(Decoder::decoder(), Frame::frame()) -> decoder_reply().
waiting the command , its first for performance reasons
decode(#decoder{state=ready}=Decoder, Frame) ->
<<Flag:1/binary, _/binary>> = Frame,
NextState = case Flag of
if bit 2 is enabled then is a traffic for a command
<<_:5, 1:1, _:1, _:1>> ->
command_ready;
if bit 2 is disabled then is a traffic for a message
<<_:5, 0:1, _:1, _:1>> ->
message_ready
end,
case Frame of
if bit 1 is disabled then is a small frame
<<_:5, _:1, 0:1, _:1, Size, _RemaingFrame/binary>> ->
require_size(Decoder, Size+2, Frame, NextState);
if bit 1 is enabled then is a large frame
<<_:5, _:1, 1:1, _:1, Size:64, _RemaingFrame/binary>> ->
require_size(Decoder, Size+9, Frame, NextState);
%% if size is remaining for small frame
<<_:5, _:1, 0:1, _:1>> ->
require_size(Decoder, 2, Frame, ready);
%% if size is remaining for large frame
<<_:5, _:1, 1:1, _:1, _TooShortToBeSize/binary>> ->
require_size(Decoder, 9, Frame, ready);
X ->
{error, {bad_ready_packet, X}}
end;
%% waiting the command to be buffered
decode(#decoder{state=command_ready}=Decoder, Frame) ->
case Frame of
<<?SMALL_COMMAND, CommandSize, RemaingFrame/binary>> ->
decode_command(Decoder, CommandSize, RemaingFrame);
<<?LARGE_COMMAND, CommandSize:64, RemaingFrame/binary>> ->
decode_command(Decoder, CommandSize, RemaingFrame);
X ->
{error, {bad_command_packet, X}}
end;
%% waiting the message to be buffered
decode(#decoder{state=message_ready}=Decoder, Frame) ->
case Frame of
if bit 1 is disabled then is a small message
<<_:5, _:1, 0:1, More:1, Size, RemaingFrame/binary>> ->
decode_message(Decoder, Size, RemaingFrame, More);
if bit 1 is enabled then is a large message
<<_:5, _:1, 1:1, More:1, Size:64, RemaingFrame/binary>> ->
decode_message(Decoder, Size, RemaingFrame, More);
X ->
{error, {bad_message_packet, X}}
end;
%% waits the size of buffer
decode(#decoder{state=require_size}=Decoder, Frame) ->
CurrentBuffer = Decoder#decoder.buffer,
require_size(Decoder, Decoder#decoder.size, <<CurrentBuffer/binary, Frame/binary>>, Decoder#decoder.next_state);
%% waiting the signature step
decode(#decoder{state=initial}=Decoder, Frame) when byte_size(Frame) >= ?SIGNATURE_SIZE->
case Frame of
<<16#ff, _Padding:64/bitstring, 16#7f, VersionMajor, RemaingFrame/binary>> when VersionMajor >= ?PROTOCOL_MAJOR ->
continue_decode(Decoder#decoder{state=waiting_minor_version, version_major={some, VersionMajor}}, RemaingFrame);
<<16#ff, _Padding:64/bitstring, 16#7f, VersionMajor, _RemaingFrame/binary>> ->
{error, {invalid_version, VersionMajor}};
X ->
{error, {bad_greeting_frame, X}}
end;
decode(#decoder{state=initial}=Decoder, Frame) ->
require_size(Decoder, ?SIGNATURE_SIZE, Frame, initial);
%% waiting the version step
decode(#decoder{state=waiting_minor_version}=Decoder, Frame) ->
case Frame of
<<VersionMinor, RemaingFrame/binary>> ->
continue_decode(Decoder#decoder{state=waiting_mechanism, version_minor={some, VersionMinor}}, RemaingFrame);
X ->
{error, {bad_greeting_frame, X}}
end;
%% waiting mechanism step
decode(#decoder{state=waiting_mechanism}=Decoder, Frame) ->
case Frame of
<<Mechanism:160/bitstring, RemaingFrame/binary>> ->
case strip_binary_to_atom(Mechanism) of
'NULL' ->
continue_decode(Decoder#decoder{state=waiting_as_server,
mechanism = null}, RemaingFrame);
'PLAIN' ->
{error, {mechanism_not_supported_yet, 'PLAIN'}};
'CURVE' ->
continue_decode(Decoder#decoder{state=waiting_as_server,
mechanism = curve}, RemaingFrame);
MechanismType ->
{error, {invalid_mechanism, MechanismType}}
end;
X ->
{error, {bad_greeting_frame, X}}
end;
%% waiting for as server
decode(#decoder{state=waiting_as_server}=Decoder, Frame) ->
case Frame of
<<AsServer, RemaingFrame/binary>> ->
AsServerBool = case AsServer of
1 -> true;
0 -> false
end,
continue_decode(Decoder#decoder{state=waiting_filler,
as_server = AsServerBool},
RemaingFrame)
end;
%% waiting for filler
decode(#decoder{state=waiting_filler}=Decoder, Frame) ->
case Frame of
<<0:248, RemaingFrame/binary>> ->
{ready, Decoder#decoder{state=ready, buffer=RemaingFrame}}
end.
%% @doc continue decoding after the decoder announce decoder has finished the greetings part
-spec continue_decode(Decoder::decoder()) -> decoder_reply().
continue_decode(#decoder{buffer=Buffer}=Decoder) when is_binary(Buffer) ->
continue_decode(Decoder#decoder{buffer=nil}, Buffer).
%% @doc decoder_state returns the current status of decoder
-spec decoder_state(Decoder::decoder()) -> State::decoder_state().
decoder_state(#decoder{state=State}) ->
State.
%% @doc decoder_version returns the current version of decoder
-spec decoder_version(Decoder::decoder()) -> State::decoder_version().
decoder_version(#decoder{version_major={some, VersionMajor}, version_minor={some, VersionMinor}}) ->
{VersionMajor, VersionMinor}.
%% @doc decoder_mechanism returns the current security mechanism
-spec decoder_mechanism(Decoder::decoder()) -> security_mechanism().
decoder_mechanism(#decoder{mechanism=Mechanism}) ->
Mechanism.
%% @doc decoder_as_server returns the as_server setting from the greeting
-spec decoder_as_server(Decoder::decoder()) -> boolean().
decoder_as_server(#decoder{as_server=AsServer}) ->
AsServer.
%% @doc Return the current buffer of a decoder
-spec decoder_buffer(Decoder::decoder()) -> binary() | nil.
decoder_buffer(#decoder{buffer=Buffer}) ->
Buffer.
%% @doc Return the security data of a decoder
-spec decoder_security_data(Decoder::decoder()) -> nil | chumak_curve:curve_data().
decoder_security_data(#decoder{security_data=SecurityData}) ->
SecurityData.
%% @doc Set the security data of a decoder
-spec set_decoder_security_data(
Decoder::decoder(),
SecurityData::decoder_security_data()) -> decoder().
set_decoder_security_data(Decoder, SecurityData) ->
Decoder#decoder{security_data = SecurityData}.
%% @doc Generate a traffic based com a command
-spec encode_command(Command::binary()) -> Traffic::binary().
encode_command(Command) when is_binary(Command) ->
encode_frame(?SMALL_COMMAND, ?LARGE_COMMAND, Command).
@doc encode a old format of subscriptions found in version 3.0 of zeromq
-spec encode_old_subscribe(Topic::binary()) -> Traffic::binary().
encode_old_subscribe(Topic) ->
{Encoded, _} = encode_last_message(<<1, Topic/binary>>, null, #{}),
Encoded.
@doc encode a old format of unsubscriptions found in version 3.0 of zeromq
-spec encode_old_cancel(Topic::binary()) -> Traffic::binary().
encode_old_cancel(Topic) ->
{Encoded, _} = encode_last_message(<<0, Topic/binary>>, null, #{}),
Encoded.
%% @doc Generate a traffic based com a message with multi parts
-spec encode_message_multipart([Message::binary()],
Mechanism::security_mechanism(),
SecurityData::map()) -> {Traffic::binary(),
NewSecurityData::map()}.
%% TODO: check this - is this how multipart messages work?
encode_message_multipart(Multipart, Mechanism, SecurityData) ->
More = lists:sublist(Multipart, length(Multipart) -1),
Last = lists:last(Multipart),
{MoreTrafficList, NewSecurityData} =
lists:mapfoldl(fun(Part, SDataAcc) ->
encode_more_message(Part, Mechanism, SDataAcc)
end, SecurityData, More),
MoreTraffic = binary:list_to_bin(MoreTrafficList),
{LastTraffic, FinalSecData} = encode_last_message(Last, Mechanism,
NewSecurityData),
{<<MoreTraffic/binary, LastTraffic/binary>>, FinalSecData}.
%% @doc Generate a traffic based on a message
-spec encode_more_message(Message::binary(),
Mechanism::security_mechanism(),
SecurityData::map()) -> {Traffic::binary(), map()}.
encode_more_message(Message, Mechanism, SecurityData)
when is_binary(Message) ->
{Frame, NewSecurityData} = build_message(Message,
Mechanism,
SecurityData),
{encode_frame(?SMALL_MORE_MESSAGE, ?LARGE_MORE_MESSAGE, Frame),
NewSecurityData}.
%% @doc Generate a traffic based on a message
-spec encode_last_message(Message::binary(),
Mechanism::security_mechanism(),
SecurityData::map()) -> {Traffic::binary(), map()}.
encode_last_message(Message, Mechanism, SecurityData)
when is_binary(Message) ->
{Frame, NewSecurityData} = build_message(Message,
Mechanism,
SecurityData),
{encode_frame(?SMALL_LAST_MESSAGE, ?LARGE_LAST_MESSAGE, Frame),
NewSecurityData}.
%% @doc Return data for a message
-spec message_data(Message::message()) -> Frame::binary().
message_data(#message{frame=Data}) ->
Data.
%% @doc Return if message has the flag marked to receive more messages
-spec message_has_more(Message::message()) -> true | false.
message_has_more(#message{has_more=HasMore}) ->
HasMore.
%%
%% Private API
%%
continue_decode(Decoder, <<>>) ->
{ok, Decoder};
continue_decode(Decoder, Frame) ->
decode(Decoder, Frame).
decode_command(#decoder{security_data = SecurityData} = Decoder,
Size, Frame) ->
<<CommandFrame:Size/binary, RemaingFrame/binary>> = Frame,
case chumak_command:decode(CommandFrame, SecurityData) of
{ok, Command, NewSecurityData} ->
accumule_commands(Decoder#decoder{security_data = NewSecurityData},
Command, RemaingFrame);
{error, _} = Error ->
Error
end.
decode_message(#decoder{security_data = SecurityData} = Decoder,
Size, Frame, MoreFlag) ->
HasMore = case MoreFlag of
1 ->
true;
0 ->
false
end,
<<MessageFrame:Size/binary, RemaingFrame/binary>> = Frame,
{DecodedFrame, NewSecurityData} = decode_frame(MessageFrame, SecurityData),
accumule_commands(Decoder#decoder{security_data = NewSecurityData},
#message{frame=DecodedFrame, has_more=HasMore},
RemaingFrame).
decode_frame(CurveMessage, #{mechanism := curve} = SecurityData) ->
case chumak_command:decode(CurveMessage, SecurityData) of
{ok, Message, NewSecurityData} ->
{Message, NewSecurityData}
end;
decode_frame(Frame, SecurityData) ->
{Frame, SecurityData}.
accumule_commands(Decoder, Command, Frame) ->
ReadyDecoder = Decoder#decoder{state=ready},
case continue_decode(ReadyDecoder, Frame) of
{ok, UpdatedDecoder} ->
{ok, UpdatedDecoder, [Command]};
{ok, UpdatedDecoder, Commands} ->
{ok, UpdatedDecoder, [Command|Commands]};
Error ->
Error
end.
%% when length of Frame are validated
require_size(Decoder, Size, Frame, NextState) when byte_size(Frame) >= Size->
decode(Decoder#decoder{state=NextState, buffer=nil}, Frame);
require_size(Decoder, Size, Frame, NextState) ->
{ok, Decoder#decoder{state=require_size, size=Size, buffer=Frame, next_state=NextState}}.
strip_binary_to_atom(Bin) ->
[T, _] = binary:split(Bin, <<0>>),
binary_to_atom(T, utf8).
%% encode small frame
encode_frame(SmallFlag, _LargeFlag, Frame) when byte_size(Frame) < 256 ->
Size = byte_size(Frame),
<<SmallFlag, Size, Frame/binary>>;
%% encode large frame
encode_frame(_SmallFlag, LargeFlag, Frame) ->
Size = byte_size(Frame),
SizeFrame = binary:encode_unsigned(Size),
Padding = binary:copy(<<0>>, 8-byte_size(SizeFrame)),
<<LargeFlag, Padding/binary, SizeFrame/binary, Frame/binary>>.
%% The security mechanism is an ASCII string, null-padded as needed to fit
20 octets .
encode_mechanism(null) ->
<< <<"NULL">>/binary, 0:128>>;
encode_mechanism(curve) ->
<< <<"CURVE">>/binary, 0:120>>.
| null |
https://raw.githubusercontent.com/zeromq/chumak/e705fa6db05dc3f4801f5cc71eb18b0e60f7ba35/src/chumak_protocol.erl
|
erlang
|
@doc Parser of ZeroMQ protocol
the client of this module needs to announce that more bytes were been received by peer.
the state of decoder
number of the major version
number of the minor version
the structure responsible to decode incoming bytes
the state of decoder
the bytes received or sent
decode fail reason
returned when decoder was finished greeting part.
returned when decoder only decoded the frame.
reply of decoder command
Public API
@doc build_greeting_frame creates a new greeting frame done to send to peer.
SHALL send a HELLO command after opening the stream connection. This command
filler field ensures the HELLO command is larger than the WELCOME command,
so an attacker who spoofs a sender IP address cannot use the server to
a unique key pair for each connection it creates to a server. It SHALL
discard this key pair when it closes the connection, and it MUST NOT store
its secret key in permanent storage, nor share it in any way.
encrypt and decrypt the signature box.
from the client's transient key C' to the server's permanent key S.
The server SHALL validate all fields and SHALL reject and disconnect clients
who send malformed HELLO commands.
When the server gets a valid HELLO command, it SHALL generate a new
transient key pair, and encode both the public and secret key in a WELCOME
command, as explained below. The server SHALL not keep this transient key
pair and SHOULD keep minimal state for the client until the client responds
with a valid INITIATE command. This protects against denial-of-service
attacks where unauthenticated clients send many HELLO commands to consume
server resources.
and MESSAGE commands. This nonce SHALL be an incrementing integer, and
unique to each command within a connection. The client SHALL NOT send more
client connection does use correctly incrementing short nonces, and SHALL
disconnect clients that reuse a short nonce.
hello = %d5 "HELLO" version padding hello-client hello-nonce hello-box
x1 % ; CurveZMQ major - minor version
hello-padding = 72%x00 ; Anti-amplification padding
hello-client = 32OCTET ; Client public transient key C'
x0](C'->S )
The server SHALL respond to a valid HELLO command with a WELCOME command.
The command ID, which is [7]"WELCOME".
decrypt the welcome box.
S to the client's transient key C'.
when creating a cookie. This nonce SHALL be unique for this server permanent
sufficiently good entropy source.
decrypt the cookie box.
from a secret short-term "cookie key". The server MUST discard from its
soon as the client sends a valid INITIATE command.
The server SHALL generate a new cookie for each WELCOME command it sends.
The client SHALL validate all fields and SHALL disconnect from servers that
send malformed WELCOME commands.
welcome = %d7 "WELCOME" welcome-nonce welcome-box
welcome-box = 144OCTET ; Box [S' + cookie](S->C')
; This is the text sent encrypted in the box
?? the Server public transient key ?? (bug in the spec).
cookie = cookie-nonce cookie-box
cookie-box = 80OCTET ; Box [C' + s'](K)
remove the transient keys (they will be returned by the client in the
initiate message).
When the client receives a WELCOME command it can decrypt this to receive
the server's transient key S', and the cookie, which it must send back to
the server. The cookie is the only memory of the server's secret transient
key s'.
The client SHALL respond to a valid WELCOME with an INITIATE command. This
- The command ID, which is [8]"INITIATE".
encrypt and decrypt the vouch box.
its permanent public key C to the server. The initiate box holds the client
(0 or more octets), encrypted from the client's transient key C' to the
server's transient key S'.
encrypt and decrypt the vouch box. This nonce SHALL be unique for all
INITIATE commands from this client permanent key. A valid strategy is to use
key C to the server transient key S'.
The metadata consists of a list of properties consisting of name and value
names are not valid. The case (upper or lower) of names SHALL NOT be
that this size field will mostly not be aligned in memory.
The server SHALL validate all fields and SHALL reject and disconnect clients
who send malformed INITIATE commands.
After decrypting the INITIATE command, the server MAY authenticate the
authentication, the server SHALL not respond except by closing the
connection. If the client passes authentication the server SHALL send a
initiate = %d8 "INITIATE" cookie initiate-nonce initiate-box
initiate-cookie = cookie ; Server-provided cookie
initiate-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQINITIATE"
initiate-box = 144*OCTET ; Box [C + vouch + metadata](C'->S')
; This is the text sent encrypted in the box
vouch = vouch-nonce vouch-box
vouch-nonce = 16OCTET ; Long nonce, prefixed by "VOUCH---"
vouch-box = 80OCTET ; Box [C',S](C->S')
metadata = *property
property = name value
name = OCTET *name-char
name-char = ALPHA | DIGIT | "-" | "_" | "." | "+"
value = value-size value-data
permanent key C to the server transient key S'.
from the client's transient key C' to the server's transient key S'.
The READY Command
The server SHALL respond to a valid INITIATE command with a READY command.
encrypt and decrypt the ready box.
format as sent in the INITIATE command, encrypted from the server's
transient key S' to the client's transient key C'.
The client SHALL validate all fields and SHALL disconnect from servers who
send malformed READY commands.
it SHALL then expect MESSAGE commands from the server.
and MESSAGE commands. This nonce SHALL be an incrementing integer, and
unique to each command within a connection. The server SHALL NOT send more
server connection does use correctly incrementing short nonces, and SHALL
disconnect from servers that reuse a short nonce.
NOTE: I am assuming that the list of commands above should be READY and
MESSAGE.
ready = %d5 "READY" ready-nonce ready-box
ready-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQREADY---"
ready-box = 16*OCTET ; Box [metadata](S'->C')
same format as sent in the INITIATE command, encrypted from the server's
transient key S' to the client's transient key C'.
message = %d7 "MESSAGE" message_nonce message-box
message-nonce = 8OCTET ; Short nonce, prefixed by "CurveZMQMESSAGE-"
; This is the text sent encrypted in the box
payload = payload-flags payload-data
payload-flags = OCTET ; Explained below
@doc new_decoder creates a new decoder waiting for greeting message
@doc decode reads incoming frame and generate an updated decoder
if size is remaining for small frame
if size is remaining for large frame
waiting the command to be buffered
waiting the message to be buffered
waits the size of buffer
waiting the signature step
waiting the version step
waiting mechanism step
waiting for as server
waiting for filler
@doc continue decoding after the decoder announce decoder has finished the greetings part
@doc decoder_state returns the current status of decoder
@doc decoder_version returns the current version of decoder
@doc decoder_mechanism returns the current security mechanism
@doc decoder_as_server returns the as_server setting from the greeting
@doc Return the current buffer of a decoder
@doc Return the security data of a decoder
@doc Set the security data of a decoder
@doc Generate a traffic based com a command
@doc Generate a traffic based com a message with multi parts
TODO: check this - is this how multipart messages work?
@doc Generate a traffic based on a message
@doc Generate a traffic based on a message
@doc Return data for a message
@doc Return if message has the flag marked to receive more messages
Private API
when length of Frame are validated
encode small frame
encode large frame
The security mechanism is an ASCII string, null-padded as needed to fit
|
This Source Code Form is subject to the terms of the Mozilla Public
License , v. 2.0 . If a copy of the MPL was not distributed with this
file , You can obtain one at /.
This module was created to make responsibility of decode and make a buffer of ZeroMQ wire protocol ,
-module(chumak_protocol).
-include("chumak.hrl").
-export_type([decoder/0]).
-export([build_greeting_frame/2,
build_hello_frame/1,
build_welcome_frame/1,
build_initiate_frame/2,
build_ready_frame/2,
new_decoder/1,
decoder_state/1, decoder_version/1, decoder_buffer/1,
decoder_mechanism/1, decoder_as_server/1,
decoder_security_data/1, set_decoder_security_data/2,
decode/2, continue_decode/1,
encode_old_subscribe/1, encode_old_cancel/1,
encode_command/1, encode_message_multipart/3,
encode_more_message/3, encode_last_message/3,
message_data/1, message_has_more/1
]).
-define(PROTOCOL_MAJOR, 3).
-define(PROTOCOL_MINOR, 1).
-define(SIGNATURE_SIZE, 11).
ENUM for frame type
-define(SMALL_LAST_MESSAGE, 0).
-define(SMALL_MORE_MESSAGE, 1).
-define(LARGE_LAST_MESSAGE, 2).
-define(LARGE_MORE_MESSAGE, 3).
-define(SMALL_COMMAND, 4).
-define(LARGE_COMMAND, 6).
-record(decoder, {
size=0 :: integer(),
buffer=nil :: nil | binary(),
next_state=nil :: nil | decoder_state(),
security_data=nil :: decoder_security_data(),
mechanism=nil :: nil | security_mechanism(),
as_server=false :: boolean()
}).
-record(message,{
frame :: binary(),
has_more :: true | false
}).
-type message() :: #message{}.
-type decoder_state() :: 'initial' | 'waiting_minor_version' | 'waiting_mechanism' |
'waiting_as_server' | 'waiting_filler' | 'ready' |
-type decoder_version() :: {MajorVersion::integer(), MinorVersion::integer()}.
-type decoder_security_data() :: #{} | chumak_curve:curve_data().
-type invalid_version() :: {invalid_version, Major::atom()}.
-type invalid_mechanism() :: {mechanism_not_supported_yet, Mechanism::atom()}.
-type bad_greeting_frame() :: {bad_greeting_frame, Frame::binary()}.
returned when decoder was found one or more commands .
-type decoder_error() :: {error, Reason::decode_reason()}.
-spec build_greeting_frame(AsServer::boolean(),
Mechanism::chumak:security_mechanism()) -> Frame::frame().
build_greeting_frame(AsServer, Mechanism) ->
Padding has size 8
Signature has size 10
MechanismBinary = encode_mechanism(Mechanism),
AsServerBinary = case AsServer of
false ->
<<8#0>>;
true ->
<<8#1>>
end,
Filler = binary:copy(<<8#0>>, 31),
<<Signature/binary, ?PROTOCOL_MAJOR, ?PROTOCOL_MINOR, MechanismBinary/binary,
AsServerBinary/binary, Filler/binary>>.
The HELLO Command
The first command on a CurveZMQ connection is the HELLO command . The client
SHALL be 200 octets long and have the following fields :
The command ID , which is [ 5]"HELLO " .
The CurveZMQ version number , which SHALL be the two octets 1 and 0 .
An anti - amplification padding field . This SHALL be 70 octets , all zero . This
overwhelm that innocent 3rd party with response data .
The client 's public transient key C ' ( 32 octets ) . The client SHALL generate
A client short nonce ( 8 octets ) . The nonce SHALL be implicitly prefixed with
the 16 characters @@"CurveZMQHELLO---"@@ to form the 24 - octet nonce used to
The signature box ( 80 octets ) . This SHALL contain 64 zero octets , encrypted
Note that the client uses an 8 octet " short nonce " in the HELLO , INITIATE ,
than 2 ^ 64 - 1 commands in one connection . The server SHALL verify that a
NOTE : the size of 70 for the padding is wrong , must be 72 .
HELLO command , 200 octets
hello - nonce = 8OCTET ; Short nonce , prefixed by " "
NOTE : there is 1 additional byte for the size of the command name ,
so it adds up to 200 .
build_hello_frame(#{client_public_transient_key := ClientPublicTransientKey,
client_secret_transient_key := ClientSecretTransientKey,
curve_serverkey := ServerPermanentKey,
client_nonce := ClientShortNonce} = SecurityData) ->
CommandName = <<"HELLO">>,
CommandNameSize = <<5>>,
Version = <<1, 0>>,
Padding = <<0:72/integer-unit:8>>,
ClientShortNonceBinary = <<ClientShortNonce:8/integer-unit:8>>,
Nonce = <<"CurveZMQHELLO---", ClientShortNonceBinary/binary>>,
box(Msg , , Pk , Sk )
SignatureBox =
chumak_curve_if:box(<<0:64/integer-unit:8>>, Nonce, ServerPermanentKey,
ClientSecretTransientKey),
Command = <<CommandNameSize/binary, CommandName/binary, Version/binary,
Padding/binary, ClientPublicTransientKey/binary,
ClientShortNonceBinary/binary, SignatureBox/binary>>,
{encode_command(Command),
SecurityData#{client_nonce => ClientShortNonce + 1}}.
The WELCOME Command
This command SHALL be 168 octets long and have the following fields :
A server long nonce ( 16 octets ) . This nonce SHALL be implicitly prefixed by
the 8 characters " WELCOME- " to form a 24 - octet nonce used to encrypt and
A welcome box ( 144 octets ) that encrypts the server public transient key S '
( 32 octets ) and the server cookie ( 96 octets ) , from the server permanent key
Note that the server uses a 16 - octet " long nonce " in the WELCOME command and
key . The recommended simplest strategy is to use 16 random octets from a
The cookie consists of two fields :
A server long nonce ( 16 octets ) . This nonce SHALL be implicitly prefixed by
the 8 characters @@"COOKIE--"@@ to form a 24 - octet nonce used to encrypt and
A cookie box ( 80 octets ) that holds the client public transient key C ' ( 32
octets ) and the server secret transient key s ' ( 32 octets ) , encrypted to and
memory the cookie key after a short interval , for example 60 seconds , or as
; WELCOME command , 168 octets
welcome - nonce = 16OCTET ; Long nonce , prefixed by " WELCOME- "
cookie - nonce = 16OCTET ; Long nonce , prefixed by " "
build_welcome_frame(#{server_public_transient_key := ServerPublicTransientKey,
server_secret_transient_key := ServerSecretTransientKey,
curve_secretkey := ServerSecretPermanentKey,
client_public_transient_key := ClientPublicTransientKey,
cookie_public_key := CookiePublicKey,
cookie_secret_key := CookieSecretKey} = CurveData) ->
LongNonce = chumak_curve_if:randombytes(16),
WelcomeBoxNonce = <<"WELCOME-", LongNonce/binary>>,
CookieBoxNonce = <<"COOKIE--", LongNonce/binary>>,
CookieBox =
chumak_curve_if:box(<<ClientPublicTransientKey/binary,
ServerSecretTransientKey/binary>>,
CookieBoxNonce, CookiePublicKey, CookieSecretKey),
Cookie = <<LongNonce/binary, CookieBox/binary>>,
WelcomeBox =
chumak_curve_if:box(<<ServerPublicTransientKey/binary, Cookie/binary>>,
WelcomeBoxNonce,
ClientPublicTransientKey, ServerSecretPermanentKey),
Welcome = <<7, <<"WELCOME">>/binary, LongNonce/binary, WelcomeBox/binary>>,
NewCD = CurveData#{server_public_transient_key => <<>>,
server_secret_transient_key => <<>>,
client_public_transient_key => <<>>},
{encode_command(Welcome), NewCD}.
The INITIATE Command
command SHALL be at least 257 octets long and have the following fields :
- The cookie provided by the server in the WELCOME command ( 96 octets ) .
- A client short nonce ( 8 octets ) . The nonce SHALL be implicitly prefixed with
the 16 characters " CurveZMQINITIATE " to form the 24 - octet nonce used to
- The initiate box ( 144 or more octets ) , by which the client securely sends
permanent public key C ( 32 octets ) , the vouch ( 96 octets ) , and the metadata
The vouch itself consists of two fields :
- A client long nonce ( 16 octets ) . This nonce SHALL be implicitly prefixed
with the 8 characters @@"VOUCH---"@@ to give a 24 - octet nonce , used to
16 random octets from a sufficiently good entropy source .
- The vouch box ( 80 octets ) , that encrypts the client 's transient key C ' ( 32
octets ) and the server permanent key S ( 32 octets ) from the client permanent
as size - specified strings . The name SHALL be 1 to 255 characters . Zero - sized
significant . The value SHALL be 0 to 2 ^ 31 - 1 octets of opaque binary data .
Zero - sized values are allowed . The semantics of the value depend on the
property . The value size field SHALL be four octets , in network order . Note
client based on its permanent public key C. If the client does not pass
READY command and then immediately send MESSAGE commands .
; INITIATE command , 257 + octets
value - size = 4OCTET ; Size in network order
value - data = * OCTET ; 0 or more octets
build_initiate_frame(MetaData,
#{client_nonce := ClientShortNonce,
client_public_transient_key := ClientPublicTransientKey,
client_secret_transient_key := ClientSecretTransientKey,
curve_publickey := ClientPublicPermanentKey,
curve_secretkey := ClientSecretPermanentKey,
server_public_transient_key := ServerPublicTransientKey,
curve_serverkey := ServerPublicPermanentKey,
cookie := Cookie} = CurveData) ->
ClientShortNonceBinary = <<ClientShortNonce:8/integer-unit:8>>,
LongNonce = chumak_curve_if:randombytes(16),
VouchBoxNonce = <<"VOUCH---", LongNonce/binary>>,
InitiateBoxNonce = <<"CurveZMQINITIATE", ClientShortNonceBinary/binary>>,
The vouch box ( 80 octets ) , that encrypts the client 's transient key C '
( 32 octets ) and the server permanent key S ( 32 octets ) from the client
VouchBox =
chumak_curve_if:box(<<ClientPublicTransientKey/binary,
ServerPublicPermanentKey/binary>>,
VouchBoxNonce,
ServerPublicTransientKey,
ClientSecretPermanentKey),
Vouch = <<LongNonce/binary, VouchBox/binary>>,
MetaDataBinary = chumak_command:encode_ready_properties(MetaData),
The initiate box holds the client permanent public key C ( 32 octets ) ,
the vouch ( 96 octets ) , and the metadata ( 0 or more octets ) , encrypted
InitiateBox =
chumak_curve_if:box(<<ClientPublicPermanentKey/binary, Vouch/binary,
MetaDataBinary/binary>>,
InitiateBoxNonce,
ServerPublicTransientKey,
ClientSecretTransientKey),
Initiate = <<8, <<"INITIATE">>/binary, Cookie/binary,
ClientShortNonceBinary/binary, InitiateBox/binary>>,
{encode_command(Initiate), CurveData#{client_nonce => ClientShortNonce + 1}}.
This command SHALL be at least 30 octets long and have the following fields :
The command ID , which is [ 5]"READY " .
A server short nonce ( 8 octets ) . The nonce SHALL be implicitly prefixed with
the 16 characters @@"CurveZMQREADY---"@@ to form the 24 - octet nonce used to
The ready box ( 16 or more octets ) . This shall contain metadata of the same
The client MAY validate the meta - data . If the client accepts the meta - data ,
Note that the server uses an 8 octet " short nonce " in the HELLO , INITIATE ,
than 2 ^ 64 - 1 commands in one connection . The client SHALL verify that a
; READY command , 30 + octets
build_ready_frame(MetaData,
#{client_public_transient_key := ClientPublicTransientKey,
server_secret_transient_key := ServerSecretTransientKey,
server_nonce := ServerShortNonce} = CurveData) ->
ServerShortNonceBinary = <<ServerShortNonce:8/integer-unit:8>>,
ReadyBoxNonce = <<"CurveZMQREADY---", ServerShortNonceBinary/binary>>,
MetaDataBinary = chumak_command:encode_ready_properties(MetaData),
The ready box ( 16 or more octets ) . This shall contain metadata of the
ReadyBox =
chumak_curve_if:box(<<MetaDataBinary/binary>>,
ReadyBoxNonce, ClientPublicTransientKey,
ServerSecretTransientKey),
Ready = <<5, "READY", ServerShortNonceBinary/binary,
ReadyBox/binary>>,
{encode_command(Ready), CurveData#{server_nonce => ServerShortNonce + 1}}.
; MESSAGE command , 33 + octets
message - box = 17*OCTET ; Box [ payload](S'->C ' ) or ( C'->S ' )
payload - data = * octet ; 0 or more octets
build_message(Message,
curve,
#{role := client,
client_secret_transient_key := SecretKey,
server_public_transient_key := PublicKey,
client_nonce := ClientNonce} = SecurityData) ->
NonceBinary = <<ClientNonce:8/integer-unit:8>>,
Nonce = <<"CurveZMQMESSAGEC", NonceBinary/binary>>,
MessageBox =
chumak_curve_if:box(<<0, Message/binary>>,
Nonce, PublicKey, SecretKey),
{<<7, "MESSAGE", NonceBinary/binary, MessageBox/binary>>,
SecurityData#{client_nonce => ClientNonce + 1}};
build_message(Message,
curve,
#{role := server,
server_secret_transient_key := SecretKey,
client_public_transient_key := PublicKey,
server_nonce := ServerNonce} = SecurityData) ->
NonceBinary = <<ServerNonce:8/integer-unit:8>>,
Nonce = <<"CurveZMQMESSAGES", NonceBinary/binary>>,
MessageBox =
chumak_curve_if:box(<<0, Message/binary>>,
Nonce, PublicKey, SecretKey),
{<<7, "MESSAGE", NonceBinary/binary, MessageBox/binary>>,
SecurityData#{server_nonce => ServerNonce + 1}};
build_message(Message, _, SecurityData) ->
{Message, SecurityData}.
-spec new_decoder(SecurityData::decoder_security_data()) -> NewDecoder::decoder().
new_decoder(SecurityData) ->
#decoder{security_data = SecurityData}.
-spec decode(Decoder::decoder(), Frame::frame()) -> decoder_reply().
waiting the command , its first for performance reasons
decode(#decoder{state=ready}=Decoder, Frame) ->
<<Flag:1/binary, _/binary>> = Frame,
NextState = case Flag of
if bit 2 is enabled then is a traffic for a command
<<_:5, 1:1, _:1, _:1>> ->
command_ready;
if bit 2 is disabled then is a traffic for a message
<<_:5, 0:1, _:1, _:1>> ->
message_ready
end,
case Frame of
if bit 1 is disabled then is a small frame
<<_:5, _:1, 0:1, _:1, Size, _RemaingFrame/binary>> ->
require_size(Decoder, Size+2, Frame, NextState);
if bit 1 is enabled then is a large frame
<<_:5, _:1, 1:1, _:1, Size:64, _RemaingFrame/binary>> ->
require_size(Decoder, Size+9, Frame, NextState);
<<_:5, _:1, 0:1, _:1>> ->
require_size(Decoder, 2, Frame, ready);
<<_:5, _:1, 1:1, _:1, _TooShortToBeSize/binary>> ->
require_size(Decoder, 9, Frame, ready);
X ->
{error, {bad_ready_packet, X}}
end;
decode(#decoder{state=command_ready}=Decoder, Frame) ->
case Frame of
<<?SMALL_COMMAND, CommandSize, RemaingFrame/binary>> ->
decode_command(Decoder, CommandSize, RemaingFrame);
<<?LARGE_COMMAND, CommandSize:64, RemaingFrame/binary>> ->
decode_command(Decoder, CommandSize, RemaingFrame);
X ->
{error, {bad_command_packet, X}}
end;
decode(#decoder{state=message_ready}=Decoder, Frame) ->
case Frame of
if bit 1 is disabled then is a small message
<<_:5, _:1, 0:1, More:1, Size, RemaingFrame/binary>> ->
decode_message(Decoder, Size, RemaingFrame, More);
if bit 1 is enabled then is a large message
<<_:5, _:1, 1:1, More:1, Size:64, RemaingFrame/binary>> ->
decode_message(Decoder, Size, RemaingFrame, More);
X ->
{error, {bad_message_packet, X}}
end;
decode(#decoder{state=require_size}=Decoder, Frame) ->
CurrentBuffer = Decoder#decoder.buffer,
require_size(Decoder, Decoder#decoder.size, <<CurrentBuffer/binary, Frame/binary>>, Decoder#decoder.next_state);
decode(#decoder{state=initial}=Decoder, Frame) when byte_size(Frame) >= ?SIGNATURE_SIZE->
case Frame of
<<16#ff, _Padding:64/bitstring, 16#7f, VersionMajor, RemaingFrame/binary>> when VersionMajor >= ?PROTOCOL_MAJOR ->
continue_decode(Decoder#decoder{state=waiting_minor_version, version_major={some, VersionMajor}}, RemaingFrame);
<<16#ff, _Padding:64/bitstring, 16#7f, VersionMajor, _RemaingFrame/binary>> ->
{error, {invalid_version, VersionMajor}};
X ->
{error, {bad_greeting_frame, X}}
end;
decode(#decoder{state=initial}=Decoder, Frame) ->
require_size(Decoder, ?SIGNATURE_SIZE, Frame, initial);
decode(#decoder{state=waiting_minor_version}=Decoder, Frame) ->
case Frame of
<<VersionMinor, RemaingFrame/binary>> ->
continue_decode(Decoder#decoder{state=waiting_mechanism, version_minor={some, VersionMinor}}, RemaingFrame);
X ->
{error, {bad_greeting_frame, X}}
end;
decode(#decoder{state=waiting_mechanism}=Decoder, Frame) ->
case Frame of
<<Mechanism:160/bitstring, RemaingFrame/binary>> ->
case strip_binary_to_atom(Mechanism) of
'NULL' ->
continue_decode(Decoder#decoder{state=waiting_as_server,
mechanism = null}, RemaingFrame);
'PLAIN' ->
{error, {mechanism_not_supported_yet, 'PLAIN'}};
'CURVE' ->
continue_decode(Decoder#decoder{state=waiting_as_server,
mechanism = curve}, RemaingFrame);
MechanismType ->
{error, {invalid_mechanism, MechanismType}}
end;
X ->
{error, {bad_greeting_frame, X}}
end;
decode(#decoder{state=waiting_as_server}=Decoder, Frame) ->
case Frame of
<<AsServer, RemaingFrame/binary>> ->
AsServerBool = case AsServer of
1 -> true;
0 -> false
end,
continue_decode(Decoder#decoder{state=waiting_filler,
as_server = AsServerBool},
RemaingFrame)
end;
decode(#decoder{state=waiting_filler}=Decoder, Frame) ->
case Frame of
<<0:248, RemaingFrame/binary>> ->
{ready, Decoder#decoder{state=ready, buffer=RemaingFrame}}
end.
-spec continue_decode(Decoder::decoder()) -> decoder_reply().
continue_decode(#decoder{buffer=Buffer}=Decoder) when is_binary(Buffer) ->
continue_decode(Decoder#decoder{buffer=nil}, Buffer).
-spec decoder_state(Decoder::decoder()) -> State::decoder_state().
decoder_state(#decoder{state=State}) ->
State.
-spec decoder_version(Decoder::decoder()) -> State::decoder_version().
decoder_version(#decoder{version_major={some, VersionMajor}, version_minor={some, VersionMinor}}) ->
{VersionMajor, VersionMinor}.
-spec decoder_mechanism(Decoder::decoder()) -> security_mechanism().
decoder_mechanism(#decoder{mechanism=Mechanism}) ->
Mechanism.
-spec decoder_as_server(Decoder::decoder()) -> boolean().
decoder_as_server(#decoder{as_server=AsServer}) ->
AsServer.
-spec decoder_buffer(Decoder::decoder()) -> binary() | nil.
decoder_buffer(#decoder{buffer=Buffer}) ->
Buffer.
-spec decoder_security_data(Decoder::decoder()) -> nil | chumak_curve:curve_data().
decoder_security_data(#decoder{security_data=SecurityData}) ->
SecurityData.
-spec set_decoder_security_data(
Decoder::decoder(),
SecurityData::decoder_security_data()) -> decoder().
set_decoder_security_data(Decoder, SecurityData) ->
Decoder#decoder{security_data = SecurityData}.
-spec encode_command(Command::binary()) -> Traffic::binary().
encode_command(Command) when is_binary(Command) ->
encode_frame(?SMALL_COMMAND, ?LARGE_COMMAND, Command).
@doc encode a old format of subscriptions found in version 3.0 of zeromq
-spec encode_old_subscribe(Topic::binary()) -> Traffic::binary().
encode_old_subscribe(Topic) ->
{Encoded, _} = encode_last_message(<<1, Topic/binary>>, null, #{}),
Encoded.
@doc encode a old format of unsubscriptions found in version 3.0 of zeromq
-spec encode_old_cancel(Topic::binary()) -> Traffic::binary().
encode_old_cancel(Topic) ->
{Encoded, _} = encode_last_message(<<0, Topic/binary>>, null, #{}),
Encoded.
-spec encode_message_multipart([Message::binary()],
Mechanism::security_mechanism(),
SecurityData::map()) -> {Traffic::binary(),
NewSecurityData::map()}.
encode_message_multipart(Multipart, Mechanism, SecurityData) ->
More = lists:sublist(Multipart, length(Multipart) -1),
Last = lists:last(Multipart),
{MoreTrafficList, NewSecurityData} =
lists:mapfoldl(fun(Part, SDataAcc) ->
encode_more_message(Part, Mechanism, SDataAcc)
end, SecurityData, More),
MoreTraffic = binary:list_to_bin(MoreTrafficList),
{LastTraffic, FinalSecData} = encode_last_message(Last, Mechanism,
NewSecurityData),
{<<MoreTraffic/binary, LastTraffic/binary>>, FinalSecData}.
-spec encode_more_message(Message::binary(),
Mechanism::security_mechanism(),
SecurityData::map()) -> {Traffic::binary(), map()}.
encode_more_message(Message, Mechanism, SecurityData)
when is_binary(Message) ->
{Frame, NewSecurityData} = build_message(Message,
Mechanism,
SecurityData),
{encode_frame(?SMALL_MORE_MESSAGE, ?LARGE_MORE_MESSAGE, Frame),
NewSecurityData}.
-spec encode_last_message(Message::binary(),
Mechanism::security_mechanism(),
SecurityData::map()) -> {Traffic::binary(), map()}.
encode_last_message(Message, Mechanism, SecurityData)
when is_binary(Message) ->
{Frame, NewSecurityData} = build_message(Message,
Mechanism,
SecurityData),
{encode_frame(?SMALL_LAST_MESSAGE, ?LARGE_LAST_MESSAGE, Frame),
NewSecurityData}.
-spec message_data(Message::message()) -> Frame::binary().
message_data(#message{frame=Data}) ->
Data.
-spec message_has_more(Message::message()) -> true | false.
message_has_more(#message{has_more=HasMore}) ->
HasMore.
continue_decode(Decoder, <<>>) ->
{ok, Decoder};
continue_decode(Decoder, Frame) ->
decode(Decoder, Frame).
decode_command(#decoder{security_data = SecurityData} = Decoder,
Size, Frame) ->
<<CommandFrame:Size/binary, RemaingFrame/binary>> = Frame,
case chumak_command:decode(CommandFrame, SecurityData) of
{ok, Command, NewSecurityData} ->
accumule_commands(Decoder#decoder{security_data = NewSecurityData},
Command, RemaingFrame);
{error, _} = Error ->
Error
end.
decode_message(#decoder{security_data = SecurityData} = Decoder,
Size, Frame, MoreFlag) ->
HasMore = case MoreFlag of
1 ->
true;
0 ->
false
end,
<<MessageFrame:Size/binary, RemaingFrame/binary>> = Frame,
{DecodedFrame, NewSecurityData} = decode_frame(MessageFrame, SecurityData),
accumule_commands(Decoder#decoder{security_data = NewSecurityData},
#message{frame=DecodedFrame, has_more=HasMore},
RemaingFrame).
decode_frame(CurveMessage, #{mechanism := curve} = SecurityData) ->
case chumak_command:decode(CurveMessage, SecurityData) of
{ok, Message, NewSecurityData} ->
{Message, NewSecurityData}
end;
decode_frame(Frame, SecurityData) ->
{Frame, SecurityData}.
accumule_commands(Decoder, Command, Frame) ->
ReadyDecoder = Decoder#decoder{state=ready},
case continue_decode(ReadyDecoder, Frame) of
{ok, UpdatedDecoder} ->
{ok, UpdatedDecoder, [Command]};
{ok, UpdatedDecoder, Commands} ->
{ok, UpdatedDecoder, [Command|Commands]};
Error ->
Error
end.
require_size(Decoder, Size, Frame, NextState) when byte_size(Frame) >= Size->
decode(Decoder#decoder{state=NextState, buffer=nil}, Frame);
require_size(Decoder, Size, Frame, NextState) ->
{ok, Decoder#decoder{state=require_size, size=Size, buffer=Frame, next_state=NextState}}.
strip_binary_to_atom(Bin) ->
[T, _] = binary:split(Bin, <<0>>),
binary_to_atom(T, utf8).
encode_frame(SmallFlag, _LargeFlag, Frame) when byte_size(Frame) < 256 ->
Size = byte_size(Frame),
<<SmallFlag, Size, Frame/binary>>;
encode_frame(_SmallFlag, LargeFlag, Frame) ->
Size = byte_size(Frame),
SizeFrame = binary:encode_unsigned(Size),
Padding = binary:copy(<<0>>, 8-byte_size(SizeFrame)),
<<LargeFlag, Padding/binary, SizeFrame/binary, Frame/binary>>.
20 octets .
encode_mechanism(null) ->
<< <<"NULL">>/binary, 0:128>>;
encode_mechanism(curve) ->
<< <<"CURVE">>/binary, 0:120>>.
|
5801e49d62d2156bd5eca75c53fc14468acec0ab357bc4ea1b532f46e0d85b40
|
district0x/cljs-ipfs-http-client
|
pubsub.cljs
|
(ns cljs-ipfs-api.pubsub
(:require [cljs-ipfs-api.core :refer-macros [defsignatures]]
[cljs-ipfs-api.utils :refer [wrap-callback api-call js->cljkk cljkk->js]]))
(defsignatures
[[pubsub.subscribe [topic options handler callback]]
[pubsub.unsubscribe [topic handler]]
[pubsub.publish [topic data callback]]
[pubsub.ls [topic callback]]
[pubsub.peers [topic callback]]])
| null |
https://raw.githubusercontent.com/district0x/cljs-ipfs-http-client/2352396430fb1ca179054845b956184c871ceedd/src/cljs_ipfs_api/pubsub.cljs
|
clojure
|
(ns cljs-ipfs-api.pubsub
(:require [cljs-ipfs-api.core :refer-macros [defsignatures]]
[cljs-ipfs-api.utils :refer [wrap-callback api-call js->cljkk cljkk->js]]))
(defsignatures
[[pubsub.subscribe [topic options handler callback]]
[pubsub.unsubscribe [topic handler]]
[pubsub.publish [topic data callback]]
[pubsub.ls [topic callback]]
[pubsub.peers [topic callback]]])
|
|
a92ddbf3cd51dda3ed8b9582c400e492439f7b8aa517d124fc5444d7b280cd3c
|
maitria/avi
|
normal.clj
|
(ns avi.mode.normal
(:require [packthread.core :refer :all]
[avi.beep :as beep]
[avi.brackets :as brackets]
[avi.edit-context :as ec]
[avi.editor :as e]
[avi.events :as ev]
[avi.layout.panes :as p]
[avi.mode command-line insert]
[avi.nfa :as nfa]
[avi.pervasive :refer :all]
[avi.search]))
(def operators
{"" {:operator :move-point}
"d" {:operator :delete}})
(def motions
'{"<Down>"{:span :linewise,
:motion [:down]}
"<Left>"{:span :exclusive,
:motion [:left]}
"<Right>"{:span :exclusive,
:motion [:right]}
"<Up>" {:span :linewise,
:motion [:up]}
"0" {:span :exclusive,
:motion [:goto [:current 0]]}
"^" {:span :exclusive,
:motion [:goto [:current :first-non-blank]]}
"$" {:span :inclusive,
:motion [:goto [:current :end-of-line]]}
"b" {:span :exclusive
:motion [:word {:direction :backward
:position-in-word :start
:empty-lines? true}]}
"e" {:span :inclusive
:motion [:word {:direction :forward
:position-in-word :end
:empty-lines? false}]}
"f<.>" {:span :inclusive,
:motion [:move-to-char]}
"ge" {:span :inclusive,
:motion [:word {:direction :backward
:position-in-word :end
:empty-lines? true}]}
"gg" {:span :linewise,
:motion [:goto-line {:default-line 0}]}
"gE" {:span :inclusive,
:motion [:word {:direction :backward
:position-in-word :end
:big? true
:empty-lines? true}]}
"h" {:span :exclusive,
:motion [:left]}
"iw" {:span :inclusive,
:motion [:in-word]}
"j" {:span :linewise,
:motion [:down]}
"k" {:span :linewise,
:motion [:up]}
"l" {:span :exclusive,
:motion [:right]}
"t<.>" {:span :inclusive,
:motion [:move-to-char {:offset -1}]}
"w" {:span :exclusive,
:motion [:word {:weird-delete-clip? true
:direction :forward
:position-in-word :start
:empty-lines? true}]}
"E" {:span :inclusive
:motion [:word {:direction :forward
:position-in-word :end
:big? true
:empty-lines? false}]}
"F<.>" {:span :exclusive,
:motion [:move-to-char {:direction -1}]}
"G" {:span :linewise,
:motion [:goto-line {:default-line :last}]}
"H" {:span :linewise,
:motion [:goto-line {:from :viewport-top}]}
"L" {:span :linewise,
:motion [:goto-line {:from :viewport-bottom
:multiplier -1}]}
"M" {:span :linewise,
:motion [:goto-line {:from :viewport-middle
:multiplier 0}]}
"T<.>" {:span :exclusive,
:motion [:move-to-char {:direction -1
:offset 1}]}
"W" {:span :exclusive,
:motion [:word {:direction :forward
:position-in-word :start
:big? true
:empty-lines? true}]}})
(defn motion-handler
[editor spec]
(+> editor
(in e/edit-context
(ec/operate spec))))
(def non-motion-commands
{"dd" ^:no-repeat (fn+> [editor spec]
(let [repeat-count (:count spec)]
(in e/edit-context
ec/start-transaction
(n-times (or repeat-count 1) ec/delete-current-line)
ec/commit)))
"u" (fn+> [editor _]
(in e/edit-context
ec/undo))
"x" ^:no-repeat (fn+> [editor spec]
(in e/edit-context
(ec/operate (merge
spec
{:operator :delete
:span :exclusive
:motion [:right]}))))
"D" (fn+> [editor _]
(in e/edit-context
(ec/operate {:operator :delete
:span :inclusive
:motion [:goto [:current :end-of-line]]})))
"J" ^:no-repeat (fn+> [editor spec]
(let [n (or (:count spec) 2)]
(in e/edit-context
ec/start-transaction
(n-times (dec n) (fn+> [{[i] :avi.lenses/point :as ec}]
(let [start-j (count (ec/line ec i))]
(ec/change [i start-j] [(inc i) 0] " " :left)
(ec/operate {:operator :move-point
:motion [:goto [i start-j]]}))))
ec/commit)))
"<C-D>" (fn+> [editor _]
(let [edit-context (e/edit-context editor)]
(if (ec/on-last-line? edit-context)
beep/beep
(in e/edit-context
(ec/move-and-scroll-half-page :down)))))
"<C-E>" (fn+> [editor _]
(in e/edit-context
(ec/scroll inc)))
"<C-G>" (fn+> [editor _]
(let [edit-context (e/edit-context editor)
[i] (:avi.lenses/point edit-context)
document (get-in editor (e/current-document-path editor))
num-lines (transduce
(filter #(= % \newline))
(completing (fn [r _] (inc r)))
0
(:avi.documents/text document))
line-no (inc i)
msg-txt (str "\"" (or (:avi.documents/name document) "[No Name]") "\"\t")]
(if (not= (:avi.documents/text document) "")
(assoc :message [:white :blue (str msg-txt num-lines " lines --" (int (/ (* line-no 100) num-lines)) "%--")])
(assoc :message [:white :blue (str msg-txt "--No lines in buffer--")]))))
"<C-R>" (fn+> [editor _]
(in e/edit-context
ec/redo))
"<C-U>" (fn+> [editor _]
(let [edit-context (e/edit-context editor)
[i] (:avi.lenses/point edit-context)]
(if (zero? i)
beep/beep
(in e/edit-context
(ec/move-and-scroll-half-page :up)))))
"<C-W>h" (fn+> [editor _] (p/move [0 -1]))
"<C-W>j" (fn+> [editor _] (p/move [+1 0]))
"<C-W>k" (fn+> [editor _] (p/move [-1 0]))
"<C-W>l" (fn+> [editor _] (p/move [0 +1]))
"<C-Y>" (fn+> [editor _]
(in e/edit-context
(ec/scroll dec)))})
(defn wrap-handler-with-repeat-loop
[handler]
(fn [editor spec]
(let [repeat-count (or (:count spec) 1)]
(nth (iterate #(handler % spec) editor) repeat-count))))
(defn decorate-event-handler
[f]
(+> f
(if-not (:no-repeat (meta f))
wrap-handler-with-repeat-loop)))
(defn- event-nfa
[event]
(cond
(= [:keystroke "<.>"] event)
(nfa/on nfa/any (fn [v [_ key-string]]
(assoc v :char (get key-string 0))))
;; It's not the "0" motion if we have a count (it's
;; part of the count).
(= [:keystroke "0"] event)
(nfa/prune (nfa/match [:keystroke "0"]) :count)
:else
(nfa/match event)))
(defn- event-string-nfa
[event-string]
(->> event-string
ev/events
(map event-nfa)
(apply nfa/chain)))
(defn- map->nfa
[mappings]
(->> mappings
(map (fn [[event-string handler]]
(let [handler (decorate-event-handler handler)]
(nfa/on (event-string-nfa event-string)
(fn [v _]
(assoc v :handler handler))))))
(apply nfa/choice)))
(def operator-nfa
(nfa/maybe
(->> operators
(filter (fn [[prefix _]]
(not= "" prefix)))
(map (fn [[prefix spec]]
(nfa/on (nfa/match [:keystroke prefix])
(fn [v _]
(merge v spec)))))
(apply nfa/choice))))
(def motion-nfa
(let [default-operator-spec (get operators "")]
(->> motions
(map (fn [[event-string spec]]
(nfa/on (event-string-nfa event-string)
(fn motion-reducer [v _]
(merge
default-operator-spec
v
{:handler motion-handler}
spec)))))
(apply nfa/choice))))
(defn count-digits-nfa
[from to]
(nfa/on (->> (range from (inc to))
(map str)
(map (partial vector :keystroke))
(map nfa/match)
(apply nfa/choice))
(fn [v [_ key-string]]
(let [old-value (or (:count v) 0)
new-value (+ (* 10 old-value)
(Integer/parseInt key-string))]
(assoc v :count new-value)))))
(def count-nfa
(nfa/maybe
(nfa/chain
(count-digits-nfa 1 9)
(nfa/kleene
(count-digits-nfa 0 9)))))
(def normal-nfa
(nfa/chain
count-nfa
(nfa/choice
(nfa/chain (nfa/maybe operator-nfa) motion-nfa)
(map->nfa non-motion-commands)
(map->nfa avi.mode.command-line/normal-commands)
(map->nfa avi.search/normal-search-commands)
(map->nfa brackets/normal-commands)
(map->nfa avi.mode.insert/mappings-which-enter-insert-mode))))
(defn normal-responder
[editor event]
(+> editor
(dissoc :normal-state)
(let [state (or (:normal-state editor) (nfa/start normal-nfa))
state' (nfa/advance state [nil event])]
(cond
(nfa/reject? state')
beep/beep
(nfa/accept? state')
(let [value (nfa/accept-value state')]
((:handler value) value))
:else
(assoc :normal-state state')))))
(def wrap-mode (e/mode-middleware :normal normal-responder))
| null |
https://raw.githubusercontent.com/maitria/avi/c641e9e32af4300ea7273a41e86b4f47d0f2c092/src/avi/mode/normal.clj
|
clojure
|
It's not the "0" motion if we have a count (it's
part of the count).
|
(ns avi.mode.normal
(:require [packthread.core :refer :all]
[avi.beep :as beep]
[avi.brackets :as brackets]
[avi.edit-context :as ec]
[avi.editor :as e]
[avi.events :as ev]
[avi.layout.panes :as p]
[avi.mode command-line insert]
[avi.nfa :as nfa]
[avi.pervasive :refer :all]
[avi.search]))
(def operators
{"" {:operator :move-point}
"d" {:operator :delete}})
(def motions
'{"<Down>"{:span :linewise,
:motion [:down]}
"<Left>"{:span :exclusive,
:motion [:left]}
"<Right>"{:span :exclusive,
:motion [:right]}
"<Up>" {:span :linewise,
:motion [:up]}
"0" {:span :exclusive,
:motion [:goto [:current 0]]}
"^" {:span :exclusive,
:motion [:goto [:current :first-non-blank]]}
"$" {:span :inclusive,
:motion [:goto [:current :end-of-line]]}
"b" {:span :exclusive
:motion [:word {:direction :backward
:position-in-word :start
:empty-lines? true}]}
"e" {:span :inclusive
:motion [:word {:direction :forward
:position-in-word :end
:empty-lines? false}]}
"f<.>" {:span :inclusive,
:motion [:move-to-char]}
"ge" {:span :inclusive,
:motion [:word {:direction :backward
:position-in-word :end
:empty-lines? true}]}
"gg" {:span :linewise,
:motion [:goto-line {:default-line 0}]}
"gE" {:span :inclusive,
:motion [:word {:direction :backward
:position-in-word :end
:big? true
:empty-lines? true}]}
"h" {:span :exclusive,
:motion [:left]}
"iw" {:span :inclusive,
:motion [:in-word]}
"j" {:span :linewise,
:motion [:down]}
"k" {:span :linewise,
:motion [:up]}
"l" {:span :exclusive,
:motion [:right]}
"t<.>" {:span :inclusive,
:motion [:move-to-char {:offset -1}]}
"w" {:span :exclusive,
:motion [:word {:weird-delete-clip? true
:direction :forward
:position-in-word :start
:empty-lines? true}]}
"E" {:span :inclusive
:motion [:word {:direction :forward
:position-in-word :end
:big? true
:empty-lines? false}]}
"F<.>" {:span :exclusive,
:motion [:move-to-char {:direction -1}]}
"G" {:span :linewise,
:motion [:goto-line {:default-line :last}]}
"H" {:span :linewise,
:motion [:goto-line {:from :viewport-top}]}
"L" {:span :linewise,
:motion [:goto-line {:from :viewport-bottom
:multiplier -1}]}
"M" {:span :linewise,
:motion [:goto-line {:from :viewport-middle
:multiplier 0}]}
"T<.>" {:span :exclusive,
:motion [:move-to-char {:direction -1
:offset 1}]}
"W" {:span :exclusive,
:motion [:word {:direction :forward
:position-in-word :start
:big? true
:empty-lines? true}]}})
(defn motion-handler
[editor spec]
(+> editor
(in e/edit-context
(ec/operate spec))))
(def non-motion-commands
{"dd" ^:no-repeat (fn+> [editor spec]
(let [repeat-count (:count spec)]
(in e/edit-context
ec/start-transaction
(n-times (or repeat-count 1) ec/delete-current-line)
ec/commit)))
"u" (fn+> [editor _]
(in e/edit-context
ec/undo))
"x" ^:no-repeat (fn+> [editor spec]
(in e/edit-context
(ec/operate (merge
spec
{:operator :delete
:span :exclusive
:motion [:right]}))))
"D" (fn+> [editor _]
(in e/edit-context
(ec/operate {:operator :delete
:span :inclusive
:motion [:goto [:current :end-of-line]]})))
"J" ^:no-repeat (fn+> [editor spec]
(let [n (or (:count spec) 2)]
(in e/edit-context
ec/start-transaction
(n-times (dec n) (fn+> [{[i] :avi.lenses/point :as ec}]
(let [start-j (count (ec/line ec i))]
(ec/change [i start-j] [(inc i) 0] " " :left)
(ec/operate {:operator :move-point
:motion [:goto [i start-j]]}))))
ec/commit)))
"<C-D>" (fn+> [editor _]
(let [edit-context (e/edit-context editor)]
(if (ec/on-last-line? edit-context)
beep/beep
(in e/edit-context
(ec/move-and-scroll-half-page :down)))))
"<C-E>" (fn+> [editor _]
(in e/edit-context
(ec/scroll inc)))
"<C-G>" (fn+> [editor _]
(let [edit-context (e/edit-context editor)
[i] (:avi.lenses/point edit-context)
document (get-in editor (e/current-document-path editor))
num-lines (transduce
(filter #(= % \newline))
(completing (fn [r _] (inc r)))
0
(:avi.documents/text document))
line-no (inc i)
msg-txt (str "\"" (or (:avi.documents/name document) "[No Name]") "\"\t")]
(if (not= (:avi.documents/text document) "")
(assoc :message [:white :blue (str msg-txt num-lines " lines --" (int (/ (* line-no 100) num-lines)) "%--")])
(assoc :message [:white :blue (str msg-txt "--No lines in buffer--")]))))
"<C-R>" (fn+> [editor _]
(in e/edit-context
ec/redo))
"<C-U>" (fn+> [editor _]
(let [edit-context (e/edit-context editor)
[i] (:avi.lenses/point edit-context)]
(if (zero? i)
beep/beep
(in e/edit-context
(ec/move-and-scroll-half-page :up)))))
"<C-W>h" (fn+> [editor _] (p/move [0 -1]))
"<C-W>j" (fn+> [editor _] (p/move [+1 0]))
"<C-W>k" (fn+> [editor _] (p/move [-1 0]))
"<C-W>l" (fn+> [editor _] (p/move [0 +1]))
"<C-Y>" (fn+> [editor _]
(in e/edit-context
(ec/scroll dec)))})
(defn wrap-handler-with-repeat-loop
[handler]
(fn [editor spec]
(let [repeat-count (or (:count spec) 1)]
(nth (iterate #(handler % spec) editor) repeat-count))))
(defn decorate-event-handler
[f]
(+> f
(if-not (:no-repeat (meta f))
wrap-handler-with-repeat-loop)))
(defn- event-nfa
[event]
(cond
(= [:keystroke "<.>"] event)
(nfa/on nfa/any (fn [v [_ key-string]]
(assoc v :char (get key-string 0))))
(= [:keystroke "0"] event)
(nfa/prune (nfa/match [:keystroke "0"]) :count)
:else
(nfa/match event)))
(defn- event-string-nfa
[event-string]
(->> event-string
ev/events
(map event-nfa)
(apply nfa/chain)))
(defn- map->nfa
[mappings]
(->> mappings
(map (fn [[event-string handler]]
(let [handler (decorate-event-handler handler)]
(nfa/on (event-string-nfa event-string)
(fn [v _]
(assoc v :handler handler))))))
(apply nfa/choice)))
(def operator-nfa
(nfa/maybe
(->> operators
(filter (fn [[prefix _]]
(not= "" prefix)))
(map (fn [[prefix spec]]
(nfa/on (nfa/match [:keystroke prefix])
(fn [v _]
(merge v spec)))))
(apply nfa/choice))))
(def motion-nfa
(let [default-operator-spec (get operators "")]
(->> motions
(map (fn [[event-string spec]]
(nfa/on (event-string-nfa event-string)
(fn motion-reducer [v _]
(merge
default-operator-spec
v
{:handler motion-handler}
spec)))))
(apply nfa/choice))))
(defn count-digits-nfa
[from to]
(nfa/on (->> (range from (inc to))
(map str)
(map (partial vector :keystroke))
(map nfa/match)
(apply nfa/choice))
(fn [v [_ key-string]]
(let [old-value (or (:count v) 0)
new-value (+ (* 10 old-value)
(Integer/parseInt key-string))]
(assoc v :count new-value)))))
(def count-nfa
(nfa/maybe
(nfa/chain
(count-digits-nfa 1 9)
(nfa/kleene
(count-digits-nfa 0 9)))))
(def normal-nfa
(nfa/chain
count-nfa
(nfa/choice
(nfa/chain (nfa/maybe operator-nfa) motion-nfa)
(map->nfa non-motion-commands)
(map->nfa avi.mode.command-line/normal-commands)
(map->nfa avi.search/normal-search-commands)
(map->nfa brackets/normal-commands)
(map->nfa avi.mode.insert/mappings-which-enter-insert-mode))))
(defn normal-responder
[editor event]
(+> editor
(dissoc :normal-state)
(let [state (or (:normal-state editor) (nfa/start normal-nfa))
state' (nfa/advance state [nil event])]
(cond
(nfa/reject? state')
beep/beep
(nfa/accept? state')
(let [value (nfa/accept-value state')]
((:handler value) value))
:else
(assoc :normal-state state')))))
(def wrap-mode (e/mode-middleware :normal normal-responder))
|
e429f6cb142618f8e70ee288894bc0b263898409358efae2d588e219c100797e
|
javalib-team/sawja
|
jPrintPlugin.ml
|
* This file is part of SAWJA
* Copyright ( c)2011 ( INRIA )
*
* This program is free software : you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation , either version 3 of
* the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* General Public License for more details .
*
* You should have received a copy of the GNU General Public
* License along with this program . If not , see
* < / > .
* This file is part of SAWJA
* Copyright (c)2011 Vincent Monfort (INRIA)
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* </>.
*)
open Javalib_pack
open JBasics
open JProgram
open Javalib
open JPrintUtil
(* Tags and attributes*)
let warn_tag = "warning"
let warn_pp_tag = "warning_pp"
let wmsg_tag = "msg"
let wpp_line = "line"
let wpp_pc = "pc"
let warn_pp_precise = "precise"
let wastnode = "astnode"
let wcname = "cname"
let wvtype = "jtype"
let wsenter = "synch_enter"
let wvname = "vname"
let desc_attr = "descriptor"
let meth_arg="arg_desc"
let meth_sig_on = "on"
let meth_arg_num = "arg"
let class_tag = "class"
let class_cname = "name"
let class_sf = "sourcefile"
let class_inner = "inner"
let class_anon = "anon"
let html_info_tag = "html"
let info_tag = "info"
let ival_tag = "value"
let pp_tag = "pp"
let true_val = "true"
let false_val = "false"
let method_sig_desc ms =
((ms_name ms) ^":(")
^(List.fold_left
(fun msg t ->
msg^(JDumpBasics.type2shortstring t))
""
(ms_args ms))
^(")"^JDumpBasics.rettype2shortstring (ms_rtype ms))
type method_info =
| MethodSignature of string
| Argument of int * string
| Return of string
| This of string
type 'a warning_pp = string * 'a option
type 'a plugin_info =
{
mutable p_infos :
(string list
* string list FieldMap.t
* (method_info list * string list Ptmap.t) MethodMap.t)
ClassMap.t;
mutable p_warnings :
(string list
* string list FieldMap.t
* (method_info list * 'a warning_pp list Ptmap.t) MethodMap.t)
ClassMap.t;
}
type ('c,'f,'m,'p) iow = ('c list
* 'f list FieldMap.t
* ('m list * 'p list Ptmap.t) MethodMap.t)
let find_class_infos cn map =
try ClassMap.find cn map
with Not_found ->
([],FieldMap.empty,MethodMap.empty)
let find_field_infos fs map =
try FieldMap.find fs map with Not_found -> []
let find_meth_infos ms map =
try MethodMap.find ms map with Not_found -> ([],Ptmap.empty)
let find_pp_infos ms pc map =
let (mil,pmap) =
try MethodMap.find ms map
with Not_found -> ([],Ptmap.empty)
in
let ppinfos =
try Ptmap.find pc pmap
with Not_found -> []
in
((mil,pmap),ppinfos)
let add_class_iow i cn map =
let (ci,fi,mi) = find_class_infos cn map in
ClassMap.add cn (i::ci,fi,mi) map
let add_field_iow i cn fs map =
let (ci,fi,mi) = find_class_infos cn map in
let fil = find_field_infos fs fi in
let fi = FieldMap.add fs (i::fil) fi in
ClassMap.add cn (ci,fi,mi) map
let add_meth_iow i cn ms map =
let (ci,fi,mi) = find_class_infos cn map in
let (mil,ptmap) = find_meth_infos ms mi in
let mi = MethodMap.add ms (i::mil,ptmap) mi in
ClassMap.add cn (ci,fi,mi) map
let add_pp_iow i cn ms pc map =
let (ci,fi,mi) = find_class_infos cn map in
let ((mil,pmap),ppil) = find_pp_infos ms pc mi in
let mi = MethodMap.add ms (mil,(Ptmap.add pc (i::ppil) pmap)) mi in
ClassMap.add cn (ci,fi,mi) map
module NewCodePrinter =
struct
module AdaptedASTGrammar =
struct
type identifier =
SimpleName of string * value_type option
(** It could be a variable identifier, field name, class name,
etc. Only use the shortest name possible (no package name
before class name, no class name before a field name, etc.).*)
type expression =
(*| NullLiteral
| StringLiteral of string
| TypeLiteral of identifier
| OtherLiteral of float*)
(* Others constants (impossible to differenciate int and bool in bytecode, ...)*)
| Assignment of identifier
(** Identifier must be the identifier of the left_side of
assignment (field's name or variable's name)*)
| ClassInstanceCreation of class_name
| ArrayCreation of value_type
| MethodInvocationNonVirtual of class_name * method_signature (* ms ? *)
| MethodInvocationVirtual of object_type * method_signature
Ok if a [ ] [ ] we could not know , optimistic ( only one tab access on a line ? )
| ArrayStore of value_type option(* It will be searched only in left_side of assignements*)
| InstanceOf of object_type
| Cast of object_type
type statement =
of InfixExpr option
* Includes all If ' like ' statements ( If , For , While , ConditionnalExpr , etc . )
| Catch of class_name (*type given by handlers table*)
| Finally
| Switch
| Synchronized of bool(* ?Monitor exit corresponds to end parenthisis...*)
| Return
| Throw
(*| AssertStat (*How to find them in bytecode: creation of a field
in class + creation of exception to throw*)*)
type node_unit =
Statement of statement
| Expression of expression
| Name of identifier
let ot2attr ot =
(wvtype,JPrint.object_type ~jvm:true ot)
let vt_opt2attrs =
function
None -> []
| Some vt -> [wvtype,JPrint.value_type ~jvm:true vt]
let ast_node2attributes =
function
Statement st ->
(match st with
If -> [wastnode,"If"]
| Catch cn -> [(wastnode,"Catch");(wcname,cn_name cn)]
| Finally -> [wastnode,"Finally"]
| Switch -> [wastnode,"Switch"]
| Synchronized enterb -> [(wastnode,"Synchronized");(wsenter,string_of_bool enterb)]
| Return -> [wastnode,"Return"]
| Throw -> [wastnode,"Throw"])
| Expression e ->
(match e with
| Assignment id ->
let id_attrs =
match id with
SimpleName (name, vt_opt) ->
(wvname,name)::(vt_opt2attrs vt_opt)
in
(wastnode,"Assignment")::id_attrs
| ClassInstanceCreation cn -> [(wastnode,"ClassInstanceCreation");(wcname,cn_name cn)]
| ArrayCreation vt -> (wastnode,"ArrayCreation")::(vt_opt2attrs (Some vt))
| MethodInvocationNonVirtual (cn,ms) -> [(wastnode,"MethodInvocationNonVirtual"); (wcname, cn_name cn);
(wvname,ms_name ms); (desc_attr, method_sig_desc ms)]
| MethodInvocationVirtual (ot,ms) -> [(wastnode,"MethodInvocationVirtual"); (ot2attr ot);
(wvname,ms_name ms); (desc_attr, method_sig_desc ms)]
| ArrayAccess vt_opt -> (wastnode,"ArrayAccess")::(vt_opt2attrs vt_opt)
| ArrayStore vt_opt -> (wastnode,"ArrayStore")::(vt_opt2attrs vt_opt)
| InstanceOf ot -> [(wastnode,"InstanceOf");(ot2attr ot)]
| Cast ot -> [(wastnode,"Cast");(ot2attr ot)])
| Name id ->
(match id with
SimpleName (name,vt_opt) ->
(wastnode,"SimpleName")::(wvname,name)::(vt_opt2attrs vt_opt))
end
type 'a precise_warning_pp =
LineWarning of 'a warning_pp
(**warning description * optional precision depending of code
representation (used for PreciseLineWarning generation)*)
| PreciseLineWarning of string * AdaptedASTGrammar.node_unit
* same as LineWarning * AST information *
module type PluginPrinter =
sig
type code
type expr
val empty_infos: expr plugin_info
val print_class: ?html_info:bool -> expr plugin_info -> code interface_or_class -> string -> unit
val print_program: ?html_info:bool -> expr plugin_info -> code program -> string -> unit
end
module type PrintInterface =
sig
type p_code
type p_expr
* [ pc code ] returns the source line number
corresponding the program point pp of the method code m.
corresponding the program point pp of the method code m.*)
val get_source_line_number : int -> p_code -> int option
(** [inst_disp code pc] returns a string representation of instruction at program point [pc].*)
val inst_disp : int -> p_code -> string
(** Function to provide in order to display the source variable
names in the method signatures. *)
val method_param_names : p_code Javalib.interface_or_class -> method_signature
-> string list option
* Allows to construct detailed warning but it requires good
knowledge of org.eclipse.jdt.core.dom . AST representation . See
existant implementation of to_plugin_warning or simply transform a
warning_pp SimpleWarning in a PreciseWarning of warning .
knowledge of org.eclipse.jdt.core.dom.AST representation. See
existant implementation of to_plugin_warning or simply transform a
warning_pp SimpleWarning in a PreciseWarning of warning.
*)
val to_plugin_warning : p_code jmethod -> p_expr precise_warning_pp list Ptmap.t
-> p_expr precise_warning_pp list Ptmap.t
end
let gen_warning_sig wlist =
List.map
(fun msg ->
let attr = [(wmsg_tag,msg)] in
gen_simple_tag warn_tag attr)
wlist
let gen_info_sig fhtml ilist =
List.map
(fun info ->
let info_xml =
fhtml info
in
gen_custom_tag info_tag [] [info_xml]
)
ilist
let gen_warning_msig wlist =
List.map
(fun meth_i ->
let attr =
match meth_i with
| MethodSignature msg -> [(meth_sig_on,"method");(wmsg_tag,msg)]
| Argument (num,msg) -> [(meth_sig_on,"argument");(meth_arg_num,string_of_int num);(wmsg_tag,msg)]
| Return msg -> [(meth_sig_on,"return");(wmsg_tag,msg)]
| This msg -> [(meth_sig_on,"this");(wmsg_tag,msg)]
in
gen_simple_tag warn_tag attr)
wlist
let gen_info_msig fhtml ilist =
List.map
(fun info ->
let attr, msg =
match info with
| MethodSignature msg -> ([(meth_sig_on,"method")],msg)
| Argument (num,msg) -> ([(meth_sig_on,"argument");(meth_arg_num,string_of_int num)],msg)
| Return msg -> ([(meth_sig_on,"return")],msg)
| This msg -> ([(meth_sig_on,"this")],msg)
in
gen_custom_tag info_tag attr [(fhtml msg)])
ilist
let gen_warning_pp line pc wlist =
let line =
match line with
None -> -1
| Some l -> l
in
List.map
(function wsig ->
let attrs =
match wsig with
LineWarning (msg,_) ->
[(warn_pp_precise, false_val);(wpp_pc,string_of_int pc)
;(wpp_line,string_of_int line);(wmsg_tag,msg)]
| PreciseLineWarning (msg,ast_node) ->
(warn_pp_precise, true_val)::(wpp_pc,string_of_int pc)
::(wpp_line,string_of_int line)::(wmsg_tag,msg)
::(AdaptedASTGrammar.ast_node2attributes ast_node)
in
gen_simple_tag warn_pp_tag attrs)
wlist
let gen_info_pp fhtml disp line pc ilist =
let line =
match line with
None -> -1
| Some l -> l
in
let attrs = [(wpp_pc,string_of_int pc);(wpp_line,string_of_int line);(ival_tag,disp)] in
let infos =
List.map
(fun info ->
gen_custom_tag info_tag [] [(fhtml info)])
ilist
in
gen_custom_tag pp_tag attrs infos
let gen_field_tag fs warnings =
let attrs =
(desc_attr,(fs_name fs)^":"^(JDumpBasics.type2shortstring (fs_type fs)))::[]
in
gen_custom_tag "field" attrs warnings
let gen_method_tag ms warnings =
let attrs =
(desc_attr,method_sig_desc ms)::[]
in
gen_custom_tag "method" attrs warnings
let gen_info_method_tag mpn ms infos =
let attrs =
(desc_attr,method_sig_desc ms)
::("rtype",JPrint.return_type (ms_rtype ms))
::("name",ms_name ms)::[]
in
let args =
ExtList.List.mapi
(fun i vt ->
let name =
match mpn with
None -> []
| Some mpn ->
try ("name",List.nth mpn i)::[] with _ -> []
in
let arg_attrs =
("num",string_of_int i)
::("type",JPrint.value_type vt)
::name
in
gen_simple_tag meth_arg arg_attrs
)
(ms_args ms)
in
gen_custom_tag "method" attrs (args@infos)
let gen_class_tag ?(html=false) ioc treel =
let classname = get_name ioc in
let attrs =
let others_attrs =
if html
then [(html_info_tag,true_val)]
else []
in
let class_attrs =
let rec name_inner_anon inner_list =
match inner_list with
[] -> (class_cname,cn_name classname)::others_attrs
| ic::r ->
(match ic.ic_class_name with
None -> name_inner_anon r
| Some cn ->
if (cn_equal classname cn)
then
(match ic.ic_source_name with
None ->
(class_cname,cn_name classname)::
(class_inner,true_val)::
(class_anon,true_val)::others_attrs
| Some _ ->
(class_cname,cn_name classname)::
(class_inner,true_val)::others_attrs)
else name_inner_anon r)
in
name_inner_anon (get_inner_classes ioc)
in
let sourcefile_attrs =
match get_sourcefile ioc with
Some name ->
let pack =
List.fold_left
(fun pack element -> pack ^ element ^ ".")
"" (cn_package classname)
in
let pname = pack ^name in
(class_sf,pname)::class_attrs
| None -> class_attrs
in
sourcefile_attrs
in
gen_custom_tag class_tag attrs treel
module Make (S : PrintInterface) =
struct
type code = S.p_code
type expr = S.p_expr
let (empty_infos:expr plugin_info) = {
p_infos = ClassMap.empty;
p_warnings = ClassMap.empty
}
let ioc2xml_warn precise_warn info ioc =
let cn = get_name ioc in
if ClassMap.mem cn info.p_warnings
then
begin
let wclass, wfields, wmeth_pp =
ClassMap.find cn info.p_warnings
in
let cl_warn =
gen_warning_sig wclass
in
let fields_tags =
FieldMap.fold
(fun fs wsiglist tree_list ->
(gen_field_tag fs (gen_warning_sig wsiglist))::tree_list
)
wfields
[]
in
let meths_tags =
MethodMap.fold
(fun ms jm tlm ->
let get_source_line pc =
match jm with
AbstractMethod _ -> None
| ConcreteMethod cm ->
begin
match cm.cm_implementation with
| Native -> None
| Java lazcode ->
S.get_source_line_number pc (Lazy.force lazcode)
end
in
let tlm =
let tlpp =
try
let wpps_of_meth =
precise_warn jm (snd (MethodMap.find ms wmeth_pp)) in
Ptmap.fold
(fun pc wpplist tree_list ->
match wpplist with
[] -> tree_list
| _ -> (gen_warning_pp (get_source_line pc) pc wpplist)@tree_list
)
wpps_of_meth
[]
with Not_found -> []
in
let wms_meths =
try
fst (MethodMap.find ms wmeth_pp)
with Not_found -> []
in
match wms_meths, tlpp with
[],[] -> tlm
| _ ->
(gen_method_tag ms
((gen_warning_msig wms_meths)@tlpp)
)::tlm
in
tlm
)
(get_methods ioc)
[]
in
cl_warn@fields_tags@meths_tags
end
else []
let ioc2xml_info fhtml info ioc =
let cn = get_name ioc in
if ClassMap.mem cn info.p_infos
then
begin
let iclass, ifields, imeth_pp =
ClassMap.find cn info.p_infos
in
let class_tags =
match iclass with
[] -> []
| l -> gen_info_sig fhtml l
in
let fields_tags =
FieldMap.fold
(fun fs infos tree_list ->
match infos with
[] -> tree_list
| _ -> (gen_field_tag fs (gen_info_sig fhtml infos))::tree_list
)
ifields
[]
in
let meths_tags =
MethodMap.fold
(fun ms jm tlm ->
let code =
match jm with
AbstractMethod _ -> None
| ConcreteMethod cm ->
begin
match cm.cm_implementation with
| Native -> None
| Java lazcode ->
Some (Lazy.force lazcode)
end
in
let get_source_line pc =
match code with
None -> None
| Some code ->
S.get_source_line_number pc code
in
let pc_disp pc =
match code with
None -> ""
| Some code ->
S.inst_disp pc code
in
let tlm =
let tlpp =
try
let ipps_of_meth = snd (MethodMap.find ms imeth_pp) in
Ptmap.fold
(fun pc ipplist tree_list ->
match ipplist with
[] -> tree_list
| _ ->
(gen_info_pp
fhtml
(pc_disp pc)
(get_source_line pc)
pc ipplist)
::tree_list
)
ipps_of_meth
[]
with Not_found -> []
in
let ims_meths =
try
fst (MethodMap.find ms imeth_pp)
with Not_found -> []
in
match ims_meths, tlpp with
[],[] -> tlm
| _ ->
(gen_info_method_tag
(S.method_param_names ioc ms)
ms
((gen_info_msig fhtml ims_meths)@tlpp))
::tlm
in
tlm
)
(get_methods ioc)
[]
in
class_tags@fields_tags@meths_tags
end
else []
let gen_class_warn_doc precise_warn info ioc =
let tree_list = ioc2xml_warn precise_warn info ioc in
match tree_list with
[] -> None
| _ -> Some (gen_class_tag ioc tree_list)
let gen_class_info_doc html info ioc =
let fhtml = if html then
((*TODO: check it is valid html for plugin*)
fun s -> CData s)
else
(fun s -> PCData s)
in
let tree_list = ioc2xml_info fhtml info ioc in
match tree_list with
[] -> None
| _ -> Some (gen_class_tag ~html:html ioc tree_list)
let print_info html (info_p: 'a plugin_info) ioc outputdir =
let cs = get_name ioc in
let package_and_source =
match get_sourcefile ioc with
None ->
(* Try with class name as a source name.*)
"info"::(cn_package cs @ [(cn_simple_name cs)^".java"])
| Some filename -> "info"::(cn_package cs @ [filename])
and cname = cn_simple_name cs in
let doc = gen_class_info_doc html info_p ioc in
match doc with
None -> ()
| Some doc ->
create_package_dir outputdir package_and_source;
let out =
open_out (Filename.concat outputdir
(List.fold_left
Filename.concat "" (package_and_source @ [cname ^ ".xml"])))
in
print_xml_tree ~spc:3 doc out;
close_out out
let print_warnings (info_p: 'a plugin_info) ioc outputdir =
let cs = get_name ioc in
let package_and_source =
"warn"::(cn_package cs)
and cname = cn_simple_name cs in
let ( fun c - > if c = ' . ' then ' / ' else c ) ( cn_name cs ) in
(fun c -> if c = '.' then '/' else c) (cn_name cs) in*)
let pp2pp_precise c map =
(S.to_plugin_warning)
c
(Ptmap.map
(fun lpp ->
List.map (fun (s,prec) -> LineWarning (s,prec)) lpp)
map)
in
let doc = gen_class_warn_doc pp2pp_precise info_p ioc in
match doc with
None -> ()
| Some doc ->
create_package_dir outputdir package_and_source;
let out =
open_out (Filename.concat outputdir
(List.fold_left
Filename.concat "" (package_and_source @ [cname ^ ".xml"])))
in
print_xml_tree ~spc:3 doc out;
close_out out
let print_class ?(html_info=false) (info_p: 'a plugin_info) ioc outputdir =
print_warnings info_p ioc outputdir;
print_info html_info info_p ioc outputdir
let print_program ?(html_info=false) (info_p: 'a plugin_info) (p: S.p_code program) outputdir =
ClassMap.iter
(fun _ node ->
print_class ~html_info:html_info info_p (to_ioc node) outputdir)
p.classes
end
end
open NewCodePrinter
module JCodePrinter = Make(
struct
open JCode
open AdaptedASTGrammar
type p_code = jcode
type p_expr = unit
include from JPrintUtil that contains common code
with JPrintHtml
with JPrintHtml*)
include JCodeUtil
let get_source_line_number pp code =
get_source_line_number pp code
let inst_disp pp code =
(* TODO: create a display function that uses names of variables ?*)
JPrint.jopcode code.c_code.(pp)
let find_ast_node code pc op =
let catch_or_finally =
List.fold_left
(fun nu eh ->
if eh.e_handler = pc
then
match eh.e_catch_type with
None -> Some (Statement
Finally)
| Some cn -> Some (Statement
(Catch cn))
else nu
)
None
code.c_exc_tbl
in
match catch_or_finally with
Some _ -> catch_or_finally
| None ->
begin
match op with
| OpNop | OpPop | OpPop2 | OpDup | OpDupX1 | OpDupX2 | OpDup2 | OpDup2X1
| OpDup2X2 | OpSwap | OpAdd _ | OpSub _ | OpMult _ | OpDiv _ | OpRem _
| OpNeg _ | OpIShl | OpIShr | OpIAnd | OpIOr | OpIXor | OpIUShr | OpLShr
| OpLShl | OpLAnd | OpLOr | OpLXor | OpLUShr | OpI2L | OpI2F | OpI2D
| OpL2I | OpL2F | OpL2D | OpF2I | OpF2L | OpF2D | OpD2I | OpD2L
| OpD2F | OpI2B | OpI2C | OpI2S | OpCmp _ | OpGoto _ | OpJsr _
| OpRet _ | OpBreakpoint | OpInvalid | OpArrayLength
| OpConst _ -> None
| OpIf (_, _)
| OpIfCmp (_, _) -> Some (Statement
If)
| OpLoad (_jvmt,var_num) ->
(match get_local_variable_info var_num pc code with
None -> None
| Some (name,vt) ->
Some (Name
(SimpleName (name,Some vt))))
| OpArrayLoad _jvmt -> Some (Expression (ArrayAccess None))
| OpStore (_,var_num)
| OpIInc (var_num,_) ->
(match get_local_variable_info var_num pc code with
None -> None
| Some (name,vt) ->
Some (Expression
(Assignment (SimpleName (name,Some vt)))))
| OpArrayStore _ -> Some (Expression (ArrayStore None))
| OpGetField (_cn, fs)
| OpGetStatic (_cn, fs) ->
Some (Name
(SimpleName (fs_name fs,Some (fs_type fs))))
| OpPutStatic (_cn,fs)
| OpPutField (_cn,fs) ->
Some ( Expression
(Assignment
(SimpleName (fs_name fs,Some (fs_type fs)))))
| OpTableSwitch _
| OpLookupSwitch _ -> Some (Statement Switch)
| OpReturn _ -> Some (Statement Return)
| OpInvoke (invtype, ms) ->
begin
match invtype with
`Interface cn
| `Special (_,cn)
| `Static (_,cn) ->
Some (Expression
(MethodInvocationNonVirtual (cn,ms)))
| `Dynamic _ -> None (* not supported *)
| `Virtual ot ->
Some (Expression
(MethodInvocationVirtual (ot,ms)))
end
| OpNew cn -> Some (Expression
(ClassInstanceCreation cn))
| OpNewArray vt -> Some (Expression
(ArrayCreation vt))
| OpAMultiNewArray (ot,_) -> Some (Expression
(ArrayCreation (TObject ot)))
| OpThrow -> Some (Statement
Throw)
| OpCheckCast ot -> Some (Expression
(Cast ot))
| OpInstanceOf ot-> Some (Expression
(InstanceOf ot))
| OpMonitorEnter -> Some (Statement
(Synchronized true))
| OpMonitorExit -> Some (Statement
(Synchronized false))
end
let to_plugin_warning jm pp_warn_map =
match jm with
AbstractMethod _ -> pp_warn_map
| ConcreteMethod cm ->
begin
match cm.cm_implementation with
Native -> pp_warn_map
| Java laz -> let code = Lazy.force laz in
Ptmap.mapi
(fun pc ppwlist ->
let op = code.c_code.(pc) in
List.map
(fun ppw ->
match ppw with
PreciseLineWarning _ -> ppw
| LineWarning (msg,_) as lw ->
(match find_ast_node code pc op with
Some node -> PreciseLineWarning (msg,node)
| None -> lw)
)
ppwlist)
pp_warn_map
end
end)
| null |
https://raw.githubusercontent.com/javalib-team/sawja/da39f9c1c4fc52a1a1a6350be0e39789812b6c00/src/jPrintPlugin.ml
|
ocaml
|
Tags and attributes
* It could be a variable identifier, field name, class name,
etc. Only use the shortest name possible (no package name
before class name, no class name before a field name, etc.).
| NullLiteral
| StringLiteral of string
| TypeLiteral of identifier
| OtherLiteral of float
Others constants (impossible to differenciate int and bool in bytecode, ...)
* Identifier must be the identifier of the left_side of
assignment (field's name or variable's name)
ms ?
It will be searched only in left_side of assignements
type given by handlers table
?Monitor exit corresponds to end parenthisis...
| AssertStat (*How to find them in bytecode: creation of a field
in class + creation of exception to throw
*warning description * optional precision depending of code
representation (used for PreciseLineWarning generation)
* [inst_disp code pc] returns a string representation of instruction at program point [pc].
* Function to provide in order to display the source variable
names in the method signatures.
TODO: check it is valid html for plugin
Try with class name as a source name.
TODO: create a display function that uses names of variables ?
not supported
|
* This file is part of SAWJA
* Copyright ( c)2011 ( INRIA )
*
* This program is free software : you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation , either version 3 of
* the License , or ( at your option ) any later version .
*
* This program is distributed in the hope that it will be useful , but
* WITHOUT ANY WARRANTY ; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE . See the GNU
* General Public License for more details .
*
* You should have received a copy of the GNU General Public
* License along with this program . If not , see
* < / > .
* This file is part of SAWJA
* Copyright (c)2011 Vincent Monfort (INRIA)
*
* This program is free software: you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* </>.
*)
open Javalib_pack
open JBasics
open JProgram
open Javalib
open JPrintUtil
let warn_tag = "warning"
let warn_pp_tag = "warning_pp"
let wmsg_tag = "msg"
let wpp_line = "line"
let wpp_pc = "pc"
let warn_pp_precise = "precise"
let wastnode = "astnode"
let wcname = "cname"
let wvtype = "jtype"
let wsenter = "synch_enter"
let wvname = "vname"
let desc_attr = "descriptor"
let meth_arg="arg_desc"
let meth_sig_on = "on"
let meth_arg_num = "arg"
let class_tag = "class"
let class_cname = "name"
let class_sf = "sourcefile"
let class_inner = "inner"
let class_anon = "anon"
let html_info_tag = "html"
let info_tag = "info"
let ival_tag = "value"
let pp_tag = "pp"
let true_val = "true"
let false_val = "false"
let method_sig_desc ms =
((ms_name ms) ^":(")
^(List.fold_left
(fun msg t ->
msg^(JDumpBasics.type2shortstring t))
""
(ms_args ms))
^(")"^JDumpBasics.rettype2shortstring (ms_rtype ms))
type method_info =
| MethodSignature of string
| Argument of int * string
| Return of string
| This of string
type 'a warning_pp = string * 'a option
type 'a plugin_info =
{
mutable p_infos :
(string list
* string list FieldMap.t
* (method_info list * string list Ptmap.t) MethodMap.t)
ClassMap.t;
mutable p_warnings :
(string list
* string list FieldMap.t
* (method_info list * 'a warning_pp list Ptmap.t) MethodMap.t)
ClassMap.t;
}
type ('c,'f,'m,'p) iow = ('c list
* 'f list FieldMap.t
* ('m list * 'p list Ptmap.t) MethodMap.t)
let find_class_infos cn map =
try ClassMap.find cn map
with Not_found ->
([],FieldMap.empty,MethodMap.empty)
let find_field_infos fs map =
try FieldMap.find fs map with Not_found -> []
let find_meth_infos ms map =
try MethodMap.find ms map with Not_found -> ([],Ptmap.empty)
let find_pp_infos ms pc map =
let (mil,pmap) =
try MethodMap.find ms map
with Not_found -> ([],Ptmap.empty)
in
let ppinfos =
try Ptmap.find pc pmap
with Not_found -> []
in
((mil,pmap),ppinfos)
let add_class_iow i cn map =
let (ci,fi,mi) = find_class_infos cn map in
ClassMap.add cn (i::ci,fi,mi) map
let add_field_iow i cn fs map =
let (ci,fi,mi) = find_class_infos cn map in
let fil = find_field_infos fs fi in
let fi = FieldMap.add fs (i::fil) fi in
ClassMap.add cn (ci,fi,mi) map
let add_meth_iow i cn ms map =
let (ci,fi,mi) = find_class_infos cn map in
let (mil,ptmap) = find_meth_infos ms mi in
let mi = MethodMap.add ms (i::mil,ptmap) mi in
ClassMap.add cn (ci,fi,mi) map
let add_pp_iow i cn ms pc map =
let (ci,fi,mi) = find_class_infos cn map in
let ((mil,pmap),ppil) = find_pp_infos ms pc mi in
let mi = MethodMap.add ms (mil,(Ptmap.add pc (i::ppil) pmap)) mi in
ClassMap.add cn (ci,fi,mi) map
module NewCodePrinter =
struct
module AdaptedASTGrammar =
struct
type identifier =
SimpleName of string * value_type option
type expression =
| Assignment of identifier
| ClassInstanceCreation of class_name
| ArrayCreation of value_type
| MethodInvocationVirtual of object_type * method_signature
Ok if a [ ] [ ] we could not know , optimistic ( only one tab access on a line ? )
| InstanceOf of object_type
| Cast of object_type
type statement =
of InfixExpr option
* Includes all If ' like ' statements ( If , For , While , ConditionnalExpr , etc . )
| Finally
| Switch
| Return
| Throw
type node_unit =
Statement of statement
| Expression of expression
| Name of identifier
let ot2attr ot =
(wvtype,JPrint.object_type ~jvm:true ot)
let vt_opt2attrs =
function
None -> []
| Some vt -> [wvtype,JPrint.value_type ~jvm:true vt]
let ast_node2attributes =
function
Statement st ->
(match st with
If -> [wastnode,"If"]
| Catch cn -> [(wastnode,"Catch");(wcname,cn_name cn)]
| Finally -> [wastnode,"Finally"]
| Switch -> [wastnode,"Switch"]
| Synchronized enterb -> [(wastnode,"Synchronized");(wsenter,string_of_bool enterb)]
| Return -> [wastnode,"Return"]
| Throw -> [wastnode,"Throw"])
| Expression e ->
(match e with
| Assignment id ->
let id_attrs =
match id with
SimpleName (name, vt_opt) ->
(wvname,name)::(vt_opt2attrs vt_opt)
in
(wastnode,"Assignment")::id_attrs
| ClassInstanceCreation cn -> [(wastnode,"ClassInstanceCreation");(wcname,cn_name cn)]
| ArrayCreation vt -> (wastnode,"ArrayCreation")::(vt_opt2attrs (Some vt))
| MethodInvocationNonVirtual (cn,ms) -> [(wastnode,"MethodInvocationNonVirtual"); (wcname, cn_name cn);
(wvname,ms_name ms); (desc_attr, method_sig_desc ms)]
| MethodInvocationVirtual (ot,ms) -> [(wastnode,"MethodInvocationVirtual"); (ot2attr ot);
(wvname,ms_name ms); (desc_attr, method_sig_desc ms)]
| ArrayAccess vt_opt -> (wastnode,"ArrayAccess")::(vt_opt2attrs vt_opt)
| ArrayStore vt_opt -> (wastnode,"ArrayStore")::(vt_opt2attrs vt_opt)
| InstanceOf ot -> [(wastnode,"InstanceOf");(ot2attr ot)]
| Cast ot -> [(wastnode,"Cast");(ot2attr ot)])
| Name id ->
(match id with
SimpleName (name,vt_opt) ->
(wastnode,"SimpleName")::(wvname,name)::(vt_opt2attrs vt_opt))
end
type 'a precise_warning_pp =
LineWarning of 'a warning_pp
| PreciseLineWarning of string * AdaptedASTGrammar.node_unit
* same as LineWarning * AST information *
module type PluginPrinter =
sig
type code
type expr
val empty_infos: expr plugin_info
val print_class: ?html_info:bool -> expr plugin_info -> code interface_or_class -> string -> unit
val print_program: ?html_info:bool -> expr plugin_info -> code program -> string -> unit
end
module type PrintInterface =
sig
type p_code
type p_expr
* [ pc code ] returns the source line number
corresponding the program point pp of the method code m.
corresponding the program point pp of the method code m.*)
val get_source_line_number : int -> p_code -> int option
val inst_disp : int -> p_code -> string
val method_param_names : p_code Javalib.interface_or_class -> method_signature
-> string list option
* Allows to construct detailed warning but it requires good
knowledge of org.eclipse.jdt.core.dom . AST representation . See
existant implementation of to_plugin_warning or simply transform a
warning_pp SimpleWarning in a PreciseWarning of warning .
knowledge of org.eclipse.jdt.core.dom.AST representation. See
existant implementation of to_plugin_warning or simply transform a
warning_pp SimpleWarning in a PreciseWarning of warning.
*)
val to_plugin_warning : p_code jmethod -> p_expr precise_warning_pp list Ptmap.t
-> p_expr precise_warning_pp list Ptmap.t
end
let gen_warning_sig wlist =
List.map
(fun msg ->
let attr = [(wmsg_tag,msg)] in
gen_simple_tag warn_tag attr)
wlist
let gen_info_sig fhtml ilist =
List.map
(fun info ->
let info_xml =
fhtml info
in
gen_custom_tag info_tag [] [info_xml]
)
ilist
let gen_warning_msig wlist =
List.map
(fun meth_i ->
let attr =
match meth_i with
| MethodSignature msg -> [(meth_sig_on,"method");(wmsg_tag,msg)]
| Argument (num,msg) -> [(meth_sig_on,"argument");(meth_arg_num,string_of_int num);(wmsg_tag,msg)]
| Return msg -> [(meth_sig_on,"return");(wmsg_tag,msg)]
| This msg -> [(meth_sig_on,"this");(wmsg_tag,msg)]
in
gen_simple_tag warn_tag attr)
wlist
let gen_info_msig fhtml ilist =
List.map
(fun info ->
let attr, msg =
match info with
| MethodSignature msg -> ([(meth_sig_on,"method")],msg)
| Argument (num,msg) -> ([(meth_sig_on,"argument");(meth_arg_num,string_of_int num)],msg)
| Return msg -> ([(meth_sig_on,"return")],msg)
| This msg -> ([(meth_sig_on,"this")],msg)
in
gen_custom_tag info_tag attr [(fhtml msg)])
ilist
let gen_warning_pp line pc wlist =
let line =
match line with
None -> -1
| Some l -> l
in
List.map
(function wsig ->
let attrs =
match wsig with
LineWarning (msg,_) ->
[(warn_pp_precise, false_val);(wpp_pc,string_of_int pc)
;(wpp_line,string_of_int line);(wmsg_tag,msg)]
| PreciseLineWarning (msg,ast_node) ->
(warn_pp_precise, true_val)::(wpp_pc,string_of_int pc)
::(wpp_line,string_of_int line)::(wmsg_tag,msg)
::(AdaptedASTGrammar.ast_node2attributes ast_node)
in
gen_simple_tag warn_pp_tag attrs)
wlist
let gen_info_pp fhtml disp line pc ilist =
let line =
match line with
None -> -1
| Some l -> l
in
let attrs = [(wpp_pc,string_of_int pc);(wpp_line,string_of_int line);(ival_tag,disp)] in
let infos =
List.map
(fun info ->
gen_custom_tag info_tag [] [(fhtml info)])
ilist
in
gen_custom_tag pp_tag attrs infos
let gen_field_tag fs warnings =
let attrs =
(desc_attr,(fs_name fs)^":"^(JDumpBasics.type2shortstring (fs_type fs)))::[]
in
gen_custom_tag "field" attrs warnings
let gen_method_tag ms warnings =
let attrs =
(desc_attr,method_sig_desc ms)::[]
in
gen_custom_tag "method" attrs warnings
let gen_info_method_tag mpn ms infos =
let attrs =
(desc_attr,method_sig_desc ms)
::("rtype",JPrint.return_type (ms_rtype ms))
::("name",ms_name ms)::[]
in
let args =
ExtList.List.mapi
(fun i vt ->
let name =
match mpn with
None -> []
| Some mpn ->
try ("name",List.nth mpn i)::[] with _ -> []
in
let arg_attrs =
("num",string_of_int i)
::("type",JPrint.value_type vt)
::name
in
gen_simple_tag meth_arg arg_attrs
)
(ms_args ms)
in
gen_custom_tag "method" attrs (args@infos)
let gen_class_tag ?(html=false) ioc treel =
let classname = get_name ioc in
let attrs =
let others_attrs =
if html
then [(html_info_tag,true_val)]
else []
in
let class_attrs =
let rec name_inner_anon inner_list =
match inner_list with
[] -> (class_cname,cn_name classname)::others_attrs
| ic::r ->
(match ic.ic_class_name with
None -> name_inner_anon r
| Some cn ->
if (cn_equal classname cn)
then
(match ic.ic_source_name with
None ->
(class_cname,cn_name classname)::
(class_inner,true_val)::
(class_anon,true_val)::others_attrs
| Some _ ->
(class_cname,cn_name classname)::
(class_inner,true_val)::others_attrs)
else name_inner_anon r)
in
name_inner_anon (get_inner_classes ioc)
in
let sourcefile_attrs =
match get_sourcefile ioc with
Some name ->
let pack =
List.fold_left
(fun pack element -> pack ^ element ^ ".")
"" (cn_package classname)
in
let pname = pack ^name in
(class_sf,pname)::class_attrs
| None -> class_attrs
in
sourcefile_attrs
in
gen_custom_tag class_tag attrs treel
module Make (S : PrintInterface) =
struct
type code = S.p_code
type expr = S.p_expr
let (empty_infos:expr plugin_info) = {
p_infos = ClassMap.empty;
p_warnings = ClassMap.empty
}
let ioc2xml_warn precise_warn info ioc =
let cn = get_name ioc in
if ClassMap.mem cn info.p_warnings
then
begin
let wclass, wfields, wmeth_pp =
ClassMap.find cn info.p_warnings
in
let cl_warn =
gen_warning_sig wclass
in
let fields_tags =
FieldMap.fold
(fun fs wsiglist tree_list ->
(gen_field_tag fs (gen_warning_sig wsiglist))::tree_list
)
wfields
[]
in
let meths_tags =
MethodMap.fold
(fun ms jm tlm ->
let get_source_line pc =
match jm with
AbstractMethod _ -> None
| ConcreteMethod cm ->
begin
match cm.cm_implementation with
| Native -> None
| Java lazcode ->
S.get_source_line_number pc (Lazy.force lazcode)
end
in
let tlm =
let tlpp =
try
let wpps_of_meth =
precise_warn jm (snd (MethodMap.find ms wmeth_pp)) in
Ptmap.fold
(fun pc wpplist tree_list ->
match wpplist with
[] -> tree_list
| _ -> (gen_warning_pp (get_source_line pc) pc wpplist)@tree_list
)
wpps_of_meth
[]
with Not_found -> []
in
let wms_meths =
try
fst (MethodMap.find ms wmeth_pp)
with Not_found -> []
in
match wms_meths, tlpp with
[],[] -> tlm
| _ ->
(gen_method_tag ms
((gen_warning_msig wms_meths)@tlpp)
)::tlm
in
tlm
)
(get_methods ioc)
[]
in
cl_warn@fields_tags@meths_tags
end
else []
let ioc2xml_info fhtml info ioc =
let cn = get_name ioc in
if ClassMap.mem cn info.p_infos
then
begin
let iclass, ifields, imeth_pp =
ClassMap.find cn info.p_infos
in
let class_tags =
match iclass with
[] -> []
| l -> gen_info_sig fhtml l
in
let fields_tags =
FieldMap.fold
(fun fs infos tree_list ->
match infos with
[] -> tree_list
| _ -> (gen_field_tag fs (gen_info_sig fhtml infos))::tree_list
)
ifields
[]
in
let meths_tags =
MethodMap.fold
(fun ms jm tlm ->
let code =
match jm with
AbstractMethod _ -> None
| ConcreteMethod cm ->
begin
match cm.cm_implementation with
| Native -> None
| Java lazcode ->
Some (Lazy.force lazcode)
end
in
let get_source_line pc =
match code with
None -> None
| Some code ->
S.get_source_line_number pc code
in
let pc_disp pc =
match code with
None -> ""
| Some code ->
S.inst_disp pc code
in
let tlm =
let tlpp =
try
let ipps_of_meth = snd (MethodMap.find ms imeth_pp) in
Ptmap.fold
(fun pc ipplist tree_list ->
match ipplist with
[] -> tree_list
| _ ->
(gen_info_pp
fhtml
(pc_disp pc)
(get_source_line pc)
pc ipplist)
::tree_list
)
ipps_of_meth
[]
with Not_found -> []
in
let ims_meths =
try
fst (MethodMap.find ms imeth_pp)
with Not_found -> []
in
match ims_meths, tlpp with
[],[] -> tlm
| _ ->
(gen_info_method_tag
(S.method_param_names ioc ms)
ms
((gen_info_msig fhtml ims_meths)@tlpp))
::tlm
in
tlm
)
(get_methods ioc)
[]
in
class_tags@fields_tags@meths_tags
end
else []
let gen_class_warn_doc precise_warn info ioc =
let tree_list = ioc2xml_warn precise_warn info ioc in
match tree_list with
[] -> None
| _ -> Some (gen_class_tag ioc tree_list)
let gen_class_info_doc html info ioc =
let fhtml = if html then
fun s -> CData s)
else
(fun s -> PCData s)
in
let tree_list = ioc2xml_info fhtml info ioc in
match tree_list with
[] -> None
| _ -> Some (gen_class_tag ~html:html ioc tree_list)
let print_info html (info_p: 'a plugin_info) ioc outputdir =
let cs = get_name ioc in
let package_and_source =
match get_sourcefile ioc with
None ->
"info"::(cn_package cs @ [(cn_simple_name cs)^".java"])
| Some filename -> "info"::(cn_package cs @ [filename])
and cname = cn_simple_name cs in
let doc = gen_class_info_doc html info_p ioc in
match doc with
None -> ()
| Some doc ->
create_package_dir outputdir package_and_source;
let out =
open_out (Filename.concat outputdir
(List.fold_left
Filename.concat "" (package_and_source @ [cname ^ ".xml"])))
in
print_xml_tree ~spc:3 doc out;
close_out out
let print_warnings (info_p: 'a plugin_info) ioc outputdir =
let cs = get_name ioc in
let package_and_source =
"warn"::(cn_package cs)
and cname = cn_simple_name cs in
let ( fun c - > if c = ' . ' then ' / ' else c ) ( cn_name cs ) in
(fun c -> if c = '.' then '/' else c) (cn_name cs) in*)
let pp2pp_precise c map =
(S.to_plugin_warning)
c
(Ptmap.map
(fun lpp ->
List.map (fun (s,prec) -> LineWarning (s,prec)) lpp)
map)
in
let doc = gen_class_warn_doc pp2pp_precise info_p ioc in
match doc with
None -> ()
| Some doc ->
create_package_dir outputdir package_and_source;
let out =
open_out (Filename.concat outputdir
(List.fold_left
Filename.concat "" (package_and_source @ [cname ^ ".xml"])))
in
print_xml_tree ~spc:3 doc out;
close_out out
let print_class ?(html_info=false) (info_p: 'a plugin_info) ioc outputdir =
print_warnings info_p ioc outputdir;
print_info html_info info_p ioc outputdir
let print_program ?(html_info=false) (info_p: 'a plugin_info) (p: S.p_code program) outputdir =
ClassMap.iter
(fun _ node ->
print_class ~html_info:html_info info_p (to_ioc node) outputdir)
p.classes
end
end
open NewCodePrinter
module JCodePrinter = Make(
struct
open JCode
open AdaptedASTGrammar
type p_code = jcode
type p_expr = unit
include from JPrintUtil that contains common code
with JPrintHtml
with JPrintHtml*)
include JCodeUtil
let get_source_line_number pp code =
get_source_line_number pp code
let inst_disp pp code =
JPrint.jopcode code.c_code.(pp)
let find_ast_node code pc op =
let catch_or_finally =
List.fold_left
(fun nu eh ->
if eh.e_handler = pc
then
match eh.e_catch_type with
None -> Some (Statement
Finally)
| Some cn -> Some (Statement
(Catch cn))
else nu
)
None
code.c_exc_tbl
in
match catch_or_finally with
Some _ -> catch_or_finally
| None ->
begin
match op with
| OpNop | OpPop | OpPop2 | OpDup | OpDupX1 | OpDupX2 | OpDup2 | OpDup2X1
| OpDup2X2 | OpSwap | OpAdd _ | OpSub _ | OpMult _ | OpDiv _ | OpRem _
| OpNeg _ | OpIShl | OpIShr | OpIAnd | OpIOr | OpIXor | OpIUShr | OpLShr
| OpLShl | OpLAnd | OpLOr | OpLXor | OpLUShr | OpI2L | OpI2F | OpI2D
| OpL2I | OpL2F | OpL2D | OpF2I | OpF2L | OpF2D | OpD2I | OpD2L
| OpD2F | OpI2B | OpI2C | OpI2S | OpCmp _ | OpGoto _ | OpJsr _
| OpRet _ | OpBreakpoint | OpInvalid | OpArrayLength
| OpConst _ -> None
| OpIf (_, _)
| OpIfCmp (_, _) -> Some (Statement
If)
| OpLoad (_jvmt,var_num) ->
(match get_local_variable_info var_num pc code with
None -> None
| Some (name,vt) ->
Some (Name
(SimpleName (name,Some vt))))
| OpArrayLoad _jvmt -> Some (Expression (ArrayAccess None))
| OpStore (_,var_num)
| OpIInc (var_num,_) ->
(match get_local_variable_info var_num pc code with
None -> None
| Some (name,vt) ->
Some (Expression
(Assignment (SimpleName (name,Some vt)))))
| OpArrayStore _ -> Some (Expression (ArrayStore None))
| OpGetField (_cn, fs)
| OpGetStatic (_cn, fs) ->
Some (Name
(SimpleName (fs_name fs,Some (fs_type fs))))
| OpPutStatic (_cn,fs)
| OpPutField (_cn,fs) ->
Some ( Expression
(Assignment
(SimpleName (fs_name fs,Some (fs_type fs)))))
| OpTableSwitch _
| OpLookupSwitch _ -> Some (Statement Switch)
| OpReturn _ -> Some (Statement Return)
| OpInvoke (invtype, ms) ->
begin
match invtype with
`Interface cn
| `Special (_,cn)
| `Static (_,cn) ->
Some (Expression
(MethodInvocationNonVirtual (cn,ms)))
| `Virtual ot ->
Some (Expression
(MethodInvocationVirtual (ot,ms)))
end
| OpNew cn -> Some (Expression
(ClassInstanceCreation cn))
| OpNewArray vt -> Some (Expression
(ArrayCreation vt))
| OpAMultiNewArray (ot,_) -> Some (Expression
(ArrayCreation (TObject ot)))
| OpThrow -> Some (Statement
Throw)
| OpCheckCast ot -> Some (Expression
(Cast ot))
| OpInstanceOf ot-> Some (Expression
(InstanceOf ot))
| OpMonitorEnter -> Some (Statement
(Synchronized true))
| OpMonitorExit -> Some (Statement
(Synchronized false))
end
let to_plugin_warning jm pp_warn_map =
match jm with
AbstractMethod _ -> pp_warn_map
| ConcreteMethod cm ->
begin
match cm.cm_implementation with
Native -> pp_warn_map
| Java laz -> let code = Lazy.force laz in
Ptmap.mapi
(fun pc ppwlist ->
let op = code.c_code.(pc) in
List.map
(fun ppw ->
match ppw with
PreciseLineWarning _ -> ppw
| LineWarning (msg,_) as lw ->
(match find_ast_node code pc op with
Some node -> PreciseLineWarning (msg,node)
| None -> lw)
)
ppwlist)
pp_warn_map
end
end)
|
a511b19f3ff17f60412632b82652308895200de76428fde28357863843c3224f
|
roburio/dnsvizor
|
unikernel.ml
|
module Main (R : Mirage_random.S) (P : Mirage_clock.PCLOCK)
(M : Mirage_clock.MCLOCK)
(Time : Mirage_time.S) (S : Tcpip.Stack.V4V6) = struct
module Stub = Dns_stub_mirage.Make(R)(Time)(P)(M)(S)
let start () () () () s =
let stub_t =
let nameservers =
Option.map (fun ns -> [ ns ]) (Key_gen.dns_upstream ())
and primary_t =
setup DNS server state :
Dns_server.Primary.create ~rng:Mirage_crypto_rng.generate Dns_trie.empty
in
(* setup stub forwarding state and IP listeners: *)
try
Stub.create ?cache_size:(Key_gen.dns_cache ()) ?nameservers primary_t s
with
Invalid_argument a ->
Logs.err (fun m -> m "error %s" a);
exit Mirage_runtime.argument_error
in
let _ = stub_t in
Since { Stub.create } registers UDP + TCP listeners asynchronously there
is no Lwt task .
We need to return an infinite Lwt task to prevent the unikernel from
exiting early :
is no Lwt task.
We need to return an infinite Lwt task to prevent the unikernel from
exiting early: *)
fst (Lwt.task ())
end
| null |
https://raw.githubusercontent.com/roburio/dnsvizor/6c31f0adaad69c3342affcd836b44e0a5746db5f/dns-only/unikernel.ml
|
ocaml
|
setup stub forwarding state and IP listeners:
|
module Main (R : Mirage_random.S) (P : Mirage_clock.PCLOCK)
(M : Mirage_clock.MCLOCK)
(Time : Mirage_time.S) (S : Tcpip.Stack.V4V6) = struct
module Stub = Dns_stub_mirage.Make(R)(Time)(P)(M)(S)
let start () () () () s =
let stub_t =
let nameservers =
Option.map (fun ns -> [ ns ]) (Key_gen.dns_upstream ())
and primary_t =
setup DNS server state :
Dns_server.Primary.create ~rng:Mirage_crypto_rng.generate Dns_trie.empty
in
try
Stub.create ?cache_size:(Key_gen.dns_cache ()) ?nameservers primary_t s
with
Invalid_argument a ->
Logs.err (fun m -> m "error %s" a);
exit Mirage_runtime.argument_error
in
let _ = stub_t in
Since { Stub.create } registers UDP + TCP listeners asynchronously there
is no Lwt task .
We need to return an infinite Lwt task to prevent the unikernel from
exiting early :
is no Lwt task.
We need to return an infinite Lwt task to prevent the unikernel from
exiting early: *)
fst (Lwt.task ())
end
|
268c918069b35b8ac1464727f80679cd20b1b71eef1eb015306e1069d0cc5757
|
tolitius/grete
|
streams.clj
|
(ns grete.streams
(:require [clojure.string :as s]
[grete.tools :as t]
[jsonista.core :as json])
(:import [clojure.lang Reflector]
[java.util Properties]
[org.apache.kafka.common.serialization Serde
Serdes]
[org.apache.kafka.streams KafkaStreams
KeyValue
StreamsBuilder
StreamsConfig]
[org.apache.kafka.streams.kstream Consumed
KStream
Named
Produced
Predicate
ValueMapper
ValueJoiner
KeyValueMapper
ForeachAction]))
;; config
{ : application - id - config " "
; :client-id-config "augment-plan-snooper"
; :bootstrap-servers-config "localhost:9092"
; :default-key-serde-class-config (-> (k/string-serde) .getClass .getName)
; :default-value-serde-class-config (-> (k/string-serde) .getClass .getName)
: producer.max - request - size ( int 16384255 )
: consumer.max - request - size ( int 16384255 ) }
(defn to-stream-prop [prop]
(try
(if (some #(s/starts-with? (name prop) %) #{StreamsConfig/CONSUMER_PREFIX
StreamsConfig/PRODUCER_PREFIX
StreamsConfig/ADMIN_CLIENT_PREFIX
StreamsConfig/GLOBAL_CONSUMER_PREFIX
StreamsConfig/MAIN_CONSUMER_PREFIX
StreamsConfig/RESTORE_CONSUMER_PREFIX
StreamsConfig/TOPIC_PREFIX})
(t/kebab->dotted prop)
(->> prop
t/kebab->screaming-snake
(Reflector/getStaticField StreamsConfig)))
(catch Exception e
(let [msg (str "kafka streams does not understand this property name \"" prop "\"")]
(println "(!)" msg)
(throw (RuntimeException. msg e))))))
(defn to-stream-config [m]
(let [ps (Properties.)]
(doseq [[k v] m]
(.put ps (to-stream-prop k)
v))
ps))
;; core
(defn stream-builder []
(StreamsBuilder.))
;; serializers / deserializers
(defn string-serde []
(Serdes/String))
(defn long-serde []
(Serdes/Long))
(defn int-serde []
(Serdes/Integer))
;; directing flow
(defn topic->stream
([builder topic]
(topic->stream builder topic {}))
([builder topic {:keys [key-serde value-serde]
:or {key-serde (string-serde)
value-serde (string-serde)}}]
(.stream builder topic (Consumed/with key-serde
value-serde))))
(defn topic->table
([builder topic]
(topic->table builder topic {}))
([builder topic {:keys [key-serde value-serde]
:or {key-serde (string-serde)
value-serde (string-serde)}}]
(.table builder topic (Consumed/with key-serde
value-serde))))
(defn topic->global-table
([builder topic]
(topic->global-table builder topic {}))
([builder topic {:keys [key-serde value-serde]
:or {key-serde (string-serde)
value-serde (string-serde)}}]
(.globalTable builder topic (Consumed/with key-serde
value-serde))))
(defn stream->topic
([stream topic]
(stream->topic stream topic {}))
([stream topic {:keys [key-serde value-serde]
:or {key-serde (string-serde)
value-serde (string-serde)}}]
(.to stream topic (Produced/with key-serde
value-serde))))
;; ->fn kafka stream wrappers
(defn named-as [op f]
(Named/as (str
(name op) "." (t/stream-fn->name f))))
(deftype FunValueMapper [fun]
ValueMapper
(apply [_ v]
(fun v)))
(defn map-values
([fun]
(partial map-values fun))
([fun stream]
(.mapValues stream
(FunValueMapper. fun)
(named-as :map-values fun))))
(defn to-kv [[k v]]
(KeyValue. k v))
(deftype FunKeyValueMapper [fun]
KeyValueMapper
(apply [_ k v]
(-> (fun k v)
to-kv)))
(defn map-kv
([fun]
(partial map-kv fun))
([fun stream]
(.map stream
(FunKeyValueMapper. fun)
(named-as :map-kv fun))))
(deftype FunPredicate [fun]
Predicate
(test [_ k v]
(boolean (fun k v))))
(defn filter-kv
([fun]
(partial filter-kv fun))
([fun stream]
(.filter stream
(FunPredicate. fun)
(named-as :filter fun))))
(deftype FunValueJoiner [fun]
ValueJoiner
(apply [_ left right]
(fun left right)))
(defn left-join
([fun]
(partial left-join fun))
([fun stream table]
(.leftJoin stream
table
.. ) does not have a Named arg ¯\_(ツ)_/¯
(deftype FunForeachAction [fun]
ForeachAction
(apply [_ k v]
(fun k v)
nil))
(defn for-each
"you would use foreach to cause side effects based on the input data (similar to peek)
and then stop further processing of the input data
(unlike peek, which is not a terminal operation)"
([fun]
(partial for-each fun))
([fun stream]
(.foreach stream
(FunForeachAction. fun)
(named-as :for-each fun))))
(defn peek
"performs a stateless action on each record, and returns an unchanged stream. (details)
you would use peek to cause side effects based on the input data (similar to foreach)
and continue processing the input data (unlike foreach, which is a terminal operation)
peek returns the input stream as-is; if you need to modify the input stream, use map or mapValues instead
peek is helpful for use cases such as logging or tracking metrics or for debugging and troubleshooting"
([fun]
(partial peek fun))
([fun stream]
(.peek stream
(FunForeachAction. fun)
(named-as :peek fun))))
;; topology plumbing
(defn make-streams [config builder]
(let [topology (.build builder)]
{:topology topology
:streams (KafkaStreams. topology
(to-stream-config config))}))
(defn describe-topology [streams]
(-> streams :topology .describe))
(defn start-streams [streams]
(.start (-> streams :streams))
streams)
(defn cleanup-streams [streams]
(.cleanUp (-> streams :streams))
streams)
(defn stop-streams [streams]
(.close (-> streams :streams))
streams)
(defn stream-on! [config make-topology]
(let [builder (stream-builder)
_ (make-topology builder) ;; custom fn, can't rely on it returning a builder
streams (make-streams config builder)]
(start-streams streams)
streams)) ;; returns {:streams .. :topology ..}
;; helpers: thinking phase, subject to change
(defn transform
"for single topic to topic streams
takes one or more kafka stream functions: map-kv, map-values, filter-kv, etc.
applies them on a stream from one topic to another
(transform builder
[{:from \"foo-topic\" :to \"bar-topc\" :via (k/map-kv some-fn-that-takes-k-and-v)}
{:from \"baz-topic\" :to \"moo-topc\" :via [(k/map-values some-fn-that-takes-value)
(k/filter-kv some-fn-that-takes-k-and-v-and-returns-boolean)]}
{:from \"zoo-topic\" :via (k/for-each some-fn-that-takes-k-and-v)}])"
[builder streams]
(mapv (fn [{:keys [from to via]
:or {via identity}}]
(let [funs (-> via t/to-coll reverse)
stream (->> (topic->stream builder from)
((apply comp funs)))]
(when to
(stream->topic stream to))))
streams))
| null |
https://raw.githubusercontent.com/tolitius/grete/b76c308060fad1e4eac252e0e89eb98852d4adec/src/grete/streams.clj
|
clojure
|
config
:client-id-config "augment-plan-snooper"
:bootstrap-servers-config "localhost:9092"
:default-key-serde-class-config (-> (k/string-serde) .getClass .getName)
:default-value-serde-class-config (-> (k/string-serde) .getClass .getName)
core
serializers / deserializers
directing flow
->fn kafka stream wrappers
if you need to modify the input stream, use map or mapValues instead
topology plumbing
custom fn, can't rely on it returning a builder
returns {:streams .. :topology ..}
helpers: thinking phase, subject to change
|
(ns grete.streams
(:require [clojure.string :as s]
[grete.tools :as t]
[jsonista.core :as json])
(:import [clojure.lang Reflector]
[java.util Properties]
[org.apache.kafka.common.serialization Serde
Serdes]
[org.apache.kafka.streams KafkaStreams
KeyValue
StreamsBuilder
StreamsConfig]
[org.apache.kafka.streams.kstream Consumed
KStream
Named
Produced
Predicate
ValueMapper
ValueJoiner
KeyValueMapper
ForeachAction]))
{ : application - id - config " "
: producer.max - request - size ( int 16384255 )
: consumer.max - request - size ( int 16384255 ) }
(defn to-stream-prop [prop]
(try
(if (some #(s/starts-with? (name prop) %) #{StreamsConfig/CONSUMER_PREFIX
StreamsConfig/PRODUCER_PREFIX
StreamsConfig/ADMIN_CLIENT_PREFIX
StreamsConfig/GLOBAL_CONSUMER_PREFIX
StreamsConfig/MAIN_CONSUMER_PREFIX
StreamsConfig/RESTORE_CONSUMER_PREFIX
StreamsConfig/TOPIC_PREFIX})
(t/kebab->dotted prop)
(->> prop
t/kebab->screaming-snake
(Reflector/getStaticField StreamsConfig)))
(catch Exception e
(let [msg (str "kafka streams does not understand this property name \"" prop "\"")]
(println "(!)" msg)
(throw (RuntimeException. msg e))))))
(defn to-stream-config [m]
(let [ps (Properties.)]
(doseq [[k v] m]
(.put ps (to-stream-prop k)
v))
ps))
(defn stream-builder []
(StreamsBuilder.))
(defn string-serde []
(Serdes/String))
(defn long-serde []
(Serdes/Long))
(defn int-serde []
(Serdes/Integer))
(defn topic->stream
([builder topic]
(topic->stream builder topic {}))
([builder topic {:keys [key-serde value-serde]
:or {key-serde (string-serde)
value-serde (string-serde)}}]
(.stream builder topic (Consumed/with key-serde
value-serde))))
(defn topic->table
([builder topic]
(topic->table builder topic {}))
([builder topic {:keys [key-serde value-serde]
:or {key-serde (string-serde)
value-serde (string-serde)}}]
(.table builder topic (Consumed/with key-serde
value-serde))))
(defn topic->global-table
([builder topic]
(topic->global-table builder topic {}))
([builder topic {:keys [key-serde value-serde]
:or {key-serde (string-serde)
value-serde (string-serde)}}]
(.globalTable builder topic (Consumed/with key-serde
value-serde))))
(defn stream->topic
([stream topic]
(stream->topic stream topic {}))
([stream topic {:keys [key-serde value-serde]
:or {key-serde (string-serde)
value-serde (string-serde)}}]
(.to stream topic (Produced/with key-serde
value-serde))))
(defn named-as [op f]
(Named/as (str
(name op) "." (t/stream-fn->name f))))
(deftype FunValueMapper [fun]
ValueMapper
(apply [_ v]
(fun v)))
(defn map-values
([fun]
(partial map-values fun))
([fun stream]
(.mapValues stream
(FunValueMapper. fun)
(named-as :map-values fun))))
(defn to-kv [[k v]]
(KeyValue. k v))
(deftype FunKeyValueMapper [fun]
KeyValueMapper
(apply [_ k v]
(-> (fun k v)
to-kv)))
(defn map-kv
([fun]
(partial map-kv fun))
([fun stream]
(.map stream
(FunKeyValueMapper. fun)
(named-as :map-kv fun))))
(deftype FunPredicate [fun]
Predicate
(test [_ k v]
(boolean (fun k v))))
(defn filter-kv
([fun]
(partial filter-kv fun))
([fun stream]
(.filter stream
(FunPredicate. fun)
(named-as :filter fun))))
(deftype FunValueJoiner [fun]
ValueJoiner
(apply [_ left right]
(fun left right)))
(defn left-join
([fun]
(partial left-join fun))
([fun stream table]
(.leftJoin stream
table
.. ) does not have a Named arg ¯\_(ツ)_/¯
(deftype FunForeachAction [fun]
ForeachAction
(apply [_ k v]
(fun k v)
nil))
(defn for-each
"you would use foreach to cause side effects based on the input data (similar to peek)
and then stop further processing of the input data
(unlike peek, which is not a terminal operation)"
([fun]
(partial for-each fun))
([fun stream]
(.foreach stream
(FunForeachAction. fun)
(named-as :for-each fun))))
(defn peek
"performs a stateless action on each record, and returns an unchanged stream. (details)
you would use peek to cause side effects based on the input data (similar to foreach)
and continue processing the input data (unlike foreach, which is a terminal operation)
peek is helpful for use cases such as logging or tracking metrics or for debugging and troubleshooting"
([fun]
(partial peek fun))
([fun stream]
(.peek stream
(FunForeachAction. fun)
(named-as :peek fun))))
(defn make-streams [config builder]
(let [topology (.build builder)]
{:topology topology
:streams (KafkaStreams. topology
(to-stream-config config))}))
(defn describe-topology [streams]
(-> streams :topology .describe))
(defn start-streams [streams]
(.start (-> streams :streams))
streams)
(defn cleanup-streams [streams]
(.cleanUp (-> streams :streams))
streams)
(defn stop-streams [streams]
(.close (-> streams :streams))
streams)
(defn stream-on! [config make-topology]
(let [builder (stream-builder)
streams (make-streams config builder)]
(start-streams streams)
(defn transform
"for single topic to topic streams
takes one or more kafka stream functions: map-kv, map-values, filter-kv, etc.
applies them on a stream from one topic to another
(transform builder
[{:from \"foo-topic\" :to \"bar-topc\" :via (k/map-kv some-fn-that-takes-k-and-v)}
{:from \"baz-topic\" :to \"moo-topc\" :via [(k/map-values some-fn-that-takes-value)
(k/filter-kv some-fn-that-takes-k-and-v-and-returns-boolean)]}
{:from \"zoo-topic\" :via (k/for-each some-fn-that-takes-k-and-v)}])"
[builder streams]
(mapv (fn [{:keys [from to via]
:or {via identity}}]
(let [funs (-> via t/to-coll reverse)
stream (->> (topic->stream builder from)
((apply comp funs)))]
(when to
(stream->topic stream to))))
streams))
|
35eaf052f4a06b7254f7b7c0af00b5495f687bdc2db7c5afac203654d4791d47
|
jafingerhut/thalia
|
doc.clj
|
(ns thalia.doc
(:require [clojure.pprint :as pp]
[clojure.java.io :as io]
[clojure.set :as set]
[thalia.utils :refer [iprintf read-safely]]))
(defn- append-doc! [v additional-docstring]
(let [m (meta v)
;; Save the original doc string if we have not done so earlier
m (if (contains? m :thalia/original-doc)
m
(assoc m :thalia/original-doc (:doc m)))
^String orig-doc (:thalia/original-doc m)
new-doc (str orig-doc
(if (.endsWith orig-doc "\n")
""
"\n")
"--------- ^^^ original docs --------- VVV unofficial extra docs ---------\n"
additional-docstring)
m (assoc m :doc new-doc)]
(reset-meta! v m)))
;; TBD: Find somewhere appropriate to describe the behavior of
;; keywords looking themselves up in collections via (:keyword coll)
;; syntax.
TBD : Are the sequences returned by subseq and rsubseq lazy ?
(defn- ns-if-loaded [ns-name-str]
(try
(the-ns (symbol ns-name-str))
(catch Exception e
nil)))
(defn- do-the-add! [opts rsrc-fname doc-data]
;; TBD: Is there a 'standard' way to check for libraries other
;; than clojure.core what version is loaded?
(let [missing-namespaces-warned (atom #{})]
(doseq [[{:keys [library version]} data-for-symbols] doc-data]
(doseq [one-sym-data data-for-symbols]
(if-let [missing-keys (seq (set/difference #{:ns :symbol
:extended-docstring}
(set (keys one-sym-data))))]
(do
(binding [*out* *err*]
(iprintf "Resource file '%s' has the following map that is missing needed keys %s:\n"
rsrc-fname missing-keys)
(pp/pprint one-sym-data)
(println)))
(let [ns-name-str (:ns one-sym-data)
sym-name-str (:symbol one-sym-data)
extended-docstring (:extended-docstring one-sym-data)
ns (find-ns (symbol ns-name-str))
sym (symbol ns-name-str sym-name-str)]
(if-let [var (try (resolve sym)
(catch Exception e nil))]
(do
(append-doc! var extended-docstring)
(when (:debug opts)
(iprintf *err* "Added extended doc string for symbol %s\n" sym)))
(if ns
(iprintf *err* "Resource file '%s' has extra docs for var %s in namespace %s, but you have no such symbol in that namespace -- do you have a different version of library '%s' than '%s'?\n"
rsrc-fname sym-name-str ns-name-str library version)
(do
(when-not (@missing-namespaces-warned ns-name-str)
(iprintf *err* "Skipping extra docs for namespace %s in resource file '%s -- no such namespace is loaded\n"
ns-name-str rsrc-fname)
(swap! missing-namespaces-warned conj ns-name-str)))))))))))
(defn add-extra-docs!
"Modify the doc strings of vars, by adding extra docs specified in a
resource file. Options can be given as args: key1 val1 key2 val2 ...
Examples:
(add-extra-docs!)
(add-extra-docs! :debug true :language \"en_US\")
:language - A string naming the language of the extra docs to add.
Defaults to the language of your default locale in the
JVM, e.g. \"en_US\" is US English.
:debug - A boolean indicating whether to print extra debug
messages. Defaults to false."
[& args]
(let [default-locale (str (java.util.Locale/getDefault))
opts (merge {:language default-locale}
(apply hash-map args))
rsrc-fname (str (:language opts) ".clj")
file (io/resource rsrc-fname)]
(if-not file
(iprintf *err* "No resource file %s exists. Either '%s' is not a language,
or no one has written thalia docs in that language yet.\n"
rsrc-fname (:language opts))
(let [doc-data (read-safely file)]
(do-the-add! opts rsrc-fname doc-data)))))
(comment
(in-ns 'user) (use 'clojure.repl) (require 'thalia.doc) (thalia.doc/add-extra-docs!)
)
| null |
https://raw.githubusercontent.com/jafingerhut/thalia/20c98eec8168ff72c5b3965cc048b817d34a4583/src/thalia/doc.clj
|
clojure
|
Save the original doc string if we have not done so earlier
TBD: Find somewhere appropriate to describe the behavior of
keywords looking themselves up in collections via (:keyword coll)
syntax.
TBD: Is there a 'standard' way to check for libraries other
than clojure.core what version is loaded?
|
(ns thalia.doc
(:require [clojure.pprint :as pp]
[clojure.java.io :as io]
[clojure.set :as set]
[thalia.utils :refer [iprintf read-safely]]))
(defn- append-doc! [v additional-docstring]
(let [m (meta v)
m (if (contains? m :thalia/original-doc)
m
(assoc m :thalia/original-doc (:doc m)))
^String orig-doc (:thalia/original-doc m)
new-doc (str orig-doc
(if (.endsWith orig-doc "\n")
""
"\n")
"--------- ^^^ original docs --------- VVV unofficial extra docs ---------\n"
additional-docstring)
m (assoc m :doc new-doc)]
(reset-meta! v m)))
TBD : Are the sequences returned by subseq and rsubseq lazy ?
(defn- ns-if-loaded [ns-name-str]
(try
(the-ns (symbol ns-name-str))
(catch Exception e
nil)))
(defn- do-the-add! [opts rsrc-fname doc-data]
(let [missing-namespaces-warned (atom #{})]
(doseq [[{:keys [library version]} data-for-symbols] doc-data]
(doseq [one-sym-data data-for-symbols]
(if-let [missing-keys (seq (set/difference #{:ns :symbol
:extended-docstring}
(set (keys one-sym-data))))]
(do
(binding [*out* *err*]
(iprintf "Resource file '%s' has the following map that is missing needed keys %s:\n"
rsrc-fname missing-keys)
(pp/pprint one-sym-data)
(println)))
(let [ns-name-str (:ns one-sym-data)
sym-name-str (:symbol one-sym-data)
extended-docstring (:extended-docstring one-sym-data)
ns (find-ns (symbol ns-name-str))
sym (symbol ns-name-str sym-name-str)]
(if-let [var (try (resolve sym)
(catch Exception e nil))]
(do
(append-doc! var extended-docstring)
(when (:debug opts)
(iprintf *err* "Added extended doc string for symbol %s\n" sym)))
(if ns
(iprintf *err* "Resource file '%s' has extra docs for var %s in namespace %s, but you have no such symbol in that namespace -- do you have a different version of library '%s' than '%s'?\n"
rsrc-fname sym-name-str ns-name-str library version)
(do
(when-not (@missing-namespaces-warned ns-name-str)
(iprintf *err* "Skipping extra docs for namespace %s in resource file '%s -- no such namespace is loaded\n"
ns-name-str rsrc-fname)
(swap! missing-namespaces-warned conj ns-name-str)))))))))))
(defn add-extra-docs!
"Modify the doc strings of vars, by adding extra docs specified in a
resource file. Options can be given as args: key1 val1 key2 val2 ...
Examples:
(add-extra-docs!)
(add-extra-docs! :debug true :language \"en_US\")
:language - A string naming the language of the extra docs to add.
Defaults to the language of your default locale in the
JVM, e.g. \"en_US\" is US English.
:debug - A boolean indicating whether to print extra debug
messages. Defaults to false."
[& args]
(let [default-locale (str (java.util.Locale/getDefault))
opts (merge {:language default-locale}
(apply hash-map args))
rsrc-fname (str (:language opts) ".clj")
file (io/resource rsrc-fname)]
(if-not file
(iprintf *err* "No resource file %s exists. Either '%s' is not a language,
or no one has written thalia docs in that language yet.\n"
rsrc-fname (:language opts))
(let [doc-data (read-safely file)]
(do-the-add! opts rsrc-fname doc-data)))))
(comment
(in-ns 'user) (use 'clojure.repl) (require 'thalia.doc) (thalia.doc/add-extra-docs!)
)
|
7644aebcebe196b5e6f06168c323b37fdfcfe582d7b3cf6cea02815aa543c0c2
|
weavejester/lein-auto
|
project.clj
|
(defproject lein-auto "0.1.3"
:description "Leiningen plugin that executes tasks when files are modified"
:url "-auto"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:eval-in-leiningen true
:dependencies [[hawk "0.2.11"]
[medley "1.0.0"]])
| null |
https://raw.githubusercontent.com/weavejester/lein-auto/218ddef2894b42ad91434350fac38652a7d35e13/project.clj
|
clojure
|
(defproject lein-auto "0.1.3"
:description "Leiningen plugin that executes tasks when files are modified"
:url "-auto"
:license {:name "Eclipse Public License"
:url "-v10.html"}
:eval-in-leiningen true
:dependencies [[hawk "0.2.11"]
[medley "1.0.0"]])
|
|
f9d2870d1466475737eb0282f6121cbe0c322f58f063f1f46402d38e8bbc7f9d
|
rjray/advent-2020-clojure
|
day25.clj
|
(ns advent-of-code.day25
(:require [clojure.string :as str]))
(defn- get-input [func input]
(->> input
str/split-lines
func))
(defn- parse-data [lines]
[(read-string (first lines)) (read-string (last lines))])
(defn- iteration [value subjnum]
(rem (* value subjnum) 20201227))
(defn- find-loops [target]
(loop [n 1, value 1]
(cond
(= value target) (dec n)
:else (recur (inc n) (iteration value 7)))))
(defn- transform [value loops]
(reduce (fn [x _]
(iteration x value ))
1 (range loops)))
(defn- find-key [[card door]]
(let [loops (find-loops card)]
(transform door loops)))
(defn part-1
"Day 25 Part 1"
[input]
(->> input
(get-input parse-data)
find-key))
No part 2 on day 25 .
| null |
https://raw.githubusercontent.com/rjray/advent-2020-clojure/631b36545ae1efdebd11ca3dd4dca032346e8601/src/advent_of_code/day25.clj
|
clojure
|
(ns advent-of-code.day25
(:require [clojure.string :as str]))
(defn- get-input [func input]
(->> input
str/split-lines
func))
(defn- parse-data [lines]
[(read-string (first lines)) (read-string (last lines))])
(defn- iteration [value subjnum]
(rem (* value subjnum) 20201227))
(defn- find-loops [target]
(loop [n 1, value 1]
(cond
(= value target) (dec n)
:else (recur (inc n) (iteration value 7)))))
(defn- transform [value loops]
(reduce (fn [x _]
(iteration x value ))
1 (range loops)))
(defn- find-key [[card door]]
(let [loops (find-loops card)]
(transform door loops)))
(defn part-1
"Day 25 Part 1"
[input]
(->> input
(get-input parse-data)
find-key))
No part 2 on day 25 .
|
|
f6e6c83086eab414e450f773160f1c215cc0033e2b69e4f746c9ef730a6df3a6
|
langston-barrett/CoverTranslator
|
Newtype.hs
|
Test for Core2Agda
module Newtype where
newtype L a = L [a] -- produces currently a "typeOfBind" error
data LL a = LL [ a ] -- this works
| null |
https://raw.githubusercontent.com/langston-barrett/CoverTranslator/4172bef9f4eede7e45dc002a70bf8c6dd9a56b5c/src/test/Newtype.hs
|
haskell
|
produces currently a "typeOfBind" error
this works
|
Test for Core2Agda
module Newtype where
|
ad6419b6ef66aef066584b7f3ea8739a548c07a22c1aa476b65f3d0a7c44af59
|
8c6794b6/guile-tjit
|
message.scm
|
;;; User interface messages
Copyright ( C ) 2009 , 2010 , 2011 , 2012 Free Software Foundation , Inc.
;;; This library 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 ; either
version 3 of the License , or ( at your option ) any later version .
;;;
;;; This library 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 library; if not, write to the Free Software
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
;;; Commentary:
;;;
;;; This module provide a simple interface to send messages to the user.
;;; TODO: Internationalize messages.
;;;
;;; Code:
(define-module (system base message)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
#:use-module (ice-9 match)
#:export (*current-warning-port*
*current-warning-prefix*
warning
warning-type? warning-type-name warning-type-description
warning-type-printer lookup-warning-type
%warning-types))
;;;
;;; Source location
;;;
(define (location-string loc)
(if (pair? loc)
(format #f "~a:~a:~a"
(or (assoc-ref loc 'filename) "<stdin>")
(1+ (assoc-ref loc 'line))
(assoc-ref loc 'column))
"<unknown-location>"))
;;;
;;; Warnings
;;;
;; This name existed before %current-warning-port was introduced, but
;; otherwise it is a deprecated binding.
(define *current-warning-port*
Ca n't play the identifier - syntax deprecation game in Guile 2.0 , as
;; other modules might depend on this being a normal binding and not a
;; syntax binding.
(parameter-fluid current-warning-port))
(define *current-warning-prefix*
;; Prefix string when emitting a warning.
(make-fluid ";;; "))
(define-record-type <warning-type>
(make-warning-type name description printer)
warning-type?
(name warning-type-name)
(description warning-type-description)
(printer warning-type-printer))
(define %warning-types
;; List of known warning types.
(map (lambda (args)
(apply make-warning-type args))
(let-syntax ((emit
(lambda (s)
(syntax-case s ()
((_ port fmt args ...)
(string? (syntax->datum #'fmt))
(with-syntax ((fmt
(string-append "~a"
(syntax->datum
#'fmt))))
#'(format port fmt
(fluid-ref *current-warning-prefix*)
args ...)))))))
`((unsupported-warning ;; a "meta warning"
"warn about unknown warning types"
,(lambda (port unused name)
(emit port "warning: unknown warning type `~A'~%"
name)))
(unused-variable
"report unused variables"
,(lambda (port loc name)
(emit port "~A: warning: unused variable `~A'~%"
loc name)))
(unused-toplevel
"report unused local top-level variables"
,(lambda (port loc name)
(emit port "~A: warning: possibly unused local top-level variable `~A'~%"
loc name)))
(unbound-variable
"report possibly unbound variables"
,(lambda (port loc name)
(emit port "~A: warning: possibly unbound variable `~A'~%"
loc name)))
(macro-use-before-definition
"report possibly mis-use of macros before they are defined"
,(lambda (port loc name)
(emit port "~A: warning: macro `~A' used before definition~%"
loc name)))
(arity-mismatch
"report procedure arity mismatches (wrong number of arguments)"
,(lambda (port loc name certain?)
(if certain?
(emit port
"~A: warning: wrong number of arguments to `~A'~%"
loc name)
(emit port
"~A: warning: possibly wrong number of arguments to `~A'~%"
loc name))))
(duplicate-case-datum
"report a duplicate datum in a case expression"
,(lambda (port loc datum clause case-expr)
(emit port
"~A: warning: duplicate datum ~S in clause ~S of case expression ~S~%"
loc datum clause case-expr)))
(bad-case-datum
"report a case datum that cannot be meaningfully compared using `eqv?'"
,(lambda (port loc datum clause case-expr)
(emit port
"~A: warning: datum ~S cannot be meaningfully compared using `eqv?' in clause ~S of case expression ~S~%"
loc datum clause case-expr)))
(format
"report wrong number of arguments to `format'"
,(lambda (port loc . rest)
(define (escape-newlines str)
(list->string
(string-fold-right (lambda (c r)
(if (eq? c #\newline)
(append '(#\\ #\n) r)
(cons c r)))
'()
str)))
(define (range min max)
(cond ((eq? min 'any)
(if (eq? max 'any)
"any number" ;; can't happen
(emit #f "up to ~a" max)))
((eq? max 'any)
(emit #f "at least ~a" min))
((= min max) (number->string min))
(else
(emit #f "~a to ~a" min max))))
(match rest
(('simple-format fmt opt)
(emit port
"~A: warning: ~S: unsupported format option ~~~A, use (ice-9 format) instead~%"
loc (escape-newlines fmt) opt))
(('wrong-format-arg-count fmt min max actual)
(emit port
"~A: warning: ~S: wrong number of `format' arguments: expected ~A, got ~A~%"
loc (escape-newlines fmt)
(range min max) actual))
(('syntax-error 'unterminated-iteration fmt)
(emit port "~A: warning: ~S: unterminated iteration~%"
loc (escape-newlines fmt)))
(('syntax-error 'unterminated-conditional fmt)
(emit port "~A: warning: ~S: unterminated conditional~%"
loc (escape-newlines fmt)))
(('syntax-error 'unexpected-semicolon fmt)
(emit port "~A: warning: ~S: unexpected `~~;'~%"
loc (escape-newlines fmt)))
(('syntax-error 'unexpected-conditional-termination fmt)
(emit port "~A: warning: ~S: unexpected `~~]'~%"
loc (escape-newlines fmt)))
(('wrong-port wrong-port)
(emit port
"~A: warning: ~S: wrong port argument~%"
loc wrong-port))
(('wrong-format-string fmt)
(emit port
"~A: warning: ~S: wrong format string~%"
loc fmt))
(('non-literal-format-string)
(emit port
"~A: warning: non-literal format string~%"
loc))
(('wrong-num-args count)
(emit port
"~A: warning: wrong number of arguments to `format'~%"
loc))
(else
(emit port "~A: `format' warning~%" loc)))))))))
(define (lookup-warning-type name)
"Return the warning type NAME or `#f' if not found."
(find (lambda (wt)
(eq? name (warning-type-name wt)))
%warning-types))
(define (warning type location . args)
"Emit a warning of type TYPE for source location LOCATION (a source
property alist) using the data in ARGS."
(let ((wt (lookup-warning-type type))
(port (current-warning-port)))
(if (warning-type? wt)
(apply (warning-type-printer wt)
port (location-string location)
args)
(format port "~A: unknown warning type `~A': ~A~%"
(location-string location) type args))))
;;; message.scm ends here
| null |
https://raw.githubusercontent.com/8c6794b6/guile-tjit/9566e480af2ff695e524984992626426f393414f/module/system/base/message.scm
|
scheme
|
User interface messages
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
either
This library 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.
License along with this library; if not, write to the Free Software
Commentary:
This module provide a simple interface to send messages to the user.
TODO: Internationalize messages.
Code:
Source location
Warnings
This name existed before %current-warning-port was introduced, but
otherwise it is a deprecated binding.
other modules might depend on this being a normal binding and not a
syntax binding.
Prefix string when emitting a warning.
List of known warning types.
a "meta warning"
can't happen
message.scm ends here
|
Copyright ( C ) 2009 , 2010 , 2011 , 2012 Free Software Foundation , Inc.
version 3 of the License , or ( at your option ) any later version .
You should have received a copy of the GNU Lesser General Public
Foundation , Inc. , 51 Franklin Street , Fifth Floor , Boston , USA
(define-module (system base message)
#:use-module (srfi srfi-1)
#:use-module (srfi srfi-9)
#:use-module (ice-9 match)
#:export (*current-warning-port*
*current-warning-prefix*
warning
warning-type? warning-type-name warning-type-description
warning-type-printer lookup-warning-type
%warning-types))
(define (location-string loc)
(if (pair? loc)
(format #f "~a:~a:~a"
(or (assoc-ref loc 'filename) "<stdin>")
(1+ (assoc-ref loc 'line))
(assoc-ref loc 'column))
"<unknown-location>"))
(define *current-warning-port*
Ca n't play the identifier - syntax deprecation game in Guile 2.0 , as
(parameter-fluid current-warning-port))
(define *current-warning-prefix*
(make-fluid ";;; "))
(define-record-type <warning-type>
(make-warning-type name description printer)
warning-type?
(name warning-type-name)
(description warning-type-description)
(printer warning-type-printer))
(define %warning-types
(map (lambda (args)
(apply make-warning-type args))
(let-syntax ((emit
(lambda (s)
(syntax-case s ()
((_ port fmt args ...)
(string? (syntax->datum #'fmt))
(with-syntax ((fmt
(string-append "~a"
(syntax->datum
#'fmt))))
#'(format port fmt
(fluid-ref *current-warning-prefix*)
args ...)))))))
"warn about unknown warning types"
,(lambda (port unused name)
(emit port "warning: unknown warning type `~A'~%"
name)))
(unused-variable
"report unused variables"
,(lambda (port loc name)
(emit port "~A: warning: unused variable `~A'~%"
loc name)))
(unused-toplevel
"report unused local top-level variables"
,(lambda (port loc name)
(emit port "~A: warning: possibly unused local top-level variable `~A'~%"
loc name)))
(unbound-variable
"report possibly unbound variables"
,(lambda (port loc name)
(emit port "~A: warning: possibly unbound variable `~A'~%"
loc name)))
(macro-use-before-definition
"report possibly mis-use of macros before they are defined"
,(lambda (port loc name)
(emit port "~A: warning: macro `~A' used before definition~%"
loc name)))
(arity-mismatch
"report procedure arity mismatches (wrong number of arguments)"
,(lambda (port loc name certain?)
(if certain?
(emit port
"~A: warning: wrong number of arguments to `~A'~%"
loc name)
(emit port
"~A: warning: possibly wrong number of arguments to `~A'~%"
loc name))))
(duplicate-case-datum
"report a duplicate datum in a case expression"
,(lambda (port loc datum clause case-expr)
(emit port
"~A: warning: duplicate datum ~S in clause ~S of case expression ~S~%"
loc datum clause case-expr)))
(bad-case-datum
"report a case datum that cannot be meaningfully compared using `eqv?'"
,(lambda (port loc datum clause case-expr)
(emit port
"~A: warning: datum ~S cannot be meaningfully compared using `eqv?' in clause ~S of case expression ~S~%"
loc datum clause case-expr)))
(format
"report wrong number of arguments to `format'"
,(lambda (port loc . rest)
(define (escape-newlines str)
(list->string
(string-fold-right (lambda (c r)
(if (eq? c #\newline)
(append '(#\\ #\n) r)
(cons c r)))
'()
str)))
(define (range min max)
(cond ((eq? min 'any)
(if (eq? max 'any)
(emit #f "up to ~a" max)))
((eq? max 'any)
(emit #f "at least ~a" min))
((= min max) (number->string min))
(else
(emit #f "~a to ~a" min max))))
(match rest
(('simple-format fmt opt)
(emit port
"~A: warning: ~S: unsupported format option ~~~A, use (ice-9 format) instead~%"
loc (escape-newlines fmt) opt))
(('wrong-format-arg-count fmt min max actual)
(emit port
"~A: warning: ~S: wrong number of `format' arguments: expected ~A, got ~A~%"
loc (escape-newlines fmt)
(range min max) actual))
(('syntax-error 'unterminated-iteration fmt)
(emit port "~A: warning: ~S: unterminated iteration~%"
loc (escape-newlines fmt)))
(('syntax-error 'unterminated-conditional fmt)
(emit port "~A: warning: ~S: unterminated conditional~%"
loc (escape-newlines fmt)))
(('syntax-error 'unexpected-semicolon fmt)
(emit port "~A: warning: ~S: unexpected `~~;'~%"
loc (escape-newlines fmt)))
(('syntax-error 'unexpected-conditional-termination fmt)
(emit port "~A: warning: ~S: unexpected `~~]'~%"
loc (escape-newlines fmt)))
(('wrong-port wrong-port)
(emit port
"~A: warning: ~S: wrong port argument~%"
loc wrong-port))
(('wrong-format-string fmt)
(emit port
"~A: warning: ~S: wrong format string~%"
loc fmt))
(('non-literal-format-string)
(emit port
"~A: warning: non-literal format string~%"
loc))
(('wrong-num-args count)
(emit port
"~A: warning: wrong number of arguments to `format'~%"
loc))
(else
(emit port "~A: `format' warning~%" loc)))))))))
(define (lookup-warning-type name)
"Return the warning type NAME or `#f' if not found."
(find (lambda (wt)
(eq? name (warning-type-name wt)))
%warning-types))
(define (warning type location . args)
"Emit a warning of type TYPE for source location LOCATION (a source
property alist) using the data in ARGS."
(let ((wt (lookup-warning-type type))
(port (current-warning-port)))
(if (warning-type? wt)
(apply (warning-type-printer wt)
port (location-string location)
args)
(format port "~A: unknown warning type `~A': ~A~%"
(location-string location) type args))))
|
2a12d4fc555c152052c5fa53eb76e7b0caca0f676f15064c6cff95854d9353c5
|
carotene/carotene
|
carotene_broker_sup.erl
|
-module(carotene_broker_sup).
-behaviour(supervisor).
%% API
-export([start_link/0, get_broker/0]).
%% Supervisor callbacks
-export([init/1]).
%% ===================================================================
%% API functions
%% ===================================================================
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
%% ===================================================================
%% Supervisor callbacks
%% ===================================================================
init([]) ->
case read_broker_config() of
undefined -> {ok, { {one_for_one, 5, 10}, []}};
BrokerModule -> {ok, { {one_for_one, 5, 10}, [
{broker,
{BrokerModule, start_link, [self()]},
permanent,
infinity,
worker,
[BrokerModule]
} ]} }
end.
read_broker_config() ->
case application:get_env(carotene, broker) of
undefined -> undefined;
{ok, rabbitmq} -> rabbitmq_broker;
{ok, redis} -> redis_broker
end.
get_broker() ->
case read_broker_config() of
undefined ->
undefined;
BrokerModule ->
Children = supervisor:which_children(?MODULE),
{broker, Broker, _, _} = lists:keyfind(broker, 1, Children),
{BrokerModule, Broker}
end.
| null |
https://raw.githubusercontent.com/carotene/carotene/963ecad344ec1c318c173ad828a5af3c000ddbfc/src/carotene_broker_sup.erl
|
erlang
|
API
Supervisor callbacks
===================================================================
API functions
===================================================================
===================================================================
Supervisor callbacks
===================================================================
|
-module(carotene_broker_sup).
-behaviour(supervisor).
-export([start_link/0, get_broker/0]).
-export([init/1]).
start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []).
init([]) ->
case read_broker_config() of
undefined -> {ok, { {one_for_one, 5, 10}, []}};
BrokerModule -> {ok, { {one_for_one, 5, 10}, [
{broker,
{BrokerModule, start_link, [self()]},
permanent,
infinity,
worker,
[BrokerModule]
} ]} }
end.
read_broker_config() ->
case application:get_env(carotene, broker) of
undefined -> undefined;
{ok, rabbitmq} -> rabbitmq_broker;
{ok, redis} -> redis_broker
end.
get_broker() ->
case read_broker_config() of
undefined ->
undefined;
BrokerModule ->
Children = supervisor:which_children(?MODULE),
{broker, Broker, _, _} = lists:keyfind(broker, 1, Children),
{BrokerModule, Broker}
end.
|
4f921b697a223e394aa4ffe521013d0d15b9dafeaf8b4ac7fb0da54db7357818
|
coord-e/mlml
|
bytes.ml
|
external of_string : string -> bytes = "_mlml_shallow_copy"
external to_string : bytes -> string = "_mlml_shallow_copy"
external copy : bytes -> bytes = "_mlml_shallow_copy"
external create : int -> bytes = "_mlml_create_string"
external length : bytes -> int = "_mlml_length_string"
external _get : bytes * int -> char = "_mlml_get_string"
external _set : bytes * int * char -> unit = "_mlml_set_string"
let get s n = _get (s, n)
let set s n c = _set (s, n, c)
let empty = create 0
let blit src srcoff dst dstoff len =
let rec aux i =
let srcidx = srcoff + i in
let dstidx = dstoff + i in
set dst dstidx @@ get src srcidx;
if i != 0 then aux (i - 1)
in
match len with 0 -> () | len -> aux (len - 1)
;;
let blit_string src srcoff dst dstoff len = blit src srcoff dst dstoff len |> to_string
let sub s start len =
let b = create len in
blit s start b 0 len;
b
;;
let sub_string s start len = sub s start len |> to_string
let init n f =
let b = create n in
let rec aux i =
set b i (f i);
if i != 0 then aux (i - 1)
in
(match n with 0 -> () | n -> aux (n - 1));
b
;;
let make n c = init n (fun _ -> c)
| null |
https://raw.githubusercontent.com/coord-e/mlml/ec34b1fe8766901fab6842b790267f32b77a2861/stdlib/bytes.ml
|
ocaml
|
external of_string : string -> bytes = "_mlml_shallow_copy"
external to_string : bytes -> string = "_mlml_shallow_copy"
external copy : bytes -> bytes = "_mlml_shallow_copy"
external create : int -> bytes = "_mlml_create_string"
external length : bytes -> int = "_mlml_length_string"
external _get : bytes * int -> char = "_mlml_get_string"
external _set : bytes * int * char -> unit = "_mlml_set_string"
let get s n = _get (s, n)
let set s n c = _set (s, n, c)
let empty = create 0
let blit src srcoff dst dstoff len =
let rec aux i =
let srcidx = srcoff + i in
let dstidx = dstoff + i in
set dst dstidx @@ get src srcidx;
if i != 0 then aux (i - 1)
in
match len with 0 -> () | len -> aux (len - 1)
;;
let blit_string src srcoff dst dstoff len = blit src srcoff dst dstoff len |> to_string
let sub s start len =
let b = create len in
blit s start b 0 len;
b
;;
let sub_string s start len = sub s start len |> to_string
let init n f =
let b = create n in
let rec aux i =
set b i (f i);
if i != 0 then aux (i - 1)
in
(match n with 0 -> () | n -> aux (n - 1));
b
;;
let make n c = init n (fun _ -> c)
|
|
2e8b6b3e62ee1b470e77a9c0112d96de8fb64751cd79badc8fc84feee0533b21
|
ndmitchell/catch
|
Main.hs
|
module Main where
import Yhc.Core
import System.FilePath hiding (normalise)
import System.Environment
import System.Directory
import System.IO
import Data.Proposition
import Control.Monad
import Prepare
import Propagate
import Req
import Backward
import Template
main = do
xs <- getArgs
mapM_ exec xs
findFile :: String -> IO FilePath
findFile file = do
bs <- mapM doesFileExist files
case [a | (a,b) <- zip files bs, b] of
(x:_) -> return x
_ -> error $ "File not found, " ++ file
where files = file : ["../examples" </> s </> "ycr" </> file <.> "letelim.yca" | s <- ["Example","Nofib"]]
exec fil = do
file <- findFile fil
core <- liftM prepare $ loadCore file
hCore <- beginLog file "core"
hPutStrLn hCore (show core)
hBack <- beginLog file "back"
hFore <- beginLog file "fore"
template <- templateInit core hFore
let conds = initialReqs core
res <- mapM (f hFore hBack core template) conds
let ress = valsAnds core res
when (null conds) $
putStrLn "No pattern match errors, trivially safe"
let msg = show ress
lmsg = length msg
putStrLn $ "Final: \\forall main, " ++ msg
when (lmsg > 200) $
putStrLn $ "Long: " ++ show lmsg
hClose hCore
hClose hBack
hClose hFore
where
f hFore hBack core template cond = do
let pref = "\n\n" ++ replicate 70 '-' ++ "\n"
msg1 = "Solving " ++ show cond
putStrLn msg1
hPutStrLn hFore (pref ++ msg1)
hPutStrLn hBack (pref ++ msg1)
res <- backward core template hBack [cond]
let msg2 = "Result \\forall main, " ++ show res
putStrLn msg2
hPutStrLn hBack $ "\n" ++ msg2
return res
initialReqs :: Core -> Scopes
initialReqs core = [Scope func (f reqs) | (func,reqs,expr) <- collect core isError, not $ propIsTrue reqs]
where
f = blur core . collapse core
isError (CoreApp (CorePrim "error") _) = True
isError _ = False
beginLog :: String -> String -> IO Handle
beginLog file temp = do
let dir = "../logs/" ++ dropExtensions (takeBaseName file)
createDirectoryIfMissing True dir
hndl <- openFile (dir </> temp <.> "log") WriteMode
hSetBuffering hndl NoBuffering
return hndl
| null |
https://raw.githubusercontent.com/ndmitchell/catch/5d834416a27b4df3f7ce7830c4757d4505aaf96e/inspect/Main.hs
|
haskell
|
module Main where
import Yhc.Core
import System.FilePath hiding (normalise)
import System.Environment
import System.Directory
import System.IO
import Data.Proposition
import Control.Monad
import Prepare
import Propagate
import Req
import Backward
import Template
main = do
xs <- getArgs
mapM_ exec xs
findFile :: String -> IO FilePath
findFile file = do
bs <- mapM doesFileExist files
case [a | (a,b) <- zip files bs, b] of
(x:_) -> return x
_ -> error $ "File not found, " ++ file
where files = file : ["../examples" </> s </> "ycr" </> file <.> "letelim.yca" | s <- ["Example","Nofib"]]
exec fil = do
file <- findFile fil
core <- liftM prepare $ loadCore file
hCore <- beginLog file "core"
hPutStrLn hCore (show core)
hBack <- beginLog file "back"
hFore <- beginLog file "fore"
template <- templateInit core hFore
let conds = initialReqs core
res <- mapM (f hFore hBack core template) conds
let ress = valsAnds core res
when (null conds) $
putStrLn "No pattern match errors, trivially safe"
let msg = show ress
lmsg = length msg
putStrLn $ "Final: \\forall main, " ++ msg
when (lmsg > 200) $
putStrLn $ "Long: " ++ show lmsg
hClose hCore
hClose hBack
hClose hFore
where
f hFore hBack core template cond = do
let pref = "\n\n" ++ replicate 70 '-' ++ "\n"
msg1 = "Solving " ++ show cond
putStrLn msg1
hPutStrLn hFore (pref ++ msg1)
hPutStrLn hBack (pref ++ msg1)
res <- backward core template hBack [cond]
let msg2 = "Result \\forall main, " ++ show res
putStrLn msg2
hPutStrLn hBack $ "\n" ++ msg2
return res
initialReqs :: Core -> Scopes
initialReqs core = [Scope func (f reqs) | (func,reqs,expr) <- collect core isError, not $ propIsTrue reqs]
where
f = blur core . collapse core
isError (CoreApp (CorePrim "error") _) = True
isError _ = False
beginLog :: String -> String -> IO Handle
beginLog file temp = do
let dir = "../logs/" ++ dropExtensions (takeBaseName file)
createDirectoryIfMissing True dir
hndl <- openFile (dir </> temp <.> "log") WriteMode
hSetBuffering hndl NoBuffering
return hndl
|
|
748d865631c272aadb041a0264f71452d8913db1172cd081f3990d4360bf8604
|
CoNarrative/precept
|
rules_debug.cljc
|
(ns precept.rules-debug
#?(:cljs (:require-macros [precept.dsl :refer [<- entity]]))
(:require [clara.rules.accumulators :as acc]
[clara.rules :as cr]
[precept.core :as core]
[precept.spec.sub :as sub]
[precept.spec.rulegen :as rulegen]
[precept.spec.error :as err]
[precept.listeners :as l]
[precept.schema :as schema]
[precept.state :as state]
[precept.schema-fixture :refer [test-schema]]
[clara.rules.compiler :as com]
[precept.repl :as repl]
[precept.util :refer [insert! insert-unconditional! retract! guid] :as util]
#?(:clj
[precept.dsl :refer [<- entity entities]])
#?(:clj
[precept.rules :refer [session rule define defsub] :as rules])
#?(:cljs [precept.rules :refer-macros [define defsub session rule]])))
(defn trace [& args]
(apply println args))
;(declare app-session)
;@state/rules
;(core/matching-consequences
' ( do ( precept.util/insert [ ? e : entry / new - title " Hello again ! " ] ) )
@state / rules ) )
;(reset! state/rules {})
( vals @state / rules )
(define [?e :entry/new-title (str "Hello " ?v)]
:- [[?e :entry/title ?v]])
(rule detect-new-title
[[_ :entry/new-title ?v]]
=>
(println "New title!" ?v))
;(rule check-conflicting-insert-logical
; [?fact <- [?e :entry/title]]
; =>
; (println "This should produce a conflict" (into [] (vals ?fact)))
( insert ! [ ? e : entry / new - title " Hello again ! " ] ) )
;
;(rule check-conflicting-insert-unconditional-on-top-of-insert-logical
; [?fact <- [?e :entry/title]]
; =>
; (println "This should produce a conflict too" (into [] (vals ?fact)))
( insert - unconditional ! [ ? e : entry / new - title " Hello again ! " ] ) )
;(rule all-facts
; {:group :report}
[ ? facts < - ( acc / all ) : from [: all ] ]
; =>
; (do nil))
( println " FACTs at the end ! " ? facts ) )
;(rule print-entity
; [[?e :todo/title]]
; [(<- ?entity (entity ?e))]
; =>
; (insert! {:db/id "hey" :some-entity ?entity})
; (trace "Entity!" ?entity))
(defsub :my-sub
[?name <- [_ :foo/name]]
=>
(let [my-var "x"]
(trace "Heyo" my-var)
{:foo/name ?name}))
;(define [(util/guid) :intresting-fact/eids ?eids]
: - [ ? eids < - ( acc / all : e ) : from [: interesting - fact ] ] )
( : my - sub-2
[ ? eids < - ( acc / all : e ) : from [: interesting - fact ] ] ; ; Maybe new special form ` ( eids [: interesting - fact ] ) `
; [[_ :interesting-fact/eids ?eids
;[(<- ?interesting-entities (entities ?eids))]
;=>
;(let [_ (println "Sub with entities -----" ?interesting-entities)]
; {:entities-sub ?interesting-entities}))
(rule log-errors
[[?e ::err/type]]
[(<- ?error (entity ?e))]
=>
(trace "Found error!" ?error)
(retract! ?error))
(defn foo? [x y] (not= x y))
(rule greater-than-42
[[_ :interesting-fact (foo? ?v 42)]]
=>
(trace "Greater than 42:" ?v))
(rule find-43
[[_ :interesting-fact 43]]
=>
(insert! [(guid) :the-number 43]))
(rule pred-w-bound-variable
[[_ :interesting-fact ?v2]]
[[_ :the-number (< ?v2 ?v1)]]
=>
(println "42s" ?v2))
(cr/defrule greater-than-42
[:interesting-fact (= ?v (:v this)) (foo? ?v 42)]
=>
(trace "Greater than 42:" ?v))
(rule dynamic-type-tuple
[[_ :some-type-name ?attr]]
[?x <- (acc/all :e) :from [_ ?attr]]
[[_ ?attr]]
=>
(trace "Attr" ?attr)
(trace "eids" ?x))
-rules/issues/313
;(cr/defrule variable-binding-in-accumulator
; [:the-keyword-e (= ?v (:v this))]
[ ? xs < - ( acc / all ? v ) : from [: interesting - fact ] ]
; =>
; (println "[variable-binding-in-acc] " ?xs))
;(rule variable-binding-in-accumulator
; [[_ :the-keyword-e ?v]]
[ ? xs < - ( acc / all ? v ) : from [ _ : interesting - fact ] ]
; =>
; (println "[variable-binding-in-acc] " ?xs))
(session app-session
'precept.rules-debug
:db-schema test-schema)
;(reset! precept.state/fact-index {})
;(reset! state/session-defs {})
@state/fact-index
@state/session-defs
;(reset! state/session-defs {})
@state/rules
@state/rule-files
@state/unconditional-inserts
(ns-interns *ns*)
(def end-session
(-> app-session
(l/replace-listener)
(util/insert [[1 :entry/title "First"]
[1 :entry/title "Second"]
[2 :todo/title "First"]
[5 :some-type-name :todo/title]
[6 :the-keyword-e :e]
[3 ::sub/request :my-sub]
[:transient :test "foo"]
[1 :interesting-fact 42]
[2 :interesting-fact 42]
[3 :interesting-fact 42]
[4 :interesting-fact 42]
[4 :interesting-fact 43]
[2 :todo/title "Second"]
[3 :todo/title "Second"]
[5 ::sub/request :my-sub-2]])
(cr/fire-rules)))
;(l/vec-ops))
;(l/vec-ops app-session)
| null |
https://raw.githubusercontent.com/CoNarrative/precept/6078286cae641b924a2bffca4ecba19dcc304dde/test/cljc/precept/rules_debug.cljc
|
clojure
|
(declare app-session)
@state/rules
(core/matching-consequences
(reset! state/rules {})
(rule check-conflicting-insert-logical
[?fact <- [?e :entry/title]]
=>
(println "This should produce a conflict" (into [] (vals ?fact)))
(rule check-conflicting-insert-unconditional-on-top-of-insert-logical
[?fact <- [?e :entry/title]]
=>
(println "This should produce a conflict too" (into [] (vals ?fact)))
(rule all-facts
{:group :report}
=>
(do nil))
(rule print-entity
[[?e :todo/title]]
[(<- ?entity (entity ?e))]
=>
(insert! {:db/id "hey" :some-entity ?entity})
(trace "Entity!" ?entity))
(define [(util/guid) :intresting-fact/eids ?eids]
; Maybe new special form ` ( eids [: interesting - fact ] ) `
[[_ :interesting-fact/eids ?eids
[(<- ?interesting-entities (entities ?eids))]
=>
(let [_ (println "Sub with entities -----" ?interesting-entities)]
{:entities-sub ?interesting-entities}))
(cr/defrule variable-binding-in-accumulator
[:the-keyword-e (= ?v (:v this))]
=>
(println "[variable-binding-in-acc] " ?xs))
(rule variable-binding-in-accumulator
[[_ :the-keyword-e ?v]]
=>
(println "[variable-binding-in-acc] " ?xs))
(reset! precept.state/fact-index {})
(reset! state/session-defs {})
(reset! state/session-defs {})
(l/vec-ops))
(l/vec-ops app-session)
|
(ns precept.rules-debug
#?(:cljs (:require-macros [precept.dsl :refer [<- entity]]))
(:require [clara.rules.accumulators :as acc]
[clara.rules :as cr]
[precept.core :as core]
[precept.spec.sub :as sub]
[precept.spec.rulegen :as rulegen]
[precept.spec.error :as err]
[precept.listeners :as l]
[precept.schema :as schema]
[precept.state :as state]
[precept.schema-fixture :refer [test-schema]]
[clara.rules.compiler :as com]
[precept.repl :as repl]
[precept.util :refer [insert! insert-unconditional! retract! guid] :as util]
#?(:clj
[precept.dsl :refer [<- entity entities]])
#?(:clj
[precept.rules :refer [session rule define defsub] :as rules])
#?(:cljs [precept.rules :refer-macros [define defsub session rule]])))
(defn trace [& args]
(apply println args))
' ( do ( precept.util/insert [ ? e : entry / new - title " Hello again ! " ] ) )
@state / rules ) )
( vals @state / rules )
(define [?e :entry/new-title (str "Hello " ?v)]
:- [[?e :entry/title ?v]])
(rule detect-new-title
[[_ :entry/new-title ?v]]
=>
(println "New title!" ?v))
( insert ! [ ? e : entry / new - title " Hello again ! " ] ) )
( insert - unconditional ! [ ? e : entry / new - title " Hello again ! " ] ) )
[ ? facts < - ( acc / all ) : from [: all ] ]
( println " FACTs at the end ! " ? facts ) )
(defsub :my-sub
[?name <- [_ :foo/name]]
=>
(let [my-var "x"]
(trace "Heyo" my-var)
{:foo/name ?name}))
: - [ ? eids < - ( acc / all : e ) : from [: interesting - fact ] ] )
( : my - sub-2
(rule log-errors
[[?e ::err/type]]
[(<- ?error (entity ?e))]
=>
(trace "Found error!" ?error)
(retract! ?error))
(defn foo? [x y] (not= x y))
(rule greater-than-42
[[_ :interesting-fact (foo? ?v 42)]]
=>
(trace "Greater than 42:" ?v))
(rule find-43
[[_ :interesting-fact 43]]
=>
(insert! [(guid) :the-number 43]))
(rule pred-w-bound-variable
[[_ :interesting-fact ?v2]]
[[_ :the-number (< ?v2 ?v1)]]
=>
(println "42s" ?v2))
(cr/defrule greater-than-42
[:interesting-fact (= ?v (:v this)) (foo? ?v 42)]
=>
(trace "Greater than 42:" ?v))
(rule dynamic-type-tuple
[[_ :some-type-name ?attr]]
[?x <- (acc/all :e) :from [_ ?attr]]
[[_ ?attr]]
=>
(trace "Attr" ?attr)
(trace "eids" ?x))
-rules/issues/313
[ ? xs < - ( acc / all ? v ) : from [: interesting - fact ] ]
[ ? xs < - ( acc / all ? v ) : from [ _ : interesting - fact ] ]
(session app-session
'precept.rules-debug
:db-schema test-schema)
@state/fact-index
@state/session-defs
@state/rules
@state/rule-files
@state/unconditional-inserts
(ns-interns *ns*)
(def end-session
(-> app-session
(l/replace-listener)
(util/insert [[1 :entry/title "First"]
[1 :entry/title "Second"]
[2 :todo/title "First"]
[5 :some-type-name :todo/title]
[6 :the-keyword-e :e]
[3 ::sub/request :my-sub]
[:transient :test "foo"]
[1 :interesting-fact 42]
[2 :interesting-fact 42]
[3 :interesting-fact 42]
[4 :interesting-fact 42]
[4 :interesting-fact 43]
[2 :todo/title "Second"]
[3 :todo/title "Second"]
[5 ::sub/request :my-sub-2]])
(cr/fire-rules)))
|
d831b0f08b18c01b6ef2f9cbc3140ff362134ac1a912fc88e13df72fd0748f24
|
tmfg/mmtis-national-access-point
|
service_type.cljs
|
(ns ote.views.transport-service.service-type
"Select type for transport service"
(:require [cljs-react-material-ui.reagent :as ui]
[cljs-react-material-ui.icons :as ic]
[reagent.core :as r]
[ote.db.transport-service :as t-service]
[ote.db.transport-operator :as t-operator]
[ote.localization :refer [tr tr-key]]
[stylefy.core :as stylefy]
[ote.theme.colors :as colors]
[ote.style.base :as style-base]
[ote.style.form :as style-form]
[ote.style.dialog :as style-dialog]
[ote.ui.buttons :as buttons]
[ote.ui.circular_progress :as circular-progress]
[ote.ui.info :as info]
[ote.ui.form-fields :as form-fields]
[ote.ui.common :as ui-common]
[ote.app.controller.transport-service :as ts-controller]
[ote.app.controller.transport-operator :as to]
[ote.views.transport-service.passenger-transportation :as pt]
[ote.views.transport-service.terminal :as terminal]
[ote.views.transport-service.parking :as parking]
[ote.views.transport-service.rental :as rental]))
(def modified-transport-service-types
;; Create order for service type selection dropdown
[:taxi
:request
:schedule
:terminal
:rentals
:parking])
(defn select-service-type [e! {:keys [transport-operator transport-service] :as state}]
(let [disabled? (or (nil? (::t-service/sub-type transport-service))
(nil? (::t-operator/id transport-operator)))]
[:div.row
[:div {:class "col-sx-12 col-md-12"}
[:div
[:h1 (tr [:select-service-type-page :title-required-data])]]
[:div.row
[info/info-toggle
(tr [:common-texts :instructions])
[:span
[:p (tr [:select-service-type-page :transport-service-type-selection-help-text])]
[:p (tr [:select-service-type-page :transport-service-type-brokerage-help-text])]
[:p {:style {:font-style "italic"}}
(tr [:select-service-type-page :transport-service-type-selection-help-example])]]
{:default-open? false}]]
[:div.row
[:div
[:div {:class "col-sx-12 col-sm-4 col-md-4"}
[form-fields/field
{:label (tr [:field-labels :transport-service-type-subtype])
:name ::t-service/sub-type
:type :selection
:update! #(e! (ts-controller/->SelectServiceType %))
:show-option (tr-key [:enums ::t-service/sub-type])
:options modified-transport-service-types
:auto-width? true}
(::t-service/sub-type transport-service)]]
[:div {:class "col-sx-12 col-sm-4 col-md-4"}
[form-fields/field
{:label (tr [:field-labels :select-transport-operator])
:name :select-transport-operator
:type :selection
:update! #(e! (to/->SelectOperator %))
:show-option ::t-operator/name
:options (mapv :transport-operator (:transport-operators-with-services state))
:auto-width? true}
transport-operator]]]]
[:div.row
[:div {:class "col-sx-12 col-sm-4 col-md-4"}
[ui/raised-button {:id "own-service-next-btn"
:style {:margin-top "20px"}
:label (tr [:buttons :next])
:on-click #(e! (ts-controller/->NavigateToNewService))
:primary true
:disabled disabled?}]]]]]))
| null |
https://raw.githubusercontent.com/tmfg/mmtis-national-access-point/a86cc890ffa1fe4f773083be5d2556e87a93d975/ote/src/cljs/ote/views/transport_service/service_type.cljs
|
clojure
|
Create order for service type selection dropdown
|
(ns ote.views.transport-service.service-type
"Select type for transport service"
(:require [cljs-react-material-ui.reagent :as ui]
[cljs-react-material-ui.icons :as ic]
[reagent.core :as r]
[ote.db.transport-service :as t-service]
[ote.db.transport-operator :as t-operator]
[ote.localization :refer [tr tr-key]]
[stylefy.core :as stylefy]
[ote.theme.colors :as colors]
[ote.style.base :as style-base]
[ote.style.form :as style-form]
[ote.style.dialog :as style-dialog]
[ote.ui.buttons :as buttons]
[ote.ui.circular_progress :as circular-progress]
[ote.ui.info :as info]
[ote.ui.form-fields :as form-fields]
[ote.ui.common :as ui-common]
[ote.app.controller.transport-service :as ts-controller]
[ote.app.controller.transport-operator :as to]
[ote.views.transport-service.passenger-transportation :as pt]
[ote.views.transport-service.terminal :as terminal]
[ote.views.transport-service.parking :as parking]
[ote.views.transport-service.rental :as rental]))
(def modified-transport-service-types
[:taxi
:request
:schedule
:terminal
:rentals
:parking])
(defn select-service-type [e! {:keys [transport-operator transport-service] :as state}]
(let [disabled? (or (nil? (::t-service/sub-type transport-service))
(nil? (::t-operator/id transport-operator)))]
[:div.row
[:div {:class "col-sx-12 col-md-12"}
[:div
[:h1 (tr [:select-service-type-page :title-required-data])]]
[:div.row
[info/info-toggle
(tr [:common-texts :instructions])
[:span
[:p (tr [:select-service-type-page :transport-service-type-selection-help-text])]
[:p (tr [:select-service-type-page :transport-service-type-brokerage-help-text])]
[:p {:style {:font-style "italic"}}
(tr [:select-service-type-page :transport-service-type-selection-help-example])]]
{:default-open? false}]]
[:div.row
[:div
[:div {:class "col-sx-12 col-sm-4 col-md-4"}
[form-fields/field
{:label (tr [:field-labels :transport-service-type-subtype])
:name ::t-service/sub-type
:type :selection
:update! #(e! (ts-controller/->SelectServiceType %))
:show-option (tr-key [:enums ::t-service/sub-type])
:options modified-transport-service-types
:auto-width? true}
(::t-service/sub-type transport-service)]]
[:div {:class "col-sx-12 col-sm-4 col-md-4"}
[form-fields/field
{:label (tr [:field-labels :select-transport-operator])
:name :select-transport-operator
:type :selection
:update! #(e! (to/->SelectOperator %))
:show-option ::t-operator/name
:options (mapv :transport-operator (:transport-operators-with-services state))
:auto-width? true}
transport-operator]]]]
[:div.row
[:div {:class "col-sx-12 col-sm-4 col-md-4"}
[ui/raised-button {:id "own-service-next-btn"
:style {:margin-top "20px"}
:label (tr [:buttons :next])
:on-click #(e! (ts-controller/->NavigateToNewService))
:primary true
:disabled disabled?}]]]]]))
|
830b660c339ad6cd0c18b64e2d0e096dce6c5b48b9f32bc65bc60c1c0d724563
|
lijunsong/pollen-rock
|
watch-handler.rkt
|
#lang racket
(require json)
(require web-server/http/request-structs)
(require "../http-util.rkt")
(require "../logger.rkt")
(require "fs-watch.rkt")
(provide watch-handler do-watch)
;;;; POST /watch/$path
(define/contract (watch-answer errno mtime)
(-> integer? integer? jsexpr?)
;; make mutable hash because fs evt needs to mutate the hash table
;; in callback function.
(make-hash `((errno . ,errno)
(mtime . ,mtime))))
;; Http long polling issue may have impact.
see
(define/contract (watch-handler req url-parts watching)
(-> request? (listof string?)
(-> path? (or/c false? integer?) jsexpr?) jsexpr?)
(define source-path (apply build-path url-parts))
(define bindings (request-bindings/raw req))
we may or may not get from request
(define mtime (get-binding-value #"mtime" bindings))
(log-rest-info "watching file ~a" source-path)
(with-handlers
([exn:fail:filesystem? (lambda (e) (watch-answer 1 0))])
(define int-mtime
(if mtime
(string->number (bytes->string/utf-8 mtime))
#f))
(watching source-path int-mtime)))
(define/contract (do-watch file-path last-seen-seconds)
(-> path? (or/c false? integer?) jsexpr?)
(define ans (watch-answer 0 0))
;; when the file is changed, update and return this ans.
(define (update-mtime _ last-mod)
(hash-set! ans 'mtime last-mod))
(when (file-watch file-path update-mtime last-seen-seconds)
ans))
(module+ test
(require rackunit)
;; test watch-handler
(define watch-request-url-parts
(list "watch" "this" "file.txt"))
(define watch-request
(make-test-request "watch" watch-request-url-parts
(hash #"mtime" #"100")))
(define watch-request-no-mtime
(make-test-request "watch" watch-request-url-parts
(hash)))
test watch - handler returns when the watching file does n't exist
(check-equal?
(watch-answer 1 0)
(watch-handler watch-request (list "watch" "this" "file.txt")
(lambda (path mtime)
(raise (make-exn:fail:filesystem
"exists"
(current-continuation-marks))))))
test watch - handler passes correct path and to watching function
(check-equal?
(watch-answer 0 1001)
(watch-handler watch-request (list "watch" "this" "file.txt")
(lambda (path mtime)
(check-equal? path (string->path "watch/this/file.txt"))
(check-equal? mtime 100)
(watch-answer 0 1001))))
test watch - handler passes false as
(check-equal?
(watch-answer 0 1002)
(watch-handler watch-request-no-mtime
(list "watch" "this" "file.txt")
(lambda (path mtime)
(check-false mtime)
(watch-answer 0 1002))))
)
| null |
https://raw.githubusercontent.com/lijunsong/pollen-rock/8107c7c1a1ca1e5ab125650f38002683b15b22c9/pollen-rock/handlers/watch-handler.rkt
|
racket
|
POST /watch/$path
make mutable hash because fs evt needs to mutate the hash table
in callback function.
Http long polling issue may have impact.
when the file is changed, update and return this ans.
test watch-handler
|
#lang racket
(require json)
(require web-server/http/request-structs)
(require "../http-util.rkt")
(require "../logger.rkt")
(require "fs-watch.rkt")
(provide watch-handler do-watch)
(define/contract (watch-answer errno mtime)
(-> integer? integer? jsexpr?)
(make-hash `((errno . ,errno)
(mtime . ,mtime))))
see
(define/contract (watch-handler req url-parts watching)
(-> request? (listof string?)
(-> path? (or/c false? integer?) jsexpr?) jsexpr?)
(define source-path (apply build-path url-parts))
(define bindings (request-bindings/raw req))
we may or may not get from request
(define mtime (get-binding-value #"mtime" bindings))
(log-rest-info "watching file ~a" source-path)
(with-handlers
([exn:fail:filesystem? (lambda (e) (watch-answer 1 0))])
(define int-mtime
(if mtime
(string->number (bytes->string/utf-8 mtime))
#f))
(watching source-path int-mtime)))
(define/contract (do-watch file-path last-seen-seconds)
(-> path? (or/c false? integer?) jsexpr?)
(define ans (watch-answer 0 0))
(define (update-mtime _ last-mod)
(hash-set! ans 'mtime last-mod))
(when (file-watch file-path update-mtime last-seen-seconds)
ans))
(module+ test
(require rackunit)
(define watch-request-url-parts
(list "watch" "this" "file.txt"))
(define watch-request
(make-test-request "watch" watch-request-url-parts
(hash #"mtime" #"100")))
(define watch-request-no-mtime
(make-test-request "watch" watch-request-url-parts
(hash)))
test watch - handler returns when the watching file does n't exist
(check-equal?
(watch-answer 1 0)
(watch-handler watch-request (list "watch" "this" "file.txt")
(lambda (path mtime)
(raise (make-exn:fail:filesystem
"exists"
(current-continuation-marks))))))
test watch - handler passes correct path and to watching function
(check-equal?
(watch-answer 0 1001)
(watch-handler watch-request (list "watch" "this" "file.txt")
(lambda (path mtime)
(check-equal? path (string->path "watch/this/file.txt"))
(check-equal? mtime 100)
(watch-answer 0 1001))))
test watch - handler passes false as
(check-equal?
(watch-answer 0 1002)
(watch-handler watch-request-no-mtime
(list "watch" "this" "file.txt")
(lambda (path mtime)
(check-false mtime)
(watch-answer 0 1002))))
)
|
9e9c656cc133db31fee5c496526bd95f0b3930fa32c8650279c115c7c2320c51
|
erlang/otp
|
shell.erl
|
%%
%% %CopyrightBegin%
%%
Copyright Ericsson AB 1996 - 2023 . 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(shell).
-export([start/0, start/1, start/2, server/1, server/2, history/1, results/1]).
-export([get_state/0, get_function/2]).
-export([start_restricted/1, stop_restricted/0]).
-export([local_func/0, local_func/1, local_allowed/3, non_local_allowed/3]).
-export([catch_exception/1, prompt_func/1, strings/1]).
-export([start_interactive/0, start_interactive/1]).
-export([read_and_add_records/5]).
-export([whereis/0]).
-define(LINEMAX, 30).
-define(CHAR_MAX, 60).
-define(DEF_HISTORY, 20).
-define(DEF_RESULTS, 20).
-define(DEF_CATCH_EXCEPTION, false).
-define(DEF_PROMPT_FUNC, default).
-define(DEF_STRINGS, true).
-define(RECORDS, shell_records).
-define(MAXSIZE_HEAPBINARY, 64).
-record(shell_state,{
bindings = [],
records = [],
functions = []
}).
%% When used as the fallback restricted shell callback module...
local_allowed(q,[],State) ->
{true,State};
local_allowed(_,_,State) ->
{false,State}.
non_local_allowed({init,stop},[],State) ->
{true,State};
non_local_allowed(_,_,State) ->
{false,State}.
-spec start_interactive() -> ok | {error, already_started}.
start_interactive() ->
user_drv:start_shell().
-spec start_interactive(noshell | mfa()) ->
ok | {error, already_started};
({remote, string()}) ->
ok | {error, already_started | noconnection};
({node(), mfa()} | {remote, string(), mfa()}) ->
ok | {error, already_started | noconnection | badfile | nofile | on_load_failure}.
start_interactive({Node, {M, F, A}}) ->
user_drv:start_shell(#{ initial_shell => {Node, M, F ,A} });
start_interactive(InitialShell) ->
user_drv:start_shell(#{ initial_shell => InitialShell }).
-spec whereis() -> pid() | undefined.
whereis() ->
group:whereis_shell().
-spec start() -> pid().
start() ->
start(false, false).
start(init) ->
start(false, true);
start(NoCtrlG) ->
start(NoCtrlG, false).
start(NoCtrlG, StartSync) ->
_ = code:ensure_loaded(user_default),
Ancestors = [self() | case get('$ancestors') of
undefined -> [];
Anc -> Anc
end],
spawn(fun() ->
put('$ancestors', Ancestors),
server(NoCtrlG, StartSync)
end).
%% Call this function to start a user restricted shell
%% from a normal shell session.
-spec start_restricted(Module) -> {'error', Reason} when
Module :: module(),
Reason :: code:load_error_rsn().
start_restricted(RShMod) when is_atom(RShMod) ->
case code:ensure_loaded(RShMod) of
{module,RShMod} ->
application:set_env(stdlib, restricted_shell, RShMod),
exit(restricted_shell_started);
{error,What} = Error ->
error_logger:error_report(
lists:flatten(
io_lib:fwrite(
"Restricted shell module ~w not found: ~tp\n",
[RShMod,What]))),
Error
end.
-spec stop_restricted() -> no_return().
stop_restricted() ->
application:unset_env(stdlib, restricted_shell),
exit(restricted_shell_stopped).
-spec server(boolean(), boolean()) -> 'terminated'.
server(NoCtrlG, StartSync) ->
put(no_control_g, NoCtrlG),
server(StartSync).
%%% The shell should not start until the system is up and running.
%%% We subscribe with init to get a notification of when.
%%% In older releases we didn't syncronize the shell with init, but let it
%%% start in parallell with other system processes. This was bad since
%%% accessing the shell too early could interfere with the boot procedure.
%%% Still, by means of a flag, we make it possible to start the shell the
%%% old way (for backwards compatibility reasons). This should however not
%%% be used unless for very special reasons necessary.
-spec server(boolean()) -> 'terminated'.
server(StartSync) ->
case init:get_argument(async_shell_start) of
{ok,_} ->
ok; % no sync with init
_ when not StartSync ->
ok;
_ ->
case init:notify_when_started(self()) of
started ->
ok;
_ ->
init:wait_until_started()
end
end,
%% Our spawner has fixed the process groups.
Bs = erl_eval:new_bindings(),
%% Use an Ets table for record definitions. It takes too long to
%% send a huge term to and from the evaluator. Ets makes it
possible to have thousands of record definitions .
RT = ets:new(?RECORDS, [public,ordered_set]),
_ = initiate_records(Bs, RT),
process_flag(trap_exit, true),
%% Store function definitions and types in an ets table.
FT = ets:new(user_functions, [public,ordered_set]),
%% Check if we're in user restricted mode.
RShErr =
case application:get_env(stdlib, restricted_shell) of
{ok,RShMod} when is_atom(RShMod) ->
io:fwrite(<<"Restricted ">>, []),
case code:ensure_loaded(RShMod) of
{module,RShMod} ->
undefined;
{error,What} ->
{RShMod,What}
end;
{ok, Term} ->
{Term,not_an_atom};
undefined ->
undefined
end,
JCL =
case get(no_control_g) of
true -> " (type help(). for help)";
_ -> " (press Ctrl+G to abort, type help(). for help)"
end,
DefaultSessionSlogan =
io_lib:format(<<"Eshell V~s">>, [erlang:system_info(version)]),
SessionSlogan =
case application:get_env(stdlib, shell_session_slogan, DefaultSessionSlogan) of
SloganFun when is_function(SloganFun, 0) ->
SloganFun();
Slogan ->
Slogan
end,
try
io:fwrite("~ts~ts\n",[unicode:characters_to_list(SessionSlogan),JCL])
catch _:_ ->
io:fwrite("Warning! The slogan \"~p\" could not be printed.\n",[SessionSlogan])
end,
erase(no_control_g),
case RShErr of
undefined ->
ok;
{RShMod2,What2} ->
io:fwrite(
("Warning! Restricted shell module ~w not found: ~tp.\n"
"Only the commands q() and init:stop() will be allowed!\n"),
[RShMod2,What2]),
application:set_env(stdlib, restricted_shell, ?MODULE)
end,
{History,Results} = check_and_get_history_and_results(),
server_loop(0, start_eval(Bs, RT, FT, []), Bs, RT, FT, [], History, Results).
server_loop(N0, Eval_0, Bs00, RT, FT, Ds00, History0, Results0) ->
N = N0 + 1,
{Eval_1,Bs0,Ds0,Prompt} = prompt(N, Eval_0, Bs00, RT, FT, Ds00),
{Res,Eval0} = get_command(Prompt, Eval_1, Bs0, RT, FT, Ds0),
case Res of
{ok,Es0} ->
case expand_hist(Es0, N) of
{ok,Es} ->
{V,Eval,Bs,Ds} = shell_cmd(Es, Eval0, Bs0, RT, FT, Ds0, cmd),
{History,Results} = check_and_get_history_and_results(),
add_cmd(N, Es, V),
HB1 = del_cmd(command, N - History, N - History0, false),
HB = del_cmd(result, N - Results, N - Results0, HB1),
%% The following test makes sure that large binaries
%% (outside of the heap) are garbage collected as soon
%% as possible.
if
HB ->
garb(self());
true ->
ok
end,
server_loop(N, Eval, Bs, RT, FT, Ds, History, Results);
{error,E} ->
fwrite_severity(benign, <<"~ts">>, [E]),
server_loop(N0, Eval0, Bs0, RT, FT, Ds0, History0, Results0)
end;
{error,{Location,Mod,What}} ->
fwrite_severity(benign, <<"~s: ~ts">>,
[pos(Location), Mod:format_error(What)]),
server_loop(N0, Eval0, Bs0, RT, FT, Ds0, History0, Results0);
Io process terminated
exit(Eval0, kill),
terminated;
Io process interrupted us
exit(Eval0, kill),
{_,Eval,_,_} = shell_rep(Eval0, Bs0, RT, FT, Ds0),
server_loop(N0, Eval, Bs0, RT, FT, Ds0, History0, Results0);
Most probably character > 255
fwrite_severity(benign, <<"~w: Invalid tokens.">>,
[N]),
server_loop(N0, Eval0, Bs0, RT, FT, Ds0, History0, Results0);
eof ->
fwrite_severity(fatal, <<"Terminating erlang (~w)">>, [node()]),
halt()
end.
get_command(Prompt, Eval, Bs, RT, FT, Ds) ->
Ancestors = [self() | get('$ancestors')],
ResWordFun = fun erl_scan:reserved_word/1,
Parse =
fun() ->
put('$ancestors', Ancestors),
exit(
case
io:scan_erl_exprs(group_leader(), Prompt, {1,1},
[text,{reserved_word_fun,ResWordFun}])
of
{ok,Toks,_EndPos} ->
%% NOTE: we can handle function definitions, records and soon type declarations
%% but this cannot be handled by the function which only expects erl_parse:abstract_expressions()
%% for now just pattern match against those types and pass the string to shell local func.
case Toks of
[{'-', _}, {atom, _, Atom}|_] ->
SpecialCase = fun(LocalFunc) ->
FakeLine = begin
case erl_parse:parse_form(Toks) of
{ok, Def} -> lists:flatten(erl_pp:form(Def));
E ->
exit(E)
end
end,
{done, {ok, FakeResult, _}, _} = erl_scan:tokens(
[], atom_to_list(LocalFunc) ++ "(\""++FakeLine++"\").\n",
{1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]),
erl_eval:extended_parse_exprs(FakeResult)
end,
case Atom of
record -> SpecialCase(rd);
spec -> SpecialCase(ft);
type -> SpecialCase(td)
end;
[{atom, _, FunName}, {'(', _}|_] ->
case erl_parse:parse_form(Toks) of
{ok, FunDef} ->
case {edlin_expand:shell_default_or_bif(atom_to_list(FunName)), shell:local_func(FunName)} of
{"user_defined", false} ->
FakeLine =reconstruct(FunDef, FunName),
{done, {ok, FakeResult, _}, _} = erl_scan:tokens(
[], "fd("++ atom_to_list(FunName) ++ ", " ++ FakeLine ++ ").\n",
{1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]),
erl_eval:extended_parse_exprs(FakeResult);
_ -> erl_eval:extended_parse_exprs(Toks)
end;
_ -> erl_eval:extended_parse_exprs(Toks)
end;
_ ->
erl_eval:extended_parse_exprs(Toks)
end;
{eof,_EndPos} ->
eof;
{error,ErrorInfo,_EndPos} ->
%% Skip the rest of the line:
Opts = io:getopts(),
TmpOpts = lists:keyreplace(echo, 1, Opts,
{echo, false}),
_ = io:setopts(TmpOpts),
_ = io:get_line(''),
_ = io:setopts(Opts),
{error,ErrorInfo};
Else ->
Else
end
)
end,
Pid = spawn_link(Parse),
get_command1(Pid, Eval, Bs, RT, FT, Ds).
reconstruct(Fun, Name) ->
lists:flatten(erl_pp:expr(reconstruct1(Fun, Name))).
reconstruct1({function, Anno, Name, Arity, Clauses}, Name) ->
{named_fun, Anno, 'RecursiveFuncVar', reconstruct1(Clauses, Name, Arity)}.
reconstruct1([{call, Anno, {atom, Anno1, Name}, Args}|Body], Name, Arity) when length(Args) =:= Arity ->
[{call, Anno, {var, Anno1, 'RecursiveFuncVar'}, reconstruct1(Args, Name, Arity)}| reconstruct1(Body, Name, Arity)];
reconstruct1([{call, Anno, {atom, Anno1, Name}, Args}|Body], Name, Arity) -> % arity not the same
[{call, Anno, {remote, Anno1, {atom, Anno1, shell_default}, {atom, Anno1, Name}}, reconstruct1(Args, Name, Arity)}|
reconstruct1(Body, Name, Arity)];
reconstruct1([{call, Anno, {atom, Anno1, Fun}, Args}|Body], Name, Arity) -> % Name not the same
case {edlin_expand:shell_default_or_bif(atom_to_list(Fun)), shell:local_func(Fun)} of
{"user_defined", false} ->
[{call, Anno, {remote, Anno1, {atom, Anno1, shell_default}, {atom, Anno1, Fun}}, reconstruct1(Args, Name, Arity)}|
reconstruct1(Body, Name, Arity)];
{"shell_default", false} ->
[{call, Anno, {remote, Anno1, {atom, Anno1, shell_default}, {atom, Anno1, Fun}}, reconstruct1(Args, Name, Arity)}| reconstruct1(Body, Name, Arity)];
{"erlang", false} ->
[{call, Anno, {remote, Anno1, {atom, Anno1, erlang}, {atom, Anno1, Fun}}, reconstruct1(Args, Name, Arity)}| reconstruct1(Body, Name, Arity)];
{_, true} ->
[{call, Anno, {atom, Anno1, Fun}, reconstruct1(Args, Name, Arity)}| reconstruct1(Body, Name, Arity)]
end;
reconstruct1([E|Body], Name, Arity) when is_tuple(E) ->
[list_to_tuple(reconstruct1(tuple_to_list(E), Name, Arity))|reconstruct1(Body, Name, Arity)];
reconstruct1([E|Body], Name, Arity) when is_list(E) ->
[reconstruct1(E, Name, Arity)|reconstruct1(Body, Name, Arity)];
reconstruct1([E|Body], Name, Arity) ->
[E|reconstruct1(Body, Name, Arity)];
reconstruct1([], _, _) -> [].
get_command1(Pid, Eval, Bs, RT, FT, Ds) ->
receive
{shell_state, From} ->
From ! {shell_state, Bs, RT, FT},
get_command1(Pid, Eval, Bs, RT, FT, Ds);
{'EXIT', Pid, Res} ->
{Res, Eval};
{'EXIT', Eval, {Reason,Stacktrace}} ->
report_exception(error, {Reason,Stacktrace}, RT),
get_command1(Pid, start_eval(Bs, RT, FT, Ds), Bs, RT, FT, Ds);
{'EXIT', Eval, Reason} ->
report_exception(error, {Reason,[]}, RT),
get_command1(Pid, start_eval(Bs, RT, FT, Ds), Bs, RT, FT, Ds)
end.
prompt(N, Eval0, Bs0, RT, FT, Ds0) ->
case get_prompt_func() of
{M,F} ->
A = erl_anno:new(1),
L = {cons,A,{tuple,A,[{atom,A,history},{integer,A,N}]},{nil,A}},
C = {call,A,{remote,A,{atom,A,M},{atom,A,F}},[L]},
{V,Eval,Bs,Ds} = shell_cmd([C], Eval0, Bs0, RT, FT, Ds0, pmt),
{Eval,Bs,Ds,case V of
{pmt,Val} ->
Val;
_ ->
bad_prompt_func({M,F}),
default_prompt(N)
end};
default ->
{Eval0,Bs0,Ds0,default_prompt(N)}
end.
get_prompt_func() ->
case application:get_env(stdlib, shell_prompt_func, default) of
{M,F}=PromptFunc when is_atom(M), is_atom(F) ->
PromptFunc;
default=Default ->
Default;
Term ->
bad_prompt_func(Term),
default
end.
bad_prompt_func(M) ->
fwrite_severity(benign, "Bad prompt function: ~tp", [M]).
default_prompt(N) ->
%% Don't bother flattening the list irrespective of what the
%% I/O-protocol states.
case is_alive() of
true -> io_lib:format(<<"(~s)~w> ">>, [node(), N]);
false -> io_lib:format(<<"~w> ">>, [N])
end.
expand_hist(Expressions , )
Preprocess the expression list replacing all history list commands
%% with their expansions.
expand_hist(Es, C) ->
catch {ok,expand_exprs(Es, C)}.
expand_exprs([E|Es], C) ->
[expand_expr(E, C)|expand_exprs(Es, C)];
expand_exprs([], _C) ->
[].
expand_expr({cons,A,H,T}, C) ->
{cons,A,expand_expr(H, C),expand_expr(T, C)};
expand_expr({lc,A,E,Qs}, C) ->
{lc,A,expand_expr(E, C),expand_quals(Qs, C)};
expand_expr({bc,A,E,Qs}, C) ->
{bc,A,expand_expr(E, C),expand_quals(Qs, C)};
expand_expr({tuple,A,Elts}, C) ->
{tuple,A,expand_exprs(Elts, C)};
expand_expr({map,A,Es}, C) ->
{map,A,expand_exprs(Es, C)};
expand_expr({map,A,Arg,Es}, C) ->
{map,A,expand_expr(Arg, C),expand_exprs(Es, C)};
expand_expr({map_field_assoc,A,K,V}, C) ->
{map_field_assoc,A,expand_expr(K, C),expand_expr(V, C)};
expand_expr({map_field_exact,A,K,V}, C) ->
{map_field_exact,A,expand_expr(K, C),expand_expr(V, C)};
expand_expr({record_index,A,Name,F}, C) ->
{record_index,A,Name,expand_expr(F, C)};
expand_expr({record,A,Name,Is}, C) ->
{record,A,Name,expand_fields(Is, C)};
expand_expr({record_field,A,R,Name,F}, C) ->
{record_field,A,expand_expr(R, C),Name,expand_expr(F, C)};
expand_expr({record,A,R,Name,Ups}, C) ->
{record,A,expand_expr(R, C),Name,expand_fields(Ups, C)};
expand_expr({record_field,A,R,F}, C) -> %This is really illegal!
{record_field,A,expand_expr(R, C),expand_expr(F, C)};
expand_expr({block,A,Es}, C) ->
{block,A,expand_exprs(Es, C)};
expand_expr({'if',A,Cs}, C) ->
{'if',A,expand_cs(Cs, C)};
expand_expr({'case',A,E,Cs}, C) ->
{'case',A,expand_expr(E, C),expand_cs(Cs, C)};
expand_expr({'try',A,Es,Scs,Ccs,As}, C) ->
{'try',A,expand_exprs(Es, C),expand_cs(Scs, C),
expand_cs(Ccs, C),expand_exprs(As, C)};
expand_expr({'receive',A,Cs}, C) ->
{'receive',A,expand_cs(Cs, C)};
expand_expr({'receive',A,Cs,To,ToEs}, C) ->
{'receive',A,expand_cs(Cs, C), expand_expr(To, C), expand_exprs(ToEs, C)};
expand_expr({call,A,{atom,_,e},[N]}, C) ->
case get_cmd(N, C) of
{undefined,_,_} ->
no_command(N);
{[Ce],_V,_CommandN} ->
Ce;
{Ces,_V,_CommandN} when is_list(Ces) ->
{block,A,Ces}
end;
expand_expr({call,CA,{atom,VA,v},[N]}, C) ->
case get_cmd(N, C) of
{_,undefined,_} ->
no_command(N);
{Ces,_V,CommandN} when is_list(Ces) ->
{call,CA,{atom,VA,v},[{integer,VA,CommandN}]}
end;
expand_expr({call,A,F,Args}, C) ->
{call,A,expand_expr(F, C),expand_exprs(Args, C)};
expand_expr({'catch',A,E}, C) ->
{'catch',A,expand_expr(E, C)};
expand_expr({match,A,Lhs,Rhs}, C) ->
{match,A,Lhs,expand_expr(Rhs, C)};
expand_expr({op,A,Op,Arg}, C) ->
{op,A,Op,expand_expr(Arg, C)};
expand_expr({op,A,Op,Larg,Rarg}, C) ->
{op,A,Op,expand_expr(Larg, C),expand_expr(Rarg, C)};
expand_expr({remote,A,M,F}, C) ->
{remote,A,expand_expr(M, C),expand_expr(F, C)};
expand_expr({'fun',A,{clauses,Cs}}, C) ->
{'fun',A,{clauses,expand_exprs(Cs, C)}};
expand_expr({named_fun,A,Name,Cs}, C) ->
{named_fun,A,Name,expand_exprs(Cs, C)};
expand_expr({clause,A,H,G,B}, C) ->
%% Could expand H and G, but then erl_eval has to be changed as well.
{clause,A,H, G, expand_exprs(B, C)};
expand_expr({bin,A,Fs}, C) ->
{bin,A,expand_bin_elements(Fs, C)};
expand_expr({'- ' } )
expand_expr(E, _C) -> % Constants.
E.
expand_cs([{clause,A,P,G,B}|Cs], C) ->
[{clause,A,P,G,expand_exprs(B, C)}|expand_cs(Cs, C)];
expand_cs([], _C) ->
[].
expand_fields([{record_field,A,F,V}|Fs], C) ->
[{record_field,A,expand_expr(F, C),expand_expr(V, C)}|
expand_fields(Fs, C)];
expand_fields([], _C) -> [].
expand_quals([{generate,A,P,E}|Qs], C) ->
[{generate,A,P,expand_expr(E, C)}|expand_quals(Qs, C)];
expand_quals([{b_generate,A,P,E}|Qs], C) ->
[{b_generate,A,P,expand_expr(E, C)}|expand_quals(Qs, C)];
expand_quals([E|Qs], C) ->
[expand_expr(E, C)|expand_quals(Qs, C)];
expand_quals([], _C) -> [].
expand_bin_elements([], _C) ->
[];
expand_bin_elements([{bin_element,A,E,Sz,Ts}|Fs], C) ->
[{bin_element,A,expand_expr(E, C),Sz,Ts}|expand_bin_elements(Fs, C)].
no_command(N) ->
throw({error,
io_lib:fwrite(<<"~ts: command not found">>,
[erl_pp:expr(N, enc())])}).
%% add_cmd(Number, Expressions, Value)
%% get_cmd(Number, CurrentCommand)
%% del_cmd(Number, NewN, OldN, HasBin0) -> bool()
add_cmd(N, Es, V) ->
put({command,N}, Es),
put({result,N}, V).
getc(N) ->
{get({command,N}), get({result,N}), N}.
get_cmd(Num, C) ->
case catch erl_eval:expr(Num, erl_eval:new_bindings()) of
{value,N,_} when N < 0 -> getc(C+N);
{value,N,_} -> getc(N);
_Other -> {undefined,undefined,undefined}
end.
del_cmd(_Type, N, N0, HasBin) when N < N0 ->
HasBin;
del_cmd(Type, N, N0, HasBin0) ->
T = erase({Type,N}),
HasBin = HasBin0 orelse has_binary(T),
del_cmd(Type, N-1, N0, HasBin).
has_binary(T) ->
try has_bin(T), false
catch true=Thrown -> Thrown
end.
has_bin(T) when is_tuple(T) ->
has_bin(T, tuple_size(T));
has_bin([E | Es]) ->
has_bin(E),
has_bin(Es);
has_bin(B) when byte_size(B) > ?MAXSIZE_HEAPBINARY ->
throw(true);
has_bin(T) ->
T.
has_bin(T, 0) ->
T;
has_bin(T, I) ->
has_bin(element(I, T)),
has_bin(T, I - 1).
get_state() ->
whereis() ! {shell_state, self()},
receive
{shell_state, Bs, RT, FT} ->
#shell_state{bindings = Bs, records = ets:tab2list(RT), functions = ets:tab2list(FT)}
end.
get_function(Func, Arity) ->
{shell_state, _Bs, _RT, FT} = get_state(),
try
{value, {_, Fun}} = lists:keysearch({function, {shell_default,Func,Arity}}, 1, FT),
Fun
catch _:_ ->
undefined
end.
shell_cmd(Sequence , Evaluator , , , Dictionary , What )
shell_rep(Evaluator , , , Dictionary ) - >
%% {Value,Evaluator,Bindings,Dictionary}
%% Send a command to the evaluator and wait for the reply. Start a new
%% evaluator if necessary.
%% What = pmt | cmd. When evaluating a prompt ('pmt') the evaluated value
%% must not be displayed, and it has to be returned.
shell_cmd(Es, Eval, Bs, RT, FT, Ds, W) ->
Eval ! {shell_cmd,self(),{eval,Es}, W},
shell_rep(Eval, Bs, RT, FT, Ds).
shell_rep(Ev, Bs0, RT, FT, Ds0) ->
receive
{shell_rep,Ev,{value,V,Bs,Ds}} ->
{V,Ev,Bs,Ds};
{shell_rep,Ev,{command_error,{Location,M,Error}}} ->
fwrite_severity(benign, <<"~s: ~ts">>,
[pos(Location), M:format_error(Error)]),
{{'EXIT',Error},Ev,Bs0,Ds0};
{shell_req,Ev,{get_cmd,N}} ->
Ev ! {shell_rep,self(),getc(N)},
shell_rep(Ev, Bs0, RT, FT, Ds0);
{shell_req,Ev,get_cmd} ->
Ev ! {shell_rep,self(),get()},
shell_rep(Ev, Bs0, RT, FT, Ds0);
{shell_req,Ev,exit} ->
Ev ! {shell_rep,self(),exit},
exit(normal);
{shell_req,Ev,{update_dict,Ds}} -> % Update dictionary
Ev ! {shell_rep,self(),ok},
shell_rep(Ev, Bs0, RT, FT, Ds);
{shell_state, From} ->
From ! {shell_state, Bs0, RT, FT},
shell_rep(Ev, Bs0, RT, FT, Ds0);
{ev_exit,{Ev,Class,Reason0}} -> % It has exited unnaturally
receive {'EXIT',Ev,normal} -> ok end,
report_exception(Class, Reason0, RT),
Reason = nocatch(Class, Reason0),
{{'EXIT',Reason},start_eval(Bs0, RT, FT, Ds0), Bs0, Ds0};
{ev_caught,{Ev,Class,Reason0}} -> % catch_exception is in effect
report_exception(Class, benign, Reason0, RT),
Reason = nocatch(Class, Reason0),
{{'EXIT',Reason},Ev,Bs0,Ds0};
{'EXIT',_Id,interrupt} -> % Someone interrupted us
exit(Ev, kill),
shell_rep(Ev, Bs0, RT, FT, Ds0);
{'EXIT',Ev,{Reason,Stacktrace}} ->
report_exception(exit, {Reason,Stacktrace}, RT),
{{'EXIT',Reason},start_eval(Bs0, RT, FT, Ds0), Bs0, Ds0};
{'EXIT',Ev,Reason} ->
report_exception(exit, {Reason,[]}, RT),
{{'EXIT',Reason},start_eval(Bs0, RT, FT, Ds0), Bs0, Ds0};
{'EXIT',_Id,R} ->
exit(Ev, R),
exit(R);
_Other -> % Ignore everything else
io:format("Throwing ~p~n", [_Other]),
shell_rep(Ev, Bs0, RT, FT, Ds0)
end.
nocatch(throw, {Term,Stack}) ->
{{nocatch,Term},Stack};
nocatch(error, Reason) ->
Reason;
nocatch(exit, Reason) ->
Reason.
report_exception(Class, Reason, RT) ->
report_exception(Class, serious, Reason, RT).
report_exception(Class, Severity, {Reason,Stacktrace}, RT) ->
Tag = severity_tag(Severity),
I = iolist_size(Tag) + 1,
PF = fun(Term, I1) -> pp(Term, I1, RT) end,
SF = fun(M, _F, _A) -> (M =:= erl_eval) or (M =:= ?MODULE) end,
Enc = encoding(),
Str = erl_error:format_exception(I, Class, Reason, Stacktrace, SF, PF, Enc),
io:requests([{put_chars, latin1, Tag},
{put_chars, unicode, Str},
nl]).
start_eval(Bs, RT, FT, Ds) ->
Self = self(),
Ancestors = [self() | get('$ancestors')],
Eval = spawn_link(fun() ->
put('$ancestors', Ancestors),
evaluator(Self, Bs, RT, FT, Ds)
end),
put(evaluator, Eval),
Eval.
evaluator(Shell , Bindings , , ProcessDictionary )
%% Evaluate expressions from the shell. Use the "old" variable bindings
%% and dictionary.
evaluator(Shell, Bs, RT, FT, Ds) ->
init_dict(Ds),
case application:get_env(stdlib, restricted_shell) of
undefined ->
eval_loop(Shell, Bs, RT, FT);
{ok,RShMod} ->
case get(restricted_shell_state) of
undefined -> put(restricted_shell_state, []);
_ -> ok
end,
put(restricted_expr_state, []),
restricted_eval_loop(Shell, Bs, RT, FT, RShMod)
end.
eval_loop(Shell, Bs0, RT, FT) ->
receive
{shell_cmd,Shell,{eval,Es},W} ->
Ef = {value,
fun(MForFun, As) -> apply_fun(MForFun, As, Shell) end},
Lf = local_func_handler(Shell, RT, FT, Ef),
Bs = eval_exprs(Es, Shell, Bs0, RT, Lf, Ef, W),
eval_loop(Shell, Bs, RT, FT)
end.
restricted_eval_loop(Shell, Bs0, RT, FT, RShMod) ->
receive
{shell_cmd,Shell,{eval,Es}, W} ->
{LFH,NLFH} = restrict_handlers(RShMod, Shell, RT, FT),
put(restricted_expr_state, []),
Bs = eval_exprs(Es, Shell, Bs0, RT, {eval,LFH}, {value,NLFH}, W),
restricted_eval_loop(Shell, Bs, RT, FT, RShMod)
end.
eval_exprs(Es, Shell, Bs0, RT, Lf, Ef, W) ->
try
{R,Bs2} = exprs(Es, Bs0, RT, Lf, Ef, W),
Shell ! {shell_rep,self(),R},
Bs2
catch
exit:normal ->
exit(normal);
Class:Reason:Stacktrace ->
M = {self(),Class,{Reason,Stacktrace}},
case do_catch(Class, Reason) of
true ->
Shell ! {ev_caught,M},
Bs0;
false ->
%% We don't want the ERROR REPORT generated by the
%% emulator. Note: exit(kill) needs nothing special.
{links,LPs} = process_info(self(), links),
ER = nocatch(Class, {Reason,Stacktrace}),
lists:foreach(fun(P) -> exit(P, ER) end, LPs--[Shell]),
Shell ! {ev_exit,M},
exit(normal)
end
end.
do_catch(exit, restricted_shell_stopped) ->
false;
do_catch(exit, restricted_shell_started) ->
false;
do_catch(_Class, _Reason) ->
case application:get_env(stdlib, shell_catch_exception, false) of
true ->
true;
_ ->
false
end.
exprs(Es, Bs0, RT, Lf, Ef, W) ->
exprs(Es, Bs0, RT, Lf, Ef, Bs0, W).
exprs([E0|Es], Bs1, RT, Lf, Ef, Bs0, W) ->
UsedRecords = used_record_defs(E0, RT),
RBs = record_bindings(UsedRecords, Bs1),
case check_command(prep_check([E0]), RBs) of
ok ->
E1 = expand_records(UsedRecords, E0),
{value,V0,Bs2} = expr(E1, Bs1, Lf, Ef),
Bs = orddict:from_list([VV || {X,_}=VV <- erl_eval:bindings(Bs2),
not is_expand_variable(X)]),
if
Es =:= [] ->
VS = pp(V0, 1, RT),
case W of
cmd -> io:requests([{put_chars, unicode, VS}, nl]);
pmt -> ok
end,
%% Don't send the result back if it will be
%% discarded anyway.
V = if
W =:= pmt ->
{W,V0};
true -> case result_will_be_saved() of
true -> V0;
false ->
erlang:garbage_collect(),
ignored
end
end,
{{value,V,Bs,get()},Bs};
true ->
exprs(Es, Bs, RT, Lf, Ef, Bs0, W)
end;
{error,Error} ->
{{command_error,Error},Bs0}
end.
is_expand_variable(V) ->
case catch atom_to_list(V) of
"rec" ++ _Integer -> true;
_ -> false
end.
result_will_be_saved() ->
case get_history_and_results() of
{_, 0} -> false;
_ -> true
end.
used_record_defs(E, RT) ->
%% Be careful to return a list where used records come before
%% records that use them. The linter wants them ordered that way.
UR = case used_records(E, [], RT, []) of
[] ->
[];
L0 ->
L1 = lists:zip(L0, lists:seq(1, length(L0))),
L2 = lists:keysort(2, lists:ukeysort(1, L1)),
[R || {R, _} <- L2]
end,
record_defs(RT, UR).
used_records(E, U0, RT, Skip) ->
case used_records(E) of
{name,Name,E1} ->
U = case lists:member(Name, Skip) of
true ->
U0;
false ->
R = ets:lookup(RT, Name),
used_records(R, [Name | U0], RT, [Name | Skip])
end,
used_records(E1, U, RT, Skip);
{expr,[E1 | Es]} ->
used_records(Es, used_records(E1, U0, RT, Skip), RT, Skip);
_ ->
U0
end.
used_records({record_index,_,Name,F}) ->
{name, Name, F};
used_records({record,_,Name,Is}) ->
{name, Name, Is};
used_records({record_field,_,R,Name,F}) ->
{name, Name, [R | F]};
used_records({record,_,R,Name,Ups}) ->
{name, Name, [R | Ups]};
used_records({record_field,_,R,F}) -> % illegal
{expr, [R | F]};
used_records({call,_,{atom,_,record},[A,{atom,_,Name}]}) ->
{name, Name, A};
used_records({call,_,{atom,_,is_record},[A,{atom,_,Name}]}) ->
{name, Name, A};
used_records({call,_,{remote,_,{atom,_,erlang},{atom,_,is_record}},
[A,{atom,_,Name}]}) ->
{name, Name, A};
used_records({call,_,{atom,_,record_info},[A,{atom,_,Name}]}) ->
{name, Name, A};
used_records({call,A,{tuple,_,[M,F]},As}) ->
used_records({call,A,{remote,A,M,F},As});
used_records({type,_,record,[{atom,_,Name}|Fs]}) ->
{name, Name, Fs};
used_records(T) when is_tuple(T) ->
{expr, tuple_to_list(T)};
used_records(E) ->
{expr, E}.
fwrite_severity(Severity, S, As) ->
io:fwrite(<<"~ts\n">>, [format_severity(Severity, S, As)]).
format_severity(Severity, S, As) ->
add_severity(Severity, io_lib:fwrite(S, As)).
add_severity(Severity, S) ->
[severity_tag(Severity), S].
severity_tag(fatal) -> <<"*** ">>;
severity_tag(serious) -> <<"** ">>;
severity_tag(benign) -> <<"* ">>.
restrict_handlers(RShMod, Shell, RT, FT) ->
{ fun(F,As,Binds) ->
local_allowed(F, As, RShMod, Binds, Shell, RT, FT)
end,
fun(MF,As) ->
non_local_allowed(MF, As, RShMod, Shell)
end }.
-define(BAD_RETURN(M, F, V),
try erlang:error(reason)
catch _:_:S -> erlang:raise(exit, {restricted_shell_bad_return,V},
[{M,F,3} | S])
end).
local_allowed(F, As, RShMod, Bs, Shell, RT, FT) when is_atom(F) ->
{LFH,NLFH} = restrict_handlers(RShMod, Shell, RT, FT),
case not_restricted(F, As) of % Not restricted is the same as builtin.
% variable and record manipulations local
% to the shell process. Those are never
% restricted.
true ->
local_func(F, As, Bs, Shell, RT, FT, {eval,LFH}, {value,NLFH});
false ->
{AsEv,Bs1} = expr_list(As, Bs, {eval,LFH}, {value,NLFH}),
case RShMod:local_allowed(F, AsEv, {get(restricted_shell_state),
get(restricted_expr_state)}) of
{Result,{RShShSt,RShExprSt}} ->
put(restricted_shell_state, RShShSt),
put(restricted_expr_state, RShExprSt),
if not Result ->
shell_req(Shell, {update_dict,get()}),
exit({restricted_shell_disallowed,{F,AsEv}});
true -> % This is never a builtin,
% those are handled above.
non_builtin_local_func(F,AsEv,Bs1, FT)
end;
Unexpected -> % The user supplied non conforming module
?BAD_RETURN(RShMod, local_allowed, Unexpected)
end
end.
non_local_allowed(MForFun, As, RShMod, Shell) ->
case RShMod:non_local_allowed(MForFun, As, {get(restricted_shell_state),
get(restricted_expr_state)}) of
{Result,{RShShSt,RShExprSt}} ->
put(restricted_shell_state, RShShSt),
put(restricted_expr_state, RShExprSt),
case Result of
false ->
shell_req(Shell, {update_dict,get()}),
exit({restricted_shell_disallowed,{MForFun,As}});
{redirect, NewMForFun, NewAs} ->
apply_fun(NewMForFun, NewAs, Shell);
_ ->
apply_fun(MForFun, As, Shell)
end;
Unexpected -> % The user supplied non conforming module
?BAD_RETURN(RShMod, non_local_allowed, Unexpected)
end.
%% The commands implemented in shell should not be checked if allowed
%% This *has* to correspond to the function local_func/7!
%% (especially true for f/1, the argument must not be evaluated).
not_restricted(f, []) ->
true;
not_restricted(f, [_]) ->
true;
not_restricted(h, []) ->
true;
not_restricted(b, []) ->
true;
not_restricted(history, [_]) ->
true;
not_restricted(results, [_]) ->
true;
not_restricted(catch_exception, [_]) ->
true;
not_restricted(exit, []) ->
true;
not_restricted(fl, []) ->
true;
not_restricted(fd, [_]) ->
true;
not_restricted(ft, [_]) ->
true;
not_restricted(td, [_]) ->
true;
not_restricted(rd, [_]) ->
true;
not_restricted(rd, [_,_]) ->
true;
not_restricted(rf, []) ->
true;
not_restricted(rf, [_]) ->
true;
not_restricted(rl, []) ->
true;
not_restricted(rl, [_]) ->
true;
not_restricted(rp, [_]) ->
true;
not_restricted(rr, [_]) ->
true;
not_restricted(rr, [_,_]) ->
true;
not_restricted(rr, [_,_,_]) ->
true;
not_restricted(_, _) ->
false.
When : ( ) is called from the shell ,
%% the shell process process that spawned the evaluating
%% process is garbage collected as well.
%% To garbage collect the evaluating process only the command
%% garbage_collect(self()). can be used.
apply_fun({erlang,garbage_collect}, [], Shell) ->
garb(Shell);
apply_fun({M,F}, As, _Shell) ->
apply(M, F, As);
apply_fun(MForFun, As, _Shell) ->
apply(MForFun, As).
prep_check({call,Anno,{atom,_,f},[{var,_,_Name}]}) ->
%% Do not emit a warning for f(V) when V is unbound.
{atom,Anno,ok};
prep_check({value,_CommandN,_Val}) ->
%% erl_lint cannot handle the history expansion {value,_,_}.
{atom,a0(),ok};
prep_check(T) when is_tuple(T) ->
list_to_tuple(prep_check(tuple_to_list(T)));
prep_check([E | Es]) ->
[prep_check(E) | prep_check(Es)];
prep_check(E) ->
E.
expand_records([], E0) ->
E0;
expand_records(UsedRecords, E0) ->
RecordDefs = [Def || {_Name,Def} <- UsedRecords],
A = erl_anno:new(1),
E = prep_rec(E0),
Forms0 = RecordDefs ++ [{function,A,foo,0,[{clause,A,[],[],[E]}]}],
Forms = erl_expand_records:module(Forms0, [strict_record_tests]),
{function,A,foo,0,[{clause,A,[],[],[NE]}]} = lists:last(Forms),
prep_rec(NE).
prep_rec({value,_CommandN,_V}=Value) ->
%% erl_expand_records cannot handle the history expansion {value,_,_}.
{atom,Value,ok};
prep_rec({atom,{value,_CommandN,_V}=Value,ok}) ->
%% Undo the effect of the previous clause...
Value;
prep_rec(T) when is_tuple(T) -> list_to_tuple(prep_rec(tuple_to_list(T)));
prep_rec([E | Es]) -> [prep_rec(E) | prep_rec(Es)];
prep_rec(E) -> E.
init_dict([{K,V}|Ds]) ->
put(K, V),
init_dict(Ds);
init_dict([]) -> true.
local_func(Function , , Bindings , Shell , ,
LocalFuncHandler , ExternalFuncHandler ) - > { value , , Bs }
%% Evaluate local functions, including shell commands.
%%
Note that the predicate not_restricted/2 has to correspond to what 's
%% handled internally - it should return 'true' for all local functions
%% handled in this module (i.e. those that are not eventually handled by
non_builtin_local_func/3 ( user_default / shell_default ) .
local_func() -> [v,h,b,f,fl,rd,rf,rl,rp,rr,history,results,catch_exception].
local_func(Func) ->
lists:member(Func, local_func()).
local_func(v, [{integer,_,V}], Bs, Shell, _RT, _FT, _Lf, _Ef) ->
%% This command is validated and expanded prior.
{_Ces,Value,_N} = shell_req(Shell, {get_cmd, V}),
{value,Value,Bs};
local_func(h, [], Bs, Shell, RT, _FT, _Lf, _Ef) ->
Cs = shell_req(Shell, get_cmd),
Cs1 = lists:filter(fun({{command, _},_}) -> true;
({{result, _},_}) -> true;
(_) -> false
end,
Cs),
Cs2 = lists:map(fun({{T, N}, V}) -> {{N, T}, V} end,
Cs1),
Cs3 = lists:keysort(1, Cs2),
{value,list_commands(Cs3, RT),Bs};
local_func(b, [], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
{value,list_bindings(erl_eval:bindings(Bs), RT),Bs};
local_func(f, [], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
{value,ok,erl_eval:new_bindings()};
local_func(f, [{var,_,Name}], Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
{value,ok,erl_eval:del_binding(Name, Bs)};
local_func(f, [_Other], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,f,1}]);
local_func(fl, [], Bs, _Shell, _RT, FT, _Lf, _Ef) ->
{value, ets:tab2list(FT), Bs};
local_func(fd, [{atom,_,FunName}, FunExpr], Bs, _Shell, _RT, FT, _Lf, _Ef) ->
{value, Fun, []} = erl_eval:expr(FunExpr, []),
{arity, Arity} = erlang:fun_info(Fun, arity),
ets:insert(FT, [{{function, {shell_default, FunName, Arity}}, Fun}]),
{value, ok, Bs};
local_func(fd, [_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell, fd, 1}]);
local_func(ft, [{string, _, TypeDef}], Bs, _Shell, _RT, FT, _Lf, _Ef) ->
case erl_scan:tokens([], TypeDef, {1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]) of
{done, {ok, Toks, _}, _} ->
case erl_parse:parse_form(Toks) of
{ok, {attribute,_,spec,{{FunName, Arity},_}}=AttrForm} ->
ets:insert(FT, [{{function_type, {shell_default, FunName, Arity}}, AttrForm}]),
{value, ok, Bs};
{error,{_Location,M,ErrDesc}} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
{done, {error,{_Location, M, ErrDesc}, _}, _} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
local_func(ft, [_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell, ft, 1}]);
local_func(td, [{string, _, TypeDef}], Bs, _Shell, _RT, FT, _Lf, _Ef) ->
case erl_scan:tokens([], TypeDef, {1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]) of
{done, {ok, Toks, _}, _} ->
case erl_parse:parse_form(Toks) of
{ok, {attribute,_,type,{TypeName, _, _}}=AttrForm} ->
ets:insert(FT, [{{type, TypeName}, AttrForm}]),
{value, ok, Bs};
{error,{_Location,M,ErrDesc}} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
{done, {error,{_Location, M, ErrDesc}, _}, _} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
local_func(td, [_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell, td, 1}]);
local_func(rd, [{string, _, TypeDef}], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
case erl_scan:tokens([], TypeDef, {1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]) of
{done, {ok, Toks, _}, _} ->
case erl_parse:parse_form(Toks) of
{ok,{attribute,_,_,_}=AttrForm} ->
[_] = add_records([AttrForm], Bs, RT),
{value,ok,Bs};
{error,{_Location,M,ErrDesc}} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
{done, {error,{_Location, M, ErrDesc}, _}, _} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
local_func(rd, [_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell, rd, 1}]);
local_func(rd, [{atom,_,RecName0},RecDef0], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
RecDef = expand_value(RecDef0),
RDs = lists:flatten(erl_pp:expr(RecDef)),
RecName = io_lib:write_atom_as_latin1(RecName0),
Attr = lists:concat(["-record(", RecName, ",", RDs, ")."]),
{ok, Tokens, _} = erl_scan:string(Attr),
case erl_parse:parse_form(Tokens) of
{ok,AttrForm} ->
[RN] = add_records([AttrForm], Bs, RT),
{value,RN,Bs};
{error,{_Location,M,ErrDesc}} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
local_func(rd, [_,_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,rd,2}]);
local_func(rf, [], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
true = ets:delete_all_objects(RT),
{value,initiate_records(Bs, RT),Bs};
local_func(rf, [A], Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[Recs],Bs} = expr_list([A], Bs0, Lf, Ef),
if '_' =:= Recs ->
true = ets:delete_all_objects(RT);
true ->
lists:foreach(fun(Name) -> true = ets:delete(RT, Name)
end, listify(Recs))
end,
{value,ok,Bs};
local_func(rl, [], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
{value,list_records(ets:tab2list(RT)),Bs};
local_func(rl, [A], Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[Recs],Bs} = expr_list([A], Bs0, Lf, Ef),
{value,list_records(record_defs(RT, listify(Recs))),Bs};
local_func(rp, [A], Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[V],Bs} = expr_list([A], Bs0, Lf, Ef),
Cs = pp(V, _Column=1, _Depth=-1, RT),
io:requests([{put_chars, unicode, Cs}, nl]),
{value,ok,Bs};
local_func(rr, [A], Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[File],Bs} = expr_list([A], Bs0, Lf, Ef),
{value,read_and_add_records(File, '_', [], Bs, RT),Bs};
local_func(rr, [_,_]=As0, Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[File,Sel],Bs} = expr_list(As0, Bs0, Lf, Ef),
{value,read_and_add_records(File, Sel, [], Bs, RT),Bs};
local_func(rr, [_,_,_]=As0, Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[File,Sel,Options],Bs} = expr_list(As0, Bs0, Lf, Ef),
{value,read_and_add_records(File, Sel, Options, Bs, RT),Bs};
local_func(history, [{integer,_,N}], Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
{value,history(N),Bs};
local_func(history, [_Other], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,history,1}]);
local_func(results, [{integer,_,N}], Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
{value,results(N),Bs};
local_func(results, [_Other], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,results,1}]);
local_func(catch_exception, [{atom,_,Bool}], Bs, _Shell, _RT, _FT, _Lf, _Ef)
when Bool; not Bool ->
{value,catch_exception(Bool),Bs};
local_func(catch_exception, [_Other], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,catch_exception,1}]);
local_func(exit, [], _Bs, Shell, _RT, _FT, _Lf, _Ef) ->
shell_req(Shell, exit), %This terminates us
exit(normal);
local_func(F, As0, Bs0, _Shell, _RT, FT, Lf, Ef) when is_atom(F) ->
{As,Bs} = expr_list(As0, Bs0, Lf, Ef),
non_builtin_local_func(F,As,Bs, FT).
non_builtin_local_func(F,As,Bs, FT) ->
Arity = length(As),
case erlang:function_exported(user_default, F, Arity) of
true ->
{eval,erlang:make_fun(user_default, F, Arity),As,Bs};
false ->
shell_default(F,As,Bs, FT)
end.
shell_default(F,As,Bs, FT) ->
M = shell_default,
A = length(As),
case code:ensure_loaded(M) of
{module, _} ->
case erlang:function_exported(M,F,A) of
true ->
{eval,erlang:make_fun(M, F, A),As,Bs};
false ->
shell_default_local_func(F,As, Bs, FT)
end;
{error, _} ->
shell_default_local_func(F,As, Bs, FT)
end.
shell_default_local_func(F, As, Bs, FT) ->
case ets:lookup(FT, {function, {shell_default, F, length(As)}}) of
[] -> shell_undef(F, length(As));
[{_, Fun}] -> {eval, Fun, As, Bs}
end.
shell_undef(F,A) ->
erlang:error({shell_undef,F,A,[]}).
local_func_handler(Shell, RT, FT, Ef) ->
H = fun(Lf) ->
fun(F, As, Bs) ->
local_func(F, As, Bs, Shell, RT, FT, {eval,Lf(Lf)}, Ef)
end
end,
{eval,H(H)}.
record_print_fun(RT) ->
fun(Tag, NoFields) ->
case ets:lookup(RT, Tag) of
[{_,{attribute,_,record,{Tag,Fields}}}]
when length(Fields) =:= NoFields ->
record_fields(Fields);
_ ->
no
end
end.
record_fields([{record_field,_,{atom,_,Field}} | Fs]) ->
[Field | record_fields(Fs)];
record_fields([{record_field,_,{atom,_,Field},_} | Fs]) ->
[Field | record_fields(Fs)];
record_fields([{typed_record_field,Field,_Type} | Fs]) ->
record_fields([Field | Fs]);
record_fields([]) ->
[].
initiate_records(Bs, RT) ->
RNs1 = init_rec(shell_default, Bs, RT),
RNs2 = case code:is_loaded(user_default) of
{file,_File} ->
init_rec(user_default, Bs, RT);
false ->
[]
end,
lists:usort(RNs1 ++ RNs2).
init_rec(Module, Bs, RT) ->
case read_records(Module, []) of
RAs when is_list(RAs) ->
case catch add_records(RAs, Bs, RT) of
{'EXIT',_} ->
[];
RNs ->
RNs
end;
_Error ->
[]
end.
read_and_add_records(File, Selected, Options, Bs, RT) ->
case read_records(File, Selected, Options) of
RAs when is_list(RAs) ->
add_records(RAs, Bs, RT);
Error ->
Error
end.
read_records(File, Selected, Options) ->
case read_records(File, listify(Options)) of
Error when is_tuple(Error) ->
Error;
RAs when Selected =:= '_' ->
RAs;
RAs ->
Sel = listify(Selected),
[RA || {attribute,_,_,{Name,_}}=RA <- RAs,
lists:member(Name, Sel)]
end.
add_records(RAs, Bs0, RT) ->
TODO store File name to support type completion
Recs = [{Name,D} || {attribute,_,_,{Name,_}}=D <- RAs],
Bs1 = record_bindings(Recs, Bs0),
case check_command([], Bs1) of
{error,{_Location,M,ErrDesc}} ->
%% A source file that has not been compiled.
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr));
ok ->
true = ets:insert(RT, Recs),
lists:usort([Name || {Name,_} <- Recs])
end.
listify(L) when is_list(L) ->
L;
listify(E) ->
[E].
check_command(Es, Bs) ->
erl_eval:check_command(Es, Bs).
expr(E, Bs, Lf, Ef) ->
erl_eval:expr(E, Bs, Lf, Ef).
expr_list(Es, Bs, Lf, Ef) ->
erl_eval:expr_list(Es, Bs, Lf, Ef).
%% Note that a sequence number is used here to make sure that if a
record is used by another record , then the first record is parsed
before the second record . ( erl_eval : check_command ( ) calls the
%% linter which needs the records in a proper order.)
record_bindings([], Bs) ->
Bs;
record_bindings(Recs0, Bs0) ->
{Recs1, _} = lists:mapfoldl(fun ({Name,Def}, I) -> {{Name,I,Def},I+1}
end, 0, Recs0),
Recs2 = lists:keysort(2, lists:ukeysort(1, Recs1)),
lists:foldl(fun ({Name,I,Def}, Bs) ->
erl_eval:add_binding({record,I,Name}, Def, Bs)
end, Bs0, Recs2).
%%% Read record information from file(s)
read_records(FileOrModule, Opts0) ->
Opts = lists:delete(report_warnings, Opts0),
case find_file(FileOrModule) of
{beam, Beam, File} ->
read_records_from_beam(Beam, File);
{files,[File]} ->
read_file_records(File, Opts);
{files,Files} ->
lists:flatmap(fun(File) ->
case read_file_records(File, Opts) of
RAs when is_list(RAs) -> RAs;
_ -> []
end
end, Files);
Error ->
Error
end.
-include_lib("kernel/include/file.hrl").
find_file(Mod) when is_atom(Mod) ->
case code:which(Mod) of
File when is_list(File) ->
%% Special cases:
%% - Modules not in the code path (loaded with code:load_abs/1):
%% code:get_object_code/1 only searches in the code path
but code : finds all loaded modules
%% - File can also be a file in an archive,
%% beam_lib:chunks/2 cannot handle such paths but
%% erl_prim_loader:get_file/1 can
case erl_prim_loader:get_file(File) of
{ok, Beam, _} ->
{beam, Beam, File};
error ->
{error, nofile}
end;
preloaded ->
{_M, Beam, File} = code:get_object_code(Mod),
{beam, Beam, File};
_Else -> % non_existing, interpreted, cover_compiled
{error,nofile}
end;
find_file(File) ->
case catch filelib:wildcard(File) of
{'EXIT',_} ->
{error,invalid_filename};
Files ->
{files,Files}
end.
read_file_records(File, Opts) ->
case filename:extension(File) of
".beam" ->
read_records_from_beam(File, File);
_ ->
parse_file(File, Opts)
end.
read_records_from_beam(Beam, File) ->
case beam_lib:chunks(Beam, [abstract_code,"CInf"]) of
{ok,{_Mod,[{abstract_code,{Version,Forms}},{"CInf",CB}]}} ->
case record_attrs(Forms) of
[] when Version =:= raw_abstract_v1 ->
[];
[] ->
%% If the version is raw_X, then this test
%% is unnecessary.
try_source(File, CB);
Records ->
Records
end;
{ok,{_Mod,[{abstract_code,no_abstract_code},{"CInf",CB}]}} ->
try_source(File, CB);
Error ->
Could be that the " Abst " chunk is missing ( pre R6 ) .
Error
end.
%% This is how the debugger searches for source files. See int.erl.
try_source(Beam, RawCB) ->
EbinDir = filename:dirname(Beam),
CB = binary_to_term(RawCB),
Os = proplists:get_value(options,CB, []),
Src0 = filename:rootname(Beam) ++ ".erl",
Src1 = filename:join([filename:dirname(EbinDir), "src",
filename:basename(Src0)]),
Src2 = proplists:get_value(source, CB, []),
try_sources([Src0,Src1,Src2], Os).
try_sources([], _) ->
{error, nofile};
try_sources([Src|Rest], Os) ->
case is_file(Src) of
true -> parse_file(Src, Os);
false -> try_sources(Rest, Os)
end.
is_file(Name) ->
case filelib:is_file(Name) of
true ->
not filelib:is_dir(Name);
false ->
false
end.
parse_file(File, Opts) ->
Cwd = ".",
Dir = filename:dirname(File),
IncludePath = [Cwd,Dir|inc_paths(Opts)],
case epp:parse_file(File, IncludePath, pre_defs(Opts)) of
{ok,Forms} ->
record_attrs(Forms);
Error ->
Error
end.
pre_defs([{d,M,V}|Opts]) ->
[{M,V}|pre_defs(Opts)];
pre_defs([{d,M}|Opts]) ->
[M|pre_defs(Opts)];
pre_defs([_|Opts]) ->
pre_defs(Opts);
pre_defs([]) -> [].
inc_paths(Opts) ->
[P || {i,P} <- Opts, is_list(P)].
record_attrs(Forms) ->
[A || A = {attribute,_,record,_D} <- Forms].
%%% End of reading record information from file(s)
shell_req(Shell, Req) ->
Shell ! {shell_req,self(),Req},
receive
{shell_rep,Shell,Rep} -> Rep
end.
list_commands([{{N,command},Es0}, {{N,result}, V} |Ds], RT) ->
Es = prep_list_commands(Es0),
VS = pp(V, 4, RT),
Ns = io_lib:fwrite(<<"~w: ">>, [N]),
I = iolist_size(Ns),
io:requests([{put_chars, latin1, Ns},
{format,<<"~ts\n">>,[erl_pp:exprs(Es, I, enc())]},
{format,<<"-> ">>,[]},
{put_chars, unicode, VS},
nl]),
list_commands(Ds, RT);
list_commands([{{N,command},Es0} |Ds], RT) ->
Es = prep_list_commands(Es0),
Ns = io_lib:fwrite(<<"~w: ">>, [N]),
I = iolist_size(Ns),
io:requests([{put_chars, latin1, Ns},
{format,<<"~ts\n">>,[erl_pp:exprs(Es, I, enc())]}]),
list_commands(Ds, RT);
list_commands([_D|Ds], RT) ->
list_commands(Ds, RT);
list_commands([], _RT) -> ok.
list_bindings([{Name,Val}|Bs], RT) ->
case erl_eval:fun_data(Val) of
{fun_data,_FBs,FCs0} ->
FCs = expand_value(FCs0), % looks nicer
A = a0(),
F = {'fun',A,{clauses,FCs}},
M = {match,A,{var,A,Name},F},
io:fwrite(<<"~ts\n">>, [erl_pp:expr(M, enc())]);
{named_fun_data,_FBs,FName,FCs0} ->
FCs = expand_value(FCs0), % looks nicer
A = a0(),
F = {named_fun,A,FName,FCs},
M = {match,A,{var,A,Name},F},
io:fwrite(<<"~ts\n">>, [erl_pp:expr(M, enc())]);
false ->
Namel = io_lib:fwrite(<<"~s = ">>, [Name]),
Nl = iolist_size(Namel)+1,
ValS = pp(Val, Nl, RT),
io:requests([{put_chars, latin1, Namel},
{put_chars, unicode, ValS},
nl])
end,
list_bindings(Bs, RT);
list_bindings([], _RT) ->
ok.
list_records(Records) ->
lists:foreach(fun({_Name,Attr}) ->
io:fwrite(<<"~ts">>, [erl_pp:attribute(Attr, enc())])
end, Records).
record_defs(RT, Names) ->
lists:flatmap(fun(Name) -> ets:lookup(RT, Name)
end, Names).
expand_value(E) ->
substitute_v1(fun({value,CommandN,V}) -> try_abstract(V, CommandN)
end, E).
%% There is no abstract representation of funs.
try_abstract(V, CommandN) ->
try erl_parse:abstract(V)
catch
_:_ ->
A = a0(),
{call,A,{atom,A,v},[{integer,A,CommandN}]}
end.
%% Rather than listing possibly huge results the calls to v/1 are shown.
prep_list_commands(E) ->
A = a0(),
substitute_v1(fun({value,Anno,_V}) ->
CommandN = erl_anno:line(Anno),
{call,A,{atom,A,v},[{integer,A,CommandN}]}
end, E).
substitute_v1(F, {value,_,_}=Value) ->
F(Value);
substitute_v1(F, T) when is_tuple(T) ->
list_to_tuple(substitute_v1(F, tuple_to_list(T)));
substitute_v1(F, [E | Es]) ->
[substitute_v1(F, E) | substitute_v1(F, Es)];
substitute_v1(_F, E) ->
E.
a0() ->
erl_anno:new(0).
pos({Line,Col}) ->
io_lib:format("~w:~w", [Line,Col]);
pos(Line) ->
io_lib:format("~w", [Line]).
check_and_get_history_and_results() ->
check_env(shell_history_length),
check_env(shell_saved_results),
get_history_and_results().
get_history_and_results() ->
History = get_env(shell_history_length, ?DEF_HISTORY),
Results = get_env(shell_saved_results, ?DEF_RESULTS),
{History, erlang:min(Results, History)}.
pp(V, I, RT) ->
pp(V, I, _Depth=?LINEMAX, RT).
pp(V, I, D, RT) ->
Strings = application:get_env(stdlib, shell_strings, true) =/= false,
io_lib_pretty:print(V, ([{column, I}, {line_length, columns()},
{depth, D}, {line_max_chars, ?CHAR_MAX},
{strings, Strings},
{record_print_fun, record_print_fun(RT)}]
++ enc())).
columns() ->
case io:columns() of
{ok,N} -> N;
_ -> 80
end.
encoding() ->
[{encoding, Encoding}] = enc(),
Encoding.
enc() ->
case lists:keyfind(encoding, 1, io:getopts()) of
false -> [{encoding,latin1}]; % should never happen
Enc -> [Enc]
end.
garb(Shell) ->
erlang:garbage_collect(Shell),
catch erlang:garbage_collect(whereis(user)),
catch erlang:garbage_collect(group_leader()),
erlang:garbage_collect().
get_env(V, Def) ->
case application:get_env(stdlib, V, Def) of
Val when is_integer(Val), Val >= 0 ->
Val;
_ ->
Def
end.
check_env(V) ->
case application:get_env(stdlib, V, 0) of
Val when is_integer(Val), Val >= 0 ->
ok;
Val ->
Txt = io_lib:fwrite
("Invalid value of STDLIB configuration parameter"
"~tw: ~tp\n", [V, Val]),
error_logger:info_report(lists:flatten(Txt))
end.
set_env(App, Name, Val, Default) ->
Prev = case application:get_env(App, Name) of
undefined ->
Default;
{ok, Old} ->
Old
end,
application_controller:set_env(App, Name, Val),
Prev.
-spec history(N) -> non_neg_integer() when
N :: non_neg_integer().
history(L) when is_integer(L), L >= 0 ->
set_env(stdlib, shell_history_length, L, ?DEF_HISTORY).
-spec results(N) -> non_neg_integer() when
N :: non_neg_integer().
results(L) when is_integer(L), L >= 0 ->
set_env(stdlib, shell_saved_results, L, ?DEF_RESULTS).
-spec catch_exception(Bool) -> boolean() when
Bool :: boolean().
catch_exception(Bool) ->
set_env(stdlib, shell_catch_exception, Bool, ?DEF_CATCH_EXCEPTION).
-spec prompt_func(PromptFunc) -> PromptFunc2 when
PromptFunc :: 'default' | {module(),atom()},
PromptFunc2 :: 'default' | {module(),atom()}.
prompt_func(PromptFunc) ->
set_env(stdlib, shell_prompt_func, PromptFunc, ?DEF_PROMPT_FUNC).
-spec strings(Strings) -> Strings2 when
Strings :: boolean(),
Strings2 :: boolean().
strings(Strings) ->
set_env(stdlib, shell_strings, Strings, ?DEF_STRINGS).
| null |
https://raw.githubusercontent.com/erlang/otp/2b397d7e5580480dc32fa9751db95f4b89ff029e/lib/stdlib/src/shell.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%
When used as the fallback restricted shell callback module...
Call this function to start a user restricted shell
from a normal shell session.
The shell should not start until the system is up and running.
We subscribe with init to get a notification of when.
In older releases we didn't syncronize the shell with init, but let it
start in parallell with other system processes. This was bad since
accessing the shell too early could interfere with the boot procedure.
Still, by means of a flag, we make it possible to start the shell the
old way (for backwards compatibility reasons). This should however not
be used unless for very special reasons necessary.
no sync with init
Our spawner has fixed the process groups.
Use an Ets table for record definitions. It takes too long to
send a huge term to and from the evaluator. Ets makes it
Store function definitions and types in an ets table.
Check if we're in user restricted mode.
The following test makes sure that large binaries
(outside of the heap) are garbage collected as soon
as possible.
NOTE: we can handle function definitions, records and soon type declarations
but this cannot be handled by the function which only expects erl_parse:abstract_expressions()
for now just pattern match against those types and pass the string to shell local func.
Skip the rest of the line:
arity not the same
Name not the same
Don't bother flattening the list irrespective of what the
I/O-protocol states.
with their expansions.
This is really illegal!
Could expand H and G, but then erl_eval has to be changed as well.
Constants.
add_cmd(Number, Expressions, Value)
get_cmd(Number, CurrentCommand)
del_cmd(Number, NewN, OldN, HasBin0) -> bool()
{Value,Evaluator,Bindings,Dictionary}
Send a command to the evaluator and wait for the reply. Start a new
evaluator if necessary.
What = pmt | cmd. When evaluating a prompt ('pmt') the evaluated value
must not be displayed, and it has to be returned.
Update dictionary
It has exited unnaturally
catch_exception is in effect
Someone interrupted us
Ignore everything else
Evaluate expressions from the shell. Use the "old" variable bindings
and dictionary.
We don't want the ERROR REPORT generated by the
emulator. Note: exit(kill) needs nothing special.
Don't send the result back if it will be
discarded anyway.
Be careful to return a list where used records come before
records that use them. The linter wants them ordered that way.
illegal
Not restricted is the same as builtin.
variable and record manipulations local
to the shell process. Those are never
restricted.
This is never a builtin,
those are handled above.
The user supplied non conforming module
The user supplied non conforming module
The commands implemented in shell should not be checked if allowed
This *has* to correspond to the function local_func/7!
(especially true for f/1, the argument must not be evaluated).
the shell process process that spawned the evaluating
process is garbage collected as well.
To garbage collect the evaluating process only the command
garbage_collect(self()). can be used.
Do not emit a warning for f(V) when V is unbound.
erl_lint cannot handle the history expansion {value,_,_}.
erl_expand_records cannot handle the history expansion {value,_,_}.
Undo the effect of the previous clause...
Evaluate local functions, including shell commands.
handled internally - it should return 'true' for all local functions
handled in this module (i.e. those that are not eventually handled by
This command is validated and expanded prior.
This terminates us
A source file that has not been compiled.
Note that a sequence number is used here to make sure that if a
linter which needs the records in a proper order.)
Read record information from file(s)
Special cases:
- Modules not in the code path (loaded with code:load_abs/1):
code:get_object_code/1 only searches in the code path
- File can also be a file in an archive,
beam_lib:chunks/2 cannot handle such paths but
erl_prim_loader:get_file/1 can
non_existing, interpreted, cover_compiled
If the version is raw_X, then this test
is unnecessary.
This is how the debugger searches for source files. See int.erl.
End of reading record information from file(s)
looks nicer
looks nicer
There is no abstract representation of funs.
Rather than listing possibly huge results the calls to v/1 are shown.
should never happen
|
Copyright Ericsson AB 1996 - 2023 . 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(shell).
-export([start/0, start/1, start/2, server/1, server/2, history/1, results/1]).
-export([get_state/0, get_function/2]).
-export([start_restricted/1, stop_restricted/0]).
-export([local_func/0, local_func/1, local_allowed/3, non_local_allowed/3]).
-export([catch_exception/1, prompt_func/1, strings/1]).
-export([start_interactive/0, start_interactive/1]).
-export([read_and_add_records/5]).
-export([whereis/0]).
-define(LINEMAX, 30).
-define(CHAR_MAX, 60).
-define(DEF_HISTORY, 20).
-define(DEF_RESULTS, 20).
-define(DEF_CATCH_EXCEPTION, false).
-define(DEF_PROMPT_FUNC, default).
-define(DEF_STRINGS, true).
-define(RECORDS, shell_records).
-define(MAXSIZE_HEAPBINARY, 64).
-record(shell_state,{
bindings = [],
records = [],
functions = []
}).
local_allowed(q,[],State) ->
{true,State};
local_allowed(_,_,State) ->
{false,State}.
non_local_allowed({init,stop},[],State) ->
{true,State};
non_local_allowed(_,_,State) ->
{false,State}.
-spec start_interactive() -> ok | {error, already_started}.
start_interactive() ->
user_drv:start_shell().
-spec start_interactive(noshell | mfa()) ->
ok | {error, already_started};
({remote, string()}) ->
ok | {error, already_started | noconnection};
({node(), mfa()} | {remote, string(), mfa()}) ->
ok | {error, already_started | noconnection | badfile | nofile | on_load_failure}.
start_interactive({Node, {M, F, A}}) ->
user_drv:start_shell(#{ initial_shell => {Node, M, F ,A} });
start_interactive(InitialShell) ->
user_drv:start_shell(#{ initial_shell => InitialShell }).
-spec whereis() -> pid() | undefined.
whereis() ->
group:whereis_shell().
-spec start() -> pid().
start() ->
start(false, false).
start(init) ->
start(false, true);
start(NoCtrlG) ->
start(NoCtrlG, false).
start(NoCtrlG, StartSync) ->
_ = code:ensure_loaded(user_default),
Ancestors = [self() | case get('$ancestors') of
undefined -> [];
Anc -> Anc
end],
spawn(fun() ->
put('$ancestors', Ancestors),
server(NoCtrlG, StartSync)
end).
-spec start_restricted(Module) -> {'error', Reason} when
Module :: module(),
Reason :: code:load_error_rsn().
start_restricted(RShMod) when is_atom(RShMod) ->
case code:ensure_loaded(RShMod) of
{module,RShMod} ->
application:set_env(stdlib, restricted_shell, RShMod),
exit(restricted_shell_started);
{error,What} = Error ->
error_logger:error_report(
lists:flatten(
io_lib:fwrite(
"Restricted shell module ~w not found: ~tp\n",
[RShMod,What]))),
Error
end.
-spec stop_restricted() -> no_return().
stop_restricted() ->
application:unset_env(stdlib, restricted_shell),
exit(restricted_shell_stopped).
-spec server(boolean(), boolean()) -> 'terminated'.
server(NoCtrlG, StartSync) ->
put(no_control_g, NoCtrlG),
server(StartSync).
-spec server(boolean()) -> 'terminated'.
server(StartSync) ->
case init:get_argument(async_shell_start) of
{ok,_} ->
_ when not StartSync ->
ok;
_ ->
case init:notify_when_started(self()) of
started ->
ok;
_ ->
init:wait_until_started()
end
end,
Bs = erl_eval:new_bindings(),
possible to have thousands of record definitions .
RT = ets:new(?RECORDS, [public,ordered_set]),
_ = initiate_records(Bs, RT),
process_flag(trap_exit, true),
FT = ets:new(user_functions, [public,ordered_set]),
RShErr =
case application:get_env(stdlib, restricted_shell) of
{ok,RShMod} when is_atom(RShMod) ->
io:fwrite(<<"Restricted ">>, []),
case code:ensure_loaded(RShMod) of
{module,RShMod} ->
undefined;
{error,What} ->
{RShMod,What}
end;
{ok, Term} ->
{Term,not_an_atom};
undefined ->
undefined
end,
JCL =
case get(no_control_g) of
true -> " (type help(). for help)";
_ -> " (press Ctrl+G to abort, type help(). for help)"
end,
DefaultSessionSlogan =
io_lib:format(<<"Eshell V~s">>, [erlang:system_info(version)]),
SessionSlogan =
case application:get_env(stdlib, shell_session_slogan, DefaultSessionSlogan) of
SloganFun when is_function(SloganFun, 0) ->
SloganFun();
Slogan ->
Slogan
end,
try
io:fwrite("~ts~ts\n",[unicode:characters_to_list(SessionSlogan),JCL])
catch _:_ ->
io:fwrite("Warning! The slogan \"~p\" could not be printed.\n",[SessionSlogan])
end,
erase(no_control_g),
case RShErr of
undefined ->
ok;
{RShMod2,What2} ->
io:fwrite(
("Warning! Restricted shell module ~w not found: ~tp.\n"
"Only the commands q() and init:stop() will be allowed!\n"),
[RShMod2,What2]),
application:set_env(stdlib, restricted_shell, ?MODULE)
end,
{History,Results} = check_and_get_history_and_results(),
server_loop(0, start_eval(Bs, RT, FT, []), Bs, RT, FT, [], History, Results).
server_loop(N0, Eval_0, Bs00, RT, FT, Ds00, History0, Results0) ->
N = N0 + 1,
{Eval_1,Bs0,Ds0,Prompt} = prompt(N, Eval_0, Bs00, RT, FT, Ds00),
{Res,Eval0} = get_command(Prompt, Eval_1, Bs0, RT, FT, Ds0),
case Res of
{ok,Es0} ->
case expand_hist(Es0, N) of
{ok,Es} ->
{V,Eval,Bs,Ds} = shell_cmd(Es, Eval0, Bs0, RT, FT, Ds0, cmd),
{History,Results} = check_and_get_history_and_results(),
add_cmd(N, Es, V),
HB1 = del_cmd(command, N - History, N - History0, false),
HB = del_cmd(result, N - Results, N - Results0, HB1),
if
HB ->
garb(self());
true ->
ok
end,
server_loop(N, Eval, Bs, RT, FT, Ds, History, Results);
{error,E} ->
fwrite_severity(benign, <<"~ts">>, [E]),
server_loop(N0, Eval0, Bs0, RT, FT, Ds0, History0, Results0)
end;
{error,{Location,Mod,What}} ->
fwrite_severity(benign, <<"~s: ~ts">>,
[pos(Location), Mod:format_error(What)]),
server_loop(N0, Eval0, Bs0, RT, FT, Ds0, History0, Results0);
Io process terminated
exit(Eval0, kill),
terminated;
Io process interrupted us
exit(Eval0, kill),
{_,Eval,_,_} = shell_rep(Eval0, Bs0, RT, FT, Ds0),
server_loop(N0, Eval, Bs0, RT, FT, Ds0, History0, Results0);
Most probably character > 255
fwrite_severity(benign, <<"~w: Invalid tokens.">>,
[N]),
server_loop(N0, Eval0, Bs0, RT, FT, Ds0, History0, Results0);
eof ->
fwrite_severity(fatal, <<"Terminating erlang (~w)">>, [node()]),
halt()
end.
get_command(Prompt, Eval, Bs, RT, FT, Ds) ->
Ancestors = [self() | get('$ancestors')],
ResWordFun = fun erl_scan:reserved_word/1,
Parse =
fun() ->
put('$ancestors', Ancestors),
exit(
case
io:scan_erl_exprs(group_leader(), Prompt, {1,1},
[text,{reserved_word_fun,ResWordFun}])
of
{ok,Toks,_EndPos} ->
case Toks of
[{'-', _}, {atom, _, Atom}|_] ->
SpecialCase = fun(LocalFunc) ->
FakeLine = begin
case erl_parse:parse_form(Toks) of
{ok, Def} -> lists:flatten(erl_pp:form(Def));
E ->
exit(E)
end
end,
{done, {ok, FakeResult, _}, _} = erl_scan:tokens(
[], atom_to_list(LocalFunc) ++ "(\""++FakeLine++"\").\n",
{1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]),
erl_eval:extended_parse_exprs(FakeResult)
end,
case Atom of
record -> SpecialCase(rd);
spec -> SpecialCase(ft);
type -> SpecialCase(td)
end;
[{atom, _, FunName}, {'(', _}|_] ->
case erl_parse:parse_form(Toks) of
{ok, FunDef} ->
case {edlin_expand:shell_default_or_bif(atom_to_list(FunName)), shell:local_func(FunName)} of
{"user_defined", false} ->
FakeLine =reconstruct(FunDef, FunName),
{done, {ok, FakeResult, _}, _} = erl_scan:tokens(
[], "fd("++ atom_to_list(FunName) ++ ", " ++ FakeLine ++ ").\n",
{1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]),
erl_eval:extended_parse_exprs(FakeResult);
_ -> erl_eval:extended_parse_exprs(Toks)
end;
_ -> erl_eval:extended_parse_exprs(Toks)
end;
_ ->
erl_eval:extended_parse_exprs(Toks)
end;
{eof,_EndPos} ->
eof;
{error,ErrorInfo,_EndPos} ->
Opts = io:getopts(),
TmpOpts = lists:keyreplace(echo, 1, Opts,
{echo, false}),
_ = io:setopts(TmpOpts),
_ = io:get_line(''),
_ = io:setopts(Opts),
{error,ErrorInfo};
Else ->
Else
end
)
end,
Pid = spawn_link(Parse),
get_command1(Pid, Eval, Bs, RT, FT, Ds).
reconstruct(Fun, Name) ->
lists:flatten(erl_pp:expr(reconstruct1(Fun, Name))).
reconstruct1({function, Anno, Name, Arity, Clauses}, Name) ->
{named_fun, Anno, 'RecursiveFuncVar', reconstruct1(Clauses, Name, Arity)}.
reconstruct1([{call, Anno, {atom, Anno1, Name}, Args}|Body], Name, Arity) when length(Args) =:= Arity ->
[{call, Anno, {var, Anno1, 'RecursiveFuncVar'}, reconstruct1(Args, Name, Arity)}| reconstruct1(Body, Name, Arity)];
[{call, Anno, {remote, Anno1, {atom, Anno1, shell_default}, {atom, Anno1, Name}}, reconstruct1(Args, Name, Arity)}|
reconstruct1(Body, Name, Arity)];
case {edlin_expand:shell_default_or_bif(atom_to_list(Fun)), shell:local_func(Fun)} of
{"user_defined", false} ->
[{call, Anno, {remote, Anno1, {atom, Anno1, shell_default}, {atom, Anno1, Fun}}, reconstruct1(Args, Name, Arity)}|
reconstruct1(Body, Name, Arity)];
{"shell_default", false} ->
[{call, Anno, {remote, Anno1, {atom, Anno1, shell_default}, {atom, Anno1, Fun}}, reconstruct1(Args, Name, Arity)}| reconstruct1(Body, Name, Arity)];
{"erlang", false} ->
[{call, Anno, {remote, Anno1, {atom, Anno1, erlang}, {atom, Anno1, Fun}}, reconstruct1(Args, Name, Arity)}| reconstruct1(Body, Name, Arity)];
{_, true} ->
[{call, Anno, {atom, Anno1, Fun}, reconstruct1(Args, Name, Arity)}| reconstruct1(Body, Name, Arity)]
end;
reconstruct1([E|Body], Name, Arity) when is_tuple(E) ->
[list_to_tuple(reconstruct1(tuple_to_list(E), Name, Arity))|reconstruct1(Body, Name, Arity)];
reconstruct1([E|Body], Name, Arity) when is_list(E) ->
[reconstruct1(E, Name, Arity)|reconstruct1(Body, Name, Arity)];
reconstruct1([E|Body], Name, Arity) ->
[E|reconstruct1(Body, Name, Arity)];
reconstruct1([], _, _) -> [].
get_command1(Pid, Eval, Bs, RT, FT, Ds) ->
receive
{shell_state, From} ->
From ! {shell_state, Bs, RT, FT},
get_command1(Pid, Eval, Bs, RT, FT, Ds);
{'EXIT', Pid, Res} ->
{Res, Eval};
{'EXIT', Eval, {Reason,Stacktrace}} ->
report_exception(error, {Reason,Stacktrace}, RT),
get_command1(Pid, start_eval(Bs, RT, FT, Ds), Bs, RT, FT, Ds);
{'EXIT', Eval, Reason} ->
report_exception(error, {Reason,[]}, RT),
get_command1(Pid, start_eval(Bs, RT, FT, Ds), Bs, RT, FT, Ds)
end.
prompt(N, Eval0, Bs0, RT, FT, Ds0) ->
case get_prompt_func() of
{M,F} ->
A = erl_anno:new(1),
L = {cons,A,{tuple,A,[{atom,A,history},{integer,A,N}]},{nil,A}},
C = {call,A,{remote,A,{atom,A,M},{atom,A,F}},[L]},
{V,Eval,Bs,Ds} = shell_cmd([C], Eval0, Bs0, RT, FT, Ds0, pmt),
{Eval,Bs,Ds,case V of
{pmt,Val} ->
Val;
_ ->
bad_prompt_func({M,F}),
default_prompt(N)
end};
default ->
{Eval0,Bs0,Ds0,default_prompt(N)}
end.
get_prompt_func() ->
case application:get_env(stdlib, shell_prompt_func, default) of
{M,F}=PromptFunc when is_atom(M), is_atom(F) ->
PromptFunc;
default=Default ->
Default;
Term ->
bad_prompt_func(Term),
default
end.
bad_prompt_func(M) ->
fwrite_severity(benign, "Bad prompt function: ~tp", [M]).
default_prompt(N) ->
case is_alive() of
true -> io_lib:format(<<"(~s)~w> ">>, [node(), N]);
false -> io_lib:format(<<"~w> ">>, [N])
end.
expand_hist(Expressions , )
Preprocess the expression list replacing all history list commands
expand_hist(Es, C) ->
catch {ok,expand_exprs(Es, C)}.
expand_exprs([E|Es], C) ->
[expand_expr(E, C)|expand_exprs(Es, C)];
expand_exprs([], _C) ->
[].
expand_expr({cons,A,H,T}, C) ->
{cons,A,expand_expr(H, C),expand_expr(T, C)};
expand_expr({lc,A,E,Qs}, C) ->
{lc,A,expand_expr(E, C),expand_quals(Qs, C)};
expand_expr({bc,A,E,Qs}, C) ->
{bc,A,expand_expr(E, C),expand_quals(Qs, C)};
expand_expr({tuple,A,Elts}, C) ->
{tuple,A,expand_exprs(Elts, C)};
expand_expr({map,A,Es}, C) ->
{map,A,expand_exprs(Es, C)};
expand_expr({map,A,Arg,Es}, C) ->
{map,A,expand_expr(Arg, C),expand_exprs(Es, C)};
expand_expr({map_field_assoc,A,K,V}, C) ->
{map_field_assoc,A,expand_expr(K, C),expand_expr(V, C)};
expand_expr({map_field_exact,A,K,V}, C) ->
{map_field_exact,A,expand_expr(K, C),expand_expr(V, C)};
expand_expr({record_index,A,Name,F}, C) ->
{record_index,A,Name,expand_expr(F, C)};
expand_expr({record,A,Name,Is}, C) ->
{record,A,Name,expand_fields(Is, C)};
expand_expr({record_field,A,R,Name,F}, C) ->
{record_field,A,expand_expr(R, C),Name,expand_expr(F, C)};
expand_expr({record,A,R,Name,Ups}, C) ->
{record,A,expand_expr(R, C),Name,expand_fields(Ups, C)};
{record_field,A,expand_expr(R, C),expand_expr(F, C)};
expand_expr({block,A,Es}, C) ->
{block,A,expand_exprs(Es, C)};
expand_expr({'if',A,Cs}, C) ->
{'if',A,expand_cs(Cs, C)};
expand_expr({'case',A,E,Cs}, C) ->
{'case',A,expand_expr(E, C),expand_cs(Cs, C)};
expand_expr({'try',A,Es,Scs,Ccs,As}, C) ->
{'try',A,expand_exprs(Es, C),expand_cs(Scs, C),
expand_cs(Ccs, C),expand_exprs(As, C)};
expand_expr({'receive',A,Cs}, C) ->
{'receive',A,expand_cs(Cs, C)};
expand_expr({'receive',A,Cs,To,ToEs}, C) ->
{'receive',A,expand_cs(Cs, C), expand_expr(To, C), expand_exprs(ToEs, C)};
expand_expr({call,A,{atom,_,e},[N]}, C) ->
case get_cmd(N, C) of
{undefined,_,_} ->
no_command(N);
{[Ce],_V,_CommandN} ->
Ce;
{Ces,_V,_CommandN} when is_list(Ces) ->
{block,A,Ces}
end;
expand_expr({call,CA,{atom,VA,v},[N]}, C) ->
case get_cmd(N, C) of
{_,undefined,_} ->
no_command(N);
{Ces,_V,CommandN} when is_list(Ces) ->
{call,CA,{atom,VA,v},[{integer,VA,CommandN}]}
end;
expand_expr({call,A,F,Args}, C) ->
{call,A,expand_expr(F, C),expand_exprs(Args, C)};
expand_expr({'catch',A,E}, C) ->
{'catch',A,expand_expr(E, C)};
expand_expr({match,A,Lhs,Rhs}, C) ->
{match,A,Lhs,expand_expr(Rhs, C)};
expand_expr({op,A,Op,Arg}, C) ->
{op,A,Op,expand_expr(Arg, C)};
expand_expr({op,A,Op,Larg,Rarg}, C) ->
{op,A,Op,expand_expr(Larg, C),expand_expr(Rarg, C)};
expand_expr({remote,A,M,F}, C) ->
{remote,A,expand_expr(M, C),expand_expr(F, C)};
expand_expr({'fun',A,{clauses,Cs}}, C) ->
{'fun',A,{clauses,expand_exprs(Cs, C)}};
expand_expr({named_fun,A,Name,Cs}, C) ->
{named_fun,A,Name,expand_exprs(Cs, C)};
expand_expr({clause,A,H,G,B}, C) ->
{clause,A,H, G, expand_exprs(B, C)};
expand_expr({bin,A,Fs}, C) ->
{bin,A,expand_bin_elements(Fs, C)};
expand_expr({'- ' } )
E.
expand_cs([{clause,A,P,G,B}|Cs], C) ->
[{clause,A,P,G,expand_exprs(B, C)}|expand_cs(Cs, C)];
expand_cs([], _C) ->
[].
expand_fields([{record_field,A,F,V}|Fs], C) ->
[{record_field,A,expand_expr(F, C),expand_expr(V, C)}|
expand_fields(Fs, C)];
expand_fields([], _C) -> [].
expand_quals([{generate,A,P,E}|Qs], C) ->
[{generate,A,P,expand_expr(E, C)}|expand_quals(Qs, C)];
expand_quals([{b_generate,A,P,E}|Qs], C) ->
[{b_generate,A,P,expand_expr(E, C)}|expand_quals(Qs, C)];
expand_quals([E|Qs], C) ->
[expand_expr(E, C)|expand_quals(Qs, C)];
expand_quals([], _C) -> [].
expand_bin_elements([], _C) ->
[];
expand_bin_elements([{bin_element,A,E,Sz,Ts}|Fs], C) ->
[{bin_element,A,expand_expr(E, C),Sz,Ts}|expand_bin_elements(Fs, C)].
no_command(N) ->
throw({error,
io_lib:fwrite(<<"~ts: command not found">>,
[erl_pp:expr(N, enc())])}).
add_cmd(N, Es, V) ->
put({command,N}, Es),
put({result,N}, V).
getc(N) ->
{get({command,N}), get({result,N}), N}.
get_cmd(Num, C) ->
case catch erl_eval:expr(Num, erl_eval:new_bindings()) of
{value,N,_} when N < 0 -> getc(C+N);
{value,N,_} -> getc(N);
_Other -> {undefined,undefined,undefined}
end.
del_cmd(_Type, N, N0, HasBin) when N < N0 ->
HasBin;
del_cmd(Type, N, N0, HasBin0) ->
T = erase({Type,N}),
HasBin = HasBin0 orelse has_binary(T),
del_cmd(Type, N-1, N0, HasBin).
has_binary(T) ->
try has_bin(T), false
catch true=Thrown -> Thrown
end.
has_bin(T) when is_tuple(T) ->
has_bin(T, tuple_size(T));
has_bin([E | Es]) ->
has_bin(E),
has_bin(Es);
has_bin(B) when byte_size(B) > ?MAXSIZE_HEAPBINARY ->
throw(true);
has_bin(T) ->
T.
has_bin(T, 0) ->
T;
has_bin(T, I) ->
has_bin(element(I, T)),
has_bin(T, I - 1).
get_state() ->
whereis() ! {shell_state, self()},
receive
{shell_state, Bs, RT, FT} ->
#shell_state{bindings = Bs, records = ets:tab2list(RT), functions = ets:tab2list(FT)}
end.
get_function(Func, Arity) ->
{shell_state, _Bs, _RT, FT} = get_state(),
try
{value, {_, Fun}} = lists:keysearch({function, {shell_default,Func,Arity}}, 1, FT),
Fun
catch _:_ ->
undefined
end.
shell_cmd(Sequence , Evaluator , , , Dictionary , What )
shell_rep(Evaluator , , , Dictionary ) - >
shell_cmd(Es, Eval, Bs, RT, FT, Ds, W) ->
Eval ! {shell_cmd,self(),{eval,Es}, W},
shell_rep(Eval, Bs, RT, FT, Ds).
shell_rep(Ev, Bs0, RT, FT, Ds0) ->
receive
{shell_rep,Ev,{value,V,Bs,Ds}} ->
{V,Ev,Bs,Ds};
{shell_rep,Ev,{command_error,{Location,M,Error}}} ->
fwrite_severity(benign, <<"~s: ~ts">>,
[pos(Location), M:format_error(Error)]),
{{'EXIT',Error},Ev,Bs0,Ds0};
{shell_req,Ev,{get_cmd,N}} ->
Ev ! {shell_rep,self(),getc(N)},
shell_rep(Ev, Bs0, RT, FT, Ds0);
{shell_req,Ev,get_cmd} ->
Ev ! {shell_rep,self(),get()},
shell_rep(Ev, Bs0, RT, FT, Ds0);
{shell_req,Ev,exit} ->
Ev ! {shell_rep,self(),exit},
exit(normal);
Ev ! {shell_rep,self(),ok},
shell_rep(Ev, Bs0, RT, FT, Ds);
{shell_state, From} ->
From ! {shell_state, Bs0, RT, FT},
shell_rep(Ev, Bs0, RT, FT, Ds0);
receive {'EXIT',Ev,normal} -> ok end,
report_exception(Class, Reason0, RT),
Reason = nocatch(Class, Reason0),
{{'EXIT',Reason},start_eval(Bs0, RT, FT, Ds0), Bs0, Ds0};
report_exception(Class, benign, Reason0, RT),
Reason = nocatch(Class, Reason0),
{{'EXIT',Reason},Ev,Bs0,Ds0};
exit(Ev, kill),
shell_rep(Ev, Bs0, RT, FT, Ds0);
{'EXIT',Ev,{Reason,Stacktrace}} ->
report_exception(exit, {Reason,Stacktrace}, RT),
{{'EXIT',Reason},start_eval(Bs0, RT, FT, Ds0), Bs0, Ds0};
{'EXIT',Ev,Reason} ->
report_exception(exit, {Reason,[]}, RT),
{{'EXIT',Reason},start_eval(Bs0, RT, FT, Ds0), Bs0, Ds0};
{'EXIT',_Id,R} ->
exit(Ev, R),
exit(R);
io:format("Throwing ~p~n", [_Other]),
shell_rep(Ev, Bs0, RT, FT, Ds0)
end.
nocatch(throw, {Term,Stack}) ->
{{nocatch,Term},Stack};
nocatch(error, Reason) ->
Reason;
nocatch(exit, Reason) ->
Reason.
report_exception(Class, Reason, RT) ->
report_exception(Class, serious, Reason, RT).
report_exception(Class, Severity, {Reason,Stacktrace}, RT) ->
Tag = severity_tag(Severity),
I = iolist_size(Tag) + 1,
PF = fun(Term, I1) -> pp(Term, I1, RT) end,
SF = fun(M, _F, _A) -> (M =:= erl_eval) or (M =:= ?MODULE) end,
Enc = encoding(),
Str = erl_error:format_exception(I, Class, Reason, Stacktrace, SF, PF, Enc),
io:requests([{put_chars, latin1, Tag},
{put_chars, unicode, Str},
nl]).
start_eval(Bs, RT, FT, Ds) ->
Self = self(),
Ancestors = [self() | get('$ancestors')],
Eval = spawn_link(fun() ->
put('$ancestors', Ancestors),
evaluator(Self, Bs, RT, FT, Ds)
end),
put(evaluator, Eval),
Eval.
evaluator(Shell , Bindings , , ProcessDictionary )
evaluator(Shell, Bs, RT, FT, Ds) ->
init_dict(Ds),
case application:get_env(stdlib, restricted_shell) of
undefined ->
eval_loop(Shell, Bs, RT, FT);
{ok,RShMod} ->
case get(restricted_shell_state) of
undefined -> put(restricted_shell_state, []);
_ -> ok
end,
put(restricted_expr_state, []),
restricted_eval_loop(Shell, Bs, RT, FT, RShMod)
end.
eval_loop(Shell, Bs0, RT, FT) ->
receive
{shell_cmd,Shell,{eval,Es},W} ->
Ef = {value,
fun(MForFun, As) -> apply_fun(MForFun, As, Shell) end},
Lf = local_func_handler(Shell, RT, FT, Ef),
Bs = eval_exprs(Es, Shell, Bs0, RT, Lf, Ef, W),
eval_loop(Shell, Bs, RT, FT)
end.
restricted_eval_loop(Shell, Bs0, RT, FT, RShMod) ->
receive
{shell_cmd,Shell,{eval,Es}, W} ->
{LFH,NLFH} = restrict_handlers(RShMod, Shell, RT, FT),
put(restricted_expr_state, []),
Bs = eval_exprs(Es, Shell, Bs0, RT, {eval,LFH}, {value,NLFH}, W),
restricted_eval_loop(Shell, Bs, RT, FT, RShMod)
end.
eval_exprs(Es, Shell, Bs0, RT, Lf, Ef, W) ->
try
{R,Bs2} = exprs(Es, Bs0, RT, Lf, Ef, W),
Shell ! {shell_rep,self(),R},
Bs2
catch
exit:normal ->
exit(normal);
Class:Reason:Stacktrace ->
M = {self(),Class,{Reason,Stacktrace}},
case do_catch(Class, Reason) of
true ->
Shell ! {ev_caught,M},
Bs0;
false ->
{links,LPs} = process_info(self(), links),
ER = nocatch(Class, {Reason,Stacktrace}),
lists:foreach(fun(P) -> exit(P, ER) end, LPs--[Shell]),
Shell ! {ev_exit,M},
exit(normal)
end
end.
do_catch(exit, restricted_shell_stopped) ->
false;
do_catch(exit, restricted_shell_started) ->
false;
do_catch(_Class, _Reason) ->
case application:get_env(stdlib, shell_catch_exception, false) of
true ->
true;
_ ->
false
end.
exprs(Es, Bs0, RT, Lf, Ef, W) ->
exprs(Es, Bs0, RT, Lf, Ef, Bs0, W).
exprs([E0|Es], Bs1, RT, Lf, Ef, Bs0, W) ->
UsedRecords = used_record_defs(E0, RT),
RBs = record_bindings(UsedRecords, Bs1),
case check_command(prep_check([E0]), RBs) of
ok ->
E1 = expand_records(UsedRecords, E0),
{value,V0,Bs2} = expr(E1, Bs1, Lf, Ef),
Bs = orddict:from_list([VV || {X,_}=VV <- erl_eval:bindings(Bs2),
not is_expand_variable(X)]),
if
Es =:= [] ->
VS = pp(V0, 1, RT),
case W of
cmd -> io:requests([{put_chars, unicode, VS}, nl]);
pmt -> ok
end,
V = if
W =:= pmt ->
{W,V0};
true -> case result_will_be_saved() of
true -> V0;
false ->
erlang:garbage_collect(),
ignored
end
end,
{{value,V,Bs,get()},Bs};
true ->
exprs(Es, Bs, RT, Lf, Ef, Bs0, W)
end;
{error,Error} ->
{{command_error,Error},Bs0}
end.
is_expand_variable(V) ->
case catch atom_to_list(V) of
"rec" ++ _Integer -> true;
_ -> false
end.
result_will_be_saved() ->
case get_history_and_results() of
{_, 0} -> false;
_ -> true
end.
used_record_defs(E, RT) ->
UR = case used_records(E, [], RT, []) of
[] ->
[];
L0 ->
L1 = lists:zip(L0, lists:seq(1, length(L0))),
L2 = lists:keysort(2, lists:ukeysort(1, L1)),
[R || {R, _} <- L2]
end,
record_defs(RT, UR).
used_records(E, U0, RT, Skip) ->
case used_records(E) of
{name,Name,E1} ->
U = case lists:member(Name, Skip) of
true ->
U0;
false ->
R = ets:lookup(RT, Name),
used_records(R, [Name | U0], RT, [Name | Skip])
end,
used_records(E1, U, RT, Skip);
{expr,[E1 | Es]} ->
used_records(Es, used_records(E1, U0, RT, Skip), RT, Skip);
_ ->
U0
end.
used_records({record_index,_,Name,F}) ->
{name, Name, F};
used_records({record,_,Name,Is}) ->
{name, Name, Is};
used_records({record_field,_,R,Name,F}) ->
{name, Name, [R | F]};
used_records({record,_,R,Name,Ups}) ->
{name, Name, [R | Ups]};
{expr, [R | F]};
used_records({call,_,{atom,_,record},[A,{atom,_,Name}]}) ->
{name, Name, A};
used_records({call,_,{atom,_,is_record},[A,{atom,_,Name}]}) ->
{name, Name, A};
used_records({call,_,{remote,_,{atom,_,erlang},{atom,_,is_record}},
[A,{atom,_,Name}]}) ->
{name, Name, A};
used_records({call,_,{atom,_,record_info},[A,{atom,_,Name}]}) ->
{name, Name, A};
used_records({call,A,{tuple,_,[M,F]},As}) ->
used_records({call,A,{remote,A,M,F},As});
used_records({type,_,record,[{atom,_,Name}|Fs]}) ->
{name, Name, Fs};
used_records(T) when is_tuple(T) ->
{expr, tuple_to_list(T)};
used_records(E) ->
{expr, E}.
fwrite_severity(Severity, S, As) ->
io:fwrite(<<"~ts\n">>, [format_severity(Severity, S, As)]).
format_severity(Severity, S, As) ->
add_severity(Severity, io_lib:fwrite(S, As)).
add_severity(Severity, S) ->
[severity_tag(Severity), S].
severity_tag(fatal) -> <<"*** ">>;
severity_tag(serious) -> <<"** ">>;
severity_tag(benign) -> <<"* ">>.
restrict_handlers(RShMod, Shell, RT, FT) ->
{ fun(F,As,Binds) ->
local_allowed(F, As, RShMod, Binds, Shell, RT, FT)
end,
fun(MF,As) ->
non_local_allowed(MF, As, RShMod, Shell)
end }.
-define(BAD_RETURN(M, F, V),
try erlang:error(reason)
catch _:_:S -> erlang:raise(exit, {restricted_shell_bad_return,V},
[{M,F,3} | S])
end).
local_allowed(F, As, RShMod, Bs, Shell, RT, FT) when is_atom(F) ->
{LFH,NLFH} = restrict_handlers(RShMod, Shell, RT, FT),
true ->
local_func(F, As, Bs, Shell, RT, FT, {eval,LFH}, {value,NLFH});
false ->
{AsEv,Bs1} = expr_list(As, Bs, {eval,LFH}, {value,NLFH}),
case RShMod:local_allowed(F, AsEv, {get(restricted_shell_state),
get(restricted_expr_state)}) of
{Result,{RShShSt,RShExprSt}} ->
put(restricted_shell_state, RShShSt),
put(restricted_expr_state, RShExprSt),
if not Result ->
shell_req(Shell, {update_dict,get()}),
exit({restricted_shell_disallowed,{F,AsEv}});
non_builtin_local_func(F,AsEv,Bs1, FT)
end;
?BAD_RETURN(RShMod, local_allowed, Unexpected)
end
end.
non_local_allowed(MForFun, As, RShMod, Shell) ->
case RShMod:non_local_allowed(MForFun, As, {get(restricted_shell_state),
get(restricted_expr_state)}) of
{Result,{RShShSt,RShExprSt}} ->
put(restricted_shell_state, RShShSt),
put(restricted_expr_state, RShExprSt),
case Result of
false ->
shell_req(Shell, {update_dict,get()}),
exit({restricted_shell_disallowed,{MForFun,As}});
{redirect, NewMForFun, NewAs} ->
apply_fun(NewMForFun, NewAs, Shell);
_ ->
apply_fun(MForFun, As, Shell)
end;
?BAD_RETURN(RShMod, non_local_allowed, Unexpected)
end.
not_restricted(f, []) ->
true;
not_restricted(f, [_]) ->
true;
not_restricted(h, []) ->
true;
not_restricted(b, []) ->
true;
not_restricted(history, [_]) ->
true;
not_restricted(results, [_]) ->
true;
not_restricted(catch_exception, [_]) ->
true;
not_restricted(exit, []) ->
true;
not_restricted(fl, []) ->
true;
not_restricted(fd, [_]) ->
true;
not_restricted(ft, [_]) ->
true;
not_restricted(td, [_]) ->
true;
not_restricted(rd, [_]) ->
true;
not_restricted(rd, [_,_]) ->
true;
not_restricted(rf, []) ->
true;
not_restricted(rf, [_]) ->
true;
not_restricted(rl, []) ->
true;
not_restricted(rl, [_]) ->
true;
not_restricted(rp, [_]) ->
true;
not_restricted(rr, [_]) ->
true;
not_restricted(rr, [_,_]) ->
true;
not_restricted(rr, [_,_,_]) ->
true;
not_restricted(_, _) ->
false.
When : ( ) is called from the shell ,
apply_fun({erlang,garbage_collect}, [], Shell) ->
garb(Shell);
apply_fun({M,F}, As, _Shell) ->
apply(M, F, As);
apply_fun(MForFun, As, _Shell) ->
apply(MForFun, As).
prep_check({call,Anno,{atom,_,f},[{var,_,_Name}]}) ->
{atom,Anno,ok};
prep_check({value,_CommandN,_Val}) ->
{atom,a0(),ok};
prep_check(T) when is_tuple(T) ->
list_to_tuple(prep_check(tuple_to_list(T)));
prep_check([E | Es]) ->
[prep_check(E) | prep_check(Es)];
prep_check(E) ->
E.
expand_records([], E0) ->
E0;
expand_records(UsedRecords, E0) ->
RecordDefs = [Def || {_Name,Def} <- UsedRecords],
A = erl_anno:new(1),
E = prep_rec(E0),
Forms0 = RecordDefs ++ [{function,A,foo,0,[{clause,A,[],[],[E]}]}],
Forms = erl_expand_records:module(Forms0, [strict_record_tests]),
{function,A,foo,0,[{clause,A,[],[],[NE]}]} = lists:last(Forms),
prep_rec(NE).
prep_rec({value,_CommandN,_V}=Value) ->
{atom,Value,ok};
prep_rec({atom,{value,_CommandN,_V}=Value,ok}) ->
Value;
prep_rec(T) when is_tuple(T) -> list_to_tuple(prep_rec(tuple_to_list(T)));
prep_rec([E | Es]) -> [prep_rec(E) | prep_rec(Es)];
prep_rec(E) -> E.
init_dict([{K,V}|Ds]) ->
put(K, V),
init_dict(Ds);
init_dict([]) -> true.
local_func(Function , , Bindings , Shell , ,
LocalFuncHandler , ExternalFuncHandler ) - > { value , , Bs }
Note that the predicate not_restricted/2 has to correspond to what 's
non_builtin_local_func/3 ( user_default / shell_default ) .
local_func() -> [v,h,b,f,fl,rd,rf,rl,rp,rr,history,results,catch_exception].
local_func(Func) ->
lists:member(Func, local_func()).
local_func(v, [{integer,_,V}], Bs, Shell, _RT, _FT, _Lf, _Ef) ->
{_Ces,Value,_N} = shell_req(Shell, {get_cmd, V}),
{value,Value,Bs};
local_func(h, [], Bs, Shell, RT, _FT, _Lf, _Ef) ->
Cs = shell_req(Shell, get_cmd),
Cs1 = lists:filter(fun({{command, _},_}) -> true;
({{result, _},_}) -> true;
(_) -> false
end,
Cs),
Cs2 = lists:map(fun({{T, N}, V}) -> {{N, T}, V} end,
Cs1),
Cs3 = lists:keysort(1, Cs2),
{value,list_commands(Cs3, RT),Bs};
local_func(b, [], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
{value,list_bindings(erl_eval:bindings(Bs), RT),Bs};
local_func(f, [], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
{value,ok,erl_eval:new_bindings()};
local_func(f, [{var,_,Name}], Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
{value,ok,erl_eval:del_binding(Name, Bs)};
local_func(f, [_Other], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,f,1}]);
local_func(fl, [], Bs, _Shell, _RT, FT, _Lf, _Ef) ->
{value, ets:tab2list(FT), Bs};
local_func(fd, [{atom,_,FunName}, FunExpr], Bs, _Shell, _RT, FT, _Lf, _Ef) ->
{value, Fun, []} = erl_eval:expr(FunExpr, []),
{arity, Arity} = erlang:fun_info(Fun, arity),
ets:insert(FT, [{{function, {shell_default, FunName, Arity}}, Fun}]),
{value, ok, Bs};
local_func(fd, [_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell, fd, 1}]);
local_func(ft, [{string, _, TypeDef}], Bs, _Shell, _RT, FT, _Lf, _Ef) ->
case erl_scan:tokens([], TypeDef, {1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]) of
{done, {ok, Toks, _}, _} ->
case erl_parse:parse_form(Toks) of
{ok, {attribute,_,spec,{{FunName, Arity},_}}=AttrForm} ->
ets:insert(FT, [{{function_type, {shell_default, FunName, Arity}}, AttrForm}]),
{value, ok, Bs};
{error,{_Location,M,ErrDesc}} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
{done, {error,{_Location, M, ErrDesc}, _}, _} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
local_func(ft, [_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell, ft, 1}]);
local_func(td, [{string, _, TypeDef}], Bs, _Shell, _RT, FT, _Lf, _Ef) ->
case erl_scan:tokens([], TypeDef, {1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]) of
{done, {ok, Toks, _}, _} ->
case erl_parse:parse_form(Toks) of
{ok, {attribute,_,type,{TypeName, _, _}}=AttrForm} ->
ets:insert(FT, [{{type, TypeName}, AttrForm}]),
{value, ok, Bs};
{error,{_Location,M,ErrDesc}} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
{done, {error,{_Location, M, ErrDesc}, _}, _} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
local_func(td, [_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell, td, 1}]);
local_func(rd, [{string, _, TypeDef}], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
case erl_scan:tokens([], TypeDef, {1,1}, [text,{reserved_word_fun,fun erl_scan:reserved_word/1}]) of
{done, {ok, Toks, _}, _} ->
case erl_parse:parse_form(Toks) of
{ok,{attribute,_,_,_}=AttrForm} ->
[_] = add_records([AttrForm], Bs, RT),
{value,ok,Bs};
{error,{_Location,M,ErrDesc}} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
{done, {error,{_Location, M, ErrDesc}, _}, _} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
local_func(rd, [_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell, rd, 1}]);
local_func(rd, [{atom,_,RecName0},RecDef0], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
RecDef = expand_value(RecDef0),
RDs = lists:flatten(erl_pp:expr(RecDef)),
RecName = io_lib:write_atom_as_latin1(RecName0),
Attr = lists:concat(["-record(", RecName, ",", RDs, ")."]),
{ok, Tokens, _} = erl_scan:string(Attr),
case erl_parse:parse_form(Tokens) of
{ok,AttrForm} ->
[RN] = add_records([AttrForm], Bs, RT),
{value,RN,Bs};
{error,{_Location,M,ErrDesc}} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr))
end;
local_func(rd, [_,_], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,rd,2}]);
local_func(rf, [], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
true = ets:delete_all_objects(RT),
{value,initiate_records(Bs, RT),Bs};
local_func(rf, [A], Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[Recs],Bs} = expr_list([A], Bs0, Lf, Ef),
if '_' =:= Recs ->
true = ets:delete_all_objects(RT);
true ->
lists:foreach(fun(Name) -> true = ets:delete(RT, Name)
end, listify(Recs))
end,
{value,ok,Bs};
local_func(rl, [], Bs, _Shell, RT, _FT, _Lf, _Ef) ->
{value,list_records(ets:tab2list(RT)),Bs};
local_func(rl, [A], Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[Recs],Bs} = expr_list([A], Bs0, Lf, Ef),
{value,list_records(record_defs(RT, listify(Recs))),Bs};
local_func(rp, [A], Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[V],Bs} = expr_list([A], Bs0, Lf, Ef),
Cs = pp(V, _Column=1, _Depth=-1, RT),
io:requests([{put_chars, unicode, Cs}, nl]),
{value,ok,Bs};
local_func(rr, [A], Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[File],Bs} = expr_list([A], Bs0, Lf, Ef),
{value,read_and_add_records(File, '_', [], Bs, RT),Bs};
local_func(rr, [_,_]=As0, Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[File,Sel],Bs} = expr_list(As0, Bs0, Lf, Ef),
{value,read_and_add_records(File, Sel, [], Bs, RT),Bs};
local_func(rr, [_,_,_]=As0, Bs0, _Shell, RT, _FT, Lf, Ef) ->
{[File,Sel,Options],Bs} = expr_list(As0, Bs0, Lf, Ef),
{value,read_and_add_records(File, Sel, Options, Bs, RT),Bs};
local_func(history, [{integer,_,N}], Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
{value,history(N),Bs};
local_func(history, [_Other], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,history,1}]);
local_func(results, [{integer,_,N}], Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
{value,results(N),Bs};
local_func(results, [_Other], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,results,1}]);
local_func(catch_exception, [{atom,_,Bool}], Bs, _Shell, _RT, _FT, _Lf, _Ef)
when Bool; not Bool ->
{value,catch_exception(Bool),Bs};
local_func(catch_exception, [_Other], _Bs, _Shell, _RT, _FT, _Lf, _Ef) ->
erlang:raise(error, function_clause, [{shell,catch_exception,1}]);
local_func(exit, [], _Bs, Shell, _RT, _FT, _Lf, _Ef) ->
exit(normal);
local_func(F, As0, Bs0, _Shell, _RT, FT, Lf, Ef) when is_atom(F) ->
{As,Bs} = expr_list(As0, Bs0, Lf, Ef),
non_builtin_local_func(F,As,Bs, FT).
non_builtin_local_func(F,As,Bs, FT) ->
Arity = length(As),
case erlang:function_exported(user_default, F, Arity) of
true ->
{eval,erlang:make_fun(user_default, F, Arity),As,Bs};
false ->
shell_default(F,As,Bs, FT)
end.
shell_default(F,As,Bs, FT) ->
M = shell_default,
A = length(As),
case code:ensure_loaded(M) of
{module, _} ->
case erlang:function_exported(M,F,A) of
true ->
{eval,erlang:make_fun(M, F, A),As,Bs};
false ->
shell_default_local_func(F,As, Bs, FT)
end;
{error, _} ->
shell_default_local_func(F,As, Bs, FT)
end.
shell_default_local_func(F, As, Bs, FT) ->
case ets:lookup(FT, {function, {shell_default, F, length(As)}}) of
[] -> shell_undef(F, length(As));
[{_, Fun}] -> {eval, Fun, As, Bs}
end.
shell_undef(F,A) ->
erlang:error({shell_undef,F,A,[]}).
local_func_handler(Shell, RT, FT, Ef) ->
H = fun(Lf) ->
fun(F, As, Bs) ->
local_func(F, As, Bs, Shell, RT, FT, {eval,Lf(Lf)}, Ef)
end
end,
{eval,H(H)}.
record_print_fun(RT) ->
fun(Tag, NoFields) ->
case ets:lookup(RT, Tag) of
[{_,{attribute,_,record,{Tag,Fields}}}]
when length(Fields) =:= NoFields ->
record_fields(Fields);
_ ->
no
end
end.
record_fields([{record_field,_,{atom,_,Field}} | Fs]) ->
[Field | record_fields(Fs)];
record_fields([{record_field,_,{atom,_,Field},_} | Fs]) ->
[Field | record_fields(Fs)];
record_fields([{typed_record_field,Field,_Type} | Fs]) ->
record_fields([Field | Fs]);
record_fields([]) ->
[].
initiate_records(Bs, RT) ->
RNs1 = init_rec(shell_default, Bs, RT),
RNs2 = case code:is_loaded(user_default) of
{file,_File} ->
init_rec(user_default, Bs, RT);
false ->
[]
end,
lists:usort(RNs1 ++ RNs2).
init_rec(Module, Bs, RT) ->
case read_records(Module, []) of
RAs when is_list(RAs) ->
case catch add_records(RAs, Bs, RT) of
{'EXIT',_} ->
[];
RNs ->
RNs
end;
_Error ->
[]
end.
read_and_add_records(File, Selected, Options, Bs, RT) ->
case read_records(File, Selected, Options) of
RAs when is_list(RAs) ->
add_records(RAs, Bs, RT);
Error ->
Error
end.
read_records(File, Selected, Options) ->
case read_records(File, listify(Options)) of
Error when is_tuple(Error) ->
Error;
RAs when Selected =:= '_' ->
RAs;
RAs ->
Sel = listify(Selected),
[RA || {attribute,_,_,{Name,_}}=RA <- RAs,
lists:member(Name, Sel)]
end.
add_records(RAs, Bs0, RT) ->
TODO store File name to support type completion
Recs = [{Name,D} || {attribute,_,_,{Name,_}}=D <- RAs],
Bs1 = record_bindings(Recs, Bs0),
case check_command([], Bs1) of
{error,{_Location,M,ErrDesc}} ->
ErrStr = io_lib:fwrite(<<"~ts">>, [M:format_error(ErrDesc)]),
exit(lists:flatten(ErrStr));
ok ->
true = ets:insert(RT, Recs),
lists:usort([Name || {Name,_} <- Recs])
end.
listify(L) when is_list(L) ->
L;
listify(E) ->
[E].
check_command(Es, Bs) ->
erl_eval:check_command(Es, Bs).
expr(E, Bs, Lf, Ef) ->
erl_eval:expr(E, Bs, Lf, Ef).
expr_list(Es, Bs, Lf, Ef) ->
erl_eval:expr_list(Es, Bs, Lf, Ef).
record is used by another record , then the first record is parsed
before the second record . ( erl_eval : check_command ( ) calls the
record_bindings([], Bs) ->
Bs;
record_bindings(Recs0, Bs0) ->
{Recs1, _} = lists:mapfoldl(fun ({Name,Def}, I) -> {{Name,I,Def},I+1}
end, 0, Recs0),
Recs2 = lists:keysort(2, lists:ukeysort(1, Recs1)),
lists:foldl(fun ({Name,I,Def}, Bs) ->
erl_eval:add_binding({record,I,Name}, Def, Bs)
end, Bs0, Recs2).
read_records(FileOrModule, Opts0) ->
Opts = lists:delete(report_warnings, Opts0),
case find_file(FileOrModule) of
{beam, Beam, File} ->
read_records_from_beam(Beam, File);
{files,[File]} ->
read_file_records(File, Opts);
{files,Files} ->
lists:flatmap(fun(File) ->
case read_file_records(File, Opts) of
RAs when is_list(RAs) -> RAs;
_ -> []
end
end, Files);
Error ->
Error
end.
-include_lib("kernel/include/file.hrl").
find_file(Mod) when is_atom(Mod) ->
case code:which(Mod) of
File when is_list(File) ->
but code : finds all loaded modules
case erl_prim_loader:get_file(File) of
{ok, Beam, _} ->
{beam, Beam, File};
error ->
{error, nofile}
end;
preloaded ->
{_M, Beam, File} = code:get_object_code(Mod),
{beam, Beam, File};
{error,nofile}
end;
find_file(File) ->
case catch filelib:wildcard(File) of
{'EXIT',_} ->
{error,invalid_filename};
Files ->
{files,Files}
end.
read_file_records(File, Opts) ->
case filename:extension(File) of
".beam" ->
read_records_from_beam(File, File);
_ ->
parse_file(File, Opts)
end.
read_records_from_beam(Beam, File) ->
case beam_lib:chunks(Beam, [abstract_code,"CInf"]) of
{ok,{_Mod,[{abstract_code,{Version,Forms}},{"CInf",CB}]}} ->
case record_attrs(Forms) of
[] when Version =:= raw_abstract_v1 ->
[];
[] ->
try_source(File, CB);
Records ->
Records
end;
{ok,{_Mod,[{abstract_code,no_abstract_code},{"CInf",CB}]}} ->
try_source(File, CB);
Error ->
Could be that the " Abst " chunk is missing ( pre R6 ) .
Error
end.
try_source(Beam, RawCB) ->
EbinDir = filename:dirname(Beam),
CB = binary_to_term(RawCB),
Os = proplists:get_value(options,CB, []),
Src0 = filename:rootname(Beam) ++ ".erl",
Src1 = filename:join([filename:dirname(EbinDir), "src",
filename:basename(Src0)]),
Src2 = proplists:get_value(source, CB, []),
try_sources([Src0,Src1,Src2], Os).
try_sources([], _) ->
{error, nofile};
try_sources([Src|Rest], Os) ->
case is_file(Src) of
true -> parse_file(Src, Os);
false -> try_sources(Rest, Os)
end.
is_file(Name) ->
case filelib:is_file(Name) of
true ->
not filelib:is_dir(Name);
false ->
false
end.
parse_file(File, Opts) ->
Cwd = ".",
Dir = filename:dirname(File),
IncludePath = [Cwd,Dir|inc_paths(Opts)],
case epp:parse_file(File, IncludePath, pre_defs(Opts)) of
{ok,Forms} ->
record_attrs(Forms);
Error ->
Error
end.
pre_defs([{d,M,V}|Opts]) ->
[{M,V}|pre_defs(Opts)];
pre_defs([{d,M}|Opts]) ->
[M|pre_defs(Opts)];
pre_defs([_|Opts]) ->
pre_defs(Opts);
pre_defs([]) -> [].
inc_paths(Opts) ->
[P || {i,P} <- Opts, is_list(P)].
record_attrs(Forms) ->
[A || A = {attribute,_,record,_D} <- Forms].
shell_req(Shell, Req) ->
Shell ! {shell_req,self(),Req},
receive
{shell_rep,Shell,Rep} -> Rep
end.
list_commands([{{N,command},Es0}, {{N,result}, V} |Ds], RT) ->
Es = prep_list_commands(Es0),
VS = pp(V, 4, RT),
Ns = io_lib:fwrite(<<"~w: ">>, [N]),
I = iolist_size(Ns),
io:requests([{put_chars, latin1, Ns},
{format,<<"~ts\n">>,[erl_pp:exprs(Es, I, enc())]},
{format,<<"-> ">>,[]},
{put_chars, unicode, VS},
nl]),
list_commands(Ds, RT);
list_commands([{{N,command},Es0} |Ds], RT) ->
Es = prep_list_commands(Es0),
Ns = io_lib:fwrite(<<"~w: ">>, [N]),
I = iolist_size(Ns),
io:requests([{put_chars, latin1, Ns},
{format,<<"~ts\n">>,[erl_pp:exprs(Es, I, enc())]}]),
list_commands(Ds, RT);
list_commands([_D|Ds], RT) ->
list_commands(Ds, RT);
list_commands([], _RT) -> ok.
list_bindings([{Name,Val}|Bs], RT) ->
case erl_eval:fun_data(Val) of
{fun_data,_FBs,FCs0} ->
A = a0(),
F = {'fun',A,{clauses,FCs}},
M = {match,A,{var,A,Name},F},
io:fwrite(<<"~ts\n">>, [erl_pp:expr(M, enc())]);
{named_fun_data,_FBs,FName,FCs0} ->
A = a0(),
F = {named_fun,A,FName,FCs},
M = {match,A,{var,A,Name},F},
io:fwrite(<<"~ts\n">>, [erl_pp:expr(M, enc())]);
false ->
Namel = io_lib:fwrite(<<"~s = ">>, [Name]),
Nl = iolist_size(Namel)+1,
ValS = pp(Val, Nl, RT),
io:requests([{put_chars, latin1, Namel},
{put_chars, unicode, ValS},
nl])
end,
list_bindings(Bs, RT);
list_bindings([], _RT) ->
ok.
list_records(Records) ->
lists:foreach(fun({_Name,Attr}) ->
io:fwrite(<<"~ts">>, [erl_pp:attribute(Attr, enc())])
end, Records).
record_defs(RT, Names) ->
lists:flatmap(fun(Name) -> ets:lookup(RT, Name)
end, Names).
expand_value(E) ->
substitute_v1(fun({value,CommandN,V}) -> try_abstract(V, CommandN)
end, E).
try_abstract(V, CommandN) ->
try erl_parse:abstract(V)
catch
_:_ ->
A = a0(),
{call,A,{atom,A,v},[{integer,A,CommandN}]}
end.
prep_list_commands(E) ->
A = a0(),
substitute_v1(fun({value,Anno,_V}) ->
CommandN = erl_anno:line(Anno),
{call,A,{atom,A,v},[{integer,A,CommandN}]}
end, E).
substitute_v1(F, {value,_,_}=Value) ->
F(Value);
substitute_v1(F, T) when is_tuple(T) ->
list_to_tuple(substitute_v1(F, tuple_to_list(T)));
substitute_v1(F, [E | Es]) ->
[substitute_v1(F, E) | substitute_v1(F, Es)];
substitute_v1(_F, E) ->
E.
a0() ->
erl_anno:new(0).
pos({Line,Col}) ->
io_lib:format("~w:~w", [Line,Col]);
pos(Line) ->
io_lib:format("~w", [Line]).
check_and_get_history_and_results() ->
check_env(shell_history_length),
check_env(shell_saved_results),
get_history_and_results().
get_history_and_results() ->
History = get_env(shell_history_length, ?DEF_HISTORY),
Results = get_env(shell_saved_results, ?DEF_RESULTS),
{History, erlang:min(Results, History)}.
pp(V, I, RT) ->
pp(V, I, _Depth=?LINEMAX, RT).
pp(V, I, D, RT) ->
Strings = application:get_env(stdlib, shell_strings, true) =/= false,
io_lib_pretty:print(V, ([{column, I}, {line_length, columns()},
{depth, D}, {line_max_chars, ?CHAR_MAX},
{strings, Strings},
{record_print_fun, record_print_fun(RT)}]
++ enc())).
columns() ->
case io:columns() of
{ok,N} -> N;
_ -> 80
end.
encoding() ->
[{encoding, Encoding}] = enc(),
Encoding.
enc() ->
case lists:keyfind(encoding, 1, io:getopts()) of
Enc -> [Enc]
end.
garb(Shell) ->
erlang:garbage_collect(Shell),
catch erlang:garbage_collect(whereis(user)),
catch erlang:garbage_collect(group_leader()),
erlang:garbage_collect().
get_env(V, Def) ->
case application:get_env(stdlib, V, Def) of
Val when is_integer(Val), Val >= 0 ->
Val;
_ ->
Def
end.
check_env(V) ->
case application:get_env(stdlib, V, 0) of
Val when is_integer(Val), Val >= 0 ->
ok;
Val ->
Txt = io_lib:fwrite
("Invalid value of STDLIB configuration parameter"
"~tw: ~tp\n", [V, Val]),
error_logger:info_report(lists:flatten(Txt))
end.
set_env(App, Name, Val, Default) ->
Prev = case application:get_env(App, Name) of
undefined ->
Default;
{ok, Old} ->
Old
end,
application_controller:set_env(App, Name, Val),
Prev.
-spec history(N) -> non_neg_integer() when
N :: non_neg_integer().
history(L) when is_integer(L), L >= 0 ->
set_env(stdlib, shell_history_length, L, ?DEF_HISTORY).
-spec results(N) -> non_neg_integer() when
N :: non_neg_integer().
results(L) when is_integer(L), L >= 0 ->
set_env(stdlib, shell_saved_results, L, ?DEF_RESULTS).
-spec catch_exception(Bool) -> boolean() when
Bool :: boolean().
catch_exception(Bool) ->
set_env(stdlib, shell_catch_exception, Bool, ?DEF_CATCH_EXCEPTION).
-spec prompt_func(PromptFunc) -> PromptFunc2 when
PromptFunc :: 'default' | {module(),atom()},
PromptFunc2 :: 'default' | {module(),atom()}.
prompt_func(PromptFunc) ->
set_env(stdlib, shell_prompt_func, PromptFunc, ?DEF_PROMPT_FUNC).
-spec strings(Strings) -> Strings2 when
Strings :: boolean(),
Strings2 :: boolean().
strings(Strings) ->
set_env(stdlib, shell_strings, Strings, ?DEF_STRINGS).
|
747562a3b26fde3504f97a0d2a1600f14e189e103c8f53429eccc583d9ab79f1
|
dinosaure/bob
|
stream.ml
|
Copyright ( c ) 2020 >
Copyright ( c ) 2022 < >
Permission to use , copy , modify , and 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
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 .
): stream + fiber . The [ Lwt_stream ] is too bad and we have
an opportunity to do one on our own way . Thanks to rizo for the start .
Again , the limitation is the higher kind polymorphism where we need to
modify the code to put the [ Fiber.t ] into all retunred values .
Copyright (c) 2022 Romain Calascibetta <>
Permission to use, copy, modify, and 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.
XXX(dinosaure): stream + fiber. The [Lwt_stream] is too bad and we have
an opportunity to do one on our own way. Thanks to rizo for the start.
Again, the limitation is the higher kind polymorphism where we need to
modify the code to put the [Fiber.t] into all retunred values.
*)
open Stdbob
open Fiber
let src = Logs.Src.create "bob.stream"
module Log = (val Logs.src_log src : Logs.LOG)
type 'a source =
| Source : {
init : unit -> 's Fiber.t;
pull : 's -> ('a * 's) option Fiber.t;
stop : 's -> unit Fiber.t;
}
-> 'a source
module Source = struct
let file ?offset path =
let init () =
Fiber.openfile path Unix.[ O_RDONLY ] 0o644 >>= function
| Error errno ->
Fmt.failwith "openfile(%a): %s" Bob_fpath.pp path
(Unix.error_message errno)
| Ok fd -> (
match offset with
| None -> Fiber.return fd
| Some offset ->
let _ = Unix.LargeFile.lseek fd offset Unix.SEEK_SET in
Fiber.return fd)
in
let stop fd = Fiber.close fd in
let pull fd =
Fiber.read fd >>= function
| Ok `End -> Fiber.return None
| Ok (`Data str) -> Fiber.return (Some (str, fd))
| Error errno ->
Fmt.failwith "read(%d|%a): %s" (Obj.magic fd) Bob_fpath.pp path
(Unix.error_message errno)
in
Source { init; stop; pull }
let array arr =
let len = Array.length arr in
let pull i =
if i >= len then Fiber.return None
else Fiber.return (Some (arr.(i), succ i))
in
Source { init = Fiber.always 0; pull; stop = Fiber.ignore }
let list lst =
let pull = function
| [] -> Fiber.return None
| x :: r -> Fiber.return (Some (x, r))
in
Source { init = Fiber.always lst; pull; stop = Fiber.ignore }
let fold f r0 (Source src) =
let rec go r s =
src.pull s >>= function
| None -> Fiber.return r
| Some (a, s') -> f r a >>= fun a -> go a s'
in
src.init () >>= fun s0 ->
Fiber.catch
(fun () ->
go r0 s0 >>= fun r ->
src.stop s0 >>= fun () -> Fiber.return r)
(fun exn -> src.stop s0 >>= fun () -> raise exn)
let length src = fold (fun count _ -> Fiber.return (succ count)) 0 src
let unfold seed pull =
Source { init = Fiber.always seed; pull; stop = (fun _ -> Fiber.return ()) }
let iterate ~f x =
unfold x (fun x -> f x >>= fun acc -> Fiber.return (Some (x, acc)))
let next (Source src) =
let go s =
src.pull s >>| function
| Some (x, s') -> Some (x, Source { src with init = Fiber.always s' })
| None -> None
in
src.init () >>= fun s0 ->
Fiber.catch
(fun () -> go s0)
(fun exn -> src.stop s0 >>= fun () -> raise exn)
let prepend v (Source source) =
let init () = Fiber.return (`Pre v) in
let pull = function
| `Pre v -> source.init () >>= fun r -> Fiber.return (Some (v, `Src r))
| `Src r -> (
source.pull r >>= function
| Some (v, r) -> Fiber.return (Some (v, `Src r))
| None -> Fiber.return None)
in
let stop = function `Pre _ -> Fiber.return () | `Src r -> source.stop r in
Source { init; pull; stop }
let dispose (Source src) = src.init () >>= src.stop
end
type ('a, 'r) sink =
| Sink : {
init : unit -> 's Fiber.t;
push : 's -> 'a -> 's Fiber.t;
full : 's -> bool Fiber.t;
stop : 's -> 'r Fiber.t;
}
-> ('a, 'r) sink
let rec full_write ~path fd bstr off len =
Fiber.write fd bstr ~off ~len >>= function
| Ok len' when len' - len = 0 -> Fiber.return fd
| Ok len' -> full_write ~path fd bstr (off + len') (len - len')
| Error `Closed ->
Log.err (fun m ->
m "%d (%a) was closed." (Obj.magic fd) Bob_fpath.pp path);
Fmt.failwith "Unexpected closed fd %d (%a)" (Obj.magic fd) Bob_fpath.pp
path
| Error (`Unix errno) ->
Log.err (fun m ->
m "Got an error when we tried to write into %d (%a): %s"
(Obj.magic fd) Bob_fpath.pp path (Unix.error_message errno));
Fmt.failwith "write(%d|%a): %s" (Obj.magic fd) Bob_fpath.pp path
(Unix.error_message errno)
module Sink = struct
let make ~init ~push ?(full = Fiber.always false) ~stop () =
Sink { init; push; full; stop }
let list =
let init () = Fiber.return [] in
let push acc x = Fiber.return (x :: acc) in
let full _ = Fiber.return false in
let stop acc = Fiber.return (List.rev acc) in
Sink { init; push; full; stop }
let string =
let init () = Fiber.return (Buffer.create 128) in
let push buf str =
Buffer.add_string buf str;
Fiber.return buf
in
let full = Fiber.always false in
let stop buf = Fiber.return (Buffer.contents buf) in
Sink { init; push; full; stop }
let array =
let init () = Fiber.return [] in
let push acc x = Fiber.return (x :: acc) in
let full _ = Fiber.return false in
let stop acc =
match acc with
| [] -> Fiber.return [||]
| [ x ] -> Fiber.return [| x |]
| _ -> Fiber.return (Array.of_list acc)
in
Sink { init; push; full; stop }
let zip (Sink l) (Sink r) =
let init () =
l.init () >>= fun l_acc ->
r.init () >>= fun r_acc -> Fiber.return (l_acc, r_acc)
in
let push (l_acc, r_acc) x =
l.push l_acc x >>= fun l_acc ->
r.push r_acc x >>= fun r_acc -> Fiber.return (l_acc, r_acc)
in
let full (l_acc, r_acc) =
l.full l_acc >>= fun lb ->
r.full r_acc >>= fun rb -> Fiber.return (lb || rb)
in
let stop (l_acc, r_acc) =
l.stop l_acc >>= fun l_ret ->
r.stop r_acc >>= fun r_ret -> Fiber.return (l_ret, r_ret)
in
Sink { init; push; full; stop }
type ('top, 'a, 'b) flat_map =
| Flat_map_top : 'top -> ('top, 'a, 'b) flat_map
| Flat_map_sub : {
init : 'sub;
push : 'sub -> 'a -> 'sub Fiber.t;
full : 'sub -> bool Fiber.t;
stop : 'sub -> 'b Fiber.t;
}
-> ('top, 'a, 'b) flat_map
let flat_map f (Sink top) =
let init () = top.init () >>| fun top -> Flat_map_top top in
let push s x =
match s with
| Flat_map_sub sub ->
sub.push sub.init x >>| fun init -> Flat_map_sub { sub with init }
| Flat_map_top acc -> (
top.push acc x >>= fun acc' ->
top.full acc' >>= function
| false -> Fiber.return (Flat_map_top acc')
| true ->
top.stop acc' >>= f >>= fun (Sink sub) ->
sub.init () >>| fun init ->
Flat_map_sub
{ init; push = sub.push; full = sub.full; stop = sub.stop })
in
let full = function
| Flat_map_top acc -> top.full acc
| Flat_map_sub sub -> sub.full sub.init
in
let stop = function
| Flat_map_top acc ->
top.stop acc >>= f >>= fun (Sink sub) -> sub.init () >>= sub.stop
| Flat_map_sub sub -> sub.stop sub.init
in
Sink { init; push; full; stop }
let fill v =
Sink
{
init = Fiber.always ();
push = (fun () _ -> Fiber.return ());
full = Fiber.always true;
stop = Fiber.always v;
}
type ('a, 'b) race = Both of 'a * 'b | Left of 'a | Right of 'b
let race (Sink l) (Sink r) =
let init () =
l.init () >>= fun l_acc ->
r.init () >>= fun r_acc -> Fiber.return (Both (l_acc, r_acc))
in
let push state x =
match state with
| Left _ | Right _ -> Fmt.invalid_arg "One of the sinks is already filled"
| Both (l_acc, r_acc) -> (
l.push l_acc x >>= fun l_acc' ->
r.push r_acc x >>= fun r_acc' ->
l.full l_acc' >>= fun l_full ->
r.full r_acc' >>= fun r_full ->
match (l_full, r_full) with
| true, _ -> Fiber.return (Right r_acc')
| false, true -> Fiber.return (Left l_acc')
| false, false -> Fiber.return (Both (l_acc', r_acc')))
in
let full = function
| Both _ -> Fiber.return false
| _ -> Fiber.return true
in
let stop = function
| Left l_acc -> l.stop l_acc >>| fun l -> Left l
| Right r_acc -> r.stop r_acc >>| fun r -> Right r
| Both (l_acc, r_acc) ->
l.stop l_acc >>= fun l ->
r.stop r_acc >>= fun r -> Fiber.return (Both (l, r))
in
Sink { init; push; full; stop }
let bigstring =
let init () = Fiber.return (Qe.create 128) in
let push ke bstr =
Qe.push ke bstr;
Fiber.return ke
in
let full = Fiber.always false in
let stop ke =
match Qe.peek ke with
| [] -> Fiber.return De.bigstring_empty
| [ x ] -> Fiber.return x
| _ ->
Log.err (fun m ->
m "Too many elements returned by our internal queue.");
assert false
in
Sink { init; push; full; stop }
let to_string =
let init () = Fiber.return (Buffer.create 0x100) in
let push buf bstr =
Buffer.add_string buf (bigstring_to_string bstr);
Fiber.return buf
in
let full = Fiber.always false in
let stop buf = Fiber.return (Buffer.contents buf) in
Sink { init; push; full; stop }
let is_full (Sink k) = k.init () >>= k.full
let push x (Sink k) =
Sink { k with init = (fun () -> k.init () >>= fun acc -> k.push acc x) }
let file ?(erase = true) path =
let init () =
let flags = Unix.[ O_WRONLY; O_APPEND; O_CREAT ] in
let flags = if erase then Unix.O_TRUNC :: flags else flags in
Fiber.openfile path flags 0o644 >>= function
| Ok fd -> Fiber.return fd
| Error errno ->
Fmt.failwith "openfile(%a): %s" Bob_fpath.pp path
(Unix.error_message errno)
in
let stop fd = Fiber.close fd in
let push fd bstr = full_write ~path fd bstr 0 (Bigarray.Array1.dim bstr) in
let full = Fiber.always false in
Sink { init; stop; full; push }
let stdout =
let init () = Fiber.return () in
let push () bstr =
full_write ~path:(Bob_fpath.v "<stdout>") Unix.stdout bstr 0
(Bigarray.Array1.dim bstr)
>>= fun _stdout -> Fiber.return ()
in
let full = Fiber.always false in
let stop () = Fiber.return () in
Sink { init; push; full; stop }
let first =
Sink
{
init = (fun () -> Fiber.return None);
push = (fun _ x -> Fiber.return (Some x));
full =
(function None -> Fiber.return false | Some _ -> Fiber.return true);
stop = Fiber.return;
}
end
type ('a, 'b) flow = { flow : 'r. ('b, 'r) sink -> ('a, 'r) sink } [@@unboxed]
module Flow = struct
let identity = { flow = identity }
let compose { flow = f } { flow = g } = { flow = (fun sink -> f (g sink)) }
let ( << ) a b = compose a b
let ( >> ) b a = compose a b
let map f =
let flow (Sink k) =
let push r x = f x >>= k.push r in
Sink { k with push }
in
{ flow }
let filter_map f =
let flow (Sink k) =
let push r x =
f x >>= function Some x' -> k.push r x' | None -> Fiber.return r
in
Sink { k with push }
in
{ flow }
let tap f =
let flow (Sink k) =
let push r x = f x >>= fun () -> k.push r x in
Sink { k with push }
in
{ flow }
Zlib
let rec deflate_zlib_until_end ~push ~acc encoder o =
match Zl.Def.encode encoder with
| `Await _ -> assert false
| `Flush encoder ->
let len = Bigarray.Array1.dim o - Zl.Def.dst_rem encoder in
let encoder = Zl.Def.dst encoder o 0 (Bigarray.Array1.dim o) in
push acc (Bigarray.Array1.sub o 0 len) >>= fun acc ->
deflate_zlib_until_end ~push ~acc encoder o
| `End encoder ->
let len = Bigarray.Array1.dim o - Zl.Def.dst_rem encoder in
push acc (Bigarray.Array1.sub o 0 len)
let rec deflate_zlib_until_await ~push ~acc encoder o =
match Zl.Def.encode encoder with
| `Await encoder -> Fiber.return (encoder, o, acc)
| `Flush encoder ->
let len = Bigarray.Array1.dim o - Zl.Def.dst_rem encoder in
let encoder = Zl.Def.dst encoder o 0 (Bigarray.Array1.dim o) in
push acc (Bigarray.Array1.sub o 0 len) >>= fun acc ->
deflate_zlib_until_await ~push ~acc encoder o
| `End _ -> assert false
let deflate_zlib ?(len = Stdbob.io_buffer_size) ~q ~w level =
let flow (Sink k) =
let init () =
let encoder = Zl.Def.encoder ~q ~w ~level `Manual `Manual in
let o = De.bigstring_create len in
let encoder = Zl.Def.dst encoder o 0 len in
k.init () >>= fun acc -> Fiber.return (encoder, o, acc)
in
let push (encoder, o, acc) i =
if Bigarray.Array1.dim i = 0 then Fiber.return (encoder, o, acc)
else
deflate_zlib_until_await ~push:k.push ~acc
(Zl.Def.src encoder i 0 (Bigarray.Array1.dim i))
o
in
let full (_, _, acc) = k.full acc in
let stop (encoder, o, acc) =
deflate_zlib_until_end ~push:k.push ~acc
(Zl.Def.src encoder De.bigstring_empty 0 0)
o
>>= k.stop
in
Sink { init; stop; full; push }
in
{ flow }
let save_into ?offset path =
let flow (Sink k) =
let init () =
let flags = Unix.[ O_WRONLY; O_CREAT ] in
let flags =
if Stdlib.Option.is_some offset then flags else Unix.O_APPEND :: flags
in
Fiber.openfile path flags 0o644 >>= function
| Error errno ->
Fmt.failwith "openfile(%a): %s" Bob_fpath.pp path
(Unix.error_message errno)
| Ok fd -> (
match offset with
| Some offset ->
let _ = Unix.LargeFile.lseek fd offset Unix.SEEK_END in
k.init () >>= fun acc -> Fiber.return (fd, acc)
| None -> k.init () >>= fun acc -> Fiber.return (fd, acc))
in
let push (fd, acc) bstr =
full_write ~path fd bstr 0 (Bigarray.Array1.dim bstr) >>= fun fd ->
k.push acc bstr >>= fun acc -> Fiber.return (fd, acc)
in
let full (_, acc) = k.full acc in
let stop (fd, acc) = Fiber.close fd >>= fun () -> k.stop acc in
Sink { init; stop; full; push }
in
{ flow }
let with_digest :
type ctx.
(module Digestif.S with type ctx = ctx) ->
ctx ref ->
(Stdbob.bigstring, Stdbob.bigstring) flow =
fun (module Digestif) ctx ->
let flow (Sink k) =
let init () = k.init () in
let push acc bstr =
k.push acc bstr >>= fun acc ->
k.full acc >>= function
| true -> Fiber.return acc
| false ->
Log.debug (fun m -> m "Digest:");
Log.debug (fun m ->
m "@[<hov>%a@]"
(Hxd_string.pp Hxd.default)
(Stdbob.bigstring_to_string bstr));
ctx := Digestif.feed_bigstring !ctx bstr;
Fiber.return acc
in
let full acc = k.full acc in
let stop acc = k.stop acc in
Sink { init; stop; full; push }
in
{ flow }
end
type 'a stream = { stream : 'r. ('a, 'r) sink -> 'r Fiber.t } [@@unboxed]
let bracket :
init:(unit -> 's Fiber.t) ->
stop:('s -> 'r Fiber.t) ->
('s -> 's Fiber.t) ->
'r Fiber.t =
fun ~init ~stop f ->
init () >>= fun acc ->
Fiber.catch
(fun () -> f acc >>= stop)
(fun exn -> stop acc >>= fun _ -> raise exn)
module Stream = struct
let run ~from:(Source src) ~via:{ flow } ~into:snk =
let (Sink snk) = flow snk in
let rec loop r s =
snk.full r >>= function
| true ->
snk.stop r >>= fun r' ->
let leftover =
Source { src with init = (fun () -> Fiber.return s) }
in
Fiber.return (r', Some leftover)
| false -> (
src.pull s >>= function
| Some (x, s') -> snk.push r x >>= fun r' -> loop r' s'
| None ->
src.stop s >>= fun () ->
snk.stop r >>= fun r' -> Fiber.return (r', None))
in
snk.init () >>= fun r0 ->
snk.full r0 >>= function
| true -> snk.stop r0 >>= fun r' -> Fiber.return (r', Some (Source src))
| false ->
Fiber.catch
(fun () -> src.init ())
(fun exn -> snk.stop r0 >>= fun _ -> raise exn)
>>= fun s0 ->
Fiber.catch
(fun () -> loop r0 s0)
(fun exn ->
src.stop s0 >>= fun () ->
snk.stop r0 >>= fun _r' -> raise exn)
(* Composition *)
let into sink t = t.stream sink
let via { flow } t =
let stream sink = into (flow sink) t in
{ stream }
let from (Source src) =
let stream (Sink k) =
let rec go r s =
k.full r >>= function
| true -> k.stop r
| false -> (
src.pull s >>= function
| None -> src.stop s >>= fun () -> k.stop r
| Some (x, s') -> k.push r x >>= fun r -> go r s')
in
k.init () >>= fun r0 ->
k.full r0 >>= function
| true -> k.stop r0
| false ->
Fiber.catch
(fun () -> src.init ())
(fun exn -> k.stop r0 >>= fun _ -> raise exn)
>>= fun s0 ->
Fiber.catch
(fun () -> go r0 s0)
(fun exn ->
src.stop s0 >>= fun () ->
k.stop r0 >>= fun _ -> raise exn)
in
{ stream }
(* Basics *)
let concat a b =
let stream (Sink k) =
let stop r =
k.full r >>= function
| true -> k.stop r
| false -> b.stream (Sink { k with init = (fun () -> Fiber.return r) })
in
a.stream (Sink { k with stop })
in
{ stream }
let flat_map f t =
let stream (Sink k) =
let push r x =
f x >>= fun { stream } ->
stream
(Sink
{
k with
init = (fun () -> Fiber.return r);
stop = (fun r -> Fiber.return r);
})
in
t.stream (Sink { k with push })
in
{ stream }
let empty =
let stream (Sink k) = k.init () >>= k.stop in
{ stream }
let singleton v =
let stream (Sink k) = k.init () >>= fun acc -> k.push acc v >>= k.stop in
{ stream }
let double a b =
let stream (Sink k) =
k.init () >>= fun acc ->
k.push acc a >>= fun acc -> k.push acc b >>= k.stop
in
{ stream }
let map f t = via (Flow.map f) t
let filter_map f t = via (Flow.filter_map f) t
let tap f t = via (Flow.tap f) t
let of_fiber f =
let stream (Sink k) =
k.init () >>= fun acc -> f () >>= k.push acc >>= k.stop
in
{ stream }
let of_iter iter =
let exception Stop in
let stream (Sink k) =
let go r =
k.full r >>= function
| true -> Fiber.return r
| false ->
let acc = ref r in
Fiber.catch
(fun () ->
iter (fun x ->
k.push !acc x >>= fun acc' ->
acc := acc';
k.full !acc >>= function
| true -> raise Stop
| false -> Fiber.return ())
>>= fun () -> Fiber.return !acc)
(function Stop -> Fiber.return !acc | exn -> raise exn)
in
bracket go ~init:k.init ~stop:k.stop
in
{ stream }
let to_list t = into Sink.list t
let of_list lst =
let stream (Sink k) =
let rec go s r =
k.full r >>= function
| true -> Fiber.return r
| false -> (
match s with
| [] -> Fiber.return r
| x :: s' -> k.push r x >>= go s')
in
bracket (go lst) ~init:k.init ~stop:k.stop
in
{ stream }
let to_array stream = into Sink.array stream
let of_array arr = from (Source.array arr)
let to_bigstring stream = into Sink.bigstring stream
let to_string stream = into Sink.string stream
let iterate ~f x = from (Source.iterate ~f x)
(* Input & Output *)
let of_file ?(len = Stdbob.io_buffer_size) path =
Fiber.openfile path Unix.[ O_RDONLY ] 0o644 >>= function
| Error errno ->
Fiber.return
(Error
(msgf "openfile(%a): %s" Bob_fpath.pp path
(Unix.error_message errno)))
| Ok fd ->
let stream (Sink k) =
let rec go r =
k.full r >>= function
| true ->
Log.debug (fun m ->
m "The given sink is full, stop to read into: %a."
Bob_fpath.pp path);
Fiber.return r
| false -> (
Fiber.read ~len fd >>= function
| Ok `End ->
Log.debug (fun m ->
m "End of the file: %a" Bob_fpath.pp path);
Fiber.return r
| Ok (`Data bstr) -> k.push r bstr >>= go
| Error errno ->
Fmt.failwith "read(%d:%a): %s" (Obj.magic fd) Bob_fpath.pp
path (Unix.error_message errno))
in
let stop r =
Log.debug (fun m -> m "Close the file %a." Bob_fpath.pp path);
Fiber.close fd >>= fun () -> k.stop r
in
bracket go ~init:k.init ~stop
in
Fiber.return (Ok { stream })
let stdin =
let stream (Sink k) =
let rec go r =
k.full r >>= function
| true -> Fiber.return r
| false -> (
Fiber.read Unix.stdin >>= function
| Ok `End -> Fiber.return r
| Ok (`Data bstr) -> k.push r bstr >>= go
| Error errno ->
Fmt.failwith "read(<stdin>): %s" (Unix.error_message errno))
in
bracket go ~init:k.init ~stop:k.stop
in
{ stream }
let to_file path = into (Sink.file path)
let stdout = into Sink.stdout
let ( >>= ) x f = flat_map f x
let ( ++ ) = concat
end
| null |
https://raw.githubusercontent.com/dinosaure/bob/210dce2f3f7bfe1b15472a7d09544b4afbac8ca6/lib/stream.ml
|
ocaml
|
Composition
Basics
Input & Output
|
Copyright ( c ) 2020 >
Copyright ( c ) 2022 < >
Permission to use , copy , modify , and 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
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 .
): stream + fiber . The [ Lwt_stream ] is too bad and we have
an opportunity to do one on our own way . Thanks to rizo for the start .
Again , the limitation is the higher kind polymorphism where we need to
modify the code to put the [ Fiber.t ] into all retunred values .
Copyright (c) 2022 Romain Calascibetta <>
Permission to use, copy, modify, and 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.
XXX(dinosaure): stream + fiber. The [Lwt_stream] is too bad and we have
an opportunity to do one on our own way. Thanks to rizo for the start.
Again, the limitation is the higher kind polymorphism where we need to
modify the code to put the [Fiber.t] into all retunred values.
*)
open Stdbob
open Fiber
let src = Logs.Src.create "bob.stream"
module Log = (val Logs.src_log src : Logs.LOG)
type 'a source =
| Source : {
init : unit -> 's Fiber.t;
pull : 's -> ('a * 's) option Fiber.t;
stop : 's -> unit Fiber.t;
}
-> 'a source
module Source = struct
let file ?offset path =
let init () =
Fiber.openfile path Unix.[ O_RDONLY ] 0o644 >>= function
| Error errno ->
Fmt.failwith "openfile(%a): %s" Bob_fpath.pp path
(Unix.error_message errno)
| Ok fd -> (
match offset with
| None -> Fiber.return fd
| Some offset ->
let _ = Unix.LargeFile.lseek fd offset Unix.SEEK_SET in
Fiber.return fd)
in
let stop fd = Fiber.close fd in
let pull fd =
Fiber.read fd >>= function
| Ok `End -> Fiber.return None
| Ok (`Data str) -> Fiber.return (Some (str, fd))
| Error errno ->
Fmt.failwith "read(%d|%a): %s" (Obj.magic fd) Bob_fpath.pp path
(Unix.error_message errno)
in
Source { init; stop; pull }
let array arr =
let len = Array.length arr in
let pull i =
if i >= len then Fiber.return None
else Fiber.return (Some (arr.(i), succ i))
in
Source { init = Fiber.always 0; pull; stop = Fiber.ignore }
let list lst =
let pull = function
| [] -> Fiber.return None
| x :: r -> Fiber.return (Some (x, r))
in
Source { init = Fiber.always lst; pull; stop = Fiber.ignore }
let fold f r0 (Source src) =
let rec go r s =
src.pull s >>= function
| None -> Fiber.return r
| Some (a, s') -> f r a >>= fun a -> go a s'
in
src.init () >>= fun s0 ->
Fiber.catch
(fun () ->
go r0 s0 >>= fun r ->
src.stop s0 >>= fun () -> Fiber.return r)
(fun exn -> src.stop s0 >>= fun () -> raise exn)
let length src = fold (fun count _ -> Fiber.return (succ count)) 0 src
let unfold seed pull =
Source { init = Fiber.always seed; pull; stop = (fun _ -> Fiber.return ()) }
let iterate ~f x =
unfold x (fun x -> f x >>= fun acc -> Fiber.return (Some (x, acc)))
let next (Source src) =
let go s =
src.pull s >>| function
| Some (x, s') -> Some (x, Source { src with init = Fiber.always s' })
| None -> None
in
src.init () >>= fun s0 ->
Fiber.catch
(fun () -> go s0)
(fun exn -> src.stop s0 >>= fun () -> raise exn)
let prepend v (Source source) =
let init () = Fiber.return (`Pre v) in
let pull = function
| `Pre v -> source.init () >>= fun r -> Fiber.return (Some (v, `Src r))
| `Src r -> (
source.pull r >>= function
| Some (v, r) -> Fiber.return (Some (v, `Src r))
| None -> Fiber.return None)
in
let stop = function `Pre _ -> Fiber.return () | `Src r -> source.stop r in
Source { init; pull; stop }
let dispose (Source src) = src.init () >>= src.stop
end
type ('a, 'r) sink =
| Sink : {
init : unit -> 's Fiber.t;
push : 's -> 'a -> 's Fiber.t;
full : 's -> bool Fiber.t;
stop : 's -> 'r Fiber.t;
}
-> ('a, 'r) sink
let rec full_write ~path fd bstr off len =
Fiber.write fd bstr ~off ~len >>= function
| Ok len' when len' - len = 0 -> Fiber.return fd
| Ok len' -> full_write ~path fd bstr (off + len') (len - len')
| Error `Closed ->
Log.err (fun m ->
m "%d (%a) was closed." (Obj.magic fd) Bob_fpath.pp path);
Fmt.failwith "Unexpected closed fd %d (%a)" (Obj.magic fd) Bob_fpath.pp
path
| Error (`Unix errno) ->
Log.err (fun m ->
m "Got an error when we tried to write into %d (%a): %s"
(Obj.magic fd) Bob_fpath.pp path (Unix.error_message errno));
Fmt.failwith "write(%d|%a): %s" (Obj.magic fd) Bob_fpath.pp path
(Unix.error_message errno)
module Sink = struct
let make ~init ~push ?(full = Fiber.always false) ~stop () =
Sink { init; push; full; stop }
let list =
let init () = Fiber.return [] in
let push acc x = Fiber.return (x :: acc) in
let full _ = Fiber.return false in
let stop acc = Fiber.return (List.rev acc) in
Sink { init; push; full; stop }
let string =
let init () = Fiber.return (Buffer.create 128) in
let push buf str =
Buffer.add_string buf str;
Fiber.return buf
in
let full = Fiber.always false in
let stop buf = Fiber.return (Buffer.contents buf) in
Sink { init; push; full; stop }
let array =
let init () = Fiber.return [] in
let push acc x = Fiber.return (x :: acc) in
let full _ = Fiber.return false in
let stop acc =
match acc with
| [] -> Fiber.return [||]
| [ x ] -> Fiber.return [| x |]
| _ -> Fiber.return (Array.of_list acc)
in
Sink { init; push; full; stop }
let zip (Sink l) (Sink r) =
let init () =
l.init () >>= fun l_acc ->
r.init () >>= fun r_acc -> Fiber.return (l_acc, r_acc)
in
let push (l_acc, r_acc) x =
l.push l_acc x >>= fun l_acc ->
r.push r_acc x >>= fun r_acc -> Fiber.return (l_acc, r_acc)
in
let full (l_acc, r_acc) =
l.full l_acc >>= fun lb ->
r.full r_acc >>= fun rb -> Fiber.return (lb || rb)
in
let stop (l_acc, r_acc) =
l.stop l_acc >>= fun l_ret ->
r.stop r_acc >>= fun r_ret -> Fiber.return (l_ret, r_ret)
in
Sink { init; push; full; stop }
type ('top, 'a, 'b) flat_map =
| Flat_map_top : 'top -> ('top, 'a, 'b) flat_map
| Flat_map_sub : {
init : 'sub;
push : 'sub -> 'a -> 'sub Fiber.t;
full : 'sub -> bool Fiber.t;
stop : 'sub -> 'b Fiber.t;
}
-> ('top, 'a, 'b) flat_map
let flat_map f (Sink top) =
let init () = top.init () >>| fun top -> Flat_map_top top in
let push s x =
match s with
| Flat_map_sub sub ->
sub.push sub.init x >>| fun init -> Flat_map_sub { sub with init }
| Flat_map_top acc -> (
top.push acc x >>= fun acc' ->
top.full acc' >>= function
| false -> Fiber.return (Flat_map_top acc')
| true ->
top.stop acc' >>= f >>= fun (Sink sub) ->
sub.init () >>| fun init ->
Flat_map_sub
{ init; push = sub.push; full = sub.full; stop = sub.stop })
in
let full = function
| Flat_map_top acc -> top.full acc
| Flat_map_sub sub -> sub.full sub.init
in
let stop = function
| Flat_map_top acc ->
top.stop acc >>= f >>= fun (Sink sub) -> sub.init () >>= sub.stop
| Flat_map_sub sub -> sub.stop sub.init
in
Sink { init; push; full; stop }
let fill v =
Sink
{
init = Fiber.always ();
push = (fun () _ -> Fiber.return ());
full = Fiber.always true;
stop = Fiber.always v;
}
type ('a, 'b) race = Both of 'a * 'b | Left of 'a | Right of 'b
let race (Sink l) (Sink r) =
let init () =
l.init () >>= fun l_acc ->
r.init () >>= fun r_acc -> Fiber.return (Both (l_acc, r_acc))
in
let push state x =
match state with
| Left _ | Right _ -> Fmt.invalid_arg "One of the sinks is already filled"
| Both (l_acc, r_acc) -> (
l.push l_acc x >>= fun l_acc' ->
r.push r_acc x >>= fun r_acc' ->
l.full l_acc' >>= fun l_full ->
r.full r_acc' >>= fun r_full ->
match (l_full, r_full) with
| true, _ -> Fiber.return (Right r_acc')
| false, true -> Fiber.return (Left l_acc')
| false, false -> Fiber.return (Both (l_acc', r_acc')))
in
let full = function
| Both _ -> Fiber.return false
| _ -> Fiber.return true
in
let stop = function
| Left l_acc -> l.stop l_acc >>| fun l -> Left l
| Right r_acc -> r.stop r_acc >>| fun r -> Right r
| Both (l_acc, r_acc) ->
l.stop l_acc >>= fun l ->
r.stop r_acc >>= fun r -> Fiber.return (Both (l, r))
in
Sink { init; push; full; stop }
let bigstring =
let init () = Fiber.return (Qe.create 128) in
let push ke bstr =
Qe.push ke bstr;
Fiber.return ke
in
let full = Fiber.always false in
let stop ke =
match Qe.peek ke with
| [] -> Fiber.return De.bigstring_empty
| [ x ] -> Fiber.return x
| _ ->
Log.err (fun m ->
m "Too many elements returned by our internal queue.");
assert false
in
Sink { init; push; full; stop }
let to_string =
let init () = Fiber.return (Buffer.create 0x100) in
let push buf bstr =
Buffer.add_string buf (bigstring_to_string bstr);
Fiber.return buf
in
let full = Fiber.always false in
let stop buf = Fiber.return (Buffer.contents buf) in
Sink { init; push; full; stop }
let is_full (Sink k) = k.init () >>= k.full
let push x (Sink k) =
Sink { k with init = (fun () -> k.init () >>= fun acc -> k.push acc x) }
let file ?(erase = true) path =
let init () =
let flags = Unix.[ O_WRONLY; O_APPEND; O_CREAT ] in
let flags = if erase then Unix.O_TRUNC :: flags else flags in
Fiber.openfile path flags 0o644 >>= function
| Ok fd -> Fiber.return fd
| Error errno ->
Fmt.failwith "openfile(%a): %s" Bob_fpath.pp path
(Unix.error_message errno)
in
let stop fd = Fiber.close fd in
let push fd bstr = full_write ~path fd bstr 0 (Bigarray.Array1.dim bstr) in
let full = Fiber.always false in
Sink { init; stop; full; push }
let stdout =
let init () = Fiber.return () in
let push () bstr =
full_write ~path:(Bob_fpath.v "<stdout>") Unix.stdout bstr 0
(Bigarray.Array1.dim bstr)
>>= fun _stdout -> Fiber.return ()
in
let full = Fiber.always false in
let stop () = Fiber.return () in
Sink { init; push; full; stop }
let first =
Sink
{
init = (fun () -> Fiber.return None);
push = (fun _ x -> Fiber.return (Some x));
full =
(function None -> Fiber.return false | Some _ -> Fiber.return true);
stop = Fiber.return;
}
end
type ('a, 'b) flow = { flow : 'r. ('b, 'r) sink -> ('a, 'r) sink } [@@unboxed]
module Flow = struct
let identity = { flow = identity }
let compose { flow = f } { flow = g } = { flow = (fun sink -> f (g sink)) }
let ( << ) a b = compose a b
let ( >> ) b a = compose a b
let map f =
let flow (Sink k) =
let push r x = f x >>= k.push r in
Sink { k with push }
in
{ flow }
let filter_map f =
let flow (Sink k) =
let push r x =
f x >>= function Some x' -> k.push r x' | None -> Fiber.return r
in
Sink { k with push }
in
{ flow }
let tap f =
let flow (Sink k) =
let push r x = f x >>= fun () -> k.push r x in
Sink { k with push }
in
{ flow }
Zlib
let rec deflate_zlib_until_end ~push ~acc encoder o =
match Zl.Def.encode encoder with
| `Await _ -> assert false
| `Flush encoder ->
let len = Bigarray.Array1.dim o - Zl.Def.dst_rem encoder in
let encoder = Zl.Def.dst encoder o 0 (Bigarray.Array1.dim o) in
push acc (Bigarray.Array1.sub o 0 len) >>= fun acc ->
deflate_zlib_until_end ~push ~acc encoder o
| `End encoder ->
let len = Bigarray.Array1.dim o - Zl.Def.dst_rem encoder in
push acc (Bigarray.Array1.sub o 0 len)
let rec deflate_zlib_until_await ~push ~acc encoder o =
match Zl.Def.encode encoder with
| `Await encoder -> Fiber.return (encoder, o, acc)
| `Flush encoder ->
let len = Bigarray.Array1.dim o - Zl.Def.dst_rem encoder in
let encoder = Zl.Def.dst encoder o 0 (Bigarray.Array1.dim o) in
push acc (Bigarray.Array1.sub o 0 len) >>= fun acc ->
deflate_zlib_until_await ~push ~acc encoder o
| `End _ -> assert false
let deflate_zlib ?(len = Stdbob.io_buffer_size) ~q ~w level =
let flow (Sink k) =
let init () =
let encoder = Zl.Def.encoder ~q ~w ~level `Manual `Manual in
let o = De.bigstring_create len in
let encoder = Zl.Def.dst encoder o 0 len in
k.init () >>= fun acc -> Fiber.return (encoder, o, acc)
in
let push (encoder, o, acc) i =
if Bigarray.Array1.dim i = 0 then Fiber.return (encoder, o, acc)
else
deflate_zlib_until_await ~push:k.push ~acc
(Zl.Def.src encoder i 0 (Bigarray.Array1.dim i))
o
in
let full (_, _, acc) = k.full acc in
let stop (encoder, o, acc) =
deflate_zlib_until_end ~push:k.push ~acc
(Zl.Def.src encoder De.bigstring_empty 0 0)
o
>>= k.stop
in
Sink { init; stop; full; push }
in
{ flow }
let save_into ?offset path =
let flow (Sink k) =
let init () =
let flags = Unix.[ O_WRONLY; O_CREAT ] in
let flags =
if Stdlib.Option.is_some offset then flags else Unix.O_APPEND :: flags
in
Fiber.openfile path flags 0o644 >>= function
| Error errno ->
Fmt.failwith "openfile(%a): %s" Bob_fpath.pp path
(Unix.error_message errno)
| Ok fd -> (
match offset with
| Some offset ->
let _ = Unix.LargeFile.lseek fd offset Unix.SEEK_END in
k.init () >>= fun acc -> Fiber.return (fd, acc)
| None -> k.init () >>= fun acc -> Fiber.return (fd, acc))
in
let push (fd, acc) bstr =
full_write ~path fd bstr 0 (Bigarray.Array1.dim bstr) >>= fun fd ->
k.push acc bstr >>= fun acc -> Fiber.return (fd, acc)
in
let full (_, acc) = k.full acc in
let stop (fd, acc) = Fiber.close fd >>= fun () -> k.stop acc in
Sink { init; stop; full; push }
in
{ flow }
let with_digest :
type ctx.
(module Digestif.S with type ctx = ctx) ->
ctx ref ->
(Stdbob.bigstring, Stdbob.bigstring) flow =
fun (module Digestif) ctx ->
let flow (Sink k) =
let init () = k.init () in
let push acc bstr =
k.push acc bstr >>= fun acc ->
k.full acc >>= function
| true -> Fiber.return acc
| false ->
Log.debug (fun m -> m "Digest:");
Log.debug (fun m ->
m "@[<hov>%a@]"
(Hxd_string.pp Hxd.default)
(Stdbob.bigstring_to_string bstr));
ctx := Digestif.feed_bigstring !ctx bstr;
Fiber.return acc
in
let full acc = k.full acc in
let stop acc = k.stop acc in
Sink { init; stop; full; push }
in
{ flow }
end
type 'a stream = { stream : 'r. ('a, 'r) sink -> 'r Fiber.t } [@@unboxed]
let bracket :
init:(unit -> 's Fiber.t) ->
stop:('s -> 'r Fiber.t) ->
('s -> 's Fiber.t) ->
'r Fiber.t =
fun ~init ~stop f ->
init () >>= fun acc ->
Fiber.catch
(fun () -> f acc >>= stop)
(fun exn -> stop acc >>= fun _ -> raise exn)
module Stream = struct
let run ~from:(Source src) ~via:{ flow } ~into:snk =
let (Sink snk) = flow snk in
let rec loop r s =
snk.full r >>= function
| true ->
snk.stop r >>= fun r' ->
let leftover =
Source { src with init = (fun () -> Fiber.return s) }
in
Fiber.return (r', Some leftover)
| false -> (
src.pull s >>= function
| Some (x, s') -> snk.push r x >>= fun r' -> loop r' s'
| None ->
src.stop s >>= fun () ->
snk.stop r >>= fun r' -> Fiber.return (r', None))
in
snk.init () >>= fun r0 ->
snk.full r0 >>= function
| true -> snk.stop r0 >>= fun r' -> Fiber.return (r', Some (Source src))
| false ->
Fiber.catch
(fun () -> src.init ())
(fun exn -> snk.stop r0 >>= fun _ -> raise exn)
>>= fun s0 ->
Fiber.catch
(fun () -> loop r0 s0)
(fun exn ->
src.stop s0 >>= fun () ->
snk.stop r0 >>= fun _r' -> raise exn)
let into sink t = t.stream sink
let via { flow } t =
let stream sink = into (flow sink) t in
{ stream }
let from (Source src) =
let stream (Sink k) =
let rec go r s =
k.full r >>= function
| true -> k.stop r
| false -> (
src.pull s >>= function
| None -> src.stop s >>= fun () -> k.stop r
| Some (x, s') -> k.push r x >>= fun r -> go r s')
in
k.init () >>= fun r0 ->
k.full r0 >>= function
| true -> k.stop r0
| false ->
Fiber.catch
(fun () -> src.init ())
(fun exn -> k.stop r0 >>= fun _ -> raise exn)
>>= fun s0 ->
Fiber.catch
(fun () -> go r0 s0)
(fun exn ->
src.stop s0 >>= fun () ->
k.stop r0 >>= fun _ -> raise exn)
in
{ stream }
let concat a b =
let stream (Sink k) =
let stop r =
k.full r >>= function
| true -> k.stop r
| false -> b.stream (Sink { k with init = (fun () -> Fiber.return r) })
in
a.stream (Sink { k with stop })
in
{ stream }
let flat_map f t =
let stream (Sink k) =
let push r x =
f x >>= fun { stream } ->
stream
(Sink
{
k with
init = (fun () -> Fiber.return r);
stop = (fun r -> Fiber.return r);
})
in
t.stream (Sink { k with push })
in
{ stream }
let empty =
let stream (Sink k) = k.init () >>= k.stop in
{ stream }
let singleton v =
let stream (Sink k) = k.init () >>= fun acc -> k.push acc v >>= k.stop in
{ stream }
let double a b =
let stream (Sink k) =
k.init () >>= fun acc ->
k.push acc a >>= fun acc -> k.push acc b >>= k.stop
in
{ stream }
let map f t = via (Flow.map f) t
let filter_map f t = via (Flow.filter_map f) t
let tap f t = via (Flow.tap f) t
let of_fiber f =
let stream (Sink k) =
k.init () >>= fun acc -> f () >>= k.push acc >>= k.stop
in
{ stream }
let of_iter iter =
let exception Stop in
let stream (Sink k) =
let go r =
k.full r >>= function
| true -> Fiber.return r
| false ->
let acc = ref r in
Fiber.catch
(fun () ->
iter (fun x ->
k.push !acc x >>= fun acc' ->
acc := acc';
k.full !acc >>= function
| true -> raise Stop
| false -> Fiber.return ())
>>= fun () -> Fiber.return !acc)
(function Stop -> Fiber.return !acc | exn -> raise exn)
in
bracket go ~init:k.init ~stop:k.stop
in
{ stream }
let to_list t = into Sink.list t
let of_list lst =
let stream (Sink k) =
let rec go s r =
k.full r >>= function
| true -> Fiber.return r
| false -> (
match s with
| [] -> Fiber.return r
| x :: s' -> k.push r x >>= go s')
in
bracket (go lst) ~init:k.init ~stop:k.stop
in
{ stream }
let to_array stream = into Sink.array stream
let of_array arr = from (Source.array arr)
let to_bigstring stream = into Sink.bigstring stream
let to_string stream = into Sink.string stream
let iterate ~f x = from (Source.iterate ~f x)
let of_file ?(len = Stdbob.io_buffer_size) path =
Fiber.openfile path Unix.[ O_RDONLY ] 0o644 >>= function
| Error errno ->
Fiber.return
(Error
(msgf "openfile(%a): %s" Bob_fpath.pp path
(Unix.error_message errno)))
| Ok fd ->
let stream (Sink k) =
let rec go r =
k.full r >>= function
| true ->
Log.debug (fun m ->
m "The given sink is full, stop to read into: %a."
Bob_fpath.pp path);
Fiber.return r
| false -> (
Fiber.read ~len fd >>= function
| Ok `End ->
Log.debug (fun m ->
m "End of the file: %a" Bob_fpath.pp path);
Fiber.return r
| Ok (`Data bstr) -> k.push r bstr >>= go
| Error errno ->
Fmt.failwith "read(%d:%a): %s" (Obj.magic fd) Bob_fpath.pp
path (Unix.error_message errno))
in
let stop r =
Log.debug (fun m -> m "Close the file %a." Bob_fpath.pp path);
Fiber.close fd >>= fun () -> k.stop r
in
bracket go ~init:k.init ~stop
in
Fiber.return (Ok { stream })
let stdin =
let stream (Sink k) =
let rec go r =
k.full r >>= function
| true -> Fiber.return r
| false -> (
Fiber.read Unix.stdin >>= function
| Ok `End -> Fiber.return r
| Ok (`Data bstr) -> k.push r bstr >>= go
| Error errno ->
Fmt.failwith "read(<stdin>): %s" (Unix.error_message errno))
in
bracket go ~init:k.init ~stop:k.stop
in
{ stream }
let to_file path = into (Sink.file path)
let stdout = into Sink.stdout
let ( >>= ) x f = flat_map f x
let ( ++ ) = concat
end
|
56f3097b13b4a1ac3311c15187b32959a2d1d97e9d9b880f1f31363a1de7ce16
|
mistupv/cauder
|
purchase.erl
|
FASE 2014 example
-module(purchase).
-export([main/0, asynchAnd/2, checkCredit/2, checkAddress/1, checkItem/1]).
main() ->
Pid = spawn(?MODULE, asynchAnd, [2, self()]),
spawn(?MODULE, checkCredit, [15, Pid]),
spawn(?MODULE, checkAddress, [Pid]),
spawn(?MODULE, checkItem, [Pid]),
receive
true ->
io:format("All checks successful.~n"),
true;
false ->
io:format("Check failure.~n"),
false
end.
asynchAnd(N, Out) ->
if
N > 0 ->
receive
true -> asynchAnd(N - 1, Out);
false -> Out ! false
end;
true ->
Out ! true
end.
checkCredit(Price, Pid) ->
if
Price < 10 ->
io:format("Credit check successful~n"),
Pid ! true;
true ->
io:format("Credit check failed~n"),
Pid ! false
end.
checkAddress(Pid) ->
io:format("Address check successful~n"),
Pid ! true.
checkItem(Pid) ->
io:format("Item check successful~n"),
Pid ! true.
| null |
https://raw.githubusercontent.com/mistupv/cauder/ff4955cca4b0aa6ae9d682e9f0532be188a5cc16/case-studies/purchase/purchase.erl
|
erlang
|
FASE 2014 example
-module(purchase).
-export([main/0, asynchAnd/2, checkCredit/2, checkAddress/1, checkItem/1]).
main() ->
Pid = spawn(?MODULE, asynchAnd, [2, self()]),
spawn(?MODULE, checkCredit, [15, Pid]),
spawn(?MODULE, checkAddress, [Pid]),
spawn(?MODULE, checkItem, [Pid]),
receive
true ->
io:format("All checks successful.~n"),
true;
false ->
io:format("Check failure.~n"),
false
end.
asynchAnd(N, Out) ->
if
N > 0 ->
receive
true -> asynchAnd(N - 1, Out);
false -> Out ! false
end;
true ->
Out ! true
end.
checkCredit(Price, Pid) ->
if
Price < 10 ->
io:format("Credit check successful~n"),
Pid ! true;
true ->
io:format("Credit check failed~n"),
Pid ! false
end.
checkAddress(Pid) ->
io:format("Address check successful~n"),
Pid ! true.
checkItem(Pid) ->
io:format("Item check successful~n"),
Pid ! true.
|
|
4e4620855368aac32f022ca5ad73fd764ddc18dec314ca4f7ce3b02e970335b3
|
derbear/steal
|
periodicpayment.rkt
|
#lang racket
(provide periodicpayment)
(provide periodicpayment-doc)
(provide periodicpayment-escrow)
(provide periodicpayment-escrow-doc)
(define periodicpayment-core
'(and (= (txn TypeEnum) 1)
(< (txn Fee) (int TMPL_FEE))
(= (% (txn FirstValid) (int TMPL_PERIOD)) 0)
(= (txn LastValid) (+ (int TMPL_DUR) (txn FirstValid)))
(= (txn Lease) (byte base64 TMPL_LEASE))))
(define periodicpayment-transfer
'(and (= (txn CloseRemainderTo) (global ZeroAddress))
(= (txn Receiver) (addr TMPL_RCV))
(= (txn Amount) (int TMPL_AMT))))
(define periodicpayment-close
'(and (= (txn CloseRemainderTo) (addr TMPL_RCV))
(= (txn Receiver) (global ZeroAddress))
(> (txn FirstValid) (int TMPL_TIMEOUT))
(= (txn Amount) 0)))
(define periodicpayment-doc
"Allows some account to execute periodic withdrawal of funds.
This is delegate logic.
This allows TMPL_RCV to withdraw TMPL_AMT every
TMPL_PERIOD rounds for TMPL_DUR after every multiple
of TMPL_PERIOD.
Parameters:
- TMPL_RCV: address which is authorized to make withdrawals
- TMPL_PERIOD: the time between a pair of withdrawal periods
- TMPL_DUR: the duration of a withdrawal period
- TMPL_AMT: the maximum number of funds allowed for a single withdrawal
- TMPL_LEASE: string to use for the transaction lease
- TMPL_FEE: maximum fee used by the withdrawal transaction
")
(define periodicpayment
`(and ,periodicpayment-core
,periodicpayment-transfer))
(define periodicpayment-escrow-doc
"Allows some account to execute periodic withdrawal of funds.
This is a contract account.
This allows TMPL_RCV to withdraw TMPL_AMT every
TMPL_PERIOD rounds for TMPL_DUR after every multiple
of TMPL_PERIOD.
After TMPL_TIMEOUT, all remaining funds in the escrow
are available to TMPL_RCV.
Parameters:
- TMPL_RCV: address which is authorized to make withdrawals
- TMPL_PERIOD: the time between a pair of withdrawal periods
- TMPL_DUR: the duration of a withdrawal period
- TMPL_AMT: the maximum number of funds allowed for a single withdrawal
- TMPL_LEASE: string to use for the transaction lease
- TMPL_TIMEOUT: the round at which the account expires
- TMPL_FEE: maximum fee used by the withdrawal transaction
")
(define periodicpayment-escrow
`(and ,periodicpayment-core
(or ,periodicpayment-transfer
,periodicpayment-close)))
| null |
https://raw.githubusercontent.com/derbear/steal/afd746a574728dd04c76a5538449caa6f6876d99/examples/periodicpayment.rkt
|
racket
|
#lang racket
(provide periodicpayment)
(provide periodicpayment-doc)
(provide periodicpayment-escrow)
(provide periodicpayment-escrow-doc)
(define periodicpayment-core
'(and (= (txn TypeEnum) 1)
(< (txn Fee) (int TMPL_FEE))
(= (% (txn FirstValid) (int TMPL_PERIOD)) 0)
(= (txn LastValid) (+ (int TMPL_DUR) (txn FirstValid)))
(= (txn Lease) (byte base64 TMPL_LEASE))))
(define periodicpayment-transfer
'(and (= (txn CloseRemainderTo) (global ZeroAddress))
(= (txn Receiver) (addr TMPL_RCV))
(= (txn Amount) (int TMPL_AMT))))
(define periodicpayment-close
'(and (= (txn CloseRemainderTo) (addr TMPL_RCV))
(= (txn Receiver) (global ZeroAddress))
(> (txn FirstValid) (int TMPL_TIMEOUT))
(= (txn Amount) 0)))
(define periodicpayment-doc
"Allows some account to execute periodic withdrawal of funds.
This is delegate logic.
This allows TMPL_RCV to withdraw TMPL_AMT every
TMPL_PERIOD rounds for TMPL_DUR after every multiple
of TMPL_PERIOD.
Parameters:
- TMPL_RCV: address which is authorized to make withdrawals
- TMPL_PERIOD: the time between a pair of withdrawal periods
- TMPL_DUR: the duration of a withdrawal period
- TMPL_AMT: the maximum number of funds allowed for a single withdrawal
- TMPL_LEASE: string to use for the transaction lease
- TMPL_FEE: maximum fee used by the withdrawal transaction
")
(define periodicpayment
`(and ,periodicpayment-core
,periodicpayment-transfer))
(define periodicpayment-escrow-doc
"Allows some account to execute periodic withdrawal of funds.
This is a contract account.
This allows TMPL_RCV to withdraw TMPL_AMT every
TMPL_PERIOD rounds for TMPL_DUR after every multiple
of TMPL_PERIOD.
After TMPL_TIMEOUT, all remaining funds in the escrow
are available to TMPL_RCV.
Parameters:
- TMPL_RCV: address which is authorized to make withdrawals
- TMPL_PERIOD: the time between a pair of withdrawal periods
- TMPL_DUR: the duration of a withdrawal period
- TMPL_AMT: the maximum number of funds allowed for a single withdrawal
- TMPL_LEASE: string to use for the transaction lease
- TMPL_TIMEOUT: the round at which the account expires
- TMPL_FEE: maximum fee used by the withdrawal transaction
")
(define periodicpayment-escrow
`(and ,periodicpayment-core
(or ,periodicpayment-transfer
,periodicpayment-close)))
|
|
d1a14eca834decc711d1d5ee01395fadd8b99bf7431009eba313e87d5e584749
|
lambdaisland/kaocha
|
core_ext.clj
|
(ns kaocha.core-ext
"Core language extensions"
(:require [kaocha.platform :as platform])
(:refer-clojure :exclude [symbol])
(:import (java.util.regex Pattern)))
(defn regex? [x]
(instance? Pattern x))
(defn exception? [x]
(instance? java.lang.Exception x))
(defn error? [x]
(instance? java.lang.Error x))
(defn throwable? [x]
(instance? java.lang.Throwable x))
(defn ns? [x]
(instance? clojure.lang.Namespace x))
(defn file? [x]
(and (instance? java.io.File x) (.isFile ^java.io.File x)))
(defn directory? [x]
(and (instance? java.io.File x) (.isDirectory ^java.io.File x)))
(defn path? [x]
(instance? java.nio.file.Path x))
(defn regex
([x & xs]
(regex (apply str x xs)))
([x]
(cond
(regex? x) x
(string? x) (Pattern/compile x)
:else (throw (ex-info (str "Can't coerce " (class x) " to regex.") {})))))
(defn mapply
"Applies a function f to the argument list formed by concatenating
everything but the last element of args with the last element of
args. This is useful for applying a function that accepts keyword
arguments to a map."
[f & args]
(apply f (apply concat (butlast args) (last args))))
(defn symbol
"Backport from Clojure 1.10, symbol function that's a bit more lenient on its
inputs.
Returns a Symbol with the given namespace and name. Arity-1 works on strings,
keywords, and vars."
^clojure.lang.Symbol
([name]
(cond
(symbol? name) name
(instance? String name) (clojure.lang.Symbol/intern name)
(instance? clojure.lang.Var name) (.toSymbol ^clojure.lang.Var name)
(instance? clojure.lang.Keyword name) (.sym ^clojure.lang.Keyword name)
:else (throw (IllegalArgumentException. "no conversion to symbol"))))
([ns name]
(clojure.core/symbol ns name)))
1.10 backport
(when-not (resolve 'clojure.core/requiring-resolve)
using defn generates a warning even when not evaluated
(intern *ns*
^{:doc "Resolves namespace-qualified sym per 'resolve'. If initial resolve
fails, attempts to require sym's namespace and retries."}
'requiring-resolve
(fn [sym]
(if (qualified-symbol? sym)
(or (resolve sym)
(do (-> sym namespace symbol require)
(resolve sym)))
(throw (IllegalArgumentException. (str "Not a qualified symbol: " sym)))))))
| null |
https://raw.githubusercontent.com/lambdaisland/kaocha/9ac9406e4a2ab8c5dc3a0edb84038d277818de37/src/kaocha/core_ext.clj
|
clojure
|
(ns kaocha.core-ext
"Core language extensions"
(:require [kaocha.platform :as platform])
(:refer-clojure :exclude [symbol])
(:import (java.util.regex Pattern)))
(defn regex? [x]
(instance? Pattern x))
(defn exception? [x]
(instance? java.lang.Exception x))
(defn error? [x]
(instance? java.lang.Error x))
(defn throwable? [x]
(instance? java.lang.Throwable x))
(defn ns? [x]
(instance? clojure.lang.Namespace x))
(defn file? [x]
(and (instance? java.io.File x) (.isFile ^java.io.File x)))
(defn directory? [x]
(and (instance? java.io.File x) (.isDirectory ^java.io.File x)))
(defn path? [x]
(instance? java.nio.file.Path x))
(defn regex
([x & xs]
(regex (apply str x xs)))
([x]
(cond
(regex? x) x
(string? x) (Pattern/compile x)
:else (throw (ex-info (str "Can't coerce " (class x) " to regex.") {})))))
(defn mapply
"Applies a function f to the argument list formed by concatenating
everything but the last element of args with the last element of
args. This is useful for applying a function that accepts keyword
arguments to a map."
[f & args]
(apply f (apply concat (butlast args) (last args))))
(defn symbol
"Backport from Clojure 1.10, symbol function that's a bit more lenient on its
inputs.
Returns a Symbol with the given namespace and name. Arity-1 works on strings,
keywords, and vars."
^clojure.lang.Symbol
([name]
(cond
(symbol? name) name
(instance? String name) (clojure.lang.Symbol/intern name)
(instance? clojure.lang.Var name) (.toSymbol ^clojure.lang.Var name)
(instance? clojure.lang.Keyword name) (.sym ^clojure.lang.Keyword name)
:else (throw (IllegalArgumentException. "no conversion to symbol"))))
([ns name]
(clojure.core/symbol ns name)))
1.10 backport
(when-not (resolve 'clojure.core/requiring-resolve)
using defn generates a warning even when not evaluated
(intern *ns*
^{:doc "Resolves namespace-qualified sym per 'resolve'. If initial resolve
fails, attempts to require sym's namespace and retries."}
'requiring-resolve
(fn [sym]
(if (qualified-symbol? sym)
(or (resolve sym)
(do (-> sym namespace symbol require)
(resolve sym)))
(throw (IllegalArgumentException. (str "Not a qualified symbol: " sym)))))))
|
|
e72fefb36816527dce68b99471907c4af382193b3c3cfafc04cf5ce0742e6c7e
|
SimulaVR/godot-haskell
|
AnimationNodeTimeSeek.hs
|
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.AnimationNodeTimeSeek () where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.AnimationNode()
| null |
https://raw.githubusercontent.com/SimulaVR/godot-haskell/e8f2c45f1b9cc2f0586ebdc9ec6002c8c2d384ae/src/Godot/Core/AnimationNodeTimeSeek.hs
|
haskell
|
# LANGUAGE DerivingStrategies , GeneralizedNewtypeDeriving ,
TypeFamilies , TypeOperators , FlexibleContexts , DataKinds ,
MultiParamTypeClasses #
TypeFamilies, TypeOperators, FlexibleContexts, DataKinds,
MultiParamTypeClasses #-}
module Godot.Core.AnimationNodeTimeSeek () where
import Data.Coerce
import Foreign.C
import Godot.Internal.Dispatch
import qualified Data.Vector as V
import Linear(V2(..),V3(..),M22)
import Data.Colour(withOpacity)
import Data.Colour.SRGB(sRGB)
import System.IO.Unsafe
import Godot.Gdnative.Internal
import Godot.Api.Types
import Godot.Core.AnimationNode()
|
|
8b4ddea249bb2048cb00802bf31909e2b0778f70d1774e365eb8e79cc9e226d3
|
avsm/mirage-duniverse
|
spawn.mli
|
(** Mini spawn library *)
(** Note: on Unix, spawn uses vfork by default. It has been tested,
but if you believe this is causing a problem in your application,
you can change this default at runtime by setting the environment
variable [SPAWN_USE_FORK]. *)
module Working_dir : sig
type t =
| Path of string (** Path in the filesystem *)
* File descriptor pointing to a directory .
Not supported on Windows .
Not supported on Windows. *)
| Inherit (** Inherit the working directory of
the current process *)
end
module Unix_backend : sig
(** System call to use on Unix. *)
type t =
| Fork
| Vfork
(** [Fork] if the [SPAWN_USE_FORK] environment variable is set,
[Vfork] otherwise. *)
val default : t
end
module Env : sig
(** Representation of an environment *)
type t
(** Create an environment from a list of strings of the form
["KEY=VALUE"]. *)
val of_list : string list -> t
end
* Spawn a sub - command and return its PID . This function is low - level
and should be used to build higher - level APIs .
In case of errors , it raises [ Unix . Unix_error ] .
{ b Binary }
[ prog ] is not searched in [ PATH ] . It is up to the caller to do the
path resolution before calling this function . Note that there is no
special treatment of executable text files without a proper # ! . The
execvp function from the C library calls [ /bin / sh ] in this case to
imitate the behaviors of a shell but this function does n't .
{ b Environment }
[ env ] represents the environment in which the sub - process is
executed . If not specified , the environment from the process
calling this function is used .
{ b Working directory }
[ cwd ] describes what the current working directory of the
sub - process should be . It defaults to [ Inherit ] . It is an error to
pass [ Fd _ ] on Windows .
{ b Standard input / outputs }
[ stdin ] , [ stdout ] and [ stderr ] are the file descriptors used as
standard input , output and error output of the sub - process . When
not specified , they default to the ones from the calling process .
{ b Signals }
On Unix , the sub - process will have all its signals unblocked .
{ b Implementation }
[ unix_backend ] describes what backend to use on Unix . If set to
[ Default ] , [ vfork ] is used unless the environment variable
[ SPAWN_USE_FORK ] is set . On Windows , [ CreateProcess ] is used .
and should be used to build higher-level APIs.
In case of errors, it raises [Unix.Unix_error].
{b Binary}
[prog] is not searched in [PATH]. It is up to the caller to do the
path resolution before calling this function. Note that there is no
special treatment of executable text files without a proper #!. The
execvp function from the C library calls [/bin/sh] in this case to
imitate the behaviors of a shell but this function doesn't.
{b Environment}
[env] represents the environment in which the sub-process is
executed. If not specified, the environment from the process
calling this function is used.
{b Working directory}
[cwd] describes what the current working directory of the
sub-process should be. It defaults to [Inherit]. It is an error to
pass [Fd _] on Windows.
{b Standard input/outputs}
[stdin], [stdout] and [stderr] are the file descriptors used as
standard input, output and error output of the sub-process. When
not specified, they default to the ones from the calling process.
{b Signals}
On Unix, the sub-process will have all its signals unblocked.
{b Implementation}
[unix_backend] describes what backend to use on Unix. If set to
[Default], [vfork] is used unless the environment variable
[SPAWN_USE_FORK] is set. On Windows, [CreateProcess] is used. *)
val spawn
: ?env:Env.t
-> ?cwd:Working_dir.t (** default: [Inherit] *)
-> prog:string
-> argv:string list
-> ?stdin:Unix.file_descr
-> ?stdout:Unix.file_descr
-> ?stderr:Unix.file_descr
-> ?unix_backend:Unix_backend.t (** default: [Unix_backend.default] *)
-> unit
-> int
(**/**)
Create a pipe with [ O_CLOEXEC ] sets for both fds . This is the same
as creating a pipe and setting [ O_CLOEXEC ] manually on both ends ,
with the difference that there is no race condition between [ spawn ]
and [ safe_pipe ] . I.e. if a thread calls [ safe_pipe ] and another
calls [ spawn ] , it is guaranteed that the sub - process does n't have
the pipe without [ O_CLOEXEC ] set on one or the two file
descriptors . The latter situation is problematic as one often reads
a pipe until it is closed , however if some random process keeps a
handle of it because it inherited it from its parent by mistake ,
the pipe will never be closed .
It is implemented using the [ pipe2 ] system calls , except on OSX
where [ pipe2 ] is not available . On OSX , both [ safe_pipe ] and
[ spawn ] lock the same mutex to prevent race conditions .
as creating a pipe and setting [O_CLOEXEC] manually on both ends,
with the difference that there is no race condition between [spawn]
and [safe_pipe]. I.e. if a thread calls [safe_pipe] and another
calls [spawn], it is guaranteed that the sub-process doesn't have
the pipe without [O_CLOEXEC] set on one or the two file
descriptors. The latter situation is problematic as one often reads
a pipe until it is closed, however if some random process keeps a
handle of it because it inherited it from its parent by mistake,
the pipe will never be closed.
It is implemented using the [pipe2] system calls, except on OSX
where [pipe2] is not available. On OSX, both [safe_pipe] and
[spawn] lock the same mutex to prevent race conditions. *)
val safe_pipe : unit -> Unix.file_descr * Unix.file_descr
| null |
https://raw.githubusercontent.com/avsm/mirage-duniverse/983e115ff5a9fb37e3176c373e227e9379f0d777/ocaml_modules/spawn/src/spawn.mli
|
ocaml
|
* Mini spawn library
* Note: on Unix, spawn uses vfork by default. It has been tested,
but if you believe this is causing a problem in your application,
you can change this default at runtime by setting the environment
variable [SPAWN_USE_FORK].
* Path in the filesystem
* Inherit the working directory of
the current process
* System call to use on Unix.
* [Fork] if the [SPAWN_USE_FORK] environment variable is set,
[Vfork] otherwise.
* Representation of an environment
* Create an environment from a list of strings of the form
["KEY=VALUE"].
* default: [Inherit]
* default: [Unix_backend.default]
*/*
|
module Working_dir : sig
type t =
* File descriptor pointing to a directory .
Not supported on Windows .
Not supported on Windows. *)
end
module Unix_backend : sig
type t =
| Fork
| Vfork
val default : t
end
module Env : sig
type t
val of_list : string list -> t
end
* Spawn a sub - command and return its PID . This function is low - level
and should be used to build higher - level APIs .
In case of errors , it raises [ Unix . Unix_error ] .
{ b Binary }
[ prog ] is not searched in [ PATH ] . It is up to the caller to do the
path resolution before calling this function . Note that there is no
special treatment of executable text files without a proper # ! . The
execvp function from the C library calls [ /bin / sh ] in this case to
imitate the behaviors of a shell but this function does n't .
{ b Environment }
[ env ] represents the environment in which the sub - process is
executed . If not specified , the environment from the process
calling this function is used .
{ b Working directory }
[ cwd ] describes what the current working directory of the
sub - process should be . It defaults to [ Inherit ] . It is an error to
pass [ Fd _ ] on Windows .
{ b Standard input / outputs }
[ stdin ] , [ stdout ] and [ stderr ] are the file descriptors used as
standard input , output and error output of the sub - process . When
not specified , they default to the ones from the calling process .
{ b Signals }
On Unix , the sub - process will have all its signals unblocked .
{ b Implementation }
[ unix_backend ] describes what backend to use on Unix . If set to
[ Default ] , [ vfork ] is used unless the environment variable
[ SPAWN_USE_FORK ] is set . On Windows , [ CreateProcess ] is used .
and should be used to build higher-level APIs.
In case of errors, it raises [Unix.Unix_error].
{b Binary}
[prog] is not searched in [PATH]. It is up to the caller to do the
path resolution before calling this function. Note that there is no
special treatment of executable text files without a proper #!. The
execvp function from the C library calls [/bin/sh] in this case to
imitate the behaviors of a shell but this function doesn't.
{b Environment}
[env] represents the environment in which the sub-process is
executed. If not specified, the environment from the process
calling this function is used.
{b Working directory}
[cwd] describes what the current working directory of the
sub-process should be. It defaults to [Inherit]. It is an error to
pass [Fd _] on Windows.
{b Standard input/outputs}
[stdin], [stdout] and [stderr] are the file descriptors used as
standard input, output and error output of the sub-process. When
not specified, they default to the ones from the calling process.
{b Signals}
On Unix, the sub-process will have all its signals unblocked.
{b Implementation}
[unix_backend] describes what backend to use on Unix. If set to
[Default], [vfork] is used unless the environment variable
[SPAWN_USE_FORK] is set. On Windows, [CreateProcess] is used. *)
val spawn
: ?env:Env.t
-> prog:string
-> argv:string list
-> ?stdin:Unix.file_descr
-> ?stdout:Unix.file_descr
-> ?stderr:Unix.file_descr
-> unit
-> int
Create a pipe with [ O_CLOEXEC ] sets for both fds . This is the same
as creating a pipe and setting [ O_CLOEXEC ] manually on both ends ,
with the difference that there is no race condition between [ spawn ]
and [ safe_pipe ] . I.e. if a thread calls [ safe_pipe ] and another
calls [ spawn ] , it is guaranteed that the sub - process does n't have
the pipe without [ O_CLOEXEC ] set on one or the two file
descriptors . The latter situation is problematic as one often reads
a pipe until it is closed , however if some random process keeps a
handle of it because it inherited it from its parent by mistake ,
the pipe will never be closed .
It is implemented using the [ pipe2 ] system calls , except on OSX
where [ pipe2 ] is not available . On OSX , both [ safe_pipe ] and
[ spawn ] lock the same mutex to prevent race conditions .
as creating a pipe and setting [O_CLOEXEC] manually on both ends,
with the difference that there is no race condition between [spawn]
and [safe_pipe]. I.e. if a thread calls [safe_pipe] and another
calls [spawn], it is guaranteed that the sub-process doesn't have
the pipe without [O_CLOEXEC] set on one or the two file
descriptors. The latter situation is problematic as one often reads
a pipe until it is closed, however if some random process keeps a
handle of it because it inherited it from its parent by mistake,
the pipe will never be closed.
It is implemented using the [pipe2] system calls, except on OSX
where [pipe2] is not available. On OSX, both [safe_pipe] and
[spawn] lock the same mutex to prevent race conditions. *)
val safe_pipe : unit -> Unix.file_descr * Unix.file_descr
|
95f179b0eb7f152000b417eaaac71d624a7f24c96dac763572cf603f49339e87
|
SNePS/SNePS2
|
wordize.lisp
|
-*- Mode : Lisp ; Syntax : Common - Lisp ; Package : ENGLEX ; Base : 10 -*-
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
Version : $ I d : wordize.lisp , v 1.2 2013/08/28 19:07:24 shapiro Exp $
;; This file is part of SNePS.
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Buffalo Public License Version 1.0 ( the " License " ) ; you may
;;; not use this file except in compliance with the License. You
;;; may obtain a copy of the License at
;;; . edu/sneps/Downloads/ubpl.pdf.
;;;
Software distributed under the License is distributed on an
" AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express
;;; or implied. See the License for the specific language gov
;;; erning rights and limitations under the License.
;;;
The Original Code is SNePS 2.8 .
;;;
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
;;;
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(in-package :englex)
(defun wordize (numbr lexeme)
"Returns the singular or plural form of the 2nd arg according to the
feature given as the 1st arg."
(let* ((lex (first-atom lexeme))
(lexeme (typecase lex
(string lex)
(symbol (symbol-name lex))
(sneps::node (symbol-name (sneps::node-na lex))))))
(cond ((null numbr) (or (lookup-lexical-feature 'root lexeme) lexeme))
((eq numbr 'sing) (or (lookup-lexical-feature 'root lexeme) lexeme))
((lookup-lexical-feature 'plur lexeme))
(t (pluralize (or (lookup-lexical-feature 'root lexeme) lexeme))))))
(defun pluralize (wform)
(let ((wlength (1- (length wform)))
(vowls '(#\a #\e #\i #\o #\u)))
(cond ((char= (schar wform wlength) #\f)
(concatenate 'string (subseq wform 0 wlength) "ves"))
((char= (schar wform wlength) #\y)
(cond ((member (schar wform (1- wlength)) vowls :test #'char=)
(concatenate 'string wform "s"))
(t
(concatenate 'string (subseq wform 0 wlength) "ies"))))
((string= (subseq wform (- wlength 2) (1+ wlength)) "sis")
(concatenate 'string (subseq wform 0 (1- wlength)) "es"))
((or (char= (schar wform wlength) #\x)
(char= (schar wform wlength) #\s)
(char= (schar wform wlength) #\z)
(and (char= (schar wform wlength) #\o)
(not (member (schar wform (1- wlength)) vowls
:test #'char=)))
(and (char= (schar wform wlength) #\h)
(char= (schar wform (1- wlength)) #\c)))
(concatenate 'string wform "es"))
(t (concatenate 'string wform "s")))))
| null |
https://raw.githubusercontent.com/SNePS/SNePS2/d3862108609b1879f2c546112072ad4caefc050d/nlint/englex/wordize.lisp
|
lisp
|
Syntax : Common - Lisp ; Package : ENGLEX ; Base : 10 -*-
This file is part of SNePS.
you may
not use this file except in compliance with the License. You
may obtain a copy of the License at
. edu/sneps/Downloads/ubpl.pdf.
or implied. See the License for the specific language gov
erning rights and limitations under the License.
|
Copyright ( C ) 1984 - -2013
Research Foundation of State University of New York
Version : $ I d : wordize.lisp , v 1.2 2013/08/28 19:07:24 shapiro Exp $
$ BEGIN LICENSE$
The contents of this file are subject to the University at
Software distributed under the License is distributed on an
" AS IS " basis , WITHOUT WARRANTY OF ANY KIND , either express
The Original Code is SNePS 2.8 .
The Initial Developer of the Original Code is Research Foun
dation of State University of New York , on behalf of Univer
sity at Buffalo .
Portions created by the Initial Developer are Copyright ( C )
2011 Research Foundation of State University of New York , on
behalf of University at Buffalo . All Rights Reserved .
$ END LICENSE$
(in-package :englex)
(defun wordize (numbr lexeme)
"Returns the singular or plural form of the 2nd arg according to the
feature given as the 1st arg."
(let* ((lex (first-atom lexeme))
(lexeme (typecase lex
(string lex)
(symbol (symbol-name lex))
(sneps::node (symbol-name (sneps::node-na lex))))))
(cond ((null numbr) (or (lookup-lexical-feature 'root lexeme) lexeme))
((eq numbr 'sing) (or (lookup-lexical-feature 'root lexeme) lexeme))
((lookup-lexical-feature 'plur lexeme))
(t (pluralize (or (lookup-lexical-feature 'root lexeme) lexeme))))))
(defun pluralize (wform)
(let ((wlength (1- (length wform)))
(vowls '(#\a #\e #\i #\o #\u)))
(cond ((char= (schar wform wlength) #\f)
(concatenate 'string (subseq wform 0 wlength) "ves"))
((char= (schar wform wlength) #\y)
(cond ((member (schar wform (1- wlength)) vowls :test #'char=)
(concatenate 'string wform "s"))
(t
(concatenate 'string (subseq wform 0 wlength) "ies"))))
((string= (subseq wform (- wlength 2) (1+ wlength)) "sis")
(concatenate 'string (subseq wform 0 (1- wlength)) "es"))
((or (char= (schar wform wlength) #\x)
(char= (schar wform wlength) #\s)
(char= (schar wform wlength) #\z)
(and (char= (schar wform wlength) #\o)
(not (member (schar wform (1- wlength)) vowls
:test #'char=)))
(and (char= (schar wform wlength) #\h)
(char= (schar wform (1- wlength)) #\c)))
(concatenate 'string wform "es"))
(t (concatenate 'string wform "s")))))
|
effbb8330c2c1fa2996c92fff7fa8f4f1a448156d198807cdcadc924273d095e
|
haskell-compat/base-compat
|
Batteries.hs
|
{-# LANGUAGE PackageImports #-}
# OPTIONS_GHC -fno - warn - dodgy - exports -fno - warn - unused - imports #
| Reexports " Data . Functor . . Compat "
-- from a globally unique namespace.
module Data.Functor.Contravariant.Compat.Repl.Batteries (
module Data.Functor.Contravariant.Compat
) where
import "this" Data.Functor.Contravariant.Compat
| null |
https://raw.githubusercontent.com/haskell-compat/base-compat/847aa35c4142f529525ffc645cd035ddb23ce8ee/base-compat-batteries/src/Data/Functor/Contravariant/Compat/Repl/Batteries.hs
|
haskell
|
# LANGUAGE PackageImports #
from a globally unique namespace.
|
# OPTIONS_GHC -fno - warn - dodgy - exports -fno - warn - unused - imports #
| Reexports " Data . Functor . . Compat "
module Data.Functor.Contravariant.Compat.Repl.Batteries (
module Data.Functor.Contravariant.Compat
) where
import "this" Data.Functor.Contravariant.Compat
|
1bf4c0f385f655cc0fb4b8ebefb5347822f5c48841b64b889845c5cd7cb05ab7
|
VisionsGlobalEmpowerment/webchange
|
views.cljs
|
(ns webchange.ui.components.card.views
(:require
[reagent.core :as r]
[webchange.ui.components.available-values :as available-values]
[webchange.ui.components.button.views :refer [button]]
[webchange.ui.components.card.background :as background]
[webchange.ui.components.icon.views :refer [navigation-icon]]
[webchange.ui.components.panel.views :refer [panel]]
[webchange.ui.utils.get-class-name :refer [get-class-name]]))
(defn- card-wrapper
[{:keys [actions background class-name]
:or {background "blue-1"}}]
(->> (r/current-component)
(r/children)
(into [panel {:class-name class-name
:class-name-content (get-class-name {"bbs--card--content" true
(str "bbs--card--content--background-" background) true
"bbs--card--content--no-actions" (empty? actions)})
:color background}
(when-not (= background "transparent")
background/data)])))
(defn- card-counter
[{:keys [counter type]}]
[:div {:class-name (get-class-name {"bbs--card--counter" true
(str "bbs--card--counter--type-" type) true})}
(if (number? counter) counter "-")])
(defn- card-icon
[{:keys [counter icon icon-background type] :as props}]
[:div {:class-name (get-class-name {"bbs--card--icon" true
(str "bbs--card--icon--background-" icon-background) (some? icon-background)})}
[navigation-icon {:icon icon
:class-name "bbs--card--icon-data"}]
(when (and (some? counter)
(= type "vertical"))
[card-counter props])])
(defn- card-data
[{:keys [background text type] :as props
:or {background "blue-1"}}]
[:div {:class-name (get-class-name {"bbs--card--data" true
(str "bbs--card--data--background-" background) true})}
(when (= type "horizontal")
[card-counter props])
[:div.bbs--card--text text]])
(defn- card-action
[{:keys [on-click text] :as props}]
(let [handle-click #(when (fn? on-click) (on-click))
button-props (-> props
(dissoc :text)
(assoc :on-click handle-click
:shape "rounded"
:class-name "bbs--card--action"))]
[button button-props
text]))
(defn- card-actions
[{:keys [actions]}]
(when-not (empty? actions)
[:div {:class-name "bbs--card--actions"}
(for [[idx action-data] (->> actions
(remove nil?)
(map-indexed vector))]
^{:key (str "action-" idx)}
[card-action action-data])]))
(defn- card-horizontal
[props]
[:<>
[card-icon props]
[card-data (assoc props :type "horizontal")]
[card-actions props]])
(defn- card-vertical
[props]
[:<>
[card-icon props]
[card-data props]
[card-actions props]])
(defn card
[{:keys [actions background counter icon icon-background text type]
:or {type "horizontal"}
:as props}]
{:pre [(some #{icon} available-values/icon-navigation)
(or (nil? icon-background) (some #{icon-background} available-values/color))
(or (nil? background) (some #{background} available-values/color))
(or (nil? counter) (number? counter))
(or (nil? text) (string? text))
(some #{type} ["horizontal" "vertical"])
(or (nil? actions) (every? #(or (nil? %)
(and (string? (:text %))
(fn? (:on-click %))))
actions))]}
[card-wrapper (merge props
{:class-name (get-class-name {"bbs--card" true
(str "bbs--card--" type) true
(str "bbs--card--background-" background) (some? background)})})
(case type
"horizontal" [card-horizontal props]
"vertical" [card-vertical props])])
| null |
https://raw.githubusercontent.com/VisionsGlobalEmpowerment/webchange/2b14cfa0b116034312a382763e6aebd67e2f25a7/src/cljs/webchange/ui/components/card/views.cljs
|
clojure
|
(ns webchange.ui.components.card.views
(:require
[reagent.core :as r]
[webchange.ui.components.available-values :as available-values]
[webchange.ui.components.button.views :refer [button]]
[webchange.ui.components.card.background :as background]
[webchange.ui.components.icon.views :refer [navigation-icon]]
[webchange.ui.components.panel.views :refer [panel]]
[webchange.ui.utils.get-class-name :refer [get-class-name]]))
(defn- card-wrapper
[{:keys [actions background class-name]
:or {background "blue-1"}}]
(->> (r/current-component)
(r/children)
(into [panel {:class-name class-name
:class-name-content (get-class-name {"bbs--card--content" true
(str "bbs--card--content--background-" background) true
"bbs--card--content--no-actions" (empty? actions)})
:color background}
(when-not (= background "transparent")
background/data)])))
(defn- card-counter
[{:keys [counter type]}]
[:div {:class-name (get-class-name {"bbs--card--counter" true
(str "bbs--card--counter--type-" type) true})}
(if (number? counter) counter "-")])
(defn- card-icon
[{:keys [counter icon icon-background type] :as props}]
[:div {:class-name (get-class-name {"bbs--card--icon" true
(str "bbs--card--icon--background-" icon-background) (some? icon-background)})}
[navigation-icon {:icon icon
:class-name "bbs--card--icon-data"}]
(when (and (some? counter)
(= type "vertical"))
[card-counter props])])
(defn- card-data
[{:keys [background text type] :as props
:or {background "blue-1"}}]
[:div {:class-name (get-class-name {"bbs--card--data" true
(str "bbs--card--data--background-" background) true})}
(when (= type "horizontal")
[card-counter props])
[:div.bbs--card--text text]])
(defn- card-action
[{:keys [on-click text] :as props}]
(let [handle-click #(when (fn? on-click) (on-click))
button-props (-> props
(dissoc :text)
(assoc :on-click handle-click
:shape "rounded"
:class-name "bbs--card--action"))]
[button button-props
text]))
(defn- card-actions
[{:keys [actions]}]
(when-not (empty? actions)
[:div {:class-name "bbs--card--actions"}
(for [[idx action-data] (->> actions
(remove nil?)
(map-indexed vector))]
^{:key (str "action-" idx)}
[card-action action-data])]))
(defn- card-horizontal
[props]
[:<>
[card-icon props]
[card-data (assoc props :type "horizontal")]
[card-actions props]])
(defn- card-vertical
[props]
[:<>
[card-icon props]
[card-data props]
[card-actions props]])
(defn card
[{:keys [actions background counter icon icon-background text type]
:or {type "horizontal"}
:as props}]
{:pre [(some #{icon} available-values/icon-navigation)
(or (nil? icon-background) (some #{icon-background} available-values/color))
(or (nil? background) (some #{background} available-values/color))
(or (nil? counter) (number? counter))
(or (nil? text) (string? text))
(some #{type} ["horizontal" "vertical"])
(or (nil? actions) (every? #(or (nil? %)
(and (string? (:text %))
(fn? (:on-click %))))
actions))]}
[card-wrapper (merge props
{:class-name (get-class-name {"bbs--card" true
(str "bbs--card--" type) true
(str "bbs--card--background-" background) (some? background)})})
(case type
"horizontal" [card-horizontal props]
"vertical" [card-vertical props])])
|
|
bfad479d1d5c3bd127f7574b330d95fd1bda8317aa3af3263f1a1f3939d18118
|
adomokos/haskell-katas
|
Ex42_FaMoreApplicativesSpec.hs
|
module Ex42_FaMoreApplicativesSpec
( spec
) where
import Control.Applicative
import Test.Hspec
main :: IO ()
main = hspec spec
You can think of functions as boxes , that contain their
eventual result .
Applicative law : pure f < * > x = fmap f x
In conclusion , applicative functors are n't just interesting ,
they 're also useful , because they allow us to combine different
computations , such as I / O computations , non - deterministic computations ,
computations that might have failed , etc . by using the applicative style .
You can think of functions as boxes, that contain their
eventual result.
Applicative law: pure f <*> x = fmap f x
In conclusion, applicative functors aren't just interesting,
they're also useful, because they allow us to combine different
computations, such as I/O computations, non-deterministic computations,
computations that might have failed, etc. by using the applicative style.
-}
-- Implement this function
-- sequenceA' :: (Applicative f) => [f a] -> f [a]
spec :: Spec
spec =
describe "Applicative" $ do
it "works with IO ()" $ do
pending
-- combined <- (___ <$> return "hello" <*> return ___)
combined ` shouldBe ` " helloworld "
it "works with combination of functions" $ do
pending
( ( _ _ _ ) < $ > ( +3 ) < * > ( * 100 ) $ _ _ _ )
` shouldBe ` 508
it "works with lambdas" $ do
pending
( ( _ _ _ ) < $ > ( +3 ) < * > ( * 2 ) < * > ( /2 ) $ 5 )
` shouldBe ` [ 8.0,10.0,2.5 ]
it "works with zipList" $ do
pending
-- newtype ZipList a = ZipList { getZipList :: [a] }
( _ _ _ $ ( _ _ _ ) < $ > ZipList [ 1,2,3 ] < * > ZipList [ 100,100,100 ] )
` shouldBe ` [ 101,102,103 ]
it "applies a function between two applicatives" $ do
pending
fmap ( _ _ _ ) ( Just 4 ) ` shouldBe ` Just [ 4 ]
liftA2 ( _ _ _ ) ( _ _ _ ) ( Just [ 4 ] ) ` shouldBe ` Just [ 3,4 ]
( ( _ _ _ ) < $ > _ _ _ < * > Just [ 4 ] ) ` shouldBe ` Just [ 3,4 ]
it "can create a sequence" $ do
pending
sequenceA ' [ Just 3 , Just 2 , Just 1 ]
` shouldBe ` Just [ 3,2,1 ]
sequenceA ' [ Just 3 , Nothing , Just 1 ]
` shouldBe ` Nothing
sequenceA ' [ ( +3),(+2),(+1 ) ] 3
` shouldBe ` [ 6,5,4 ]
it "can tell if a number satisfies all the predicates in a list" $ do
pending
map ( _ _ _ ) [ ( > 4),(<10),odd ]
` shouldBe ` [ True , True , True ]
( _ _ _ $ map ( \f - > f 7 ) [ ( > 4),(<10),odd ] )
` shouldBe ` True
| null |
https://raw.githubusercontent.com/adomokos/haskell-katas/be06d23192e6aca4297814455247fc74814ccbf1/test/Ex42_FaMoreApplicativesSpec.hs
|
haskell
|
Implement this function
sequenceA' :: (Applicative f) => [f a] -> f [a]
combined <- (___ <$> return "hello" <*> return ___)
newtype ZipList a = ZipList { getZipList :: [a] }
|
module Ex42_FaMoreApplicativesSpec
( spec
) where
import Control.Applicative
import Test.Hspec
main :: IO ()
main = hspec spec
You can think of functions as boxes , that contain their
eventual result .
Applicative law : pure f < * > x = fmap f x
In conclusion , applicative functors are n't just interesting ,
they 're also useful , because they allow us to combine different
computations , such as I / O computations , non - deterministic computations ,
computations that might have failed , etc . by using the applicative style .
You can think of functions as boxes, that contain their
eventual result.
Applicative law: pure f <*> x = fmap f x
In conclusion, applicative functors aren't just interesting,
they're also useful, because they allow us to combine different
computations, such as I/O computations, non-deterministic computations,
computations that might have failed, etc. by using the applicative style.
-}
spec :: Spec
spec =
describe "Applicative" $ do
it "works with IO ()" $ do
pending
combined ` shouldBe ` " helloworld "
it "works with combination of functions" $ do
pending
( ( _ _ _ ) < $ > ( +3 ) < * > ( * 100 ) $ _ _ _ )
` shouldBe ` 508
it "works with lambdas" $ do
pending
( ( _ _ _ ) < $ > ( +3 ) < * > ( * 2 ) < * > ( /2 ) $ 5 )
` shouldBe ` [ 8.0,10.0,2.5 ]
it "works with zipList" $ do
pending
( _ _ _ $ ( _ _ _ ) < $ > ZipList [ 1,2,3 ] < * > ZipList [ 100,100,100 ] )
` shouldBe ` [ 101,102,103 ]
it "applies a function between two applicatives" $ do
pending
fmap ( _ _ _ ) ( Just 4 ) ` shouldBe ` Just [ 4 ]
liftA2 ( _ _ _ ) ( _ _ _ ) ( Just [ 4 ] ) ` shouldBe ` Just [ 3,4 ]
( ( _ _ _ ) < $ > _ _ _ < * > Just [ 4 ] ) ` shouldBe ` Just [ 3,4 ]
it "can create a sequence" $ do
pending
sequenceA ' [ Just 3 , Just 2 , Just 1 ]
` shouldBe ` Just [ 3,2,1 ]
sequenceA ' [ Just 3 , Nothing , Just 1 ]
` shouldBe ` Nothing
sequenceA ' [ ( +3),(+2),(+1 ) ] 3
` shouldBe ` [ 6,5,4 ]
it "can tell if a number satisfies all the predicates in a list" $ do
pending
map ( _ _ _ ) [ ( > 4),(<10),odd ]
` shouldBe ` [ True , True , True ]
( _ _ _ $ map ( \f - > f 7 ) [ ( > 4),(<10),odd ] )
` shouldBe ` True
|
697325786c58ff75fb02be4cb74f2d160d025751d2b09ad42e20008db8495002
|
ndmitchell/supero
|
integrate.hs
|
module Main (integrate1D, main) where
import System
integrate1D :: Double -> Double -> (Double->Double) -> Double
integrate1D l u f =
let d = (u-l)/8.0 in
d * sum
((f l)*0.5 :
f (l+d) :
f (l+(2.0*d)) :
f (l+(3.0*d)) :
f (l+(4.0*d)) :
f (u-(3.0*d)) :
f (u-(2.0*d)) :
f (u-d) :
(f u)*0.5 : [])
integrate2D l1 u1 l2 u2 f = integrate1D l2 u2
(\y->integrate1D l1 u1
(\x->f x y))
zark u v = integrate2D 0.0 u 0.0 v (\x->(\y->x*y))
-- type signature required for compilers lacking the monomorphism restriction
ints = enumFrom 1.0
zarks = zipWith zark ints (map (2.0*) ints)
rtotals = head zarks : zipWith (+) (tail zarks) rtotals
is = map (pow 4) ints
itotals = head is : zipWith (+) (tail is) itotals
es = map (pow 2) (zipWith (-) rtotals itotals)
etotal n = sum (take n es)
The ( analytical ) result should be zero
root n = etotal n
pow x y = y ^ x
#if MAIN
main = print $ root 5000
mul'2 = (*) :: Double -> Double -> Double
add'2 = (+) :: Double -> Double -> Double
sub'2 = (-) :: Double -> Double -> Double
div'2 = (/) :: Double -> Double -> Double
hat'2 = (^) :: Double -> Int -> Double
error'1 = error
eqIntZero'1 = (== 0) :: Int -> Bool
decInt'1 n = (n-1) :: Int -> Int
#endif
#if SUPERO
(*) = mul'2
(+) = add'2
(-) = sub'2
(/) = div'2
(^) = hat'2
error = error'1
enumFrom x = x : enumFrom (x+1.0)
zipWith f x y = case x of
x:xs -> case y of
y:ys -> f x y : zipWith f xs ys
[] -> []
[] -> []
head x = case x of
[] -> error "head"
x:xs -> x
tail x = case x of
[] -> error "tail"
x:xs -> xs
sum xs = case xs of
[] -> 0
x:xs -> sum2 x xs
sum2 x xs = case xs of
[] -> x
y:ys -> sum2 (y + x) ys
map f x = case x of
y:ys -> f y : map f ys
[] -> []
take n xs = case eqIntZero'1 n of
True -> []
False -> case xs of
x:xs -> x : take (decInt'1 n) xs
[] -> []
#endif
| null |
https://raw.githubusercontent.com/ndmitchell/supero/a8b16ea90862e2c021bb139d7a7e9a83700b43b2/supero3/samples/nofib/integrate.hs
|
haskell
|
type signature required for compilers lacking the monomorphism restriction
|
module Main (integrate1D, main) where
import System
integrate1D :: Double -> Double -> (Double->Double) -> Double
integrate1D l u f =
let d = (u-l)/8.0 in
d * sum
((f l)*0.5 :
f (l+d) :
f (l+(2.0*d)) :
f (l+(3.0*d)) :
f (l+(4.0*d)) :
f (u-(3.0*d)) :
f (u-(2.0*d)) :
f (u-d) :
(f u)*0.5 : [])
integrate2D l1 u1 l2 u2 f = integrate1D l2 u2
(\y->integrate1D l1 u1
(\x->f x y))
zark u v = integrate2D 0.0 u 0.0 v (\x->(\y->x*y))
ints = enumFrom 1.0
zarks = zipWith zark ints (map (2.0*) ints)
rtotals = head zarks : zipWith (+) (tail zarks) rtotals
is = map (pow 4) ints
itotals = head is : zipWith (+) (tail is) itotals
es = map (pow 2) (zipWith (-) rtotals itotals)
etotal n = sum (take n es)
The ( analytical ) result should be zero
root n = etotal n
pow x y = y ^ x
#if MAIN
main = print $ root 5000
mul'2 = (*) :: Double -> Double -> Double
add'2 = (+) :: Double -> Double -> Double
sub'2 = (-) :: Double -> Double -> Double
div'2 = (/) :: Double -> Double -> Double
hat'2 = (^) :: Double -> Int -> Double
error'1 = error
eqIntZero'1 = (== 0) :: Int -> Bool
decInt'1 n = (n-1) :: Int -> Int
#endif
#if SUPERO
(*) = mul'2
(+) = add'2
(-) = sub'2
(/) = div'2
(^) = hat'2
error = error'1
enumFrom x = x : enumFrom (x+1.0)
zipWith f x y = case x of
x:xs -> case y of
y:ys -> f x y : zipWith f xs ys
[] -> []
[] -> []
head x = case x of
[] -> error "head"
x:xs -> x
tail x = case x of
[] -> error "tail"
x:xs -> xs
sum xs = case xs of
[] -> 0
x:xs -> sum2 x xs
sum2 x xs = case xs of
[] -> x
y:ys -> sum2 (y + x) ys
map f x = case x of
y:ys -> f y : map f ys
[] -> []
take n xs = case eqIntZero'1 n of
True -> []
False -> case xs of
x:xs -> x : take (decInt'1 n) xs
[] -> []
#endif
|
b50077c1bf160ca45b7def952a340decdb1b13b1f3f3bb4f0ca0e5817ec3bf46
|
phadej/saison
|
Result.hs
|
{-# LANGUAGE RankNTypes #-}
module Saison.Decoding.Result where
-- | /TODO/ I'm not sure this is the type we want.
--
-- Maybe we want bundle input into this, and make this class
" Profunctor - y " .
--
newtype Result e k a = Result
{ unResult :: forall r. (e -> r) -> (a -> k -> r) -> r }
instance Functor (Result e k) where
fmap h (Result k) = Result $ \g f -> k g $ \x -> f (h x)
pureResult :: a -> k -> Result e k a
pureResult x k = Result $ \_ f -> f x k
failResult :: e -> Result e k a
failResult e = Result $ \g _ -> g e
(>>>=) :: Result e k a -> (a -> k -> Result e k' b) -> Result e k' b
Result x >>>= y = Result $ \g f -> x g $ \a k -> unResult (y a k) g f
infixl 1 >>>=
| null |
https://raw.githubusercontent.com/phadej/saison/991d1244b97dadb35adabdf217eb3d5fe2d310fc/src/Saison/Decoding/Result.hs
|
haskell
|
# LANGUAGE RankNTypes #
| /TODO/ I'm not sure this is the type we want.
Maybe we want bundle input into this, and make this class
|
module Saison.Decoding.Result where
" Profunctor - y " .
newtype Result e k a = Result
{ unResult :: forall r. (e -> r) -> (a -> k -> r) -> r }
instance Functor (Result e k) where
fmap h (Result k) = Result $ \g f -> k g $ \x -> f (h x)
pureResult :: a -> k -> Result e k a
pureResult x k = Result $ \_ f -> f x k
failResult :: e -> Result e k a
failResult e = Result $ \g _ -> g e
(>>>=) :: Result e k a -> (a -> k -> Result e k' b) -> Result e k' b
Result x >>>= y = Result $ \g f -> x g $ \a k -> unResult (y a k) g f
infixl 1 >>>=
|
6501956a45092e58dda67a07b7671743f96131e4893477c276e086d47db82994
|
channable/alfred-margaret
|
Automaton.hs
|
-- Alfred-Margaret: Fast Aho-Corasick string searching
Copyright 2019 Channable
--
Licensed under the 3 - clause BSD license , see the LICENSE file in the
-- repository root.
{-# LANGUAGE BangPatterns #-}
# LANGUAGE CPP #
{-# LANGUAGE DeriveAnyClass #-}
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
| An efficient implementation of the Boyer - Moore string search algorithm .
-- -igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140
-- -search_algorithm
--
-- This is case insensitive variant of the algorithm which, unlike the case
-- sensitive variant, has to be aware of the unicode code points that the bytes
-- represent.
--
module Data.Text.BoyerMooreCI.Automaton
( Automaton
, CaseSensitivity (..)
, CodeUnitIndex (..)
, Next (..)
, buildAutomaton
, patternLength
, patternText
, runText
-- Exposed for testing
, minimumSkipForCodePoint
) where
import Control.DeepSeq (NFData)
import Control.Monad.ST (runST)
import Data.Hashable (Hashable (..))
import Data.Text.Internal (Text (..))
import GHC.Generics (Generic)
#if defined(HAS_AESON)
import qualified Data.Aeson as AE
#endif
import Data.Text.CaseSensitivity (CaseSensitivity (..))
import Data.Text.Utf8 (BackwardsIter (..), CodePoint, CodeUnitIndex (..))
import Data.TypedByteArray (Prim, TypedByteArray)
import qualified Data.Char as Char
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import qualified Data.Text.Utf8 as Utf8
import qualified Data.TypedByteArray as TBA
data Next a
= Done !a
| Step !a
| A Boyer - Moore automaton is based on lookup - tables that allow skipping through the haystack .
-- This allows for sub-linear matching in some cases, as we do not have to look at every input
-- character.
--
NOTE : Unlike the AcMachine , a Boyer - Moore automaton only returns non - overlapping matches .
This means that a Boyer - Moore automaton is not a 100 % drop - in replacement for Aho - Corasick .
--
-- Returning overlapping matches would degrade the performance to /O(nm)/ in pathological cases like
-- finding @aaaa@ in @aaaaa....aaaaaa@ as for each match it would scan back the whole /m/ characters
-- of the pattern.
data Automaton = Automaton
{ automatonPattern :: !(TypedByteArray CodePoint)
, automatonPatternHash :: !Int
, automatonSuffixTable :: !SuffixTable
, automatonBadCharLookup :: !BadCharLookup
, automatonMinPatternSkip :: !CodeUnitIndex
}
deriving stock (Generic, Show)
deriving anyclass (NFData)
instance Hashable Automaton where
hashWithSalt salt = hashWithSalt salt . automatonPatternHash
instance Eq Automaton where
x == y = automatonPattern x == automatonPattern y
#if defined(HAS_AESON)
instance AE.FromJSON Automaton where
parseJSON v = buildAutomaton <$> AE.parseJSON v
instance AE.ToJSON Automaton where
toJSON = AE.toJSON . patternText
#endif
buildAutomaton :: Text -> Automaton
buildAutomaton pattern_ =
Automaton
{ automatonPattern = patternVec
, automatonPatternHash = hash pattern_
, automatonSuffixTable = buildSuffixTable patternVec
, automatonBadCharLookup = buildBadCharLookup patternVec
, automatonMinPatternSkip = minimumSkipForVector patternVec
}
where
patternVec = TBA.fromList (Text.unpack pattern_)
| Finds all matches in the text , calling the match callback with the first and last byte index of
-- each match of the pattern.
runText :: forall a
. a
-> (a -> CodeUnitIndex -> CodeUnitIndex -> Next a)
-> Automaton
-> Text
-> a
# INLINE runText #
runText seed f automaton !text
| TBA.null pattern_ = seed
| otherwise = alignPattern seed initialHaystackMin (initialHaystackMin + minPatternSkip - 1)
where
Automaton pattern_ _ suffixTable badCharTable minPatternSkip = automaton
-- In the pattern we always count codepoints,
-- in the haystack we always count code units
-- Highest index that we're allowed to use in the text
haystackMax = case text of Text _ offset len -> CodeUnitIndex (offset + len - 1)
How far we can look back in the text data is first limited by the text
-- offset, and later by what we matched before.
initialHaystackMin = case text of Text _ offset _ -> CodeUnitIndex offset
-- This is our _outer_ loop, called when the pattern is moved
alignPattern
:: a
-> CodeUnitIndex -- Don't read before this point in the haystack
-> CodeUnitIndex -- End of pattern is aligned at this point in the haystack
-> a
# INLINE alignPattern #
alignPattern !result !haystackMin !alignmentEnd
| alignmentEnd > haystackMax = result
| otherwise =
let
!iter = Utf8.unsafeIndexAnywhereInCodePoint' (case text of Text d _ _ -> d) alignmentEnd
!patternIndex = TBA.length pattern_ - 1
-- End of char may be somewhere different than where we started looking
!alignmentEnd' = backwardsIterEndOfChar iter
in
matchLoop result haystackMin alignmentEnd' iter patternIndex
-- The _inner_ loop, called for every pattern character back to front within a pattern alignment.
matchLoop
:: a
-> CodeUnitIndex -- haystackMin, don't read before this point in the haystack
-> CodeUnitIndex -- (adjusted) alignmentEnd, end of pattern is aligned at this point in the haystack
-> BackwardsIter
-> Int -- index in the pattern
-> a
matchLoop !result !haystackMin !alignmentEnd !iter !patternIndex =
let
!haystackCodePointLower = Utf8.lowerCodePoint (backwardsIterChar iter)
in
case haystackCodePointLower == TBA.unsafeIndex pattern_ patternIndex of
True | patternIndex == 0 ->
-- We found a complete match (all pattern characters matched)
let !from = backwardsIterNext iter + 1 - initialHaystackMin
!to = alignmentEnd - initialHaystackMin
in
case f result from to of
Done final -> final
Step intermediate ->
let haystackMin' = alignmentEnd + 1 -- Disallow overlapping matches
alignmentEnd' = alignmentEnd + minPatternSkip
in alignPattern intermediate haystackMin' alignmentEnd'
-- The pattern may be aligned in such a way that the start is before the start of the
-- haystack. This _only_ happens when ⱥ and ⱦ characters occur (due to how minPatternSkip
-- is calculated).
True | backwardsIterNext iter < haystackMin ->
alignPattern result haystackMin (alignmentEnd + 1)
-- We continue by comparing the next character
True ->
let
next = backwardsIterNext iter
!iter' = Utf8.unsafeIndexEndOfCodePoint' (case text of Text d _ _ -> d) next
in
matchLoop result haystackMin alignmentEnd iter' (patternIndex - 1)
-- Character did _not_ match at current position. Check how far the pattern has to move.
False ->
let
-- The bad character table tells us how far we can advance to the right so that the
-- character at the current position in the input string, where matching failed,
-- is lined up with it's rightmost occurrence in the pattern.
!fromBadChar =
backwardsIterEndOfChar iter + badCharLookup badCharTable haystackCodePointLower
This is always at least 1 , ensuring that we make progress
-- Suffixlookup tells us how far we can move the pattern
!fromSuffixLookup =
alignmentEnd + suffixLookup suffixTable patternIndex
!alignmentEnd' = max fromBadChar fromSuffixLookup
in
-- Minimum stays the same
alignPattern result haystackMin alignmentEnd'
| Length of the matched pattern measured in UTF-8 code units ( bytes ) .
patternLength :: Automaton -> CodeUnitIndex
patternLength = Utf8.lengthUtf8 . patternText
-- | Return the pattern that was used to construct the automaton, O(n).
patternText :: Automaton -> Text
patternText = Text.pack . TBA.toList . automatonPattern
-- | Number of bytes that we can skip in the haystack if we want to skip no more
-- than 1 pattern codepoint.
--
-- It must always be a low (safe) estimate, otherwise the algorithm can miss
-- matches. It must account for any variation of upper/lower case characters
-- that may occur in the haystack. In most cases, this is the same number of
-- bytes as for the given codepoint
--
minimumSkipForCodePoint ' a ' = = 1
minimumSkipForCodePoint ' д ' = = 2
minimumSkipForCodePoint ' ⓟ ' = = 3
minimumSkipForCodePoint ' 🎄 ' = = 4
--
minimumSkipForCodePoint :: CodePoint -> CodeUnitIndex
minimumSkipForCodePoint cp =
case Char.ord cp of
c | c < 0x80 -> 1
c | c < 0x800 -> 2
The letters ⱥ and ⱦ are 3 UTF8 bytes , but have unlowerings Ⱥ and Ⱦ of 2 bytes
0x2C65 -> 2 -- ⱥ
0x2C66 -> 2 -- ⱦ
c | c < 0x10000 -> 3
_ -> 4
-- | Number of bytes of the shortest case variation of the given needle. Needles
-- are assumed to be lower case.
--
minimumSkipForVector ( TBA.fromList " ab .. cd " ) = = 6
minimumSkipForVector ( TBA.fromList " aⱥ 💩 " ) = = 7
--
minimumSkipForVector :: TypedByteArray CodePoint -> CodeUnitIndex
minimumSkipForVector = TBA.foldr (\cp s -> s + minimumSkipForCodePoint cp) 0
-- | The suffix table tells us for each codepoint (not byte!) of the pattern how many bytes (not
-- codepoints!) we can jump ahead if the match fails at that point.
newtype SuffixTable = SuffixTable (TypedByteArray CodeUnitIndex)
deriving stock (Generic)
deriving anyclass (NFData)
instance Show SuffixTable where
show (SuffixTable table) = "SuffixTable (TBA.toList " <> show (TBA.toList table) <> ")"
-- | Lookup an entry in the suffix table.
suffixLookup :: SuffixTable -> Int -> CodeUnitIndex
# INLINE suffixLookup #
suffixLookup (SuffixTable table) = indexTable table
buildSuffixTable :: TypedByteArray CodePoint -> SuffixTable
buildSuffixTable pattern_ = runST $ do
let
patLen = TBA.length pattern_
wholePatternSkip = minimumSkipForVector pattern_
table <- TBA.newTypedByteArray patLen
let
-- Case 1: For each position of the pattern we record the shift that would align the pattern so
-- that it starts at the longest suffix that is at the same time a prefix, if a mismatch would
-- happen at that position.
--
-- Suppose the length of the pattern is n, a mismatch occurs at position i in the pattern and j
-- in the haystack, then we know that pattern[i+1..n] == haystack[j+1..j+n-i]. That is, we know
-- that the part of the haystack that we already matched is a suffix of the pattern.
-- If the pattern happens to have a prefix that is equal to or a shorter suffix of that matched
-- suffix, we can shift the pattern to the right so that the pattern starts at the longest
-- suffix that we have seen that conincides with a prefix of the pattern.
--
Consider the pattern ` ababa ` . Then we get
--
p : 0 1 2 3 4
-- Pattern: a b a b a
lastSkipBytes : 5 not touched by
lastSkipBytes : 4 5 " a " = = " a " so if we get a mismatch here we can skip
-- everything but the length of "a"
lastSkipBytes : 4 4 5 " ab " /= " ba " so keep skip value
lastSkipBytes : 2 4 4 5 " " = = " "
lastSkipBytes : 2 2 4 4 5 " abab " /= " baba "
init1 lastSkipBytes p
| p >= 0 = do
let
skipBytes = case suffixIsPrefix pattern_ (p + 1) of
Nothing -> lastSkipBytes
-- Skip the whole pattern _except_ the bytes for the suffix(==prefix)
Just nonSkippableBytes -> wholePatternSkip - nonSkippableBytes
TBA.writeTypedByteArray table p skipBytes
init1 skipBytes (p - 1)
| otherwise = pure ()
-- Case 2: We also have to account for the fact that the matching suffix of the pattern might
-- occur again somewhere within the pattern. In that case, we may not shift as far as if it was
a prefix . That is why the ` init2 ` loop is run after ` init1 ` , potentially overwriting some
-- entries with smaller shifts.
init2 p skipBytes
| p < patLen - 1 = do
If we find a suffix that ends at p , we can skip everything _ after _ p.
let skipBytes' = skipBytes - minimumSkipForCodePoint (TBA.unsafeIndex pattern_ p)
case substringIsSuffix pattern_ p of
Nothing -> pure ()
Just suffixLen -> do
TBA.writeTypedByteArray table (patLen - 1 - suffixLen) skipBytes'
init2 (p + 1) skipBytes'
| otherwise = pure ()
init1 (wholePatternSkip-1) (patLen - 1)
init2 0 wholePatternSkip
TBA.writeTypedByteArray table (patLen - 1) (CodeUnitIndex 1)
SuffixTable <$> TBA.unsafeFreezeTypedByteArray table
| True if the suffix of the @pattern@ starting from @pos@ is a prefix of the pattern
For example , @suffixIsPrefix \"aabbaa\ " 4 = = Just 2@.
suffixIsPrefix :: TypedByteArray CodePoint -> Int -> Maybe CodeUnitIndex
suffixIsPrefix pattern_ pos = go 0 (CodeUnitIndex 0)
where
suffixLen = TBA.length pattern_ - pos
go !i !skipBytes
| i < suffixLen =
let prefixChar = TBA.unsafeIndex pattern_ i in
if prefixChar == TBA.unsafeIndex pattern_ (pos + i)
then go (i + 1) (skipBytes + minimumSkipForCodePoint prefixChar)
else Nothing
| otherwise = Just skipBytes
-- | Length in bytes of the longest suffix of the pattern ending on @pos@. For
example , @substringIsSuffix \"abaacbbaac\ " 4 = = Just 4@ , because the
substring \"baac\ " ends at position 4 and is at the same time the longest
suffix that does so , having a length of 4 characters .
--
For a string like " " , when we detect at pos=4 that baac==baac ,
-- it means that if we get a mismatch before the "baac" suffix, we can skip the
-- "aabcbaac" characters _after_ the "baac" substring. So we can put
-- (minimumSkipForText "aabcbaac") at that point in the suffix table.
--
-- substringIsSuffix (Vector.fromList "ababa") 0 == Nothing -- a == a, but not a proper substring
substringIsSuffix ( Vector.fromList " ababa " ) 1 = = Nothing -- b /= a
substringIsSuffix ( Vector.fromList " ababa " ) 2 = = Nothing -- aba = = , but not a proper substring
substringIsSuffix ( Vector.fromList " ababa " ) 3 = = Nothing -- b /= a
substringIsSuffix ( Vector.fromList " ababa " ) 4 = = Nothing -- ababa = = ababa , but not a proper substring
substringIsSuffix ( Vector.fromList " baba " ) 0 = = Nothing -- b /= a
substringIsSuffix ( Vector.fromList " baba " ) 1 = = Nothing -- ba = = ba , but not a proper substring
substringIsSuffix ( Vector.fromList " abaacaabcbaac " ) 4 = = Just 4 -- baac = = baac
substringIsSuffix ( Vector.fromList " abaacaabcbaac " ) 8 = = Just 1 -- c = = c
--
substringIsSuffix :: TypedByteArray CodePoint -> Int -> Maybe Int
substringIsSuffix pattern_ pos = go 0
where
patLen = TBA.length pattern_
prefix==suffix , so already covered by
| TBA.unsafeIndex pattern_ (pos - i) == TBA.unsafeIndex pattern_ (patLen - 1 - i) =
go (i + 1)
| i == 0 = Nothing -- Nothing matched
| otherwise = Just i
-- | The bad char table tells us how many bytes we may skip ahead when encountering a certain
-- character in the input string. For example, if there's a character that is not contained in the
-- pattern at all, we can skip ahead until after that character.
data BadCharLookup = BadCharLookup
{ badCharLookupTable :: {-# UNPACK #-} !(TypedByteArray CodeUnitIndex)
, badCharLookupMap :: !(HashMap.HashMap CodePoint CodeUnitIndex)
, badCharLookupDefault :: !CodeUnitIndex
}
deriving stock (Generic, Show)
deriving anyclass (NFData)
-- | Number of entries in the fixed-size lookup-table of the bad char table.
badCharTableSize :: Int
# INLINE badCharTableSize #
badCharTableSize = 256
-- | Lookup an entry in the bad char table.
badCharLookup :: BadCharLookup -> CodePoint -> CodeUnitIndex
# INLINE badCharLookup #
badCharLookup (BadCharLookup bclTable bclMap bclDefault) char
| intChar < badCharTableSize = indexTable bclTable intChar
| otherwise = HashMap.lookupDefault bclDefault char bclMap
where
intChar = fromEnum char
buildBadCharLookup :: TypedByteArray CodePoint -> BadCharLookup
buildBadCharLookup pattern_ = runST $ do
let
defaultSkip = minimumSkipForVector pattern_
Initialize table with the maximum skip distance , which is the length of the pattern .
-- This applies to all characters that are not part of the pattern.
table <- (TBA.replicate badCharTableSize defaultSkip)
let
-- Fill the bad character table based on the rightmost occurrence of a character in the pattern.
Note that there is also a variant of Boyer - Moore that records all positions ( see Wikipedia ,
-- but that requires even more storage space).
-- Also note that we exclude the last character of the pattern when building the table.
-- This is because
--
1 . If the last character does not occur anywhere else in the pattern and we encounter it
-- during a mismatch, we can advance the pattern to just after that character:
--
Haystack : aaadcdabcdbb
-- Pattern: abcd
--
-- In the above example, we would match `d` and `c`, but then fail because `d` != `b`.
-- Since `d` only occurs at the very last position of the pattern, we can shift to
--
Haystack : aaadcdabcdbb
-- Pattern: abcd
--
2 . If it does occur anywhere else in the pattern , we can only shift as far as it 's necessary
-- to align it with the haystack:
--
Haystack : aaadddabcdbb
-- Pattern: adcd
--
-- We match `d`, and then there is a mismatch `d` != `c`, which allows us to shift only up to:
Haystack : aaadddabcdbb
-- Pattern: adcd
fillTable !badCharMap !skipBytes = \case
[] -> pure badCharMap
[_] -> pure badCharMap -- The last pattern character doesn't count.
(!patChar : !patChars) ->
let skipBytes' = skipBytes - minimumSkipForCodePoint patChar in
if fromEnum patChar < badCharTableSize
then do
TBA.writeTypedByteArray table (fromEnum patChar) skipBytes'
fillTable badCharMap skipBytes' patChars
else
let badCharMap' = HashMap.insert patChar skipBytes' badCharMap
in fillTable badCharMap' skipBytes' patChars
badCharMap <- fillTable HashMap.empty defaultSkip (TBA.toList pattern_)
tableFrozen <- TBA.unsafeFreezeTypedByteArray table
pure BadCharLookup
{ badCharLookupTable = tableFrozen
, badCharLookupMap = badCharMap
, badCharLookupDefault = defaultSkip
}
-- Helper functions for easily toggling the safety of this module
-- | Read from a lookup table at the specified index.
indexTable :: Prim a => TypedByteArray a -> Int -> a
# INLINE indexTable #
indexTable = TBA.unsafeIndex
| null |
https://raw.githubusercontent.com/channable/alfred-margaret/be96f07bb74c5aa65ce01d664de5d98badbee307/src/Data/Text/BoyerMooreCI/Automaton.hs
|
haskell
|
Alfred-Margaret: Fast Aho-Corasick string searching
repository root.
# LANGUAGE BangPatterns #
# LANGUAGE DeriveAnyClass #
-igm.univ-mlv.fr/~lecroq/string/node14.html#SECTION00140
-search_algorithm
This is case insensitive variant of the algorithm which, unlike the case
sensitive variant, has to be aware of the unicode code points that the bytes
represent.
Exposed for testing
This allows for sub-linear matching in some cases, as we do not have to look at every input
character.
Returning overlapping matches would degrade the performance to /O(nm)/ in pathological cases like
finding @aaaa@ in @aaaaa....aaaaaa@ as for each match it would scan back the whole /m/ characters
of the pattern.
each match of the pattern.
In the pattern we always count codepoints,
in the haystack we always count code units
Highest index that we're allowed to use in the text
offset, and later by what we matched before.
This is our _outer_ loop, called when the pattern is moved
Don't read before this point in the haystack
End of pattern is aligned at this point in the haystack
End of char may be somewhere different than where we started looking
The _inner_ loop, called for every pattern character back to front within a pattern alignment.
haystackMin, don't read before this point in the haystack
(adjusted) alignmentEnd, end of pattern is aligned at this point in the haystack
index in the pattern
We found a complete match (all pattern characters matched)
Disallow overlapping matches
The pattern may be aligned in such a way that the start is before the start of the
haystack. This _only_ happens when ⱥ and ⱦ characters occur (due to how minPatternSkip
is calculated).
We continue by comparing the next character
Character did _not_ match at current position. Check how far the pattern has to move.
The bad character table tells us how far we can advance to the right so that the
character at the current position in the input string, where matching failed,
is lined up with it's rightmost occurrence in the pattern.
Suffixlookup tells us how far we can move the pattern
Minimum stays the same
| Return the pattern that was used to construct the automaton, O(n).
| Number of bytes that we can skip in the haystack if we want to skip no more
than 1 pattern codepoint.
It must always be a low (safe) estimate, otherwise the algorithm can miss
matches. It must account for any variation of upper/lower case characters
that may occur in the haystack. In most cases, this is the same number of
bytes as for the given codepoint
ⱥ
ⱦ
| Number of bytes of the shortest case variation of the given needle. Needles
are assumed to be lower case.
| The suffix table tells us for each codepoint (not byte!) of the pattern how many bytes (not
codepoints!) we can jump ahead if the match fails at that point.
| Lookup an entry in the suffix table.
Case 1: For each position of the pattern we record the shift that would align the pattern so
that it starts at the longest suffix that is at the same time a prefix, if a mismatch would
happen at that position.
Suppose the length of the pattern is n, a mismatch occurs at position i in the pattern and j
in the haystack, then we know that pattern[i+1..n] == haystack[j+1..j+n-i]. That is, we know
that the part of the haystack that we already matched is a suffix of the pattern.
If the pattern happens to have a prefix that is equal to or a shorter suffix of that matched
suffix, we can shift the pattern to the right so that the pattern starts at the longest
suffix that we have seen that conincides with a prefix of the pattern.
Pattern: a b a b a
everything but the length of "a"
Skip the whole pattern _except_ the bytes for the suffix(==prefix)
Case 2: We also have to account for the fact that the matching suffix of the pattern might
occur again somewhere within the pattern. In that case, we may not shift as far as if it was
entries with smaller shifts.
| Length in bytes of the longest suffix of the pattern ending on @pos@. For
it means that if we get a mismatch before the "baac" suffix, we can skip the
"aabcbaac" characters _after_ the "baac" substring. So we can put
(minimumSkipForText "aabcbaac") at that point in the suffix table.
substringIsSuffix (Vector.fromList "ababa") 0 == Nothing -- a == a, but not a proper substring
b /= a
aba = = , but not a proper substring
b /= a
ababa = = ababa , but not a proper substring
b /= a
ba = = ba , but not a proper substring
baac = = baac
c = = c
Nothing matched
| The bad char table tells us how many bytes we may skip ahead when encountering a certain
character in the input string. For example, if there's a character that is not contained in the
pattern at all, we can skip ahead until after that character.
# UNPACK #
| Number of entries in the fixed-size lookup-table of the bad char table.
| Lookup an entry in the bad char table.
This applies to all characters that are not part of the pattern.
Fill the bad character table based on the rightmost occurrence of a character in the pattern.
but that requires even more storage space).
Also note that we exclude the last character of the pattern when building the table.
This is because
during a mismatch, we can advance the pattern to just after that character:
Pattern: abcd
In the above example, we would match `d` and `c`, but then fail because `d` != `b`.
Since `d` only occurs at the very last position of the pattern, we can shift to
Pattern: abcd
to align it with the haystack:
Pattern: adcd
We match `d`, and then there is a mismatch `d` != `c`, which allows us to shift only up to:
Pattern: adcd
The last pattern character doesn't count.
Helper functions for easily toggling the safety of this module
| Read from a lookup table at the specified index.
|
Copyright 2019 Channable
Licensed under the 3 - clause BSD license , see the LICENSE file in the
# LANGUAGE CPP #
# LANGUAGE DeriveGeneric #
# LANGUAGE DerivingStrategies #
# LANGUAGE LambdaCase #
# LANGUAGE ScopedTypeVariables #
| An efficient implementation of the Boyer - Moore string search algorithm .
module Data.Text.BoyerMooreCI.Automaton
( Automaton
, CaseSensitivity (..)
, CodeUnitIndex (..)
, Next (..)
, buildAutomaton
, patternLength
, patternText
, runText
, minimumSkipForCodePoint
) where
import Control.DeepSeq (NFData)
import Control.Monad.ST (runST)
import Data.Hashable (Hashable (..))
import Data.Text.Internal (Text (..))
import GHC.Generics (Generic)
#if defined(HAS_AESON)
import qualified Data.Aeson as AE
#endif
import Data.Text.CaseSensitivity (CaseSensitivity (..))
import Data.Text.Utf8 (BackwardsIter (..), CodePoint, CodeUnitIndex (..))
import Data.TypedByteArray (Prim, TypedByteArray)
import qualified Data.Char as Char
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import qualified Data.Text.Utf8 as Utf8
import qualified Data.TypedByteArray as TBA
data Next a
= Done !a
| Step !a
| A Boyer - Moore automaton is based on lookup - tables that allow skipping through the haystack .
NOTE : Unlike the AcMachine , a Boyer - Moore automaton only returns non - overlapping matches .
This means that a Boyer - Moore automaton is not a 100 % drop - in replacement for Aho - Corasick .
data Automaton = Automaton
{ automatonPattern :: !(TypedByteArray CodePoint)
, automatonPatternHash :: !Int
, automatonSuffixTable :: !SuffixTable
, automatonBadCharLookup :: !BadCharLookup
, automatonMinPatternSkip :: !CodeUnitIndex
}
deriving stock (Generic, Show)
deriving anyclass (NFData)
instance Hashable Automaton where
hashWithSalt salt = hashWithSalt salt . automatonPatternHash
instance Eq Automaton where
x == y = automatonPattern x == automatonPattern y
#if defined(HAS_AESON)
instance AE.FromJSON Automaton where
parseJSON v = buildAutomaton <$> AE.parseJSON v
instance AE.ToJSON Automaton where
toJSON = AE.toJSON . patternText
#endif
buildAutomaton :: Text -> Automaton
buildAutomaton pattern_ =
Automaton
{ automatonPattern = patternVec
, automatonPatternHash = hash pattern_
, automatonSuffixTable = buildSuffixTable patternVec
, automatonBadCharLookup = buildBadCharLookup patternVec
, automatonMinPatternSkip = minimumSkipForVector patternVec
}
where
patternVec = TBA.fromList (Text.unpack pattern_)
| Finds all matches in the text , calling the match callback with the first and last byte index of
runText :: forall a
. a
-> (a -> CodeUnitIndex -> CodeUnitIndex -> Next a)
-> Automaton
-> Text
-> a
# INLINE runText #
runText seed f automaton !text
| TBA.null pattern_ = seed
| otherwise = alignPattern seed initialHaystackMin (initialHaystackMin + minPatternSkip - 1)
where
Automaton pattern_ _ suffixTable badCharTable minPatternSkip = automaton
haystackMax = case text of Text _ offset len -> CodeUnitIndex (offset + len - 1)
How far we can look back in the text data is first limited by the text
initialHaystackMin = case text of Text _ offset _ -> CodeUnitIndex offset
alignPattern
:: a
-> a
# INLINE alignPattern #
alignPattern !result !haystackMin !alignmentEnd
| alignmentEnd > haystackMax = result
| otherwise =
let
!iter = Utf8.unsafeIndexAnywhereInCodePoint' (case text of Text d _ _ -> d) alignmentEnd
!patternIndex = TBA.length pattern_ - 1
!alignmentEnd' = backwardsIterEndOfChar iter
in
matchLoop result haystackMin alignmentEnd' iter patternIndex
matchLoop
:: a
-> BackwardsIter
-> a
matchLoop !result !haystackMin !alignmentEnd !iter !patternIndex =
let
!haystackCodePointLower = Utf8.lowerCodePoint (backwardsIterChar iter)
in
case haystackCodePointLower == TBA.unsafeIndex pattern_ patternIndex of
True | patternIndex == 0 ->
let !from = backwardsIterNext iter + 1 - initialHaystackMin
!to = alignmentEnd - initialHaystackMin
in
case f result from to of
Done final -> final
Step intermediate ->
alignmentEnd' = alignmentEnd + minPatternSkip
in alignPattern intermediate haystackMin' alignmentEnd'
True | backwardsIterNext iter < haystackMin ->
alignPattern result haystackMin (alignmentEnd + 1)
True ->
let
next = backwardsIterNext iter
!iter' = Utf8.unsafeIndexEndOfCodePoint' (case text of Text d _ _ -> d) next
in
matchLoop result haystackMin alignmentEnd iter' (patternIndex - 1)
False ->
let
!fromBadChar =
backwardsIterEndOfChar iter + badCharLookup badCharTable haystackCodePointLower
This is always at least 1 , ensuring that we make progress
!fromSuffixLookup =
alignmentEnd + suffixLookup suffixTable patternIndex
!alignmentEnd' = max fromBadChar fromSuffixLookup
in
alignPattern result haystackMin alignmentEnd'
| Length of the matched pattern measured in UTF-8 code units ( bytes ) .
patternLength :: Automaton -> CodeUnitIndex
patternLength = Utf8.lengthUtf8 . patternText
patternText :: Automaton -> Text
patternText = Text.pack . TBA.toList . automatonPattern
minimumSkipForCodePoint ' a ' = = 1
minimumSkipForCodePoint ' д ' = = 2
minimumSkipForCodePoint ' ⓟ ' = = 3
minimumSkipForCodePoint ' 🎄 ' = = 4
minimumSkipForCodePoint :: CodePoint -> CodeUnitIndex
minimumSkipForCodePoint cp =
case Char.ord cp of
c | c < 0x80 -> 1
c | c < 0x800 -> 2
The letters ⱥ and ⱦ are 3 UTF8 bytes , but have unlowerings Ⱥ and Ⱦ of 2 bytes
c | c < 0x10000 -> 3
_ -> 4
minimumSkipForVector ( TBA.fromList " ab .. cd " ) = = 6
minimumSkipForVector ( TBA.fromList " aⱥ 💩 " ) = = 7
minimumSkipForVector :: TypedByteArray CodePoint -> CodeUnitIndex
minimumSkipForVector = TBA.foldr (\cp s -> s + minimumSkipForCodePoint cp) 0
newtype SuffixTable = SuffixTable (TypedByteArray CodeUnitIndex)
deriving stock (Generic)
deriving anyclass (NFData)
instance Show SuffixTable where
show (SuffixTable table) = "SuffixTable (TBA.toList " <> show (TBA.toList table) <> ")"
suffixLookup :: SuffixTable -> Int -> CodeUnitIndex
# INLINE suffixLookup #
suffixLookup (SuffixTable table) = indexTable table
buildSuffixTable :: TypedByteArray CodePoint -> SuffixTable
buildSuffixTable pattern_ = runST $ do
let
patLen = TBA.length pattern_
wholePatternSkip = minimumSkipForVector pattern_
table <- TBA.newTypedByteArray patLen
let
Consider the pattern ` ababa ` . Then we get
p : 0 1 2 3 4
lastSkipBytes : 5 not touched by
lastSkipBytes : 4 5 " a " = = " a " so if we get a mismatch here we can skip
lastSkipBytes : 4 4 5 " ab " /= " ba " so keep skip value
lastSkipBytes : 2 4 4 5 " " = = " "
lastSkipBytes : 2 2 4 4 5 " abab " /= " baba "
init1 lastSkipBytes p
| p >= 0 = do
let
skipBytes = case suffixIsPrefix pattern_ (p + 1) of
Nothing -> lastSkipBytes
Just nonSkippableBytes -> wholePatternSkip - nonSkippableBytes
TBA.writeTypedByteArray table p skipBytes
init1 skipBytes (p - 1)
| otherwise = pure ()
a prefix . That is why the ` init2 ` loop is run after ` init1 ` , potentially overwriting some
init2 p skipBytes
| p < patLen - 1 = do
If we find a suffix that ends at p , we can skip everything _ after _ p.
let skipBytes' = skipBytes - minimumSkipForCodePoint (TBA.unsafeIndex pattern_ p)
case substringIsSuffix pattern_ p of
Nothing -> pure ()
Just suffixLen -> do
TBA.writeTypedByteArray table (patLen - 1 - suffixLen) skipBytes'
init2 (p + 1) skipBytes'
| otherwise = pure ()
init1 (wholePatternSkip-1) (patLen - 1)
init2 0 wholePatternSkip
TBA.writeTypedByteArray table (patLen - 1) (CodeUnitIndex 1)
SuffixTable <$> TBA.unsafeFreezeTypedByteArray table
| True if the suffix of the @pattern@ starting from @pos@ is a prefix of the pattern
For example , @suffixIsPrefix \"aabbaa\ " 4 = = Just 2@.
suffixIsPrefix :: TypedByteArray CodePoint -> Int -> Maybe CodeUnitIndex
suffixIsPrefix pattern_ pos = go 0 (CodeUnitIndex 0)
where
suffixLen = TBA.length pattern_ - pos
go !i !skipBytes
| i < suffixLen =
let prefixChar = TBA.unsafeIndex pattern_ i in
if prefixChar == TBA.unsafeIndex pattern_ (pos + i)
then go (i + 1) (skipBytes + minimumSkipForCodePoint prefixChar)
else Nothing
| otherwise = Just skipBytes
example , @substringIsSuffix \"abaacbbaac\ " 4 = = Just 4@ , because the
substring \"baac\ " ends at position 4 and is at the same time the longest
suffix that does so , having a length of 4 characters .
For a string like " " , when we detect at pos=4 that baac==baac ,
substringIsSuffix :: TypedByteArray CodePoint -> Int -> Maybe Int
substringIsSuffix pattern_ pos = go 0
where
patLen = TBA.length pattern_
prefix==suffix , so already covered by
| TBA.unsafeIndex pattern_ (pos - i) == TBA.unsafeIndex pattern_ (patLen - 1 - i) =
go (i + 1)
| otherwise = Just i
data BadCharLookup = BadCharLookup
, badCharLookupMap :: !(HashMap.HashMap CodePoint CodeUnitIndex)
, badCharLookupDefault :: !CodeUnitIndex
}
deriving stock (Generic, Show)
deriving anyclass (NFData)
badCharTableSize :: Int
# INLINE badCharTableSize #
badCharTableSize = 256
badCharLookup :: BadCharLookup -> CodePoint -> CodeUnitIndex
# INLINE badCharLookup #
badCharLookup (BadCharLookup bclTable bclMap bclDefault) char
| intChar < badCharTableSize = indexTable bclTable intChar
| otherwise = HashMap.lookupDefault bclDefault char bclMap
where
intChar = fromEnum char
buildBadCharLookup :: TypedByteArray CodePoint -> BadCharLookup
buildBadCharLookup pattern_ = runST $ do
let
defaultSkip = minimumSkipForVector pattern_
Initialize table with the maximum skip distance , which is the length of the pattern .
table <- (TBA.replicate badCharTableSize defaultSkip)
let
Note that there is also a variant of Boyer - Moore that records all positions ( see Wikipedia ,
1 . If the last character does not occur anywhere else in the pattern and we encounter it
Haystack : aaadcdabcdbb
Haystack : aaadcdabcdbb
2 . If it does occur anywhere else in the pattern , we can only shift as far as it 's necessary
Haystack : aaadddabcdbb
Haystack : aaadddabcdbb
fillTable !badCharMap !skipBytes = \case
[] -> pure badCharMap
(!patChar : !patChars) ->
let skipBytes' = skipBytes - minimumSkipForCodePoint patChar in
if fromEnum patChar < badCharTableSize
then do
TBA.writeTypedByteArray table (fromEnum patChar) skipBytes'
fillTable badCharMap skipBytes' patChars
else
let badCharMap' = HashMap.insert patChar skipBytes' badCharMap
in fillTable badCharMap' skipBytes' patChars
badCharMap <- fillTable HashMap.empty defaultSkip (TBA.toList pattern_)
tableFrozen <- TBA.unsafeFreezeTypedByteArray table
pure BadCharLookup
{ badCharLookupTable = tableFrozen
, badCharLookupMap = badCharMap
, badCharLookupDefault = defaultSkip
}
indexTable :: Prim a => TypedByteArray a -> Int -> a
# INLINE indexTable #
indexTable = TBA.unsafeIndex
|
e77ce57e3ee13df652dd92c318a7e49ab5e0fa01a97802ed9a367c1ad34d0920
|
mirage/mirage-nat
|
mirage_nat_lru.ml
|
TODO : types should be more complex and allow for entries mapping
networks and port ranges ( with logic disallowing many : many mappings ) , e.g.
type One = port
type Many = port list
type mapping = [ One * One , One * Many , Many * One ]
Doing this will cause us to need a real parser .
networks and port ranges (with logic disallowing many:many mappings), e.g.
type One = port
type Many = port list
type mapping = [ One * One, One * Many, Many * One ]
Doing this will cause us to need a real parser.
*)
type 'a channel = Ipaddr.V4.t * Ipaddr.V4.t * 'a
module Uniform_weights(T : sig type t end) = struct
type t = T.t
let weight _ = 1
end
module Id = struct
type t = Cstruct.uint16 channel
let compare = Stdlib.compare
end
module Ports = struct
type t = (Mirage_nat.port * Mirage_nat.port) channel
let compare = Stdlib.compare
end
module Port_cache = Lru.F.Make(Ports)(Uniform_weights(Ports))
module Id_cache = Lru.F.Make(Id)(Uniform_weights(Id))
module Storage = struct
type defaults = {
empty_tcp : Port_cache.t;
empty_udp : Port_cache.t;
empty_icmp : Id_cache.t;
}
type t = {
defaults : defaults;
mutable tcp: Port_cache.t;
mutable udp: Port_cache.t;
mutable icmp: Id_cache.t;
}
module Subtable
(L : sig
type transport_channel
module LRU : Lru.F.S with type v = transport_channel channel
val table : t -> LRU.t
val update_table : t -> LRU.t -> unit
end)
= struct
type transport_channel = L.transport_channel
type nonrec channel = transport_channel channel
let lookup t key =
MProf.Trace.label "Mirage_nat_lru.lookup.read";
let table = L.table t in
match L.LRU.find key table with
| None -> None
| Some _ as r -> L.update_table t (L.LRU.promote key table); r
(* cases that should result in a valid mapping:
neither side is already mapped *)
let insert t mappings =
MProf.Trace.label "Mirage_nat_lru.insert";
let table = L.table t in
match mappings with
| [] -> Ok ()
| m :: ms ->
let known (src, _dst) = L.LRU.mem src table in
let first_known = known m in
if List.exists (fun x -> known x <> first_known) ms then Error `Overlap
else (
(* TODO: this is not quite right if all mappings already exist, because it's possible that
the lookups are part of differing pairs -- this situation is pathological, but possible *)
let table' =
List.fold_left (fun t (a, b) -> L.LRU.add a b t) table mappings
in
L.update_table t (L.LRU.trim table');
Ok ()
)
let delete t mappings =
let table = L.table t in
let table' = List.fold_left (fun t m -> L.LRU.remove m t) table mappings in
L.update_table t table'
let pp f t = Fmt.pf f "%d/%d" (L.LRU.size t) (L.LRU.capacity t)
end
module TCP = Subtable(struct module LRU = Port_cache
let table t = t.tcp
let update_table t tcp = t.tcp <- tcp
type transport_channel = Mirage_nat.port * Mirage_nat.port
end)
module UDP = Subtable(struct module LRU = Port_cache
let table t = t.udp
let update_table t udp = t.udp <- udp
type transport_channel = Mirage_nat.port * Mirage_nat.port
end)
module ICMP = Subtable(struct module LRU = Id_cache
let table t = t.icmp
let update_table t icmp = t.icmp <- icmp
type transport_channel = Cstruct.uint16
end)
let reset t =
t.tcp <- t.defaults.empty_tcp;
t.udp <- t.defaults.empty_udp;
t.icmp <- t.defaults.empty_icmp
let remove_connections t ip =
let (=) a b = Ipaddr.V4.compare a b = 0 in
let rec remove pop_lru add f t_old t freed_ports =
match pop_lru t_old with
| None -> t, freed_ports
| Some ((((src, _, _) as k), ((src', _, data) as v)), t_old) ->
let t, freed_ports =
if ip = src then
t, f data :: freed_ports
else if ip = src' then
t, freed_ports
else
add k v t, freed_ports
in
remove pop_lru add f t_old t freed_ports
in
let tcp, freed_tcp_ports = remove Port_cache.pop_lru Port_cache.add fst (t.tcp) t.defaults.empty_tcp [] in
t.tcp <- tcp;
let udp, freed_udp_ports = remove Port_cache.pop_lru Port_cache.add fst (t.udp) t.defaults.empty_udp [] in
t.udp <- udp;
let icmp, freed_icmp_ports = remove Id_cache.pop_lru Id_cache.add (fun x -> x) (t.icmp) t.defaults.empty_icmp [] in
t.icmp <- icmp;
Mirage_nat.{ tcp = freed_tcp_ports ; udp = freed_udp_ports ; icmp = freed_icmp_ports }
let empty ~tcp_size ~udp_size ~icmp_size =
let defaults = {
empty_tcp = Port_cache.empty tcp_size;
empty_udp = Port_cache.empty udp_size;
empty_icmp = Id_cache.empty icmp_size;
} in
{
defaults;
tcp = defaults.empty_tcp;
udp = defaults.empty_udp;
icmp = defaults.empty_icmp;
}
let pp_summary f t =
Fmt.pf f "NAT{tcp:%a udp:%a icmp:%a}"
TCP.pp t.tcp
UDP.pp t.udp
ICMP.pp t.icmp
let is_port_free t protocol ~src ~dst ~src_port ~dst_port =
not
(match protocol with
| `Tcp -> Port_cache.mem (src, dst, (src_port, dst_port)) t.tcp
| `Udp -> Port_cache.mem (src, dst, (src_port, dst_port)) t.udp
| `Icmp -> Id_cache.mem (src, dst, src_port) t.icmp)
end
include Nat_rewrite.Make(Storage)
let empty = Storage.empty
let pp_summary = Storage.pp_summary
| null |
https://raw.githubusercontent.com/mirage/mirage-nat/ca43415d503b4178135f1df4ecde5e27b5444aa1/lib/mirage_nat_lru.ml
|
ocaml
|
cases that should result in a valid mapping:
neither side is already mapped
TODO: this is not quite right if all mappings already exist, because it's possible that
the lookups are part of differing pairs -- this situation is pathological, but possible
|
TODO : types should be more complex and allow for entries mapping
networks and port ranges ( with logic disallowing many : many mappings ) , e.g.
type One = port
type Many = port list
type mapping = [ One * One , One * Many , Many * One ]
Doing this will cause us to need a real parser .
networks and port ranges (with logic disallowing many:many mappings), e.g.
type One = port
type Many = port list
type mapping = [ One * One, One * Many, Many * One ]
Doing this will cause us to need a real parser.
*)
type 'a channel = Ipaddr.V4.t * Ipaddr.V4.t * 'a
module Uniform_weights(T : sig type t end) = struct
type t = T.t
let weight _ = 1
end
module Id = struct
type t = Cstruct.uint16 channel
let compare = Stdlib.compare
end
module Ports = struct
type t = (Mirage_nat.port * Mirage_nat.port) channel
let compare = Stdlib.compare
end
module Port_cache = Lru.F.Make(Ports)(Uniform_weights(Ports))
module Id_cache = Lru.F.Make(Id)(Uniform_weights(Id))
module Storage = struct
type defaults = {
empty_tcp : Port_cache.t;
empty_udp : Port_cache.t;
empty_icmp : Id_cache.t;
}
type t = {
defaults : defaults;
mutable tcp: Port_cache.t;
mutable udp: Port_cache.t;
mutable icmp: Id_cache.t;
}
module Subtable
(L : sig
type transport_channel
module LRU : Lru.F.S with type v = transport_channel channel
val table : t -> LRU.t
val update_table : t -> LRU.t -> unit
end)
= struct
type transport_channel = L.transport_channel
type nonrec channel = transport_channel channel
let lookup t key =
MProf.Trace.label "Mirage_nat_lru.lookup.read";
let table = L.table t in
match L.LRU.find key table with
| None -> None
| Some _ as r -> L.update_table t (L.LRU.promote key table); r
let insert t mappings =
MProf.Trace.label "Mirage_nat_lru.insert";
let table = L.table t in
match mappings with
| [] -> Ok ()
| m :: ms ->
let known (src, _dst) = L.LRU.mem src table in
let first_known = known m in
if List.exists (fun x -> known x <> first_known) ms then Error `Overlap
else (
let table' =
List.fold_left (fun t (a, b) -> L.LRU.add a b t) table mappings
in
L.update_table t (L.LRU.trim table');
Ok ()
)
let delete t mappings =
let table = L.table t in
let table' = List.fold_left (fun t m -> L.LRU.remove m t) table mappings in
L.update_table t table'
let pp f t = Fmt.pf f "%d/%d" (L.LRU.size t) (L.LRU.capacity t)
end
module TCP = Subtable(struct module LRU = Port_cache
let table t = t.tcp
let update_table t tcp = t.tcp <- tcp
type transport_channel = Mirage_nat.port * Mirage_nat.port
end)
module UDP = Subtable(struct module LRU = Port_cache
let table t = t.udp
let update_table t udp = t.udp <- udp
type transport_channel = Mirage_nat.port * Mirage_nat.port
end)
module ICMP = Subtable(struct module LRU = Id_cache
let table t = t.icmp
let update_table t icmp = t.icmp <- icmp
type transport_channel = Cstruct.uint16
end)
let reset t =
t.tcp <- t.defaults.empty_tcp;
t.udp <- t.defaults.empty_udp;
t.icmp <- t.defaults.empty_icmp
let remove_connections t ip =
let (=) a b = Ipaddr.V4.compare a b = 0 in
let rec remove pop_lru add f t_old t freed_ports =
match pop_lru t_old with
| None -> t, freed_ports
| Some ((((src, _, _) as k), ((src', _, data) as v)), t_old) ->
let t, freed_ports =
if ip = src then
t, f data :: freed_ports
else if ip = src' then
t, freed_ports
else
add k v t, freed_ports
in
remove pop_lru add f t_old t freed_ports
in
let tcp, freed_tcp_ports = remove Port_cache.pop_lru Port_cache.add fst (t.tcp) t.defaults.empty_tcp [] in
t.tcp <- tcp;
let udp, freed_udp_ports = remove Port_cache.pop_lru Port_cache.add fst (t.udp) t.defaults.empty_udp [] in
t.udp <- udp;
let icmp, freed_icmp_ports = remove Id_cache.pop_lru Id_cache.add (fun x -> x) (t.icmp) t.defaults.empty_icmp [] in
t.icmp <- icmp;
Mirage_nat.{ tcp = freed_tcp_ports ; udp = freed_udp_ports ; icmp = freed_icmp_ports }
let empty ~tcp_size ~udp_size ~icmp_size =
let defaults = {
empty_tcp = Port_cache.empty tcp_size;
empty_udp = Port_cache.empty udp_size;
empty_icmp = Id_cache.empty icmp_size;
} in
{
defaults;
tcp = defaults.empty_tcp;
udp = defaults.empty_udp;
icmp = defaults.empty_icmp;
}
let pp_summary f t =
Fmt.pf f "NAT{tcp:%a udp:%a icmp:%a}"
TCP.pp t.tcp
UDP.pp t.udp
ICMP.pp t.icmp
let is_port_free t protocol ~src ~dst ~src_port ~dst_port =
not
(match protocol with
| `Tcp -> Port_cache.mem (src, dst, (src_port, dst_port)) t.tcp
| `Udp -> Port_cache.mem (src, dst, (src_port, dst_port)) t.udp
| `Icmp -> Id_cache.mem (src, dst, src_port) t.icmp)
end
include Nat_rewrite.Make(Storage)
let empty = Storage.empty
let pp_summary = Storage.pp_summary
|
31d4ff67e4c7deeb0ae6ef885288b0e24ee7ea6532683ca7d3281c94f742ffd5
|
CodyReichert/qi
|
tf-cmucl.lisp
|
;;;; -*- Mode: lisp; indent-tabs-mode: nil -*-
;;;
;;; tf-cmucl.lisp --- CMUCL implementation of trivial-features.
;;;
Copyright ( C ) 2007 ,
;;;
;;; 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 :cl-user)
;;;; Endianness
(pushnew (alien:with-alien ((ptr (array (alien:unsigned 8) 2)))
(setf (sys:sap-ref-16 (alien:alien-sap ptr) 0) #xfeff)
(ecase (sys:sap-ref-8 (alien:alien-sap ptr) 0)
(#xfe (intern "BIG-ENDIAN" :keyword))
(#xff (intern "LITTLE-ENDIAN" :keyword))))
*features*)
;;;; OS
CMUCL already pushes : UNIX , : BSD , : and : .
;;;; CPU
CMUCL already pushes : PPC and : X86 .
| null |
https://raw.githubusercontent.com/CodyReichert/qi/9cf6d31f40e19f4a7f60891ef7c8c0381ccac66f/dependencies/trivial-features-latest/src/tf-cmucl.lisp
|
lisp
|
-*- Mode: lisp; indent-tabs-mode: nil -*-
tf-cmucl.lisp --- CMUCL implementation of trivial-features.
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.
Endianness
OS
CPU
|
Copyright ( C ) 2007 ,
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 :cl-user)
(pushnew (alien:with-alien ((ptr (array (alien:unsigned 8) 2)))
(setf (sys:sap-ref-16 (alien:alien-sap ptr) 0) #xfeff)
(ecase (sys:sap-ref-8 (alien:alien-sap ptr) 0)
(#xfe (intern "BIG-ENDIAN" :keyword))
(#xff (intern "LITTLE-ENDIAN" :keyword))))
*features*)
CMUCL already pushes : UNIX , : BSD , : and : .
CMUCL already pushes : PPC and : X86 .
|
e1461a98b6b48c3b771dc716ad678350a98ca6a24204df868d3313f623879bfb
|
NorfairKing/smos
|
Archive.hs
|
module Smos.Archive (smosArchive) where
import Control.Monad.Logger
import Smos.Archive.Commands
import Smos.Archive.Env
import Smos.Archive.OptParse
smosArchive :: IO ()
smosArchive = do
Instructions dispatch settings <- getInstructions
runStderrLoggingT $
filterLogger (\_ ll -> ll >= setLogLevel settings) $
runA settings $ case dispatch of
DispatchFile file -> smosArchiveFile file
DispatchExport exportSets -> smosArchiveExport exportSets
| null |
https://raw.githubusercontent.com/NorfairKing/smos/489f5b510c9a30a3c79fef0a0d1a796464705923/smos-archive/src/Smos/Archive.hs
|
haskell
|
module Smos.Archive (smosArchive) where
import Control.Monad.Logger
import Smos.Archive.Commands
import Smos.Archive.Env
import Smos.Archive.OptParse
smosArchive :: IO ()
smosArchive = do
Instructions dispatch settings <- getInstructions
runStderrLoggingT $
filterLogger (\_ ll -> ll >= setLogLevel settings) $
runA settings $ case dispatch of
DispatchFile file -> smosArchiveFile file
DispatchExport exportSets -> smosArchiveExport exportSets
|
|
1dbc261669a33a03104301dc320a906fd589047d84295331fc630989fce9a129
|
tebeka/popen
|
project.clj
|
(defproject popen "0.3.1"
:description "popen (subprocess) library for Clojure"
:url ""
:dependencies [[org.clojure/clojure "1.8.0"]])
| null |
https://raw.githubusercontent.com/tebeka/popen/91cc8b16426e2db025c361888a8b9322e37808d9/project.clj
|
clojure
|
(defproject popen "0.3.1"
:description "popen (subprocess) library for Clojure"
:url ""
:dependencies [[org.clojure/clojure "1.8.0"]])
|
|
7c11df97799b44e6fac5e6fe09130ab30e00956f764bba60c1c80fb13a9c16af
|
igorhvr/bedlam
|
root.scm
|
" root.scm " 's and Laguerre 's methods for finding roots .
Copyright ( C ) 1996 , 1997
;
;Permission to copy this software, to modify it, to redistribute it,
;to distribute modified versions, and to use it for any purpose is
;granted, subject to the following restrictions and understandings.
;
1 . Any copy made of this software must include this copyright notice
;in full.
;
2 . I have made no warranty or representation that the operation of
;this software will be error-free, and I am under no obligation to
;provide any services, by way of maintenance, update, or otherwise.
;
3 . In conjunction with products arising from the use of this
;material, there shall be no use of my name in any advertising,
;promotional, or sales literature without prior written consent in
;each case.
(require 'logical)
;;;; Newton's Method explained in:
, " The Art of Computer Programming " , Vol 2 /
Seminumerical Algorithms , Reading Massachusetts , Addison - Wesley
Publishing Company , 2nd Edition , p. 510
;@
(define (newton:find-integer-root f df/dx x_0)
(let loop ((x x_0) (fx (f x_0)))
(cond
((zero? fx) x)
(else
(let ((df (df/dx x)))
(cond
((zero? df) #f) ; stuck at local min/max
(else
(let* ((delta (quotient (+ fx (quotient df 2)) df))
(next-x (cond ((not (zero? delta)) (- x delta))
((positive? fx) (- x 1))
(else (- x -1))))
(next-fx (f next-x)))
(cond ((>= (abs next-fx) (abs fx)) x)
(else (loop next-x next-fx)))))))))))
;;(define (integer-sqrt y)
( : find - integer - root ( lambda ( x ) ( - ( * x x ) y ) )
( lambda ( x ) ( * 2 x ) )
( ash 1 ( quotient ( integer - length y ) 2 ) ) ) )
;@
(define (newton:find-root f df/dx x_0 prec)
(if (and (negative? prec) (integer? prec))
(let loop ((x x_0) (fx (f x_0)) (count prec))
(cond ((zero? count) x)
(else (let ((df (df/dx x)))
(cond ((zero? df) #f) ; stuck at local min/max
(else (let* ((next-x (- x (/ fx df)))
(next-fx (f next-x)))
(cond ((= next-x x) x)
((> (abs next-fx) (abs fx)) #f)
(else (loop next-x next-fx
(+ 1 count)))))))))))
(let loop ((x x_0) (fx (f x_0)))
(cond ((< (abs fx) prec) x)
(else (let ((df (df/dx x)))
(cond ((zero? df) #f) ; stuck at local min/max
(else (let* ((next-x (- x (/ fx df)))
(next-fx (f next-x)))
(cond ((= next-x x) x)
((> (abs next-fx) (abs fx)) #f)
(else (loop next-x next-fx))))))))))))
, " The Laguerre Method for Finding the Zeros of
Polynomials " , IEEE Transactions on Circuits and Systems , Vol . 36 ,
No . 11 , November 1989 , pp 1377 - 1381 .
;@
(define (laguerre:find-root f df/dz ddf/dz^2 z_0 prec)
(if (and (negative? prec) (integer? prec))
(let loop ((z z_0) (fz (f z_0)) (count prec))
(cond ((zero? count) z)
(else
(let* ((df (df/dz z))
(ddf (ddf/dz^2 z))
(disc (sqrt (- (* df df) (* fz ddf)))))
(if (zero? disc)
#f
(let* ((next-z
(- z (/ fz (if (negative? (+ (* (real-part df)
(real-part disc))
(* (imag-part df)
(imag-part disc))))
(- disc) disc))))
(next-fz (f next-z)))
(cond ((>= (magnitude next-fz) (magnitude fz)) z)
(else (loop next-z next-fz (+ 1 count))))))))))
(let loop ((z z_0) (fz (f z_0)) (delta-z #f))
(cond ((< (magnitude fz) prec) z)
(else
(let* ((df (df/dz z))
(ddf (ddf/dz^2 z))
(disc (sqrt (- (* df df) (* fz ddf)))))
;;(print 'disc disc)
(if (zero? disc)
#f
(let* ((next-z
(- z (/ fz (if (negative? (+ (* (real-part df)
(real-part disc))
(* (imag-part df)
(imag-part disc))))
(- disc) disc))))
(next-delta-z (magnitude (- next-z z))))
;;(print 'next-z next-z )
;;(print '(f next-z) (f next-z))
;;(print 'delta-z delta-z 'next-delta-z next-delta-z)
(cond ((zero? next-delta-z) z)
((and delta-z (>= next-delta-z delta-z)) z)
(else
(loop next-z (f next-z) next-delta-z)))))))))))
;@
(define (laguerre:find-polynomial-root deg f df/dz ddf/dz^2 z_0 prec)
(if (and (negative? prec) (integer? prec))
(let loop ((z z_0) (fz (f z_0)) (count prec))
(cond ((zero? count) z)
(else
(let* ((df (df/dz z))
(ddf (ddf/dz^2 z))
(tmp (* (+ deg -1) df))
(sqrt-H (sqrt (- (* tmp tmp) (* deg (+ deg -1) fz ddf))))
(df+sqrt-H (+ df sqrt-H))
(df-sqrt-H (- df sqrt-H))
(next-z
(- z (/ (* deg fz)
(if (>= (magnitude df+sqrt-H)
(magnitude df-sqrt-H))
df+sqrt-H
df-sqrt-H)))))
(loop next-z (f next-z) (+ 1 count))))))
(let loop ((z z_0) (fz (f z_0)))
(cond ((< (magnitude fz) prec) z)
(else
(let* ((df (df/dz z))
(ddf (ddf/dz^2 z))
(tmp (* (+ deg -1) df))
(sqrt-H (sqrt (- (* tmp tmp) (* deg (+ deg -1) fz ddf))))
(df+sqrt-H (+ df sqrt-H))
(df-sqrt-H (- df sqrt-H))
(next-z
(- z (/ (* deg fz)
(if (>= (magnitude df+sqrt-H)
(magnitude df-sqrt-H))
df+sqrt-H
df-sqrt-H)))))
(loop next-z (f next-z))))))))
(define (secant:find-root-1 f x0 x1 prec must-bracket?)
(letrec ((stop?
(cond ((procedure? prec) prec)
((and (integer? prec) (negative? prec))
(lambda (x0 f0 x1 f1 count)
(>= count (- prec))))
(else
(lambda (x0 f0 x1 f1 count)
(and (< (abs f0) prec)
(< (abs f1) prec))))))
(bracket-iter
(lambda (xlo flo glo xhi fhi ghi count)
(define (step xnew fnew)
(cond ((or (= xnew xlo)
(= xnew xhi))
(let ((xmid (+ xlo (* 1/2 (- xhi xlo)))))
(if (= xnew xmid)
xmid
(step xmid (f xmid)))))
((positive? fnew)
(bracket-iter xlo flo (if glo (* 0.5 glo) 1)
xnew fnew #f
(+ count 1)))
(else
(bracket-iter xnew fnew #f
xhi fhi (if ghi (* 0.5 ghi) 1)
(+ count 1)))))
(if (stop? xlo flo xhi fhi count)
(if (> (abs flo) (abs fhi)) xhi xlo)
(let* ((fflo (if glo (* glo flo) flo))
(ffhi (if ghi (* ghi fhi) fhi))
(del (- (/ fflo (- ffhi fflo))))
(xnew (+ xlo (* del (- xhi xlo))))
(fnew (f xnew)))
(step xnew fnew))))))
(let ((f0 (f x0))
(f1 (f x1)))
(cond ((<= f0 0 f1)
(bracket-iter x0 f0 #f x1 f1 #f 0))
((<= f1 0 f0)
(bracket-iter x1 f1 #f x0 f0 #f 0))
(must-bracket? #f)
(else
(let secant-iter ((x0 x0)
(f0 f0)
(x1 x1)
(f1 f1)
(count 0))
(cond ((stop? x0 f0 x1 f1 count)
(if (> (abs f0) (abs f1)) x1 x0))
((<= f0 0 f1)
(bracket-iter x0 f0 #f x1 f1 #f count))
((>= f0 0 f1)
(bracket-iter x1 f1 #f x0 f0 #f count))
((= f0 f1) #f)
(else
(let* ((xnew (+ x0 (* (- (/ f0 (- f1 f0))) (- x1 x0))))
(fnew (f xnew))
(fmax (max (abs f1) (abs fnew))))
(secant-iter x1 f1 xnew fnew (+ count 1)))))))))))
;@
(define (secant:find-root f x0 x1 prec)
(secant:find-root-1 f x0 x1 prec #f))
(define (secant:find-bracketed-root f x0 x1 prec)
(secant:find-root-1 f x0 x1 prec #t))
| null |
https://raw.githubusercontent.com/igorhvr/bedlam/b62e0d047105bb0473bdb47c58b23f6ca0f79a4e/iasylum/slib/3b2/root.scm
|
scheme
|
Permission to copy this software, to modify it, to redistribute it,
to distribute modified versions, and to use it for any purpose is
granted, subject to the following restrictions and understandings.
in full.
this software will be error-free, and I am under no obligation to
provide any services, by way of maintenance, update, or otherwise.
material, there shall be no use of my name in any advertising,
promotional, or sales literature without prior written consent in
each case.
Newton's Method explained in:
@
stuck at local min/max
(define (integer-sqrt y)
@
stuck at local min/max
stuck at local min/max
@
(print 'disc disc)
(print 'next-z next-z )
(print '(f next-z) (f next-z))
(print 'delta-z delta-z 'next-delta-z next-delta-z)
@
@
|
" root.scm " 's and Laguerre 's methods for finding roots .
Copyright ( C ) 1996 , 1997
1 . Any copy made of this software must include this copyright notice
2 . I have made no warranty or representation that the operation of
3 . In conjunction with products arising from the use of this
(require 'logical)
, " The Art of Computer Programming " , Vol 2 /
Seminumerical Algorithms , Reading Massachusetts , Addison - Wesley
Publishing Company , 2nd Edition , p. 510
(define (newton:find-integer-root f df/dx x_0)
(let loop ((x x_0) (fx (f x_0)))
(cond
((zero? fx) x)
(else
(let ((df (df/dx x)))
(cond
(else
(let* ((delta (quotient (+ fx (quotient df 2)) df))
(next-x (cond ((not (zero? delta)) (- x delta))
((positive? fx) (- x 1))
(else (- x -1))))
(next-fx (f next-x)))
(cond ((>= (abs next-fx) (abs fx)) x)
(else (loop next-x next-fx)))))))))))
( : find - integer - root ( lambda ( x ) ( - ( * x x ) y ) )
( lambda ( x ) ( * 2 x ) )
( ash 1 ( quotient ( integer - length y ) 2 ) ) ) )
(define (newton:find-root f df/dx x_0 prec)
(if (and (negative? prec) (integer? prec))
(let loop ((x x_0) (fx (f x_0)) (count prec))
(cond ((zero? count) x)
(else (let ((df (df/dx x)))
(else (let* ((next-x (- x (/ fx df)))
(next-fx (f next-x)))
(cond ((= next-x x) x)
((> (abs next-fx) (abs fx)) #f)
(else (loop next-x next-fx
(+ 1 count)))))))))))
(let loop ((x x_0) (fx (f x_0)))
(cond ((< (abs fx) prec) x)
(else (let ((df (df/dx x)))
(else (let* ((next-x (- x (/ fx df)))
(next-fx (f next-x)))
(cond ((= next-x x) x)
((> (abs next-fx) (abs fx)) #f)
(else (loop next-x next-fx))))))))))))
, " The Laguerre Method for Finding the Zeros of
Polynomials " , IEEE Transactions on Circuits and Systems , Vol . 36 ,
No . 11 , November 1989 , pp 1377 - 1381 .
(define (laguerre:find-root f df/dz ddf/dz^2 z_0 prec)
(if (and (negative? prec) (integer? prec))
(let loop ((z z_0) (fz (f z_0)) (count prec))
(cond ((zero? count) z)
(else
(let* ((df (df/dz z))
(ddf (ddf/dz^2 z))
(disc (sqrt (- (* df df) (* fz ddf)))))
(if (zero? disc)
#f
(let* ((next-z
(- z (/ fz (if (negative? (+ (* (real-part df)
(real-part disc))
(* (imag-part df)
(imag-part disc))))
(- disc) disc))))
(next-fz (f next-z)))
(cond ((>= (magnitude next-fz) (magnitude fz)) z)
(else (loop next-z next-fz (+ 1 count))))))))))
(let loop ((z z_0) (fz (f z_0)) (delta-z #f))
(cond ((< (magnitude fz) prec) z)
(else
(let* ((df (df/dz z))
(ddf (ddf/dz^2 z))
(disc (sqrt (- (* df df) (* fz ddf)))))
(if (zero? disc)
#f
(let* ((next-z
(- z (/ fz (if (negative? (+ (* (real-part df)
(real-part disc))
(* (imag-part df)
(imag-part disc))))
(- disc) disc))))
(next-delta-z (magnitude (- next-z z))))
(cond ((zero? next-delta-z) z)
((and delta-z (>= next-delta-z delta-z)) z)
(else
(loop next-z (f next-z) next-delta-z)))))))))))
(define (laguerre:find-polynomial-root deg f df/dz ddf/dz^2 z_0 prec)
(if (and (negative? prec) (integer? prec))
(let loop ((z z_0) (fz (f z_0)) (count prec))
(cond ((zero? count) z)
(else
(let* ((df (df/dz z))
(ddf (ddf/dz^2 z))
(tmp (* (+ deg -1) df))
(sqrt-H (sqrt (- (* tmp tmp) (* deg (+ deg -1) fz ddf))))
(df+sqrt-H (+ df sqrt-H))
(df-sqrt-H (- df sqrt-H))
(next-z
(- z (/ (* deg fz)
(if (>= (magnitude df+sqrt-H)
(magnitude df-sqrt-H))
df+sqrt-H
df-sqrt-H)))))
(loop next-z (f next-z) (+ 1 count))))))
(let loop ((z z_0) (fz (f z_0)))
(cond ((< (magnitude fz) prec) z)
(else
(let* ((df (df/dz z))
(ddf (ddf/dz^2 z))
(tmp (* (+ deg -1) df))
(sqrt-H (sqrt (- (* tmp tmp) (* deg (+ deg -1) fz ddf))))
(df+sqrt-H (+ df sqrt-H))
(df-sqrt-H (- df sqrt-H))
(next-z
(- z (/ (* deg fz)
(if (>= (magnitude df+sqrt-H)
(magnitude df-sqrt-H))
df+sqrt-H
df-sqrt-H)))))
(loop next-z (f next-z))))))))
(define (secant:find-root-1 f x0 x1 prec must-bracket?)
(letrec ((stop?
(cond ((procedure? prec) prec)
((and (integer? prec) (negative? prec))
(lambda (x0 f0 x1 f1 count)
(>= count (- prec))))
(else
(lambda (x0 f0 x1 f1 count)
(and (< (abs f0) prec)
(< (abs f1) prec))))))
(bracket-iter
(lambda (xlo flo glo xhi fhi ghi count)
(define (step xnew fnew)
(cond ((or (= xnew xlo)
(= xnew xhi))
(let ((xmid (+ xlo (* 1/2 (- xhi xlo)))))
(if (= xnew xmid)
xmid
(step xmid (f xmid)))))
((positive? fnew)
(bracket-iter xlo flo (if glo (* 0.5 glo) 1)
xnew fnew #f
(+ count 1)))
(else
(bracket-iter xnew fnew #f
xhi fhi (if ghi (* 0.5 ghi) 1)
(+ count 1)))))
(if (stop? xlo flo xhi fhi count)
(if (> (abs flo) (abs fhi)) xhi xlo)
(let* ((fflo (if glo (* glo flo) flo))
(ffhi (if ghi (* ghi fhi) fhi))
(del (- (/ fflo (- ffhi fflo))))
(xnew (+ xlo (* del (- xhi xlo))))
(fnew (f xnew)))
(step xnew fnew))))))
(let ((f0 (f x0))
(f1 (f x1)))
(cond ((<= f0 0 f1)
(bracket-iter x0 f0 #f x1 f1 #f 0))
((<= f1 0 f0)
(bracket-iter x1 f1 #f x0 f0 #f 0))
(must-bracket? #f)
(else
(let secant-iter ((x0 x0)
(f0 f0)
(x1 x1)
(f1 f1)
(count 0))
(cond ((stop? x0 f0 x1 f1 count)
(if (> (abs f0) (abs f1)) x1 x0))
((<= f0 0 f1)
(bracket-iter x0 f0 #f x1 f1 #f count))
((>= f0 0 f1)
(bracket-iter x1 f1 #f x0 f0 #f count))
((= f0 f1) #f)
(else
(let* ((xnew (+ x0 (* (- (/ f0 (- f1 f0))) (- x1 x0))))
(fnew (f xnew))
(fmax (max (abs f1) (abs fnew))))
(secant-iter x1 f1 xnew fnew (+ count 1)))))))))))
(define (secant:find-root f x0 x1 prec)
(secant:find-root-1 f x0 x1 prec #f))
(define (secant:find-bracketed-root f x0 x1 prec)
(secant:find-root-1 f x0 x1 prec #t))
|
c0d744ccd451f4675c1f27e11485827ac03f5fe10ca3c69755f4d003af6d5ecd
|
shayan-najd/NativeMetaprogramming
|
CompilerDebugging.hs
|
module Options.CompilerDebugging where
import Types
compilerDebuggingOptions :: [Flag]
compilerDebuggingOptions =
[ flag { flagName = "-dcore-lint"
, flagDescription = "Turn on internal sanity checking"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-to-file"
, flagDescription = "Dump to files instead of stdout"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-asm"
, flagDescription = "Dump assembly"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-bcos"
, flagDescription = "Dump interpreter byte code"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-cmm"
, flagDescription = "Dump C-- output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-core-stats"
, flagDescription =
"Print a one-line summary of the size of the Core program at the "++
"end of the optimisation pipeline"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-cse"
, flagDescription = "Dump CSE output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-deriv"
, flagDescription = "Dump deriving output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-ds"
, flagDescription = "Dump desugarer output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-foreign"
, flagDescription = "Dump ``foreign export`` stubs"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-hpc"
, flagDescription = "Dump after instrumentation for program coverage"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-inlinings"
, flagDescription = "Dump inlining info"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-llvm"
, flagDescription = "Dump LLVM intermediate code. "++
"Implies :ghc-flag:`-fllvm`."
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-occur-anal"
, flagDescription = "Dump occurrence analysis output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-opt-cmm"
, flagDescription = "Dump the results of C-- to C-- optimising passes"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-parsed"
, flagDescription = "Dump parse tree"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-prep"
, flagDescription = "Dump prepared core"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rn"
, flagDescription = "Dump renamer output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rule-firings"
, flagDescription = "Dump rule firing info"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rule-rewrites"
, flagDescription = "Dump detailed rule firing info"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rules"
, flagDescription = "Dump rules"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-vect"
, flagDescription = "Dump vectoriser input and output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-simpl"
, flagDescription = "Dump final simplifier output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-simpl-iterations"
, flagDescription = "Dump output from each simplifier iteration"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-spec"
, flagDescription = "Dump specialiser output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-splices"
, flagDescription =
"Dump TH spliced expressions, and what they evaluate to"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-stg"
, flagDescription = "Dump final STG"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-stranal"
, flagDescription = "Dump strictness analyser output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-str-signatures"
, flagDescription = "Dump strictness signatures"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-tc"
, flagDescription = "Dump typechecker output"
, flagType = DynamicFlag
}
, flag { flagName = "-dth-dec-file"
, flagDescription =
"Show evaluated TH declarations in a .th.hs file"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-types"
, flagDescription = "Dump type signatures"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-worker-wrapper"
, flagDescription = "Dump worker-wrapper output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-if-trace"
, flagDescription = "Trace interface files"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-tc-trace"
, flagDescription = "Trace typechecker"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-vt-trace"
, flagDescription = "Trace vectoriser"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rn-trace"
, flagDescription = "Trace renamer"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rn-stats"
, flagDescription = "Renamer stats"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-simpl-stats"
, flagDescription = "Dump simplifier stats"
, flagType = DynamicFlag
}
, flag { flagName = "-dno-debug-output"
, flagDescription = "Suppress unsolicited debugging output"
, flagType = StaticFlag
}
, flag { flagName = "-dppr-debug"
, flagDescription = "Turn on debug printing (more verbose)"
, flagType = StaticFlag
}
, flag { flagName = "-dppr-user-length"
, flagDescription =
"Set the depth for printing expressions in error msgs"
, flagType = DynamicFlag
}
, flag { flagName = "-dppr-cols⟨N⟩"
, flagDescription =
"Set the width of debugging output. For example ``-dppr-cols200``"
, flagType = DynamicFlag
}
, flag { flagName = "-dppr-case-as-let"
, flagDescription =
"Print single alternative case expressions as strict lets."
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-all"
, flagDescription =
"In core dumps, suppress everything (except for uniques) that is "++
"suppressible."
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-uniques"
, flagDescription =
"Suppress the printing of uniques in debug output (easier to use "++
"``diff``)"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-idinfo"
, flagDescription =
"Suppress extended information about identifiers where they "++
"are bound"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-unfoldings"
, flagDescription =
"Suppress the printing of the stable unfolding of a variable at "++
"its binding site"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-module-prefixes"
, flagDescription =
"Suppress the printing of module qualification prefixes"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-type-signatures"
, flagDescription = "Suppress type signatures"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-type-applications"
, flagDescription = "Suppress type applications"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-coercions"
, flagDescription =
"Suppress the printing of coercions in Core dumps to make them "++
"shorter"
, flagType = DynamicFlag
}
, flag { flagName = "-dsource-stats"
, flagDescription = "Dump haskell source stats"
, flagType = DynamicFlag
}
, flag { flagName = "-dcmm-lint"
, flagDescription = "C-- pass sanity checking"
, flagType = DynamicFlag
}
, flag { flagName = "-dstg-lint"
, flagDescription = "STG pass sanity checking"
, flagType = DynamicFlag
}
, flag { flagName = "-dstg-stats"
, flagDescription = "Dump STG stats"
, flagType = DynamicFlag
}
, flag { flagName = "-dverbose-core2core"
, flagDescription = "Show output from each core-to-core pass"
, flagType = DynamicFlag
}
, flag { flagName = "-dverbose-stg2stg"
, flagDescription = "Show output from each STG-to-STG pass"
, flagType = DynamicFlag
}
, flag { flagName = "-dshow-passes"
, flagDescription = "Print out each pass name as it happens"
, flagType = DynamicFlag
}
, flag { flagName = "-dfaststring-stats"
, flagDescription =
"Show statistics for fast string usage when finished"
, flagType = DynamicFlag
}
, flag { flagName = "-frule-check"
, flagDescription =
"Report sites with rules that could have fired but didn't. "++
"Takes a string argument."
, flagType = DynamicFlag
}
]
| null |
https://raw.githubusercontent.com/shayan-najd/NativeMetaprogramming/24e5f85990642d3f0b0044be4327b8f52fce2ba3/utils/mkUserGuidePart/Options/CompilerDebugging.hs
|
haskell
|
module Options.CompilerDebugging where
import Types
compilerDebuggingOptions :: [Flag]
compilerDebuggingOptions =
[ flag { flagName = "-dcore-lint"
, flagDescription = "Turn on internal sanity checking"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-to-file"
, flagDescription = "Dump to files instead of stdout"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-asm"
, flagDescription = "Dump assembly"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-bcos"
, flagDescription = "Dump interpreter byte code"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-cmm"
, flagDescription = "Dump C-- output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-core-stats"
, flagDescription =
"Print a one-line summary of the size of the Core program at the "++
"end of the optimisation pipeline"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-cse"
, flagDescription = "Dump CSE output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-deriv"
, flagDescription = "Dump deriving output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-ds"
, flagDescription = "Dump desugarer output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-foreign"
, flagDescription = "Dump ``foreign export`` stubs"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-hpc"
, flagDescription = "Dump after instrumentation for program coverage"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-inlinings"
, flagDescription = "Dump inlining info"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-llvm"
, flagDescription = "Dump LLVM intermediate code. "++
"Implies :ghc-flag:`-fllvm`."
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-occur-anal"
, flagDescription = "Dump occurrence analysis output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-opt-cmm"
, flagDescription = "Dump the results of C-- to C-- optimising passes"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-parsed"
, flagDescription = "Dump parse tree"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-prep"
, flagDescription = "Dump prepared core"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rn"
, flagDescription = "Dump renamer output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rule-firings"
, flagDescription = "Dump rule firing info"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rule-rewrites"
, flagDescription = "Dump detailed rule firing info"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rules"
, flagDescription = "Dump rules"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-vect"
, flagDescription = "Dump vectoriser input and output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-simpl"
, flagDescription = "Dump final simplifier output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-simpl-iterations"
, flagDescription = "Dump output from each simplifier iteration"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-spec"
, flagDescription = "Dump specialiser output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-splices"
, flagDescription =
"Dump TH spliced expressions, and what they evaluate to"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-stg"
, flagDescription = "Dump final STG"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-stranal"
, flagDescription = "Dump strictness analyser output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-str-signatures"
, flagDescription = "Dump strictness signatures"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-tc"
, flagDescription = "Dump typechecker output"
, flagType = DynamicFlag
}
, flag { flagName = "-dth-dec-file"
, flagDescription =
"Show evaluated TH declarations in a .th.hs file"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-types"
, flagDescription = "Dump type signatures"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-worker-wrapper"
, flagDescription = "Dump worker-wrapper output"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-if-trace"
, flagDescription = "Trace interface files"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-tc-trace"
, flagDescription = "Trace typechecker"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-vt-trace"
, flagDescription = "Trace vectoriser"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rn-trace"
, flagDescription = "Trace renamer"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-rn-stats"
, flagDescription = "Renamer stats"
, flagType = DynamicFlag
}
, flag { flagName = "-ddump-simpl-stats"
, flagDescription = "Dump simplifier stats"
, flagType = DynamicFlag
}
, flag { flagName = "-dno-debug-output"
, flagDescription = "Suppress unsolicited debugging output"
, flagType = StaticFlag
}
, flag { flagName = "-dppr-debug"
, flagDescription = "Turn on debug printing (more verbose)"
, flagType = StaticFlag
}
, flag { flagName = "-dppr-user-length"
, flagDescription =
"Set the depth for printing expressions in error msgs"
, flagType = DynamicFlag
}
, flag { flagName = "-dppr-cols⟨N⟩"
, flagDescription =
"Set the width of debugging output. For example ``-dppr-cols200``"
, flagType = DynamicFlag
}
, flag { flagName = "-dppr-case-as-let"
, flagDescription =
"Print single alternative case expressions as strict lets."
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-all"
, flagDescription =
"In core dumps, suppress everything (except for uniques) that is "++
"suppressible."
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-uniques"
, flagDescription =
"Suppress the printing of uniques in debug output (easier to use "++
"``diff``)"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-idinfo"
, flagDescription =
"Suppress extended information about identifiers where they "++
"are bound"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-unfoldings"
, flagDescription =
"Suppress the printing of the stable unfolding of a variable at "++
"its binding site"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-module-prefixes"
, flagDescription =
"Suppress the printing of module qualification prefixes"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-type-signatures"
, flagDescription = "Suppress type signatures"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-type-applications"
, flagDescription = "Suppress type applications"
, flagType = DynamicFlag
}
, flag { flagName = "-dsuppress-coercions"
, flagDescription =
"Suppress the printing of coercions in Core dumps to make them "++
"shorter"
, flagType = DynamicFlag
}
, flag { flagName = "-dsource-stats"
, flagDescription = "Dump haskell source stats"
, flagType = DynamicFlag
}
, flag { flagName = "-dcmm-lint"
, flagDescription = "C-- pass sanity checking"
, flagType = DynamicFlag
}
, flag { flagName = "-dstg-lint"
, flagDescription = "STG pass sanity checking"
, flagType = DynamicFlag
}
, flag { flagName = "-dstg-stats"
, flagDescription = "Dump STG stats"
, flagType = DynamicFlag
}
, flag { flagName = "-dverbose-core2core"
, flagDescription = "Show output from each core-to-core pass"
, flagType = DynamicFlag
}
, flag { flagName = "-dverbose-stg2stg"
, flagDescription = "Show output from each STG-to-STG pass"
, flagType = DynamicFlag
}
, flag { flagName = "-dshow-passes"
, flagDescription = "Print out each pass name as it happens"
, flagType = DynamicFlag
}
, flag { flagName = "-dfaststring-stats"
, flagDescription =
"Show statistics for fast string usage when finished"
, flagType = DynamicFlag
}
, flag { flagName = "-frule-check"
, flagDescription =
"Report sites with rules that could have fired but didn't. "++
"Takes a string argument."
, flagType = DynamicFlag
}
]
|
|
356c9a61ae50cb87c9a2e7aa86c99522333352f6bb7066f9b23793cbb108fc9d
|
quchen/generative-art
|
Main.hs
|
module Main (main) where
import Control.Monad
import Data.Coerce
import Data.List
import qualified Data.Vector as V
import Graphics.Rendering.Cairo as C hiding (height, width, x, y)
import Options.Applicative
import System.Random.MWC (initialize)
import qualified Data.Set as S
import Data.Vector (Vector)
import Draw
import Draw.Plotting
import Draw.Plotting.CmdArgs
import Geometry as G
import Geometry.Algorithms.PerlinNoise
import Geometry.Algorithms.Sampling
import qualified Geometry.Processes.FlowField as ODE
import Numerics.DifferentialEquation
import Numerics.Functions
import Numerics.VectorAnalysis
-- Higher values yield lower-frequency noise
noiseScale :: Double
noiseScale = 0.5
noiseSeed :: Int
noiseSeed = 519496
main :: IO ()
main = do
options <- commandLineOptions
geometry <- mkGeometry options
let (width, height, _) = widthHeightMargin options
render "out/vector_fields.svg" (round width) (round height) $ do
cairoScope $ do
setColor black
C.paint
cairoScope $ do
setColor white
setLineWidth 0.3
for_ geometry drawFieldLine
let drawing = sequence
[ plot (Polyline part)
| trajectory <- geometry
, part <- simplifyTrajectoryRadial 2 <$> splitIntoInsideParts options trajectory ]
plottingSettings = def { _feedrate = 6000, _zTravelHeight = 5, _zDrawingHeight = -2 }
writeGCodeFile (_outputFileG options) (runPlot plottingSettings drawing)
mkGeometry :: Options -> IO [Polyline Vector]
mkGeometry options = do
let (width_opt, height_opt, margin_opt) = widthHeightMargin options
width_mm = width_opt - 2 * margin_opt
height_mm = height_opt - 2 * margin_opt
gen <- initialize (V.fromList [fromIntegral noiseSeed])
startPoints <- poissonDisc gen PoissonDiscParams
{ _poissonShape = boundingBox [ Vec2 (-50) 0, Vec2 (width_mm + 50) (height_mm / 10) ]
, _poissonK = 3
, _poissonRadius = 5
}
let mkTrajectory start =
Polyline
. map (\(_t, pos) -> pos)
. takeWhile
(\(t, pos) -> t <= 200 && pos `insideBoundingBox` (Vec2 (-50) (-50), Vec2 (width_mm+50) (height_mm+50)))
$ fieldLine (velocityField options) (G.transform (G.scale' 1 10) start)
pure ((coerce . minimizePenHovering . S.fromList . concatMap (splitIntoInsideParts options . mkTrajectory)) startPoints)
drawFieldLine :: Polyline Vector -> Render ()
drawFieldLine (Polyline polyLine) = cairoScope $ do
let simplified = simplifyTrajectoryRadial 2 polyLine
unless (null (drop 2 simplified)) $ do
sketch (PolyBezier (bezierSmoothen simplified))
stroke
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn f = groupBy (\x y -> f x == f y)
splitIntoInsideParts :: Sequential list => Options -> Polyline list -> [[Vec2]]
splitIntoInsideParts options (Polyline xs) = filter (\(x:_) -> x `insideBoundingBox` drawBB) . groupOn (\p -> insideBoundingBox p drawBB) . toList $ xs
where
drawBB = boundingBox (Vec2 margin margin, Vec2 (width - margin) (height - margin))
(width, height, margin) = widthHeightMargin options
-- 2D vector potential, which in 2D is umm well a scalar potential.
vectorPotential :: Options -> Vec2 -> Double
vectorPotential options p = noiseScale *. perlin2 params p
where
(width, height, _) = widthHeightMargin options
params = PerlinParameters
{ _perlinFrequency = 3 / (noiseScale * min width height)
, _perlinLacunarity = 2
, _perlinOctaves = 1
, _perlinPersistence = 0.5
, _perlinSeed = noiseSeed
}
rotationField :: Options -> Vec2 -> Vec2
rotationField options = curlZ (vectorPotential options)
velocityField :: Options -> Vec2 -> Vec2
velocityField options p@(Vec2 x y) = Vec2 1 0 +. perturbationStrength *. rotationField options p
where
perturbationStrength =
0.8
* logisticRamp (0.6*width_mm) (width_mm/6) x
* gaussianFalloff (0.5*height_mm) (0.4*height_mm) y
(width, height, margin) = widthHeightMargin options
width_mm = width - 2 * margin
height_mm = height - 2 * margin
widthHeightMargin :: Options -> (Double, Double, Double)
widthHeightMargin Options{_canvas=Canvas{_canvasWidth=width, _canvasHeight=height, _canvasMargin=margin}} = (width, height, margin)
fieldLine
:: (Vec2 -> Vec2)
-> Vec2
-> [(Double, Vec2)]
fieldLine f p0 = rungeKuttaAdaptiveStep (ODE.fieldLine f) p0 t0 dt0 tolNorm tol
where
t0 = 0
dt0 = 1
-- Decrease exponent for more accurate results
tol = 1e-4
tolNorm = norm
data Options = Options
{ _outputFileG :: FilePath
, _canvas :: Canvas
} deriving (Eq, Ord, Show)
commandLineOptions :: IO Options
commandLineOptions = execParser parserOpts
where
progOpts = Options
<$> strOption (mconcat
[ long "output"
, short 'o'
, metavar "<file>"
, help "Output GCode file"
])
<*> canvasP
parserOpts = info (progOpts <**> helper)
( fullDesc
<> progDesc "Convert SVG to GCode"
<> header "Not that much of SVG is supported, bear with me…" )
| null |
https://raw.githubusercontent.com/quchen/generative-art/245bb2948642d5d7fdd538b5095c00ba3a9cbaa2/penplotting/FlowLines/Main.hs
|
haskell
|
Higher values yield lower-frequency noise
2D vector potential, which in 2D is umm well a scalar potential.
Decrease exponent for more accurate results
|
module Main (main) where
import Control.Monad
import Data.Coerce
import Data.List
import qualified Data.Vector as V
import Graphics.Rendering.Cairo as C hiding (height, width, x, y)
import Options.Applicative
import System.Random.MWC (initialize)
import qualified Data.Set as S
import Data.Vector (Vector)
import Draw
import Draw.Plotting
import Draw.Plotting.CmdArgs
import Geometry as G
import Geometry.Algorithms.PerlinNoise
import Geometry.Algorithms.Sampling
import qualified Geometry.Processes.FlowField as ODE
import Numerics.DifferentialEquation
import Numerics.Functions
import Numerics.VectorAnalysis
noiseScale :: Double
noiseScale = 0.5
noiseSeed :: Int
noiseSeed = 519496
main :: IO ()
main = do
options <- commandLineOptions
geometry <- mkGeometry options
let (width, height, _) = widthHeightMargin options
render "out/vector_fields.svg" (round width) (round height) $ do
cairoScope $ do
setColor black
C.paint
cairoScope $ do
setColor white
setLineWidth 0.3
for_ geometry drawFieldLine
let drawing = sequence
[ plot (Polyline part)
| trajectory <- geometry
, part <- simplifyTrajectoryRadial 2 <$> splitIntoInsideParts options trajectory ]
plottingSettings = def { _feedrate = 6000, _zTravelHeight = 5, _zDrawingHeight = -2 }
writeGCodeFile (_outputFileG options) (runPlot plottingSettings drawing)
mkGeometry :: Options -> IO [Polyline Vector]
mkGeometry options = do
let (width_opt, height_opt, margin_opt) = widthHeightMargin options
width_mm = width_opt - 2 * margin_opt
height_mm = height_opt - 2 * margin_opt
gen <- initialize (V.fromList [fromIntegral noiseSeed])
startPoints <- poissonDisc gen PoissonDiscParams
{ _poissonShape = boundingBox [ Vec2 (-50) 0, Vec2 (width_mm + 50) (height_mm / 10) ]
, _poissonK = 3
, _poissonRadius = 5
}
let mkTrajectory start =
Polyline
. map (\(_t, pos) -> pos)
. takeWhile
(\(t, pos) -> t <= 200 && pos `insideBoundingBox` (Vec2 (-50) (-50), Vec2 (width_mm+50) (height_mm+50)))
$ fieldLine (velocityField options) (G.transform (G.scale' 1 10) start)
pure ((coerce . minimizePenHovering . S.fromList . concatMap (splitIntoInsideParts options . mkTrajectory)) startPoints)
drawFieldLine :: Polyline Vector -> Render ()
drawFieldLine (Polyline polyLine) = cairoScope $ do
let simplified = simplifyTrajectoryRadial 2 polyLine
unless (null (drop 2 simplified)) $ do
sketch (PolyBezier (bezierSmoothen simplified))
stroke
groupOn :: Eq b => (a -> b) -> [a] -> [[a]]
groupOn f = groupBy (\x y -> f x == f y)
splitIntoInsideParts :: Sequential list => Options -> Polyline list -> [[Vec2]]
splitIntoInsideParts options (Polyline xs) = filter (\(x:_) -> x `insideBoundingBox` drawBB) . groupOn (\p -> insideBoundingBox p drawBB) . toList $ xs
where
drawBB = boundingBox (Vec2 margin margin, Vec2 (width - margin) (height - margin))
(width, height, margin) = widthHeightMargin options
vectorPotential :: Options -> Vec2 -> Double
vectorPotential options p = noiseScale *. perlin2 params p
where
(width, height, _) = widthHeightMargin options
params = PerlinParameters
{ _perlinFrequency = 3 / (noiseScale * min width height)
, _perlinLacunarity = 2
, _perlinOctaves = 1
, _perlinPersistence = 0.5
, _perlinSeed = noiseSeed
}
rotationField :: Options -> Vec2 -> Vec2
rotationField options = curlZ (vectorPotential options)
velocityField :: Options -> Vec2 -> Vec2
velocityField options p@(Vec2 x y) = Vec2 1 0 +. perturbationStrength *. rotationField options p
where
perturbationStrength =
0.8
* logisticRamp (0.6*width_mm) (width_mm/6) x
* gaussianFalloff (0.5*height_mm) (0.4*height_mm) y
(width, height, margin) = widthHeightMargin options
width_mm = width - 2 * margin
height_mm = height - 2 * margin
widthHeightMargin :: Options -> (Double, Double, Double)
widthHeightMargin Options{_canvas=Canvas{_canvasWidth=width, _canvasHeight=height, _canvasMargin=margin}} = (width, height, margin)
fieldLine
:: (Vec2 -> Vec2)
-> Vec2
-> [(Double, Vec2)]
fieldLine f p0 = rungeKuttaAdaptiveStep (ODE.fieldLine f) p0 t0 dt0 tolNorm tol
where
t0 = 0
dt0 = 1
tol = 1e-4
tolNorm = norm
data Options = Options
{ _outputFileG :: FilePath
, _canvas :: Canvas
} deriving (Eq, Ord, Show)
commandLineOptions :: IO Options
commandLineOptions = execParser parserOpts
where
progOpts = Options
<$> strOption (mconcat
[ long "output"
, short 'o'
, metavar "<file>"
, help "Output GCode file"
])
<*> canvasP
parserOpts = info (progOpts <**> helper)
( fullDesc
<> progDesc "Convert SVG to GCode"
<> header "Not that much of SVG is supported, bear with me…" )
|
8a644e76f0a5e15287db528ff37528b32da2ebe4ef58035085b7b353bed39884
|
hipsleek/hipsleek
|
predicate.ml
|
#include "xdebug.cppo"
open VarGen
open Globals
open Gen
module DD = Debug
module Err = Error
module I = Iast
module CA = Cast
module CP = Cpure
module CPP = Cpure_pred
module CF = Cformula
module MCP = Mcpure
module CEQ = Checkeq
module TP = Tpdispatcher
let pure_relation_name_of_heap_pred (CP.SpecVar (_, hp, p))=
let rec look_up map=
match map with
| [] -> report_error no_pos "predicate.pure_relation_name_of_heap_pred"
| (id1,id2)::rest -> if String.compare id1 hp = 0 then (CP.SpecVar (RelT [], id2, p)) else
look_up rest
in
look_up !Cast.pure_hprel_map
let heap_pred_name_of_pure_relation (CP.SpecVar (_, pure_hp, p))=
let rec look_up map=
match map with
| [] -> None
| (id1,id2)::rest -> if String.compare id2 pure_hp = 0 then Some (CP.SpecVar(HpT, id1, p)) else
look_up rest
in
look_up !Cast.pure_hprel_map
let pure_of_heap_pred_gen_h hf0=
let rec helper hf=
match hf with
| CF.Star { CF.h_formula_star_h1 = hf1;
CF.h_formula_star_h2 = hf2;
CF.h_formula_star_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1,nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.Star {CF.h_formula_star_h1 = nh1;
CF.h_formula_star_h2 = nh2;
CF.h_formula_star_pos = pos}
in (nh, ps1@ps2)
| CF.StarMinus { CF.h_formula_starminus_h1 = hf1;
CF.h_formula_starminus_h2 = hf2;
CF.h_formula_starminus_aliasing = al;
CF.h_formula_starminus_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.StarMinus { CF.h_formula_starminus_h1 = nh1;
CF.h_formula_starminus_h2 = nh2;
CF.h_formula_starminus_aliasing = al;
CF.h_formula_starminus_pos = pos}
in (nh, ps1@ps2)
| CF.ConjStar { CF.h_formula_conjstar_h1 = hf1;
CF.h_formula_conjstar_h2 = hf2;
CF.h_formula_conjstar_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.ConjStar { CF.h_formula_conjstar_h1 = nh1;
CF.h_formula_conjstar_h2 = nh2;
CF.h_formula_conjstar_pos = pos}
in (nh, ps1@ps2)
| CF.ConjConj { CF.h_formula_conjconj_h1 = hf1;
CF.h_formula_conjconj_h2 = hf2;
CF.h_formula_conjconj_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.ConjConj { CF.h_formula_conjconj_h1 = nh1;
CF.h_formula_conjconj_h2 = nh2;
CF.h_formula_conjconj_pos = pos}
in (nh, ps1@ps2)
| CF.Phase { CF.h_formula_phase_rd = hf1;
CF.h_formula_phase_rw = hf2;
CF.h_formula_phase_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.Phase { CF.h_formula_phase_rd = nh1;
CF.h_formula_phase_rw = nh2;
CF.h_formula_phase_pos = pos}
in (nh, ps1@ps2)
| CF.Conj { CF.h_formula_conj_h1 = hf1;
CF.h_formula_conj_h2 = hf2;
CF.h_formula_conj_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.Conj { CF.h_formula_conj_h1 = nh1;
CF.h_formula_conj_h2 = nh2;
CF.h_formula_conj_pos = pos}
in (nh, ps1@ps2)
| CF.HRel (hp, eargs, p) ->
let prel = pure_relation_name_of_heap_pred hp in
let p= CP.mkRel prel eargs p in
(CF.HEmp, [(p,hp)])
| _ -> (hf,[])
in
helper hf0
let pure_of_heap_pred_x pos hfs=
let ps, p_hps = List.fold_left ( fun (ls,ls2) hf ->
let _, pr_ps = pure_of_heap_pred_gen_h hf in
let ps,hprels = List.split pr_ps in
(ls@ps, ls2@hprels)
) ([],[]) hfs
in
let p = CP.conj_of_list ps pos in
p,p_hps
let pure_of_heap_pred pos hfs=
let pr1 = !CP.print_formula in
let pr2 = pr_list_ln Cprinter.prtt_string_of_h_formula in
let pr3 = pr_list ( pr_pair ! CP.print_sv ! ) in
Debug.no_1 "pure_of_heap_pred" pr2 (pr_pair pr1 !CP.print_svl)
(fun _ -> pure_of_heap_pred_x pos hfs) hfs
let pure_of_heap_pred_x f0=
(* let rec helper f= *)
(* match f with *)
(* | CF.Base fb -> *)
let nh , ps = pure_of_heap_pred_h fb . CF.formula_base_heap in
let new_p = CP.conj_of_list ps fb . CF.formula_base_pos in
{ fb with CF.formula_base_pure = MCP.merge_mems fb . CF.formula_base_pure ( MCP.mix_of_pure new_p ) true ;
(* CF.formula_base_heap = nh; *)
(* } *)
(* | CF.Exists _ -> *)
let qvars , base1 = CF.split_quantifiers f in
let nf = helper in
(* CF.add_quantifiers qvars nf *)
(* | CF.Or orf -> *)
let nf1 = helper orf . CF.formula_or_f1 in
(* let nf2 = helper orf.CF.formula_or_f2 in *)
( CF.Or { orf with CF.formula_or_f1 = nf1 ;
CF.formula_or_f2 = nf2 ; } )
(* in *)
(* helper f0 *)
let trans_rels_gen pf0 =
let rec helper pf=
match pf with
| CP.BForm (bf,a) -> begin
match bf with
| (CP.RelForm (r, eargs, p),x) ->
let ohp = heap_pred_name_of_pure_relation r in
(
match ohp with
| None -> (pf,[])
| Some hp -> (CP.BForm (((CP.BConst (true, p)), x) ,a), [(CF.HRel (hp, eargs, p))])
)
| _ -> (pf, [])
end
| CP.And (f1,f2,p) -> let nf1, hf1 = helper f1 in
let nf2, hf2= helper f2 in
let np = match (CP.isConstTrue nf1), (CP.isConstTrue nf2) with
| true,true -> nf1
| true,_ -> nf2
| _, true -> nf1
| _ -> CP.And (nf1,nf2,p)
in (np, hf1@hf2)
| CP.AndList lp-> let r,hfs = List.fold_left (fun (ps, hfs) (l, p) ->
let np, n_hfs = helper p in
if CP.isConstTrue np then
(ps, hfs@n_hfs)
else (ps@[(l,np)], hfs@n_hfs)
) ([],[]) lp in
if r = [] then (CP.mkTrue no_pos, hfs) else (CP.AndList r,hfs)
| CP.Or (f1,f2,c,p) -> let nf1, hf1 = helper f1 in
let nf2, hf2= helper f2 in
let np = match (CP.isConstTrue nf1), (CP.isConstTrue nf2) with
| true,true -> nf1
| true,_ -> nf2
| _, true -> nf1
| _ -> CP.Or (nf1,nf2, c,p)
in (np, hf1@hf2)
| CP.Not (f,b,p) -> let np,hfs = helper f in
if CP.isConstTrue np then
(CP.mkTrue p, hfs)
else (CP.Not (np, b, p), hfs)
| CP.Forall (a,f,c,p) -> let np,hfs = helper f in
if CP.isConstTrue np then
(CP.mkTrue p, hfs)
else
(CP.Forall (a,np,c,p), hfs)
| CP.Exists (a,f,b,p) -> let np,hfs = helper f in
if CP.isConstTrue np then
(CP.mkTrue p, hfs)
else
(CP.Exists (a,np,b,p), hfs)
in
helper pf0
let trans_rels_x pf0 =
let rec helper pf=
match pf with
| CP.BForm (bf,a) -> begin
match bf with
| (CP.RelForm (r, eargs, p),x) ->
let ohp = heap_pred_name_of_pure_relation r in
(
match ohp with
| None -> None
| Some hp -> Some (hp, CF.HRel (hp, eargs, p))
)
| _ -> None
end
| _ -> None
in
let ps = CP.list_of_conjs pf0 in
let pr_hp_rhs = List.map helper ps in
List.fold_left (fun r (r_opt) -> match r_opt with
| None -> r
| Some a -> r@[a]
) [] pr_hp_rhs
let trans_rels pf0 =
let pr1 = !CP.print_formula in
let pr2 = pr_list (pr_pair !CP.print_sv Cprinter.prtt_string_of_h_formula) in
Debug.no_1 "trans_rels" pr1 ( pr2)
(fun _ -> trans_rels_x pf0) pf0
let heap_pred_of_pure_x p0=
let _,hfs = trans_rels_gen p0 in
match hfs with
| [] -> false, CF.HEmp
| _ -> let hf = CF.join_star_conjunctions hfs in
true,hf
(* let pos = CP.pos_of_formula p0 in *)
(* let f0 = CF.formula_of_heap hf pos in *)
(* CF.mkAnd_pure f0 (MCP.mix_of_pure np) pos *)
let heap_pred_of_pure p0=
let pr1 = !CP.print_formula in
let pr2 = Cprinter.prtt_string_of_h_formula in
Debug.no_1 "heap_pred_of_pure" pr1 (pr_pair string_of_bool pr2)
(fun _ -> heap_pred_of_pure_x p0) p0
(******************************************)
(***************PRED_EXTN**********************)
(******************************************)
(******************************************)
(***************PURE*****************)
(******************************************)
let partition_extn_svl_x p svl=
let check_one f=
let svl0 = CP.fv f in
(CP.intersect_svl svl0 svl <> [])
in
let ps = CP.list_of_conjs p in
let ps_extn,ps_non_extn = List.partition check_one ps in
let new_p= CP.conj_of_list ps_extn (CP.pos_of_formula p) in
let p_non_extn= CP.conj_of_list ps_non_extn (CP.pos_of_formula p) in
(new_p, p_non_extn)
let partition_extn_svl p svl=
let pr1 = !CP.print_formula in
let pr2 = !CP.print_svl in
Debug.no_2 "partition_extn_svl" pr1 pr2 (pr_pair pr1 pr1)
(fun _ _ -> partition_extn_svl_x p svl) p svl
(******************************************)
(*************END PURE***************)
(******************************************)
let generate_extn_ho_procs prog cviews extn_view_name extn_args=
let mk_ho_b args val_extns p =
fun svl val_extns1 ->
let ( ) = Debug.info_pprint ( " val_extns : " ^ ( ! ) ) no_pos in
let ( ) = Debug.info_pprint ( " val_extns1 : " ^ ( ! ) ) no_pos in
may be
let ss = if List.length val_extns = List.length val_extns1 then
List.combine (args@val_extns) (svl@val_extns1)
else List.combine (args) (svl)
in
let ( ) = Debug.info_pprint ( " p : " ^ ( ! ) ) no_pos in
let n_p = CP.subst ss p in
let n_p1,_ = CPP.norm_exp_min_max n_p in
let ( ) = Debug.info_pprint ( " n_p : " ^ ( ! ) ) no_pos in
(* let () = Debug.info_pprint (" n_p1: "^ (!CP.print_formula n_p1)) no_pos in *)
n_p1
in
let mk_ho_ind_rec ann args p =
match args with
| [a] -> [a]
| [] -> [] (*rec null pointer*)
| _ -> report_error no_pos "astsimp.generate_extn_ho_procs: extend one property"
(* (args, CP.mkTrue no_pos) *)
in
let process_other_const from_args to_args p=
(*may need some filter: CP.filter_var: omit now*)
if from_args <> [] then (*ind_case*)
let rec_args0 = List.concat ( List.map ( fun ( , args ) - > mk_ho_ind_rec ann args p ) rec_ls ) in
(* let () = Debug.info_pprint (" from_args: "^ (!CP.print_svl from_args)) no_pos in *)
(* let () = Debug.info_pprint (" to_args: "^ (!CP.print_svl to_args)) no_pos in *)
let ss3 = List.combine from_args to_args in
let new_p = CP.subst ss3 p in
let ( ) = Debug.info_pprint ( " p_non_extn1 : " ^ ( ! ) ) no_pos in
new_p
else p
in
let mk_ho_ind args val_extns p rec_ls=
let rec_args = List.map ( fun ( , args ) - > mk_ho_ind_rec ann args p ) in
let ( ) = CP.extract_outer_inner p args val_extns rec_args in [ ]
fun svl val_extns1 rec_ls1->
let svl1 = List.concat ( snd ( List.split rec_ls ) ) in
(*find subformula has svl1*)
let ( ) = Debug.info_pprint ( " p : " ^ ( ! ) ) no_pos in
let ( ) = Debug.info_pprint ( " : " ^ ( ! ) ) no_pos in
let p_extn, p_non_extn = partition_extn_svl p svl in
(* let () = Debug.info_pprint (" p_extn: "^ (!CP.print_formula p_extn)) no_pos in *)
let from_rec_args = List.concat (List.map (fun (ann,args) -> mk_ho_ind_rec ann args p) rec_ls) in
let rec_args = List.concat (List.map (fun (ann,args) -> mk_ho_ind_rec ann args p) rec_ls1) in
let ((is_bag_constr,(outer, root_e), (inner_e, first_e)), exquans, irr_ps) = CPP.extract_outer_inner p_extn args val_extns from_rec_args in
(*combine bag or non-bag constrs*)
let comb_fn= if is_bag_constr then CPP.mk_exp_from_bag_tmpl else CPP.mk_exp_from_non_bag_tmpl in
(*cmb inner most exp*)
let ( ) = Debug.info_pprint ( " val_extns : " ^ ( ! ) ) no_pos in
let ( ) = Debug.info_pprint ( " val_extns1 : " ^ ( ! ) ) no_pos in
(* let ss1 = List.combine val_extns val_extns1 in *)
let n_first_e = CP.e_apply_subs ss1 first_e in
let n_inner_e = List.fold_left (fun e1 e2 -> comb_fn inner_e e1 e2 no_pos)
first_e (List.map (fun sv -> CP.Var (sv,no_pos)) (val_extns1@rec_args)) in
outer most pformula
let ss2 = List.combine args svl in
let n_root_e = CP.e_apply_subs ss2 root_e in
let CP.mk_pformula_from_tmpl outer n_root_e n_inner_e no_pos in
let n_p = ( CP.BForm ( ( n_outer , None ) , None ) ) in
let n_p1,quans = in
let n_p2,quans = CPP.mk_formula_from_tmp outer n_root_e n_inner_e exquans irr_ps no_pos in
let ( ) = Debug.info_pprint ( " n_p : " ^ ( ! ) ) no_pos in
(*other constraints*)
let n_p3= if CP.isConstTrue p_non_extn then n_p2 else
assume we extend one property each
let ls_to_args = List.concat (List.map (fun (ann,args) -> mk_ho_ind_rec ann args p) rec_ls1) in
(*this step is necessary for tree like*)
let new_ps = List.map (fun to_arg -> process_other_const (from_rec_args@val_extns) ([to_arg]@val_extns1) p_non_extn) ls_to_args in
let pos = CP.pos_of_formula n_p2 in
let n_p4 = List.fold_left (fun p1 p2 -> CP.mkAnd p1 p2 pos) n_p2 new_ps in
n_p4
in
(n_p3,quans)
in
let extn_v = x_add Cast.look_up_view_def_raw 44 cviews extn_view_name in
let extn_fs0 = fst (List.split extn_v.Cast.view_un_struc_formula) in
let inv_p0 = (MCP.pure_of_mix extn_v.Cast.view_user_inv) in
let pr_ext_vars = List.combine extn_v.Cast.view_vars extn_args in
let fr_extn_args,ss = List.fold_left (fun (r1,r2) (CP.SpecVar (t, id, p), new_id) ->
let n_sv = CP.SpecVar (t, new_id, p) in
(r1@[n_sv], r2@[(CP.SpecVar (t, id, p), n_sv)])
) ([],[]) pr_ext_vars in
let extn_fs = List.map (fun f -> CF.subst ss f) extn_fs0 in
let inv_p = CP.subst ss inv_p0 in
let (brs, val_extns) = CF.classify_formula_branch extn_fs inv_p extn_view_name
fr_extn_args (* extn_v.Cast.view_vars *) extn_v.Cast.view_prop_extns in
let b_brs, ind_brs = List.partition (fun (_, ls) -> ls=[]) brs in
now , we assume we always have < = 1 base case and < = 1 case
let ho_bs = List.map (fun (p,_) -> mk_ho_b (* extn_v.Cast.view_vars *)fr_extn_args val_extns p) b_brs in
let ho_inds = List.map (fun (p, ls) -> mk_ho_ind (*extn_v.Cast.view_vars*) fr_extn_args
val_extns p ls) ind_brs in
( extn_view_name , b_brs , ind_brs , val_extns , extn_inv )
let ( ) = Debug.info_pprint ( " extn_v . C.view_vars : " ^ ( ! CP.print_svl extn_v . ) ) no_pos in
(extn_view_name, ho_bs, ho_inds(* , CP.filter_var inv_p extn_v.C.view_vars *))
let extend_pred_one_derv_x (prog : I.prog_decl) cprog hp_defs hp args ((orig_pred_name,orig_args),(extn_view_name,extn_props,extn_args), ls_extn_pos) =
(*********INTERNAL********)
let cviews = cprog.Cast.prog_view_decls in
let rec look_up_hp_def hp defs=
match defs with
| [] -> report_error no_pos "Pred.extend_pred_one_derv: base pred has not not defined"
| def::rest -> let hp1,_ = CF.extract_HRel def.CF.def_lhs in
if String.compare hp (CP.name_of_spec_var hp1) = 0 then def else
look_up_hp_def hp rest
in
let do_extend_base_case ho_bs extn_args val_svl f=
match ho_bs with
| [] -> f
now , we just care the first one
let extn_p = ho_fn extn_args val_svl in
(* let () = Debug.info_pprint (" pure np: "^ (!CP.print_formula extn_p)) no_pos in *)
let nf = CF.mkAnd_pure f (MCP.mix_of_pure extn_p) no_pos in
(*let () = Debug.info_pprint (" nf: "^ (!CF.print_formula nf)) no_pos in *)
nf
in
let do_extend_ind_case ho_inds extn_args (f,val_extns,rec_extns)=
match ho_inds with
| [] -> f
now , we just care the first one
: ex quans from normalize min / max
let quans0, bare_f = CF.split_quantifiers f in
let extn_p,quans = ho_fn extn_args val_extns rec_extns in
let nf = CF.mkAnd_pure bare_f (MCP.mix_of_pure extn_p) no_pos in
(*add rec_extns into exists*)
let new_extn_args = CP.remove_dups_svl (List.concat (snd (List.split rec_extns))) in
let nf1 = CF.add_quantifiers (quans0@new_extn_args@quans) nf in
let ( ) = Debug.info_pprint ( " nf1 : " ^ ( ! CF.print_formula nf1 ) ) no_pos in
nf1
in
(*********END INTERNAL********)
let extn_view = x_add Cast.look_up_view_def_raw 45 cviews extn_view_name in
let (extn_vname, extn_ho_bs, extn_ho_inds(* , extn_user_inv *)) = generate_extn_ho_procs prog cviews extn_view_name extn_args in
(**********************************)
BASE VIEW : ( 1 ) abs untruct formula , ( 2 ) extract ANN and ( 3 ) apply extn_ho
BASE VIEW: (1) abs untruct formula, (2) extract ANN and (3) apply extn_ho
*)
(**********************************)
(*new args*)
let ss = List.combine extn_args extn_view.Cast.view_vars in
let n_args = List.map (fun (id, CP.SpecVar (t,_,pr)) -> CP.SpecVar (t,id,pr)) ss in
let orig_pred = look_up_hp_def orig_pred_name hp_defs in
let _,orig_args_in_def = CF.extract_HRel orig_pred.CF.def_lhs in
let pr_orig_vars = List.combine orig_args_in_def orig_args in
let orig_args,orig_ss = List.fold_left (fun (r1,r2) (CP.SpecVar (t, id, p), new_id) ->
let n_sv = CP.SpecVar (t, new_id, p) in
(r1@[n_sv], r2@[(CP.SpecVar (t, id, p), n_sv)])
) ([],[]) pr_orig_vars in
let orig_pred_data_name = Cast.look_up_hp_decl_data_name cprog.Cast.prog_hp_decls (CP.name_of_spec_var hp) (List.hd ls_extn_pos) in
find data fields
let ls_dname_pos = I.look_up_field_ann prog orig_pred_data_name extn_props in
(*formula: extend with new args*)
let fs0 = List.fold_left (fun r (f,_) -> r@(CF.list_of_disjs f)) [] orig_pred.CF.def_rhs in
let fs = List.map (CF.subst orig_ss) fs0 in
let pure_extn_svl = CF.retrieve_args_from_locs orig_args ls_extn_pos in
let (base_brs,ind_brs) = CF.extract_abs_formula_branch fs orig_pred_name (CP.name_of_spec_var hp) n_args ls_dname_pos pure_extn_svl false false in
(*extend base cases*)
let extn_base_brs = List.map (fun (p,val_svl)-> do_extend_base_case extn_ho_bs n_args val_svl p) base_brs in
extend ind cases
let extn_ind_brs = List.map (do_extend_ind_case extn_ho_inds n_args) ind_brs in
let rhs = CF.disj_of_list (extn_base_brs@extn_ind_brs) no_pos in
rhs
let extend_pred_one_derv (prog : I.prog_decl) cprog hp_defs hp args extn_info =
let pr1 = Cprinter.prtt_string_of_formula in
let pr2 = !CP.print_svl in
let pr3 = pr_triple (pr_pair pr_id (pr_list pr_id)) (pr_triple pr_id (pr_list pr_id) (pr_list pr_id)) (pr_list string_of_int) in
Debug.no_3 "extend_pred_one_derv" !CP.print_sv pr2 pr3 pr1
(fun _ _ _ -> extend_pred_one_derv_x prog cprog hp_defs hp args extn_info)
hp args extn_info
let derv=
(* let derv_args = derv.I.view_vars in *)
let all_extn_args = List.concat ( List.map ( fun ( ( _ , orig_args),(_,_,extn_args ) ) - > orig_args@extn_args ) . I.view_derv_info ) in
(* let diff = Gen.BList.difference_eq (fun s1 s2 -> String.compare s1 s2 =0) derv_args all_extn_args in *)
(* if diff <> [] then *)
report_error no_pos ( " in view_extn : " ^ . I.view_name ^ " , args : " ^
(* (String.concat ", " diff) ^ " are not declared.") *)
(* else () *)
let extend_pred_dervs_x (prog : I.prog_decl) cprog hp_defs hp args derv_info =
let ( ) = derv_info in
match derv_info with
| [] -> report_error no_pos "astsimp.trans_view_dervs: 1"
| [((orig_pred_name,orig_args),(extn_view_name,extn_props,extn_args), extn_poss)] ->
let der_view(*,s*) =
let extn_view = x_add Cast.look_up_view_def_raw 46 cprog . Cast.prog_view_decls extn_view_name in
if extn_view . C.view_kind = then
(* let der_view = trans_view_one_spec prog cviews derv ((orig_view_name,orig_args),(extn_view_name,extn_props,extn_args)) in *)
(* (der_view(\*,("************VIEW_SPECIFIED*************")*\)) *)
(* else *)
let der_view = extend_pred_one_derv prog cprog hp_defs hp args ((orig_pred_name,orig_args),(extn_view_name,extn_props,extn_args), extn_poss) in
(der_view(*,("************VIEW_DERIVED*************")*))
in
der_view
| _ -> report_error no_pos "astsimp.trans_view_dervs: not handle yet"
let extend_pred_dervs (prog : I.prog_decl) cprog hp_defs hp args derv_info =
let pr1 = Cprinter.prtt_string_of_formula in
let pr2 = !CP.print_svl in
Debug.no_2 "extend_pred_dervs" !CP.print_sv pr2 pr1
(fun _ _ -> extend_pred_dervs_x prog cprog hp_defs hp args derv_info) hp args
let leverage_self_info_x xform formulas anns data_name=
let detect_anns_f f=
let svl = CF.fv f in
CP.intersect_svl anns svl <> []
in
let fs = CF.list_of_disjs formulas in
let ls_self_not_null = List.map detect_anns_f fs in
let self_not_null = List.for_all (fun b -> b) ls_self_not_null in
let self_info =
let self_sv = CP.SpecVar (Named data_name,self,Unprimed) in
if self_not_null then
CP.mkNeqNull self_sv no_pos
else CP.mkNull self_sv no_pos
in
CP.mkAnd xform self_info (CP.pos_of_formula xform)
let leverage_self_info xform formulas anns data_name=
let pr1= !CP.print_formula in
let pr2 = !CF.print_formula in
Debug.no_3 "leverage_self_info" pr1 pr2 (!CP.print_svl) pr1
(fun _ _ _ -> leverage_self_info_x xform formulas anns data_name) xform formulas anns
(***************END PRED_EXTN**********************)
| null |
https://raw.githubusercontent.com/hipsleek/hipsleek/596f7fa7f67444c8309da2ca86ba4c47d376618c/bef_indent/predicate.ml
|
ocaml
|
let rec helper f=
match f with
| CF.Base fb ->
CF.formula_base_heap = nh;
}
| CF.Exists _ ->
CF.add_quantifiers qvars nf
| CF.Or orf ->
let nf2 = helper orf.CF.formula_or_f2 in
in
helper f0
let pos = CP.pos_of_formula p0 in
let f0 = CF.formula_of_heap hf pos in
CF.mkAnd_pure f0 (MCP.mix_of_pure np) pos
****************************************
**************PRED_EXTN*********************
****************************************
****************************************
**************PURE****************
****************************************
****************************************
************END PURE**************
****************************************
let () = Debug.info_pprint (" n_p1: "^ (!CP.print_formula n_p1)) no_pos in
rec null pointer
(args, CP.mkTrue no_pos)
may need some filter: CP.filter_var: omit now
ind_case
let () = Debug.info_pprint (" from_args: "^ (!CP.print_svl from_args)) no_pos in
let () = Debug.info_pprint (" to_args: "^ (!CP.print_svl to_args)) no_pos in
find subformula has svl1
let () = Debug.info_pprint (" p_extn: "^ (!CP.print_formula p_extn)) no_pos in
combine bag or non-bag constrs
cmb inner most exp
let ss1 = List.combine val_extns val_extns1 in
other constraints
this step is necessary for tree like
extn_v.Cast.view_vars
extn_v.Cast.view_vars
extn_v.Cast.view_vars
, CP.filter_var inv_p extn_v.C.view_vars
********INTERNAL*******
let () = Debug.info_pprint (" pure np: "^ (!CP.print_formula extn_p)) no_pos in
let () = Debug.info_pprint (" nf: "^ (!CF.print_formula nf)) no_pos in
add rec_extns into exists
********END INTERNAL*******
, extn_user_inv
********************************
********************************
new args
formula: extend with new args
extend base cases
let derv_args = derv.I.view_vars in
let diff = Gen.BList.difference_eq (fun s1 s2 -> String.compare s1 s2 =0) derv_args all_extn_args in
if diff <> [] then
(String.concat ", " diff) ^ " are not declared.")
else ()
,s
let der_view = trans_view_one_spec prog cviews derv ((orig_view_name,orig_args),(extn_view_name,extn_props,extn_args)) in
(der_view(\*,("************VIEW_SPECIFIED*************")*\))
else
,("************VIEW_DERIVED*************")
**************END PRED_EXTN*********************
|
#include "xdebug.cppo"
open VarGen
open Globals
open Gen
module DD = Debug
module Err = Error
module I = Iast
module CA = Cast
module CP = Cpure
module CPP = Cpure_pred
module CF = Cformula
module MCP = Mcpure
module CEQ = Checkeq
module TP = Tpdispatcher
let pure_relation_name_of_heap_pred (CP.SpecVar (_, hp, p))=
let rec look_up map=
match map with
| [] -> report_error no_pos "predicate.pure_relation_name_of_heap_pred"
| (id1,id2)::rest -> if String.compare id1 hp = 0 then (CP.SpecVar (RelT [], id2, p)) else
look_up rest
in
look_up !Cast.pure_hprel_map
let heap_pred_name_of_pure_relation (CP.SpecVar (_, pure_hp, p))=
let rec look_up map=
match map with
| [] -> None
| (id1,id2)::rest -> if String.compare id2 pure_hp = 0 then Some (CP.SpecVar(HpT, id1, p)) else
look_up rest
in
look_up !Cast.pure_hprel_map
let pure_of_heap_pred_gen_h hf0=
let rec helper hf=
match hf with
| CF.Star { CF.h_formula_star_h1 = hf1;
CF.h_formula_star_h2 = hf2;
CF.h_formula_star_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1,nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.Star {CF.h_formula_star_h1 = nh1;
CF.h_formula_star_h2 = nh2;
CF.h_formula_star_pos = pos}
in (nh, ps1@ps2)
| CF.StarMinus { CF.h_formula_starminus_h1 = hf1;
CF.h_formula_starminus_h2 = hf2;
CF.h_formula_starminus_aliasing = al;
CF.h_formula_starminus_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.StarMinus { CF.h_formula_starminus_h1 = nh1;
CF.h_formula_starminus_h2 = nh2;
CF.h_formula_starminus_aliasing = al;
CF.h_formula_starminus_pos = pos}
in (nh, ps1@ps2)
| CF.ConjStar { CF.h_formula_conjstar_h1 = hf1;
CF.h_formula_conjstar_h2 = hf2;
CF.h_formula_conjstar_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.ConjStar { CF.h_formula_conjstar_h1 = nh1;
CF.h_formula_conjstar_h2 = nh2;
CF.h_formula_conjstar_pos = pos}
in (nh, ps1@ps2)
| CF.ConjConj { CF.h_formula_conjconj_h1 = hf1;
CF.h_formula_conjconj_h2 = hf2;
CF.h_formula_conjconj_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.ConjConj { CF.h_formula_conjconj_h1 = nh1;
CF.h_formula_conjconj_h2 = nh2;
CF.h_formula_conjconj_pos = pos}
in (nh, ps1@ps2)
| CF.Phase { CF.h_formula_phase_rd = hf1;
CF.h_formula_phase_rw = hf2;
CF.h_formula_phase_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.Phase { CF.h_formula_phase_rd = nh1;
CF.h_formula_phase_rw = nh2;
CF.h_formula_phase_pos = pos}
in (nh, ps1@ps2)
| CF.Conj { CF.h_formula_conj_h1 = hf1;
CF.h_formula_conj_h2 = hf2;
CF.h_formula_conj_pos = pos} ->
let nh1,ps1 = helper hf1 in
let nh2, ps2 = helper hf2 in
let nh = match nh1, nh2 with
| (CF.HEmp,CF.HEmp) -> CF.HEmp
| (CF.HEmp,_) -> nh2
| (_, CF.HEmp) -> nh1
| _ -> CF.Conj { CF.h_formula_conj_h1 = nh1;
CF.h_formula_conj_h2 = nh2;
CF.h_formula_conj_pos = pos}
in (nh, ps1@ps2)
| CF.HRel (hp, eargs, p) ->
let prel = pure_relation_name_of_heap_pred hp in
let p= CP.mkRel prel eargs p in
(CF.HEmp, [(p,hp)])
| _ -> (hf,[])
in
helper hf0
let pure_of_heap_pred_x pos hfs=
let ps, p_hps = List.fold_left ( fun (ls,ls2) hf ->
let _, pr_ps = pure_of_heap_pred_gen_h hf in
let ps,hprels = List.split pr_ps in
(ls@ps, ls2@hprels)
) ([],[]) hfs
in
let p = CP.conj_of_list ps pos in
p,p_hps
let pure_of_heap_pred pos hfs=
let pr1 = !CP.print_formula in
let pr2 = pr_list_ln Cprinter.prtt_string_of_h_formula in
let pr3 = pr_list ( pr_pair ! CP.print_sv ! ) in
Debug.no_1 "pure_of_heap_pred" pr2 (pr_pair pr1 !CP.print_svl)
(fun _ -> pure_of_heap_pred_x pos hfs) hfs
let pure_of_heap_pred_x f0=
let nh , ps = pure_of_heap_pred_h fb . CF.formula_base_heap in
let new_p = CP.conj_of_list ps fb . CF.formula_base_pos in
{ fb with CF.formula_base_pure = MCP.merge_mems fb . CF.formula_base_pure ( MCP.mix_of_pure new_p ) true ;
let qvars , base1 = CF.split_quantifiers f in
let nf = helper in
let nf1 = helper orf . CF.formula_or_f1 in
( CF.Or { orf with CF.formula_or_f1 = nf1 ;
CF.formula_or_f2 = nf2 ; } )
let trans_rels_gen pf0 =
let rec helper pf=
match pf with
| CP.BForm (bf,a) -> begin
match bf with
| (CP.RelForm (r, eargs, p),x) ->
let ohp = heap_pred_name_of_pure_relation r in
(
match ohp with
| None -> (pf,[])
| Some hp -> (CP.BForm (((CP.BConst (true, p)), x) ,a), [(CF.HRel (hp, eargs, p))])
)
| _ -> (pf, [])
end
| CP.And (f1,f2,p) -> let nf1, hf1 = helper f1 in
let nf2, hf2= helper f2 in
let np = match (CP.isConstTrue nf1), (CP.isConstTrue nf2) with
| true,true -> nf1
| true,_ -> nf2
| _, true -> nf1
| _ -> CP.And (nf1,nf2,p)
in (np, hf1@hf2)
| CP.AndList lp-> let r,hfs = List.fold_left (fun (ps, hfs) (l, p) ->
let np, n_hfs = helper p in
if CP.isConstTrue np then
(ps, hfs@n_hfs)
else (ps@[(l,np)], hfs@n_hfs)
) ([],[]) lp in
if r = [] then (CP.mkTrue no_pos, hfs) else (CP.AndList r,hfs)
| CP.Or (f1,f2,c,p) -> let nf1, hf1 = helper f1 in
let nf2, hf2= helper f2 in
let np = match (CP.isConstTrue nf1), (CP.isConstTrue nf2) with
| true,true -> nf1
| true,_ -> nf2
| _, true -> nf1
| _ -> CP.Or (nf1,nf2, c,p)
in (np, hf1@hf2)
| CP.Not (f,b,p) -> let np,hfs = helper f in
if CP.isConstTrue np then
(CP.mkTrue p, hfs)
else (CP.Not (np, b, p), hfs)
| CP.Forall (a,f,c,p) -> let np,hfs = helper f in
if CP.isConstTrue np then
(CP.mkTrue p, hfs)
else
(CP.Forall (a,np,c,p), hfs)
| CP.Exists (a,f,b,p) -> let np,hfs = helper f in
if CP.isConstTrue np then
(CP.mkTrue p, hfs)
else
(CP.Exists (a,np,b,p), hfs)
in
helper pf0
let trans_rels_x pf0 =
let rec helper pf=
match pf with
| CP.BForm (bf,a) -> begin
match bf with
| (CP.RelForm (r, eargs, p),x) ->
let ohp = heap_pred_name_of_pure_relation r in
(
match ohp with
| None -> None
| Some hp -> Some (hp, CF.HRel (hp, eargs, p))
)
| _ -> None
end
| _ -> None
in
let ps = CP.list_of_conjs pf0 in
let pr_hp_rhs = List.map helper ps in
List.fold_left (fun r (r_opt) -> match r_opt with
| None -> r
| Some a -> r@[a]
) [] pr_hp_rhs
let trans_rels pf0 =
let pr1 = !CP.print_formula in
let pr2 = pr_list (pr_pair !CP.print_sv Cprinter.prtt_string_of_h_formula) in
Debug.no_1 "trans_rels" pr1 ( pr2)
(fun _ -> trans_rels_x pf0) pf0
let heap_pred_of_pure_x p0=
let _,hfs = trans_rels_gen p0 in
match hfs with
| [] -> false, CF.HEmp
| _ -> let hf = CF.join_star_conjunctions hfs in
true,hf
let heap_pred_of_pure p0=
let pr1 = !CP.print_formula in
let pr2 = Cprinter.prtt_string_of_h_formula in
Debug.no_1 "heap_pred_of_pure" pr1 (pr_pair string_of_bool pr2)
(fun _ -> heap_pred_of_pure_x p0) p0
let partition_extn_svl_x p svl=
let check_one f=
let svl0 = CP.fv f in
(CP.intersect_svl svl0 svl <> [])
in
let ps = CP.list_of_conjs p in
let ps_extn,ps_non_extn = List.partition check_one ps in
let new_p= CP.conj_of_list ps_extn (CP.pos_of_formula p) in
let p_non_extn= CP.conj_of_list ps_non_extn (CP.pos_of_formula p) in
(new_p, p_non_extn)
let partition_extn_svl p svl=
let pr1 = !CP.print_formula in
let pr2 = !CP.print_svl in
Debug.no_2 "partition_extn_svl" pr1 pr2 (pr_pair pr1 pr1)
(fun _ _ -> partition_extn_svl_x p svl) p svl
let generate_extn_ho_procs prog cviews extn_view_name extn_args=
let mk_ho_b args val_extns p =
fun svl val_extns1 ->
let ( ) = Debug.info_pprint ( " val_extns : " ^ ( ! ) ) no_pos in
let ( ) = Debug.info_pprint ( " val_extns1 : " ^ ( ! ) ) no_pos in
may be
let ss = if List.length val_extns = List.length val_extns1 then
List.combine (args@val_extns) (svl@val_extns1)
else List.combine (args) (svl)
in
let ( ) = Debug.info_pprint ( " p : " ^ ( ! ) ) no_pos in
let n_p = CP.subst ss p in
let n_p1,_ = CPP.norm_exp_min_max n_p in
let ( ) = Debug.info_pprint ( " n_p : " ^ ( ! ) ) no_pos in
n_p1
in
let mk_ho_ind_rec ann args p =
match args with
| [a] -> [a]
| _ -> report_error no_pos "astsimp.generate_extn_ho_procs: extend one property"
in
let process_other_const from_args to_args p=
let rec_args0 = List.concat ( List.map ( fun ( , args ) - > mk_ho_ind_rec ann args p ) rec_ls ) in
let ss3 = List.combine from_args to_args in
let new_p = CP.subst ss3 p in
let ( ) = Debug.info_pprint ( " p_non_extn1 : " ^ ( ! ) ) no_pos in
new_p
else p
in
let mk_ho_ind args val_extns p rec_ls=
let rec_args = List.map ( fun ( , args ) - > mk_ho_ind_rec ann args p ) in
let ( ) = CP.extract_outer_inner p args val_extns rec_args in [ ]
fun svl val_extns1 rec_ls1->
let svl1 = List.concat ( snd ( List.split rec_ls ) ) in
let ( ) = Debug.info_pprint ( " p : " ^ ( ! ) ) no_pos in
let ( ) = Debug.info_pprint ( " : " ^ ( ! ) ) no_pos in
let p_extn, p_non_extn = partition_extn_svl p svl in
let from_rec_args = List.concat (List.map (fun (ann,args) -> mk_ho_ind_rec ann args p) rec_ls) in
let rec_args = List.concat (List.map (fun (ann,args) -> mk_ho_ind_rec ann args p) rec_ls1) in
let ((is_bag_constr,(outer, root_e), (inner_e, first_e)), exquans, irr_ps) = CPP.extract_outer_inner p_extn args val_extns from_rec_args in
let comb_fn= if is_bag_constr then CPP.mk_exp_from_bag_tmpl else CPP.mk_exp_from_non_bag_tmpl in
let ( ) = Debug.info_pprint ( " val_extns : " ^ ( ! ) ) no_pos in
let ( ) = Debug.info_pprint ( " val_extns1 : " ^ ( ! ) ) no_pos in
let n_first_e = CP.e_apply_subs ss1 first_e in
let n_inner_e = List.fold_left (fun e1 e2 -> comb_fn inner_e e1 e2 no_pos)
first_e (List.map (fun sv -> CP.Var (sv,no_pos)) (val_extns1@rec_args)) in
outer most pformula
let ss2 = List.combine args svl in
let n_root_e = CP.e_apply_subs ss2 root_e in
let CP.mk_pformula_from_tmpl outer n_root_e n_inner_e no_pos in
let n_p = ( CP.BForm ( ( n_outer , None ) , None ) ) in
let n_p1,quans = in
let n_p2,quans = CPP.mk_formula_from_tmp outer n_root_e n_inner_e exquans irr_ps no_pos in
let ( ) = Debug.info_pprint ( " n_p : " ^ ( ! ) ) no_pos in
let n_p3= if CP.isConstTrue p_non_extn then n_p2 else
assume we extend one property each
let ls_to_args = List.concat (List.map (fun (ann,args) -> mk_ho_ind_rec ann args p) rec_ls1) in
let new_ps = List.map (fun to_arg -> process_other_const (from_rec_args@val_extns) ([to_arg]@val_extns1) p_non_extn) ls_to_args in
let pos = CP.pos_of_formula n_p2 in
let n_p4 = List.fold_left (fun p1 p2 -> CP.mkAnd p1 p2 pos) n_p2 new_ps in
n_p4
in
(n_p3,quans)
in
let extn_v = x_add Cast.look_up_view_def_raw 44 cviews extn_view_name in
let extn_fs0 = fst (List.split extn_v.Cast.view_un_struc_formula) in
let inv_p0 = (MCP.pure_of_mix extn_v.Cast.view_user_inv) in
let pr_ext_vars = List.combine extn_v.Cast.view_vars extn_args in
let fr_extn_args,ss = List.fold_left (fun (r1,r2) (CP.SpecVar (t, id, p), new_id) ->
let n_sv = CP.SpecVar (t, new_id, p) in
(r1@[n_sv], r2@[(CP.SpecVar (t, id, p), n_sv)])
) ([],[]) pr_ext_vars in
let extn_fs = List.map (fun f -> CF.subst ss f) extn_fs0 in
let inv_p = CP.subst ss inv_p0 in
let (brs, val_extns) = CF.classify_formula_branch extn_fs inv_p extn_view_name
let b_brs, ind_brs = List.partition (fun (_, ls) -> ls=[]) brs in
now , we assume we always have < = 1 base case and < = 1 case
val_extns p ls) ind_brs in
( extn_view_name , b_brs , ind_brs , val_extns , extn_inv )
let ( ) = Debug.info_pprint ( " extn_v . C.view_vars : " ^ ( ! CP.print_svl extn_v . ) ) no_pos in
let extend_pred_one_derv_x (prog : I.prog_decl) cprog hp_defs hp args ((orig_pred_name,orig_args),(extn_view_name,extn_props,extn_args), ls_extn_pos) =
let cviews = cprog.Cast.prog_view_decls in
let rec look_up_hp_def hp defs=
match defs with
| [] -> report_error no_pos "Pred.extend_pred_one_derv: base pred has not not defined"
| def::rest -> let hp1,_ = CF.extract_HRel def.CF.def_lhs in
if String.compare hp (CP.name_of_spec_var hp1) = 0 then def else
look_up_hp_def hp rest
in
let do_extend_base_case ho_bs extn_args val_svl f=
match ho_bs with
| [] -> f
now , we just care the first one
let extn_p = ho_fn extn_args val_svl in
let nf = CF.mkAnd_pure f (MCP.mix_of_pure extn_p) no_pos in
nf
in
let do_extend_ind_case ho_inds extn_args (f,val_extns,rec_extns)=
match ho_inds with
| [] -> f
now , we just care the first one
: ex quans from normalize min / max
let quans0, bare_f = CF.split_quantifiers f in
let extn_p,quans = ho_fn extn_args val_extns rec_extns in
let nf = CF.mkAnd_pure bare_f (MCP.mix_of_pure extn_p) no_pos in
let new_extn_args = CP.remove_dups_svl (List.concat (snd (List.split rec_extns))) in
let nf1 = CF.add_quantifiers (quans0@new_extn_args@quans) nf in
let ( ) = Debug.info_pprint ( " nf1 : " ^ ( ! CF.print_formula nf1 ) ) no_pos in
nf1
in
let extn_view = x_add Cast.look_up_view_def_raw 45 cviews extn_view_name in
BASE VIEW : ( 1 ) abs untruct formula , ( 2 ) extract ANN and ( 3 ) apply extn_ho
BASE VIEW: (1) abs untruct formula, (2) extract ANN and (3) apply extn_ho
*)
let ss = List.combine extn_args extn_view.Cast.view_vars in
let n_args = List.map (fun (id, CP.SpecVar (t,_,pr)) -> CP.SpecVar (t,id,pr)) ss in
let orig_pred = look_up_hp_def orig_pred_name hp_defs in
let _,orig_args_in_def = CF.extract_HRel orig_pred.CF.def_lhs in
let pr_orig_vars = List.combine orig_args_in_def orig_args in
let orig_args,orig_ss = List.fold_left (fun (r1,r2) (CP.SpecVar (t, id, p), new_id) ->
let n_sv = CP.SpecVar (t, new_id, p) in
(r1@[n_sv], r2@[(CP.SpecVar (t, id, p), n_sv)])
) ([],[]) pr_orig_vars in
let orig_pred_data_name = Cast.look_up_hp_decl_data_name cprog.Cast.prog_hp_decls (CP.name_of_spec_var hp) (List.hd ls_extn_pos) in
find data fields
let ls_dname_pos = I.look_up_field_ann prog orig_pred_data_name extn_props in
let fs0 = List.fold_left (fun r (f,_) -> r@(CF.list_of_disjs f)) [] orig_pred.CF.def_rhs in
let fs = List.map (CF.subst orig_ss) fs0 in
let pure_extn_svl = CF.retrieve_args_from_locs orig_args ls_extn_pos in
let (base_brs,ind_brs) = CF.extract_abs_formula_branch fs orig_pred_name (CP.name_of_spec_var hp) n_args ls_dname_pos pure_extn_svl false false in
let extn_base_brs = List.map (fun (p,val_svl)-> do_extend_base_case extn_ho_bs n_args val_svl p) base_brs in
extend ind cases
let extn_ind_brs = List.map (do_extend_ind_case extn_ho_inds n_args) ind_brs in
let rhs = CF.disj_of_list (extn_base_brs@extn_ind_brs) no_pos in
rhs
let extend_pred_one_derv (prog : I.prog_decl) cprog hp_defs hp args extn_info =
let pr1 = Cprinter.prtt_string_of_formula in
let pr2 = !CP.print_svl in
let pr3 = pr_triple (pr_pair pr_id (pr_list pr_id)) (pr_triple pr_id (pr_list pr_id) (pr_list pr_id)) (pr_list string_of_int) in
Debug.no_3 "extend_pred_one_derv" !CP.print_sv pr2 pr3 pr1
(fun _ _ _ -> extend_pred_one_derv_x prog cprog hp_defs hp args extn_info)
hp args extn_info
let derv=
let all_extn_args = List.concat ( List.map ( fun ( ( _ , orig_args),(_,_,extn_args ) ) - > orig_args@extn_args ) . I.view_derv_info ) in
report_error no_pos ( " in view_extn : " ^ . I.view_name ^ " , args : " ^
let extend_pred_dervs_x (prog : I.prog_decl) cprog hp_defs hp args derv_info =
let ( ) = derv_info in
match derv_info with
| [] -> report_error no_pos "astsimp.trans_view_dervs: 1"
| [((orig_pred_name,orig_args),(extn_view_name,extn_props,extn_args), extn_poss)] ->
let extn_view = x_add Cast.look_up_view_def_raw 46 cprog . Cast.prog_view_decls extn_view_name in
if extn_view . C.view_kind = then
let der_view = extend_pred_one_derv prog cprog hp_defs hp args ((orig_pred_name,orig_args),(extn_view_name,extn_props,extn_args), extn_poss) in
in
der_view
| _ -> report_error no_pos "astsimp.trans_view_dervs: not handle yet"
let extend_pred_dervs (prog : I.prog_decl) cprog hp_defs hp args derv_info =
let pr1 = Cprinter.prtt_string_of_formula in
let pr2 = !CP.print_svl in
Debug.no_2 "extend_pred_dervs" !CP.print_sv pr2 pr1
(fun _ _ -> extend_pred_dervs_x prog cprog hp_defs hp args derv_info) hp args
let leverage_self_info_x xform formulas anns data_name=
let detect_anns_f f=
let svl = CF.fv f in
CP.intersect_svl anns svl <> []
in
let fs = CF.list_of_disjs formulas in
let ls_self_not_null = List.map detect_anns_f fs in
let self_not_null = List.for_all (fun b -> b) ls_self_not_null in
let self_info =
let self_sv = CP.SpecVar (Named data_name,self,Unprimed) in
if self_not_null then
CP.mkNeqNull self_sv no_pos
else CP.mkNull self_sv no_pos
in
CP.mkAnd xform self_info (CP.pos_of_formula xform)
let leverage_self_info xform formulas anns data_name=
let pr1= !CP.print_formula in
let pr2 = !CF.print_formula in
Debug.no_3 "leverage_self_info" pr1 pr2 (!CP.print_svl) pr1
(fun _ _ _ -> leverage_self_info_x xform formulas anns data_name) xform formulas anns
|
0241ba1c7af5a2d8fe336d6f41c73773f568016fd82b7e7cc87024705054914d
|
sanjoy/Snippets
|
Overflow.hs
|
{-# LANGUAGE RankNTypes, NegativeLiterals #-}
import Data.Int
import Data.Word
import Data.Bits
import Data.Maybe
import Data.List
import qualified Data.Set as S
-- import Test.QuickCheck
sext :: Int8 -> Int16
sext i = fromIntegral i
zext :: Int8 -> Int16
zext i = let w = fromIntegral i :: Word8
in fromIntegral w
udiv8 :: Int8 -> Int8 -> Int8
udiv8 a b = let result = ((fromIntegral a)::Word8) `div` ((fromIntegral b)::Word8)
in fromIntegral result
trunc :: Int16 -> Int8
trunc i = fromIntegral i
allInt8 = [-128..127] :: [Int8]
allInt8Pairs = [(x, y) | x <- allInt8, y <- allInt8]
allInt8Triples = [(x, y, z) | x <- allInt8, y <- allInt8, z <- allInt8]
allInt8Quads = [(x, y, z, w) | x <- allInt8, y <- allInt8, z <- allInt8, w <- allInt8]
sign_overflows_op :: (Int8 -> Int8 -> Int8) -> (Int16 -> Int16 -> Int16) ->
Int8 -> Int8 -> Bool
sign_overflows_op a b c d = (\(_,_,r)->r) (sign_overflows_op_full a b c d)
unsign_overflows_op :: (Int8 -> Int8 -> Int8) -> (Int16 -> Int16 -> Int16) ->
Int8 -> Int8 -> Bool
unsign_overflows_op a b c d = (\(_,_,r)->r) (unsign_overflows_op_full a b c d)
unsign_overflows_add = unsign_overflows_op (+) (+)
sign_overflows_op_full :: (Int8 -> Int8 -> Int8) -> (Int16 -> Int16 -> Int16) ->
Int8 -> Int8 -> (Int16, Int16, Bool)
sign_overflows_op_full f8 f16 x y =
let a = sext (x `f8` y)
b = sext x `f16` sext y
in (a, b, a /= b)
unsign_overflows_op_full :: (Int8 -> Int8 -> Int8) -> (Int16 -> Int16 -> Int16) ->
Int8 -> Int8 -> (Int16, Int16, Bool)
unsign_overflows_op_full f8 f16 x y =
let a = zext (x `f8` y)
b = zext x `f16` zext y
in (a, b, a /= b)
sign_overflows_mul = sign_overflows_op (*) (*)
unsign_overflows_sub = unsign_overflows_op (-) (-)
getSignBit x = if x < 0 then 1 else 0::Int8
sign_overflows_shl_2 :: Int8 -> Int -> Bool
sign_overflows_shl_2 a s =
let t = shiftL (zext a) s
tw = fromIntegral t :: Word16
tws = shiftR tw 8
tws_trunc = fromIntegral tws :: Int8
sb = (shiftL a s) `xor` (shiftL 1 s)
in if sb >= 0
then tws_trunc /= 0
else (tws_trunc /= ((shiftL 1 s) - 1))
sign_overflows_shl_3 :: Int8 -> Int -> Bool
sign_overflows_shl_3 a s =
s == 7 || sign_overflows_mul a (shiftL 1 s)
sign_overflows_shl_4 :: Int8 -> Int -> Bool
sign_overflows_shl_4 a s =
a /= 1 && sign_overflows_shl a s
sign_overflows_shl_5 :: Int8 -> Int -> Bool
sign_overflows_shl_5 a s =
if s == 7 then
unsign_overflows_shl a s
else
sign_overflows_shl a s
sign_overflows_shl_6 :: Int8 -> Int -> Bool
sign_overflows_shl_6 a s =
let f0 = \p q-> shiftL p (fromIntegral q)
f1 = \p q-> shiftL p (fromIntegral q)
in sign_overflows_op f0 f1 a (fromIntegral s)
sign_overflows_shl :: Int8 -> Int -> Bool
sign_overflows_shl a s = let t = shiftL (zext a) s
tw = fromIntegral t :: Word16
tws = shiftR tw 8
tws_trunc = fromIntegral tws :: Int8
in if shiftL a s >= 0
then tws_trunc /= 0
else (tws_trunc /= ((shiftL 1 s) - 1))
sign_overflows_shl_f :: Int8 -> Int -> (Int8, Int8, Bool)
sign_overflows_shl_f a s = let t = shiftL (zext a) s
tw = fromIntegral t :: Word16
tws = shiftR tw 8
tws_trunc = fromIntegral tws :: Int8
in (tws_trunc, shiftL a s,
if shiftL a s >= 0
then tws_trunc /= 0
else (tws_trunc /= ((shiftL 1 s) - 1)))
unsign_overflows_shl :: Int8 -> Int -> Bool
unsign_overflows_shl a s = let t = shiftL (zext a) s
tw = fromIntegral t :: Word16
tws = shiftR tw 8
tws_trunc = fromIntegral tws :: Int8
in tws_trunc /= 0
sign_overflows :: Int8 -> Int8 -> Bool
sign_overflows x y = sext (x + y) /= (sext x + sext y)
sign_overflows_sub :: Int8 -> Int8 -> Bool
sign_overflows_sub x y = sext (x - y) /= (sext x - sext y)
sign_overflows_sub_full :: Int8 -> Int8 -> (Bool, Int16, Int16)
sign_overflows_sub_full x y =
let m = sext (x - y)
n = sext x - sext y
in (m /= n, m, n)
sign_overflows_full :: Int8 -> Int8 -> (Int16, Int16)
sign_overflows_full x y = (sext (x + y), (sext x + sext y))
unsign_overflows :: Int8 -> Int8 -> Bool
unsign_overflows x y = zext (x + y) /= (zext x + zext y)
unsign_overflows_mul :: Int8 -> Int8 -> Bool
unsign_overflows_mul x y = zext (x * y) /= (zext x * zext y)
urange :: Int8 -> Int8 -> [Int8]
urange a b = if a == b then [] else a:urange (a+1) b
ult8 :: Int8 -> Int8 -> Bool
ult8 x y = ((fromIntegral x)::Word8) < ((fromIntegral y)::Word8)
ugt8 :: Int8 -> Int8 -> Bool
ugt8 x y = ult8 y x
ule8 :: Int8 -> Int8 -> Bool
ule8 x y = not(ugt8 x y)
uge8 :: Int8 -> Int8 -> Bool
uge8 x y = not(ult8 x y)
ult16 :: Int16 -> Int16 -> Bool
ult16 x y = ((fromIntegral x)::Word16) < ((fromIntegral y)::Word16)
log2 :: Int8 -> Int8
log2 n
| n < 1 = error "agument of logarithm must be positive"
| otherwise = go 0 1
where
go exponent prod
| prod < n = go (exponent + 1) (2*prod)
| otherwise = exponent
mul_lohi :: Int8 -> Int8 -> (Int8, Int8) -- (lo, hi)
mul_lohi x y = let x' = zext x
y' = zext y
m = x' * y'
in (fromIntegral m, fromIntegral (m `rotateR` 8))
clz :: Int8 -> Int
clz x = let asBool = reverse $ map (testBit x) [0..7]
in case elemIndex True asBool of
Just x -> x
Nothing -> 8
clo :: Int8 -> Int
clo x = let asBool = reverse $ map (testBit x) [0..7]
in case elemIndex False asBool of
Just x -> x
Nothing -> 8
cls :: Int8 -> Int
cls x = max (clo x) (clz x)
toBin :: Word8 -> String
toBin w = map (\i->if testBit w i then '1' else '0') [0..7]
log_floor :: Word8 -> Int
log_floor x = foldl1 max $ filter (\i -> (shift 1 i) <= x) [0..7]
log_ceil :: Word8 -> Int
log_ceil x = foldl1 min $ filter (\i -> (shift 1 i) >= x) [0..7]
---
w :: Int8 -> Bool
w x = not (unsign_overflows_mul (-1) x)
w2 :: Int8 -> Bool
w2 x = sign_overflows_sub 0 x /= sign_overflows_mul (-1) x
w3 :: Int8 -> Bool
w3 x = unsign_overflows_sub 0 x /= unsign_overflows_mul (-1) x
w4 :: (Int8, Int8) -> Bool
w4 (a, b) = b /= 0 && a + b == a
w5 :: (Int8, Int8) -> Bool
w5 (x, y) = (x < y) /= ((x + (-128)) `ult8` (y + (-128)))
w6 :: (Int8, Int8) -> Bool
w6 (x, y) = sign_overflows_op (-) (-) x y /= sign_overflows_op (+) (+) x (-y)
-- w8 :: Int8 -> Bool
w8 x = let = if x + 1 > x then x + 1 else x
-- mi = if x + 1 < x then x + 1 else x
-- in (ma - mi) /
-- main = print $ filter w8 allInt8
w7 :: (Int8, Int8) -> Bool
w7 (x, y) = (x > y) /= ((comp x) < (comp y))
where comp t = (-1) - t
w8 :: (Int8, Int8, Int8) -> Bool
w8 (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s < e)
is_protected = (s - stride) < e
in is_protected && is_zero_trip_count && computed_trip_count /= 0
w8_full (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s < e)
is_protected = (s - stride) < e
result = is_protected && is_zero_trip_count && computed_trip_count /= 0
in (computed_trip_count, is_zero_trip_count, is_protected, result)
( e - s ) ` ugt8 ` 1 & & ( e - s ) ` ule8 ` 128 & & s > = e & & ( s + 128 ) < e
w9 :: (Int8, Int8, Int8) -> Bool
w9 (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s `ult8` e)
is_protected = (s - stride) `ult8` e
in is_protected && is_zero_trip_count && computed_trip_count /= 0
w10 :: (Int8, Int8, Int8) -> Bool
w10 (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s `ult8` e)
is_one_trip_count = s `ult8` e && not (unsign_overflows_add s stride) && (not $ (s + stride) `ult8` e)
is_protected = (s - stride) `ult8` e
in is_protected && is_one_trip_count && computed_trip_count /= 1
--w10_full :: (Int8, Int8, Int8) -> Bool
w10_full (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s `ult8` e)
is_one_trip_count = s `ult8` e && not (unsign_overflows_add s stride) && (not $ (s + stride) `ult8` e)
is_protected = (s - stride) `ult8` e
result = is_protected && is_one_trip_count && computed_trip_count /= 1
in (is_protected, is_one_trip_count, computed_trip_count, result)
| null |
https://raw.githubusercontent.com/sanjoy/Snippets/76dcbff1da333b010662d42d0d235f614a882b87/Overflow.hs
|
haskell
|
# LANGUAGE RankNTypes, NegativeLiterals #
import Test.QuickCheck
(lo, hi)
-
w8 :: Int8 -> Bool
mi = if x + 1 < x then x + 1 else x
in (ma - mi) /
main = print $ filter w8 allInt8
w10_full :: (Int8, Int8, Int8) -> Bool
|
import Data.Int
import Data.Word
import Data.Bits
import Data.Maybe
import Data.List
import qualified Data.Set as S
sext :: Int8 -> Int16
sext i = fromIntegral i
zext :: Int8 -> Int16
zext i = let w = fromIntegral i :: Word8
in fromIntegral w
udiv8 :: Int8 -> Int8 -> Int8
udiv8 a b = let result = ((fromIntegral a)::Word8) `div` ((fromIntegral b)::Word8)
in fromIntegral result
trunc :: Int16 -> Int8
trunc i = fromIntegral i
allInt8 = [-128..127] :: [Int8]
allInt8Pairs = [(x, y) | x <- allInt8, y <- allInt8]
allInt8Triples = [(x, y, z) | x <- allInt8, y <- allInt8, z <- allInt8]
allInt8Quads = [(x, y, z, w) | x <- allInt8, y <- allInt8, z <- allInt8, w <- allInt8]
sign_overflows_op :: (Int8 -> Int8 -> Int8) -> (Int16 -> Int16 -> Int16) ->
Int8 -> Int8 -> Bool
sign_overflows_op a b c d = (\(_,_,r)->r) (sign_overflows_op_full a b c d)
unsign_overflows_op :: (Int8 -> Int8 -> Int8) -> (Int16 -> Int16 -> Int16) ->
Int8 -> Int8 -> Bool
unsign_overflows_op a b c d = (\(_,_,r)->r) (unsign_overflows_op_full a b c d)
unsign_overflows_add = unsign_overflows_op (+) (+)
sign_overflows_op_full :: (Int8 -> Int8 -> Int8) -> (Int16 -> Int16 -> Int16) ->
Int8 -> Int8 -> (Int16, Int16, Bool)
sign_overflows_op_full f8 f16 x y =
let a = sext (x `f8` y)
b = sext x `f16` sext y
in (a, b, a /= b)
unsign_overflows_op_full :: (Int8 -> Int8 -> Int8) -> (Int16 -> Int16 -> Int16) ->
Int8 -> Int8 -> (Int16, Int16, Bool)
unsign_overflows_op_full f8 f16 x y =
let a = zext (x `f8` y)
b = zext x `f16` zext y
in (a, b, a /= b)
sign_overflows_mul = sign_overflows_op (*) (*)
unsign_overflows_sub = unsign_overflows_op (-) (-)
getSignBit x = if x < 0 then 1 else 0::Int8
sign_overflows_shl_2 :: Int8 -> Int -> Bool
sign_overflows_shl_2 a s =
let t = shiftL (zext a) s
tw = fromIntegral t :: Word16
tws = shiftR tw 8
tws_trunc = fromIntegral tws :: Int8
sb = (shiftL a s) `xor` (shiftL 1 s)
in if sb >= 0
then tws_trunc /= 0
else (tws_trunc /= ((shiftL 1 s) - 1))
sign_overflows_shl_3 :: Int8 -> Int -> Bool
sign_overflows_shl_3 a s =
s == 7 || sign_overflows_mul a (shiftL 1 s)
sign_overflows_shl_4 :: Int8 -> Int -> Bool
sign_overflows_shl_4 a s =
a /= 1 && sign_overflows_shl a s
sign_overflows_shl_5 :: Int8 -> Int -> Bool
sign_overflows_shl_5 a s =
if s == 7 then
unsign_overflows_shl a s
else
sign_overflows_shl a s
sign_overflows_shl_6 :: Int8 -> Int -> Bool
sign_overflows_shl_6 a s =
let f0 = \p q-> shiftL p (fromIntegral q)
f1 = \p q-> shiftL p (fromIntegral q)
in sign_overflows_op f0 f1 a (fromIntegral s)
sign_overflows_shl :: Int8 -> Int -> Bool
sign_overflows_shl a s = let t = shiftL (zext a) s
tw = fromIntegral t :: Word16
tws = shiftR tw 8
tws_trunc = fromIntegral tws :: Int8
in if shiftL a s >= 0
then tws_trunc /= 0
else (tws_trunc /= ((shiftL 1 s) - 1))
sign_overflows_shl_f :: Int8 -> Int -> (Int8, Int8, Bool)
sign_overflows_shl_f a s = let t = shiftL (zext a) s
tw = fromIntegral t :: Word16
tws = shiftR tw 8
tws_trunc = fromIntegral tws :: Int8
in (tws_trunc, shiftL a s,
if shiftL a s >= 0
then tws_trunc /= 0
else (tws_trunc /= ((shiftL 1 s) - 1)))
unsign_overflows_shl :: Int8 -> Int -> Bool
unsign_overflows_shl a s = let t = shiftL (zext a) s
tw = fromIntegral t :: Word16
tws = shiftR tw 8
tws_trunc = fromIntegral tws :: Int8
in tws_trunc /= 0
sign_overflows :: Int8 -> Int8 -> Bool
sign_overflows x y = sext (x + y) /= (sext x + sext y)
sign_overflows_sub :: Int8 -> Int8 -> Bool
sign_overflows_sub x y = sext (x - y) /= (sext x - sext y)
sign_overflows_sub_full :: Int8 -> Int8 -> (Bool, Int16, Int16)
sign_overflows_sub_full x y =
let m = sext (x - y)
n = sext x - sext y
in (m /= n, m, n)
sign_overflows_full :: Int8 -> Int8 -> (Int16, Int16)
sign_overflows_full x y = (sext (x + y), (sext x + sext y))
unsign_overflows :: Int8 -> Int8 -> Bool
unsign_overflows x y = zext (x + y) /= (zext x + zext y)
unsign_overflows_mul :: Int8 -> Int8 -> Bool
unsign_overflows_mul x y = zext (x * y) /= (zext x * zext y)
urange :: Int8 -> Int8 -> [Int8]
urange a b = if a == b then [] else a:urange (a+1) b
ult8 :: Int8 -> Int8 -> Bool
ult8 x y = ((fromIntegral x)::Word8) < ((fromIntegral y)::Word8)
ugt8 :: Int8 -> Int8 -> Bool
ugt8 x y = ult8 y x
ule8 :: Int8 -> Int8 -> Bool
ule8 x y = not(ugt8 x y)
uge8 :: Int8 -> Int8 -> Bool
uge8 x y = not(ult8 x y)
ult16 :: Int16 -> Int16 -> Bool
ult16 x y = ((fromIntegral x)::Word16) < ((fromIntegral y)::Word16)
log2 :: Int8 -> Int8
log2 n
| n < 1 = error "agument of logarithm must be positive"
| otherwise = go 0 1
where
go exponent prod
| prod < n = go (exponent + 1) (2*prod)
| otherwise = exponent
mul_lohi x y = let x' = zext x
y' = zext y
m = x' * y'
in (fromIntegral m, fromIntegral (m `rotateR` 8))
clz :: Int8 -> Int
clz x = let asBool = reverse $ map (testBit x) [0..7]
in case elemIndex True asBool of
Just x -> x
Nothing -> 8
clo :: Int8 -> Int
clo x = let asBool = reverse $ map (testBit x) [0..7]
in case elemIndex False asBool of
Just x -> x
Nothing -> 8
cls :: Int8 -> Int
cls x = max (clo x) (clz x)
toBin :: Word8 -> String
toBin w = map (\i->if testBit w i then '1' else '0') [0..7]
log_floor :: Word8 -> Int
log_floor x = foldl1 max $ filter (\i -> (shift 1 i) <= x) [0..7]
log_ceil :: Word8 -> Int
log_ceil x = foldl1 min $ filter (\i -> (shift 1 i) >= x) [0..7]
w :: Int8 -> Bool
w x = not (unsign_overflows_mul (-1) x)
w2 :: Int8 -> Bool
w2 x = sign_overflows_sub 0 x /= sign_overflows_mul (-1) x
w3 :: Int8 -> Bool
w3 x = unsign_overflows_sub 0 x /= unsign_overflows_mul (-1) x
w4 :: (Int8, Int8) -> Bool
w4 (a, b) = b /= 0 && a + b == a
w5 :: (Int8, Int8) -> Bool
w5 (x, y) = (x < y) /= ((x + (-128)) `ult8` (y + (-128)))
w6 :: (Int8, Int8) -> Bool
w6 (x, y) = sign_overflows_op (-) (-) x y /= sign_overflows_op (+) (+) x (-y)
w8 x = let = if x + 1 > x then x + 1 else x
w7 :: (Int8, Int8) -> Bool
w7 (x, y) = (x > y) /= ((comp x) < (comp y))
where comp t = (-1) - t
w8 :: (Int8, Int8, Int8) -> Bool
w8 (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s < e)
is_protected = (s - stride) < e
in is_protected && is_zero_trip_count && computed_trip_count /= 0
w8_full (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s < e)
is_protected = (s - stride) < e
result = is_protected && is_zero_trip_count && computed_trip_count /= 0
in (computed_trip_count, is_zero_trip_count, is_protected, result)
( e - s ) ` ugt8 ` 1 & & ( e - s ) ` ule8 ` 128 & & s > = e & & ( s + 128 ) < e
w9 :: (Int8, Int8, Int8) -> Bool
w9 (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s `ult8` e)
is_protected = (s - stride) `ult8` e
in is_protected && is_zero_trip_count && computed_trip_count /= 0
w10 :: (Int8, Int8, Int8) -> Bool
w10 (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s `ult8` e)
is_one_trip_count = s `ult8` e && not (unsign_overflows_add s stride) && (not $ (s + stride) `ult8` e)
is_protected = (s - stride) `ult8` e
in is_protected && is_one_trip_count && computed_trip_count /= 1
w10_full (e, s, stride) =
let computed_trip_count = ((e - s) + stride - 1) `udiv8` stride
is_zero_trip_count = not(s `ult8` e)
is_one_trip_count = s `ult8` e && not (unsign_overflows_add s stride) && (not $ (s + stride) `ult8` e)
is_protected = (s - stride) `ult8` e
result = is_protected && is_one_trip_count && computed_trip_count /= 1
in (is_protected, is_one_trip_count, computed_trip_count, result)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.