MCPcopy Create free account
hub / github.com/danja/dogalog / parseProgram

Function parseProgram

src/prolog/parser.js:8–225  ·  view source on GitHub ↗
(src)

Source from the content-addressed store, hash-verified

6}
7
8export function parseProgram(src) {
9 const tokens = tokenize(stripComments(src));
10 let index = 0;
11
12 function peek() { return tokens[index]; }
13 function eat(type, value) {
14 const tok = tokens[index];
15 if (!tok || tok.type !== type || (value && tok.value !== value)) {
16 throw new Error(`Parse error near token ${JSON.stringify(tok)}; expected ${type} ${value ?? ''}`);
17 }
18 index++;
19 return tok;
20 }
21
22 function parseClause() {
23 const head = parseExpression();
24 let bodyAst = null;
25
26 if (peek() && peek().type === 'sym' && peek().value === ':-') {
27 eat('sym', ':-');
28 bodyAst = parseGoalOr();
29 }
30
31 eat('sym', '.');
32 const bodies = bodyAst ? expandGoals(bodyAst) : [[]];
33 return bodies.map((body) => ({ head, body }));
34 }
35
36 function parseGoalOr() {
37 let left = parseGoalAnd();
38 while (peek() && peek().type === 'sym' && peek().value === ';') {
39 eat('sym', ';');
40 const right = parseGoalAnd();
41 left = { type: 'or', left, right };
42 }
43 return left;
44 }
45
46 function parseGoalAnd() {
47 let left = parseGoalUnary();
48 while (peek() && peek().type === 'sym' && peek().value === ',') {
49 eat('sym', ',');
50 const right = parseGoalUnary();
51 left = { type: 'and', left, right };
52 }
53 return left;
54 }
55
56 function parseGoalUnary() {
57 const tok = peek();
58 if (tok && tok.type === 'sym' && tok.value === '\\+') {
59 eat('sym', '\\+');
60 const goal = parseGoalUnary();
61 return { type: 'not', goal };
62 }
63 if (tok && tok.type === 'sym' && tok.value === '(') {
64 eat('sym', '(');
65 const inner = parseGoalOr();

Callers 8

validatePrologCodeFunction · 0.90
executeQueryMethod · 0.90
scheduler.test.jsFile · 0.90
engine.test.jsFile · 0.90
parser.test.jsFile · 0.90
repl.test.jsFile · 0.90

Calls 3

tokenizeFunction · 0.90
stripCommentsFunction · 0.85
parseClauseFunction · 0.85

Tested by

no test coverage detected