class Parser {
#name
#text
#buffer
#subject
#subjectId
#subjectType
#predicate
#range
#set = new Set
constructor(name) {
this.#name = name
this.#buffer = ''
}
parseTriple = (text) => {
const parts = text.split(';'),
subject = parts.shift(),
ontology = new RDF_Ontology,
obSubject = ontology.addSubject(this.parseResource(subject)),
{id, type} = obSubject.export()
console.log('prev==', this.#subjectId, 'sub==', subject, 'id=', id)
if(id) {
this.#subjectId = id
} if(type)
this.#subjectType = type
while(parts.length) {
const objects = parts.shift().split(','),
//First element is Predicate
obPredicate = obSubject.addPredicate(this.parsePredicate(objects.shift()))
//Other elements is Objects
const objs = objects.map(o => {
obPredicate.addObject(o)
return o
}).map(this.parseObjects)
.map(i => (i.length && i.includes('#') ? `<${i}>` : `'${i}'`))
.join(',')
this.#buffer += ` .
<${id}> ${this.#predicate} ${objs}`
}
this.#set.add(obSubject)
}
parseResource = (text) => {
let id, type, literal
if(text.includes('#')) {
[type, id] = text.split('#')
id = `#${id}`
if(type.includes(':'))
text = type
}
if(text.includes(':')) {
type = null
const classes = text.split(':').filter(s => s).map(c => `:${c}`)
console.log('classes', classes, type)
if(!type)
type = classes[0]
while(classes.length > 1) {
let subClass = classes.shift()
this.#buffer += ` .
${subClass} rdfs:subClassOf ${classes[0]}`
}
} else {
id = text
}
console.log('return', [id, type])
if(id && type) {
this.#buffer += ` .
<${id}> rdf:type ${type}`
}
return {id, type, literal}
}
parsePredicate = (text) => {
[this.#predicate, this.#range] = text.substr(1).split(':')
this.#predicate = `:${this.#predicate.replace(' ', '_')}`
if(this.#range) {
this.#range = `:${this.#range}`
this.#buffer += ` .
${this.#predicate} rdf:type owl:ObjectProperty ;
rdfs:domain ${this.#subjectType} ;
rdfs:range ${this.#range}`
}
return [this.#predicate, this.#range]
}
parseObjects = (text) => {
return this.parseResource(text)
}
loadText(text) {
this.#text = text
}
parse = () => {
console.clear()
this.#text.split('.').map(this.parseTriple.bind(this))
}
owl(prefix) {
this.parse()
const owl = `@prefix : <${prefix}${this.#name}#> .
@prefix owl: <http://www.w3.org/2002/07/owl#> .
@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .
@prefix xml: <http://www.w3.org/XML/1998/namespace> .
@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .
@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .
@base <${prefix}${this.#name}> .
<${prefix}${this.#name}> rdf:type owl:Ontology${this.#buffer} .`
console.log(this.#text)
console.log(this.#set)
console.log(owl)
return owl
}
}