Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Home
Help
Recent changes
Contributor Help Pages
Tasks and Tools
Modify a page
Add new content
Page elements
Typographical guidelines
More markup help
Translator Help Pages
Get a Translator Account
Languages represented
Translation Workflow
Translate a Page
Off-line Translation
Translation Statistics
More Help pages
Search
Search
English
Log in
Personal tools
Log in
Export translations
Translate
English
Language statistics
Message group statistics
Export
Tools
Tools
move to sidebar
hide
Actions
Language statistics
Message group statistics
Export
General
Special pages
Printable version
Settings
Group
Category:Phonon
Contribute/List of KDE Modules
Development
Development/FAQs/General FAQ
Development/FAQs/Technical FAQ
Development/KDevelop-PG-Qt Introduction
Development/Tools
Development/Tutorials
Development/Tutorials/CommandLineArguments
Development/Tutorials/Common Programming Mistakes
Development/Tutorials/First program
Development/Tutorials/First program/KDE4
Development/Tutorials/First program/KF5
Development/Tutorials/KDE3/Qt Designer and KDevelop 3.0 for Beginners
Development/Tutorials/Metadata/Nepomuk/TipsAndTricks
Development/Tutorials/Physical Simulation
Development/Tutorials/Qt4 Ruby Tutorial
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 01
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 04
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 05
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 06
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 07
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 08
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 09
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 10
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 11
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 12
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 13
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 14
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 2
Development/Tutorials/Qt4 Ruby Tutorial/Chapter 3
Development/Tutorials/Saving and loading
Development/Tutorials/Setting Up
Development/Tutorials/Using Actions
Development/Tutorials/Using KXmlGuiWindow
Documentation Primer
Edit Markup
Getting Started
Help:Contents
Help:Contribute
How To Convert a UserBase Manual to Docbook
KDE Frameworks
KDE Frameworks/Getting Started
KDE TechBase:About
KDE TechBase:Contributors
KDE TechBase:General disclaimer
KDE TechBase:Privacy policy
Off-line Translation
Projects/Calligra/Plugin Tutorials
Toolbox
Translate a Page
Translation Workflow
Typographical Guidelines
User:Neverendingo
Welcome to KDE TechBase
Language
aa - Afar
ab - Abkhazian
abs - Ambonese Malay
ace - Achinese
acm - Iraqi Arabic
ady - Adyghe
ady-cyrl - Adyghe (Cyrillic script)
aeb - Tunisian Arabic
aeb-arab - Tunisian Arabic (Arabic script)
aeb-latn - Tunisian Arabic (Latin script)
af - Afrikaans
aln - Gheg Albanian
alt - Southern Altai
am - Amharic
ami - Amis
an - Aragonese
ang - Old English
ann - Obolo
anp - Angika
ar - Arabic
arc - Aramaic
arn - Mapuche
arq - Algerian Arabic
ary - Moroccan Arabic
arz - Egyptian Arabic
as - Assamese
ase - American Sign Language
ast - Asturian
atj - Atikamekw
av - Avaric
avk - Kotava
awa - Awadhi
ay - Aymara
az - Azerbaijani
azb - South Azerbaijani
ba - Bashkir
ban - Balinese
ban-bali - Balinese (Balinese script)
bar - Bavarian
bbc - Batak Toba
bbc-latn - Batak Toba (Latin script)
bcc - Southern Balochi
bci - Baoulé
bcl - Central Bikol
bdr - West Coast Bajau
be - Belarusian
be-tarask - Belarusian (Taraškievica orthography)
bew - Betawi
bg - Bulgarian
bgn - Western Balochi
bh - Bhojpuri
bho - Bhojpuri
bi - Bislama
bjn - Banjar
blk - Pa'O
bm - Bambara
bn - Bangla
bo - Tibetan
bpy - Bishnupriya
bqi - Bakhtiari
br - Breton
brh - Brahui
bs - Bosnian
btm - Batak Mandailing
bto - Iriga Bicolano
bug - Buginese
bxr - Russia Buriat
ca - Catalan
cbk-zam - Chavacano
cdo - Min Dong Chinese
ce - Chechen
ceb - Cebuano
ch - Chamorro
cho - Choctaw
chr - Cherokee
chy - Cheyenne
ckb - Central Kurdish
co - Corsican
cps - Capiznon
cpx - Pu-Xian Min
cpx-hans - Pu-Xian Min (Simplified Han script)
cpx-hant - Pu-Xian Min (Traditional Han script)
cpx-latn - Pu-Xian Min (Latin script)
cr - Cree
crh - Crimean Tatar
crh-cyrl - Crimean Tatar (Cyrillic script)
crh-latn - Crimean Tatar (Latin script)
crh-ro - Crimean Tatar (Romania)
cs - Czech
csb - Kashubian
cu - Church Slavic
cv - Chuvash
cy - Welsh
da - Danish
dag - Dagbani
de - German
de-at - Austrian German
de-ch - Swiss High German
de-formal - German (formal address)
dga - Dagaare
din - Dinka
diq - Zazaki
dsb - Lower Sorbian
dtp - Central Dusun
dty - Doteli
dv - Divehi
dz - Dzongkha
ee - Ewe
egl - Emilian
el - Greek
eml - Emiliano-Romagnolo
en - English
en-ca - Canadian English
en-gb - British English
eo - Esperanto
es - Spanish
es-419 - Latin American Spanish
es-formal - Spanish (formal address)
et - Estonian
eu - Basque
ext - Extremaduran
fa - Persian
fat - Fanti
ff - Fula
fi - Finnish
fit - Tornedalen Finnish
fj - Fijian
fo - Faroese
fon - Fon
fr - French
frc - Cajun French
frp - Arpitan
frr - Northern Frisian
fur - Friulian
fy - Western Frisian
ga - Irish
gaa - Ga
gag - Gagauz
gan - Gan Chinese
gan-hans - Gan (Simplified)
gan-hant - Gan (Traditional)
gcr - Guianan Creole
gd - Scottish Gaelic
gl - Galician
gld - Nanai
glk - Gilaki
gn - Guarani
gom - Goan Konkani
gom-deva - Goan Konkani (Devanagari script)
gom-latn - Goan Konkani (Latin script)
gor - Gorontalo
got - Gothic
gpe - Ghanaian Pidgin
grc - Ancient Greek
gsw - Alemannic
gu - Gujarati
guc - Wayuu
gur - Frafra
guw - Gun
gv - Manx
ha - Hausa
hak - Hakka Chinese
haw - Hawaiian
he - Hebrew
hi - Hindi
hif - Fiji Hindi
hif-latn - Fiji Hindi (Latin script)
hil - Hiligaynon
hno - Northern Hindko
ho - Hiri Motu
hr - Croatian
hrx - Hunsrik
hsb - Upper Sorbian
hsn - Xiang Chinese
ht - Haitian Creole
hu - Hungarian
hu-formal - Hungarian (formal address)
hy - Armenian
hyw - Western Armenian
hz - Herero
ia - Interlingua
id - Indonesian
ie - Interlingue
ig - Igbo
igl - Igala
ii - Sichuan Yi
ik - Inupiaq
ike-cans - Eastern Canadian (Aboriginal syllabics)
ike-latn - Eastern Canadian (Latin script)
ilo - Iloko
inh - Ingush
io - Ido
is - Icelandic
it - Italian
iu - Inuktitut
ja - Japanese
jam - Jamaican Creole English
jbo - Lojban
jut - Jutish
jv - Javanese
ka - Georgian
kaa - Kara-Kalpak
kab - Kabyle
kai - Karekare
kbd - Kabardian
kbd-cyrl - Kabardian (Cyrillic script)
kbp - Kabiye
kcg - Tyap
kea - Kabuverdianu
kg - Kongo
khw - Khowar
ki - Kikuyu
kiu - Kirmanjki
kj - Kuanyama
kjh - Khakas
kjp - Eastern Pwo
kk - Kazakh
kk-arab - Kazakh (Arabic script)
kk-cn - Kazakh (China)
kk-cyrl - Kazakh (Cyrillic script)
kk-kz - Kazakh (Kazakhstan)
kk-latn - Kazakh (Latin script)
kk-tr - Kazakh (Turkey)
kl - Kalaallisut
km - Khmer
kn - Kannada
ko - Korean
ko-kp - Korean (North Korea)
koi - Komi-Permyak
kr - Kanuri
krc - Karachay-Balkar
kri - Krio
krj - Kinaray-a
krl - Karelian
ks - Kashmiri
ks-arab - Kashmiri (Arabic script)
ks-deva - Kashmiri (Devanagari script)
ksh - Colognian
ksw - S'gaw Karen
ku - Kurdish
ku-arab - Kurdish (Arabic script)
ku-latn - Kurdish (Latin script)
kum - Kumyk
kus - Kʋsaal
kv - Komi
kw - Cornish
ky - Kyrgyz
la - Latin
lad - Ladino
lb - Luxembourgish
lbe - Lak
lez - Lezghian
lfn - Lingua Franca Nova
lg - Ganda
li - Limburgish
lij - Ligurian
liv - Livonian
lki - Laki
lld - Ladin
lmo - Lombard
ln - Lingala
lo - Lao
loz - Lozi
lrc - Northern Luri
lt - Lithuanian
ltg - Latgalian
lus - Mizo
luz - Southern Luri
lv - Latvian
lzh - Literary Chinese
lzz - Laz
mad - Madurese
mag - Magahi
mai - Maithili
map-bms - Basa Banyumasan
mdf - Moksha
mg - Malagasy
mh - Marshallese
mhr - Eastern Mari
mi - Māori
min - Minangkabau
mk - Macedonian
ml - Malayalam
mn - Mongolian
mnc - Manchu
mnc-latn - Manchu (Latin script)
mnc-mong - Manchu (Mongolian script)
mni - Manipuri
mnw - Mon
mo - Moldovan
mos - Mossi
mr - Marathi
mrh - Mara
mrj - Western Mari
ms - Malay
ms-arab - Malay (Jawi script)
mt - Maltese
mus - Muscogee
mwl - Mirandese
my - Burmese
myv - Erzya
mzn - Mazanderani
na - Nauru
nah - Nāhuatl
nan - Min Nan Chinese
nap - Neapolitan
nb - Norwegian Bokmål
nds - Low German
nds-nl - Low Saxon
ne - Nepali
new - Newari
ng - Ndonga
nia - Nias
niu - Niuean
nl - Dutch
nl-informal - Dutch (informal address)
nmz - Nawdm
nn - Norwegian Nynorsk
no - Norwegian
nod - Northern Thai
nog - Nogai
nov - Novial
nqo - N’Ko
nrm - Norman
nso - Northern Sotho
nv - Navajo
ny - Nyanja
nyn - Nyankole
nys - Nyungar
oc - Occitan
ojb - Northwestern Ojibwa
olo - Livvi-Karelian
om - Oromo
or - Odia
os - Ossetic
pa - Punjabi
pag - Pangasinan
pam - Pampanga
pap - Papiamento
pcd - Picard
pcm - Nigerian Pidgin
pdc - Pennsylvania German
pdt - Plautdietsch
pfl - Palatine German
pi - Pali
pih - Norfuk / Pitkern
pl - Polish
pms - Piedmontese
pnb - Western Punjabi
pnt - Pontic
prg - Prussian
ps - Pashto
pt - Portuguese
pt-br - Brazilian Portuguese
pwn - Paiwan
qu - Quechua
qug - Chimborazo Highland Quichua
rgn - Romagnol
rif - Riffian
rki - Arakanese
rm - Romansh
rmc - Carpathian Romani
rmy - Vlax Romani
rn - Rundi
ro - Romanian
roa-tara - Tarantino
rsk - Pannonian Rusyn
ru - Russian
rue - Rusyn
rup - Aromanian
ruq - Megleno-Romanian
ruq-cyrl - Megleno-Romanian (Cyrillic script)
ruq-latn - Megleno-Romanian (Latin script)
rw - Kinyarwanda
ryu - Okinawan
sa - Sanskrit
sah - Yakut
sat - Santali
sc - Sardinian
scn - Sicilian
sco - Scots
sd - Sindhi
sdc - Sassarese Sardinian
sdh - Southern Kurdish
se - Northern Sami
se-fi - Northern Sami (Finland)
se-no - Northern Sami (Norway)
se-se - Northern Sami (Sweden)
sei - Seri
ses - Koyraboro Senni
sg - Sango
sgs - Samogitian
sh - Serbo-Croatian
sh-cyrl - Serbo-Croatian (Cyrillic script)
sh-latn - Serbo-Croatian (Latin script)
shi - Tachelhit
shi-latn - Tachelhit (Latin script)
shi-tfng - Tachelhit (Tifinagh script)
shn - Shan
shy - Shawiya
shy-latn - Shawiya (Latin script)
si - Sinhala
simple - Simple English
sjd - Kildin Sami
sje - Pite Sami
sk - Slovak
skr - Saraiki
skr-arab - Saraiki (Arabic script)
sl - Slovenian
sli - Lower Silesian
sm - Samoan
sma - Southern Sami
smn - Inari Sami
sms - Skolt Sami
sn - Shona
so - Somali
sq - Albanian
sr - Serbian
sr-ec - српски (ћирилица)
sr-el - srpski (latinica)
srn - Sranan Tongo
sro - Campidanese Sardinian
ss - Swati
st - Southern Sotho
stq - Saterland Frisian
sty - Siberian Tatar
su - Sundanese
sv - Swedish
sw - Swahili
syl - Sylheti
szl - Silesian
szy - Sakizaya
ta - Tamil
tay - Tayal
tcy - Tulu
tdd - Tai Nuea
te - Telugu
tet - Tetum
tg - Tajik
tg-cyrl - Tajik (Cyrillic script)
tg-latn - Tajik (Latin script)
th - Thai
ti - Tigrinya
tk - Turkmen
tl - Tagalog
tly - Talysh
tly-cyrl - Talysh (Cyrillic script)
tn - Tswana
to - Tongan
tok - Toki Pona
tpi - Tok Pisin
tr - Turkish
tru - Turoyo
trv - Taroko
ts - Tsonga
tt - Tatar
tt-cyrl - Tatar (Cyrillic script)
tt-latn - Tatar (Latin script)
tum - Tumbuka
tw - Twi
ty - Tahitian
tyv - Tuvinian
tzm - Central Atlas Tamazight
udm - Udmurt
ug - Uyghur
ug-arab - Uyghur (Arabic script)
ug-latn - Uyghur (Latin script)
uk - Ukrainian
ur - Urdu
uz - Uzbek
uz-cyrl - Uzbek (Cyrillic script)
uz-latn - Uzbek (Latin script)
ve - Venda
vec - Venetian
vep - Veps
vi - Vietnamese
vls - West Flemish
vmf - Main-Franconian
vmw - Makhuwa
vo - Volapük
vot - Votic
vro - Võro
wa - Walloon
wal - Wolaytta
war - Waray
wls - Wallisian
wo - Wolof
wuu - Wu Chinese
wuu-hans - Wu Chinese (Simplified)
wuu-hant - Wu Chinese (Traditional)
xal - Kalmyk
xh - Xhosa
xmf - Mingrelian
xsy - Saisiyat
yi - Yiddish
yo - Yoruba
yrl - Nheengatu
yue - Cantonese
yue-hans - Cantonese (Simplified)
yue-hant - Cantonese (Traditional)
za - Zhuang
zea - Zeelandic
zgh - Standard Moroccan Tamazight
zh - Chinese
zh-cn - Chinese (China)
zh-hans - Simplified Chinese
zh-hant - Traditional Chinese
zh-hk - Chinese (Hong Kong)
zh-mo - Chinese (Macau)
zh-my - Chinese (Malaysia)
zh-sg - Chinese (Singapore)
zh-tw - Chinese (Taiwan)
zu - Zulu
qqq - Message documentation
Format
Export for off-line translation
Export in native format
Export in CSV format
Fetch
{{DISPLAYTITLE:Development/KDevelop-PG-Qt Introduction}} <languages /> == Preface == '''KDevelop-PG-Qt''' is the parser-generator from ''KDevplatform''. It is used for some ''KDevelop-languagesupport-plugins'' (Ruby, PHP, CSS...). It uses Qt classes internally. There's also the original '''KDevelop-PG parser''', which used types from the STL, but has since been superceeded by '''KDevelop-PG-Qt'''. Most of the features are the same, though it could be that the ...-Qt parser generator is more up to date and feature rich than the plain STL style generator. The ...-Qt version should be used to write parsers for KDevelop language plugins. == In-Depth information == This document is not supposed to be a full-fledged and in-depth resource for all parts of '''KDevelop-PG'''. Instead it is intended to be a short introduction and, more importantly, a reference for developers. To get an in-depth introduction, read Jakob Petsovits' excellent Bachelor thesis. You find it in the Weblinks section at the bottom of this page. However, it does not cover recently added features. == The Application == === Usage === You can find '''KDevelop-PG-Qt''' in [https://projects.kde.org/projects/extragear/kdevelop/utilities/kdevelop-pg-qt git]. Four example packages are also included in the sources.<br /> To download it try: {{Input|1=git clone git://anongit.kde.org/kdevelop-pg-qt.git}} or: {{Input|1=git clone kde:kdevelop-pg-qt}} (when having setup '''git''' with kde:-prefix) The program itself requests a .g file, a so called grammar, as input: {{Input|1=./kdev-pg-qt --output=''prefix'' syntax.g}} The value of the ''--output'' switch decides the prefix of the output files and additionally the namespace for the generated code. '''Kate''' provides elementary highlighting for '''KDevelop-PG-Qt's''' grammar-files. === Output Format === While evaluating the grammar and generating its parser files, the application will output information about so called ''conflicts'' to STDOUT. As said above, the following files will actually be prefixed. ==== ast.h ==== AST stands for [http://en.wikipedia.org/wiki/Abstract_syntax_tree Abstract Syntax Tree]. It defines the data structure in which the parse tree is saved. Each node is a struct with the postfix ''Ast'', which contains members that point to any possible sub elements. ==== parser.h and parser.cpp ==== One important part of ''parser.h'' is the definition of the parser tokens, the ''TokenType'' enum. The TokenStream of your lexer should to use this. You have to write your own lexer or let one generate by '''Flex'''. See also the part about Tokenizers/Lexers below. Having the token stream available, you create your root item and call the parser on the parse method for the top-level AST item, e.g. DocumentAst* => parseDocument(&root). On success, root will contain the AST.<br /> The parser will have one parse method for each possible node of the AST. This is nice for e.g. an expression parser or parsers that should only parse a sub-element of a full document. ==== visitor.h and visitor.cpp ==== The Visitor class provides an abstract interface to walk the AST. Most of the time you don't need to use this directly, the DefaultVisitor takes some work off your shoulders. ==== defaultvisitor.h and defaultvisitor.cpp ==== The DefaultVisitor is an implementation of the abstract Visitor interface and automatically visits each node in the AST. Hence, this is probably the best candidate for a base class for your personal visitors. Most language plugins use these in their Builder classes to create the DUChain.<br /> === Command-Line-Options === * --namespace=''namespace'' - sets the C++ namespace for the generated sources independently from the file prefix. When this option is set, you can also use / in the --ouput option * --no-ast - don't create the ast.h file, more to that below * --debug-visitor - generates a debug visitor that prints the AST * --serialize-visitor - generates code for serialization via a QIODevice * --terminals - all tokens will be written into the file ''kdev-pg-terminals'' * --symbols - all possible nodes from the AST (not the leafs) will be written into the file ''kdev-pg-symbols'' * --rules - all grammar rules with informationen about their syntactic correlations will be written into a file called ''kdev-pg-rules''. useful for debugging and solving conflicts * --token-text - generates a function to map token-numbers onto token-names * --help - print usage information == Tokenizers/Lexers == As mentioned, '''KDevelop-PG-Qt''' requires a Tokenizer. You can either let '''KDevelop-PG-Qt''' generate one for you, write one per hand, as it has been done for C++ and PHP, or you can use external tools like '''Flex'''. The tokenizer's job, in principle, boils down to: * converting keywords and chars with special meanings to tokens * converting literals and identifier to tokens * clean out anything that doesn't change the semantics, e.g. comments or whitespace (the latter of course not in Python) * while doing the above, handling character encoding (we recommend using UTF8 as much as possible) <div class="mw-translate-fuzzy"> The rest, e.g. actually building the tree and evaluating the semantics, is part of the parser and the AST visitors.<br> </div> === Using KDevelop-PG-Qt === '''KDevelop-PG-Qt''' can generate lexers being well integrated into its architecture (you do not have to create a token-stream-class invoking lex or something like that). See examples/foolisp in the code for a simplistic example, there is also an incomplete PHP-Lexer for demonstration purposes. ==== Regular Expressions ==== Regular expressions are used to write rules using the KDevelop-PG-Qt, we use the following syntax (α and β are arbitrary regular expressions, a and b characters): *α|β accepts any word accepted by α or accepted by β *α&β accepts any word accepted by both α and β *α^β accepts any word accepted by a but not by β *~α accepts any word not accepted by α *?α like α, but also accepts the empty word *α* accepts any (maybe empty) sequence of words accepted by α *α+ accepts any nonempty sequence of words accepted by α (equivalent to αα*) *α@β accepts any nonempty sequence of words accepted by α separated by words accepted by β (equivalent to α(βα)*) *αβ accepts words consisting of a word accepted by α followed by a word accepted by β *[…] switches to “disjunctive” environment, αβ will get interpreted as α|β, you can use (…) inside the brackets to go back to normal mode *. accepts any single character *a-b accepts a single character between a and b (including a and b) in the Unicode (of course only characters that can be represented in the used encoding) *"…" will accept the word enclosed by the quotation marks, escape sequences will still get interpreted *a accepts the word consisting of the single character a *Any escape sequence (see below), accepts the word consisting of the character represented by the escape sequence *{⟨name⟩} accepts any word accepted by the regex named ⟨name⟩ All regular expressions are case sensitive. Sorry, there is currently no way for insensitivity. ==== Known Escape Sequences ==== There are several escape sequences which can be used to encode special characters: *\n, \t, \f, \v, \r, \0, \b, \a like in C *\x, \X, \u or \U followed by hex digits: character represented by this Unicode value (in hex) *\d, \D followed by decimal digits, same, but in decimal representation *\o, \O followed by octal digits, same, but in octal representation *\y, \Y followed by binary digits, same, but in binary representation ==== Predefined named regex ==== Some regexes are predefined and can be used using braces {⟨name⟩}. They get imported from the official Unicode data, some important regexes: *{alphabetic} any alphabetic character *{num} any numeric character *{ascii-range} any character representable in ASCII *{latin1-range} any character representable in Latin 1 (8 Bit) *{uppercase} *{lowercase} *{math} ==== Rules ==== Rules can be written as: {{Input|1= ⟨regular expression⟩ TOKEN; }} Then the Lexer will generate the token TOKEN for lexemes matching the given regular expression. Which token will be chosen if there are multiple options? We use the ''first longest match'' rule: It will take the longest possible match (eating as many characters as possible), if there are multiple of those matches, it will take the first one. Rules can perform code actions and you can also omit tokens (then no token will be generated): {{Input|1= ⟨regular expression⟩ [: ⟨code⟩ :] TOKEN; ⟨regular expression⟩ [: ⟨code⟩ :]; ⟨regular expression⟩ ; }} There is rudimentary support for ''lookahead'' and so called (our invention) ''barriers'': {{Input|1= ⟨regular expression⟩ %la(⟨regular expression⟩); ⟨regular expression⟩ %ba(⟨regular expression⟩); }} The first rule will only accept words if they match the first regular expression and are followed by anything matching the expression specified using %la. The second rule will accept words matched by the first regular expression but will never run into a character sequence matching the regex specified by %ba. However, currently only rules with fixed length are allowed in %la and %ba (for example foo|bar, but not qux|garply). When applying the “first longest match” rule the %la/%ba expressions count, too. You can create your own named regexes using an arrow: {{Input|1= ⟨regular expression⟩ -> ⟨identifier⟩; }} The first character of the identifier should not be upper case. Additionally there are two special actions: {{Input|1= ⟨regular expression⟩ %fail; ⟨regular expression⟩ %continue; }} %fail will stop tokenization. %continue will make the matched characters part of the next token. ==== Rulesets ==== A grammar file can contain multiple ''rulesets''. A ruleset is a set of rules, as described in the previous section. It gets declared using: {{Input|1= %lexer "name" -> ⟨rules⟩ ; }} For your main-ruleset you omit the name (the name will be “start”). Usually the start-ruleset will be used. But you can change the ruleset in code actions using the macro lxSET_RULE_SET(⟨name⟩). You can specify code to be executed when entering or leaving a ruleset by using %enter [: ⟨code⟩ :]; or %leave [: ⟨code⟩ :]; respectively inside the definition of the ruleset. ==== Further Configuration and Output ==== The standard statements %lexer_declaration_header and %lexer_bits_header are available to include files in the generated lexer.h/lexer.cpp. By using %lexer_base you can specify the baseclass for the lexer-class, by default it is the TokenStream class defined by KDevelop-PG-Qt. After %lexerclass(bits) you can specify code to be inserted in lexer.cpp. You have to specify an encoding the lexer should work with internally using %input_encoding "⟨encoding⟩", possible values: *ASCII (7-Bit) *Latin 1 (8-Bit) *UTF-8 (8-Bit, full Unicode) *UCS-2 (16-Bit, UCS-2 part of Unicode) *UTF-16 (16-Bit, full Unicode) *UTF-32 (32-Bit, full Unicode) With %input_stream you can specify which class the lexer should use to get the characters to process, there are some predefined classes: *QStringIterator, reads from QString, required (internal) encoding: UTF-16 or UCS-2 *QByteArrayIterator, reads from QByteArray, required encoding: ASCII, Latin-1 or UTF-8 *QUtf16ToUcs4Iterator, reads from UTF-16 QString, required encoding: UTF-32 (UCS-4) *QUtf8ToUcs4Iterator, reads from UTF-8 QByteArray, required encoding: UTF-32 (UCS-4) *QUtf8ToUcs2Iterator, reads from UTF-8 QByteArray, required encoding: UCS-2 *QUtf8ToUtf16Iterator, reads from UTF-8 QByteArray, required encoding: UTF-16 *QUtf8ToAsciiIterator, reads from UTF-8 QByteArray, will ignore all non-ASCII characters, reqired encoding: ASCII Whether you choose UTF-8, UTF-16 or UTF-32 is irrelevant for functionality, but it may significantly affect compile-time and run-time performance (you may want to test your Lexer with ASCII if compilation takes too long). For example you want to work with a QByteArray containing UTF-8 data, and you want to get full Unicode support: You could either use the QByteArrayIterator and UTF-8 as internal encoding, or the QUtf8ToUtf16Iterator and UTF-16, or the QUtf8ToUcs4Iterator and UTF-32. You can also choose between %table_lexer; and %sequence_lexer; In the first case transitions between states of the lexer will get represented by big tables while generating the lexer (cases in the generated code). In the second case sequences will get stored in a compressed data structure and transitions will get represented by nested if-statements. For UTF-32 %table_lexer is infeasible, thus there %sequence_lexer is the onliest option. Inside your actions of the lexer you can use some predefined macros: {{Input|1= lxCURR_POS // position in the input (some kind of iterator or pointer) lxCURR_IDX // index of the position in the input // (it is the index as presented in the input, for example: input is a QByteArray, index incrementation per byte, but the lexer may operate on 32-bit codepoints) lxCONTINUE // like %continue, add the current lexeme to the next token lxLENGTH // length of the current lexeme (as presented in the input) lxBEGIN_POS // position of the first character of the current lexeme lxBEGIN_IDX // corresponding index lxNAMED_TOKEN(⟨name⟩, ⟨type⟩) // create a variable representing named ⟨name⟩ with the token type ⟨type⟩ lxTOKEN(⟨type⟩) // create such a variable named “token” lxDONE // return the token generated before lxRETURN(X) // create a token of type X and return it lxEOF // create the EOF-token lxFINISH // create the EOF-token and return it (will stop tokenization) lxFAIL // raise the tokenization error lxSKIP // continue with the next lexeme (do not return a token, you should not have created one before) lxNEXT_CHR(⟨chr⟩) // set the variable ⟨chr⟩ to the next char in the input yytoken // current token }} === Using Flex === With the existing examples, it shouldn't be too hard to write such a lexer. Between most languages, especially those ''"inheriting"'' C, there are many common syntactic elements. Especially comments and literals can be handled just the same way over and over again. Adding a simple token is trivial: {{Input|1="special-command" return Parser::Token_SPECIAL_COMMAND; }} That's pretty much it, take a look at eg. ''java.ll'' for an excellent example. However, it is quite tricky and ugly to handle UTF-8 with Flex. == How to write Grammar-Files == === Context-Free Grammars === '''KDevelop-PG-Qt''' uses so called [http://en.wikipedia.org/wiki/Context-free_grammars context-free grammars] using a concept of non-terminals (nodes) and terminals(tokens). While writing the grammar for the basic structure of your language, you should try to mimic the semantics of the language. Lets take a look at an example: C++-document consists of lots of declarations and definitions, a class definition could be handled e.g. in the following way: #''CLASS-token'' #a ''identifier'' #the ''{-token'' #a ''member-declarations-list'' #the ''}-token'' #and finally the '';-token'' The ''member-declarations-list'' is of course not a part of any C++ description, it is just a ''helper'' to explain the structure of a given semantic part of your language. The grammar could then define how exactly such helper might look like. === Basic Syntax === Now let us have a look at a basic example, a declaration in C++, as described in grammar syntax: {{Input|1= class_declaration | struct_declaration | function_declaration | union_declaration | namespace_declaration | typedef_declaration | extern_declaration -> declaration ; }} This is called a ''rule'' definition. Every lower-case string in the grammar file references such a rule. Our case above defines what a ''declaration'' looks like. The ''|''-char stands for a logical ''or'', all rules have to end on two semicolons. In the example we reference other rules which also have to be defined. Here's for example the ''class_declaration'', note the tokens in all-upper-case: {{Input|1= CLASS IDENTIFIER SEMICOLON | CLASS IDENTIFIER LBRACE class_declaration* RBRACE SEMICOLON -> class_declaration ; }} There is a new char in there: The asterisk has the same meaning as in regular expressions, i.e. that the previous rule can occur arbitrarily often or not at all. In a grammar <code> 0 </code> stands for an empty token. Using it in addition with parenthesizing and the logical ''or'' from above, you can express optional elements: {{Input|1= some_required_rule SOME_TOKEN <nowiki>( some_optional_stuff | some_other_stuff | 0 )</nowiki> -> my_rule ; }} All symbols never occuring on the left side of a rule are start-symbols. You can use one of them to start parsing. === Making matched rules available to Visitors === The simple rule above could be used to parse the token stream, yet no elements would be saved in the parsetree. This can be easily done though: {{Input|1= class_declaration=class_declaration | struct_declaration=struct_declaration | function_declaration=function_declaration | union_declaration=union_declaration | namespace_declaration=namespace_declaration | typedef_declaration=typedef_declaration | extern_declaration=extern_declaration -> declaration ; }} The DeclarationAst struct now contains pointers to each of these elements. During the parse process the pointer for each found element gets set, all others become NULL. To store lists of elements, prepend the identifier with a hash <keycap> # </keycap>: {{Input|1= CLASS IDENTIFIER SEMICOLON | CLASS IDENTIFIER LBRACE (#class_declaration=class_declaration)* RBRACE SEMICOLON -> class_declaration ; }} '''TODO: internal structure of the list, important for Visitors''' Identifier and targets can be used in more than one place: {{Input|1= #one=one (#one=one)* -> one_or_more ; }} In the example above, all matches to the rule ''one'' will be stored in one and the same list ''one''. === Defining available Tokens === Somewhere in the grammar (you should probably put it near the head) you'll have to define a list of available Tokens. From this list, the ''TokenType'' enum in ''parser.h'' will be created. Additionally to the enum value names you should define an explanation name which will e.g. be used in error messages. Note that the representation of a Token inside the source code is not required for the grammar/parser as it operates on a TokenStream, see Lexer/Tokenizer section above. {{Input|1= %token T1 ("T1-Name"), T2 ("T2-Name"), COMMA (";"), SEMICOLON (";") ; }} It is possible to use ''%token'' multiple times to group tokens in the grammar. Though all tokens will still be put into the same ''TokenType'' enum. '''TODO: explain process of using the parser Tokens''' === Special Syntax... === ==== ...to use inside Rules ==== ===== List of one or more elements ===== Alternatively to the asterisk (''*'') you can use a plus sign (''+'') to mark lists of one-or-more elements: {{Input|1= (#one=one)+ -> one_or_more ; }} ==== Separated lists ==== Using the ''#rule @ TOKEN'' syntax you can mark a list of ''rule'', separated by ''TOKEN'': {{Input|1= #item=item @ COMMA -> comma_separated_list ; }} ==== Optional items ==== Alternatively to the above mentioned ''(item=item | 0)'' syntax you can use the following to mark optional items: {{Input|1= ?item=item -> optional_item ; }} {{Attention|1= ''<nowiki>(0|x)</nowiki>'' is equivalent to ''0''}} ==== Local variables for the parse-process ==== Using a colon '''<keycap> : </keycap>''' instead of the equal sign '''<keycap> = </keycap> you can store the sub-AST in a local variable that will only be available during parsing, and only in the current rule. '''TODO: need example''' ==== Inlining ==== Instead of a name you can also place a dot <keycap> . </keycap> before the equal sign <keycap> = </keycap>. Then the AST will inherit all class-members from the sub-AST and the parsing-method for the sub-AST will be merged into the parent-AST. An example: {{Input|1= op=PLUS | op=MUL | op=MOD -> operator ;; val1=number .=op val2=number -> simpleArithmetics ; }} In SimpleArithmeticsAst there will be the fields ''val1'', ''val2'' (storing the operands) and ''op'' (storing the operator-token). ''parseSimpleArithmetics'' will not have to call ''parseOperator''. Obviously recursive inlining is not allowed. === ...to add Hand-Written Code === Sometimes it is required to integrate hand-written code into the generated parser. Instead of editing the end-result (**never** do that!) you should put this code into the grammar at the correct places. Here are a few examples when you'd need this: * custom error handling / error recovery, i.e. to prevent the parser to stop at the first error * creating tokens, if you don't want to do that externally * setting custom variables, especially for state tracking. e.g. in C++ you could save whether you are inside a ''private'', ''protected'' oder ''public'' section. then you could save this information inside each node of the class elements. * additional verifications, lookaheads etc. ==== General Syntax ==== <div class="mw-translate-fuzzy"> {{Input|1= [: // here be dragons^W code ;-) :] }} </div> The code will be put into the generated ''parser.cpp'' file. If you use it inside a grammar rule, it will be put into the correct position during the parse process. You can access the current node via the variable ''yynode'', it will have the type 'XYZAst**'. ==== Global Code ==== In '''KDevelop''' language plugins, you'll see that most grammars start with something like: <div class="mw-translate-fuzzy"> {{Input|1= [: </div> #include <QtCore/QString> #include <kdebug.h> #include <tokenstream.h> #include <language/interfaces/iproblem.h> #include "phplexer.h" namespace KDevelop { class DUContext; } <div class="mw-translate-fuzzy"> :] }} </div> This is a code section, that will be put at the beginning of ''ast.h'', i.e. into the global context. But there are also some newer statements available to include header-files: {{Input|1= %ast_header "header.h" %parser_declaration_header "header.h" %parser_bits_header "header.h" }} The include-statement will be inserted into ast.h, parser.h respectively parser.cpp. ==== Namespace Code ==== Also it's very common to define a set of enumerations e.g. for operators, modifiers, etc. pp. Here's an stripped example from PHP, note that the code will again be put into the generated ''parser.h'' file: {{Input|1= %namespace [: enum ModifierFlags { ModifierPrivate = 1, ModifierPublic = 1 << 1, ModifierProtected = 1 << 2, ModifierStatic = 1 << 3, ModifierFinal = 1 << 4, ModifierAbstract = 1 << 5 }; ... enum OperationType { OperationPlus = 1, OperationMinus, OperationConcat, OperationMul, OperationDiv, OperationMod, OperationAnd, OperationOr, OperationXor, OperationSl, OperationSr }; :] }} When you write code at the end of the grammar-file simply between ''[:'' and '':]'', it will be added to ''parser.cpp''. ==== Additional AST member ==== To add additional members to _every_ AST variable, use the following syntax: {{Input|1= %ast_extra_members [: KDevelop::DUContext* ducontext; :] }} You can also specify the base-class for the nodes: {{Input|1= %ast_base symbol_name "BaseClass" }} ''BaseClass'' has to inherit from ''AstNode''. ==== Additional parser class members ==== Instead of polluting the global context with state tracker variables, and hence destroying the whole advantages of OOP, you can add additional members to the parser class. It's also very convenient to define functions for error reporting etc. pp. Again a stripped example from PHP: {{Input|1= %parserclass (public declaration) [: enum ProblemType { Error, Warning, Info }; void reportProblem( Parser::ProblemType type, const QString& message ); QList<KDevelop::ProblemPointer> problems() { return m_problems; } ... enum InitialLexerState { HtmlState = 0, DefaultState = 1 }; :] }} Note, that we used ''%parserclass (public declaration)'', we could instead have used ''private'' or ''protected'' declaration. {{Input|1= %parserclass ( [private|protected|public] declaration) [: // Code :] }} There is also a statement to specify a base-class: {{Input|1= %parser_base "ClassName" }} ==== Initializing additional parser class members ==== When you add member variables to the class, you'll have to initialize and or destroy them as well. Here's how (either use ctor or dtor, of course): {{Input|1= %parserclass ( [constructor|desctructor] ) [: // Code :] }} ==== Boolean Checks ==== {{Input|1= ?[: // some bool expression :] }} The following rule will only apply if the boolean expression evaluates to ''true''. Here's an advanced example, which also shows that you can use the pipe symbol ('|') as logical or, i.e. essentially this is a ''if... else...' conditional: {{Input|1= ?[: someCondition :] SOMETOKEN ifrule=myVar | elserule=myVar }} This is especially convenient together with lookaheads (see below). ==== Defining local variables inside rules ==== You can set up the grammar to define local variables whenever a rule gets applied: {{Input|1= ... -> class_member [: enum { A_PUBLIC, A_PROTECTED, A_PRIVATE } access; :]; }} This variable is local to the rule ''class_member''. ==== Defining additional variables for the parse tree ==== Similar to the syntax above, you can define members whenever a rule gets applied: {{Input|1= ... -> class_member [ [member|temporary] variable yourName: yourType ]; }} For example: {{input|1= ... -> class_member [ member variable access : AccessType; ]; }} Of course ''AccessType'' has to be defined somewhere else, see e.g. the ''Additional parser class members'' section above. Using ''temporary'' or ''member'' is equivalent. == Conflicts == The first time you write a grammar, you'll potentially fail: Since '''KDevelop-PG-Qt''' is a ''LL(1)'' parser generator, conflicts can occur and have to be solved by hand. Here's an example for a FIRST/FIRST conflict: <div class="mw-translate-fuzzy"> {{Input|1= CLASS IDENTIFIER SEMICOLON -> class_declaration ; </div> CLASS IDENTIFIER LBRACE class_content RBRACE SEMICOLON -> class_definition ; <div class="mw-translate-fuzzy"> class_declaration | class_definition -> class_expression ; }} </div> KDevelop-PG-Qt will output: {{Output|1= ** WARNING found FIRST/FIRST conflict in "class_expression" }} Sometime's it's these warnings can be ignored, but most of the time it will lead to problems in parsing. In our example the ''class_expression'' rule won't be evaluated properly: When you try to parse a ''class_definition'', the parser will see that the first part (''CLASS'') of ''class_declaration'' matches, and jumps think's that this rule is to be applied. Since the next part of the rule does ''not'' match, an error will be reported. It does _not_ try to evaluate ''class_definition'' automatically, but there are different ways to solve this problem: === Backtracking === In theory such behavior might be unexpected: In BNF e.g. the above syntax would be enough and the parser would automatically jump back and retry with the next rule, here ''class_definition''. But in practice such behaviour is ''- most of the time -'' not necessary and would slow down the parser. If however such behavior is explicitly what you want, you can use an explicit backtracking syntax in your grammar: {{Input|1= try/rollback(class_declaration) catch(class_definition) -> class_expression ; }} In theory, every FIRST/FIRST could be solved this way, but keep in mind that the more you use this feature, the slower your parser gets. If you use it, sort the rules in order of likeliness. Also, there could be cases where the sort order could make the difference between correct and wrong parsing, especially with rules that "extend" others. == Look ahead == '''KDevelop-PG-Qt''' has an alternative to the - ''potentially'' slow - backtracking mechanism: Look ahead. You can use the ''LA(qint64)'' function in embedded C++ code (see sections above). ''LA(1)'' will return the current token, you most probably never need to use that. Accordingly, ''LA(2)'' returns the next and ''LA(0)'' the previous token. (If you wonder where these somewhat uncommon indexes come from: Read the thesis, or make yourself acquainted with ''LA(k)'' parser theory.) {{Input|1= (?[: LA(2) == Token_LBRACE :] class_definition) | class_declaration -> class_expression }} Note: The conflict will still be output, but it is ''manually'' resolved. You should always document this somewhere with a comment, for future contributors to know that this is a false-positive. == Elegant Solutions == Often you can solve the conflict all-together with an elegant solution. Like in our example: <div class="mw-translate-fuzzy"> {{Input|1= LBRACE class_content RBRACE -> class_definition ; </div> <div class="mw-translate-fuzzy"> CLASS IDENTIFIER ?class_definition SEMICOLON -> class_expression ; }} </div> No conflicts, fast: everybody is happy! == FIRST/FOLLOW-Conflicts == A FIRST/FOLLOW conflict says, that it is undefined where a symbol ends and the parent symbol continues. A pretty stupid example is: <div class="mw-translate-fuzzy"> {{Input|1= item* -> item_list ; </div> <div class="mw-translate-fuzzy"> item_list item* -> items ; }} </div> You probably see the glaring error. ''try/rollback'' helps with serious problems (e.g. parser doesn't work), though often you can ignore these conflicts. But if you do so, be aware that the parser is ''greedy'': In our example ''item_list'' will always contain ''all'' ''item'' elements, and ''items'' will ''never'' have an ''item'' member. If this is an issue that leads to later conflicts, only ''try/rollback'', custom manual code to check which rule should be used, or a refactoring of your grammar structure. === Changing the Greedy Behaviour === Alternatively it is sometimes helpful/required to change the greedy behaviour. In lists you can use manual code to force a break at a given position. Here's an example that shows this on a declaration of an array with fixed size: {{Input|1= typed_identifier=typed_identifier LBRACKET UNSIGNED_INTEGER [: count = static_cast<MyTokenStream*>(token)->strForCurrentToken().toUInt(); :] RBRACKET EQUAL LBRACE (#expression=expression [: if(--count == 0) break; :] @ COMMA) ?[: count == 0 :] RBRACE SEMICOLON -> initialized_fixed_array [ temporary variable count: uint; ]; }} '''TODO: return true/false or break??''' Via ''return false'' you can enforce a premature stop (== error) of the evaluation of the current rule. Using ''return true'' you stop the evaluation prematurely, but signalize that the parse process was successful. == try/recover == <syntaxhighlight lang="text"> try/recover(expression) -> symbol ;; </syntaxhighlight> This is approximately the same as: <syntaxhighlight lang="text"> [: ParserState *state = copyCurrentState(); :] try/rollback(expression) catch( [: restoreState(state); :] ) -> symbol ; </syntaxhighlight> Hence you have to implement the member-functions copyCurrentState and restoreState and you have to define a type called ParseState. You do not have to write the declaration of those functions in the header-file, it is generated automatically if you use ''try/recover''. This concept seems to be useful if there are additional states used while parsing. The Java-parser takes usage from it very often. But I do not know a lot about this feature and it seems unimportant for me. (I guess, it is not) I would be happy when somebody could explain it to me. == Operator Expression Parsing == '''TODO''' == Weblinks == * [http://quickgit.kde.org/?p=kdevelop-pg-qt.git&a=blob&f=kdev-pg/kdev-pg-parser.yy The KDevelop-PG-Qt-Grammar (it is a Bison/Yacc-grammar-file)] * [https://quickgit.kde.org/?p=kdevelop-pg-qt.git Project at quickgit.kde.org] * [http://the-user.org/category/computing/kde/kdev-pg-qt Some blog-posts by “The User” about KDevelop-PG-Qt (informative for recently added features)] * [http://stud4.tuwien.ac.at/~e0127236/thesis/jpetso-javaparser.pdf Jakob Petsovits' bachelor thesis about using KDevelop-PG for Java Java-Parsers]- It is a good in-depth introduction to everything you might want to know for writing your own grammar. Keep in mind that it is partly outdated. In doubt, refer to this page for updated syntax. Also some of the shortcomings of KDevelop-PG layed out in the thesis have been fixed in the meantime. [[Category:Getting_Started]] [[Category:Programming]]
Toggle limited content width