Hum Code Base
Hum-FileIn
Hum-FileIn -- HumFileInSubclass
subclassMethod: anArgument3
Hum-FileIn -- HumFileIn
anotherMethod: anArgument2
"This is a second method to check for iteration anomolies."
"Another minor edit."
someMethod: anArgument
"This method provides means to test file in from generated code."
"Minor Edit"
^someInstanceVariable.
Hum-FileIn -- HumFileOut
myInstanceVariable
^ myInstanceVariable.
Hum-Graph
Hum-Graph -- HumGraphTests
test110GraphHasNodes
"A graph has a collection (set) of nodes"
test120GraphHasConnections
"A graph has a collection (set) of connections."
test130PutGetNode
"A graph has a collection (set) of nodes"
test140PutGetConnector
"A graph has a collection (set) of connections."
test150PutGetLabeledConnections
"A graph has a collection (set) of connections"
***22 lines of code ***
test152PutGetParallelConnections
"A graph has a collection (set) of nodes"
***40 lines of code ***
test160DetectCycle
"A graph has a collection (set) of nodes"
Hum-Graph -- HumGraph
addConnection: anAssociation
addConnection: anAssociation label: aString
"Note: A pair of nodes may have more than one relation."
"Make sure the nodes are in the node set."
"There can be multiple connections between two nodes. But must have distinct labels."
addNode: anObject
"Add the given object to the set of nodes"
" Note that each object / node is unique"
addNode: anObject label: aString
"Add the given object to the Set of node-labels"
" Note that each object / node is unique"
"TODO: Shouldn't this be an association?"
connectionLabels
"Note: A pair of nodes may have more than one relation."
"See: #addConnection:label:"
"Set of { fromNode -> toNode. label. }"
^ connectionLabels ifNil: [ connectionLabels := Set new ].
connections
"Return the connections (associations) in this graph."
"TODO: Improve code readability.
"entry looks like { association. label. }"
^bagConnections.
connectionsFrom: aNode
"Get the outbound connections from this node. "
^outboundConnections.
countNeighborsOfNode: aNode
"Return the number of neighbors of this node.
^ count
hasCycle
"Does the graph contain at least one cycle?"
"downStreamFrom: will not extend leafs that match root"
^false.
nodeLabels
^nodeLabels ifNil: [ nodeLabels := Set new ].
nodes
"Return the nodes in this graph."
"entry looks like { label. object. }"
^bagNodes.
nodesDownStreamFrom: aRootNode
"Collect the nodes that are down-stream from a root node."
"Set up recursive loop."
"Avoid cycles."
^downStream.
nodesDownStreamFrom: aRootNode butNotIn: upStreamNodes
"Find nodes that are down-stream from the root node but not in the upStreamNodes."
"Note: It is possible for a pair of nodes to have more than one relationship."
"Unpack the tuple."
"TODO: ADD RECURSION AFTER THIS IS DEBUGGED."
^downStreamNodes.
Hum-IDE
Hum-IDE -- HumCodeBase
everythingIsClassSide
"This is organized as a singleton - all the methods are on the class side."
Hum-IDE -- HumCodeStream
<< aString
asString
^self printString.
contents
^(self stream) contents.
limit
"At what point do we assume code generation has run amock?"
^ limit ifNil: [ limit := 200 ].
limit: aSmallInteger
printString
^(self stream) contents.
stream
^stream.
Hum-IDE -- HumFrameUpdater
addActionLine: aSourceString
"Start a new action frame. This action is in the role`s PUBLIC API."
self frame: (HumFrame4Action ontology: ontology
"Start a new action frame. This action is in the role`s PRIVATE API."
***22 lines of code ***
addDictionaryLine: aSourceString
addMarkUp: aSourceString
addPlanLine: aSourceString
"The kind of line is modal."
"Look for lines that reset the mode."
^self.
^self.
"Process the source line according to mode set by prior source line."
^self
^self.
^self
***41 lines of code ***
addVignetteInstruction: anInstructionLine
addVignetteLine: aSourceString
"DEBUG
"
"Store prior vignette frame and Start a new vignette frame."
***52 lines of code ***
addVignetteResponse: aResponseString
appendFrameLine: aSourceString
"Create appropriate frameLine type and append to frame."
"For vignette lines, we want to preserve leading dot because it identifies instruction lines."
appendInstructionRole: aRole statement: aStatement
appendInstructionRole: aRole statement: aStatement comment: aComment
appendInstructionStatement: aStatement
"Append a simple instruction (no delegation, no comment) to the frame."
appendPrecondition: aPreconditionStatement
appendRole: aRole action: aStatement
"Pass through to frame."
checkFrameSyntax
^errors.
compileToOntology: aHumOntology
"Delegate to the frame."
^errors.
frame
"If frame is not initialized before this call, we have a logic error."
^frame ifNil: [ Error signal: 'frame has not bee initialized in FrameEditor instance.'].
frame: aFrame
"What frame am I editing ?"
getInstructionAt: aSmallInteger
^self lines at: aSmallInteger .
isEmpty
^ (frame isNil) or: [frame isEmpty].
lines
^ (self frame) lines.
nextVignetteContext: aString
ontology
^ (ontology) ifNil: [ Error signal: 'Frame Updater instance must have an ontology.']
ontology: aHumOntology
parseInstruction: sourceWith
"Allow blank lines for readability."
"Identify pattern and parse accordingly."
^resultLine.
***21 lines of code ***
prettyPrint
"Pretty print the frame content (rendering as HTML)."
^html
programmersAssistant
^ programmersAssistant ifNil: [programmersAssistant := HumProgrammersAssistant new].
putInstruction: aHumInstruction at: aSmallInteger
storeFrameInOntology
"Store my frame in my ontology"
"The frame must have a title."
stripLeaderFrom: aLine
^stmt
vignetteContext
^result.
vignetteMode
"What mode is the vignette parser in?"
^vignetteMode
vignetteMode: newMode
"What mode is the vignette parser in?"
Hum-IDE -- HumProgrammersAssistant
clearOntology
getAnnotationFromSource: aSourceString
"Match '[...]' if any, and extract it from source."
^annotation.
getCommentFromSource: aSourceString
"Match '(...)' if any, and extract it from source."
^comment.
getLabelFromSource: aSourceString
"Match 'word:' at the front of the string.
^label.
loadOntology: anOntology fromTextFileNamed: fileName
"Load an ontology from the given text file."
^ontology.
loadOntologyFromSaveFileNamed: aFileNameString
"Reload an ontology from the given save file."
^ontology.
loadOntologyFromTextFileNamed: fileName
"Load an ontology from the given text file."
^ontology.
loadOntologyFromTextStream: aStream
"Discover frame type and store each frame in ontology."
"Use ontology provided by caller or lazy initialization."
"Define a function to detect action subframe case."
"Read frames from the stream."
"Get a fresh frameUpdater."
"Get the title line and discover what kind of frame comes next."
"Strore frame - unless frame is empty."
^ontology.
***28 lines of code ***
makeFramePerTitleLine: source
"The label on the title line indicates the kind of frame."
"Track which ontology the frame was defined in."
^frame.
***45 lines of code ***
ontology
"Return the ontolgy. If nil initialize one."
^ ontology ifNil: [ ontology := HumOntology new. ].
ontology: aHumOntology
parseActionLine: source
"An action line begins with 'Action:' or 'To:' label.
"
"Look-up #word types to see if they are #noun types."
^ tokenPairsWithNounsMarked.
***22 lines of code ***
parseActionLine: aString keywords: aCollection
"An action line begins with 'Action:' or 'To:' keyword.
parseInstructionSource: source keywords: keywords
"Parse the source -- Return a list of token-type pairs: ( token -> tokenType ).
"
"Look-up #word types to see if they are #noun types."
"If second token is colon, first token is a role."
^ tokenPairsWithNounsMarked.
***33 lines of code ***
parseMarkupSource: aSourceString
^result.
parseSource: source keywords: keywords
"Parse the source -- Return a list of token-type pairs: ( token -> tokenType ).
"
"Look-up #word types to see if they are #noun types."
^ tokenPairsWithNounsMarked.
***25 lines of code ***
removeAnnotationFromSource: aSourceString
^cleanerSource.
removeCommentFromSource: aSourceString
^cleanerSource.
removeLabelFromSource: aSourceString
"If there is a label, remove it and return the remainder."
^remainder.
saveOntologyOnFileNamed: aFileName
"Save my ontology on the given ReferenceStream file."
"Note: This method does not provide any kind of versioning."
"ToDo: If we save ontology in a WorldBase instead,
"Open the file for write -- clear it if necessary."
"Write the various data structures to the file."
writeFrame: aFrame onStream: aStream
"Write frame-lines to given stream in canonical format. *** NO SENDERS ***
"My indent convention involves dot leader"
writeOntologyContextVignettesOnStream: aStream
writeOntologyFrame: aFrame onStream: aStream
"Write to given stream - customize per frame-type as needed."
"Eh? - All lines have the same dotLeader ??? What was I thinking???"
"See also: writeOntologyFrameWithIndents:onStream:"
writeOntologyFrameWithIndents: aSubFrame onStream: aStream
"Vignette and View frames use dot-leader only for instruction lines."
"My indent convention involves dot leader"
"NOTE: This assumes the source does not contain its own dot-leader."
writeOntologyFramesOfType: aFrameClass onStream: aStream
"Select frames of given class and write them on the stream."
writeOntologyOnTextFileNamed: aFileName
"Save my ontology in text format on the file with the given name. "
"Order: Comment, Dictionary, Vignette, Role-Action, Plan, View"
" -- NOTE: Original file order (if any) is not maintained. That means that comment frames may lack original context."
"Write context vignettes in consolidated frames."
"Write role-actions in consolidated frames."
"Write the remaining frames. ( Plan, View )"
writeOntologyRoleActionsOnStream: aStream
"Write role-action frames ordered by role and action."
***21 lines of code ***
writeOntologyVFrame: aFrame onStream: aStream
"Write UI frames: Vignette and View frames only use dot-leader for instruction lines."
"My indent convention involves dot leader"
Hum-IDE -- HumTextEditor
beep
"Signal that cursor is out-of-bounds."
bumpColumn: anInteger
bumpRow: anInteger
column
"What is the current column position of the cursor?"
^column ifNil: [ column := 1 ].
column: anInteger
"Move cursor to given column position."
currentLine
^self lineAt: (self row).
currentLine: aString
cursorPosition
"Where is the insert point?"
^ (self row)@(self column).
deleteOrMerge
"Delete character to left of cursor.
"Move remaining lines up"
***38 lines of code ***
drawTextOnCanvas: aHumCanvas font: aFont
drawTextOnPane: aHumPane font: aFont
hasNewContent
"Has the content been changed? -- (Dirty data flag)"
^hasNewContent ifNil: [ hasNewContent := false ].
hasNewContent: aBoolean
"Set true whenever the content has been changed."
"TODO: Notify watchers if the boolean is true."
insertCharacter: aCharacter
keyStroke: aCharacter
"Respond to simple keyboard input. (KISS: a character)
"NOTE: Character does not support control, command, or shift modes."
lineAt: anInteger
"Get string for given row"
^aLine.
lines
"PRIVATE: My text lines.
^lines ifNil: [ lines := Dictionary new ].
row
"What is the current row position of the cursor?"
^row ifNil: [ row := 1 ].
row: anInteger
"Move cursor to given row position."
"Note: You can move row beyond current lines."
splitRow
"Everything after the current row is moved down one."
"Split the current line."
***22 lines of code ***
Hum-Language
Hum-Language -- HumCommentLine
source: aString
"override supertype parsing"
Hum-Language -- HumConditionLine
<= aHumConditionLine
"Provide a way to order preconditions
^(self source) <= (aHumConditionLine source)
annotation
^ annotation ifNil: [ '' ].
annotation: aString
"Annotation may indicate that condition is 'assumed'. Other cases are not yet defined."
checkSyntaxWithOntology: aHumOntology
"Is the precondition assumed?"
"Otherwise: See if we have a plan for satisfying this precondition."
"NOTE: #getPlanFrameForGoal: will return an empty plan frame if there is none in the ontology.
"
^errors.
***21 lines of code ***
comment
^ comment ifNil: [ '' ].
compileLineToOntology: aHumOntology
"compile a precondition line into the ontology.
"
^problems.
source
| s |
^ s.
source: aString
"DEBUG: Should not be 'Precondition' or: 'Pre'"
^super source: aString.
statement
^ statement ifNil: [ '' ].
statement: aSource
"Set my statement."
Hum-Language -- HumDictionaryLine
comment
^ comment ifNil: [ comment := String new. ].
compileLineToOntology: aHumOntology
"Add nouns and noun-relations to the ontology.
"
"We may discover syntax errors while compiling.
"
^lineErrors.
^lineErrors.
^lineErrors.
^lineErrors.
^lineErrors.
^lineErrors.
^lineErrors.
^lineErrors.
^ lineErrors.
^ lineErrors.
^lineErrors.
^lineErrors.
^lineErrors.].
"Comment: Shorthand and synonym and abbreviation features enable jargon.
"
"If we fall through to here,
^ lineErrors.
***134 lines of code ***
getListAfter: aString
"Remove the word 'and' from the list."
^list.
source
"Construct a source line based on convention and content of my attributes."
^source ifNil: [ source := '*** No Source? ***' ].
statement
^ statement ifNil: [ statement := HumStatement source: (self source). ]
statement: aStatementString
Hum-Language -- HumFrame4Action
actionStatement
^ actionStatement ifNil:[ Error signal: 'Action frame must have an action statement'].
actionStatement: anObject
appendInstructionRole: aRole statement: aStatement
appendInstructionRole: aRole statement: aStatement comment: aComment
appendInstructionStatement: aSource
checkSyntaxWithOntology: anOntology
"Critique the instructions for this role action."
"Return the critique as a sequence of strings."
"The action should contain at least one noun."
"There should be at least one instruction for the action statement."
"Nouns in the instructions should find antecedants in the action statement."
"TODO: The line after 'For . . . : ' or 'If . . . : ' or 'Else:' should be indented."
"TODO: Think about how indentation should be assured.
"
^critique.
***31 lines of code ***
compileToOntology: aHumOntology
"Compile the frame into the ontology."
"Make sure frame is stored."
"Index the role-action"
"Add the instruction sequence"
"aHumOntology appendInstruction: instruction toRole: (self role) action: (self actionStatement)."
"Return no errors."
^ (self checkSyntaxWithOntology: aHumOntology ).
***22 lines of code ***
instructionLines
^ instructions ifNil: [ instructions := OrderedCollection new ].
instructions
^ instructions ifNil: [ instructions := OrderedCollection new. ].
instructions: anObject
role
^ role.
role: anObject
titleLine
"Format a cannonical title line."
^ 'Role: ', ( self role asString capitalized), ' -- ', ( self actionStatement asString ).
Hum-Language -- HumFrame4Comment
appendFrameLine: aLine
Hum-Language -- HumFrame4Data
appendEntity: aEntityName attrribute: anAttributeName value: aValueString
asString
^s.
Hum-Language -- HumFrame4Dictionary
addDictionaryLine: aSourceString
compileToOntology: aHumOntology
"Each dictionary line will have some additive effect on the ontology."
"Make sure frame is stored."
"We may discover syntax errors while compiling."
^syntaxErrors.
Hum-Language -- HumFrame4Plan
actionStatements
^self planActions.
appendInstructionRole: aRole statement: aStatement
appendPrecondition: aSource
appendPrecondition: aStatement annotation: anAnnotation
appendRole: aRole action: aSource
"Add 'role: action-statement' to plan-frame"
appendRole: aRole action: aSource comment: aComment
"Add 'role: action-statement. (comment)' to plan-frame"
check
"Check the basic integrity of the plan frame."
"The callers sees the problems in the same order we do."
"The plan frame must have a goal."
"A plan frame should have at least two preconditions."
^problems.
checkSyntaxWithOntology: anOntology
"Check stand-alone syntax.
"
"Check data flow.
^frameErrors.
***24 lines of code ***
compileToOntology: aHumOntology
"Check the basic integrity of the plan frame.
"Make sure frame is stored."
"The callers sees the problems in the same order we do."
"A plan frame should have at least two preconditions. (should not must)"
"The plan frame must have a goal."
"If the frame has a goal, store the frame regardless of errors."
"Compile the preconditions"
"Index the precondition"
"aHumOntology frameRelations add: { (self title). #precondition. (precondition statement asString). }."
"TODO: Decide if we want the title or the frame itself. (frame reference)"
"Note: The title may change when the goal statement is edited. However, recompile should fix."
"Note: Our structure could enable changing definition, changes all references."
"Compile the actions"
"Index the precondition"
"aHumOntology frameRelations add: { (self title). #invokesAction. ( action titleLine ). }."
^problems.
***53 lines of code ***
goal
"Get the plan frame's goal statement."
^ goal
goal: aSource
"This instance variable contains the plan frame's goal statement."
isNoPlan
"Frame is no plan if there are no preconditions and no actions.
"
^true.
planActions
"A sequence of actions to be performed after preconditions are satisfied.
"
^ planActions ifNil: [ planActions := OrderedCollection new. ].
preconditions
"Preconditions are ordered to preserve the author`s sequence,
"
^ preconditions ifNil: [ preconditions := OrderedCollection new ].
Hum-Language -- HumFrame4View
addMarkUp: aSource
compileToOntology: aHumOntology
""
"Make sure frame is stored."
"Index cases where a widget refers to another view."
"(aHumOntology frameRelations) add: { (self title). #invokesView. viewName. }"
^errors := (super compileToOntology: aHumOntology ).
***24 lines of code ***
entity
^ entity ifNil: [ entity := HumCalculator given: (self titleLine) extractAfter: ': '].
entity: anObject
viewEntity: anEntityType.
"What entity-type is this view displaying."
viewName: aString
"Caller passes the name of the view - to be used in calls."
"View-name is a noun."
Hum-Language -- HumFrame4Vignette
addPattern: aPatternString
"Enter a pattern -- What pattern will the vignette respond to?"
"Nil is ignored when parser is running."
addVignetteInstruction: anInstructionLine
"Append an instruction to be executed in response to the user / client."
"check for role"
addVignettePattern: patternString
"Append an Pattern to be matched in response to the user / client."
addVignetteResponse: aResponseString
"Append a verbal response line."
checkSyntaxWithOntology: anOntology
"Check the vignette for syntax problems."
"First get the critique of the frame lines."
"The vignette must have a context and a pattern."
"The nextContext should be known to the ontology.
"
"Each [noun] field in the pattern should reference known nouns."
^critique.
***35 lines of code ***
compileToOntology: anOntology
"Update the ontology with this vignette."
"Make sure frame is stored."
"Index any external action calls."
^ ( self checkSyntaxWithOntology: anOntology ) .
***42 lines of code ***
inputToken: inputToken isEquivalentTo: patternToken
"Is the input equivalent to the pattern?
"
"Simple case."
"Handle tricky pattern tokens."
inputTokensIn: aString
"Return the pattern tokens in the given string."
"Extract strings in the input as separate tokens."
"TODO: Numbers followed by measurement units should be treated as a single token."
^tokens.
***27 lines of code ***
instructionLines
"Return the vignette's instruction lines. "
^ instructionLines ifNil: [ instructionLines := OrderedCollection new. ].
nextVignetteContext
"By default, the next context is the current context."
^ nextContext.
nextVignetteContext: aContextName
"What will be the context after the response is rendered?
"
patternFields: pattern
"Parse the pattern and return the [noun] fields - including the brackets.
^fields.
patternMatchScore: aString
"How well does the string (from client) match the pattern int this vignette?
"
"But first, one pattern has to match. Then we score it."
"These parsers remove noise words (a, an, the)."
"Attempt to match input to pattern."
"Does the remaining input have the next pattern token?
"
"xNextInput := inputTokens indexOf: nextPatternToken startingAt: xInput ifAbsent: [ -1 ]."
"For now, assume the next input token matches the bracket expression."
"Advance the pattern token index to the closing bracket."
"A missing bracket should have been caught at compile-time."
"Advance the input to the next pattern token."
"Force out to the next pattern."
"Partial match does not score."
"Force out to the next pattern."
^ bestPatternPoints.
***99 lines of code ***
patternNouns
"TODO: DOES THIS BELONG IN HumVignettePatternLine ?"
^ nouns.
patternNouns: pattern
"Parse the pattern and return the nouns referenced in [noun] fields.
"
^fields.
patternTokensIn: aString
"Return the pattern tokens in the given string.
"
^tokens.
patterns
^ patterns ifNil: [ patterns := OrderedCollection new ].
responseLines
"What will be the verbal response? "
^ responseLines ifNil: [ responseLines := OrderedCollection new. ].
titleLine
^s.
vignetteContext
"The context is used to prioritize responses when two or more patterns match a user input.
"
^ vignetteContext
vignetteContext: aContextString
"The context is used to prioritize responses when two or more patterns match a user input.
"
zpatternMatchScore: aString
"How well does the string (from client) match the pattern int this vignette?
"
"(aString beginsWith: 'My name is') ifTrue: [self halt]." "DEBUG"
"But first, one pattern has to match. Then we score it."
"Remove noise words and punctuation"
"Attempt to match input to pattern."
"Does the remaining input have the next pattern token?
"
"TODO: HOW SHOULD WE INTERPRET THIS?
"
"For now, assume the next input token matches the bracket expression."
"Advance the pattern token index to the closing bracket."
"Force out to the next pattern."
"Force out to the next pattern."
^ bestPatternPoints.
***93 lines of code ***
Hum-Language -- HumFrameLine
checkForAntecedantsIn: aHumStatement withOntology: aHumOntology
^result.
checkSyntaxWithOntology: aHumOntology
^ errors.
comment
"Any frame line can have a comment."
^comment ifNil: [comment := ''].
comment: aString
"Any frame line can have a comment."
compileLineToOntology: aHumOntology
"Compile this instruction line."
"Subtypes should implement."
"Error signal: 'Subtypes should implement.'."
^ errors.
doTokensIn: input at: x matchPatternTokensIn: patternTokens at: xPattern
"See if we can get any matching sequence."
"TODO: Everything in this method category should probably be in HumOntologyTranslator."
"If we run out of pattern, we have succeeded."
"If we run out self before we run out of pattern, we have failed."
"A pattern token that is a digit will match anything.
"
^isMatch.
"Remainder assumes that current pattern token is NOT a digit."
"If the current pattern token matches the current self token, proceed to the next token in both lists."
^isMatch
^isMatch. ].
"At this point we have a mismatch for sure. (I think maybe.)"
^isMatch.
***34 lines of code ***
extractPatternParameters: aPatternString
"Extract parameters (tokens) from source that match the pattern."
"Search to see if a sequence in my tokens matches a sequence in pattern tokens."
^ parameters reversed.
generateCodeFrom: aTemplateString using: parameterValues
"Generate code (string) from the template replacing parameters with values in the parameter list."
"TODO: Does this method belong in HumOntologyTranslator ?"
^code.
getParametersIn: input at: x thatMatchParametersIn: patternTokens at: xPattern accumulating: parameters
"See if we can get any matching sequence."
"If we run out of pattern, we have succeeded."
"If we run out self before we run out of pattern, we have failed."
"A pattern token that is a digit will match anything.
"
^isMatch.
"Remainder assumes that current pattern token is not a parameter."
"If the current pattern token matches the current self token, proceed to the next token in both lists."
^isMatch
^isMatch. ].
"At this point we have a mismatch for sure. (I think maybe.)"
^isMatch.
***35 lines of code ***
getTokensIn: aString
"This is a helper for #matchesPattern: (). It implements a Hum-friendly tokenizer."
"TODO: Does this method belong in HumOntologyTranslator ? It also might be in HumCalculator."
"Punctuation does not include hyphen because nouns may be hypenated."
"White space includes space, cr, tab."
"Tokens are all lower-case and include punctuation."
^tokens.
matchesPattern: aPatternString
"Does some part of the frame-line match the given pattern?"
"Search to see if a sequence in my tokens matches a sequence in pattern tokens."
^isMatch.
onMatch: aPatternString generate: aTemplateString
"When some part of the content in the current line matches the pattern,
"
"If there is no match, there is nothing to do. Return an empty string."
"Otherwise, we have a match.
"
^code.
printOn: aStream
"Append to the argument, aStream, a sequence of characters that
"nextPutAll: (title first isVowel ifTrue: ['an '] ifFalse: ['a ']);"
sameAs: anotherFrameLine
"Eh? Why are we here?"
source
^ source
source: aString
"Any frame line might have a comment between ()."
" (self comment size > 0)
Hum-Language -- HumFrame
appendFrameLine: aFrameLine
"Append a line to the frame."
checkSyntaxWithOntology: anOntology
"Check stand-alone syntax.
"
^frameErrors.
compileToOntology: aHumOntology
"Regardless of errors add frame to the ontology."
^problems.
debug
"Am I in debug mode?"
^ debug ifNil: [debug := false].
debug: aBoolean
delegateToTranslator
delegated
frameLines
^frameLines ifNil: [ frameLines := OrderedCollection new.]
frameName
"The name of the frame is guaranteed to be a string.
"
^ frameName.
initialize
"The instance should always be a subtype."
isEmpty
^result.
linesAsHTMLwithOntology: anOntology
^html.
ontology
^ ontology
ontology: anOntology
origin
"Where did this frame come from?"
^origin ifNil: [ origin := 'unknown' ].
origin: aString
"Where did this frame come from?"
prettyPrintWithOntology: aHumOntology
"Pretty-print using HTML5 and CSS
^html.
printOn: aStream
"Append to the argument, aStream, a sequence of characters that
"nextPutAll: (title first isVowel ifTrue: ['an '] ifFalse: ['a ']);"
title
^ self titleLine
titleLine
^titleLine
titleLine: anObject
uniqueIdentifier
"Note: Lazy initialization for this frame`s identifier."
^ uniqueIdentifier
zcompileToOntology: aHumOntology
"Regardless of errors add frame to the ontology."
"Looking for trouble!"
"Action, Plan, and Vignette frames all may have instruction lines."
^problems.
Hum-Language -- HumInstructionLine
= anInstruction
"??? Looks like bad code ??? "
"Find out where this is used. (2015-12-26: None of the unit tests trip over this halt.)"
annotation
^ annotation ifNil: [^'' ].
annotation: aString
"Annotation may indicate timing for simulations.
"
checkSyntaxWithOntology: aHumOntology
^ errors.
checkSyntaxWithOntology: aHumOntology defaultRole: aRole
"Forgive a nil statement. Sometimes an instruction line has no statement."
"Ignore empty statement"
"Check that the nouns in the statement are known. (defined in the ontology)."
"Check that a delegated action is defined in the ontology."
^ errors.
comment
^ comment ifNil: [''].
comment: aString
"Comment is not executable. May be displayed in certain contexts."
compileLineToOntology: aHumOntology
"Compile this instruction line."
"Check syntax"
"remember the errors - May show in HTML and other views"
^ errors.
compileLineToOntology: aHumOntology defaultRole: aRole
"Compile this instruction line."
"TODO: Kludge some polymorphism.
"Check syntax"
"remember the errors - May show in HTML and other views"
^ errors.
indent
"How many indents (tabs) before the start of the code-text ?"
^ indent ifNil: [ indent := 1 ].
indent: aSmallInteger
"How many indents (tabs) before the start of the code-text ?"
jobTicket
"There should be a job ticket if the (run-time) caller expects one."
^ jobTicket ifNil: [ Error signal: 'no jobTicket']
jobTicket: aJobTicket
"At run-time, a job ticket may be associated with action request."
"TODO: This instance variable is here because the run-time needs to pass a jobTicket when delegating an instruction. (?)
onComment: aBlockClosure
"If instruction includes a comment, execute the block."
onRole: aBlockClosure
"If instruction includes a role prefix, execute the block."
role
"What role am I delegating to? If none, the instruction is to myself."
^ role ifNotNil: [ (role) ] ifNil: [''].
"TODO: Consider returning #self instead of an empty string."
role: aString
"Delegate the task (statement) to this role at run-time. "
source
"Construct a source line based on convention and content of my attributes."
^ s.
source: aString
"Should not be: 'Action:' block-label."
^super source: aString.
statement
"What will be done . . . will be done at run-time."
^ statement
statement: aSource
"What to do at run-time?"
"Determine the indent level."
^self.
^self. ].
***26 lines of code ***
title
^ self titleLine.
titleLine
^ ( self role), ': ', ( self statement asString ).
translation: aString
Hum-Language -- HumMarkupLine
checkSyntaxWithOntology: aHumOntology
"Syntax errors in mark-up mainly have to do with widgets that won't work.
"
""
"Look for unknown nouns in widgets."
"TODO: Look for unknown widget-types in widgets.
"
^errors.
***32 lines of code ***
compileLineToOntology: aHumOntology
""
"Look for unknown nouns in widgets."
"TODO: Look for unknown widget-types in widgets."
^errors.
***24 lines of code ***
generateCodeOfType: aSymbol fromTokens: tokens at: xToken
"Generate code of the given type HTML/Seaside/JavaScript based on token stream."
"Current experiment is to generate HTML5 from Hum mark-up."
"If we ran out of tokens, we are done?"
"If we are at beginning of line, there are special rules."
^ code.
"Remainder of line is in this header"
^code.
"If level has changed, we need to output <ul> or </ul>"
"Remainder of line is in this header"
^code.
"If we have come this far, the line begins with nothing special."
"Go on as if we were not on the first token."
"Look for quotes -- we need to remove tokens between quotes from translation."
^code.
"Look for emphasis -- tokens between are in scope of . . ."
"Note: Above is a bit simplistic.
"
^code.
"Look for widgets."
***80 lines of code ***
generateHtmlTableFor: aNoun withOntology: anOntology
"If the entity has no attributes, generate a default table."
"Otherwise generate a normal table."
^html.
getWidgetArgument: aWidgetString
"Parse the widget string to get verb`s argument, if any."
^argument
getWidgetNoun: aWidgetString
"Parse the widget-string to get the widget`s noun (blackboard entity-attribute-name), if any."
^noun
getWidgetVerb: aWidgetString
"Parse the widget-string to get the widget`s verb, if any."
^verb
widgets
"Scan the source matching pairs of [. . .] or [[. . .]]."
"Scan for widgets"
^widgets.
***21 lines of code ***
Hum-Language -- HumOntologyTranslator
asJava
"This is crude version.
"
^ code.
attachAction: aMethodName toActorClass: aClassName fromSource: aSource
"Attach the given method source
attachPrologToActorClass: aClassName fromSource: aSourceString
"Attach the given prologue source code to the named class."
"Note: There can be only one prologue for each actor class"
contextEntity: aString
countLeading: aCharacter inString: line
"Count leading"
^n-1.
genHTML: generatedCodeString
"Append generated code to 'html' instance variable. (YIKES!)"
"If code begins with a tag, insert cr to improve readability."
generateErlangDocumentation
"2015-12-26: I wrote some experimental versions of an Erlang Messenger some time ago.
"
^translationStrategy, runTimeStrategy.
generateErlangForActionCall: aString
"Translate a Hum Action call into an Erlang OTP call."
"Extract the statement string from the Instruction Line."
"TODO: HumStatement knows how to parse better than HumCalculator. It knows about comments and annotations."
^erlang
generateErlangForActionHeader: aString
"Then: The do header looks like 'do( { action-statement, noun-values } )' "
"TODO: Fix case where statementString contains single quote/s."
^ erlang.
generateErlangForEntity: anEntity
"Translate entity into an Erlang record data structure. <<< OBSOLETE
"
"After all, action call will be ?CALL({',roleAtom,',"',statementString,'",NounValues}). where NounValues is a list of {noun, noun-value} tuples."
"Generate the preamble."
"Generate the tuple elements."
^erlangCode.
***33 lines of code ***
generateErlangForInstruction: aHumInstructionLine
"Generate self-call or RPC for given instruction."
"Insert comment, if any, before the Erlang translation of the statement."
"If a role-label is present, the action is delegated to another role; otherwise calling self."
^erlangCode contents.
***22 lines of code ***
generateErlangForPlanFrame: aHumFrame4Plan
"Translate the plan frame into an Erlang data structure.
"
^erlangCode.
***28 lines of code ***
generateErlangForRole: aRoleName
"Generate Erlang code for the given role-name."
"Generate the module`s declarations."
"TODO: Define TBD string (see above) - Call is routed to appropriate Hum Dispatcher via Hum Messenger."
"Following causes compiler to show macro expansion. "
"Generate the logic for each action frame."
^moduleDeclarationCode contents, moduleLogicCode contents.
***37 lines of code ***
generateErlangForRoles
"Generate a Erlang module file for each Hum role."
generateErlangForSelfCall: aString
"Translate a Hum Self call into an Erlang self call."
"TODO: HumStatement knows how to parse better than above. It knows about comments and annotations."
^erlang
generateErlangNounValuesForStatement: aStatementString
"Get statement nouns."
^ nounValueTuples contents.
generateHTMLforMarkupLines: aListOfFrameLines blackboard: aBlackboard
"Build HTML for the given list of frame-lines"
"My code produces side-effect in instance-variable 'html', (shame on me)
"
"There should be no remainder"
^self html contents.
***59 lines of code ***
generateHTMLforMarkupString: aMarkupString blackboard: aBlackBoard
"Build output until we see a substring matching aStopString."
"When we need to recurse,
"
"Emphasis patterns. (bold, italic, underline, superscript)"
"Hypertext"
"Delegate to another pane."
"Button"
"Treat button as a special case?"
"Radio Button or Comment"
"Is a radio button intended?"
"Input widgets"
"TODO: When view is invoked with 'Show:' rather than 'Ask:', the input fields should be disabled."
"TODO: Adapt input to datatype."
"Catch checkbox case"
"TODO: Adapt input to datatype.
"
"table row -- Should be implemented elsewhere."
"Just ordinary text."
^remainder := ''.
"Recurse"
^self generateHTMLforMarkupString: remainder blackboard: aBlackBoard.
***123 lines of code ***
generateHTMLforViewFrame: aHumFrame4View blackboard: aHumBlackBoard
"Wrap viewframe lines with HTML form and submit logic."
"Translate the Hum markup"
"Add a submit button"
"The user might not be ready to fill-in-the-blanks. Give user a way to decline."
"TODO: The Scribe must interpret 'Go!' versus 'NoGo!' -- to invoke appropriate dialog vignette."
"Wrap in a form."
^formHTML.
***23 lines of code ***
generateJavaCallForFrameLine: aHumInstructionLine
"space := Character space asString."
"Generate optional code if role or comment is present."
"Generate Java code -- depending on type of statement."
^instructionCode.
***21 lines of code ***
generateJavaCallForStatement: aHumStatement
^code.
***22 lines of code ***
generateJavaConditionalForStatement: aHumStatement
^code.
generateJavaForFrame: aHumFrame4Action
"Translate frame to Java using the nouns given in the ontology."
"TODO: Translate if/else/for"
^ javaDoc, cr, selectorCode, space, '{', frameCode, cr, '}' .
***23 lines of code ***
generateJavaForFrameLine: aHumInstructionLine
"space := Character space asString."
"Generate optional code if role or comment is present."
"Generate Java code -- depending on type of statement."
^instructionCode.
generateJavaForPlanFrame: aHumFrame4Plan
"The plan is data, so translation involves translating each goal frame into a series of Java setters.
"
^javaCode.
***22 lines of code ***
generateJavaForStatement: aHumStatement
"TODO -- This will fail if there is a comment appended to the statement."
^code
generateJavaIterationForStatement: aHumStatement
"Given a Hum for-statement, generate a Java for-statement."
"TODO: Refactor this to use a template. (Should be cleaner code.)"
^code.
generateJavaMethodDeclarationForStatement: aHumStatement
^code.
***22 lines of code ***
generateJavaScriptAngularReadMe
"Angular is a JavaScript user interface framework."
"Angular-Bootstrap simplifies the programming of layouts and rich interface effects."
generateSeasideForView: aHumFrame4View
"Implement the view frame via Seaside components.
"
"Generate Seaside code for each line in the view frame"
"TODO: SUSPECT THERE SHOULD BE A COMMA IN GENERATED CODE ABOVE."
^frameCode.
***22 lines of code ***
generateSeasideForViewMarkup: aHumMarkupLine
"Generate Seaside code to implement a view mark-up line."
"Parse into tokens"
"Generate for heading"
"Generate input fields."
^lineCode.
generateSeasideHeadingFor: source
"Generate Seaside heading code for the given heading line."
^outlineCode.
***28 lines of code ***
generateSeasideWidgetForField: fieldName
"This is the default to cover when we fall through the cases."
"Does widget contain a colon. If not, we have a simple attribute."
"TODO: REFACTOR above so that it is more sensitive to the attribute`s data-type.
"
"TODO: Hum panes need to be enclosed in table <td> or perhaps <div>
"
^ commentCode, String cr, widgetCode.
***76 lines of code ***
generateSeasideWidgetsForSource: aSourceString
"Generate Seaside calls for the widgets found in this mark-up line."
"*** CALLER MUST REPLACE ALL [] WITH {} BECAUSE WE GENERATE [] IN SEASIDE CODE. ***"
"Match button."
"Get all the buttons before we go on."
"Match check-box"
"Get all the check-boxes before we go on."
"Match other widgets."
"Name followed by space and digit means multi-line text box"
"TODO: If the attribute-name is plural, render as a table."
"TODO: Special handling for other types: category, date-time, measure."
"Match radio-button -- TODO: THIS RADIO BUTTON STRATEGY WILL FAIL."
"Call myself recursively"
"TODO: Need <group> tags."
^wip.
***68 lines of code ***
generateSmalltalk
"This is crude version.
"
^ code.
generateSmalltalkActionFor: aHumFrame4Action
"Translate frame to Smalltalk using the nouns given in the ontology."
"Translate the lines. Adding block ends when indent is reduced."
^ selectorCode, String cr, frameCode .
***22 lines of code ***
generateSmalltalkForConditional: aHumStatement
^code.
generateSmalltalkForFrame: aHumFrame
"Translate frame to Smalltalk using the nouns given in the ontology."
^frameCode.
generateSmalltalkForFrameLine: anInstructionLine
"space := Character space asString."
^instructionCode.
generateSmalltalkForStatement: aHumStatement
"TODO -- This will fail if there is a comment appended to the statement."
^code ].
^code
generateSmalltalkIfFor: aHumStatement
"Translate a Hum if-statement into a Smalltalk ( ) ifTrue: [] expression."
"TODO: Refactor this to use a template. (Should be cleaner code.)"
"TODO: Refactor to make the operator an argument."
^code := smalltalkIf valueWithArguments: { entity1. attribute2. entity3. attribute4. '>'.}
^code := smalltalkIf valueWithArguments: { entity1. attribute2. entity3. attribute4. '>'.}
^code := smalltalkIf valueWithArguments: { entity1. attribute2. entity3. attribute4. '<'.}
^code := smalltalkIf valueWithArguments: { entity1. attribute2. entity3. attribute4. '<'.}
^code := smalltalkIf valueWithArguments: { entity1. attribute2. entity3. attribute4. '='.}
^code := smalltalkIf valueWithArguments: { entity1. attribute2. entity3. attribute4. '='.}
^code.
***41 lines of code ***
generateSmalltalkIterationFor: aHumStatement
"TODO: Refactor this to use a template. (Should be cleaner code.)"
^code.
generateSmalltalkOnFile: aFileName
"Open file and produce File-Out / File-In format."
"Following is template for file-out / file-in format."
"
""@@MethodComment""
"
"This is crude version.
"
***37 lines of code ***
generateXamarinReadMe
"Xamarin runs on Windows, iOS, and Android devices. (client side)
"See XamarinHQ on YouTube for tutorials."
getMethodsForClass: aClassName
"Get the methods colletion (a Dictionary) for the given Class"
^methods.
html
^html ifNil: [html := ReadWriteStream on: ''.].
humParserError: aComplaint inCodeFragment: aCodeFragment
"TODO: In the future, we might not want this to stop execution."
"Generate HTML to embed critique near problem"
^complaintHTML.
methodsForClasses
^ methodsForClasses ifNil: [ methodsForClasses := Dictionary new ].
moveCodeGenerator
nounAsCamelCase: aNoun
"Generate camel-case string the the given noun."
"Note: First letter is also capitalized.
^camelCase.
nounsAsJava
"Emit java code that implements noun relations."
"Currently this emits all classes into a single code stream.
"
"Get a list of the entities."
"Define a private function that determines the correct supertype for a given noun."
"TODO: Fix this up so that multiple inheritance is correctly handled."
"Function returns the discovered supertype or the default supertype"
"Emit a class for each entity."
"Everything extends Entity class -- which provides toHTML(), toXML(), and persistence methods (TBD)."
"TODO: If the entity has a single superclass, override the extendsSuperType value with that superclass name."
"Get the entity's attributes."
"Emit instance variable declarations for each attribute. -- Default type is String."
"If noun is plural, make the type Bag<Entity>"
"Class ends with closing brace and a comment."
"Comment: This demonstrates that entities can be translated to java classes.
^code.
***56 lines of code ***
ontology
^ ontology ifNil: [ontology := HumOntology new.]
ontology: aHumOntology
prologues
^ prologues ifNil: [ prologues := Dictionary new ].
rolesAsJava
^code.
***25 lines of code ***
when: aSource matchesPattern: aPattern produce: aBlock
"Convertstrings to streams."
"Does source begin with markup?"
^remainder.
"The source must begin with a markup character."
"If the pattern does not match,
"If there is a match, build the argument list."
"Does the pattern match the source?
"If we matched, run the production block"
"Return the remainder of the source."
^remainder.
***66 lines of code ***
Hum-Language -- HumOntologyViewer
asHTML5
"Render the ontology as an HTML5 page.
"
^html
asHTML5withCritique
"Render the ontology as an HTML5 page.
"
^html
asHTML5withCritique: withCritique withBase: withBase
"Render the ontology as an HTML5 page.
"
"Creating a fresh calculator initializes XML indent."
"Build the HTML body"
"Render the ontology fiilename, if any, as an HTML5 heading element."
"Delegate rendering of the frames to the frames."
"The <hr/> seems to be needed. I cannot figure out how to do that with CSS."
"The <hr/> also seems to be needed. I cannot figure out how to do that in CSS either."
"TODO: Add plan-tree rendering. Render plan-tree for each goal that is invoked in a vignette."
"See: renderPlanTreeForGoal: aGoal"
"TODO: Add noun-tree rendeing. Render a noun-tree for each entity."
"See: renderNounTreeForNoun: aNoun"
"TODO: Add role-dependency rendering. Render a dependency tree for each role."
"TODO: Add context-path rendering. Render the context path diagram starting with 'Start' context. "
^html.
***40 lines of code ***
asHTML5withCritiqueSkippingBaseOntology
"Render the ontology as an HTML5 page.
"
^html.
buildDiagramForNoun: aNoun onDiagram: aDiagram
"Add the noun`s relationships to that diagram."
buildNounTreeForNoun: aNoun indent: anIndentLevel
""
"Detect a cycle in the tree."
^nounTree.
css
"generate HTML Cascading Style Sheet (CSS) code segment"
"TODO: Consider using class='indentN' to control indent in action frames.
"
^html.
***49 lines of code ***
generateCategoryPullDownFor: aNoun
"Render category noun as a pull-down selection."
"Use global HumCalculator to generate XML "
^html.
generateHtmlTableFor: anEntity
"Generate a dummy table showing the attributes for this entity-name."
"If the entity has no attributes, generate a default table."
"Otherwise generate a normal table."
^html.
initialize
modeStack
"Stack to track list-type modes."
^ modeStack ifNil: [ modeStack := Stack new.]
ontology: aHumOntology
render: asSymbol onFileNamed: aNewFile
^string.
renderActionFrame: aHumFrame4Action
"Render action frame with indentation.
"Else: reduces indent for self."
"If, Else, for-each, all increase indent."
^html.
***28 lines of code ***
renderActionFrame: aHumFrame4Action withCritique: aBoolean
"Render source code.
"Else: reduces indent for self."
"If, Else, for-each, all increase indent."
^html.
***28 lines of code ***
renderActionLine: aHumFrameLine
"Tests indicate this is redundant."
^ calc xml: 'titleLine' with: [source].
renderAs: aSymbol
"FUTURE: Render as X -- Currently not needed."
"Call the HTML rendering code."
renderAsHTMLonFileNamed: aNewFile
"Render as HTML5 and echo on given file."
^html.
renderAsHTMLwithCritique: withCritique withBase: withBase onFileNamed: aNewFile
"Render as HTML5 and echo on given file."
^html.
renderAsHTMLwithCritiqueOnFileNamed: aNewFile
"Render as HTML5 and echo on given file."
^html.
renderCommentIn: aFrameLine
"Render comment (if any) as HTML"
^html.
renderConditionLine: aHumConditionLine
"Avoid empty statement element."
"Avoid empty comment element.
"Render the annotation."
"Assemble it without any line breaks."
"TODO: Add hyperlink to frame (if any) that has goal matching this precondition."
^html.
renderCritiqueForFrame: aHumFrame
"Return (HTML5) rendering of the frame`s critique"
^html.
renderDictionaryLine: aHumDictionaryLine
^ calc xml: 'DictionaryLine'
renderFrame: aHumFrame withCritique: withCritique
"Render (pretty print) source code.
^html.
renderFrame: aHumFrame withCritique: withCritique withBase: withBaseOntology
"Render (pretty print) source code.
"Abbreviate the frame if we are skipping base ontology frames."
"html := calc xml: 'commentLine' with: [ (aHumFrame titleLine), ' -- See base ontology.' ]. "
^html.
"Wrap the lines with a HumFrame tag."
"Note: <frame> has semantics in HTML, so we use <HumFrame> tag instead."
"Return"
^'<hr/>',String cr,html.
***30 lines of code ***
renderFrameLine: frameLine
"Dispatch frameLine to rendering specialist."
"(class = HumCommentLine) ifTrue: [^ calc xml: 'commentLine' with: [ frameLine source ]]."
"Under some conditions we get an ordinary frame line in Action frames."
***22 lines of code ***
renderFrameLinesIn: aHumFrame
"Iterate throught the frame lines"
"View frames are rendered as HTML forms with widgets."
"Plan frames are rendered with Precondition and Action sections"
"Action frames are rendered with Role: and Action: labels."
"Other frame types are just pretty-printed?"
^html.
renderInstruction: aHumStatement
"Pretty-print statement as HTML"
^self renderStatement: aHumStatement triggerWords: triggerWords keywords: keywords.
renderInstructionLine: aHumInstructionLine
"Pretty-print using HTML5 tags and CSS."
"Avoid an empty role element.
"Avoid empty statement element."
"Avoid empty comment element.
"Render the annotation."
"Assemble it without any line breaks."
^html.
***26 lines of code ***
renderMarkupAsHTML5: markupSource
"Render the given mark-up text as HTML headings, lists, emphasis."
"TODO: REFACTOR this with call to HumOntologyTranslator."
"Maintain spacing."
"Is this markup line a heading?"
"If this is a heading, render the whole line as a heading. "
"Call self recursively to catch any additional emphasis (e.g. italics)"
"Is this markup line a bullet/numbered list item."
"TODO: Figure out how to emit '</ul>' and '</ol>.' -- Might need MODES. (heavens)"
^html.
"None of the above"
"Delegate emphasis"
^html.
***61 lines of code ***
renderMarkupEmphasisAsHTML5: aString
"Render bold, italic, underscore emphasis."
"REFACTOR: THIS FUNCTIONALITY BELONGS IN HumOntologyTranslator."
"Initialize work-in-progress."
"Cannot use #match: for asterisk case. So we use this trick:"
^wip.
***33 lines of code ***
renderNounTreeForNoun: aNoun
"Render a noun-tree rooted at the given noun (entity)."
^ string.
***28 lines of code ***
renderNounTreeForNounAsHTML: aNoun
"Render a noun-tree rooted at the given noun (entity)."
^html
renderPlanActionsIn: aHumFrame4Plan
"render precondition lines"
"html := html, '<br/>', ( self renderStatement: actionLine ), cr."
^ html
renderPlanFrame: aHumFrame4Plan
"Render source code.
^html.
renderPlanPreconditionsIn: aHumFrame4Plan
"render precondition lines"
"Always include this subheading."
^ html
renderPlanTreeForGoal: aGoal
"Render HTML for a previous created planTree (generated by buildPlanTreeForGoal: )"
"NOTE: The goals that are most relevant are those found in dialog vignettes."
"See: HumOntologyTests>>test540GetPlanTree
"
^ string.
***26 lines of code ***
renderStatement: aHumStatement keywords: keywords
"Assign a tag that the CSS can then style."
"Just another token with no particular type."
^html
renderStatement: aHumStatement triggerWords: triggerWords keywords: keywords
"Assign a tag that the CSS can then style."
"Just another token with no particular type."
^html
renderView: aHumViewFrame
"Views are rendered as HTML forms -- which is different from other frames."
"Markup lines will control line-breaks without my help."
"Future: View might have instruction-lines for tables."
"Block returns "
^html.
***21 lines of code ***
renderWidgetsInMarkup: aSourceString
"Return HTML5 equivalent of the widgets found in this mark-up line."
"Match button."
"Get all the buttons before we go on."
"Match check-box"
"Get all the check-boxes before we go on."
"Match other widgets."
"Name followed by space and digit means multi-line text box"
"TODO: If the attribute-name is plural, render as a table."
"TODO: Special handling for other types: category, date-time, measure."
"Match radio-button"
"TODO: Need <group> tags. HOW ARE WE GOING TO DO THAT?"
"If no widgets were found in this pass: Return; Otherwise: Iterate."
***68 lines of code ***
showPlanTree: aPlanTree
"Display a previous created planTree (generated by buildPlanTreeForGoal: )"
"See: HumOntologyTests>>test540GetPlanTree
"
"TODO: What does this produce? It looks like a simple rendering with no indentation."
^ string.
showPlanTreeForGoal: aGoal
"Display a previous created planTree (generated by buildPlanTreeForGoal: )"
"See: HumOntologyTests>>test540GetPlanTree
"
^ string.
***24 lines of code ***
Hum-Language -- HumOntology
actionsOf: aRole
"The actions of a role define its public interface. (API).
"
^self projectValuesOf: (self roleActions) from: (aRole capitalized).
addEntity: anEntity attribute: anAttribute
"Define these nouns and their relationship."
"Add entity-attribute relationship."
addEntity: anEntity attributes: anAttributeCollection
"Define these nouns and their relationship."
addNoun: aNoun
"Remember noun."
^self.
"Watch for parsing bug -- NOTE: category nouns are not strings."
"Check if noun has an implied supertype."
addNoun: aSubType isA: aSuperType
"Add these nouns and add is-A relation."
"Add these nouns in case they are not already added."
"Add inverse relation -- Note: subtypes is also a Set."
addNoun: aNoun isDerivedFrom: anotherNoun
addNoun: aSynonym isSynonymFor: aStandardNoun
"Add these nouns and add is-A relation."
"Add these nouns in case they are not already added."
"Add inverse relation -- Note: subtypes is also a Set."
addNoun: aNounString reference: aFrameLine
"Remember where nouns are referenced."
addNouns: anArrayOfNouns
addPlanFrame: aPlanFrame ForGoal: aGoalString
"Store frame as a plan frame - index as needed."
addRole: aRole
addViewFrame: aHumFrame4View
addVignette: aFrame4Vignette toContext: aContext
"Add to store"
"frame defines context"
allAttributesOfEntity: anEntity
"Get the attributes, the attributes of the attributes, and the attributes of the supertypes."
"Get the immediate properties of this entity."
"Entity properties include attributes and supertypes."
"For each local property: Look up attributes and add them to the result set."
"RECURSIVE CALL !!!"
"Detect cycles in the tree."
^allAttributes
***32 lines of code ***
allSubtypesOf: aSuperType
"Get the subtypes (if any) of this noun and the subtypes of the subtypes all the way down"
"RECURSION: Get the subtypes for each of those subtypes."
"Merge the sets"
"Detect cycles in the tree."
"Return the merged set of all subtypes."
^allSubtypes.
allSupertypesOf: aSubType
"Get the Supertypes (if any) of this noun and the Supertypes of the Supertypes all the way down"
"RECURSION: Get the Supertypes for each of those Supertypes."
"Merge the sets"
"Detect cycles in the tree."
"Return the merged set of all Supertypes."
^allSupertypes.
appendInstruction: aHumInstruction toRole: aRole action: anAction
"Append the given instruction to the action's sequence of instructions."
"Get the sequence of instructions belonging to this role action."
"Append the given instruction to the sequence."
"Assure that the data store is updated."
appendRole: aRole action: actionStatement
"Add role and action statement."
"Assure role is in set."
"Assure statement is in set."
asString
^s
attributeChain
^attributeChain ifNil: [ attributeChain := Stack new.]
attributeChainPop: anAttribute
attributeChainPush: anAttribute
buildPlanTreeForGoal: aGoal indent: anIndentLevel
"Build a list of associations: ( goalStatement -> { anIndentLevel. precondition statement.} )"
"Stop building the plan subtree if the root frame is not defined."
"Detect a cycle in the tree."
^planTree.
categoriesOf: anAttributeName
^categories := (self nounCategories) at: anAttributeName ifAbsent: [Set new].
categoriesOf: anAttributeName include: anArrayOfCategoryNames
"Add this noun in case it is not already added;"
"and make it a kind of category"
checkPlanTreeForGoal: aGoal
"Check for problems that would prevent the plan from working."
"Safety check -- >>buildPlanTreeForGoal: . . . will stop execution if there is a cycle in the plan-tree."
^ planTreeProblems ].
" Look for preconditions that have no corresponding plan frame in the ontology."
^planTreeProblems.
***24 lines of code ***
cleanKey: aString
"Assure that the string will be a clean key -- convert to lower-case, trim blanks."
^camelCase.
codeGenerator
"Return a translator."
^translator
"Precondition: Assure we are compiled."
"TODO: This 'Assure we are compiled.' strategy will fail
"Post condition: translator is set."
collectPlanFramesForGoal: aGoalStatement
"| goalStatement planTree subTree rootFrame |
^planTree."
"First check to make sure the plan frames are complete."
"Collect the plan frames."
^frameCollection.
***30 lines of code ***
compileAllFrames
"Compile the dictionary frames first, then the others."
"Return any problems found."
"Reset the frame index"
"Compile the dictionary frames first."
"Compile the remaining frames."
^problems.
***25 lines of code ***
contextVignettes
"This list holds the (1:M) relation (context -> vignette)."
"Vignettes are evaluated in the order seen."
"TODO: Decide if we need a priority attribute on a vignette to enable re-ordering."
^contextVignettes.
contexts
^ contexts ifNil: [ contexts := Set new. ]
critiqueRole: aRole action: anAction
"Critique the instructions for this role action."
"Return the critique as a sequence of strings."
"The action should contain at least one noun."
"There should be at least one instruction for the action statement."
"Nouns in the instructions should find antecedants in the action statement."
^critique.
***26 lines of code ***
debug
"Am I in debug mode?"
^ debug ifNil: [debug := false].
entityAttributes
"This instance variable is a map, a set of associations ( anEntity -> anAttribute )"
^entityAttributes ifNil: [ entityAttributes := Set new.].
fetchFrameByIdentifier: aPrimaryKey
"Fetch the frame with this identifier."
^frame.
fetchFrameByName: aString
"self assert: (aString endsWith: '.')."
^frame.
file
^ fromFile ifNil: [ fromFile := 'HumOntologyFile.ontology' ].
file: aString
findBestMatchingVignetteForInput: aString inContextStack: aStack
"Search the vignette frames for the one whose pattern is the best match
"We want the best match with a score better than zero."
"See if we have any vignettes that match that context."
"Get the bestMatch from that set."
^ bestMatch.
***28 lines of code ***
frameRelations
"The cross index collection tracks relationships between frames."
"Entries have the form: { frameA. #symbol. frameB. }
"
^ frameRelations ifNil: [ frameRelations := Set new. ].
frameRelationsWhere: aBlock
"Return frame relations where aBlock evaluates as true"
^selectedRelations.
frames
^ frames ifNil: [ frames := Set new. ].
framesByIdentifier
"Each frame is given a unique identifier.
^ framesByIdentifier ifNil: [ framesByIdentifier := Dictionary new. ].
framesByName
"Enable access to frames by their name (title line string)."
^ framesByName ifNil: [ framesByName := Dictionary new ].
fromFile
"The file name serves as a natural identifier. "
^ fromFile ifNil: [ ^ '(untitled)' ].
getEntityAttributePhraseFromStatement: aHumStatement
"Return collection of 'entity attribute' pairs when statement contains possessive nouns."
"TODO: Perhaps we should put '`s' in the pair. Leave a clue, other than the space, for other processes."
^pairs.
getFrameForRole: aRole action: anAction
"Get the frame that matches given role and action."
"TODO: Kludge some polymorphism.
^frame.
"If no frame is found/generated (will happen for a new role), return an empty frame."
^frame.
***30 lines of code ***
getFramesThatDefineContext: aContextName
"Get the vignette frames that define the given context."
^resultSet.
getFramesThatInvokeAction: anActionString
"Lookup the frames where action is invoked."
^ resultSet.
getFramesThatInvokeContext: aContextName
"Get frames with 'Push context <aContextName>.' instructions."
^resultSet.
getFramesThatInvokePrecondition: aStatementString
"Lookup the frames where precondition is invoked."
^ resultSet.
getFramesThatInvokeView: aViewName
"A view may be invoked by another view or by a vignette."
"Compiler will scan views to index [pane: ...] pattern. "
"Compiler will scan vignettes to index instructions 'Show <viewname>.' and 'Ask <viewname>.'"
^resultSet.
getFramesWithRelation: aSymbol object: aName
"Get frames that are indexed with given relation and object."
^resultSet.
getPlanFrameForGoal: aGoalString
^ HumFrame4Plan ontology: self goal: (aGoalString asString).
^frame.
getRole: aRole action: aStringOrStatement
"Get the action if it already exists."
"TODO: Kludge some polymorphism.
"Assure that we are dealing with a HumStatment."
"If the role action set already contains the action statement,
"
"TODO: Refactor to handle polymorphism."
^nil ].
^actionStatement.
getViewFrame: nameString
"Get the view frame with the given name."
^frame.
hasNoVignetteMatchFor: aString
^ defaultVignette.
immediateAttributesOfEntity: anEntity
^ self projectValuesOf: (self entityAttributes) from: anEntity.
immediateSubtypesOf: aSuperType
"Get the subtypes (if any) of this noun."
^ self projectValuesOf: (self nounSubtypes) from: aSuperType.
immediateSupertypesOf: aNoun
"Get the immedate supertypes (if any) for this noun."
"Initialize the result set."
"for each map ( supertype -> subtype ):"
^supertypes.
indexFrame: aHumFrame relation: aSymbol object: aKeyString
"Add the given frame to the index"
indexRole: aRole action: actionStatement
"Index role and action statement."
"Assure role is in set."
"Assure statement is in set."
instructionsForRole: aRole action: anAction
^lines.
isActionDefined: anInstructionLine inRole: aRole
"Has the given statement been defined as an action for the given role?"
"TODO: Kludge some polymorphism.
"(result) ifFalse: [ self halt. ]."
^ result.
isActionDefinedV01: anInstructionLine
"See if we have a definition for the given action."
^ numberOfDefinitions > 0.
isAttribute: aNameString
"Does the string name an attribute? (An attribute has no attributes of its own.)"
"First: Does it name a noun?"
"An attribute has no attributes.
^result.
isCategory: aNameString
"Does the string name an attribute? (An attribute has no attributes of its own.)"
"First: Does it name a noun?"
^result.
isEntity: aNameString
"Does the string name an entity?"
"First: Does it name a noun?"
"An entity has one or more attributes."
^result.
isEntity: entityName attribute: attributeName
"Does this combination make sense? "
"Does the first noun name an entity?"
"Is the second noun an attribute of the first noun?"
^result.
isNoun: aNounString
"Is the given string a noun?"
"TODO: Refactor to deal with possessive case. e.g. 'user`s name'. "
^( self nouns ) include: singular.
isPluralNoun: aNoun
"Return true if the noun is plural."
^isSingular not.
isViewName: aString
"Does the string name a view frame?"
^result.
nounAsCamelCase: aString
^result.
nounCategories
"(self nounCategories) at: attribute put: setOfCategories."
^ nounCategories ifNil: [ nounCategories := Dictionary new ].
nounReferences
"(self nounReferences ) add: ( aNounString -> aFrameLine )."
^ nounReferences ifNil: [ nounReferences := Set new. ].
nounSubtypes
"This instance variable is a map, a set of associations ( aSuperType -> aSubType )."
"(self nounSubtypes) add: ( theSuperType -> theNoun)."
^ nounSubtypes ifNil: [ nounSubtypes := Set new.].
nounSynonyms
"(self nounSynonyms) add: ( theSynonym -> theNoun)."
^nounSynonyms ifNil: [ nounSynonyms := Set new ].
nouns
"This instance variable is the set of all nouns that have been defined so far."
^nouns ifNil: [ nouns := Set new.].
nounsInStatement: aHumStatement
"Return the (known) nouns found in the statement."
"Forgive a nil statement. (Sometimes an instruction line has no statement.)"
"Forgive a string instead of a statement."
"TODO: Detect entity-attribute noun-phrase. Example: recipe`s bake-time."
"Remove nouns in each pair from the prior set."
"TODO: Technical strategy for dealing with explicit constants in caller code."
"TODO: Detect quoted strings as nouns? -- (Caller side)"
"TODO: Detect measurements as nouns? -- (Caller side)"
"TODO: Detect names as nouns? -- (Caller side) "
^statementNouns.
***32 lines of code ***
parseFrameLine: frameLine keywords: keywords
"Parse the frameLine -- Return a list of token-type pairs: ( token -> tokenType ).
"Note: Preserve uppercase in tokens so that first word of a sentence is capitalized."
"QUESTION: Is the role-label part of the statement?
"Does the source have a comment?"
"Does the source have annotation?"
^ tokenTypePairs.
***46 lines of code ***
parseStatement: aHumStatement triggerWords: triggerWords keywords: keywords
"Parse the statement -- Return a list of token-type pairs: ( token -> tokenType ).
"TODO: Scan to detect and remove strings delimited by quote or double-quote."
"Note: Preserve uppercase in tokens so that first word of a sentence is capitalized."
"QUESTION: Is the role-label part of the statement?
"TODO: Detect measurement pattern: 'number unit-of-measure' "
^ tokenTypes.
***31 lines of code ***
planFrames
^planFrames
printOn: aStream
projectValuesOf: aSetOfAssociations from: aKey
"encapsulate a bit of recurring code"
^resultSet.
roleActions
"This instance variable is a map, a set of associations ( role -> actionStatement ) "
^roleActions ifNil: [ roleActions := Set new.]
roles
"This instance variable contains the set of all roles that have been defined so far."
^roles ifNil: [ roles := Set new.].
setAutomaticSupertypeForNoun: aNoun
"If a hyphenated nouns ends with the name of another noun,
"See if there is a hyphen in the noun."
"See if the last token is currently a noun."
"The last token is currently a noun, so make this noun a subtype."
singularFormOfNoun: aNoun
"If noun ends in 's' remove the 's'. Crude."
"Following is first approximation.
"Following cases end in 's'. "
^singular.
storeFrame: aFrame
"Store this frame in the ontology.
"
"If the frame does not have an ID (serial-number) give it one."
"The title of the frame can serve to index it but cannot be used to ID it
"Also enable caller to fetch a frame by its name."
"Also enable caller to fetch frames by role."
"Enable caller to fetch vignettes by context-name."
"Also enable caller to fetch frame collection without any keys."
***27 lines of code ***
title
^ title ifNil: [ title := (self fromFile), ' -- No title yet.'. ].
title: aString
view
^viewer ifNil: [ viewer := HumOntologyViewer ontology: self. ].
vignettesForContext: aRequestedContext
"DEBUG ('*activity*' match: aRequestedContext ) ifTrue: [ self halt. ]."
^vignettes.
xparseString: aStatementString keywords: keywords
"Coding experiment to see if I can tweak existing code to handle quoted strings."
"Parse the statement string -- Return a list of token-type pairs: ( token -> tokenType ).
"Note: Preserve uppercase in tokens so that first word of a sentence is capitalized."
"QUESTION: Is the role-label part of the statement?
"Collapse quoted string."
"TODO: Detect measurement pattern: 'number unit-of-measure' "
^ tokenTypes.
***34 lines of code ***
yesNoun: aSubtype isAKindOf: aSuperType
"Is the noun a subtype of the given supertype? Used when matching action statements."
"Check for special case:
"
"Normal case:"
^result.
yesRole: aRole hasAction: aSource
"Is the given action defined for the given role?"
"Convert String to Statement, if needed."
^(self actionsOf: (aRole capitalized ) ) anySatisfy: [ :statement |
Hum-Language -- HumParser2
alphanumeric: aString
"Match that part of the string that is alpha-numeric"
^result.
checkbox: aSource
"Does the current source start with a check box widget?"
checkbox: aSource produce: aProductionBlock
"Does the current source start with a check box widget?"
"A check box must contain a single letter.
digits: source
"Match leading part of source that is digits"
^result.
generateChoicesFor: anAttributeName inOntology: aHumOntology
"Generate HTML choice tags"
^html.
generatedCode
""
^code.
ignoreNext
^ignoreNext ifNil: [ ignoreNext := false. ].
ignoreNext: aBoolean
markupSyntax
"Experimental BNF syntax"
"x is the matched text -- see alphanum below"
"n is the size of the match -- see _prefix below"
^markup.
***38 lines of code ***
markupSyntaxWithOntology: anOntology
"Experimental BNF syntax"
"x is the matched text -- see alphanum below"
"n is the size of the match -- see _prefix below"
"TODO: FIGURE OUT HOW TO DO AN ORDERED (NUMBERED) LIST."
"Note the name='...' value must be HTML, CSS, jQuery and HumBlackboard compatible "
^markup.
***70 lines of code ***
markupSyntaxWithOntology: anOntology blackBoard: aBlackBoard
"Experimental BNF syntax"
"x is the matched text -- see alphanum below"
"n is the size of the match -- see _prefix below"
"TODO: FIGURE OUT HOW TO DO AN ORDERED (NUMBERED) LIST."
"humNoun := [:s | x := (self noun: s ). self halt. ]."
"Note the name='...' value must be HTML, CSS, jQuery and HumBlackboard compatible "
^markup.
***73 lines of code ***
match: source oneOf: anArrayOfSyntaxThings
^result.
match: source oneOf: anArrayOfSyntaxThings produce: productionBlock
"Does current source match array? If so, run the production."
^result.
match: source repeat: anArrayOfSyntaxThings
"Does current source match array?"
^result].
"Call myself recursively."
^result.
"If we fall through we've matched nothing"
^result.
***30 lines of code ***
match: source sequence: anArrayOfSyntaxThings
"Does current source match array?"
^result.
match: source sequence: anArrayOfSyntaxThings produce: productionBlock
"Does current source match array? If so, run the production."
^result.
match: aString with: syntaxThing
"Does aString match with syntaxThing?"
^result.
noun: source
"Match that part of the string that might name a Hum noun"
"A Hum noun must start with a letter."
"A Hum noun must be more than a single letter."
^result
^result.
ontology: aHumOntology blackBoard: aBlackBoard produceView: aViewName
"Produce the HTML for the given view frame."
"Set up an indepent parser so that we don't interfere with caller."
"Pass the view name through -- is also default entity-name."
^code := parser generatedCode .
***22 lines of code ***
ontology: aHumOntology isAttribute: aSource
"Does the current source, upto some delimiter, match an ontology attribute name?"
"An attribute name must be alphanumeric"
^result.
ontology: aHumOntology isCategory: aSource
"Does the current source, upto some delimiter, match an ontology category name?"
"A category name must be alphanumeric"
^result.
ontology: aHumOntology isEntity: aSource
"Does the current source, upto some delimiter, match an ontology entity name?"
"An entity name must be alphanumeric"
^result.
ontology: aHumOntology isViewName: aSource
"Does the current source, upto some delimiter, match an ontology view name?"
"a view name must be alphanumeric"
^result.
ontology: aHumOntology isViewName: aSource produce: productionBlock
"Does the current source, upto some delimiter, match an ontology view name?
"a view name must be alphanumeric"
^result.
ontology: aHumOntology produceView: aViewName
"Produce the HTML for the given view frame."
"Set up an indepent parser so that we don't interfere with caller."
^code := parser generatedCode .
pop: aSmallInteger
push: aString
^aString
pushIgnore: aString
^aString
radioButton: aSource produce: aProductionBlock
"Does the current source start with a radio button widget?"
"A radio button must contain a single letter.
spaces: source
"Match leading part of source that is digits"
^result.
stack
^stack ifNil: [ stack := OrderedCollection new.]
text: aString
"Return that part of string that contains no mark-up."
"Terminate on any character that indicates emphasis or widget."
^self push: result.
top
^item.
url: source
"Does current source match a URL pattern?"
"Note: Calling trimBoth above might accidentally clean up a bad URL."
^result.
Hum-Language -- HumStatement
= aStatement
^self halt.
asCamelCase
"Convert this statement to camelCase."
"Do not inlude articles in the camel case."
^code
asCamelCaseWithOntology: aHumOntology
"Convert this statement to camelCase."
"TODO: Deal with polymorphism by looking up the proper definition.
"
^code
asString
^ self source asString.
delegateToTranslator
errors
^errors ifNil: [ errors := Set new.].
hash
"This HACK (which may be a bad idea) makes HumStatement hash the same as a matching string.
"
^ ( source hash ).
isConditional
^false.
isSatisfied: aBoolean
matchesCandidateStatement: aCandidate inOntology: aHumOntology
"Does the candidate match me? (Candidate nouns might be subtypes of my nouns.)"
"Get tokens minus articles."
"TODO: Parse allowing for quoted strings."
"Is my noun a supertype of the argument`s noun?"
"TODO: A series of nouns (example: entity attribute attribute) matches a single noun. "
^ true.
***34 lines of code ***
matchesTemplateStatement: aStatementTemplate inOntology: aHumOntology
"Do I match the given template? (My nouns may be subtypes of template nouns)"
"First try a shortcut."
"Get tokens minus articles."
"TODO: Parse statements containing quoted strings."
"Is each template noun a supertype of my noun?"
"TODO: A series of nouns (example: entity attribute attribute) matches a single noun. "
^ true.
***30 lines of code ***
noun: aNoun value: aValueObject
"Noun values are set at run-time just prior to executing the statement.
"
***24 lines of code ***
nounAsCamelCase: aString
"Delegate to ontology class"
^ HumOntology nounAsCamelCase: aString.
nounValues
"Noun values are set at run-time.
"
^ nounValues ifNil: [ nounValues := Dictionary new.].
onMatch: aPatternString do: aBlockClosure
"When my source matches pattern, execute the block with matching arguments.
printOn: aStream
"Append to the argument, aStream, a sequence of characters that
"nextPutAll: (title first isVowel ifTrue: ['an '] ifFalse: ['a ']);"
role
^role ifNil: [ Error signal: 'role was not set in HumStatement']
role: aString
"What role is meant to execute this statement?
"
sameAs: aHumStatement
"Return true if receiver is semantically equivalent to (argument) aHumStatement."
"TODO: Allow variations in use of 'a' 'an' 'the'. "
"TODO: Allow a cascade of nouns. (example: entity attribute-entity attribute-entity attribute)"
source
^ source ifNil: [ source := '' ].
source: aSource
"Set and check the source string."
"Remember my source string."
"Reset errors."
"self stripLeader." "Leader is a UI artifact. Not really part of the source."
"Syntax check: A statement ends with a period or a colon."
"Last character was not a period or colon."
***27 lines of code ***
stripRole
"Source should not contain a role prefix in this context.
"Note: Preserve uppercase in tokens so that first word of a sentence is capitalized."
"role := tokens at: 1.
syntaxError: anErrorMessage
"Error signal: anErrorMessage."
tokens
"Return the tokens in the statement as an array of strings."
"WARNING: Hum has a quirk: Accent (`) is used as apostrophe.
^tokens.
translation
"How might the statement be translated into another programming language?"
^translation
translation: aString
"How might the statement be translated into another programming language?"
Hum-Language -- HumVignettePatternLine
checkSyntaxWithOntology: aHumOntology
"TODO: Look for [noun]. Is the noun defined in the ontology?"
^ OrderedCollection new.
Hum-Language -- HumVignetteResponseLine
checkSyntaxWithOntology: aHumOntology
"TODO: Look for [noun]. Is the noun defined in the ontology?"
^ OrderedCollection new.
Hum-RunTime
Hum-RunTime -- HumActor
blackboard
^ blackboard ifNil: [ blackboard := HumBlackBoard new. ].
blackboard: aHumBlackBoard
checkIn
"First, check-in with the messenger."
"TODO: REFACTOR THIS CALL. --- Why? Why? "
"Don't check-in with self."
"Coordinator is not dispatched by Dispatcher"
"Allow Dialog Agents to be dispatched for Push messages."
"We don't expect Scribes here.
"Send check-in message to my Dispatcher."
***35 lines of code ***
checkOut
"Tell the Dispather that this actor is no longer available for assignments."
"Don't check-in with self."
"Coordinator is not dispatched by Dispatcher"
"Send check-out message to my Dispatcher."
completedAction: anAction inRole: aRoleString onJob: aHumJobTicket
"Following is first-cut direct call.
"
"TODO: Refactor above - It is using the messengers back door and is only valid in test mode."
completedInstruction: aHumInstructionLine inRole: aRoleString onJob: aHumJobTicket
"Following is first-cut direct call.
"
"TODO: Refactor above - It is using the messengers back door and is only valid in test mode."
delegateAction: anAction toRole: aRole onJob: aJobTicket
"Delegate action to another role."
dispatcherID
^self configuration dispatcherID.
ontology
^self configuration ontology.
roles
^roles ifNil: [ roles := { self class name. }].
roles: anArray
runAction: anAction inRole: aRole onJob: aHumJobTicket
"Run the action frame named ..."
"TODO: Ontology has instruction sequence, but lacks frame lines."
"Tell Dispatcher that we completed action normally."
runInstruction: anInstruction inRole: aRole onJob: aJobTicket
"Execute, simulate, or log the given statement"
"If instruction role is not one of my roles, delegate the instruction."
"If statement has a translation (assume Smalltalk), run the translation."
"Charge to job ticket"
"Tell Dispatcher that we completed action normally."
^self.
"Append to log"
"Charge to job ticket"
^ self.
***36 lines of code ***
updateBlackBoardFromBlackBoard: aHumBlackBoard
"Update my blackboard with entries from callers blackboard."
"Delegate this to Blackboard. Note: Subtypes might want to override."
zrunInstruction: anInstruction inRole: aRole onJob: aJobTicket
"Execute, simulate, or log the given statement"
"If instruction role is not one of my roles, delegate the instruction."
"If statement has a translation (assume Smalltalk), run the translation."
"Charge to job ticket"
"Tell Dispatcher that we completed action normally."
^self.
"Append to log"
"Charge to job ticket"
^ self.
***32 lines of code ***
Hum-RunTime -- HumBase
entitiesOfType
^ entitiesOfType ifNil: [ entitiesOfType := Dictionary new ].
entitiesWithValue
"A dictionary of sets. The set of entities with the given { attribute value }."
^ entitiesWithValue ifNil: [ entitiesWithValue := Dictionary new].
entityAttributeValue
"A dictionary holding a temporal stack of {value event} for each {entity attribute}.
^ entityAttributeValue ifNil: [ entityAttributeValue := Dictionary new ].
entityID: anID entityType: aType attribute: anAttribute value: aValue event: anEvent
"Create a record of entity-attribute-value from event."
"Add entity to set of that type."
"ASSUMED: The entity does not change type over time."
"Add entity to index by value."
"TODO: entitiesWithValue is meant to be current value. We need to remove old entry, if any."
"Add record."
"( self entityAttributeValue ) at: { anID. anAttribute. } put: { aValue. anEvent. }."
eventWho: aWho what: aWhat where: aWhere why: aWhy
"when := yyyy*1e4+mo*1e2+day*1e2+hh*1e2+mm*1e2+ss*1e12+nn."
^eventID.
***21 lines of code ***
events
^ events ifNil: [ events := Dictionary new].
findEntitiesOfType: anEntityType
^setOfEntities.
findEntitiesWhereAttribute: anAttributeType satisfies: aBlockClosure
"Get collections of entities where current attribute value satisfies condition"
^setOfEntities.
getEntityID: anEntityID attribute: anAttributeType
"Get the current value for given entityID attributeType"
^result.
insert: anItem at: aKey into: aDictionaryOfSets
"Insert the item into a set at the given key."
"Add entity to set associated with that key."
push: anItem at: aKey onto: aDictionaryOfStacks
"Insert the item into a list at the given key."
"Add entity to list of that type."
remove: anEntityID at: aKey from: aDictionaryOfSets
"Remove the entityID from the set associated with the key."
Hum-RunTime -- HumBlackBoard
appendEntity: childEntityID toEntity: parentEntityID list: anAttributeName
"Append the given child entity to the named list attribute"
businessEvent
"What business event is in progress?"
^businessEvent ifNil: [Error signal: 'event not set']
businessEvent: aString
"What business event is in progress?"
"TODO: We need a stronger (W5) business-event representation."
"TODO: Create a Business Event class with W5 (who, what, when, where, why) attributes."
^businessEvent := aString
cleanAttribute: anAttributeNameString
^result.
cleanEntity: anEntityTypeString
"Assure that the type-name is properly-trimmed, lowercase string"
^result.
clearEntity: anEntityType
"Clear all data for the given entity-name / entity-type."
"REFACTOR/RETHINK: The BlackBoard seems to be built for single instances of an entity-type."
"TODO: Think about the interaction between business roles, views, and persistence."
"Hum`s general rule is 'Persist everthing, then add purge rules.'"
"REFACTOR/RETHINK: The WorldBase should check for valid ID (defensive code). "
"Why? - Because an long-running dialog may have already created an entity of this type,
"(cleanName = 'topic') ifTrue: [self halt.]."
"At this point, quadsToBe has no data associated with the entity-type."
***29 lines of code ***
entityIdentifiers
"What identifier is associated with a entity type noun (entity name)?"
^ entityIdentifiers ifNil: [entityIdentifiers := Dictionary new].
generateNewIdentifierForEntityName: anEntityName
"Create a unique identifier for an instance of the given entity-name noun."
^id.
getEntityID: entityID attribute: anAttributeName
" Get requested value (if any) from the blackboard instance "
"ToDo: If I don't have it, maybe WorldBase does. "
"TODO: If the entity-attribute-value is updated in the worldbase, are the Blackboards notified? If so, how?"
^ value.
getEntityName: anEntityName attribute: anAttributeName
"Get the entityID for that entity-name and fetch the requested attribute."
^value.
identifierForEntityName: anEntityName
"Do I already have an entity of that name?
^id.
makeEntityOfType: anEntityType
"Add a new entity ID for the given entity type. (entity name)."
"Generally invoked via 'New entityType.' in a dialog vignette. "
"NOTE: If dialog blackboard already contains an entity of this type, it is no longer accessable."
quads
"a dictionary of { aValue. tau. } keyed by ( entityID -> attribute )"
^ quads ifNil: [ quads := Dictionary new. ].
setEntityID: entityID attribute: anAttributeName toValue: aValue
"Store given value in the blackboard with a time-stamp.
"Put value of entity attribute and the timestamp."
"Update the world base also."
"NOTE: Mutation in the world-base is treated via versioning."
"TODO: Blackboard detects mutations ? -- And then what?"
"TODO: Code critic flags mutation as Error?"
"COMMENT: Mutation in a business-entity is mainly a danger when a natural-key is mutated."
***24 lines of code ***
setEntityName: anEntityName attribute: anAttributeName toValue: aValue
"for now -- same as:"
"Do I already have an entity of that name?
^self.
***21 lines of code ***
updateBlackBoardFromBlackBoard: aHumBlackBoard
"Update myself from entries in the other blackboard."
"Assume that caller is not sharing this blackboard."
"Interpret caller quads"
"Parse dictionary key - it is a map of the form: (entitID -> attributeType)"
"Parse dictionary value - It is a tuple of the form: { value. tau. }"
"tau := value at: 2."
"Update myself -- Note: I will generate my own tau."
***25 lines of code ***
worldbase
^ worldbase ifNil: [Error signal: 'Blackboard configured without a world base.']
worldbase: aHumWorldBase
Hum-RunTime -- HumBookkeeper
chargesBy: attribute
"Produce dictionary of sums for given subdivision type."
^sums.
***22 lines of code ***
chargesByAction
"Produce dictionary of sums keyed by action."
^sums.
chargesByActor
"Produce dictionary of sums keyed by actor."
^sums.
chargesByJob
"Produce dictionary of sums keyed by job."
^sums.
chargesByMetric
"Produce dictionary of sums keyed by unit of measure. "
^sums.
***21 lines of code ***
chargesByRole
"Produce dictionary of sums keyed by role-name.."
^sums.
jobTickets
^ jobTickets ifNil: [ jobTickets := OrderedCollection new. ].
recordJobTicket: aHumJobTicket
"Add the given job ticket to my collection of job tickets."
Hum-RunTime -- HumBusinessEvent
what: aString
"What is the cause/actor doing in the business event?"
when: aTimeStamp
"When (at what date-time) is business event happening?"
where: aString
"Where (at what location/context) is business event happening?"
who: aString
"Who is the cause/actor in the business event"
who: aWho what: aWhat when: aTimeStamp where: aWhere why: aJobTicket
"Set the business event attributes."
why: aJobTicket
"Why (job-ticket) is business event happening?"
Hum-RunTime -- HumCalculator
cases
"Initialize case cascade.
"
doTokensIn: input at: xInput matchPatternTokensIn: pattern at: xPattern
^result.
exdent
"Remove a tab from the global indent string."
fillTemplate: template fromDictionary: dictionary
"Create a String based on the given template and parameters."
"Get and remove the name of the parameter"
"Insert the value of the parameter"
^result.
given: sourceString extractAfter: stringA
"Return the substring in the sourceString between the two."
^result.
given: input extractAfterSecond: marker
"Parse cases like matching quotes or markup emphasis."
^result.
given: sourceString extractBetween: stringA and: stringB
"Return the substring in the sourceString between the two."
^result.
given: sourceString extractUpto: stringA
"Return the substring in the sourceString between the two."
^result.
given: inputString onMatch: aPatternString do: aBlockClosure
"When the inputString matches pattern, execute the block with matching arguments.
given: input replaceAll: old with: new
^result.
given: s topic: aTopic doOnce: aBlock
"Use this to produce subheadings."
indent
"Append a tab to the global indent string."
indentLevel: n
"Reset the indent level. Produce indent string (tabs)."
initialize
justTheWordsIn: aString
^self class justTheWordsIn: aString.
on: aValue do: aBlockClosure
otherwise: thenBlock
"If a prior case was true, ignore this case.
"otherwise"
^self.
parse: aString
"Parse into { token. type. start. stop. }"
^sequence.
priorCaseIsTrue
^ priorCaseIsTrue ifNil: [priorCaseIsTrue := false ].
scoreCandidate: candidateString againstPattern: patternString
"Return a score indicating the number of tokens that match."
"Parse."
^commonTokens size.
string: stringA isLike: stringB
"Compare ignoring differences in whitespace."
^self class string: stringA isLike: stringB.
string: aString isLike: aString2 ignore: aString3
^self class string: aString isLike: aString2 ignore: aString3.
switch: aCharacter
testValue: anObject
when: whenBlock then: thenBlock
"If the whenBlock evaluated to true, execute the thenBlock."
"If a prior case was true, ignore this case."
"If the when block is true"
^self.
xml: aTagString dictionary: aDictionaryOrList
"Create a stand-alone tag (ending with '/>') with the given attribute values."
"Don not mess with indent here. Caller should handle."
^xml.
xml: aTagString dictionary: aDictionary with: aBlockClosure
"Generate the front tag and the end tag with block to produce the middle"
"Restore prior indent"
^xml.
xml: tagString list: anArray
"Iterate: Enclose each item with given tagString"
^result.
xml: aTag with: aBlock
"Fix up the indent after we get this working."
"Restore prior indent."
^xml.
xmlOpen: aTagString dictionary: aDictionary
"Create an opening tag ( NOT ending with '/>' ) with the given attribute values."
^xml.
Hum-RunTime -- HumConfiguration
bookkeeperID
^ bookkeeperID
bookkeeperID: anObject
clock
"What object is providing time-keeping?"
^ clock ifNil: [clock := HTime "class singleton"].
clock: anObjectThatImplementsNow
"Clock must be an object that imlements >>now as a number of seconds (an Integer)."
configuration: aHumConfiguration
"Copy configuration."
debug
"Am I in debug mode?"
^ debug ifNil: [debug := false].
dispatcherID
^ dispatcherID ifNil: [ Error signal: 'A configuration must have a Dispatcher.' ].
dispatcherID: anObject
getWorldBase
"Get this configuration`s worldbase instance."
^worldbaseInstance.
isTest
"Are we running in TEST mode?"
^isTest ifNil: [ isTest := true. ].
isTest: aBoolean
"Are we running in TEST mode?"
messenger
^ messengerProxy
messenger: aHumMessenger
"Set the messenger -- Use to configure mocks when needed."
messengerID
^ messengerID
messengerID: aString
messengerID: idMessenger dispatcherID: idDispatcher bookkeeperID: idBookkeeper worldbaseID: idWorldbase
"WARNING: I am not sure this is a good idea."
now
"What time is it in configured world (may be simulation)?"
^ clock now.
ontology
^ ontology ifNil: [ Error signal: 'ontology is missing from configuration'].
"TODO: Perhaps we should return HumOntology baseOntology instead."
ontology: aHumOntology
openWorldBase
"Create world base instance and register with messenger."
^worldbaseInstance.
worldbaseID
^ worldbaseID
worldbaseID: anObject
Hum-RunTime -- HumCoordinator
conditionIsSatisfied: precondition
"Note that condition is satisfied.
"
context: aHumActor
coordinatorID: anID uri: aURI goal: aGoalStatementString dialog: aHumDialogAgent configuration: aHumConfiguration
^self.
dialogAgent: aHumDialogAgent
"Concept: The dialog agent provides noun values
getActionSequence
"Parse the job ticket to show the sequence of actions."
^listOfActions.
goal: aStatement
^self.
goalStatement
"Translate goal string to goal statement"
"TODO: THERE IS SOMETHING WRONG HERE."
^ statement.
isPlanFrameRunnable: aHumFrame4Plan
"Determine if the given plan frame is runnable.
"
^true
jobTicket
^ jobTicket ifNil: [ jobTicket := HumJobTicket title: goal ].
planIsRunnable
"TODO: ADD NEEDED CHECKS TO THIS STUB."

^true.
remainingConditions
^ remainingConditions ifNil: [ remainingConditions := Set new.] .
runAction: anInstructionLine
"Run the given action statement."
"TODO: Track work-in-progress so that run-time instrumentation can view."
runPlan
"Run my plan.
"
runPlanFrameForCondition: aGoalString
"This visits the subtree and runs each frame that is ready to run.
"
"If the condition is already satisfied (not in remainingConditions set), we can skip and return immediately."
"Get the root of this subtree."
"REFACTOR: The rootFrame does not know if it is runnable. But the Coordinator knows."
"Run actions"
"Declare goal satisfied"
^true. "Indicates something was runnable. See check below."
"Call recursively on preconditions."
"Check post condition
"Fall through to here when goal frame is not runnable and we ran preconditions.
"In this context,
^result.
***48 lines of code ***
runPlanSetup
"Setup to run a plan:
"
"Populate the remaining conditions collection"
***21 lines of code ***
Hum-RunTime -- HumDecimal
fromString: aString
"Count the digits in the string to estimate accuracy."
nDecimal
"How many decimal places should we display."
^nDecimal ifNil: [ 0 ].
nDecimal: anInteger
"How many decimal places should we display."
printOn: aStream
Hum-RunTime -- HumDialogAgent
askView: aViewName
"Delegate display to my scribe."
buildDialogAgentOntology
"Return ontology with Dialog Agent actions defined and executable in Smalltalk."
^ontology.
clearEntity: entityType
"Clear prior data in my blackboard for the given entity type."
"WARNING: Assumes dialogs vignettes only address one instance of an entity at a time."
"TODO: I think there is a UX problem here. This behavior may confuse users."
"PROBLE: It makes no sense to clear a real-world entity.
client: aString
clientSays: aString
"Match user utterance to vignette patterns in the ontology
"
"We need a context stack to define the best match."
"Delegate the search to the ontology."
"TODO: Now that I've got a vignette (or not), what do I do with it?"
"TODO: We need a stronger (W5: who, what, when, where, why) business-event representation."
"who = clientID, what = says: ___, when = date-stamp, where = dialog, why = vignette"
"*** Return vignette for DEBUG? *** "
"TODO: THINK -- Should test cases examine my step log instead?"
^ bestMatch.
***22 lines of code ***
contextStack
^ contextStack ifNil: [ contextStack := Stack new. self pushContext: 'Start.'. contextStack ].
dialogAgentOntology
"Return ontology with Dialog Agent actions defined and executable in Smalltalk."
^ dialogAgentOntology ifNil: [dialogAgentOntology := self buildDialogAgentOntology].
dialogOntologySourceStream
"Return a stream of frames defining Dialog Agent actions."
^stream.
***24 lines of code ***
extractFieldValuesFromUserInput: inputString pattern: patternString
"Extract values from user input and post to my blackboard.
"
***44 lines of code ***
fillInSlotIn: aMarkupString
" Fill-in first [entity attribute] dialog-response-slot with data from blackboard.
"
"Break the field name into entityName and attributeType."
"Insert field-value into markup string."
^result.
interpretVignette: aHumFrame4Vignette withInput: aUserInput
"Send response lines. Execute response instructions."
"Extract any values in user input and update blackboard.
"Interpret the response lines (fill in any value slots as needed)."
"Interpret markup."
"If there are no instructions in the response, we are done."
"TODO: What is the rationale for job-ticket in this context?"
"Interpret any instructions found in the response."
***51 lines of code ***
newEntity: anEntityType
"Create a new entity to be associated with the given entity-type/entity-name."
"TODO: If the blackboard already contains and entity of that type,
"TODO: Think about the interaction between business process roles, entity-type, and views."
"Advice: New business entities are created in the blackboard when a dialog requires them.
"
pushContext: aString
runAction: anAction inRole: aRole onJob: aHumJobTicket
"Dialog Agent knows: 'Ask view', 'Show view', 'Push context ...'"
"TODO: Give some thought to the interaction of business process roles and views."
***28 lines of code ***
sayToClient: aHumMarkupLine
"Say something to the client.
"Delegate actual UI to my Scribe."
scribeProxy
"Return an instance that understands #systemSays:
"
^scribeProxy
showView: aViewName
"Delegate display to my scribe."
Hum-RunTime -- HumDispatcher
actor: anActor completedAction: aHumStatement
"Dispatcher is informed that the actor completed the assigned action.
"
"Send charges to bookkeeper."
"For now, just call direct.
"
"TODO: Refactor this. It is by-passing the messenger."
assignAction: aHumInstructionLine toRole: aByteString forJob: aHumJobTicket
assignRole: roleString action: actionInstruction
"Assign the given action to an actor advertising the given role."
"Find an actor that knows the role."
"Filter potential actors to include only available actors."
"Assign an actor at random."
"Send the action to the actor."
"Simulating asynch:
***31 lines of code ***
availableActors
^ availableActors ifNil: [ availableActors := Set new. ].
busyActors
^ busyActors ifNil: [ busyActors := Set new ].
checkInActor: actorID at: aURI withRoles: actorKnowsRoles
"The Dispatcher should delegate finding the URI to messenger."
"For each actor role:
checkOutActor: anActorID at: anActorURI
"Actor is no longer available for assignments."
"Remove the actor from role->actor map."
"Remove the actor from the available actor list."
"Assume actor will not check-out with work in progress.
"
^self.
roleActor
"Return the role->actor map set."
^ roleActor ifNil: [ roleActor := Set new. ].
runAction: anAction inRole: aRole onJob: aHumJobTicket
"Dispatch the action to an actor in the given role."
^self.
"Otherwise: Assign action to an actor that has registered previously with that role."
sendMessage: aMessageObject to: recipientID.
"TODO: HumActor does not need to know that delegating a statement is a message send.
"
"self checkID: recipientID."
Hum-RunTime -- HumEntity
asString
^self title.
debug
"Am I in debug mode?"
^ debug ifNil: [debug := false].
id
"Return a unique identifier."
^ id ifNil: [ Error signal: 'Entity ID should be set by Blackboard or DialogAgent.'.
id: aString
"Set the entity`s identifier."
printOn: aStream
title
"a display string describing this entity"
^ title ifNil: [title := 'Unknown Entity'].
title: aString
"a display string describing this entity"
Hum-RunTime -- HumFuzzy
* aHumFuzzy
^result.
+ aHumFuzzy
^result.
- aHumFuzzy
^result.
/ aHumFuzzy
^result.
asCrudeMorph
"verticle grid"
"horizontal grid"
"You can delete morph by double-clicking it."
***32 lines of code ***
asCrudeMorph2
"Normalize v range to [0,100]."
"Flip Y. Screen coordinates have Y pointing down."
"Paint grid lines"
"vertical grid"
"horizontal grid"
"You can delete morph by double-clicking it."
***40 lines of code ***
asCrudeMorphInRectangle: aRectangle
"Display a plot in a Morph with the origin and extent indicated by the given Rectangle."
"Pixels per normalized value unit."
"Normalize v range to [0,100]."
"Flip Y. Screen coordinates have Y pointing down."
"Paint grid lines"
"vertical grid"
"horizontal grid"
"You can delete morph by double-clicking it."
***44 lines of code ***
atP: aFloat
"Return the appropriate value from the distribution.
"Check that aFloat is between zero and one"
"Look up value or interpolate to get a result."
^ result.
correctInterceptInDistribution: aDistribution
"-- Use slope-intercept to get a better estimate of the S-curve value at probability 0.
"
***25 lines of code ***
distribution: aDictionary
"Distribution is an S-curve that maps probability to value.
"
distributionDo: pvBlock
"Vist the key->value (probability->value) entries in the distribution."
fromScaledDecimal: aScaledDecimal
"Set the distribution from the given string.
"
***22 lines of code ***
fromString: aString
"Set the distribution from the given string.
"
initialize
interpolate: aProbability
"Return the predicted value at aProbability using linear interpolation."
"Following depends on Dictionary semantics"
"Find the interval that brackets the requested point."
"Do simple linear interpolation."
"Check: for an S-Curve the slope is always positive."
"Check: the result must be between upper and lower function values"
"TODO: If we need more accuracy, use two quadratic splines.
"
^result.
***29 lines of code ***
mean
^result.
median
"find the point that represents the median"
"Distribution is list of f->p".
"Look for<EMAIL_ADDRESS>^medianPoint.
op: aSymbol with: aHumFuzzy
"Add two fuzzy distibutions using Monte Carlo sampling"
"Create a new distribution with points every 10%"
"Note: Assertion above occasionally fails due to accidental matches in set.
"self correctInterceptInDistribution: distributionC."
^fuzzyC.
***39 lines of code ***
sampleSize: anInteger
"Reset the sample size used in Monte Carlo sampling of input distributions.
"
sampleSize: aSampleSize resultDivisions: aDivisionCount
"Reset the sample size used in Monte Carlo sampling of input distributions.
"
"The Monte Carlo will randomly sample the inputs this many times."
"The resulting S-curve will have N+1 points selected from sampleSize points."
sampleWithBlock: aBlock
"Operate on fuzzy distibution using Monte Carlo sampling"
Hum-RunTime -- HumHttpRequest
atField: aKey put: aValue
"The Http Request form included this input name:value pair."
fields
^myFields ifNil: [myFields := Dictionary new.].
Hum-RunTime -- HumIdentifier
< aHumIdentifier
^ result.
<= aHumIdentifier
^ result.
asString
^(entityName asString),':',(bigNumber asString)].
^ (entityName asString),':',(bigNumber printStringHex).
entityName
"Return entity name -- force nil to string if needed."
^ entityName asString.
generateForEntityName: anEntityName inContext: aBusinessEvent
"Make self a unique identifier for given entity context."
"TODO: Think: Should the business context where the entity originates be embedded in the ID somehow ???"
"Singleton holds prior values."
"Post Conditions:"
"Set the singleton values."
***27 lines of code ***
initialize
"This UUID represents the run-time.
printOn: aStream
uuid: aUUID
Hum-RunTime -- HumJobTicket
appendCharge: aHumMeasure forAction: action byActor: anID inRole: aRoleName onJob: aJobID
"Use a dictionary to represent a charge."
"Append this charge to ticket`s charges."
***22 lines of code ***
charges
^charges ifNil: [ charges := OrderedCollection new.]
getActionSequence
"Parse the job ticket to show the sequence of actions."
^listOfActions.
printOn: aStream
Hum-RunTime -- HumMeasure
* multiplier
^result.
^result.
"Increment and net-out the dimensions."
^result.
***22 lines of code ***
+ operand
"The units of measure must be the same."
"Make a deep copy to get fresh dimensions and quantity."
^result.
- operand
^result.
/ aDivisor
"If the dimensions match, the result is a ratio. But we keep it as a HumMeasure to enable cascade."
"Otherwise"
"Decrement and net-out the dimensions."
^result.
***22 lines of code ***
< operand
"The units of measure must be the same."
^result.
= operand
"The units of measure must be the same."
^result.
***21 lines of code ***
> operand
"The units of measure must be the same."
^result.
@ aHumMeasure
^point.
abs
^measure.
adaptToCollection: aCollection andSend: aSymbol
^resultingCollection.
arcTan: aDenominator
"Return the arc-tangent (angle) for self divided by aDenominator"
^angle.
as: aSymbol
"Convert to the unit of measure indicated by aSymbol, and renders as String"
^string.
asFloat
^q.
asMillimeter
"Convert pixel dimensions to millimeter dimensions"
"For convenience while debugging. Enlarge those pixels?"
^result.
asMillimeters
^self asMillimeter.
asPercent
"This is valid only if given measure is dimensionless."
"For this to be useful,
"TODO: Consider simply returning a scalar: (^self * 0.01)"
^measure.
asString
^result.
compareAngle: aRadianMeasure
"Handle special arithmetic for comparing angles."
^result.
cos
^ quantity cos.
cubed
^result.
dimensions
"Tracks units and powers of units -- "
^ dimensions ifNil: [ dimensions := Dictionary new.]
dimensions: aDictionary
displayUnits
^displayUnits.
incrementDimensionsAt: aUnit by: anIncrement
"Increment / Decrement dimension exponent by given increment (negative when decrementing).
"
"Remove zeroed dimensions."
"TODO: THINK: This discards potentially useful information."
" e.g. meter^0 indicates scale or stress or coeficient of expansion ... "
"TODO: When units cancel (e.g. length/length), find some way to preserve information.
"
isDimensionless
"Is the current measure dimensionless?"
isPixels
^result.
isRadian
^result.
negated
^result.
printOn: aStream
"Append to the argument, aStream, a sequence of characters that
quantity
"Return the quantity that was observed for this instance."
"Raise an error if caller attempts to access without a previous set."
^ quantity ifNil: [ Error signal: 'measure quantity not set.' ].
quantity: aNumber
quantity: aNumber per: denominatorUnits
"Set instance denominator units.
"
quantity: aNumber units: numeratorUnits
"Set instance numerator units
"
quantity: aNumber units: numeratorUnits per: denominatorUnits
"Set instance numerator and denominator units.
"
"Get matching numerator exponent, if any, so that we correctly handle ratios
***26 lines of code ***
quantityAsString
"Return the quantity that was observed for this instance."
^result.
quantityAsString: q
"Return the quantity that was observed for this instance."
^result.
^result.
sin
^ quantity sin.
sqrt
^instance.
standardNameFor: aString
"Fix up names of units to assure consistency."
"Remove square- cubic-"
"Standardize terms"
^unitsString.
units
"Render dimensions as a string"
^string trimBoth.
***32 lines of code ***
unitsSynonyms
^ self class unitsSynonyms
Hum-RunTime -- HumMessage
nounValues: associations
"TODO: Consider: a HumStatement also has nounValues. Which noun values are which?"
receiver: aString
sender: aString
statement: aHumStatement
whenSent: aTimeStamp
" "
Hum-RunTime -- HumMessenger
getActorInstanceFromID: actorID
"*** Backdoor *** during debug to bypass the messenger"
^actorInstance.
logInstruction: aHumStatement sentFrom: senderURI to: recipientURI
"Get the clock time - may be a simulator clock"
network
"Return the chosen physical implementation of network service."
^ network ifNil: [ network := HumNetwork new].
nodeIDtoURI
"actorURI contains (actor->URI) maps"
^ nodeIDtoURI ifNil: [ nodeIDtoURI := Dictionary new ].
ping: aURI
"MOCK: Return the ID of the given URI"
^ ( self uriToNodeID ) at: aURI ifAbsent: [ Error signal: 'Messenger has no ID entry for URI: ', aURI ].
playbackLog
^playbackLog ifNil: [ playbackLog := Dictionary new].
playbackLogFromActor: aHumActor
"Extract/Get log entries sent to/from a specific actor.
"TODO: Add timestamp feature.
^result.
***23 lines of code ***
playbackLogFromURI: aURI
"Extract/Get log entries sent to/from a specific actor.
"TODO: Add timestamp feature.
^result.
playbackLogToURI: aURI
"Extract/Get log entries sent to/from a specific actor.
"TODO: Add timestamp feature.
^result.
***21 lines of code ***
registerActor: anActor atURI: aURI
"Track actor."
"Track URI->actor association."
registerNode: aNode atURI: aURI
"Track actor."
"Track URI->actor association."
sendAction: anInstructionLine toID: recipientID fromID: senderID
"Transmit action request between actors."
"Translate ID to URI."
"Send . . ."
sendAction: anInstruction toURI: recipientURI fromURI: senderURI
"Send the (action) statement to the given actor."
"Delegate implementation to HumNetwork"
sendInstruction: anInstruction toURI: recipientURI fromURI: senderURI
"Send the (action) statement to the given actor."
"TODO: REFACTOR so that this pushes to a network.
"Following only works when actor is local."
"TODO: Fix so that it works when actor is remote."
"TODO: Need a better simulation of async."
"========================================"
uriToNodeID
"What actor ID is associated with URI?"
^ uriToNodeID ifNil: [ uriToNodeID := Dictionary new]
Hum-RunTime -- HumNetwork
sendAction: anInstruction toURI: recipientURI fromURI: senderURI
"Send the (action) statement to the given actor."
"Following only works when actor is local."
"TODO: Fix so that it works when actor is remote."
uriToNode
"Return dictionary that maps a URI to an actual actor instance"
"NOTE: This should only be used in test/local mode.
^ uriToNode ifNil: [ uriToNode := Dictionary new. ].
Hum-RunTime -- HumNode
asString
^ self id ifNil: [ 'no ID'].
checkIn
"Check-in with the messenger."
clock
^ clock ifNil: [clock := DateAndTime "class singleton"].
clock: anObjectThatImplementsNow
"WARNING: #clock also appears in HumConfiguration."
configuration
^ configuration ifNil: [Error signal: 'Node has not been configured.'].
configuration: aHumConfiguration
htmlAgent
"Return http/html agent implementation.
^ htmlAgent ifNil: [ htmlAgent := self ].
id
^myID
id: aString
log
^ log ifNil: [ log := OrderedCollection new ].
messenger
^self configuration messenger.
printOn: aStream
"Append to the argument, aStream, a sequence of characters that
sendHTML: htmlString
"This is a dummy/mock for testing."
sendHTML: htmlString to: aURL
"This is a dummy/mock for testing. TODO: Make this real."
stepLog
^ stepLog ifNil: [ stepLog := OrderedCollection new.].
stepLogDisplay
"Display the step log"
uri
^myURI.
uri: aURI
Hum-RunTime -- HumNumberParser
nDigits
^nDigits.
Hum-RunTime -- HumScribe
about
"See also: HumRunTimeTests>>testS100ScribeReadMe"
"
"
"
"“
"SUMMARY?
"
***36 lines of code ***
askView: viewFrame withBlackBoard: aBlackBoard
"Current implementation assumes user interface is a HTML browser."
"TODO: HTML stuff belongs in a subtype of Scribe."
"Generate an HTML form for the view."
"Wrap the view with HTML prolog, navigation, epilog, etc."
"TODO: Associate an event with the ask-view data-entry."
askViewCompleted
"Inform caller that the 'Ask viewName' task
"Skip this if there was no dialog caller."
"Send results back to my Dialog Agent"
"TODO: ?? Do we return results in completion message ??
"Get current task context and send task complete message."
blackboard
"This instance variable should be set by the instance-creation logic. "
^blackboard ifNil: [Error signal: 'Scribe blackboard should point to Dialog Agent blackboard.']
client: aClientConection
"synonym"
clientConnection
^ clientConnection ifNil:[ clientConnection := myURI ].
clientConnection: aConnectionOfSomeKind
"How does the Scribe connect to the user/client sensors?"
"TODO: THIS NEEDS DEEPER/MORE DETAILED THOUGHT."
self assert: ( aConnectionOfSomeKind isKindOf: ZnUrl ).
clientSays: aString
"After a client sensor input is interpreted,
"
"*** Following is here for DEBUG? -- Scribe need not be coupled to ontology."
^vignette.
dialogAgent
"Returns the Dialog Agent that was attached to this Scribe when the Scribe was instantiated."
^dialogAgent ifNil: [ Error signal: 'Scribe {',myID asString,'} has no dialog agent.']
dialogAgent: aHumDialogAgent
dialogAgentURI
"Returns an instance of HumDialogAgent."
^dialogAgentURI
dialogAgentURI: aHumDialogAgentURI
handleHttpPostRequest: aHumHttpRequest
"The scribe handles the post request by
"
"TODO: Should I clear the blackboard before placing these (new/replacement) values?
"
"Put the data on my blackboard.
"I am ready to send data back to the dialog agent
***28 lines of code ***
htmlStyle
"Return CSS style element."
^styleElement.
initialize
"DEBUG Check: Scribe should be initialized with a dialogAgent at creation."
mockDataEntry: userData
"Mock the user entering given data into view.
"
"HTML/HTTP magic places data into HTTP Request."
runAction: anAction inRole: aRole onJob: aHumJobTicket
"Over-ride HumActor to handle Scribe actions."
runInstruction: anInstruction inRole: aRole onJob: aJobID
"Override the HumActor -- (Why?)"
"We cannot accept statement strings here because we need noun values."
"We are expecting 'Ask viewName.' or 'Show viewName.'"
^self.
***33 lines of code ***
sendToDialogAgent: aClientSpeechString
"Send the string to my Dialog Agent."
^vignette.
sendView: htmlView
"Wrap the view element with HTML header, navigation, epilog, etc."
"TODO: When we more than one kind of scribe, this method will be abstract."
^htmlResult.
systemSays: aString
"The Dialog Agent has responded with this String.
"
"*** Subtype implementations will override this method. ***"
zdialogAgent: aHumDialogAgent
Hum-RunTime -- HumSimulator
after: aDuration sendSpeech: aString from: aClientID
"Put this event into my queue."
"TODO: Generalize to send string to specific actor, not just user dialog."
buildDialogAgentNamed: clientID
"Build a dialog agent configured for our simulation."
"Check-in with Messenger to enable communication with Dispatcher and WorldBase."
^clientAgent.
clientScribes
^clientScribes ifNil: [ clientScribes := Dictionary new.]
dialogAgents
^ dialogAgents ifNil: [ dialogAgents := Dictionary new ].
dialogSequence: anArrayOfString
"Identify the sequence of dialog responses to be sent during this simulation."
getDialogAgentNamed: aClientID
^clientAgent.
getScribeForClient: aClientID
"Get the Scribe instance corresponding to the client ID."
^scribe
initialize
"Use factory methods to build singleton accomplices"
"self dispatcher: (HumActor dispatcherID: 'SimDispatcherID' uri: 'SimDispatcherURI' configuration: self)."
"self bookkeeper: (HumActor bookkeeperID: 'SimBookkeeperID' uri: 'SimBookkeeperURI' configuration: self)."
"self worldBase: (HumWorldBase openWorldBase: 'SimWorldBase')."
log4Dialog
^ log4Dialog ifNil: [ log4Dialog := OrderedCollection new. ].
logDialogWhen: aDuration who: aClientID why: clientSaid what: systemSaid
now
^ self simulatedClockSecond.
now: aDuration
numberOfDialogs: aSmallInteger
"How many dialogs are to be run simulataneously?"
queue
^ queue
randomStartingIntervals: aDistribution
"Express the distribution as an S-curve in seconds."
simulatedClockSecond
^ simulatedClockSecond ifNil: [simulatedClockSecond := 0 seconds].
step
"Send all events with timing that matches the top event."
"If the queue is empty, do nothing.
"Update my clock."
"Pull the events for this clock-time from the queue."
"Send those events"
"Someday we might do more than one type of event. But, currently, we just do speech events."
"The *fundamental* idea is that user-gestures are translated to speech-acts
"TODO: Generalize to send event to specific actor, not just the user dialog."
"The dialog agent may, in turn, trigger self-actions, plans, and/or actions. "
***27 lines of code ***
stepUntilDone
Hum-RunTime -- HumText
= anotherHumText
"Does this text have same content as the other"
^isSame.
Hum-RunTime -- HumTextLine
copy
^newInstance.
indentLevel
"The indent level indicates the level of indentation,
^ indentLevel ifNil: [ indentLevel := 0 ].
indentLevel: aSmallInteger
size
^ self string size
string
^string.
string: aByteString
Hum-RunTime -- HumText
addLine: aString
"Append given line at bottom of text."
copy
^newInstance.
insertEmptyLineAfter: lineIndex
"Note: Following will call self changed."
lines
"Return the HumText list of HumTextLine instances"
^lines.
lines: anOrderedCollection
printOn: aStream
"Append to the argument, aStream, a sequence of characters that
string
"Return self as a string. (Lines with CR inserted as needed.)"
^result.
Hum-RunTime -- HumVMInstruction
opCodeName
^name.
operand
^ operand ifNil: [ Error signal: 'operand not set in HumInstruction'. operand := 000].
operand: objectIndex
operation
^ operation ifNil: [ Error signal: 'op code not set in HumInstruction'. operation := 000].
operation: opCode
slotName
^'Undefined.'
Hum-RunTime -- HumVM
measureRegister
^ measure ifNil: [ measure := HumMeasure new. ].
runInstruction: aHumInstruction
"Get the microCode. (a block)"
"Run the microCode. (a block)"
"Assure cascade."
^self.
setSlot: slotIndex to: aHumObject
"The slots allow objects to be referenced by byte-code indices."
"Slots are used like registers in this VM thought-experiment. "
slots
"slots allow objects to be referenced by byte-code indices."
^ slots ifNil: [slots := Dictionary new. ].
transferVector
^transferVector.
Hum-RunTime -- HumVector
asString
"render my value as a string"
^result.
at: index
^v.
at: k put: aValue
cross: anotherHumVector
"Return the 3-dimensional vector cross product U x V
"
^s.
***25 lines of code ***
dot: aHumVector
^sum.
length
^length.
lengthSquared
"length := s sqrt."
^s.
pitch: anAngleInRadians
"Transform receiver by a rotation about x (East pointing) axis."
^vector.
pitch: anAngleInRadians aboutPivot: pivot
"Transform receiver by a rotation about X (side pointing) axis."
"The effect is to move the effective origin."
"Restore the coordinate origin."
"Post condition: The length of the vector should not change"
"TODO: Write a test-suite for yaw, pitch, roll."
^vector.
***22 lines of code ***
quantityAsString
^s.
roll: anAngleInRadians
"Transform receiver by a rotation about y (North pointing) axis."
^vector.
roll: anAngleInRadians aboutPivot: pivot
"Transform receiver by a rotation about Y (forward pointing) axis."
"Arithmetic is all via HumMeasure"
"The effect is to move the effective origin."
"Restore the coordinate origin."
"Post condition: The length of the vector should not change"
^vector.
***25 lines of code ***
size
"compatibility"
x
^(self at: 1).
x: xValue y: yValue z: zValue
"Hum coordinates are plan-view. x points East. y North. z Up."
"Create array and store as quantity."
"Assume all elements have same unit of measure (by definition)."
y
^self at: 2.
yaw: anAngleInRadians
"Transform receiver by a rotation about z (Up pointing) axis."
^vector.
yaw: anAngleInRadians aboutPivot: pivot
"Transform receiver by a rotation about Z (Up pointing) axis."
"The effect is to move the effective origin."
"Restore the coordinate origin."
"Post condition: The length of the vector should not change"
^vector.
***23 lines of code ***
z
^z := self at: 3.
Hum-RunTime -- HumWorldBase
checkTau: aTau
getEntityID: entityID attribute: attributeType
" Get requested value (if any) from the world base instance "
^ value.
history
^ history ifNil: [ history := Dictionary new. ].
initialize
quads
"For quad internal structure see
^ quads ifNil: [ quads := Dictionary new. ].
setEntityID: entityID attribute: attributeType toValue: aValue
"Put attribute-value (if any) into the world base instance. "
"TODO: Tau should refer to a business event."
"If there is a different prior value, archive in history."
"Put value of entity attribute and the timestamp."
"TODO: For large scale applications,
"
"TODO: Should (other) blackboards holding the same entityID be notified of the change? If so, how?"
***22 lines of code ***
title
^ title ifNil: [ Error signal: 'A world base instance must have a title.'].
title: aWorldBaseName
whereAttribute: attributeType satisfies: aBlockClosure
"Return a set of entity identifiers where the attribute value satisfies the block"
"Tau (timestamp) is not really used. I've included it for clarity and debug."
^identifierSet.
Hum-Seaside
Hum-Seaside -- HumApplication
bookkeeper: aHumBookkeeper
"This application instance will be served by this bookkeeper instance."
dispatcher: aHumResourceManager
"This application instance will be served by this Dispatcher instance."
messenger: aHumMessenger
"This application instance will be served by this messenger instance."
ontology: aHumOntology
"This application a run-time manifestation of that ontology."
worldBase: aHumWorldBase
"This application instance will be served by this world-base instance."
Hum-Seaside -- HumBrowserEditFrame
critic
^ critic ifNil: [ critic := '*** No frame critique yet ***' ].
critic: aTextString
"This is a dummy to accomodate a side-effect of using a TextArea to display the critique.
"
"self trace: 'critc called with: ', aTextString. "
fetchCodeForTitle: aString
firstLine
^ result.
frameCode
^ frameCode ifNil: [ frameCode := '*** No frame code yet. ***']
frameCode: aTextString
initialize
lastSaved
^ lastSaved ifNil: [ lastSaved := '*** NOT SAVED YET ***' ].
lastSaved: anObject
layoutFrameAsColumnsOnCanvas: aWAHtmlCanvas
"Generate the column style layout"
***33 lines of code ***
layoutFrameAsRowsOnCanvas: aWAHtmlCanvas
"Generate the row style layout."
"readonly: False; "
***39 lines of code ***
renderContentOn: html
runCritic
"Run the ontology critic that is appropriate to this type of frame."
setCritique: aTextString
"Set the critique value.
"
title
^ title ifNil: [ title := 'TBD']
title: aString
"Otherwise -- fetch the code for the new title."
trace: aString
Hum-Seaside -- HumBrowserSession
currentFrame
"What frame is currently being editted?"
^ currentFrame ifNil: [ currentFrame := HumBrowserEditFrame new. ].
Hum-Seaside -- HumBrowser
blackboard
^ blackboard ifNil: [blackboard := HumBlackBoard worldbase: 'none'.]
clearOntology
contextDiagram
^ contextDiagram ifNil: [ contextDiagram := HumDiagram new title: 'Context Diagram '].
currentFrame
"What frame is currently being editted?"
^ self session currentFrame.
dialog
^ dialog ifNil: [ dialog := HumSeasideComponentThingy new. ].
editActionFrame: aTitleString forRole: aRoleString
"Create / View / Edit the frame with the given title."
editDialogFrame: aString
"Create / View / Edit the frame with the given title."
editDictionaryFrame: aString
"Create / View / Edit the frame with the given title."
editPlanFrame: aString
"Create / View / Edit the frame with the given title. (Use goal statement as title.)"
editViewFrame: aString
"Create / View / Edit the frame with the given title."
hideDiagrams
^ hideDiagrams ifNil: [ hideDiagrams = False ].
hideDiagrams: aBoolean
^ hideDiagrams := aBoolean.
initialize
layout
"What style of browser layout (#rows or #columns)?
"
^ layout ifNil: [ layout = #rows ].
layout: aSymbol
"What style of browser layout (#rows or #columns)?
"
^ layout := aSymbol.
layoutDiagramsAsColumnOnCanvas: aWAHtmlhtml
^ html div
"html label: 'Diagram Column'.
"Draw plan diagram on this html."
***25 lines of code ***
layoutDiagramsAsRowOnCanvas: aWAHtmlCanvas
"html label: 'Diagram Row'.
***25 lines of code ***
layoutMenuActionsAsColumnOnCanvas: html
"Identify the actions that the user may invoke via menu navigation."
"A menu is a sequence of name -> action pairs.
"
"
"
"
"* Save will overwrite an existing file without asking.
"* I expect Save-As to be used like it is in Smalltalk
"
"
"
"
"Hide or UnHide"
"Render the main menu"
***86 lines of code ***
layoutWindowAsColumns
"*** This is a design document defining layout in Hum markup. ***
"Hum view mark-up for the window layout.
"
"The Source Frame Tabs are similar to Eclipse source code navigation.
"
"The Diagram Column shows a set of diagram viewers.
"
"The menu bar is a row of tabs identical to common desktop window menus in operation.
"What does the user/programmer need in the status bar?
"
***64 lines of code ***
layoutWindowAsColumnsOnCanvas: aWAHtmlCanvas
"This layout is visually two columns with editor on left and diagrams on right."
"Layout the Window as a table with three rows."
"Finally we generate the window contents by calling the functions [blocks] that we defined above."
"html render: [ htmlMenuBar value: html ].
"Editor Column and Diagram Column"
***32 lines of code ***
layoutWindowAsRows
"This layout is visually two rows with editor on bottom row and diagrams on top row."
"Hum view mark-up for the window layout.
"
"The Source Frame Tabs are similar to Eclipse source code navigation.
"
"The Diagram Row shows a set of diagram viewers.
"
"The menu bar is a row of tabs identical to common desktop window menus in operation.
"What does the user/programmer need in the status bar?
"
***56 lines of code ***
layoutWindowAsRowsOnCanvas: aWAHtmlCanvas
"This layout is visually two Rows with diagrams in top row and editor in lower row."
"Layout the Window as a table with three rows."
"Finally we generate the window contents by calling the functions [blocks] that we defined above."
"html render: [ htmlMenuBar value: html ].
***39 lines of code ***
loadOntologyFile: aFileSpec
"To be consistent with Hum design ideas, we will use a WorldBase instead of local file."
loadOntologyInstance: ontologyTitle
"Initialize / Replace my ontology instance."
^ontology.
log: aString
"Use #logUserAction instead."
logUserAction: aString
"Log the user action for potential analysis / diagnosis."
menuActions
"Identify the actions that the user may invoke via menu navigation."
"A menu is a sequence of name -> action pairs.
"
"
"
"
"* Save will overwrite an existing file without asking If file is not known, it will dialog for a file name. (Relatively harmless if we have infinite undo.)"
"* I expect Save-As to be used like it is in Smalltalk - as a kind of poor-man's source code label mechanism."
"
"
"
"
"The following will force each menu action to be defined, if not implemented."
"Evaluate the block to force the selectors it references to be created."
"force value: ontologyMenu."
^ combinedMenu.
***68 lines of code ***
newOntology
"Start with a fresh new ontology and clear any related views."
nounDiagram
^ nounDiagram ifNil: [ nounDiagram := HumDiagram new title: 'Noun Diagram '].
ontology
^ ontology ifNil: [ ontology := HumOntology new. ].
openOntology
"Clear all views and load an ontology from a save file."
openOntologyDialog
planDiagram
^ planDiagram ifNil: [ planDiagram := HumDiagram new title: 'Plan Diagram '].
printOntology
"Document the current ontology in a HTML document"
programmersAssistant
^ programmersAssistant ifNil: [ programmersAssistant := HumProgrammersAssistant new ].
renderContentOn: html
roleDiagram
^ roleDiagram ifNil: [ roleDiagram := HumDiagram new title: 'Role Diagram '].
saveOntology
"Write the current ontology into a save file."
showSubMenu: aMenu title: aString onCanvas: html
"aMenu is an OrderedCollection of ( name -> action ).
"
***21 lines of code ***
toggleDiagramView
toggleFullScreen
transposeLayout
userActions
^ userActions ifNil: [ userActions := OrderedCollection new.].
Hum-Seaside -- HumSeasideComponentThingy
ask: aSymbol
"Ask, set, and return the requested attrbute."

^result.
askV00: aSymbol
"Ask, set, and return the requested attrbute."
"*** THIS IS A MOCK ***"
^result.
attributes
^ attributes ifNil: [ attributes := Dictionary new. ].
logDialogAction: aString
renderView: anEntityID onCanvas: html
"**** Check generated code by pasting it below. ****"
***24 lines of code ***
valueOfAttribute: aSymbol
"Return the requested attrbute."
^result.
Hum-Tests
Hum-Tests -- GivenWhenThen4Seaside
assert: aBlock match: aPatternString
"This is a utility function to improve readability."
assert: aBlock matches: aPatternString
"This is a utility function to improve readability."
assertString: stringA includesSubstring: stringB
" stringB should be a substring in stringA "
expect: expectedValue actual: actualValue
given: aDescriptionString code: aBlock
"Given in a given-when-then triplet
"
"Save the block so that multiple *when* can restore initial state before running."

test105GivenWhenThenSuccess
"Test the test utility - In this situation the test assertion is true."
"A typical test looks like this."
"Blocks should have executed."
test106GivenWhenThenFail
"Test the test utility - In this situation the test assertion is true."
"Normally, this test is not needed."
"A typical test looks like this."
"Following should show assertion fails."
test110BasicLog
"Test the testcase`s own log"
test120GivenWhenThenLogging
"Test the testcase`s own log"
"A typical test looks like this."
"The log should contain the descriptions."
then: aDescriptionString code: aBlock
"*Then* in a given-when-then triplet
"
"Run my assertions."
^self.
when: aDescriptionString code: whenBlock
"*When* in a given-when-then triplet
"
"Run the given block to reset to initial state.
"
"Now run my block"
^self.
Hum-Tests -- GivenWhenThen
assertString: stringA includesSubstring: stringB
" stringB should be a substring in stringA "
given: aDescriptionString code: aBlock
"Given in a given-when-then triplet
"
"Save the block so that multiple *when* can restore initial state before running."

test105GivenWhenThenSuccess
"Test the test utility - In this situation the test assertion is true."
"A typical test looks like this."
"Blocks should have executed."
test106GivenWhenThenFail
"Test the test utility - In this situation the test assertion is true."
"Normally, this test is not needed."
"A typical test looks like this."
"Following should show assertion fails."
test110BasicLog
"Test the testcase`s own log"
test120GivenWhenThenLogging
"Test the testcase`s own log"
"A typical test looks like this."
"The log should contain the descriptions."
then: aDescriptionString code: aBlock
"*Then* in a given-when-then triplet
"
"Run my assertions."
^self.
when: aDescriptionString code: whenBlock
"*When* in a given-when-then triplet
"
"Run the given block to reset to initial state.
"
"Now run my block"
^self.
Hum-Tests -- Hum000RefactoringTests
givenOntology
"Create an Action Frame."
"Create a Dictionary Frame."
"Create a View Frame."
"Frames must be compiled if nouns are to be marked."
^ontology
***60 lines of code ***
humClassResponsiblityCollaboration
^'Collaborative Roles and Responsibilities
***228 lines of code ***
strategyForSeaside
^'TBD -- Currently considering subtyping HumWidgets as WAComponents
test110addFrame
"Add frame to ontology"
"A plan frame should have a goal and at least two preconditions."
test121getFrameForGoal
"Get the plan frame that defines a goal."
"A plan frame should have a goal and at least two preconditions."
test122getFrameForAction
"Get frame where action statement is defined."
"Initialize for an Action Frame."
***21 lines of code ***
test123getFrameForView
"Get frame where view is defined."
test131getFramesInvokingPrecondition
"Get the goal frames that invoke a given precondition."
***24 lines of code ***
test132getFramesInvokingAction
"Get the frames that invoke a given action."
"Actions may be invoked in goal-frames, action-frames, and vignettes."
"Create a goal frame. "
"Create an action frame."
"Create a vignette."
***28 lines of code ***
test133getFramesInvokingView
"Get views frames and vignettes that invoke a view."
"Create an ontology"
"Create a view that invokes another view."
"Create a vignette that invokes a view."
***26 lines of code ***
test134getFramesDefiningContext
"Get vignettes that define a context."
"Create an ontology"
"Create a vignette that defines part of a context."
"Create another vignette in the same context."
"Test: Make this not case-sensitive."
***26 lines of code ***
test135getFramesInvokingContext
"Get vignettes that define a context."
"Create an ontology"
"Create a vignette that defines part of a context."
"Create another vignette in the same context."
"Test: Make this not case-sensitive."
***26 lines of code ***
test210prettyPrintOntologyAsHTML
"Refactor so that this function is view OntologyViewer"
"Call via a OntologyViewer instance."
test211prettyPrintOntologyAsHTMLonFile
"Pretty print the given ontology on an HTML file."
"Call via a OntologyViewer instance."
test220renderCollectionAsHtmlTable
"A plural noun indicates a collection.
"
"Call via a OntologyViewer instance."
"Should see two tables"
"Should see attributes of steps."
"Should see attributes of ingredients."
"html inspect."
test221renderCollectionAsHtmlTableOnFile
"A plural noun indicates a collection.
"
"Call via a OntologyViewer instance."
"Should see two tables"
"Should see attributes of steps."
"Should see attributes of ingredients."
test230renderEmphasisAsHTML
"Render emphasis in the markup as underscore, italic, bold.
"
"Create a View Frame."
"Frames must be compiled if nouns are to be marked."
"Call via a OntologyViewer instance."
"Expect _not_ to become <u>not</u> "
"Expect ~preheat~ to become <i>preheat</i> "
"Expect *oven* to become <b>oven</b> "
"Note: Might also see noun <n> tags."
***30 lines of code ***
Hum-Tests -- Hum000TestPlanOverview
aReadMe
"See the class description for the intended (future) tests."
^'See the class description for the intended (future) tests.'
givenWhenThenInHTML
"HTML GivenWhenThen frames."
^'<html>
***157 lines of code ***
progress
^ '
***41 lines of code ***
Hum-Tests -- HumBaseTest
test110putGetValue
"Save entity-attribute-value and fetch."
***29 lines of code ***
test120updateGetValue
"Save entity-attribute-value and fetch."
"Set initial value"
"Update value"
***42 lines of code ***
test130putGetEvent
"put get event"
Hum-Tests -- HumByteCodeTests
setUp
"For convenience, create a Hum VM instance for all of the tests to use."
test110EachInstructionHasTwoBytes