Lex (software)

Lex
Original author(s)Mike Lesk, Eric Schmidt
Initial release1975; 49 years ago (1975)
Repository
Written inC
Operating systemUnix, Unix-like, Plan 9
PlatformCross-platform
TypeCommand
LicensePlan 9: MIT License

Lex is a computer program that generates lexical analyzers ("scanners" or "lexers").[1][2] It is commonly used with the yacc parser generator and is the standard lexical analyzer generator on many Unix and Unix-like systems. An equivalent tool is specified as part of the POSIX standard.[3]

Lex reads an input stream specifying the lexical analyzer and writes source code which implements the lexical analyzer in the C programming language.

In addition to C, some old versions of Lex could generate a lexer in Ratfor.[4]

History

Lex was originally written by Mike Lesk and Eric Schmidt[5] and described in 1975.[6][7] In the following years, Lex became standard lexical analyzer generator on many Unix and Unix-like systems. In 1983, Lex was one of several UNIX tools available for Charles River Data Systems' UNOS operating system under Bell Laboratories license.[8] Although originally distributed as proprietary software, some versions of Lex are now open-source. Open-source versions of Lex, based on the original proprietary code, are now distributed with open-source operating systems such as OpenSolaris and Plan 9 from Bell Labs. One popular open-source version of Lex, called flex, or the "fast lexical analyzer", is not derived from proprietary coding.

Structure of a Lex file

The structure of a Lex file is intentionally similar to that of a yacc file: files are divided into three sections, separated by lines that contain only two percent signs, as follows:

  • The definitions section defines macros and imports header files written in C. It is also possible to write any C code here, which will be copied verbatim into the generated source file.
  • The rules section associates regular expression patterns with C statements. When the lexer sees text in the input matching a given pattern, it will execute the associated C code.
  • The C code section contains C statements and functions that are copied verbatim to the generated source file. These statements presumably contain code called by the rules in the rules section. In large programs it is more convenient to place this code in a separate file linked in at compile time.

Example of a Lex file

The following is an example Lex file for the flex version of Lex. It recognizes strings of numbers (positive integers) in the input, and simply prints them out.

/*** Definition section ***/

%{
/* C code to be copied verbatim */
#include <stdio.h>
%}

%%
    /*** Rules section ***/

    /* [0-9]+ matches a string of one or more digits */
[0-9]+  {
            /* yytext is a string containing the matched text. */
            printf("Saw an integer: %s\n", yytext);
        }

.|\n    {   /* Ignore all other characters. */   }

%%
/*** C Code section ***/

int main(void)
{
    /* Call the lexer, then quit. */
    yylex();
    return 0;
}

If this input is given to flex, it will be converted into a C file, lex.yy.c. This can be compiled into an executable which matches and outputs strings of integers. For example, given the input:

abc123z.!&*2gj6

the program will print:

Saw an integer: 123
Saw an integer: 2
Saw an integer: 6

Using Lex with other programming tools

Using Lex with parser generators

Lex, as with other lexical analyzers, limits rules to those which can be described by regular expressions. Due to this, Lex can be implemented by a finite state automata as shown by the Chomsky hierarchy of languages. To recognize more complex languages, Lex is often used with parser generators such as Yacc or Bison. Parser generators use a formal grammar to parse an input stream.

It is typically preferable to have a parser, one generated by Yacc for instance, accept a stream of tokens (a "token-stream") as input, rather than having to process a stream of characters (a "character-stream") directly. Lex is often used to produce such a token-stream.

Scannerless parsing refers to parsing the input character-stream directly, without a distinct lexer.

Lex and make

make is a utility that can be used to maintain programs involving Lex. Make assumes that a file that has an extension of .l is a Lex source file. The make internal macro LFLAGS can be used to specify Lex options to be invoked automatically by make.[9]

See also

References

  1. ^ Levine, John R.; Mason, Tony; Brown, Doug (1992). lex & yacc (2 ed.). O'Reilly. pp. 1–2. ISBN 1-56592-000-7.
  2. ^ Levine, John (August 2009). flex & bison. O'Reilly Media. p. 304. ISBN 978-0-596-15597-1.
  3. ^ The Open Group Base Specifications Issue 7, 2018 edition § Shell & Utilities § Utilities § lex
  4. ^ John R. Levine; John Mason; Doug Brown (1992). Lex & Yacc. O'Reilly. ISBN 9781565920002.
  5. ^ Lesk, M.E.; Schmidt, E. "Lex – A Lexical Analyzer Generator". Archived from the original on 2012-07-28. Retrieved August 16, 2010.
  6. ^ Lesk, M.E.; Schmidt, E. (July 21, 1975). "Lex – A Lexical Analyzer Generator" (PDF). UNIX TIME-SHARING SYSTEM:UNIX PROGRAMMER’S MANUAL, Seventh Edition, Volume 2B. bell-labs.com. Retrieved Dec 20, 2011.
  7. ^ Lesk, M.E. (October 1975). "Lex – A Lexical Analyzer Generator". Comp. Sci. Tech. Rep. No. 39. Murray Hill, New Jersey: Bell Laboratories.
  8. ^ The Insider's Guide To The Universe (PDF). Charles River Data Systems, Inc. 1983. p. 13.
  9. ^ "make". The Open Group Base Specifications (6). The IEEE and The Open Group. 2004. IEEE Std 1003.1, 2004 Edition.

Read other articles:

YKK AP株式会社YKK AP Inc. 種類 株式会社機関設計 監査役会設置会社本社所在地 日本〒101-0024東京都千代田区神田和泉町1番地 北緯35度41分57.5秒 東経139度46分33.5秒 / 北緯35.699306度 東経139.775972度 / 35.699306; 139.775972座標: 北緯35度41分57.5秒 東経139度46分33.5秒 / 北緯35.699306度 東経139.775972度 / 35.699306; 139.775972設立 1957年(昭和32年)7月22日(吉田商...

This article contains content that is written like an advertisement. Please help improve it by removing promotional content and inappropriate external links, and by adding encyclopedic content written from a neutral point of view. (October 2021) (Learn how and when to remove this template message) Samm HenshawBackground informationBirth nameIniabasi Samuel Henshaw[1]Also known asSamm HenshawBorn (1994-02-22) 22 February 1994 (age 29)London, EnglandGenres Soul R&B[2] p...

This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: Quidditch in Canada – news · newspapers · books · scholar · JSTOR (February 2018) (Learn how and when to remove this template message) This article needs...

Campeonato MundialPiscina Curta 2014 Nado crawl/livre 50 m masc fem 100 m masc fem 200 m masc fem 400 m masc fem 800 m fem 1500 m masc Nado costas 50 m masc fem 100 m masc fem 200 m masc fem Nado bruços/peito 50 m masc fem 100 m masc fem 200 m masc fem Nado mariposa/borboleta 50 m masc fem 100 m masc fem 200 m masc fem Estilos/medley 100 m masc fem 200 m masc fem 400 m masc fem Revezamento/livre 4x50 m masc fem 4x100 m masc fem 4x200 m masc fem Revezamento/medley 4x50 m masc fem 4x100 m masc...

Monte Kosciusko Localización geográficaContinente AntártidaCordillera Ames RangeCoordenadas 75°43′00″S 132°13′01″O / -75.7167, -132.217Localización administrativaDivisión Región del Tratado AntárticoCaracterísticas generalesAltitud 2909 metrosMapa de localización Monte Kosciusko Ubicación en Antártida. [editar datos en Wikidata] El monte Kosciusko es una montaña, en la Antártida. Su cumbre alcanza una altura de 2910 m, la misma comprende el sec...

Kepolisian Resor CilegonSingkatanPolres CilegonMottoMelindungi, Mengayomi dan Melayani MasyarakatYurisdiksi hukumKota Cilegon dan 5 Kecamatan Kabupaten SerangMarkas besarJl. Jend. Sudirman No 1, Ramanuju, Kec. Purwakarta, Kota Cilegon, Banten, 42426Pejabat eksekutifAKBP. Eko Tjahyo Untoro, S.H., S.IK., M.H., KapolresKomisaris Polisi Andie Firmansyah, S.E, WakapolresSitus webPolres Cilegon Kepolisian Resor Cilegon atau Polres Cilegon[1] adalah pelaksana tugas Kepolisian Negara Republik...

Sungai LoaPetaLokasiNegaraChiliCiri-ciri fisikHulu sungaidekat 21°11′59″S 68°40′05″W / 21.1996°S 68.668°W / -21.1996; -68.668 - elevasi4,277 m Muara sungai21°25′48″S 70°03′27″W / 21.43°S 70.0576°W / -21.43; -70.0576Koordinat: 21°25′48″S 70°03′27″W / 21.43°S 70.0576°W / -21.43; -70.0576 ke Samudra PasifikPanjang440 km [1]Debit air  - rata-rata2.43 m³/s L...

Consonantal sound represented by ⟨ɲ̊⟩ in IPA Voiceless palatal nasalɲ̊ɲ̥ The voiceless palatal nasal is a type of consonantal sound, used in some spoken languages. The symbols in the International Phonetic Alphabet that represent this sound are ⟨ɲ̊⟩ and ⟨ɲ̥⟩, which are combinations of the letter for the voiced palatal nasal and a diacritic indicating voicelessness. The equivalent X-SAMPA symbol is J_0. If distinction is necessary, the voiceless alveol...

Extinct genus of dinosaurs KotasaurusTemporal range: Early Jurassic, 196.5–183 Ma PreꞒ Ꞓ O S D C P T J K Pg N Mounted skeleton of Kotasaurus; based on the holotype Scientific classification Domain: Eukaryota Kingdom: Animalia Phylum: Chordata Clade: Dinosauria Clade: Saurischia Clade: †Sauropodomorpha Clade: †Sauropoda Clade: †Eusauropoda Genus: †KotasaurusYadagiri, 1988 Type species †Kotasaurus yamanpalliensisYadagiri, 1988 Kotasaurus (/ˌkoʊtəˈsɔːrəs/ KOH-tə-SOR-...

العلاقات البرتغالية الجامايكية البرتغال جامايكا   البرتغال   جامايكا تعديل مصدري - تعديل   العلاقات البرتغالية الجامايكية هي العلاقات الثنائية التي تجمع بين البرتغال وجامايكا.[1][2][3][4][5] مقارنة بين البلدين هذه مقارنة عامة ومرجعية للدولتين...

Peta infrastruktur dan tata guna lahan di Komune Avon.  = Kawasan perkotaan  = Lahan subur  = Padang rumput  = Lahan pertanaman campuran  = Hutan  = Vegetasi perdu  = Lahan basah  = Anak sungaiAvonNegaraPrancisArondisemenFontainebleauKantonFontainebleauAntarkomuneFontainebleau-AvonPemerintahan • Wali kota (2014-2020) Marie-Charlotte Nouhaud • Populasi114.362Kode INSEE/pos77014 / 2 Population sans doubles comptes: penghitunga...

American college football season 2021 Ohio State Buckeyes footballBig Ten East Division co-champion Rose Bowl championRose Bowl, W 48–45 vs. UtahConferenceBig Ten ConferenceDivisionEast DivisionRankingCoachesNo. 5APNo. 6Record11–2 (8–1 Big Ten)Head coachRyan Day (3rd season)Offensive coordinatorKevin Wilson (5th season)Defensive coordinatorKerry Coombs (2nd season)CaptainKamryn BabbHaskell GarrettZach HarrisonTeradja MitchellThayer MunfordChris OlaveHome st...

Cet article est une ébauche concernant le droit, une université et le Royaume-Uni. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Article principal : King's College London. La Faculté de droit de King's College London, dont le nom officiel est Dickson Poon School of Law, est une faculté de droit prestigieuse, située dans l'aile est de Somerset House. Elle est l'une des neuf facultés de l'université K...

The former Theatre Suburbia building in Oak Forest Theatre Suburbia is a non-profit community theatre company in northwest Houston, Texas. The company is the city's longest running all-volunteer playhouse, having presented a full season of performances every year since 1961. History Theatre Suburbia was formed in the summer of 1961 and opened its inaugural season with Philip Barry's, The Philadelphia Story on October 27, 1961. Tickets for the first show sold for $1.50 and the original buildin...

American television journalist Juju ChangChang in March 2007BornHyunju Chang (1965-09-17) September 17, 1965 (age 58)Seoul, South KoreaEducationStanford University (B.A., political science and communication, 1987)OccupationTelevision journalistYears active1984–presentTitleSpecial correspondent, NightlineSpouse Neal Shapiro ​(m. 1995)​Children3RelativesMitch White (nephew)WebsiteJuju-Chang-bio Hyunju Juju Chang[1] (born September 17, 1965) is an...

この項目には性的な表現や記述が含まれます。免責事項もお読みください。 すぎさき なつき杉崎 夏希プロフィール生年月日 1986年7月4日現年齢 37歳出身地 日本・東京都公称サイズ[いつ?]身長 / 体重 148 cm / ― kgスリーサイズ 82 - 59 - 86 cmブラサイズ C65 単位系換算身長 / 体重 4′ 11″ / ― lbスリーサイズ 32 - 23 - 34 in活動ジャンル アダルトビデオ出演期間 2007年 - 2008�...

1996 film by Pankaj Parashar RajkumarDirected byPankaj ParasharWritten byVinay Shukla,Kamlesh PandeyProduced byTutu SharmaStarringNaseeruddin ShahAnil KapoorMadhuri DixitDanny DenzongpaReena RoyFarida JalalSanjai MishraCinematographyKabir LalEdited byAfaque HussainMusic byLaxmikant-PyarelalProductioncompanyTutu filmsRelease date 22 March 1996 (1996-03-22) CountryIndiaLanguageHindi Rajkumar (transl. Prince) is a 1996 Indian Hindi historical fantasy film directed by Pankaj Parash...

Holy Cross CemeteryDetailsLocation3620 Tilden Avenue, East Flatbush, Brooklyn, New York CityCountryUnited StatesCoordinates40°38′47″N 73°56′19″W / 40.6465°N 73.9386°W / 40.6465; -73.9386TypeRoman CatholicOwned byDiocese of BrooklynWebsiteOfficial websiteFind a GraveHoly Cross Cemetery Holy Cross Cemetery, located at 3620 Tilden Avenue in East Flatbush, Brooklyn, New York City, is an American Roman Catholic cemetery operated by the Diocese of Brooklyn. Notab...

Park in Seattle, Washington, U.S. This article is about the park in Seattle. For the park in Manila, Philippines, see Rizal Park. Dr. Jose Rizal ParkSeattle skyline as seen from the parkLocationSeattle, Washington, U.S.Coordinates47°35′35.1″N 122°19′6.9″W / 47.593083°N 122.318583°W / 47.593083; -122.318583 Dr. Jose Rizal Park is a 9.6 acre (39,000 m²) park on the west slope of Beacon Hill in Seattle, Washington. The land, condemned by the city in 1917 for ...

Histoire des Juifs en Écosse Populations importantes par région Autres modifier Synagogue de Garnethill, à Glasgow. Les premières traces de Juifs en Écosse datent de la fin du XVIIe siècle, mais il est possible que des Juifs y soient arrivés à l'époque de la conquête romaine de la Grande-Bretagne, bien qu'il n'en existe aucune preuve. La grande majorité des Juifs écossais d'aujourd'hui sont d'origine ashkénaze, installés pour la plupart à Édi...